put.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. # Copyright © 2024-2024 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 itertools
  21. import posixpath
  22. import socket
  23. import sys
  24. from http import client
  25. from types import TracebackType
  26. from typing import Iterator, List, Mapping, MutableMapping, Optional, Tuple
  27. import vobject
  28. import radicale.item as radicale_item
  29. from radicale import httputils, pathutils, rights, storage, types, xmlutils
  30. from radicale.app.base import Access, ApplicationBase
  31. from radicale.hook import HookNotificationItem, HookNotificationItemTypes
  32. from radicale.log import logger
  33. MIMETYPE_TAGS: Mapping[str, str] = {value: key for key, value in
  34. xmlutils.MIMETYPES.items()}
  35. def prepare(vobject_items: List[vobject.base.Component], path: str,
  36. content_type: str, permission: bool, parent_permission: bool,
  37. tag: Optional[str] = None,
  38. write_whole_collection: Optional[bool] = None) -> Tuple[
  39. Iterator[radicale_item.Item], # items
  40. Optional[str], # tag
  41. Optional[bool], # write_whole_collection
  42. Optional[MutableMapping[str, str]], # props
  43. Optional[Tuple[type, BaseException, Optional[TracebackType]]]]:
  44. if (write_whole_collection or permission and not parent_permission):
  45. write_whole_collection = True
  46. tag = radicale_item.predict_tag_of_whole_collection(
  47. vobject_items, MIMETYPE_TAGS.get(content_type))
  48. if not tag:
  49. raise ValueError("Can't determine collection tag")
  50. collection_path = pathutils.strip_path(path)
  51. elif (write_whole_collection is not None and not write_whole_collection or
  52. not permission and parent_permission):
  53. write_whole_collection = False
  54. if tag is None:
  55. tag = radicale_item.predict_tag_of_parent_collection(vobject_items)
  56. collection_path = posixpath.dirname(pathutils.strip_path(path))
  57. props: Optional[MutableMapping[str, str]] = None
  58. stored_exc_info = None
  59. items = []
  60. try:
  61. if tag and write_whole_collection is not None:
  62. radicale_item.check_and_sanitize_items(
  63. vobject_items, is_collection=write_whole_collection, tag=tag)
  64. if write_whole_collection and tag == "VCALENDAR":
  65. vobject_components: List[vobject.base.Component] = []
  66. vobject_item, = vobject_items
  67. for content in ("vevent", "vtodo", "vjournal"):
  68. vobject_components.extend(
  69. getattr(vobject_item, "%s_list" % content, []))
  70. vobject_components_by_uid = itertools.groupby(
  71. sorted(vobject_components, key=radicale_item.get_uid),
  72. radicale_item.get_uid)
  73. for _, components in vobject_components_by_uid:
  74. vobject_collection = vobject.iCalendar()
  75. for component in components:
  76. vobject_collection.add(component)
  77. item = radicale_item.Item(collection_path=collection_path,
  78. vobject_item=vobject_collection)
  79. item.prepare()
  80. items.append(item)
  81. elif write_whole_collection and tag == "VADDRESSBOOK":
  82. for vobject_item in vobject_items:
  83. item = radicale_item.Item(collection_path=collection_path,
  84. vobject_item=vobject_item)
  85. item.prepare()
  86. items.append(item)
  87. elif not write_whole_collection:
  88. vobject_item, = vobject_items
  89. item = radicale_item.Item(collection_path=collection_path,
  90. vobject_item=vobject_item)
  91. item.prepare()
  92. items.append(item)
  93. if write_whole_collection:
  94. props = {}
  95. if tag:
  96. props["tag"] = tag
  97. if tag == "VCALENDAR" and vobject_items:
  98. if hasattr(vobject_items[0], "x_wr_calname"):
  99. calname = vobject_items[0].x_wr_calname.value
  100. if calname:
  101. props["D:displayname"] = calname
  102. if hasattr(vobject_items[0], "x_wr_caldesc"):
  103. caldesc = vobject_items[0].x_wr_caldesc.value
  104. if caldesc:
  105. props["C:calendar-description"] = caldesc
  106. props = radicale_item.check_and_sanitize_props(props)
  107. except Exception:
  108. exc_info_or_none_tuple = sys.exc_info()
  109. assert exc_info_or_none_tuple[0] is not None
  110. stored_exc_info = exc_info_or_none_tuple
  111. # Use iterator for items and delete references to free memory early
  112. def items_iter() -> Iterator[radicale_item.Item]:
  113. while items:
  114. yield items.pop(0)
  115. return items_iter(), tag, write_whole_collection, props, stored_exc_info
  116. class ApplicationPartPut(ApplicationBase):
  117. def do_PUT(self, environ: types.WSGIEnviron, base_prefix: str,
  118. path: str, user: str) -> types.WSGIResponse:
  119. """Manage PUT request."""
  120. access = Access(self._rights, user, path)
  121. if not access.check("w"):
  122. return httputils.NOT_ALLOWED
  123. try:
  124. content = httputils.read_request_body(self.configuration, environ)
  125. except RuntimeError as e:
  126. logger.warning("Bad PUT request on %r (read_request_body): %s", path, e, exc_info=True)
  127. return httputils.BAD_REQUEST
  128. except socket.timeout:
  129. logger.debug("Client timed out", exc_info=True)
  130. return httputils.REQUEST_TIMEOUT
  131. # Prepare before locking
  132. content_type = environ.get("CONTENT_TYPE", "").split(";",
  133. maxsplit=1)[0]
  134. try:
  135. vobject_items = radicale_item.read_components(content or "")
  136. except Exception as e:
  137. logger.warning(
  138. "Bad PUT request on %r (read_components): %s", path, e, exc_info=True)
  139. if self._log_bad_put_request_content:
  140. logger.warning("Bad PUT request content of %r:\n%s", path, content)
  141. else:
  142. logger.debug("Bad PUT request content: suppressed by config/option [logging] bad_put_request_content")
  143. return httputils.BAD_REQUEST
  144. (prepared_items, prepared_tag, prepared_write_whole_collection,
  145. prepared_props, prepared_exc_info) = prepare(
  146. vobject_items, path, content_type,
  147. bool(rights.intersect(access.permissions, "Ww")),
  148. bool(rights.intersect(access.parent_permissions, "w")))
  149. with self._storage.acquire_lock("w", user):
  150. item = next(iter(self._storage.discover(path)), None)
  151. parent_item = next(iter(
  152. self._storage.discover(access.parent_path)), None)
  153. if not isinstance(parent_item, storage.BaseCollection):
  154. return httputils.CONFLICT
  155. write_whole_collection = (
  156. isinstance(item, storage.BaseCollection) or
  157. not parent_item.tag)
  158. if write_whole_collection:
  159. tag = prepared_tag
  160. else:
  161. tag = parent_item.tag
  162. if write_whole_collection:
  163. if ("w" if tag else "W") not in access.permissions:
  164. return httputils.NOT_ALLOWED
  165. if not self._permit_overwrite_collection:
  166. if ("O") not in access.permissions:
  167. logger.info("overwrite of collection is prevented by config/option [rights] permit_overwrite_collection and not explicit allowed by permssion 'O': %s", path)
  168. return httputils.NOT_ALLOWED
  169. else:
  170. if ("o") in access.permissions:
  171. logger.info("overwrite of collection is allowed by config/option [rights] permit_overwrite_collection but explicit forbidden by permission 'o': %s", path)
  172. return httputils.NOT_ALLOWED
  173. elif "w" not in access.parent_permissions:
  174. return httputils.NOT_ALLOWED
  175. etag = environ.get("HTTP_IF_MATCH", "")
  176. if not item and etag:
  177. # Etag asked but no item found: item has been removed
  178. return httputils.PRECONDITION_FAILED
  179. if item and etag and item.etag != etag:
  180. # Etag asked but item not matching: item has changed
  181. return httputils.PRECONDITION_FAILED
  182. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  183. if item and match:
  184. # Creation asked but item found: item can't be replaced
  185. return httputils.PRECONDITION_FAILED
  186. if (tag != prepared_tag or
  187. prepared_write_whole_collection != write_whole_collection):
  188. (prepared_items, prepared_tag, prepared_write_whole_collection,
  189. prepared_props, prepared_exc_info) = prepare(
  190. vobject_items, path, content_type,
  191. bool(rights.intersect(access.permissions, "Ww")),
  192. bool(rights.intersect(access.parent_permissions, "w")),
  193. tag, write_whole_collection)
  194. props = prepared_props
  195. if prepared_exc_info:
  196. logger.warning(
  197. "Bad PUT request on %r (prepare): %s", path, prepared_exc_info[1],
  198. exc_info=prepared_exc_info)
  199. return httputils.BAD_REQUEST
  200. if write_whole_collection:
  201. try:
  202. etag = self._storage.create_collection(
  203. path, prepared_items, props).etag
  204. for item in prepared_items:
  205. hook_notification_item = HookNotificationItem(
  206. HookNotificationItemTypes.UPSERT,
  207. access.path,
  208. item.serialize()
  209. )
  210. self._hook.notify(hook_notification_item)
  211. except ValueError as e:
  212. logger.warning(
  213. "Bad PUT request on %r (create_collection): %s", path, e, exc_info=True)
  214. return httputils.BAD_REQUEST
  215. else:
  216. assert not isinstance(item, storage.BaseCollection)
  217. prepared_item, = prepared_items
  218. if (item and item.uid != prepared_item.uid or
  219. not item and parent_item.has_uid(prepared_item.uid)):
  220. return self._webdav_error_response(
  221. client.CONFLICT, "%s:no-uid-conflict" % (
  222. "C" if tag == "VCALENDAR" else "CR"))
  223. href = posixpath.basename(pathutils.strip_path(path))
  224. try:
  225. etag = parent_item.upload(href, prepared_item).etag
  226. hook_notification_item = HookNotificationItem(
  227. HookNotificationItemTypes.UPSERT,
  228. access.path,
  229. prepared_item.serialize()
  230. )
  231. self._hook.notify(hook_notification_item)
  232. except ValueError as e:
  233. logger.warning(
  234. "Bad PUT request on %r (upload): %s", path, e, exc_info=True)
  235. return httputils.BAD_REQUEST
  236. headers = {"ETag": etag}
  237. return client.CREATED, headers, None