xmlutils.py 21 KB

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