Debian Codegraph @

src/websockets/trio/server.py

raw
1 from __future__ import annotations
2
3 import functools
4 import http
5 import logging
6 import re
7 import ssl as ssl_module
8 from collections.abc import Awaitable, Mapping, Sequence
9 from types import TracebackType
10 from typing import Any, Callable, Coroutine, Self
11
12 import trio
13 import trio.abc
14
15 from ..asyncio.server import basic_auth
16 from ..extensions.base import ServerExtensionFactory
17 from ..extensions.permessage_deflate import enable_server_permessage_deflate
18 from ..frames import CloseCode
19 from ..headers import validate_subprotocols
20 from ..http11 import SERVER, Request, Response
21 from ..protocol import CONNECTING, OPEN, Event
22 from ..server import ServerProtocol
23 from ..typing import LoggerLike, Origin, StatusLike, Subprotocol
24 from ..utils import get_socket_name
25 from .connection import Connection, broadcast
26 from .utils import race_events
27
28
29 __all__ = [
30 "broadcast",
31 "serve",
32 "ServerConnection",
33 "Server",
34 "basic_auth",
35 ]
36
37
38 class ServerConnection(Connection):
39 """
40 :mod:`trio` implementation of a WebSocket server connection.
41
42 :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
43 receiving and sending messages.
44
45 It supports asynchronous iteration to receive messages::
46
47 async for message in websocket:
48 await process(message)
49
50 The iterator exits normally when the connection is closed with close code
51 1000 (OK) or 1001 (going away) or without a close code. It raises a
52 :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
53 closed with any other code.
54
55 The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and
56 ``max_queue`` arguments have the same meaning as in :func:`serve`.
57
58 Args:
59 nursery: Trio nursery.
60 stream: Trio stream connected to a WebSocket client.
61 protocol: Sans-I/O connection.
62 server: Server that manages this connection.
63
64 """
65
66 def __init__(
67 self,
68 nursery: trio.Nursery,
69 stream: trio.abc.Stream,
70 protocol: ServerProtocol,
71 server: Server,
72 *,
73 ping_interval: float | None = 20,
74 ping_timeout: float | None = 20,
75 close_timeout: float | None = 10,
76 max_queue: int | None | tuple[int | None, int | None] = 16,
77 ) -> None:
78 self.protocol: ServerProtocol
79 super().__init__(
80 nursery,
81 stream,
82 protocol,
83 ping_interval=ping_interval,
84 ping_timeout=ping_timeout,
85 close_timeout=close_timeout,
86 max_queue=max_queue,
87 )
88 self.server = server
89 self.request_rcvd: trio.Event = trio.Event()
90 self.username: str # see basic_auth()
91 self.handler: Callable[[ServerConnection], Awaitable[None]] # see route()
92 self.handler_kwargs: Mapping[str, Any] # see route()
93
94 def respond(self, status: StatusLike, text: str) -> Response:
95 """
96 Create a plain text HTTP response.
97
98 ``process_request`` and ``process_response`` may call this method to
99 return an HTTP response instead of performing the WebSocket opening
100 handshake.
101
102 You can modify the response before returning it, for example by changing
103 HTTP headers.
104
105 Args:
106 status: HTTP status code.
107 text: HTTP response body; it will be encoded to UTF-8.
108
109 Returns:
110 HTTP response to send to the client.
111
112 """
113 return self.protocol.reject(status, text)
114
115 async def handshake(
116 self,
117 process_request: (
118 Callable[
119 [ServerConnection, Request],
120 Awaitable[Response | None] | Response | None,
121 ]
122 | None
123 ) = None,
124 process_response: (
125 Callable[
126 [ServerConnection, Request, Response],
127 Awaitable[Response | None] | Response | None,
128 ]
129 | None
130 ) = None,
131 server_header: str | None = SERVER,
132 ) -> None:
133 """
134 Perform the opening handshake.
135
136 """
137 await race_events(self.request_rcvd, self.stream_closed)
138
139 if self.request is not None:
140 response = None
141
142 if process_request is not None:
143 try:
144 response = process_request(self, self.request)
145 if isinstance(response, Awaitable):
146 response = await response
147 except Exception as exc:
148 self.protocol.handshake_exc = exc
149 self.logger.error("process_request failed", exc_info=True)
150 response = self.protocol.reject(
151 http.HTTPStatus.INTERNAL_SERVER_ERROR,
152 (
153 "Failed to open a WebSocket connection.\n"
154 "See server log for more information.\n"
155 ),
156 )
157
158 if response is None:
159 self.response = self.protocol.accept(self.request)
160 else:
161 assert isinstance(response, Response) # help mypy
162 self.response = response
163
164 if server_header is not None:
165 self.response.headers["Server"] = server_header
166
167 response = None
168
169 if process_response is not None:
170 try:
171 response = process_response(self, self.request, self.response)
172 if isinstance(response, Awaitable):
173 response = await response
174 except Exception as exc:
175 self.protocol.handshake_exc = exc
176 self.logger.error("process_response failed", exc_info=True)
177 response = self.protocol.reject(
178 http.HTTPStatus.INTERNAL_SERVER_ERROR,
179 (
180 "Failed to open a WebSocket connection.\n"
181 "See server log for more information.\n"
182 ),
183 )
184
185 if response is not None:
186 assert isinstance(response, Response) # help mypy
187 self.response = response
188
189 # Reject the connection if the server started closing during the
190 # opening handshake. Don't yield before send_response() to avoid
191 # a race condition after checking if the server is closing.
192 if (
193 self.response.status_code == http.HTTPStatus.SWITCHING_PROTOCOLS
194 and self.server.closing
195 ):
196 self.response = self.protocol.reject(
197 http.HTTPStatus.SERVICE_UNAVAILABLE,
198 "Server is shutting down.\n",
199 )
200
201 # Don't respond if the connection was closed during the handshake.
202 if self.state is CONNECTING:
203 async with self.send_context(expected_state=CONNECTING):
204 self.protocol.send_response(self.response)
205
206 def process_event(self, event: Event) -> None:
207 """
208 Process one incoming event.
209
210 """
211 # First event - handshake request.
212 if self.request is None:
213 assert isinstance(event, Request)
214 self.request = event
215 self.request_rcvd.set()
216 # Later events - frames.
217 else:
218 super().process_event(event)
219
220
221 class Server(trio.abc.AsyncResource):
222 """
223 WebSocket server returned by :func:`serve`.
224
225 Args:
226 listeners: List of Trio listeners accepting new connections.
227 handler: Handler for one connection. It receives a Trio stream.
228 logger: Logger for this server.
229 It defaults to ``logging.getLogger("websockets.server")``.
230 See the :doc:`logging guide <../../topics/logging>` for details.
231
232 """
233
234 def __init__(
235 self,
236 listeners: list[trio.SocketListener],
237 handler: Callable[[trio.abc.Stream], Coroutine[Any, Any, None]],
238 logger: LoggerLike | None = None,
239 ) -> None:
240 self.listeners = listeners
241 self.handler = handler
242 if logger is None:
243 logger = logging.getLogger("websockets.server")
244 self.logger = logger
245
246 # Keep track of active connections.
247 # Trio keeps track of connection handler tasks.
248 self.all_connections: set[ServerConnection] = set()
249
250 # Completed when all handlers are done.
251 self.handlers_waiter = trio.Event()
252
253 self.closing = False
254
255 @property
256 def connections(self) -> set[ServerConnection]:
257 """
258 Set of active connections.
259
260 This property contains all connections that completed the opening
261 handshake successfully and didn't start the closing handshake yet.
262 It can be useful in combination with :func:`~broadcast`.
263
264 """
265 return {
266 connection
267 for connection in self.all_connections
268 if connection.protocol.state is OPEN
269 }
270
271 async def serve_forever(
272 self,
273 task_status: trio.TaskStatus[Server] = trio.TASK_STATUS_IGNORED,
274 ) -> None:
275 # Running handlers in a dedicated nursery makes it possible to close
276 # listeners while handlers finish running. The nursery for listeners
277 # is created in trio.serve_listeners().
278 async with trio.open_nursery() as self.handler_nursery:
279 # Wrap trio.serve_listeners() in another nursery to return the
280 # Server object in task_status instead of a list of listeners.
281 async with trio.open_nursery() as self.serve_nursery:
282 await self.serve_nursery.start(
283 functools.partial(
284 trio.serve_listeners,
285 self.handler,
286 self.listeners,
287 handler_nursery=self.handler_nursery,
288 )
289 )
290 for listener in self.listeners:
291 self.logger.info(
292 "server listening on %s",
293 # listener.socket is a Trio socket, not a socket.socket,
294 # but it offers the same APIs used by get_socket_name().
295 get_socket_name(listener.socket), # type: ignore
296 )
297 task_status.started(self)
298 # When the nursery for handlers has exited, all handlers have returned.
299 self.handlers_waiter.set()
300
301 # Shutting down the server cleanly when serve_forever() is canceled would be
302 # the most idiomatic in Trio. However, that would require shielding too many
303 # asynchronous operations, including the TLS & WebSocket opening handshakes.
304
305 async def aclose(
306 self,
307 close_connections: bool = True,
308 code: CloseCode | int = CloseCode.GOING_AWAY,
309 reason: str = "",
310 ) -> None:
311 """
312 Close the server.
313
314 * Close the TCP listeners.
315 * When ``close_connections`` is :obj:`True`, which is the default,
316 close existing connections. Specifically:
317
318 * Reject opening WebSocket connections with an HTTP 503 (service
319 unavailable) error. This happens when the server accepted the TCP
320 connection but didn't complete the opening handshake before closing.
321 * Close open WebSocket connections with close code 1001 (going away).
322 ``code`` and ``reason`` can be customized, for example to use code
323 1012 (service restart).
324
325 * Wait until all connection handlers have returned.
326
327 :meth:`aclose` is idempotent.
328
329 """
330 self.logger.info("server closing")
331
332 # Stop accepting new connections.
333 self.serve_nursery.cancel_scope.cancel()
334
335 # Reject OPENING connections with HTTP 503 — see handshake().
336 self.closing = True
337
338 # Close OPEN connections.
339 if close_connections:
340 for connection in self.all_connections:
341 if connection.protocol.state is OPEN: # pragma: no branch
342 self.handler_nursery.start_soon(connection.aclose, code, reason)
343
344 # Wait until all connection handlers have returned.
345 await self.handlers_waiter.wait()
346
347 self.logger.info("server closed")
348
349 async def __aenter__(self) -> Self:
350 return self
351
352 async def __aexit__(
353 self,
354 exc_type: type[BaseException] | None,
355 exc_value: BaseException | None,
356 traceback: TracebackType | None,
357 ) -> None:
358 await self.aclose()
359
360
361 async def serve(
362 handler: Callable[[ServerConnection], Awaitable[None]],
363 port: int | None = None,
364 *,
365 # TCP/TLS
366 host: str | bytes | None = None,
367 backlog: int | None = None,
368 listeners: list[trio.SocketListener] | None = None,
369 ssl: ssl_module.SSLContext | None = None,
370 # WebSocket
371 origins: Sequence[Origin | re.Pattern[str] | None] | None = None,
372 extensions: Sequence[ServerExtensionFactory] | None = None,
373 subprotocols: Sequence[Subprotocol] | None = None,
374 select_subprotocol: (
375 Callable[
376 [ServerConnection, Sequence[Subprotocol]],
377 Subprotocol | None,
378 ]
379 | None
380 ) = None,
381 compression: str | None = "deflate",
382 # HTTP
383 process_request: (
384 Callable[
385 [ServerConnection, Request],
386 Awaitable[Response | None] | Response | None,
387 ]
388 | None
389 ) = None,
390 process_response: (
391 Callable[
392 [ServerConnection, Request, Response],
393 Awaitable[Response | None] | Response | None,
394 ]
395 | None
396 ) = None,
397 server_header: str | None = SERVER,
398 # Timeouts
399 open_timeout: float | None = 10,
400 ping_interval: float | None = 20,
401 ping_timeout: float | None = 20,
402 close_timeout: float | None = 10,
403 # Limits
404 max_size: int | None | tuple[int | None, int | None] = 2**20,
405 max_queue: int | None | tuple[int | None, int | None] = 16,
406 # Logging
407 logger: LoggerLike | None = None,
408 # Escape hatch for advanced customization
409 create_connection: type[ServerConnection] | None = None,
410 # Compatibility with trio.Nursery.start()
411 task_status: trio.TaskStatus[Server] = trio.TASK_STATUS_IGNORED,
412 ) -> None:
413 """
414 Create a WebSocket server listening on ``port``.
415
416 Whenever a client connects, the server creates a :class:`ServerConnection`,
417 performs the opening handshake, and delegates to the ``handler`` coroutine.
418
419 The handler receives the :class:`ServerConnection` instance, which you can
420 use to send and receive messages.
421
422 Once the handler completes, either normally or with an exception, the server
423 performs the closing handshake and closes the connection.
424
425 When using :func:`serve` with :meth:`nursery.start <trio.Nursery.start>`,
426 you get back a :class:`Server` object. Treat it as an asynchronous context
427 manager to ensure that the server will be closed gracefully::
428
429 from websockets.trio.server import serve
430
431 async def handler(websocket):
432 ...
433
434 # set this event to exit the server
435 stop = trio.Event()
436
437 with trio.open_nursery() as nursery:
438 server = await nursery.start(serve, handler, port)
439 async with server:
440 await stop.wait()
441
442 Alternatively, to stop the server gracefully, call its
443 :meth:`~Server.aclose` method::
444
445 with trio.open_nursery() as nursery:
446 server = await nursery.start(serve, handler, port)
447 try:
448 await stop.wait()
449 finally:
450 await server.aclose()
451
452 Args:
453 handler: Connection handler. It receives the WebSocket connection,
454 which is a :class:`ServerConnection`, in argument.
455 port: TCP port the server listens on.
456 See :func:`~trio.open_tcp_listeners` for details.
457 host: Network interfaces the server binds to.
458 See :func:`~trio.open_tcp_listeners` for details.
459 backlog: Listen backlog. See :func:`~trio.open_tcp_listeners` for
460 details.
461 listeners: Preexisting TCP listeners. ``listeners`` replaces ``port``,
462 ``host``, and ``backlog``. See :func:`trio.serve_listeners` for
463 details.
464 ssl: Configuration for enabling TLS on the connection.
465 origins: Acceptable values of the ``Origin`` header, for defending
466 against Cross-Site WebSocket Hijacking attacks. Values can be
467 :class:`str` to test for an exact match or regular expressions
468 compiled by :func:`re.compile` to test against a pattern. Include
469 :obj:`None` in the list if the lack of an origin is acceptable.
470 extensions: List of supported extensions, in order in which they
471 should be negotiated and run.
472 subprotocols: List of supported subprotocols, in order of decreasing
473 preference.
474 select_subprotocol: Callback for selecting a subprotocol among
475 those supported by the client and the server. It receives a
476 :class:`ServerConnection` (not a
477 :class:`~websockets.server.ServerProtocol`!) instance and a list of
478 subprotocols offered by the client. Other than the first argument,
479 it has the same behavior as the
480 :meth:`ServerProtocol.select_subprotocol
481 <websockets.server.ServerProtocol.select_subprotocol>` method.
482 compression: The "permessage-deflate" extension is enabled by default.
483 Set ``compression`` to :obj:`None` to disable it. See the
484 :doc:`compression guide <../../topics/compression>` for details.
485 process_request: Intercept the request during the opening handshake.
486 Return an HTTP response to force the response or :obj:`None` to
487 continue normally. When you force an HTTP 101 Continue response, the
488 handshake is successful. Else, the connection is aborted.
489 ``process_request`` may be a function or a coroutine.
490 process_response: Intercept the response during the opening handshake.
491 Return an HTTP response to force the response or :obj:`None` to
492 continue normally. When you force an HTTP 101 Continue response, the
493 handshake is successful. Else, the connection is aborted.
494 ``process_response`` may be a function or a coroutine.
495 server_header: Value of the ``Server`` response header.
496 It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
497 :obj:`None` removes the header.
498 open_timeout: Timeout for opening connections in seconds.
499 :obj:`None` disables the timeout.
500 ping_interval: Interval between keepalive pings in seconds.
501 :obj:`None` disables keepalive.
502 ping_timeout: Timeout for keepalive pings in seconds.
503 :obj:`None` disables timeouts.
504 close_timeout: Timeout for closing connections in seconds.
505 :obj:`None` disables the timeout.
506 max_size: Maximum size of incoming messages in bytes.
507 :obj:`None` disables the limit. You may pass a ``(max_message_size,
508 max_fragment_size)`` tuple to set different limits for messages and
509 fragments when you expect long messages sent in short fragments.
510 max_queue: High-water mark of the buffer where frames are received.
511 It defaults to 16 frames. The low-water mark defaults to ``max_queue
512 // 4``. You may pass a ``(high, low)`` tuple to set the high-water
513 and low-water marks. If you want to disable flow control entirely,
514 you may set it to ``None``, although that's a bad idea.
515 logger: Logger for this server.
516 It defaults to ``logging.getLogger("websockets.server")``.
517 See the :doc:`logging guide <../../topics/logging>` for details.
518 create_connection: Factory for the :class:`ServerConnection` managing
519 the connection. Set it to a wrapper or a subclass to customize
520 connection handling.
521 task_status: For compatibility with :meth:`nursery.start
522 <trio.Nursery.start>`.
523
524 """
525
526 # Process parameters
527
528 if subprotocols is not None:
529 validate_subprotocols(subprotocols)
530
531 if compression == "deflate":
532 extensions = enable_server_permessage_deflate(extensions)
533 elif compression is not None:
534 raise ValueError(f"unsupported compression: {compression}")
535
536 if create_connection is None:
537 create_connection = ServerConnection
538
539 # Create listeners
540
541 if listeners is None:
542 if port is None:
543 raise ValueError("port is required when listeners is not provided")
544 listeners = await trio.open_tcp_listeners(port, host=host, backlog=backlog)
545 else:
546 if port is not None:
547 raise ValueError("port is incompatible with listeners")
548 if host is not None:
549 raise ValueError("host is incompatible with listeners")
550 if backlog is not None:
551 raise ValueError("backlog is incompatible with listeners")
552
553 async def stream_handler(stream: trio.abc.Stream) -> None:
554 """
555 Handle the lifecycle of a WebSocket connection.
556
557 Since this coroutine doesn't have a caller that can handle
558 exceptions, it attempts to log relevant ones.
559
560 It guarantees that the TCP connection is closed before exiting.
561
562 """
563 async with trio.open_nursery() as nursery:
564 try:
565 # Apply open_timeout to the TLS and WebSocket handshake.
566 with (
567 trio.CancelScope()
568 if open_timeout is None
569 else trio.fail_after(open_timeout)
570 ):
571 # Enable TLS.
572 if ssl is not None:
573 # Wrap with SSLStream here rather than with TLSListener
574 # in order to include the TLS handshake within open_timeout.
575 stream = trio.SSLStream(
576 stream,
577 ssl,
578 server_side=True,
579 https_compatible=True,
580 )
581 assert isinstance(stream, trio.SSLStream) # help mypy
582 try:
583 await stream.do_handshake()
584 except trio.BrokenResourceError:
585 return
586
587 # Create a closure to give select_subprotocol access to connection.
588 protocol_select_subprotocol: (
589 Callable[
590 [ServerProtocol, Sequence[Subprotocol]],
591 Subprotocol | None,
592 ]
593 | None
594 ) = None
595 if select_subprotocol is not None:
596
597 def protocol_select_subprotocol(
598 protocol: ServerProtocol,
599 subprotocols: Sequence[Subprotocol],
600 ) -> Subprotocol | None:
601 # mypy doesn't know that select_subprotocol is immutable.
602 assert select_subprotocol is not None
603 # Ensure this function is only used in the intended context.
604 assert protocol is connection.protocol
605 return select_subprotocol(connection, subprotocols)
606
607 # Initialize WebSocket protocol.
608 protocol = ServerProtocol(
609 origins=origins,
610 extensions=extensions,
611 subprotocols=subprotocols,
612 select_subprotocol=protocol_select_subprotocol,
613 max_size=max_size,
614 logger=logger,
615 )
616
617 # Initialize WebSocket connection.
618 connection = create_connection(
619 nursery,
620 stream,
621 protocol,
622 server,
623 ping_interval=ping_interval,
624 ping_timeout=ping_timeout,
625 close_timeout=close_timeout,
626 max_queue=max_queue,
627 )
628
629 await connection.handshake(
630 process_request,
631 process_response,
632 server_header,
633 )
634
635 if connection.protocol.state is not OPEN:
636 await connection.close_stream()
637 return
638
639 server.all_connections.add(connection)
640 connection.start_keepalive()
641 try:
642 await handler(connection)
643 except Exception:
644 connection.logger.error("connection handler failed", exc_info=True)
645 await connection.aclose(CloseCode.INTERNAL_ERROR)
646 else:
647 await connection.aclose()
648 finally:
649 server.all_connections.discard(connection)
650
651 except Exception:
652 # Don't leak connections when the opening handshake times out or
653 # an unexpected error occurs.
654 await trio.aclose_forcefully(stream)
655
656 # The server variable is captured by the closure of conn_handler().
657 server = Server(listeners, stream_handler, logger)
658 await server.serve_forever(task_status=task_status)