__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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
  35. try:
  36. from http import client, server
  37. import urllib.parse as urllib
  38. except ImportError:
  39. import httplib as client
  40. import BaseHTTPServer as server
  41. import urllib
  42. # pylint: enable=F0401
  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. self.socket = ssl.wrap_socket(
  66. self.socket,
  67. server_side=True,
  68. certfile=config.get("server", "certificate"),
  69. keyfile=config.get("server", "key"),
  70. ssl_version=ssl.PROTOCOL_SSLv23)
  71. self.server_bind()
  72. self.server_activate()
  73. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  74. """HTTP requests handler."""
  75. def log_message(self, *args, **kwargs):
  76. """Disable inner logging management."""
  77. class Application(object):
  78. """WSGI application managing calendars."""
  79. def __init__(self):
  80. """Initialize application."""
  81. super(Application, self).__init__()
  82. self.acl = acl.load()
  83. self.encoding = config.get("encoding", "request")
  84. if config.getboolean('logging', 'full_environment'):
  85. self.headers_log = lambda environ: environ
  86. # This method is overriden in __init__ if full_environment is set
  87. # pylint: disable=E0202
  88. @staticmethod
  89. def headers_log(environ):
  90. """Remove environment variables from the headers for logging purpose."""
  91. request_environ = dict(environ)
  92. for shell_variable in os.environ:
  93. del request_environ[shell_variable]
  94. return request_environ
  95. # pylint: enable=E0202
  96. def decode(self, text, environ):
  97. """Try to magically decode ``text`` according to given ``environ``."""
  98. # List of charsets to try
  99. charsets = []
  100. # First append content charset given in the request
  101. content_type = environ.get("CONTENT_TYPE")
  102. if content_type and "charset=" in content_type:
  103. charsets.append(content_type.split("charset=")[1].strip())
  104. # Then append default Radicale charset
  105. charsets.append(self.encoding)
  106. # Then append various fallbacks
  107. charsets.append("utf-8")
  108. charsets.append("iso8859-1")
  109. # Try to decode
  110. for charset in charsets:
  111. try:
  112. return text.decode(charset)
  113. except UnicodeDecodeError:
  114. pass
  115. raise UnicodeDecodeError
  116. @staticmethod
  117. def sanitize_uri(uri):
  118. """Clean URI: unquote and remove /../ to prevent access to other data."""
  119. return posixpath.normpath(urllib.unquote(uri))
  120. def __call__(self, environ, start_response):
  121. """Manage a request."""
  122. log.LOGGER.info("%s request at %s received" % (
  123. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  124. headers = pprint.pformat(self.headers_log(environ))
  125. log.LOGGER.debug("Request headers:\n%s" % headers)
  126. # Sanitize request URI
  127. environ["PATH_INFO"] = self.sanitize_uri(environ["PATH_INFO"])
  128. log.LOGGER.debug("Sanitized path: %s", environ["PATH_INFO"])
  129. # Get content
  130. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  131. if content_length:
  132. content = self.decode(
  133. environ["wsgi.input"].read(content_length), environ)
  134. log.LOGGER.debug("Request content:\n%s" % content)
  135. else:
  136. content = None
  137. # Find calendar(s)
  138. items = ical.Calendar.from_path(
  139. environ["PATH_INFO"], environ.get("HTTP_DEPTH", "0"))
  140. # Get function corresponding to method
  141. function = getattr(self, environ["REQUEST_METHOD"].lower())
  142. # Check rights
  143. if not items or not self.acl:
  144. # No calendar or no acl, don't check rights
  145. status, headers, answer = function(environ, items, content)
  146. else:
  147. # Ask authentication backend to check rights
  148. authorization = environ.get("HTTP_AUTHORIZATION", None)
  149. if authorization:
  150. auth = authorization.lstrip("Basic").strip().encode("ascii")
  151. user, password = self.decode(
  152. base64.b64decode(auth), environ).split(":")
  153. environ['USER'] = user
  154. else:
  155. user = password = None
  156. last_allowed = False
  157. calendars = []
  158. for calendar in items:
  159. if not isinstance(calendar, ical.Calendar):
  160. if last_allowed:
  161. calendars.append(calendar)
  162. continue
  163. if calendar.owner in acl.PUBLIC_USERS:
  164. log.LOGGER.info("Public calendar")
  165. calendars.append(calendar)
  166. last_allowed = True
  167. else:
  168. log.LOGGER.info(
  169. "Checking rights for calendar owned by %s" % (
  170. calendar.owner or "nobody"))
  171. if self.acl.has_right(calendar.owner, user, password):
  172. log.LOGGER.info(
  173. "%s allowed" % (user or "Anonymous user"))
  174. calendars.append(calendar)
  175. last_allowed = True
  176. else:
  177. log.LOGGER.info(
  178. "%s refused" % (user or "Anonymous user"))
  179. last_allowed = False
  180. if calendars:
  181. status, headers, answer = function(environ, calendars, content)
  182. else:
  183. status = client.UNAUTHORIZED
  184. headers = {
  185. "WWW-Authenticate":
  186. "Basic realm=\"Radicale Server - Password Required\""}
  187. answer = None
  188. # Set content length
  189. if answer:
  190. log.LOGGER.debug(
  191. "Response content:\n%s" % self.decode(answer, environ))
  192. headers["Content-Length"] = str(len(answer))
  193. # Start response
  194. status = "%i %s" % (status, client.responses.get(status, ""))
  195. start_response(status, list(headers.items()))
  196. # Return response content
  197. return [answer] if answer else []
  198. # All these functions must have the same parameters, some are useless
  199. # pylint: disable=W0612,W0613,R0201
  200. def delete(self, environ, calendars, content):
  201. """Manage DELETE request."""
  202. calendar = calendars[0]
  203. item = calendar.get_item(
  204. xmlutils.name_from_path(environ["PATH_INFO"], calendar))
  205. if item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag:
  206. # No ETag precondition or precondition verified, delete item
  207. answer = xmlutils.delete(environ["PATH_INFO"], calendar)
  208. status = client.NO_CONTENT
  209. else:
  210. # No item or ETag precondition not verified, do not delete item
  211. answer = None
  212. status = client.PRECONDITION_FAILED
  213. return status, {}, answer
  214. def get(self, environ, calendars, content):
  215. """Manage GET request."""
  216. calendar = calendars[0]
  217. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  218. if item_name:
  219. # Get calendar item
  220. item = calendar.get_item(item_name)
  221. if item:
  222. items = calendar.timezones
  223. items.append(item)
  224. answer_text = ical.serialize(
  225. headers=calendar.headers, items=items)
  226. etag = item.etag
  227. else:
  228. return client.GONE, {}, None
  229. else:
  230. # Get whole calendar
  231. answer_text = calendar.text
  232. etag = calendar.etag
  233. headers = {
  234. "Content-Type": "text/calendar",
  235. "Last-Modified": calendar.last_modified,
  236. "ETag": etag}
  237. answer = answer_text.encode(self.encoding)
  238. return client.OK, headers, answer
  239. def head(self, environ, calendars, content):
  240. """Manage HEAD request."""
  241. status, headers, answer = self.get(environ, calendars, content)
  242. return status, headers, None
  243. def mkcalendar(self, environ, calendars, content):
  244. """Manage MKCALENDAR request."""
  245. calendar = calendars[0]
  246. props = xmlutils.props_from_request(content)
  247. timezone = props.get('C:calendar-timezone')
  248. if timezone:
  249. calendar.replace('', timezone)
  250. del props['C:calendar-timezone']
  251. with calendar.props as calendar_props:
  252. for key, value in props.items():
  253. calendar_props[key] = value
  254. calendar.write()
  255. return client.CREATED, {}, None
  256. def options(self, environ, calendars, content):
  257. """Manage OPTIONS request."""
  258. headers = {
  259. "Allow": "DELETE, HEAD, GET, MKCALENDAR, " \
  260. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT",
  261. "DAV": "1, calendar-access"}
  262. return client.OK, headers, None
  263. def propfind(self, environ, calendars, content):
  264. """Manage PROPFIND request."""
  265. headers = {
  266. "DAV": "1, calendar-access",
  267. "Content-Type": "text/xml"}
  268. answer = xmlutils.propfind(
  269. environ["PATH_INFO"], content, calendars, environ.get("USER"))
  270. return client.MULTI_STATUS, headers, answer
  271. def proppatch(self, environ, calendars, content):
  272. """Manage PROPPATCH request."""
  273. calendar = calendars[0]
  274. answer = xmlutils.proppatch(environ["PATH_INFO"], content, calendar)
  275. headers = {
  276. "DAV": "1, calendar-access",
  277. "Content-Type": "text/xml"}
  278. return client.MULTI_STATUS, headers, answer
  279. def put(self, environ, calendars, content):
  280. """Manage PUT request."""
  281. calendar = calendars[0]
  282. headers = {}
  283. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  284. item = calendar.get_item(item_name)
  285. if (not item and not environ.get("HTTP_IF_MATCH")) or (
  286. item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag):
  287. # PUT allowed in 3 cases
  288. # Case 1: No item and no ETag precondition: Add new item
  289. # Case 2: Item and ETag precondition verified: Modify item
  290. # Case 3: Item and no Etag precondition: Force modifying item
  291. xmlutils.put(environ["PATH_INFO"], content, calendar)
  292. status = client.CREATED
  293. headers["ETag"] = calendar.get_item(item_name).etag
  294. else:
  295. # PUT rejected in all other cases
  296. status = client.PRECONDITION_FAILED
  297. return status, headers, None
  298. def report(self, environ, calendars, content):
  299. """Manage REPORT request."""
  300. # TODO: support multiple calendars here
  301. calendar = calendars[0]
  302. headers = {'Content-Type': 'text/xml'}
  303. answer = xmlutils.report(environ["PATH_INFO"], content, calendar)
  304. return client.MULTI_STATUS, headers, answer
  305. # pylint: enable=W0612,W0613,R0201