__init__.py 42 KB

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