xmlutils.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 posixpath
  25. import re
  26. import xml.etree.ElementTree as ET
  27. from collections import OrderedDict
  28. from datetime import datetime, timedelta, timezone
  29. from urllib.parse import unquote, urlparse
  30. import vobject
  31. from . import client, storage
  32. NAMESPACES = {
  33. "C": "urn:ietf:params:xml:ns:caldav",
  34. "CR": "urn:ietf:params:xml:ns:carddav",
  35. "D": "DAV:",
  36. "CS": "http://calendarserver.org/ns/",
  37. "ICAL": "http://apple.com/ns/ical/",
  38. "ME": "http://me.com/_namespace/"}
  39. NAMESPACES_REV = {}
  40. for short, url in NAMESPACES.items():
  41. NAMESPACES_REV[url] = short
  42. ET.register_namespace("" if short == "D" else short, url)
  43. CLARK_TAG_REGEX = re.compile(r"""
  44. { # {
  45. (?P<namespace>[^}]*) # namespace URL
  46. } # }
  47. (?P<tag>.*) # short tag name
  48. """, re.VERBOSE)
  49. def _pretty_xml(element, level=0):
  50. """Indent an ElementTree ``element`` and its children."""
  51. i = "\n" + level * " "
  52. if len(element):
  53. if not element.text or not element.text.strip():
  54. element.text = i + " "
  55. if not element.tail or not element.tail.strip():
  56. element.tail = i
  57. for sub_element in element:
  58. _pretty_xml(sub_element, level + 1)
  59. # ``sub_element`` is always defined as len(element) > 0
  60. # pylint: disable=W0631
  61. if not sub_element.tail or not sub_element.tail.strip():
  62. sub_element.tail = i
  63. # pylint: enable=W0631
  64. else:
  65. if level and (not element.tail or not element.tail.strip()):
  66. element.tail = i
  67. if not level:
  68. return '<?xml version="1.0"?>\n%s' % ET.tostring(element, "unicode")
  69. def _tag(short_name, local):
  70. """Get XML Clark notation {uri(``short_name``)}``local``."""
  71. return "{%s}%s" % (NAMESPACES[short_name], local)
  72. def _tag_from_clark(name):
  73. """Get a human-readable variant of the XML Clark notation tag ``name``.
  74. For a given name using the XML Clark notation, return a human-readable
  75. variant of the tag name for known namespaces. Otherwise, return the name as
  76. is.
  77. """
  78. match = CLARK_TAG_REGEX.match(name)
  79. if match and match.group("namespace") in NAMESPACES_REV:
  80. args = {
  81. "ns": NAMESPACES_REV[match.group("namespace")],
  82. "tag": match.group("tag")}
  83. return "%(ns)s:%(tag)s" % args
  84. return name
  85. def _response(code):
  86. """Return full W3C names from HTTP status codes."""
  87. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  88. def _href(collection, href):
  89. """Return prefixed href."""
  90. return "%s%s" % (
  91. collection.configuration.get("server", "base_prefix"),
  92. href.lstrip("/"))
  93. def _comp_match(item, filter_, scope="collection"):
  94. """Check whether the ``item`` matches the comp ``filter_``.
  95. If ``scope`` is ``"collection"``, the filter is applied on the
  96. item's collection. Otherwise, it's applied on the item.
  97. See rfc4791-9.7.1.
  98. """
  99. filter_length = len(filter_)
  100. if scope == "collection":
  101. tag = item.collection.get_meta("tag")
  102. else:
  103. for component in item.components():
  104. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  105. tag = component.name
  106. break
  107. else:
  108. return False
  109. if filter_length == 0:
  110. # Point #1 of rfc4791-9.7.1
  111. return filter_.get("name") == tag
  112. else:
  113. if filter_length == 1:
  114. if filter_[0].tag == _tag("C", "is-not-defined"):
  115. # Point #2 of rfc4791-9.7.1
  116. return filter_.get("name") != tag
  117. if filter_[0].tag == _tag("C", "time-range"):
  118. # Point #3 of rfc4791-9.7.1
  119. if not _time_range_match(item.item, filter_[0], tag):
  120. return False
  121. filter_ = filter_[1:]
  122. # Point #4 of rfc4791-9.7.1
  123. return all(
  124. _prop_match(item, child) if child.tag == _tag("C", "prop-filter")
  125. else _comp_match(item, child, scope="component")
  126. for child in filter_)
  127. def _prop_match(item, filter_):
  128. """Check whether the ``item`` matches the prop ``filter_``.
  129. See rfc4791-9.7.2 and rfc6352-10.5.1.
  130. """
  131. filter_length = len(filter_)
  132. if item.collection.get_meta("tag") == "VCALENDAR":
  133. for component in item.components():
  134. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  135. vobject_item = component
  136. else:
  137. vobject_item = item.item
  138. if filter_length == 0:
  139. # Point #1 of rfc4791-9.7.2
  140. return filter_.get("name").lower() in vobject_item.contents
  141. else:
  142. name = filter_.get("name").lower()
  143. if filter_length == 1:
  144. if filter_[0].tag == _tag("C", "is-not-defined"):
  145. # Point #2 of rfc4791-9.7.2
  146. return name not in vobject_item.contents
  147. if filter_[0].tag == _tag("C", "time-range"):
  148. # Point #3 of rfc4791-9.7.2
  149. if not _time_range_match(vobject_item, filter_[0], name):
  150. return False
  151. filter_ = filter_[1:]
  152. elif filter_[0].tag == _tag("C", "text-match"):
  153. # Point #4 of rfc4791-9.7.2
  154. if not _text_match(vobject_item, filter_[0], name):
  155. return False
  156. filter_ = filter_[1:]
  157. return all(
  158. _param_filter_match(vobject_item, param_filter, name)
  159. for param_filter in filter_)
  160. def _time_range_match(vobject_item, filter_, child_name):
  161. """Check whether the ``item`` matches the time-range ``filter_``.
  162. See rfc4791-9.9.
  163. """
  164. start = filter_.get("start")
  165. end = filter_.get("end")
  166. if not start and not end:
  167. return False
  168. if start:
  169. start = datetime.strptime(start, "%Y%m%dT%H%M%SZ")
  170. else:
  171. start = datetime.datetime.min
  172. if end:
  173. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  174. else:
  175. end = datetime.datetime.max
  176. start = start.replace(tzinfo=timezone.utc)
  177. end = end.replace(tzinfo=timezone.utc)
  178. child = getattr(vobject_item, child_name.lower())
  179. # Comments give the lines in the tables of the specification
  180. if child_name == "VEVENT":
  181. # TODO: check if there's a timezone
  182. dtstart = child.dtstart.value
  183. if not isinstance(dtstart, datetime):
  184. dtstart_is_datetime = False
  185. # TODO: changing dates to datetimes may be wrong because of tz
  186. dtstart = datetime.combine(dtstart, datetime.min.time()).replace(
  187. tzinfo=timezone.utc)
  188. else:
  189. dtstart_is_datetime = True
  190. dtend = getattr(child, "dtend", None)
  191. duration = getattr(child, "duration", None)
  192. if dtend is not None:
  193. # Line 1
  194. dtend = dtend.value
  195. if not isinstance(dtend, datetime):
  196. dtend = datetime.combine(dtend, datetime.min.time()).replace(
  197. tzinfo=timezone.utc)
  198. return start < dtend and end > dtstart
  199. elif duration is not None:
  200. duration = duration.value
  201. if duration.seconds > 0:
  202. # Line 2
  203. return start < dtstart + duration and end > dtstart
  204. else:
  205. # Line 3
  206. return start <= dtstart and end > dtstart
  207. elif dtstart_is_datetime:
  208. # Line 4
  209. return start <= dtstart and end > dtstart
  210. else:
  211. # Line 5
  212. return start < dtstart + timedelta(days=1) and end > dtstart
  213. elif child_name == "VTODO":
  214. # TODO: implement this
  215. pass
  216. elif child_name == "VJOURNAL":
  217. # TODO: implement this
  218. pass
  219. return True
  220. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  221. """Check whether the ``item`` matches the text-match ``filter_``.
  222. See rfc4791-9.7.5.
  223. """
  224. # TODO: collations are not supported, but the default ones needed
  225. # for DAV servers are actually pretty useless. Texts are lowered to
  226. # be case-insensitive, almost as the "i;ascii-casemap" value.
  227. match = next(filter_.itertext()).lower()
  228. children = getattr(vobject_item, "%s_list" % child_name, [])
  229. if attrib_name:
  230. condition = any(
  231. match in attrib.lower() for child in children
  232. for attrib in child.params.get(attrib_name, []))
  233. else:
  234. condition = any(match in child.value.lower() for child in children)
  235. if filter_.get("negate-condition") == "yes":
  236. return not condition
  237. else:
  238. return condition
  239. def _param_filter_match(vobject_item, filter_, parent_name):
  240. """Check whether the ``item`` matches the param-filter ``filter_``.
  241. See rfc4791-9.7.3.
  242. """
  243. name = filter_.get("name")
  244. children = getattr(vobject_item, "%s_list" % parent_name, [])
  245. condition = any(name in child.params for child in children)
  246. if len(filter_):
  247. if filter_[0].tag == _tag("C", "text-match"):
  248. return condition and _text_match(
  249. vobject_item, filter_[0], parent_name, name)
  250. elif filter_[0].tag == _tag("C", "is-not-defined"):
  251. return not condition
  252. else:
  253. return condition
  254. def name_from_path(path, collection):
  255. """Return Radicale item name from ``path``."""
  256. collection_parts = collection.path.strip("/").split("/")
  257. path_parts = path.strip("/").split("/")
  258. if (len(path_parts) - len(collection_parts)):
  259. return path_parts[-1]
  260. def props_from_request(root, actions=("set", "remove")):
  261. """Return a list of properties as a dictionary."""
  262. result = OrderedDict()
  263. if root:
  264. if not hasattr(root, "tag"):
  265. root = ET.fromstring(root.encode("utf8"))
  266. else:
  267. return result
  268. for action in actions:
  269. action_element = root.find(_tag("D", action))
  270. if action_element is not None:
  271. break
  272. else:
  273. action_element = root
  274. prop_element = action_element.find(_tag("D", "prop"))
  275. if prop_element is not None:
  276. for prop in prop_element:
  277. if prop.tag == _tag("D", "resourcetype"):
  278. for resource_type in prop:
  279. if resource_type.tag == _tag("C", "calendar"):
  280. result["tag"] = "VCALENDAR"
  281. break
  282. elif resource_type.tag == _tag("CR", "addressbook"):
  283. result["tag"] = "VADDRESSBOOK"
  284. break
  285. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  286. result[_tag_from_clark(prop.tag)] = ",".join(
  287. supported_comp.attrib["name"]
  288. for supported_comp in prop
  289. if supported_comp.tag == _tag("C", "comp"))
  290. else:
  291. result[_tag_from_clark(prop.tag)] = prop.text
  292. return result
  293. def delete(path, collection):
  294. """Read and answer DELETE requests.
  295. Read rfc4918-9.6 for info.
  296. """
  297. # Reading request
  298. if collection.path == path.strip("/"):
  299. # Delete the whole collection
  300. collection.delete()
  301. else:
  302. # Remove an item from the collection
  303. collection.delete(name_from_path(path, collection))
  304. # Writing answer
  305. multistatus = ET.Element(_tag("D", "multistatus"))
  306. response = ET.Element(_tag("D", "response"))
  307. multistatus.append(response)
  308. href = ET.Element(_tag("D", "href"))
  309. href.text = _href(collection, path)
  310. response.append(href)
  311. status = ET.Element(_tag("D", "status"))
  312. status.text = _response(200)
  313. response.append(status)
  314. return _pretty_xml(multistatus)
  315. def propfind(path, xml_request, read_collections, write_collections,
  316. user=None):
  317. """Read and answer PROPFIND requests.
  318. Read rfc4918-9.1 for info.
  319. The collections parameter is a list of collections that are to be included
  320. in the output.
  321. """
  322. # Reading request
  323. if xml_request:
  324. root = ET.fromstring(xml_request.encode("utf8"))
  325. props = [prop.tag for prop in root.find(_tag("D", "prop"))]
  326. else:
  327. props = [_tag("D", "getcontenttype"),
  328. _tag("D", "resourcetype"),
  329. _tag("D", "displayname"),
  330. _tag("D", "owner"),
  331. _tag("D", "getetag"),
  332. _tag("ICAL", "calendar-color"),
  333. _tag("CS", "getctag")]
  334. # Writing answer
  335. multistatus = ET.Element(_tag("D", "multistatus"))
  336. collections = []
  337. for collection in write_collections:
  338. collections.append(collection)
  339. response = _propfind_response(
  340. path, collection, props, user, write=True)
  341. multistatus.append(response)
  342. for collection in read_collections:
  343. if collection in collections:
  344. continue
  345. response = _propfind_response(
  346. path, collection, props, user, write=False)
  347. multistatus.append(response)
  348. return _pretty_xml(multistatus)
  349. def _propfind_response(path, item, props, user, write=False):
  350. """Build and return a PROPFIND response."""
  351. # TODO: fix this
  352. is_collection = hasattr(item, "list")
  353. if is_collection:
  354. is_leaf = bool(item.list())
  355. collection = item
  356. else:
  357. collection = item.collection
  358. response = ET.Element(_tag("D", "response"))
  359. href = ET.Element(_tag("D", "href"))
  360. if is_collection:
  361. uri = item.path
  362. else:
  363. # TODO: fix this
  364. if path.split("/")[-1] == item.href:
  365. # Happening when depth is 0
  366. uri = path
  367. else:
  368. # Happening when depth is 1
  369. uri = "/".join((path, item.href))
  370. # TODO: fix this
  371. href.text = _href(collection, uri.replace("//", "/"))
  372. response.append(href)
  373. propstat404 = ET.Element(_tag("D", "propstat"))
  374. propstat200 = ET.Element(_tag("D", "propstat"))
  375. response.append(propstat200)
  376. prop200 = ET.Element(_tag("D", "prop"))
  377. propstat200.append(prop200)
  378. prop404 = ET.Element(_tag("D", "prop"))
  379. propstat404.append(prop404)
  380. for tag in props:
  381. element = ET.Element(tag)
  382. is404 = False
  383. if tag == _tag("D", "getetag"):
  384. element.text = item.etag
  385. elif tag == _tag("D", "principal-URL"):
  386. tag = ET.Element(_tag("D", "href"))
  387. tag.text = _href(collection, path)
  388. element.append(tag)
  389. elif tag == _tag("D", "getlastmodified"):
  390. element.text = item.last_modified
  391. elif tag in (_tag("D", "principal-collection-set"),
  392. _tag("C", "calendar-user-address-set"),
  393. _tag("CR", "addressbook-home-set"),
  394. _tag("C", "calendar-home-set")):
  395. tag = ET.Element(_tag("D", "href"))
  396. tag.text = _href(collection, path)
  397. element.append(tag)
  398. elif tag == _tag("C", "supported-calendar-component-set"):
  399. # This is not a Todo
  400. # pylint: disable=W0511
  401. human_tag = _tag_from_clark(tag)
  402. if is_collection and is_leaf:
  403. meta = item.get_meta(human_tag)
  404. if meta:
  405. components = meta.split(",")
  406. else:
  407. components = ("VTODO", "VEVENT", "VJOURNAL")
  408. for component in components:
  409. comp = ET.Element(_tag("C", "comp"))
  410. comp.set("name", component)
  411. element.append(comp)
  412. else:
  413. is404 = True
  414. # pylint: enable=W0511
  415. elif tag == _tag("D", "current-user-principal") and user:
  416. tag = ET.Element(_tag("D", "href"))
  417. tag.text = _href(collection, "/%s/" % user)
  418. element.append(tag)
  419. elif tag == _tag("D", "current-user-privilege-set"):
  420. privilege = ET.Element(_tag("D", "privilege"))
  421. if write:
  422. privilege.append(ET.Element(_tag("D", "all")))
  423. privilege.append(ET.Element(_tag("D", "write")))
  424. privilege.append(ET.Element(_tag("D", "write-properties")))
  425. privilege.append(ET.Element(_tag("D", "write-content")))
  426. privilege.append(ET.Element(_tag("D", "read")))
  427. element.append(privilege)
  428. elif tag == _tag("D", "supported-report-set"):
  429. for report_name in (
  430. "principal-property-search", "sync-collection",
  431. "expand-property", "principal-search-property-set"):
  432. supported = ET.Element(_tag("D", "supported-report"))
  433. report_tag = ET.Element(_tag("D", "report"))
  434. report_tag.text = report_name
  435. supported.append(report_tag)
  436. element.append(supported)
  437. elif is_collection:
  438. if tag == _tag("D", "getcontenttype"):
  439. item_tag = item.get_meta("tag")
  440. if item_tag:
  441. element.text = storage.MIMETYPES[item_tag]
  442. else:
  443. is404 = True
  444. elif tag == _tag("D", "resourcetype"):
  445. if item.is_principal:
  446. tag = ET.Element(_tag("D", "principal"))
  447. element.append(tag)
  448. item_tag = item.get_meta("tag")
  449. if is_leaf or item_tag:
  450. # 2nd case happens when the collection is not stored yet,
  451. # but the resource type is guessed
  452. if item.get_meta("tag") == "VADDRESSBOOK":
  453. tag = ET.Element(_tag("CR", "addressbook"))
  454. element.append(tag)
  455. elif item.get_meta("tag") == "VCALENDAR":
  456. tag = ET.Element(_tag("C", "calendar"))
  457. element.append(tag)
  458. tag = ET.Element(_tag("D", "collection"))
  459. element.append(tag)
  460. elif is_leaf:
  461. if tag == _tag("D", "owner") and item.owner:
  462. element.text = "/%s/" % item.owner
  463. elif tag == _tag("CS", "getctag"):
  464. element.text = item.etag
  465. elif tag == _tag("C", "calendar-timezone"):
  466. timezones = set()
  467. for href, _ in item.list():
  468. event = item.get(href)
  469. if "vtimezone" in event.contents:
  470. for timezone_ in event.vtimezone_list:
  471. timezones.add(timezone_)
  472. timezone_collection = vobject.iCalendar()
  473. for timezone_ in timezones:
  474. timezone_collection.add(timezone_)
  475. element.text = timezone_collection.serialize()
  476. elif tag == _tag("D", "displayname"):
  477. element.text = item.get_meta("D:displayname") or item.path
  478. elif tag == _tag("ICAL", "calendar-color"):
  479. element.text = item.get_meta("ICAL:calendar-color")
  480. else:
  481. human_tag = _tag_from_clark(tag)
  482. meta = item.get_meta(human_tag)
  483. if meta:
  484. element.text = meta
  485. else:
  486. is404 = True
  487. else:
  488. is404 = True
  489. # Not for collections
  490. elif tag == _tag("D", "getcontenttype"):
  491. name = item.name.lower()
  492. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  493. element.text = "%s; component=%s" % (mimetype, name)
  494. elif tag == _tag("D", "resourcetype"):
  495. # resourcetype must be returned empty for non-collection elements
  496. pass
  497. elif tag == _tag("D", "getcontentlength"):
  498. encoding = collection.configuration.get("encoding", "request")
  499. element.text = str(len(item.serialize().encode(encoding)))
  500. else:
  501. is404 = True
  502. if is404:
  503. prop404.append(element)
  504. else:
  505. prop200.append(element)
  506. status200 = ET.Element(_tag("D", "status"))
  507. status200.text = _response(200)
  508. propstat200.append(status200)
  509. status404 = ET.Element(_tag("D", "status"))
  510. status404.text = _response(404)
  511. propstat404.append(status404)
  512. if len(prop404):
  513. response.append(propstat404)
  514. return response
  515. def _add_propstat_to(element, tag, status_number):
  516. """Add a PROPSTAT response structure to an element.
  517. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  518. given ``element``, for the following ``tag`` with the given
  519. ``status_number``.
  520. """
  521. propstat = ET.Element(_tag("D", "propstat"))
  522. element.append(propstat)
  523. prop = ET.Element(_tag("D", "prop"))
  524. propstat.append(prop)
  525. if "{" in tag:
  526. clark_tag = tag
  527. else:
  528. clark_tag = _tag(*tag.split(":", 1))
  529. prop_tag = ET.Element(clark_tag)
  530. prop.append(prop_tag)
  531. status = ET.Element(_tag("D", "status"))
  532. status.text = _response(status_number)
  533. propstat.append(status)
  534. def proppatch(path, xml_request, collection):
  535. """Read and answer PROPPATCH requests.
  536. Read rfc4918-9.2 for info.
  537. """
  538. # Reading request
  539. root = ET.fromstring(xml_request.encode("utf8"))
  540. props_to_set = props_from_request(root, actions=("set",))
  541. props_to_remove = props_from_request(root, actions=("remove",))
  542. # Writing answer
  543. multistatus = ET.Element(_tag("D", "multistatus"))
  544. response = ET.Element(_tag("D", "response"))
  545. multistatus.append(response)
  546. href = ET.Element(_tag("D", "href"))
  547. href.text = _href(collection, path)
  548. response.append(href)
  549. for short_name, value in props_to_set.items():
  550. collection.set_meta(short_name, value)
  551. _add_propstat_to(response, short_name, 200)
  552. for short_name in props_to_remove:
  553. collection.set_meta(short_name, '')
  554. _add_propstat_to(response, short_name, 200)
  555. return _pretty_xml(multistatus)
  556. def report(path, xml_request, collection):
  557. """Read and answer REPORT requests.
  558. Read rfc3253-3.6 for info.
  559. """
  560. # Reading request
  561. root = ET.fromstring(xml_request.encode("utf8"))
  562. prop_element = root.find(_tag("D", "prop"))
  563. props = (
  564. [prop.tag for prop in prop_element]
  565. if prop_element is not None else [])
  566. if collection:
  567. if root.tag in (_tag("C", "calendar-multiget"),
  568. _tag("CR", "addressbook-multiget")):
  569. # Read rfc4791-7.9 for info
  570. base_prefix = collection.configuration.get("server", "base_prefix")
  571. hreferences = set()
  572. for href_element in root.findall(_tag("D", "href")):
  573. href_path = unquote(urlparse(href_element.text).path)
  574. if href_path.startswith(base_prefix):
  575. hreferences.add(href_path[len(base_prefix) - 1:])
  576. else:
  577. hreferences = (path,)
  578. filters = (
  579. root.findall(".//%s" % _tag("C", "filter")) +
  580. root.findall(".//%s" % _tag("CR", "filter")))
  581. else:
  582. hreferences = filters = ()
  583. # Writing answer
  584. multistatus = ET.Element(_tag("D", "multistatus"))
  585. for hreference in hreferences:
  586. # Check if the reference is an item or a collection
  587. name = name_from_path(hreference, collection)
  588. if name:
  589. # Reference is an item
  590. path = "/".join(hreference.split("/")[:-1]) + "/"
  591. item = collection.get(name)
  592. if item is None:
  593. multistatus.append(
  594. _item_response(hreference, found_item=False))
  595. continue
  596. items = [item]
  597. else:
  598. # Reference is a collection
  599. path = hreference
  600. items = [collection.get(href) for href, etag in collection.list()]
  601. for item in items:
  602. if filters:
  603. match = (
  604. _comp_match if collection.get_meta("tag") == "VCALENDAR"
  605. else _prop_match)
  606. if not all(match(item, filter_[0]) for filter_ in filters):
  607. continue
  608. found_props = []
  609. not_found_props = []
  610. for tag in props:
  611. element = ET.Element(tag)
  612. if tag == _tag("D", "getetag"):
  613. element.text = item.etag
  614. found_props.append(element)
  615. elif tag == _tag("D", "getcontenttype"):
  616. name = item.name.lower()
  617. mimetype = (
  618. "text/vcard" if name == "vcard" else "text/calendar")
  619. element.text = "%s; component=%s" % (mimetype, name)
  620. found_props.append(element)
  621. elif tag in (_tag("C", "calendar-data"),
  622. _tag("CR", "address-data")):
  623. element.text = item.serialize()
  624. found_props.append(element)
  625. else:
  626. not_found_props.append(element)
  627. # TODO: fix this
  628. if hreference.split("/")[-1] == item.href:
  629. # Happening when depth is 0
  630. uri = hreference
  631. else:
  632. # Happening when depth is 1
  633. uri = posixpath.join(hreference, item.href)
  634. multistatus.append(_item_response(
  635. uri, found_props=found_props,
  636. not_found_props=not_found_props, found_item=True))
  637. return _pretty_xml(multistatus)
  638. def _item_response(href, found_props=(), not_found_props=(), found_item=True):
  639. response = ET.Element(_tag("D", "response"))
  640. href_tag = ET.Element(_tag("D", "href"))
  641. href_tag.text = href
  642. response.append(href_tag)
  643. if found_item:
  644. if found_props:
  645. propstat = ET.Element(_tag("D", "propstat"))
  646. status = ET.Element(_tag("D", "status"))
  647. status.text = _response(200)
  648. prop = ET.Element(_tag("D", "prop"))
  649. for p in found_props:
  650. prop.append(p)
  651. propstat.append(prop)
  652. propstat.append(status)
  653. response.append(propstat)
  654. if not_found_props:
  655. propstat = ET.Element(_tag("D", "propstat"))
  656. status = ET.Element(_tag("D", "status"))
  657. status.text = _response(404)
  658. prop = ET.Element(_tag("D", "prop"))
  659. for p in not_found_props:
  660. prop.append(p)
  661. propstat.append(prop)
  662. propstat.append(status)
  663. response.append(propstat)
  664. else:
  665. status = ET.Element(_tag("D", "status"))
  666. status.text = _response(404)
  667. response.append(status)
  668. return response