propfind.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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_resource_size: 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_resource_size=max_resource_size))
  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_resource_size: 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. if not allprop:
  99. # RFC4791#5.2.5: SHOULD NOT be returned by a PROPFIND DAV:allprop request
  100. props.append(xmlutils.make_clark("C:max-resource-size"))
  101. if is_collection and collection.is_principal:
  102. props.append(xmlutils.make_clark("C:calendar-user-address-set"))
  103. props.append(xmlutils.make_clark("D:principal-URL"))
  104. props.append(xmlutils.make_clark("CR:addressbook-home-set"))
  105. props.append(xmlutils.make_clark("C:calendar-home-set"))
  106. if not is_collection or is_leaf:
  107. props.append(xmlutils.make_clark("D:getetag"))
  108. props.append(xmlutils.make_clark("D:getlastmodified"))
  109. props.append(xmlutils.make_clark("D:getcontenttype"))
  110. props.append(xmlutils.make_clark("D:getcontentlength"))
  111. if is_collection:
  112. if is_leaf:
  113. props.append(xmlutils.make_clark("D:displayname"))
  114. props.append(xmlutils.make_clark("D:sync-token"))
  115. if collection.tag == "VCALENDAR":
  116. props.append(xmlutils.make_clark("CS:getctag"))
  117. props.append(
  118. xmlutils.make_clark("C:supported-calendar-component-set"))
  119. meta = collection.get_meta()
  120. for tag in meta:
  121. if tag == "tag":
  122. continue
  123. clark_tag = xmlutils.make_clark(tag)
  124. if clark_tag not in props:
  125. props.append(clark_tag)
  126. responses: Dict[int, List[ET.Element]] = collections.defaultdict(list)
  127. if propname:
  128. for tag in props:
  129. responses[200].append(ET.Element(tag))
  130. props = []
  131. for tag in props:
  132. element = ET.Element(tag)
  133. is404 = False
  134. if tag == xmlutils.make_clark("D:getetag"):
  135. if not is_collection or is_leaf:
  136. element.text = item.etag
  137. else:
  138. is404 = True
  139. elif tag == xmlutils.make_clark("D:getlastmodified"):
  140. if not is_collection or is_leaf:
  141. element.text = item.last_modified
  142. else:
  143. is404 = True
  144. elif tag == xmlutils.make_clark("D:principal-collection-set"):
  145. child_element = ET.Element(xmlutils.make_clark("D:href"))
  146. child_element.text = xmlutils.make_href(base_prefix, "/")
  147. element.append(child_element)
  148. elif (tag in (xmlutils.make_clark("C:calendar-user-address-set"),
  149. xmlutils.make_clark("D:principal-URL"),
  150. xmlutils.make_clark("CR:addressbook-home-set"),
  151. xmlutils.make_clark("C:calendar-home-set")) and
  152. is_collection and collection.is_principal):
  153. child_element = ET.Element(xmlutils.make_clark("D:href"))
  154. child_element.text = xmlutils.make_href(base_prefix, path)
  155. element.append(child_element)
  156. elif tag == xmlutils.make_clark("C:supported-calendar-component-set"):
  157. human_tag = xmlutils.make_human_tag(tag)
  158. if is_collection and is_leaf:
  159. components_text = collection.get_meta(human_tag)
  160. if components_text:
  161. components = components_text.split(",")
  162. else:
  163. components = ["VTODO", "VEVENT", "VJOURNAL"]
  164. for component in components:
  165. comp = ET.Element(xmlutils.make_clark("C:comp"))
  166. comp.set("name", component)
  167. element.append(comp)
  168. else:
  169. is404 = True
  170. elif tag == xmlutils.make_clark("D:current-user-principal"):
  171. if user:
  172. child_element = ET.Element(xmlutils.make_clark("D:href"))
  173. child_element.text = xmlutils.make_href(
  174. base_prefix, "/%s/" % user)
  175. element.append(child_element)
  176. else:
  177. element.append(ET.Element(
  178. xmlutils.make_clark("D:unauthenticated")))
  179. elif tag == xmlutils.make_clark("D:current-user-privilege-set"):
  180. privileges = ["D:read"]
  181. if write:
  182. privileges.append("D:all")
  183. privileges.append("D:write")
  184. privileges.append("D:write-properties")
  185. privileges.append("D:write-content")
  186. for human_tag in privileges:
  187. privilege = ET.Element(xmlutils.make_clark("D:privilege"))
  188. privilege.append(ET.Element(
  189. xmlutils.make_clark(human_tag)))
  190. element.append(privilege)
  191. elif tag == xmlutils.make_clark("D:supported-report-set"):
  192. # These 3 reports are not implemented
  193. reports = ["D:expand-property",
  194. "D:principal-search-property-set",
  195. "D:principal-property-search"]
  196. if is_collection and is_leaf:
  197. reports.append("D:sync-collection")
  198. if collection.tag == "VADDRESSBOOK":
  199. reports.append("CR:addressbook-multiget")
  200. reports.append("CR:addressbook-query")
  201. elif collection.tag == "VCALENDAR":
  202. reports.append("C:calendar-multiget")
  203. reports.append("C:calendar-query")
  204. for human_tag in reports:
  205. supported_report = ET.Element(
  206. xmlutils.make_clark("D:supported-report"))
  207. report_element = ET.Element(xmlutils.make_clark("D:report"))
  208. report_element.append(
  209. ET.Element(xmlutils.make_clark(human_tag)))
  210. supported_report.append(report_element)
  211. element.append(supported_report)
  212. elif tag == xmlutils.make_clark("D:getcontentlength"):
  213. if not is_collection or is_leaf:
  214. element.text = str(len(item.serialize().encode(encoding)))
  215. else:
  216. is404 = True
  217. elif tag == xmlutils.make_clark("D:owner"):
  218. # return empty elment, if no owner available (rfc3744-5.1)
  219. if collection.owner:
  220. child_element = ET.Element(xmlutils.make_clark("D:href"))
  221. child_element.text = xmlutils.make_href(
  222. base_prefix, "/%s/" % collection.owner)
  223. element.append(child_element)
  224. elif tag == xmlutils.make_clark("C:max-resource-size"):
  225. # RFC4791#5.2.5
  226. element.text = str(max_resource_size)
  227. elif is_collection:
  228. if tag == xmlutils.make_clark("D:getcontenttype"):
  229. if is_leaf:
  230. element.text = xmlutils.MIMETYPES[
  231. collection.tag]
  232. else:
  233. is404 = True
  234. elif tag == xmlutils.make_clark("D:resourcetype"):
  235. if collection.is_principal:
  236. child_element = ET.Element(
  237. xmlutils.make_clark("D:principal"))
  238. element.append(child_element)
  239. if is_leaf:
  240. if collection.tag == "VADDRESSBOOK":
  241. child_element = ET.Element(
  242. xmlutils.make_clark("CR:addressbook"))
  243. element.append(child_element)
  244. elif collection.tag == "VCALENDAR":
  245. child_element = ET.Element(
  246. xmlutils.make_clark("C:calendar"))
  247. element.append(child_element)
  248. elif collection.tag == "VSUBSCRIBED":
  249. child_element = ET.Element(
  250. xmlutils.make_clark("CS:subscribed"))
  251. element.append(child_element)
  252. child_element = ET.Element(xmlutils.make_clark("D:collection"))
  253. element.append(child_element)
  254. elif tag == xmlutils.make_clark("RADICALE:displayname"):
  255. # Only for internal use by the web interface
  256. displayname = collection.get_meta("D:displayname")
  257. if displayname is not None:
  258. element.text = displayname
  259. else:
  260. is404 = True
  261. elif tag == xmlutils.make_clark("RADICALE:getcontentcount"):
  262. # Only for internal use by the web interface
  263. if isinstance(item, storage.BaseCollection) and not collection.is_principal:
  264. element.text = str(sum(1 for x in item.get_all()))
  265. else:
  266. is404 = True
  267. elif tag == xmlutils.make_clark("D:displayname"):
  268. displayname = collection.get_meta("D:displayname")
  269. if not displayname and is_leaf:
  270. displayname = collection.path
  271. if displayname is not None:
  272. element.text = displayname
  273. else:
  274. is404 = True
  275. elif tag == xmlutils.make_clark("CS:getctag"):
  276. if is_leaf:
  277. element.text = collection.etag
  278. else:
  279. is404 = True
  280. elif tag == xmlutils.make_clark("D:sync-token"):
  281. if is_leaf:
  282. element.text, _ = collection.sync()
  283. else:
  284. is404 = True
  285. elif tag == xmlutils.make_clark("CS:source"):
  286. if is_leaf:
  287. child_element = ET.Element(xmlutils.make_clark("D:href"))
  288. child_element.text = collection.get_meta('CS:source')
  289. element.append(child_element)
  290. else:
  291. is404 = True
  292. else:
  293. human_tag = xmlutils.make_human_tag(tag)
  294. tag_text = collection.get_meta(human_tag)
  295. if tag_text is not None:
  296. element.text = tag_text
  297. else:
  298. is404 = True
  299. # Not for collections
  300. elif tag == xmlutils.make_clark("D:getcontenttype"):
  301. assert not isinstance(item, storage.BaseCollection)
  302. element.text = xmlutils.get_content_type(item, encoding)
  303. elif tag == xmlutils.make_clark("D:resourcetype"):
  304. # resourcetype must be returned empty for non-collection elements
  305. pass
  306. else:
  307. is404 = True
  308. responses[404 if is404 else 200].append(element)
  309. for status_code, children in responses.items():
  310. if not children:
  311. continue
  312. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  313. response.append(propstat)
  314. prop = ET.Element(xmlutils.make_clark("D:prop"))
  315. prop.extend(children)
  316. propstat.append(prop)
  317. status = ET.Element(xmlutils.make_clark("D:status"))
  318. status.text = xmlutils.make_response(status_code)
  319. propstat.append(status)
  320. return response
  321. class ApplicationPartPropfind(ApplicationBase):
  322. def _collect_allowed_items(
  323. self, items: Iterable[types.CollectionOrItem], user: str
  324. ) -> Iterator[Tuple[types.CollectionOrItem, str]]:
  325. """Get items from request that user is allowed to access."""
  326. for item in items:
  327. if isinstance(item, storage.BaseCollection):
  328. path = pathutils.unstrip_path(item.path, True)
  329. if item.tag:
  330. permissions = rights.intersect(
  331. self._rights.authorization(user, path), "rw")
  332. target = "collection with tag %r" % item.path
  333. else:
  334. permissions = rights.intersect(
  335. self._rights.authorization(user, path), "RW")
  336. target = "collection %r" % item.path
  337. else:
  338. assert item.collection is not None
  339. path = pathutils.unstrip_path(item.collection.path, True)
  340. permissions = rights.intersect(
  341. self._rights.authorization(user, path), "rw")
  342. target = "item %r from %r" % (item.href, item.collection.path)
  343. if rights.intersect(permissions, "Ww"):
  344. permission = "w"
  345. status = "write"
  346. elif rights.intersect(permissions, "Rr"):
  347. permission = "r"
  348. status = "read"
  349. else:
  350. permission = ""
  351. status = "NO"
  352. logger.debug(
  353. "%s has %s access to %s",
  354. repr(user) if user else "anonymous user", status, target)
  355. if permission:
  356. yield item, permission
  357. def do_PROPFIND(self, environ: types.WSGIEnviron, base_prefix: str,
  358. path: str, user: str, remote_host: str, remote_useragent: str) -> types.WSGIResponse:
  359. """Manage PROPFIND request."""
  360. access = Access(self._rights, user, path)
  361. if not access.check("r"):
  362. return httputils.NOT_ALLOWED
  363. try:
  364. xml_content = self._read_xml_request_body(environ)
  365. except RuntimeError as e:
  366. logger.warning(
  367. "Bad PROPFIND request on %r: %s", path, e, exc_info=True)
  368. return httputils.BAD_REQUEST
  369. except socket.timeout:
  370. logger.debug("Client timed out", exc_info=True)
  371. return httputils.REQUEST_TIMEOUT
  372. with self._storage.acquire_lock("r", user):
  373. items_iter = iter(self._storage.discover(
  374. path, environ.get("HTTP_DEPTH", "0"),
  375. None, self._rights._user_groups))
  376. # take root item for rights checking
  377. item = next(items_iter, None)
  378. if not item:
  379. return httputils.NOT_FOUND
  380. if not access.check("r", item):
  381. return httputils.NOT_ALLOWED
  382. # put item back
  383. items_iter = itertools.chain([item], items_iter)
  384. allowed_items = self._collect_allowed_items(items_iter, user)
  385. headers = {"DAV": httputils.DAV_HEADERS,
  386. "Content-Type": "text/xml; charset=%s" % self._encoding}
  387. xml_answer = xml_propfind(base_prefix, path, xml_content,
  388. allowed_items, user, self._encoding, max_resource_size=self._max_resource_size)
  389. if xml_answer is None:
  390. return httputils.NOT_ALLOWED
  391. return client.MULTI_STATUS, headers, self._xml_response(xml_answer), xmlutils.pretty_xml(xml_content)