1
0

xmlutils.py 31 KB

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