1
0

__init__.py 11 KB

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