__init__.py 24 KB

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