xmlutils.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. else:
  147. vobject_item = item.item
  148. if filter_length == 0:
  149. # Point #1 of rfc4791-9.7.2
  150. return filter_.get("name").lower() in vobject_item.contents
  151. else:
  152. name = filter_.get("name").lower()
  153. if filter_length == 1:
  154. if filter_[0].tag == _tag("C", "is-not-defined"):
  155. # Point #2 of rfc4791-9.7.2
  156. return name not in vobject_item.contents
  157. if filter_[0].tag == _tag("C", "time-range"):
  158. # Point #3 of rfc4791-9.7.2
  159. if not _time_range_match(vobject_item, filter_[0], name):
  160. return False
  161. filter_ = filter_[1:]
  162. elif filter_[0].tag == _tag("C", "text-match"):
  163. # Point #4 of rfc4791-9.7.2
  164. if not _text_match(vobject_item, filter_[0], name):
  165. return False
  166. filter_ = filter_[1:]
  167. return all(
  168. _param_filter_match(vobject_item, param_filter, name)
  169. for param_filter in filter_)
  170. def _time_range_match(vobject_item, filter_, child_name):
  171. """Check whether the ``item`` matches the time-range ``filter_``.
  172. See rfc4791-9.9.
  173. """
  174. start = filter_.get("start")
  175. end = filter_.get("end")
  176. if not start and not end:
  177. return False
  178. if start:
  179. start = datetime.strptime(start, "%Y%m%dT%H%M%SZ")
  180. else:
  181. start = datetime.min
  182. if end:
  183. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  184. else:
  185. end = datetime.max
  186. start = start.replace(tzinfo=timezone.utc)
  187. end = end.replace(tzinfo=timezone.utc)
  188. child = getattr(vobject_item, child_name.lower())
  189. # Comments give the lines in the tables of the specification
  190. if child_name == "VEVENT":
  191. # TODO: check if there's a timezone
  192. dtstart = child.dtstart.value
  193. if child.rruleset:
  194. dtstarts = child.getrruleset(addRDate=True)
  195. else:
  196. dtstarts = (dtstart,)
  197. dtend = getattr(child, "dtend", None)
  198. if dtend is not None:
  199. dtend = dtend.value
  200. original_duration = (dtend - dtstart).total_seconds()
  201. dtend = _date_to_datetime(dtend)
  202. duration = getattr(child, "duration", None)
  203. if duration is not None:
  204. original_duration = duration = duration.value
  205. for dtstart in dtstarts:
  206. dtstart_is_datetime = isinstance(dtstart, datetime)
  207. dtstart = _date_to_datetime(dtstart)
  208. if dtstart > end:
  209. break
  210. if dtend is not None:
  211. # Line 1
  212. dtend = dtstart + timedelta(seconds=original_duration)
  213. if start < dtend and end > dtstart:
  214. return True
  215. elif duration is not None:
  216. if original_duration is None:
  217. original_duration = duration.seconds
  218. if duration.seconds > 0:
  219. # Line 2
  220. if start < dtstart + duration and end > dtstart:
  221. return True
  222. elif start <= dtstart and end > dtstart:
  223. # Line 3
  224. return True
  225. elif dtstart_is_datetime:
  226. # Line 4
  227. if start <= dtstart and end > dtstart:
  228. return True
  229. elif start < dtstart + timedelta(days=1) and end > dtstart:
  230. # Line 5
  231. return True
  232. elif child_name == "VTODO":
  233. dtstart = getattr(child, "dtstart", None)
  234. duration = getattr(child, "duration", None)
  235. due = getattr(child, "due", None)
  236. completed = getattr(child, "completed", None)
  237. created = getattr(child, "created", None)
  238. if dtstart is not None:
  239. dtstart = _date_to_datetime(dtstart.value)
  240. if duration is not None:
  241. duration = duration.value
  242. if due is not None:
  243. due = _date_to_datetime(due.value)
  244. if dtstart is not None:
  245. original_duration = (due - dtstart).total_seconds()
  246. if completed is not None:
  247. completed = _date_to_datetime(completed.value)
  248. if created is not None:
  249. created = _date_to_datetime(created.value)
  250. original_duration = (completed - created).total_seconds()
  251. elif created is not None:
  252. created = _date_to_datetime(created.value)
  253. if child.rruleset:
  254. reference_dates = child.getrruleset(addRDate=True)
  255. else:
  256. if dtstart is not None:
  257. reference_dates = (dtstart,)
  258. elif due is not None:
  259. reference_dates = (due,)
  260. elif completed is not None:
  261. reference_dates = (completed,)
  262. elif created is not None:
  263. reference_dates = (created,)
  264. else:
  265. # Line 8
  266. return True
  267. for reference_date in reference_dates:
  268. reference_date = _date_to_datetime(reference_date)
  269. if reference_date > end:
  270. break
  271. if dtstart is not None and duration is not None:
  272. # Line 1
  273. if start <= reference_date + duration and (
  274. end > reference_date or
  275. end >= reference_date + duration):
  276. return True
  277. elif dtstart is not None and due is not None:
  278. # Line 2
  279. due = reference_date + timedelta(seconds=original_duration)
  280. if (start < due or start <= reference_date) and (
  281. end > reference_date or end >= due):
  282. return True
  283. elif dtstart is not None:
  284. if start <= reference_date and end > reference_date:
  285. return True
  286. elif due is not None:
  287. # Line 4
  288. if start < reference_date and end >= reference_date:
  289. return True
  290. elif completed is not None and created is not None:
  291. # Line 5
  292. completed = reference_date + timedelta(
  293. seconds=original_duration)
  294. if (start <= reference_date or start <= completed) and (
  295. end >= reference_date or end >= completed):
  296. return True
  297. elif completed is not None:
  298. # Line 6
  299. if start <= reference_date and end >= reference_date:
  300. return True
  301. elif created is not None:
  302. # Line 7
  303. if end > reference_date:
  304. return True
  305. elif child_name == "VJOURNAL":
  306. dtstart = getattr(child, "dtstart", None)
  307. if dtstart is not None:
  308. dtstart = dtstart.value
  309. if child.rruleset:
  310. dtstarts = child.getrruleset(addRDate=True)
  311. else:
  312. dtstarts = (dtstart,)
  313. for dtstart in dtstarts:
  314. dtstart_is_datetime = isinstance(dtstart, datetime)
  315. dtstart = _date_to_datetime(dtstart)
  316. if dtstart > end:
  317. break
  318. if dtstart_is_datetime:
  319. # Line 1
  320. if start <= dtstart and end > dtstart:
  321. return True
  322. elif start < dtstart + timedelta(days=1) and end > dtstart:
  323. # Line 2
  324. return True
  325. return False
  326. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  327. """Check whether the ``item`` matches the text-match ``filter_``.
  328. See rfc4791-9.7.5.
  329. """
  330. # TODO: collations are not supported, but the default ones needed
  331. # for DAV servers are actually pretty useless. Texts are lowered to
  332. # be case-insensitive, almost as the "i;ascii-casemap" value.
  333. match = next(filter_.itertext()).lower()
  334. children = getattr(vobject_item, "%s_list" % child_name, [])
  335. if attrib_name:
  336. condition = any(
  337. match in attrib.lower() for child in children
  338. for attrib in child.params.get(attrib_name, []))
  339. else:
  340. condition = any(match in child.value.lower() for child in children)
  341. if filter_.get("negate-condition") == "yes":
  342. return not condition
  343. else:
  344. return condition
  345. def _param_filter_match(vobject_item, filter_, parent_name):
  346. """Check whether the ``item`` matches the param-filter ``filter_``.
  347. See rfc4791-9.7.3.
  348. """
  349. name = filter_.get("name")
  350. children = getattr(vobject_item, "%s_list" % parent_name, [])
  351. condition = any(name in child.params for child in children)
  352. if len(filter_):
  353. if filter_[0].tag == _tag("C", "text-match"):
  354. return condition and _text_match(
  355. vobject_item, filter_[0], parent_name, name)
  356. elif filter_[0].tag == _tag("C", "is-not-defined"):
  357. return not condition
  358. else:
  359. return condition
  360. def name_from_path(path, collection):
  361. """Return Radicale item name from ``path``."""
  362. path = path.strip("/") + "/"
  363. start = collection.path + "/"
  364. if not path.startswith(start):
  365. raise ValueError("'%s' doesn't start with '%s'" % (path, start))
  366. name = path[len(start):][:-1]
  367. if name and not storage.is_safe_path_component(name):
  368. raise ValueError("'%s' is not a component in collection '%s'" %
  369. (path, collection.path))
  370. return name
  371. def props_from_request(root, actions=("set", "remove")):
  372. """Return a list of properties as a dictionary."""
  373. result = OrderedDict()
  374. if root:
  375. if not hasattr(root, "tag"):
  376. root = ET.fromstring(root.encode("utf8"))
  377. else:
  378. return result
  379. for action in actions:
  380. action_element = root.find(_tag("D", action))
  381. if action_element is not None:
  382. break
  383. else:
  384. action_element = root
  385. prop_element = action_element.find(_tag("D", "prop"))
  386. if prop_element is not None:
  387. for prop in prop_element:
  388. if prop.tag == _tag("D", "resourcetype"):
  389. for resource_type in prop:
  390. if resource_type.tag == _tag("C", "calendar"):
  391. result["tag"] = "VCALENDAR"
  392. break
  393. elif resource_type.tag == _tag("CR", "addressbook"):
  394. result["tag"] = "VADDRESSBOOK"
  395. break
  396. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  397. result[_tag_from_clark(prop.tag)] = ",".join(
  398. supported_comp.attrib["name"]
  399. for supported_comp in prop
  400. if supported_comp.tag == _tag("C", "comp"))
  401. else:
  402. result[_tag_from_clark(prop.tag)] = prop.text
  403. return result
  404. def delete(base_prefix, path, collection, href=None):
  405. """Read and answer DELETE requests.
  406. Read rfc4918-9.6 for info.
  407. """
  408. collection.delete(href)
  409. multistatus = ET.Element(_tag("D", "multistatus"))
  410. response = ET.Element(_tag("D", "response"))
  411. multistatus.append(response)
  412. href = ET.Element(_tag("D", "href"))
  413. href.text = _href(base_prefix, path)
  414. response.append(href)
  415. status = ET.Element(_tag("D", "status"))
  416. status.text = _response(200)
  417. response.append(status)
  418. return _pretty_xml(multistatus)
  419. def propfind(base_prefix, path, xml_request, read_collections,
  420. write_collections, user):
  421. """Read and answer PROPFIND requests.
  422. Read rfc4918-9.1 for info.
  423. The collections parameter is a list of collections that are to be included
  424. in the output.
  425. """
  426. # Reading request
  427. root = ET.fromstring(xml_request.encode("utf8")) if xml_request else None
  428. # A client may choose not to submit a request body. An empty PROPFIND
  429. # request body MUST be treated as if it were an 'allprop' request.
  430. top_tag = root[0] if root is not None else 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, _pretty_xml(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. privilege = ET.Element(_tag("D", "privilege"))
  568. if write:
  569. privilege.append(ET.Element(_tag("D", "all")))
  570. privilege.append(ET.Element(_tag("D", "write")))
  571. privilege.append(ET.Element(_tag("D", "write-properties")))
  572. privilege.append(ET.Element(_tag("D", "write-content")))
  573. privilege.append(ET.Element(_tag("D", "read")))
  574. element.append(privilege)
  575. elif tag == _tag("D", "supported-report-set"):
  576. for report_name in (
  577. "principal-property-search", "sync-collection",
  578. "expand-property", "principal-search-property-set"):
  579. supported = ET.Element(_tag("D", "supported-report"))
  580. report_tag = ET.Element(_tag("D", "report"))
  581. supported_report_tag = ET.Element(_tag("D", report_name))
  582. report_tag.append(supported_report_tag)
  583. supported.append(report_tag)
  584. element.append(supported)
  585. elif is_collection:
  586. if tag == _tag("D", "getcontenttype"):
  587. item_tag = item.get_meta("tag")
  588. if item_tag:
  589. element.text = MIMETYPES[item_tag]
  590. else:
  591. is404 = True
  592. elif tag == _tag("D", "resourcetype"):
  593. if item.is_principal:
  594. tag = ET.Element(_tag("D", "principal"))
  595. element.append(tag)
  596. item_tag = item.get_meta("tag")
  597. if is_leaf or item_tag:
  598. # 2nd case happens when the collection is not stored yet,
  599. # but the resource type is guessed
  600. if item.get_meta("tag") == "VADDRESSBOOK":
  601. tag = ET.Element(_tag("CR", "addressbook"))
  602. element.append(tag)
  603. elif item.get_meta("tag") == "VCALENDAR":
  604. tag = ET.Element(_tag("C", "calendar"))
  605. element.append(tag)
  606. tag = ET.Element(_tag("D", "collection"))
  607. element.append(tag)
  608. elif tag == _tag("D", "owner"):
  609. if is_leaf and item.owner:
  610. element.text = "/%s/" % item.owner
  611. else:
  612. is404 = True
  613. elif tag == _tag("D", "displayname"):
  614. if is_leaf:
  615. element.text = item.get_meta("D:displayname") or item.path
  616. else:
  617. is404 = True
  618. elif tag == _tag("CS", "getctag"):
  619. if is_leaf:
  620. element.text = item.etag
  621. else:
  622. is404 = True
  623. else:
  624. human_tag = _tag_from_clark(tag)
  625. meta = item.get_meta(human_tag)
  626. if meta:
  627. element.text = meta
  628. else:
  629. is404 = True
  630. # Not for collections
  631. elif tag == _tag("D", "getcontenttype"):
  632. name = item.name.lower()
  633. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  634. element.text = "%s; component=%s" % (mimetype, name)
  635. elif tag == _tag("D", "resourcetype"):
  636. # resourcetype must be returned empty for non-collection elements
  637. pass
  638. elif tag == _tag("D", "getcontentlength"):
  639. encoding = collection.configuration.get("encoding", "request")
  640. element.text = str(len(item.serialize().encode(encoding)))
  641. else:
  642. is404 = True
  643. if is404:
  644. prop404.append(element)
  645. else:
  646. prop200.append(element)
  647. status200 = ET.Element(_tag("D", "status"))
  648. status200.text = _response(200)
  649. propstat200.append(status200)
  650. status404 = ET.Element(_tag("D", "status"))
  651. status404.text = _response(404)
  652. propstat404.append(status404)
  653. if len(prop404):
  654. response.append(propstat404)
  655. return response
  656. def _add_propstat_to(element, tag, status_number):
  657. """Add a PROPSTAT response structure to an element.
  658. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  659. given ``element``, for the following ``tag`` with the given
  660. ``status_number``.
  661. """
  662. propstat = ET.Element(_tag("D", "propstat"))
  663. element.append(propstat)
  664. prop = ET.Element(_tag("D", "prop"))
  665. propstat.append(prop)
  666. clark_tag = tag if "{" in tag else _tag(*tag.split(":", 1))
  667. prop_tag = ET.Element(clark_tag)
  668. prop.append(prop_tag)
  669. status = ET.Element(_tag("D", "status"))
  670. status.text = _response(status_number)
  671. propstat.append(status)
  672. def proppatch(base_prefix, path, xml_request, collection):
  673. """Read and answer PROPPATCH requests.
  674. Read rfc4918-9.2 for info.
  675. """
  676. root = ET.fromstring(xml_request.encode("utf8"))
  677. props_to_set = props_from_request(root, actions=("set",))
  678. props_to_remove = props_from_request(root, actions=("remove",))
  679. multistatus = ET.Element(_tag("D", "multistatus"))
  680. response = ET.Element(_tag("D", "response"))
  681. multistatus.append(response)
  682. href = ET.Element(_tag("D", "href"))
  683. href.text = _href(base_prefix, path)
  684. response.append(href)
  685. for short_name in props_to_remove:
  686. props_to_set[short_name] = ""
  687. collection.set_meta(props_to_set)
  688. for short_name in props_to_set:
  689. _add_propstat_to(response, short_name, 200)
  690. return _pretty_xml(multistatus)
  691. def report(base_prefix, path, xml_request, collection):
  692. """Read and answer REPORT requests.
  693. Read rfc3253-3.6 for info.
  694. """
  695. root = ET.fromstring(xml_request.encode("utf8"))
  696. prop_element = root.find(_tag("D", "prop"))
  697. props = (
  698. [prop.tag for prop in prop_element]
  699. if prop_element is not None else [])
  700. if collection:
  701. if root.tag in (
  702. _tag("C", "calendar-multiget"),
  703. _tag("CR", "addressbook-multiget")):
  704. # Read rfc4791-7.9 for info
  705. hreferences = set()
  706. for href_element in root.findall(_tag("D", "href")):
  707. href_path = storage.sanitize_path(
  708. unquote(urlparse(href_element.text).path))
  709. if (href_path + "/").startswith(base_prefix + "/"):
  710. hreferences.add(href_path[len(base_prefix):])
  711. else:
  712. collection.logger.info(
  713. "Skipping invalid path: %s", href_path)
  714. else:
  715. hreferences = (path,)
  716. filters = (
  717. root.findall(".//%s" % _tag("C", "filter")) +
  718. root.findall(".//%s" % _tag("CR", "filter")))
  719. else:
  720. hreferences = filters = ()
  721. multistatus = ET.Element(_tag("D", "multistatus"))
  722. for hreference in hreferences:
  723. try:
  724. name = name_from_path(hreference, collection)
  725. except ValueError:
  726. collection.logger.info("Skipping invalid path: %s", hreference)
  727. response = _item_response(base_prefix, hreference,
  728. found_item=False)
  729. multistatus.append(response)
  730. continue
  731. if name:
  732. # Reference is an item
  733. item = collection.get(name)
  734. if not item:
  735. response = _item_response(base_prefix, hreference,
  736. found_item=False)
  737. multistatus.append(response)
  738. continue
  739. items = [item]
  740. else:
  741. # Reference is a collection
  742. items = collection.pre_filtered_list(filters)
  743. for item in items:
  744. if not item:
  745. continue
  746. if filters:
  747. match = (
  748. _comp_match if collection.get_meta("tag") == "VCALENDAR"
  749. else _prop_match)
  750. if not all(match(item, filter_[0]) for filter_ in filters
  751. if filter_):
  752. continue
  753. found_props = []
  754. not_found_props = []
  755. for tag in props:
  756. element = ET.Element(tag)
  757. if tag == _tag("D", "getetag"):
  758. element.text = item.etag
  759. found_props.append(element)
  760. elif tag == _tag("D", "getcontenttype"):
  761. name = item.name.lower()
  762. mimetype = (
  763. "text/vcard" if name == "vcard" else "text/calendar")
  764. element.text = "%s; component=%s" % (mimetype, name)
  765. found_props.append(element)
  766. elif tag in (
  767. _tag("C", "calendar-data"),
  768. _tag("CR", "address-data")):
  769. element.text = item.serialize()
  770. found_props.append(element)
  771. else:
  772. not_found_props.append(element)
  773. uri = "/" + posixpath.join(collection.path, item.href)
  774. multistatus.append(_item_response(
  775. base_prefix, uri, found_props=found_props,
  776. not_found_props=not_found_props, found_item=True))
  777. return _pretty_xml(multistatus)
  778. def _item_response(base_prefix, href, found_props=(), not_found_props=(),
  779. found_item=True):
  780. response = ET.Element(_tag("D", "response"))
  781. href_tag = ET.Element(_tag("D", "href"))
  782. href_tag.text = _href(base_prefix, href)
  783. response.append(href_tag)
  784. if found_item:
  785. for code, props in ((200, found_props), (404, not_found_props)):
  786. if props:
  787. propstat = ET.Element(_tag("D", "propstat"))
  788. status = ET.Element(_tag("D", "status"))
  789. status.text = _response(code)
  790. prop_tag = ET.Element(_tag("D", "prop"))
  791. for prop in props:
  792. prop_tag.append(prop)
  793. propstat.append(prop_tag)
  794. propstat.append(status)
  795. response.append(propstat)
  796. else:
  797. status = ET.Element(_tag("D", "status"))
  798. status.text = _response(404)
  799. response.append(status)
  800. return response