__init__.py 26 KB

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