__init__.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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, object):
  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 = {
  218. "WWW-Authenticate":
  219. "Basic realm=\"%s\"" % realm}
  220. self.logger.info(
  221. "Refused /.well-known/ redirection to anonymous user")
  222. else:
  223. status = client.SEE_OTHER
  224. self.logger.info("/.well-known/ redirection to: %s" % redirect)
  225. headers = {"Location": redirect}
  226. status = "%i %s" % (
  227. status, client.responses.get(status, "Unknown"))
  228. start_response(status, list(headers.items()))
  229. return []
  230. is_authenticated = self.is_authenticated(user, password)
  231. is_valid_user = is_authenticated or not user
  232. if is_valid_user:
  233. items = self.Collection.discover(
  234. path, environ.get("HTTP_DEPTH", "0"))
  235. read_allowed_items, write_allowed_items = (
  236. self.collect_allowed_items(items, user))
  237. else:
  238. read_allowed_items, write_allowed_items = None, None
  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 and (
  248. (read_allowed_items or write_allowed_items) or
  249. (is_authenticated and function == self.do_PROPFIND) or
  250. function == self.do_OPTIONS):
  251. status, headers, answer = function(
  252. environ, read_allowed_items, write_allowed_items, content,
  253. user)
  254. else:
  255. status, headers, answer = NOT_ALLOWED
  256. if (status, headers, answer) == NOT_ALLOWED and not is_authenticated:
  257. # Unknown or unauthorized user
  258. self.logger.info("%s refused" % (user or "Anonymous user"))
  259. status = client.UNAUTHORIZED
  260. realm = self.configuration.get("server", "realm")
  261. headers = {
  262. "WWW-Authenticate":
  263. "Basic realm=\"%s\"" % realm}
  264. answer = None
  265. # Set content length
  266. if answer:
  267. self.logger.debug("Response content:\n%s" % answer, environ)
  268. answer = answer.encode(self.encoding)
  269. headers["Content-Length"] = str(len(answer))
  270. if self.configuration.has_section("headers"):
  271. for key in self.configuration.options("headers"):
  272. headers[key] = self.configuration.get("headers", key)
  273. # Start response
  274. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  275. self.logger.debug("Answer status: %s" % status)
  276. start_response(status, list(headers.items()))
  277. # Return response content
  278. return [answer] if answer else []
  279. # All these functions must have the same parameters, some are useless
  280. # pylint: disable=W0612,W0613,R0201
  281. def do_DELETE(self, environ, read_collections, write_collections, content,
  282. user):
  283. """Manage DELETE request."""
  284. if not write_collections:
  285. return NOT_ALLOWED
  286. collection = write_collections[0]
  287. if collection.path == environ["PATH_INFO"].strip("/"):
  288. # Path matching the collection, the collection must be deleted
  289. item = collection
  290. else:
  291. # Try to get an item matching the path
  292. name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  293. item = collection.get(name)
  294. if item:
  295. if_match = environ.get("HTTP_IF_MATCH", "*")
  296. if if_match in ("*", item.etag):
  297. # No ETag precondition or precondition verified, delete item
  298. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  299. return client.OK, {}, answer
  300. # No item or ETag precondition not verified, do not delete item
  301. return client.PRECONDITION_FAILED, {}, None
  302. def do_GET(self, environ, read_collections, write_collections, content,
  303. user):
  304. """Manage GET request."""
  305. # Display a "Radicale works!" message if the root URL is requested
  306. if environ["PATH_INFO"] == "/":
  307. headers = {"Content-type": "text/html"}
  308. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  309. return client.OK, headers, answer
  310. if not read_collections:
  311. return NOT_ALLOWED
  312. collection = read_collections[0]
  313. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  314. if item_name:
  315. # Get collection item
  316. item = collection.get(item_name)
  317. if item:
  318. answer_text = item.serialize()
  319. etag = item.etag
  320. else:
  321. return client.NOT_FOUND, {}, None
  322. else:
  323. # Get whole collection
  324. answer_text = collection.serialize()
  325. if not answer_text:
  326. self.logger.debug("Collection at %s unknown" % environ["PATH_INFO"])
  327. return client.NOT_FOUND, {}, None
  328. etag = collection.etag
  329. headers = {
  330. "Content-Type": storage.MIMETYPES[collection.get_meta("tag")],
  331. "Last-Modified": collection.last_modified,
  332. "ETag": etag}
  333. answer = answer_text
  334. return client.OK, headers, answer
  335. def do_HEAD(self, environ, read_collections, write_collections, content,
  336. user):
  337. """Manage HEAD request."""
  338. status, headers, answer = self.do_GET(
  339. environ, read_collections, write_collections, content, user)
  340. return status, headers, None
  341. def do_MKCALENDAR(self, environ, read_collections, write_collections,
  342. content, user):
  343. """Manage MKCALENDAR request."""
  344. if not write_collections:
  345. return NOT_ALLOWED
  346. collection = write_collections[0]
  347. props = xmlutils.props_from_request(content)
  348. # TODO: use this?
  349. # timezone = props.get("C:calendar-timezone")
  350. collection = self.Collection.create_collection(
  351. environ["PATH_INFO"], tag="VCALENDAR")
  352. for key, value in props.items():
  353. collection.set_meta(key, value)
  354. return client.CREATED, {}, None
  355. def do_MKCOL(self, environ, read_collections, write_collections, content,
  356. user):
  357. """Manage MKCOL request."""
  358. if not write_collections:
  359. return NOT_ALLOWED
  360. collection = write_collections[0]
  361. props = xmlutils.props_from_request(content)
  362. collection = self.Collection.create_collection(environ["PATH_INFO"])
  363. for key, value in props.items():
  364. collection.set_meta(key, value)
  365. return client.CREATED, {}, None
  366. def do_MOVE(self, environ, read_collections, write_collections, content,
  367. user):
  368. """Manage MOVE request."""
  369. if not write_collections:
  370. return NOT_ALLOWED
  371. from_collection = write_collections[0]
  372. from_name = xmlutils.name_from_path(
  373. environ["PATH_INFO"], from_collection)
  374. item = from_collection.get(from_name)
  375. if item:
  376. # Move the item
  377. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  378. if to_url_parts.netloc == environ["HTTP_HOST"]:
  379. to_url = to_url_parts.path
  380. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  381. for to_collection in self.Collection.discover(
  382. to_path, depth="0"):
  383. if to_collection in write_collections:
  384. to_collection.upload(to_name, item)
  385. from_collection.delete(from_name)
  386. return client.CREATED, {}, None
  387. else:
  388. return NOT_ALLOWED
  389. else:
  390. # Remote destination server, not supported
  391. return client.BAD_GATEWAY, {}, None
  392. else:
  393. # No item found
  394. return client.GONE, {}, None
  395. def do_OPTIONS(self, environ, read_collections, write_collections,
  396. content, user):
  397. """Manage OPTIONS request."""
  398. headers = {
  399. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  400. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  401. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  402. return client.OK, headers, None
  403. def do_PROPFIND(self, environ, read_collections, write_collections,
  404. content, user):
  405. """Manage PROPFIND request."""
  406. if not read_collections:
  407. return client.NOT_FOUND, {}, None
  408. headers = {
  409. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  410. "Content-Type": "text/xml"}
  411. answer = xmlutils.propfind(
  412. environ["PATH_INFO"], content, read_collections, write_collections, user)
  413. return client.MULTI_STATUS, headers, answer
  414. def do_PROPPATCH(self, environ, read_collections, write_collections,
  415. content, user):
  416. """Manage PROPPATCH request."""
  417. if not write_collections:
  418. return NOT_ALLOWED
  419. collection = write_collections[0]
  420. answer = xmlutils.proppatch(environ["PATH_INFO"], content, collection)
  421. headers = {
  422. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  423. "Content-Type": "text/xml"}
  424. return client.MULTI_STATUS, headers, answer
  425. def do_PUT(self, environ, read_collections, write_collections, content,
  426. user):
  427. """Manage PUT request."""
  428. if not write_collections:
  429. return NOT_ALLOWED
  430. collection = write_collections[0]
  431. content_type = environ.get("CONTENT_TYPE")
  432. if content_type:
  433. tags = {value: key for key, value in storage.MIMETYPES.items()}
  434. collection.set_meta("tag", tags[content_type.split(";")[0]])
  435. headers = {}
  436. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  437. item = collection.get(item_name)
  438. etag = environ.get("HTTP_IF_MATCH", "")
  439. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  440. if (not item and not etag) or (
  441. item and ((etag or item.etag) == item.etag) and not match):
  442. # PUT allowed in 3 cases
  443. # Case 1: No item and no ETag precondition: Add new item
  444. # Case 2: Item and ETag precondition verified: Modify item
  445. # Case 3: Item and no Etag precondition: Force modifying item
  446. items = list(vobject.readComponents(content))
  447. if items:
  448. if item:
  449. # PUT is modifying an existing item
  450. new_item = collection.update(item_name, items[0])
  451. elif item_name:
  452. # PUT is adding a new item
  453. new_item = collection.upload(item_name, items[0])
  454. else:
  455. # PUT is replacing the whole collection
  456. collection.delete()
  457. new_item = self.Collection.create_collection(
  458. environ["PATH_INFO"], items)
  459. if new_item:
  460. headers["ETag"] = new_item.etag
  461. status = client.CREATED
  462. else:
  463. # PUT rejected in all other cases
  464. status = client.PRECONDITION_FAILED
  465. return status, headers, None
  466. def do_REPORT(self, environ, read_collections, write_collections, content,
  467. user):
  468. """Manage REPORT request."""
  469. if not read_collections:
  470. return NOT_ALLOWED
  471. collection = read_collections[0]
  472. headers = {"Content-Type": "text/xml"}
  473. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  474. return client.MULTI_STATUS, headers, answer
  475. # pylint: enable=W0612,W0613,R0201