__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008-2011 Guillaume Ayoub
  5. # Copyright © 2008 Nicolas Kandel
  6. # Copyright © 2008 Pascal Halter
  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 pprint
  28. import base64
  29. import posixpath
  30. import socket
  31. import ssl
  32. import wsgiref.simple_server
  33. # Manage Python2/3 different modules
  34. # pylint: disable=F0401,E0611
  35. try:
  36. from http import client
  37. from urllib.parse import quote, unquote, urlparse
  38. except ImportError:
  39. import httplib as client
  40. from urllib import quote, unquote
  41. from urlparse import urlparse
  42. # pylint: enable=F0401,E0611
  43. from radicale import acl, config, ical, log, xmlutils
  44. VERSION = "git"
  45. class HTTPServer(wsgiref.simple_server.WSGIServer, object):
  46. """HTTP server."""
  47. def __init__(self, address, handler, bind_and_activate=True):
  48. """Create server."""
  49. ipv6 = ":" in address[0]
  50. if ipv6:
  51. self.address_family = socket.AF_INET6
  52. # Do not bind and activate, as we might change socket options
  53. super(HTTPServer, self).__init__(address, handler, False)
  54. if ipv6:
  55. # Only allow IPv6 connections to the IPv6 socket
  56. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  57. if bind_and_activate:
  58. self.server_bind()
  59. self.server_activate()
  60. class HTTPSServer(HTTPServer):
  61. """HTTPS server."""
  62. def __init__(self, address, handler):
  63. """Create server by wrapping HTTP socket in an SSL socket."""
  64. super(HTTPSServer, self).__init__(address, handler, False)
  65. # Test if the SSL files can be read
  66. for name in ("certificate", "key"):
  67. filename = config.get("server", name)
  68. try:
  69. open(filename, "r").close()
  70. except IOError as exception:
  71. log.LOGGER.warn(
  72. "Error while reading SSL %s %r: %s" % (
  73. name, filename, exception))
  74. self.socket = ssl.wrap_socket(
  75. self.socket,
  76. server_side=True,
  77. certfile=config.get("server", "certificate"),
  78. keyfile=config.get("server", "key"),
  79. ssl_version=ssl.PROTOCOL_SSLv23)
  80. self.server_bind()
  81. self.server_activate()
  82. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  83. """HTTP requests handler."""
  84. def log_message(self, *args, **kwargs):
  85. """Disable inner logging management."""
  86. class Application(object):
  87. """WSGI application managing collections."""
  88. def __init__(self):
  89. """Initialize application."""
  90. super(Application, self).__init__()
  91. self.acl = acl.load()
  92. self.encoding = config.get("encoding", "request")
  93. if config.getboolean('logging', 'full_environment'):
  94. self.headers_log = lambda environ: environ
  95. # This method is overriden in __init__ if full_environment is set
  96. # pylint: disable=E0202
  97. @staticmethod
  98. def headers_log(environ):
  99. """Remove environment variables from the headers for logging."""
  100. request_environ = dict(environ)
  101. for shell_variable in os.environ:
  102. if shell_variable in request_environ:
  103. del request_environ[shell_variable]
  104. return request_environ
  105. # pylint: enable=E0202
  106. def decode(self, text, environ):
  107. """Try to magically decode ``text`` according to given ``environ``."""
  108. # List of charsets to try
  109. charsets = []
  110. # First append content charset given in the request
  111. content_type = environ.get("CONTENT_TYPE")
  112. if content_type and "charset=" in content_type:
  113. charsets.append(content_type.split("charset=")[1].strip())
  114. # Then append default Radicale charset
  115. charsets.append(self.encoding)
  116. # Then append various fallbacks
  117. charsets.append("utf-8")
  118. charsets.append("iso8859-1")
  119. # Try to decode
  120. for charset in charsets:
  121. try:
  122. return text.decode(charset)
  123. except UnicodeDecodeError:
  124. pass
  125. raise UnicodeDecodeError
  126. @staticmethod
  127. def sanitize_uri(uri):
  128. """Unquote and remove /../ to prevent access to other data."""
  129. uri = unquote(uri)
  130. trailing_slash = "/" if uri.endswith("/") else ""
  131. uri = posixpath.normpath(uri)
  132. trailing_slash = "" if uri == "/" else trailing_slash
  133. return uri + trailing_slash
  134. def __call__(self, environ, start_response):
  135. """Manage a request."""
  136. log.LOGGER.info("%s request at %s received" % (
  137. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  138. headers = pprint.pformat(self.headers_log(environ))
  139. log.LOGGER.debug("Request headers:\n%s" % headers)
  140. # Sanitize request URI
  141. environ["PATH_INFO"] = self.sanitize_uri(environ["PATH_INFO"])
  142. log.LOGGER.debug("Sanitized path: %s", environ["PATH_INFO"])
  143. # Get content
  144. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  145. if content_length:
  146. content = self.decode(
  147. environ["wsgi.input"].read(content_length), environ)
  148. log.LOGGER.debug("Request content:\n%s" % content)
  149. else:
  150. content = None
  151. # Find collection(s)
  152. items = ical.Collection.from_path(
  153. environ["PATH_INFO"], environ.get("HTTP_DEPTH", "0"))
  154. # Get function corresponding to method
  155. function = getattr(self, environ["REQUEST_METHOD"].lower())
  156. # Check rights
  157. if not items or not self.acl:
  158. # No collection or no acl, don't check rights
  159. status, headers, answer = function(environ, items, content, None)
  160. else:
  161. # Ask authentication backend to check rights
  162. authorization = environ.get("HTTP_AUTHORIZATION", None)
  163. if authorization:
  164. auth = authorization.lstrip("Basic").strip().encode("ascii")
  165. user, password = self.decode(
  166. base64.b64decode(auth), environ).split(":")
  167. else:
  168. user = password = None
  169. last_allowed = None
  170. collections = []
  171. for collection in items:
  172. if not isinstance(collection, ical.Collection):
  173. if last_allowed:
  174. collections.append(collection)
  175. continue
  176. if collection.owner in acl.PUBLIC_USERS:
  177. log.LOGGER.info("Public collection")
  178. collections.append(collection)
  179. last_allowed = True
  180. else:
  181. log.LOGGER.info(
  182. "Checking rights for collection owned by %s" % (
  183. collection.owner or "nobody"))
  184. if self.acl.has_right(collection.owner, user, password):
  185. log.LOGGER.info(
  186. "%s allowed" % (user or "Anonymous user"))
  187. collections.append(collection)
  188. last_allowed = True
  189. else:
  190. log.LOGGER.info(
  191. "%s refused" % (user or "Anonymous user"))
  192. last_allowed = False
  193. if collections:
  194. # Collections found
  195. status, headers, answer = function(
  196. environ, collections, content, user)
  197. elif user and last_allowed is None:
  198. # Good user and no collections found, redirect user to home
  199. location = "/%s/" % str(quote(user))
  200. log.LOGGER.info("redirecting to %s" % location)
  201. status = client.FOUND
  202. headers = {"Location": location}
  203. answer = "Redirecting to %s" % location
  204. else:
  205. # Unknown or unauthorized user
  206. status = client.UNAUTHORIZED
  207. headers = {
  208. "WWW-Authenticate":
  209. "Basic realm=\"Radicale Server - Password Required\""}
  210. answer = None
  211. # Set content length
  212. if answer:
  213. log.LOGGER.debug(
  214. "Response content:\n%s" % self.decode(answer, environ))
  215. headers["Content-Length"] = str(len(answer))
  216. # Start response
  217. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  218. log.LOGGER.debug("Answer status: %s" % status)
  219. start_response(status, list(headers.items()))
  220. # Return response content
  221. return [answer] if answer else []
  222. # All these functions must have the same parameters, some are useless
  223. # pylint: disable=W0612,W0613,R0201
  224. def delete(self, environ, collections, content, user):
  225. """Manage DELETE request."""
  226. collection = collections[0]
  227. if collection.local_path == environ["PATH_INFO"].strip("/"):
  228. # Path matching the collection, the collection must be deleted
  229. item = collection
  230. else:
  231. # Try to get an item matching the path
  232. item = collection.get_item(
  233. xmlutils.name_from_path(environ["PATH_INFO"], collection))
  234. if item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag:
  235. # No ETag precondition or precondition verified, delete item
  236. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  237. status = client.NO_CONTENT
  238. else:
  239. # No item or ETag precondition not verified, do not delete item
  240. answer = None
  241. status = client.PRECONDITION_FAILED
  242. return status, {}, answer
  243. def get(self, environ, collections, content, user):
  244. """Manage GET request."""
  245. # Display a "Radicale works!" message if the root URL is requested
  246. if environ["PATH_INFO"] == "/":
  247. headers = {"Content-type": "text/html"}
  248. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  249. return client.OK, headers, answer
  250. collection = collections[0]
  251. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  252. if item_name:
  253. # Get collection item
  254. item = collection.get_item(item_name)
  255. if item:
  256. items = collection.timezones
  257. items.append(item)
  258. answer_text = ical.serialize(
  259. collection.tag, collection.headers, items)
  260. etag = item.etag
  261. else:
  262. return client.GONE, {}, None
  263. else:
  264. # Get whole collection
  265. answer_text = collection.text
  266. etag = collection.etag
  267. headers = {
  268. "Content-Type": collection.mimetype,
  269. "Last-Modified": collection.last_modified,
  270. "ETag": etag}
  271. answer = answer_text.encode(self.encoding)
  272. return client.OK, headers, answer
  273. def head(self, environ, collections, content, user):
  274. """Manage HEAD request."""
  275. status, headers, answer = self.get(environ, collections, content, user)
  276. return status, headers, None
  277. def mkcalendar(self, environ, collections, content, user):
  278. """Manage MKCALENDAR request."""
  279. collection = collections[0]
  280. props = xmlutils.props_from_request(content)
  281. timezone = props.get('C:calendar-timezone')
  282. if timezone:
  283. collection.replace('', timezone)
  284. del props['C:calendar-timezone']
  285. with collection.props as collection_props:
  286. for key, value in props.items():
  287. collection_props[key] = value
  288. collection.write()
  289. return client.CREATED, {}, None
  290. def mkcol(self, environ, collections, content, user):
  291. """Manage MKCOL request."""
  292. collection = collections[0]
  293. props = xmlutils.props_from_request(content)
  294. with collection.props as collection_props:
  295. for key, value in props.items():
  296. collection_props[key] = value
  297. collection.write()
  298. return client.CREATED, {}, None
  299. def move(self, environ, collections, content, user):
  300. """Manage MOVE request."""
  301. from_collection = collections[0]
  302. from_name = xmlutils.name_from_path(
  303. environ["PATH_INFO"], from_collection)
  304. if from_name:
  305. item = from_collection.get_item(from_name)
  306. if item:
  307. # Move the item
  308. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  309. if to_url_parts.netloc == environ["HTTP_HOST"]:
  310. to_url = to_url_parts.path
  311. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  312. to_collection = ical.Collection.from_path(
  313. to_path, depth="0")[0]
  314. to_collection.append(to_name, item.text)
  315. from_collection.remove(from_name)
  316. return client.CREATED, {}, None
  317. else:
  318. # Remote destination server, not supported
  319. return client.BAD_GATEWAY, {}, None
  320. else:
  321. # No item found
  322. return client.GONE, {}, None
  323. else:
  324. # Moving collections, not supported
  325. return client.FORBIDDEN, {}, None
  326. def options(self, environ, collections, content, user):
  327. """Manage OPTIONS request."""
  328. headers = {
  329. "Allow": "DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, " \
  330. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT",
  331. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  332. return client.OK, headers, None
  333. def propfind(self, environ, collections, content, user):
  334. """Manage PROPFIND request."""
  335. headers = {
  336. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  337. "Content-Type": "text/xml"}
  338. answer = xmlutils.propfind(
  339. environ["PATH_INFO"], content, collections, user)
  340. return client.MULTI_STATUS, headers, answer
  341. def proppatch(self, environ, collections, content, user):
  342. """Manage PROPPATCH request."""
  343. collection = collections[0]
  344. answer = xmlutils.proppatch(environ["PATH_INFO"], content, collection)
  345. headers = {
  346. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  347. "Content-Type": "text/xml"}
  348. return client.MULTI_STATUS, headers, answer
  349. def put(self, environ, collections, content, user):
  350. """Manage PUT request."""
  351. collection = collections[0]
  352. collection.set_mimetype(environ.get("CONTENT_TYPE"))
  353. headers = {}
  354. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  355. item = collection.get_item(item_name)
  356. if (not item and not environ.get("HTTP_IF_MATCH")) or (
  357. item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag):
  358. # PUT allowed in 3 cases
  359. # Case 1: No item and no ETag precondition: Add new item
  360. # Case 2: Item and ETag precondition verified: Modify item
  361. # Case 3: Item and no Etag precondition: Force modifying item
  362. xmlutils.put(environ["PATH_INFO"], content, collection)
  363. status = client.CREATED
  364. headers["ETag"] = collection.get_item(item_name).etag
  365. else:
  366. # PUT rejected in all other cases
  367. status = client.PRECONDITION_FAILED
  368. return status, headers, None
  369. def report(self, environ, collections, content, user):
  370. """Manage REPORT request."""
  371. collection = collections[0]
  372. headers = {'Content-Type': 'text/xml'}
  373. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  374. return client.MULTI_STATUS, headers, answer
  375. # pylint: enable=W0612,W0613,R0201