__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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):
  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 socketopts
  49. wsgiref.simple_server.WSGIServer.__init__(self, 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, bind_and_activate=True):
  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. HTTPServer.__init__(self, 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. if bind_and_activate:
  72. self.server_bind()
  73. self.server_activate()
  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 recieved" % (
  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["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. if not calendar or not self.acl:
  127. # No calendar or no acl, don't check rights
  128. status, headers, answer = function(environ, calendar, content)
  129. elif calendar.owner is None and config.getboolean("acl", "personal"):
  130. # No owner and personal calendars, don't check rights
  131. status, headers, answer = function(environ, calendar, content)
  132. else:
  133. # Check rights
  134. log.LOGGER.info(
  135. "Checking rights for calendar owned by %s" % calendar.owner)
  136. authorization = environ.get("HTTP_AUTHORIZATION", None)
  137. if authorization:
  138. auth = authorization.lstrip("Basic").strip().encode("ascii")
  139. user, password = self.decode(
  140. base64.b64decode(auth), environ).split(":")
  141. else:
  142. user = password = None
  143. if self.acl.has_right(calendar.owner, user, password):
  144. log.LOGGER.info("%s allowed" % calendar.owner)
  145. status, headers, answer = function(environ, calendar, content)
  146. else:
  147. log.LOGGER.info("%s refused" % calendar.owner)
  148. status = client.UNAUTHORIZED
  149. headers = {
  150. "WWW-Authenticate":
  151. "Basic realm=\"Radicale Server - Password Required\""}
  152. answer = None
  153. # Set content length
  154. if answer:
  155. log.LOGGER.debug("Response content:\n%s" % answer)
  156. headers["Content-Length"] = "%i" % len(answer)
  157. # Start response
  158. status = "%i %s" % (status, client.responses.get(status, ""))
  159. start_response(status, headers.items())
  160. # Return response content
  161. return [answer] if answer else []
  162. def get(self, environ, calendar, content):
  163. """Manage GET request."""
  164. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  165. if item_name:
  166. # Get calendar item
  167. item = calendar.get_item(item_name)
  168. if item:
  169. items = calendar.timezones
  170. items.append(item)
  171. answer_text = ical.serialize(
  172. headers=calendar.headers, items=items)
  173. etag = item.etag
  174. else:
  175. return client.GONE, {}, None
  176. else:
  177. # Get whole calendar
  178. answer_text = calendar.text
  179. etag = calendar.etag
  180. headers = {
  181. "Content-Type": "text/calendar",
  182. "Last-Modified": calendar.last_modified,
  183. "ETag": etag}
  184. answer = answer_text.encode(self.encoding)
  185. return client.OK, headers, answer
  186. def head(self, environ, calendar, content):
  187. """Manage HEAD request."""
  188. status, headers, answer = self.get(environ, calendar, content)
  189. return status, headers, None
  190. def delete(self, environ, calendar, content):
  191. """Manage DELETE request."""
  192. item = calendar.get_item(
  193. xmlutils.name_from_path(environ["PATH_INFO"], calendar))
  194. if item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag:
  195. # No ETag precondition or precondition verified, delete item
  196. answer = xmlutils.delete(environ["PATH_INFO"], calendar)
  197. status = client.NO_CONTENT
  198. else:
  199. # No item or ETag precondition not verified, do not delete item
  200. answer = None
  201. status = client.PRECONDITION_FAILED
  202. return status, {}, answer
  203. def mkcalendar(self, environ, calendar, content):
  204. """Manage MKCALENDAR request."""
  205. return client.CREATED, {}, None
  206. def options(self, environ, calendar, content):
  207. """Manage OPTIONS request."""
  208. headers = {
  209. "Allow": "DELETE, HEAD, GET, MKCALENDAR, " \
  210. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT",
  211. "DAV": "1, calendar-access"}
  212. return client.OK, headers, None
  213. def propfind(self, environ, calendar, content):
  214. """Manage PROPFIND request."""
  215. headers = {
  216. "DAV": "1, calendar-access",
  217. "Content-Type": "text/xml"}
  218. answer = xmlutils.propfind(
  219. environ["PATH_INFO"], content, calendar,
  220. environ.get("HTTP_DEPTH", "infinity"))
  221. return client.MULTI_STATUS, headers, answer
  222. def proppatch(self, environ, calendar, content):
  223. """Manage PROPPATCH request."""
  224. xmlutils.proppatch(environ["PATH_INFO"], content, calendar)
  225. headers = {
  226. "DAV": "1, calendar-access",
  227. "Content-Type": "text/xml"}
  228. return client.MULTI_STATUS, headers, None
  229. def put(self, environ, calendar, content):
  230. """Manage PUT request."""
  231. headers = {}
  232. item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
  233. item = calendar.get_item(item_name)
  234. if (not item and not environ.get("HTTP_IF_MATCH")) or (
  235. item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag):
  236. # PUT allowed in 3 cases
  237. # Case 1: No item and no ETag precondition: Add new item
  238. # Case 2: Item and ETag precondition verified: Modify item
  239. # Case 3: Item and no Etag precondition: Force modifying item
  240. xmlutils.put(environ["PATH_INFO"], content, calendar)
  241. status = client.CREATED
  242. headers["ETag"] = calendar.get_item(item_name).etag
  243. else:
  244. # PUT rejected in all other cases
  245. status = client.PRECONDITION_FAILED
  246. return status, headers, None
  247. def report(self, environ, calendar, content):
  248. """Manage REPORT request."""
  249. answer = xmlutils.report(environ["PATH_INFO"], content, calendar)
  250. return client.MULTI_STATUS, {}, answer