__init__.py 25 KB

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