xmlutils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 name_from_path(path, collection):
  98. """Return Radicale item name from ``path``."""
  99. collection_parts = collection.path.strip("/").split("/")
  100. path_parts = path.strip("/").split("/")
  101. if (len(path_parts) - len(collection_parts)):
  102. return path_parts[-1]
  103. def props_from_request(root, actions=("set", "remove")):
  104. """Return a list of properties as a dictionary."""
  105. result = OrderedDict()
  106. if not hasattr(root, "tag"):
  107. root = ET.fromstring(root.encode("utf8"))
  108. for action in actions:
  109. action_element = root.find(_tag("D", action))
  110. if action_element is not None:
  111. break
  112. else:
  113. action_element = root
  114. prop_element = action_element.find(_tag("D", "prop"))
  115. if prop_element is not None:
  116. for prop in prop_element:
  117. result[_tag_from_clark(prop.tag)] = prop.text
  118. if prop.tag == "resourcetype":
  119. for resource_type in prop:
  120. if resource_type.tag in ("calendar", "addressbook"):
  121. result["resourcetype"] = \
  122. "V%s" % resource_type.tag.upper()
  123. break
  124. return result
  125. def delete(path, collection):
  126. """Read and answer DELETE requests.
  127. Read rfc4918-9.6 for info.
  128. """
  129. # Reading request
  130. if collection.path == path.strip("/"):
  131. # Delete the whole collection
  132. collection.delete()
  133. else:
  134. # Remove an item from the collection
  135. collection.remove(name_from_path(path, collection))
  136. # Writing answer
  137. multistatus = ET.Element(_tag("D", "multistatus"))
  138. response = ET.Element(_tag("D", "response"))
  139. multistatus.append(response)
  140. href = ET.Element(_tag("D", "href"))
  141. href.text = path
  142. response.append(href)
  143. status = ET.Element(_tag("D", "status"))
  144. status.text = _response(200)
  145. response.append(status)
  146. return _pretty_xml(multistatus)
  147. def propfind(path, xml_request, collections, user=None):
  148. """Read and answer PROPFIND requests.
  149. Read rfc4918-9.1 for info.
  150. The collections parameter is a list of collections that are
  151. to be included in the output. Rights checking has to be done
  152. by the caller.
  153. """
  154. # Reading request
  155. root = ET.fromstring(xml_request.encode("utf8"))
  156. prop_element = root.find(_tag("D", "prop"))
  157. props = [prop.tag for prop in prop_element]
  158. # Writing answer
  159. multistatus = ET.Element(_tag("D", "multistatus"))
  160. for collection in collections:
  161. response = _propfind_response(path, collection, props, user)
  162. multistatus.append(response)
  163. return _pretty_xml(multistatus)
  164. def _propfind_response(path, item, props, user):
  165. """Build and return a PROPFIND response."""
  166. is_collection = isinstance(item, ical.Collection)
  167. if is_collection:
  168. with item.props as properties:
  169. collection_props = properties
  170. response = ET.Element(_tag("D", "response"))
  171. href = ET.Element(_tag("D", "href"))
  172. uri = item.url if is_collection else "%s/%s" % (path, item.name)
  173. href.text = uri.replace("//", "/")
  174. response.append(href)
  175. propstat404 = ET.Element(_tag("D", "propstat"))
  176. propstat200 = ET.Element(_tag("D", "propstat"))
  177. response.append(propstat200)
  178. prop200 = ET.Element(_tag("D", "prop"))
  179. propstat200.append(prop200)
  180. prop404 = ET.Element(_tag("D", "prop"))
  181. propstat404.append(prop404)
  182. for tag in props:
  183. element = ET.Element(tag)
  184. is404 = False
  185. if tag == _tag("D", "getetag"):
  186. element.text = item.etag
  187. elif tag == _tag("D", "principal-URL"):
  188. tag = ET.Element(_tag("D", "href"))
  189. tag.text = path
  190. element.append(tag)
  191. elif tag in (_tag("D", "principal-collection-set"),
  192. _tag("C", "calendar-user-address-set"),
  193. _tag("CR", "addressbook-home-set"),
  194. _tag("C", "calendar-home-set")):
  195. tag = ET.Element(_tag("D", "href"))
  196. tag.text = path
  197. element.append(tag)
  198. elif tag == _tag("C", "supported-calendar-component-set"):
  199. # This is not a Todo
  200. # pylint: disable=W0511
  201. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  202. comp = ET.Element(_tag("C", "comp"))
  203. comp.set("name", component)
  204. element.append(comp)
  205. # pylint: enable=W0511
  206. elif tag == _tag("D", "current-user-principal") and user:
  207. tag = ET.Element(_tag("D", "href"))
  208. tag.text = "/%s/" % user
  209. element.append(tag)
  210. elif tag == _tag("D", "current-user-privilege-set"):
  211. privilege = ET.Element(_tag("D", "privilege"))
  212. privilege.append(ET.Element(_tag("D", "all")))
  213. privilege.append(ET.Element(_tag("D", "read")))
  214. privilege.append(ET.Element(_tag("D", "write")))
  215. privilege.append(ET.Element(_tag("D", "write-properties")))
  216. privilege.append(ET.Element(_tag("D", "write-content")))
  217. element.append(privilege)
  218. elif tag == _tag("D", "supported-report-set"):
  219. for report_name in (
  220. "principal-property-search", "sync-collection"
  221. "expand-property", "principal-search-property-set"):
  222. supported = ET.Element(_tag("D", "supported-report"))
  223. report_tag = ET.Element(_tag("D", "report"))
  224. report_tag.text = report_name
  225. supported.append(report_tag)
  226. element.append(supported)
  227. elif is_collection:
  228. if tag == _tag("D", "getcontenttype"):
  229. element.text = item.mimetype
  230. elif tag == _tag("D", "resourcetype"):
  231. if item.is_principal:
  232. tag = ET.Element(_tag("D", "principal"))
  233. element.append(tag)
  234. if item.is_leaf(item.path) or (
  235. not item.exists and item.resource_type):
  236. # 2nd case happens when the collection is not stored yet,
  237. # but the resource type is guessed
  238. if item.resource_type == "addressbook":
  239. tag = ET.Element(_tag("CR", item.resource_type))
  240. else:
  241. tag = ET.Element(_tag("C", item.resource_type))
  242. element.append(tag)
  243. tag = ET.Element(_tag("D", "collection"))
  244. element.append(tag)
  245. elif tag == _tag("D", "owner") and item.owner_url:
  246. element.text = item.owner_url
  247. elif tag == _tag("CS", "getctag"):
  248. element.text = item.etag
  249. elif tag == _tag("C", "calendar-timezone"):
  250. element.text = ical.serialize(
  251. item.tag, item.headers, item.timezones)
  252. elif tag == _tag("D", "displayname"):
  253. element.text = item.name
  254. else:
  255. human_tag = _tag_from_clark(tag)
  256. if human_tag in collection_props:
  257. element.text = collection_props[human_tag]
  258. else:
  259. is404 = True
  260. # Not for collections
  261. elif tag == _tag("D", "getcontenttype"):
  262. element.text = "%s; component=%s" % (
  263. item.mimetype, item.tag.lower())
  264. elif tag == _tag("D", "resourcetype"):
  265. # resourcetype must be returned empty for non-collection elements
  266. pass
  267. else:
  268. is404 = True
  269. if is404:
  270. prop404.append(element)
  271. else:
  272. prop200.append(element)
  273. status200 = ET.Element(_tag("D", "status"))
  274. status200.text = _response(200)
  275. propstat200.append(status200)
  276. status404 = ET.Element(_tag("D", "status"))
  277. status404.text = _response(404)
  278. propstat404.append(status404)
  279. if len(prop404):
  280. response.append(propstat404)
  281. return response
  282. def _add_propstat_to(element, tag, status_number):
  283. """Add a PROPSTAT response structure to an element.
  284. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  285. given ``element``, for the following ``tag`` with the given
  286. ``status_number``.
  287. """
  288. propstat = ET.Element(_tag("D", "propstat"))
  289. element.append(propstat)
  290. prop = ET.Element(_tag("D", "prop"))
  291. propstat.append(prop)
  292. if "{" in tag:
  293. clark_tag = tag
  294. else:
  295. clark_tag = _tag(*tag.split(":", 1))
  296. prop_tag = ET.Element(clark_tag)
  297. prop.append(prop_tag)
  298. status = ET.Element(_tag("D", "status"))
  299. status.text = _response(status_number)
  300. propstat.append(status)
  301. def proppatch(path, xml_request, collection):
  302. """Read and answer PROPPATCH requests.
  303. Read rfc4918-9.2 for info.
  304. """
  305. # Reading request
  306. root = ET.fromstring(xml_request.encode("utf8"))
  307. props_to_set = props_from_request(root, actions=("set",))
  308. props_to_remove = props_from_request(root, actions=("remove",))
  309. # Writing answer
  310. multistatus = ET.Element(_tag("D", "multistatus"))
  311. response = ET.Element(_tag("D", "response"))
  312. multistatus.append(response)
  313. href = ET.Element(_tag("D", "href"))
  314. href.text = path
  315. response.append(href)
  316. with collection.props as collection_props:
  317. for short_name, value in props_to_set.items():
  318. if short_name.split(":")[-1] == "calendar-timezone":
  319. collection.replace(None, value)
  320. collection_props[short_name] = value
  321. _add_propstat_to(response, short_name, 200)
  322. for short_name in props_to_remove:
  323. try:
  324. del collection_props[short_name]
  325. except KeyError:
  326. _add_propstat_to(response, short_name, 412)
  327. else:
  328. _add_propstat_to(response, short_name, 200)
  329. return _pretty_xml(multistatus)
  330. def put(path, ical_request, collection):
  331. """Read PUT requests."""
  332. name = name_from_path(path, collection)
  333. if name in (item.name for item in collection.items):
  334. # PUT is modifying an existing item
  335. collection.replace(name, ical_request)
  336. else:
  337. # PUT is adding a new item
  338. collection.append(name, ical_request)
  339. def report(path, xml_request, collection):
  340. """Read and answer REPORT requests.
  341. Read rfc3253-3.6 for info.
  342. """
  343. # Reading request
  344. root = ET.fromstring(xml_request.encode("utf8"))
  345. prop_element = root.find(_tag("D", "prop"))
  346. props = [prop.tag for prop in prop_element]
  347. if collection:
  348. if root.tag in (_tag("C", "calendar-multiget"),
  349. _tag("CR", "addressbook-multiget")):
  350. # Read rfc4791-7.9 for info
  351. hreferences = set(
  352. href_element.text for href_element
  353. in root.findall(_tag("D", "href")))
  354. else:
  355. hreferences = (path,)
  356. # TODO: handle other filters
  357. # TODO: handle the nested comp-filters correctly
  358. # Read rfc4791-9.7.1 for info
  359. tag_filters = set(
  360. element.get("name") for element
  361. in root.findall(".//%s" % _tag("C", "comp-filter")))
  362. else:
  363. hreferences = ()
  364. tag_filters = None
  365. # Writing answer
  366. multistatus = ET.Element(_tag("D", "multistatus"))
  367. collection_tag = collection.tag
  368. collection_items = collection.items
  369. collection_headers = collection.headers
  370. collection_timezones = collection.timezones
  371. for hreference in hreferences:
  372. # Check if the reference is an item or a collection
  373. name = name_from_path(hreference, collection)
  374. if name:
  375. # Reference is an item
  376. path = "/".join(hreference.split("/")[:-1]) + "/"
  377. items = (item for item in collection_items if item.name == name)
  378. else:
  379. # Reference is a collection
  380. path = hreference
  381. items = collection.components
  382. for item in items:
  383. if tag_filters and item.tag not in tag_filters:
  384. continue
  385. response = ET.Element(_tag("D", "response"))
  386. multistatus.append(response)
  387. href = ET.Element(_tag("D", "href"))
  388. href.text = "%s/%s" % (path.rstrip("/"), item.name)
  389. response.append(href)
  390. propstat = ET.Element(_tag("D", "propstat"))
  391. response.append(propstat)
  392. prop = ET.Element(_tag("D", "prop"))
  393. propstat.append(prop)
  394. for tag in props:
  395. element = ET.Element(tag)
  396. if tag == _tag("D", "getetag"):
  397. element.text = item.etag
  398. elif tag in (_tag("C", "calendar-data"),
  399. _tag("CR", "address-data")):
  400. if isinstance(item, ical.Component):
  401. element.text = ical.serialize(
  402. collection_tag, collection_headers,
  403. collection_timezones + [item])
  404. prop.append(element)
  405. status = ET.Element(_tag("D", "status"))
  406. status.text = _response(200)
  407. propstat.append(status)
  408. return _pretty_xml(multistatus)