__init__.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. headers = headers.copy()
  217. # Set content length
  218. if answer:
  219. self.logger.debug("Response content:\n%s", answer)
  220. answer = answer.encode(self.encoding)
  221. accept_encoding = [
  222. encoding.strip() for encoding in
  223. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  224. if encoding.strip()]
  225. if "gzip" in accept_encoding:
  226. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  227. answer = zcomp.compress(answer) + zcomp.flush()
  228. headers["Content-Encoding"] = "gzip"
  229. headers["Content-Length"] = str(len(answer))
  230. # Add extra headers set in configuration
  231. if self.configuration.has_section("headers"):
  232. for key in self.configuration.options("headers"):
  233. headers[key] = self.configuration.get("headers", key)
  234. # Start response
  235. status = "%i %s" % (
  236. status, client.responses.get(status, "Unknown"))
  237. self.logger.debug("Answer status: %s", status)
  238. start_response(status, list(headers.items()))
  239. # Return response content
  240. return [answer] if answer else []
  241. self.logger.info("%s request at %s received",
  242. environ["REQUEST_METHOD"], environ["PATH_INFO"])
  243. headers = pprint.pformat(self.headers_log(environ))
  244. self.logger.debug("Request headers:\n%s", headers)
  245. # Strip base_prefix from request URI
  246. base_prefix = self.configuration.get("server", "base_prefix")
  247. if environ["PATH_INFO"].startswith(base_prefix):
  248. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  249. elif self.configuration.get("server", "can_skip_base_prefix"):
  250. self.logger.debug(
  251. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  252. else:
  253. # Request path not starting with base_prefix, not allowed
  254. self.logger.debug(
  255. "Path not starting with prefix: %s", environ["PATH_INFO"])
  256. return response(*NOT_ALLOWED)
  257. # Sanitize request URI
  258. environ["PATH_INFO"] = storage.sanitize_path(
  259. unquote(environ["PATH_INFO"]))
  260. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  261. path = environ["PATH_INFO"]
  262. # Get function corresponding to method
  263. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  264. # Ask authentication backend to check rights
  265. authorization = environ.get("HTTP_AUTHORIZATION", None)
  266. if authorization and authorization.startswith("Basic"):
  267. authorization = authorization[len("Basic"):].strip()
  268. login, password = self.decode(base64.b64decode(
  269. authorization.encode("ascii")), environ).split(":", 1)
  270. user = self.Auth.map_login_to_user(login)
  271. else:
  272. user = self.Auth.map_login_to_user(environ.get("REMOTE_USER", ""))
  273. password = None
  274. # If "/.well-known" is not available, clients query "/"
  275. if path == "/.well-known" or path.startswith("/.well-known/"):
  276. return response(*NOT_FOUND)
  277. if user and not storage.is_safe_path_component(user):
  278. # Prevent usernames like "user/calendar.ics"
  279. self.logger.info("Refused unsafe username: %s", user)
  280. is_authenticated = False
  281. else:
  282. is_authenticated = self.Auth.is_authenticated(user, password)
  283. is_valid_user = is_authenticated or not user
  284. # Create principal collection
  285. if user and is_authenticated:
  286. principal_path = "/%s/" % user
  287. if self.authorized(user, principal_path, "w"):
  288. with self.Collection.acquire_lock("r", user):
  289. principal = next(
  290. self.Collection.discover(principal_path, depth="1"),
  291. None)
  292. if not principal:
  293. with self.Collection.acquire_lock("w", user):
  294. self.Collection.create_collection(principal_path)
  295. # Verify content length
  296. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  297. if content_length:
  298. max_content_length = self.configuration.getint(
  299. "server", "max_content_length")
  300. if max_content_length and content_length > max_content_length:
  301. self.logger.debug(
  302. "Request body too large: %d", content_length)
  303. return response(*REQUEST_ENTITY_TOO_LARGE)
  304. if is_valid_user:
  305. try:
  306. status, headers, answer = function(environ, path, user)
  307. except socket.timeout:
  308. return response(*REQUEST_TIMEOUT)
  309. else:
  310. status, headers, answer = NOT_ALLOWED
  311. if (status, headers, answer) == NOT_ALLOWED and not (
  312. user and is_authenticated):
  313. # Unknown or unauthorized user
  314. self.logger.info("%s refused" % (user or "Anonymous user"))
  315. status = client.UNAUTHORIZED
  316. realm = self.configuration.get("server", "realm")
  317. headers = headers.copy()
  318. headers.update ({
  319. "WWW-Authenticate":
  320. "Basic realm=\"%s\"" % realm})
  321. return response(status, headers, answer)
  322. def _access(self, user, path, permission, item=None):
  323. """Check if ``user`` can access ``path`` or the parent collection.
  324. ``permission`` must either be "r" or "w".
  325. If ``item`` is given, only access to that class of item is checked.
  326. """
  327. path = storage.sanitize_path(path)
  328. parent_path = storage.sanitize_path(
  329. "/%s/" % posixpath.dirname(path.strip("/")))
  330. allowed = False
  331. if not item or isinstance(item, self.Collection):
  332. allowed |= self.authorized(user, path, permission)
  333. if not item or not isinstance(item, self.Collection):
  334. allowed |= self.authorized(user, parent_path, permission)
  335. return allowed
  336. def _read_content(self, environ):
  337. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  338. if content_length > 0:
  339. content = self.decode(
  340. environ["wsgi.input"].read(content_length), environ)
  341. self.logger.debug("Request content:\n%s", content.strip())
  342. else:
  343. content = None
  344. return content
  345. def do_DELETE(self, environ, path, user):
  346. """Manage DELETE request."""
  347. if not self._access(user, path, "w"):
  348. return NOT_ALLOWED
  349. with self.Collection.acquire_lock("w", user):
  350. item = next(self.Collection.discover(path), None)
  351. if not self._access(user, path, "w", item):
  352. return NOT_ALLOWED
  353. if not item:
  354. return NOT_FOUND
  355. if_match = environ.get("HTTP_IF_MATCH", "*")
  356. if if_match not in ("*", item.etag):
  357. # ETag precondition not verified, do not delete item
  358. return PRECONDITION_FAILED
  359. if isinstance(item, self.Collection):
  360. answer = xmlutils.delete(path, item)
  361. else:
  362. answer = xmlutils.delete(path, item.collection, item.href)
  363. return client.OK, {}, answer
  364. def do_GET(self, environ, path, user):
  365. """Manage GET request."""
  366. # Display a "Radicale works!" message if the root URL is requested
  367. if not path.strip("/"):
  368. return client.OK, {"Content-type": "text/plain"}, "Radicale works!"
  369. if not self._access(user, path, "r"):
  370. return NOT_ALLOWED
  371. with self.Collection.acquire_lock("r", user):
  372. item = next(self.Collection.discover(path), None)
  373. if not self._access(user, path, "r", item):
  374. return NOT_ALLOWED
  375. if not item:
  376. return NOT_FOUND
  377. if isinstance(item, self.Collection):
  378. collection = item
  379. if collection.get_meta("tag") not in ("VADDRESSBOOK", "VCALENDAR"):
  380. return DIRECTORY_LISTING
  381. else:
  382. collection = item.collection
  383. content_type = xmlutils.MIMETYPES.get(
  384. collection.get_meta("tag"), "text/plain")
  385. headers = {
  386. "Content-Type": content_type,
  387. "Last-Modified": collection.last_modified,
  388. "ETag": item.etag}
  389. answer = item.serialize()
  390. return client.OK, headers, answer
  391. def do_HEAD(self, environ, path, user):
  392. """Manage HEAD request."""
  393. status, headers, answer = self.do_GET(environ, path, user)
  394. return status, headers, None
  395. def do_MKCALENDAR(self, environ, path, user):
  396. """Manage MKCALENDAR request."""
  397. if not self.authorized(user, path, "w"):
  398. return NOT_ALLOWED
  399. content = self._read_content(environ)
  400. with self.Collection.acquire_lock("w", user):
  401. item = next(self.Collection.discover(path), None)
  402. if item:
  403. return WEBDAV_PRECONDITION_FAILED
  404. props = xmlutils.props_from_request(content)
  405. props["tag"] = "VCALENDAR"
  406. # TODO: use this?
  407. # timezone = props.get("C:calendar-timezone")
  408. self.Collection.create_collection(path, props=props)
  409. return client.CREATED, {}, None
  410. def do_MKCOL(self, environ, path, user):
  411. """Manage MKCOL request."""
  412. if not self.authorized(user, path, "w"):
  413. return NOT_ALLOWED
  414. content = self._read_content(environ)
  415. with self.Collection.acquire_lock("w", user):
  416. item = next(self.Collection.discover(path), None)
  417. if item:
  418. return WEBDAV_PRECONDITION_FAILED
  419. props = xmlutils.props_from_request(content)
  420. self.Collection.create_collection(path, props=props)
  421. return client.CREATED, {}, None
  422. def do_MOVE(self, environ, path, user):
  423. """Manage MOVE request."""
  424. to_url = urlparse(environ["HTTP_DESTINATION"])
  425. if to_url.netloc != environ["HTTP_HOST"]:
  426. # Remote destination server, not supported
  427. return REMOTE_DESTINATION
  428. if not self._access(user, path, "w"):
  429. return NOT_ALLOWED
  430. to_path = storage.sanitize_path(to_url.path)
  431. if not self._access(user, to_path, "w"):
  432. return NOT_ALLOWED
  433. with self.Collection.acquire_lock("w", user):
  434. item = next(self.Collection.discover(path), None)
  435. if not self._access(user, path, "w", item):
  436. return NOT_ALLOWED
  437. if not self._access(user, to_path, "w", item):
  438. return NOT_ALLOWED
  439. if not item:
  440. return NOT_FOUND
  441. if isinstance(item, self.Collection):
  442. return WEBDAV_PRECONDITION_FAILED
  443. to_item = next(self.Collection.discover(to_path), None)
  444. if (isinstance(to_item, self.Collection) or
  445. to_item and environ.get("HTTP_OVERWRITE", "F") != "T"):
  446. return WEBDAV_PRECONDITION_FAILED
  447. to_parent_path = storage.sanitize_path(
  448. "/%s/" % posixpath.dirname(to_path.strip("/")))
  449. to_collection = next(
  450. self.Collection.discover(to_parent_path), None)
  451. if not to_collection:
  452. return WEBDAV_PRECONDITION_FAILED
  453. to_href = posixpath.basename(to_path.strip("/"))
  454. self.Collection.move(item, to_collection, to_href)
  455. return client.CREATED, {}, None
  456. def do_OPTIONS(self, environ, path, user):
  457. """Manage OPTIONS request."""
  458. headers = {
  459. "Allow": ", ".join(
  460. name[3:] for name in dir(self) if name.startswith("do_")),
  461. "DAV": DAV_HEADERS}
  462. return client.OK, headers, None
  463. def do_PROPFIND(self, environ, path, user):
  464. """Manage PROPFIND request."""
  465. if not self._access(user, path, "r"):
  466. return NOT_ALLOWED
  467. content = self._read_content(environ)
  468. with self.Collection.acquire_lock("r", user):
  469. items = self.Collection.discover(
  470. path, environ.get("HTTP_DEPTH", "0"))
  471. # take root item for rights checking
  472. item = next(items, None)
  473. if not self._access(user, path, "r", item):
  474. return NOT_ALLOWED
  475. if not item:
  476. return NOT_FOUND
  477. # put item back
  478. items = itertools.chain([item], items)
  479. read_items, write_items = self.collect_allowed_items(items, user)
  480. headers = {"DAV": DAV_HEADERS, "Content-Type": "text/xml"}
  481. status, answer = xmlutils.propfind(
  482. path, content, read_items, write_items, user)
  483. if status == client.FORBIDDEN:
  484. return NOT_ALLOWED
  485. else:
  486. return status, headers, answer
  487. def do_PROPPATCH(self, environ, path, user):
  488. """Manage PROPPATCH request."""
  489. if not self.authorized(user, path, "w"):
  490. return NOT_ALLOWED
  491. content = self._read_content(environ)
  492. with self.Collection.acquire_lock("w", user):
  493. item = next(self.Collection.discover(path), None)
  494. if not isinstance(item, self.Collection):
  495. return WEBDAV_PRECONDITION_FAILED
  496. headers = {"DAV": DAV_HEADERS, "Content-Type": "text/xml"}
  497. answer = xmlutils.proppatch(path, content, item)
  498. return client.MULTI_STATUS, headers, answer
  499. def do_PUT(self, environ, path, user):
  500. """Manage PUT request."""
  501. if not self._access(user, path, "w"):
  502. return NOT_ALLOWED
  503. content = self._read_content(environ)
  504. with self.Collection.acquire_lock("w", user):
  505. parent_path = storage.sanitize_path(
  506. "/%s/" % posixpath.dirname(path.strip("/")))
  507. item = next(self.Collection.discover(path), None)
  508. parent_item = next(self.Collection.discover(parent_path), None)
  509. write_whole_collection = (
  510. isinstance(item, self.Collection) or
  511. not parent_item or (
  512. not next(parent_item.list(), None) and
  513. parent_item.get_meta("tag") not in (
  514. "VADDRESSBOOK", "VCALENDAR")))
  515. if write_whole_collection:
  516. if not self.authorized(user, path, "w"):
  517. return NOT_ALLOWED
  518. elif not self.authorized(user, parent_path, "w"):
  519. return NOT_ALLOWED
  520. etag = environ.get("HTTP_IF_MATCH", "")
  521. if not item and etag:
  522. # Etag asked but no item found: item has been removed
  523. return PRECONDITION_FAILED
  524. if item and etag and item.etag != etag:
  525. # Etag asked but item not matching: item has changed
  526. return PRECONDITION_FAILED
  527. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  528. if item and match:
  529. # Creation asked but item found: item can't be replaced
  530. return PRECONDITION_FAILED
  531. items = list(vobject.readComponents(content or ""))
  532. content_type = environ.get("CONTENT_TYPE", "").split(";")[0]
  533. tags = {value: key for key, value in xmlutils.MIMETYPES.items()}
  534. tag = tags.get(content_type)
  535. if write_whole_collection:
  536. new_item = self.Collection.create_collection(
  537. path, items, {"tag": tag})
  538. else:
  539. if tag:
  540. parent_item.set_meta({"tag": tag})
  541. href = posixpath.basename(path.strip("/"))
  542. new_item = parent_item.upload(href, items[0])
  543. headers = {"ETag": new_item.etag}
  544. return client.CREATED, headers, None
  545. def do_REPORT(self, environ, path, user):
  546. """Manage REPORT request."""
  547. if not self._access(user, path, "w"):
  548. return NOT_ALLOWED
  549. content = self._read_content(environ)
  550. with self.Collection.acquire_lock("r", user):
  551. item = next(self.Collection.discover(path), None)
  552. if not self._access(user, path, "w", item):
  553. return NOT_ALLOWED
  554. if not item:
  555. return NOT_FOUND
  556. if isinstance(item, self.Collection):
  557. collection = item
  558. else:
  559. collection = item.collection
  560. headers = {"Content-Type": "text/xml"}
  561. answer = xmlutils.report(path, content, collection)
  562. return client.MULTI_STATUS, headers, answer