put.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. import vobject
  25. from radicale import httputils
  26. from radicale import item as radicale_item
  27. from radicale import pathutils, storage, xmlutils
  28. from radicale.log import logger
  29. def prepare(vobject_items, path, content_type, permissions, parent_permissions,
  30. tag=None, write_whole_collection=None):
  31. if (write_whole_collection or
  32. permissions and not parent_permissions):
  33. write_whole_collection = True
  34. tags = {value: key
  35. for key, value in xmlutils.MIMETYPES.items()}
  36. tag = radicale_item.predict_tag_of_whole_collection(
  37. vobject_items, tags.get(content_type))
  38. if not tag:
  39. raise ValueError("Can't determine collection tag")
  40. collection_path = pathutils.strip_path(path)
  41. elif (write_whole_collection is not None and
  42. not write_whole_collection or
  43. not permissions and parent_permissions):
  44. write_whole_collection = False
  45. if tag is None:
  46. tag = radicale_item.predict_tag_of_parent_collection(
  47. vobject_items)
  48. collection_path = posixpath.dirname(
  49. pathutils.strip_path(path))
  50. props = None
  51. stored_exc_info = None
  52. items = []
  53. try:
  54. if tag:
  55. radicale_item.check_and_sanitize_items(
  56. vobject_items, is_collection=write_whole_collection,
  57. tag=tag)
  58. if write_whole_collection and tag == "VCALENDAR":
  59. vobject_components = []
  60. vobject_item, = vobject_items
  61. for content in ("vevent", "vtodo", "vjournal"):
  62. vobject_components.extend(
  63. getattr(vobject_item, "%s_list" % content, []))
  64. vobject_components_by_uid = itertools.groupby(
  65. sorted(vobject_components,
  66. key=radicale_item.get_uid),
  67. radicale_item.get_uid)
  68. for _, components in vobject_components_by_uid:
  69. vobject_collection = vobject.iCalendar()
  70. for component in components:
  71. vobject_collection.add(component)
  72. item = radicale_item.Item(
  73. collection_path=collection_path,
  74. vobject_item=vobject_collection)
  75. item.prepare()
  76. items.append(item)
  77. elif write_whole_collection and tag == "VADDRESSBOOK":
  78. for vobject_item in vobject_items:
  79. item = radicale_item.Item(
  80. collection_path=collection_path,
  81. vobject_item=vobject_item)
  82. item.prepare()
  83. items.append(item)
  84. elif not write_whole_collection:
  85. vobject_item, = vobject_items
  86. item = radicale_item.Item(
  87. 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. radicale_item.check_and_sanitize_props(props)
  105. except Exception:
  106. stored_exc_info = sys.exc_info()
  107. # Use generator for items and delete references to free memory
  108. # early
  109. def items_generator():
  110. while items:
  111. yield items.pop(0)
  112. return (items_generator(), tag, write_whole_collection, props,
  113. stored_exc_info)
  114. class ApplicationPutMixin:
  115. def do_PUT(self, environ, base_prefix, path, user):
  116. """Manage PUT request."""
  117. if not self.access(user, path, "w"):
  118. return httputils.NOT_ALLOWED
  119. try:
  120. content = self.read_content(environ)
  121. except RuntimeError as e:
  122. logger.warning("Bad PUT request on %r: %s", path, e, exc_info=True)
  123. return httputils.BAD_REQUEST
  124. except socket.timeout:
  125. logger.debug("client timed out", exc_info=True)
  126. return httputils.REQUEST_TIMEOUT
  127. # Prepare before locking
  128. content_type = environ.get("CONTENT_TYPE", "").split(";")[0]
  129. parent_path = pathutils.unstrip_path(
  130. posixpath.dirname(pathutils.strip_path(path)), True)
  131. permissions = self._rights.authorized(user, path, "Ww")
  132. parent_permissions = self._rights.authorized(user, parent_path, "w")
  133. try:
  134. vobject_items = tuple(vobject.readComponents(content or ""))
  135. except Exception as e:
  136. logger.warning(
  137. "Bad PUT request on %r: %s", path, e, exc_info=True)
  138. return httputils.BAD_REQUEST
  139. (prepared_items, prepared_tag, prepared_write_whole_collection,
  140. prepared_props, prepared_exc_info) = prepare(
  141. vobject_items, path, content_type, permissions,
  142. parent_permissions)
  143. with self._storage.acquire_lock("w", user):
  144. item = next(self._storage.discover(path), None)
  145. parent_item = next(self._storage.discover(parent_path), None)
  146. if not parent_item:
  147. return httputils.CONFLICT
  148. write_whole_collection = (
  149. isinstance(item, storage.BaseCollection) or
  150. not parent_item.get_meta("tag"))
  151. if write_whole_collection:
  152. tag = prepared_tag
  153. else:
  154. tag = parent_item.get_meta("tag")
  155. if write_whole_collection:
  156. if not self._rights.authorized(
  157. user, path, "w" if tag else "W"):
  158. return httputils.NOT_ALLOWED
  159. elif not self._rights.authorized(user, parent_path, "w"):
  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, permissions,
  177. parent_permissions, tag, write_whole_collection)
  178. props = prepared_props
  179. if prepared_exc_info:
  180. logger.warning(
  181. "Bad PUT request on %r: %s", path, prepared_exc_info[1],
  182. exc_info=prepared_exc_info)
  183. return httputils.BAD_REQUEST
  184. if write_whole_collection:
  185. try:
  186. etag = self._storage.create_collection(
  187. path, prepared_items, props).etag
  188. except ValueError as e:
  189. logger.warning(
  190. "Bad PUT request on %r: %s", path, e, exc_info=True)
  191. return httputils.BAD_REQUEST
  192. else:
  193. prepared_item, = prepared_items
  194. if (item and item.uid != prepared_item.uid or
  195. not item and parent_item.has_uid(prepared_item.uid)):
  196. return self.webdav_error_response(
  197. "C" if tag == "VCALENDAR" else "CR",
  198. "no-uid-conflict")
  199. href = posixpath.basename(pathutils.strip_path(path))
  200. try:
  201. etag = parent_item.upload(href, prepared_item).etag
  202. except ValueError as e:
  203. logger.warning(
  204. "Bad PUT request on %r: %s", path, e, exc_info=True)
  205. return httputils.BAD_REQUEST
  206. headers = {"ETag": etag}
  207. return client.CREATED, headers, None