__init__.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 base64
  32. import socket
  33. # Manage Python2/3 different modules
  34. # pylint: disable-msg=F0401
  35. try:
  36. from http import client, server
  37. except ImportError:
  38. import httplib as client
  39. import BaseHTTPServer as server
  40. # pylint: enable-msg=F0401
  41. from radicale import acl, config, ical, xmlutils
  42. def _check(request, function):
  43. """Check if user has sufficient rights for performing ``request``."""
  44. authorization = request.headers.get("Authorization", None)
  45. if authorization:
  46. challenge = authorization.lstrip("Basic").strip().encode("ascii")
  47. plain = request.decode(base64.b64decode(challenge))
  48. user, password = plain.split(":")
  49. else:
  50. user = password = None
  51. if request.server.acl.has_right(user, password):
  52. function(request)
  53. else:
  54. request.send_response(client.UNAUTHORIZED)
  55. request.send_header(
  56. "WWW-Authenticate",
  57. "Basic realm=\"Radicale Server - Password Required\"")
  58. request.end_headers()
  59. class HTTPServer(server.HTTPServer):
  60. """HTTP server."""
  61. def __init__(self, address, handler):
  62. """Create server."""
  63. server.HTTPServer.__init__(self, address, handler)
  64. self.acl = acl.load()
  65. class HTTPSServer(HTTPServer):
  66. """HTTPS server."""
  67. def __init__(self, address, handler):
  68. """Create server by wrapping HTTP socket in an SSL socket."""
  69. # Fails with Python 2.5, import if needed
  70. # pylint: disable-msg=F0401
  71. import ssl
  72. # pylint: enable-msg=F0401
  73. HTTPServer.__init__(self, address, handler)
  74. self.socket = ssl.wrap_socket(
  75. socket.socket(self.address_family, self.socket_type),
  76. server_side=True,
  77. certfile=config.get("server", "certificate"),
  78. keyfile=config.get("server", "key"),
  79. ssl_version=ssl.PROTOCOL_SSLv23)
  80. self.server_bind()
  81. self.server_activate()
  82. class CalendarHTTPHandler(server.BaseHTTPRequestHandler):
  83. """HTTP requests handler for calendars."""
  84. _encoding = config.get("encoding", "request")
  85. # Decorator checking rights before performing request
  86. check_rights = lambda function: lambda request: _check(request, function)
  87. @property
  88. def _calendar(self):
  89. """The ``ical.Calendar`` object corresponding to the given path."""
  90. # ``normpath`` should clean malformed and malicious request paths
  91. attributes = os.path.normpath(self.path.strip("/")).split("/")
  92. if len(attributes) >= 2:
  93. path = "%s/%s" % (attributes[0], attributes[1])
  94. return ical.Calendar(path)
  95. def _decode(self, text):
  96. """Try to decode text according to various parameters."""
  97. # List of charsets to try
  98. charsets = []
  99. # First append content charset given in the request
  100. content_type = self.headers["Content-Type"]
  101. if content_type and "charset=" in content_type:
  102. charsets.append(content_type.split("charset=")[1].strip())
  103. # Then append default Radicale charset
  104. charsets.append(self._encoding)
  105. # Then append various fallbacks
  106. charsets.append("utf-8")
  107. charsets.append("iso8859-1")
  108. # Try to decode
  109. for charset in charsets:
  110. try:
  111. return text.decode(charset)
  112. except UnicodeDecodeError:
  113. pass
  114. raise UnicodeDecodeError
  115. # Naming methods ``do_*`` is OK here
  116. # pylint: disable-msg=C0103
  117. @check_rights
  118. def do_GET(self):
  119. """Manage GET request."""
  120. answer = self._calendar.read().encode(self._encoding)
  121. self.send_response(client.OK)
  122. self.send_header("Content-Length", len(answer))
  123. self.end_headers()
  124. self.wfile.write(answer)
  125. @check_rights
  126. def do_DELETE(self):
  127. """Manage DELETE request."""
  128. obj = self.headers.get("If-Match", None)
  129. answer = xmlutils.delete(obj, self._calendar, self.path)
  130. self.send_response(client.NO_CONTENT)
  131. self.send_header("Content-Length", len(answer))
  132. self.end_headers()
  133. self.wfile.write(answer)
  134. def do_OPTIONS(self):
  135. """Manage OPTIONS request."""
  136. self.send_response(client.OK)
  137. self.send_header("Allow", "DELETE, GET, OPTIONS, PROPFIND, PUT, REPORT")
  138. self.send_header("DAV", "1, calendar-access")
  139. self.end_headers()
  140. def do_PROPFIND(self):
  141. """Manage PROPFIND request."""
  142. xml_request = self.rfile.read(int(self.headers["Content-Length"]))
  143. answer = xmlutils.propfind(xml_request, self._calendar, self.path)
  144. self.send_response(client.MULTI_STATUS)
  145. self.send_header("DAV", "1, calendar-access")
  146. self.send_header("Content-Length", len(answer))
  147. self.end_headers()
  148. self.wfile.write(answer)
  149. @check_rights
  150. def do_PUT(self):
  151. """Manage PUT request."""
  152. ical_request = self._decode(
  153. self.rfile.read(int(self.headers["Content-Length"])))
  154. obj = self.headers.get("If-Match", None)
  155. xmlutils.put(ical_request, self._calendar, self.path, obj)
  156. self.send_response(client.CREATED)
  157. @check_rights
  158. def do_REPORT(self):
  159. """Manage REPORT request."""
  160. xml_request = self.rfile.read(int(self.headers["Content-Length"]))
  161. answer = xmlutils.report(xml_request, self._calendar, self.path)
  162. self.send_response(client.MULTI_STATUS)
  163. self.send_header("Content-Length", len(answer))
  164. self.end_headers()
  165. self.wfile.write(answer)
  166. # pylint: enable-msg=C0103