__init__.py 35 KB

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