put.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. return httputils.BAD_REQUEST
  142. (prepared_items, prepared_tag, prepared_write_whole_collection,
  143. prepared_props, prepared_exc_info) = prepare(
  144. vobject_items, path, content_type,
  145. bool(rights.intersect(access.permissions, "Ww")),
  146. bool(rights.intersect(access.parent_permissions, "w")))
  147. with self._storage.acquire_lock("w", user):
  148. item = next(iter(self._storage.discover(path)), None)
  149. parent_item = next(iter(
  150. self._storage.discover(access.parent_path)), None)
  151. if not isinstance(parent_item, storage.BaseCollection):
  152. return httputils.CONFLICT
  153. write_whole_collection = (
  154. isinstance(item, storage.BaseCollection) or
  155. not parent_item.tag)
  156. if write_whole_collection:
  157. tag = prepared_tag
  158. else:
  159. tag = parent_item.tag
  160. if write_whole_collection:
  161. if ("w" if tag else "W") not in access.permissions:
  162. return httputils.NOT_ALLOWED
  163. elif "w" not in access.parent_permissions:
  164. return httputils.NOT_ALLOWED
  165. etag = environ.get("HTTP_IF_MATCH", "")
  166. if not item and etag:
  167. # Etag asked but no item found: item has been removed
  168. return httputils.PRECONDITION_FAILED
  169. if item and etag and item.etag != etag:
  170. # Etag asked but item not matching: item has changed
  171. return httputils.PRECONDITION_FAILED
  172. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  173. if item and match:
  174. # Creation asked but item found: item can't be replaced
  175. return httputils.PRECONDITION_FAILED
  176. if (tag != prepared_tag or
  177. prepared_write_whole_collection != write_whole_collection):
  178. (prepared_items, prepared_tag, prepared_write_whole_collection,
  179. prepared_props, prepared_exc_info) = prepare(
  180. vobject_items, path, content_type,
  181. bool(rights.intersect(access.permissions, "Ww")),
  182. bool(rights.intersect(access.parent_permissions, "w")),
  183. tag, write_whole_collection)
  184. props = prepared_props
  185. if prepared_exc_info:
  186. logger.warning(
  187. "Bad PUT request on %r (prepare): %s", path, prepared_exc_info[1],
  188. exc_info=prepared_exc_info)
  189. return httputils.BAD_REQUEST
  190. if write_whole_collection:
  191. try:
  192. etag = self._storage.create_collection(
  193. path, prepared_items, props).etag
  194. for item in prepared_items:
  195. hook_notification_item = HookNotificationItem(
  196. HookNotificationItemTypes.UPSERT,
  197. access.path,
  198. item.serialize()
  199. )
  200. self._hook.notify(hook_notification_item)
  201. except ValueError as e:
  202. logger.warning(
  203. "Bad PUT request on %r (create_collection): %s", path, e, exc_info=True)
  204. return httputils.BAD_REQUEST
  205. else:
  206. assert not isinstance(item, storage.BaseCollection)
  207. prepared_item, = prepared_items
  208. if (item and item.uid != prepared_item.uid or
  209. not item and parent_item.has_uid(prepared_item.uid)):
  210. return self._webdav_error_response(
  211. client.CONFLICT, "%s:no-uid-conflict" % (
  212. "C" if tag == "VCALENDAR" else "CR"))
  213. href = posixpath.basename(pathutils.strip_path(path))
  214. try:
  215. etag = parent_item.upload(href, prepared_item).etag
  216. hook_notification_item = HookNotificationItem(
  217. HookNotificationItemTypes.UPSERT,
  218. access.path,
  219. prepared_item.serialize()
  220. )
  221. self._hook.notify(hook_notification_item)
  222. except ValueError as e:
  223. logger.warning(
  224. "Bad PUT request on %r (upload): %s", path, e, exc_info=True)
  225. return httputils.BAD_REQUEST
  226. headers = {"ETag": etag}
  227. return client.CREATED, headers, None