propfind.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # This file is part of Radicale Server - Calendar 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 itertools
  20. import socket
  21. from http import client
  22. from xml.etree import ElementTree as ET
  23. from radicale import httputils, pathutils, rights, storage, xmlutils
  24. from radicale.log import logger
  25. import posixpath # isort:skip
  26. def xml_propfind(base_prefix, path, xml_request, allowed_items, user):
  27. """Read and answer PROPFIND requests.
  28. Read rfc4918-9.1 for info.
  29. The collections parameter is a list of collections that are to be included
  30. in the output.
  31. """
  32. # A client may choose not to submit a request body. An empty PROPFIND
  33. # request body MUST be treated as if it were an 'allprop' request.
  34. top_tag = (xml_request[0] if xml_request is not None else
  35. ET.Element(xmlutils.make_tag("D", "allprop")))
  36. props = ()
  37. allprop = False
  38. propname = False
  39. if top_tag.tag == xmlutils.make_tag("D", "allprop"):
  40. allprop = True
  41. elif top_tag.tag == xmlutils.make_tag("D", "propname"):
  42. propname = True
  43. elif top_tag.tag == xmlutils.make_tag("D", "prop"):
  44. props = [prop.tag for prop in top_tag]
  45. if xmlutils.make_tag("D", "current-user-principal") in props and not user:
  46. # Ask for authentication
  47. # Returning the DAV:unauthenticated pseudo-principal as specified in
  48. # RFC 5397 doesn't seem to work with DAVdroid.
  49. return client.FORBIDDEN, None
  50. # Writing answer
  51. multistatus = ET.Element(xmlutils.make_tag("D", "multistatus"))
  52. for item, permission in allowed_items:
  53. write = permission == "w"
  54. response = xml_propfind_response(
  55. base_prefix, path, item, props, user, write=write,
  56. allprop=allprop, propname=propname)
  57. if response:
  58. multistatus.append(response)
  59. return client.MULTI_STATUS, multistatus
  60. def xml_propfind_response(base_prefix, path, item, props, user, write=False,
  61. propname=False, allprop=False):
  62. """Build and return a PROPFIND response."""
  63. if propname and allprop or (props and (propname or allprop)):
  64. raise ValueError("Only use one of props, propname and allprops")
  65. is_collection = isinstance(item, storage.BaseCollection)
  66. if is_collection:
  67. is_leaf = item.get_meta("tag") in ("VADDRESSBOOK", "VCALENDAR")
  68. collection = item
  69. else:
  70. collection = item.collection
  71. response = ET.Element(xmlutils.make_tag("D", "response"))
  72. href = ET.Element(xmlutils.make_tag("D", "href"))
  73. if is_collection:
  74. # Some clients expect collections to end with /
  75. uri = pathutils.unstrip_path(item.path, True)
  76. else:
  77. uri = pathutils.unstrip_path(
  78. posixpath.join(collection.path, item.href))
  79. href.text = xmlutils.make_href(base_prefix, uri)
  80. response.append(href)
  81. propstat404 = ET.Element(xmlutils.make_tag("D", "propstat"))
  82. propstat200 = ET.Element(xmlutils.make_tag("D", "propstat"))
  83. response.append(propstat200)
  84. prop200 = ET.Element(xmlutils.make_tag("D", "prop"))
  85. propstat200.append(prop200)
  86. prop404 = ET.Element(xmlutils.make_tag("D", "prop"))
  87. propstat404.append(prop404)
  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_tag("D", "principal-collection-set"))
  92. props.append(xmlutils.make_tag("D", "current-user-principal"))
  93. props.append(xmlutils.make_tag("D", "current-user-privilege-set"))
  94. props.append(xmlutils.make_tag("D", "supported-report-set"))
  95. props.append(xmlutils.make_tag("D", "resourcetype"))
  96. props.append(xmlutils.make_tag("D", "owner"))
  97. if is_collection and collection.is_principal:
  98. props.append(xmlutils.make_tag("C", "calendar-user-address-set"))
  99. props.append(xmlutils.make_tag("D", "principal-URL"))
  100. props.append(xmlutils.make_tag("CR", "addressbook-home-set"))
  101. props.append(xmlutils.make_tag("C", "calendar-home-set"))
  102. if not is_collection or is_leaf:
  103. props.append(xmlutils.make_tag("D", "getetag"))
  104. props.append(xmlutils.make_tag("D", "getlastmodified"))
  105. props.append(xmlutils.make_tag("D", "getcontenttype"))
  106. props.append(xmlutils.make_tag("D", "getcontentlength"))
  107. if is_collection:
  108. if is_leaf:
  109. props.append(xmlutils.make_tag("D", "displayname"))
  110. props.append(xmlutils.make_tag("D", "sync-token"))
  111. if collection.get_meta("tag") == "VCALENDAR":
  112. props.append(xmlutils.make_tag("CS", "getctag"))
  113. props.append(
  114. xmlutils.make_tag("C", "supported-calendar-component-set"))
  115. meta = item.get_meta()
  116. for tag in meta:
  117. if tag == "tag":
  118. continue
  119. clark_tag = xmlutils.tag_from_human(tag)
  120. if clark_tag not in props:
  121. props.append(clark_tag)
  122. if propname:
  123. for tag in props:
  124. prop200.append(ET.Element(tag))
  125. props = ()
  126. for tag in props:
  127. element = ET.Element(tag)
  128. is404 = False
  129. if tag == xmlutils.make_tag("D", "getetag"):
  130. if not is_collection or is_leaf:
  131. element.text = item.etag
  132. else:
  133. is404 = True
  134. elif tag == xmlutils.make_tag("D", "getlastmodified"):
  135. if not is_collection or is_leaf:
  136. element.text = item.last_modified
  137. else:
  138. is404 = True
  139. elif tag == xmlutils.make_tag("D", "principal-collection-set"):
  140. tag = ET.Element(xmlutils.make_tag("D", "href"))
  141. tag.text = xmlutils.make_href(base_prefix, "/")
  142. element.append(tag)
  143. elif (tag in (xmlutils.make_tag("C", "calendar-user-address-set"),
  144. xmlutils.make_tag("D", "principal-URL"),
  145. xmlutils.make_tag("CR", "addressbook-home-set"),
  146. xmlutils.make_tag("C", "calendar-home-set")) and
  147. collection.is_principal and is_collection):
  148. tag = ET.Element(xmlutils.make_tag("D", "href"))
  149. tag.text = xmlutils.make_href(base_prefix, path)
  150. element.append(tag)
  151. elif tag == xmlutils.make_tag("C", "supported-calendar-component-set"):
  152. human_tag = xmlutils.tag_from_clark(tag)
  153. if is_collection and is_leaf:
  154. meta = item.get_meta(human_tag)
  155. if meta:
  156. components = meta.split(",")
  157. else:
  158. components = ("VTODO", "VEVENT", "VJOURNAL")
  159. for component in components:
  160. comp = ET.Element(xmlutils.make_tag("C", "comp"))
  161. comp.set("name", component)
  162. element.append(comp)
  163. else:
  164. is404 = True
  165. elif tag == xmlutils.make_tag("D", "current-user-principal"):
  166. if user:
  167. tag = ET.Element(xmlutils.make_tag("D", "href"))
  168. tag.text = xmlutils.make_href(base_prefix, "/%s/" % user)
  169. element.append(tag)
  170. else:
  171. element.append(ET.Element(
  172. xmlutils.make_tag("D", "unauthenticated")))
  173. elif tag == xmlutils.make_tag("D", "current-user-privilege-set"):
  174. privileges = [("D", "read")]
  175. if write:
  176. privileges.append(("D", "all"))
  177. privileges.append(("D", "write"))
  178. privileges.append(("D", "write-properties"))
  179. privileges.append(("D", "write-content"))
  180. for ns, privilege_name in privileges:
  181. privilege = ET.Element(xmlutils.make_tag("D", "privilege"))
  182. privilege.append(ET.Element(
  183. xmlutils.make_tag(ns, privilege_name)))
  184. element.append(privilege)
  185. elif tag == xmlutils.make_tag("D", "supported-report-set"):
  186. # These 3 reports are not implemented
  187. reports = [
  188. ("D", "expand-property"),
  189. ("D", "principal-search-property-set"),
  190. ("D", "principal-property-search")]
  191. if is_collection and is_leaf:
  192. reports.append(("D", "sync-collection"))
  193. if item.get_meta("tag") == "VADDRESSBOOK":
  194. reports.append(("CR", "addressbook-multiget"))
  195. reports.append(("CR", "addressbook-query"))
  196. elif item.get_meta("tag") == "VCALENDAR":
  197. reports.append(("C", "calendar-multiget"))
  198. reports.append(("C", "calendar-query"))
  199. for ns, report_name in reports:
  200. supported = ET.Element(
  201. xmlutils.make_tag("D", "supported-report"))
  202. report_tag = ET.Element(xmlutils.make_tag("D", "report"))
  203. supported_report_tag = ET.Element(
  204. xmlutils.make_tag(ns, report_name))
  205. report_tag.append(supported_report_tag)
  206. supported.append(report_tag)
  207. element.append(supported)
  208. elif tag == xmlutils.make_tag("D", "getcontentlength"):
  209. if not is_collection or is_leaf:
  210. encoding = collection.configuration.get("encoding", "request")
  211. element.text = str(len(item.serialize().encode(encoding)))
  212. else:
  213. is404 = True
  214. elif tag == xmlutils.make_tag("D", "owner"):
  215. # return empty elment, if no owner available (rfc3744-5.1)
  216. if collection.owner:
  217. tag = ET.Element(xmlutils.make_tag("D", "href"))
  218. tag.text = xmlutils.make_href(
  219. base_prefix, "/%s/" % collection.owner)
  220. element.append(tag)
  221. elif is_collection:
  222. if tag == xmlutils.make_tag("D", "getcontenttype"):
  223. if is_leaf:
  224. element.text = xmlutils.MIMETYPES[item.get_meta("tag")]
  225. else:
  226. is404 = True
  227. elif tag == xmlutils.make_tag("D", "resourcetype"):
  228. if item.is_principal:
  229. tag = ET.Element(xmlutils.make_tag("D", "principal"))
  230. element.append(tag)
  231. if is_leaf:
  232. if item.get_meta("tag") == "VADDRESSBOOK":
  233. tag = ET.Element(
  234. xmlutils.make_tag("CR", "addressbook"))
  235. element.append(tag)
  236. elif item.get_meta("tag") == "VCALENDAR":
  237. tag = ET.Element(xmlutils.make_tag("C", "calendar"))
  238. element.append(tag)
  239. tag = ET.Element(xmlutils.make_tag("D", "collection"))
  240. element.append(tag)
  241. elif tag == xmlutils.make_tag("RADICALE", "displayname"):
  242. # Only for internal use by the web interface
  243. displayname = item.get_meta("D:displayname")
  244. if displayname is not None:
  245. element.text = displayname
  246. else:
  247. is404 = True
  248. elif tag == xmlutils.make_tag("D", "displayname"):
  249. displayname = item.get_meta("D:displayname")
  250. if not displayname and is_leaf:
  251. displayname = item.path
  252. if displayname is not None:
  253. element.text = displayname
  254. else:
  255. is404 = True
  256. elif tag == xmlutils.make_tag("CS", "getctag"):
  257. if is_leaf:
  258. element.text = item.etag
  259. else:
  260. is404 = True
  261. elif tag == xmlutils.make_tag("D", "sync-token"):
  262. if is_leaf:
  263. element.text, _ = item.sync()
  264. else:
  265. is404 = True
  266. else:
  267. human_tag = xmlutils.tag_from_clark(tag)
  268. meta = item.get_meta(human_tag)
  269. if meta is not None:
  270. element.text = meta
  271. else:
  272. is404 = True
  273. # Not for collections
  274. elif tag == xmlutils.make_tag("D", "getcontenttype"):
  275. element.text = xmlutils.get_content_type(item)
  276. elif tag == xmlutils.make_tag("D", "resourcetype"):
  277. # resourcetype must be returned empty for non-collection elements
  278. pass
  279. else:
  280. is404 = True
  281. if is404:
  282. prop404.append(element)
  283. else:
  284. prop200.append(element)
  285. status200 = ET.Element(xmlutils.make_tag("D", "status"))
  286. status200.text = xmlutils.make_response(200)
  287. propstat200.append(status200)
  288. status404 = ET.Element(xmlutils.make_tag("D", "status"))
  289. status404.text = xmlutils.make_response(404)
  290. propstat404.append(status404)
  291. if len(prop404):
  292. response.append(propstat404)
  293. return response
  294. class ApplicationPropfindMixin:
  295. def _collect_allowed_items(self, items, user):
  296. """Get items from request that user is allowed to access."""
  297. for item in items:
  298. if isinstance(item, storage.BaseCollection):
  299. path = pathutils.unstrip_path(item.path, True)
  300. if item.get_meta("tag"):
  301. permissions = self.Rights.authorized(user, path, "rw")
  302. target = "collection with tag %r" % item.path
  303. else:
  304. permissions = self.Rights.authorized(user, path, "RW")
  305. target = "collection %r" % item.path
  306. else:
  307. path = pathutils.unstrip_path(item.collection.path, True)
  308. permissions = self.Rights.authorized(user, path, "rw")
  309. target = "item %r from %r" % (item.href, item.collection.path)
  310. if rights.intersect_permissions(permissions, "Ww"):
  311. permission = "w"
  312. status = "write"
  313. elif rights.intersect_permissions(permissions, "Rr"):
  314. permission = "r"
  315. status = "read"
  316. else:
  317. permission = ""
  318. status = "NO"
  319. logger.debug(
  320. "%s has %s access to %s",
  321. repr(user) if user else "anonymous user", status, target)
  322. if permission:
  323. yield item, permission
  324. def do_PROPFIND(self, environ, base_prefix, path, user):
  325. """Manage PROPFIND request."""
  326. if not self.access(user, path, "r"):
  327. return httputils.NOT_ALLOWED
  328. try:
  329. xml_content = self.read_xml_content(environ)
  330. except RuntimeError as e:
  331. logger.warning(
  332. "Bad PROPFIND request on %r: %s", path, e, exc_info=True)
  333. return httputils.BAD_REQUEST
  334. except socket.timeout as e:
  335. logger.debug("client timed out", exc_info=True)
  336. return httputils.REQUEST_TIMEOUT
  337. with self.Collection.acquire_lock("r", user):
  338. items = self.Collection.discover(
  339. path, environ.get("HTTP_DEPTH", "0"))
  340. # take root item for rights checking
  341. item = next(items, None)
  342. if not item:
  343. return httputils.NOT_FOUND
  344. if not self.access(user, path, "r", item):
  345. return httputils.NOT_ALLOWED
  346. # put item back
  347. items = itertools.chain([item], items)
  348. allowed_items = self._collect_allowed_items(items, user)
  349. headers = {"DAV": httputils.DAV_HEADERS,
  350. "Content-Type": "text/xml; charset=%s" % self.encoding}
  351. status, xml_answer = xml_propfind(
  352. base_prefix, path, xml_content, allowed_items, user)
  353. if status == client.FORBIDDEN:
  354. return httputils.NOT_ALLOWED
  355. return status, headers, self.write_xml_content(xml_answer)