Debian Codegraph @

src/websockets/legacy/server.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import email.utils
5 import functools
6 import http
7 import inspect
8 import logging
9 import socket
10 import warnings
11 from collections.abc import Awaitable, Generator, Iterable, Sequence
12 from types import TracebackType
13 from typing import Any, Callable, Self, cast
14
15 from ..datastructures import Headers, HeadersLike, MultipleValuesError
16 from ..exceptions import (
17 InvalidHandshake,
18 InvalidHeader,
19 InvalidMessage,
20 InvalidOrigin,
21 InvalidUpgrade,
22 NegotiationError,
23 )
24 from ..extensions import Extension, ServerExtensionFactory
25 from ..extensions.permessage_deflate import enable_server_permessage_deflate
26 from ..headers import (
27 build_extension,
28 parse_extension,
29 parse_subprotocol,
30 validate_subprotocols,
31 )
32 from ..http11 import SERVER
33 from ..protocol import State
34 from ..typing import ExtensionHeader, LoggerLike, Origin, StatusLike, Subprotocol
35 from .exceptions import AbortHandshake
36 from .handshake import build_response, check_request
37 from .http import read_request
38 from .protocol import WebSocketCommonProtocol, broadcast
39
40
41 __all__ = [
42 "broadcast",
43 "serve",
44 "unix_serve",
45 "WebSocketServerProtocol",
46 "WebSocketServer",
47 ]
48
49
50 HeadersLikeOrCallable = HeadersLike | Callable[[str, Headers], HeadersLike]
51
52 HTTPResponse = tuple[StatusLike, HeadersLike, bytes]
53
54
55 class WebSocketServerProtocol(WebSocketCommonProtocol):
56 """
57 WebSocket server connection.
58
59 :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send`
60 coroutines for receiving and sending messages.
61
62 It supports asynchronous iteration to receive messages::
63
64 async for message in websocket:
65 await process(message)
66
67 The iterator exits normally when the connection is closed with close code
68 1000 (OK) or 1001 (going away) or without a close code. It raises
69 a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
70 is closed with any other code.
71
72 You may customize the opening handshake in a subclass by
73 overriding :meth:`process_request` or :meth:`select_subprotocol`.
74
75 Args:
76 ws_server: WebSocket server that created this connection.
77
78 See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``,
79 ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``.
80
81 See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
82 documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
83 ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
84
85 """
86
87 is_client = False
88 side = "server"
89
90 def __init__(
91 self,
92 # The version that accepts the path in the second argument is deprecated.
93 ws_handler: (
94 Callable[[WebSocketServerProtocol], Awaitable[Any]]
95 | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
96 ),
97 ws_server: WebSocketServer,
98 *,
99 logger: LoggerLike | None = None,
100 origins: Sequence[Origin | None] | None = None,
101 extensions: Sequence[ServerExtensionFactory] | None = None,
102 subprotocols: Sequence[Subprotocol] | None = None,
103 extra_headers: HeadersLikeOrCallable | None = None,
104 server_header: str | None = SERVER,
105 process_request: (
106 Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None
107 ) = None,
108 select_subprotocol: (
109 Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None
110 ) = None,
111 open_timeout: float | None = 10,
112 **kwargs: Any,
113 ) -> None:
114 if logger is None:
115 logger = logging.getLogger("websockets.server")
116 super().__init__(logger=logger, **kwargs)
117 # For backwards compatibility with 6.0 or earlier.
118 if origins is not None and "" in origins:
119 warnings.warn("use None instead of '' in origins", DeprecationWarning)
120 origins = [None if origin == "" else origin for origin in origins]
121 # For backwards compatibility with 10.0 or earlier. Done here in
122 # addition to serve to trigger the deprecation warning on direct
123 # use of WebSocketServerProtocol.
124 self.ws_handler = remove_path_argument(ws_handler)
125 self.ws_server = ws_server
126 self.origins = origins
127 self.available_extensions = extensions
128 self.available_subprotocols = subprotocols
129 self.extra_headers = extra_headers
130 self.server_header = server_header
131 self._process_request = process_request
132 self._select_subprotocol = select_subprotocol
133 self.open_timeout = open_timeout
134
135 def connection_made(self, transport: asyncio.BaseTransport) -> None:
136 """
137 Register connection and initialize a task to handle it.
138
139 """
140 super().connection_made(transport)
141 # Register the connection with the server before creating the handler
142 # task. Registering at the beginning of the handler coroutine would
143 # create a race condition between the creation of the task, which
144 # schedules its execution, and the moment the handler starts running.
145 self.ws_server.register(self)
146 self.handler_task = self.loop.create_task(self.handler())
147
148 async def handler(self) -> None:
149 """
150 Handle the lifecycle of a WebSocket connection.
151
152 Since this method doesn't have a caller able to handle exceptions, it
153 attempts to log relevant ones and guarantees that the TCP connection is
154 closed before exiting.
155
156 """
157 try:
158 try:
159 async with asyncio.timeout(self.open_timeout):
160 await self.handshake(
161 origins=self.origins,
162 available_extensions=self.available_extensions,
163 available_subprotocols=self.available_subprotocols,
164 extra_headers=self.extra_headers,
165 )
166 except asyncio.TimeoutError: # pragma: no cover
167 raise
168 except ConnectionError:
169 raise
170 except Exception as exc:
171 if isinstance(exc, AbortHandshake):
172 status, headers, body = exc.status, exc.headers, exc.body
173 elif isinstance(exc, InvalidOrigin):
174 if self.debug:
175 self.logger.debug("! invalid origin", exc_info=True)
176 status, headers, body = (
177 http.HTTPStatus.FORBIDDEN,
178 Headers(),
179 f"Failed to open a WebSocket connection: {exc}.\n".encode(),
180 )
181 elif isinstance(exc, InvalidUpgrade):
182 if self.debug:
183 self.logger.debug("! invalid upgrade", exc_info=True)
184 status, headers, body = (
185 http.HTTPStatus.UPGRADE_REQUIRED,
186 Headers([("Upgrade", "websocket")]),
187 (
188 f"Failed to open a WebSocket connection: {exc}.\n"
189 f"\n"
190 f"You cannot access a WebSocket server directly "
191 f"with a browser. You need a WebSocket client.\n"
192 ).encode(),
193 )
194 elif isinstance(exc, InvalidHandshake):
195 if self.debug:
196 self.logger.debug("! invalid handshake", exc_info=True)
197 exc_chain = cast(BaseException, exc)
198 exc_str = f"{exc_chain}"
199 while exc_chain.__cause__ is not None:
200 exc_chain = exc_chain.__cause__
201 exc_str += f"; {exc_chain}"
202 status, headers, body = (
203 http.HTTPStatus.BAD_REQUEST,
204 Headers(),
205 f"Failed to open a WebSocket connection: {exc_str}.\n".encode(),
206 )
207 else:
208 self.logger.error("opening handshake failed", exc_info=True)
209 status, headers, body = (
210 http.HTTPStatus.INTERNAL_SERVER_ERROR,
211 Headers(),
212 (
213 b"Failed to open a WebSocket connection.\n"
214 b"See server log for more information.\n"
215 ),
216 )
217
218 headers.setdefault("Date", email.utils.formatdate(usegmt=True))
219 if self.server_header:
220 headers.setdefault("Server", self.server_header)
221
222 headers.setdefault("Content-Length", str(len(body)))
223 headers.setdefault("Content-Type", "text/plain")
224 headers.setdefault("Connection", "close")
225
226 self.write_http_response(status, headers, body)
227 self.logger.info(
228 "connection rejected (%d %s)", status.value, status.phrase
229 )
230 await self.close_transport()
231 return
232
233 try:
234 await self.ws_handler(self)
235 except Exception:
236 self.logger.error("connection handler failed", exc_info=True)
237 if not self.closed:
238 self.fail_connection(1011)
239 raise
240
241 try:
242 await self.close()
243 except ConnectionError:
244 raise
245 except Exception:
246 self.logger.error("closing handshake failed", exc_info=True)
247 raise
248
249 except Exception:
250 # Last-ditch attempt to avoid leaking connections on errors.
251 try:
252 self.transport.close()
253 except Exception: # pragma: no cover
254 pass
255
256 finally:
257 # Unregister the connection with the server when the handler task
258 # terminates. Registration is tied to the lifecycle of the handler
259 # task because the server waits for tasks attached to registered
260 # connections before terminating.
261 self.ws_server.unregister(self)
262 self.logger.info("connection closed")
263
264 async def read_http_request(self) -> tuple[str, Headers]:
265 """
266 Read request line and headers from the HTTP request.
267
268 If the request contains a body, it may be read from ``self.reader``
269 after this coroutine returns.
270
271 Raises:
272 InvalidMessage: If the HTTP message is malformed or isn't an
273 HTTP/1.1 GET request.
274
275 """
276 try:
277 path, headers = await read_request(self.reader)
278 except asyncio.CancelledError: # pragma: no cover
279 raise
280 except Exception as exc:
281 raise InvalidMessage("did not receive a valid HTTP request") from exc
282
283 if self.debug:
284 self.logger.debug("< GET %s HTTP/1.1", path)
285 for key, value in headers.raw_items():
286 self.logger.debug("< %s: %s", key, value)
287
288 self.path = path
289 self.request_headers = headers
290
291 return path, headers
292
293 def write_http_response(
294 self, status: http.HTTPStatus, headers: Headers, body: bytes | None = None
295 ) -> None:
296 """
297 Write status line and headers to the HTTP response.
298
299 This coroutine is also able to write a response body.
300
301 """
302 self.response_headers = headers
303
304 if self.debug:
305 self.logger.debug("> HTTP/1.1 %d %s", status.value, status.phrase)
306 for key, value in headers.raw_items():
307 self.logger.debug("> %s: %s", key, value)
308 if body is not None:
309 self.logger.debug("> [body] (%d bytes)", len(body))
310
311 # Since the status line and headers only contain ASCII characters,
312 # we can keep this simple.
313 response = f"HTTP/1.1 {status.value} {status.phrase}\r\n"
314 response += str(headers)
315
316 self.transport.write(response.encode())
317
318 if body is not None:
319 self.transport.write(body)
320
321 async def process_request(
322 self, path: str, request_headers: Headers
323 ) -> HTTPResponse | None:
324 """
325 Intercept the HTTP request and return an HTTP response if appropriate.
326
327 You may override this method in a :class:`WebSocketServerProtocol`
328 subclass, for example:
329
330 * to return an HTTP 200 OK response on a given path; then a load
331 balancer can use this path for a health check;
332 * to authenticate the request and return an HTTP 401 Unauthorized or an
333 HTTP 403 Forbidden when authentication fails.
334
335 You may also override this method with the ``process_request``
336 argument of :func:`serve` and :class:`WebSocketServerProtocol`. This
337 is equivalent, except ``process_request`` won't have access to the
338 protocol instance, so it can't store information for later use.
339
340 :meth:`process_request` is expected to complete quickly. If it may run
341 for a long time, then it should await :meth:`wait_closed` and exit if
342 :meth:`wait_closed` completes, or else it could prevent the server
343 from shutting down.
344
345 Args:
346 path: Request path, including optional query string.
347 request_headers: Request headers.
348
349 Returns:
350 tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to
351 continue the WebSocket handshake normally.
352
353 An HTTP response, represented by a 3-uple of the response status,
354 headers, and body, to abort the WebSocket handshake and return
355 that HTTP response instead.
356
357 """
358 if self._process_request is not None:
359 response = self._process_request(path, request_headers)
360 if isinstance(response, Awaitable):
361 return await response
362 else:
363 # For backwards compatibility with 7.0.
364 warnings.warn(
365 "declare process_request as a coroutine", DeprecationWarning
366 )
367 return response
368 return None
369
370 @staticmethod
371 def process_origin(
372 headers: Headers, origins: Sequence[Origin | None] | None = None
373 ) -> Origin | None:
374 """
375 Handle the Origin HTTP request header.
376
377 Args:
378 headers: Request headers.
379 origins: Optional list of acceptable origins.
380
381 Raises:
382 InvalidOrigin: If the origin isn't acceptable.
383
384 """
385 # "The user agent MUST NOT include more than one Origin header field"
386 # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3.
387 try:
388 origin = headers.get("Origin")
389 except MultipleValuesError as exc:
390 raise InvalidHeader("Origin", "multiple values") from exc
391 if origin is not None:
392 origin = cast(Origin, origin)
393 if origins is not None:
394 if origin not in origins:
395 raise InvalidOrigin(origin)
396 return origin
397
398 @staticmethod
399 def process_extensions(
400 headers: Headers,
401 available_extensions: Sequence[ServerExtensionFactory] | None,
402 ) -> tuple[str | None, list[Extension]]:
403 """
404 Handle the Sec-WebSocket-Extensions HTTP request header.
405
406 Accept or reject each extension proposed in the client request.
407 Negotiate parameters for accepted extensions.
408
409 Return the Sec-WebSocket-Extensions HTTP response header and the list
410 of accepted extensions.
411
412 :rfc:`6455` leaves the rules up to the specification of each
413 :extension.
414
415 To provide this level of flexibility, for each extension proposed by
416 the client, we check for a match with each extension available in the
417 server configuration. If no match is found, the extension is ignored.
418
419 If several variants of the same extension are proposed by the client,
420 it may be accepted several times, which won't make sense in general.
421 Extensions must implement their own requirements. For this purpose,
422 the list of previously accepted extensions is provided.
423
424 This process doesn't allow the server to reorder extensions. It can
425 only select a subset of the extensions proposed by the client.
426
427 Other requirements, for example related to mandatory extensions or the
428 order of extensions, may be implemented by overriding this method.
429
430 Args:
431 headers: Request headers.
432 extensions: Optional list of supported extensions.
433
434 Raises:
435 InvalidHandshake: To abort the handshake with an HTTP 400 error.
436
437 """
438 response_header_value: str | None = None
439
440 extension_headers: list[ExtensionHeader] = []
441 accepted_extensions: list[Extension] = []
442
443 header_values = headers.get_all("Sec-WebSocket-Extensions")
444
445 if header_values and available_extensions:
446 parsed_header_values: list[ExtensionHeader] = sum(
447 [parse_extension(header_value) for header_value in header_values], []
448 )
449
450 for name, request_params in parsed_header_values:
451 for ext_factory in available_extensions:
452 # Skip non-matching extensions based on their name.
453 if ext_factory.name != name:
454 continue
455
456 # Skip non-matching extensions based on their params.
457 try:
458 response_params, extension = ext_factory.process_request_params(
459 request_params, accepted_extensions
460 )
461 except NegotiationError:
462 continue
463
464 # Add matching extension to the final list.
465 extension_headers.append((name, response_params))
466 accepted_extensions.append(extension)
467
468 # Break out of the loop once we have a match.
469 break
470
471 # If we didn't break from the loop, no extension in our list
472 # matched what the client sent. The extension is declined.
473
474 # Serialize extension header.
475 if extension_headers:
476 response_header_value = build_extension(extension_headers)
477
478 return response_header_value, accepted_extensions
479
480 # Not @staticmethod because it calls self.select_subprotocol()
481 def process_subprotocol(
482 self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None
483 ) -> Subprotocol | None:
484 """
485 Handle the Sec-WebSocket-Protocol HTTP request header.
486
487 Return Sec-WebSocket-Protocol HTTP response header, which is the same
488 as the selected subprotocol.
489
490 Args:
491 headers: Request headers.
492 available_subprotocols: Optional list of supported subprotocols.
493
494 Raises:
495 InvalidHandshake: To abort the handshake with an HTTP 400 error.
496
497 """
498 subprotocol: Subprotocol | None = None
499
500 header_values = headers.get_all("Sec-WebSocket-Protocol")
501
502 if header_values and available_subprotocols:
503 parsed_header_values: list[Subprotocol] = sum(
504 [parse_subprotocol(header_value) for header_value in header_values], []
505 )
506
507 subprotocol = self.select_subprotocol(
508 parsed_header_values, available_subprotocols
509 )
510
511 return subprotocol
512
513 def select_subprotocol(
514 self,
515 client_subprotocols: Sequence[Subprotocol],
516 server_subprotocols: Sequence[Subprotocol],
517 ) -> Subprotocol | None:
518 """
519 Pick a subprotocol among those supported by the client and the server.
520
521 If several subprotocols are available, select the preferred subprotocol
522 by giving equal weight to the preferences of the client and the server.
523
524 If no subprotocol is available, proceed without a subprotocol.
525
526 You may provide a ``select_subprotocol`` argument to :func:`serve` or
527 :class:`WebSocketServerProtocol` to override this logic. For example,
528 you could reject the handshake if the client doesn't support a
529 particular subprotocol, rather than accept the handshake without that
530 subprotocol.
531
532 Args:
533 client_subprotocols: List of subprotocols offered by the client.
534 server_subprotocols: List of subprotocols available on the server.
535
536 Returns:
537 Selected subprotocol, if a common subprotocol was found.
538
539 :obj:`None` to continue without a subprotocol.
540
541 """
542 if self._select_subprotocol is not None:
543 return self._select_subprotocol(client_subprotocols, server_subprotocols)
544
545 subprotocols = set(client_subprotocols) & set(server_subprotocols)
546 if not subprotocols:
547 return None
548 return sorted(
549 subprotocols,
550 key=lambda p: client_subprotocols.index(p) + server_subprotocols.index(p),
551 )[0]
552
553 async def handshake(
554 self,
555 origins: Sequence[Origin | None] | None = None,
556 available_extensions: Sequence[ServerExtensionFactory] | None = None,
557 available_subprotocols: Sequence[Subprotocol] | None = None,
558 extra_headers: HeadersLikeOrCallable | None = None,
559 ) -> str:
560 """
561 Perform the server side of the opening handshake.
562
563 Args:
564 origins: List of acceptable values of the Origin HTTP header;
565 include :obj:`None` if the lack of an origin is acceptable.
566 extensions: List of supported extensions, in order in which they
567 should be tried.
568 subprotocols: List of supported subprotocols, in order of
569 decreasing preference.
570 extra_headers: Arbitrary HTTP headers to add to the response when
571 the handshake succeeds.
572
573 Returns:
574 path of the URI of the request.
575
576 Raises:
577 InvalidHandshake: If the handshake fails.
578
579 """
580 path, request_headers = await self.read_http_request()
581
582 # Hook for customizing request handling, for example checking
583 # authentication or treating some paths as plain HTTP endpoints.
584 early_response_awaitable = self.process_request(path, request_headers)
585 if isinstance(early_response_awaitable, Awaitable):
586 early_response = await early_response_awaitable
587 else:
588 # For backwards compatibility with 7.0.
589 warnings.warn("declare process_request as a coroutine", DeprecationWarning)
590 early_response = early_response_awaitable
591
592 # The connection may drop while process_request is running.
593 if self.state is State.CLOSED:
594 # This subclass of ConnectionError is silently ignored in handler().
595 raise BrokenPipeError("connection closed during opening handshake")
596
597 # Change the response to a 503 error if the server is shutting down.
598 if not self.ws_server.is_serving():
599 early_response = (
600 http.HTTPStatus.SERVICE_UNAVAILABLE,
601 [],
602 b"Server is shutting down.\n",
603 )
604
605 if early_response is not None:
606 raise AbortHandshake(*early_response)
607
608 key = check_request(request_headers)
609
610 self.origin = self.process_origin(request_headers, origins)
611
612 extensions_header, self.extensions = self.process_extensions(
613 request_headers, available_extensions
614 )
615
616 protocol_header = self.subprotocol = self.process_subprotocol(
617 request_headers, available_subprotocols
618 )
619
620 response_headers = Headers()
621
622 build_response(response_headers, key)
623
624 if extensions_header is not None:
625 response_headers["Sec-WebSocket-Extensions"] = extensions_header
626
627 if protocol_header is not None:
628 response_headers["Sec-WebSocket-Protocol"] = protocol_header
629
630 if callable(extra_headers):
631 extra_headers = extra_headers(path, self.request_headers)
632 if extra_headers is not None:
633 response_headers.update(extra_headers)
634
635 response_headers.setdefault("Date", email.utils.formatdate(usegmt=True))
636 if self.server_header is not None:
637 response_headers.setdefault("Server", self.server_header)
638
639 self.write_http_response(http.HTTPStatus.SWITCHING_PROTOCOLS, response_headers)
640
641 self.logger.info("connection open")
642
643 self.connection_open()
644
645 return path
646
647
648 class WebSocketServer:
649 """
650 WebSocket server returned by :func:`serve`.
651
652 This class mirrors the API of :class:`~asyncio.Server`.
653
654 It keeps track of WebSocket connections in order to close them properly
655 when shutting down.
656
657 Args:
658 logger: Logger for this server.
659 It defaults to ``logging.getLogger("websockets.server")``.
660 See the :doc:`logging guide <../../topics/logging>` for details.
661
662 """
663
664 def __init__(self, logger: LoggerLike | None = None) -> None:
665 if logger is None:
666 logger = logging.getLogger("websockets.server")
667 self.logger = logger
668
669 # Keep track of active connections.
670 self.websockets: set[WebSocketServerProtocol] = set()
671
672 # Task responsible for closing the server and terminating connections.
673 self.close_task: asyncio.Task[None] | None = None
674
675 # Completed when the server is closed and connections are terminated.
676 self.closed_waiter: asyncio.Future[None]
677
678 def wrap(self, server: asyncio.base_events.Server) -> None:
679 """
680 Attach to a given :class:`~asyncio.Server`.
681
682 Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
683 custom ``Server`` class, the easiest solution that doesn't rely on
684 private :mod:`asyncio` APIs is to:
685
686 - instantiate a :class:`WebSocketServer`
687 - give the protocol factory a reference to that instance
688 - call :meth:`~asyncio.loop.create_server` with the factory
689 - attach the resulting :class:`~asyncio.Server` with this method
690
691 """
692 self.server = server
693 for sock in server.sockets:
694 if sock.family == socket.AF_INET:
695 name = "%s:%d" % sock.getsockname()
696 elif sock.family == socket.AF_INET6:
697 name = "[%s]:%d" % sock.getsockname()[:2]
698 elif sock.family == socket.AF_UNIX:
699 name = sock.getsockname()
700 # In the unlikely event that someone runs websockets over a
701 # protocol other than IP or Unix sockets, avoid crashing.
702 else: # pragma: no cover
703 name = str(sock.getsockname())
704 self.logger.info("server listening on %s", name)
705
706 # Initialized here because we need a reference to the event loop.
707 # This could be moved back to __init__ now that Python < 3.10 isn't
708 # supported anymore, but I'm not taking that risk in legacy code.
709 self.closed_waiter = server.get_loop().create_future()
710
711 def register(self, protocol: WebSocketServerProtocol) -> None:
712 """
713 Register a connection with this server.
714
715 """
716 self.websockets.add(protocol)
717
718 def unregister(self, protocol: WebSocketServerProtocol) -> None:
719 """
720 Unregister a connection with this server.
721
722 """
723 self.websockets.remove(protocol)
724
725 def close(self, close_connections: bool = True) -> None:
726 """
727 Close the server.
728
729 * Close the underlying :class:`~asyncio.Server`.
730 * When ``close_connections`` is :obj:`True`, which is the default,
731 close existing connections. Specifically:
732
733 * Reject opening WebSocket connections with an HTTP 503 (service
734 unavailable) error. This happens when the server accepted the TCP
735 connection but didn't complete the opening handshake before closing.
736 * Close open WebSocket connections with close code 1001 (going away).
737
738 * Wait until all connection handlers terminate.
739
740 :meth:`close` is idempotent.
741
742 """
743 if self.close_task is None:
744 self.close_task = self.get_loop().create_task(
745 self._close(close_connections)
746 )
747
748 async def _close(self, close_connections: bool) -> None:
749 """
750 Implementation of :meth:`close`.
751
752 This calls :meth:`~asyncio.Server.close` on the underlying
753 :class:`~asyncio.Server` object to stop accepting new connections and
754 then closes open connections with close code 1001.
755
756 """
757 self.logger.info("server closing")
758
759 # Stop accepting new connections.
760 self.server.close()
761
762 if close_connections:
763 # Close OPEN connections with close code 1001. After server.close(),
764 # handshake() closes OPENING connections with an HTTP 503 error.
765 close_tasks = [
766 asyncio.create_task(websocket.close(1001))
767 for websocket in self.websockets
768 if websocket.state is not State.CONNECTING
769 ]
770 # asyncio.wait doesn't accept an empty first argument.
771 if close_tasks:
772 await asyncio.wait(close_tasks)
773
774 # Wait until all TCP connections are closed.
775 await self.server.wait_closed()
776
777 # Wait until all connection handlers terminate.
778 # asyncio.wait doesn't accept an empty first argument.
779 if self.websockets:
780 await asyncio.wait(
781 [websocket.handler_task for websocket in self.websockets]
782 )
783
784 # Tell wait_closed() to return.
785 self.closed_waiter.set_result(None)
786
787 self.logger.info("server closed")
788
789 async def wait_closed(self) -> None:
790 """
791 Wait until the server is closed.
792
793 When :meth:`wait_closed` returns, all TCP connections are closed and
794 all connection handlers have returned.
795
796 To ensure a fast shutdown, a connection handler should always be
797 awaiting at least one of:
798
799 * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed,
800 it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
801 * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is
802 closed, it returns.
803
804 Then the connection handler is immediately notified of the shutdown;
805 it can clean up and exit.
806
807 """
808 await asyncio.shield(self.closed_waiter)
809
810 def get_loop(self) -> asyncio.AbstractEventLoop:
811 """
812 See :meth:`asyncio.Server.get_loop`.
813
814 """
815 return self.server.get_loop()
816
817 def is_serving(self) -> bool:
818 """
819 See :meth:`asyncio.Server.is_serving`.
820
821 """
822 return self.server.is_serving()
823
824 async def start_serving(self) -> None: # pragma: no cover
825 """
826 See :meth:`asyncio.Server.start_serving`.
827
828 Typical use::
829
830 server = await serve(..., start_serving=False)
831 # perform additional setup here...
832 # ... then start the server
833 await server.start_serving()
834
835 """
836 await self.server.start_serving()
837
838 async def serve_forever(self) -> None: # pragma: no cover
839 """
840 See :meth:`asyncio.Server.serve_forever`.
841
842 Typical use::
843
844 server = await serve(...)
845 # this coroutine doesn't return
846 # canceling it stops the server
847 await server.serve_forever()
848
849 This is an alternative to using :func:`serve` as an asynchronous context
850 manager. Shutdown is triggered by canceling :meth:`serve_forever`
851 instead of exiting a :func:`serve` context.
852
853 """
854 await self.server.serve_forever()
855
856 @property
857 def sockets(self) -> Iterable[socket.socket]:
858 """
859 See :attr:`asyncio.Server.sockets`.
860
861 """
862 return self.server.sockets
863
864 async def __aenter__(self) -> Self: # pragma: no cover
865 return self
866
867 async def __aexit__(
868 self,
869 exc_type: type[BaseException] | None,
870 exc_value: BaseException | None,
871 traceback: TracebackType | None,
872 ) -> None: # pragma: no cover
873 self.close()
874 await self.wait_closed()
875
876
877 class Serve:
878 """
879 Start a WebSocket server listening on ``host`` and ``port``.
880
881 Whenever a client connects, the server creates a
882 :class:`WebSocketServerProtocol`, performs the opening handshake, and
883 delegates to the connection handler, ``ws_handler``.
884
885 The handler receives the :class:`WebSocketServerProtocol` and uses it to
886 send and receive messages.
887
888 Once the handler completes, either normally or with an exception, the
889 server performs the closing handshake and closes the connection.
890
891 Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object
892 provides a :meth:`~WebSocketServer.close` method to shut down the server::
893
894 # set this future to exit the server
895 stop = asyncio.get_running_loop().create_future()
896
897 server = await serve(...)
898 await stop
899 server.close()
900 await server.wait_closed()
901
902 :func:`serve` can be used as an asynchronous context manager. Then, the
903 server is shut down automatically when exiting the context::
904
905 # set this future to exit the server
906 stop = asyncio.get_running_loop().create_future()
907
908 async with serve(...):
909 await stop
910
911 Args:
912 ws_handler: Connection handler. It receives the WebSocket connection,
913 which is a :class:`WebSocketServerProtocol`, in argument.
914 host: Network interfaces the server binds to.
915 See :meth:`~asyncio.loop.create_server` for details.
916 port: TCP port the server listens on.
917 See :meth:`~asyncio.loop.create_server` for details.
918 create_protocol: Factory for the :class:`asyncio.Protocol` managing
919 the connection. It defaults to :class:`WebSocketServerProtocol`.
920 Set it to a wrapper or a subclass to customize connection handling.
921 logger: Logger for this server.
922 It defaults to ``logging.getLogger("websockets.server")``.
923 See the :doc:`logging guide <../../topics/logging>` for details.
924 compression: The "permessage-deflate" extension is enabled by default.
925 Set ``compression`` to :obj:`None` to disable it. See the
926 :doc:`compression guide <../../topics/compression>` for details.
927 origins: Acceptable values of the ``Origin`` header, for defending
928 against Cross-Site WebSocket Hijacking attacks. Include :obj:`None`
929 in the list if the lack of an origin is acceptable.
930 extensions: List of supported extensions, in order in which they
931 should be negotiated and run.
932 subprotocols: List of supported subprotocols, in order of decreasing
933 preference.
934 extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]):
935 Arbitrary HTTP headers to add to the response. This can be
936 a :data:`~websockets.datastructures.HeadersLike` or a callable
937 taking the request path and headers in arguments and returning
938 a :data:`~websockets.datastructures.HeadersLike`.
939 server_header: Value of the ``Server`` response header.
940 It defaults to ``"Python/x.y.z websockets/X.Y"``.
941 Setting it to :obj:`None` removes the header.
942 process_request (Callable[[str, Headers], \
943 Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None):
944 Intercept HTTP request before the opening handshake.
945 See :meth:`~WebSocketServerProtocol.process_request` for details.
946 select_subprotocol: Select a subprotocol supported by the client.
947 See :meth:`~WebSocketServerProtocol.select_subprotocol` for details.
948 open_timeout: Timeout for opening connections in seconds.
949 :obj:`None` disables the timeout.
950
951 See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
952 documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
953 ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
954
955 Any other keyword arguments are passed the event loop's
956 :meth:`~asyncio.loop.create_server` method.
957
958 For example:
959
960 * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.
961
962 * You can set ``sock`` to a :obj:`~socket.socket` that you created
963 outside of websockets.
964
965 Returns:
966 WebSocket server.
967
968 """
969
970 def __init__(
971 self,
972 # The version that accepts the path in the second argument is deprecated.
973 ws_handler: (
974 Callable[[WebSocketServerProtocol], Awaitable[Any]]
975 | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
976 ),
977 host: str | Sequence[str] | None = None,
978 port: int | None = None,
979 *,
980 create_protocol: Callable[..., WebSocketServerProtocol] | None = None,
981 logger: LoggerLike | None = None,
982 compression: str | None = "deflate",
983 origins: Sequence[Origin | None] | None = None,
984 extensions: Sequence[ServerExtensionFactory] | None = None,
985 subprotocols: Sequence[Subprotocol] | None = None,
986 extra_headers: HeadersLikeOrCallable | None = None,
987 server_header: str | None = SERVER,
988 process_request: (
989 Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None
990 ) = None,
991 select_subprotocol: (
992 Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None
993 ) = None,
994 open_timeout: float | None = 10,
995 ping_interval: float | None = 20,
996 ping_timeout: float | None = 20,
997 close_timeout: float | None = None,
998 max_size: int | None = 2**20,
999 max_queue: int | None = 2**5,
1000 read_limit: int = 2**16,
1001 write_limit: int = 2**16,
1002 **kwargs: Any,
1003 ) -> None:
1004 # Backwards compatibility: close_timeout used to be called timeout.
1005 timeout: float | None = kwargs.pop("timeout", None)
1006 if timeout is None:
1007 timeout = 10
1008 else:
1009 warnings.warn("rename timeout to close_timeout", DeprecationWarning)
1010 # If both are specified, timeout is ignored.
1011 if close_timeout is None:
1012 close_timeout = timeout
1013
1014 # Backwards compatibility: create_protocol used to be called klass.
1015 klass: type[WebSocketServerProtocol] | None = kwargs.pop("klass", None)
1016 if klass is None:
1017 klass = WebSocketServerProtocol
1018 else:
1019 warnings.warn("rename klass to create_protocol", DeprecationWarning)
1020 # If both are specified, klass is ignored.
1021 if create_protocol is None:
1022 create_protocol = klass
1023
1024 # Backwards compatibility: recv() used to return None on closed connections
1025 legacy_recv: bool = kwargs.pop("legacy_recv", False)
1026
1027 # Backwards compatibility: the loop parameter used to be supported.
1028 _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None)
1029 if _loop is None:
1030 loop = asyncio.get_event_loop()
1031 else:
1032 loop = _loop
1033 warnings.warn("remove loop argument", DeprecationWarning)
1034
1035 ws_server = WebSocketServer(logger=logger)
1036
1037 secure = kwargs.get("ssl") is not None
1038
1039 if compression == "deflate":
1040 extensions = enable_server_permessage_deflate(extensions)
1041 elif compression is not None:
1042 raise ValueError(f"unsupported compression: {compression}")
1043
1044 if subprotocols is not None:
1045 validate_subprotocols(subprotocols)
1046
1047 # Help mypy and avoid this error: "type[WebSocketServerProtocol] |
1048 # Callable[..., WebSocketServerProtocol]" not callable [misc]
1049 create_protocol = cast(Callable[..., WebSocketServerProtocol], create_protocol)
1050 factory = functools.partial(
1051 create_protocol,
1052 # For backwards compatibility with 10.0 or earlier. Done here in
1053 # addition to WebSocketServerProtocol to trigger the deprecation
1054 # warning once per serve() call rather than once per connection.
1055 remove_path_argument(ws_handler),
1056 ws_server,
1057 host=host,
1058 port=port,
1059 secure=secure,
1060 open_timeout=open_timeout,
1061 ping_interval=ping_interval,
1062 ping_timeout=ping_timeout,
1063 close_timeout=close_timeout,
1064 max_size=max_size,
1065 max_queue=max_queue,
1066 read_limit=read_limit,
1067 write_limit=write_limit,
1068 loop=_loop,
1069 legacy_recv=legacy_recv,
1070 origins=origins,
1071 extensions=extensions,
1072 subprotocols=subprotocols,
1073 extra_headers=extra_headers,
1074 server_header=server_header,
1075 process_request=process_request,
1076 select_subprotocol=select_subprotocol,
1077 logger=logger,
1078 )
1079
1080 if kwargs.pop("unix", False):
1081 path: str | None = kwargs.pop("path", None)
1082 # unix_serve(path) must not specify host and port parameters.
1083 assert host is None and port is None
1084 create_server = functools.partial(
1085 loop.create_unix_server, factory, path, **kwargs
1086 )
1087 else:
1088 create_server = functools.partial(
1089 loop.create_server, factory, host, port, **kwargs
1090 )
1091
1092 # This is a coroutine function.
1093 self._create_server = create_server
1094 self.ws_server = ws_server
1095
1096 # async with serve(...)
1097
1098 async def __aenter__(self) -> WebSocketServer:
1099 return await self
1100
1101 async def __aexit__(
1102 self,
1103 exc_type: type[BaseException] | None,
1104 exc_value: BaseException | None,
1105 traceback: TracebackType | None,
1106 ) -> None:
1107 self.ws_server.close()
1108 await self.ws_server.wait_closed()
1109
1110 # await serve(...)
1111
1112 def __await__(self) -> Generator[Any, None, WebSocketServer]:
1113 # Create a suitable iterator by calling __await__ on a coroutine.
1114 return self.__await_impl__().__await__()
1115
1116 async def __await_impl__(self) -> WebSocketServer:
1117 server = await self._create_server()
1118 self.ws_server.wrap(server)
1119 return self.ws_server
1120
1121
1122 serve = Serve
1123
1124
1125 def unix_serve(
1126 # The version that accepts the path in the second argument is deprecated.
1127 ws_handler: (
1128 Callable[[WebSocketServerProtocol], Awaitable[Any]]
1129 | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
1130 ),
1131 path: str | None = None,
1132 **kwargs: Any,
1133 ) -> Serve:
1134 """
1135 Start a WebSocket server listening on a Unix socket.
1136
1137 This function is identical to :func:`serve`, except the ``host`` and
1138 ``port`` arguments are replaced by ``path``. It is only available on Unix.
1139
1140 Unrecognized keyword arguments are passed the event loop's
1141 :meth:`~asyncio.loop.create_unix_server` method.
1142
1143 It's useful for deploying a server behind a reverse proxy such as nginx.
1144
1145 Args:
1146 path: File system path to the Unix socket.
1147
1148 """
1149 return serve(ws_handler, path=path, unix=True, **kwargs)
1150
1151
1152 def remove_path_argument(
1153 ws_handler: (
1154 Callable[[WebSocketServerProtocol], Awaitable[Any]]
1155 | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]
1156 ),
1157 ) -> Callable[[WebSocketServerProtocol], Awaitable[Any]]:
1158 try:
1159 inspect.signature(ws_handler).bind(None)
1160 except TypeError:
1161 try:
1162 inspect.signature(ws_handler).bind(None, "")
1163 except TypeError: # pragma: no cover
1164 # ws_handler accepts neither one nor two arguments; leave it alone.
1165 pass
1166 else:
1167 # ws_handler accepts two arguments; activate backwards compatibility.
1168 warnings.warn("remove second argument of ws_handler", DeprecationWarning)
1169
1170 async def _ws_handler(websocket: WebSocketServerProtocol) -> Any:
1171 return await cast(
1172 Callable[[WebSocketServerProtocol, str], Awaitable[Any]],
1173 ws_handler,
1174 )(websocket, websocket.path)
1175
1176 return _ws_handler
1177
1178 return cast(
1179 Callable[[WebSocketServerProtocol], Awaitable[Any]],
1180 ws_handler,
1181 )