1
0

__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. # Standard "not allowed" response that is returned when an authenticated user
  44. # tries to access information they don't have rights to
  45. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  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 credentials
  122. if (self.configuration.getboolean("logging", "mask_passwords") and
  123. request_environ.get("HTTP_AUTHORIZATION",
  124. "").startswith("Basic")):
  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.info("%s request at %s received" % (
  187. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  188. headers = pprint.pformat(self.headers_log(environ))
  189. self.logger.debug("Request headers:\n%s" % headers)
  190. # Strip base_prefix from request URI
  191. base_prefix = self.configuration.get("server", "base_prefix")
  192. if environ["PATH_INFO"].startswith(base_prefix):
  193. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  194. elif self.configuration.get("server", "can_skip_base_prefix"):
  195. self.logger.debug(
  196. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  197. else:
  198. # Request path not starting with base_prefix, not allowed
  199. self.logger.debug(
  200. "Path not starting with prefix: %s", environ["PATH_INFO"])
  201. return response(*NOT_ALLOWED)
  202. # Sanitize request URI
  203. environ["PATH_INFO"] = storage.sanitize_path(
  204. unquote(environ["PATH_INFO"]))
  205. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  206. path = environ["PATH_INFO"]
  207. # Get function corresponding to method
  208. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  209. # Ask authentication backend to check rights
  210. authorization = environ.get("HTTP_AUTHORIZATION", None)
  211. if authorization and authorization.startswith("Basic"):
  212. authorization = authorization[len("Basic"):].strip()
  213. user, password = self.decode(base64.b64decode(
  214. authorization.encode("ascii")), environ).split(":", 1)
  215. else:
  216. user = environ.get("REMOTE_USER")
  217. password = None
  218. # If /.well-known is not available, clients query /
  219. if path == "/.well-known" or path.startswith("/.well-known/"):
  220. return response(client.NOT_FOUND, {})
  221. if user and not storage.is_safe_path_component(user):
  222. # Prevent usernames like "user/calendar.ics"
  223. self.logger.info("Refused unsafe username: %s", user)
  224. is_authenticated = False
  225. else:
  226. is_authenticated = self.is_authenticated(user, password)
  227. is_valid_user = is_authenticated or not user
  228. # Create principal collection
  229. if user and is_authenticated:
  230. principal_path = "/%s/" % user
  231. if self.authorized(user, principal_path, "w"):
  232. with self.Collection.acquire_lock("r"):
  233. principal = next(
  234. self.Collection.discover(principal_path), None)
  235. if not principal:
  236. with self.Collection.acquire_lock("w"):
  237. self.Collection.create_collection(principal_path)
  238. # Get content
  239. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  240. if content_length:
  241. max_content_length = self.configuration.getint(
  242. "server", "max_content_length")
  243. if max_content_length and content_length > max_content_length:
  244. self.logger.debug(
  245. "Request body too large: %d", content_length)
  246. return response(client.REQUEST_ENTITY_TOO_LARGE)
  247. try:
  248. content = self.decode(
  249. environ["wsgi.input"].read(content_length), environ)
  250. except socket.timeout:
  251. return response(client.REQUEST_TIMEOUT)
  252. self.logger.debug("Request content:\n%s" % content)
  253. else:
  254. content = None
  255. if is_valid_user:
  256. status, headers, answer = function(environ, path, content, user)
  257. else:
  258. status, headers, answer = NOT_ALLOWED
  259. if (status, headers, answer) == NOT_ALLOWED and not (
  260. user and is_authenticated):
  261. # Unknown or unauthorized user
  262. self.logger.info("%s refused" % (user or "Anonymous user"))
  263. status = client.UNAUTHORIZED
  264. realm = self.configuration.get("server", "realm")
  265. headers = {
  266. "WWW-Authenticate":
  267. "Basic realm=\"%s\"" % realm}
  268. answer = None
  269. # Set content length
  270. if answer:
  271. self.logger.debug("Response content:\n%s" % answer, environ)
  272. answer = answer.encode(self.encoding)
  273. accept_encoding = [
  274. encoding.strip() for encoding in
  275. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  276. if encoding.strip()]
  277. if "gzip" in accept_encoding:
  278. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  279. answer = zcomp.compress(answer) + zcomp.flush()
  280. headers["Content-Encoding"] = "gzip"
  281. headers["Content-Length"] = str(len(answer))
  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. """Checks if ``user`` can access ``path`` or the parent collection
  288. with ``permission``.
  289. ``permission`` must either be "r" or "w".
  290. If ``item`` is given, only access to that class of item is checked.
  291. """
  292. path = storage.sanitize_path(path)
  293. parent_path = storage.sanitize_path(
  294. "/%s/" % posixpath.dirname(path.strip("/")))
  295. allowed = False
  296. if not item or isinstance(item, self.Collection):
  297. allowed |= self.authorized(user, path, permission)
  298. if not item or not isinstance(item, self.Collection):
  299. allowed |= self.authorized(user, parent_path, permission)
  300. return allowed
  301. @contextmanager
  302. def _lock_collection(self, lock_mode, user):
  303. """Lock the collection with ``permission`` and execute hook."""
  304. with self.Collection.acquire_lock(lock_mode) as value:
  305. yield value
  306. hook = self.configuration.get("storage", "hook")
  307. if lock_mode == "w" and hook:
  308. self.logger.debug("Running hook")
  309. folder = os.path.expanduser(self.configuration.get(
  310. "storage", "filesystem_folder"))
  311. subprocess.check_call(
  312. hook % {"user": shlex.quote(user or "Anonymous")},
  313. shell=True, cwd=folder)
  314. def do_DELETE(self, environ, path, content, user):
  315. """Manage DELETE request."""
  316. if not self._access(user, path, "w"):
  317. return NOT_ALLOWED
  318. with self._lock_collection("w", user):
  319. item = next(self.Collection.discover(path, depth="0"), None)
  320. if not self._access(user, path, "w", item):
  321. return NOT_ALLOWED
  322. if not item:
  323. return client.GONE, {}, None
  324. if_match = environ.get("HTTP_IF_MATCH", "*")
  325. if if_match not in ("*", item.etag):
  326. # ETag precondition not verified, do not delete item
  327. return client.PRECONDITION_FAILED, {}, None
  328. if isinstance(item, self.Collection):
  329. answer = xmlutils.delete(path, item)
  330. else:
  331. answer = xmlutils.delete(path, item.collection, item.href)
  332. return client.OK, {}, answer
  333. def do_GET(self, environ, path, content, user):
  334. """Manage GET request."""
  335. # Display a "Radicale works!" message if the root URL is requested
  336. if not path.strip("/"):
  337. headers = {"Content-type": "text/html"}
  338. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  339. return client.OK, headers, answer
  340. if not self._access(user, path, "r"):
  341. return NOT_ALLOWED
  342. with self._lock_collection("r", user):
  343. item = next(self.Collection.discover(path, depth="0"), None)
  344. if not self._access(user, path, "r", item):
  345. return NOT_ALLOWED
  346. if not item:
  347. return client.NOT_FOUND, {}, None
  348. if isinstance(item, self.Collection):
  349. collection = item
  350. else:
  351. collection = item.collection
  352. content_type = storage.MIMETYPES.get(collection.get_meta("tag"),
  353. "text/plain")
  354. headers = {
  355. "Content-Type": content_type,
  356. "Last-Modified": collection.last_modified,
  357. "ETag": item.etag}
  358. answer = item.serialize()
  359. return client.OK, headers, answer
  360. def do_HEAD(self, environ, path, content, user):
  361. """Manage HEAD request."""
  362. status, headers, answer = self.do_GET(environ, path, content, user)
  363. return status, headers, None
  364. def do_MKCALENDAR(self, environ, path, content, user):
  365. """Manage MKCALENDAR request."""
  366. if not self.authorized(user, path, "w"):
  367. return NOT_ALLOWED
  368. with self._lock_collection("w", user):
  369. item = next(self.Collection.discover(path, depth="0"), None)
  370. if item:
  371. return client.CONFLICT, {}, None
  372. props = xmlutils.props_from_request(content)
  373. props["tag"] = "VCALENDAR"
  374. # TODO: use this?
  375. # timezone = props.get("C:calendar-timezone")
  376. self.Collection.create_collection(path, props=props)
  377. return client.CREATED, {}, None
  378. def do_MKCOL(self, environ, path, content, user):
  379. """Manage MKCOL request."""
  380. if not self.authorized(user, path, "w"):
  381. return NOT_ALLOWED
  382. with self._lock_collection("w", user):
  383. item = next(self.Collection.discover(path, depth="0"), None)
  384. if item:
  385. return client.CONFLICT, {}, None
  386. props = xmlutils.props_from_request(content)
  387. collection = self.Collection.create_collection(path, props=props)
  388. for key, value in props.items():
  389. collection.set_meta(key, value)
  390. return client.CREATED, {}, None
  391. def do_MOVE(self, environ, path, content, user):
  392. """Manage MOVE request."""
  393. to_url = urlparse(environ["HTTP_DESTINATION"])
  394. if to_url.netloc != environ["HTTP_HOST"]:
  395. # Remote destination server, not supported
  396. return client.BAD_GATEWAY, {}, None
  397. to_path = storage.sanitize_path(to_url.path)
  398. if (not self._access(user, path, "w") or
  399. not self._access(user, to_path, "w")):
  400. return NOT_ALLOWED
  401. with self._lock_collection("w", user):
  402. item = next(self.Collection.discover(path, depth="0"), None)
  403. if (not self._access(user, path, "w", item) or
  404. not self._access(user, to_path, "w", item)):
  405. return NOT_ALLOWED
  406. if not item:
  407. return client.GONE, {}, None
  408. to_item = next(self.Collection.discover(to_path, depth="0"), None)
  409. to_parent_path = storage.sanitize_path(
  410. "/%s/" % posixpath.dirname(to_path.strip("/")))
  411. to_href = posixpath.basename(to_path.strip("/"))
  412. to_collection = next(self.Collection.discover(
  413. to_parent_path, depth="0"), None)
  414. print(path, isinstance(item, self.Collection))
  415. if (isinstance(item, self.Collection) or not to_collection or
  416. to_item or to_path.strip("/").startswith(path.strip("/"))):
  417. return client.CONFLICT, {}, None
  418. to_collection.upload(to_href, item.item)
  419. item.collection.delete(item.href)
  420. return client.CREATED, {}, None
  421. def do_OPTIONS(self, environ, path, content, user):
  422. """Manage OPTIONS request."""
  423. headers = {
  424. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  425. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  426. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  427. return client.OK, headers, None
  428. def do_PROPFIND(self, environ, path, content, user):
  429. """Manage PROPFIND request."""
  430. with self._lock_collection("r", user):
  431. items = self.Collection.discover(path,
  432. environ.get("HTTP_DEPTH", "0"))
  433. read_items, write_items = self.collect_allowed_items(items, user)
  434. if not read_items and not write_items:
  435. return (client.NOT_FOUND, {}, None) if user else NOT_ALLOWED
  436. headers = {
  437. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  438. "Content-Type": "text/xml"}
  439. answer = xmlutils.propfind(
  440. path, content, read_items, write_items, user)
  441. return client.MULTI_STATUS, headers, answer
  442. def do_PROPPATCH(self, environ, path, content, user):
  443. """Manage PROPPATCH request."""
  444. if not self.authorized(user, path, "w"):
  445. return NOT_ALLOWED
  446. with self._lock_collection("w", user):
  447. item = next(self.Collection.discover(path, depth="0"), None)
  448. if not isinstance(item, self.Collection):
  449. return client.CONFLICT, {}, None
  450. answer = xmlutils.proppatch(path, content, item)
  451. headers = {
  452. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  453. "Content-Type": "text/xml"}
  454. return client.MULTI_STATUS, headers, answer
  455. def do_PUT(self, environ, path, content, user):
  456. """Manage PUT request."""
  457. if not self._access(user, path, "w"):
  458. return NOT_ALLOWED
  459. with self._lock_collection("w", user):
  460. parent_path = storage.sanitize_path(
  461. "/%s/" % posixpath.dirname(path.strip("/")))
  462. item = next(self.Collection.discover(path, depth="0"), None)
  463. parent_item = next(self.Collection.discover(
  464. parent_path, depth="0"), None)
  465. write_whole_collection = (
  466. isinstance(item, self.Collection) or
  467. not parent_item or
  468. not next(parent_item.list(), None) and
  469. parent_item.get_meta("tag") not in (
  470. "VADDRESSBOOK", "VCALENDAR"))
  471. if (write_whole_collection and
  472. not self.authorized(user, path, "w") or
  473. not write_whole_collection and
  474. not self.authorized(user, parent_path, "w")):
  475. return NOT_ALLOWED
  476. etag = environ.get("HTTP_IF_MATCH", "")
  477. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  478. if ((not item and etag) or (item and etag and item.etag != etag) or
  479. (item and match)):
  480. return client.PRECONDITION_FAILED, {}, None
  481. items = list(vobject.readComponents(content or ""))
  482. content_type = environ.get("CONTENT_TYPE")
  483. tag = None
  484. if content_type:
  485. tags = {value: key for key, value in storage.MIMETYPES.items()}
  486. tag = tags.get(content_type.split(";")[0])
  487. if write_whole_collection:
  488. if item:
  489. # Delete old collection
  490. item.delete()
  491. new_item = self.Collection.create_collection(path, items, tag)
  492. else:
  493. if tag:
  494. parent_item.set_meta({"tag": tag})
  495. href = posixpath.basename(path.strip("/"))
  496. if item:
  497. new_item = parent_item.update(href, items[0])
  498. else:
  499. new_item = parent_item.upload(href, items[0])
  500. headers = {"ETag": new_item.etag}
  501. return client.CREATED, headers, None
  502. def do_REPORT(self, environ, path, content, user):
  503. """Manage REPORT request."""
  504. if not self._access(user, path, "w"):
  505. return NOT_ALLOWED
  506. with self._lock_collection("r", user):
  507. item = next(self.Collection.discover(path, depth="0"), None)
  508. if not self._access(user, path, "w", item):
  509. return NOT_ALLOWED
  510. if not item:
  511. return client.NOT_FOUND, {}, None
  512. if isinstance(item, self.Collection):
  513. collection = item
  514. else:
  515. collection = item.collection
  516. headers = {"Content-Type": "text/xml"}
  517. answer = xmlutils.report(path, content, collection)
  518. return client.MULTI_STATUS, headers, answer