__init__.py 11 KB

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