__init__.py 6.4 KB

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