__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. def headers_log(self, environ):
  92. """Sanitize headers for logging."""
  93. request_environ = dict(environ)
  94. # Remove environment variables
  95. if not self.configuration.getboolean("logging", "full_environment"):
  96. for shell_variable in os.environ:
  97. request_environ.pop(shell_variable, None)
  98. # Mask credentials
  99. if (self.configuration.getboolean("logging", "mask_passwords") and
  100. request_environ.get("HTTP_AUTHORIZATION",
  101. "").startswith("Basic")):
  102. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  103. return request_environ
  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. self.logger.info("%s request at %s received" % (
  181. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  182. headers = pprint.pformat(self.headers_log(environ))
  183. self.logger.debug("Request headers:\n%s" % headers)
  184. # Strip base_prefix from request URI
  185. base_prefix = self.configuration.get("server", "base_prefix")
  186. if environ["PATH_INFO"].startswith(base_prefix):
  187. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  188. elif self.configuration.get("server", "can_skip_base_prefix"):
  189. self.logger.debug(
  190. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  191. else:
  192. # Request path not starting with base_prefix, not allowed
  193. self.logger.debug(
  194. "Path not starting with prefix: %s", environ["PATH_INFO"])
  195. status, headers, _ = NOT_ALLOWED
  196. start_response(status, list(headers.items()))
  197. return []
  198. # Sanitize request URI
  199. environ["PATH_INFO"] = storage.sanitize_path(
  200. unquote(environ["PATH_INFO"]))
  201. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  202. path = environ["PATH_INFO"]
  203. # Get function corresponding to method
  204. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  205. # Ask authentication backend to check rights
  206. authorization = environ.get("HTTP_AUTHORIZATION", None)
  207. if authorization and authorization.startswith("Basic"):
  208. authorization = authorization[len("Basic"):].strip()
  209. user, password = self.decode(base64.b64decode(
  210. authorization.encode("ascii")), environ).split(":", 1)
  211. else:
  212. user = environ.get("REMOTE_USER")
  213. password = None
  214. well_known = WELL_KNOWN_RE.match(path)
  215. if well_known:
  216. redirect = self.configuration.get(
  217. "well-known", well_known.group(1))
  218. try:
  219. redirect = redirect % ({"user": user} if user else {})
  220. except KeyError:
  221. status = client.UNAUTHORIZED
  222. realm = self.configuration.get("server", "realm")
  223. headers = {"WWW-Authenticate": "Basic realm=\"%s\"" % realm}
  224. self.logger.info(
  225. "Refused /.well-known/ redirection to anonymous user")
  226. else:
  227. status = client.SEE_OTHER
  228. self.logger.info("/.well-known/ redirection to: %s" % redirect)
  229. headers = {"Location": redirect}
  230. status = "%i %s" % (
  231. status, client.responses.get(status, "Unknown"))
  232. start_response(status, list(headers.items()))
  233. return []
  234. is_authenticated = self.is_authenticated(user, password)
  235. is_valid_user = is_authenticated or not user
  236. # Get content
  237. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  238. if content_length:
  239. content = self.decode(
  240. environ["wsgi.input"].read(content_length), environ)
  241. self.logger.debug("Request content:\n%s" % content)
  242. else:
  243. content = None
  244. if is_valid_user:
  245. if function in (self.do_GET, self.do_HEAD,
  246. self.do_OPTIONS, self.do_PROPFIND,
  247. self.do_REPORT):
  248. lock_mode = "r"
  249. else:
  250. lock_mode = "w"
  251. with self.Collection.acquire_lock(lock_mode):
  252. items = self.Collection.discover(
  253. path, environ.get("HTTP_DEPTH", "0"))
  254. read_allowed_items, write_allowed_items = (
  255. self.collect_allowed_items(items, user))
  256. if (read_allowed_items or write_allowed_items or
  257. is_authenticated and function == self.do_PROPFIND or
  258. function == self.do_OPTIONS):
  259. status, headers, answer = function(
  260. environ, read_allowed_items, write_allowed_items,
  261. content, user)
  262. else:
  263. status, headers, answer = NOT_ALLOWED
  264. else:
  265. status, headers, answer = NOT_ALLOWED
  266. if (status, headers, answer) == NOT_ALLOWED and not is_authenticated:
  267. # Unknown or unauthorized user
  268. self.logger.info("%s refused" % (user or "Anonymous user"))
  269. status = client.UNAUTHORIZED
  270. realm = self.configuration.get("server", "realm")
  271. headers = {
  272. "WWW-Authenticate":
  273. "Basic realm=\"%s\"" % realm}
  274. answer = None
  275. # Set content length
  276. if answer:
  277. self.logger.debug("Response content:\n%s" % answer, environ)
  278. answer = answer.encode(self.encoding)
  279. accept_encoding = [
  280. encoding.strip() for encoding in
  281. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  282. if encoding.strip()]
  283. if "gzip" in accept_encoding:
  284. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  285. answer = zcomp.compress(answer) + zcomp.flush()
  286. headers["Content-Encoding"] = "gzip"
  287. headers["Content-Length"] = str(len(answer))
  288. if self.configuration.has_section("headers"):
  289. for key in self.configuration.options("headers"):
  290. headers[key] = self.configuration.get("headers", key)
  291. # Start response
  292. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  293. self.logger.debug("Answer status: %s" % status)
  294. start_response(status, list(headers.items()))
  295. # Return response content
  296. return [answer] if answer else []
  297. # All these functions must have the same parameters, some are useless
  298. # pylint: disable=W0612,W0613,R0201
  299. def do_DELETE(self, environ, read_collections, write_collections, content,
  300. user):
  301. """Manage DELETE request."""
  302. if not write_collections:
  303. return NOT_ALLOWED
  304. collection = write_collections[0]
  305. if collection.path == environ["PATH_INFO"].strip("/"):
  306. # Path matching the collection, the collection must be deleted
  307. item = collection
  308. else:
  309. # Try to get an item matching the path
  310. name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  311. item = collection.get(name)
  312. if item:
  313. if_match = environ.get("HTTP_IF_MATCH", "*")
  314. if if_match in ("*", item.etag):
  315. # No ETag precondition or precondition verified, delete item
  316. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  317. return client.OK, {}, answer
  318. # No item or ETag precondition not verified, do not delete item
  319. return client.PRECONDITION_FAILED, {}, None
  320. def do_GET(self, environ, read_collections, write_collections, content,
  321. user):
  322. """Manage GET request."""
  323. # Display a "Radicale works!" message if the root URL is requested
  324. if environ["PATH_INFO"] == "/":
  325. headers = {"Content-type": "text/html"}
  326. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  327. return client.OK, headers, answer
  328. if not read_collections:
  329. return NOT_ALLOWED
  330. collection = read_collections[0]
  331. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  332. if item_name:
  333. # Get collection item
  334. item = collection.get(item_name)
  335. if item:
  336. answer = item.serialize()
  337. etag = item.etag
  338. else:
  339. return client.NOT_FOUND, {}, None
  340. else:
  341. # Get whole collection
  342. answer = collection.serialize()
  343. etag = collection.etag
  344. if answer:
  345. headers = {
  346. "Content-Type": storage.MIMETYPES[collection.get_meta("tag")],
  347. "Last-Modified": collection.last_modified,
  348. "ETag": etag}
  349. else:
  350. headers = {}
  351. return client.OK, headers, answer
  352. def do_HEAD(self, environ, read_collections, write_collections, content,
  353. user):
  354. """Manage HEAD request."""
  355. status, headers, answer = self.do_GET(
  356. environ, read_collections, write_collections, content, user)
  357. return status, headers, None
  358. def do_MKCALENDAR(self, environ, read_collections, write_collections,
  359. content, user):
  360. """Manage MKCALENDAR request."""
  361. if not write_collections:
  362. return NOT_ALLOWED
  363. collection = write_collections[0]
  364. props = xmlutils.props_from_request(content)
  365. # TODO: use this?
  366. # timezone = props.get("C:calendar-timezone")
  367. collection = self.Collection.create_collection(
  368. environ["PATH_INFO"], tag="VCALENDAR")
  369. for key, value in props.items():
  370. collection.set_meta(key, value)
  371. return client.CREATED, {}, None
  372. def do_MKCOL(self, environ, read_collections, write_collections, content,
  373. user):
  374. """Manage MKCOL request."""
  375. if not write_collections:
  376. return NOT_ALLOWED
  377. collection = write_collections[0]
  378. props = xmlutils.props_from_request(content)
  379. collection = self.Collection.create_collection(environ["PATH_INFO"])
  380. for key, value in props.items():
  381. collection.set_meta(key, value)
  382. return client.CREATED, {}, None
  383. def do_MOVE(self, environ, read_collections, write_collections, content,
  384. user):
  385. """Manage MOVE request."""
  386. if not write_collections:
  387. return NOT_ALLOWED
  388. from_collection = write_collections[0]
  389. from_name = xmlutils.name_from_path(
  390. environ["PATH_INFO"], from_collection)
  391. item = from_collection.get(from_name)
  392. if item:
  393. # Move the item
  394. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  395. if to_url_parts.netloc == environ["HTTP_HOST"]:
  396. to_url = to_url_parts.path
  397. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  398. for to_collection in self.Collection.discover(
  399. to_path, depth="0"):
  400. if to_collection in write_collections:
  401. to_collection.upload(to_name, item)
  402. from_collection.delete(from_name)
  403. return client.CREATED, {}, None
  404. else:
  405. return NOT_ALLOWED
  406. else:
  407. # Remote destination server, not supported
  408. return client.BAD_GATEWAY, {}, None
  409. else:
  410. # No item found
  411. return client.GONE, {}, None
  412. def do_OPTIONS(self, environ, read_collections, write_collections,
  413. content, user):
  414. """Manage OPTIONS request."""
  415. headers = {
  416. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  417. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  418. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  419. return client.OK, headers, None
  420. def do_PROPFIND(self, environ, read_collections, write_collections,
  421. content, user):
  422. """Manage PROPFIND request."""
  423. if not read_collections:
  424. return client.NOT_FOUND, {}, None
  425. headers = {
  426. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  427. "Content-Type": "text/xml"}
  428. answer = xmlutils.propfind(
  429. environ["PATH_INFO"], content, read_collections, write_collections,
  430. user)
  431. return client.MULTI_STATUS, headers, answer
  432. def do_PROPPATCH(self, environ, read_collections, write_collections,
  433. content, user):
  434. """Manage PROPPATCH request."""
  435. if not write_collections:
  436. return NOT_ALLOWED
  437. collection = write_collections[0]
  438. answer = xmlutils.proppatch(environ["PATH_INFO"], content, collection)
  439. headers = {
  440. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  441. "Content-Type": "text/xml"}
  442. return client.MULTI_STATUS, headers, answer
  443. def do_PUT(self, environ, read_collections, write_collections, content,
  444. user):
  445. """Manage PUT request."""
  446. if not write_collections:
  447. return NOT_ALLOWED
  448. collection = write_collections[0]
  449. content_type = environ.get("CONTENT_TYPE")
  450. if content_type:
  451. tags = {value: key for key, value in storage.MIMETYPES.items()}
  452. tag = tags.get(content_type.split(";")[0])
  453. if tag:
  454. collection.set_meta("tag", tag)
  455. headers = {}
  456. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  457. item = collection.get(item_name)
  458. etag = environ.get("HTTP_IF_MATCH", "")
  459. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  460. if (not item and not etag) or (
  461. item and ((etag or item.etag) == item.etag) and not match):
  462. # PUT allowed in 3 cases
  463. # Case 1: No item and no ETag precondition: Add new item
  464. # Case 2: Item and ETag precondition verified: Modify item
  465. # Case 3: Item and no Etag precondition: Force modifying item
  466. items = list(vobject.readComponents(content or ""))
  467. if item:
  468. # PUT is modifying an existing item
  469. if items:
  470. new_item = collection.update(item_name, items[0])
  471. else:
  472. new_item = None
  473. elif item_name:
  474. # PUT is adding a new item
  475. if items:
  476. new_item = collection.upload(item_name, items[0])
  477. else:
  478. new_item = None
  479. else:
  480. # PUT is replacing the whole collection
  481. collection.delete()
  482. new_item = self.Collection.create_collection(
  483. environ["PATH_INFO"], items)
  484. if new_item:
  485. headers["ETag"] = new_item.etag
  486. status = client.CREATED
  487. else:
  488. # PUT rejected in all other cases
  489. status = client.PRECONDITION_FAILED
  490. return status, headers, None
  491. def do_REPORT(self, environ, read_collections, write_collections, content,
  492. user):
  493. """Manage REPORT request."""
  494. if not read_collections:
  495. return NOT_ALLOWED
  496. collection = read_collections[0]
  497. headers = {"Content-Type": "text/xml"}
  498. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  499. return client.MULTI_STATUS, headers, answer
  500. # pylint: enable=W0612,W0613,R0201