server.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Radicale WSGI server.
  20. """
  21. import contextlib
  22. import os
  23. import select
  24. import signal
  25. import socket
  26. import socketserver
  27. import ssl
  28. import sys
  29. import threading
  30. import wsgiref.simple_server
  31. from urllib.parse import unquote
  32. from radicale import Application
  33. from radicale.log import logger
  34. class HTTPServer(wsgiref.simple_server.WSGIServer):
  35. """HTTP server."""
  36. # These class attributes must be set before creating instance
  37. client_timeout = None
  38. max_connections = None
  39. def __init__(self, address, handler, bind_and_activate=True):
  40. """Create server."""
  41. ipv6 = ":" in address[0]
  42. if ipv6:
  43. self.address_family = socket.AF_INET6
  44. # Do not bind and activate, as we might change socket options
  45. super().__init__(address, handler, False)
  46. if ipv6:
  47. # Only allow IPv6 connections to the IPv6 socket
  48. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  49. if self.max_connections:
  50. self.connections_guard = threading.BoundedSemaphore(
  51. self.max_connections)
  52. else:
  53. # use dummy context manager
  54. self.connections_guard = contextlib.ExitStack()
  55. if bind_and_activate:
  56. try:
  57. self.server_bind()
  58. self.server_activate()
  59. except BaseException:
  60. self.server_close()
  61. raise
  62. def get_request(self):
  63. # Set timeout for client
  64. _socket, address = super().get_request()
  65. if self.client_timeout:
  66. _socket.settimeout(self.client_timeout)
  67. return _socket, address
  68. def handle_error(self, request, client_address):
  69. if issubclass(sys.exc_info()[0], socket.timeout):
  70. logger.info("client timed out", exc_info=True)
  71. else:
  72. logger.error("An exception occurred during request: %s",
  73. sys.exc_info()[1], exc_info=True)
  74. class HTTPSServer(HTTPServer):
  75. """HTTPS server."""
  76. # These class attributes must be set before creating instance
  77. certificate = None
  78. key = None
  79. protocol = None
  80. ciphers = None
  81. certificate_authority = None
  82. def __init__(self, address, handler):
  83. """Create server by wrapping HTTP socket in an SSL socket."""
  84. super().__init__(address, handler, bind_and_activate=False)
  85. self.socket = ssl.wrap_socket(
  86. self.socket, self.key, self.certificate, server_side=True,
  87. cert_reqs=ssl.CERT_REQUIRED if self.certificate_authority else
  88. ssl.CERT_NONE,
  89. ca_certs=self.certificate_authority or None,
  90. ssl_version=self.protocol, ciphers=self.ciphers,
  91. do_handshake_on_connect=False)
  92. self.server_bind()
  93. self.server_activate()
  94. class ThreadedHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
  95. def process_request_thread(self, request, client_address):
  96. with self.connections_guard:
  97. return super().process_request_thread(request, client_address)
  98. class ThreadedHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer):
  99. def process_request_thread(self, request, client_address):
  100. try:
  101. try:
  102. request.do_handshake()
  103. except socket.timeout:
  104. raise
  105. except Exception as e:
  106. raise RuntimeError("SSL handshake failed: %s" % e) from e
  107. except Exception:
  108. try:
  109. self.handle_error(request, client_address)
  110. finally:
  111. self.shutdown_request(request)
  112. return
  113. with self.connections_guard:
  114. return super().process_request_thread(request, client_address)
  115. class ServerHandler(wsgiref.simple_server.ServerHandler):
  116. # Don't pollute WSGI environ with OS environment
  117. os_environ = {}
  118. def log_exception(self, exc_info):
  119. logger.error("An exception occurred during request: %s",
  120. exc_info[1], exc_info=exc_info)
  121. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  122. """HTTP requests handler."""
  123. def log_request(self, code="-", size="-"):
  124. """Disable request logging."""
  125. def log_error(self, format, *args):
  126. msg = format % args
  127. logger.error("An error occurred during request: %s" % msg)
  128. def get_environ(self):
  129. env = super().get_environ()
  130. if hasattr(self.connection, "getpeercert"):
  131. # The certificate can be evaluated by the auth module
  132. env["REMOTE_CERTIFICATE"] = self.connection.getpeercert()
  133. # Parent class only tries latin1 encoding
  134. env["PATH_INFO"] = unquote(self.path.split("?", 1)[0])
  135. return env
  136. def handle(self):
  137. """Copy of WSGIRequestHandler.handle with different ServerHandler"""
  138. self.raw_requestline = self.rfile.readline(65537)
  139. if len(self.raw_requestline) > 65536:
  140. self.requestline = ''
  141. self.request_version = ''
  142. self.command = ''
  143. self.send_error(414)
  144. return
  145. if not self.parse_request():
  146. return
  147. handler = ServerHandler(
  148. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  149. )
  150. handler.request_handler = self
  151. handler.run(self.server.get_app())
  152. def serve(configuration):
  153. """Serve radicale from configuration."""
  154. logger.info("Starting Radicale")
  155. # Create collection servers
  156. servers = {}
  157. if configuration.getboolean("server", "ssl"):
  158. server_class = ThreadedHTTPSServer
  159. server_class.certificate = configuration.get("server", "certificate")
  160. server_class.key = configuration.get("server", "key")
  161. server_class.certificate_authority = configuration.get(
  162. "server", "certificate_authority")
  163. server_class.ciphers = configuration.get("server", "ciphers")
  164. server_class.protocol = getattr(
  165. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  166. # Test if the SSL files can be read
  167. for name in ["certificate", "key"] + (
  168. ["certificate_authority"]
  169. if server_class.certificate_authority else []):
  170. filename = getattr(server_class, name)
  171. try:
  172. open(filename, "r").close()
  173. except OSError as e:
  174. raise RuntimeError("Failed to read SSL %s %r: %s" %
  175. (name, filename, e)) from e
  176. else:
  177. server_class = ThreadedHTTPServer
  178. server_class.client_timeout = configuration.getint("server", "timeout")
  179. server_class.max_connections = configuration.getint(
  180. "server", "max_connections")
  181. if not configuration.getboolean("server", "dns_lookup"):
  182. RequestHandler.address_string = lambda self: self.client_address[0]
  183. shutdown_program = False
  184. for host in configuration.get("server", "hosts").split(","):
  185. try:
  186. address, port = host.strip().rsplit(":", 1)
  187. address, port = address.strip("[] "), int(port)
  188. except ValueError as e:
  189. raise RuntimeError(
  190. "Failed to parse address %r: %s" % (host, e)) from e
  191. application = Application(configuration, internal_server=True)
  192. try:
  193. server = wsgiref.simple_server.make_server(
  194. address, port, application, server_class, RequestHandler)
  195. except OSError as e:
  196. raise RuntimeError(
  197. "Failed to start server %r: %s" % (host, e)) from e
  198. servers[server.socket] = server
  199. logger.info("Listening to %r on port %d%s",
  200. server.server_name, server.server_port, " using SSL"
  201. if configuration.getboolean("server", "ssl") else "")
  202. # Create a socket pair to notify the select syscall of program shutdown
  203. shutdown_program_socket_in, shutdown_program_socket_out = (
  204. socket.socketpair())
  205. # SIGTERM and SIGINT (aka KeyboardInterrupt) should just mark this for
  206. # shutdown
  207. def shutdown(*args):
  208. nonlocal shutdown_program
  209. if shutdown_program:
  210. # Ignore following signals
  211. return
  212. logger.info("Stopping Radicale")
  213. shutdown_program = True
  214. shutdown_program_socket_in.sendall(b" ")
  215. signal.signal(signal.SIGTERM, shutdown)
  216. signal.signal(signal.SIGINT, shutdown)
  217. # Main loop: wait for requests on any of the servers or program shutdown
  218. sockets = list(servers.keys())
  219. # Use socket pair to get notified of program shutdown
  220. sockets.append(shutdown_program_socket_out)
  221. select_timeout = None
  222. if os.name == "nt":
  223. # Fallback to busy waiting. (select.select blocks SIGINT on Windows.)
  224. select_timeout = 1.0
  225. logger.info("Radicale server ready")
  226. while not shutdown_program:
  227. try:
  228. rlist, _, xlist = select.select(
  229. sockets, [], sockets, select_timeout)
  230. except (KeyboardInterrupt, select.error):
  231. # SIGINT is handled by signal handler above
  232. rlist, xlist = [], []
  233. if xlist:
  234. raise RuntimeError("unhandled socket error")
  235. if rlist:
  236. server = servers.get(rlist[0])
  237. if server:
  238. server.handle_request()