__init__.py 24 KB

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