__init__.py 39 KB

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