xmlutils.py 18 KB

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