Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. from __future__ import annotations
  2. import http
  3. import logging
  4. import os
  5. import selectors
  6. import socket
  7. import ssl
  8. import sys
  9. import threading
  10. from types import TracebackType
  11. from typing import Any, Callable, Optional, Sequence, Type
  12. from ..extensions.base import ServerExtensionFactory
  13. from ..extensions.permessage_deflate import enable_server_permessage_deflate
  14. from ..headers import validate_subprotocols
  15. from ..http import USER_AGENT
  16. from ..http11 import Request, Response
  17. from ..protocol import CONNECTING, OPEN, Event
  18. from ..server import ServerProtocol
  19. from ..typing import LoggerLike, Origin, Subprotocol
  20. from .compatibility import socket_create_server
  21. from .connection import Connection
  22. from .utils import Deadline
  23. __all__ = ["serve", "unix_serve", "ServerConnection", "WebSocketServer"]
  24. class ServerConnection(Connection):
  25. """
  26. Threaded implementation of a WebSocket server connection.
  27. :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
  28. receiving and sending messages.
  29. It supports iteration to receive messages::
  30. for message in websocket:
  31. process(message)
  32. The iterator exits normally when the connection is closed with close code
  33. 1000 (OK) or 1001 (going away) or without a close code. It raises a
  34. :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
  35. closed with any other code.
  36. Args:
  37. socket: Socket connected to a WebSocket client.
  38. protocol: Sans-I/O connection.
  39. close_timeout: Timeout for closing the connection in seconds.
  40. """
  41. def __init__(
  42. self,
  43. socket: socket.socket,
  44. protocol: ServerProtocol,
  45. *,
  46. close_timeout: Optional[float] = 10,
  47. ) -> None:
  48. self.protocol: ServerProtocol
  49. self.request_rcvd = threading.Event()
  50. super().__init__(
  51. socket,
  52. protocol,
  53. close_timeout=close_timeout,
  54. )
  55. def handshake(
  56. self,
  57. process_request: Optional[
  58. Callable[
  59. [ServerConnection, Request],
  60. Optional[Response],
  61. ]
  62. ] = None,
  63. process_response: Optional[
  64. Callable[
  65. [ServerConnection, Request, Response],
  66. Optional[Response],
  67. ]
  68. ] = None,
  69. server_header: Optional[str] = USER_AGENT,
  70. timeout: Optional[float] = None,
  71. ) -> None:
  72. """
  73. Perform the opening handshake.
  74. """
  75. if not self.request_rcvd.wait(timeout):
  76. self.close_socket()
  77. self.recv_events_thread.join()
  78. raise TimeoutError("timed out during handshake")
  79. if self.request is None:
  80. self.close_socket()
  81. self.recv_events_thread.join()
  82. raise ConnectionError("connection closed during handshake")
  83. with self.send_context(expected_state=CONNECTING):
  84. self.response = None
  85. if process_request is not None:
  86. try:
  87. self.response = process_request(self, self.request)
  88. except Exception as exc:
  89. self.protocol.handshake_exc = exc
  90. self.logger.error("opening handshake failed", exc_info=True)
  91. self.response = self.protocol.reject(
  92. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  93. (
  94. "Failed to open a WebSocket connection.\n"
  95. "See server log for more information.\n"
  96. ),
  97. )
  98. if self.response is None:
  99. self.response = self.protocol.accept(self.request)
  100. if server_header is not None:
  101. self.response.headers["Server"] = server_header
  102. if process_response is not None:
  103. try:
  104. response = process_response(self, self.request, self.response)
  105. except Exception as exc:
  106. self.protocol.handshake_exc = exc
  107. self.logger.error("opening handshake failed", exc_info=True)
  108. self.response = self.protocol.reject(
  109. http.HTTPStatus.INTERNAL_SERVER_ERROR,
  110. (
  111. "Failed to open a WebSocket connection.\n"
  112. "See server log for more information.\n"
  113. ),
  114. )
  115. else:
  116. if response is not None:
  117. self.response = response
  118. self.protocol.send_response(self.response)
  119. if self.protocol.state is not OPEN:
  120. self.recv_events_thread.join(self.close_timeout)
  121. self.close_socket()
  122. self.recv_events_thread.join()
  123. if self.protocol.handshake_exc is not None:
  124. raise self.protocol.handshake_exc
  125. def process_event(self, event: Event) -> None:
  126. """
  127. Process one incoming event.
  128. """
  129. # First event - handshake request.
  130. if self.request is None:
  131. assert isinstance(event, Request)
  132. self.request = event
  133. self.request_rcvd.set()
  134. # Later events - frames.
  135. else:
  136. super().process_event(event)
  137. def recv_events(self) -> None:
  138. """
  139. Read incoming data from the socket and process events.
  140. """
  141. try:
  142. super().recv_events()
  143. finally:
  144. # If the connection is closed during the handshake, unblock it.
  145. self.request_rcvd.set()
  146. class WebSocketServer:
  147. """
  148. WebSocket server returned by :func:`serve`.
  149. This class mirrors the API of :class:`~socketserver.BaseServer`, notably the
  150. :meth:`~socketserver.BaseServer.serve_forever` and
  151. :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context
  152. manager protocol.
  153. Args:
  154. socket: Server socket listening for new connections.
  155. handler: Handler for one connection. Receives the socket and address
  156. returned by :meth:`~socket.socket.accept`.
  157. logger: Logger for this server.
  158. """
  159. def __init__(
  160. self,
  161. socket: socket.socket,
  162. handler: Callable[[socket.socket, Any], None],
  163. logger: Optional[LoggerLike] = None,
  164. ):
  165. self.socket = socket
  166. self.handler = handler
  167. if logger is None:
  168. logger = logging.getLogger("websockets.server")
  169. self.logger = logger
  170. if sys.platform != "win32":
  171. self.shutdown_watcher, self.shutdown_notifier = os.pipe()
  172. def serve_forever(self) -> None:
  173. """
  174. See :meth:`socketserver.BaseServer.serve_forever`.
  175. This method doesn't return. Calling :meth:`shutdown` from another thread
  176. stops the server.
  177. Typical use::
  178. with serve(...) as server:
  179. server.serve_forever()
  180. """
  181. poller = selectors.DefaultSelector()
  182. poller.register(self.socket, selectors.EVENT_READ)
  183. if sys.platform != "win32":
  184. poller.register(self.shutdown_watcher, selectors.EVENT_READ)
  185. while True:
  186. poller.select()
  187. try:
  188. # If the socket is closed, this will raise an exception and exit
  189. # the loop. So we don't need to check the return value of select().
  190. sock, addr = self.socket.accept()
  191. except OSError:
  192. break
  193. thread = threading.Thread(target=self.handler, args=(sock, addr))
  194. thread.start()
  195. def shutdown(self) -> None:
  196. """
  197. See :meth:`socketserver.BaseServer.shutdown`.
  198. """
  199. self.socket.close()
  200. if sys.platform != "win32":
  201. os.write(self.shutdown_notifier, b"x")
  202. def fileno(self) -> int:
  203. """
  204. See :meth:`socketserver.BaseServer.fileno`.
  205. """
  206. return self.socket.fileno()
  207. def __enter__(self) -> WebSocketServer:
  208. return self
  209. def __exit__(
  210. self,
  211. exc_type: Optional[Type[BaseException]],
  212. exc_value: Optional[BaseException],
  213. traceback: Optional[TracebackType],
  214. ) -> None:
  215. self.shutdown()
  216. def serve(
  217. handler: Callable[[ServerConnection], None],
  218. host: Optional[str] = None,
  219. port: Optional[int] = None,
  220. *,
  221. # TCP/TLS — unix and path are only for unix_serve()
  222. sock: Optional[socket.socket] = None,
  223. ssl_context: Optional[ssl.SSLContext] = None,
  224. unix: bool = False,
  225. path: Optional[str] = None,
  226. # WebSocket
  227. origins: Optional[Sequence[Optional[Origin]]] = None,
  228. extensions: Optional[Sequence[ServerExtensionFactory]] = None,
  229. subprotocols: Optional[Sequence[Subprotocol]] = None,
  230. select_subprotocol: Optional[
  231. Callable[
  232. [ServerConnection, Sequence[Subprotocol]],
  233. Optional[Subprotocol],
  234. ]
  235. ] = None,
  236. process_request: Optional[
  237. Callable[
  238. [ServerConnection, Request],
  239. Optional[Response],
  240. ]
  241. ] = None,
  242. process_response: Optional[
  243. Callable[
  244. [ServerConnection, Request, Response],
  245. Optional[Response],
  246. ]
  247. ] = None,
  248. server_header: Optional[str] = USER_AGENT,
  249. compression: Optional[str] = "deflate",
  250. # Timeouts
  251. open_timeout: Optional[float] = 10,
  252. close_timeout: Optional[float] = 10,
  253. # Limits
  254. max_size: Optional[int] = 2**20,
  255. # Logging
  256. logger: Optional[LoggerLike] = None,
  257. # Escape hatch for advanced customization
  258. create_connection: Optional[Type[ServerConnection]] = None,
  259. ) -> WebSocketServer:
  260. """
  261. Create a WebSocket server listening on ``host`` and ``port``.
  262. Whenever a client connects, the server creates a :class:`ServerConnection`,
  263. performs the opening handshake, and delegates to the ``handler``.
  264. The handler receives a :class:`ServerConnection` instance, which you can use
  265. to send and receive messages.
  266. Once the handler completes, either normally or with an exception, the server
  267. performs the closing handshake and closes the connection.
  268. :class:`WebSocketServer` mirrors the API of
  269. :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
  270. that it will be closed and call the :meth:`~WebSocketServer.serve_forever`
  271. method to serve requests::
  272. def handler(websocket):
  273. ...
  274. with websockets.sync.server.serve(handler, ...) as server:
  275. server.serve_forever()
  276. Args:
  277. handler: Connection handler. It receives the WebSocket connection,
  278. which is a :class:`ServerConnection`, in argument.
  279. host: Network interfaces the server binds to.
  280. See :func:`~socket.create_server` for details.
  281. port: TCP port the server listens on.
  282. See :func:`~socket.create_server` for details.
  283. sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.
  284. You may call :func:`socket.create_server` to create a suitable TCP
  285. socket.
  286. ssl_context: Configuration for enabling TLS on the connection.
  287. origins: Acceptable values of the ``Origin`` header, for defending
  288. against Cross-Site WebSocket Hijacking attacks. Include :obj:`None`
  289. in the list if the lack of an origin is acceptable.
  290. extensions: List of supported extensions, in order in which they
  291. should be negotiated and run.
  292. subprotocols: List of supported subprotocols, in order of decreasing
  293. preference.
  294. select_subprotocol: Callback for selecting a subprotocol among
  295. those supported by the client and the server. It receives a
  296. :class:`ServerConnection` (not a
  297. :class:`~websockets.server.ServerProtocol`!) instance and a list of
  298. subprotocols offered by the client. Other than the first argument,
  299. it has the same behavior as the
  300. :meth:`ServerProtocol.select_subprotocol
  301. <websockets.server.ServerProtocol.select_subprotocol>` method.
  302. process_request: Intercept the request during the opening handshake.
  303. Return an HTTP response to force the response or :obj:`None` to
  304. continue normally. When you force an HTTP 101 Continue response,
  305. the handshake is successful. Else, the connection is aborted.
  306. process_response: Intercept the response during the opening handshake.
  307. Return an HTTP response to force the response or :obj:`None` to
  308. continue normally. When you force an HTTP 101 Continue response,
  309. the handshake is successful. Else, the connection is aborted.
  310. server_header: Value of the ``Server`` response header.
  311. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
  312. :obj:`None` removes the header.
  313. compression: The "permessage-deflate" extension is enabled by default.
  314. Set ``compression`` to :obj:`None` to disable it. See the
  315. :doc:`compression guide <../../topics/compression>` for details.
  316. open_timeout: Timeout for opening connections in seconds.
  317. :obj:`None` disables the timeout.
  318. close_timeout: Timeout for closing connections in seconds.
  319. :obj:`None` disables the timeout.
  320. max_size: Maximum size of incoming messages in bytes.
  321. :obj:`None` disables the limit.
  322. logger: Logger for this server.
  323. It defaults to ``logging.getLogger("websockets.server")``. See the
  324. :doc:`logging guide <../../topics/logging>` for details.
  325. create_connection: Factory for the :class:`ServerConnection` managing
  326. the connection. Set it to a wrapper or a subclass to customize
  327. connection handling.
  328. """
  329. # Process parameters
  330. if subprotocols is not None:
  331. validate_subprotocols(subprotocols)
  332. if compression == "deflate":
  333. extensions = enable_server_permessage_deflate(extensions)
  334. elif compression is not None:
  335. raise ValueError(f"unsupported compression: {compression}")
  336. if create_connection is None:
  337. create_connection = ServerConnection
  338. # Bind socket and listen
  339. if sock is None:
  340. if unix:
  341. if path is None:
  342. raise TypeError("missing path argument")
  343. sock = socket_create_server(path, family=socket.AF_UNIX)
  344. else:
  345. sock = socket_create_server((host, port))
  346. else:
  347. if path is not None:
  348. raise TypeError("path and sock arguments are incompatible")
  349. # Initialize TLS wrapper
  350. if ssl_context is not None:
  351. sock = ssl_context.wrap_socket(
  352. sock,
  353. server_side=True,
  354. # Delay TLS handshake until after we set a timeout on the socket.
  355. do_handshake_on_connect=False,
  356. )
  357. # Define request handler
  358. def conn_handler(sock: socket.socket, addr: Any) -> None:
  359. # Calculate timeouts on the TLS and WebSocket handshakes.
  360. # The TLS timeout must be set on the socket, then removed
  361. # to avoid conflicting with the WebSocket timeout in handshake().
  362. deadline = Deadline(open_timeout)
  363. try:
  364. # Disable Nagle algorithm
  365. if not unix:
  366. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
  367. # Perform TLS handshake
  368. if ssl_context is not None:
  369. sock.settimeout(deadline.timeout())
  370. assert isinstance(sock, ssl.SSLSocket) # mypy cannot figure this out
  371. sock.do_handshake()
  372. sock.settimeout(None)
  373. # Create a closure so that select_subprotocol has access to self.
  374. protocol_select_subprotocol: Optional[
  375. Callable[
  376. [ServerProtocol, Sequence[Subprotocol]],
  377. Optional[Subprotocol],
  378. ]
  379. ] = None
  380. if select_subprotocol is not None:
  381. def protocol_select_subprotocol(
  382. protocol: ServerProtocol,
  383. subprotocols: Sequence[Subprotocol],
  384. ) -> Optional[Subprotocol]:
  385. # mypy doesn't know that select_subprotocol is immutable.
  386. assert select_subprotocol is not None
  387. # Ensure this function is only used in the intended context.
  388. assert protocol is connection.protocol
  389. return select_subprotocol(connection, subprotocols)
  390. # Initialize WebSocket connection
  391. protocol = ServerProtocol(
  392. origins=origins,
  393. extensions=extensions,
  394. subprotocols=subprotocols,
  395. select_subprotocol=protocol_select_subprotocol,
  396. state=CONNECTING,
  397. max_size=max_size,
  398. logger=logger,
  399. )
  400. # Initialize WebSocket protocol
  401. assert create_connection is not None # help mypy
  402. connection = create_connection(
  403. sock,
  404. protocol,
  405. close_timeout=close_timeout,
  406. )
  407. # On failure, handshake() closes the socket, raises an exception, and
  408. # logs it.
  409. connection.handshake(
  410. process_request,
  411. process_response,
  412. server_header,
  413. deadline.timeout(),
  414. )
  415. except Exception:
  416. sock.close()
  417. return
  418. try:
  419. handler(connection)
  420. except Exception:
  421. protocol.logger.error("connection handler failed", exc_info=True)
  422. connection.close(1011)
  423. else:
  424. connection.close()
  425. # Initialize server
  426. return WebSocketServer(sock, conn_handler, logger)
  427. def unix_serve(
  428. handler: Callable[[ServerConnection], Any],
  429. path: Optional[str] = None,
  430. **kwargs: Any,
  431. ) -> WebSocketServer:
  432. """
  433. Create a WebSocket server listening on a Unix socket.
  434. This function is identical to :func:`serve`, except the ``host`` and
  435. ``port`` arguments are replaced by ``path``. It's only available on Unix.
  436. It's useful for deploying a server behind a reverse proxy such as nginx.
  437. Args:
  438. handler: Connection handler. It receives the WebSocket connection,
  439. which is a :class:`ServerConnection`, in argument.
  440. path: File system path to the Unix socket.
  441. """
  442. return serve(handler, path=path, unix=True, **kwargs)