connection.py 41 KB

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