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. 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.item] if level == 0
  160. else list(getattr(item, "%s_list" % tag.lower())))
  161. for child in filter_:
  162. if child.tag == _tag("C", "prop-filter"):
  163. if not any(_prop_match(comp, child, "C")
  164. for comp in components):
  165. return False
  166. elif child.tag == _tag("C", "time-range"):
  167. if not _time_range_match(item.item, filter_[0], tag):
  168. return False
  169. elif child.tag == _tag("C", "comp-filter"):
  170. if not _comp_match(item, child, level=level + 1):
  171. return False
  172. else:
  173. raise ValueError("Unexpected %r in comp-filter" % child.tag)
  174. return True
  175. def _prop_match(vobject_item, filter_, ns):
  176. """Check whether the ``item`` matches the prop ``filter_``.
  177. See rfc4791-9.7.2 and rfc6352-10.5.1.
  178. """
  179. name = filter_.get("name").lower()
  180. if len(filter_) == 0:
  181. # Point #1 of rfc4791-9.7.2
  182. return name in vobject_item.contents
  183. if len(filter_) == 1:
  184. if filter_[0].tag == _tag("C", "is-not-defined"):
  185. # Point #2 of rfc4791-9.7.2
  186. return name not in vobject_item.contents
  187. if name not in vobject_item.contents:
  188. return False
  189. # Point #3 and #4 of rfc4791-9.7.2
  190. for child in filter_:
  191. if ns == "C" and child.tag == _tag("C", "time-range"):
  192. if not _time_range_match(vobject_item, child, name):
  193. return False
  194. elif child.tag == _tag(ns, "text-match"):
  195. if not _text_match(vobject_item, child, name, ns):
  196. return False
  197. elif child.tag == _tag(ns, "param-filter"):
  198. if not _param_filter_match(vobject_item, child, name, ns):
  199. return False
  200. else:
  201. raise ValueError("Unexpected %r in prop-filter" % child.tag)
  202. return True
  203. def _time_range_match(vobject_item, filter_, child_name):
  204. """Check whether the component/property ``child_name`` of
  205. ``vobject_item`` matches the time-range ``filter_``."""
  206. start = filter_.get("start")
  207. end = filter_.get("end")
  208. if not start and not end:
  209. return False
  210. if start:
  211. start = datetime.strptime(start, "%Y%m%dT%H%M%SZ")
  212. else:
  213. start = datetime.min
  214. if end:
  215. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  216. else:
  217. end = datetime.max
  218. start = start.replace(tzinfo=timezone.utc)
  219. end = end.replace(tzinfo=timezone.utc)
  220. matched = False
  221. def range_fn(range_start, range_end, is_recurrence):
  222. nonlocal matched
  223. if start < range_end and range_start < end:
  224. matched = True
  225. return True
  226. if end < range_start and not is_recurrence:
  227. return True
  228. return False
  229. def infinity_fn(start):
  230. return False
  231. _visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn)
  232. return matched
  233. def _visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn):
  234. """Visit all time ranges in the component/property ``child_name`` of
  235. `vobject_item`` with visitors ``range_fn`` and ``infinity_fn``.
  236. ``range_fn`` gets called for every time_range with ``start`` and ``end``
  237. datetimes and ``is_recurrence`` as arguments. If the function returns True,
  238. the operation is cancelled.
  239. ``infinity_fn`` gets called when an infiite recurrence rule is detected
  240. with ``start`` datetime as argument. If the function returns True, the
  241. operation is cancelled.
  242. See rfc4791-9.9.
  243. """
  244. # HACK: According to rfc5545-3.8.4.4 an recurrance that is resheduled
  245. # with Recurrence ID affects the recurrence itself and all following
  246. # recurrences too. This is not respected and client don't seem to bother
  247. # either.
  248. def getrruleset(child, ignore=()):
  249. if (hasattr(child, "rrule") and
  250. ";UNTIL=" not in child.rrule.value.upper() and
  251. ";COUNT=" not in child.rrule.value.upper()):
  252. for dtstart in child.getrruleset(addRDate=True):
  253. if dtstart in ignore:
  254. continue
  255. if infinity_fn(_date_to_datetime(dtstart)):
  256. return (), True
  257. break
  258. return filter(lambda dtstart: dtstart not in ignore,
  259. child.getrruleset(addRDate=True)), False
  260. def get_children(components):
  261. main = None
  262. recurrences = []
  263. for comp in components:
  264. if hasattr(comp, "recurrence_id") and comp.recurrence_id.value:
  265. recurrences.append(comp.recurrence_id.value)
  266. if comp.rruleset:
  267. # Prevent possible infinite loop
  268. raise ValueError("Overwritten recurrence with RRULESET")
  269. yield comp, True, ()
  270. else:
  271. if main is not None:
  272. raise ValueError("Multiple main components")
  273. main = comp
  274. if main is None:
  275. raise ValueError("Main component missing")
  276. yield main, False, recurrences
  277. # Comments give the lines in the tables of the specification
  278. if child_name == "VEVENT":
  279. for child, is_recurrence, recurrences in get_children(
  280. vobject_item.vevent_list):
  281. # TODO: check if there's a timezone
  282. dtstart = child.dtstart.value
  283. if child.rruleset:
  284. dtstarts, infinity = getrruleset(child, recurrences)
  285. if infinity:
  286. return
  287. else:
  288. dtstarts = (dtstart,)
  289. dtend = getattr(child, "dtend", None)
  290. if dtend is not None:
  291. dtend = dtend.value
  292. original_duration = (dtend - dtstart).total_seconds()
  293. dtend = _date_to_datetime(dtend)
  294. duration = getattr(child, "duration", None)
  295. if duration is not None:
  296. original_duration = duration = duration.value
  297. for dtstart in dtstarts:
  298. dtstart_is_datetime = isinstance(dtstart, datetime)
  299. dtstart = _date_to_datetime(dtstart)
  300. if dtend is not None:
  301. # Line 1
  302. dtend = dtstart + timedelta(seconds=original_duration)
  303. if range_fn(dtstart, dtend, is_recurrence):
  304. return
  305. elif duration is not None:
  306. if original_duration is None:
  307. original_duration = duration.seconds
  308. if duration.seconds > 0:
  309. # Line 2
  310. if range_fn(dtstart, dtstart + duration,
  311. is_recurrence):
  312. return
  313. else:
  314. # Line 3
  315. if range_fn(dtstart, dtstart + SECOND, is_recurrence):
  316. return
  317. elif dtstart_is_datetime:
  318. # Line 4
  319. if range_fn(dtstart, dtstart + SECOND, is_recurrence):
  320. return
  321. else:
  322. # Line 5
  323. if range_fn(dtstart, dtstart + DAY, is_recurrence):
  324. return
  325. elif child_name == "VTODO":
  326. for child, is_recurrence, recurrences in get_children(
  327. vobject_item.vtodo_list):
  328. dtstart = getattr(child, "dtstart", None)
  329. duration = getattr(child, "duration", None)
  330. due = getattr(child, "due", None)
  331. completed = getattr(child, "completed", None)
  332. created = getattr(child, "created", None)
  333. if dtstart is not None:
  334. dtstart = _date_to_datetime(dtstart.value)
  335. if duration is not None:
  336. duration = duration.value
  337. if due is not None:
  338. due = _date_to_datetime(due.value)
  339. if dtstart is not None:
  340. original_duration = (due - dtstart).total_seconds()
  341. if completed is not None:
  342. completed = _date_to_datetime(completed.value)
  343. if created is not None:
  344. created = _date_to_datetime(created.value)
  345. original_duration = (completed - created).total_seconds()
  346. elif created is not None:
  347. created = _date_to_datetime(created.value)
  348. if child.rruleset:
  349. reference_dates, infinity = getrruleset(child, recurrences)
  350. if infinity:
  351. return
  352. else:
  353. if dtstart is not None:
  354. reference_dates = (dtstart,)
  355. elif due is not None:
  356. reference_dates = (due,)
  357. elif completed is not None:
  358. reference_dates = (completed,)
  359. elif created is not None:
  360. reference_dates = (created,)
  361. else:
  362. # Line 8
  363. if range_fn(DATETIME_MIN, DATETIME_MAX, is_recurrence):
  364. return
  365. reference_dates = ()
  366. for reference_date in reference_dates:
  367. reference_date = _date_to_datetime(reference_date)
  368. if dtstart is not None and duration is not None:
  369. # Line 1
  370. if range_fn(reference_date,
  371. reference_date + duration + SECOND,
  372. is_recurrence):
  373. return
  374. if range_fn(reference_date + duration - SECOND,
  375. reference_date + duration + SECOND,
  376. is_recurrence):
  377. return
  378. elif dtstart is not None and due is not None:
  379. # Line 2
  380. due = reference_date + timedelta(seconds=original_duration)
  381. if (range_fn(reference_date, due, is_recurrence) or
  382. range_fn(reference_date,
  383. reference_date + SECOND, is_recurrence) or
  384. range_fn(due - SECOND, due, is_recurrence) or
  385. range_fn(due - SECOND, reference_date + SECOND,
  386. is_recurrence)):
  387. return
  388. elif dtstart is not None:
  389. if range_fn(reference_date, reference_date + SECOND,
  390. is_recurrence):
  391. return
  392. elif due is not None:
  393. # Line 4
  394. if range_fn(reference_date - SECOND, reference_date,
  395. is_recurrence):
  396. return
  397. elif completed is not None and created is not None:
  398. # Line 5
  399. completed = reference_date + timedelta(
  400. seconds=original_duration)
  401. if (range_fn(reference_date - SECOND,
  402. reference_date + SECOND,
  403. is_recurrence) or
  404. range_fn(completed - SECOND, completed + SECOND,
  405. is_recurrence) or
  406. range_fn(reference_date - SECOND,
  407. reference_date + SECOND, is_recurrence) or
  408. range_fn(completed - SECOND, completed + SECOND,
  409. is_recurrence)):
  410. return
  411. elif completed is not None:
  412. # Line 6
  413. if range_fn(reference_date - SECOND,
  414. reference_date + SECOND, is_recurrence):
  415. return
  416. elif created is not None:
  417. # Line 7
  418. if range_fn(reference_date, DATETIME_MAX, is_recurrence):
  419. return
  420. elif child_name == "VJOURNAL":
  421. for child, is_recurrence, recurrences in get_children(
  422. vobject_item.vjournal_list):
  423. dtstart = getattr(child, "dtstart", None)
  424. if dtstart is not None:
  425. dtstart = dtstart.value
  426. if child.rruleset:
  427. dtstarts, infinity = getrruleset(child, recurrences)
  428. if infinity:
  429. return
  430. else:
  431. dtstarts = (dtstart,)
  432. for dtstart in dtstarts:
  433. dtstart_is_datetime = isinstance(dtstart, datetime)
  434. dtstart = _date_to_datetime(dtstart)
  435. if dtstart_is_datetime:
  436. # Line 1
  437. if range_fn(dtstart, dtstart + SECOND, is_recurrence):
  438. return
  439. else:
  440. # Line 2
  441. if range_fn(dtstart, dtstart + DAY, is_recurrence):
  442. return
  443. else:
  444. # Match a property
  445. child = getattr(vobject_item, child_name.lower())
  446. if isinstance(child, date):
  447. range_fn(child, child + DAY, False)
  448. elif isinstance(child, datetime):
  449. range_fn(child, child + SECOND, False)
  450. def _text_match(vobject_item, filter_, child_name, ns, attrib_name=None):
  451. """Check whether the ``item`` matches the text-match ``filter_``.
  452. See rfc4791-9.7.5.
  453. """
  454. # TODO: collations are not supported, but the default ones needed
  455. # for DAV servers are actually pretty useless. Texts are lowered to
  456. # be case-insensitive, almost as the "i;ascii-casemap" value.
  457. text = next(filter_.itertext()).lower()
  458. match_type = "contains"
  459. if ns == "CR":
  460. match_type = filter_.get("match-type", match_type)
  461. def match(value):
  462. value = value.lower()
  463. if match_type == "equals":
  464. return value == text
  465. if match_type == "contains":
  466. return text in value
  467. if match_type == "starts-with":
  468. return value.startswith(text)
  469. if match_type == "ends-with":
  470. return value.endswith(text)
  471. raise ValueError("Unexpected text-match match-type: %r" % match_type)
  472. children = getattr(vobject_item, "%s_list" % child_name, [])
  473. if attrib_name:
  474. condition = any(
  475. match(attrib) for child in children
  476. for attrib in child.params.get(attrib_name, []))
  477. else:
  478. condition = any(match(child.value) for child in children)
  479. if filter_.get("negate-condition") == "yes":
  480. return not condition
  481. else:
  482. return condition
  483. def _param_filter_match(vobject_item, filter_, parent_name, ns):
  484. """Check whether the ``item`` matches the param-filter ``filter_``.
  485. See rfc4791-9.7.3.
  486. """
  487. name = filter_.get("name").upper()
  488. children = getattr(vobject_item, "%s_list" % parent_name, [])
  489. condition = any(name in child.params for child in children)
  490. if len(filter_):
  491. if filter_[0].tag == _tag(ns, "text-match"):
  492. return condition and _text_match(
  493. vobject_item, filter_[0], parent_name, ns, name)
  494. elif filter_[0].tag == _tag(ns, "is-not-defined"):
  495. return not condition
  496. else:
  497. return condition
  498. def simplify_prefilters(filters, collection_tag="VCALENDAR"):
  499. """Creates a simplified condition from ``filters``.
  500. Returns a tuple (``tag``, ``start``, ``end``, ``simple``) where ``tag`` is
  501. a string or None (match all) and ``start`` and ``end`` are POSIX
  502. timestamps (as int). ``simple`` is a bool that indicates that ``filters``
  503. and the simplified condition are identical.
  504. """
  505. flat_filters = tuple(chain.from_iterable(filters))
  506. simple = len(flat_filters) <= 1
  507. for col_filter in flat_filters:
  508. if collection_tag != "VCALENDAR":
  509. simple = False
  510. break
  511. if (col_filter.tag != _tag("C", "comp-filter") or
  512. col_filter.get("name").upper() != "VCALENDAR"):
  513. simple = False
  514. continue
  515. simple &= len(col_filter) <= 1
  516. for comp_filter in col_filter:
  517. if comp_filter.tag != _tag("C", "comp-filter"):
  518. simple = False
  519. continue
  520. tag = comp_filter.get("name").upper()
  521. if comp_filter.find(_tag("C", "is-not-defined")) is not None:
  522. simple = False
  523. continue
  524. simple &= len(comp_filter) <= 1
  525. for time_filter in comp_filter:
  526. if tag not in ("VTODO", "VEVENT", "VJOURNAL"):
  527. simple = False
  528. break
  529. if time_filter.tag != _tag("C", "time-range"):
  530. simple = False
  531. continue
  532. start = time_filter.get("start")
  533. end = time_filter.get("end")
  534. if start:
  535. start = math.floor(datetime.strptime(
  536. start, "%Y%m%dT%H%M%SZ").replace(
  537. tzinfo=timezone.utc).timestamp())
  538. else:
  539. start = TIMESTAMP_MIN
  540. if end:
  541. end = math.ceil(datetime.strptime(
  542. end, "%Y%m%dT%H%M%SZ").replace(
  543. tzinfo=timezone.utc).timestamp())
  544. else:
  545. end = TIMESTAMP_MAX
  546. return tag, start, end, simple
  547. return tag, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
  548. return None, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
  549. def get_content_type(item):
  550. """Get the content-type of an item with charset and component parameters.
  551. """
  552. mimetype = OBJECT_MIMETYPES[item.name]
  553. encoding = item.collection.configuration.get("encoding", "request")
  554. tag = item.component_name
  555. content_type = "%s;charset=%s" % (mimetype, encoding)
  556. if tag:
  557. content_type += ";component=%s" % tag
  558. return content_type
  559. def find_tag(vobject_item):
  560. """Find component name from ``vobject_item``."""
  561. if vobject_item.name == "VCALENDAR":
  562. for component in vobject_item.components():
  563. if component.name != "VTIMEZONE":
  564. return component.name
  565. return None
  566. def find_tag_and_time_range(vobject_item):
  567. """Find component name and enclosing time range from ``vobject item``.
  568. Returns a tuple (``tag``, ``start``, ``end``) where ``tag`` is a string
  569. and ``start`` and ``end`` are POSIX timestamps (as int).
  570. This is intened to be used for matching against simplified prefilters.
  571. """
  572. tag = find_tag(vobject_item)
  573. if not tag:
  574. return (None, TIMESTAMP_MIN, TIMESTAMP_MAX)
  575. start = end = None
  576. def range_fn(range_start, range_end, is_recurrence):
  577. nonlocal start, end
  578. if start is None or range_start < start:
  579. start = range_start
  580. if end is None or end < range_end:
  581. end = range_end
  582. return False
  583. def infinity_fn(range_start):
  584. nonlocal start, end
  585. if start is None or range_start < start:
  586. start = range_start
  587. end = DATETIME_MAX
  588. return True
  589. _visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  590. if start is None:
  591. start = DATETIME_MIN
  592. if end is None:
  593. end = DATETIME_MAX
  594. try:
  595. return tag, math.floor(start.timestamp()), math.ceil(end.timestamp())
  596. except ValueError as e:
  597. if str(e) == ("offset must be a timedelta representing a whole "
  598. "number of minutes") and sys.version_info < (3, 6):
  599. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  600. raise
  601. def name_from_path(path, collection):
  602. """Return Radicale item name from ``path``."""
  603. path = path.strip("/") + "/"
  604. start = collection.path + "/"
  605. if not path.startswith(start):
  606. raise ValueError("%r doesn't start with %r" % (path, start))
  607. name = path[len(start):][:-1]
  608. if name and not storage.is_safe_path_component(name):
  609. raise ValueError("%r is not a component in collection %r" %
  610. (name, collection.path))
  611. return name
  612. def props_from_request(xml_request, actions=("set", "remove")):
  613. """Return a list of properties as a dictionary."""
  614. result = OrderedDict()
  615. if xml_request is None:
  616. return result
  617. for action in actions:
  618. action_element = xml_request.find(_tag("D", action))
  619. if action_element is not None:
  620. break
  621. else:
  622. action_element = xml_request
  623. prop_element = action_element.find(_tag("D", "prop"))
  624. if prop_element is not None:
  625. for prop in prop_element:
  626. if prop.tag == _tag("D", "resourcetype"):
  627. for resource_type in prop:
  628. if resource_type.tag == _tag("C", "calendar"):
  629. result["tag"] = "VCALENDAR"
  630. break
  631. elif resource_type.tag == _tag("CR", "addressbook"):
  632. result["tag"] = "VADDRESSBOOK"
  633. break
  634. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  635. result[_tag_from_clark(prop.tag)] = ",".join(
  636. supported_comp.attrib["name"]
  637. for supported_comp in prop
  638. if supported_comp.tag == _tag("C", "comp"))
  639. else:
  640. result[_tag_from_clark(prop.tag)] = prop.text
  641. return result
  642. def delete(base_prefix, path, collection, href=None):
  643. """Read and answer DELETE requests.
  644. Read rfc4918-9.6 for info.
  645. """
  646. collection.delete(href)
  647. multistatus = ET.Element(_tag("D", "multistatus"))
  648. response = ET.Element(_tag("D", "response"))
  649. multistatus.append(response)
  650. href = ET.Element(_tag("D", "href"))
  651. href.text = _href(base_prefix, path)
  652. response.append(href)
  653. status = ET.Element(_tag("D", "status"))
  654. status.text = _response(200)
  655. response.append(status)
  656. return multistatus
  657. def propfind(base_prefix, path, xml_request, read_collections,
  658. write_collections, 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. collections = []
  685. for collection in write_collections:
  686. collections.append(collection)
  687. response = _propfind_response(
  688. base_prefix, path, collection, props, user, write=True,
  689. allprop=allprop, propname=propname)
  690. if response:
  691. multistatus.append(response)
  692. for collection in read_collections:
  693. if collection in collections:
  694. continue
  695. response = _propfind_response(
  696. base_prefix, path, collection, props, user, write=False,
  697. allprop=allprop, propname=propname)
  698. if response:
  699. multistatus.append(response)
  700. return client.MULTI_STATUS, multistatus
  701. def _propfind_response(base_prefix, path, item, props, user, write=False,
  702. propname=False, allprop=False):
  703. """Build and return a PROPFIND response."""
  704. if propname and allprop or (props and (propname or allprop)):
  705. raise ValueError("Only use one of props, propname and allprops")
  706. is_collection = isinstance(item, storage.BaseCollection)
  707. if is_collection:
  708. is_leaf = item.get_meta("tag") in ("VADDRESSBOOK", "VCALENDAR")
  709. collection = item
  710. else:
  711. collection = item.collection
  712. response = ET.Element(_tag("D", "response"))
  713. href = ET.Element(_tag("D", "href"))
  714. if is_collection:
  715. # Some clients expect collections to end with /
  716. uri = "/%s/" % item.path if item.path else "/"
  717. else:
  718. uri = "/" + posixpath.join(collection.path, item.href)
  719. href.text = _href(base_prefix, uri)
  720. response.append(href)
  721. propstat404 = ET.Element(_tag("D", "propstat"))
  722. propstat200 = ET.Element(_tag("D", "propstat"))
  723. response.append(propstat200)
  724. prop200 = ET.Element(_tag("D", "prop"))
  725. propstat200.append(prop200)
  726. prop404 = ET.Element(_tag("D", "prop"))
  727. propstat404.append(prop404)
  728. if propname or allprop:
  729. props = []
  730. # Should list all properties that can be retrieved by the code below
  731. props.append(_tag("D", "principal-collection-set"))
  732. props.append(_tag("D", "current-user-principal"))
  733. props.append(_tag("D", "current-user-privilege-set"))
  734. props.append(_tag("D", "supported-report-set"))
  735. props.append(_tag("D", "resourcetype"))
  736. props.append(_tag("D", "owner"))
  737. if is_collection and collection.is_principal:
  738. props.append(_tag("C", "calendar-user-address-set"))
  739. props.append(_tag("D", "principal-URL"))
  740. props.append(_tag("CR", "addressbook-home-set"))
  741. props.append(_tag("C", "calendar-home-set"))
  742. if not is_collection or is_leaf:
  743. props.append(_tag("D", "getetag"))
  744. props.append(_tag("D", "getlastmodified"))
  745. props.append(_tag("D", "getcontenttype"))
  746. props.append(_tag("D", "getcontentlength"))
  747. if is_collection:
  748. if is_leaf:
  749. props.append(_tag("D", "displayname"))
  750. props.append(_tag("D", "sync-token"))
  751. if collection.get_meta("tag") == "VCALENDAR":
  752. props.append(_tag("CS", "getctag"))
  753. props.append(_tag("C", "supported-calendar-component-set"))
  754. meta = item.get_meta()
  755. for tag in meta:
  756. if tag == "tag":
  757. continue
  758. clark_tag = _tag_from_human(tag)
  759. if clark_tag not in props:
  760. props.append(clark_tag)
  761. if propname:
  762. for tag in props:
  763. prop200.append(ET.Element(tag))
  764. props = ()
  765. for tag in props:
  766. element = ET.Element(tag)
  767. is404 = False
  768. if tag == _tag("D", "getetag"):
  769. if not is_collection or is_leaf:
  770. element.text = item.etag
  771. else:
  772. is404 = True
  773. elif tag == _tag("D", "getlastmodified"):
  774. if not is_collection or is_leaf:
  775. element.text = item.last_modified
  776. else:
  777. is404 = True
  778. elif tag == _tag("D", "principal-collection-set"):
  779. tag = ET.Element(_tag("D", "href"))
  780. tag.text = _href(base_prefix, "/")
  781. element.append(tag)
  782. elif (tag in (_tag("C", "calendar-user-address-set"),
  783. _tag("D", "principal-URL"),
  784. _tag("CR", "addressbook-home-set"),
  785. _tag("C", "calendar-home-set")) and
  786. collection.is_principal and is_collection):
  787. tag = ET.Element(_tag("D", "href"))
  788. tag.text = _href(base_prefix, path)
  789. element.append(tag)
  790. elif tag == _tag("C", "supported-calendar-component-set"):
  791. human_tag = _tag_from_clark(tag)
  792. if is_collection and is_leaf:
  793. meta = item.get_meta(human_tag)
  794. if meta:
  795. components = meta.split(",")
  796. else:
  797. components = ("VTODO", "VEVENT", "VJOURNAL")
  798. for component in components:
  799. comp = ET.Element(_tag("C", "comp"))
  800. comp.set("name", component)
  801. element.append(comp)
  802. else:
  803. is404 = True
  804. elif tag == _tag("D", "current-user-principal"):
  805. if user:
  806. tag = ET.Element(_tag("D", "href"))
  807. tag.text = _href(base_prefix, "/%s/" % user)
  808. element.append(tag)
  809. else:
  810. element.append(ET.Element(_tag("D", "unauthenticated")))
  811. elif tag == _tag("D", "current-user-privilege-set"):
  812. privileges = [("D", "read")]
  813. if write:
  814. privileges.append(("D", "all"))
  815. privileges.append(("D", "write"))
  816. privileges.append(("D", "write-properties"))
  817. privileges.append(("D", "write-content"))
  818. for ns, privilege_name in privileges:
  819. privilege = ET.Element(_tag("D", "privilege"))
  820. privilege.append(ET.Element(_tag(ns, privilege_name)))
  821. element.append(privilege)
  822. elif tag == _tag("D", "supported-report-set"):
  823. # These 3 reports are not implemented
  824. reports = [
  825. ("D", "expand-property"),
  826. ("D", "principal-search-property-set"),
  827. ("D", "principal-property-search")]
  828. if is_collection and is_leaf:
  829. reports.append(("D", "sync-collection"))
  830. if item.get_meta("tag") == "VADDRESSBOOK":
  831. reports.append(("CR", "addressbook-multiget"))
  832. reports.append(("CR", "addressbook-query"))
  833. elif item.get_meta("tag") == "VCALENDAR":
  834. reports.append(("C", "calendar-multiget"))
  835. reports.append(("C", "calendar-query"))
  836. for ns, report_name in reports:
  837. supported = ET.Element(_tag("D", "supported-report"))
  838. report_tag = ET.Element(_tag("D", "report"))
  839. supported_report_tag = ET.Element(_tag(ns, report_name))
  840. report_tag.append(supported_report_tag)
  841. supported.append(report_tag)
  842. element.append(supported)
  843. elif tag == _tag("D", "getcontentlength"):
  844. if not is_collection or is_leaf:
  845. encoding = collection.configuration.get("encoding", "request")
  846. element.text = str(len(item.serialize().encode(encoding)))
  847. else:
  848. is404 = True
  849. elif tag == _tag("D", "owner"):
  850. # return empty elment, if no owner available (rfc3744-5.1)
  851. if collection.owner:
  852. tag = ET.Element(_tag("D", "href"))
  853. tag.text = _href(base_prefix, "/%s/" % collection.owner)
  854. element.append(tag)
  855. elif is_collection:
  856. if tag == _tag("D", "getcontenttype"):
  857. if is_leaf:
  858. element.text = MIMETYPES[item.get_meta("tag")]
  859. else:
  860. is404 = True
  861. elif tag == _tag("D", "resourcetype"):
  862. if item.is_principal:
  863. tag = ET.Element(_tag("D", "principal"))
  864. element.append(tag)
  865. if is_leaf:
  866. if item.get_meta("tag") == "VADDRESSBOOK":
  867. tag = ET.Element(_tag("CR", "addressbook"))
  868. element.append(tag)
  869. elif item.get_meta("tag") == "VCALENDAR":
  870. tag = ET.Element(_tag("C", "calendar"))
  871. element.append(tag)
  872. tag = ET.Element(_tag("D", "collection"))
  873. element.append(tag)
  874. elif tag == _tag("RADICALE", "displayname"):
  875. # Only for internal use by the web interface
  876. displayname = item.get_meta("D:displayname")
  877. if displayname is not None:
  878. element.text = displayname
  879. else:
  880. is404 = True
  881. elif tag == _tag("D", "displayname"):
  882. displayname = item.get_meta("D:displayname")
  883. if not displayname and is_leaf:
  884. displayname = item.path
  885. if displayname is not None:
  886. element.text = displayname
  887. else:
  888. is404 = True
  889. elif tag == _tag("CS", "getctag"):
  890. if is_leaf:
  891. element.text = item.etag
  892. else:
  893. is404 = True
  894. elif tag == _tag("D", "sync-token"):
  895. if is_leaf:
  896. element.text, _ = item.sync()
  897. else:
  898. is404 = True
  899. else:
  900. human_tag = _tag_from_clark(tag)
  901. meta = item.get_meta(human_tag)
  902. if meta is not None:
  903. element.text = meta
  904. else:
  905. is404 = True
  906. # Not for collections
  907. elif tag == _tag("D", "getcontenttype"):
  908. element.text = get_content_type(item)
  909. elif tag == _tag("D", "resourcetype"):
  910. # resourcetype must be returned empty for non-collection elements
  911. pass
  912. else:
  913. is404 = True
  914. if is404:
  915. prop404.append(element)
  916. else:
  917. prop200.append(element)
  918. status200 = ET.Element(_tag("D", "status"))
  919. status200.text = _response(200)
  920. propstat200.append(status200)
  921. status404 = ET.Element(_tag("D", "status"))
  922. status404.text = _response(404)
  923. propstat404.append(status404)
  924. if len(prop404):
  925. response.append(propstat404)
  926. return response
  927. def _add_propstat_to(element, tag, status_number):
  928. """Add a PROPSTAT response structure to an element.
  929. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  930. given ``element``, for the following ``tag`` with the given
  931. ``status_number``.
  932. """
  933. propstat = ET.Element(_tag("D", "propstat"))
  934. element.append(propstat)
  935. prop = ET.Element(_tag("D", "prop"))
  936. propstat.append(prop)
  937. clark_tag = tag if "{" in tag else _tag(*tag.split(":", 1))
  938. prop_tag = ET.Element(clark_tag)
  939. prop.append(prop_tag)
  940. status = ET.Element(_tag("D", "status"))
  941. status.text = _response(status_number)
  942. propstat.append(status)
  943. def proppatch(base_prefix, path, xml_request, collection):
  944. """Read and answer PROPPATCH requests.
  945. Read rfc4918-9.2 for info.
  946. """
  947. props_to_set = props_from_request(xml_request, actions=("set",))
  948. props_to_remove = props_from_request(xml_request, actions=("remove",))
  949. multistatus = ET.Element(_tag("D", "multistatus"))
  950. response = ET.Element(_tag("D", "response"))
  951. multistatus.append(response)
  952. href = ET.Element(_tag("D", "href"))
  953. href.text = _href(base_prefix, path)
  954. response.append(href)
  955. new_props = collection.get_meta()
  956. for short_name, value in props_to_set.items():
  957. new_props[short_name] = value
  958. _add_propstat_to(response, short_name, 200)
  959. for short_name in props_to_remove:
  960. try:
  961. del new_props[short_name]
  962. except KeyError:
  963. pass
  964. _add_propstat_to(response, short_name, 200)
  965. storage.check_and_sanitize_props(new_props)
  966. collection.set_meta_all(new_props)
  967. return multistatus
  968. def report(base_prefix, path, xml_request, collection):
  969. """Read and answer REPORT requests.
  970. Read rfc3253-3.6 for info.
  971. """
  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.CONFLICT,
  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.CONFLICT,
  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