server.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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-2019 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 protocol: '%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. else:
  171. logger.info("SSL default protocol active")
  172. logger.info("SSL minimum acceptable protocol: %s", context.minimum_version)
  173. logger.info("SSL accepted protocols: %s", ' '.join(utils.ssl_get_protocols(context)))
  174. if ciphersuite:
  175. logger.info("SSL set explicit ciphersuite: '%s'", ciphersuite)
  176. context.set_ciphers(ciphersuite)
  177. else:
  178. logger.info("SSL default ciphersuite active")
  179. cipherlist = []
  180. for entry in context.get_ciphers():
  181. cipherlist.append(entry["name"])
  182. logger.info("SSL accepted ciphers: %s", ' '.join(cipherlist))
  183. if cafile:
  184. logger.info("SSL enable mandatory client certificate verification using CA file='%s'", cafile)
  185. context.load_verify_locations(cafile=cafile)
  186. context.verify_mode = ssl.CERT_REQUIRED
  187. self.socket = context.wrap_socket(
  188. self.socket, server_side=True, do_handshake_on_connect=False)
  189. def finish_request_locked( # type:ignore[override]
  190. self, request: ssl.SSLSocket, client_address: ADDRESS_TYPE
  191. ) -> None:
  192. try:
  193. try:
  194. request.do_handshake()
  195. except socket.timeout:
  196. raise
  197. except Exception as e:
  198. raise RuntimeError("SSL handshake failed: %s" % e) from e
  199. except Exception:
  200. try:
  201. self.handle_error(request, client_address)
  202. finally:
  203. self.shutdown_request(request) # type:ignore[attr-defined]
  204. return
  205. return super().finish_request_locked(request, client_address)
  206. class ServerHandler(wsgiref.simple_server.ServerHandler):
  207. # Don't pollute WSGI environ with OS environment
  208. os_environ: MutableMapping[str, str] = {}
  209. def log_exception(self, exc_info) -> None:
  210. logger.error("An exception occurred during request: %s",
  211. exc_info[1], exc_info=exc_info) # type:ignore[arg-type]
  212. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  213. """HTTP requests handler."""
  214. # HACK: Assigned in `socketserver.StreamRequestHandler`
  215. connection: socket.socket
  216. def log_request(self, code: Union[int, str] = "-",
  217. size: Union[int, str] = "-") -> None:
  218. pass # Disable request logging.
  219. def log_error(self, format_: str, *args: Any) -> None:
  220. logger.error("An error occurred during request: %s", format_ % args)
  221. def get_environ(self) -> Dict[str, Any]:
  222. env = super().get_environ()
  223. if isinstance(self.connection, ssl.SSLSocket):
  224. # The certificate can be evaluated by the auth module
  225. env["REMOTE_CERTIFICATE"] = self.connection.getpeercert()
  226. # Parent class only tries latin1 encoding
  227. env["PATH_INFO"] = unquote(self.path.split("?", 1)[0])
  228. return env
  229. def handle(self) -> None:
  230. """Copy of WSGIRequestHandler.handle with different ServerHandler"""
  231. self.raw_requestline = self.rfile.readline(65537)
  232. if len(self.raw_requestline) > 65536:
  233. self.requestline = ""
  234. self.request_version = ""
  235. self.command = ""
  236. self.send_error(414)
  237. return
  238. if not self.parse_request():
  239. return
  240. handler = ServerHandler(
  241. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  242. )
  243. handler.request_handler = self # type:ignore[attr-defined]
  244. app = self.server.get_app() # type:ignore[attr-defined]
  245. handler.run(app)
  246. def serve(configuration: config.Configuration,
  247. shutdown_socket: Optional[socket.socket] = None) -> None:
  248. """Serve radicale from configuration.
  249. `shutdown_socket` can be used to gracefully shutdown the server.
  250. The socket can be created with `socket.socketpair()`, when the other socket
  251. gets closed the server stops accepting new requests by clients and the
  252. function returns after all active requests are finished.
  253. """
  254. logger.info("Starting Radicale")
  255. # Copy configuration before modifying
  256. configuration = configuration.copy()
  257. configuration.update({"server": {"_internal_server": "True"}}, "server",
  258. privileged=True)
  259. use_ssl: bool = configuration.get("server", "ssl")
  260. server_class = ParallelHTTPSServer if use_ssl else ParallelHTTPServer
  261. application = Application(configuration)
  262. servers = {}
  263. try:
  264. hosts: List[Tuple[str, int]] = configuration.get("server", "hosts")
  265. for address_port in hosts:
  266. # retrieve IPv4/IPv6 address of address
  267. try:
  268. getaddrinfo = socket.getaddrinfo(address_port[0], address_port[1], 0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
  269. except OSError as e:
  270. logger.warning("cannot retrieve IPv4 or IPv6 address of '%s': %s" % (format_address(address_port), e))
  271. continue
  272. logger.debug("getaddrinfo of '%s': %s" % (format_address(address_port), getaddrinfo))
  273. for (address_family, socket_kind, socket_proto, socket_flags, socket_address) in getaddrinfo:
  274. logger.debug("try to create server socket on '%s'" % (format_address(socket_address)))
  275. try:
  276. server = server_class(configuration, address_family, (socket_address[0], socket_address[1]), RequestHandler)
  277. except OSError as e:
  278. logger.warning("cannot create server socket on '%s': %s" % (format_address(socket_address), e))
  279. continue
  280. servers[server.socket] = server
  281. server.set_app(application)
  282. logger.info("Listening on %r%s",
  283. format_address(server.server_address),
  284. " with SSL" if use_ssl else "")
  285. if not servers:
  286. raise RuntimeError("No servers started")
  287. # Mainloop
  288. select_timeout = None
  289. if sys.platform == "win32":
  290. # Fallback to busy waiting. (select(...) blocks SIGINT on Windows.)
  291. select_timeout = 1.0
  292. max_connections: int = configuration.get("server", "max_connections")
  293. logger.info("Radicale server ready")
  294. while True:
  295. rlist: List[socket.socket] = []
  296. # Wait for finished clients
  297. for server in servers.values():
  298. rlist.extend(server.worker_sockets)
  299. # Accept new connections if max_connections is not reached
  300. if max_connections <= 0 or len(rlist) < max_connections:
  301. rlist.extend(servers)
  302. # Use socket to get notified of program shutdown
  303. if shutdown_socket is not None:
  304. rlist.append(shutdown_socket)
  305. rlist, _, _ = select.select(rlist, [], [], select_timeout)
  306. rset = set(rlist)
  307. if shutdown_socket in rset:
  308. logger.info("Stopping Radicale")
  309. break
  310. for server in servers.values():
  311. finished_sockets = server.worker_sockets.intersection(rset)
  312. for s in finished_sockets:
  313. s.close()
  314. server.worker_sockets.remove(s)
  315. rset.remove(s)
  316. if finished_sockets:
  317. server.service_actions()
  318. if rset:
  319. active_server = servers.get(rset.pop())
  320. if active_server:
  321. active_server.handle_request()
  322. finally:
  323. # Wait for clients to finish and close servers
  324. for server in servers.values():
  325. for s in server.worker_sockets:
  326. s.recv(1)
  327. s.close()
  328. server.server_close()