protocol.py 62 KB

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