xmlutils.py 31 KB

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