__init__.py 6.3 KB

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