xmlutils.py 50 KB

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