__init__.py 38 KB

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