xmlutils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. "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
  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. return ET.tostring(element, config.get("encoding", "request"))
  75. def _tag(short_name, local):
  76. """Get XML Clark notation {uri(``short_name``)}``local``."""
  77. return "{%s}%s" % (NAMESPACES[short_name], local)
  78. def _tag_from_clark(name):
  79. """For a given name using the XML Clark notation returns a human-readable
  80. variant of the tag name for known namespaces. Otherwise returns the name
  81. as is.
  82. """
  83. match = CLARK_TAG_REGEX.match(name)
  84. if match and match.group('namespace') in NAMESPACES_REV:
  85. args = {
  86. 'ns': NAMESPACES_REV[match.group('namespace')],
  87. 'tag': match.group('tag')}
  88. return '%(ns)s:%(tag)s' % args
  89. return name
  90. def _response(code):
  91. """Return full W3C names from HTTP status codes."""
  92. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  93. def name_from_path(path, calendar):
  94. """Return Radicale item name from ``path``."""
  95. calendar_parts = calendar.local_path.strip("/").split("/")
  96. path_parts = path.strip("/").split("/")
  97. return path_parts[-1] if (len(path_parts) - len(calendar_parts)) else None
  98. def props_from_request(root, actions=("set", "remove")):
  99. """Returns a list of properties as a dictionary."""
  100. result = OrderedDict()
  101. if not isinstance(root, ET.Element):
  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. result[_tag_from_clark(prop.tag)] = prop.text
  113. return result
  114. def delete(path, calendar):
  115. """Read and answer DELETE requests.
  116. Read rfc4918-9.6 for info.
  117. """
  118. # Reading request
  119. calendar.remove(name_from_path(path, calendar))
  120. # Writing answer
  121. multistatus = ET.Element(_tag("D", "multistatus"))
  122. response = ET.Element(_tag("D", "response"))
  123. multistatus.append(response)
  124. href = ET.Element(_tag("D", "href"))
  125. href.text = path
  126. response.append(href)
  127. status = ET.Element(_tag("D", "status"))
  128. status.text = _response(200)
  129. response.append(status)
  130. return _pretty_xml(multistatus)
  131. def propfind(path, xml_request, calendars):
  132. """Read and answer PROPFIND requests.
  133. Read rfc4918-9.1 for info.
  134. """
  135. # Reading request
  136. root = ET.fromstring(xml_request.encode("utf8"))
  137. prop_element = root.find(_tag("D", "prop"))
  138. props = [prop.tag for prop in prop_element]
  139. # Writing answer
  140. multistatus = ET.Element(_tag("D", "multistatus"))
  141. for calendar in calendars:
  142. response = _propfind_response(path, calendar, props)
  143. multistatus.append(response)
  144. return _pretty_xml(multistatus)
  145. def _propfind_response(path, item, props):
  146. is_calendar = isinstance(item, ical.Calendar)
  147. if is_calendar:
  148. with item.props as cal_props:
  149. calendar_props = cal_props
  150. response = ET.Element(_tag("D", "response"))
  151. href = ET.Element(_tag("D", "href"))
  152. href.text = item.url if is_calendar else path + item.name
  153. response.append(href)
  154. propstat404 = ET.Element(_tag("D", "propstat"))
  155. propstat200 = ET.Element(_tag("D", "propstat"))
  156. response.append(propstat200)
  157. prop200 = ET.Element(_tag("D", "prop"))
  158. propstat200.append(prop200)
  159. prop404 = ET.Element(_tag("D", "prop"))
  160. propstat404.append(prop404)
  161. for tag in props:
  162. element = ET.Element(tag)
  163. is404 = False
  164. if tag == _tag("D", "getetag"):
  165. element.text = item.etag
  166. elif tag == _tag("D", "principal-URL"):
  167. # TODO: use a real principal URL, read rfc3744-4.2 for info
  168. tag = ET.Element(_tag("D", "href"))
  169. if item.owner_url:
  170. tag.text = item.owner_url
  171. else:
  172. tag.text = path
  173. element.append(tag)
  174. elif tag in (
  175. _tag("D", "principal-collection-set"),
  176. _tag("C", "calendar-user-address-set"),
  177. _tag("C", "calendar-home-set")):
  178. tag = ET.Element(_tag("D", "href"))
  179. tag.text = path
  180. element.append(tag)
  181. elif tag == _tag("C", "supported-calendar-component-set"):
  182. # This is not a Todo
  183. # pylint: disable=W0511
  184. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  185. comp = ET.Element(_tag("C", "comp"))
  186. comp.set("name", component)
  187. element.append(comp)
  188. # pylint: enable=W0511
  189. elif tag == _tag("D", "current-user-privilege-set"):
  190. privilege = ET.Element(_tag("D", "privilege"))
  191. privilege.append(ET.Element(_tag("D", "all")))
  192. element.append(privilege)
  193. elif tag == _tag("D", "supported-report-set"):
  194. for report_name in (
  195. "principal-property-search", "sync-collection"
  196. "expand-property", "principal-search-property-set"):
  197. supported = ET.Element(_tag("D", "supported-report"))
  198. report_tag = ET.Element(_tag("D", "report"))
  199. report_tag.text = report_name
  200. supported.append(report_tag)
  201. element.append(supported)
  202. elif is_calendar:
  203. if tag == _tag("D", "getcontenttype"):
  204. element.text = "text/calendar"
  205. elif tag == _tag("D", "resourcetype"):
  206. if not item.is_principal:
  207. tag = ET.Element(_tag("C", "calendar"))
  208. element.append(tag)
  209. tag = ET.Element(_tag("D", "collection"))
  210. element.append(tag)
  211. elif tag == _tag("D", "owner") and item.owner_url:
  212. element.text = item.owner_url
  213. elif tag == _tag("CS", "getctag"):
  214. element.text = item.etag
  215. elif tag == _tag("C", "calendar-timezone"):
  216. element.text = ical.serialize(item.headers, item.timezones)
  217. else:
  218. human_tag = _tag_from_clark(tag)
  219. if human_tag in calendar_props:
  220. element.text = calendar_props[human_tag]
  221. else:
  222. is404 = True
  223. # not for calendars
  224. elif tag == _tag("D", "getcontenttype"):
  225. element.text = \
  226. "text/calendar; component={}".format(item.tag.lower())
  227. else:
  228. is404 = True
  229. if is404:
  230. prop404.append(element)
  231. else:
  232. prop200.append(element)
  233. status200 = ET.Element(_tag("D", "status"))
  234. status200.text = _response(200)
  235. propstat200.append(status200)
  236. status404 = ET.Element(_tag("D", "status"))
  237. status404.text = _response(404)
  238. propstat404.append(status404)
  239. if len(prop404):
  240. response.append(propstat404)
  241. return response
  242. def _add_propstat_to(element, tag, status_number):
  243. """Adds a propstat structure to the given element for the
  244. following `tag` with the given `status_number`."""
  245. propstat = ET.Element(_tag("D", "propstat"))
  246. element.append(propstat)
  247. prop = ET.Element(_tag("D", "prop"))
  248. propstat.append(prop)
  249. if '{' in tag:
  250. clark_tag = tag
  251. else:
  252. clark_tag = _tag(*tag.split(':', 1))
  253. prop_tag = ET.Element(clark_tag)
  254. prop.append(prop_tag)
  255. status = ET.Element(_tag("D", "status"))
  256. status.text = _response(status_number)
  257. propstat.append(status)
  258. def proppatch(path, xml_request, calendar):
  259. """Read and answer PROPPATCH requests.
  260. Read rfc4918-9.2 for info.
  261. """
  262. # Reading request
  263. root = ET.fromstring(xml_request.encode("utf8"))
  264. props_to_set = props_from_request(root, actions=('set',))
  265. props_to_remove = props_from_request(root, actions=('remove',))
  266. # Writing answer
  267. multistatus = ET.Element(_tag("D", "multistatus"))
  268. response = ET.Element(_tag("D", "response"))
  269. multistatus.append(response)
  270. href = ET.Element(_tag("D", "href"))
  271. href.text = path
  272. response.append(href)
  273. with calendar.props as calendar_props:
  274. for short_name, value in props_to_set.items():
  275. if short_name == 'C:calendar-timezone':
  276. calendar.replace('', value)
  277. calendar.write()
  278. else:
  279. calendar_props[short_name] = value
  280. _add_propstat_to(response, short_name, 200)
  281. for short_name in props_to_remove:
  282. try:
  283. del calendar_props[short_name]
  284. except KeyError:
  285. _add_propstat_to(response, short_name, 412)
  286. else:
  287. _add_propstat_to(response, short_name, 200)
  288. return _pretty_xml(multistatus)
  289. def put(path, ical_request, calendar):
  290. """Read PUT requests."""
  291. name = name_from_path(path, calendar)
  292. if name in (item.name for item in calendar.items):
  293. # PUT is modifying an existing item
  294. calendar.replace(name, ical_request)
  295. else:
  296. # PUT is adding a new item
  297. calendar.append(name, ical_request)
  298. def report(path, xml_request, calendar):
  299. """Read and answer REPORT requests.
  300. Read rfc3253-3.6 for info.
  301. """
  302. # Reading request
  303. root = ET.fromstring(xml_request.encode("utf8"))
  304. prop_element = root.find(_tag("D", "prop"))
  305. props = [prop.tag for prop in prop_element]
  306. if calendar:
  307. if root.tag == _tag("C", "calendar-multiget"):
  308. # Read rfc4791-7.9 for info
  309. hreferences = set(
  310. href_element.text for href_element
  311. in root.findall(_tag("D", "href")))
  312. else:
  313. hreferences = (path,)
  314. else:
  315. hreferences = ()
  316. # Writing answer
  317. multistatus = ET.Element(_tag("D", "multistatus"))
  318. for hreference in hreferences:
  319. # Check if the reference is an item or a calendar
  320. name = name_from_path(hreference, calendar)
  321. if name:
  322. # Reference is an item
  323. path = "/".join(hreference.split("/")[:-1]) + "/"
  324. items = (item for item in calendar.items if item.name == name)
  325. else:
  326. # Reference is a calendar
  327. path = hreference
  328. items = calendar.components
  329. for item in items:
  330. response = ET.Element(_tag("D", "response"))
  331. multistatus.append(response)
  332. href = ET.Element(_tag("D", "href"))
  333. href.text = path + item.name
  334. response.append(href)
  335. propstat = ET.Element(_tag("D", "propstat"))
  336. response.append(propstat)
  337. prop = ET.Element(_tag("D", "prop"))
  338. propstat.append(prop)
  339. for tag in props:
  340. element = ET.Element(tag)
  341. if tag == _tag("D", "getetag"):
  342. element.text = item.etag
  343. elif tag == _tag("C", "calendar-data"):
  344. if isinstance(item, (ical.Event, ical.Todo, ical.Journal)):
  345. element.text = ical.serialize(
  346. calendar.headers, calendar.timezones + [item])
  347. prop.append(element)
  348. status = ET.Element(_tag("D", "status"))
  349. status.text = _response(200)
  350. propstat.append(status)
  351. return _pretty_xml(multistatus)