propfind.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import collections
  20. import itertools
  21. import posixpath
  22. import socket
  23. import xml.etree.ElementTree as ET
  24. from http import client
  25. from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
  26. from radicale import httputils, pathutils, rights, storage, types, xmlutils
  27. from radicale.app.base import Access, ApplicationBase
  28. from radicale.log import logger
  29. def xml_propfind(base_prefix: str, path: str,
  30. xml_request: Optional[ET.Element],
  31. allowed_items: Iterable[Tuple[types.CollectionOrItem, str]],
  32. user: str, encoding: str) -> Optional[ET.Element]:
  33. """Read and answer PROPFIND requests.
  34. Read rfc4918-9.1 for info.
  35. The collections parameter is a list of collections that are to be included
  36. in the output.
  37. """
  38. # A client may choose not to submit a request body. An empty PROPFIND
  39. # request body MUST be treated as if it were an 'allprop' request.
  40. top_element = (xml_request[0] if xml_request is not None else
  41. ET.Element(xmlutils.make_clark("D:allprop")))
  42. props: List[str] = []
  43. allprop = False
  44. propname = False
  45. if top_element.tag == xmlutils.make_clark("D:allprop"):
  46. allprop = True
  47. elif top_element.tag == xmlutils.make_clark("D:propname"):
  48. propname = True
  49. elif top_element.tag == xmlutils.make_clark("D:prop"):
  50. props.extend(prop.tag for prop in top_element)
  51. if xmlutils.make_clark("D:current-user-principal") in props and not user:
  52. # Ask for authentication
  53. # Returning the DAV:unauthenticated pseudo-principal as specified in
  54. # RFC 5397 doesn't seem to work with DAVx5.
  55. return None
  56. # Writing answer
  57. multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
  58. for item, permission in allowed_items:
  59. write = permission == "w"
  60. multistatus.append(xml_propfind_response(
  61. base_prefix, path, item, props, user, encoding, write=write,
  62. allprop=allprop, propname=propname))
  63. return multistatus
  64. def xml_propfind_response(
  65. base_prefix: str, path: str, item: types.CollectionOrItem,
  66. props: Sequence[str], user: str, encoding: str, write: bool = False,
  67. propname: bool = False, allprop: bool = False) -> ET.Element:
  68. """Build and return a PROPFIND response."""
  69. if propname and allprop or (props and (propname or allprop)):
  70. raise ValueError("Only use one of props, propname and allprops")
  71. if isinstance(item, storage.BaseCollection):
  72. is_collection = True
  73. is_leaf = item.tag in ("VADDRESSBOOK", "VCALENDAR")
  74. collection = item
  75. # Some clients expect collections to end with `/`
  76. uri = pathutils.unstrip_path(item.path, True)
  77. else:
  78. is_collection = is_leaf = False
  79. assert item.collection is not None
  80. assert item.href
  81. collection = item.collection
  82. uri = pathutils.unstrip_path(posixpath.join(
  83. collection.path, item.href))
  84. response = ET.Element(xmlutils.make_clark("D:response"))
  85. href = ET.Element(xmlutils.make_clark("D:href"))
  86. href.text = xmlutils.make_href(base_prefix, uri)
  87. response.append(href)
  88. if propname or allprop:
  89. props = []
  90. # Should list all properties that can be retrieved by the code below
  91. props.append(xmlutils.make_clark("D:principal-collection-set"))
  92. props.append(xmlutils.make_clark("D:current-user-principal"))
  93. props.append(xmlutils.make_clark("D:current-user-privilege-set"))
  94. props.append(xmlutils.make_clark("D:supported-report-set"))
  95. props.append(xmlutils.make_clark("D:resourcetype"))
  96. props.append(xmlutils.make_clark("D:owner"))
  97. if is_collection and collection.is_principal:
  98. props.append(xmlutils.make_clark("C:calendar-user-address-set"))
  99. props.append(xmlutils.make_clark("D:principal-URL"))
  100. props.append(xmlutils.make_clark("CR:addressbook-home-set"))
  101. props.append(xmlutils.make_clark("C:calendar-home-set"))
  102. if not is_collection or is_leaf:
  103. props.append(xmlutils.make_clark("D:getetag"))
  104. props.append(xmlutils.make_clark("D:getlastmodified"))
  105. props.append(xmlutils.make_clark("D:getcontenttype"))
  106. props.append(xmlutils.make_clark("D:getcontentlength"))
  107. if is_collection:
  108. if is_leaf:
  109. props.append(xmlutils.make_clark("D:displayname"))
  110. props.append(xmlutils.make_clark("D:sync-token"))
  111. if collection.tag == "VCALENDAR":
  112. props.append(xmlutils.make_clark("CS:getctag"))
  113. props.append(
  114. xmlutils.make_clark("C:supported-calendar-component-set"))
  115. meta = collection.get_meta()
  116. for tag in meta:
  117. if tag == "tag":
  118. continue
  119. clark_tag = xmlutils.make_clark(tag)
  120. if clark_tag not in props:
  121. props.append(clark_tag)
  122. responses: Dict[int, List[ET.Element]] = collections.defaultdict(list)
  123. if propname:
  124. for tag in props:
  125. responses[200].append(ET.Element(tag))
  126. props = []
  127. for tag in props:
  128. element = ET.Element(tag)
  129. is404 = False
  130. if tag == xmlutils.make_clark("D:getetag"):
  131. if not is_collection or is_leaf:
  132. element.text = item.etag
  133. else:
  134. is404 = True
  135. elif tag == xmlutils.make_clark("D:getlastmodified"):
  136. if not is_collection or is_leaf:
  137. element.text = item.last_modified
  138. else:
  139. is404 = True
  140. elif tag == xmlutils.make_clark("D:principal-collection-set"):
  141. child_element = ET.Element(xmlutils.make_clark("D:href"))
  142. child_element.text = xmlutils.make_href(base_prefix, "/")
  143. element.append(child_element)
  144. elif (tag in (xmlutils.make_clark("C:calendar-user-address-set"),
  145. xmlutils.make_clark("D:principal-URL"),
  146. xmlutils.make_clark("CR:addressbook-home-set"),
  147. xmlutils.make_clark("C:calendar-home-set")) and
  148. is_collection and collection.is_principal):
  149. child_element = ET.Element(xmlutils.make_clark("D:href"))
  150. child_element.text = xmlutils.make_href(base_prefix, path)
  151. element.append(child_element)
  152. elif tag == xmlutils.make_clark("C:supported-calendar-component-set"):
  153. human_tag = xmlutils.make_human_tag(tag)
  154. if is_collection and is_leaf:
  155. components_text = collection.get_meta(human_tag)
  156. if components_text:
  157. components = components_text.split(",")
  158. else:
  159. components = ["VTODO", "VEVENT", "VJOURNAL"]
  160. for component in components:
  161. comp = ET.Element(xmlutils.make_clark("C:comp"))
  162. comp.set("name", component)
  163. element.append(comp)
  164. else:
  165. is404 = True
  166. elif tag == xmlutils.make_clark("D:current-user-principal"):
  167. if user:
  168. child_element = ET.Element(xmlutils.make_clark("D:href"))
  169. child_element.text = xmlutils.make_href(
  170. base_prefix, "/%s/" % user)
  171. element.append(child_element)
  172. else:
  173. element.append(ET.Element(
  174. xmlutils.make_clark("D:unauthenticated")))
  175. elif tag == xmlutils.make_clark("D:current-user-privilege-set"):
  176. privileges = ["D:read"]
  177. if write:
  178. privileges.append("D:all")
  179. privileges.append("D:write")
  180. privileges.append("D:write-properties")
  181. privileges.append("D:write-content")
  182. for human_tag in privileges:
  183. privilege = ET.Element(xmlutils.make_clark("D:privilege"))
  184. privilege.append(ET.Element(
  185. xmlutils.make_clark(human_tag)))
  186. element.append(privilege)
  187. elif tag == xmlutils.make_clark("D:supported-report-set"):
  188. # These 3 reports are not implemented
  189. reports = ["D:expand-property",
  190. "D:principal-search-property-set",
  191. "D:principal-property-search"]
  192. if is_collection and is_leaf:
  193. reports.append("D:sync-collection")
  194. if collection.tag == "VADDRESSBOOK":
  195. reports.append("CR:addressbook-multiget")
  196. reports.append("CR:addressbook-query")
  197. elif collection.tag == "VCALENDAR":
  198. reports.append("C:calendar-multiget")
  199. reports.append("C:calendar-query")
  200. for human_tag in reports:
  201. supported_report = ET.Element(
  202. xmlutils.make_clark("D:supported-report"))
  203. report_element = ET.Element(xmlutils.make_clark("D:report"))
  204. report_element.append(
  205. ET.Element(xmlutils.make_clark(human_tag)))
  206. supported_report.append(report_element)
  207. element.append(supported_report)
  208. elif tag == xmlutils.make_clark("D:getcontentlength"):
  209. if not is_collection or is_leaf:
  210. element.text = str(len(item.serialize().encode(encoding)))
  211. else:
  212. is404 = True
  213. elif tag == xmlutils.make_clark("D:owner"):
  214. # return empty elment, if no owner available (rfc3744-5.1)
  215. if collection.owner:
  216. child_element = ET.Element(xmlutils.make_clark("D:href"))
  217. child_element.text = xmlutils.make_href(
  218. base_prefix, "/%s/" % collection.owner)
  219. element.append(child_element)
  220. elif is_collection:
  221. if tag == xmlutils.make_clark("D:getcontenttype"):
  222. if is_leaf:
  223. element.text = xmlutils.MIMETYPES[
  224. collection.tag]
  225. else:
  226. is404 = True
  227. elif tag == xmlutils.make_clark("D:resourcetype"):
  228. if collection.is_principal:
  229. child_element = ET.Element(
  230. xmlutils.make_clark("D:principal"))
  231. element.append(child_element)
  232. if is_leaf:
  233. if collection.tag == "VADDRESSBOOK":
  234. child_element = ET.Element(
  235. xmlutils.make_clark("CR:addressbook"))
  236. element.append(child_element)
  237. elif collection.tag == "VCALENDAR":
  238. child_element = ET.Element(
  239. xmlutils.make_clark("C:calendar"))
  240. element.append(child_element)
  241. child_element = ET.Element(xmlutils.make_clark("D:collection"))
  242. element.append(child_element)
  243. elif tag == xmlutils.make_clark("RADICALE:displayname"):
  244. # Only for internal use by the web interface
  245. displayname = collection.get_meta("D:displayname")
  246. if displayname is not None:
  247. element.text = displayname
  248. else:
  249. is404 = True
  250. elif tag == xmlutils.make_clark("D:displayname"):
  251. displayname = collection.get_meta("D:displayname")
  252. if not displayname and is_leaf:
  253. displayname = collection.path
  254. if displayname is not None:
  255. element.text = displayname
  256. else:
  257. is404 = True
  258. elif tag == xmlutils.make_clark("CS:getctag"):
  259. if is_leaf:
  260. element.text = collection.etag
  261. else:
  262. is404 = True
  263. elif tag == xmlutils.make_clark("D:sync-token"):
  264. if is_leaf:
  265. element.text, _ = collection.sync()
  266. else:
  267. is404 = True
  268. else:
  269. human_tag = xmlutils.make_human_tag(tag)
  270. tag_text = collection.get_meta(human_tag)
  271. if tag_text is not None:
  272. element.text = tag_text
  273. else:
  274. is404 = True
  275. # Not for collections
  276. elif tag == xmlutils.make_clark("D:getcontenttype"):
  277. assert not isinstance(item, storage.BaseCollection)
  278. element.text = xmlutils.get_content_type(item, encoding)
  279. elif tag == xmlutils.make_clark("D:resourcetype"):
  280. # resourcetype must be returned empty for non-collection elements
  281. pass
  282. else:
  283. is404 = True
  284. responses[404 if is404 else 200].append(element)
  285. for status_code, childs in responses.items():
  286. if not childs:
  287. continue
  288. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  289. response.append(propstat)
  290. prop = ET.Element(xmlutils.make_clark("D:prop"))
  291. prop.extend(childs)
  292. propstat.append(prop)
  293. status = ET.Element(xmlutils.make_clark("D:status"))
  294. status.text = xmlutils.make_response(status_code)
  295. propstat.append(status)
  296. return response
  297. class ApplicationPartPropfind(ApplicationBase):
  298. def _collect_allowed_items(
  299. self, items: Iterable[types.CollectionOrItem], user: str
  300. ) -> Iterator[Tuple[types.CollectionOrItem, str]]:
  301. """Get items from request that user is allowed to access."""
  302. for item in items:
  303. if isinstance(item, storage.BaseCollection):
  304. path = pathutils.unstrip_path(item.path, True)
  305. if item.tag:
  306. permissions = rights.intersect(
  307. self._rights.authorization(user, path), "rw")
  308. target = "collection with tag %r" % item.path
  309. else:
  310. permissions = rights.intersect(
  311. self._rights.authorization(user, path), "RW")
  312. target = "collection %r" % item.path
  313. else:
  314. assert item.collection is not None
  315. path = pathutils.unstrip_path(item.collection.path, True)
  316. permissions = rights.intersect(
  317. self._rights.authorization(user, path), "rw")
  318. target = "item %r from %r" % (item.href, item.collection.path)
  319. if rights.intersect(permissions, "Ww"):
  320. permission = "w"
  321. status = "write"
  322. elif rights.intersect(permissions, "Rr"):
  323. permission = "r"
  324. status = "read"
  325. else:
  326. permission = ""
  327. status = "NO"
  328. logger.debug(
  329. "%s has %s access to %s",
  330. repr(user) if user else "anonymous user", status, target)
  331. if permission:
  332. yield item, permission
  333. def do_PROPFIND(self, environ: types.WSGIEnviron, base_prefix: str,
  334. path: str, user: str) -> types.WSGIResponse:
  335. """Manage PROPFIND request."""
  336. access = Access(self._rights, user, path)
  337. if not access.check("r"):
  338. return httputils.NOT_ALLOWED
  339. try:
  340. xml_content = self._read_xml_request_body(environ)
  341. except RuntimeError as e:
  342. logger.warning(
  343. "Bad PROPFIND request on %r: %s", path, e, exc_info=True)
  344. return httputils.BAD_REQUEST
  345. except socket.timeout:
  346. logger.debug("Client timed out", exc_info=True)
  347. return httputils.REQUEST_TIMEOUT
  348. with self._storage.acquire_lock("r", user):
  349. items_iter = iter(self._storage.discover(
  350. path, environ.get("HTTP_DEPTH", "0")))
  351. # take root item for rights checking
  352. item = next(items_iter, None)
  353. if not item:
  354. return httputils.NOT_FOUND
  355. if not access.check("r", item):
  356. return httputils.NOT_ALLOWED
  357. # put item back
  358. items_iter = itertools.chain([item], items_iter)
  359. allowed_items = self._collect_allowed_items(items_iter, user)
  360. headers = {"DAV": httputils.DAV_HEADERS,
  361. "Content-Type": "text/xml; charset=%s" % self._encoding}
  362. xml_answer = xml_propfind(base_prefix, path, xml_content,
  363. allowed_items, user, self._encoding)
  364. if xml_answer is None:
  365. return httputils.NOT_ALLOWED
  366. return client.MULTI_STATUS, headers, self._xml_response(xml_answer)