__init__.py 22 KB

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