xmlutils.py 50 KB

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