put.py 10 KB

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