1
0

propfind.py 18 KB

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