__init__.py 12 KB

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