__init__.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2016 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Radicale Server module.
  20. This module offers a WSGI application class.
  21. To use this module, you should take a look at the file ``radicale.py`` that
  22. should have been included in this package.
  23. """
  24. import base64
  25. import contextlib
  26. import io
  27. import itertools
  28. import os
  29. import posixpath
  30. import pprint
  31. import socket
  32. import socketserver
  33. import ssl
  34. import threading
  35. import urllib
  36. import wsgiref.simple_server
  37. import zlib
  38. from http import client
  39. from urllib.parse import unquote, urlparse
  40. import vobject
  41. from . import auth, rights, storage, xmlutils
  42. VERSION = "2.0.0rc0"
  43. NOT_ALLOWED = (client.FORBIDDEN, {"Content-type": "text/plain"},
  44. "Access to the requested resource forbidden.")
  45. NOT_FOUND = (client.NOT_FOUND, {"Content-type": "text/plain"},
  46. "The requested resource could not be found.")
  47. GONE = (client.GONE, {"Content-type": "text/plain"},
  48. "The requested resource is no longer available.")
  49. WEBDAV_PRECONDITION_FAILED = (client.CONFLICT, {"Content-type": "text/plain"},
  50. "WebDAV precondition failed.")
  51. PRECONDITION_FAILED = (client.PRECONDITION_FAILED,
  52. {"Content-type": "text/plain"}, "Precondition failed.")
  53. REQUEST_TIMEOUT = (client.REQUEST_TIMEOUT, {"Content-type": "text/plain"},
  54. "Connection timed out.")
  55. REQUEST_ENTITY_TOO_LARGE = (client.REQUEST_ENTITY_TOO_LARGE,
  56. {"Content-type": "text/plain"},
  57. "Request body too large.")
  58. REMOTE_DESTINATION = (client.BAD_GATEWAY, {"Content-type": "text/plain"},
  59. "Remote destination not supported.")
  60. DIRECTORY_LISTING = (client.FORBIDDEN, {"Content-type": "text/plain"},
  61. "Directory listings are not supported.")
  62. DAV_HEADERS = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  63. class HTTPServer(wsgiref.simple_server.WSGIServer):
  64. """HTTP server."""
  65. # These class attributes must be set before creating instance
  66. client_timeout = None
  67. max_connections = None
  68. def __init__(self, address, handler, bind_and_activate=True):
  69. """Create server."""
  70. ipv6 = ":" in address[0]
  71. if ipv6:
  72. self.address_family = socket.AF_INET6
  73. # Do not bind and activate, as we might change socket options
  74. super().__init__(address, handler, False)
  75. if ipv6:
  76. # Only allow IPv6 connections to the IPv6 socket
  77. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  78. if bind_and_activate:
  79. self.server_bind()
  80. self.server_activate()
  81. if self.max_connections:
  82. self.connections_guard = threading.BoundedSemaphore(
  83. self.max_connections)
  84. else:
  85. # use dummy context manager
  86. self.connections_guard = contextlib.suppress()
  87. def get_request(self):
  88. # Set timeout for client
  89. _socket, address = super().get_request()
  90. if self.client_timeout:
  91. _socket.settimeout(self.client_timeout)
  92. return _socket, address
  93. class HTTPSServer(HTTPServer):
  94. """HTTPS server."""
  95. # These class attributes must be set before creating instance
  96. certificate = None
  97. key = None
  98. protocol = None
  99. ciphers = None
  100. def __init__(self, address, handler):
  101. """Create server by wrapping HTTP socket in an SSL socket."""
  102. super().__init__(address, handler, bind_and_activate=False)
  103. self.socket = ssl.wrap_socket(
  104. self.socket, self.key, self.certificate, server_side=True,
  105. ssl_version=self.protocol, ciphers=self.ciphers)
  106. self.server_bind()
  107. self.server_activate()
  108. class ThreadedHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
  109. def process_request_thread(self, request, client_address):
  110. with self.connections_guard:
  111. return super().process_request_thread(request, client_address)
  112. class ThreadedHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer):
  113. def process_request_thread(self, request, client_address):
  114. with self.connections_guard:
  115. return super().process_request_thread(request, client_address)
  116. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  117. """HTTP requests handler."""
  118. # These class attributes must be set before creating instance
  119. logger = None
  120. def __init__(self, *args, **kwargs):
  121. # Store exception for logging
  122. self.error_stream = io.StringIO()
  123. super().__init__(*args, **kwargs)
  124. def get_stderr(self):
  125. return self.error_stream
  126. def log_message(self, *args, **kwargs):
  127. """Disable inner logging management."""
  128. def get_environ(self):
  129. env = super().get_environ()
  130. # Parent class only tries latin1 encoding
  131. env["PATH_INFO"] = urllib.parse.unquote(self.path.split("?", 1)[0])
  132. return env
  133. def handle(self):
  134. super().handle()
  135. # Log exception
  136. error = self.error_stream.getvalue().strip("\n")
  137. if error:
  138. self.logger.error(
  139. "An exception occurred during request:\n%s" % error)
  140. class Application:
  141. """WSGI application managing collections."""
  142. def __init__(self, configuration, logger):
  143. """Initialize application."""
  144. super().__init__()
  145. self.configuration = configuration
  146. self.logger = logger
  147. self.is_authenticated = auth.load(configuration, logger)
  148. self.Collection = storage.load(configuration, logger)
  149. self.authorized = rights.load(configuration, logger)
  150. self.encoding = configuration.get("encoding", "request")
  151. def headers_log(self, environ):
  152. """Sanitize headers for logging."""
  153. request_environ = dict(environ)
  154. # Remove environment variables
  155. if not self.configuration.getboolean("logging", "full_environment"):
  156. for shell_variable in os.environ:
  157. request_environ.pop(shell_variable, None)
  158. # Mask passwords
  159. mask_passwords = self.configuration.getboolean(
  160. "logging", "mask_passwords")
  161. authorization = request_environ.get(
  162. "HTTP_AUTHORIZATION", "").startswith("Basic")
  163. if mask_passwords and authorization:
  164. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  165. return request_environ
  166. def decode(self, text, environ):
  167. """Try to magically decode ``text`` according to given ``environ``."""
  168. # List of charsets to try
  169. charsets = []
  170. # First append content charset given in the request
  171. content_type = environ.get("CONTENT_TYPE")
  172. if content_type and "charset=" in content_type:
  173. charsets.append(
  174. content_type.split("charset=")[1].split(";")[0].strip())
  175. # Then append default Radicale charset
  176. charsets.append(self.encoding)
  177. # Then append various fallbacks
  178. charsets.append("utf-8")
  179. charsets.append("iso8859-1")
  180. # Try to decode
  181. for charset in charsets:
  182. try:
  183. return text.decode(charset)
  184. except UnicodeDecodeError:
  185. pass
  186. raise UnicodeDecodeError
  187. def collect_allowed_items(self, items, user):
  188. """Get items from request that user is allowed to access."""
  189. read_allowed_items = []
  190. write_allowed_items = []
  191. for item in items:
  192. if isinstance(item, self.Collection):
  193. path = item.path
  194. else:
  195. path = item.collection.path
  196. if self.authorized(user, path, "r"):
  197. self.logger.debug(
  198. "%s has read access to collection %s",
  199. user or "Anonymous", path or "/")
  200. read_allowed_items.append(item)
  201. else:
  202. self.logger.debug(
  203. "%s has NO read access to collection %s",
  204. user or "Anonymous", path or "/")
  205. if self.authorized(user, path, "w"):
  206. self.logger.debug(
  207. "%s has write access to collection %s",
  208. user or "Anonymous", path or "/")
  209. write_allowed_items.append(item)
  210. else:
  211. self.logger.debug(
  212. "%s has NO write access to collection %s",
  213. user or "Anonymous", path or "/")
  214. return read_allowed_items, write_allowed_items
  215. def __call__(self, environ, start_response):
  216. """Manage a request."""
  217. def response(status, headers={}, answer=None):
  218. # Start response
  219. status = "%i %s" % (
  220. status, client.responses.get(status, "Unknown"))
  221. self.logger.debug("Answer status: %s", status)
  222. start_response(status, list(headers.items()))
  223. # Return response content
  224. return [answer] if answer else []
  225. self.logger.debug("\n") # Add empty lines between requests in debug
  226. self.logger.info("%s request at %s received",
  227. environ["REQUEST_METHOD"], environ["PATH_INFO"])
  228. headers = pprint.pformat(self.headers_log(environ))
  229. self.logger.debug("Request headers:\n%s", headers)
  230. # Strip base_prefix from request URI
  231. base_prefix = self.configuration.get("server", "base_prefix")
  232. if environ["PATH_INFO"].startswith(base_prefix):
  233. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  234. elif self.configuration.get("server", "can_skip_base_prefix"):
  235. self.logger.debug(
  236. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  237. else:
  238. # Request path not starting with base_prefix, not allowed
  239. self.logger.debug(
  240. "Path not starting with prefix: %s", environ["PATH_INFO"])
  241. return response(*NOT_ALLOWED)
  242. # Sanitize request URI
  243. environ["PATH_INFO"] = storage.sanitize_path(
  244. unquote(environ["PATH_INFO"]))
  245. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  246. path = environ["PATH_INFO"]
  247. # Get function corresponding to method
  248. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  249. # Ask authentication backend to check rights
  250. authorization = environ.get("HTTP_AUTHORIZATION", None)
  251. if authorization and authorization.startswith("Basic"):
  252. authorization = authorization[len("Basic"):].strip()
  253. user, password = self.decode(base64.b64decode(
  254. authorization.encode("ascii")), environ).split(":", 1)
  255. else:
  256. user = environ.get("REMOTE_USER")
  257. password = None
  258. # If "/.well-known" is not available, clients query "/"
  259. if path == "/.well-known" or path.startswith("/.well-known/"):
  260. return response(*NOT_FOUND)
  261. if user and not storage.is_safe_path_component(user):
  262. # Prevent usernames like "user/calendar.ics"
  263. self.logger.info("Refused unsafe username: %s", user)
  264. is_authenticated = False
  265. else:
  266. is_authenticated = self.is_authenticated(user, password)
  267. is_valid_user = is_authenticated or not user
  268. # Create principal collection
  269. if user and is_authenticated:
  270. principal_path = "/%s/" % user
  271. if self.authorized(user, principal_path, "w"):
  272. with self.Collection.acquire_lock("r", user):
  273. principal = next(
  274. self.Collection.discover(principal_path, depth="1"),
  275. None)
  276. if not principal:
  277. with self.Collection.acquire_lock("w", user):
  278. self.Collection.create_collection(principal_path)
  279. # Verify content length
  280. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  281. if content_length:
  282. max_content_length = self.configuration.getint(
  283. "server", "max_content_length")
  284. if max_content_length and content_length > max_content_length:
  285. self.logger.debug(
  286. "Request body too large: %d", content_length)
  287. return response(*REQUEST_ENTITY_TOO_LARGE)
  288. if is_valid_user:
  289. try:
  290. status, headers, answer = function(environ, path, user)
  291. except socket.timeout:
  292. return response(*REQUEST_TIMEOUT)
  293. else:
  294. status, headers, answer = NOT_ALLOWED
  295. if (status, headers, answer) == NOT_ALLOWED and not (
  296. user and is_authenticated):
  297. # Unknown or unauthorized user
  298. self.logger.info("%s refused" % (user or "Anonymous user"))
  299. status = client.UNAUTHORIZED
  300. realm = self.configuration.get("server", "realm")
  301. headers.update ({
  302. "WWW-Authenticate":
  303. "Basic realm=\"%s\"" % realm})
  304. # Set content length
  305. if answer:
  306. self.logger.debug("Response content:\n%s", answer)
  307. answer = answer.encode(self.encoding)
  308. accept_encoding = [
  309. encoding.strip() for encoding in
  310. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  311. if encoding.strip()]
  312. if "gzip" in accept_encoding:
  313. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  314. answer = zcomp.compress(answer) + zcomp.flush()
  315. headers["Content-Encoding"] = "gzip"
  316. headers["Content-Length"] = str(len(answer))
  317. # Add extra headers set in configuration
  318. if self.configuration.has_section("headers"):
  319. for key in self.configuration.options("headers"):
  320. headers[key] = self.configuration.get("headers", key)
  321. return response(status, headers, answer)
  322. def _access(self, user, path, permission, item=None):
  323. """Check if ``user`` can access ``path`` or the parent collection.
  324. ``permission`` must either be "r" or "w".
  325. If ``item`` is given, only access to that class of item is checked.
  326. """
  327. path = storage.sanitize_path(path)
  328. parent_path = storage.sanitize_path(
  329. "/%s/" % posixpath.dirname(path.strip("/")))
  330. allowed = False
  331. if not item or isinstance(item, self.Collection):
  332. allowed |= self.authorized(user, path, permission)
  333. if not item or not isinstance(item, self.Collection):
  334. allowed |= self.authorized(user, parent_path, permission)
  335. return allowed
  336. def _read_content(self, environ):
  337. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  338. if content_length > 0:
  339. content = self.decode(
  340. environ["wsgi.input"].read(content_length), environ)
  341. self.logger.debug("Request content:\n%s", content.strip())
  342. else:
  343. content = None
  344. return content
  345. def do_DELETE(self, environ, path, user):
  346. """Manage DELETE request."""
  347. if not self._access(user, path, "w"):
  348. return NOT_ALLOWED
  349. with self.Collection.acquire_lock("w", user):
  350. item = next(self.Collection.discover(path), None)
  351. if not self._access(user, path, "w", item):
  352. return NOT_ALLOWED
  353. if not item:
  354. return GONE
  355. if_match = environ.get("HTTP_IF_MATCH", "*")
  356. if if_match not in ("*", item.etag):
  357. # ETag precondition not verified, do not delete item
  358. return PRECONDITION_FAILED
  359. if isinstance(item, self.Collection):
  360. answer = xmlutils.delete(path, item)
  361. else:
  362. answer = xmlutils.delete(path, item.collection, item.href)
  363. return client.OK, {}, answer
  364. def do_GET(self, environ, path, user):
  365. """Manage GET request."""
  366. # Display a "Radicale works!" message if the root URL is requested
  367. if not path.strip("/"):
  368. headers = {"Content-type": "text/html"}
  369. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  370. return client.OK, headers, answer
  371. if not self._access(user, path, "r"):
  372. return NOT_ALLOWED
  373. with self.Collection.acquire_lock("r", user):
  374. item = next(self.Collection.discover(path), None)
  375. if not self._access(user, path, "r", item):
  376. return NOT_ALLOWED
  377. if not item:
  378. return NOT_FOUND
  379. if isinstance(item, self.Collection):
  380. collection = item
  381. if collection.get_meta("tag") not in ("VADDRESSBOOK", "VCALENDAR"):
  382. return DIRECTORY_LISTING
  383. else:
  384. collection = item.collection
  385. content_type = xmlutils.MIMETYPES.get(
  386. collection.get_meta("tag"), "text/plain")
  387. headers = {
  388. "Content-Type": content_type,
  389. "Last-Modified": collection.last_modified,
  390. "ETag": item.etag}
  391. answer = item.serialize()
  392. return client.OK, headers, answer
  393. def do_HEAD(self, environ, path, user):
  394. """Manage HEAD request."""
  395. status, headers, answer = self.do_GET(environ, path, user)
  396. return status, headers, None
  397. def do_MKCALENDAR(self, environ, path, user):
  398. """Manage MKCALENDAR request."""
  399. if not self.authorized(user, path, "w"):
  400. return NOT_ALLOWED
  401. content = self._read_content(environ)
  402. with self.Collection.acquire_lock("w", user):
  403. item = next(self.Collection.discover(path), None)
  404. if item:
  405. return WEBDAV_PRECONDITION_FAILED
  406. props = xmlutils.props_from_request(content)
  407. props["tag"] = "VCALENDAR"
  408. # TODO: use this?
  409. # timezone = props.get("C:calendar-timezone")
  410. self.Collection.create_collection(path, props=props)
  411. return client.CREATED, {}, None
  412. def do_MKCOL(self, environ, path, user):
  413. """Manage MKCOL request."""
  414. if not self.authorized(user, path, "w"):
  415. return NOT_ALLOWED
  416. content = self._read_content(environ)
  417. with self.Collection.acquire_lock("w", user):
  418. item = next(self.Collection.discover(path), None)
  419. if item:
  420. return WEBDAV_PRECONDITION_FAILED
  421. props = xmlutils.props_from_request(content)
  422. self.Collection.create_collection(path, props=props)
  423. return client.CREATED, {}, None
  424. def do_MOVE(self, environ, path, user):
  425. """Manage MOVE request."""
  426. to_url = urlparse(environ["HTTP_DESTINATION"])
  427. if to_url.netloc != environ["HTTP_HOST"]:
  428. # Remote destination server, not supported
  429. return REMOTE_DESTINATION
  430. if not self._access(user, path, "w"):
  431. return NOT_ALLOWED
  432. to_path = storage.sanitize_path(to_url.path)
  433. if not self._access(user, to_path, "w"):
  434. return NOT_ALLOWED
  435. with self.Collection.acquire_lock("w", user):
  436. item = next(self.Collection.discover(path), None)
  437. if not self._access(user, path, "w", item):
  438. return NOT_ALLOWED
  439. if not self._access(user, to_path, "w", item):
  440. return NOT_ALLOWED
  441. if not item:
  442. return GONE
  443. if isinstance(item, self.Collection):
  444. return WEBDAV_PRECONDITION_FAILED
  445. to_item = next(self.Collection.discover(to_path), None)
  446. if (isinstance(to_item, self.Collection) or
  447. to_item and environ.get("HTTP_OVERWRITE", "F") != "T"):
  448. return WEBDAV_PRECONDITION_FAILED
  449. to_parent_path = storage.sanitize_path(
  450. "/%s/" % posixpath.dirname(to_path.strip("/")))
  451. to_collection = next(
  452. self.Collection.discover(to_parent_path), None)
  453. if not to_collection:
  454. return WEBDAV_PRECONDITION_FAILED
  455. to_href = posixpath.basename(to_path.strip("/"))
  456. self.Collection.move(item, to_collection, to_href)
  457. return client.CREATED, {}, None
  458. def do_OPTIONS(self, environ, path, user):
  459. """Manage OPTIONS request."""
  460. headers = {
  461. "Allow": ", ".join(
  462. name[3:] for name in dir(self) if name.startswith("do_")),
  463. "DAV": DAV_HEADERS}
  464. return client.OK, headers, None
  465. def do_PROPFIND(self, environ, path, user):
  466. """Manage PROPFIND request."""
  467. if not self._access(user, path, "r"):
  468. return NOT_ALLOWED
  469. content = self._read_content(environ)
  470. with self.Collection.acquire_lock("r", user):
  471. items = self.Collection.discover(
  472. path, environ.get("HTTP_DEPTH", "0"))
  473. # take root item for rights checking
  474. item = next(items, None)
  475. if not self._access(user, path, "r", item):
  476. return NOT_ALLOWED
  477. if not item:
  478. return NOT_FOUND
  479. # put item back
  480. items = itertools.chain([item], items)
  481. read_items, write_items = self.collect_allowed_items(items, user)
  482. headers = {"DAV": DAV_HEADERS, "Content-Type": "text/xml"}
  483. status, answer = xmlutils.propfind(
  484. path, content, read_items, write_items, user)
  485. if status == client.FORBIDDEN:
  486. return NOT_ALLOWED
  487. else:
  488. return status, headers, answer
  489. def do_PROPPATCH(self, environ, path, user):
  490. """Manage PROPPATCH request."""
  491. if not self.authorized(user, path, "w"):
  492. return NOT_ALLOWED
  493. content = self._read_content(environ)
  494. with self.Collection.acquire_lock("w", user):
  495. item = next(self.Collection.discover(path), None)
  496. if not isinstance(item, self.Collection):
  497. return WEBDAV_PRECONDITION_FAILED
  498. headers = {"DAV": DAV_HEADERS, "Content-Type": "text/xml"}
  499. answer = xmlutils.proppatch(path, content, item)
  500. return client.MULTI_STATUS, headers, answer
  501. def do_PUT(self, environ, path, user):
  502. """Manage PUT request."""
  503. if not self._access(user, path, "w"):
  504. return NOT_ALLOWED
  505. content = self._read_content(environ)
  506. with self.Collection.acquire_lock("w", user):
  507. parent_path = storage.sanitize_path(
  508. "/%s/" % posixpath.dirname(path.strip("/")))
  509. item = next(self.Collection.discover(path), None)
  510. parent_item = next(self.Collection.discover(parent_path), None)
  511. write_whole_collection = (
  512. isinstance(item, self.Collection) or
  513. not parent_item or (
  514. not next(parent_item.list(), None) and
  515. parent_item.get_meta("tag") not in (
  516. "VADDRESSBOOK", "VCALENDAR")))
  517. if write_whole_collection:
  518. if not self.authorized(user, path, "w"):
  519. return NOT_ALLOWED
  520. elif not self.authorized(user, parent_path, "w"):
  521. return NOT_ALLOWED
  522. etag = environ.get("HTTP_IF_MATCH", "")
  523. if not item and etag:
  524. # Etag asked but no item found: item has been removed
  525. return PRECONDITION_FAILED
  526. if item and etag and item.etag != etag:
  527. # Etag asked but item not matching: item has changed
  528. return PRECONDITION_FAILED
  529. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  530. if item and match:
  531. # Creation asked but item found: item can't be replaced
  532. return PRECONDITION_FAILED
  533. items = list(vobject.readComponents(content or ""))
  534. content_type = environ.get("CONTENT_TYPE", "").split(";")[0]
  535. tags = {value: key for key, value in xmlutils.MIMETYPES.items()}
  536. tag = tags.get(content_type)
  537. if write_whole_collection:
  538. new_item = self.Collection.create_collection(
  539. path, items, {"tag": tag})
  540. else:
  541. if tag:
  542. parent_item.set_meta({"tag": tag})
  543. href = posixpath.basename(path.strip("/"))
  544. new_item = parent_item.upload(href, items[0])
  545. headers = {"ETag": new_item.etag}
  546. return client.CREATED, headers, None
  547. def do_REPORT(self, environ, path, user):
  548. """Manage REPORT request."""
  549. if not self._access(user, path, "w"):
  550. return NOT_ALLOWED
  551. content = self._read_content(environ)
  552. with self.Collection.acquire_lock("r", user):
  553. item = next(self.Collection.discover(path), None)
  554. if not self._access(user, path, "w", item):
  555. return NOT_ALLOWED
  556. if not item:
  557. return NOT_FOUND
  558. if isinstance(item, self.Collection):
  559. collection = item
  560. else:
  561. collection = item.collection
  562. headers = {"Content-Type": "text/xml"}
  563. answer = xmlutils.report(path, content, collection)
  564. return client.MULTI_STATUS, headers, answer