1
0

__init__.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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. # If "/.well-known" is not available, clients query "/"
  363. if path == "/.well-known" or path.startswith("/.well-known/"):
  364. return response(*NOT_FOUND)
  365. # Ask authentication backend to check rights
  366. external_login = self.Auth.get_external_login(environ)
  367. authorization = environ.get("HTTP_AUTHORIZATION", "")
  368. if external_login:
  369. login, password = external_login
  370. elif authorization.startswith("Basic"):
  371. authorization = authorization[len("Basic"):].strip()
  372. login, password = self.decode(base64.b64decode(
  373. authorization.encode("ascii")), environ).split(":", 1)
  374. else:
  375. # DEPRECATED: use remote_user backend instead
  376. login = environ.get("REMOTE_USER", "")
  377. password = ""
  378. user = self.Auth.map_login_to_user(login)
  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_authenticated2(login, user,
  387. password)
  388. if not is_authenticated:
  389. self.logger.info("Failed login attempt: %r", user)
  390. # Random delay to avoid timing oracles and bruteforce attacks
  391. delay = self.configuration.getfloat("auth", "delay")
  392. if delay > 0:
  393. random_delay = delay * (0.5 + random.random())
  394. self.logger.debug("Sleeping %.3f seconds", random_delay)
  395. time.sleep(random_delay)
  396. else:
  397. self.logger.info("Successful login: %r", user)
  398. # Create principal collection
  399. if user and is_authenticated:
  400. principal_path = "/%s/" % user
  401. if self.Rights.authorized(user, principal_path, "w"):
  402. with self.Collection.acquire_lock("r", user):
  403. principal = next(
  404. self.Collection.discover(principal_path, depth="1"),
  405. None)
  406. if not principal:
  407. with self.Collection.acquire_lock("w", user):
  408. try:
  409. self.Collection.create_collection(principal_path)
  410. except ValueError as e:
  411. self.logger.warning("Failed to create principal "
  412. "collection %r: %s", user, e)
  413. is_authenticated = False
  414. else:
  415. self.logger.warning("Access to principal path %r denied by "
  416. "rights backend", principal_path)
  417. # Verify content length
  418. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  419. if content_length:
  420. max_content_length = self.configuration.getint(
  421. "server", "max_content_length")
  422. if max_content_length and content_length > max_content_length:
  423. self.logger.info(
  424. "Request body too large: %d", content_length)
  425. return response(*REQUEST_ENTITY_TOO_LARGE)
  426. if is_authenticated:
  427. status, headers, answer = function(
  428. environ, base_prefix, path, user)
  429. if (status, headers, answer) == NOT_ALLOWED:
  430. self.logger.info("Access to %r denied for %s", path,
  431. repr(user) if user else "anonymous user")
  432. else:
  433. status, headers, answer = NOT_ALLOWED
  434. if (status, headers, answer) == NOT_ALLOWED and not (
  435. user and is_authenticated) and not external_login:
  436. # Unknown or unauthorized user
  437. self.logger.debug("Asking client for authentication")
  438. status = client.UNAUTHORIZED
  439. realm = self.configuration.get("server", "realm")
  440. headers = dict(headers)
  441. headers.update({
  442. "WWW-Authenticate":
  443. "Basic realm=\"%s\"" % realm})
  444. return response(status, headers, answer)
  445. def _access(self, user, path, permission, item=None):
  446. """Check if ``user`` can access ``path`` or the parent collection.
  447. ``permission`` must either be "r" or "w".
  448. If ``item`` is given, only access to that class of item is checked.
  449. """
  450. allowed = False
  451. if not item or isinstance(item, storage.BaseCollection):
  452. allowed |= self.Rights.authorized(user, path, permission)
  453. if not item or not isinstance(item, storage.BaseCollection):
  454. allowed |= self.Rights.authorized_item(user, path, permission)
  455. return allowed
  456. def _read_raw_content(self, environ):
  457. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  458. if not content_length:
  459. return b""
  460. content = environ["wsgi.input"].read(content_length)
  461. if len(content) < content_length:
  462. raise RuntimeError("Request body too short: %d" % len(content))
  463. return content
  464. def _read_content(self, environ):
  465. content = self.decode(self._read_raw_content(environ), environ)
  466. self.logger.debug("Request content:\n%s", content)
  467. return content
  468. def _read_xml_content(self, environ):
  469. content = self.decode(self._read_raw_content(environ), environ)
  470. if not content:
  471. return None
  472. try:
  473. xml_content = ET.fromstring(content)
  474. except ET.ParseError as e:
  475. self.logger.debug("Request content (Invalid XML):\n%s", content)
  476. raise RuntimeError("Failed to parse XML: %s" % e) from e
  477. if self.logger.isEnabledFor(logging.DEBUG):
  478. self.logger.debug("Request content:\n%s",
  479. xmlutils.pretty_xml(xml_content))
  480. return xml_content
  481. def _write_xml_content(self, xml_content):
  482. if self.logger.isEnabledFor(logging.DEBUG):
  483. self.logger.debug("Response content:\n%s",
  484. xmlutils.pretty_xml(xml_content))
  485. f = io.BytesIO()
  486. ET.ElementTree(xml_content).write(f, encoding=self.encoding,
  487. xml_declaration=True)
  488. return f.getvalue()
  489. def do_DELETE(self, environ, base_prefix, path, user):
  490. """Manage DELETE request."""
  491. if not self._access(user, path, "w"):
  492. return NOT_ALLOWED
  493. with self.Collection.acquire_lock("w", user):
  494. item = next(self.Collection.discover(path), None)
  495. if not self._access(user, path, "w", item):
  496. return NOT_ALLOWED
  497. if not item:
  498. return NOT_FOUND
  499. if_match = environ.get("HTTP_IF_MATCH", "*")
  500. if if_match not in ("*", item.etag):
  501. # ETag precondition not verified, do not delete item
  502. return PRECONDITION_FAILED
  503. if isinstance(item, storage.BaseCollection):
  504. xml_answer = xmlutils.delete(base_prefix, path, item)
  505. else:
  506. xml_answer = xmlutils.delete(
  507. base_prefix, path, item.collection, item.href)
  508. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  509. return client.OK, headers, self._write_xml_content(xml_answer)
  510. def do_GET(self, environ, base_prefix, path, user):
  511. """Manage GET request."""
  512. # Redirect to .web if the root URL is requested
  513. if not path.strip("/"):
  514. web_path = ".web"
  515. if not environ.get("PATH_INFO"):
  516. web_path = posixpath.join(posixpath.basename(base_prefix),
  517. web_path)
  518. return (client.FOUND,
  519. {"Location": web_path, "Content-Type": "text/plain"},
  520. "Redirected to %s" % web_path)
  521. # Dispatch .web URL to web module
  522. if path == "/.web" or path.startswith("/.web/"):
  523. return self.Web.get(environ, base_prefix, path, user)
  524. if not self._access(user, path, "r"):
  525. return NOT_ALLOWED
  526. with self.Collection.acquire_lock("r", user):
  527. item = next(self.Collection.discover(path), None)
  528. if not self._access(user, path, "r", item):
  529. return NOT_ALLOWED
  530. if not item:
  531. return NOT_FOUND
  532. if isinstance(item, storage.BaseCollection):
  533. tag = item.get_meta("tag")
  534. if not tag:
  535. return DIRECTORY_LISTING
  536. content_type = xmlutils.MIMETYPES[tag]
  537. else:
  538. content_type = xmlutils.OBJECT_MIMETYPES[item.name]
  539. headers = {
  540. "Content-Type": content_type,
  541. "Last-Modified": item.last_modified,
  542. "ETag": item.etag}
  543. answer = item.serialize()
  544. return client.OK, headers, answer
  545. def do_HEAD(self, environ, base_prefix, path, user):
  546. """Manage HEAD request."""
  547. status, headers, answer = self.do_GET(
  548. environ, base_prefix, path, user)
  549. return status, headers, None
  550. def do_MKCALENDAR(self, environ, base_prefix, path, user):
  551. """Manage MKCALENDAR request."""
  552. if not self.Rights.authorized(user, path, "w"):
  553. return NOT_ALLOWED
  554. try:
  555. xml_content = self._read_xml_content(environ)
  556. except RuntimeError as e:
  557. self.logger.warning(
  558. "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
  559. return BAD_REQUEST
  560. except socket.timeout as e:
  561. self.logger.debug("client timed out", exc_info=True)
  562. return REQUEST_TIMEOUT
  563. with self.Collection.acquire_lock("w", user):
  564. item = next(self.Collection.discover(path), None)
  565. if item:
  566. return WEBDAV_PRECONDITION_FAILED
  567. props = xmlutils.props_from_request(xml_content)
  568. props["tag"] = "VCALENDAR"
  569. # TODO: use this?
  570. # timezone = props.get("C:calendar-timezone")
  571. try:
  572. storage.check_and_sanitize_props(props)
  573. self.Collection.create_collection(path, props=props)
  574. except ValueError as e:
  575. self.logger.warning(
  576. "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
  577. return BAD_REQUEST
  578. return client.CREATED, {}, None
  579. def do_MKCOL(self, environ, base_prefix, path, user):
  580. """Manage MKCOL request."""
  581. if not self.Rights.authorized(user, path, "w"):
  582. return NOT_ALLOWED
  583. try:
  584. xml_content = self._read_xml_content(environ)
  585. except RuntimeError as e:
  586. self.logger.warning(
  587. "Bad MKCOL request on %r: %s", path, e, exc_info=True)
  588. return BAD_REQUEST
  589. except socket.timeout as e:
  590. self.logger.debug("client timed out", exc_info=True)
  591. return REQUEST_TIMEOUT
  592. with self.Collection.acquire_lock("w", user):
  593. item = next(self.Collection.discover(path), None)
  594. if item:
  595. return WEBDAV_PRECONDITION_FAILED
  596. props = xmlutils.props_from_request(xml_content)
  597. try:
  598. storage.check_and_sanitize_props(props)
  599. self.Collection.create_collection(path, props=props)
  600. except ValueError as e:
  601. self.logger.warning(
  602. "Bad MKCOL request on %r: %s", path, e, exc_info=True)
  603. return BAD_REQUEST
  604. return client.CREATED, {}, None
  605. def do_MOVE(self, environ, base_prefix, path, user):
  606. """Manage MOVE request."""
  607. raw_dest = environ.get("HTTP_DESTINATION", "")
  608. to_url = urlparse(raw_dest)
  609. if to_url.netloc != environ["HTTP_HOST"]:
  610. self.logger.info("Unsupported destination address: %r", raw_dest)
  611. # Remote destination server, not supported
  612. return REMOTE_DESTINATION
  613. if not self._access(user, path, "w"):
  614. return NOT_ALLOWED
  615. to_path = storage.sanitize_path(to_url.path)
  616. if not (to_path + "/").startswith(base_prefix + "/"):
  617. self.logger.warning("Destination %r from MOVE request on %r does"
  618. "n't start with base prefix", to_path, path)
  619. return NOT_ALLOWED
  620. to_path = to_path[len(base_prefix):]
  621. if not self._access(user, to_path, "w"):
  622. return NOT_ALLOWED
  623. with self.Collection.acquire_lock("w", user):
  624. item = next(self.Collection.discover(path), None)
  625. if not self._access(user, path, "w", item):
  626. return NOT_ALLOWED
  627. if not self._access(user, to_path, "w", item):
  628. return NOT_ALLOWED
  629. if not item:
  630. return NOT_FOUND
  631. if isinstance(item, storage.BaseCollection):
  632. return WEBDAV_PRECONDITION_FAILED
  633. to_item = next(self.Collection.discover(to_path), None)
  634. if (isinstance(to_item, storage.BaseCollection) or
  635. to_item and environ.get("HTTP_OVERWRITE", "F") != "T"):
  636. return WEBDAV_PRECONDITION_FAILED
  637. to_parent_path = storage.sanitize_path(
  638. "/%s/" % posixpath.dirname(to_path.strip("/")))
  639. to_collection = next(
  640. self.Collection.discover(to_parent_path), None)
  641. if not to_collection:
  642. return WEBDAV_PRECONDITION_FAILED
  643. to_href = posixpath.basename(to_path.strip("/"))
  644. try:
  645. self.Collection.move(item, to_collection, to_href)
  646. except ValueError as e:
  647. self.logger.warning(
  648. "Bad MOVE request on %r: %s", path, e, exc_info=True)
  649. return BAD_REQUEST
  650. return client.CREATED, {}, None
  651. def do_OPTIONS(self, environ, base_prefix, path, user):
  652. """Manage OPTIONS request."""
  653. headers = {
  654. "Allow": ", ".join(
  655. name[3:] for name in dir(self) if name.startswith("do_")),
  656. "DAV": DAV_HEADERS}
  657. return client.OK, headers, None
  658. def do_PROPFIND(self, environ, base_prefix, path, user):
  659. """Manage PROPFIND request."""
  660. if not self._access(user, path, "r"):
  661. return NOT_ALLOWED
  662. try:
  663. xml_content = self._read_xml_content(environ)
  664. except RuntimeError as e:
  665. self.logger.warning(
  666. "Bad PROPFIND request on %r: %s", path, e, exc_info=True)
  667. return BAD_REQUEST
  668. except socket.timeout as e:
  669. self.logger.debug("client timed out", exc_info=True)
  670. return REQUEST_TIMEOUT
  671. with self.Collection.acquire_lock("r", user):
  672. items = self.Collection.discover(
  673. path, environ.get("HTTP_DEPTH", "0"))
  674. # take root item for rights checking
  675. item = next(items, None)
  676. if not self._access(user, path, "r", item):
  677. return NOT_ALLOWED
  678. if not item:
  679. return NOT_FOUND
  680. # put item back
  681. items = itertools.chain([item], items)
  682. read_items, write_items = self.collect_allowed_items(items, user)
  683. headers = {"DAV": DAV_HEADERS,
  684. "Content-Type": "text/xml; charset=%s" % self.encoding}
  685. status, xml_answer = xmlutils.propfind(
  686. base_prefix, path, xml_content, read_items, write_items, user)
  687. if status == client.FORBIDDEN:
  688. return NOT_ALLOWED
  689. else:
  690. return status, headers, self._write_xml_content(xml_answer)
  691. def do_PROPPATCH(self, environ, base_prefix, path, user):
  692. """Manage PROPPATCH request."""
  693. if not self.Rights.authorized(user, path, "w"):
  694. return NOT_ALLOWED
  695. try:
  696. xml_content = self._read_xml_content(environ)
  697. except RuntimeError as e:
  698. self.logger.warning(
  699. "Bad PROPPATCH request on %r: %s", path, e, exc_info=True)
  700. return BAD_REQUEST
  701. except socket.timeout as e:
  702. self.logger.debug("client timed out", exc_info=True)
  703. return REQUEST_TIMEOUT
  704. with self.Collection.acquire_lock("w", user):
  705. item = next(self.Collection.discover(path), None)
  706. if not isinstance(item, storage.BaseCollection):
  707. return WEBDAV_PRECONDITION_FAILED
  708. headers = {"DAV": DAV_HEADERS,
  709. "Content-Type": "text/xml; charset=%s" % self.encoding}
  710. try:
  711. xml_answer = xmlutils.proppatch(base_prefix, path, xml_content,
  712. item)
  713. except ValueError as e:
  714. self.logger.warning(
  715. "Bad PROPPATCH request on %r: %s", path, e, exc_info=True)
  716. return BAD_REQUEST
  717. return (client.MULTI_STATUS, headers,
  718. self._write_xml_content(xml_answer))
  719. def do_PUT(self, environ, base_prefix, path, user):
  720. """Manage PUT request."""
  721. if not self._access(user, path, "w"):
  722. return NOT_ALLOWED
  723. try:
  724. content = self._read_content(environ)
  725. except RuntimeError as e:
  726. self.logger.warning(
  727. "Bad PUT request on %r: %s", path, e, exc_info=True)
  728. return BAD_REQUEST
  729. except socket.timeout as e:
  730. self.logger.debug("client timed out", exc_info=True)
  731. return REQUEST_TIMEOUT
  732. with self.Collection.acquire_lock("w", user):
  733. parent_path = storage.sanitize_path(
  734. "/%s/" % posixpath.dirname(path.strip("/")))
  735. item = next(self.Collection.discover(path), None)
  736. parent_item = next(self.Collection.discover(parent_path), None)
  737. write_whole_collection = (
  738. isinstance(item, storage.BaseCollection) or
  739. not parent_item or (
  740. not next(parent_item.list(), None) and
  741. parent_item.get_meta("tag") not in (
  742. "VADDRESSBOOK", "VCALENDAR")))
  743. if write_whole_collection:
  744. if not self.Rights.authorized(user, path, "w"):
  745. return NOT_ALLOWED
  746. elif not self.Rights.authorized_item(user, path, "w"):
  747. return NOT_ALLOWED
  748. etag = environ.get("HTTP_IF_MATCH", "")
  749. if not item and etag:
  750. # Etag asked but no item found: item has been removed
  751. return PRECONDITION_FAILED
  752. if item and etag and item.etag != etag:
  753. # Etag asked but item not matching: item has changed
  754. return PRECONDITION_FAILED
  755. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  756. if item and match:
  757. # Creation asked but item found: item can't be replaced
  758. return PRECONDITION_FAILED
  759. try:
  760. items = tuple(vobject.readComponents(content or ""))
  761. if not write_whole_collection and len(items) != 1:
  762. raise RuntimeError(
  763. "Item contains %d components" % len(items))
  764. if write_whole_collection or not parent_item.get_meta("tag"):
  765. content_type = environ.get("CONTENT_TYPE",
  766. "").split(";")[0]
  767. tags = {value: key
  768. for key, value in xmlutils.MIMETYPES.items()}
  769. tag = tags.get(content_type)
  770. if items and items[0].name == "VCALENDAR":
  771. tag = "VCALENDAR"
  772. elif items and items[0].name in ("VCARD", "VLIST"):
  773. tag = "VADDRESSBOOK"
  774. else:
  775. tag = parent_item.get_meta("tag")
  776. if tag == "VCALENDAR" and len(items) > 1:
  777. raise RuntimeError("VCALENDAR collection contains %d "
  778. "components" % len(items))
  779. for i in items:
  780. storage.check_and_sanitize_item(
  781. i, is_collection=write_whole_collection, uid=item.uid
  782. if not write_whole_collection and item else None,
  783. tag=tag)
  784. except Exception as e:
  785. self.logger.warning(
  786. "Bad PUT request on %r: %s", path, e, exc_info=True)
  787. return BAD_REQUEST
  788. if write_whole_collection:
  789. props = {}
  790. if tag:
  791. props["tag"] = tag
  792. if tag == "VCALENDAR" and items:
  793. if hasattr(items[0], "x_wr_calname"):
  794. calname = items[0].x_wr_calname.value
  795. if calname:
  796. props["D:displayname"] = calname
  797. if hasattr(items[0], "x_wr_caldesc"):
  798. caldesc = items[0].x_wr_caldesc.value
  799. if caldesc:
  800. props["C:calendar-description"] = caldesc
  801. try:
  802. storage.check_and_sanitize_props(props)
  803. new_item = self.Collection.create_collection(
  804. path, items, props)
  805. except ValueError as e:
  806. self.logger.warning(
  807. "Bad PUT request on %r: %s", path, e, exc_info=True)
  808. return BAD_REQUEST
  809. else:
  810. href = posixpath.basename(path.strip("/"))
  811. try:
  812. if tag and not parent_item.get_meta("tag"):
  813. new_props = parent_item.get_meta()
  814. new_props["tag"] = tag
  815. storage.check_and_sanitize_props(new_props)
  816. parent_item.set_meta_all(new_props)
  817. new_item = parent_item.upload(href, items[0])
  818. except ValueError as e:
  819. self.logger.warning(
  820. "Bad PUT request on %r: %s", path, e, exc_info=True)
  821. return BAD_REQUEST
  822. headers = {"ETag": new_item.etag}
  823. return client.CREATED, headers, None
  824. def do_REPORT(self, environ, base_prefix, path, user):
  825. """Manage REPORT request."""
  826. if not self._access(user, path, "r"):
  827. return NOT_ALLOWED
  828. try:
  829. xml_content = self._read_xml_content(environ)
  830. except RuntimeError as e:
  831. self.logger.warning(
  832. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  833. return BAD_REQUEST
  834. except socket.timeout as e:
  835. self.logger.debug("client timed out", exc_info=True)
  836. return REQUEST_TIMEOUT
  837. with self.Collection.acquire_lock("r", user):
  838. item = next(self.Collection.discover(path), None)
  839. if not self._access(user, path, "r", item):
  840. return NOT_ALLOWED
  841. if not item:
  842. return NOT_FOUND
  843. if isinstance(item, storage.BaseCollection):
  844. collection = item
  845. else:
  846. collection = item.collection
  847. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  848. try:
  849. status, xml_answer = xmlutils.report(
  850. base_prefix, path, xml_content, collection)
  851. except ValueError as e:
  852. self.logger.warning(
  853. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  854. return BAD_REQUEST
  855. return (status, headers, self._write_xml_content(xml_answer))