propfind.py 19 KB

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