您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

1642 行
62 KiB

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