xmlutils.py 32 KB

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