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 posixpath
  21. import socket
  22. from http import client
  23. from xml.etree import ElementTree as ET
  24. from radicale import httputils, pathutils, rights, storage, xmlutils
  25. from radicale.log import logger
  26. def xml_propfind(base_prefix, path, xml_request, allowed_items, user,
  27. encoding):
  28. """Read and answer PROPFIND requests.
  29. Read rfc4918-9.1 for info.
  30. The collections parameter is a list of collections that are to be included
  31. in the output.
  32. """
  33. # A client may choose not to submit a request body. An empty PROPFIND
  34. # request body MUST be treated as if it were an 'allprop' request.
  35. top_tag = (xml_request[0] if xml_request is not None else
  36. ET.Element(xmlutils.make_tag("D", "allprop")))
  37. props = ()
  38. allprop = False
  39. propname = False
  40. if top_tag.tag == xmlutils.make_tag("D", "allprop"):
  41. allprop = True
  42. elif top_tag.tag == xmlutils.make_tag("D", "propname"):
  43. propname = True
  44. elif top_tag.tag == xmlutils.make_tag("D", "prop"):
  45. props = [prop.tag for prop in top_tag]
  46. if xmlutils.make_tag("D", "current-user-principal") in props and not user:
  47. # Ask for authentication
  48. # Returning the DAV:unauthenticated pseudo-principal as specified in
  49. # RFC 5397 doesn't seem to work with DAVdroid.
  50. return client.FORBIDDEN, None
  51. # Writing answer
  52. multistatus = ET.Element(xmlutils.make_tag("D", "multistatus"))
  53. for item, permission in allowed_items:
  54. write = permission == "w"
  55. response = xml_propfind_response(
  56. base_prefix, path, item, props, user, encoding, write=write,
  57. allprop=allprop, propname=propname)
  58. if response:
  59. multistatus.append(response)
  60. return client.MULTI_STATUS, multistatus
  61. def xml_propfind_response(base_prefix, path, item, props, user, encoding,
  62. write=False, propname=False, allprop=False):
  63. """Build and return a PROPFIND response."""
  64. if propname and allprop or (props and (propname or allprop)):
  65. raise ValueError("Only use one of props, propname and allprops")
  66. is_collection = isinstance(item, storage.BaseCollection)
  67. if is_collection:
  68. is_leaf = item.get_meta("tag") in ("VADDRESSBOOK", "VCALENDAR")
  69. collection = item
  70. else:
  71. collection = item.collection
  72. response = ET.Element(xmlutils.make_tag("D", "response"))
  73. href = ET.Element(xmlutils.make_tag("D", "href"))
  74. if is_collection:
  75. # Some clients expect collections to end with /
  76. uri = pathutils.unstrip_path(item.path, True)
  77. else:
  78. uri = pathutils.unstrip_path(
  79. posixpath.join(collection.path, item.href))
  80. href.text = xmlutils.make_href(base_prefix, uri)
  81. response.append(href)
  82. propstat404 = ET.Element(xmlutils.make_tag("D", "propstat"))
  83. propstat200 = ET.Element(xmlutils.make_tag("D", "propstat"))
  84. response.append(propstat200)
  85. prop200 = ET.Element(xmlutils.make_tag("D", "prop"))
  86. propstat200.append(prop200)
  87. prop404 = ET.Element(xmlutils.make_tag("D", "prop"))
  88. propstat404.append(prop404)
  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_tag("D", "principal-collection-set"))
  93. props.append(xmlutils.make_tag("D", "current-user-principal"))
  94. props.append(xmlutils.make_tag("D", "current-user-privilege-set"))
  95. props.append(xmlutils.make_tag("D", "supported-report-set"))
  96. props.append(xmlutils.make_tag("D", "resourcetype"))
  97. props.append(xmlutils.make_tag("D", "owner"))
  98. if is_collection and collection.is_principal:
  99. props.append(xmlutils.make_tag("C", "calendar-user-address-set"))
  100. props.append(xmlutils.make_tag("D", "principal-URL"))
  101. props.append(xmlutils.make_tag("CR", "addressbook-home-set"))
  102. props.append(xmlutils.make_tag("C", "calendar-home-set"))
  103. if not is_collection or is_leaf:
  104. props.append(xmlutils.make_tag("D", "getetag"))
  105. props.append(xmlutils.make_tag("D", "getlastmodified"))
  106. props.append(xmlutils.make_tag("D", "getcontenttype"))
  107. props.append(xmlutils.make_tag("D", "getcontentlength"))
  108. if is_collection:
  109. if is_leaf:
  110. props.append(xmlutils.make_tag("D", "displayname"))
  111. props.append(xmlutils.make_tag("D", "sync-token"))
  112. if collection.get_meta("tag") == "VCALENDAR":
  113. props.append(xmlutils.make_tag("CS", "getctag"))
  114. props.append(
  115. xmlutils.make_tag("C", "supported-calendar-component-set"))
  116. meta = item.get_meta()
  117. for tag in meta:
  118. if tag == "tag":
  119. continue
  120. clark_tag = xmlutils.tag_from_human(tag)
  121. if clark_tag not in props:
  122. props.append(clark_tag)
  123. if propname:
  124. for tag in props:
  125. prop200.append(ET.Element(tag))
  126. props = ()
  127. for tag in props:
  128. element = ET.Element(tag)
  129. is404 = False
  130. if tag == xmlutils.make_tag("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_tag("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_tag("D", "principal-collection-set"):
  141. tag = ET.Element(xmlutils.make_tag("D", "href"))
  142. tag.text = xmlutils.make_href(base_prefix, "/")
  143. element.append(tag)
  144. elif (tag in (xmlutils.make_tag("C", "calendar-user-address-set"),
  145. xmlutils.make_tag("D", "principal-URL"),
  146. xmlutils.make_tag("CR", "addressbook-home-set"),
  147. xmlutils.make_tag("C", "calendar-home-set")) and
  148. collection.is_principal and is_collection):
  149. tag = ET.Element(xmlutils.make_tag("D", "href"))
  150. tag.text = xmlutils.make_href(base_prefix, path)
  151. element.append(tag)
  152. elif tag == xmlutils.make_tag("C", "supported-calendar-component-set"):
  153. human_tag = xmlutils.tag_from_clark(tag)
  154. if is_collection and is_leaf:
  155. meta = item.get_meta(human_tag)
  156. if meta:
  157. components = meta.split(",")
  158. else:
  159. components = ("VTODO", "VEVENT", "VJOURNAL")
  160. for component in components:
  161. comp = ET.Element(xmlutils.make_tag("C", "comp"))
  162. comp.set("name", component)
  163. element.append(comp)
  164. else:
  165. is404 = True
  166. elif tag == xmlutils.make_tag("D", "current-user-principal"):
  167. if user:
  168. tag = ET.Element(xmlutils.make_tag("D", "href"))
  169. tag.text = xmlutils.make_href(base_prefix, "/%s/" % user)
  170. element.append(tag)
  171. else:
  172. element.append(ET.Element(
  173. xmlutils.make_tag("D", "unauthenticated")))
  174. elif tag == xmlutils.make_tag("D", "current-user-privilege-set"):
  175. privileges = [("D", "read")]
  176. if write:
  177. privileges.append(("D", "all"))
  178. privileges.append(("D", "write"))
  179. privileges.append(("D", "write-properties"))
  180. privileges.append(("D", "write-content"))
  181. for ns, privilege_name in privileges:
  182. privilege = ET.Element(xmlutils.make_tag("D", "privilege"))
  183. privilege.append(ET.Element(
  184. xmlutils.make_tag(ns, privilege_name)))
  185. element.append(privilege)
  186. elif tag == xmlutils.make_tag("D", "supported-report-set"):
  187. # These 3 reports are not implemented
  188. reports = [
  189. ("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 item.get_meta("tag") == "VADDRESSBOOK":
  195. reports.append(("CR", "addressbook-multiget"))
  196. reports.append(("CR", "addressbook-query"))
  197. elif item.get_meta("tag") == "VCALENDAR":
  198. reports.append(("C", "calendar-multiget"))
  199. reports.append(("C", "calendar-query"))
  200. for ns, report_name in reports:
  201. supported = ET.Element(
  202. xmlutils.make_tag("D", "supported-report"))
  203. report_tag = ET.Element(xmlutils.make_tag("D", "report"))
  204. supported_report_tag = ET.Element(
  205. xmlutils.make_tag(ns, report_name))
  206. report_tag.append(supported_report_tag)
  207. supported.append(report_tag)
  208. element.append(supported)
  209. elif tag == xmlutils.make_tag("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_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, encoding)
  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:
  335. logger.debug("client timed out", exc_info=True)
  336. return httputils.REQUEST_TIMEOUT
  337. with self._storage.acquire_lock("r", user):
  338. items = self._storage.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. self._encoding)
  354. if status == client.FORBIDDEN:
  355. return httputils.NOT_ALLOWED
  356. return status, headers, self.write_xml_content(xml_answer)