xmlutils.py 30 KB

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