server.py 10 KB

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