Debian Codegraph @

src/websockets/legacy/protocol.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import codecs
5 import collections
6 import logging
7 import random
8 import ssl
9 import struct
10 import time
11 import traceback
12 import uuid
13 import warnings
14 import weakref
15 from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping
16 from typing import Any, Callable, Deque, cast
17
18 from ..datastructures import Headers
19 from ..exceptions import (
20 ConnectionClosed,
21 ConnectionClosedError,
22 ConnectionClosedOK,
23 InvalidState,
24 PayloadTooBig,
25 ProtocolError,
26 )
27 from ..extensions import Extension
28 from ..frames import (
29 BINARY as OP_BINARY,
30 CLOSE as OP_CLOSE,
31 CONT as OP_CONT,
32 OK_CLOSE_CODES,
33 PING as OP_PING,
34 PONG as OP_PONG,
35 TEXT as OP_TEXT,
36 Close,
37 CloseCode,
38 Opcode,
39 )
40 from ..protocol import State
41 from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol
42 from .framing import Frame, prepare_ctrl, prepare_data
43
44
45 __all__ = ["WebSocketCommonProtocol"]
46
47
48 # In order to ensure consistency, the code always checks the current value of
49 # WebSocketCommonProtocol.state before assigning a new value and never yields
50 # between the check and the assignment.
51
52
53 class WebSocketCommonProtocol(asyncio.Protocol):
54 """
55 WebSocket connection.
56
57 :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket
58 servers and clients. You shouldn't use it directly. Instead, use
59 :class:`~websockets.legacy.client.WebSocketClientProtocol` or
60 :class:`~websockets.legacy.server.WebSocketServerProtocol`.
61
62 This documentation focuses on low-level details that aren't covered in the
63 documentation of :class:`~websockets.legacy.client.WebSocketClientProtocol`
64 and :class:`~websockets.legacy.server.WebSocketServerProtocol` for the sake
65 of simplicity.
66
67 Once the connection is open, a Ping_ frame is sent every ``ping_interval``
68 seconds. This serves as a keepalive. It helps keeping the connection open,
69 especially in the presence of proxies with short timeouts on inactive
70 connections. Set ``ping_interval`` to :obj:`None` to disable this behavior.
71
72 .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
73
74 If the corresponding Pong_ frame isn't received within ``ping_timeout``
75 seconds, the connection is considered unusable and is closed with code 1011.
76 This ensures that the remote endpoint remains responsive. Set
77 ``ping_timeout`` to :obj:`None` to disable this behavior.
78
79 .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
80
81 See the discussion of :doc:`keepalive <../../topics/keepalive>` for details.
82
83 The ``close_timeout`` parameter defines a maximum wait time for completing
84 the closing handshake and terminating the TCP connection. For legacy
85 reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds
86 for clients and ``4 * close_timeout`` for servers.
87
88 ``close_timeout`` is a parameter of the protocol because websockets usually
89 calls :meth:`close` implicitly upon exit:
90
91 * on the client side, when using :func:`~websockets.legacy.client.connect`
92 as a context manager;
93 * on the server side, when the connection handler terminates.
94
95 To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or
96 :func:`~asyncio.wait_for`.
97
98 The ``max_size`` parameter enforces the maximum size for incoming messages
99 in bytes. The default value is 1 MiB. If a larger message is received,
100 :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError`
101 and the connection will be closed with code 1009.
102
103 The ``max_queue`` parameter sets the maximum length of the queue that
104 holds incoming messages. The default value is ``32``. Messages are added
105 to an in-memory queue when they're received; then :meth:`recv` pops from
106 that queue. In order to prevent excessive memory consumption when
107 messages are received faster than they can be processed, the queue must
108 be bounded. If the queue fills up, the protocol stops processing incoming
109 data until :meth:`recv` is called. In this situation, various receive
110 buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the
111 TCP receive window will shrink, slowing down transmission to avoid packet
112 loss.
113
114 Since Python can use up to 4 bytes of memory to represent a single
115 character, each connection may use up to ``4 * max_size * max_queue``
116 bytes of memory to store incoming messages. By default, this is 128 MiB.
117 You may want to lower the limits, depending on your application's
118 requirements.
119
120 The ``read_limit`` argument sets the high-water limit of the buffer for
121 incoming bytes. The low-water limit is half the high-water limit. The
122 default value is 64 KiB, half of asyncio's default (based on the current
123 implementation of :class:`~asyncio.StreamReader`).
124
125 The ``write_limit`` argument sets the high-water limit of the buffer for
126 outgoing bytes. The low-water limit is a quarter of the high-water limit.
127 The default value is 64 KiB, equal to asyncio's default (based on the
128 current implementation of ``FlowControlMixin``).
129
130 See the discussion of :doc:`memory usage <../../topics/memory>` for details.
131
132 Args:
133 logger: Logger for this server.
134 It defaults to ``logging.getLogger("websockets.protocol")``.
135 See the :doc:`logging guide <../../topics/logging>` for details.
136 ping_interval: Interval between keepalive pings in seconds.
137 :obj:`None` disables keepalive.
138 ping_timeout: Timeout for keepalive pings in seconds.
139 :obj:`None` disables timeouts.
140 close_timeout: Timeout for closing the connection in seconds.
141 For legacy reasons, the actual timeout is 4 or 5 times larger.
142 max_size: Maximum size of incoming messages in bytes.
143 :obj:`None` disables the limit.
144 max_queue: Maximum number of incoming messages in receive buffer.
145 :obj:`None` disables the limit.
146 read_limit: High-water mark of read buffer in bytes.
147 write_limit: High-water mark of write buffer in bytes.
148
149 """
150
151 # There are only two differences between the client-side and server-side
152 # behavior: masking the payload and closing the underlying TCP connection.
153 # Set is_client = True/False and side = "client"/"server" to pick a side.
154 is_client: bool
155 side: str = "undefined"
156
157 def __init__(
158 self,
159 *,
160 logger: LoggerLike | None = None,
161 ping_interval: float | None = 20,
162 ping_timeout: float | None = 20,
163 close_timeout: float | None = None,
164 max_size: int | None = 2**20,
165 max_queue: int | None = 2**5,
166 read_limit: int = 2**16,
167 write_limit: int = 2**16,
168 # The following arguments are kept only for backwards compatibility.
169 host: str | None = None,
170 port: int | None = None,
171 secure: bool | None = None,
172 legacy_recv: bool = False,
173 loop: asyncio.AbstractEventLoop | None = None,
174 timeout: float | None = None,
175 ) -> None:
176 if legacy_recv: # pragma: no cover
177 warnings.warn("legacy_recv is deprecated", DeprecationWarning)
178
179 # Backwards compatibility: close_timeout used to be called timeout.
180 if timeout is None:
181 timeout = 10
182 else:
183 warnings.warn("rename timeout to close_timeout", DeprecationWarning)
184 # If both are specified, timeout is ignored.
185 if close_timeout is None:
186 close_timeout = timeout
187
188 # Backwards compatibility: the loop parameter used to be supported.
189 if loop is None:
190 loop = asyncio.get_event_loop()
191 else:
192 warnings.warn("remove loop argument", DeprecationWarning)
193
194 self.ping_interval = ping_interval
195 self.ping_timeout = ping_timeout
196 self.close_timeout = close_timeout
197 self.max_size = max_size
198 self.max_queue = max_queue
199 self.read_limit = read_limit
200 self.write_limit = write_limit
201
202 # Unique identifier. For logs.
203 self.id: uuid.UUID = uuid.uuid4()
204 """Unique identifier of the connection. Useful in logs."""
205
206 # Logger or LoggerAdapter for this connection.
207 if logger is None:
208 logger = logging.getLogger("websockets.protocol")
209 self.logger: LoggerLike = logging.LoggerAdapter(
210 logger,
211 {"websocket": weakref.proxy(self)},
212 )
213 """Logger for this connection."""
214
215 # Track if DEBUG is enabled. Shortcut logging calls if it isn't.
216 self.debug = logger.isEnabledFor(logging.DEBUG)
217
218 self.loop = loop
219
220 self._host = host
221 self._port = port
222 self._secure = secure
223 self.legacy_recv = legacy_recv
224
225 # Configure read buffer limits. The high-water limit is defined by
226 # ``self.read_limit``. The ``limit`` argument controls the line length
227 # limit and half the buffer limit of :class:`~asyncio.StreamReader`.
228 # That's why it must be set to half of ``self.read_limit``.
229 self.reader = asyncio.StreamReader(limit=read_limit // 2, loop=loop)
230
231 # Copied from asyncio.FlowControlMixin
232 self._paused = False
233 self._drain_waiter: asyncio.Future[None] | None = None
234
235 # This class implements the data transfer and closing handshake, which
236 # are shared between the client-side and the server-side.
237 # Subclasses implement the opening handshake and, on success, execute
238 # :meth:`connection_open` to change the state to OPEN.
239 self.state = State.CONNECTING
240 if self.debug:
241 self.logger.debug("= connection is CONNECTING")
242
243 # HTTP protocol parameters.
244 self.path: str
245 """Path of the opening handshake request."""
246 self.request_headers: Headers
247 """Opening handshake request headers."""
248 self.response_headers: Headers
249 """Opening handshake response headers."""
250
251 # WebSocket protocol parameters.
252 self.extensions: list[Extension] = []
253 self.subprotocol: Subprotocol | None = None
254 """Subprotocol, if one was negotiated."""
255
256 # Close code and reason, set when a close frame is sent or received.
257 self.close_rcvd: Close | None = None
258 self.close_sent: Close | None = None
259 self.close_rcvd_then_sent: bool | None = None
260
261 # Completed when the connection state becomes CLOSED. Translates the
262 # :meth:`connection_lost` callback to a :class:`~asyncio.Future`
263 # that can be awaited. (Other :class:`~asyncio.Protocol` callbacks are
264 # translated by ``self.stream_reader``).
265 self.connection_lost_waiter: asyncio.Future[None] = loop.create_future()
266
267 # Queue of received messages.
268 self.messages: Deque[Data] = collections.deque()
269 self._pop_message_waiter: asyncio.Future[None] | None = None
270 self._put_message_waiter: asyncio.Future[None] | None = None
271
272 # Protect sending fragmented messages.
273 self._fragmented_message_waiter: asyncio.Future[None] | None = None
274
275 # Mapping of ping IDs to pong waiters, in chronological order.
276 self.pings: dict[bytes, tuple[asyncio.Future[float], float]] = {}
277
278 self.latency: float = 0
279 """
280 Latency of the connection, in seconds.
281
282 Latency is defined as the round-trip time of the connection. It is
283 measured by sending a Ping frame and waiting for a matching Pong frame.
284 Before the first measurement, :attr:`latency` is ``0``.
285
286 By default, websockets enables a :ref:`keepalive <keepalive>` mechanism
287 that sends Ping frames automatically at regular intervals. You can also
288 send Ping frames and measure latency with :meth:`ping`.
289 """
290
291 # Task running the data transfer.
292 self.transfer_data_task: asyncio.Task[None]
293
294 # Exception that occurred during data transfer, if any.
295 self.transfer_data_exc: BaseException | None = None
296
297 # Task sending keepalive pings.
298 self.keepalive_ping_task: asyncio.Task[None]
299
300 # Task closing the TCP connection.
301 self.close_connection_task: asyncio.Task[None]
302
303 # Copied from asyncio.FlowControlMixin
304 async def _drain_helper(self) -> None: # pragma: no cover
305 if self.connection_lost_waiter.done():
306 raise ConnectionResetError("Connection lost")
307 if not self._paused:
308 return
309 waiter = self._drain_waiter
310 assert waiter is None or waiter.cancelled()
311 waiter = self.loop.create_future()
312 self._drain_waiter = waiter
313 await waiter
314
315 # Copied from asyncio.StreamWriter
316 async def _drain(self) -> None: # pragma: no cover
317 if self.reader is not None:
318 exc = self.reader.exception()
319 if exc is not None:
320 raise exc
321 if self.transport is not None:
322 if self.transport.is_closing():
323 # Yield to the event loop so connection_lost() may be
324 # called. Without this, _drain_helper() would return
325 # immediately, and code that calls
326 # write(...); yield from drain()
327 # in a loop would never call connection_lost(), so it
328 # would not see an error when the socket is closed.
329 await asyncio.sleep(0)
330 await self._drain_helper()
331
332 def connection_open(self) -> None:
333 """
334 Callback when the WebSocket opening handshake completes.
335
336 Enter the OPEN state and start the data transfer phase.
337
338 """
339 # 4.1. The WebSocket Connection is Established.
340 assert self.state is State.CONNECTING
341 self.state = State.OPEN
342 if self.debug:
343 self.logger.debug("= connection is OPEN")
344 # Start the task that receives incoming WebSocket messages.
345 self.transfer_data_task = self.loop.create_task(self.transfer_data())
346 # Start the task that sends pings at regular intervals.
347 self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping())
348 # Start the task that eventually closes the TCP connection.
349 self.close_connection_task = self.loop.create_task(self.close_connection())
350
351 @property
352 def host(self) -> str | None:
353 alternative = "remote_address" if self.is_client else "local_address"
354 warnings.warn(f"use {alternative}[0] instead of host", DeprecationWarning)
355 return self._host
356
357 @property
358 def port(self) -> int | None:
359 alternative = "remote_address" if self.is_client else "local_address"
360 warnings.warn(f"use {alternative}[1] instead of port", DeprecationWarning)
361 return self._port
362
363 @property
364 def secure(self) -> bool | None:
365 warnings.warn("don't use secure", DeprecationWarning)
366 return self._secure
367
368 # Public API
369
370 @property
371 def local_address(self) -> Any:
372 """
373 Local address of the connection.
374
375 For IPv4 connections, this is a ``(host, port)`` tuple.
376
377 The format of the address depends on the address family;
378 see :meth:`~socket.socket.getsockname`.
379
380 :obj:`None` if the TCP connection isn't established yet.
381
382 """
383 try:
384 transport = self.transport
385 except AttributeError:
386 return None
387 else:
388 return transport.get_extra_info("sockname")
389
390 @property
391 def remote_address(self) -> Any:
392 """
393 Remote address of the connection.
394
395 For IPv4 connections, this is a ``(host, port)`` tuple.
396
397 The format of the address depends on the address family;
398 see :meth:`~socket.socket.getpeername`.
399
400 :obj:`None` if the TCP connection isn't established yet.
401
402 """
403 try:
404 transport = self.transport
405 except AttributeError:
406 return None
407 else:
408 return transport.get_extra_info("peername")
409
410 @property
411 def open(self) -> bool:
412 """
413 :obj:`True` when the connection is open; :obj:`False` otherwise.
414
415 This attribute may be used to detect disconnections. However, this
416 approach is discouraged per the EAFP_ principle. Instead, you should
417 handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
418
419 .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp
420
421 """
422 return self.state is State.OPEN and not self.transfer_data_task.done()
423
424 @property
425 def closed(self) -> bool:
426 """
427 :obj:`True` when the connection is closed; :obj:`False` otherwise.
428
429 Be aware that both :attr:`open` and :attr:`closed` are :obj:`False`
430 during the opening and closing sequences.
431
432 """
433 return self.state is State.CLOSED
434
435 @property
436 def close_code(self) -> int | None:
437 """
438 WebSocket close code, defined in `section 7.1.5 of RFC 6455`_.
439
440 .. _section 7.1.5 of RFC 6455:
441 https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
442
443 :obj:`None` if the connection isn't closed yet.
444
445 """
446 if self.state is not State.CLOSED:
447 return None
448 elif self.close_rcvd is None:
449 return CloseCode.ABNORMAL_CLOSURE
450 else:
451 return self.close_rcvd.code
452
453 @property
454 def close_reason(self) -> str | None:
455 """
456 WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_.
457
458 .. _section 7.1.6 of RFC 6455:
459 https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
460
461 :obj:`None` if the connection isn't closed yet.
462
463 """
464 if self.state is not State.CLOSED:
465 return None
466 elif self.close_rcvd is None:
467 return ""
468 else:
469 return self.close_rcvd.reason
470
471 async def __aiter__(self) -> AsyncIterator[Data]:
472 """
473 Iterate on incoming messages.
474
475 The iterator exits normally when the connection is closed with the close
476 code 1000 (OK) or 1001 (going away) or without a close code.
477
478 It raises a :exc:`~websockets.exceptions.ConnectionClosedError`
479 exception when the connection is closed with any other code.
480
481 """
482 try:
483 while True:
484 yield await self.recv()
485 except ConnectionClosedOK:
486 return
487
488 async def recv(self) -> Data:
489 """
490 Receive the next message.
491
492 When the connection is closed, :meth:`recv` raises
493 :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
494 :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
495 connection closure and
496 :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
497 error or a network failure. This is how you detect the end of the
498 message stream.
499
500 Canceling :meth:`recv` is safe. There's no risk of losing the next
501 message. The next invocation of :meth:`recv` will return it.
502
503 This makes it possible to enforce a timeout by wrapping :meth:`recv` in
504 :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
505
506 Returns:
507 A string (:class:`str`) for a Text_ frame. A bytestring
508 (:class:`bytes`) for a Binary_ frame.
509
510 .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
511 .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
512
513 Raises:
514 ConnectionClosed: When the connection is closed.
515 RuntimeError: If two coroutines call :meth:`recv` concurrently.
516
517 """
518 if self._pop_message_waiter is not None:
519 raise RuntimeError(
520 "cannot call recv while another coroutine "
521 "is already waiting for the next message"
522 )
523
524 # Don't await self.ensure_open() here:
525 # - messages could be available in the queue even if the connection
526 # is closed;
527 # - messages could be received before the closing frame even if the
528 # connection is closing.
529
530 # Wait until there's a message in the queue (if necessary) or the
531 # connection is closed.
532 while len(self.messages) <= 0:
533 pop_message_waiter: asyncio.Future[None] = self.loop.create_future()
534 self._pop_message_waiter = pop_message_waiter
535 try:
536 # If asyncio.wait() is canceled, it doesn't cancel
537 # pop_message_waiter and self.transfer_data_task.
538 await asyncio.wait(
539 [pop_message_waiter, self.transfer_data_task],
540 return_when=asyncio.FIRST_COMPLETED,
541 )
542 finally:
543 self._pop_message_waiter = None
544
545 # If asyncio.wait(...) exited because self.transfer_data_task
546 # completed before receiving a new message, raise a suitable
547 # exception (or return None if legacy_recv is enabled).
548 if not pop_message_waiter.done():
549 if self.legacy_recv:
550 return None # type: ignore
551 else:
552 # Wait until the connection is closed to raise
553 # ConnectionClosed with the correct code and reason.
554 await self.ensure_open()
555
556 # Pop a message from the queue.
557 message = self.messages.popleft()
558
559 # Notify transfer_data().
560 if self._put_message_waiter is not None:
561 self._put_message_waiter.set_result(None)
562 self._put_message_waiter = None
563
564 return message
565
566 async def send(
567 self,
568 message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike],
569 ) -> None:
570 """
571 Send a message.
572
573 A string (:class:`str`) is sent as a Text_ frame. A bytestring or
574 bytes-like object (:class:`bytes`, :class:`bytearray`, or
575 :class:`memoryview`) is sent as a Binary_ frame.
576
577 .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
578 .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
579
580 :meth:`send` also accepts an iterable or an asynchronous iterable of
581 strings, bytestrings, or bytes-like objects to enable fragmentation_.
582 Each item is treated as a message fragment and sent in its own frame.
583 All items must be of the same type, or else :meth:`send` will raise a
584 :exc:`TypeError` and the connection will be closed.
585
586 .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
587
588 :meth:`send` rejects dict-like objects because this is often an error.
589 (If you want to send the keys of a dict-like object as fragments, call
590 its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
591
592 Canceling :meth:`send` is discouraged. Instead, you should close the
593 connection with :meth:`close`. Indeed, there are only two situations
594 where :meth:`send` may yield control to the event loop and then get
595 canceled; in both cases, :meth:`close` has the same effect and is
596 more clear:
597
598 1. The write buffer is full. If you don't want to wait until enough
599 data is sent, your only alternative is to close the connection.
600 :meth:`close` will likely time out then abort the TCP connection.
601 2. ``message`` is an asynchronous iterator that yields control.
602 Stopping in the middle of a fragmented message will cause a
603 protocol error and the connection will be closed.
604
605 When the connection is closed, :meth:`send` raises
606 :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
607 raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
608 connection closure and
609 :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
610 error or a network failure.
611
612 Args:
613 message: Message to send.
614
615 Raises:
616 ConnectionClosed: When the connection is closed.
617 TypeError: If ``message`` doesn't have a supported type.
618
619 """
620 await self.ensure_open()
621
622 # While sending a fragmented message, prevent sending other messages
623 # until all fragments are sent.
624 while self._fragmented_message_waiter is not None:
625 await asyncio.shield(self._fragmented_message_waiter)
626
627 # Unfragmented message — this case must be handled first because
628 # strings and bytes-like objects are iterable.
629
630 if isinstance(message, (str, bytes, bytearray, memoryview)):
631 opcode, data = prepare_data(message)
632 await self.write_frame(True, opcode, data)
633
634 # Catch a common mistake — passing a dict to send().
635
636 elif isinstance(message, Mapping):
637 raise TypeError("data is a dict-like object")
638
639 # Fragmented message — regular iterator.
640
641 elif isinstance(message, Iterable):
642 iter_message = iter(message)
643 try:
644 fragment = next(iter_message)
645 except StopIteration:
646 return
647 opcode, data = prepare_data(fragment)
648
649 self._fragmented_message_waiter = self.loop.create_future()
650 try:
651 # First fragment.
652 await self.write_frame(False, opcode, data)
653
654 # Other fragments.
655 for fragment in iter_message:
656 confirm_opcode, data = prepare_data(fragment)
657 if confirm_opcode != opcode:
658 raise TypeError("data contains inconsistent types")
659 await self.write_frame(False, OP_CONT, data)
660
661 # Final fragment.
662 await self.write_frame(True, OP_CONT, b"")
663
664 except (Exception, asyncio.CancelledError):
665 # We're half-way through a fragmented message and we can't
666 # complete it. This makes the connection unusable.
667 self.fail_connection(CloseCode.INTERNAL_ERROR)
668 raise
669
670 finally:
671 self._fragmented_message_waiter.set_result(None)
672 self._fragmented_message_waiter = None
673
674 # Fragmented message — asynchronous iterator
675
676 elif isinstance(message, AsyncIterable):
677 # Implement aiter_message = aiter(message) without aiter
678 # Work around https://github.com/python/mypy/issues/5738
679 aiter_message = cast(
680 Callable[[AsyncIterable[DataLike]], AsyncIterator[DataLike]],
681 type(message).__aiter__,
682 )(message)
683 try:
684 # Implement fragment = anext(aiter_message) without anext
685 # Work around https://github.com/python/mypy/issues/5738
686 fragment = await cast(
687 Callable[[AsyncIterator[DataLike]], Awaitable[DataLike]],
688 type(aiter_message).__anext__,
689 )(aiter_message)
690 except StopAsyncIteration:
691 return
692 opcode, data = prepare_data(fragment)
693
694 self._fragmented_message_waiter = self.loop.create_future()
695 try:
696 # First fragment.
697 await self.write_frame(False, opcode, data)
698
699 # Other fragments.
700 async for fragment in aiter_message:
701 confirm_opcode, data = prepare_data(fragment)
702 if confirm_opcode != opcode:
703 raise TypeError("data contains inconsistent types")
704 await self.write_frame(False, OP_CONT, data)
705
706 # Final fragment.
707 await self.write_frame(True, OP_CONT, b"")
708
709 except (Exception, asyncio.CancelledError):
710 # We're half-way through a fragmented message and we can't
711 # complete it. This makes the connection unusable.
712 self.fail_connection(CloseCode.INTERNAL_ERROR)
713 raise
714
715 finally:
716 self._fragmented_message_waiter.set_result(None)
717 self._fragmented_message_waiter = None
718
719 else:
720 raise TypeError("data must be str, bytes-like, or iterable")
721
722 async def close(
723 self,
724 code: int = CloseCode.NORMAL_CLOSURE,
725 reason: str = "",
726 ) -> None:
727 """
728 Perform the closing handshake.
729
730 :meth:`close` waits for the other end to complete the handshake and
731 for the TCP connection to terminate. As a consequence, there's no need
732 to await :meth:`wait_closed` after :meth:`close`.
733
734 :meth:`close` is idempotent: it doesn't do anything once the
735 connection is closed.
736
737 Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given
738 that errors during connection termination aren't particularly useful.
739
740 Canceling :meth:`close` is discouraged. If it takes too long, you can
741 set a shorter ``close_timeout``. If you don't want to wait, let the
742 Python process exit, then the OS will take care of closing the TCP
743 connection.
744
745 Args:
746 code: WebSocket close code.
747 reason: WebSocket close reason.
748
749 """
750 try:
751 async with asyncio.timeout(self.close_timeout):
752 await self.write_close_frame(Close(code, reason))
753 except asyncio.TimeoutError:
754 # If the close frame cannot be sent because the send buffers
755 # are full, the closing handshake won't complete anyway.
756 # Fail the connection to shut down faster.
757 self.fail_connection()
758
759 # If no close frame is received within the timeout, asyncio.timeout()
760 # cancels the data transfer task and raises TimeoutError.
761
762 # If close() is called multiple times concurrently and one of these
763 # calls hits the timeout, the data transfer task will be canceled.
764 # Other calls will receive a CancelledError here.
765
766 try:
767 # If close() is canceled during the wait, self.transfer_data_task
768 # is canceled before the timeout elapses.
769 async with asyncio.timeout(self.close_timeout):
770 await self.transfer_data_task
771 except (asyncio.TimeoutError, asyncio.CancelledError):
772 pass
773
774 # Wait for the close connection task to close the TCP connection.
775 await asyncio.shield(self.close_connection_task)
776
777 async def wait_closed(self) -> None:
778 """
779 Wait until the connection is closed.
780
781 This coroutine is identical to the :attr:`closed` attribute, except it
782 can be awaited.
783
784 This can make it easier to detect connection termination, regardless
785 of its cause, in tasks that interact with the WebSocket connection.
786
787 """
788 await asyncio.shield(self.connection_lost_waiter)
789
790 async def ping(self, data: DataLike | None = None) -> Awaitable[float]:
791 """
792 Send a Ping_.
793
794 .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
795
796 A ping may serve as a keepalive, as a check that the remote endpoint
797 received all messages up to this point, or to measure :attr:`latency`.
798
799 Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return
800 immediately, it means the write buffer is full. If you don't want to
801 wait, you should close the connection.
802
803 Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no
804 effect.
805
806 Args:
807 data: Payload of the ping. A string will be encoded to UTF-8.
808 If ``data`` is :obj:`None`, the payload is four random bytes.
809
810 Returns:
811 A future that will be completed when the corresponding pong is
812 received. You can ignore it if you don't intend to wait. The result
813 of the future is the latency of the connection in seconds.
814
815 ::
816
817 pong_waiter = await ws.ping()
818 # only if you want to wait for the corresponding pong
819 latency = await pong_waiter
820
821 Raises:
822 ConnectionClosed: When the connection is closed.
823 RuntimeError: If another ping was sent with the same data and
824 the corresponding pong wasn't received yet.
825
826 """
827 await self.ensure_open()
828
829 if data is not None:
830 data = prepare_ctrl(data)
831
832 # Protect against duplicates if a payload is explicitly set.
833 if data in self.pings:
834 raise RuntimeError("already waiting for a pong with the same data")
835
836 # Generate a unique random payload otherwise.
837 while data is None or data in self.pings:
838 data = struct.pack("!I", random.getrandbits(32))
839
840 pong_waiter = self.loop.create_future()
841 # Resolution of time.monotonic() may be too low on Windows.
842 ping_timestamp = time.perf_counter()
843 self.pings[data] = (pong_waiter, ping_timestamp)
844
845 await self.write_frame(True, OP_PING, data)
846
847 return asyncio.shield(pong_waiter)
848
849 async def pong(self, data: DataLike = b"") -> None:
850 """
851 Send a Pong_.
852
853 .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
854
855 An unsolicited pong may serve as a unidirectional heartbeat.
856
857 Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return
858 immediately, it means the write buffer is full. If you don't want to
859 wait, you should close the connection.
860
861 Args:
862 data: Payload of the pong. A string will be encoded to UTF-8.
863
864 Raises:
865 ConnectionClosed: When the connection is closed.
866
867 """
868 await self.ensure_open()
869
870 data = prepare_ctrl(data)
871
872 await self.write_frame(True, OP_PONG, data)
873
874 # Private methods - no guarantees.
875
876 def connection_closed_exc(self) -> ConnectionClosed:
877 exc: ConnectionClosed
878 if (
879 self.close_rcvd is not None
880 and self.close_rcvd.code in OK_CLOSE_CODES
881 and self.close_sent is not None
882 and self.close_sent.code in OK_CLOSE_CODES
883 ):
884 exc = ConnectionClosedOK(
885 self.close_rcvd,
886 self.close_sent,
887 self.close_rcvd_then_sent,
888 )
889 else:
890 exc = ConnectionClosedError(
891 self.close_rcvd,
892 self.close_sent,
893 self.close_rcvd_then_sent,
894 )
895 # Chain to the exception that terminated data transfer, if any.
896 exc.__cause__ = self.transfer_data_exc
897 return exc
898
899 async def ensure_open(self) -> None:
900 """
901 Check that the WebSocket connection is open.
902
903 Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
904
905 """
906 # Handle cases from most common to least common for performance.
907 if self.state is State.OPEN:
908 # If self.transfer_data_task exited without a closing handshake,
909 # self.close_connection_task may be closing the connection, going
910 # straight from OPEN to CLOSED.
911 if self.transfer_data_task.done():
912 await asyncio.shield(self.close_connection_task)
913 raise self.connection_closed_exc()
914 else:
915 return
916
917 if self.state is State.CLOSED:
918 raise self.connection_closed_exc()
919
920 if self.state is State.CLOSING:
921 # If we started the closing handshake, wait for its completion to
922 # get the proper close code and reason. self.close_connection_task
923 # will complete within 4 or 5 * close_timeout after close(). The
924 # CLOSING state also occurs when failing the connection. In that
925 # case self.close_connection_task will complete even faster.
926 await asyncio.shield(self.close_connection_task)
927 raise self.connection_closed_exc()
928
929 # Control may only reach this point in buggy third-party subclasses.
930 assert self.state is State.CONNECTING
931 raise InvalidState("WebSocket connection isn't established yet")
932
933 async def transfer_data(self) -> None:
934 """
935 Read incoming messages and put them in a queue.
936
937 This coroutine runs in a task until the closing handshake is started.
938
939 """
940 try:
941 while True:
942 message = await self.read_message()
943
944 # Exit the loop when receiving a close frame.
945 if message is None:
946 break
947
948 # Wait until there's room in the queue (if necessary).
949 if self.max_queue is not None:
950 while len(self.messages) >= self.max_queue:
951 self._put_message_waiter = self.loop.create_future()
952 try:
953 await asyncio.shield(self._put_message_waiter)
954 finally:
955 self._put_message_waiter = None
956
957 # Put the message in the queue.
958 self.messages.append(message)
959
960 # Notify recv().
961 if self._pop_message_waiter is not None:
962 self._pop_message_waiter.set_result(None)
963 self._pop_message_waiter = None
964
965 except asyncio.CancelledError as exc:
966 self.transfer_data_exc = exc
967 # If fail_connection() cancels this task, avoid logging the error
968 # twice and failing the connection again.
969 raise
970
971 except ProtocolError as exc:
972 self.transfer_data_exc = exc
973 self.fail_connection(CloseCode.PROTOCOL_ERROR)
974
975 except (ConnectionError, TimeoutError, EOFError, ssl.SSLError) as exc:
976 # Reading data with self.reader.readexactly may raise:
977 # - most subclasses of ConnectionError if the TCP connection
978 # breaks, is reset, or is aborted;
979 # - TimeoutError if the TCP connection times out;
980 # - IncompleteReadError, a subclass of EOFError, if fewer
981 # bytes are available than requested;
982 # - ssl.SSLError if the other side infringes the TLS protocol.
983 self.transfer_data_exc = exc
984 self.fail_connection(CloseCode.ABNORMAL_CLOSURE)
985
986 except UnicodeDecodeError as exc:
987 self.transfer_data_exc = exc
988 self.fail_connection(CloseCode.INVALID_DATA)
989
990 except PayloadTooBig as exc:
991 self.transfer_data_exc = exc
992 self.fail_connection(CloseCode.MESSAGE_TOO_BIG)
993
994 except Exception as exc:
995 # This shouldn't happen often because exceptions expected under
996 # regular circumstances are handled above. If it does, consider
997 # catching and handling more exceptions.
998 self.logger.error("data transfer failed", exc_info=True)
999
1000 self.transfer_data_exc = exc
1001 self.fail_connection(CloseCode.INTERNAL_ERROR)
1002
1003 async def read_message(self) -> Data | None:
1004 """
1005 Read a single message from the connection.
1006
1007 Re-assemble data frames if the message is fragmented.
1008
1009 Return :obj:`None` when the closing handshake is started.
1010
1011 """
1012 frame = await self.read_data_frame(max_size=self.max_size)
1013
1014 # A close frame was received.
1015 if frame is None:
1016 return None
1017
1018 if frame.opcode == OP_TEXT:
1019 text = True
1020 elif frame.opcode == OP_BINARY:
1021 text = False
1022 else: # frame.opcode == OP_CONT
1023 raise ProtocolError("unexpected opcode")
1024
1025 # Shortcut for the common case - no fragmentation
1026 if frame.fin:
1027 if isinstance(frame.data, memoryview):
1028 raise AssertionError("only compressed outgoing frames use memoryview")
1029 return frame.data.decode() if text else bytes(frame.data)
1030
1031 # 5.4. Fragmentation
1032 fragments: list[DataLike] = []
1033 max_size = self.max_size
1034 if text:
1035 decoder_factory = codecs.getincrementaldecoder("utf-8")
1036 decoder = decoder_factory(errors="strict")
1037 if max_size is None:
1038
1039 def append(frame: Frame) -> None:
1040 nonlocal fragments
1041 fragments.append(decoder.decode(frame.data, frame.fin))
1042
1043 else:
1044
1045 def append(frame: Frame) -> None:
1046 nonlocal fragments, max_size
1047 fragments.append(decoder.decode(frame.data, frame.fin))
1048 assert isinstance(max_size, int)
1049 max_size -= len(frame.data)
1050
1051 else:
1052 if max_size is None:
1053
1054 def append(frame: Frame) -> None:
1055 nonlocal fragments
1056 fragments.append(frame.data)
1057
1058 else:
1059
1060 def append(frame: Frame) -> None:
1061 nonlocal fragments, max_size
1062 fragments.append(frame.data)
1063 assert isinstance(max_size, int)
1064 max_size -= len(frame.data)
1065
1066 append(frame)
1067
1068 while not frame.fin:
1069 frame = await self.read_data_frame(max_size=max_size)
1070 if frame is None:
1071 raise ProtocolError("incomplete fragmented message")
1072 if frame.opcode != OP_CONT:
1073 raise ProtocolError("unexpected opcode")
1074 append(frame)
1075
1076 return ("" if text else b"").join(fragments)
1077
1078 async def read_data_frame(self, max_size: int | None) -> Frame | None:
1079 """
1080 Read a single data frame from the connection.
1081
1082 Process control frames received before the next data frame.
1083
1084 Return :obj:`None` if a close frame is encountered before any data frame.
1085
1086 """
1087 # 6.2. Receiving Data
1088 while True:
1089 frame = await self.read_frame(max_size)
1090
1091 # 5.5. Control Frames
1092 if frame.opcode == OP_CLOSE:
1093 # 7.1.5. The WebSocket Connection Close Code
1094 # 7.1.6. The WebSocket Connection Close Reason
1095 self.close_rcvd = Close.parse(frame.data)
1096 if self.close_sent is not None:
1097 self.close_rcvd_then_sent = False
1098 try:
1099 # Echo the original data instead of re-serializing it with
1100 # Close.serialize() because that fails when the close frame
1101 # is empty and Close.parse() synthesizes a 1005 close code.
1102 await self.write_close_frame(self.close_rcvd, frame.data)
1103 except ConnectionClosed:
1104 # Connection closed before we could echo the close frame.
1105 pass
1106 return None
1107
1108 elif frame.opcode == OP_PING:
1109 # Answer pings, unless connection is CLOSING.
1110 if self.state is State.OPEN:
1111 try:
1112 await self.pong(frame.data)
1113 except ConnectionClosed:
1114 # Connection closed while draining write buffer.
1115 pass
1116
1117 elif frame.opcode == OP_PONG:
1118 if frame.data in self.pings:
1119 pong_timestamp = time.perf_counter()
1120 # Sending a pong for only the most recent ping is legal.
1121 # Acknowledge all previous pings too in that case.
1122 ping_id = None
1123 ping_ids = []
1124 for ping_id, (pong_waiter, ping_timestamp) in self.pings.items():
1125 ping_ids.append(ping_id)
1126 if not pong_waiter.done():
1127 pong_waiter.set_result(pong_timestamp - ping_timestamp)
1128 if ping_id == frame.data:
1129 self.latency = pong_timestamp - ping_timestamp
1130 break
1131 else:
1132 raise AssertionError("solicited pong not found in pings")
1133 # Remove acknowledged pings from self.pings.
1134 for ping_id in ping_ids:
1135 del self.pings[ping_id]
1136
1137 # 5.6. Data Frames
1138 else:
1139 return frame
1140
1141 async def read_frame(self, max_size: int | None) -> Frame:
1142 """
1143 Read a single frame from the connection.
1144
1145 """
1146 frame = await Frame.read(
1147 self.reader.readexactly,
1148 mask=not self.is_client,
1149 max_size=max_size,
1150 extensions=self.extensions,
1151 )
1152 if self.debug:
1153 self.logger.debug("< %s", frame)
1154 return frame
1155
1156 def write_frame_sync(self, fin: bool, opcode: int, data: BytesLike) -> None:
1157 frame = Frame(fin, Opcode(opcode), data)
1158 if self.debug:
1159 self.logger.debug("> %s", frame)
1160 frame.write(
1161 self.transport.write,
1162 mask=self.is_client,
1163 extensions=self.extensions,
1164 )
1165
1166 async def drain(self) -> None:
1167 try:
1168 # Handle flow control automatically.
1169 await self._drain()
1170 except ConnectionError:
1171 # Terminate the connection if the socket died.
1172 self.fail_connection()
1173 # Wait until the connection is closed to raise ConnectionClosed
1174 # with the correct code and reason.
1175 await self.ensure_open()
1176
1177 async def write_frame(
1178 self, fin: bool, opcode: int, data: BytesLike, *, _state: int = State.OPEN
1179 ) -> None:
1180 # Defensive assertion for protocol compliance.
1181 if self.state is not _state: # pragma: no cover
1182 raise InvalidState(
1183 f"Cannot write to a WebSocket in the {self.state.name} state"
1184 )
1185 self.write_frame_sync(fin, opcode, data)
1186 await self.drain()
1187
1188 async def write_close_frame(
1189 self, close: Close, data: BytesLike | None = None
1190 ) -> None:
1191 """
1192 Write a close frame if and only if the connection state is OPEN.
1193
1194 This dedicated coroutine must be used for writing close frames to
1195 ensure that at most one close frame is sent on a given connection.
1196
1197 """
1198 # Test and set the connection state before sending the close frame to
1199 # avoid sending two frames in case of concurrent calls.
1200 if self.state is State.OPEN:
1201 # 7.1.3. The WebSocket Closing Handshake is Started
1202 self.state = State.CLOSING
1203 if self.debug:
1204 self.logger.debug("= connection is CLOSING")
1205
1206 self.close_sent = close
1207 if self.close_rcvd is not None:
1208 self.close_rcvd_then_sent = True
1209 if data is None:
1210 data = close.serialize()
1211
1212 # 7.1.2. Start the WebSocket Closing Handshake
1213 await self.write_frame(True, OP_CLOSE, data, _state=State.CLOSING)
1214
1215 async def keepalive_ping(self) -> None:
1216 """
1217 Send a Ping frame and wait for a Pong frame at regular intervals.
1218
1219 This coroutine exits when the connection terminates and one of the
1220 following happens:
1221
1222 - :meth:`ping` raises :exc:`ConnectionClosed`, or
1223 - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
1224
1225 """
1226 if self.ping_interval is None:
1227 return
1228
1229 try:
1230 while True:
1231 await asyncio.sleep(self.ping_interval)
1232
1233 if self.debug:
1234 self.logger.debug("% sending keepalive ping")
1235 pong_waiter = await self.ping()
1236
1237 if self.ping_timeout is not None:
1238 try:
1239 async with asyncio.timeout(self.ping_timeout):
1240 # Raises CancelledError if the connection is closed,
1241 # when close_connection() cancels keepalive_ping().
1242 # Raises ConnectionClosed if the connection is lost,
1243 # when connection_lost() calls abort_pings().
1244 await pong_waiter
1245 if self.debug:
1246 self.logger.debug("% received keepalive pong")
1247 except asyncio.TimeoutError:
1248 if self.debug:
1249 self.logger.debug("- timed out waiting for keepalive pong")
1250 self.fail_connection(
1251 CloseCode.INTERNAL_ERROR,
1252 "keepalive ping timeout",
1253 )
1254 break
1255
1256 except ConnectionClosed:
1257 pass
1258
1259 except Exception:
1260 self.logger.error("keepalive ping failed", exc_info=True)
1261
1262 async def close_connection(self) -> None:
1263 """
1264 7.1.1. Close the WebSocket Connection
1265
1266 When the opening handshake succeeds, :meth:`connection_open` starts
1267 this coroutine in a task. It waits for the data transfer phase to
1268 complete then it closes the TCP connection cleanly.
1269
1270 When the opening handshake fails, :meth:`fail_connection` does the
1271 same. There's no data transfer phase in that case.
1272
1273 """
1274 try:
1275 # Wait for the data transfer phase to complete.
1276 if hasattr(self, "transfer_data_task"):
1277 try:
1278 await self.transfer_data_task
1279 except asyncio.CancelledError:
1280 pass
1281
1282 # Cancel the keepalive ping task.
1283 if hasattr(self, "keepalive_ping_task"):
1284 self.keepalive_ping_task.cancel()
1285 # Break reference cycle to allow immediate garbage collection.
1286 del self.keepalive_ping_task
1287
1288 # A client should wait for a TCP close from the server.
1289 if self.is_client and hasattr(self, "transfer_data_task"):
1290 if await self.wait_for_connection_lost():
1291 return
1292 if self.debug:
1293 self.logger.debug("- timed out waiting for TCP close")
1294
1295 # Half-close the TCP connection if possible (when there's no TLS).
1296 if self.transport.can_write_eof():
1297 if self.debug:
1298 self.logger.debug("x half-closing TCP connection")
1299 # write_eof() doesn't document which exceptions it raises.
1300 # "[Errno 107] Transport endpoint is not connected" happens
1301 # but it isn't completely clear under which circumstances.
1302 # uvloop can raise RuntimeError here.
1303 try:
1304 self.transport.write_eof()
1305 except (OSError, RuntimeError): # pragma: no cover
1306 pass
1307
1308 if await self.wait_for_connection_lost():
1309 return
1310 if self.debug:
1311 self.logger.debug("- timed out waiting for TCP close")
1312
1313 finally:
1314 # The try/finally ensures that the transport never remains open,
1315 # even if this coroutine is canceled (for example).
1316 await self.close_transport()
1317
1318 async def close_transport(self) -> None:
1319 """
1320 Close the TCP connection.
1321
1322 """
1323 # If connection_lost() was called, the TCP connection is closed.
1324 # However, if TLS is enabled, the transport still needs closing.
1325 # Else asyncio complains: ResourceWarning: unclosed transport.
1326 if self.connection_lost_waiter.done() and self.transport.is_closing():
1327 return
1328
1329 # Close the TCP connection. Buffers are flushed asynchronously.
1330 if self.debug:
1331 self.logger.debug("x closing TCP connection")
1332 self.transport.close()
1333
1334 if await self.wait_for_connection_lost():
1335 return
1336 if self.debug:
1337 self.logger.debug("- timed out waiting for TCP close")
1338
1339 # Abort the TCP connection. Buffers are discarded.
1340 if self.debug:
1341 self.logger.debug("x aborting TCP connection")
1342 self.transport.abort()
1343
1344 # connection_lost() is called quickly after aborting.
1345 await self.wait_for_connection_lost()
1346
1347 async def wait_for_connection_lost(self) -> bool:
1348 """
1349 Wait until the TCP connection is closed or ``self.close_timeout`` elapses.
1350
1351 Return :obj:`True` if the connection is closed and :obj:`False`
1352 otherwise.
1353
1354 """
1355 if not self.connection_lost_waiter.done():
1356 try:
1357 async with asyncio.timeout(self.close_timeout):
1358 await asyncio.shield(self.connection_lost_waiter)
1359 except asyncio.TimeoutError:
1360 pass
1361 # Re-check self.connection_lost_waiter.done() synchronously because
1362 # connection_lost() could run between the moment the timeout occurs
1363 # and the moment this coroutine resumes running.
1364 return self.connection_lost_waiter.done()
1365
1366 def fail_connection(
1367 self,
1368 code: int = CloseCode.ABNORMAL_CLOSURE,
1369 reason: str = "",
1370 ) -> None:
1371 """
1372 7.1.7. Fail the WebSocket Connection
1373
1374 This requires:
1375
1376 1. Stopping all processing of incoming data, which means canceling
1377 :attr:`transfer_data_task`. The close code will be 1006 unless a
1378 close frame was received earlier.
1379
1380 2. Sending a close frame with an appropriate code if the opening
1381 handshake succeeded and the other side is likely to process it.
1382
1383 3. Closing the connection. :meth:`close_connection` takes care of
1384 this once :attr:`transfer_data_task` exits after being canceled.
1385
1386 (The specification describes these steps in the opposite order.)
1387
1388 """
1389 if self.debug:
1390 self.logger.debug("! failing connection with code %d", code)
1391
1392 # Cancel transfer_data_task if the opening handshake succeeded.
1393 # cancel() is idempotent and ignored if the task is done already.
1394 if hasattr(self, "transfer_data_task"):
1395 self.transfer_data_task.cancel()
1396
1397 # Send a close frame when the state is OPEN (a close frame was already
1398 # sent if it's CLOSING), except when failing the connection because of
1399 # an error reading from or writing to the network.
1400 # Don't send a close frame if the connection is broken.
1401 if code != CloseCode.ABNORMAL_CLOSURE and self.state is State.OPEN:
1402 close = Close(code, reason)
1403
1404 # Write the close frame without draining the write buffer.
1405
1406 # Keeping fail_connection() synchronous guarantees it can't
1407 # get stuck and simplifies the implementation of the callers.
1408 # Not drainig the write buffer is acceptable in this context.
1409
1410 # This duplicates a few lines of code from write_close_frame().
1411
1412 self.state = State.CLOSING
1413 if self.debug:
1414 self.logger.debug("= connection is CLOSING")
1415
1416 # If self.close_rcvd was set, the connection state would be
1417 # CLOSING. Therefore self.close_rcvd isn't set and we don't
1418 # have to set self.close_rcvd_then_sent.
1419 assert self.close_rcvd is None
1420 self.close_sent = close
1421
1422 self.write_frame_sync(True, OP_CLOSE, close.serialize())
1423
1424 # Start close_connection_task if the opening handshake didn't succeed.
1425 if not hasattr(self, "close_connection_task"):
1426 self.close_connection_task = self.loop.create_task(self.close_connection())
1427
1428 def abort_pings(self) -> None:
1429 """
1430 Raise ConnectionClosed in pending keepalive pings.
1431
1432 They'll never receive a pong once the connection is closed.
1433
1434 """
1435 assert self.state is State.CLOSED
1436 exc = self.connection_closed_exc()
1437
1438 for pong_waiter, _ping_timestamp in self.pings.values():
1439 pong_waiter.set_exception(exc)
1440 # If the exception is never retrieved, it will be logged when ping
1441 # is garbage-collected. This is confusing for users.
1442 # Given that ping is done (with an exception), canceling it does
1443 # nothing, but it prevents logging the exception.
1444 pong_waiter.cancel()
1445
1446 # asyncio.Protocol methods
1447
1448 def connection_made(self, transport: asyncio.BaseTransport) -> None:
1449 """
1450 Configure write buffer limits.
1451
1452 The high-water limit is defined by ``self.write_limit``.
1453
1454 The low-water limit currently defaults to ``self.write_limit // 4`` in
1455 :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should
1456 be all right for reasonable use cases of this library.
1457
1458 This is the earliest point where we can get hold of the transport,
1459 which means it's the best point for configuring it.
1460
1461 """
1462 transport = cast(asyncio.Transport, transport)
1463 transport.set_write_buffer_limits(self.write_limit)
1464 self.transport = transport
1465
1466 # Copied from asyncio.StreamReaderProtocol
1467 self.reader.set_transport(transport)
1468
1469 def connection_lost(self, exc: Exception | None) -> None:
1470 """
1471 7.1.4. The WebSocket Connection is Closed.
1472
1473 """
1474 self.state = State.CLOSED
1475 if self.debug:
1476 self.logger.debug("= connection is CLOSED")
1477
1478 self.abort_pings()
1479
1480 # If self.connection_lost_waiter isn't pending, that's a bug, because:
1481 # - it's set only here in connection_lost() which is called only once;
1482 # - it must never be canceled.
1483 self.connection_lost_waiter.set_result(None)
1484
1485 if True: # pragma: no cover
1486 # Copied from asyncio.StreamReaderProtocol
1487 if self.reader is not None:
1488 if exc is None:
1489 self.reader.feed_eof()
1490 else:
1491 self.reader.set_exception(exc)
1492
1493 # Copied from asyncio.FlowControlMixin
1494 # Wake up the writer if currently paused.
1495 if not self._paused:
1496 return
1497 waiter = self._drain_waiter
1498 if waiter is None:
1499 return
1500 self._drain_waiter = None
1501 if waiter.done():
1502 return
1503 if exc is None:
1504 waiter.set_result(None)
1505 else:
1506 waiter.set_exception(exc)
1507
1508 def pause_writing(self) -> None: # pragma: no cover
1509 assert not self._paused
1510 self._paused = True
1511
1512 def resume_writing(self) -> None: # pragma: no cover
1513 assert self._paused
1514 self._paused = False
1515
1516 waiter = self._drain_waiter
1517 if waiter is not None:
1518 self._drain_waiter = None
1519 if not waiter.done():
1520 waiter.set_result(None)
1521
1522 def data_received(self, data: bytes) -> None:
1523 self.reader.feed_data(data)
1524
1525 def eof_received(self) -> None:
1526 """
1527 Close the transport after receiving EOF.
1528
1529 The WebSocket protocol has its own closing handshake: endpoints close
1530 the TCP or TLS connection after sending and receiving a close frame.
1531
1532 As a consequence, they never need to write after receiving EOF, so
1533 there's no reason to keep the transport open by returning :obj:`True`.
1534
1535 Besides, that doesn't work on TLS connections.
1536
1537 """
1538 self.reader.feed_eof()
1539
1540
1541 # broadcast() is defined in the protocol module even though it's primarily
1542 # used by servers and documented in the server module because it works with
1543 # client connections too and because it's easier to test together with the
1544 # WebSocketCommonProtocol class.
1545
1546
1547 def broadcast(
1548 websockets: Iterable[WebSocketCommonProtocol],
1549 message: DataLike,
1550 raise_exceptions: bool = False,
1551 ) -> None:
1552 """
1553 Broadcast a message to several WebSocket connections.
1554
1555 A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like
1556 object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent
1557 as a Binary_ frame.
1558
1559 .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
1560 .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
1561
1562 :func:`broadcast` pushes the message synchronously to all connections even
1563 if their write buffers are overflowing. There's no backpressure.
1564
1565 If you broadcast messages faster than a connection can handle them, messages
1566 will pile up in its write buffer until the connection times out. Keep
1567 ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage
1568 from slow connections.
1569
1570 Unlike :meth:`~websockets.legacy.protocol.WebSocketCommonProtocol.send`,
1571 :func:`broadcast` doesn't support sending fragmented messages. Indeed,
1572 fragmentation is useful for sending large messages without buffering them in
1573 memory, while :func:`broadcast` buffers one copy per connection as fast as
1574 possible.
1575
1576 :func:`broadcast` skips connections that aren't open in order to avoid
1577 errors on connections where the closing handshake is in progress.
1578
1579 :func:`broadcast` ignores failures to write the message on some connections.
1580 It continues writing to other connections. You may set ``raise_exceptions``
1581 to :obj:`True` to record failures and raise all exceptions in a :pep:`654`
1582 :exc:`ExceptionGroup`.
1583
1584 While :func:`broadcast` makes more sense for servers, it works identically
1585 with clients, if you have a use case for opening connections to many servers
1586 and broadcasting a message to them.
1587
1588 Args:
1589 websockets: WebSocket connections to which the message will be sent.
1590 message: Message to send.
1591 raise_exceptions: Whether to raise an exception in case of failures.
1592
1593 Raises:
1594 TypeError: If ``message`` doesn't have a supported type.
1595
1596 """
1597 if not isinstance(message, (str, bytes, bytearray, memoryview)):
1598 raise TypeError("data must be str or bytes-like")
1599
1600 if raise_exceptions:
1601 exceptions = []
1602
1603 opcode, data = prepare_data(message)
1604
1605 for websocket in websockets:
1606 if websocket.state is not State.OPEN:
1607 continue
1608
1609 if websocket._fragmented_message_waiter is not None:
1610 if raise_exceptions:
1611 exception = RuntimeError("sending a fragmented message")
1612 exceptions.append(exception)
1613 else:
1614 websocket.logger.warning(
1615 "skipped broadcast: sending a fragmented message",
1616 )
1617 continue
1618
1619 try:
1620 websocket.write_frame_sync(True, opcode, data)
1621 except Exception as write_exception:
1622 if raise_exceptions:
1623 exception = RuntimeError("failed to write message")
1624 exception.__cause__ = write_exception
1625 exceptions.append(exception)
1626 else:
1627 websocket.logger.warning(
1628 "skipped broadcast: failed to write message: %s",
1629 traceback.format_exception_only(write_exception)[0].strip(),
1630 )
1631
1632 if raise_exceptions and exceptions:
1633 raise ExceptionGroup("skipped broadcast", exceptions)
1634
1635
1636 # Pretend that broadcast is actually defined in the server module.
1637 broadcast.__module__ = "websockets.legacy.server"