__init__.py 38 KB

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