__init__.py 24 KB

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