xmlutils.py 20 KB

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