propfind.py 17 KB

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