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