xmlutils.py 19 KB

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