__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 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. def decode(self, text, environ):
  82. """Try to magically decode ``text`` according to given ``environ``."""
  83. # List of charsets to try
  84. charsets = []
  85. # First append content charset given in the request
  86. content_type = environ.get("CONTENT_TYPE")
  87. if content_type and "charset=" in content_type:
  88. charsets.append(content_type.split("charset=")[1].strip())
  89. # Then append default Radicale charset
  90. charsets.append(self.encoding)
  91. # Then append various fallbacks
  92. charsets.append("utf-8")
  93. charsets.append("iso8859-1")
  94. # Try to decode
  95. for charset in charsets:
  96. try:
  97. return text.decode(charset)
  98. except UnicodeDecodeError:
  99. pass
  100. raise UnicodeDecodeError
  101. def __call__(self, environ, start_response):
  102. """Manage a request."""
  103. log.LOGGER.info("%s request at %s received" % (
  104. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  105. log.LOGGER.debug("Request headers:\n%s" % environ.items())
  106. # Get content
  107. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  108. if content_length:
  109. content = self.decode(
  110. environ["wsgi.input"].read(content_length), environ)
  111. log.LOGGER.debug("Request content:\n%s" % content)
  112. else:
  113. content = None
  114. # Find calendar
  115. attributes = posixpath.normpath(
  116. environ["PATH_INFO"].strip("/")).split("/")
  117. if attributes:
  118. if attributes[-1].endswith(".ics"):
  119. attributes.pop()
  120. path = "/".join(attributes[:min(len(attributes), 2)])
  121. calendar = ical.Calendar(path)
  122. else:
  123. calendar = None
  124. # Get function corresponding to method
  125. function = getattr(self, environ["REQUEST_METHOD"].lower())
  126. # Check rights
  127. if not calendar or not self.acl:
  128. # No calendar or no acl, don't check rights
  129. status, headers, answer = function(environ, calendar, content)
  130. elif calendar.owner is None and config.getboolean("acl", "personal"):
  131. # No owner and personal calendars, don't check rights
  132. status, headers, answer = function(environ, calendar, content)
  133. else:
  134. # Ask authentication backend to check rights
  135. log.LOGGER.info(
  136. "Checking rights for calendar owned by %s" % calendar.owner)
  137. authorization = environ.get("HTTP_AUTHORIZATION", None)
  138. if authorization:
  139. auth = authorization.lstrip("Basic").strip().encode("ascii")
  140. user, password = self.decode(
  141. base64.b64decode(auth), environ).split(":")
  142. else:
  143. user = password = None
  144. if self.acl.has_right(calendar.owner, user, password):
  145. log.LOGGER.info("%s allowed" % calendar.owner)
  146. status, headers, answer = function(environ, calendar, content)
  147. else:
  148. log.LOGGER.info("%s refused" % calendar.owner)
  149. status = client.UNAUTHORIZED
  150. headers = {
  151. "WWW-Authenticate":
  152. "Basic realm=\"Radicale Server - Password Required\""}
  153. answer = None
  154. # Set content length
  155. if answer:
  156. # Decode the answer for logging purposes on Python 3
  157. log_answer = answer
  158. if not isinstance(log_answer, str):
  159. log_answer = log_answer.decode(
  160. config.get("encoding", "request"))
  161. log.LOGGER.debug("Response content:\n%s" % log_answer)
  162. headers["Content-Length"] = "%i" % len(answer)
  163. # Start response
  164. status = "%i %s" % (status, client.responses.get(status, ""))
  165. start_response(status, list(headers.items()))
  166. # Return response content
  167. return [answer] if answer else []
  168. # All these functions must have the same parameters, some are useless
  169. # pylint: disable=W0612,W0613,R0201
  170. def get(self, environ, calendar, content):
  171. """Manage GET request."""
  172. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  173. if item_name:
  174. # Get calendar item
  175. item = calendar.get_item(item_name)
  176. if item:
  177. items = calendar.timezones
  178. items.append(item)
  179. answer_text = ical.serialize(
  180. headers=calendar.headers, items=items)
  181. etag = item.etag
  182. else:
  183. return client.GONE, {}, None
  184. else:
  185. # Get whole calendar
  186. answer_text = calendar.text
  187. etag = calendar.etag
  188. headers = {
  189. "Content-Type": "text/calendar",
  190. "Last-Modified": calendar.last_modified,
  191. "ETag": etag}
  192. answer = answer_text.encode(self.encoding)
  193. return client.OK, headers, answer
  194. def head(self, environ, calendar, content):
  195. """Manage HEAD request."""
  196. status, headers, answer = self.get(environ, calendar, content)
  197. return status, headers, None
  198. def delete(self, environ, calendar, content):
  199. """Manage DELETE request."""
  200. item = calendar.get_item(
  201. xmlutils.name_from_path(environ["PATH_INFO"], calendar))
  202. if item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag:
  203. # No ETag precondition or precondition verified, delete item
  204. answer = xmlutils.delete(environ["PATH_INFO"], calendar)
  205. status = client.NO_CONTENT
  206. else:
  207. # No item or ETag precondition not verified, do not delete item
  208. answer = None
  209. status = client.PRECONDITION_FAILED
  210. return status, {}, answer
  211. def mkcalendar(self, environ, calendar, content):
  212. """Manage MKCALENDAR request."""
  213. return client.CREATED, {}, None
  214. def options(self, environ, calendar, content):
  215. """Manage OPTIONS request."""
  216. headers = {
  217. "Allow": "DELETE, HEAD, GET, MKCALENDAR, " \
  218. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT",
  219. "DAV": "1, calendar-access"}
  220. return client.OK, headers, None
  221. def propfind(self, environ, calendar, content):
  222. """Manage PROPFIND request."""
  223. headers = {
  224. "DAV": "1, calendar-access",
  225. "Content-Type": "text/xml"}
  226. answer = xmlutils.propfind(
  227. environ["PATH_INFO"], content, calendar,
  228. environ.get("HTTP_DEPTH", "infinity"))
  229. return client.MULTI_STATUS, headers, answer
  230. def proppatch(self, environ, calendar, content):
  231. """Manage PROPPATCH request."""
  232. xmlutils.proppatch(environ["PATH_INFO"], content, calendar)
  233. headers = {
  234. "DAV": "1, calendar-access",
  235. "Content-Type": "text/xml"}
  236. return client.MULTI_STATUS, headers, None
  237. def put(self, environ, calendar, content):
  238. """Manage PUT request."""
  239. headers = {}
  240. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  241. item = calendar.get_item(item_name)
  242. if (not item and not environ.get("HTTP_IF_MATCH")) or (
  243. item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag):
  244. # PUT allowed in 3 cases
  245. # Case 1: No item and no ETag precondition: Add new item
  246. # Case 2: Item and ETag precondition verified: Modify item
  247. # Case 3: Item and no Etag precondition: Force modifying item
  248. xmlutils.put(environ["PATH_INFO"], content, calendar)
  249. status = client.CREATED
  250. headers["ETag"] = calendar.get_item(item_name).etag
  251. else:
  252. # PUT rejected in all other cases
  253. status = client.PRECONDITION_FAILED
  254. return status, headers, None
  255. def report(self, environ, calendar, content):
  256. """Manage REPORT request."""
  257. answer = xmlutils.report(environ["PATH_INFO"], content, calendar)
  258. return client.MULTI_STATUS, {}, answer
  259. # pylint: enable=W0612,W0613,R0201