__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 3 useful classes:
  23. - ``HTTPServer`` is a simple HTTP server;
  24. - ``HTTPSServer`` is a HTTPS server, wrapping the HTTP server in a socket
  25. managing SSL connections;
  26. - ``CalendarHTTPHandler`` is a CalDAV request handler for HTTP(S) servers.
  27. To use this module, you should take a look at the file ``radicale.py`` that
  28. should have been included in this package.
  29. """
  30. import os
  31. import posixpath
  32. import base64
  33. import socket
  34. # Manage Python2/3 different modules
  35. # pylint: disable=F0401
  36. try:
  37. from http import client, server
  38. except ImportError:
  39. import httplib as client
  40. import BaseHTTPServer as server
  41. # pylint: enable=F0401
  42. from radicale import acl, config, ical, log, xmlutils
  43. VERSION = "git"
  44. # Decorators can access ``request`` protected functions
  45. # pylint: disable=W0212
  46. def _check(request, function):
  47. """Check if user has sufficient rights for performing ``request``."""
  48. # If we have no calendar or no acl, don't check rights
  49. if not request._calendar or not request.server.acl:
  50. return function(request)
  51. if request._calendar.owner is None and PERSONAL:
  52. # No owner and personal calendars, don't check rights
  53. return function(request)
  54. log.LOGGER.info(
  55. "Checking rights for calendar owned by %s" % request._calendar.owner)
  56. authorization = request.headers.get("Authorization", None)
  57. if authorization:
  58. challenge = authorization.lstrip("Basic").strip().encode("ascii")
  59. user, password = request._decode(base64.b64decode(challenge)).split(":")
  60. else:
  61. user = password = None
  62. if request.server.acl.has_right(request._calendar.owner, user, password):
  63. log.LOGGER.info("%s allowed" % request._calendar.owner)
  64. function(request)
  65. else:
  66. log.LOGGER.info("%s refused" % request._calendar.owner)
  67. request.send_response(client.UNAUTHORIZED)
  68. request.send_header(
  69. "WWW-Authenticate",
  70. "Basic realm=\"Radicale Server - Password Required\"")
  71. request.end_headers()
  72. def _log_request_content(request, function):
  73. """Log the content of the request and store it in the request object."""
  74. log.LOGGER.info(
  75. "%s request at %s recieved from %s" % (
  76. request.command, request.path, request.client_address[0]))
  77. content_length = int(request.headers.get("Content-Length", 0))
  78. if content_length:
  79. request._content = request.rfile.read(content_length)
  80. log.LOGGER.debug(
  81. "Request headers:\n%s" % "\n".join(
  82. ": ".join((key, value))
  83. for key, value in request.headers.items()))
  84. log.LOGGER.debug("Request content:\n%s" % request._content)
  85. else:
  86. request._content = None
  87. function(request)
  88. if getattr(request, "_answer"):
  89. log.LOGGER.debug(
  90. "Response content:\n%s" % request._answer)
  91. # pylint: enable=W0212
  92. class HTTPServer(server.HTTPServer):
  93. """HTTP server."""
  94. PROTOCOL = "http"
  95. # Maybe a Pylint bug, ``__init__`` calls ``server.HTTPServer.__init__``
  96. # pylint: disable=W0231
  97. def __init__(self, address, handler, bind_and_activate=True):
  98. """Create server."""
  99. ipv6 = ":" in address[0]
  100. if ipv6:
  101. self.address_family = socket.AF_INET6
  102. # Do not bind and activate, as we might change socketopts
  103. server.HTTPServer.__init__(self, address, handler, False)
  104. if ipv6:
  105. # Only allow IPv6 connections to the IPv6 socket
  106. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  107. if bind_and_activate:
  108. self.server_bind()
  109. self.server_activate()
  110. self.acl = acl.load()
  111. # pylint: enable=W0231
  112. class HTTPSServer(HTTPServer):
  113. """HTTPS server."""
  114. PROTOCOL = "https"
  115. def __init__(self, address, handler, bind_and_activate=True):
  116. """Create server by wrapping HTTP socket in an SSL socket."""
  117. # Fails with Python 2.5, import if needed
  118. # pylint: disable=F0401
  119. import ssl
  120. # pylint: enable=F0401
  121. HTTPServer.__init__(self, address, handler, False)
  122. self.socket = ssl.wrap_socket(
  123. self.socket,
  124. server_side=True,
  125. certfile=config.get("server", "certificate"),
  126. keyfile=config.get("server", "key"),
  127. ssl_version=ssl.PROTOCOL_SSLv23)
  128. if bind_and_activate:
  129. self.server_bind()
  130. self.server_activate()
  131. class CalendarHTTPHandler(server.BaseHTTPRequestHandler):
  132. """HTTP requests handler for calendars."""
  133. _encoding = config.get("encoding", "request")
  134. # Request handlers decorators
  135. check_rights = lambda function: lambda request: _check(request, function)
  136. log_request_content = \
  137. lambda function: lambda request: _log_request_content(request, function)
  138. # Maybe a Pylint bug, ``__init__`` calls ``server.HTTPServer.__init__``
  139. # pylint: disable=W0231
  140. def __init__(self, request, client_address, http_server):
  141. self._content = None
  142. self._answer = None
  143. server.BaseHTTPRequestHandler.__init__(
  144. self, request, client_address, http_server)
  145. # pylint: enable=W0231
  146. @property
  147. def _calendar(self):
  148. """The ``ical.Calendar`` object corresponding to the given path."""
  149. # ``self.path`` must be something like a posix path
  150. # ``normpath`` should clean malformed and malicious request paths
  151. attributes = posixpath.normpath(self.path.strip("/")).split("/")
  152. if attributes:
  153. if attributes[-1].endswith('.ics'):
  154. attributes.pop()
  155. path = "/".join(attributes[:min(len(attributes), 2)])
  156. return ical.Calendar(path)
  157. def _decode(self, text):
  158. """Try to decode text according to various parameters."""
  159. # List of charsets to try
  160. charsets = []
  161. # First append content charset given in the request
  162. content_type = self.headers.get("Content-Type", None)
  163. if content_type and "charset=" in content_type:
  164. charsets.append(content_type.split("charset=")[1].strip())
  165. # Then append default Radicale charset
  166. charsets.append(self._encoding)
  167. # Then append various fallbacks
  168. charsets.append("utf-8")
  169. charsets.append("iso8859-1")
  170. # Try to decode
  171. for charset in charsets:
  172. try:
  173. return text.decode(charset)
  174. except UnicodeDecodeError:
  175. pass
  176. raise UnicodeDecodeError
  177. def log_message(self, *args, **kwargs):
  178. """Disable inner logging management."""
  179. # Naming methods ``do_*`` is OK here
  180. # pylint: disable=C0103
  181. @log_request_content
  182. def do_GET(self):
  183. """Manage GET request."""
  184. self.do_HEAD()
  185. if self._answer:
  186. self.wfile.write(self._answer)
  187. @log_request_content
  188. @check_rights
  189. def do_HEAD(self):
  190. """Manage HEAD request."""
  191. item_name = xmlutils.name_from_path(self.path, self._calendar)
  192. if item_name:
  193. # Get calendar item
  194. item = self._calendar.get_item(item_name)
  195. if item:
  196. items = self._calendar.timezones
  197. items.append(item)
  198. answer_text = ical.serialize(
  199. headers=self._calendar.headers, items=items)
  200. etag = item.etag
  201. else:
  202. self._answer = None
  203. self.send_response(client.GONE)
  204. return
  205. else:
  206. # Get whole calendar
  207. answer_text = self._calendar.text
  208. etag = self._calendar.etag
  209. self._answer = answer_text.encode(self._encoding)
  210. self.send_response(client.OK)
  211. self.send_header("Content-Length", len(self._answer))
  212. self.send_header("Content-Type", "text/calendar")
  213. self.send_header("Last-Modified", self._calendar.last_modified)
  214. self.send_header("ETag", etag)
  215. self.end_headers()
  216. @log_request_content
  217. @check_rights
  218. def do_DELETE(self):
  219. """Manage DELETE request."""
  220. item = self._calendar.get_item(
  221. xmlutils.name_from_path(self.path, self._calendar))
  222. if item and self.headers.get("If-Match", item.etag) == item.etag:
  223. # No ETag precondition or precondition verified, delete item
  224. self._answer = xmlutils.delete(self.path, self._calendar)
  225. self.send_response(client.NO_CONTENT)
  226. self.send_header("Content-Length", len(self._answer))
  227. self.end_headers()
  228. self.wfile.write(self._answer)
  229. else:
  230. # No item or ETag precondition not verified, do not delete item
  231. self.send_response(client.PRECONDITION_FAILED)
  232. @log_request_content
  233. @check_rights
  234. def do_MKCALENDAR(self):
  235. """Manage MKCALENDAR request."""
  236. self.send_response(client.CREATED)
  237. self.end_headers()
  238. @log_request_content
  239. def do_OPTIONS(self):
  240. """Manage OPTIONS request."""
  241. self.send_response(client.OK)
  242. self.send_header(
  243. "Allow", "DELETE, HEAD, GET, MKCALENDAR, "
  244. "OPTIONS, PROPFIND, PUT, REPORT")
  245. self.send_header("DAV", "1, calendar-access")
  246. self.end_headers()
  247. @log_request_content
  248. def do_PROPFIND(self):
  249. """Manage PROPFIND request."""
  250. self._answer = xmlutils.propfind(
  251. self.path, self._content, self._calendar,
  252. self.headers.get("depth", "infinity"))
  253. self.send_response(client.MULTI_STATUS)
  254. self.send_header("DAV", "1, calendar-access")
  255. self.send_header("Content-Length", len(self._answer))
  256. self.send_header("Content-Type", "text/xml")
  257. self.end_headers()
  258. self.wfile.write(self._answer)
  259. @log_request_content
  260. @check_rights
  261. def do_PUT(self):
  262. """Manage PUT request."""
  263. item_name = xmlutils.name_from_path(self.path, self._calendar)
  264. item = self._calendar.get_item(item_name)
  265. if (not item and not self.headers.get("If-Match")) or \
  266. (item and self.headers.get("If-Match", item.etag) == item.etag):
  267. # PUT allowed in 3 cases
  268. # Case 1: No item and no ETag precondition: Add new item
  269. # Case 2: Item and ETag precondition verified: Modify item
  270. # Case 3: Item and no Etag precondition: Force modifying item
  271. ical_request = self._decode(self._content)
  272. xmlutils.put(self.path, ical_request, self._calendar)
  273. etag = self._calendar.get_item(item_name).etag
  274. self.send_response(client.CREATED)
  275. self.send_header("ETag", etag)
  276. self.end_headers()
  277. else:
  278. # PUT rejected in all other cases
  279. self.send_response(client.PRECONDITION_FAILED)
  280. @log_request_content
  281. @check_rights
  282. def do_REPORT(self):
  283. """Manage REPORT request."""
  284. self._answer = xmlutils.report(self.path, self._content, self._calendar)
  285. self.send_response(client.MULTI_STATUS)
  286. self.send_header("Content-Length", len(self._answer))
  287. self.end_headers()
  288. self.wfile.write(self._answer)
  289. # pylint: enable=C0103