__init__.py 38 KB

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