__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. else:
  141. user = password = None
  142. last_allowed = False
  143. calendars = []
  144. for calendar in items:
  145. if not isinstance(calendar, ical.Calendar):
  146. if last_allowed:
  147. calendars.append(calendar)
  148. continue
  149. log.LOGGER.info(
  150. "Checking rights for calendar owned by %s" % calendar.owner)
  151. if self.acl.has_right(calendar.owner, user, password):
  152. log.LOGGER.info("%s allowed" % (user or "anonymous user"))
  153. calendars.append(calendar)
  154. last_allowed = True
  155. else:
  156. log.LOGGER.info("%s refused" % (user or "anonymous user"))
  157. last_allowed = False
  158. if calendars:
  159. status, headers, answer = function(environ, calendars, content)
  160. else:
  161. status = client.UNAUTHORIZED
  162. headers = {
  163. "WWW-Authenticate":
  164. "Basic realm=\"Radicale Server - Password Required\""}
  165. answer = None
  166. # Set content length
  167. if answer:
  168. log.LOGGER.debug(
  169. "Response content:\n%s" % self.decode(answer, environ))
  170. headers["Content-Length"] = str(len(answer))
  171. # Start response
  172. status = "%i %s" % (status, client.responses.get(status, ""))
  173. start_response(status, list(headers.items()))
  174. # Return response content
  175. return [answer] if answer else []
  176. # All these functions must have the same parameters, some are useless
  177. # pylint: disable=W0612,W0613,R0201
  178. def get(self, environ, calendars, content):
  179. """Manage GET request."""
  180. calendar = calendars[0]
  181. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  182. if item_name:
  183. # Get calendar item
  184. item = calendar.get_item(item_name)
  185. if item:
  186. items = calendar.timezones
  187. items.append(item)
  188. answer_text = ical.serialize(
  189. headers=calendar.headers, items=items)
  190. etag = item.etag
  191. else:
  192. return client.GONE, {}, None
  193. else:
  194. # Get whole calendar
  195. answer_text = calendar.text
  196. etag = calendar.etag
  197. headers = {
  198. "Content-Type": "text/calendar",
  199. "Last-Modified": calendar.last_modified,
  200. "ETag": etag}
  201. answer = answer_text.encode(self.encoding)
  202. return client.OK, headers, answer
  203. def head(self, environ, calendars, content):
  204. """Manage HEAD request."""
  205. status, headers, answer = self.get(environ, calendars, content)
  206. return status, headers, None
  207. def delete(self, environ, calendars, content):
  208. """Manage DELETE request."""
  209. calendar = calendars[0]
  210. item = calendar.get_item(
  211. xmlutils.name_from_path(environ["PATH_INFO"], calendar))
  212. if item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag:
  213. # No ETag precondition or precondition verified, delete item
  214. answer = xmlutils.delete(environ["PATH_INFO"], calendar)
  215. status = client.NO_CONTENT
  216. else:
  217. # No item or ETag precondition not verified, do not delete item
  218. answer = None
  219. status = client.PRECONDITION_FAILED
  220. return status, {}, answer
  221. def mkcalendar(self, environ, calendars, content):
  222. """Manage MKCALENDAR request."""
  223. calendar = calendars[0]
  224. props = xmlutils.props_from_request(content)
  225. tz = props.get('C:calendar-timezone')
  226. if tz:
  227. calendar.replace('', tz)
  228. del props['C:calendar-timezone']
  229. with calendar.props as calendar_props:
  230. for key, value in props.items():
  231. calendar_props[key] = value
  232. calendar.write()
  233. return client.CREATED, {}, None
  234. def options(self, environ, calendars, content):
  235. """Manage OPTIONS request."""
  236. headers = {
  237. "Allow": "DELETE, HEAD, GET, MKCALENDAR, " \
  238. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT",
  239. "DAV": "1, calendar-access"}
  240. return client.OK, headers, None
  241. def propfind(self, environ, calendars, content):
  242. """Manage PROPFIND request."""
  243. headers = {
  244. "DAV": "1, calendar-access",
  245. "Content-Type": "text/xml"}
  246. answer = xmlutils.propfind(
  247. environ["PATH_INFO"], content, calendars)
  248. return client.MULTI_STATUS, headers, answer
  249. def proppatch(self, environ, calendars, content):
  250. """Manage PROPPATCH request."""
  251. calendar = calendars[0]
  252. answer = xmlutils.proppatch(environ["PATH_INFO"], content, calendar)
  253. headers = {
  254. "DAV": "1, calendar-access",
  255. "Content-Type": "text/xml"}
  256. return client.MULTI_STATUS, headers, answer
  257. def put(self, environ, calendars, content):
  258. """Manage PUT request."""
  259. calendar = calendars[0]
  260. headers = {}
  261. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  262. item = calendar.get_item(item_name)
  263. if (not item and not environ.get("HTTP_IF_MATCH")) or (
  264. item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag):
  265. # PUT allowed in 3 cases
  266. # Case 1: No item and no ETag precondition: Add new item
  267. # Case 2: Item and ETag precondition verified: Modify item
  268. # Case 3: Item and no Etag precondition: Force modifying item
  269. xmlutils.put(environ["PATH_INFO"], content, calendar)
  270. status = client.CREATED
  271. headers["ETag"] = calendar.get_item(item_name).etag
  272. else:
  273. # PUT rejected in all other cases
  274. status = client.PRECONDITION_FAILED
  275. return status, headers, None
  276. def report(self, environ, calendars, content):
  277. """Manage REPORT request."""
  278. # TODO: support multiple calendars here
  279. calendar = calendars[0]
  280. headers = {'Content-Type': 'text/xml'}
  281. answer = xmlutils.report(environ["PATH_INFO"], content, calendar)
  282. return client.MULTI_STATUS, headers, answer
  283. # pylint: enable=W0612,W0613,R0201