xmlutils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008-2012 Guillaume Ayoub
  5. # Copyright © 2008 Nicolas Kandel
  6. # Copyright © 2008 Pascal Halter
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. XML and iCal requests manager.
  22. Note that all these functions need to receive unicode objects for full
  23. iCal requests (PUT) and string objects with charset correctly defined
  24. in them for XML requests (all but PUT).
  25. """
  26. try:
  27. from collections import OrderedDict
  28. except ImportError:
  29. # Python 2.6 has no OrderedDict, use a dict instead
  30. OrderedDict = dict # pylint: disable=C0103
  31. import re
  32. import xml.etree.ElementTree as ET
  33. from . import client, config, ical
  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. if hasattr(ET, "register_namespace"):
  45. # Register namespaces cleanly with Python 2.7+ and 3.2+ ...
  46. ET.register_namespace("" if short == "D" else short, url)
  47. else:
  48. # ... and badly with Python 2.6 and 3.1
  49. ET._namespace_map[url] = short # pylint: disable=W0212
  50. CLARK_TAG_REGEX = re.compile(r"""
  51. { # {
  52. (?P<namespace>[^}]*) # namespace URL
  53. } # }
  54. (?P<tag>.*) # short tag name
  55. """, re.VERBOSE)
  56. def _pretty_xml(element, level=0):
  57. """Indent an ElementTree ``element`` and its children."""
  58. i = "\n" + level * " "
  59. if len(element):
  60. if not element.text or not element.text.strip():
  61. element.text = i + " "
  62. if not element.tail or not element.tail.strip():
  63. element.tail = i
  64. for sub_element in element:
  65. _pretty_xml(sub_element, level + 1)
  66. # ``sub_element`` is always defined as len(element) > 0
  67. # pylint: disable=W0631
  68. if not sub_element.tail or not sub_element.tail.strip():
  69. sub_element.tail = i
  70. # pylint: enable=W0631
  71. else:
  72. if level and (not element.tail or not element.tail.strip()):
  73. element.tail = i
  74. if not level:
  75. output_encoding = config.get("encoding", "request")
  76. return ('<?xml version="1.0"?>\n' + ET.tostring(
  77. element, "utf-8").decode("utf-8")).encode(output_encoding)
  78. def _tag(short_name, local):
  79. """Get XML Clark notation {uri(``short_name``)}``local``."""
  80. return "{%s}%s" % (NAMESPACES[short_name], local)
  81. def _tag_from_clark(name):
  82. """Get a human-readable variant of the XML Clark notation tag ``name``.
  83. For a given name using the XML Clark notation, return a human-readable
  84. variant of the tag name for known namespaces. Otherwise, return the name as
  85. is.
  86. """
  87. match = CLARK_TAG_REGEX.match(name)
  88. if match and match.group("namespace") in NAMESPACES_REV:
  89. args = {
  90. "ns": NAMESPACES_REV[match.group("namespace")],
  91. "tag": match.group("tag")}
  92. return "%(ns)s:%(tag)s" % args
  93. return name
  94. def _response(code):
  95. """Return full W3C names from HTTP status codes."""
  96. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  97. def _href_with_proxy_base_prefix(href):
  98. href = "%s%s" % (config.get("server", "proxy_base_prefix"), href)
  99. return href.replace("//", "/")
  100. def name_from_path(path, collection):
  101. """Return Radicale item name from ``path``."""
  102. collection_parts = collection.path.strip("/").split("/")
  103. path_parts = path.strip("/").split("/")
  104. if (len(path_parts) - len(collection_parts)):
  105. return path_parts[-1]
  106. def props_from_request(root, actions=("set", "remove")):
  107. """Return a list of properties as a dictionary."""
  108. result = OrderedDict()
  109. if not hasattr(root, "tag"):
  110. root = ET.fromstring(root.encode("utf8"))
  111. for action in actions:
  112. action_element = root.find(_tag("D", action))
  113. if action_element is not None:
  114. break
  115. else:
  116. action_element = root
  117. prop_element = action_element.find(_tag("D", "prop"))
  118. if prop_element is not None:
  119. for prop in prop_element:
  120. result[_tag_from_clark(prop.tag)] = prop.text
  121. if prop.tag == "resourcetype":
  122. for resource_type in prop:
  123. if resource_type.tag in ("calendar", "addressbook"):
  124. result["resourcetype"] = \
  125. "V%s" % resource_type.tag.upper()
  126. break
  127. return result
  128. def delete(path, collection):
  129. """Read and answer DELETE requests.
  130. Read rfc4918-9.6 for info.
  131. """
  132. # Reading request
  133. if collection.path == path.strip("/"):
  134. # Delete the whole collection
  135. collection.delete()
  136. else:
  137. # Remove an item from the collection
  138. collection.remove(name_from_path(path, collection))
  139. # Writing answer
  140. multistatus = ET.Element(_tag("D", "multistatus"))
  141. response = ET.Element(_tag("D", "response"))
  142. multistatus.append(response)
  143. href = ET.Element(_tag("D", "href"))
  144. href.text = _href_with_proxy_base_prefix(path)
  145. response.append(href)
  146. status = ET.Element(_tag("D", "status"))
  147. status.text = _response(200)
  148. response.append(status)
  149. return _pretty_xml(multistatus)
  150. def propfind(path, xml_request, collections, user=None):
  151. """Read and answer PROPFIND requests.
  152. Read rfc4918-9.1 for info.
  153. The collections parameter is a list of collections that are
  154. to be included in the output. Rights checking has to be done
  155. by the caller.
  156. """
  157. # Reading request
  158. if xml_request:
  159. root = ET.fromstring(xml_request.encode("utf8"))
  160. props = [prop.tag for prop in root.find(_tag("D", "prop"))]
  161. else:
  162. props = [_tag("D", "getcontenttype"),
  163. _tag("D", "resourcetype"),
  164. _tag("D", "displayname"),
  165. _tag("D", "owner"),
  166. _tag("D", "getetag"),
  167. _tag("CS", "getctag")]
  168. # Writing answer
  169. multistatus = ET.Element(_tag("D", "multistatus"))
  170. for collection in collections:
  171. response = _propfind_response(path, collection, props, user)
  172. multistatus.append(response)
  173. return _pretty_xml(multistatus)
  174. def _propfind_response(path, item, props, user):
  175. """Build and return a PROPFIND response."""
  176. is_collection = isinstance(item, ical.Collection)
  177. if is_collection:
  178. with item.props as properties:
  179. collection_props = properties
  180. response = ET.Element(_tag("D", "response"))
  181. href = ET.Element(_tag("D", "href"))
  182. if is_collection:
  183. uri = "%s%s" % (config.get("server", "base_prefix"), item.url)
  184. else:
  185. uri = "%s/%s" % (path, item.name)
  186. href.text = _href_with_proxy_base_prefix(uri)
  187. response.append(href)
  188. propstat404 = ET.Element(_tag("D", "propstat"))
  189. propstat200 = ET.Element(_tag("D", "propstat"))
  190. response.append(propstat200)
  191. prop200 = ET.Element(_tag("D", "prop"))
  192. propstat200.append(prop200)
  193. prop404 = ET.Element(_tag("D", "prop"))
  194. propstat404.append(prop404)
  195. for tag in props:
  196. element = ET.Element(tag)
  197. is404 = False
  198. if tag == _tag("D", "getetag"):
  199. element.text = item.etag
  200. elif tag == _tag("D", "principal-URL"):
  201. tag = ET.Element(_tag("D", "href"))
  202. tag.text = _href_with_proxy_base_prefix(path)
  203. element.append(tag)
  204. elif tag in (_tag("D", "principal-collection-set"),
  205. _tag("C", "calendar-user-address-set"),
  206. _tag("CR", "addressbook-home-set"),
  207. _tag("C", "calendar-home-set")):
  208. tag = ET.Element(_tag("D", "href"))
  209. tag.text = _href_with_proxy_base_prefix(path)
  210. element.append(tag)
  211. elif tag == _tag("C", "supported-calendar-component-set"):
  212. # This is not a Todo
  213. # pylint: disable=W0511
  214. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  215. comp = ET.Element(_tag("C", "comp"))
  216. comp.set("name", component)
  217. element.append(comp)
  218. # pylint: enable=W0511
  219. elif tag == _tag("D", "current-user-principal") and user:
  220. tag = ET.Element(_tag("D", "href"))
  221. prefixed_path = "%s/%s/" % (config.get("server", "base_prefix"), user)
  222. tag.text = _href_with_proxy_base_prefix(prefixed_path)
  223. element.append(tag)
  224. elif tag == _tag("D", "current-user-privilege-set"):
  225. privilege = ET.Element(_tag("D", "privilege"))
  226. privilege.append(ET.Element(_tag("D", "all")))
  227. privilege.append(ET.Element(_tag("D", "read")))
  228. privilege.append(ET.Element(_tag("D", "write")))
  229. privilege.append(ET.Element(_tag("D", "write-properties")))
  230. privilege.append(ET.Element(_tag("D", "write-content")))
  231. element.append(privilege)
  232. elif tag == _tag("D", "supported-report-set"):
  233. for report_name in (
  234. "principal-property-search", "sync-collection"
  235. "expand-property", "principal-search-property-set"):
  236. supported = ET.Element(_tag("D", "supported-report"))
  237. report_tag = ET.Element(_tag("D", "report"))
  238. report_tag.text = report_name
  239. supported.append(report_tag)
  240. element.append(supported)
  241. elif is_collection:
  242. if tag == _tag("D", "getcontenttype"):
  243. element.text = item.mimetype
  244. elif tag == _tag("D", "resourcetype"):
  245. if item.is_principal:
  246. tag = ET.Element(_tag("D", "principal"))
  247. element.append(tag)
  248. if item.is_leaf(item.path) or (
  249. not item.exists and item.resource_type):
  250. # 2nd case happens when the collection is not stored yet,
  251. # but the resource type is guessed
  252. if item.resource_type == "addressbook":
  253. tag = ET.Element(_tag("CR", item.resource_type))
  254. else:
  255. tag = ET.Element(_tag("C", item.resource_type))
  256. element.append(tag)
  257. tag = ET.Element(_tag("D", "collection"))
  258. element.append(tag)
  259. elif tag == _tag("D", "owner") and item.owner_url:
  260. element.text = item.owner_url
  261. elif tag == _tag("CS", "getctag"):
  262. element.text = item.etag
  263. elif tag == _tag("C", "calendar-timezone"):
  264. element.text = ical.serialize(
  265. item.tag, item.headers, item.timezones)
  266. elif tag == _tag("D", "displayname"):
  267. element.text = item.name
  268. else:
  269. human_tag = _tag_from_clark(tag)
  270. if human_tag in collection_props:
  271. element.text = collection_props[human_tag]
  272. else:
  273. is404 = True
  274. # Not for collections
  275. elif tag == _tag("D", "getcontenttype"):
  276. element.text = "%s; component=%s" % (
  277. item.mimetype, item.tag.lower())
  278. elif tag == _tag("D", "resourcetype"):
  279. # resourcetype must be returned empty for non-collection elements
  280. pass
  281. else:
  282. is404 = True
  283. if is404:
  284. prop404.append(element)
  285. else:
  286. prop200.append(element)
  287. status200 = ET.Element(_tag("D", "status"))
  288. status200.text = _response(200)
  289. propstat200.append(status200)
  290. status404 = ET.Element(_tag("D", "status"))
  291. status404.text = _response(404)
  292. propstat404.append(status404)
  293. if len(prop404):
  294. response.append(propstat404)
  295. return response
  296. def _add_propstat_to(element, tag, status_number):
  297. """Add a PROPSTAT response structure to an element.
  298. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  299. given ``element``, for the following ``tag`` with the given
  300. ``status_number``.
  301. """
  302. propstat = ET.Element(_tag("D", "propstat"))
  303. element.append(propstat)
  304. prop = ET.Element(_tag("D", "prop"))
  305. propstat.append(prop)
  306. if "{" in tag:
  307. clark_tag = tag
  308. else:
  309. clark_tag = _tag(*tag.split(":", 1))
  310. prop_tag = ET.Element(clark_tag)
  311. prop.append(prop_tag)
  312. status = ET.Element(_tag("D", "status"))
  313. status.text = _response(status_number)
  314. propstat.append(status)
  315. def proppatch(path, xml_request, collection):
  316. """Read and answer PROPPATCH requests.
  317. Read rfc4918-9.2 for info.
  318. """
  319. # Reading request
  320. root = ET.fromstring(xml_request.encode("utf8"))
  321. props_to_set = props_from_request(root, actions=("set",))
  322. props_to_remove = props_from_request(root, actions=("remove",))
  323. # Writing answer
  324. multistatus = ET.Element(_tag("D", "multistatus"))
  325. response = ET.Element(_tag("D", "response"))
  326. multistatus.append(response)
  327. href = ET.Element(_tag("D", "href"))
  328. href.text = _href_with_proxy_base_prefix(path)
  329. response.append(href)
  330. with collection.props as collection_props:
  331. for short_name, value in props_to_set.items():
  332. if short_name.split(":")[-1] == "calendar-timezone":
  333. collection.replace(None, value)
  334. collection_props[short_name] = value
  335. _add_propstat_to(response, short_name, 200)
  336. for short_name in props_to_remove:
  337. try:
  338. del collection_props[short_name]
  339. except KeyError:
  340. _add_propstat_to(response, short_name, 412)
  341. else:
  342. _add_propstat_to(response, short_name, 200)
  343. return _pretty_xml(multistatus)
  344. def put(path, ical_request, collection):
  345. """Read PUT requests."""
  346. name = name_from_path(path, collection)
  347. if name in (item.name for item in collection.items):
  348. # PUT is modifying an existing item
  349. collection.replace(name, ical_request)
  350. else:
  351. # PUT is adding a new item
  352. collection.append(name, ical_request)
  353. def report(path, xml_request, collection):
  354. """Read and answer REPORT requests.
  355. Read rfc3253-3.6 for info.
  356. """
  357. # Reading request
  358. root = ET.fromstring(xml_request.encode("utf8"))
  359. prop_element = root.find(_tag("D", "prop"))
  360. props = [prop.tag for prop in prop_element]
  361. proxy_prefix = config.get("server", "proxy_base_prefix")
  362. base_prefix = config.get("server", "base_prefix")
  363. if collection:
  364. if root.tag in (_tag("C", "calendar-multiget"),
  365. _tag("CR", "addressbook-multiget")):
  366. # Read rfc4791-7.9 for info
  367. hreferences = set()
  368. for href_element in root.findall(_tag("D", "href")):
  369. # skip elements that don't have the correct base prefixes
  370. if not href_element.text.startswith(proxy_prefix):
  371. continue
  372. unprefixed = href_element.text[len(proxy_prefix):]
  373. if not unprefixed.startswith(base_prefix):
  374. continue
  375. # we keep the base prefix here, to be aligned with other paths
  376. hreferences.add(unprefixed)
  377. else:
  378. hreferences = (path,)
  379. # TODO: handle other filters
  380. # TODO: handle the nested comp-filters correctly
  381. # Read rfc4791-9.7.1 for info
  382. tag_filters = set(
  383. element.get("name") for element
  384. in root.findall(".//%s" % _tag("C", "comp-filter")))
  385. else:
  386. hreferences = ()
  387. tag_filters = None
  388. # Writing answer
  389. multistatus = ET.Element(_tag("D", "multistatus"))
  390. collection_tag = collection.tag
  391. collection_items = collection.items
  392. collection_headers = collection.headers
  393. collection_timezones = collection.timezones
  394. for hreference in hreferences:
  395. unprefixed_hreference = hreference[len(base_prefix):]
  396. # Check if the reference is an item or a collection
  397. name = name_from_path(unprefixed_hreference, collection)
  398. if name:
  399. # Reference is an item
  400. path = "/".join(hreference.split("/")[:-1]) + "/"
  401. items = (item for item in collection_items if item.name == name)
  402. else:
  403. # Reference is a collection
  404. path = hreference
  405. items = collection.components
  406. for item in items:
  407. if tag_filters and item.tag not in tag_filters:
  408. continue
  409. response = ET.Element(_tag("D", "response"))
  410. multistatus.append(response)
  411. href = ET.Element(_tag("D", "href"))
  412. href.text = _href_with_proxy_base_prefix("%s/%s" % (path.rstrip("/"), item.name))
  413. response.append(href)
  414. propstat = ET.Element(_tag("D", "propstat"))
  415. response.append(propstat)
  416. prop = ET.Element(_tag("D", "prop"))
  417. propstat.append(prop)
  418. for tag in props:
  419. element = ET.Element(tag)
  420. if tag == _tag("D", "getetag"):
  421. element.text = item.etag
  422. elif tag in (_tag("C", "calendar-data"),
  423. _tag("CR", "address-data")):
  424. if isinstance(item, ical.Component):
  425. element.text = ical.serialize(
  426. collection_tag, collection_headers,
  427. collection_timezones + [item])
  428. prop.append(element)
  429. status = ET.Element(_tag("D", "status"))
  430. status.text = _response(200)
  431. propstat.append(status)
  432. return _pretty_xml(multistatus)