__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 pprint
  28. import shlex
  29. import socket
  30. import socketserver
  31. import ssl
  32. import subprocess
  33. import threading
  34. import wsgiref.simple_server
  35. import zlib
  36. from http import client
  37. from urllib.parse import unquote, urlparse
  38. import vobject
  39. from . import auth, rights, storage, xmlutils
  40. VERSION = "2.0.0rc0"
  41. # Standard "not allowed" response that is returned when an authenticated user
  42. # tries to access information they don't have rights to
  43. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  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 credentials
  120. if (self.configuration.getboolean("logging", "mask_passwords") and
  121. request_environ.get("HTTP_AUTHORIZATION",
  122. "").startswith("Basic")):
  123. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  124. return request_environ
  125. def decode(self, text, environ):
  126. """Try to magically decode ``text`` according to given ``environ``."""
  127. # List of charsets to try
  128. charsets = []
  129. # First append content charset given in the request
  130. content_type = environ.get("CONTENT_TYPE")
  131. if content_type and "charset=" in content_type:
  132. charsets.append(
  133. content_type.split("charset=")[1].split(";")[0].strip())
  134. # Then append default Radicale charset
  135. charsets.append(self.encoding)
  136. # Then append various fallbacks
  137. charsets.append("utf-8")
  138. charsets.append("iso8859-1")
  139. # Try to decode
  140. for charset in charsets:
  141. try:
  142. return text.decode(charset)
  143. except UnicodeDecodeError:
  144. pass
  145. raise UnicodeDecodeError
  146. def collect_allowed_items(self, items, user):
  147. """Get items from request that user is allowed to access."""
  148. read_last_collection_allowed = None
  149. write_last_collection_allowed = None
  150. read_allowed_items = []
  151. write_allowed_items = []
  152. for item in items:
  153. if isinstance(item, self.Collection):
  154. if self.authorized(user, item, "r"):
  155. self.logger.debug(
  156. "%s has read access to collection %s" %
  157. (user or "Anonymous", item.path or "/"))
  158. read_last_collection_allowed = True
  159. read_allowed_items.append(item)
  160. else:
  161. self.logger.debug(
  162. "%s has NO read access to collection %s" %
  163. (user or "Anonymous", item.path or "/"))
  164. read_last_collection_allowed = False
  165. if self.authorized(user, item, "w"):
  166. self.logger.debug(
  167. "%s has write access to collection %s" %
  168. (user or "Anonymous", item.path or "/"))
  169. write_last_collection_allowed = True
  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", item.path or "/"))
  175. write_last_collection_allowed = False
  176. else:
  177. # item is not a collection, it's the child of the last
  178. # collection we've met in the loop. Only add this item
  179. # if this last collection was allowed.
  180. if read_last_collection_allowed:
  181. self.logger.debug(
  182. "%s has read access to item %s" %
  183. (user or "Anonymous", item.href))
  184. read_allowed_items.append(item)
  185. else:
  186. self.logger.debug(
  187. "%s has NO read access to item %s" %
  188. (user or "Anonymous", item.href))
  189. if write_last_collection_allowed:
  190. self.logger.debug(
  191. "%s has write access to item %s" %
  192. (user or "Anonymous", item.href))
  193. write_allowed_items.append(item)
  194. else:
  195. self.logger.debug(
  196. "%s has NO write access to item %s" %
  197. (user or "Anonymous", item.href))
  198. return read_allowed_items, write_allowed_items
  199. def __call__(self, environ, start_response):
  200. """Manage a request."""
  201. def response(status, headers={}, answer=None):
  202. # Start response
  203. status = "%i %s" % (
  204. status, client.responses.get(status, "Unknown"))
  205. self.logger.debug("Answer status: %s" % status)
  206. start_response(status, list(headers.items()))
  207. # Return response content
  208. return [answer] if answer else []
  209. self.logger.info("%s request at %s received" % (
  210. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  211. headers = pprint.pformat(self.headers_log(environ))
  212. self.logger.debug("Request headers:\n%s" % headers)
  213. # Strip base_prefix from request URI
  214. base_prefix = self.configuration.get("server", "base_prefix")
  215. if environ["PATH_INFO"].startswith(base_prefix):
  216. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  217. elif self.configuration.get("server", "can_skip_base_prefix"):
  218. self.logger.debug(
  219. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  220. else:
  221. # Request path not starting with base_prefix, not allowed
  222. self.logger.debug(
  223. "Path not starting with prefix: %s", environ["PATH_INFO"])
  224. return response(*NOT_ALLOWED)
  225. # Sanitize request URI
  226. environ["PATH_INFO"] = storage.sanitize_path(
  227. unquote(environ["PATH_INFO"]))
  228. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  229. path = environ["PATH_INFO"]
  230. # Get function corresponding to method
  231. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  232. # Ask authentication backend to check rights
  233. authorization = environ.get("HTTP_AUTHORIZATION", None)
  234. if authorization and authorization.startswith("Basic"):
  235. authorization = authorization[len("Basic"):].strip()
  236. user, password = self.decode(base64.b64decode(
  237. authorization.encode("ascii")), environ).split(":", 1)
  238. else:
  239. user = environ.get("REMOTE_USER")
  240. password = None
  241. # If /.well-known is not available, clients query /
  242. if path == "/.well-known" or path.startswith("/.well-known/"):
  243. return response(client.NOT_FOUND, {})
  244. if user and not storage.is_safe_path_component(user):
  245. # Prevent usernames like "user/calendar.ics"
  246. self.logger.info("Refused unsafe username: %s", user)
  247. is_authenticated = False
  248. else:
  249. is_authenticated = self.is_authenticated(user, password)
  250. is_valid_user = is_authenticated or not user
  251. # Create principal collection
  252. if user and is_authenticated:
  253. principal_path = "/%s/" % user
  254. collection = self.Collection(principal_path, True)
  255. if self.authorized(user, collection, "w"):
  256. with self.Collection.acquire_lock("r"):
  257. principal = next(
  258. self.Collection.discover(principal_path), None)
  259. if not principal or principal.path != user:
  260. with self.Collection.acquire_lock("w"):
  261. self.Collection.create_collection(principal_path)
  262. # Get content
  263. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  264. if content_length:
  265. max_content_length = self.configuration.getint(
  266. "server", "max_content_length")
  267. if max_content_length and content_length > max_content_length:
  268. self.logger.debug(
  269. "Request body too large: %d", content_length)
  270. return response(client.REQUEST_ENTITY_TOO_LARGE)
  271. try:
  272. content = self.decode(
  273. environ["wsgi.input"].read(content_length), environ)
  274. except socket.timeout:
  275. return response(client.REQUEST_TIMEOUT)
  276. self.logger.debug("Request content:\n%s" % content)
  277. else:
  278. content = None
  279. if is_valid_user:
  280. if function in (
  281. self.do_GET, self.do_HEAD, self.do_OPTIONS,
  282. self.do_PROPFIND, self.do_REPORT):
  283. lock_mode = "r"
  284. else:
  285. lock_mode = "w"
  286. with self.Collection.acquire_lock(lock_mode):
  287. items = self.Collection.discover(
  288. path, environ.get("HTTP_DEPTH", "0"))
  289. read_allowed_items, write_allowed_items = (
  290. self.collect_allowed_items(items, user))
  291. if (read_allowed_items or write_allowed_items or
  292. is_authenticated and function == self.do_PROPFIND or
  293. function == self.do_OPTIONS):
  294. status, headers, answer = function(
  295. environ, read_allowed_items, write_allowed_items,
  296. content, user)
  297. hook = self.configuration.get("storage", "hook")
  298. if lock_mode == "w" and hook:
  299. self.logger.debug("Running hook")
  300. folder = os.path.expanduser(
  301. self.configuration.get(
  302. "storage", "filesystem_folder"))
  303. subprocess.check_call(
  304. hook % {"user": shlex.quote(user or "Anonymous")},
  305. shell=True, cwd=folder)
  306. else:
  307. status, headers, answer = NOT_ALLOWED
  308. else:
  309. status, headers, answer = NOT_ALLOWED
  310. if (status, headers, answer) == NOT_ALLOWED and not (
  311. user and is_authenticated):
  312. # Unknown or unauthorized user
  313. self.logger.info("%s refused" % (user or "Anonymous user"))
  314. status = client.UNAUTHORIZED
  315. realm = self.configuration.get("server", "realm")
  316. headers = {
  317. "WWW-Authenticate":
  318. "Basic realm=\"%s\"" % realm}
  319. answer = None
  320. # Set content length
  321. if answer:
  322. self.logger.debug("Response content:\n%s" % answer, environ)
  323. answer = answer.encode(self.encoding)
  324. accept_encoding = [
  325. encoding.strip() for encoding in
  326. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  327. if encoding.strip()]
  328. if "gzip" in accept_encoding:
  329. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  330. answer = zcomp.compress(answer) + zcomp.flush()
  331. headers["Content-Encoding"] = "gzip"
  332. headers["Content-Length"] = str(len(answer))
  333. if self.configuration.has_section("headers"):
  334. for key in self.configuration.options("headers"):
  335. headers[key] = self.configuration.get("headers", key)
  336. return response(status, headers, answer)
  337. def do_DELETE(self, environ, read_collections, write_collections, content,
  338. user):
  339. """Manage DELETE request."""
  340. if not write_collections:
  341. return NOT_ALLOWED
  342. collection = write_collections[0]
  343. if collection.path == environ["PATH_INFO"].strip("/"):
  344. # Path matching the collection, the collection must be deleted
  345. item = collection
  346. else:
  347. # Try to get an item matching the path
  348. name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  349. item = collection.get(name)
  350. if item:
  351. if_match = environ.get("HTTP_IF_MATCH", "*")
  352. if if_match in ("*", item.etag):
  353. # No ETag precondition or precondition verified, delete item
  354. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  355. return client.OK, {}, answer
  356. # No item or ETag precondition not verified, do not delete item
  357. return client.PRECONDITION_FAILED, {}, None
  358. def do_GET(self, environ, read_collections, write_collections, content,
  359. user):
  360. """Manage GET request."""
  361. # Display a "Radicale works!" message if the root URL is requested
  362. if environ["PATH_INFO"] == "/":
  363. headers = {"Content-type": "text/html"}
  364. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  365. return client.OK, headers, answer
  366. if not read_collections:
  367. return NOT_ALLOWED
  368. collection = read_collections[0]
  369. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  370. if item_name:
  371. # Get collection item
  372. item = collection.get(item_name)
  373. if item:
  374. answer = item.serialize()
  375. etag = item.etag
  376. else:
  377. return client.NOT_FOUND, {}, None
  378. else:
  379. # Get whole collection
  380. answer = collection.serialize()
  381. if answer is None:
  382. return client.NOT_FOUND, {}, None
  383. else:
  384. etag = collection.etag
  385. if answer:
  386. headers = {
  387. "Content-Type": storage.MIMETYPES[collection.get_meta("tag")],
  388. "Last-Modified": collection.last_modified,
  389. "ETag": etag}
  390. else:
  391. headers = {}
  392. return client.OK, headers, answer
  393. def do_HEAD(self, environ, read_collections, write_collections, content,
  394. user):
  395. """Manage HEAD request."""
  396. status, headers, answer = self.do_GET(
  397. environ, read_collections, write_collections, content, user)
  398. return status, headers, None
  399. def do_MKCALENDAR(self, environ, read_collections, write_collections,
  400. content, user):
  401. """Manage MKCALENDAR request."""
  402. if not write_collections:
  403. return NOT_ALLOWED
  404. collection = write_collections[0]
  405. props = xmlutils.props_from_request(content)
  406. props["tag"] = "VCALENDAR"
  407. # TODO: use this?
  408. # timezone = props.get("C:calendar-timezone")
  409. collection = self.Collection.create_collection(
  410. environ["PATH_INFO"], props=props)
  411. return client.CREATED, {}, None
  412. def do_MKCOL(self, environ, read_collections, write_collections, content,
  413. user):
  414. """Manage MKCOL request."""
  415. if not write_collections:
  416. return NOT_ALLOWED
  417. collection = write_collections[0]
  418. props = xmlutils.props_from_request(content)
  419. collection = self.Collection.create_collection(
  420. environ["PATH_INFO"], props=props)
  421. return client.CREATED, {}, None
  422. def do_MOVE(self, environ, read_collections, write_collections, content,
  423. user):
  424. """Manage MOVE request."""
  425. if not write_collections:
  426. return NOT_ALLOWED
  427. from_collection = write_collections[0]
  428. from_name = xmlutils.name_from_path(
  429. environ["PATH_INFO"], from_collection)
  430. item = from_collection.get(from_name)
  431. if item:
  432. # Move the item
  433. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  434. if to_url_parts.netloc == environ["HTTP_HOST"]:
  435. to_url = to_url_parts.path
  436. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  437. for to_collection in self.Collection.discover(
  438. to_path, depth="0"):
  439. if to_collection in write_collections:
  440. to_collection.upload(to_name, item)
  441. from_collection.delete(from_name)
  442. return client.CREATED, {}, None
  443. else:
  444. return NOT_ALLOWED
  445. else:
  446. # Remote destination server, not supported
  447. return client.BAD_GATEWAY, {}, None
  448. else:
  449. # No item found
  450. return client.GONE, {}, None
  451. def do_OPTIONS(self, environ, read_collections, write_collections,
  452. content, user):
  453. """Manage OPTIONS request."""
  454. headers = {
  455. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  456. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  457. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  458. return client.OK, headers, None
  459. def do_PROPFIND(self, environ, read_collections, write_collections,
  460. content, user):
  461. """Manage PROPFIND request."""
  462. if not read_collections:
  463. return (client.NOT_FOUND, {}, None) if user else NOT_ALLOWED
  464. headers = {
  465. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  466. "Content-Type": "text/xml"}
  467. answer = xmlutils.propfind(
  468. environ["PATH_INFO"], content, read_collections, write_collections,
  469. user)
  470. return client.MULTI_STATUS, headers, answer
  471. def do_PROPPATCH(self, environ, read_collections, write_collections,
  472. content, user):
  473. """Manage PROPPATCH request."""
  474. if not write_collections:
  475. return NOT_ALLOWED
  476. collection = write_collections[0]
  477. answer = xmlutils.proppatch(environ["PATH_INFO"], content, collection)
  478. headers = {
  479. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  480. "Content-Type": "text/xml"}
  481. return client.MULTI_STATUS, headers, answer
  482. def do_PUT(self, environ, read_collections, write_collections, content,
  483. user):
  484. """Manage PUT request."""
  485. if not write_collections:
  486. return NOT_ALLOWED
  487. collection = write_collections[0]
  488. content_type = environ.get("CONTENT_TYPE")
  489. if content_type:
  490. tags = {value: key for key, value in storage.MIMETYPES.items()}
  491. tag = tags.get(content_type.split(";")[0])
  492. if tag:
  493. collection.set_meta({"tag": tag})
  494. headers = {}
  495. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  496. item = collection.get(item_name)
  497. etag = environ.get("HTTP_IF_MATCH", "")
  498. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  499. if (not item and not etag) or (
  500. item and ((etag or item.etag) == item.etag) and not match):
  501. # PUT allowed in 3 cases
  502. # Case 1: No item and no ETag precondition: Add new item
  503. # Case 2: Item and ETag precondition verified: Modify item
  504. # Case 3: Item and no Etag precondition: Force modifying item
  505. items = list(vobject.readComponents(content or ""))
  506. if item:
  507. # PUT is modifying an existing item
  508. if items:
  509. new_item = collection.update(item_name, items[0])
  510. else:
  511. new_item = None
  512. elif item_name:
  513. # PUT is adding a new item
  514. if items:
  515. new_item = collection.upload(item_name, items[0])
  516. else:
  517. new_item = None
  518. else:
  519. # PUT is replacing the whole collection
  520. collection.delete()
  521. new_item = self.Collection.create_collection(
  522. environ["PATH_INFO"], items)
  523. if new_item:
  524. headers["ETag"] = new_item.etag
  525. status = client.CREATED
  526. else:
  527. # PUT rejected in all other cases
  528. status = client.PRECONDITION_FAILED
  529. return status, headers, None
  530. def do_REPORT(self, environ, read_collections, write_collections, content,
  531. user):
  532. """Manage REPORT request."""
  533. if not read_collections:
  534. return NOT_ALLOWED
  535. collection = read_collections[0]
  536. headers = {"Content-Type": "text/xml"}
  537. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  538. return client.MULTI_STATUS, headers, answer