propfind.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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", "VSUBSCRIBED")
  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. elif collection.tag == "VSUBSCRIBED":
  242. child_element = ET.Element(
  243. xmlutils.make_clark("CS:subscribed"))
  244. element.append(child_element)
  245. child_element = ET.Element(xmlutils.make_clark("D:collection"))
  246. element.append(child_element)
  247. elif tag == xmlutils.make_clark("RADICALE:displayname"):
  248. # Only for internal use by the web interface
  249. displayname = collection.get_meta("D:displayname")
  250. if displayname is not None:
  251. element.text = displayname
  252. else:
  253. is404 = True
  254. elif tag == xmlutils.make_clark("RADICALE:getcontentcount"):
  255. # Only for internal use by the web interface
  256. if isinstance(item, storage.BaseCollection) and not collection.is_principal:
  257. element.text = str(sum(1 for x in item.get_all()))
  258. else:
  259. is404 = True
  260. elif tag == xmlutils.make_clark("D:displayname"):
  261. displayname = collection.get_meta("D:displayname")
  262. if not displayname and is_leaf:
  263. displayname = collection.path
  264. if displayname is not None:
  265. element.text = displayname
  266. else:
  267. is404 = True
  268. elif tag == xmlutils.make_clark("CS:getctag"):
  269. if is_leaf:
  270. element.text = collection.etag
  271. else:
  272. is404 = True
  273. elif tag == xmlutils.make_clark("D:sync-token"):
  274. if is_leaf:
  275. element.text, _ = collection.sync()
  276. else:
  277. is404 = True
  278. elif tag == xmlutils.make_clark("CS:source"):
  279. if is_leaf:
  280. child_element = ET.Element(xmlutils.make_clark("D:href"))
  281. child_element.text = collection.get_meta('CS:source')
  282. element.append(child_element)
  283. else:
  284. is404 = True
  285. else:
  286. human_tag = xmlutils.make_human_tag(tag)
  287. tag_text = collection.get_meta(human_tag)
  288. if tag_text is not None:
  289. element.text = tag_text
  290. else:
  291. is404 = True
  292. # Not for collections
  293. elif tag == xmlutils.make_clark("D:getcontenttype"):
  294. assert not isinstance(item, storage.BaseCollection)
  295. element.text = xmlutils.get_content_type(item, encoding)
  296. elif tag == xmlutils.make_clark("D:resourcetype"):
  297. # resourcetype must be returned empty for non-collection elements
  298. pass
  299. else:
  300. is404 = True
  301. responses[404 if is404 else 200].append(element)
  302. for status_code, children in responses.items():
  303. if not children:
  304. continue
  305. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  306. response.append(propstat)
  307. prop = ET.Element(xmlutils.make_clark("D:prop"))
  308. prop.extend(children)
  309. propstat.append(prop)
  310. status = ET.Element(xmlutils.make_clark("D:status"))
  311. status.text = xmlutils.make_response(status_code)
  312. propstat.append(status)
  313. return response
  314. class ApplicationPartPropfind(ApplicationBase):
  315. def _collect_allowed_items(
  316. self, items: Iterable[types.CollectionOrItem], user: str
  317. ) -> Iterator[Tuple[types.CollectionOrItem, str]]:
  318. """Get items from request that user is allowed to access."""
  319. for item in items:
  320. if isinstance(item, storage.BaseCollection):
  321. path = pathutils.unstrip_path(item.path, True)
  322. if item.tag:
  323. permissions = rights.intersect(
  324. self._rights.authorization(user, path), "rw")
  325. target = "collection with tag %r" % item.path
  326. else:
  327. permissions = rights.intersect(
  328. self._rights.authorization(user, path), "RW")
  329. target = "collection %r" % item.path
  330. else:
  331. assert item.collection is not None
  332. path = pathutils.unstrip_path(item.collection.path, True)
  333. permissions = rights.intersect(
  334. self._rights.authorization(user, path), "rw")
  335. target = "item %r from %r" % (item.href, item.collection.path)
  336. if rights.intersect(permissions, "Ww"):
  337. permission = "w"
  338. status = "write"
  339. elif rights.intersect(permissions, "Rr"):
  340. permission = "r"
  341. status = "read"
  342. else:
  343. permission = ""
  344. status = "NO"
  345. logger.debug(
  346. "%s has %s access to %s",
  347. repr(user) if user else "anonymous user", status, target)
  348. if permission:
  349. yield item, permission
  350. def do_PROPFIND(self, environ: types.WSGIEnviron, base_prefix: str,
  351. path: str, user: str) -> types.WSGIResponse:
  352. """Manage PROPFIND request."""
  353. access = Access(self._rights, user, path)
  354. if not access.check("r"):
  355. return httputils.NOT_ALLOWED
  356. try:
  357. xml_content = self._read_xml_request_body(environ)
  358. except RuntimeError as e:
  359. logger.warning(
  360. "Bad PROPFIND request on %r: %s", path, e, exc_info=True)
  361. return httputils.BAD_REQUEST
  362. except socket.timeout:
  363. logger.debug("Client timed out", exc_info=True)
  364. return httputils.REQUEST_TIMEOUT
  365. with self._storage.acquire_lock("r", user):
  366. items_iter = iter(self._storage.discover(
  367. path, environ.get("HTTP_DEPTH", "0"),
  368. None, self._rights._user_groups))
  369. # take root item for rights checking
  370. item = next(items_iter, None)
  371. if not item:
  372. return httputils.NOT_FOUND
  373. if not access.check("r", item):
  374. return httputils.NOT_ALLOWED
  375. # put item back
  376. items_iter = itertools.chain([item], items_iter)
  377. allowed_items = self._collect_allowed_items(items_iter, user)
  378. headers = {"DAV": httputils.DAV_HEADERS,
  379. "Content-Type": "text/xml; charset=%s" % self._encoding}
  380. xml_answer = xml_propfind(base_prefix, path, xml_content,
  381. allowed_items, user, self._encoding)
  382. if xml_answer is None:
  383. return httputils.NOT_ALLOWED
  384. return client.MULTI_STATUS, headers, self._xml_response(xml_answer)