__init__.py 25 KB

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