xmlutils.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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.min
  172. if end:
  173. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  174. else:
  175. end = 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 isinstance(dtstart, datetime) and not dtstart.tzinfo:
  184. dtstart = dtstart.replace(tzinfo=timezone.utc)
  185. if not isinstance(dtstart, datetime):
  186. dtstart_is_datetime = False
  187. # TODO: changing dates to datetimes may be wrong because of tz
  188. dtstart = datetime.combine(dtstart, datetime.min.time()).replace(
  189. tzinfo=timezone.utc)
  190. else:
  191. dtstart_is_datetime = True
  192. dtend = getattr(child, "dtend", None)
  193. duration = getattr(child, "duration", None)
  194. if dtend is not None:
  195. # Line 1
  196. dtend = dtend.value
  197. if not isinstance(dtend, datetime):
  198. dtend = datetime.combine(dtend, datetime.min.time()).replace(
  199. tzinfo=timezone.utc)
  200. if isinstance(dtend, datetime) and not dtend.tzinfo:
  201. dtend = dtend.replace(tzinfo=timezone.utc)
  202. return start < dtend and end > dtstart
  203. elif duration is not None:
  204. duration = duration.value
  205. if duration.seconds > 0:
  206. # Line 2
  207. return start < dtstart + duration and end > dtstart
  208. else:
  209. # Line 3
  210. return start <= dtstart and end > dtstart
  211. elif dtstart_is_datetime:
  212. # Line 4
  213. return start <= dtstart and end > dtstart
  214. else:
  215. # Line 5
  216. return start < dtstart + timedelta(days=1) and end > dtstart
  217. elif child_name == "VTODO":
  218. # TODO: implement this
  219. dtstart = getattr(child, "dtstart", None)
  220. duration = getattr(child, "duration", None)
  221. due = getattr(child, "due", None)
  222. completed = getattr(child, "completed", None)
  223. created = getattr(child, "created", None)
  224. if dtstart is not None and duration is not None:
  225. # Line 1
  226. dtstart = dtstart.value
  227. if not isinstance(dtstart, datetime):
  228. dtstart = (datetime.combine(dtstart, datetime.min.time())
  229. .replace(tzinfo=timezone.utc))
  230. duration = duration.value
  231. return (start <= dtstart + duration and
  232. (end > dtstart or end >= dtstart + duration))
  233. elif dtstart is not None and due is not None:
  234. # Line 2
  235. dtstart = dtstart.value
  236. if not isinstance(dtstart, datetime):
  237. dtstart = (datetime.combine(dtstart, datetime.min.time())
  238. .replace(tzinfo=timezone.utc))
  239. due = due.value
  240. if not isinstance(due, datetime):
  241. due = datetime.combine(due, datetime.min.time()).replace(
  242. tzinfo=timezone.utc)
  243. return ((start < due or start <= dtstart) and
  244. (end > dtstart or end >= due))
  245. elif dtstart is not None:
  246. # Line 3
  247. dtstart = dtstart.value
  248. if not isinstance(dtstart, datetime):
  249. dtstart = (datetime.combine(dtstart, datetime.min.time())
  250. .replace(tzinfo=timezone.utc))
  251. return start <= dtstart and end > dtstart
  252. elif due is not None:
  253. # Line 4
  254. due = due.value
  255. if not isinstance(due, datetime):
  256. due = datetime.combine(due, datetime.min.time()).replace(
  257. tzinfo=timezone.utc)
  258. return start < due and end >= due
  259. elif completed is not None and created is not None:
  260. # Line 5
  261. completed = completed.value
  262. created = created.value
  263. return ((start <= created or start <= completed) and
  264. (end >= created or end >= completed))
  265. elif completed is not None:
  266. # Line 6
  267. completed = completed.value
  268. return start <= completed and end >= completed
  269. elif created is not None:
  270. # Line 7
  271. created = created.value
  272. return end > created
  273. else:
  274. return True
  275. elif child_name == "VJOURNAL":
  276. dtstart = getattr(child, "dtstart", None)
  277. if dtstart is not None:
  278. dtstart = dtstart.value
  279. if not isinstance(dtstart, datetime):
  280. dtstart_is_datetime = False
  281. # TODO: changing dates to datetimes may be wrong because of tz
  282. dtstart = (datetime.combine(dtstart, datetime.min.time())
  283. .replace(tzinfo=timezone.utc))
  284. else:
  285. dtstart_is_datetime = True
  286. if dtstart_is_datetime:
  287. # Line 1
  288. return start <= dtstart and end > dtstart
  289. else:
  290. # Line 2
  291. return start < dtstart + timedelta(days=1) and end > dtstart
  292. else:
  293. # Line 3
  294. return False
  295. return True
  296. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  297. """Check whether the ``item`` matches the text-match ``filter_``.
  298. See rfc4791-9.7.5.
  299. """
  300. # TODO: collations are not supported, but the default ones needed
  301. # for DAV servers are actually pretty useless. Texts are lowered to
  302. # be case-insensitive, almost as the "i;ascii-casemap" value.
  303. match = next(filter_.itertext()).lower()
  304. children = getattr(vobject_item, "%s_list" % child_name, [])
  305. if attrib_name:
  306. condition = any(
  307. match in attrib.lower() for child in children
  308. for attrib in child.params.get(attrib_name, []))
  309. else:
  310. condition = any(match in child.value.lower() for child in children)
  311. if filter_.get("negate-condition") == "yes":
  312. return not condition
  313. else:
  314. return condition
  315. def _param_filter_match(vobject_item, filter_, parent_name):
  316. """Check whether the ``item`` matches the param-filter ``filter_``.
  317. See rfc4791-9.7.3.
  318. """
  319. name = filter_.get("name")
  320. children = getattr(vobject_item, "%s_list" % parent_name, [])
  321. condition = any(name in child.params for child in children)
  322. if len(filter_):
  323. if filter_[0].tag == _tag("C", "text-match"):
  324. return condition and _text_match(
  325. vobject_item, filter_[0], parent_name, name)
  326. elif filter_[0].tag == _tag("C", "is-not-defined"):
  327. return not condition
  328. else:
  329. return condition
  330. def name_from_path(path, collection):
  331. """Return Radicale item name from ``path``."""
  332. collection_parts = collection.path.strip("/").split("/")
  333. path_parts = path.strip("/").split("/")
  334. if (len(path_parts) - len(collection_parts)):
  335. return path_parts[-1]
  336. def props_from_request(root, actions=("set", "remove")):
  337. """Return a list of properties as a dictionary."""
  338. result = OrderedDict()
  339. if root:
  340. if not hasattr(root, "tag"):
  341. root = ET.fromstring(root.encode("utf8"))
  342. else:
  343. return result
  344. for action in actions:
  345. action_element = root.find(_tag("D", action))
  346. if action_element is not None:
  347. break
  348. else:
  349. action_element = root
  350. prop_element = action_element.find(_tag("D", "prop"))
  351. if prop_element is not None:
  352. for prop in prop_element:
  353. if prop.tag == _tag("D", "resourcetype"):
  354. for resource_type in prop:
  355. if resource_type.tag == _tag("C", "calendar"):
  356. result["tag"] = "VCALENDAR"
  357. break
  358. elif resource_type.tag == _tag("CR", "addressbook"):
  359. result["tag"] = "VADDRESSBOOK"
  360. break
  361. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  362. result[_tag_from_clark(prop.tag)] = ",".join(
  363. supported_comp.attrib["name"]
  364. for supported_comp in prop
  365. if supported_comp.tag == _tag("C", "comp"))
  366. else:
  367. result[_tag_from_clark(prop.tag)] = prop.text
  368. return result
  369. def delete(path, collection):
  370. """Read and answer DELETE requests.
  371. Read rfc4918-9.6 for info.
  372. """
  373. # Reading request
  374. if collection.path == path.strip("/"):
  375. # Delete the whole collection
  376. collection.delete()
  377. else:
  378. # Remove an item from the collection
  379. collection.delete(name_from_path(path, collection))
  380. # Writing answer
  381. multistatus = ET.Element(_tag("D", "multistatus"))
  382. response = ET.Element(_tag("D", "response"))
  383. multistatus.append(response)
  384. href = ET.Element(_tag("D", "href"))
  385. href.text = _href(collection, path)
  386. response.append(href)
  387. status = ET.Element(_tag("D", "status"))
  388. status.text = _response(200)
  389. response.append(status)
  390. return _pretty_xml(multistatus)
  391. def propfind(path, xml_request, read_collections, write_collections,
  392. user=None):
  393. """Read and answer PROPFIND requests.
  394. Read rfc4918-9.1 for info.
  395. The collections parameter is a list of collections that are to be included
  396. in the output.
  397. """
  398. # Reading request
  399. if xml_request:
  400. root = ET.fromstring(xml_request.encode("utf8"))
  401. props = [prop.tag for prop in root.find(_tag("D", "prop"))]
  402. else:
  403. props = [_tag("D", "getcontenttype"),
  404. _tag("D", "resourcetype"),
  405. _tag("D", "displayname"),
  406. _tag("D", "owner"),
  407. _tag("D", "getetag"),
  408. _tag("ICAL", "calendar-color"),
  409. _tag("CS", "getctag")]
  410. # Writing answer
  411. multistatus = ET.Element(_tag("D", "multistatus"))
  412. collections = []
  413. for collection in write_collections:
  414. collections.append(collection)
  415. response = _propfind_response(
  416. path, collection, props, user, write=True)
  417. multistatus.append(response)
  418. for collection in read_collections:
  419. if collection in collections:
  420. continue
  421. response = _propfind_response(
  422. path, collection, props, user, write=False)
  423. multistatus.append(response)
  424. return _pretty_xml(multistatus)
  425. def _propfind_response(path, item, props, user, write=False):
  426. """Build and return a PROPFIND response."""
  427. # TODO: fix this
  428. is_collection = hasattr(item, "list")
  429. if is_collection:
  430. is_leaf = bool(item.list())
  431. collection = item
  432. else:
  433. collection = item.collection
  434. response = ET.Element(_tag("D", "response"))
  435. href = ET.Element(_tag("D", "href"))
  436. if is_collection:
  437. uri = item.path
  438. else:
  439. # TODO: fix this
  440. if path.split("/")[-1] == item.href:
  441. # Happening when depth is 0
  442. uri = path
  443. else:
  444. # Happening when depth is 1
  445. uri = "/".join((path, item.href))
  446. # TODO: fix this
  447. href.text = _href(collection, uri.replace("//", "/"))
  448. response.append(href)
  449. propstat404 = ET.Element(_tag("D", "propstat"))
  450. propstat200 = ET.Element(_tag("D", "propstat"))
  451. response.append(propstat200)
  452. prop200 = ET.Element(_tag("D", "prop"))
  453. propstat200.append(prop200)
  454. prop404 = ET.Element(_tag("D", "prop"))
  455. propstat404.append(prop404)
  456. for tag in props:
  457. element = ET.Element(tag)
  458. is404 = False
  459. if tag == _tag("D", "getetag"):
  460. element.text = item.etag
  461. elif tag == _tag("D", "principal-URL"):
  462. tag = ET.Element(_tag("D", "href"))
  463. tag.text = _href(collection, path)
  464. element.append(tag)
  465. elif tag == _tag("D", "getlastmodified"):
  466. element.text = item.last_modified
  467. elif tag in (_tag("D", "principal-collection-set"),
  468. _tag("C", "calendar-user-address-set"),
  469. _tag("CR", "addressbook-home-set"),
  470. _tag("C", "calendar-home-set")):
  471. tag = ET.Element(_tag("D", "href"))
  472. tag.text = _href(collection, path)
  473. element.append(tag)
  474. elif tag == _tag("C", "supported-calendar-component-set"):
  475. # This is not a Todo
  476. # pylint: disable=W0511
  477. human_tag = _tag_from_clark(tag)
  478. if is_collection and is_leaf:
  479. meta = item.get_meta(human_tag)
  480. if meta:
  481. components = meta.split(",")
  482. else:
  483. components = ("VTODO", "VEVENT", "VJOURNAL")
  484. for component in components:
  485. comp = ET.Element(_tag("C", "comp"))
  486. comp.set("name", component)
  487. element.append(comp)
  488. else:
  489. is404 = True
  490. # pylint: enable=W0511
  491. elif tag == _tag("D", "current-user-principal") and user:
  492. tag = ET.Element(_tag("D", "href"))
  493. tag.text = _href(collection, "/%s/" % user)
  494. element.append(tag)
  495. elif tag == _tag("D", "current-user-privilege-set"):
  496. privilege = ET.Element(_tag("D", "privilege"))
  497. if write:
  498. privilege.append(ET.Element(_tag("D", "all")))
  499. privilege.append(ET.Element(_tag("D", "write")))
  500. privilege.append(ET.Element(_tag("D", "write-properties")))
  501. privilege.append(ET.Element(_tag("D", "write-content")))
  502. privilege.append(ET.Element(_tag("D", "read")))
  503. element.append(privilege)
  504. elif tag == _tag("D", "supported-report-set"):
  505. for report_name in (
  506. "principal-property-search", "sync-collection",
  507. "expand-property", "principal-search-property-set"):
  508. supported = ET.Element(_tag("D", "supported-report"))
  509. report_tag = ET.Element(_tag("D", "report"))
  510. report_tag.text = report_name
  511. supported.append(report_tag)
  512. element.append(supported)
  513. elif is_collection:
  514. if tag == _tag("D", "getcontenttype"):
  515. item_tag = item.get_meta("tag")
  516. if item_tag:
  517. element.text = storage.MIMETYPES[item_tag]
  518. else:
  519. is404 = True
  520. elif tag == _tag("D", "resourcetype"):
  521. if item.is_principal:
  522. tag = ET.Element(_tag("D", "principal"))
  523. element.append(tag)
  524. item_tag = item.get_meta("tag")
  525. if is_leaf or item_tag:
  526. # 2nd case happens when the collection is not stored yet,
  527. # but the resource type is guessed
  528. if item.get_meta("tag") == "VADDRESSBOOK":
  529. tag = ET.Element(_tag("CR", "addressbook"))
  530. element.append(tag)
  531. elif item.get_meta("tag") == "VCALENDAR":
  532. tag = ET.Element(_tag("C", "calendar"))
  533. element.append(tag)
  534. tag = ET.Element(_tag("D", "collection"))
  535. element.append(tag)
  536. elif is_leaf:
  537. if tag == _tag("D", "owner") and item.owner:
  538. element.text = "/%s/" % item.owner
  539. elif tag == _tag("CS", "getctag"):
  540. element.text = item.etag
  541. elif tag == _tag("C", "calendar-timezone"):
  542. timezones = set()
  543. for href, _ in item.list():
  544. event = item.get(href)
  545. if "vtimezone" in event.contents:
  546. for timezone_ in event.vtimezone_list:
  547. timezones.add(timezone_)
  548. timezone_collection = vobject.iCalendar()
  549. for timezone_ in timezones:
  550. timezone_collection.add(timezone_)
  551. element.text = timezone_collection.serialize()
  552. elif tag == _tag("D", "displayname"):
  553. element.text = item.get_meta("D:displayname") or item.path
  554. elif tag == _tag("ICAL", "calendar-color"):
  555. element.text = item.get_meta("ICAL:calendar-color")
  556. else:
  557. human_tag = _tag_from_clark(tag)
  558. meta = item.get_meta(human_tag)
  559. if meta:
  560. element.text = meta
  561. else:
  562. is404 = True
  563. else:
  564. is404 = True
  565. # Not for collections
  566. elif tag == _tag("D", "getcontenttype"):
  567. name = item.name.lower()
  568. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  569. element.text = "%s; component=%s" % (mimetype, name)
  570. elif tag == _tag("D", "resourcetype"):
  571. # resourcetype must be returned empty for non-collection elements
  572. pass
  573. elif tag == _tag("D", "getcontentlength"):
  574. encoding = collection.configuration.get("encoding", "request")
  575. element.text = str(len(item.serialize().encode(encoding)))
  576. else:
  577. is404 = True
  578. if is404:
  579. prop404.append(element)
  580. else:
  581. prop200.append(element)
  582. status200 = ET.Element(_tag("D", "status"))
  583. status200.text = _response(200)
  584. propstat200.append(status200)
  585. status404 = ET.Element(_tag("D", "status"))
  586. status404.text = _response(404)
  587. propstat404.append(status404)
  588. if len(prop404):
  589. response.append(propstat404)
  590. return response
  591. def _add_propstat_to(element, tag, status_number):
  592. """Add a PROPSTAT response structure to an element.
  593. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  594. given ``element``, for the following ``tag`` with the given
  595. ``status_number``.
  596. """
  597. propstat = ET.Element(_tag("D", "propstat"))
  598. element.append(propstat)
  599. prop = ET.Element(_tag("D", "prop"))
  600. propstat.append(prop)
  601. if "{" in tag:
  602. clark_tag = tag
  603. else:
  604. clark_tag = _tag(*tag.split(":", 1))
  605. prop_tag = ET.Element(clark_tag)
  606. prop.append(prop_tag)
  607. status = ET.Element(_tag("D", "status"))
  608. status.text = _response(status_number)
  609. propstat.append(status)
  610. def proppatch(path, xml_request, collection):
  611. """Read and answer PROPPATCH requests.
  612. Read rfc4918-9.2 for info.
  613. """
  614. # Reading request
  615. root = ET.fromstring(xml_request.encode("utf8"))
  616. props_to_set = props_from_request(root, actions=("set",))
  617. props_to_remove = props_from_request(root, actions=("remove",))
  618. # Writing answer
  619. multistatus = ET.Element(_tag("D", "multistatus"))
  620. response = ET.Element(_tag("D", "response"))
  621. multistatus.append(response)
  622. href = ET.Element(_tag("D", "href"))
  623. href.text = _href(collection, path)
  624. response.append(href)
  625. for short_name, value in props_to_set.items():
  626. collection.set_meta(short_name, value)
  627. _add_propstat_to(response, short_name, 200)
  628. for short_name in props_to_remove:
  629. collection.set_meta(short_name, '')
  630. _add_propstat_to(response, short_name, 200)
  631. return _pretty_xml(multistatus)
  632. def report(path, xml_request, collection):
  633. """Read and answer REPORT requests.
  634. Read rfc3253-3.6 for info.
  635. """
  636. # Reading request
  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 (_tag("C", "calendar-multiget"),
  644. _tag("CR", "addressbook-multiget")):
  645. # Read rfc4791-7.9 for info
  646. base_prefix = collection.configuration.get("server", "base_prefix")
  647. hreferences = set()
  648. for href_element in root.findall(_tag("D", "href")):
  649. href_path = unquote(urlparse(href_element.text).path)
  650. if href_path.startswith(base_prefix):
  651. hreferences.add(href_path[len(base_prefix) - 1:])
  652. else:
  653. hreferences = (path,)
  654. filters = (
  655. root.findall(".//%s" % _tag("C", "filter")) +
  656. root.findall(".//%s" % _tag("CR", "filter")))
  657. else:
  658. hreferences = filters = ()
  659. # Writing answer
  660. multistatus = ET.Element(_tag("D", "multistatus"))
  661. for hreference in hreferences:
  662. # Check if the reference is an item or a collection
  663. name = name_from_path(hreference, collection)
  664. if name:
  665. # Reference is an item
  666. path = "/".join(hreference.split("/")[:-1]) + "/"
  667. item = collection.get(name)
  668. if item is None:
  669. multistatus.append(
  670. _item_response(hreference, found_item=False))
  671. continue
  672. items = [item]
  673. else:
  674. # Reference is a collection
  675. path = hreference
  676. items = [collection.get(href) for href, etag in collection.list()]
  677. for item in items:
  678. if filters:
  679. match = (
  680. _comp_match if collection.get_meta("tag") == "VCALENDAR"
  681. else _prop_match)
  682. if not all(match(item, filter_[0]) for filter_ in filters):
  683. continue
  684. found_props = []
  685. not_found_props = []
  686. for tag in props:
  687. element = ET.Element(tag)
  688. if tag == _tag("D", "getetag"):
  689. element.text = item.etag
  690. found_props.append(element)
  691. elif tag == _tag("D", "getcontenttype"):
  692. name = item.name.lower()
  693. mimetype = (
  694. "text/vcard" if name == "vcard" else "text/calendar")
  695. element.text = "%s; component=%s" % (mimetype, name)
  696. found_props.append(element)
  697. elif tag in (_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. if found_props:
  721. propstat = ET.Element(_tag("D", "propstat"))
  722. status = ET.Element(_tag("D", "status"))
  723. status.text = _response(200)
  724. prop = ET.Element(_tag("D", "prop"))
  725. for p in found_props:
  726. prop.append(p)
  727. propstat.append(prop)
  728. propstat.append(status)
  729. response.append(propstat)
  730. if not_found_props:
  731. propstat = ET.Element(_tag("D", "propstat"))
  732. status = ET.Element(_tag("D", "status"))
  733. status.text = _response(404)
  734. prop = ET.Element(_tag("D", "prop"))
  735. for p in not_found_props:
  736. prop.append(p)
  737. propstat.append(prop)
  738. propstat.append(status)
  739. response.append(propstat)
  740. else:
  741. status = ET.Element(_tag("D", "status"))
  742. status.text = _response(404)
  743. response.append(status)
  744. return response