__init__.py 38 KB

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