protocol.py 64 KB

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