xmlutils.py 45 KB

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