__init__.py 22 KB

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