__init__.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008-2010 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-msg=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-msg=F0401
  42. from radicale import acl, config, ical, xmlutils
  43. def _check(request, function):
  44. """Check if user has sufficient rights for performing ``request``."""
  45. authorization = request.headers.get("Authorization", None)
  46. if authorization:
  47. challenge = authorization.lstrip("Basic").strip().encode("ascii")
  48. # ``_check`` decorator can access ``request`` protected functions
  49. # pylint: disable-msg=W0212
  50. plain = request._decode(base64.b64decode(challenge))
  51. # pylint: enable-msg=W0212
  52. user, password = plain.split(":")
  53. else:
  54. user = password = None
  55. if request.server.acl.has_right(user, password):
  56. function(request)
  57. else:
  58. request.send_response(client.UNAUTHORIZED)
  59. request.send_header(
  60. "WWW-Authenticate",
  61. "Basic realm=\"Radicale Server - Password Required\"")
  62. request.end_headers()
  63. class HTTPServer(server.HTTPServer):
  64. """HTTP server."""
  65. # Maybe a Pylint bug, ``__init__`` calls ``server.HTTPServer.__init__``
  66. # pylint: disable-msg=W0231
  67. def __init__(self, address, handler):
  68. """Create server."""
  69. server.HTTPServer.__init__(self, address, handler)
  70. self.acl = acl.load()
  71. # pylint: enable-msg=W0231
  72. class HTTPSServer(HTTPServer):
  73. """HTTPS server."""
  74. def __init__(self, address, handler):
  75. """Create server by wrapping HTTP socket in an SSL socket."""
  76. # Fails with Python 2.5, import if needed
  77. # pylint: disable-msg=F0401
  78. import ssl
  79. # pylint: enable-msg=F0401
  80. HTTPServer.__init__(self, address, handler)
  81. self.socket = ssl.wrap_socket(
  82. socket.socket(self.address_family, self.socket_type),
  83. server_side=True,
  84. certfile=config.get("server", "certificate"),
  85. keyfile=config.get("server", "key"),
  86. ssl_version=ssl.PROTOCOL_SSLv23)
  87. self.server_bind()
  88. self.server_activate()
  89. class CalendarHTTPHandler(server.BaseHTTPRequestHandler):
  90. """HTTP requests handler for calendars."""
  91. _encoding = config.get("encoding", "request")
  92. # Decorator checking rights before performing request
  93. check_rights = lambda function: lambda request: _check(request, function)
  94. @property
  95. def _calendar(self):
  96. """The ``ical.Calendar`` object corresponding to the given path."""
  97. # ``self.path`` must be something like a posix path
  98. # ``normpath`` should clean malformed and malicious request paths
  99. attributes = posixpath.normpath(self.path.strip("/")).split("/")
  100. if len(attributes) >= 2:
  101. path = "%s/%s" % (attributes[0], attributes[1])
  102. return ical.Calendar(path)
  103. def _decode(self, text):
  104. """Try to decode text according to various parameters."""
  105. # List of charsets to try
  106. charsets = []
  107. # First append content charset given in the request
  108. content_type = self.headers.get("Content-Type", None)
  109. if content_type and "charset=" in content_type:
  110. charsets.append(content_type.split("charset=")[1].strip())
  111. # Then append default Radicale charset
  112. charsets.append(self._encoding)
  113. # Then append various fallbacks
  114. charsets.append("utf-8")
  115. charsets.append("iso8859-1")
  116. # Try to decode
  117. for charset in charsets:
  118. try:
  119. return text.decode(charset)
  120. except UnicodeDecodeError:
  121. pass
  122. raise UnicodeDecodeError
  123. # Naming methods ``do_*`` is OK here
  124. # pylint: disable-msg=C0103
  125. @check_rights
  126. def do_GET(self):
  127. """Manage GET request."""
  128. answer = self._calendar.text.encode(self._encoding)
  129. self.send_response(client.OK)
  130. self.send_header("Content-Length", len(answer))
  131. self.end_headers()
  132. self.wfile.write(answer)
  133. @check_rights
  134. def do_DELETE(self):
  135. """Manage DELETE request."""
  136. item = self._calendar.get_item(xmlutils.name_from_path(self.path))
  137. if item and self.headers.get("If-Match", item.etag) == item.etag:
  138. # No ETag precondition or precondition verified, delete item
  139. answer = xmlutils.delete(self.path, self._calendar)
  140. self.send_response(client.NO_CONTENT)
  141. self.send_header("Content-Length", len(answer))
  142. self.end_headers()
  143. self.wfile.write(answer)
  144. else:
  145. # No item or ETag precondition not verified, do not delete item
  146. self.send_response(client.PRECONDITION_FAILED)
  147. def do_OPTIONS(self):
  148. """Manage OPTIONS request."""
  149. self.send_response(client.OK)
  150. self.send_header("Allow", "DELETE, GET, OPTIONS, PROPFIND, PUT, REPORT")
  151. self.send_header("DAV", "1, calendar-access")
  152. self.end_headers()
  153. def do_PROPFIND(self):
  154. """Manage PROPFIND request."""
  155. xml_request = self.rfile.read(int(self.headers["Content-Length"]))
  156. answer = xmlutils.propfind(self.path, xml_request, self._calendar)
  157. self.send_response(client.MULTI_STATUS)
  158. self.send_header("DAV", "1, calendar-access")
  159. self.send_header("Content-Length", len(answer))
  160. self.end_headers()
  161. self.wfile.write(answer)
  162. @check_rights
  163. def do_PUT(self):
  164. """Manage PUT request."""
  165. item = self._calendar.get_item(xmlutils.name_from_path(self.path))
  166. if (not item and not self.headers.get("If-Match")) or \
  167. (item and self.headers.get("If-Match", item.etag) == item.etag):
  168. # PUT allowed in 3 cases
  169. # Case 1: No item and no ETag precondition: Add new item
  170. # Case 2: Item and ETag precondition verified: Modify item
  171. # Case 3: Item and no Etag precondition: Force modifying item
  172. ical_request = self._decode(
  173. self.rfile.read(int(self.headers["Content-Length"])))
  174. xmlutils.put(self.path, ical_request, self._calendar)
  175. self.send_response(client.CREATED)
  176. else:
  177. # PUT rejected in all other cases
  178. self.send_response(client.PRECONDITION_FAILED)
  179. @check_rights
  180. def do_REPORT(self):
  181. """Manage REPORT request."""
  182. xml_request = self.rfile.read(int(self.headers["Content-Length"]))
  183. answer = xmlutils.report(self.path, xml_request, self._calendar)
  184. self.send_response(client.MULTI_STATUS)
  185. self.send_header("Content-Length", len(answer))
  186. self.end_headers()
  187. self.wfile.write(answer)
  188. # pylint: enable-msg=C0103