__init__.py 42 KB

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