xmlutils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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
  30. OrderedDict = dict
  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. NAMESPACES_REV = {}
  40. for short, url in NAMESPACES.items():
  41. NAMESPACES_REV[url] = short
  42. if hasattr(ET, "register_namespace"):
  43. # Register namespaces cleanly with Python 2.7+ and 3.2+ ...
  44. ET.register_namespace("" if short == "D" else short, url)
  45. else:
  46. # ... and badly with Python 2.6 and 3.1
  47. ET._namespace_map[url] = short
  48. CLARK_TAG_REGEX = re.compile(r"""
  49. { # {
  50. (?P<namespace>[^}]*) # namespace URL
  51. } # }
  52. (?P<tag>.*) # short tag name
  53. """, re.VERBOSE)
  54. def _pretty_xml(element, level=0):
  55. """Indent an ElementTree ``element`` and its children."""
  56. i = "\n" + level * " "
  57. if len(element):
  58. if not element.text or not element.text.strip():
  59. element.text = i + " "
  60. if not element.tail or not element.tail.strip():
  61. element.tail = i
  62. for sub_element in element:
  63. _pretty_xml(sub_element, level + 1)
  64. # ``sub_element`` is always defined as len(element) > 0
  65. # pylint: disable=W0631
  66. if not sub_element.tail or not sub_element.tail.strip():
  67. sub_element.tail = i
  68. # pylint: enable=W0631
  69. else:
  70. if level and (not element.tail or not element.tail.strip()):
  71. element.tail = i
  72. if not level:
  73. return ET.tostring(element, config.get("encoding", "request"))
  74. def _tag(short_name, local):
  75. """Get XML Clark notation {uri(``short_name``)}``local``."""
  76. return "{%s}%s" % (NAMESPACES[short_name], local)
  77. def _tag_from_clark(name):
  78. """For a given name using the XML Clark notation returns a human-readable
  79. variant of the tag name for known namespaces. Otherwise returns the name
  80. as is.
  81. """
  82. match = CLARK_TAG_REGEX.match(name)
  83. if match and match.group('namespace') in NAMESPACES_REV:
  84. args = {
  85. 'ns': NAMESPACES_REV[match.group('namespace')],
  86. 'tag': match.group('tag')}
  87. tag_name = '%(ns)s:%(tag)s' % args
  88. else:
  89. tag_name = prop.tag
  90. return tag_name
  91. def _response(code):
  92. """Return full W3C names from HTTP status codes."""
  93. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  94. def name_from_path(path, calendar):
  95. """Return Radicale item name from ``path``."""
  96. calendar_parts = calendar.local_path.strip("/").split("/")
  97. path_parts = path.strip("/").split("/")
  98. return path_parts[-1] if (len(path_parts) - len(calendar_parts)) else None
  99. def props_from_request(root, actions=("set", "remove")):
  100. """Returns a list of properties as a dictionary."""
  101. result = OrderedDict()
  102. if not isinstance(root, ET.Element):
  103. root = ET.fromstring(root.encode("utf8"))
  104. for action in actions:
  105. action_element = root.find(_tag("D", action))
  106. if action_element is not None:
  107. break
  108. else:
  109. action_element = root
  110. prop_element = action_element.find(_tag("D", "prop"))
  111. if prop_element is not None:
  112. for prop in prop_element:
  113. result[_tag_from_clark(prop.tag)] = prop.text
  114. return result
  115. def delete(path, calendar):
  116. """Read and answer DELETE requests.
  117. Read rfc4918-9.6 for info.
  118. """
  119. # Reading request
  120. calendar.remove(name_from_path(path, calendar))
  121. # Writing answer
  122. multistatus = ET.Element(_tag("D", "multistatus"))
  123. response = ET.Element(_tag("D", "response"))
  124. multistatus.append(response)
  125. href = ET.Element(_tag("D", "href"))
  126. href.text = path
  127. response.append(href)
  128. status = ET.Element(_tag("D", "status"))
  129. status.text = _response(200)
  130. response.append(status)
  131. return _pretty_xml(multistatus)
  132. def propfind(path, xml_request, calendar, depth):
  133. """Read and answer PROPFIND requests.
  134. Read rfc4918-9.1 for info.
  135. """
  136. # Reading request
  137. root = ET.fromstring(xml_request.encode("utf8"))
  138. prop_element = root.find(_tag("D", "prop"))
  139. props = [prop.tag for prop in prop_element]
  140. # Writing answer
  141. multistatus = ET.Element(_tag("D", "multistatus"))
  142. if calendar:
  143. if depth == "0":
  144. items = [calendar]
  145. else:
  146. # Depth is 1, infinity or not specified
  147. # We limit ourselves to depth == 1
  148. items = [calendar] + calendar.components
  149. else:
  150. items = []
  151. for item in items:
  152. is_calendar = isinstance(item, ical.Calendar)
  153. response = ET.Element(_tag("D", "response"))
  154. multistatus.append(response)
  155. href = ET.Element(_tag("D", "href"))
  156. href.text = path if is_calendar else path + item.name
  157. response.append(href)
  158. propstat = ET.Element(_tag("D", "propstat"))
  159. response.append(propstat)
  160. prop = ET.Element(_tag("D", "prop"))
  161. propstat.append(prop)
  162. for tag in props:
  163. element = ET.Element(tag)
  164. if tag == _tag("D", "resourcetype") and is_calendar:
  165. tag = ET.Element(_tag("C", "calendar"))
  166. element.append(tag)
  167. tag = ET.Element(_tag("D", "collection"))
  168. element.append(tag)
  169. elif tag == _tag("D", "owner"):
  170. if calendar.owner:
  171. element.text = calendar.owner
  172. elif tag == _tag("D", "getcontenttype"):
  173. element.text = "text/calendar"
  174. elif tag == _tag("CS", "getctag") and is_calendar:
  175. element.text = item.etag
  176. elif tag == _tag("D", "getetag"):
  177. element.text = item.etag
  178. elif tag == _tag("D", "displayname") and is_calendar:
  179. element.text = calendar.name
  180. elif tag == _tag("D", "principal-URL"):
  181. # TODO: use a real principal URL, read rfc3744-4.2 for info
  182. tag = ET.Element(_tag("D", "href"))
  183. tag.text = path
  184. element.append(tag)
  185. elif tag in (
  186. _tag("D", "principal-collection-set"),
  187. _tag("C", "calendar-user-address-set"),
  188. _tag("C", "calendar-home-set")):
  189. tag = ET.Element(_tag("D", "href"))
  190. tag.text = path
  191. element.append(tag)
  192. elif tag == _tag("C", "supported-calendar-component-set"):
  193. # This is not a Todo
  194. # pylint: disable=W0511
  195. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  196. comp = ET.Element(_tag("C", "comp"))
  197. comp.set("name", component)
  198. element.append(comp)
  199. # pylint: enable=W0511
  200. elif tag == _tag("D", "current-user-privilege-set"):
  201. privilege = ET.Element(_tag("D", "privilege"))
  202. privilege.append(ET.Element(_tag("D", "all")))
  203. element.append(privilege)
  204. elif tag == _tag("D", "supported-report-set"):
  205. for report_name in (
  206. "principal-property-search", "sync-collection"
  207. "expand-property", "principal-search-property-set"):
  208. supported = ET.Element(_tag("D", "supported-report"))
  209. report_tag = ET.Element(_tag("D", "report"))
  210. report_tag.text = report_name
  211. supported.append(report_tag)
  212. element.append(supported)
  213. prop.append(element)
  214. status = ET.Element(_tag("D", "status"))
  215. status.text = _response(200)
  216. propstat.append(status)
  217. return _pretty_xml(multistatus)
  218. def _add_propstat_to(element, tag, status_number):
  219. """Adds a propstat structure to the given element for the
  220. following `tag` with the given `status_number`."""
  221. propstat = ET.Element(_tag("D", "propstat"))
  222. element.append(propstat)
  223. prop = ET.Element(_tag("D", "prop"))
  224. propstat.append(prop)
  225. if '{' in tag:
  226. clark_tag = tag
  227. else:
  228. clark_tag = _tag(*tag.split(':', 1))
  229. prop_tag = ET.Element(clark_tag)
  230. prop.append(prop_tag)
  231. status = ET.Element(_tag("D", "status"))
  232. status.text = _response(status_number)
  233. propstat.append(status)
  234. def proppatch(path, xml_request, calendar):
  235. """Read and answer PROPPATCH requests.
  236. Read rfc4918-9.2 for info.
  237. """
  238. # Reading request
  239. root = ET.fromstring(xml_request.encode("utf8"))
  240. props_to_set = props_from_request(root, actions=('set',))
  241. props_to_remove = props_from_request(root, actions=('remove',))
  242. # Writing answer
  243. multistatus = ET.Element(_tag("D", "multistatus"))
  244. response = ET.Element(_tag("D", "response"))
  245. multistatus.append(response)
  246. href = ET.Element(_tag("D", "href"))
  247. href.text = path
  248. response.append(href)
  249. with calendar.props as calendar_props:
  250. for short_name, value in props_to_set.items():
  251. calendar_props[short_name] = value
  252. _add_propstat_to(response, short_name, 200)
  253. for short_name in props_to_remove:
  254. try:
  255. del calendar_props[short_name]
  256. except KeyError:
  257. _add_propstat_to(response, short_name, 412)
  258. else:
  259. _add_propstat_to(response, short_name, 200)
  260. return _pretty_xml(multistatus)
  261. def put(path, ical_request, calendar):
  262. """Read PUT requests."""
  263. name = name_from_path(path, calendar)
  264. if name in (item.name for item in calendar.items):
  265. # PUT is modifying an existing item
  266. calendar.replace(name, ical_request)
  267. else:
  268. # PUT is adding a new item
  269. calendar.append(name, ical_request)
  270. def report(path, xml_request, calendar):
  271. """Read and answer REPORT requests.
  272. Read rfc3253-3.6 for info.
  273. """
  274. # Reading request
  275. root = ET.fromstring(xml_request.encode("utf8"))
  276. prop_element = root.find(_tag("D", "prop"))
  277. props = [prop.tag for prop in prop_element]
  278. if calendar:
  279. if root.tag == _tag("C", "calendar-multiget"):
  280. # Read rfc4791-7.9 for info
  281. hreferences = set(
  282. href_element.text for href_element
  283. in root.findall(_tag("D", "href")))
  284. else:
  285. hreferences = (path,)
  286. else:
  287. hreferences = ()
  288. # Writing answer
  289. multistatus = ET.Element(_tag("D", "multistatus"))
  290. for hreference in hreferences:
  291. # Check if the reference is an item or a calendar
  292. name = name_from_path(hreference, calendar)
  293. if name:
  294. # Reference is an item
  295. path = "/".join(hreference.split("/")[:-1]) + "/"
  296. items = (item for item in calendar.items if item.name == name)
  297. else:
  298. # Reference is a calendar
  299. path = hreference
  300. items = calendar.components
  301. for item in items:
  302. response = ET.Element(_tag("D", "response"))
  303. multistatus.append(response)
  304. href = ET.Element(_tag("D", "href"))
  305. href.text = path + item.name
  306. response.append(href)
  307. propstat = ET.Element(_tag("D", "propstat"))
  308. response.append(propstat)
  309. prop = ET.Element(_tag("D", "prop"))
  310. propstat.append(prop)
  311. for tag in props:
  312. element = ET.Element(tag)
  313. if tag == _tag("D", "getetag"):
  314. element.text = item.etag
  315. elif tag == _tag("C", "calendar-data"):
  316. if isinstance(item, (ical.Event, ical.Todo, ical.Journal)):
  317. element.text = ical.serialize(
  318. calendar.headers, calendar.timezones + [item])
  319. prop.append(element)
  320. status = ET.Element(_tag("D", "status"))
  321. status.text = _response(200)
  322. propstat.append(status)
  323. return _pretty_xml(multistatus)