xmlutils.py 30 KB

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