xmlutils.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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 copy
  25. import posixpath
  26. import re
  27. import xml.etree.ElementTree as ET
  28. from collections import OrderedDict
  29. from datetime import datetime, timedelta, timezone
  30. from http import client
  31. from urllib.parse import quote, unquote, urlparse
  32. from . import storage
  33. MIMETYPES = {
  34. "VADDRESSBOOK": "text/vcard",
  35. "VCALENDAR": "text/calendar"}
  36. NAMESPACES = {
  37. "C": "urn:ietf:params:xml:ns:caldav",
  38. "CR": "urn:ietf:params:xml:ns:carddav",
  39. "D": "DAV:",
  40. "CS": "http://calendarserver.org/ns/",
  41. "ICAL": "http://apple.com/ns/ical/",
  42. "ME": "http://me.com/_namespace/"}
  43. NAMESPACES_REV = {}
  44. for short, url in NAMESPACES.items():
  45. NAMESPACES_REV[url] = short
  46. ET.register_namespace("" if short == "D" else short, url)
  47. CLARK_TAG_REGEX = re.compile(r"{(?P<namespace>[^}]*)}(?P<tag>.*)", re.VERBOSE)
  48. HUMAN_REGEX = re.compile(r"(?P<namespace>[^:{}]*)(?P<tag>.*)", re.VERBOSE)
  49. def pretty_xml(element, level=0):
  50. """Indent an ElementTree ``element`` and its children."""
  51. if not level:
  52. element = copy.deepcopy(element)
  53. i = "\n" + level * " "
  54. if len(element):
  55. if not element.text or not element.text.strip():
  56. element.text = i + " "
  57. if not element.tail or not element.tail.strip():
  58. element.tail = i
  59. for sub_element in element:
  60. pretty_xml(sub_element, level + 1)
  61. if not sub_element.tail or not sub_element.tail.strip():
  62. sub_element.tail = i
  63. else:
  64. if level and (not element.tail or not element.tail.strip()):
  65. element.tail = i
  66. if not level:
  67. return '<?xml version="1.0"?>\n%s' % ET.tostring(element, "unicode")
  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 _tag_from_human(name):
  85. """Get an XML Clark notation tag from human-readable variant ``name``."""
  86. match = HUMAN_REGEX.match(name)
  87. if match and match.group("namespace") in NAMESPACES:
  88. return _tag(match.group("namespace"), match.group("tag"))
  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 _href(base_prefix, href):
  94. """Return prefixed href."""
  95. return quote("%s%s" % (base_prefix, href))
  96. def _date_to_datetime(date_):
  97. """Transform a date to a UTC datetime.
  98. If date_ is a datetime without timezone, return as UTC datetime. If date_
  99. is already a datetime with timezone, return as is.
  100. """
  101. if not isinstance(date_, datetime):
  102. date_ = datetime.combine(date_, datetime.min.time())
  103. if not date_.tzinfo:
  104. date_ = date_.replace(tzinfo=timezone.utc)
  105. return date_
  106. def _comp_match(item, filter_, scope="collection"):
  107. """Check whether the ``item`` matches the comp ``filter_``.
  108. If ``scope`` is ``"collection"``, the filter is applied on the
  109. item's collection. Otherwise, it's applied on the item.
  110. See rfc4791-9.7.1.
  111. """
  112. filter_length = len(filter_)
  113. if scope == "collection":
  114. tag = item.collection.get_meta("tag")
  115. else:
  116. for component in item.components():
  117. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  118. tag = component.name
  119. break
  120. else:
  121. return False
  122. if filter_length == 0:
  123. # Point #1 of rfc4791-9.7.1
  124. return filter_.get("name") == tag
  125. else:
  126. if filter_length == 1:
  127. if filter_[0].tag == _tag("C", "is-not-defined"):
  128. # Point #2 of rfc4791-9.7.1
  129. return filter_.get("name") != tag
  130. if filter_[0].tag == _tag("C", "time-range"):
  131. # Point #3 of rfc4791-9.7.1
  132. if not _time_range_match(item.item, filter_[0], tag):
  133. return False
  134. filter_ = filter_[1:]
  135. # Point #4 of rfc4791-9.7.1
  136. return all(
  137. _prop_match(item, child) if child.tag == _tag("C", "prop-filter")
  138. else _comp_match(item, child, scope="component")
  139. for child in filter_)
  140. def _prop_match(item, filter_):
  141. """Check whether the ``item`` matches the prop ``filter_``.
  142. See rfc4791-9.7.2 and rfc6352-10.5.1.
  143. """
  144. filter_length = len(filter_)
  145. if item.collection.get_meta("tag") == "VCALENDAR":
  146. for component in item.components():
  147. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  148. vobject_item = component
  149. break
  150. else:
  151. vobject_item = item.item
  152. if filter_length == 0:
  153. # Point #1 of rfc4791-9.7.2
  154. return filter_.get("name").lower() in vobject_item.contents
  155. else:
  156. name = filter_.get("name").lower()
  157. if filter_length == 1:
  158. if filter_[0].tag == _tag("C", "is-not-defined"):
  159. # Point #2 of rfc4791-9.7.2
  160. return name not in vobject_item.contents
  161. if filter_[0].tag == _tag("C", "time-range"):
  162. # Point #3 of rfc4791-9.7.2
  163. if not _time_range_match(vobject_item, filter_[0], name):
  164. return False
  165. filter_ = filter_[1:]
  166. elif filter_[0].tag == _tag("C", "text-match"):
  167. # Point #4 of rfc4791-9.7.2
  168. if not _text_match(vobject_item, filter_[0], name):
  169. return False
  170. filter_ = filter_[1:]
  171. return all(
  172. _param_filter_match(vobject_item, param_filter, name)
  173. for param_filter in filter_)
  174. def _time_range_match(vobject_item, filter_, child_name):
  175. """Check whether the ``item`` matches the time-range ``filter_``.
  176. See rfc4791-9.9.
  177. """
  178. start = filter_.get("start")
  179. end = filter_.get("end")
  180. if not start and not end:
  181. return False
  182. if start:
  183. start = datetime.strptime(start, "%Y%m%dT%H%M%SZ")
  184. else:
  185. start = datetime.min
  186. if end:
  187. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  188. else:
  189. end = datetime.max
  190. start = start.replace(tzinfo=timezone.utc)
  191. end = end.replace(tzinfo=timezone.utc)
  192. child = getattr(vobject_item, child_name.lower())
  193. # Comments give the lines in the tables of the specification
  194. if child_name == "VEVENT":
  195. # TODO: check if there's a timezone
  196. dtstart = child.dtstart.value
  197. if child.rruleset:
  198. dtstarts = child.getrruleset(addRDate=True)
  199. else:
  200. dtstarts = (dtstart,)
  201. dtend = getattr(child, "dtend", None)
  202. if dtend is not None:
  203. dtend = dtend.value
  204. original_duration = (dtend - dtstart).total_seconds()
  205. dtend = _date_to_datetime(dtend)
  206. duration = getattr(child, "duration", None)
  207. if duration is not None:
  208. original_duration = duration = duration.value
  209. for dtstart in dtstarts:
  210. dtstart_is_datetime = isinstance(dtstart, datetime)
  211. dtstart = _date_to_datetime(dtstart)
  212. if dtstart > end:
  213. break
  214. if dtend is not None:
  215. # Line 1
  216. dtend = dtstart + timedelta(seconds=original_duration)
  217. if start < dtend and end > dtstart:
  218. return True
  219. elif duration is not None:
  220. if original_duration is None:
  221. original_duration = duration.seconds
  222. if duration.seconds > 0:
  223. # Line 2
  224. if start < dtstart + duration and end > dtstart:
  225. return True
  226. elif start <= dtstart and end > dtstart:
  227. # Line 3
  228. return True
  229. elif dtstart_is_datetime:
  230. # Line 4
  231. if start <= dtstart and end > dtstart:
  232. return True
  233. elif start < dtstart + timedelta(days=1) and end > dtstart:
  234. # Line 5
  235. return True
  236. elif child_name == "VTODO":
  237. dtstart = getattr(child, "dtstart", None)
  238. duration = getattr(child, "duration", None)
  239. due = getattr(child, "due", None)
  240. completed = getattr(child, "completed", None)
  241. created = getattr(child, "created", None)
  242. if dtstart is not None:
  243. dtstart = _date_to_datetime(dtstart.value)
  244. if duration is not None:
  245. duration = duration.value
  246. if due is not None:
  247. due = _date_to_datetime(due.value)
  248. if dtstart is not None:
  249. original_duration = (due - dtstart).total_seconds()
  250. if completed is not None:
  251. completed = _date_to_datetime(completed.value)
  252. if created is not None:
  253. created = _date_to_datetime(created.value)
  254. original_duration = (completed - created).total_seconds()
  255. elif created is not None:
  256. created = _date_to_datetime(created.value)
  257. if child.rruleset:
  258. reference_dates = child.getrruleset(addRDate=True)
  259. else:
  260. if dtstart is not None:
  261. reference_dates = (dtstart,)
  262. elif due is not None:
  263. reference_dates = (due,)
  264. elif completed is not None:
  265. reference_dates = (completed,)
  266. elif created is not None:
  267. reference_dates = (created,)
  268. else:
  269. # Line 8
  270. return True
  271. for reference_date in reference_dates:
  272. reference_date = _date_to_datetime(reference_date)
  273. if reference_date > end:
  274. break
  275. if dtstart is not None and duration is not None:
  276. # Line 1
  277. if start <= reference_date + duration and (
  278. end > reference_date or
  279. end >= reference_date + duration):
  280. return True
  281. elif dtstart is not None and due is not None:
  282. # Line 2
  283. due = reference_date + timedelta(seconds=original_duration)
  284. if (start < due or start <= reference_date) and (
  285. end > reference_date or end >= due):
  286. return True
  287. elif dtstart is not None:
  288. if start <= reference_date and end > reference_date:
  289. return True
  290. elif due is not None:
  291. # Line 4
  292. if start < reference_date and end >= reference_date:
  293. return True
  294. elif completed is not None and created is not None:
  295. # Line 5
  296. completed = reference_date + timedelta(
  297. seconds=original_duration)
  298. if (start <= reference_date or start <= completed) and (
  299. end >= reference_date or end >= completed):
  300. return True
  301. elif completed is not None:
  302. # Line 6
  303. if start <= reference_date and end >= reference_date:
  304. return True
  305. elif created is not None:
  306. # Line 7
  307. if end > reference_date:
  308. return True
  309. elif child_name == "VJOURNAL":
  310. dtstart = getattr(child, "dtstart", None)
  311. if dtstart is not None:
  312. dtstart = dtstart.value
  313. if child.rruleset:
  314. dtstarts = child.getrruleset(addRDate=True)
  315. else:
  316. dtstarts = (dtstart,)
  317. for dtstart in dtstarts:
  318. dtstart_is_datetime = isinstance(dtstart, datetime)
  319. dtstart = _date_to_datetime(dtstart)
  320. if dtstart > end:
  321. break
  322. if dtstart_is_datetime:
  323. # Line 1
  324. if start <= dtstart and end > dtstart:
  325. return True
  326. elif start < dtstart + timedelta(days=1) and end > dtstart:
  327. # Line 2
  328. return True
  329. return False
  330. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  331. """Check whether the ``item`` matches the text-match ``filter_``.
  332. See rfc4791-9.7.5.
  333. """
  334. # TODO: collations are not supported, but the default ones needed
  335. # for DAV servers are actually pretty useless. Texts are lowered to
  336. # be case-insensitive, almost as the "i;ascii-casemap" value.
  337. match = next(filter_.itertext()).lower()
  338. children = getattr(vobject_item, "%s_list" % child_name, [])
  339. if attrib_name:
  340. condition = any(
  341. match in attrib.lower() for child in children
  342. for attrib in child.params.get(attrib_name, []))
  343. else:
  344. condition = any(match in child.value.lower() for child in children)
  345. if filter_.get("negate-condition") == "yes":
  346. return not condition
  347. else:
  348. return condition
  349. def _param_filter_match(vobject_item, filter_, parent_name):
  350. """Check whether the ``item`` matches the param-filter ``filter_``.
  351. See rfc4791-9.7.3.
  352. """
  353. name = filter_.get("name")
  354. children = getattr(vobject_item, "%s_list" % parent_name, [])
  355. condition = any(name in child.params for child in children)
  356. if len(filter_):
  357. if filter_[0].tag == _tag("C", "text-match"):
  358. return condition and _text_match(
  359. vobject_item, filter_[0], parent_name, name)
  360. elif filter_[0].tag == _tag("C", "is-not-defined"):
  361. return not condition
  362. else:
  363. return condition
  364. def name_from_path(path, collection):
  365. """Return Radicale item name from ``path``."""
  366. path = path.strip("/") + "/"
  367. start = collection.path + "/"
  368. if not path.startswith(start):
  369. raise ValueError("%r doesn't start with %r" % (path, start))
  370. name = path[len(start):][:-1]
  371. if name and not storage.is_safe_path_component(name):
  372. raise ValueError("%r is not a component in collection %r" %
  373. (name, collection.path))
  374. return name
  375. def props_from_request(xml_request, actions=("set", "remove")):
  376. """Return a list of properties as a dictionary."""
  377. result = OrderedDict()
  378. if xml_request is None:
  379. return result
  380. for action in actions:
  381. action_element = xml_request.find(_tag("D", action))
  382. if action_element is not None:
  383. break
  384. else:
  385. action_element = xml_request
  386. prop_element = action_element.find(_tag("D", "prop"))
  387. if prop_element is not None:
  388. for prop in prop_element:
  389. if prop.tag == _tag("D", "resourcetype"):
  390. for resource_type in prop:
  391. if resource_type.tag == _tag("C", "calendar"):
  392. result["tag"] = "VCALENDAR"
  393. break
  394. elif resource_type.tag == _tag("CR", "addressbook"):
  395. result["tag"] = "VADDRESSBOOK"
  396. break
  397. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  398. result[_tag_from_clark(prop.tag)] = ",".join(
  399. supported_comp.attrib["name"]
  400. for supported_comp in prop
  401. if supported_comp.tag == _tag("C", "comp"))
  402. else:
  403. result[_tag_from_clark(prop.tag)] = prop.text
  404. return result
  405. def delete(base_prefix, path, collection, href=None):
  406. """Read and answer DELETE requests.
  407. Read rfc4918-9.6 for info.
  408. """
  409. collection.delete(href)
  410. multistatus = ET.Element(_tag("D", "multistatus"))
  411. response = ET.Element(_tag("D", "response"))
  412. multistatus.append(response)
  413. href = ET.Element(_tag("D", "href"))
  414. href.text = _href(base_prefix, path)
  415. response.append(href)
  416. status = ET.Element(_tag("D", "status"))
  417. status.text = _response(200)
  418. response.append(status)
  419. return multistatus
  420. def propfind(base_prefix, path, xml_request, read_collections,
  421. write_collections, user):
  422. """Read and answer PROPFIND requests.
  423. Read rfc4918-9.1 for info.
  424. The collections parameter is a list of collections that are to be included
  425. in the output.
  426. """
  427. # A client may choose not to submit a request body. An empty PROPFIND
  428. # request body MUST be treated as if it were an 'allprop' request.
  429. top_tag = (xml_request[0] if xml_request is not None else
  430. ET.Element(_tag("D", "allprop")))
  431. props = ()
  432. if top_tag.tag == _tag("D", "allprop"):
  433. props = [
  434. _tag("D", "getcontenttype"),
  435. _tag("D", "resourcetype"),
  436. _tag("D", "displayname"),
  437. _tag("D", "owner"),
  438. _tag("D", "getetag"),
  439. _tag("ICAL", "calendar-color"),
  440. _tag("CS", "getctag"),
  441. _tag("C", "supported-calendar-component-set"),
  442. _tag("D", "supported-report-set"),
  443. ]
  444. elif top_tag.tag == _tag("D", "prop"):
  445. props = [prop.tag for prop in top_tag]
  446. if _tag("D", "current-user-principal") in props and not user:
  447. # Ask for authentication
  448. # Returning the DAV:unauthenticated pseudo-principal as specified in
  449. # RFC 5397 doesn't seem to work with DAVdroid.
  450. return client.FORBIDDEN, None
  451. # Writing answer
  452. multistatus = ET.Element(_tag("D", "multistatus"))
  453. collections = []
  454. for collection in write_collections:
  455. collections.append(collection)
  456. if top_tag.tag == _tag("D", "propname"):
  457. response = _propfind_response(
  458. base_prefix, path, collection, (), user, write=True,
  459. propnames=True)
  460. else:
  461. response = _propfind_response(
  462. base_prefix, path, collection, props, user, write=True)
  463. if response:
  464. multistatus.append(response)
  465. for collection in read_collections:
  466. if collection in collections:
  467. continue
  468. if top_tag.tag == _tag("D", "propname"):
  469. response = _propfind_response(
  470. base_prefix, path, collection, (), user, write=False,
  471. propnames=True)
  472. else:
  473. response = _propfind_response(
  474. base_prefix, path, collection, props, user, write=False)
  475. if response:
  476. multistatus.append(response)
  477. return client.MULTI_STATUS, multistatus
  478. def _propfind_response(base_prefix, path, item, props, user, write=False,
  479. propnames=False):
  480. """Build and return a PROPFIND response."""
  481. is_collection = isinstance(item, storage.BaseCollection)
  482. if is_collection:
  483. is_leaf = item.get_meta("tag") in ("VADDRESSBOOK", "VCALENDAR")
  484. collection = item
  485. else:
  486. collection = item.collection
  487. response = ET.Element(_tag("D", "response"))
  488. href = ET.Element(_tag("D", "href"))
  489. if is_collection:
  490. # Some clients expect collections to end with /
  491. uri = "/%s/" % item.path if item.path else "/"
  492. else:
  493. uri = "/" + posixpath.join(collection.path, item.href)
  494. href.text = _href(base_prefix, uri)
  495. response.append(href)
  496. propstat404 = ET.Element(_tag("D", "propstat"))
  497. propstat200 = ET.Element(_tag("D", "propstat"))
  498. response.append(propstat200)
  499. prop200 = ET.Element(_tag("D", "prop"))
  500. propstat200.append(prop200)
  501. prop404 = ET.Element(_tag("D", "prop"))
  502. propstat404.append(prop404)
  503. if propnames:
  504. # Should list all properties that can be retrieved by the code below
  505. prop200.append(ET.Element(_tag("D", "getetag")))
  506. prop200.append(ET.Element(_tag("D", "principal-URL")))
  507. prop200.append(ET.Element(_tag("D", "principal-collection-set")))
  508. prop200.append(ET.Element(_tag("C", "calendar-user-address-set")))
  509. prop200.append(ET.Element(_tag("CR", "addressbook-home-set")))
  510. prop200.append(ET.Element(_tag("C", "calendar-home-set")))
  511. prop200.append(ET.Element(
  512. _tag("C", "supported-calendar-component-set")))
  513. prop200.append(ET.Element(_tag("D", "current-user-privilege-set")))
  514. prop200.append(ET.Element(_tag("D", "supported-report-set")))
  515. prop200.append(ET.Element(_tag("D", "getcontenttype")))
  516. prop200.append(ET.Element(_tag("D", "resourcetype")))
  517. if is_collection:
  518. prop200.append(ET.Element(_tag("CS", "getctag")))
  519. prop200.append(ET.Element(_tag("C", "calendar-timezone")))
  520. prop200.append(ET.Element(_tag("D", "displayname")))
  521. prop200.append(ET.Element(_tag("ICAL", "calendar-color")))
  522. prop200.append(ET.Element(_tag("D", "owner")))
  523. if is_leaf:
  524. meta = item.get_meta()
  525. for tag in meta:
  526. clark_tag = _tag_from_human(tag)
  527. if prop200.find(clark_tag) is None:
  528. prop200.append(ET.Element(clark_tag))
  529. for tag in props:
  530. element = ET.Element(tag)
  531. is404 = False
  532. if tag == _tag("D", "getetag"):
  533. element.text = item.etag
  534. elif tag == _tag("D", "getlastmodified"):
  535. element.text = item.last_modified
  536. elif tag == _tag("D", "principal-collection-set"):
  537. tag = ET.Element(_tag("D", "href"))
  538. tag.text = _href(base_prefix, "/")
  539. element.append(tag)
  540. elif (tag in (_tag("C", "calendar-user-address-set"),
  541. _tag("D", "principal-URL"),
  542. _tag("CR", "addressbook-home-set"),
  543. _tag("C", "calendar-home-set")) and
  544. collection.is_principal and is_collection):
  545. tag = ET.Element(_tag("D", "href"))
  546. tag.text = _href(base_prefix, path)
  547. element.append(tag)
  548. elif tag == _tag("C", "supported-calendar-component-set"):
  549. human_tag = _tag_from_clark(tag)
  550. if is_collection and is_leaf:
  551. meta = item.get_meta(human_tag)
  552. if meta:
  553. components = meta.split(",")
  554. else:
  555. components = ("VTODO", "VEVENT", "VJOURNAL")
  556. for component in components:
  557. comp = ET.Element(_tag("C", "comp"))
  558. comp.set("name", component)
  559. element.append(comp)
  560. else:
  561. is404 = True
  562. elif tag == _tag("D", "current-user-principal"):
  563. tag = ET.Element(_tag("D", "href"))
  564. tag.text = _href(base_prefix, ("/%s/" % user) if user else "/")
  565. element.append(tag)
  566. elif tag == _tag("D", "current-user-privilege-set"):
  567. privileges = [("D", "read")]
  568. if write:
  569. privileges.append(("D", "all"))
  570. privileges.append(("D", "write"))
  571. privileges.append(("D", "write-properties"))
  572. privileges.append(("D", "write-content"))
  573. for ns, privilege_name in privileges:
  574. privilege = ET.Element(_tag("D", "privilege"))
  575. privilege.append(ET.Element(_tag(ns, privilege_name)))
  576. element.append(privilege)
  577. elif tag == _tag("D", "supported-report-set"):
  578. # These 3 reports are not implemented
  579. reports = [
  580. ("D", "expand-property"),
  581. ("D", "principal-search-property-set"),
  582. ("D", "principal-property-search")]
  583. if is_collection and is_leaf:
  584. reports.append(("D", "sync-collection"))
  585. if item.get_meta("tag") == "VADDRESSBOOK":
  586. reports.append(("CR", "addressbook-multiget"))
  587. reports.append(("CR", "addressbook-query"))
  588. elif item.get_meta("tag") == "VCALENDAR":
  589. reports.append(("C", "calendar-multiget"))
  590. reports.append(("C", "calendar-query"))
  591. for ns, report_name in reports:
  592. supported = ET.Element(_tag("D", "supported-report"))
  593. report_tag = ET.Element(_tag("D", "report"))
  594. supported_report_tag = ET.Element(_tag(ns, report_name))
  595. report_tag.append(supported_report_tag)
  596. supported.append(report_tag)
  597. element.append(supported)
  598. elif is_collection:
  599. if tag == _tag("D", "getcontenttype"):
  600. if is_leaf:
  601. element.text = MIMETYPES[item.get_meta("tag")]
  602. else:
  603. is404 = True
  604. elif tag == _tag("D", "resourcetype"):
  605. if item.is_principal:
  606. tag = ET.Element(_tag("D", "principal"))
  607. element.append(tag)
  608. if is_leaf:
  609. if item.get_meta("tag") == "VADDRESSBOOK":
  610. tag = ET.Element(_tag("CR", "addressbook"))
  611. element.append(tag)
  612. elif item.get_meta("tag") == "VCALENDAR":
  613. tag = ET.Element(_tag("C", "calendar"))
  614. element.append(tag)
  615. tag = ET.Element(_tag("D", "collection"))
  616. element.append(tag)
  617. elif tag == _tag("D", "owner"):
  618. if is_leaf and item.owner:
  619. element.text = "/%s/" % item.owner
  620. else:
  621. is404 = True
  622. elif tag == _tag("D", "displayname"):
  623. if is_leaf:
  624. element.text = item.get_meta("D:displayname") or item.path
  625. else:
  626. is404 = True
  627. elif tag == _tag("CS", "getctag"):
  628. if is_leaf:
  629. element.text = item.etag
  630. else:
  631. is404 = True
  632. else:
  633. human_tag = _tag_from_clark(tag)
  634. meta = item.get_meta(human_tag)
  635. if meta:
  636. element.text = meta
  637. else:
  638. is404 = True
  639. # Not for collections
  640. elif tag == _tag("D", "getcontenttype"):
  641. name = item.name.lower()
  642. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  643. element.text = "%s; component=%s" % (mimetype, name)
  644. elif tag == _tag("D", "resourcetype"):
  645. # resourcetype must be returned empty for non-collection elements
  646. pass
  647. elif tag == _tag("D", "getcontentlength"):
  648. encoding = collection.configuration.get("encoding", "request")
  649. element.text = str(len(item.serialize().encode(encoding)))
  650. else:
  651. is404 = True
  652. if is404:
  653. prop404.append(element)
  654. else:
  655. prop200.append(element)
  656. status200 = ET.Element(_tag("D", "status"))
  657. status200.text = _response(200)
  658. propstat200.append(status200)
  659. status404 = ET.Element(_tag("D", "status"))
  660. status404.text = _response(404)
  661. propstat404.append(status404)
  662. if len(prop404):
  663. response.append(propstat404)
  664. return response
  665. def _add_propstat_to(element, tag, status_number):
  666. """Add a PROPSTAT response structure to an element.
  667. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  668. given ``element``, for the following ``tag`` with the given
  669. ``status_number``.
  670. """
  671. propstat = ET.Element(_tag("D", "propstat"))
  672. element.append(propstat)
  673. prop = ET.Element(_tag("D", "prop"))
  674. propstat.append(prop)
  675. clark_tag = tag if "{" in tag else _tag(*tag.split(":", 1))
  676. prop_tag = ET.Element(clark_tag)
  677. prop.append(prop_tag)
  678. status = ET.Element(_tag("D", "status"))
  679. status.text = _response(status_number)
  680. propstat.append(status)
  681. def proppatch(base_prefix, path, xml_request, collection):
  682. """Read and answer PROPPATCH requests.
  683. Read rfc4918-9.2 for info.
  684. """
  685. props_to_set = props_from_request(xml_request, actions=("set",))
  686. props_to_remove = props_from_request(xml_request, actions=("remove",))
  687. multistatus = ET.Element(_tag("D", "multistatus"))
  688. response = ET.Element(_tag("D", "response"))
  689. multistatus.append(response)
  690. href = ET.Element(_tag("D", "href"))
  691. href.text = _href(base_prefix, path)
  692. response.append(href)
  693. for short_name in props_to_remove:
  694. props_to_set[short_name] = ""
  695. collection.set_meta(props_to_set)
  696. for short_name in props_to_set:
  697. _add_propstat_to(response, short_name, 200)
  698. return multistatus
  699. def report(base_prefix, path, xml_request, collection):
  700. """Read and answer REPORT requests.
  701. Read rfc3253-3.6 for info.
  702. """
  703. multistatus = ET.Element(_tag("D", "multistatus"))
  704. if xml_request is None:
  705. return multistatus
  706. root = xml_request
  707. if root.tag in (
  708. _tag("D", "principal-search-property-set"),
  709. _tag("D", "principal-property-search"),
  710. _tag("D", "expand-property")):
  711. # We don't support searching for principals or indirect retrieving of
  712. # properties, just return an empty result.
  713. # InfCloud asks for expand-property reports (even if we don't announce
  714. # support for them) and stops working if an error code is returned.
  715. collection.logger.warning("Unsupported REPORT method %r on %r "
  716. "requested", root.tag, path)
  717. return multistatus
  718. prop_element = root.find(_tag("D", "prop"))
  719. props = (
  720. [prop.tag for prop in prop_element]
  721. if prop_element is not None else [])
  722. if root.tag in (
  723. _tag("C", "calendar-multiget"),
  724. _tag("CR", "addressbook-multiget")):
  725. # Read rfc4791-7.9 for info
  726. hreferences = set()
  727. for href_element in root.findall(_tag("D", "href")):
  728. href_path = storage.sanitize_path(
  729. unquote(urlparse(href_element.text).path))
  730. if (href_path + "/").startswith(base_prefix + "/"):
  731. hreferences.add(href_path[len(base_prefix):])
  732. else:
  733. collection.logger.warning("Skipping invalid path %r in REPORT "
  734. "request on %r", href_path, path)
  735. else:
  736. hreferences = (path,)
  737. filters = (
  738. root.findall("./%s" % _tag("C", "filter")) +
  739. root.findall("./%s" % _tag("CR", "filter")))
  740. for hreference in hreferences:
  741. try:
  742. name = name_from_path(hreference, collection)
  743. except ValueError as e:
  744. collection.logger.warning("Skipping invalid path %r in REPORT "
  745. "request on %r: %s", hreference, path, e)
  746. response = _item_response(base_prefix, hreference,
  747. found_item=False)
  748. multistatus.append(response)
  749. continue
  750. if name:
  751. # Reference is an item
  752. item = collection.get(name)
  753. if not item:
  754. response = _item_response(base_prefix, hreference,
  755. found_item=False)
  756. multistatus.append(response)
  757. continue
  758. items = [item]
  759. else:
  760. # Reference is a collection
  761. items = collection.pre_filtered_list(filters)
  762. for item in items:
  763. if not item:
  764. continue
  765. if filters:
  766. try:
  767. match = (_comp_match
  768. if collection.get_meta("tag") == "VCALENDAR"
  769. else _prop_match)
  770. if not all(match(item, filter_[0]) for filter_ in filters
  771. if filter_):
  772. continue
  773. except Exception as e:
  774. raise RuntimeError("Failed to filter item %r from %r: %s" %
  775. (collection.path, item.href, e)) from e
  776. found_props = []
  777. not_found_props = []
  778. for tag in props:
  779. element = ET.Element(tag)
  780. if tag == _tag("D", "getetag"):
  781. element.text = item.etag
  782. found_props.append(element)
  783. elif tag == _tag("D", "getcontenttype"):
  784. name = item.name.lower()
  785. mimetype = (
  786. "text/vcard" if name == "vcard" else "text/calendar")
  787. element.text = "%s; component=%s" % (mimetype, name)
  788. found_props.append(element)
  789. elif tag in (
  790. _tag("C", "calendar-data"),
  791. _tag("CR", "address-data")):
  792. element.text = item.serialize()
  793. found_props.append(element)
  794. else:
  795. not_found_props.append(element)
  796. uri = "/" + posixpath.join(collection.path, item.href)
  797. multistatus.append(_item_response(
  798. base_prefix, uri, found_props=found_props,
  799. not_found_props=not_found_props, found_item=True))
  800. return multistatus
  801. def _item_response(base_prefix, href, found_props=(), not_found_props=(),
  802. found_item=True):
  803. response = ET.Element(_tag("D", "response"))
  804. href_tag = ET.Element(_tag("D", "href"))
  805. href_tag.text = _href(base_prefix, href)
  806. response.append(href_tag)
  807. if found_item:
  808. for code, props in ((200, found_props), (404, not_found_props)):
  809. if props:
  810. propstat = ET.Element(_tag("D", "propstat"))
  811. status = ET.Element(_tag("D", "status"))
  812. status.text = _response(code)
  813. prop_tag = ET.Element(_tag("D", "prop"))
  814. for prop in props:
  815. prop_tag.append(prop)
  816. propstat.append(prop_tag)
  817. propstat.append(status)
  818. response.append(propstat)
  819. else:
  820. status = ET.Element(_tag("D", "status"))
  821. status.text = _response(404)
  822. response.append(status)
  823. return response