__init__.py 22 KB

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