server.py 10 KB

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