xmlutils.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2015 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. XML and iCal requests manager.
  20. Note that all these functions need to receive unicode objects for full
  21. iCal requests (PUT) and string objects with charset correctly defined
  22. in them for XML requests (all but PUT).
  23. """
  24. import copy
  25. import math
  26. import posixpath
  27. import re
  28. import xml.etree.ElementTree as ET
  29. from collections import OrderedDict
  30. from datetime import date, datetime, timedelta, timezone
  31. from http import client
  32. from itertools import chain
  33. from urllib.parse import quote, unquote, urlparse
  34. from . import storage
  35. MIMETYPES = {
  36. "VADDRESSBOOK": "text/vcard",
  37. "VCALENDAR": "text/calendar"}
  38. NAMESPACES = {
  39. "C": "urn:ietf:params:xml:ns:caldav",
  40. "CR": "urn:ietf:params:xml:ns:carddav",
  41. "D": "DAV:",
  42. "CS": "http://calendarserver.org/ns/",
  43. "ICAL": "http://apple.com/ns/ical/",
  44. "ME": "http://me.com/_namespace/"}
  45. NAMESPACES_REV = {}
  46. for short, url in NAMESPACES.items():
  47. NAMESPACES_REV[url] = short
  48. ET.register_namespace("" if short == "D" else short, url)
  49. CLARK_TAG_REGEX = re.compile(r"{(?P<namespace>[^}]*)}(?P<tag>.*)", re.VERBOSE)
  50. HUMAN_REGEX = re.compile(r"(?P<namespace>[^:{}]*)(?P<tag>.*)", re.VERBOSE)
  51. DAY = timedelta(days=1)
  52. SECOND = timedelta(seconds=1)
  53. DATETIME_MIN = datetime.min.replace(tzinfo=timezone.utc)
  54. DATETIME_MAX = datetime.max.replace(tzinfo=timezone.utc)
  55. TIMESTAMP_MIN = math.floor(DATETIME_MIN.timestamp())
  56. TIMESTAMP_MAX = math.ceil(DATETIME_MAX.timestamp())
  57. def pretty_xml(element, level=0):
  58. """Indent an ElementTree ``element`` and its children."""
  59. if not level:
  60. element = copy.deepcopy(element)
  61. i = "\n" + level * " "
  62. if len(element):
  63. if not element.text or not element.text.strip():
  64. element.text = i + " "
  65. if not element.tail or not element.tail.strip():
  66. element.tail = i
  67. for sub_element in element:
  68. pretty_xml(sub_element, level + 1)
  69. if not sub_element.tail or not sub_element.tail.strip():
  70. sub_element.tail = i
  71. else:
  72. if level and (not element.tail or not element.tail.strip()):
  73. element.tail = i
  74. if not level:
  75. return '<?xml version="1.0"?>\n%s' % ET.tostring(element, "unicode")
  76. def _tag(short_name, local):
  77. """Get XML Clark notation {uri(``short_name``)}``local``."""
  78. return "{%s}%s" % (NAMESPACES[short_name], local)
  79. def _tag_from_clark(name):
  80. """Get a human-readable variant of the XML Clark notation tag ``name``.
  81. For a given name using the XML Clark notation, return a human-readable
  82. variant of the tag name for known namespaces. Otherwise, return the name as
  83. is.
  84. """
  85. match = CLARK_TAG_REGEX.match(name)
  86. if match and match.group("namespace") in NAMESPACES_REV:
  87. args = {
  88. "ns": NAMESPACES_REV[match.group("namespace")],
  89. "tag": match.group("tag")}
  90. return "%(ns)s:%(tag)s" % args
  91. return name
  92. def _tag_from_human(name):
  93. """Get an XML Clark notation tag from human-readable variant ``name``."""
  94. match = HUMAN_REGEX.match(name)
  95. if match and match.group("namespace") in NAMESPACES:
  96. return _tag(match.group("namespace"), match.group("tag"))
  97. return name
  98. def _response(code):
  99. """Return full W3C names from HTTP status codes."""
  100. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  101. def _href(base_prefix, href):
  102. """Return prefixed href."""
  103. return quote("%s%s" % (base_prefix, href))
  104. def _webdav_error(namespace, name):
  105. """Generate XML error message."""
  106. root = ET.Element(_tag("D", "error"))
  107. root.append(ET.Element(_tag(namespace, name)))
  108. return root
  109. def _date_to_datetime(date_):
  110. """Transform a date to a UTC datetime.
  111. If date_ is a datetime without timezone, return as UTC datetime. If date_
  112. is already a datetime with timezone, return as is.
  113. """
  114. if not isinstance(date_, datetime):
  115. date_ = datetime.combine(date_, datetime.min.time())
  116. if not date_.tzinfo:
  117. date_ = date_.replace(tzinfo=timezone.utc)
  118. return date_
  119. def _comp_match(item, filter_, scope="collection"):
  120. """Check whether the ``item`` matches the comp ``filter_``.
  121. If ``scope`` is ``"collection"``, the filter is applied on the
  122. item's collection. Otherwise, it's applied on the item.
  123. See rfc4791-9.7.1.
  124. """
  125. filter_length = len(filter_)
  126. if scope == "collection":
  127. tag = item.collection.get_meta("tag")
  128. else:
  129. for component in item.components():
  130. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  131. tag = component.name
  132. break
  133. else:
  134. return False
  135. if filter_length == 0:
  136. # Point #1 of rfc4791-9.7.1
  137. return filter_.get("name") == tag
  138. else:
  139. if filter_length == 1:
  140. if filter_[0].tag == _tag("C", "is-not-defined"):
  141. # Point #2 of rfc4791-9.7.1
  142. return filter_.get("name") != tag
  143. if filter_[0].tag == _tag("C", "time-range"):
  144. # Point #3 of rfc4791-9.7.1
  145. if not _time_range_match(item.item, filter_[0], tag):
  146. return False
  147. filter_ = filter_[1:]
  148. # Point #4 of rfc4791-9.7.1
  149. return all(
  150. _prop_match(item, child) if child.tag == _tag("C", "prop-filter")
  151. else _comp_match(item, child, scope="component")
  152. for child in filter_)
  153. def _prop_match(item, filter_):
  154. """Check whether the ``item`` matches the prop ``filter_``.
  155. See rfc4791-9.7.2 and rfc6352-10.5.1.
  156. """
  157. filter_length = len(filter_)
  158. if item.collection.get_meta("tag") == "VCALENDAR":
  159. for component in item.components():
  160. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  161. vobject_item = component
  162. break
  163. else:
  164. vobject_item = item.item
  165. if filter_length == 0:
  166. # Point #1 of rfc4791-9.7.2
  167. return filter_.get("name").lower() in vobject_item.contents
  168. else:
  169. name = filter_.get("name").lower()
  170. if filter_length == 1:
  171. if filter_[0].tag == _tag("C", "is-not-defined"):
  172. # Point #2 of rfc4791-9.7.2
  173. return name not in vobject_item.contents
  174. if filter_[0].tag == _tag("C", "time-range"):
  175. # Point #3 of rfc4791-9.7.2
  176. if not _time_range_match(vobject_item, filter_[0], name):
  177. return False
  178. filter_ = filter_[1:]
  179. elif filter_[0].tag == _tag("C", "text-match"):
  180. # Point #4 of rfc4791-9.7.2
  181. if not _text_match(vobject_item, filter_[0], name):
  182. return False
  183. filter_ = filter_[1:]
  184. return all(
  185. _param_filter_match(vobject_item, param_filter, name)
  186. for param_filter in filter_)
  187. def _time_range_match(vobject_item, filter_, child_name):
  188. """Check whether the component/property ``child_name`` of
  189. ``vobject_item`` matches the time-range ``filter_``."""
  190. start = filter_.get("start")
  191. end = filter_.get("end")
  192. if not start and not end:
  193. return False
  194. if start:
  195. start = datetime.strptime(start, "%Y%m%dT%H%M%SZ")
  196. else:
  197. start = datetime.min
  198. if end:
  199. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  200. else:
  201. end = datetime.max
  202. start = start.replace(tzinfo=timezone.utc)
  203. end = end.replace(tzinfo=timezone.utc)
  204. matched = False
  205. def range_fn(range_start, range_end):
  206. nonlocal matched
  207. if start < range_end and range_start < end:
  208. matched = True
  209. return True
  210. if end < range_start:
  211. return True
  212. return False
  213. def infinity_fn(start):
  214. return False
  215. _visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn)
  216. return matched
  217. def _visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn):
  218. """Visit all time ranges in the component/property ``child_name`` of
  219. `vobject_item`` with visitors ``range_fn`` and ``infinity_fn``.
  220. ``range_fn`` gets called for every time_range with ``start`` and ``end``
  221. datetimes as arguments. If the function returns True, the operation is
  222. cancelled.
  223. ``infinity_fn`` gets called when an infiite recurrence rule is detected
  224. with ``start`` datetime as argument. If the function returns True, the
  225. operation is cancelled.
  226. See rfc4791-9.9.
  227. """
  228. child = getattr(vobject_item, child_name.lower())
  229. # TODO: Single recurrences can be overwritten by components with
  230. # RECURRENCE-ID (http://www.kanzaki.com/docs/ical/recurrenceId.html). They
  231. # may overwrite the start and end time. Currently these components and
  232. # the overwritten recurrences are both considered. The overwritten
  233. # recurrence should be ignored instead.
  234. def getrruleset(child):
  235. if (hasattr(child, "rrule") and
  236. ";UNTIL=" not in child.rrule.value.upper() and
  237. ";COUNT=" not in child.rrule.value.upper()):
  238. first_dtstart = next(iter(child.getrruleset(addRDate=True)), None)
  239. if (first_dtstart is not None and
  240. infinity_fn(_date_to_datetime(first_dtstart))):
  241. return (), True
  242. return child.getrruleset(addRDate=True), False
  243. # Comments give the lines in the tables of the specification
  244. if child_name == "VEVENT":
  245. for child in vobject_item.vevent_list:
  246. # TODO: check if there's a timezone
  247. dtstart = child.dtstart.value
  248. if child.rruleset:
  249. dtstarts, infinity = getrruleset(child)
  250. if infinity:
  251. return
  252. else:
  253. dtstarts = (dtstart,)
  254. dtend = getattr(child, "dtend", None)
  255. if dtend is not None:
  256. dtend = dtend.value
  257. original_duration = (dtend - dtstart).total_seconds()
  258. dtend = _date_to_datetime(dtend)
  259. duration = getattr(child, "duration", None)
  260. if duration is not None:
  261. original_duration = duration = duration.value
  262. for dtstart in dtstarts:
  263. dtstart_is_datetime = isinstance(dtstart, datetime)
  264. dtstart = _date_to_datetime(dtstart)
  265. if dtend is not None:
  266. # Line 1
  267. dtend = dtstart + timedelta(seconds=original_duration)
  268. if range_fn(dtstart, dtend):
  269. return
  270. elif duration is not None:
  271. if original_duration is None:
  272. original_duration = duration.seconds
  273. if duration.seconds > 0:
  274. # Line 2
  275. if range_fn(dtstart, dtstart + duration):
  276. return
  277. else:
  278. # Line 3
  279. if range_fn(dtstart, dtstart + SECOND):
  280. return
  281. elif dtstart_is_datetime:
  282. # Line 4
  283. if range_fn(dtstart, dtstart + SECOND):
  284. return
  285. else:
  286. # Line 5
  287. if range_fn(dtstart, dtstart + DAY):
  288. return
  289. elif child_name == "VTODO":
  290. for child in vobject_item.vtodo_list:
  291. dtstart = getattr(child, "dtstart", None)
  292. duration = getattr(child, "duration", None)
  293. due = getattr(child, "due", None)
  294. completed = getattr(child, "completed", None)
  295. created = getattr(child, "created", None)
  296. if dtstart is not None:
  297. dtstart = _date_to_datetime(dtstart.value)
  298. if duration is not None:
  299. duration = duration.value
  300. if due is not None:
  301. due = _date_to_datetime(due.value)
  302. if dtstart is not None:
  303. original_duration = (due - dtstart).total_seconds()
  304. if completed is not None:
  305. completed = _date_to_datetime(completed.value)
  306. if created is not None:
  307. created = _date_to_datetime(created.value)
  308. original_duration = (completed - created).total_seconds()
  309. elif created is not None:
  310. created = _date_to_datetime(created.value)
  311. if child.rruleset:
  312. reference_dates, infinity = getrruleset(child)
  313. if infinity:
  314. return
  315. else:
  316. if dtstart is not None:
  317. reference_dates = (dtstart,)
  318. elif due is not None:
  319. reference_dates = (due,)
  320. elif completed is not None:
  321. reference_dates = (completed,)
  322. elif created is not None:
  323. reference_dates = (created,)
  324. else:
  325. # Line 8
  326. if range_fn(DATETIME_MIN, DATETIME_MAX):
  327. return
  328. reference_dates = ()
  329. for reference_date in reference_dates:
  330. reference_date = _date_to_datetime(reference_date)
  331. if dtstart is not None and duration is not None:
  332. # Line 1
  333. if range_fn(reference_date,
  334. reference_date + duration + SECOND):
  335. return
  336. if range_fn(reference_date + duration - SECOND,
  337. reference_date + duration + SECOND):
  338. return
  339. elif dtstart is not None and due is not None:
  340. # Line 2
  341. due = reference_date + timedelta(seconds=original_duration)
  342. if (range_fn(reference_date, due) or
  343. range_fn(reference_date,
  344. reference_date + SECOND) or
  345. range_fn(due - SECOND, due) or
  346. range_fn(due - SECOND, reference_date + SECOND)):
  347. return
  348. elif dtstart is not None:
  349. if range_fn(reference_date, reference_date + SECOND):
  350. return
  351. elif due is not None:
  352. # Line 4
  353. if range_fn(reference_date - SECOND, reference_date):
  354. return
  355. elif completed is not None and created is not None:
  356. # Line 5
  357. completed = reference_date + timedelta(
  358. seconds=original_duration)
  359. if (range_fn(reference_date - SECOND,
  360. reference_date + SECOND) or
  361. range_fn(completed - SECOND, completed + SECOND) or
  362. range_fn(reference_date - SECOND,
  363. reference_date + SECOND) or
  364. range_fn(completed - SECOND, completed + SECOND)):
  365. return
  366. elif completed is not None:
  367. # Line 6
  368. if range_fn(reference_date - SECOND,
  369. reference_date + SECOND):
  370. return
  371. elif created is not None:
  372. # Line 7
  373. if range_fn(reference_date, DATETIME_MAX):
  374. return
  375. elif child_name == "VJOURNAL":
  376. for child in vobject_item.vjournal_list:
  377. dtstart = getattr(child, "dtstart", None)
  378. if dtstart is not None:
  379. dtstart = dtstart.value
  380. if child.rruleset:
  381. dtstarts, infinity = getrruleset(child)
  382. if infinity:
  383. return
  384. else:
  385. dtstarts = (dtstart,)
  386. for dtstart in dtstarts:
  387. dtstart_is_datetime = isinstance(dtstart, datetime)
  388. dtstart = _date_to_datetime(dtstart)
  389. if dtstart_is_datetime:
  390. # Line 1
  391. if range_fn(dtstart, dtstart + SECOND):
  392. return
  393. else:
  394. # Line 2
  395. if range_fn(dtstart, dtstart + DAY):
  396. return
  397. elif isinstance(child, date):
  398. if range_fn(child, child + DAY):
  399. return
  400. elif isinstance(child, datetime):
  401. if range_fn(child, child + SECOND):
  402. return
  403. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  404. """Check whether the ``item`` matches the text-match ``filter_``.
  405. See rfc4791-9.7.5.
  406. """
  407. # TODO: collations are not supported, but the default ones needed
  408. # for DAV servers are actually pretty useless. Texts are lowered to
  409. # be case-insensitive, almost as the "i;ascii-casemap" value.
  410. match = next(filter_.itertext()).lower()
  411. children = getattr(vobject_item, "%s_list" % child_name, [])
  412. if attrib_name:
  413. condition = any(
  414. match in attrib.lower() for child in children
  415. for attrib in child.params.get(attrib_name, []))
  416. else:
  417. condition = any(match in child.value.lower() for child in children)
  418. if filter_.get("negate-condition") == "yes":
  419. return not condition
  420. else:
  421. return condition
  422. def _param_filter_match(vobject_item, filter_, parent_name):
  423. """Check whether the ``item`` matches the param-filter ``filter_``.
  424. See rfc4791-9.7.3.
  425. """
  426. name = filter_.get("name")
  427. children = getattr(vobject_item, "%s_list" % parent_name, [])
  428. condition = any(name in child.params for child in children)
  429. if len(filter_):
  430. if filter_[0].tag == _tag("C", "text-match"):
  431. return condition and _text_match(
  432. vobject_item, filter_[0], parent_name, name)
  433. elif filter_[0].tag == _tag("C", "is-not-defined"):
  434. return not condition
  435. else:
  436. return condition
  437. def simplify_prefilters(filters):
  438. """Creates a simplified condition from ``filters``.
  439. Returns a tuple (``tag``, ``start``, ``end``, ``simple``) where ``tag`` is
  440. a string or None (match all) and ``start`` and ``end`` are POSIX
  441. timestamps (as int). ``simple`` is a bool that indicates that ``filters``
  442. and the simplified condition are identical.
  443. """
  444. flat_filters = tuple(chain.from_iterable(filters))
  445. simple = len(flat_filters) <= 1
  446. for col_filter in flat_filters:
  447. if (col_filter.tag != _tag("C", "comp-filter") or
  448. col_filter.get("name") != "VCALENDAR"):
  449. simple = False
  450. continue
  451. simple &= len(col_filter) <= 1
  452. for comp_filter in col_filter:
  453. if comp_filter.tag != _tag("C", "comp-filter"):
  454. simple = False
  455. continue
  456. tag = comp_filter.get("name")
  457. if (tag not in ("VTODO", "VEVENT", "VJOURNAL") or comp_filter.find(
  458. _tag("C", "is-not-defined")) is not None):
  459. simple = False
  460. continue
  461. simple &= len(comp_filter) <= 1
  462. for time_filter in comp_filter:
  463. if time_filter.tag != _tag("C", "time-range"):
  464. simple = False
  465. continue
  466. start = time_filter.get("start")
  467. end = time_filter.get("end")
  468. if start:
  469. start = math.floor(datetime.strptime(
  470. start, "%Y%m%dT%H%M%SZ").replace(
  471. tzinfo=timezone.utc).timestamp())
  472. else:
  473. start = TIMESTAMP_MIN
  474. if end:
  475. end = math.ceil(datetime.strptime(
  476. end, "%Y%m%dT%H%M%SZ").replace(
  477. tzinfo=timezone.utc).timestamp())
  478. else:
  479. end = TIMESTAMP_MAX
  480. return tag, start, end, simple
  481. return tag, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
  482. return None, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
  483. def find_tag(vobject_item):
  484. """Find tag from ``vobject_item``."""
  485. if vobject_item.name == "VCALENDAR":
  486. for component in vobject_item.components():
  487. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  488. return component.name
  489. return None
  490. def find_tag_and_time_range(vobject_item):
  491. """Find tag and enclosing time range from ``vobject item``.
  492. Returns a tuple (``tag``, ``start``, ``end``) where ``tag`` is a string
  493. and ``start`` and ``end`` are POSIX timestamps (as int).
  494. This is intened to be used for matching against simplified prefilters.
  495. """
  496. tag = find_tag(vobject_item)
  497. if not tag:
  498. return (None, TIMESTAMP_MIN, TIMESTAMP_MAX)
  499. start = end = None
  500. def range_fn(range_start, range_end):
  501. nonlocal start, end
  502. if start is None or range_start < start:
  503. start = range_start
  504. if end is None or end < range_end:
  505. end = range_end
  506. return False
  507. def infinity_fn(range_start):
  508. nonlocal start, end
  509. if start is None or range_start < start:
  510. start = range_start
  511. end = DATETIME_MAX
  512. return True
  513. _visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  514. if start is None:
  515. start = DATETIME_MIN
  516. if end is None:
  517. end = DATETIME_MAX
  518. return tag, math.floor(start.timestamp()), math.ceil(end.timestamp())
  519. def name_from_path(path, collection):
  520. """Return Radicale item name from ``path``."""
  521. path = path.strip("/") + "/"
  522. start = collection.path + "/"
  523. if not path.startswith(start):
  524. raise ValueError("%r doesn't start with %r" % (path, start))
  525. name = path[len(start):][:-1]
  526. if name and not storage.is_safe_path_component(name):
  527. raise ValueError("%r is not a component in collection %r" %
  528. (name, collection.path))
  529. return name
  530. def props_from_request(xml_request, actions=("set", "remove")):
  531. """Return a list of properties as a dictionary."""
  532. result = OrderedDict()
  533. if xml_request is None:
  534. return result
  535. for action in actions:
  536. action_element = xml_request.find(_tag("D", action))
  537. if action_element is not None:
  538. break
  539. else:
  540. action_element = xml_request
  541. prop_element = action_element.find(_tag("D", "prop"))
  542. if prop_element is not None:
  543. for prop in prop_element:
  544. if prop.tag == _tag("D", "resourcetype"):
  545. for resource_type in prop:
  546. if resource_type.tag == _tag("C", "calendar"):
  547. result["tag"] = "VCALENDAR"
  548. break
  549. elif resource_type.tag == _tag("CR", "addressbook"):
  550. result["tag"] = "VADDRESSBOOK"
  551. break
  552. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  553. result[_tag_from_clark(prop.tag)] = ",".join(
  554. supported_comp.attrib["name"]
  555. for supported_comp in prop
  556. if supported_comp.tag == _tag("C", "comp"))
  557. else:
  558. result[_tag_from_clark(prop.tag)] = prop.text
  559. return result
  560. def delete(base_prefix, path, collection, href=None):
  561. """Read and answer DELETE requests.
  562. Read rfc4918-9.6 for info.
  563. """
  564. collection.delete(href)
  565. multistatus = ET.Element(_tag("D", "multistatus"))
  566. response = ET.Element(_tag("D", "response"))
  567. multistatus.append(response)
  568. href = ET.Element(_tag("D", "href"))
  569. href.text = _href(base_prefix, path)
  570. response.append(href)
  571. status = ET.Element(_tag("D", "status"))
  572. status.text = _response(200)
  573. response.append(status)
  574. return multistatus
  575. def propfind(base_prefix, path, xml_request, read_collections,
  576. write_collections, user):
  577. """Read and answer PROPFIND requests.
  578. Read rfc4918-9.1 for info.
  579. The collections parameter is a list of collections that are to be included
  580. in the output.
  581. """
  582. # A client may choose not to submit a request body. An empty PROPFIND
  583. # request body MUST be treated as if it were an 'allprop' request.
  584. top_tag = (xml_request[0] if xml_request is not None else
  585. ET.Element(_tag("D", "allprop")))
  586. props = ()
  587. if top_tag.tag == _tag("D", "allprop"):
  588. props = [
  589. _tag("D", "getcontenttype"),
  590. _tag("D", "resourcetype"),
  591. _tag("D", "displayname"),
  592. _tag("D", "owner"),
  593. _tag("D", "getetag"),
  594. _tag("ICAL", "calendar-color"),
  595. _tag("CS", "getctag"),
  596. _tag("C", "supported-calendar-component-set"),
  597. _tag("D", "supported-report-set"),
  598. ]
  599. elif top_tag.tag == _tag("D", "prop"):
  600. props = [prop.tag for prop in top_tag]
  601. if _tag("D", "current-user-principal") in props and not user:
  602. # Ask for authentication
  603. # Returning the DAV:unauthenticated pseudo-principal as specified in
  604. # RFC 5397 doesn't seem to work with DAVdroid.
  605. return client.FORBIDDEN, None
  606. # Writing answer
  607. multistatus = ET.Element(_tag("D", "multistatus"))
  608. collections = []
  609. for collection in write_collections:
  610. collections.append(collection)
  611. if top_tag.tag == _tag("D", "propname"):
  612. response = _propfind_response(
  613. base_prefix, path, collection, (), user, write=True,
  614. propnames=True)
  615. else:
  616. response = _propfind_response(
  617. base_prefix, path, collection, props, user, write=True)
  618. if response:
  619. multistatus.append(response)
  620. for collection in read_collections:
  621. if collection in collections:
  622. continue
  623. if top_tag.tag == _tag("D", "propname"):
  624. response = _propfind_response(
  625. base_prefix, path, collection, (), user, write=False,
  626. propnames=True)
  627. else:
  628. response = _propfind_response(
  629. base_prefix, path, collection, props, user, write=False)
  630. if response:
  631. multistatus.append(response)
  632. return client.MULTI_STATUS, multistatus
  633. def _propfind_response(base_prefix, path, item, props, user, write=False,
  634. propnames=False):
  635. """Build and return a PROPFIND response."""
  636. is_collection = isinstance(item, storage.BaseCollection)
  637. if is_collection:
  638. is_leaf = item.get_meta("tag") in ("VADDRESSBOOK", "VCALENDAR")
  639. collection = item
  640. else:
  641. collection = item.collection
  642. response = ET.Element(_tag("D", "response"))
  643. href = ET.Element(_tag("D", "href"))
  644. if is_collection:
  645. # Some clients expect collections to end with /
  646. uri = "/%s/" % item.path if item.path else "/"
  647. else:
  648. uri = "/" + posixpath.join(collection.path, item.href)
  649. href.text = _href(base_prefix, uri)
  650. response.append(href)
  651. propstat404 = ET.Element(_tag("D", "propstat"))
  652. propstat200 = ET.Element(_tag("D", "propstat"))
  653. response.append(propstat200)
  654. prop200 = ET.Element(_tag("D", "prop"))
  655. propstat200.append(prop200)
  656. prop404 = ET.Element(_tag("D", "prop"))
  657. propstat404.append(prop404)
  658. if propnames:
  659. # Should list all properties that can be retrieved by the code below
  660. prop200.append(ET.Element(_tag("D", "getetag")))
  661. prop200.append(ET.Element(_tag("D", "principal-URL")))
  662. prop200.append(ET.Element(_tag("D", "principal-collection-set")))
  663. prop200.append(ET.Element(_tag("C", "calendar-user-address-set")))
  664. prop200.append(ET.Element(_tag("CR", "addressbook-home-set")))
  665. prop200.append(ET.Element(_tag("C", "calendar-home-set")))
  666. prop200.append(ET.Element(
  667. _tag("C", "supported-calendar-component-set")))
  668. prop200.append(ET.Element(_tag("D", "current-user-privilege-set")))
  669. prop200.append(ET.Element(_tag("D", "supported-report-set")))
  670. prop200.append(ET.Element(_tag("D", "getcontenttype")))
  671. prop200.append(ET.Element(_tag("D", "resourcetype")))
  672. if is_collection:
  673. prop200.append(ET.Element(_tag("CS", "getctag")))
  674. prop200.append(ET.Element(_tag("D", "sync-token")))
  675. prop200.append(ET.Element(_tag("C", "calendar-timezone")))
  676. prop200.append(ET.Element(_tag("D", "displayname")))
  677. prop200.append(ET.Element(_tag("ICAL", "calendar-color")))
  678. prop200.append(ET.Element(_tag("D", "owner")))
  679. if is_leaf:
  680. meta = item.get_meta()
  681. for tag in meta:
  682. clark_tag = _tag_from_human(tag)
  683. if prop200.find(clark_tag) is None:
  684. prop200.append(ET.Element(clark_tag))
  685. for tag in props:
  686. element = ET.Element(tag)
  687. is404 = False
  688. if tag == _tag("D", "getetag"):
  689. element.text = item.etag
  690. elif tag == _tag("D", "getlastmodified"):
  691. element.text = item.last_modified
  692. elif tag == _tag("D", "principal-collection-set"):
  693. tag = ET.Element(_tag("D", "href"))
  694. tag.text = _href(base_prefix, "/")
  695. element.append(tag)
  696. elif (tag in (_tag("C", "calendar-user-address-set"),
  697. _tag("D", "principal-URL"),
  698. _tag("CR", "addressbook-home-set"),
  699. _tag("C", "calendar-home-set")) and
  700. collection.is_principal and is_collection):
  701. tag = ET.Element(_tag("D", "href"))
  702. tag.text = _href(base_prefix, path)
  703. element.append(tag)
  704. elif tag == _tag("C", "supported-calendar-component-set"):
  705. human_tag = _tag_from_clark(tag)
  706. if is_collection and is_leaf:
  707. meta = item.get_meta(human_tag)
  708. if meta:
  709. components = meta.split(",")
  710. else:
  711. components = ("VTODO", "VEVENT", "VJOURNAL")
  712. for component in components:
  713. comp = ET.Element(_tag("C", "comp"))
  714. comp.set("name", component)
  715. element.append(comp)
  716. else:
  717. is404 = True
  718. elif tag == _tag("D", "current-user-principal"):
  719. tag = ET.Element(_tag("D", "href"))
  720. tag.text = _href(base_prefix, ("/%s/" % user) if user else "/")
  721. element.append(tag)
  722. elif tag == _tag("D", "current-user-privilege-set"):
  723. privileges = [("D", "read")]
  724. if write:
  725. privileges.append(("D", "all"))
  726. privileges.append(("D", "write"))
  727. privileges.append(("D", "write-properties"))
  728. privileges.append(("D", "write-content"))
  729. for ns, privilege_name in privileges:
  730. privilege = ET.Element(_tag("D", "privilege"))
  731. privilege.append(ET.Element(_tag(ns, privilege_name)))
  732. element.append(privilege)
  733. elif tag == _tag("D", "supported-report-set"):
  734. # These 3 reports are not implemented
  735. reports = [
  736. ("D", "expand-property"),
  737. ("D", "principal-search-property-set"),
  738. ("D", "principal-property-search")]
  739. if is_collection and is_leaf:
  740. reports.append(("D", "sync-collection"))
  741. if item.get_meta("tag") == "VADDRESSBOOK":
  742. reports.append(("CR", "addressbook-multiget"))
  743. reports.append(("CR", "addressbook-query"))
  744. elif item.get_meta("tag") == "VCALENDAR":
  745. reports.append(("C", "calendar-multiget"))
  746. reports.append(("C", "calendar-query"))
  747. for ns, report_name in reports:
  748. supported = ET.Element(_tag("D", "supported-report"))
  749. report_tag = ET.Element(_tag("D", "report"))
  750. supported_report_tag = ET.Element(_tag(ns, report_name))
  751. report_tag.append(supported_report_tag)
  752. supported.append(report_tag)
  753. element.append(supported)
  754. elif is_collection:
  755. if tag == _tag("D", "getcontenttype"):
  756. if is_leaf:
  757. element.text = MIMETYPES[item.get_meta("tag")]
  758. else:
  759. is404 = True
  760. elif tag == _tag("D", "resourcetype"):
  761. if item.is_principal:
  762. tag = ET.Element(_tag("D", "principal"))
  763. element.append(tag)
  764. if is_leaf:
  765. if item.get_meta("tag") == "VADDRESSBOOK":
  766. tag = ET.Element(_tag("CR", "addressbook"))
  767. element.append(tag)
  768. elif item.get_meta("tag") == "VCALENDAR":
  769. tag = ET.Element(_tag("C", "calendar"))
  770. element.append(tag)
  771. tag = ET.Element(_tag("D", "collection"))
  772. element.append(tag)
  773. elif tag == _tag("D", "owner"):
  774. if is_leaf and item.owner:
  775. element.text = "/%s/" % item.owner
  776. else:
  777. is404 = True
  778. elif tag == _tag("D", "displayname"):
  779. if is_leaf:
  780. element.text = item.get_meta("D:displayname") or item.path
  781. else:
  782. is404 = True
  783. elif tag == _tag("CS", "getctag"):
  784. if is_leaf:
  785. element.text = item.etag
  786. else:
  787. is404 = True
  788. elif tag == _tag("D", "sync-token"):
  789. if is_leaf:
  790. element.text, _ = item.sync()
  791. else:
  792. is404 = True
  793. else:
  794. human_tag = _tag_from_clark(tag)
  795. meta = item.get_meta(human_tag)
  796. if meta:
  797. element.text = meta
  798. else:
  799. is404 = True
  800. # Not for collections
  801. elif tag == _tag("D", "getcontenttype"):
  802. name = item.name.lower()
  803. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  804. element.text = "%s; component=%s" % (mimetype, name)
  805. elif tag == _tag("D", "resourcetype"):
  806. # resourcetype must be returned empty for non-collection elements
  807. pass
  808. elif tag == _tag("D", "getcontentlength"):
  809. encoding = collection.configuration.get("encoding", "request")
  810. element.text = str(len(item.serialize().encode(encoding)))
  811. else:
  812. is404 = True
  813. if is404:
  814. prop404.append(element)
  815. else:
  816. prop200.append(element)
  817. status200 = ET.Element(_tag("D", "status"))
  818. status200.text = _response(200)
  819. propstat200.append(status200)
  820. status404 = ET.Element(_tag("D", "status"))
  821. status404.text = _response(404)
  822. propstat404.append(status404)
  823. if len(prop404):
  824. response.append(propstat404)
  825. return response
  826. def _add_propstat_to(element, tag, status_number):
  827. """Add a PROPSTAT response structure to an element.
  828. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  829. given ``element``, for the following ``tag`` with the given
  830. ``status_number``.
  831. """
  832. propstat = ET.Element(_tag("D", "propstat"))
  833. element.append(propstat)
  834. prop = ET.Element(_tag("D", "prop"))
  835. propstat.append(prop)
  836. clark_tag = tag if "{" in tag else _tag(*tag.split(":", 1))
  837. prop_tag = ET.Element(clark_tag)
  838. prop.append(prop_tag)
  839. status = ET.Element(_tag("D", "status"))
  840. status.text = _response(status_number)
  841. propstat.append(status)
  842. def proppatch(base_prefix, path, xml_request, collection):
  843. """Read and answer PROPPATCH requests.
  844. Read rfc4918-9.2 for info.
  845. """
  846. props_to_set = props_from_request(xml_request, actions=("set",))
  847. props_to_remove = props_from_request(xml_request, actions=("remove",))
  848. multistatus = ET.Element(_tag("D", "multistatus"))
  849. response = ET.Element(_tag("D", "response"))
  850. multistatus.append(response)
  851. href = ET.Element(_tag("D", "href"))
  852. href.text = _href(base_prefix, path)
  853. response.append(href)
  854. new_props = collection.get_meta()
  855. for short_name, value in props_to_set.items():
  856. new_props[short_name] = value
  857. _add_propstat_to(response, short_name, 200)
  858. for short_name in props_to_remove:
  859. try:
  860. del new_props[short_name]
  861. except KeyError:
  862. pass
  863. _add_propstat_to(response, short_name, 200)
  864. storage.check_and_sanitize_props(new_props)
  865. collection.set_meta_all(new_props)
  866. return multistatus
  867. def report(base_prefix, path, xml_request, collection):
  868. """Read and answer REPORT requests.
  869. Read rfc3253-3.6 for info.
  870. """
  871. multistatus = ET.Element(_tag("D", "multistatus"))
  872. if xml_request is None:
  873. return client.MULTI_STATUS, multistatus
  874. root = xml_request
  875. if root.tag in (
  876. _tag("D", "principal-search-property-set"),
  877. _tag("D", "principal-property-search"),
  878. _tag("D", "expand-property")):
  879. # We don't support searching for principals or indirect retrieving of
  880. # properties, just return an empty result.
  881. # InfCloud asks for expand-property reports (even if we don't announce
  882. # support for them) and stops working if an error code is returned.
  883. collection.logger.warning("Unsupported REPORT method %r on %r "
  884. "requested", root.tag, path)
  885. return client.MULTI_STATUS, multistatus
  886. prop_element = root.find(_tag("D", "prop"))
  887. props = (
  888. [prop.tag for prop in prop_element]
  889. if prop_element is not None else [])
  890. if root.tag in (
  891. _tag("C", "calendar-multiget"),
  892. _tag("CR", "addressbook-multiget")):
  893. # Read rfc4791-7.9 for info
  894. hreferences = set()
  895. for href_element in root.findall(_tag("D", "href")):
  896. href_path = storage.sanitize_path(
  897. unquote(urlparse(href_element.text).path))
  898. if (href_path + "/").startswith(base_prefix + "/"):
  899. hreferences.add(href_path[len(base_prefix):])
  900. else:
  901. collection.logger.warning("Skipping invalid path %r in REPORT "
  902. "request on %r", href_path, path)
  903. elif root.tag == _tag("D", "sync-collection"):
  904. old_sync_token_element = root.find(_tag("D", "sync-token"))
  905. old_sync_token = ""
  906. if old_sync_token_element is not None and old_sync_token_element.text:
  907. old_sync_token = old_sync_token_element.text.strip()
  908. collection.logger.debug("Client provided sync token: %r",
  909. old_sync_token)
  910. try:
  911. sync_token, names = collection.sync(old_sync_token)
  912. except ValueError as e:
  913. # Invalid sync token
  914. collection.logger.warning("Client provided invalid sync token %r: "
  915. "%s", old_sync_token, e, exc_info=True)
  916. return (client.PRECONDITION_FAILED,
  917. _webdav_error("D", "valid-sync-token"))
  918. hreferences = ("/" + posixpath.join(collection.path, n) for n in names)
  919. # Append current sync token to response
  920. sync_token_element = ET.Element(_tag("D", "sync-token"))
  921. sync_token_element.text = sync_token
  922. multistatus.append(sync_token_element)
  923. else:
  924. hreferences = (path,)
  925. filters = (
  926. root.findall("./%s" % _tag("C", "filter")) +
  927. root.findall("./%s" % _tag("CR", "filter")))
  928. def retrieve_items(collection, hreferences, multistatus):
  929. """Retrieves all items that are referenced in ``hreferences`` from
  930. ``collection`` and adds 404 responses for missing and invalid items
  931. to ``multistatus``."""
  932. collection_requested = False
  933. def get_names():
  934. """Extracts all names from references in ``hreferences`` and adds
  935. 404 responses for invalid references to ``multistatus``.
  936. If the whole collections is referenced ``collection_requested``
  937. gets set to ``True``."""
  938. nonlocal collection_requested
  939. for hreference in hreferences:
  940. try:
  941. name = name_from_path(hreference, collection)
  942. except ValueError as e:
  943. collection.logger.warning(
  944. "Skipping invalid path %r in REPORT request on %r: %s",
  945. hreference, path, e)
  946. response = _item_response(base_prefix, hreference,
  947. found_item=False)
  948. multistatus.append(response)
  949. continue
  950. if name:
  951. # Reference is an item
  952. yield name
  953. else:
  954. # Reference is a collection
  955. collection_requested = True
  956. for name, item in collection.get_multi2(get_names()):
  957. if not item:
  958. uri = "/" + posixpath.join(collection.path, name)
  959. response = _item_response(base_prefix, uri,
  960. found_item=False)
  961. multistatus.append(response)
  962. else:
  963. yield item, False
  964. if collection_requested:
  965. yield from collection.get_all_filtered(filters)
  966. for item, filters_matched in retrieve_items(collection, hreferences,
  967. multistatus):
  968. if filters and not filters_matched:
  969. match = (
  970. _comp_match if collection.get_meta("tag") == "VCALENDAR"
  971. else _prop_match)
  972. try:
  973. if not all(match(item, filter_[0]) for filter_ in filters
  974. if filter_):
  975. continue
  976. except Exception as e:
  977. raise RuntimeError("Failed to filter item %r from %r: %s" %
  978. (item.href, collection.path, e)) from e
  979. found_props = []
  980. not_found_props = []
  981. for tag in props:
  982. element = ET.Element(tag)
  983. if tag == _tag("D", "getetag"):
  984. element.text = item.etag
  985. found_props.append(element)
  986. elif tag == _tag("D", "getcontenttype"):
  987. name = item.name.lower()
  988. mimetype = (
  989. "text/vcard" if name == "vcard" else "text/calendar")
  990. element.text = "%s; component=%s" % (mimetype, name)
  991. found_props.append(element)
  992. elif tag in (
  993. _tag("C", "calendar-data"),
  994. _tag("CR", "address-data")):
  995. element.text = item.serialize()
  996. found_props.append(element)
  997. else:
  998. not_found_props.append(element)
  999. uri = "/" + posixpath.join(collection.path, item.href)
  1000. multistatus.append(_item_response(
  1001. base_prefix, uri, found_props=found_props,
  1002. not_found_props=not_found_props, found_item=True))
  1003. return client.MULTI_STATUS, multistatus
  1004. def _item_response(base_prefix, href, found_props=(), not_found_props=(),
  1005. found_item=True):
  1006. response = ET.Element(_tag("D", "response"))
  1007. href_tag = ET.Element(_tag("D", "href"))
  1008. href_tag.text = _href(base_prefix, href)
  1009. response.append(href_tag)
  1010. if found_item:
  1011. for code, props in ((200, found_props), (404, not_found_props)):
  1012. if props:
  1013. propstat = ET.Element(_tag("D", "propstat"))
  1014. status = ET.Element(_tag("D", "status"))
  1015. status.text = _response(code)
  1016. prop_tag = ET.Element(_tag("D", "prop"))
  1017. for prop in props:
  1018. prop_tag.append(prop)
  1019. propstat.append(prop_tag)
  1020. propstat.append(status)
  1021. response.append(propstat)
  1022. else:
  1023. status = ET.Element(_tag("D", "status"))
  1024. status.text = _response(404)
  1025. response.append(status)
  1026. return response