put.py 9.4 KB

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