xmlutils.py 20 KB

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