connection.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. from __future__ import annotations
  2. import concurrent.futures
  3. import contextlib
  4. import logging
  5. import random
  6. import socket
  7. import struct
  8. import threading
  9. import time
  10. import traceback
  11. import uuid
  12. from collections.abc import Iterable, Iterator, Mapping
  13. from types import TracebackType
  14. from typing import Any, Literal, Self, overload
  15. from ..exceptions import (
  16. ConcurrencyError,
  17. ConnectionClosed,
  18. ConnectionClosedOK,
  19. ProtocolError,
  20. )
  21. from ..frames import DATA_OPCODES, PONG, CloseCode, Frame
  22. from ..http11 import Request, Response
  23. from ..protocol import CLOSED, CONNECTING, OPEN, Event, Protocol, State
  24. from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol
  25. from .messages import Assembler
  26. from .utils import Deadline
  27. __all__ = ["Connection"]
  28. class Connection:
  29. """
  30. :mod:`threading` implementation of a WebSocket connection.
  31. :class:`Connection` provides APIs shared between WebSocket servers and
  32. clients.
  33. You shouldn't use it directly. Instead, use
  34. :class:`~websockets.sync.client.ClientConnection` or
  35. :class:`~websockets.sync.server.ServerConnection`.
  36. """
  37. recv_bufsize = 65536
  38. def __init__(
  39. self,
  40. sock: socket.socket,
  41. protocol: Protocol,
  42. *,
  43. ping_interval: float | None = 20,
  44. ping_timeout: float | None = 20,
  45. close_timeout: float | None = 10,
  46. max_queue: int | None | tuple[int | None, int | None] = 16,
  47. ) -> None:
  48. self.socket = sock
  49. self.protocol = protocol
  50. self.ping_interval = ping_interval
  51. self.ping_timeout = ping_timeout
  52. self.close_timeout = close_timeout
  53. if isinstance(max_queue, int) or max_queue is None:
  54. max_queue_high, max_queue_low = max_queue, None
  55. else:
  56. max_queue_high, max_queue_low = max_queue
  57. # Inject reference to this instance in the protocol's logger.
  58. self.protocol.logger = logging.LoggerAdapter(
  59. self.protocol.logger,
  60. {"websocket": self},
  61. )
  62. # Copy attributes from the protocol for convenience.
  63. self.id: uuid.UUID = self.protocol.id
  64. """Unique identifier of the connection. Useful in logs."""
  65. self.logger: LoggerLike = self.protocol.logger
  66. """Logger for this connection."""
  67. self.debug = self.protocol.debug
  68. # HTTP handshake request and response.
  69. self.request: Request | None = None
  70. """Opening handshake request."""
  71. self.response: Response | None = None
  72. """Opening handshake response."""
  73. # Mutex serializing interactions with the protocol.
  74. self.protocol_mutex = threading.Lock()
  75. # Lock stopping reads when the assembler buffer is full.
  76. self.recv_flow_control = threading.Lock()
  77. # Assembler turning frames into messages and serializing reads.
  78. self.recv_messages = Assembler(
  79. max_queue_high,
  80. max_queue_low,
  81. pause=self.recv_flow_control.acquire,
  82. resume=self.recv_flow_control.release,
  83. )
  84. # Deadline for the closing handshake.
  85. self.close_deadline: Deadline | None = None
  86. # Whether we are busy sending a fragmented message.
  87. self.send_in_progress = False
  88. # Mapping of ping IDs to pong waiters, in chronological order.
  89. self.pending_pings: dict[bytes, tuple[threading.Event, float, bool]] = {}
  90. self.latency: float = 0.0
  91. """
  92. Latency of the connection, in seconds.
  93. Latency is defined as the round-trip time of the connection. It is
  94. measured by sending a Ping frame and waiting for a matching Pong frame.
  95. Before the first measurement, :attr:`latency` is ``0.0``.
  96. By default, websockets enables a :ref:`keepalive <keepalive>` mechanism
  97. that sends Ping frames automatically at regular intervals. You can also
  98. send Ping frames and measure latency with :meth:`ping`.
  99. """
  100. # Thread that sends keepalive pings. None when ping_interval is None.
  101. self.keepalive_thread: threading.Thread | None = None
  102. # Exception raised while reading from the connection, to be chained to
  103. # ConnectionClosed in order to show why the TCP connection dropped.
  104. self.recv_exc: BaseException | None = None
  105. # Receiving events from the socket. This thread is marked as daemon to
  106. # allow creating a connection in a non-daemon thread and using it in a
  107. # daemon thread. This mustn't prevent the interpreter from exiting.
  108. self.recv_events_thread = threading.Thread(
  109. target=self.recv_events,
  110. daemon=True,
  111. )
  112. # Start recv_events only after all attributes are initialized.
  113. self.recv_events_thread.start()
  114. # Public attributes
  115. @property
  116. def local_address(self) -> Any:
  117. """
  118. Local address of the connection.
  119. For IPv4 connections, this is a ``(host, port)`` tuple.
  120. The format of the address depends on the address family.
  121. See :meth:`~socket.socket.getsockname`.
  122. """
  123. return self.socket.getsockname()
  124. @property
  125. def remote_address(self) -> Any:
  126. """
  127. Remote address of the connection.
  128. For IPv4 connections, this is a ``(host, port)`` tuple.
  129. The format of the address depends on the address family.
  130. See :meth:`~socket.socket.getpeername`.
  131. """
  132. return self.socket.getpeername()
  133. @property
  134. def state(self) -> State:
  135. """
  136. State of the WebSocket connection, defined in :rfc:`6455`.
  137. This attribute is provided for completeness. Typical applications
  138. shouldn't check its value. Instead, they should call :meth:`~recv` or
  139. :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed`
  140. exceptions.
  141. """
  142. return self.protocol.state
  143. @property
  144. def subprotocol(self) -> Subprotocol | None:
  145. """
  146. Subprotocol negotiated during the opening handshake.
  147. :obj:`None` if no subprotocol was negotiated.
  148. """
  149. return self.protocol.subprotocol
  150. @property
  151. def close_code(self) -> int | None:
  152. """
  153. State of the WebSocket connection, defined in :rfc:`6455`.
  154. This attribute is provided for completeness. Typical applications
  155. shouldn't check its value. Instead, they should inspect attributes
  156. of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
  157. """
  158. return self.protocol.close_code
  159. @property
  160. def close_reason(self) -> str | None:
  161. """
  162. State of the WebSocket connection, defined in :rfc:`6455`.
  163. This attribute is provided for completeness. Typical applications
  164. shouldn't check its value. Instead, they should inspect attributes
  165. of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
  166. """
  167. return self.protocol.close_reason
  168. # Public methods
  169. def __enter__(self) -> Self:
  170. return self
  171. def __exit__(
  172. self,
  173. exc_type: type[BaseException] | None,
  174. exc_value: BaseException | None,
  175. traceback: TracebackType | None,
  176. ) -> None:
  177. if exc_type is None:
  178. self.close()
  179. else:
  180. self.close(CloseCode.INTERNAL_ERROR)
  181. def __iter__(self) -> Iterator[Data]:
  182. """
  183. Iterate on incoming messages.
  184. The iterator calls :meth:`recv` and yields messages in an infinite loop.
  185. It exits when the connection is closed normally. It raises a
  186. :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
  187. protocol error or a network failure.
  188. """
  189. try:
  190. while True:
  191. yield self.recv()
  192. except ConnectionClosedOK:
  193. return
  194. # This overload structure is required to avoid the error:
  195. # "parameter without a default follows parameter with a default"
  196. @overload
  197. def recv(self, timeout: float | None, decode: Literal[True]) -> str: ...
  198. @overload
  199. def recv(self, timeout: float | None, decode: Literal[False]) -> bytes: ...
  200. @overload
  201. def recv(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ...
  202. @overload
  203. def recv(
  204. self, timeout: float | None = None, *, decode: Literal[False]
  205. ) -> bytes: ...
  206. @overload
  207. def recv(
  208. self, timeout: float | None = None, decode: bool | None = None
  209. ) -> Data: ...
  210. def recv(self, timeout: float | None = None, decode: bool | None = None) -> Data:
  211. """
  212. Receive the next message.
  213. When the connection is closed, :meth:`recv` raises
  214. :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
  215. :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure
  216. and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
  217. error or a network failure. This is how you detect the end of the
  218. message stream.
  219. If ``timeout`` is :obj:`None`, block until a message is received. If
  220. ``timeout`` is set, wait up to ``timeout`` seconds for a message to be
  221. received and return it, else raise :exc:`TimeoutError`. If ``timeout``
  222. is ``0`` or negative, check if a message has been received already and
  223. return it, else raise :exc:`TimeoutError`.
  224. When the message is fragmented, :meth:`recv` waits until all fragments
  225. are received, reassembles them, and returns the whole message.
  226. Args:
  227. timeout: Timeout for receiving a message in seconds.
  228. decode: Set this flag to override the default behavior of returning
  229. :class:`str` or :class:`bytes`. See below for details.
  230. Returns:
  231. A string (:class:`str`) for a Text_ frame or a bytestring
  232. (:class:`bytes`) for a Binary_ frame.
  233. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  234. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  235. You may override this behavior with the ``decode`` argument:
  236. * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
  237. return a bytestring (:class:`bytes`). This improves performance
  238. when decoding isn't needed, for example if the message contains
  239. JSON and you're using a JSON library that expects a bytestring.
  240. * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and
  241. return strings (:class:`str`). This may be useful for servers that
  242. send binary frames instead of text frames.
  243. Raises:
  244. ConnectionClosed: When the connection is closed.
  245. ConcurrencyError: If two threads call :meth:`recv` or
  246. :meth:`recv_streaming` concurrently.
  247. """
  248. try:
  249. return self.recv_messages.get(timeout, decode)
  250. except EOFError:
  251. pass
  252. # fallthrough
  253. except ConcurrencyError:
  254. raise ConcurrencyError(
  255. "cannot call recv while another thread "
  256. "is already running recv or recv_streaming"
  257. ) from None
  258. except UnicodeDecodeError as exc:
  259. with self.send_context():
  260. self.protocol.fail(
  261. CloseCode.INVALID_DATA,
  262. f"{exc.reason} at position {exc.start}",
  263. )
  264. # fallthrough
  265. # Wait for the protocol state to be CLOSED before accessing close_exc.
  266. self.recv_events_thread.join()
  267. raise self.protocol.close_exc from self.recv_exc
  268. @overload
  269. def recv_streaming(self, decode: Literal[True]) -> Iterator[str]: ...
  270. @overload
  271. def recv_streaming(self, decode: Literal[False]) -> Iterator[bytes]: ...
  272. @overload
  273. def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: ...
  274. def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]:
  275. """
  276. Receive the next message frame by frame.
  277. This method is designed for receiving fragmented messages. It returns an
  278. iterator that yields each fragment as it is received. This iterator must
  279. be fully consumed. Else, future calls to :meth:`recv` or
  280. :meth:`recv_streaming` will raise
  281. :exc:`~websockets.exceptions.ConcurrencyError`, making the connection
  282. unusable.
  283. :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.
  284. Args:
  285. decode: Set this flag to override the default behavior of returning
  286. :class:`str` or :class:`bytes`. See below for details.
  287. Returns:
  288. An iterator of strings (:class:`str`) for a Text_ frame or
  289. bytestrings (:class:`bytes`) for a Binary_ frame.
  290. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  291. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  292. You may override this behavior with the ``decode`` argument:
  293. * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
  294. yield bytestrings (:class:`bytes`). This improves performance
  295. when decoding isn't needed.
  296. * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and
  297. yield strings (:class:`str`). This may be useful for servers that
  298. send binary frames instead of text frames.
  299. Raises:
  300. ConnectionClosed: When the connection is closed.
  301. ConcurrencyError: If two threads call :meth:`recv` or
  302. :meth:`recv_streaming` concurrently.
  303. """
  304. try:
  305. yield from self.recv_messages.get_iter(decode)
  306. return
  307. except EOFError:
  308. pass
  309. # fallthrough
  310. except ConcurrencyError:
  311. raise ConcurrencyError(
  312. "cannot call recv_streaming while another thread "
  313. "is already running recv or recv_streaming"
  314. ) from None
  315. except UnicodeDecodeError as exc:
  316. with self.send_context():
  317. self.protocol.fail(
  318. CloseCode.INVALID_DATA,
  319. f"{exc.reason} at position {exc.start}",
  320. )
  321. # fallthrough
  322. # Wait for the protocol state to be CLOSED before accessing close_exc.
  323. self.recv_events_thread.join()
  324. raise self.protocol.close_exc from self.recv_exc
  325. def send(
  326. self,
  327. message: DataLike | Iterable[DataLike],
  328. *,
  329. text: bool | None = None,
  330. ) -> None:
  331. """
  332. Send a message.
  333. A string (:class:`str`) is sent as a Text_ frame. A bytestring or
  334. bytes-like object (:class:`bytes`, :class:`bytearray`, or
  335. :class:`memoryview`) is sent as a Binary_ frame.
  336. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  337. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  338. You may override this behavior with the ``text`` argument:
  339. * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object
  340. (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a
  341. Text_ frame. This improves performance when the message is already
  342. UTF-8 encoded, for example if the message contains JSON and you're
  343. using a JSON library that produces a bytestring.
  344. * Set ``text=False`` to send a string (:class:`str`) in a Binary_
  345. frame. This may be useful for servers that expect binary frames
  346. instead of text frames.
  347. :meth:`send` also accepts an iterable of strings, bytestrings, or
  348. bytes-like objects to enable fragmentation_. Each item is treated as a
  349. message fragment and sent in its own frame. All items must be of the
  350. same type, or else :meth:`send` will raise a :exc:`TypeError` and the
  351. connection will be closed.
  352. .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
  353. :meth:`send` rejects dict-like objects because this is often an error.
  354. (If you really want to send the keys of a dict-like object as fragments,
  355. call its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
  356. When the connection is closed, :meth:`send` raises
  357. :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
  358. raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
  359. connection closure and
  360. :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
  361. error or a network failure.
  362. Args:
  363. message: Message to send.
  364. text: Force sending in a Text_ or Binary_ frame.
  365. Raises:
  366. ConnectionClosed: When the connection is closed.
  367. ConcurrencyError: If the connection is sending a fragmented message.
  368. TypeError: If ``message`` doesn't have a supported type.
  369. """
  370. # Unfragmented message — this case must be handled first because
  371. # strings and bytes-like objects are iterable.
  372. if isinstance(message, str):
  373. with self.send_context():
  374. if self.send_in_progress:
  375. raise ConcurrencyError(
  376. "cannot call send while another thread is already running send"
  377. )
  378. if text is False:
  379. self.protocol.send_binary(message.encode())
  380. else:
  381. self.protocol.send_text(message.encode())
  382. elif isinstance(message, BytesLike):
  383. with self.send_context():
  384. if self.send_in_progress:
  385. raise ConcurrencyError(
  386. "cannot call send while another thread is already running send"
  387. )
  388. if text is True:
  389. self.protocol.send_text(message)
  390. else:
  391. self.protocol.send_binary(message)
  392. # Catch a common mistake — passing a dict to send().
  393. elif isinstance(message, Mapping):
  394. raise TypeError("data is a dict-like object")
  395. # Fragmented message — regular iterator.
  396. elif isinstance(message, Iterable):
  397. chunks = iter(message)
  398. try:
  399. chunk = next(chunks)
  400. except StopIteration:
  401. return
  402. try:
  403. # First fragment.
  404. if isinstance(chunk, str):
  405. with self.send_context():
  406. if self.send_in_progress:
  407. raise ConcurrencyError(
  408. "cannot call send while another thread "
  409. "is already running send"
  410. )
  411. self.send_in_progress = True
  412. if text is False:
  413. self.protocol.send_binary(chunk.encode(), fin=False)
  414. else:
  415. self.protocol.send_text(chunk.encode(), fin=False)
  416. encode = True
  417. elif isinstance(chunk, BytesLike):
  418. with self.send_context():
  419. if self.send_in_progress:
  420. raise ConcurrencyError(
  421. "cannot call send while another thread "
  422. "is already running send"
  423. )
  424. self.send_in_progress = True
  425. if text is True:
  426. self.protocol.send_text(chunk, fin=False)
  427. else:
  428. self.protocol.send_binary(chunk, fin=False)
  429. encode = False
  430. else:
  431. raise TypeError("iterable must contain bytes or str")
  432. # Other fragments
  433. for chunk in chunks:
  434. if isinstance(chunk, str) and encode:
  435. with self.send_context():
  436. assert self.send_in_progress
  437. self.protocol.send_continuation(chunk.encode(), fin=False)
  438. elif isinstance(chunk, BytesLike) and not encode:
  439. with self.send_context():
  440. assert self.send_in_progress
  441. self.protocol.send_continuation(chunk, fin=False)
  442. else:
  443. raise TypeError("iterable must contain uniform types")
  444. # Final fragment.
  445. with self.send_context():
  446. self.protocol.send_continuation(b"", fin=True)
  447. self.send_in_progress = False
  448. except ConcurrencyError:
  449. # We didn't start sending a fragmented message.
  450. # The connection is still usable.
  451. raise
  452. except Exception:
  453. # We're half-way through a fragmented message and we can't
  454. # complete it. This makes the connection unusable.
  455. with self.send_context():
  456. self.protocol.fail(
  457. CloseCode.INTERNAL_ERROR,
  458. "error in fragmented message",
  459. )
  460. raise
  461. else:
  462. raise TypeError("data must be str, bytes, or iterable")
  463. def close(
  464. self,
  465. code: CloseCode | int = CloseCode.NORMAL_CLOSURE,
  466. reason: str = "",
  467. ) -> None:
  468. """
  469. Perform the closing handshake.
  470. :meth:`close` waits for the other end to complete the handshake and
  471. for the TCP connection to terminate.
  472. :meth:`close` is idempotent: it doesn't do anything once the
  473. connection is closed.
  474. Args:
  475. code: WebSocket close code.
  476. reason: WebSocket close reason.
  477. """
  478. try:
  479. # The context manager takes care of waiting for the TCP connection
  480. # to terminate after calling a method that sends a close frame.
  481. with self.send_context():
  482. if self.send_in_progress:
  483. self.protocol.fail(
  484. CloseCode.INTERNAL_ERROR,
  485. "close during fragmented message",
  486. )
  487. else:
  488. self.protocol.send_close(code, reason)
  489. except ConnectionClosed:
  490. # Ignore ConnectionClosed exceptions raised from send_context().
  491. # They mean that the connection is closed, which was the goal.
  492. pass
  493. def ping(
  494. self,
  495. data: DataLike | None = None,
  496. *,
  497. ack_on_close: bool = False,
  498. ) -> threading.Event:
  499. """
  500. Send a Ping_.
  501. .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
  502. A ping may serve as a keepalive or as a check that the remote endpoint
  503. received all messages up to this point
  504. Args:
  505. data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
  506. If ``data`` is :obj:`None`, the payload is four random bytes.
  507. ack_on_close: when this option is :obj:`True`, the event will also
  508. be set when the connection is closed. While this avoids getting
  509. stuck waiting for a pong that will never arrive, it requires
  510. checking that the state of the connection is still ``OPEN`` to
  511. confirm that a pong was received, rather than the connection
  512. being closed.
  513. Returns:
  514. An event that will be set when the corresponding pong is received.
  515. You can ignore it if you don't intend to wait.
  516. ::
  517. pong_received = ws.ping()
  518. # only if you want to wait for the corresponding pong
  519. pong_received.wait()
  520. Raises:
  521. ConnectionClosed: When the connection is closed.
  522. ConcurrencyError: If another ping was sent with the same data and
  523. the corresponding pong wasn't received yet.
  524. """
  525. if isinstance(data, BytesLike):
  526. data = bytes(data)
  527. elif isinstance(data, str):
  528. data = data.encode()
  529. elif data is not None:
  530. raise TypeError("data must be str or bytes-like")
  531. with self.send_context():
  532. # Protect against duplicates if a payload is explicitly set.
  533. if data in self.pending_pings:
  534. raise ConcurrencyError("already waiting for a pong with the same data")
  535. # Generate a unique random payload otherwise.
  536. while data is None or data in self.pending_pings:
  537. data = struct.pack("!I", random.getrandbits(32))
  538. pong_received = threading.Event()
  539. ping_timestamp = time.monotonic()
  540. self.pending_pings[data] = (pong_received, ping_timestamp, ack_on_close)
  541. self.protocol.send_ping(data)
  542. return pong_received
  543. def pong(self, data: DataLike = b"") -> None:
  544. """
  545. Send a Pong_.
  546. .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
  547. An unsolicited pong may serve as a unidirectional heartbeat.
  548. Args:
  549. data: Payload of the pong. A :class:`str` will be encoded to UTF-8.
  550. Raises:
  551. ConnectionClosed: When the connection is closed.
  552. """
  553. if isinstance(data, BytesLike):
  554. data = bytes(data)
  555. elif isinstance(data, str):
  556. data = data.encode()
  557. else:
  558. raise TypeError("data must be str or bytes-like")
  559. with self.send_context():
  560. self.protocol.send_pong(data)
  561. # Private methods
  562. def process_event(self, event: Event) -> None:
  563. """
  564. Process one incoming event.
  565. This method is overridden in subclasses to handle the handshake.
  566. """
  567. assert isinstance(event, Frame)
  568. if event.opcode in DATA_OPCODES:
  569. self.recv_messages.put(event)
  570. if event.opcode is PONG:
  571. self.acknowledge_pings(bytes(event.data))
  572. def acknowledge_pings(self, data: bytes) -> None:
  573. """
  574. Acknowledge pings when receiving a pong.
  575. """
  576. with self.protocol_mutex:
  577. # Ignore unsolicited pong.
  578. if data not in self.pending_pings:
  579. return
  580. pong_timestamp = time.monotonic()
  581. # Sending a pong for only the most recent ping is legal.
  582. # Acknowledge all previous pings too in that case.
  583. ping_id = None
  584. ping_ids = []
  585. for ping_id, (
  586. pong_received,
  587. ping_timestamp,
  588. _ack_on_close,
  589. ) in self.pending_pings.items():
  590. ping_ids.append(ping_id)
  591. pong_received.set()
  592. if ping_id == data:
  593. self.latency = pong_timestamp - ping_timestamp
  594. break
  595. else:
  596. raise AssertionError("solicited pong not found in pings")
  597. # Remove acknowledged pings from self.pending_pings.
  598. for ping_id in ping_ids:
  599. del self.pending_pings[ping_id]
  600. def terminate_pending_pings(self) -> None:
  601. """
  602. Acknowledge pending pings when the connection is closed.
  603. """
  604. assert self.protocol_mutex.locked()
  605. assert self.protocol.state is CLOSED
  606. for pong_received, _ping_timestamp, ack_on_close in self.pending_pings.values():
  607. if ack_on_close:
  608. pong_received.set()
  609. self.pending_pings.clear()
  610. def keepalive(self) -> None:
  611. """
  612. Send a Ping frame and wait for a Pong frame at regular intervals.
  613. """
  614. assert self.ping_interval is not None
  615. try:
  616. while True:
  617. # If self.ping_timeout > self.latency > self.ping_interval,
  618. # pings will be sent immediately after receiving pongs.
  619. # The period will be longer than self.ping_interval.
  620. self.recv_events_thread.join(self.ping_interval - self.latency)
  621. if not self.recv_events_thread.is_alive():
  622. break
  623. try:
  624. pong_received = self.ping(ack_on_close=True)
  625. except ConnectionClosed:
  626. break
  627. if self.debug:
  628. self.logger.debug("% sent keepalive ping")
  629. if self.ping_timeout is not None:
  630. if pong_received.wait(self.ping_timeout):
  631. if self.debug:
  632. self.logger.debug("% received keepalive pong")
  633. else:
  634. if self.debug:
  635. self.logger.debug("- timed out waiting for keepalive pong")
  636. with self.send_context():
  637. self.protocol.fail(
  638. CloseCode.INTERNAL_ERROR,
  639. "keepalive ping timeout",
  640. )
  641. break
  642. except Exception:
  643. self.logger.error("keepalive ping failed", exc_info=True)
  644. def start_keepalive(self) -> None:
  645. """
  646. Run :meth:`keepalive` in a thread, unless keepalive is disabled.
  647. """
  648. if self.ping_interval is not None:
  649. # This thread is marked as daemon like self.recv_events_thread.
  650. self.keepalive_thread = threading.Thread(
  651. target=self.keepalive,
  652. daemon=True,
  653. )
  654. self.keepalive_thread.start()
  655. def recv_events(self) -> None:
  656. """
  657. Read incoming data from the socket and process events.
  658. Run this method in a thread as long as the connection is alive.
  659. ``recv_events()`` exits immediately when ``self.socket`` is closed.
  660. """
  661. # When the opening handshake fails, we cannot trust rules in RFC 6455
  662. # for closing TCP connections will be followed. The HTTP server could
  663. # keep the connection alive after sending the response. We attempt to
  664. # close the connection immediately. Unfortunately, this is unreliable
  665. # on macOS; recv() may block until close_timeout elapses:
  666. # https://github.com/python-websockets/websockets/issues/1596
  667. # https://github.com/python/cpython/issues/154224
  668. # In that case, break out of the loop to prevent recv() from blocking
  669. # until close_timeout elapses.
  670. close_expected_while_connecting = False
  671. try:
  672. while not close_expected_while_connecting:
  673. try:
  674. # If the assembler buffer is full, block until it drains.
  675. with self.recv_flow_control:
  676. pass
  677. if self.close_deadline is not None:
  678. self.socket.settimeout(self.close_deadline.timeout())
  679. data = self.socket.recv(self.recv_bufsize)
  680. except Exception as exc:
  681. if self.debug:
  682. self.logger.debug(
  683. "! error while receiving data",
  684. exc_info=True,
  685. )
  686. # When the closing handshake is initiated by our side,
  687. # recv() may block until send_context() closes the socket.
  688. # In that case, send_context() already set recv_exc.
  689. # Calling set_recv_exc() avoids overwriting it.
  690. with self.protocol_mutex:
  691. self.set_recv_exc(exc)
  692. break
  693. if data == b"":
  694. break
  695. # Acquire the connection lock.
  696. with self.protocol_mutex:
  697. # Feed incoming data to the protocol.
  698. self.protocol.receive_data(data)
  699. # This isn't expected to raise an exception.
  700. events = self.protocol.events_received()
  701. # Write outgoing data to the socket.
  702. try:
  703. self.send_data()
  704. except Exception as exc:
  705. if self.debug:
  706. self.logger.debug(
  707. "! error while sending data",
  708. exc_info=True,
  709. )
  710. # Similarly to the above, avoid overriding an exception
  711. # set by send_context(), in case of a race condition
  712. # i.e. send_context() closes the socket after recv()
  713. # returns above but before send_data() calls send().
  714. self.set_recv_exc(exc)
  715. break
  716. # If needed, set the close deadline based on the close timeout.
  717. if self.protocol.close_expected():
  718. if self.close_deadline is None:
  719. self.close_deadline = Deadline(self.close_timeout)
  720. if self.protocol.state is CONNECTING:
  721. close_expected_while_connecting = True
  722. # Unlock conn_mutex before processing events. Else, the
  723. # application can't send messages in response to events.
  724. # If self.send_data raised an exception, then events are lost.
  725. # Given that automatic responses write small amounts of data,
  726. # this should be uncommon, so we don't handle the edge case.
  727. for event in events:
  728. # This isn't expected to raise an exception.
  729. self.process_event(event)
  730. # Breaking out of the while not close_expected_while_connecting: ...
  731. # loop means that we believe that the socket doesn't work anymore.
  732. with self.protocol_mutex:
  733. # Feed the end of the data stream to the protocol.
  734. self.protocol.receive_eof()
  735. # This isn't expected to raise an exception.
  736. events = self.protocol.events_received()
  737. # There is no error handling because send_data() can only write
  738. # the end of the data stream and it handles errors by itself.
  739. self.send_data()
  740. # This code path is triggered when receiving an HTTP response
  741. # without a Content-Length header. This is the only case where
  742. # reading until EOF generates an event; all other events have
  743. # a known length. Ignore for coverage measurement because tests
  744. # are in test_client.py rather than test_connection.py.
  745. for event in events: # pragma: no cover
  746. # This isn't expected to raise an exception.
  747. self.process_event(event)
  748. except Exception as exc:
  749. # This branch should never run. It's a safety net in case of bugs.
  750. self.logger.error("unexpected internal error", exc_info=True)
  751. with self.protocol_mutex:
  752. self.set_recv_exc(exc)
  753. finally:
  754. # This isn't expected to raise an exception.
  755. self.close_socket()
  756. @contextlib.contextmanager
  757. def send_context(
  758. self,
  759. *,
  760. expected_state: State = OPEN, # CONNECTING during the opening handshake
  761. ) -> Iterator[None]:
  762. """
  763. Create a context for writing to the connection from user code.
  764. On entry, :meth:`send_context` acquires the connection lock and checks
  765. that the connection is open; on exit, it writes outgoing data to the
  766. socket and releases the connection lock::
  767. with self.send_context():
  768. self.protocol.send_text(message.encode())
  769. When the connection isn't open on entry, when the connection is expected
  770. to close on exit, or when an unexpected error happens, terminating the
  771. connection, :meth:`send_context` waits until the connection is closed
  772. then raises :exc:`~websockets.exceptions.ConnectionClosed`.
  773. """
  774. # Should we wait until the connection is closed?
  775. wait_for_close = False
  776. # Should we close the socket and raise ConnectionClosed?
  777. raise_close_exc = False
  778. # What exception should we chain ConnectionClosed to?
  779. original_exc: BaseException | None = None
  780. # Acquire the protocol lock.
  781. with self.protocol_mutex:
  782. if self.protocol.state is expected_state:
  783. # Let the caller interact with the protocol.
  784. try:
  785. yield
  786. except (ProtocolError, ConcurrencyError):
  787. # The protocol state wasn't changed. Exit immediately.
  788. raise
  789. except Exception as exc:
  790. self.logger.error("unexpected internal error", exc_info=True)
  791. # This branch should never run. It's a safety net in case of
  792. # bugs. Since we don't know what happened, we will close the
  793. # connection and raise the exception to the caller.
  794. wait_for_close = False
  795. raise_close_exc = True
  796. original_exc = exc
  797. else:
  798. # Check if the connection is expected to close soon.
  799. if self.protocol.close_expected():
  800. wait_for_close = True
  801. # Set the close deadline based on the close timeout.
  802. # Since we tested earlier that protocol.state is OPEN
  803. # (or CONNECTING) and we didn't release protocol_mutex,
  804. # self.close_deadline is still None.
  805. assert self.close_deadline is None
  806. self.close_deadline = Deadline(self.close_timeout)
  807. # Write outgoing data to the socket.
  808. try:
  809. self.send_data()
  810. except Exception as exc:
  811. if self.debug:
  812. self.logger.debug(
  813. "! error while sending data",
  814. exc_info=True,
  815. )
  816. # While the only expected exception here is OSError,
  817. # other exceptions would be treated identically.
  818. wait_for_close = False
  819. raise_close_exc = True
  820. original_exc = exc
  821. else: # self.protocol.state is not expected_state
  822. # Minor layering violation: we assume that the connection
  823. # will be closing soon if it isn't in the expected state.
  824. wait_for_close = True
  825. # Calculate close_deadline if it wasn't set yet.
  826. if self.close_deadline is None:
  827. self.close_deadline = Deadline(self.close_timeout)
  828. raise_close_exc = True
  829. # To avoid a deadlock, release the connection lock by exiting the
  830. # context manager before waiting for recv_events() to terminate.
  831. # If the connection is expected to close soon and the close timeout
  832. # elapses, close the socket to terminate the connection.
  833. if wait_for_close:
  834. # Thread.join() returns immediately if timeout is negative.
  835. assert self.close_deadline is not None
  836. timeout = self.close_deadline.timeout(raise_if_elapsed=False)
  837. self.recv_events_thread.join(timeout)
  838. if self.recv_events_thread.is_alive():
  839. # There's no risk of overwriting another error because
  840. # original_exc is never set when wait_for_close is True.
  841. assert original_exc is None
  842. original_exc = TimeoutError("timed out while closing connection")
  843. # Set recv_exc before closing the socket in order to get
  844. # proper exception reporting.
  845. raise_close_exc = True
  846. with self.protocol_mutex:
  847. self.set_recv_exc(original_exc)
  848. # If an error occurred, close the socket to terminate the connection and
  849. # raise an exception.
  850. if raise_close_exc:
  851. self.close_socket()
  852. # Wait for the protocol state to be CLOSED before accessing close_exc.
  853. self.recv_events_thread.join()
  854. raise self.protocol.close_exc from original_exc
  855. def send_data(self) -> None:
  856. """
  857. Send outgoing data.
  858. This method requires holding protocol_mutex.
  859. """
  860. assert self.protocol_mutex.locked()
  861. for data in self.protocol.data_to_send():
  862. if data:
  863. if self.close_deadline is not None:
  864. self.socket.settimeout(self.close_deadline.timeout())
  865. self.socket.sendall(data)
  866. else:
  867. try:
  868. self.socket.shutdown(socket.SHUT_WR)
  869. except OSError: # socket already closed
  870. pass
  871. def set_recv_exc(self, exc: BaseException | None) -> None:
  872. """
  873. Set recv_exc, if not set yet.
  874. This method requires holding protocol_mutex and must be called only from
  875. the thread running recv_events().
  876. """
  877. assert self.protocol_mutex.locked()
  878. if self.recv_exc is None:
  879. self.recv_exc = exc
  880. def close_socket(self) -> None:
  881. """
  882. Shutdown and close socket. Close message assembler.
  883. Calling close_socket() guarantees that recv_events() terminates. Indeed,
  884. recv_events() may block only on socket.recv() or on recv_messages.put().
  885. """
  886. # shutdown() is required to interrupt recv() on Linux.
  887. try:
  888. self.socket.shutdown(socket.SHUT_RDWR)
  889. except OSError: # socket already closed
  890. pass
  891. try:
  892. self.socket.close()
  893. except OSError: # socket already closed # pragma: no cover
  894. # OSError: [Errno 9] Bad file descriptor
  895. # (only observed on free-threaded Python)
  896. pass
  897. # Calling protocol.receive_eof() is safe because it's idempotent.
  898. # This guarantees that the protocol state becomes CLOSED.
  899. with self.protocol_mutex:
  900. self.protocol.receive_eof()
  901. assert self.protocol.state is CLOSED
  902. # Abort recv() with a ConnectionClosed exception.
  903. self.recv_messages.close()
  904. # Acknowledge pings sent with the ack_on_close option.
  905. self.terminate_pending_pings()
  906. # broadcast() is defined in the connection module even though it's primarily
  907. # used by servers and documented in the server module because it works with
  908. # client connections too and because it's easier to test together with the
  909. # Connection class.
  910. def broadcast(
  911. connections: Iterable[Connection],
  912. message: DataLike,
  913. *,
  914. raise_exceptions: bool = False,
  915. text: bool | None = None,
  916. **kwargs: Any,
  917. ) -> None:
  918. """
  919. Broadcast a message to several WebSocket connections.
  920. A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like
  921. object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent
  922. as a Binary_ frame.
  923. .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  924. .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
  925. You may override this behavior with the ``text`` argument:
  926. * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object
  927. (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a
  928. Text_ frame. This improves performance when the message is already
  929. UTF-8 encoded, for example if the message contains JSON and you're
  930. using a JSON library that produces a bytestring.
  931. * Set ``text=False`` to send a string (:class:`str`) in a Binary_
  932. frame. This may be useful for servers that expect binary frames
  933. instead of text frames.
  934. :func:`broadcast` relies on :class:`concurrent.futures.ThreadPoolExecutor`
  935. to send the messages. Make sure the thread pool is large enough relative to
  936. the number of clients, so that slow or stuck connections don't clog it. If
  937. that's an issue, then you should be using an asynchronous implementation.
  938. You can configure the thread pool by passing additional keyword arguments to
  939. :func:`broadcast`, such as ``max_workers``.
  940. Unlike :meth:`~websockets.asyncio.connection.Connection.send`,
  941. :func:`broadcast` doesn't support sending fragmented messages. Indeed,
  942. fragmentation is useful for sending large messages without buffering them in
  943. memory, while :func:`broadcast` buffers one copy per connection as fast as
  944. possible.
  945. :func:`broadcast` skips connections that aren't open in order to avoid
  946. errors on connections where the closing handshake is in progress.
  947. :func:`broadcast` ignores failures to write the message on some connections.
  948. It continues writing to other connections. You may set ``raise_exceptions``
  949. to :obj:`True` to record failures and raise all exceptions in a :pep:`654`
  950. :exc:`ExceptionGroup`.
  951. While :func:`broadcast` makes more sense for servers, it works identically
  952. with clients, if you have a use case for opening connections to many servers
  953. and broadcasting a message to them.
  954. Args:
  955. websockets: WebSocket connections to which the message will be sent.
  956. message: Message to send.
  957. raise_exceptions: Whether to raise an exception in case of failures.
  958. text: Force sending in Text_ or Binary_ frames.
  959. Raises:
  960. TypeError: If ``message`` doesn't have a supported type.
  961. """
  962. if isinstance(message, str):
  963. send_method = "send_binary" if text is False else "send_text"
  964. message = message.encode()
  965. elif isinstance(message, BytesLike):
  966. send_method = "send_text" if text is True else "send_binary"
  967. else:
  968. raise TypeError("data must be str or bytes")
  969. if raise_exceptions:
  970. exceptions: list[Exception] = []
  971. def send_message(connection: Connection) -> None:
  972. exception: Exception
  973. with connection.protocol_mutex:
  974. if connection.protocol.state is not OPEN:
  975. return
  976. if connection.send_in_progress:
  977. if raise_exceptions:
  978. exception = ConcurrencyError("sending a fragmented message")
  979. exceptions.append(exception)
  980. else:
  981. connection.logger.warning(
  982. "skipped broadcast: sending a fragmented message",
  983. )
  984. return
  985. try:
  986. # Call connection.protocol.send_text or send_binary.
  987. # Either way, message is already converted to bytes.
  988. getattr(connection.protocol, send_method)(message)
  989. connection.send_data()
  990. except Exception as write_exception:
  991. if raise_exceptions:
  992. exception = RuntimeError("failed to write message")
  993. exception.__cause__ = write_exception
  994. exceptions.append(exception)
  995. else:
  996. connection.logger.warning(
  997. "skipped broadcast: failed to write message: %s",
  998. traceback.format_exception_only(write_exception)[0].strip(),
  999. )
  1000. with concurrent.futures.ThreadPoolExecutor(**kwargs) as executor:
  1001. executor.map(send_message, connections)
  1002. if raise_exceptions and exceptions:
  1003. raise ExceptionGroup("skipped broadcast", exceptions)
  1004. # Pretend that broadcast is actually defined in the server module.
  1005. broadcast.__module__ = "websockets.sync.server"