__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008 Nicolas Kandel
  5. # Copyright © 2008 Pascal Halter
  6. # Copyright © 2008-2015 Guillaume Ayoub
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Radicale Server module.
  22. This module offers a WSGI application class.
  23. To use this module, you should take a look at the file ``radicale.py`` that
  24. should have been included in this package.
  25. """
  26. import os
  27. import sys
  28. import pprint
  29. import base64
  30. import posixpath
  31. import socket
  32. import ssl
  33. import wsgiref.simple_server
  34. import re
  35. # Manage Python2/3 different modules
  36. # pylint: disable=F0401,E0611
  37. try:
  38. from http import client
  39. from urllib.parse import unquote, urlparse
  40. except ImportError:
  41. import httplib as client
  42. from urllib import unquote
  43. from urlparse import urlparse
  44. # pylint: enable=F0401,E0611
  45. from . import auth, config, ical, log, rights, storage, xmlutils
  46. VERSION = "1.0.1"
  47. # Standard "not allowed" response that is returned when an authenticated user
  48. # tries to access information they don't have rights to
  49. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  50. WELL_KNOWN_RE = re.compile(r"/\.well-known/(carddav|caldav)/?$")
  51. class HTTPServer(wsgiref.simple_server.WSGIServer, object):
  52. """HTTP server."""
  53. def __init__(self, address, handler, bind_and_activate=True):
  54. """Create server."""
  55. ipv6 = ":" in address[0]
  56. if ipv6:
  57. self.address_family = socket.AF_INET6
  58. # Do not bind and activate, as we might change socket options
  59. super(HTTPServer, self).__init__(address, handler, False)
  60. if ipv6:
  61. # Only allow IPv6 connections to the IPv6 socket
  62. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  63. if bind_and_activate:
  64. self.server_bind()
  65. self.server_activate()
  66. class HTTPSServer(HTTPServer):
  67. """HTTPS server."""
  68. def __init__(self, address, handler):
  69. """Create server by wrapping HTTP socket in an SSL socket."""
  70. super(HTTPSServer, self).__init__(address, handler, False)
  71. # Test if the SSL files can be read
  72. for name in ("certificate", "key"):
  73. filename = config.get("server", name)
  74. try:
  75. open(filename, "r").close()
  76. except IOError as exception:
  77. log.LOGGER.warning(
  78. "Error while reading SSL %s %r: %s" % (
  79. name, filename, exception))
  80. ssl_kwargs = dict(
  81. server_side=True,
  82. certfile=config.get("server", "certificate"),
  83. keyfile=config.get("server", "key"),
  84. ssl_version=getattr(
  85. ssl, config.get("server", "protocol"), ssl.PROTOCOL_SSLv23))
  86. # add ciphers argument only if supported (Python 2.7+)
  87. if sys.version_info >= (2, 7):
  88. ssl_kwargs["ciphers"] = config.get("server", "ciphers") or None
  89. self.socket = ssl.wrap_socket(self.socket, **ssl_kwargs)
  90. self.server_bind()
  91. self.server_activate()
  92. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  93. """HTTP requests handler."""
  94. def log_message(self, *args, **kwargs):
  95. """Disable inner logging management."""
  96. def address_string(self):
  97. """Client address, formatted for logging."""
  98. if config.getboolean("server", "dns_lookup"):
  99. return \
  100. wsgiref.simple_server.WSGIRequestHandler.address_string(self)
  101. else:
  102. return self.client_address[0]
  103. class Application(object):
  104. """WSGI application managing collections."""
  105. def __init__(self):
  106. """Initialize application."""
  107. super(Application, self).__init__()
  108. auth.load()
  109. storage.load()
  110. rights.load()
  111. self.encoding = config.get("encoding", "request")
  112. if config.getboolean("logging", "full_environment"):
  113. self.headers_log = lambda environ: environ
  114. # This method is overriden in __init__ if full_environment is set
  115. # pylint: disable=E0202
  116. @staticmethod
  117. def headers_log(environ):
  118. """Remove environment variables from the headers for logging."""
  119. request_environ = dict(environ)
  120. for shell_variable in os.environ:
  121. if shell_variable in request_environ:
  122. del request_environ[shell_variable]
  123. return request_environ
  124. # pylint: enable=E0202
  125. def decode(self, text, environ):
  126. """Try to magically decode ``text`` according to given ``environ``."""
  127. # List of charsets to try
  128. charsets = []
  129. # First append content charset given in the request
  130. content_type = environ.get("CONTENT_TYPE")
  131. if content_type and "charset=" in content_type:
  132. charsets.append(
  133. content_type.split("charset=")[1].split(";")[0].strip())
  134. # Then append default Radicale charset
  135. charsets.append(self.encoding)
  136. # Then append various fallbacks
  137. charsets.append("utf-8")
  138. charsets.append("iso8859-1")
  139. # Try to decode
  140. for charset in charsets:
  141. try:
  142. return text.decode(charset)
  143. except UnicodeDecodeError:
  144. pass
  145. raise UnicodeDecodeError
  146. @staticmethod
  147. def sanitize_uri(uri):
  148. """Unquote and make absolute to prevent access to other data."""
  149. uri = unquote(uri)
  150. trailing_slash = "/" if uri.endswith("/") else ""
  151. uri = posixpath.normpath(uri)
  152. new_uri = "/"
  153. for part in uri.split("/"):
  154. if not part or part in (".", ".."):
  155. continue
  156. new_uri = posixpath.join(new_uri, part)
  157. trailing_slash = "" if new_uri.endswith("/") else trailing_slash
  158. return new_uri + trailing_slash
  159. def collect_allowed_items(self, items, user):
  160. """Get items from request that user is allowed to access."""
  161. read_last_collection_allowed = None
  162. write_last_collection_allowed = None
  163. read_allowed_items = []
  164. write_allowed_items = []
  165. for item in items:
  166. if isinstance(item, ical.Collection):
  167. if rights.authorized(user, item, "r"):
  168. log.LOGGER.debug(
  169. "%s has read access to collection %s" %
  170. (user or "Anonymous", item.url or "/"))
  171. read_last_collection_allowed = True
  172. read_allowed_items.append(item)
  173. else:
  174. log.LOGGER.debug(
  175. "%s has NO read access to collection %s" %
  176. (user or "Anonymous", item.url or "/"))
  177. read_last_collection_allowed = False
  178. if rights.authorized(user, item, "w"):
  179. log.LOGGER.debug(
  180. "%s has write access to collection %s" %
  181. (user or "Anonymous", item.url or "/"))
  182. write_last_collection_allowed = True
  183. write_allowed_items.append(item)
  184. else:
  185. log.LOGGER.debug(
  186. "%s has NO write access to collection %s" %
  187. (user or "Anonymous", item.url or "/"))
  188. write_last_collection_allowed = False
  189. else:
  190. # item is not a collection, it's the child of the last
  191. # collection we've met in the loop. Only add this item
  192. # if this last collection was allowed.
  193. if read_last_collection_allowed:
  194. log.LOGGER.debug(
  195. "%s has read access to item %s" %
  196. (user or "Anonymous", item.name))
  197. read_allowed_items.append(item)
  198. else:
  199. log.LOGGER.debug(
  200. "%s has NO read access to item %s" %
  201. (user or "Anonymous", item.name))
  202. if write_last_collection_allowed:
  203. log.LOGGER.debug(
  204. "%s has write access to item %s" %
  205. (user or "Anonymous", item.name))
  206. write_allowed_items.append(item)
  207. else:
  208. log.LOGGER.debug(
  209. "%s has NO write access to item %s" %
  210. (user or "Anonymous", item.name))
  211. return read_allowed_items, write_allowed_items
  212. def __call__(self, environ, start_response):
  213. """Manage a request."""
  214. log.LOGGER.info("%s request at %s received" % (
  215. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  216. headers = pprint.pformat(self.headers_log(environ))
  217. log.LOGGER.debug("Request headers:\n%s" % headers)
  218. # Strip base_prefix from request URI
  219. base_prefix = config.get("server", "base_prefix")
  220. if environ["PATH_INFO"].startswith(base_prefix):
  221. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  222. elif config.get("server", "can_skip_base_prefix"):
  223. log.LOGGER.debug(
  224. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  225. else:
  226. # Request path not starting with base_prefix, not allowed
  227. log.LOGGER.debug(
  228. "Path not starting with prefix: %s", environ["PATH_INFO"])
  229. environ["PATH_INFO"] = None
  230. # Sanitize request URI
  231. environ["PATH_INFO"] = self.sanitize_uri(environ["PATH_INFO"])
  232. log.LOGGER.debug("Sanitized path: %s", environ["PATH_INFO"])
  233. path = environ["PATH_INFO"]
  234. # Get function corresponding to method
  235. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  236. # Ask authentication backend to check rights
  237. authorization = environ.get("HTTP_AUTHORIZATION", None)
  238. if authorization:
  239. authorization = authorization.lstrip("Basic").strip()
  240. user, password = self.decode(base64.b64decode(
  241. authorization.encode("ascii")), environ).split(":", 1)
  242. else:
  243. user = environ.get("REMOTE_USER")
  244. password = None
  245. well_known = WELL_KNOWN_RE.match(path)
  246. if well_known:
  247. redirect = config.get("well-known", well_known.group(1))
  248. try:
  249. redirect = redirect % ({"user": user} if user else {})
  250. except KeyError:
  251. status = client.UNAUTHORIZED
  252. headers = {
  253. "WWW-Authenticate":
  254. "Basic realm=\"%s\"" % config.get("server", "realm")}
  255. log.LOGGER.info(
  256. "Refused /.well-known/ redirection to anonymous user")
  257. else:
  258. status = client.SEE_OTHER
  259. log.LOGGER.info("/.well-known/ redirection to: %s" % redirect)
  260. if sys.version_info < (3, 0):
  261. redirect = redirect.encode(self.encoding)
  262. headers = {"Location": redirect}
  263. status = "%i %s" % (
  264. status, client.responses.get(status, "Unknown"))
  265. start_response(status, list(headers.items()))
  266. return []
  267. is_authenticated = auth.is_authenticated(user, password)
  268. is_valid_user = is_authenticated or not user
  269. if is_valid_user:
  270. items = ical.Collection.from_path(
  271. path, environ.get("HTTP_DEPTH", "0"))
  272. read_allowed_items, write_allowed_items = \
  273. self.collect_allowed_items(items, user)
  274. else:
  275. read_allowed_items, write_allowed_items = None, None
  276. # Get content
  277. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  278. if content_length:
  279. content = self.decode(
  280. environ["wsgi.input"].read(content_length), environ)
  281. log.LOGGER.debug("Request content:\n%s" % content)
  282. else:
  283. content = None
  284. if is_valid_user and (
  285. (read_allowed_items or write_allowed_items) or
  286. (is_authenticated and function == self.do_PROPFIND) or
  287. function == self.do_OPTIONS):
  288. status, headers, answer = function(
  289. environ, read_allowed_items, write_allowed_items, content,
  290. user)
  291. else:
  292. status, headers, answer = NOT_ALLOWED
  293. if ((status, headers, answer) == NOT_ALLOWED and
  294. not auth.is_authenticated(user, password) and
  295. config.get("auth", "type") != "None"):
  296. # Unknown or unauthorized user
  297. log.LOGGER.info("%s refused" % (user or "Anonymous user"))
  298. status = client.UNAUTHORIZED
  299. headers = {
  300. "WWW-Authenticate":
  301. "Basic realm=\"%s\"" % config.get("server", "realm")}
  302. answer = None
  303. # Set content length
  304. if answer:
  305. log.LOGGER.debug(
  306. "Response content:\n%s" % self.decode(answer, environ))
  307. headers["Content-Length"] = str(len(answer))
  308. if config.has_section("headers"):
  309. for key in config.options("headers"):
  310. headers[key] = config.get("headers", key)
  311. # Start response
  312. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  313. log.LOGGER.debug("Answer status: %s" % status)
  314. start_response(status, list(headers.items()))
  315. # Return response content
  316. return [answer] if answer else []
  317. # All these functions must have the same parameters, some are useless
  318. # pylint: disable=W0612,W0613,R0201
  319. def do_DELETE(self, environ, read_collections, write_collections, content,
  320. user):
  321. """Manage DELETE request."""
  322. if not len(write_collections):
  323. return NOT_ALLOWED
  324. collection = write_collections[0]
  325. if collection.path == environ["PATH_INFO"].strip("/"):
  326. # Path matching the collection, the collection must be deleted
  327. item = collection
  328. else:
  329. # Try to get an item matching the path
  330. name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  331. item = collection.items.get(name)
  332. if item:
  333. # Evolution bug workaround
  334. if_match = environ.get("HTTP_IF_MATCH", "*").replace("\\", "")
  335. if if_match in ("*", item.etag):
  336. # No ETag precondition or precondition verified, delete item
  337. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  338. return client.OK, {}, answer
  339. # No item or ETag precondition not verified, do not delete item
  340. return client.PRECONDITION_FAILED, {}, None
  341. def do_GET(self, environ, read_collections, write_collections, content,
  342. user):
  343. """Manage GET request.
  344. In Radicale, GET requests create collections when the URL is not
  345. available. This is useful for clients with no MKCOL or MKCALENDAR
  346. support.
  347. """
  348. # Display a "Radicale works!" message if the root URL is requested
  349. if environ["PATH_INFO"] == "/":
  350. headers = {"Content-type": "text/html"}
  351. answer = b"<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  352. return client.OK, headers, answer
  353. if not len(read_collections):
  354. return NOT_ALLOWED
  355. collection = read_collections[0]
  356. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  357. if item_name:
  358. # Get collection item
  359. item = collection.items.get(item_name)
  360. if item:
  361. items = [item]
  362. if collection.resource_type == "calendar":
  363. items.extend(collection.timezones)
  364. answer_text = ical.serialize(
  365. collection.tag, collection.headers, items)
  366. etag = item.etag
  367. else:
  368. return client.NOT_FOUND, {}, None
  369. else:
  370. # Create the collection if it does not exist
  371. if not collection.exists:
  372. if collection in write_collections:
  373. log.LOGGER.debug(
  374. "Creating collection %s" % collection.name)
  375. collection.write()
  376. else:
  377. log.LOGGER.debug(
  378. "Collection %s not available and could not be created "
  379. "due to missing write rights" % collection.name)
  380. return NOT_ALLOWED
  381. # Get whole collection
  382. answer_text = collection.text
  383. etag = collection.etag
  384. headers = {
  385. "Content-Type": collection.mimetype,
  386. "Last-Modified": collection.last_modified,
  387. "ETag": etag}
  388. answer = answer_text.encode(self.encoding)
  389. return client.OK, headers, answer
  390. def do_HEAD(self, environ, read_collections, write_collections, content,
  391. user):
  392. """Manage HEAD request."""
  393. status, headers, answer = self.get(
  394. environ, read_collections, write_collections, content, user)
  395. return status, headers, None
  396. def do_MKCALENDAR(self, environ, read_collections, write_collections,
  397. content, user):
  398. """Manage MKCALENDAR request."""
  399. if not len(write_collections):
  400. return NOT_ALLOWED
  401. collection = write_collections[0]
  402. props = xmlutils.props_from_request(content)
  403. timezone = props.get("C:calendar-timezone")
  404. if timezone:
  405. collection.replace("", timezone)
  406. del props["C:calendar-timezone"]
  407. with collection.props as collection_props:
  408. for key, value in props.items():
  409. collection_props[key] = value
  410. collection.write()
  411. return client.CREATED, {}, None
  412. def do_MKCOL(self, environ, read_collections, write_collections, content,
  413. user):
  414. """Manage MKCOL request."""
  415. if not len(write_collections):
  416. return NOT_ALLOWED
  417. collection = write_collections[0]
  418. props = xmlutils.props_from_request(content)
  419. with collection.props as collection_props:
  420. for key, value in props.items():
  421. collection_props[key] = value
  422. collection.write()
  423. return client.CREATED, {}, None
  424. def do_MOVE(self, environ, read_collections, write_collections, content,
  425. user):
  426. """Manage MOVE request."""
  427. if not len(write_collections):
  428. return NOT_ALLOWED
  429. from_collection = write_collections[0]
  430. from_name = xmlutils.name_from_path(
  431. environ["PATH_INFO"], from_collection)
  432. if from_name:
  433. item = from_collection.items.get(from_name)
  434. if item:
  435. # Move the item
  436. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  437. if to_url_parts.netloc == environ["HTTP_HOST"]:
  438. to_url = to_url_parts.path
  439. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  440. to_collection = ical.Collection.from_path(
  441. to_path, depth="0")[0]
  442. if to_collection in write_collections:
  443. to_collection.append(to_name, item.text)
  444. from_collection.remove(from_name)
  445. return client.CREATED, {}, None
  446. else:
  447. return NOT_ALLOWED
  448. else:
  449. # Remote destination server, not supported
  450. return client.BAD_GATEWAY, {}, None
  451. else:
  452. # No item found
  453. return client.GONE, {}, None
  454. else:
  455. # Moving collections, not supported
  456. return client.FORBIDDEN, {}, None
  457. def do_OPTIONS(self, environ, read_collections, write_collections,
  458. content, user):
  459. """Manage OPTIONS request."""
  460. headers = {
  461. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  462. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  463. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  464. return client.OK, headers, None
  465. def do_PROPFIND(self, environ, read_collections, write_collections,
  466. content, user):
  467. """Manage PROPFIND request."""
  468. # Rights is handled by collection in xmlutils.propfind
  469. headers = {
  470. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  471. "Content-Type": "text/xml"}
  472. collections = set(read_collections + write_collections)
  473. answer = xmlutils.propfind(
  474. environ["PATH_INFO"], content, collections, user)
  475. return client.MULTI_STATUS, headers, answer
  476. def do_PROPPATCH(self, environ, read_collections, write_collections,
  477. content, user):
  478. """Manage PROPPATCH request."""
  479. if not len(write_collections):
  480. return NOT_ALLOWED
  481. collection = write_collections[0]
  482. answer = xmlutils.proppatch(
  483. environ["PATH_INFO"], content, collection)
  484. headers = {
  485. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  486. "Content-Type": "text/xml"}
  487. return client.MULTI_STATUS, headers, answer
  488. def do_PUT(self, environ, read_collections, write_collections, content,
  489. user):
  490. """Manage PUT request."""
  491. if not len(write_collections):
  492. return NOT_ALLOWED
  493. collection = write_collections[0]
  494. collection.set_mimetype(environ.get("CONTENT_TYPE"))
  495. headers = {}
  496. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  497. item = collection.items.get(item_name)
  498. # Evolution bug workaround
  499. etag = environ.get("HTTP_IF_MATCH", "").replace("\\", "")
  500. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  501. if (not item and not etag) or (
  502. item and ((etag or item.etag) == item.etag) and not match):
  503. # PUT allowed in 3 cases
  504. # Case 1: No item and no ETag precondition: Add new item
  505. # Case 2: Item and ETag precondition verified: Modify item
  506. # Case 3: Item and no Etag precondition: Force modifying item
  507. xmlutils.put(environ["PATH_INFO"], content, collection)
  508. status = client.CREATED
  509. # Try to return the etag in the header.
  510. # If the added item doesn't have the same name as the one given
  511. # by the client, then there's no obvious way to generate an
  512. # etag, we can safely ignore it.
  513. new_item = collection.items.get(item_name)
  514. if new_item:
  515. headers["ETag"] = new_item.etag
  516. else:
  517. # PUT rejected in all other cases
  518. status = client.PRECONDITION_FAILED
  519. return status, headers, None
  520. def do_REPORT(self, environ, read_collections, write_collections, content,
  521. user):
  522. """Manage REPORT request."""
  523. if not len(read_collections):
  524. return NOT_ALLOWED
  525. collection = read_collections[0]
  526. headers = {"Content-Type": "text/xml"}
  527. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  528. return client.MULTI_STATUS, headers, answer
  529. # pylint: enable=W0612,W0613,R0201