xmlutils.py 46 KB

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