__init__.py 11 KB

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