xmlutils.py 45 KB

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