server.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2023 Unrud <unrud@outlook.com>
  6. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  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. Built-in WSGI server.
  22. """
  23. import http
  24. import select
  25. import socket
  26. import socketserver
  27. import ssl
  28. import sys
  29. import wsgiref.simple_server
  30. from typing import (Any, Callable, Dict, List, MutableMapping, Optional, Set,
  31. Tuple, Union)
  32. from urllib.parse import unquote
  33. from radicale import Application, config, utils
  34. from radicale.log import logger
  35. COMPAT_EAI_ADDRFAMILY: int
  36. if hasattr(socket, "EAI_ADDRFAMILY"):
  37. COMPAT_EAI_ADDRFAMILY = socket.EAI_ADDRFAMILY # type:ignore[attr-defined]
  38. elif hasattr(socket, "EAI_NONAME"):
  39. # Windows and BSD don't have a special error code for this
  40. COMPAT_EAI_ADDRFAMILY = socket.EAI_NONAME
  41. COMPAT_EAI_NODATA: int
  42. if hasattr(socket, "EAI_NODATA"):
  43. COMPAT_EAI_NODATA = socket.EAI_NODATA
  44. elif hasattr(socket, "EAI_NONAME"):
  45. # Windows and BSD don't have a special error code for this
  46. COMPAT_EAI_NODATA = socket.EAI_NONAME
  47. COMPAT_IPPROTO_IPV6: int
  48. if hasattr(socket, "IPPROTO_IPV6"):
  49. COMPAT_IPPROTO_IPV6 = socket.IPPROTO_IPV6
  50. elif sys.platform == "win32":
  51. # HACK: https://bugs.python.org/issue29515
  52. COMPAT_IPPROTO_IPV6 = 41
  53. # IPv4 (host, port) and IPv6 (host, port, flowinfo, scopeid)
  54. ADDRESS_TYPE = Union[Tuple[Union[str, bytes, bytearray], int],
  55. Tuple[str, int, int, int]]
  56. def format_address(address: ADDRESS_TYPE) -> str:
  57. host, port, *_ = address
  58. if not isinstance(host, str):
  59. raise NotImplementedError("Unsupported address format: %r" %
  60. (address,))
  61. if host.find(":") == -1:
  62. return "%s:%d" % (host, port)
  63. else:
  64. return "[%s]:%d" % (host, port)
  65. class ParallelHTTPServer(socketserver.ThreadingMixIn,
  66. wsgiref.simple_server.WSGIServer):
  67. configuration: config.Configuration
  68. worker_sockets: Set[socket.socket]
  69. _timeout: float
  70. # We wait for child threads ourself (ThreadingMixIn)
  71. block_on_close: bool = False
  72. daemon_threads: bool = True
  73. def __init__(self, configuration: config.Configuration, family: int,
  74. address: Tuple[str, int], RequestHandlerClass:
  75. Callable[..., http.server.BaseHTTPRequestHandler]) -> None:
  76. self.configuration = configuration
  77. self.address_family = family
  78. super().__init__(address, RequestHandlerClass)
  79. self.worker_sockets = set()
  80. self._timeout = configuration.get("server", "timeout")
  81. def server_bind(self) -> None:
  82. if self.address_family == socket.AF_INET6:
  83. # Only allow IPv6 connections to the IPv6 socket
  84. self.socket.setsockopt(COMPAT_IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  85. super().server_bind()
  86. def get_request( # type:ignore[override]
  87. self) -> Tuple[socket.socket, Tuple[ADDRESS_TYPE, socket.socket]]:
  88. # Set timeout for client
  89. request: socket.socket
  90. client_address: ADDRESS_TYPE
  91. request, client_address = super().get_request() # type:ignore[misc]
  92. if self._timeout > 0:
  93. request.settimeout(self._timeout)
  94. worker_socket, worker_socket_out = socket.socketpair()
  95. self.worker_sockets.add(worker_socket_out)
  96. # HACK: Forward `worker_socket` via `client_address` return value
  97. # to worker thread.
  98. # The super class calls `verify_request`, `process_request` and
  99. # `handle_error` with modified `client_address` value.
  100. return request, (client_address, worker_socket)
  101. def verify_request( # type:ignore[override]
  102. self, request: socket.socket, client_address_and_socket:
  103. Tuple[ADDRESS_TYPE, socket.socket]) -> bool:
  104. return True
  105. def process_request( # type:ignore[override]
  106. self, request: socket.socket, client_address_and_socket:
  107. Tuple[ADDRESS_TYPE, socket.socket]) -> None:
  108. # HACK: Super class calls `finish_request` in new thread with
  109. # `client_address_and_socket`
  110. return super().process_request(
  111. request, client_address_and_socket) # type:ignore[arg-type]
  112. def finish_request( # type:ignore[override]
  113. self, request: socket.socket, client_address_and_socket:
  114. Tuple[ADDRESS_TYPE, socket.socket]) -> None:
  115. # HACK: Unpack `client_address_and_socket` and call super class
  116. # `finish_request` with original `client_address`
  117. client_address, worker_socket = client_address_and_socket
  118. try:
  119. return self.finish_request_locked(request, client_address)
  120. finally:
  121. worker_socket.close()
  122. def finish_request_locked(self, request: socket.socket,
  123. client_address: ADDRESS_TYPE) -> None:
  124. return super().finish_request(
  125. request, client_address) # type:ignore[arg-type]
  126. def handle_error( # type:ignore[override]
  127. self, request: socket.socket,
  128. client_address_or_client_address_and_socket:
  129. Union[ADDRESS_TYPE, Tuple[ADDRESS_TYPE, socket.socket]]) -> None:
  130. # HACK: This method can be called with the modified
  131. # `client_address_and_socket` or the original `client_address` value
  132. e = sys.exc_info()[1]
  133. assert e is not None
  134. if isinstance(e, socket.timeout):
  135. logger.info("Client timed out", exc_info=True)
  136. else:
  137. logger.error("An exception occurred during request: %s",
  138. sys.exc_info()[1], exc_info=True)
  139. class ParallelHTTPSServer(ParallelHTTPServer):
  140. def server_bind(self) -> None:
  141. super().server_bind()
  142. # Wrap the TCP socket in an SSL socket
  143. certfile: str = self.configuration.get("server", "certificate")
  144. keyfile: str = self.configuration.get("server", "key")
  145. cafile: str = self.configuration.get("server", "certificate_authority")
  146. protocol: str = self.configuration.get("server", "protocol")
  147. ciphersuite: str = self.configuration.get("server", "ciphersuite")
  148. # Test if the files can be read
  149. for name, filename in [("certificate", certfile), ("key", keyfile),
  150. ("certificate_authority", cafile)]:
  151. type_name = config.DEFAULT_CONFIG_SCHEMA["server"][name][
  152. "type"].__name__
  153. source = self.configuration.get_source("server", name)
  154. if name == "certificate_authority" and not filename:
  155. continue
  156. try:
  157. open(filename).close()
  158. except OSError as e:
  159. raise RuntimeError(
  160. "Invalid %s value for option %r in section %r in %s: %r "
  161. "(%s)" % (type_name, name, "server", source, filename,
  162. e)) from e
  163. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  164. logger.info("SSL load files certificate='%s' key='%s'", certfile, keyfile)
  165. context.load_cert_chain(certfile=certfile, keyfile=keyfile)
  166. if protocol:
  167. logger.info("SSL set explicit protocols (maybe not all supported by underlying OpenSSL): '%s'", protocol)
  168. context.options = utils.ssl_context_options_by_protocol(protocol, context.options)
  169. context.minimum_version = utils.ssl_context_minimum_version_by_options(context.options)
  170. if (context.minimum_version == 0):
  171. raise RuntimeError("No SSL minimum protocol active")
  172. context.maximum_version = utils.ssl_context_maximum_version_by_options(context.options)
  173. if (context.maximum_version == 0):
  174. raise RuntimeError("No SSL maximum protocol active")
  175. else:
  176. logger.info("SSL active protocols: (system-default)")
  177. logger.debug("SSL minimum acceptable protocol: %s", context.minimum_version)
  178. logger.debug("SSL maximum acceptable protocol: %s", context.maximum_version)
  179. logger.info("SSL accepted protocols: %s", ' '.join(utils.ssl_get_protocols(context)))
  180. if ciphersuite:
  181. logger.info("SSL set explicit ciphersuite (maybe not all supported by underlying OpenSSL): '%s'", ciphersuite)
  182. context.set_ciphers(ciphersuite)
  183. else:
  184. logger.info("SSL active ciphersuite: (system-default)")
  185. cipherlist = []
  186. for entry in context.get_ciphers():
  187. cipherlist.append(entry["name"])
  188. logger.info("SSL accepted ciphers: %s", ' '.join(cipherlist))
  189. if cafile:
  190. logger.info("SSL enable mandatory client certificate verification using CA file='%s'", cafile)
  191. context.load_verify_locations(cafile=cafile)
  192. context.verify_mode = ssl.CERT_REQUIRED
  193. self.socket = context.wrap_socket(
  194. self.socket, server_side=True, do_handshake_on_connect=False)
  195. def finish_request_locked( # type:ignore[override]
  196. self, request: ssl.SSLSocket, client_address: ADDRESS_TYPE
  197. ) -> None:
  198. try:
  199. try:
  200. request.do_handshake()
  201. except socket.timeout:
  202. raise
  203. except Exception as e:
  204. raise RuntimeError("SSL handshake failed: %s" % e) from e
  205. except Exception:
  206. try:
  207. self.handle_error(request, client_address)
  208. finally:
  209. self.shutdown_request(request) # type:ignore[attr-defined]
  210. return
  211. return super().finish_request_locked(request, client_address)
  212. class ServerHandler(wsgiref.simple_server.ServerHandler):
  213. # Don't pollute WSGI environ with OS environment
  214. os_environ: MutableMapping[str, str] = {}
  215. def log_exception(self, exc_info) -> None:
  216. logger.error("An exception occurred during request: %s",
  217. exc_info[1], exc_info=exc_info) # type:ignore[arg-type]
  218. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  219. """HTTP requests handler."""
  220. # HACK: Assigned in `socketserver.StreamRequestHandler`
  221. connection: socket.socket
  222. def log_request(self, code: Union[int, str] = "-",
  223. size: Union[int, str] = "-") -> None:
  224. pass # Disable request logging.
  225. def log_error(self, format_: str, *args: Any) -> None:
  226. logger.error("An error occurred during request: %s", format_ % args)
  227. def get_environ(self) -> Dict[str, Any]:
  228. env = super().get_environ()
  229. if isinstance(self.connection, ssl.SSLSocket):
  230. # The certificate can be evaluated by the auth module
  231. env["REMOTE_CERTIFICATE"] = self.connection.getpeercert()
  232. # Parent class only tries latin1 encoding
  233. env["PATH_INFO"] = unquote(self.path.split("?", 1)[0])
  234. return env
  235. def handle(self) -> None:
  236. """Copy of WSGIRequestHandler.handle with different ServerHandler"""
  237. self.raw_requestline = self.rfile.readline(65537)
  238. if len(self.raw_requestline) > 65536:
  239. self.requestline = ""
  240. self.request_version = ""
  241. self.command = ""
  242. self.send_error(414)
  243. return
  244. if not self.parse_request():
  245. return
  246. handler = ServerHandler(
  247. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  248. )
  249. handler.request_handler = self # type:ignore[attr-defined]
  250. app = self.server.get_app() # type:ignore[attr-defined]
  251. handler.run(app)
  252. def serve(configuration: config.Configuration,
  253. shutdown_socket: Optional[socket.socket] = None) -> None:
  254. """Serve radicale from configuration.
  255. `shutdown_socket` can be used to gracefully shutdown the server.
  256. The socket can be created with `socket.socketpair()`, when the other socket
  257. gets closed the server stops accepting new requests by clients and the
  258. function returns after all active requests are finished.
  259. """
  260. logger.info("Starting Radicale (%s)", utils.packages_version())
  261. # Copy configuration before modifying
  262. configuration = configuration.copy()
  263. configuration.update({"server": {"_internal_server": "True"}}, "server",
  264. privileged=True)
  265. use_ssl: bool = configuration.get("server", "ssl")
  266. server_class = ParallelHTTPSServer if use_ssl else ParallelHTTPServer
  267. application = Application(configuration)
  268. servers = {}
  269. try:
  270. hosts: List[Tuple[str, int]] = configuration.get("server", "hosts")
  271. for address_port in hosts:
  272. # retrieve IPv4/IPv6 address of address
  273. try:
  274. getaddrinfo = socket.getaddrinfo(address_port[0], address_port[1], 0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
  275. except OSError as e:
  276. logger.warning("cannot retrieve IPv4 or IPv6 address of '%s': %s" % (format_address(address_port), e))
  277. continue
  278. logger.debug("getaddrinfo of '%s': %s" % (format_address(address_port), getaddrinfo))
  279. for (address_family, socket_kind, socket_proto, socket_flags, socket_address) in getaddrinfo:
  280. logger.debug("try to create server socket on '%s'" % (format_address(socket_address)))
  281. try:
  282. server = server_class(configuration, address_family, (socket_address[0], socket_address[1]), RequestHandler)
  283. except OSError as e:
  284. logger.warning("cannot create server socket on '%s': %s" % (format_address(socket_address), e))
  285. continue
  286. servers[server.socket] = server
  287. server.set_app(application)
  288. logger.info("Listening on %r%s",
  289. format_address(server.server_address),
  290. " with SSL" if use_ssl else "")
  291. if not servers:
  292. raise RuntimeError("No servers started")
  293. # Mainloop
  294. select_timeout = None
  295. if sys.platform == "win32":
  296. # Fallback to busy waiting. (select(...) blocks SIGINT on Windows.)
  297. select_timeout = 1.0
  298. max_connections: int = configuration.get("server", "max_connections")
  299. logger.info("Radicale server ready")
  300. while True:
  301. rlist: List[socket.socket] = []
  302. # Wait for finished clients
  303. for server in servers.values():
  304. rlist.extend(server.worker_sockets)
  305. # Accept new connections if max_connections is not reached
  306. if max_connections <= 0 or len(rlist) < max_connections:
  307. rlist.extend(servers)
  308. # Use socket to get notified of program shutdown
  309. if shutdown_socket is not None:
  310. rlist.append(shutdown_socket)
  311. rlist, _, _ = select.select(rlist, [], [], select_timeout)
  312. rset = set(rlist)
  313. if shutdown_socket in rset:
  314. logger.info("Stopping Radicale")
  315. break
  316. for server in servers.values():
  317. finished_sockets = server.worker_sockets.intersection(rset)
  318. for s in finished_sockets:
  319. s.close()
  320. server.worker_sockets.remove(s)
  321. rset.remove(s)
  322. if finished_sockets:
  323. server.service_actions()
  324. if rset:
  325. active_server = servers.get(rset.pop())
  326. if active_server:
  327. active_server.handle_request()
  328. finally:
  329. # Wait for clients to finish and close servers
  330. for server in servers.values():
  331. for s in server.worker_sockets:
  332. s.recv(1)
  333. s.close()
  334. server.server_close()