__init__.py 33 KB

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