server.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 socket
  27. import socketserver
  28. import ssl
  29. import sys
  30. import wsgiref.simple_server
  31. from configparser import ConfigParser
  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_locked(self, request, client_address):
  74. return super().finish_request(request, client_address)
  75. def finish_request(self, request, client_address):
  76. with self.connections_guard:
  77. return self.finish_request_locked(request, client_address)
  78. def handle_error(self, request, client_address):
  79. if issubclass(sys.exc_info()[0], socket.timeout):
  80. logger.info("client timed out", exc_info=True)
  81. else:
  82. logger.error("An exception occurred during request: %s",
  83. sys.exc_info()[1], exc_info=True)
  84. class ParallelHTTPSServer(ParallelHTTPServer):
  85. # These class attributes must be set before creating instance
  86. certificate = None
  87. key = None
  88. protocol = None
  89. ciphers = None
  90. certificate_authority = None
  91. def __init__(self, address, handler, bind_and_activate=True):
  92. """Create server by wrapping HTTP socket in an SSL socket."""
  93. # Do not bind and activate, as we change the socket
  94. super().__init__(address, handler, False)
  95. self.socket = ssl.wrap_socket(
  96. self.socket, self.key, self.certificate, server_side=True,
  97. cert_reqs=ssl.CERT_REQUIRED if self.certificate_authority else
  98. ssl.CERT_NONE,
  99. ca_certs=self.certificate_authority or None,
  100. ssl_version=self.protocol, ciphers=self.ciphers,
  101. do_handshake_on_connect=False)
  102. if bind_and_activate:
  103. try:
  104. self.server_bind()
  105. self.server_activate()
  106. except BaseException:
  107. self.server_close()
  108. raise
  109. def finish_request(self, request, client_address):
  110. with self.connections_guard:
  111. try:
  112. try:
  113. request.do_handshake()
  114. except socket.timeout:
  115. raise
  116. except Exception as e:
  117. raise RuntimeError("SSL handshake failed: %s" % e) from e
  118. except Exception:
  119. try:
  120. self.handle_error(request, client_address)
  121. finally:
  122. self.shutdown_request(request)
  123. return
  124. return super().finish_request_locked(request, client_address)
  125. class ServerHandler(wsgiref.simple_server.ServerHandler):
  126. # Don't pollute WSGI environ with OS environment
  127. os_environ = {}
  128. def log_exception(self, exc_info):
  129. logger.error("An exception occurred during request: %s",
  130. exc_info[1], exc_info=exc_info)
  131. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  132. """HTTP requests handler."""
  133. def log_request(self, code="-", size="-"):
  134. """Disable request logging."""
  135. def log_error(self, format, *args):
  136. msg = format % args
  137. logger.error("An error occurred during request: %s" % msg)
  138. def get_environ(self):
  139. env = super().get_environ()
  140. if hasattr(self.connection, "getpeercert"):
  141. # The certificate can be evaluated by the auth module
  142. env["REMOTE_CERTIFICATE"] = self.connection.getpeercert()
  143. # Parent class only tries latin1 encoding
  144. env["PATH_INFO"] = unquote(self.path.split("?", 1)[0])
  145. return env
  146. def handle(self):
  147. """Copy of WSGIRequestHandler.handle with different ServerHandler"""
  148. self.raw_requestline = self.rfile.readline(65537)
  149. if len(self.raw_requestline) > 65536:
  150. self.requestline = ""
  151. self.request_version = ""
  152. self.command = ""
  153. self.send_error(414)
  154. return
  155. if not self.parse_request():
  156. return
  157. handler = ServerHandler(
  158. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  159. )
  160. handler.request_handler = self
  161. handler.run(self.server.get_app())
  162. def serve(configuration, shutdown_socket=None):
  163. """Serve radicale from configuration."""
  164. logger.info("Starting Radicale")
  165. # Copy configuration before modifying
  166. config_copy = ConfigParser()
  167. config_copy.read_dict(configuration)
  168. configuration = config_copy
  169. configuration["internal"]["internal_server"] = "True"
  170. # Create collection servers
  171. servers = {}
  172. if configuration.getboolean("server", "ssl"):
  173. server_class = ParallelHTTPSServer
  174. else:
  175. server_class = ParallelHTTPServer
  176. class ServerCopy(server_class):
  177. """Copy, avoids overriding the original class attributes."""
  178. ServerCopy.client_timeout = configuration.getint("server", "timeout")
  179. ServerCopy.max_connections = configuration.getint(
  180. "server", "max_connections")
  181. if configuration.getboolean("server", "ssl"):
  182. ServerCopy.certificate = configuration.get("server", "certificate")
  183. ServerCopy.key = configuration.get("server", "key")
  184. ServerCopy.certificate_authority = configuration.get(
  185. "server", "certificate_authority")
  186. ServerCopy.ciphers = configuration.get("server", "ciphers")
  187. ServerCopy.protocol = getattr(
  188. ssl, configuration.get("server", "protocol"), ssl.PROTOCOL_SSLv23)
  189. # Test if the SSL files can be read
  190. for name in ["certificate", "key"] + (
  191. ["certificate_authority"]
  192. if ServerCopy.certificate_authority else []):
  193. filename = getattr(ServerCopy, name)
  194. try:
  195. open(filename, "r").close()
  196. except OSError as e:
  197. raise RuntimeError("Failed to read SSL %s %r: %s" %
  198. (name, filename, e)) from e
  199. class RequestHandlerCopy(RequestHandler):
  200. """Copy, avoids overriding the original class attributes."""
  201. if not configuration.getboolean("server", "dns_lookup"):
  202. RequestHandlerCopy.address_string = lambda self: self.client_address[0]
  203. for host in configuration.get("server", "hosts").split(","):
  204. try:
  205. address, port = host.strip().rsplit(":", 1)
  206. address, port = address.strip("[] "), int(port)
  207. except ValueError as e:
  208. raise RuntimeError(
  209. "Failed to parse address %r: %s" % (host, e)) from e
  210. application = Application(configuration)
  211. try:
  212. server = wsgiref.simple_server.make_server(
  213. address, port, application, ServerCopy, RequestHandlerCopy)
  214. except OSError as e:
  215. raise RuntimeError(
  216. "Failed to start server %r: %s" % (host, e)) from e
  217. servers[server.socket] = server
  218. logger.info("Listening to %r on port %d%s",
  219. server.server_name, server.server_port, " using SSL"
  220. if configuration.getboolean("server", "ssl") else "")
  221. # Main loop: wait for requests on any of the servers or program shutdown
  222. sockets = list(servers.keys())
  223. # Use socket pair to get notified of program shutdown
  224. if shutdown_socket:
  225. sockets.append(shutdown_socket)
  226. select_timeout = None
  227. if os.name == "nt":
  228. # Fallback to busy waiting. (select.select blocks SIGINT on Windows.)
  229. select_timeout = 1.0
  230. logger.info("Radicale server ready")
  231. while True:
  232. rlist, _, xlist = select.select(sockets, [], sockets, select_timeout)
  233. if xlist:
  234. raise RuntimeError("unhandled socket error")
  235. if shutdown_socket in rlist:
  236. logger.info("Stopping Radicale")
  237. break
  238. if rlist:
  239. server = servers.get(rlist[0])
  240. if server:
  241. server.handle_request()