__init__.py 26 KB

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