__init__.py 25 KB

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