__init__.py 40 KB

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