1
0

server.py 16 KB

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