xmlutils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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, ical, rights
  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, 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
  152. to be included in the output. Rights checking has to be done
  153. by the caller.
  154. """
  155. # Reading request
  156. if xml_request:
  157. root = ET.fromstring(xml_request.encode("utf8"))
  158. props = [prop.tag for prop in root.find(_tag("D", "prop"))]
  159. else:
  160. props = [_tag("D", "getcontenttype"),
  161. _tag("D", "resourcetype"),
  162. _tag("D", "displayname"),
  163. _tag("D", "owner"),
  164. _tag("D", "getetag"),
  165. _tag("ICAL", "calendar-color"),
  166. _tag("CS", "getctag")]
  167. # Writing answer
  168. multistatus = ET.Element(_tag("D", "multistatus"))
  169. for collection in collections:
  170. response = _propfind_response(path, collection, props, user)
  171. multistatus.append(response)
  172. return _pretty_xml(multistatus)
  173. def _propfind_response(path, item, props, user):
  174. """Build and return a PROPFIND response."""
  175. is_collection = isinstance(item, ical.Collection)
  176. if is_collection:
  177. with item.props as properties:
  178. collection_props = properties
  179. response = ET.Element(_tag("D", "response"))
  180. href = ET.Element(_tag("D", "href"))
  181. uri = item.url if is_collection else "%s/%s" % (path, item.name)
  182. href.text = _href(uri.replace("//", "/"))
  183. response.append(href)
  184. propstat404 = ET.Element(_tag("D", "propstat"))
  185. propstat200 = ET.Element(_tag("D", "propstat"))
  186. response.append(propstat200)
  187. prop200 = ET.Element(_tag("D", "prop"))
  188. propstat200.append(prop200)
  189. prop404 = ET.Element(_tag("D", "prop"))
  190. propstat404.append(prop404)
  191. for tag in props:
  192. element = ET.Element(tag)
  193. is404 = False
  194. if tag == _tag("D", "getetag"):
  195. element.text = item.etag
  196. elif tag == _tag("D", "principal-URL"):
  197. tag = ET.Element(_tag("D", "href"))
  198. tag.text = _href(path)
  199. element.append(tag)
  200. elif tag in (_tag("D", "principal-collection-set"),
  201. _tag("C", "calendar-user-address-set"),
  202. _tag("CR", "addressbook-home-set"),
  203. _tag("C", "calendar-home-set")):
  204. tag = ET.Element(_tag("D", "href"))
  205. tag.text = _href(path)
  206. element.append(tag)
  207. elif tag == _tag("C", "supported-calendar-component-set"):
  208. # This is not a Todo
  209. # pylint: disable=W0511
  210. human_tag = _tag_from_clark(tag)
  211. if is_collection and human_tag in collection_props:
  212. # TODO: what do we have to do if it's not a collection?
  213. components = collection_props[human_tag].split(",")
  214. else:
  215. components = ("VTODO", "VEVENT", "VJOURNAL")
  216. for component in components:
  217. comp = ET.Element(_tag("C", "comp"))
  218. comp.set("name", component)
  219. element.append(comp)
  220. # pylint: enable=W0511
  221. elif tag == _tag("D", "current-user-principal") and user:
  222. tag = ET.Element(_tag("D", "href"))
  223. tag.text = _href("/%s/" % user)
  224. element.append(tag)
  225. elif tag == _tag("D", "current-user-privilege-set"):
  226. privilege = ET.Element(_tag("D", "privilege"))
  227. if rights.authorized(user, item, "w"):
  228. privilege.append(ET.Element(_tag("D", "all")))
  229. privilege.append(ET.Element(_tag("D", "read")))
  230. if rights.authorized(user, item, "w"):
  231. privilege.append(ET.Element(_tag("D", "write")))
  232. privilege.append(ET.Element(_tag("D", "write-properties")))
  233. privilege.append(ET.Element(_tag("D", "write-content")))
  234. element.append(privilege)
  235. elif tag == _tag("D", "supported-report-set"):
  236. for report_name in (
  237. "principal-property-search", "sync-collection",
  238. "expand-property", "principal-search-property-set"):
  239. supported = ET.Element(_tag("D", "supported-report"))
  240. report_tag = ET.Element(_tag("D", "report"))
  241. report_tag.text = report_name
  242. supported.append(report_tag)
  243. element.append(supported)
  244. elif is_collection:
  245. if tag == _tag("D", "getcontenttype"):
  246. element.text = item.mimetype
  247. elif tag == _tag("D", "resourcetype"):
  248. if item.is_principal:
  249. tag = ET.Element(_tag("D", "principal"))
  250. element.append(tag)
  251. if item.is_leaf(item.path) or (
  252. not item.exists and item.resource_type):
  253. # 2nd case happens when the collection is not stored yet,
  254. # but the resource type is guessed
  255. if item.resource_type == "addressbook":
  256. tag = ET.Element(_tag("CR", item.resource_type))
  257. else:
  258. tag = ET.Element(_tag("C", item.resource_type))
  259. element.append(tag)
  260. tag = ET.Element(_tag("D", "collection"))
  261. element.append(tag)
  262. elif tag == _tag("D", "owner") and item.owner_url:
  263. element.text = item.owner_url
  264. elif tag == _tag("CS", "getctag"):
  265. element.text = item.etag
  266. elif tag == _tag("C", "calendar-timezone"):
  267. element.text = ical.serialize(
  268. item.tag, item.headers, item.timezones)
  269. elif tag == _tag("D", "displayname"):
  270. element.text = item.name
  271. elif tag == _tag("ICAL", "calendar-color"):
  272. element.text = item.color
  273. else:
  274. human_tag = _tag_from_clark(tag)
  275. if human_tag in collection_props:
  276. element.text = collection_props[human_tag]
  277. else:
  278. is404 = True
  279. # Not for collections
  280. elif tag == _tag("D", "getcontenttype"):
  281. element.text = "%s; component=%s" % (
  282. item.mimetype, item.tag.lower())
  283. elif tag == _tag("D", "resourcetype"):
  284. # resourcetype must be returned empty for non-collection elements
  285. pass
  286. else:
  287. is404 = True
  288. if is404:
  289. prop404.append(element)
  290. else:
  291. prop200.append(element)
  292. status200 = ET.Element(_tag("D", "status"))
  293. status200.text = _response(200)
  294. propstat200.append(status200)
  295. status404 = ET.Element(_tag("D", "status"))
  296. status404.text = _response(404)
  297. propstat404.append(status404)
  298. if len(prop404):
  299. response.append(propstat404)
  300. return response
  301. def _add_propstat_to(element, tag, status_number):
  302. """Add a PROPSTAT response structure to an element.
  303. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  304. given ``element``, for the following ``tag`` with the given
  305. ``status_number``.
  306. """
  307. propstat = ET.Element(_tag("D", "propstat"))
  308. element.append(propstat)
  309. prop = ET.Element(_tag("D", "prop"))
  310. propstat.append(prop)
  311. if "{" in tag:
  312. clark_tag = tag
  313. else:
  314. clark_tag = _tag(*tag.split(":", 1))
  315. prop_tag = ET.Element(clark_tag)
  316. prop.append(prop_tag)
  317. status = ET.Element(_tag("D", "status"))
  318. status.text = _response(status_number)
  319. propstat.append(status)
  320. def proppatch(path, xml_request, collection):
  321. """Read and answer PROPPATCH requests.
  322. Read rfc4918-9.2 for info.
  323. """
  324. # Reading request
  325. root = ET.fromstring(xml_request.encode("utf8"))
  326. props_to_set = props_from_request(root, actions=("set",))
  327. props_to_remove = props_from_request(root, actions=("remove",))
  328. # Writing answer
  329. multistatus = ET.Element(_tag("D", "multistatus"))
  330. response = ET.Element(_tag("D", "response"))
  331. multistatus.append(response)
  332. href = ET.Element(_tag("D", "href"))
  333. href.text = _href(path)
  334. response.append(href)
  335. with collection.props as collection_props:
  336. for short_name, value in props_to_set.items():
  337. if short_name.split(":")[-1] == "calendar-timezone":
  338. collection.replace(None, value)
  339. collection_props[short_name] = value
  340. _add_propstat_to(response, short_name, 200)
  341. for short_name in props_to_remove:
  342. try:
  343. del collection_props[short_name]
  344. except KeyError:
  345. _add_propstat_to(response, short_name, 412)
  346. else:
  347. _add_propstat_to(response, short_name, 200)
  348. return _pretty_xml(multistatus)
  349. def put(path, ical_request, collection):
  350. """Read PUT requests."""
  351. name = name_from_path(path, collection)
  352. if name in collection.items:
  353. # PUT is modifying an existing item
  354. collection.replace(name, ical_request)
  355. elif name:
  356. # PUT is adding a new item
  357. collection.append(name, ical_request)
  358. else:
  359. # PUT is replacing the whole collection
  360. collection.save(ical_request)
  361. def report(path, xml_request, collection):
  362. """Read and answer REPORT requests.
  363. Read rfc3253-3.6 for info.
  364. """
  365. # Reading request
  366. root = ET.fromstring(xml_request.encode("utf8"))
  367. prop_element = root.find(_tag("D", "prop"))
  368. props = (
  369. [prop.tag for prop in prop_element]
  370. if prop_element is not None else [])
  371. if collection:
  372. if root.tag in (_tag("C", "calendar-multiget"),
  373. _tag("CR", "addressbook-multiget")):
  374. # Read rfc4791-7.9 for info
  375. base_prefix = config.get("server", "base_prefix")
  376. hreferences = set()
  377. for href_element in root.findall(_tag("D", "href")):
  378. href_path = unquote(urlparse(href_element.text).path)
  379. if href_path.startswith(base_prefix):
  380. hreferences.add(href_path[len(base_prefix):])
  381. else:
  382. hreferences = (path,)
  383. # TODO: handle other filters
  384. # TODO: handle the nested comp-filters correctly
  385. # Read rfc4791-9.7.1 for info
  386. tag_filters = set(
  387. element.get("name") for element
  388. in root.findall(".//%s" % _tag("C", "comp-filter")))
  389. tag_filters.discard('VCALENDAR')
  390. else:
  391. hreferences = ()
  392. tag_filters = None
  393. # Writing answer
  394. multistatus = ET.Element(_tag("D", "multistatus"))
  395. collection_tag = collection.tag
  396. collection_headers = collection.headers
  397. collection_timezones = collection.timezones
  398. for hreference in hreferences:
  399. # Check if the reference is an item or a collection
  400. name = name_from_path(hreference, collection)
  401. if name:
  402. # Reference is an item
  403. path = "/".join(hreference.split("/")[:-1]) + "/"
  404. try:
  405. items = [collection.items[name]]
  406. except KeyError:
  407. multistatus.append(
  408. _item_response(hreference, found_item=False))
  409. continue
  410. else:
  411. # Reference is a collection
  412. path = hreference
  413. items = collection.components
  414. for item in items:
  415. href = _href("%s/%s" % (path.rstrip("/"), item.name))
  416. if tag_filters and item.tag not in tag_filters:
  417. continue
  418. found_props = []
  419. not_found_props = []
  420. for tag in props:
  421. element = ET.Element(tag)
  422. if tag == _tag("D", "getetag"):
  423. element.text = item.etag
  424. found_props.append(element)
  425. elif tag == _tag("D", "getcontenttype"):
  426. element.text = "%s; component=%s" % (
  427. item.mimetype, item.tag.lower())
  428. found_props.append(element)
  429. elif tag in (_tag("C", "calendar-data"),
  430. _tag("CR", "address-data")):
  431. if isinstance(item, ical.Component):
  432. element.text = ical.serialize(
  433. collection_tag, collection_headers,
  434. collection_timezones + [item])
  435. found_props.append(element)
  436. else:
  437. not_found_props.append(element)
  438. multistatus.append(_item_response(
  439. href, found_props=found_props, not_found_props=not_found_props,
  440. found_item=True))
  441. return _pretty_xml(multistatus)
  442. def _item_response(href, found_props=(), not_found_props=(), found_item=True):
  443. response = ET.Element(_tag("D", "response"))
  444. href_tag = ET.Element(_tag("D", "href"))
  445. href_tag.text = href
  446. response.append(href_tag)
  447. if found_item:
  448. if found_props:
  449. propstat = ET.Element(_tag("D", "propstat"))
  450. status = ET.Element(_tag("D", "status"))
  451. status.text = _response(200)
  452. prop = ET.Element(_tag("D", "prop"))
  453. for p in found_props:
  454. prop.append(p)
  455. propstat.append(prop)
  456. propstat.append(status)
  457. response.append(propstat)
  458. if not_found_props:
  459. propstat = ET.Element(_tag("D", "propstat"))
  460. status = ET.Element(_tag("D", "status"))
  461. status.text = _response(404)
  462. prop = ET.Element(_tag("D", "prop"))
  463. for p in not_found_props:
  464. prop.append(p)
  465. propstat.append(prop)
  466. propstat.append(status)
  467. response.append(propstat)
  468. else:
  469. status = ET.Element(_tag("D", "status"))
  470. status.text = _response(404)
  471. response.append(status)
  472. return response