xmlutils.py 49 KB

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