__init__.py 26 KB

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