xmlutils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008-2011 Guillaume Ayoub
  5. # Copyright © 2008 Nicolas Kandel
  6. # Copyright © 2008 Pascal Halter
  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. import re
  32. import xml.etree.ElementTree as ET
  33. from radicale import client, config, ical
  34. NAMESPACES = {
  35. "C": "urn:ietf:params:xml:ns:caldav",
  36. "D": "DAV:",
  37. "CS": "http://calendarserver.org/ns/",
  38. "ICAL": "http://apple.com/ns/ical/",
  39. "ME": "http://me.com/_namespace/"}
  40. NAMESPACES_REV = {}
  41. for short, url in NAMESPACES.items():
  42. NAMESPACES_REV[url] = short
  43. if hasattr(ET, "register_namespace"):
  44. # Register namespaces cleanly with Python 2.7+ and 3.2+ ...
  45. ET.register_namespace("" if short == "D" else short, url)
  46. else:
  47. # ... and badly with Python 2.6 and 3.1
  48. ET._namespace_map[url] = short # pylint: disable=W0212
  49. CLARK_TAG_REGEX = re.compile(r"""
  50. { # {
  51. (?P<namespace>[^}]*) # namespace URL
  52. } # }
  53. (?P<tag>.*) # short tag name
  54. """, re.VERBOSE)
  55. def _pretty_xml(element, level=0):
  56. """Indent an ElementTree ``element`` and its children."""
  57. i = "\n" + level * " "
  58. if len(element):
  59. if not element.text or not element.text.strip():
  60. element.text = i + " "
  61. if not element.tail or not element.tail.strip():
  62. element.tail = i
  63. for sub_element in element:
  64. _pretty_xml(sub_element, level + 1)
  65. # ``sub_element`` is always defined as len(element) > 0
  66. # pylint: disable=W0631
  67. if not sub_element.tail or not sub_element.tail.strip():
  68. sub_element.tail = i
  69. # pylint: enable=W0631
  70. else:
  71. if level and (not element.tail or not element.tail.strip()):
  72. element.tail = i
  73. if not level:
  74. output_encoding = config.get("encoding", "request")
  75. return ('<?xml version="1.0"?>\n' + ET.tostring(
  76. element, "utf-8").decode("utf-8")).encode(output_encoding)
  77. def _tag(short_name, local):
  78. """Get XML Clark notation {uri(``short_name``)}``local``."""
  79. return "{%s}%s" % (NAMESPACES[short_name], local)
  80. def _tag_from_clark(name):
  81. """Get a human-readable variant of the XML Clark notation tag ``name``.
  82. For a given name using the XML Clark notation, return a human-readable
  83. variant of the tag name for known namespaces. Otherwise, return the name as
  84. is.
  85. """
  86. match = CLARK_TAG_REGEX.match(name)
  87. if match and match.group('namespace') in NAMESPACES_REV:
  88. args = {
  89. 'ns': NAMESPACES_REV[match.group('namespace')],
  90. 'tag': match.group('tag')}
  91. return '%(ns)s:%(tag)s' % args
  92. return name
  93. def _response(code):
  94. """Return full W3C names from HTTP status codes."""
  95. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  96. def name_from_path(path, calendar):
  97. """Return Radicale item name from ``path``."""
  98. calendar_parts = calendar.path.split("/")
  99. path_parts = path.strip("/").split("/")
  100. return path_parts[-1] if (len(path_parts) - len(calendar_parts)) else None
  101. def props_from_request(root, actions=("set", "remove")):
  102. """Return a list of properties as a dictionary."""
  103. result = OrderedDict()
  104. if not hasattr(root, "tag"):
  105. root = ET.fromstring(root.encode("utf8"))
  106. for action in actions:
  107. action_element = root.find(_tag("D", action))
  108. if action_element is not None:
  109. break
  110. else:
  111. action_element = root
  112. prop_element = action_element.find(_tag("D", "prop"))
  113. if prop_element is not None:
  114. for prop in prop_element:
  115. result[_tag_from_clark(prop.tag)] = prop.text
  116. return result
  117. def delete(path, calendar):
  118. """Read and answer DELETE requests.
  119. Read rfc4918-9.6 for info.
  120. """
  121. # Reading request
  122. if calendar.path == path.strip("/"):
  123. # Delete the whole calendar
  124. calendar.delete()
  125. else:
  126. # Remove an item from the calendar
  127. calendar.remove(name_from_path(path, calendar))
  128. # Writing answer
  129. multistatus = ET.Element(_tag("D", "multistatus"))
  130. response = ET.Element(_tag("D", "response"))
  131. multistatus.append(response)
  132. href = ET.Element(_tag("D", "href"))
  133. href.text = path
  134. response.append(href)
  135. status = ET.Element(_tag("D", "status"))
  136. status.text = _response(200)
  137. response.append(status)
  138. return _pretty_xml(multistatus)
  139. def propfind(path, xml_request, calendars, user=None):
  140. """Read and answer PROPFIND requests.
  141. Read rfc4918-9.1 for info.
  142. """
  143. # Reading request
  144. root = ET.fromstring(xml_request.encode("utf8"))
  145. prop_element = root.find(_tag("D", "prop"))
  146. props = [prop.tag for prop in prop_element]
  147. # Writing answer
  148. multistatus = ET.Element(_tag("D", "multistatus"))
  149. for calendar in calendars:
  150. response = _propfind_response(path, calendar, props, user)
  151. multistatus.append(response)
  152. return _pretty_xml(multistatus)
  153. def _propfind_response(path, item, props, user):
  154. """Build and return a PROPFIND response."""
  155. is_calendar = isinstance(item, ical.Calendar)
  156. if is_calendar:
  157. with item.props as cal_props:
  158. calendar_props = cal_props
  159. response = ET.Element(_tag("D", "response"))
  160. href = ET.Element(_tag("D", "href"))
  161. uri = item.url if is_calendar else "%s/%s" % (path, item.name)
  162. href.text = uri.replace("//", "/")
  163. response.append(href)
  164. propstat404 = ET.Element(_tag("D", "propstat"))
  165. propstat200 = ET.Element(_tag("D", "propstat"))
  166. response.append(propstat200)
  167. prop200 = ET.Element(_tag("D", "prop"))
  168. propstat200.append(prop200)
  169. prop404 = ET.Element(_tag("D", "prop"))
  170. propstat404.append(prop404)
  171. for tag in props:
  172. element = ET.Element(tag)
  173. is404 = False
  174. if tag == _tag("D", "getetag"):
  175. element.text = item.etag
  176. elif tag == _tag("D", "principal-URL"):
  177. tag = ET.Element(_tag("D", "href"))
  178. tag.text = path
  179. element.append(tag)
  180. elif tag in (
  181. _tag("D", "principal-collection-set"),
  182. _tag("C", "calendar-user-address-set"),
  183. _tag("C", "calendar-home-set")):
  184. tag = ET.Element(_tag("D", "href"))
  185. tag.text = path
  186. element.append(tag)
  187. elif tag == _tag("C", "supported-calendar-component-set"):
  188. # This is not a Todo
  189. # pylint: disable=W0511
  190. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  191. comp = ET.Element(_tag("C", "comp"))
  192. comp.set("name", component)
  193. element.append(comp)
  194. # pylint: enable=W0511
  195. elif tag == _tag("D", "current-user-principal") and user:
  196. tag = ET.Element(_tag("D", "href"))
  197. tag.text = '/%s/' % user
  198. element.append(tag)
  199. elif tag == _tag("D", "current-user-privilege-set"):
  200. privilege = ET.Element(_tag("D", "privilege"))
  201. privilege.append(ET.Element(_tag("D", "all")))
  202. element.append(privilege)
  203. elif tag == _tag("D", "supported-report-set"):
  204. for report_name in (
  205. "principal-property-search", "sync-collection"
  206. "expand-property", "principal-search-property-set"):
  207. supported = ET.Element(_tag("D", "supported-report"))
  208. report_tag = ET.Element(_tag("D", "report"))
  209. report_tag.text = report_name
  210. supported.append(report_tag)
  211. element.append(supported)
  212. elif is_calendar:
  213. if tag == _tag("D", "getcontenttype"):
  214. element.text = "text/calendar"
  215. elif tag == _tag("D", "resourcetype"):
  216. if item.is_principal:
  217. tag = ET.Element(_tag("D", "principal"))
  218. element.append(tag)
  219. else:
  220. tag = ET.Element(_tag("C", "calendar"))
  221. element.append(tag)
  222. tag = ET.Element(_tag("D", "collection"))
  223. element.append(tag)
  224. elif tag == _tag("D", "owner") and item.owner_url:
  225. element.text = item.owner_url
  226. elif tag == _tag("CS", "getctag"):
  227. element.text = item.etag
  228. elif tag == _tag("C", "calendar-timezone"):
  229. element.text = ical.serialize(item.headers, item.timezones)
  230. else:
  231. human_tag = _tag_from_clark(tag)
  232. if human_tag in calendar_props:
  233. element.text = calendar_props[human_tag]
  234. else:
  235. is404 = True
  236. # Not for calendars
  237. elif tag == _tag("D", "getcontenttype"):
  238. element.text = "text/calendar; component=%s" % item.tag.lower()
  239. elif tag == _tag("D", "resourcetype"):
  240. # resourcetype must be returned empty for non-collection elements
  241. pass
  242. else:
  243. is404 = True
  244. if is404:
  245. prop404.append(element)
  246. else:
  247. prop200.append(element)
  248. status200 = ET.Element(_tag("D", "status"))
  249. status200.text = _response(200)
  250. propstat200.append(status200)
  251. status404 = ET.Element(_tag("D", "status"))
  252. status404.text = _response(404)
  253. propstat404.append(status404)
  254. if len(prop404):
  255. response.append(propstat404)
  256. return response
  257. def _add_propstat_to(element, tag, status_number):
  258. """Add a PROPSTAT response structure to an element.
  259. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  260. given ``element``, for the following ``tag`` with the given
  261. ``status_number``.
  262. """
  263. propstat = ET.Element(_tag("D", "propstat"))
  264. element.append(propstat)
  265. prop = ET.Element(_tag("D", "prop"))
  266. propstat.append(prop)
  267. if '{' in tag:
  268. clark_tag = tag
  269. else:
  270. clark_tag = _tag(*tag.split(':', 1))
  271. prop_tag = ET.Element(clark_tag)
  272. prop.append(prop_tag)
  273. status = ET.Element(_tag("D", "status"))
  274. status.text = _response(status_number)
  275. propstat.append(status)
  276. def proppatch(path, xml_request, calendar):
  277. """Read and answer PROPPATCH requests.
  278. Read rfc4918-9.2 for info.
  279. """
  280. # Reading request
  281. root = ET.fromstring(xml_request.encode("utf8"))
  282. props_to_set = props_from_request(root, actions=('set',))
  283. props_to_remove = props_from_request(root, actions=('remove',))
  284. # Writing answer
  285. multistatus = ET.Element(_tag("D", "multistatus"))
  286. response = ET.Element(_tag("D", "response"))
  287. multistatus.append(response)
  288. href = ET.Element(_tag("D", "href"))
  289. href.text = path
  290. response.append(href)
  291. with calendar.props as calendar_props:
  292. for short_name, value in props_to_set.items():
  293. if short_name == 'C:calendar-timezone':
  294. calendar.replace('', value)
  295. calendar.write()
  296. else:
  297. calendar_props[short_name] = value
  298. _add_propstat_to(response, short_name, 200)
  299. for short_name in props_to_remove:
  300. try:
  301. del calendar_props[short_name]
  302. except KeyError:
  303. _add_propstat_to(response, short_name, 412)
  304. else:
  305. _add_propstat_to(response, short_name, 200)
  306. return _pretty_xml(multistatus)
  307. def put(path, ical_request, calendar):
  308. """Read PUT requests."""
  309. name = name_from_path(path, calendar)
  310. if name in (item.name for item in calendar.items):
  311. # PUT is modifying an existing item
  312. calendar.replace(name, ical_request)
  313. else:
  314. # PUT is adding a new item
  315. calendar.append(name, ical_request)
  316. def report(path, xml_request, calendar):
  317. """Read and answer REPORT requests.
  318. Read rfc3253-3.6 for info.
  319. """
  320. # Reading request
  321. root = ET.fromstring(xml_request.encode("utf8"))
  322. prop_element = root.find(_tag("D", "prop"))
  323. props = [prop.tag for prop in prop_element]
  324. if calendar:
  325. if root.tag == _tag("C", "calendar-multiget"):
  326. # Read rfc4791-7.9 for info
  327. hreferences = set(
  328. href_element.text for href_element
  329. in root.findall(_tag("D", "href")))
  330. else:
  331. hreferences = (path,)
  332. else:
  333. hreferences = ()
  334. # Writing answer
  335. multistatus = ET.Element(_tag("D", "multistatus"))
  336. calendar_items = calendar.items
  337. calendar_headers = calendar.headers
  338. calendar_timezones = calendar.timezones
  339. for hreference in hreferences:
  340. # Check if the reference is an item or a calendar
  341. name = name_from_path(hreference, calendar)
  342. if name:
  343. # Reference is an item
  344. path = "/".join(hreference.split("/")[:-1]) + "/"
  345. items = (item for item in calendar_items if item.name == name)
  346. else:
  347. # Reference is a calendar
  348. path = hreference
  349. items = calendar.components
  350. for item in items:
  351. response = ET.Element(_tag("D", "response"))
  352. multistatus.append(response)
  353. href = ET.Element(_tag("D", "href"))
  354. href.text = "%s/%s" % (path.rstrip("/"), item.name)
  355. response.append(href)
  356. propstat = ET.Element(_tag("D", "propstat"))
  357. response.append(propstat)
  358. prop = ET.Element(_tag("D", "prop"))
  359. propstat.append(prop)
  360. for tag in props:
  361. element = ET.Element(tag)
  362. if tag == _tag("D", "getetag"):
  363. element.text = item.etag
  364. elif tag == _tag("C", "calendar-data"):
  365. if isinstance(item, (ical.Event, ical.Todo, ical.Journal)):
  366. element.text = ical.serialize(
  367. calendar_headers, calendar_timezones + [item])
  368. prop.append(element)
  369. status = ET.Element(_tag("D", "status"))
  370. status.text = _response(200)
  371. propstat.append(status)
  372. return _pretty_xml(multistatus)