xmlutils.py 43 KB

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