__init__.py 9.1 KB

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