__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2016 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 os
  27. import posixpath
  28. import pprint
  29. import shlex
  30. import socket
  31. import socketserver
  32. import ssl
  33. import subprocess
  34. import threading
  35. import wsgiref.simple_server
  36. import zlib
  37. from contextlib import contextmanager
  38. from http import client
  39. from urllib.parse import unquote, urlparse
  40. import vobject
  41. from . import auth, rights, storage, xmlutils
  42. VERSION = "2.0.0rc0"
  43. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  44. DAV_HEADERS = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  45. class HTTPServer(wsgiref.simple_server.WSGIServer):
  46. """HTTP server."""
  47. # These class attributes must be set before creating instance
  48. client_timeout = None
  49. max_connections = None
  50. def __init__(self, address, handler, bind_and_activate=True):
  51. """Create server."""
  52. ipv6 = ":" in address[0]
  53. if ipv6:
  54. self.address_family = socket.AF_INET6
  55. # Do not bind and activate, as we might change socket options
  56. super().__init__(address, handler, False)
  57. if ipv6:
  58. # Only allow IPv6 connections to the IPv6 socket
  59. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  60. if bind_and_activate:
  61. self.server_bind()
  62. self.server_activate()
  63. if self.max_connections:
  64. self.connections_guard = threading.BoundedSemaphore(
  65. self.max_connections)
  66. else:
  67. # use dummy context manager
  68. self.connections_guard = contextlib.suppress()
  69. def get_request(self):
  70. # Set timeout for client
  71. _socket, address = super().get_request()
  72. if self.client_timeout:
  73. _socket.settimeout(self.client_timeout)
  74. return _socket, address
  75. class HTTPSServer(HTTPServer):
  76. """HTTPS server."""
  77. # These class attributes must be set before creating instance
  78. certificate = None
  79. key = None
  80. protocol = None
  81. cyphers = None
  82. def __init__(self, address, handler):
  83. """Create server by wrapping HTTP socket in an SSL socket."""
  84. super().__init__(address, handler, bind_and_activate=False)
  85. self.socket = ssl.wrap_socket(
  86. self.socket, self.key, self.certificate, server_side=True,
  87. ssl_version=self.protocol, cyphers=self.cyphers)
  88. self.server_bind()
  89. self.server_activate()
  90. class ThreadedHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
  91. def process_request_thread(self, request, client_address):
  92. with self.connections_guard:
  93. return super().process_request_thread(request, client_address)
  94. class ThreadedHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer):
  95. def process_request_thread(self, request, client_address):
  96. with self.connections_guard:
  97. return super().process_request_thread(request, client_address)
  98. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  99. """HTTP requests handler."""
  100. def log_message(self, *args, **kwargs):
  101. """Disable inner logging management."""
  102. class Application:
  103. """WSGI application managing collections."""
  104. def __init__(self, configuration, logger):
  105. """Initialize application."""
  106. super().__init__()
  107. self.configuration = configuration
  108. self.logger = logger
  109. self.is_authenticated = auth.load(configuration, logger)
  110. self.Collection = storage.load(configuration, logger)
  111. self.authorized = rights.load(configuration, logger)
  112. self.encoding = configuration.get("encoding", "request")
  113. def headers_log(self, environ):
  114. """Sanitize headers for logging."""
  115. request_environ = dict(environ)
  116. # Remove environment variables
  117. if not self.configuration.getboolean("logging", "full_environment"):
  118. for shell_variable in os.environ:
  119. request_environ.pop(shell_variable, None)
  120. # Mask passwords
  121. mask_passwords = self.configuration.getboolean(
  122. "logging", "mask_passwords")
  123. authorization = request_environ.get(
  124. "HTTP_AUTHORIZATION", "").startswith("Basic")
  125. if mask_passwords and authorization:
  126. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  127. return request_environ
  128. def decode(self, text, environ):
  129. """Try to magically decode ``text`` according to given ``environ``."""
  130. # List of charsets to try
  131. charsets = []
  132. # First append content charset given in the request
  133. content_type = environ.get("CONTENT_TYPE")
  134. if content_type and "charset=" in content_type:
  135. charsets.append(
  136. content_type.split("charset=")[1].split(";")[0].strip())
  137. # Then append default Radicale charset
  138. charsets.append(self.encoding)
  139. # Then append various fallbacks
  140. charsets.append("utf-8")
  141. charsets.append("iso8859-1")
  142. # Try to decode
  143. for charset in charsets:
  144. try:
  145. return text.decode(charset)
  146. except UnicodeDecodeError:
  147. pass
  148. raise UnicodeDecodeError
  149. def collect_allowed_items(self, items, user):
  150. """Get items from request that user is allowed to access."""
  151. read_allowed_items = []
  152. write_allowed_items = []
  153. for item in items:
  154. if isinstance(item, self.Collection):
  155. path = item.path
  156. else:
  157. path = item.collection.path
  158. if self.authorized(user, path, "r"):
  159. self.logger.debug(
  160. "%s has read access to collection %s" %
  161. (user or "Anonymous", path or "/"))
  162. read_allowed_items.append(item)
  163. else:
  164. self.logger.debug(
  165. "%s has NO read access to collection %s" %
  166. (user or "Anonymous", path or "/"))
  167. if self.authorized(user, path, "w"):
  168. self.logger.debug(
  169. "%s has write access to collection %s" %
  170. (user or "Anonymous", path or "/"))
  171. write_allowed_items.append(item)
  172. else:
  173. self.logger.debug(
  174. "%s has NO write access to collection %s" %
  175. (user or "Anonymous", path or "/"))
  176. return read_allowed_items, write_allowed_items
  177. def __call__(self, environ, start_response):
  178. """Manage a request."""
  179. def response(status, headers={}, answer=None):
  180. # Start response
  181. status = "%i %s" % (
  182. status, client.responses.get(status, "Unknown"))
  183. self.logger.debug("Answer status: %s" % status)
  184. start_response(status, list(headers.items()))
  185. # Return response content
  186. return [answer] if answer else []
  187. self.logger.debug("\n") # Add empty lines between requests in debug
  188. self.logger.info("%s request at %s received" % (
  189. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  190. headers = pprint.pformat(self.headers_log(environ))
  191. self.logger.debug("Request headers:\n%s" % headers)
  192. # Strip base_prefix from request URI
  193. base_prefix = self.configuration.get("server", "base_prefix")
  194. if environ["PATH_INFO"].startswith(base_prefix):
  195. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  196. elif self.configuration.get("server", "can_skip_base_prefix"):
  197. self.logger.debug(
  198. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  199. else:
  200. # Request path not starting with base_prefix, not allowed
  201. self.logger.debug(
  202. "Path not starting with prefix: %s", environ["PATH_INFO"])
  203. return response(*NOT_ALLOWED)
  204. # Sanitize request URI
  205. environ["PATH_INFO"] = storage.sanitize_path(
  206. unquote(environ["PATH_INFO"]))
  207. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  208. path = environ["PATH_INFO"]
  209. # Get function corresponding to method
  210. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  211. # Ask authentication backend to check rights
  212. authorization = environ.get("HTTP_AUTHORIZATION", None)
  213. if authorization and authorization.startswith("Basic"):
  214. authorization = authorization[len("Basic"):].strip()
  215. user, password = self.decode(base64.b64decode(
  216. authorization.encode("ascii")), environ).split(":", 1)
  217. else:
  218. user = environ.get("REMOTE_USER")
  219. password = None
  220. # If "/.well-known" is not available, clients query "/"
  221. if path == "/.well-known" or path.startswith("/.well-known/"):
  222. return response(client.NOT_FOUND, {})
  223. if user and not storage.is_safe_path_component(user):
  224. # Prevent usernames like "user/calendar.ics"
  225. self.logger.info("Refused unsafe username: %s", user)
  226. is_authenticated = False
  227. else:
  228. is_authenticated = self.is_authenticated(user, password)
  229. is_valid_user = is_authenticated or not user
  230. # Create principal collection
  231. if user and is_authenticated:
  232. principal_path = "/%s/" % user
  233. if self.authorized(user, principal_path, "w"):
  234. with self._lock_collection("r", user):
  235. principal = next(
  236. self.Collection.discover(principal_path, depth="1"),
  237. None)
  238. if not principal:
  239. with self._lock_collection("w", user):
  240. self.Collection.create_collection(principal_path)
  241. # Verify content length
  242. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  243. if content_length:
  244. max_content_length = self.configuration.getint(
  245. "server", "max_content_length")
  246. if max_content_length and content_length > max_content_length:
  247. self.logger.debug(
  248. "Request body too large: %d", content_length)
  249. return response(client.REQUEST_ENTITY_TOO_LARGE)
  250. if is_valid_user:
  251. try:
  252. status, headers, answer = function(environ, path, user)
  253. except socket.timeout:
  254. return response(client.REQUEST_TIMEOUT)
  255. else:
  256. status, headers, answer = NOT_ALLOWED
  257. if (status, headers, answer) == NOT_ALLOWED and not (
  258. user and is_authenticated):
  259. # Unknown or unauthorized user
  260. self.logger.info("%s refused" % (user or "Anonymous user"))
  261. status = client.UNAUTHORIZED
  262. realm = self.configuration.get("server", "realm")
  263. headers = {
  264. "WWW-Authenticate":
  265. "Basic realm=\"%s\"" % realm}
  266. answer = None
  267. # Set content length
  268. if answer:
  269. self.logger.debug("Response content:\n%s" % answer, environ)
  270. answer = answer.encode(self.encoding)
  271. accept_encoding = [
  272. encoding.strip() for encoding in
  273. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  274. if encoding.strip()]
  275. if "gzip" in accept_encoding:
  276. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  277. answer = zcomp.compress(answer) + zcomp.flush()
  278. headers["Content-Encoding"] = "gzip"
  279. headers["Content-Length"] = str(len(answer))
  280. # Add extra headers set in configuration
  281. if self.configuration.has_section("headers"):
  282. for key in self.configuration.options("headers"):
  283. headers[key] = self.configuration.get("headers", key)
  284. return response(status, headers, answer)
  285. def _access(self, user, path, permission, item=None):
  286. """Check if ``user`` can access ``path`` or the parent collection.
  287. ``permission`` must either be "r" or "w".
  288. If ``item`` is given, only access to that class of item is checked.
  289. """
  290. path = storage.sanitize_path(path)
  291. parent_path = storage.sanitize_path(
  292. "/%s/" % posixpath.dirname(path.strip("/")))
  293. allowed = False
  294. if not item or isinstance(item, self.Collection):
  295. allowed |= self.authorized(user, path, permission)
  296. if not item or not isinstance(item, self.Collection):
  297. allowed |= self.authorized(user, parent_path, permission)
  298. return allowed
  299. @contextmanager
  300. def _lock_collection(self, lock_mode, user):
  301. """Lock the collection with ``permission`` and execute hook."""
  302. with self.Collection.acquire_lock(lock_mode) as value:
  303. yield value
  304. hook = self.configuration.get("storage", "hook")
  305. if lock_mode == "w" and hook:
  306. self.logger.debug("Running hook")
  307. folder = os.path.expanduser(self.configuration.get(
  308. "storage", "filesystem_folder"))
  309. subprocess.check_call(
  310. hook % {"user": shlex.quote(user or "Anonymous")},
  311. shell=True, cwd=folder)
  312. def _read_content(self, environ):
  313. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  314. if content_length > 0:
  315. content = self.decode(
  316. environ["wsgi.input"].read(content_length), environ)
  317. self.logger.debug("Request content:\n%s" % content.strip())
  318. else:
  319. content = None
  320. return content
  321. def do_DELETE(self, environ, path, user):
  322. """Manage DELETE request."""
  323. if not self._access(user, path, "w"):
  324. return NOT_ALLOWED
  325. with self._lock_collection("w", user):
  326. item = next(self.Collection.discover(path), None)
  327. if not self._access(user, path, "w", item):
  328. return NOT_ALLOWED
  329. if not item:
  330. return client.GONE, {}, None
  331. if_match = environ.get("HTTP_IF_MATCH", "*")
  332. if if_match not in ("*", item.etag):
  333. # ETag precondition not verified, do not delete item
  334. return client.PRECONDITION_FAILED, {}, None
  335. if isinstance(item, self.Collection):
  336. answer = xmlutils.delete(path, item)
  337. else:
  338. answer = xmlutils.delete(path, item.collection, item.href)
  339. return client.OK, {}, answer
  340. def do_GET(self, environ, path, user):
  341. """Manage GET request."""
  342. # Display a "Radicale works!" message if the root URL is requested
  343. if not path.strip("/"):
  344. headers = {"Content-type": "text/html"}
  345. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  346. return client.OK, headers, answer
  347. if not self._access(user, path, "r"):
  348. return NOT_ALLOWED
  349. with self._lock_collection("r", user):
  350. item = next(self.Collection.discover(path), None)
  351. if not self._access(user, path, "r", item):
  352. return NOT_ALLOWED
  353. if not item:
  354. return client.NOT_FOUND, {}, None
  355. if isinstance(item, self.Collection):
  356. collection = item
  357. else:
  358. collection = item.collection
  359. content_type = xmlutils.MIMETYPES.get(
  360. collection.get_meta("tag"), "text/plain")
  361. headers = {
  362. "Content-Type": content_type,
  363. "Last-Modified": collection.last_modified,
  364. "ETag": item.etag}
  365. answer = item.serialize()
  366. return client.OK, headers, answer
  367. def do_HEAD(self, environ, path, user):
  368. """Manage HEAD request."""
  369. status, headers, answer = self.do_GET(environ, path, user)
  370. return status, headers, None
  371. def do_MKCALENDAR(self, environ, path, user):
  372. """Manage MKCALENDAR request."""
  373. if not self.authorized(user, path, "w"):
  374. return NOT_ALLOWED
  375. content = self._read_content(environ)
  376. with self._lock_collection("w", user):
  377. item = next(self.Collection.discover(path), None)
  378. if item:
  379. return client.CONFLICT, {}, None
  380. props = xmlutils.props_from_request(content)
  381. props["tag"] = "VCALENDAR"
  382. # TODO: use this?
  383. # timezone = props.get("C:calendar-timezone")
  384. self.Collection.create_collection(path, props=props)
  385. return client.CREATED, {}, None
  386. def do_MKCOL(self, environ, path, user):
  387. """Manage MKCOL request."""
  388. if not self.authorized(user, path, "w"):
  389. return NOT_ALLOWED
  390. content = self._read_content(environ)
  391. with self._lock_collection("w", user):
  392. item = next(self.Collection.discover(path), None)
  393. if item:
  394. return client.CONFLICT, {}, None
  395. props = xmlutils.props_from_request(content)
  396. self.Collection.create_collection(path, props=props)
  397. return client.CREATED, {}, None
  398. def do_MOVE(self, environ, path, user):
  399. """Manage MOVE request."""
  400. to_url = urlparse(environ["HTTP_DESTINATION"])
  401. if to_url.netloc != environ["HTTP_HOST"]:
  402. # Remote destination server, not supported
  403. return client.BAD_GATEWAY, {}, None
  404. if not self._access(user, path, "w"):
  405. return NOT_ALLOWED
  406. to_path = storage.sanitize_path(to_url.path)
  407. if not self._access(user, to_path, "w"):
  408. return NOT_ALLOWED
  409. with self._lock_collection("w", user):
  410. item = next(self.Collection.discover(path), None)
  411. if not self._access(user, path, "w", item):
  412. return NOT_ALLOWED
  413. if not self._access(user, to_path, "w", item):
  414. return NOT_ALLOWED
  415. if not item:
  416. return client.GONE, {}, None
  417. if isinstance(item, self.Collection):
  418. return client.CONFLICT, {}, None
  419. to_item = next(self.Collection.discover(to_path), None)
  420. if (isinstance(to_item, self.Collection) or
  421. to_item and environ.get("HTTP_OVERWRITE", "F") != "T"):
  422. return client.CONFLICT, {}, None
  423. to_parent_path = storage.sanitize_path(
  424. "/%s/" % posixpath.dirname(to_path.strip("/")))
  425. to_collection = next(
  426. self.Collection.discover(to_parent_path), None)
  427. if not to_collection:
  428. return client.CONFLICT, {}, None
  429. to_href = posixpath.basename(to_path.strip("/"))
  430. self.Collection.move(item, to_collection, to_href)
  431. return client.CREATED, {}, None
  432. def do_OPTIONS(self, environ, path, user):
  433. """Manage OPTIONS request."""
  434. headers = {
  435. "Allow": ", ".join(
  436. name[3:] for name in dir(self) if name.startswith("do_")),
  437. "DAV": DAV_HEADERS}
  438. return client.OK, headers, None
  439. def do_PROPFIND(self, environ, path, user):
  440. """Manage PROPFIND request."""
  441. if not self._access(user, path, "r"):
  442. return NOT_ALLOWED
  443. content = self._read_content(environ)
  444. with self._lock_collection("r", user):
  445. items = self.Collection.discover(
  446. path, environ.get("HTTP_DEPTH", "0"))
  447. read_items, write_items = self.collect_allowed_items(items, user)
  448. if not read_items and not write_items:
  449. return (client.NOT_FOUND, {}, None) if user else NOT_ALLOWED
  450. headers = {"DAV": DAV_HEADERS, "Content-Type": "text/xml"}
  451. answer = xmlutils.propfind(
  452. path, content, read_items, write_items, user)
  453. return client.MULTI_STATUS, headers, answer
  454. def do_PROPPATCH(self, environ, path, user):
  455. """Manage PROPPATCH request."""
  456. if not self.authorized(user, path, "w"):
  457. return NOT_ALLOWED
  458. content = self._read_content(environ)
  459. with self._lock_collection("w", user):
  460. item = next(self.Collection.discover(path), None)
  461. if not isinstance(item, self.Collection):
  462. return client.CONFLICT, {}, None
  463. headers = {"DAV": DAV_HEADERS, "Content-Type": "text/xml"}
  464. answer = xmlutils.proppatch(path, content, item)
  465. return client.MULTI_STATUS, headers, answer
  466. def do_PUT(self, environ, path, user):
  467. """Manage PUT request."""
  468. if not self._access(user, path, "w"):
  469. return NOT_ALLOWED
  470. content = self._read_content(environ)
  471. with self._lock_collection("w", user):
  472. parent_path = storage.sanitize_path(
  473. "/%s/" % posixpath.dirname(path.strip("/")))
  474. item = next(self.Collection.discover(path), None)
  475. parent_item = next(self.Collection.discover(parent_path), None)
  476. write_whole_collection = (
  477. isinstance(item, self.Collection) or
  478. not parent_item or (
  479. not next(parent_item.list(), None) and
  480. parent_item.get_meta("tag") not in (
  481. "VADDRESSBOOK", "VCALENDAR")))
  482. if write_whole_collection:
  483. if not self.authorized(user, path, "w"):
  484. return NOT_ALLOWED
  485. elif not self.authorized(user, parent_path, "w"):
  486. return NOT_ALLOWED
  487. etag = environ.get("HTTP_IF_MATCH", "")
  488. if not item and etag:
  489. # Etag asked but no item found: item has been removed
  490. return client.PRECONDITION_FAILED, {}, None
  491. if item and etag and item.etag != etag:
  492. # Etag asked but item not matching: item has changed
  493. return client.PRECONDITION_FAILED, {}, None
  494. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  495. if item and match:
  496. # Creation asked but item found: item can't be replaced
  497. return client.PRECONDITION_FAILED, {}, None
  498. items = list(vobject.readComponents(content or ""))
  499. content_type = environ.get("CONTENT_TYPE", "").split(";")[0]
  500. tags = {value: key for key, value in xmlutils.MIMETYPES.items()}
  501. tag = tags.get(content_type)
  502. if write_whole_collection:
  503. new_item = self.Collection.create_collection(
  504. path, items, {"tag": tag})
  505. else:
  506. if tag:
  507. parent_item.set_meta({"tag": tag})
  508. href = posixpath.basename(path.strip("/"))
  509. if item:
  510. new_item = parent_item.update(href, items[0])
  511. else:
  512. new_item = parent_item.upload(href, items[0])
  513. headers = {"ETag": new_item.etag}
  514. return client.CREATED, headers, None
  515. def do_REPORT(self, environ, path, user):
  516. """Manage REPORT request."""
  517. if not self._access(user, path, "w"):
  518. return NOT_ALLOWED
  519. content = self._read_content(environ)
  520. with self._lock_collection("r", user):
  521. item = next(self.Collection.discover(path), None)
  522. if not self._access(user, path, "w", item):
  523. return NOT_ALLOWED
  524. if not item:
  525. return client.NOT_FOUND, {}, None
  526. if isinstance(item, self.Collection):
  527. collection = item
  528. else:
  529. collection = item.collection
  530. headers = {"Content-Type": "text/xml"}
  531. answer = xmlutils.report(path, content, collection)
  532. return client.MULTI_STATUS, headers, answer