__init__.py 13 KB

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