__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 socket
  28. import ssl
  29. import wsgiref.simple_server
  30. import re
  31. import zlib
  32. from http import client
  33. from urllib.parse import unquote, urlparse
  34. import vobject
  35. from . import auth, rights, storage, xmlutils
  36. VERSION = "2.0.0-pre"
  37. # Standard "not allowed" response that is returned when an authenticated user
  38. # tries to access information they don't have rights to
  39. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  40. WELL_KNOWN_RE = re.compile(r"/\.well-known/(carddav|caldav)/?$")
  41. class HTTPServer(wsgiref.simple_server.WSGIServer):
  42. """HTTP server."""
  43. def __init__(self, address, handler, bind_and_activate=True):
  44. """Create server."""
  45. ipv6 = ":" in address[0]
  46. if ipv6:
  47. self.address_family = socket.AF_INET6
  48. # Do not bind and activate, as we might change socket options
  49. super().__init__(address, handler, False)
  50. if ipv6:
  51. # Only allow IPv6 connections to the IPv6 socket
  52. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  53. if bind_and_activate:
  54. self.server_bind()
  55. self.server_activate()
  56. class HTTPSServer(HTTPServer):
  57. """HTTPS server."""
  58. # These class attributes must be set before creating instance
  59. certificate = None
  60. key = None
  61. protocol = None
  62. cyphers = None
  63. def __init__(self, address, handler):
  64. """Create server by wrapping HTTP socket in an SSL socket."""
  65. super().__init__(address, handler, bind_and_activate=False)
  66. self.socket = ssl.wrap_socket(
  67. self.socket, self.key, self.certificate, server_side=True,
  68. ssl_version=self.protocol, cyphers=self.cyphers)
  69. self.server_bind()
  70. self.server_activate()
  71. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  72. """HTTP requests handler."""
  73. def log_message(self, *args, **kwargs):
  74. """Disable inner logging management."""
  75. class Application:
  76. """WSGI application managing collections."""
  77. def __init__(self, configuration, logger):
  78. """Initialize application."""
  79. super().__init__()
  80. self.configuration = configuration
  81. self.logger = logger
  82. self.is_authenticated = auth.load(configuration, logger)
  83. self.Collection = storage.load(configuration, logger)
  84. self.authorized = rights.load(configuration, logger)
  85. self.encoding = configuration.get("encoding", "request")
  86. if configuration.getboolean("logging", "full_environment"):
  87. self.headers_log = lambda environ: environ
  88. # This method is overriden in __init__ if full_environment is set
  89. # pylint: disable=E0202
  90. @staticmethod
  91. def headers_log(environ):
  92. """Remove environment variables from the headers for logging."""
  93. request_environ = dict(environ)
  94. for shell_variable in os.environ:
  95. if shell_variable in request_environ:
  96. del request_environ[shell_variable]
  97. return request_environ
  98. # pylint: enable=E0202
  99. def decode(self, text, environ):
  100. """Try to magically decode ``text`` according to given ``environ``."""
  101. # List of charsets to try
  102. charsets = []
  103. # First append content charset given in the request
  104. content_type = environ.get("CONTENT_TYPE")
  105. if content_type and "charset=" in content_type:
  106. charsets.append(
  107. content_type.split("charset=")[1].split(";")[0].strip())
  108. # Then append default Radicale charset
  109. charsets.append(self.encoding)
  110. # Then append various fallbacks
  111. charsets.append("utf-8")
  112. charsets.append("iso8859-1")
  113. # Try to decode
  114. for charset in charsets:
  115. try:
  116. return text.decode(charset)
  117. except UnicodeDecodeError:
  118. pass
  119. raise UnicodeDecodeError
  120. def collect_allowed_items(self, items, user):
  121. """Get items from request that user is allowed to access."""
  122. read_last_collection_allowed = None
  123. write_last_collection_allowed = None
  124. read_allowed_items = []
  125. write_allowed_items = []
  126. for item in items:
  127. if isinstance(item, self.Collection):
  128. if self.authorized(user, item, "r"):
  129. self.logger.debug(
  130. "%s has read access to collection %s" %
  131. (user or "Anonymous", item.path or "/"))
  132. read_last_collection_allowed = True
  133. read_allowed_items.append(item)
  134. else:
  135. self.logger.debug(
  136. "%s has NO read access to collection %s" %
  137. (user or "Anonymous", item.path or "/"))
  138. read_last_collection_allowed = False
  139. if self.authorized(user, item, "w"):
  140. self.logger.debug(
  141. "%s has write access to collection %s" %
  142. (user or "Anonymous", item.path or "/"))
  143. write_last_collection_allowed = True
  144. write_allowed_items.append(item)
  145. else:
  146. self.logger.debug(
  147. "%s has NO write access to collection %s" %
  148. (user or "Anonymous", item.path or "/"))
  149. write_last_collection_allowed = False
  150. else:
  151. # item is not a collection, it's the child of the last
  152. # collection we've met in the loop. Only add this item
  153. # if this last collection was allowed.
  154. if read_last_collection_allowed:
  155. self.logger.debug(
  156. "%s has read access to item %s" %
  157. (user or "Anonymous", item.href))
  158. read_allowed_items.append(item)
  159. else:
  160. self.logger.debug(
  161. "%s has NO read access to item %s" %
  162. (user or "Anonymous", item.href))
  163. if write_last_collection_allowed:
  164. self.logger.debug(
  165. "%s has write access to item %s" %
  166. (user or "Anonymous", item.href))
  167. write_allowed_items.append(item)
  168. else:
  169. self.logger.debug(
  170. "%s has NO write access to item %s" %
  171. (user or "Anonymous", item.href))
  172. return read_allowed_items, write_allowed_items
  173. def __call__(self, environ, start_response):
  174. """Manage a request."""
  175. self.logger.info("%s request at %s received" % (
  176. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  177. headers = pprint.pformat(self.headers_log(environ))
  178. self.logger.debug("Request headers:\n%s" % headers)
  179. # Strip base_prefix from request URI
  180. base_prefix = self.configuration.get("server", "base_prefix")
  181. if environ["PATH_INFO"].startswith(base_prefix):
  182. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  183. elif self.configuration.get("server", "can_skip_base_prefix"):
  184. self.logger.debug(
  185. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  186. else:
  187. # Request path not starting with base_prefix, not allowed
  188. self.logger.debug(
  189. "Path not starting with prefix: %s", environ["PATH_INFO"])
  190. status, headers, _ = NOT_ALLOWED
  191. start_response(status, list(headers.items()))
  192. return []
  193. # Sanitize request URI
  194. environ["PATH_INFO"] = storage.sanitize_path(
  195. unquote(environ["PATH_INFO"]))
  196. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  197. path = environ["PATH_INFO"]
  198. # Get function corresponding to method
  199. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  200. # Ask authentication backend to check rights
  201. authorization = environ.get("HTTP_AUTHORIZATION", None)
  202. if authorization:
  203. authorization = authorization.lstrip("Basic").strip()
  204. user, password = self.decode(base64.b64decode(
  205. authorization.encode("ascii")), environ).split(":", 1)
  206. else:
  207. user = environ.get("REMOTE_USER")
  208. password = None
  209. well_known = WELL_KNOWN_RE.match(path)
  210. if well_known:
  211. redirect = self.configuration.get(
  212. "well-known", well_known.group(1))
  213. try:
  214. redirect = redirect % ({"user": user} if user else {})
  215. except KeyError:
  216. status = client.UNAUTHORIZED
  217. realm = self.configuration.get("server", "realm")
  218. headers = {"WWW-Authenticate": "Basic realm=\"%s\"" % realm}
  219. self.logger.info(
  220. "Refused /.well-known/ redirection to anonymous user")
  221. else:
  222. status = client.SEE_OTHER
  223. self.logger.info("/.well-known/ redirection to: %s" % redirect)
  224. headers = {"Location": redirect}
  225. status = "%i %s" % (
  226. status, client.responses.get(status, "Unknown"))
  227. start_response(status, list(headers.items()))
  228. return []
  229. is_authenticated = self.is_authenticated(user, password)
  230. is_valid_user = is_authenticated or not user
  231. if is_valid_user:
  232. items = self.Collection.discover(
  233. path, environ.get("HTTP_DEPTH", "0"))
  234. read_allowed_items, write_allowed_items = (
  235. self.collect_allowed_items(items, user))
  236. else:
  237. read_allowed_items, write_allowed_items = None, None
  238. # Get content
  239. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  240. if content_length:
  241. content = self.decode(
  242. environ["wsgi.input"].read(content_length), environ)
  243. self.logger.debug("Request content:\n%s" % content)
  244. else:
  245. content = None
  246. if is_valid_user and (
  247. (read_allowed_items or write_allowed_items) or
  248. (is_authenticated and function == self.do_PROPFIND) or
  249. function == self.do_OPTIONS):
  250. status, headers, answer = function(
  251. environ, read_allowed_items, write_allowed_items, content,
  252. user)
  253. else:
  254. status, headers, answer = NOT_ALLOWED
  255. if (status, headers, answer) == NOT_ALLOWED and not is_authenticated:
  256. # Unknown or unauthorized user
  257. self.logger.info("%s refused" % (user or "Anonymous user"))
  258. status = client.UNAUTHORIZED
  259. realm = self.configuration.get("server", "realm")
  260. headers = {
  261. "WWW-Authenticate":
  262. "Basic realm=\"%s\"" % realm}
  263. answer = None
  264. # Set content length
  265. if answer:
  266. self.logger.debug("Response content:\n%s" % answer, environ)
  267. answer = answer.encode(self.encoding)
  268. accept_encoding = [
  269. encoding.strip() for encoding in
  270. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  271. if encoding.strip()]
  272. if "deflate" in accept_encoding:
  273. answer = zlib.compress(answer)
  274. headers["Content-Encoding"] = "deflate"
  275. headers["Content-Length"] = str(len(answer))
  276. if self.configuration.has_section("headers"):
  277. for key in self.configuration.options("headers"):
  278. headers[key] = self.configuration.get("headers", key)
  279. # Start response
  280. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  281. self.logger.debug("Answer status: %s" % status)
  282. start_response(status, list(headers.items()))
  283. # Return response content
  284. return [answer] if answer else []
  285. # All these functions must have the same parameters, some are useless
  286. # pylint: disable=W0612,W0613,R0201
  287. def do_DELETE(self, environ, read_collections, write_collections, content,
  288. user):
  289. """Manage DELETE request."""
  290. if not write_collections:
  291. return NOT_ALLOWED
  292. collection = write_collections[0]
  293. if collection.path == environ["PATH_INFO"].strip("/"):
  294. # Path matching the collection, the collection must be deleted
  295. item = collection
  296. else:
  297. # Try to get an item matching the path
  298. name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  299. item = collection.get(name)
  300. if item:
  301. if_match = environ.get("HTTP_IF_MATCH", "*")
  302. if if_match in ("*", item.etag):
  303. # No ETag precondition or precondition verified, delete item
  304. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  305. return client.OK, {}, answer
  306. # No item or ETag precondition not verified, do not delete item
  307. return client.PRECONDITION_FAILED, {}, None
  308. def do_GET(self, environ, read_collections, write_collections, content,
  309. user):
  310. """Manage GET request."""
  311. # Display a "Radicale works!" message if the root URL is requested
  312. if environ["PATH_INFO"] == "/":
  313. headers = {"Content-type": "text/html"}
  314. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  315. return client.OK, headers, answer
  316. if not read_collections:
  317. return NOT_ALLOWED
  318. collection = read_collections[0]
  319. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  320. if item_name:
  321. # Get collection item
  322. item = collection.get(item_name)
  323. if item:
  324. answer = item.serialize()
  325. etag = item.etag
  326. else:
  327. return client.NOT_FOUND, {}, None
  328. else:
  329. # Get whole collection
  330. answer = collection.serialize()
  331. etag = collection.etag
  332. if answer:
  333. headers = {
  334. "Content-Type": storage.MIMETYPES[collection.get_meta("tag")],
  335. "Last-Modified": collection.last_modified,
  336. "ETag": etag}
  337. else:
  338. headers = {}
  339. return client.OK, headers, answer
  340. def do_HEAD(self, environ, read_collections, write_collections, content,
  341. user):
  342. """Manage HEAD request."""
  343. status, headers, answer = self.do_GET(
  344. environ, read_collections, write_collections, content, user)
  345. return status, headers, None
  346. def do_MKCALENDAR(self, environ, read_collections, write_collections,
  347. content, user):
  348. """Manage MKCALENDAR request."""
  349. if not write_collections:
  350. return NOT_ALLOWED
  351. collection = write_collections[0]
  352. props = xmlutils.props_from_request(content)
  353. # TODO: use this?
  354. # timezone = props.get("C:calendar-timezone")
  355. collection = self.Collection.create_collection(
  356. environ["PATH_INFO"], tag="VCALENDAR")
  357. for key, value in props.items():
  358. collection.set_meta(key, value)
  359. return client.CREATED, {}, None
  360. def do_MKCOL(self, environ, read_collections, write_collections, content,
  361. user):
  362. """Manage MKCOL request."""
  363. if not write_collections:
  364. return NOT_ALLOWED
  365. collection = write_collections[0]
  366. props = xmlutils.props_from_request(content)
  367. collection = self.Collection.create_collection(environ["PATH_INFO"])
  368. for key, value in props.items():
  369. collection.set_meta(key, value)
  370. return client.CREATED, {}, None
  371. def do_MOVE(self, environ, read_collections, write_collections, content,
  372. user):
  373. """Manage MOVE request."""
  374. if not write_collections:
  375. return NOT_ALLOWED
  376. from_collection = write_collections[0]
  377. from_name = xmlutils.name_from_path(
  378. environ["PATH_INFO"], from_collection)
  379. item = from_collection.get(from_name)
  380. if item:
  381. # Move the item
  382. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  383. if to_url_parts.netloc == environ["HTTP_HOST"]:
  384. to_url = to_url_parts.path
  385. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  386. for to_collection in self.Collection.discover(
  387. to_path, depth="0"):
  388. if to_collection in write_collections:
  389. to_collection.upload(to_name, item)
  390. from_collection.delete(from_name)
  391. return client.CREATED, {}, None
  392. else:
  393. return NOT_ALLOWED
  394. else:
  395. # Remote destination server, not supported
  396. return client.BAD_GATEWAY, {}, None
  397. else:
  398. # No item found
  399. return client.GONE, {}, None
  400. def do_OPTIONS(self, environ, read_collections, write_collections,
  401. content, user):
  402. """Manage OPTIONS request."""
  403. headers = {
  404. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  405. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  406. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  407. return client.OK, headers, None
  408. def do_PROPFIND(self, environ, read_collections, write_collections,
  409. content, user):
  410. """Manage PROPFIND request."""
  411. if not read_collections:
  412. return client.NOT_FOUND, {}, None
  413. headers = {
  414. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  415. "Content-Type": "text/xml"}
  416. answer = xmlutils.propfind(
  417. environ["PATH_INFO"], content, read_collections, write_collections,
  418. user)
  419. return client.MULTI_STATUS, headers, answer
  420. def do_PROPPATCH(self, environ, read_collections, write_collections,
  421. content, user):
  422. """Manage PROPPATCH request."""
  423. if not write_collections:
  424. return NOT_ALLOWED
  425. collection = write_collections[0]
  426. answer = xmlutils.proppatch(environ["PATH_INFO"], content, collection)
  427. headers = {
  428. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  429. "Content-Type": "text/xml"}
  430. return client.MULTI_STATUS, headers, answer
  431. def do_PUT(self, environ, read_collections, write_collections, content,
  432. user):
  433. """Manage PUT request."""
  434. if not write_collections:
  435. return NOT_ALLOWED
  436. collection = write_collections[0]
  437. content_type = environ.get("CONTENT_TYPE")
  438. if content_type:
  439. tags = {value: key for key, value in storage.MIMETYPES.items()}
  440. collection.set_meta("tag", tags[content_type.split(";")[0]])
  441. headers = {}
  442. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  443. item = collection.get(item_name)
  444. etag = environ.get("HTTP_IF_MATCH", "")
  445. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  446. if (not item and not etag) or (
  447. item and ((etag or item.etag) == item.etag) and not match):
  448. # PUT allowed in 3 cases
  449. # Case 1: No item and no ETag precondition: Add new item
  450. # Case 2: Item and ETag precondition verified: Modify item
  451. # Case 3: Item and no Etag precondition: Force modifying item
  452. items = list(vobject.readComponents(content))
  453. if items:
  454. if item:
  455. # PUT is modifying an existing item
  456. new_item = collection.update(item_name, items[0])
  457. elif item_name:
  458. # PUT is adding a new item
  459. new_item = collection.upload(item_name, items[0])
  460. else:
  461. # PUT is replacing the whole collection
  462. collection.delete()
  463. new_item = self.Collection.create_collection(
  464. environ["PATH_INFO"], items)
  465. if new_item:
  466. headers["ETag"] = new_item.etag
  467. status = client.CREATED
  468. else:
  469. # PUT rejected in all other cases
  470. status = client.PRECONDITION_FAILED
  471. return status, headers, None
  472. def do_REPORT(self, environ, read_collections, write_collections, content,
  473. user):
  474. """Manage REPORT request."""
  475. if not read_collections:
  476. return NOT_ALLOWED
  477. collection = read_collections[0]
  478. headers = {"Content-Type": "text/xml"}
  479. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  480. return client.MULTI_STATUS, headers, answer
  481. # pylint: enable=W0612,W0613,R0201