__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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-2013 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 = "0.9"
  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(content_type.split("charset=")[1].strip())
  133. # Then append default Radicale charset
  134. charsets.append(self.encoding)
  135. # Then append various fallbacks
  136. charsets.append("utf-8")
  137. charsets.append("iso8859-1")
  138. # Try to decode
  139. for charset in charsets:
  140. try:
  141. return text.decode(charset)
  142. except UnicodeDecodeError:
  143. pass
  144. raise UnicodeDecodeError
  145. @staticmethod
  146. def sanitize_uri(uri):
  147. """Unquote and remove /../ to prevent access to other data."""
  148. uri = unquote(uri)
  149. trailing_slash = "/" if uri.endswith("/") else ""
  150. uri = posixpath.normpath(uri)
  151. trailing_slash = "" if uri == "/" else trailing_slash
  152. return uri + trailing_slash
  153. def collect_allowed_items(self, items, user):
  154. """Get items from request that user is allowed to access."""
  155. read_last_collection_allowed = None
  156. write_last_collection_allowed = None
  157. read_allowed_items = []
  158. write_allowed_items = []
  159. for item in items:
  160. if isinstance(item, ical.Collection):
  161. if rights.authorized(user, item, "r"):
  162. log.LOGGER.debug(
  163. "%s has read access to collection %s" %
  164. (user or "Anonymous", item.url or "/"))
  165. read_last_collection_allowed = True
  166. read_allowed_items.append(item)
  167. else:
  168. log.LOGGER.debug(
  169. "%s has NO read access to collection %s" %
  170. (user or "Anonymous", item.url or "/"))
  171. read_last_collection_allowed = False
  172. if rights.authorized(user, item, "w"):
  173. log.LOGGER.debug(
  174. "%s has write access to collection %s" %
  175. (user or "Anonymous", item.url or "/"))
  176. write_last_collection_allowed = True
  177. write_allowed_items.append(item)
  178. else:
  179. log.LOGGER.debug(
  180. "%s has NO write access to collection %s" %
  181. (user or "Anonymous", item.url or "/"))
  182. write_last_collection_allowed = False
  183. else:
  184. # item is not a collection, it's the child of the last
  185. # collection we've met in the loop. Only add this item
  186. # if this last collection was allowed.
  187. if read_last_collection_allowed:
  188. log.LOGGER.debug(
  189. "%s has read access to item %s" %
  190. (user or "Anonymous", item.name))
  191. read_allowed_items.append(item)
  192. else:
  193. log.LOGGER.debug(
  194. "%s has NO read access to item %s" %
  195. (user or "Anonymous", item.name))
  196. if write_last_collection_allowed:
  197. log.LOGGER.debug(
  198. "%s has write access to item %s" %
  199. (user or "Anonymous", item.name))
  200. write_allowed_items.append(item)
  201. else:
  202. log.LOGGER.debug(
  203. "%s has NO write access to item %s" %
  204. (user or "Anonymous", item.name))
  205. return read_allowed_items, write_allowed_items
  206. def __call__(self, environ, start_response):
  207. """Manage a request."""
  208. log.LOGGER.info("%s request at %s received" % (
  209. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  210. headers = pprint.pformat(self.headers_log(environ))
  211. log.LOGGER.debug("Request headers:\n%s" % headers)
  212. base_prefix = config.get("server", "base_prefix")
  213. if environ["PATH_INFO"].startswith(base_prefix):
  214. # Sanitize request URI
  215. environ["PATH_INFO"] = self.sanitize_uri(
  216. "/%s" % environ["PATH_INFO"][len(base_prefix):])
  217. log.LOGGER.debug("Sanitized path: %s", environ["PATH_INFO"])
  218. elif config.get("server", "can_skip_base_prefix"):
  219. log.LOGGER.debug(
  220. "Skipped already sanitized path: %s", environ["PATH_INFO"])
  221. else:
  222. # Request path not starting with base_prefix, not allowed
  223. log.LOGGER.debug(
  224. "Path not starting with prefix: %s", environ["PATH_INFO"])
  225. environ["PATH_INFO"] = None
  226. path = environ["PATH_INFO"]
  227. # Get function corresponding to method
  228. function = getattr(self, environ["REQUEST_METHOD"].lower())
  229. # Ask authentication backend to check rights
  230. authorization = environ.get("HTTP_AUTHORIZATION", None)
  231. if authorization:
  232. authorization = authorization.lstrip("Basic").strip()
  233. user, password = self.decode(base64.b64decode(
  234. authorization.encode("ascii")), environ).split(":", 1)
  235. else:
  236. user = environ.get("REMOTE_USER")
  237. password = None
  238. well_known = WELL_KNOWN_RE.match(path)
  239. if well_known:
  240. redirect = config.get("well-known", well_known.group(1))
  241. try:
  242. redirect = redirect % ({"user": user} if user else {})
  243. except KeyError:
  244. status = client.UNAUTHORIZED
  245. headers = {
  246. "WWW-Authenticate":
  247. "Basic realm=\"%s\"" % config.get("server", "realm")}
  248. log.LOGGER.info(
  249. "Refused /.well-known/ redirection to anonymous user")
  250. else:
  251. status = client.SEE_OTHER
  252. log.LOGGER.info("/.well-known/ redirection to: %s" % redirect)
  253. if sys.version_info < (3, 0):
  254. redirect = redirect.encode(self.encoding)
  255. headers = {"Location": redirect}
  256. status = "%i %s" % (
  257. status, client.responses.get(status, "Unknown"))
  258. start_response(status, list(headers.items()))
  259. return []
  260. is_authenticated = auth.is_authenticated(user, password)
  261. is_valid_user = is_authenticated or not user
  262. if is_valid_user:
  263. items = ical.Collection.from_path(
  264. path, environ.get("HTTP_DEPTH", "0"))
  265. read_allowed_items, write_allowed_items = \
  266. self.collect_allowed_items(items, user)
  267. else:
  268. read_allowed_items, write_allowed_items = None, None
  269. # Get content
  270. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  271. if content_length:
  272. content = self.decode(
  273. environ["wsgi.input"].read(content_length), environ)
  274. log.LOGGER.debug("Request content:\n%s" % content)
  275. else:
  276. content = None
  277. if is_valid_user and (
  278. (read_allowed_items or write_allowed_items) or
  279. (is_authenticated and function == self.propfind) or
  280. function == self.options):
  281. status, headers, answer = function(
  282. environ, read_allowed_items, write_allowed_items, content,
  283. user)
  284. else:
  285. status, headers, answer = NOT_ALLOWED
  286. if ((status, headers, answer) == NOT_ALLOWED and
  287. not auth.is_authenticated(user, password) and
  288. config.get("auth", "type") != "None"):
  289. # Unknown or unauthorized user
  290. log.LOGGER.info("%s refused" % (user or "Anonymous user"))
  291. status = client.UNAUTHORIZED
  292. headers = {
  293. "WWW-Authenticate":
  294. "Basic realm=\"%s\"" % config.get("server", "realm")}
  295. answer = None
  296. # Set content length
  297. if answer:
  298. log.LOGGER.debug(
  299. "Response content:\n%s" % self.decode(answer, environ))
  300. headers["Content-Length"] = str(len(answer))
  301. if config.has_section("headers"):
  302. for key in config.options("headers"):
  303. headers[key] = config.get("headers", key)
  304. # Start response
  305. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  306. log.LOGGER.debug("Answer status: %s" % status)
  307. start_response(status, list(headers.items()))
  308. # Return response content
  309. return [answer] if answer else []
  310. # All these functions must have the same parameters, some are useless
  311. # pylint: disable=W0612,W0613,R0201
  312. def delete(self, environ, read_collections, write_collections, content,
  313. user):
  314. """Manage DELETE request."""
  315. if not len(write_collections):
  316. return NOT_ALLOWED
  317. collection = write_collections[0]
  318. if collection.path == environ["PATH_INFO"].strip("/"):
  319. # Path matching the collection, the collection must be deleted
  320. item = collection
  321. else:
  322. # Try to get an item matching the path
  323. item = collection.get_item(
  324. xmlutils.name_from_path(environ["PATH_INFO"], collection))
  325. if item:
  326. # Evolution bug workaround
  327. etag = environ.get("HTTP_IF_MATCH", item.etag).replace("\\", "")
  328. if etag == item.etag:
  329. # No ETag precondition or precondition verified, delete item
  330. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  331. return client.OK, {}, answer
  332. # No item or ETag precondition not verified, do not delete item
  333. return client.PRECONDITION_FAILED, {}, None
  334. def get(self, environ, read_collections, write_collections, content, user):
  335. """Manage GET request.
  336. In Radicale, GET requests create collections when the URL is not
  337. available. This is useful for clients with no MKCOL or MKCALENDAR
  338. support.
  339. """
  340. # Display a "Radicale works!" message if the root URL is requested
  341. if environ["PATH_INFO"] == "/":
  342. headers = {"Content-type": "text/html"}
  343. answer = b"<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  344. return client.OK, headers, answer
  345. if not len(read_collections):
  346. return NOT_ALLOWED
  347. collection = read_collections[0]
  348. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  349. if item_name:
  350. # Get collection item
  351. item = collection.get_item(item_name)
  352. if item:
  353. items = collection.timezones
  354. items.append(item)
  355. answer_text = ical.serialize(
  356. collection.tag, collection.headers, items)
  357. etag = item.etag
  358. else:
  359. return client.GONE, {}, None
  360. else:
  361. # Create the collection if it does not exist
  362. if not collection.exists:
  363. if collection in write_collections:
  364. log.LOGGER.debug(
  365. "Creating collection %s" % collection.name)
  366. collection.write()
  367. else:
  368. log.LOGGER.debug(
  369. "Collection %s not available and could not be created "
  370. "due to missing write rights" % collection.name)
  371. return NOT_ALLOWED
  372. # Get whole collection
  373. answer_text = collection.text
  374. etag = collection.etag
  375. headers = {
  376. "Content-Type": collection.mimetype,
  377. "Last-Modified": collection.last_modified,
  378. "ETag": etag}
  379. answer = answer_text.encode(self.encoding)
  380. return client.OK, headers, answer
  381. def head(self, environ, read_collections, write_collections, content,
  382. user):
  383. """Manage HEAD request."""
  384. status, headers, answer = self.get(
  385. environ, read_collections, write_collections, content, user)
  386. return status, headers, None
  387. def mkcalendar(self, environ, read_collections, write_collections, content,
  388. user):
  389. """Manage MKCALENDAR request."""
  390. if not len(write_collections):
  391. return NOT_ALLOWED
  392. collection = write_collections[0]
  393. props = xmlutils.props_from_request(content)
  394. timezone = props.get("C:calendar-timezone")
  395. if timezone:
  396. collection.replace("", timezone)
  397. del props["C:calendar-timezone"]
  398. with collection.props as collection_props:
  399. for key, value in props.items():
  400. collection_props[key] = value
  401. collection.write()
  402. return client.CREATED, {}, None
  403. def mkcol(self, environ, read_collections, write_collections, content,
  404. user):
  405. """Manage MKCOL request."""
  406. if not len(write_collections):
  407. return NOT_ALLOWED
  408. collection = write_collections[0]
  409. props = xmlutils.props_from_request(content)
  410. with collection.props as collection_props:
  411. for key, value in props.items():
  412. collection_props[key] = value
  413. collection.write()
  414. return client.CREATED, {}, None
  415. def move(self, environ, read_collections, write_collections, content,
  416. user):
  417. """Manage MOVE request."""
  418. if not len(write_collections):
  419. return NOT_ALLOWED
  420. from_collection = write_collections[0]
  421. from_name = xmlutils.name_from_path(
  422. environ["PATH_INFO"], from_collection)
  423. if from_name:
  424. item = from_collection.get_item(from_name)
  425. if item:
  426. # Move the item
  427. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  428. if to_url_parts.netloc == environ["HTTP_HOST"]:
  429. to_url = to_url_parts.path
  430. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  431. to_collection = ical.Collection.from_path(
  432. to_path, depth="0")[0]
  433. if to_collection in write_collections:
  434. to_collection.append(to_name, item.text)
  435. from_collection.remove(from_name)
  436. return client.CREATED, {}, None
  437. else:
  438. return NOT_ALLOWED
  439. else:
  440. # Remote destination server, not supported
  441. return client.BAD_GATEWAY, {}, None
  442. else:
  443. # No item found
  444. return client.GONE, {}, None
  445. else:
  446. # Moving collections, not supported
  447. return client.FORBIDDEN, {}, None
  448. def options(self, environ, read_collections, write_collections, content,
  449. user):
  450. """Manage OPTIONS request."""
  451. headers = {
  452. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  453. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  454. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  455. return client.OK, headers, None
  456. def propfind(self, environ, read_collections, write_collections, content,
  457. user):
  458. """Manage PROPFIND request."""
  459. # Rights is handled by collection in xmlutils.propfind
  460. headers = {
  461. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  462. "Content-Type": "text/xml"}
  463. collections = set(read_collections + write_collections)
  464. answer = xmlutils.propfind(
  465. environ["PATH_INFO"], content, collections, user)
  466. return client.MULTI_STATUS, headers, answer
  467. def proppatch(self, environ, read_collections, write_collections, content,
  468. user):
  469. """Manage PROPPATCH request."""
  470. if not len(write_collections):
  471. return NOT_ALLOWED
  472. collection = write_collections[0]
  473. answer = xmlutils.proppatch(
  474. environ["PATH_INFO"], content, collection)
  475. headers = {
  476. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  477. "Content-Type": "text/xml"}
  478. return client.MULTI_STATUS, headers, answer
  479. def put(self, environ, read_collections, write_collections, content, user):
  480. """Manage PUT request."""
  481. if not len(write_collections):
  482. return NOT_ALLOWED
  483. collection = write_collections[0]
  484. collection.set_mimetype(environ.get("CONTENT_TYPE"))
  485. headers = {}
  486. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  487. item = collection.get_item(item_name)
  488. # Evolution bug workaround
  489. etag = environ.get("HTTP_IF_MATCH", "").replace("\\", "")
  490. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  491. if (not item and not etag) or (
  492. item and ((etag or item.etag) == item.etag) and not match):
  493. # PUT allowed in 3 cases
  494. # Case 1: No item and no ETag precondition: Add new item
  495. # Case 2: Item and ETag precondition verified: Modify item
  496. # Case 3: Item and no Etag precondition: Force modifying item
  497. xmlutils.put(environ["PATH_INFO"], content, collection)
  498. status = client.CREATED
  499. # Try to return the etag in the header.
  500. # If the added item doesn't have the same name as the one given
  501. # by the client, then there's no obvious way to generate an
  502. # etag, we can safely ignore it.
  503. new_item = collection.get_item(item_name)
  504. if new_item:
  505. headers["ETag"] = new_item.etag
  506. else:
  507. # PUT rejected in all other cases
  508. status = client.PRECONDITION_FAILED
  509. return status, headers, None
  510. def report(self, environ, read_collections, write_collections, content,
  511. user):
  512. """Manage REPORT request."""
  513. if not len(read_collections):
  514. return NOT_ALLOWED
  515. collection = read_collections[0]
  516. headers = {"Content-Type": "text/xml"}
  517. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  518. return client.MULTI_STATUS, headers, answer
  519. # pylint: enable=W0612,W0613,R0201