__init__.py 22 KB

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