__init__.py 25 KB

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