__init__.py 35 KB

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