__init__.py 28 KB

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