xmlutils.py 34 KB

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