__init__.py 21 KB

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