__init__.py 9.5 KB

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