Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection.py 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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 uuid
  9. from types import TracebackType
  10. from typing import Any, Dict, Iterable, Iterator, Mapping, Optional, Type, Union
  11. from ..exceptions import ConnectionClosed, ConnectionClosedOK, ProtocolError
  12. from ..frames import DATA_OPCODES, BytesLike, Frame, Opcode, prepare_ctrl
  13. from ..http11 import Request, Response
  14. from ..protocol import CLOSED, OPEN, Event, Protocol, State
  15. from ..typing import Data, LoggerLike, Subprotocol
  16. from .messages import Assembler
  17. from .utils import Deadline
  18. __all__ = ["Connection"]
  19. logger = logging.getLogger(__name__)
  20. BUFSIZE = 65536
  21. class Connection:
  22. """
  23. Threaded implementation of a WebSocket connection.
  24. :class:`Connection` provides APIs shared between WebSocket servers and
  25. clients.
  26. You shouldn't use it directly. Instead, use
  27. :class:`~websockets.sync.client.ClientConnection` or
  28. :class:`~websockets.sync.server.ServerConnection`.
  29. """
  30. def __init__(
  31. self,
  32. socket: socket.socket,
  33. protocol: Protocol,
  34. *,
  35. close_timeout: Optional[float] = 10,
  36. ) -> None:
  37. self.socket = socket
  38. self.protocol = protocol
  39. self.close_timeout = close_timeout
  40. # Inject reference to this instance in the protocol's logger.
  41. self.protocol.logger = logging.LoggerAdapter(
  42. self.protocol.logger,
  43. {"websocket": self},
  44. )
  45. # Copy attributes from the protocol for convenience.
  46. self.id: uuid.UUID = self.protocol.id
  47. """Unique identifier of the connection. Useful in logs."""
  48. self.logger: LoggerLike = self.protocol.logger
  49. """Logger for this connection."""
  50. self.debug = self.protocol.debug
  51. # HTTP handshake request and response.
  52. self.request: Optional[Request] = None
  53. """Opening handshake request."""
  54. self.response: Optional[Response] = None
  55. """Opening handshake response."""
  56. # Mutex serializing interactions with the protocol.
  57. self.protocol_mutex = threading.Lock()
  58. # Assembler turning frames into messages and serializing reads.
  59. self.recv_messages = Assembler()
  60. # Whether we are busy sending a fragmented message.
  61. self.send_in_progress = False
  62. # Deadline for the closing handshake.
  63. self.close_deadline: Optional[Deadline] = None
  64. # Mapping of ping IDs to pong waiters, in chronological order.
  65. self.pings: Dict[bytes, threading.Event] = {}
  66. # Receiving events from the socket.
  67. self.recv_events_thread = threading.Thread(target=self.recv_events)
  68. self.recv_events_thread.start()
  69. # Exception raised in recv_events, to be chained to ConnectionClosed
  70. # in the user thread in order to show why the TCP connection dropped.
  71. self.recv_events_exc: Optional[BaseException] = None
  72. # Public attributes
  73. @property
  74. def local_address(self) -> Any:
  75. """
  76. Local address of the connection.
  77. For IPv4 connections, this is a ``(host, port)`` tuple.
  78. The format of the address depends on the address family.
  79. See :meth:`~socket.socket.getsockname`.
  80. """
  81. return self.socket.getsockname()
  82. @property
  83. def remote_address(self) -> Any:
  84. """
  85. Remote address of the connection.
  86. For IPv4 connections, this is a ``(host, port)`` tuple.
  87. The format of the address depends on the address family.
  88. See :meth:`~socket.socket.getpeername`.
  89. """
  90. return self.socket.getpeername()
  91. @property
  92. def subprotocol(self) -> Optional[Subprotocol]:
  93. """
  94. Subprotocol negotiated during the opening handshake.
  95. :obj:`None` if no subprotocol was negotiated.
  96. """
  97. return self.protocol.subprotocol
  98. # Public methods
  99. def __enter__(self) -> Connection:
  100. return self
  101. def __exit__(
  102. self,
  103. exc_type: Optional[Type[BaseException]],
  104. exc_value: Optional[BaseException],
  105. traceback: Optional[TracebackType],
  106. ) -> None:
  107. self.close(1000 if exc_type is None else 1011)
  108. def __iter__(self) -> Iterator[Data]:
  109. """
  110. Iterate on incoming messages.
  111. The iterator calls :meth:`recv` and yields messages in an infinite loop.
  112. It exits when the connection is closed normally. It raises a
  113. :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
  114. protocol error or a network failure.
  115. """
  116. try:
  117. while True:
  118. yield self.recv()
  119. except ConnectionClosedOK:
  120. return
  121. def recv(self, timeout: Optional[float] = None) -> Data:
  122. """
  123. Receive the next message.
  124. When the connection is closed, :meth:`recv` raises
  125. :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
  126. :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure
  127. and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
  128. error or a network failure. This is how you detect the end of the
  129. message stream.
  130. If ``timeout`` is :obj:`None`, block until a message is received. If
  131. ``timeout`` is set and no message is received within ``timeout``
  132. seconds, raise :exc:`TimeoutError`. Set ``timeout`` to ``0`` to check if
  133. a message was already received.
  134. If the message is fragmented, wait until all fragments are received,
  135. reassemble them, and return the whole message.
  136. Returns:
  137. A string (:class:`str`) for a Text_ frame or a bytestring
  138. (:class:`bytes`) for a Binary_ frame.
  139. .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
  140. .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
  141. Raises:
  142. ConnectionClosed: When the connection is closed.
  143. RuntimeError: If two threads call :meth:`recv` or
  144. :meth:`recv_streaming` concurrently.
  145. """
  146. try:
  147. return self.recv_messages.get(timeout)
  148. except EOFError:
  149. raise self.protocol.close_exc from self.recv_events_exc
  150. except RuntimeError:
  151. raise RuntimeError(
  152. "cannot call recv while another thread "
  153. "is already running recv or recv_streaming"
  154. ) from None
  155. def recv_streaming(self) -> Iterator[Data]:
  156. """
  157. Receive the next message frame by frame.
  158. If the message is fragmented, yield each fragment as it is received.
  159. The iterator must be fully consumed, or else the connection will become
  160. unusable.
  161. :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.
  162. Returns:
  163. An iterator of strings (:class:`str`) for a Text_ frame or
  164. bytestrings (:class:`bytes`) for a Binary_ frame.
  165. .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
  166. .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
  167. Raises:
  168. ConnectionClosed: When the connection is closed.
  169. RuntimeError: If two threads call :meth:`recv` or
  170. :meth:`recv_streaming` concurrently.
  171. """
  172. try:
  173. yield from self.recv_messages.get_iter()
  174. except EOFError:
  175. raise self.protocol.close_exc from self.recv_events_exc
  176. except RuntimeError:
  177. raise RuntimeError(
  178. "cannot call recv_streaming while another thread "
  179. "is already running recv or recv_streaming"
  180. ) from None
  181. def send(self, message: Union[Data, Iterable[Data]]) -> None:
  182. """
  183. Send a message.
  184. A string (:class:`str`) is sent as a Text_ frame. A bytestring or
  185. bytes-like object (:class:`bytes`, :class:`bytearray`, or
  186. :class:`memoryview`) is sent as a Binary_ frame.
  187. .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
  188. .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
  189. :meth:`send` also accepts an iterable of strings, bytestrings, or
  190. bytes-like objects to enable fragmentation_. Each item is treated as a
  191. message fragment and sent in its own frame. All items must be of the
  192. same type, or else :meth:`send` will raise a :exc:`TypeError` and the
  193. connection will be closed.
  194. .. _fragmentation: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.4
  195. :meth:`send` rejects dict-like objects because this is often an error.
  196. (If you really want to send the keys of a dict-like object as fragments,
  197. call its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
  198. When the connection is closed, :meth:`send` raises
  199. :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
  200. raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
  201. connection closure and
  202. :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
  203. error or a network failure.
  204. Args:
  205. message: Message to send.
  206. Raises:
  207. ConnectionClosed: When the connection is closed.
  208. RuntimeError: If a connection is busy sending a fragmented message.
  209. TypeError: If ``message`` doesn't have a supported type.
  210. """
  211. # Unfragmented message -- this case must be handled first because
  212. # strings and bytes-like objects are iterable.
  213. if isinstance(message, str):
  214. with self.send_context():
  215. if self.send_in_progress:
  216. raise RuntimeError(
  217. "cannot call send while another thread "
  218. "is already running send"
  219. )
  220. self.protocol.send_text(message.encode("utf-8"))
  221. elif isinstance(message, BytesLike):
  222. with self.send_context():
  223. if self.send_in_progress:
  224. raise RuntimeError(
  225. "cannot call send while another thread "
  226. "is already running send"
  227. )
  228. self.protocol.send_binary(message)
  229. # Catch a common mistake -- passing a dict to send().
  230. elif isinstance(message, Mapping):
  231. raise TypeError("data is a dict-like object")
  232. # Fragmented message -- regular iterator.
  233. elif isinstance(message, Iterable):
  234. chunks = iter(message)
  235. try:
  236. chunk = next(chunks)
  237. except StopIteration:
  238. return
  239. try:
  240. # First fragment.
  241. if isinstance(chunk, str):
  242. text = True
  243. with self.send_context():
  244. if self.send_in_progress:
  245. raise RuntimeError(
  246. "cannot call send while another thread "
  247. "is already running send"
  248. )
  249. self.send_in_progress = True
  250. self.protocol.send_text(
  251. chunk.encode("utf-8"),
  252. fin=False,
  253. )
  254. elif isinstance(chunk, BytesLike):
  255. text = False
  256. with self.send_context():
  257. if self.send_in_progress:
  258. raise RuntimeError(
  259. "cannot call send while another thread "
  260. "is already running send"
  261. )
  262. self.send_in_progress = True
  263. self.protocol.send_binary(
  264. chunk,
  265. fin=False,
  266. )
  267. else:
  268. raise TypeError("data iterable must contain bytes or str")
  269. # Other fragments
  270. for chunk in chunks:
  271. if isinstance(chunk, str) and text:
  272. with self.send_context():
  273. assert self.send_in_progress
  274. self.protocol.send_continuation(
  275. chunk.encode("utf-8"),
  276. fin=False,
  277. )
  278. elif isinstance(chunk, BytesLike) and not text:
  279. with self.send_context():
  280. assert self.send_in_progress
  281. self.protocol.send_continuation(
  282. chunk,
  283. fin=False,
  284. )
  285. else:
  286. raise TypeError("data iterable must contain uniform types")
  287. # Final fragment.
  288. with self.send_context():
  289. self.protocol.send_continuation(b"", fin=True)
  290. self.send_in_progress = False
  291. except RuntimeError:
  292. # We didn't start sending a fragmented message.
  293. raise
  294. except Exception:
  295. # We're half-way through a fragmented message and we can't
  296. # complete it. This makes the connection unusable.
  297. with self.send_context():
  298. self.protocol.fail(1011, "error in fragmented message")
  299. raise
  300. else:
  301. raise TypeError("data must be bytes, str, or iterable")
  302. def close(self, code: int = 1000, reason: str = "") -> None:
  303. """
  304. Perform the closing handshake.
  305. :meth:`close` waits for the other end to complete the handshake, for the
  306. TCP connection to terminate, and for all incoming messages to be read
  307. with :meth:`recv`.
  308. :meth:`close` is idempotent: it doesn't do anything once the
  309. connection is closed.
  310. Args:
  311. code: WebSocket close code.
  312. reason: WebSocket close reason.
  313. """
  314. try:
  315. # The context manager takes care of waiting for the TCP connection
  316. # to terminate after calling a method that sends a close frame.
  317. with self.send_context():
  318. if self.send_in_progress:
  319. self.protocol.fail(1011, "close during fragmented message")
  320. else:
  321. self.protocol.send_close(code, reason)
  322. except ConnectionClosed:
  323. # Ignore ConnectionClosed exceptions raised from send_context().
  324. # They mean that the connection is closed, which was the goal.
  325. pass
  326. def ping(self, data: Optional[Data] = None) -> threading.Event:
  327. """
  328. Send a Ping_.
  329. .. _Ping: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.2
  330. A ping may serve as a keepalive or as a check that the remote endpoint
  331. received all messages up to this point
  332. Args:
  333. data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
  334. If ``data`` is :obj:`None`, the payload is four random bytes.
  335. Returns:
  336. An event that will be set when the corresponding pong is received.
  337. You can ignore it if you don't intend to wait.
  338. ::
  339. pong_event = ws.ping()
  340. pong_event.wait() # only if you want to wait for the pong
  341. Raises:
  342. ConnectionClosed: When the connection is closed.
  343. RuntimeError: If another ping was sent with the same data and
  344. the corresponding pong wasn't received yet.
  345. """
  346. if data is not None:
  347. data = prepare_ctrl(data)
  348. with self.send_context():
  349. # Protect against duplicates if a payload is explicitly set.
  350. if data in self.pings:
  351. raise RuntimeError("already waiting for a pong with the same data")
  352. # Generate a unique random payload otherwise.
  353. while data is None or data in self.pings:
  354. data = struct.pack("!I", random.getrandbits(32))
  355. pong_waiter = threading.Event()
  356. self.pings[data] = pong_waiter
  357. self.protocol.send_ping(data)
  358. return pong_waiter
  359. def pong(self, data: Data = b"") -> None:
  360. """
  361. Send a Pong_.
  362. .. _Pong: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.3
  363. An unsolicited pong may serve as a unidirectional heartbeat.
  364. Args:
  365. data: Payload of the pong. A :class:`str` will be encoded to UTF-8.
  366. Raises:
  367. ConnectionClosed: When the connection is closed.
  368. """
  369. data = prepare_ctrl(data)
  370. with self.send_context():
  371. self.protocol.send_pong(data)
  372. # Private methods
  373. def process_event(self, event: Event) -> None:
  374. """
  375. Process one incoming event.
  376. This method is overridden in subclasses to handle the handshake.
  377. """
  378. assert isinstance(event, Frame)
  379. if event.opcode in DATA_OPCODES:
  380. self.recv_messages.put(event)
  381. if event.opcode is Opcode.PONG:
  382. self.acknowledge_pings(bytes(event.data))
  383. def acknowledge_pings(self, data: bytes) -> None:
  384. """
  385. Acknowledge pings when receiving a pong.
  386. """
  387. with self.protocol_mutex:
  388. # Ignore unsolicited pong.
  389. if data not in self.pings:
  390. return
  391. # Sending a pong for only the most recent ping is legal.
  392. # Acknowledge all previous pings too in that case.
  393. ping_id = None
  394. ping_ids = []
  395. for ping_id, ping in self.pings.items():
  396. ping_ids.append(ping_id)
  397. ping.set()
  398. if ping_id == data:
  399. break
  400. else:
  401. raise AssertionError("solicited pong not found in pings")
  402. # Remove acknowledged pings from self.pings.
  403. for ping_id in ping_ids:
  404. del self.pings[ping_id]
  405. def recv_events(self) -> None:
  406. """
  407. Read incoming data from the socket and process events.
  408. Run this method in a thread as long as the connection is alive.
  409. ``recv_events()`` exits immediately when the ``self.socket`` is closed.
  410. """
  411. try:
  412. while True:
  413. try:
  414. if self.close_deadline is not None:
  415. self.socket.settimeout(self.close_deadline.timeout())
  416. data = self.socket.recv(BUFSIZE)
  417. except Exception as exc:
  418. if self.debug:
  419. self.logger.debug("error while receiving data", exc_info=True)
  420. # When the closing handshake is initiated by our side,
  421. # recv() may block until send_context() closes the socket.
  422. # In that case, send_context() already set recv_events_exc.
  423. # Calling set_recv_events_exc() avoids overwriting it.
  424. with self.protocol_mutex:
  425. self.set_recv_events_exc(exc)
  426. break
  427. if data == b"":
  428. break
  429. # Acquire the connection lock.
  430. with self.protocol_mutex:
  431. # Feed incoming data to the connection.
  432. self.protocol.receive_data(data)
  433. # This isn't expected to raise an exception.
  434. events = self.protocol.events_received()
  435. # Write outgoing data to the socket.
  436. try:
  437. self.send_data()
  438. except Exception as exc:
  439. if self.debug:
  440. self.logger.debug("error while sending data", exc_info=True)
  441. # Similarly to the above, avoid overriding an exception
  442. # set by send_context(), in case of a race condition
  443. # i.e. send_context() closes the socket after recv()
  444. # returns above but before send_data() calls send().
  445. self.set_recv_events_exc(exc)
  446. break
  447. if self.protocol.close_expected():
  448. # If the connection is expected to close soon, set the
  449. # close deadline based on the close timeout.
  450. if self.close_deadline is None:
  451. self.close_deadline = Deadline(self.close_timeout)
  452. # Unlock conn_mutex before processing events. Else, the
  453. # application can't send messages in response to events.
  454. # If self.send_data raised an exception, then events are lost.
  455. # Given that automatic responses write small amounts of data,
  456. # this should be uncommon, so we don't handle the edge case.
  457. try:
  458. for event in events:
  459. # This may raise EOFError if the closing handshake
  460. # times out while a message is waiting to be read.
  461. self.process_event(event)
  462. except EOFError:
  463. break
  464. # Breaking out of the while True: ... loop means that we believe
  465. # that the socket doesn't work anymore.
  466. with self.protocol_mutex:
  467. # Feed the end of the data stream to the connection.
  468. self.protocol.receive_eof()
  469. # This isn't expected to generate events.
  470. assert not self.protocol.events_received()
  471. # There is no error handling because send_data() can only write
  472. # the end of the data stream here and it handles errors itself.
  473. self.send_data()
  474. except Exception as exc:
  475. # This branch should never run. It's a safety net in case of bugs.
  476. self.logger.error("unexpected internal error", exc_info=True)
  477. with self.protocol_mutex:
  478. self.set_recv_events_exc(exc)
  479. # We don't know where we crashed. Force protocol state to CLOSED.
  480. self.protocol.state = CLOSED
  481. finally:
  482. # This isn't expected to raise an exception.
  483. self.close_socket()
  484. @contextlib.contextmanager
  485. def send_context(
  486. self,
  487. *,
  488. expected_state: State = OPEN, # CONNECTING during the opening handshake
  489. ) -> Iterator[None]:
  490. """
  491. Create a context for writing to the connection from user code.
  492. On entry, :meth:`send_context` acquires the connection lock and checks
  493. that the connection is open; on exit, it writes outgoing data to the
  494. socket::
  495. with self.send_context():
  496. self.protocol.send_text(message.encode("utf-8"))
  497. When the connection isn't open on entry, when the connection is expected
  498. to close on exit, or when an unexpected error happens, terminating the
  499. connection, :meth:`send_context` waits until the connection is closed
  500. then raises :exc:`~websockets.exceptions.ConnectionClosed`.
  501. """
  502. # Should we wait until the connection is closed?
  503. wait_for_close = False
  504. # Should we close the socket and raise ConnectionClosed?
  505. raise_close_exc = False
  506. # What exception should we chain ConnectionClosed to?
  507. original_exc: Optional[BaseException] = None
  508. # Acquire the protocol lock.
  509. with self.protocol_mutex:
  510. if self.protocol.state is expected_state:
  511. # Let the caller interact with the protocol.
  512. try:
  513. yield
  514. except (ProtocolError, RuntimeError):
  515. # The protocol state wasn't changed. Exit immediately.
  516. raise
  517. except Exception as exc:
  518. self.logger.error("unexpected internal error", exc_info=True)
  519. # This branch should never run. It's a safety net in case of
  520. # bugs. Since we don't know what happened, we will close the
  521. # connection and raise the exception to the caller.
  522. wait_for_close = False
  523. raise_close_exc = True
  524. original_exc = exc
  525. else:
  526. # Check if the connection is expected to close soon.
  527. if self.protocol.close_expected():
  528. wait_for_close = True
  529. # If the connection is expected to close soon, set the
  530. # close deadline based on the close timeout.
  531. # Since we tested earlier that protocol.state was OPEN
  532. # (or CONNECTING) and we didn't release protocol_mutex,
  533. # it is certain that self.close_deadline is still None.
  534. assert self.close_deadline is None
  535. self.close_deadline = Deadline(self.close_timeout)
  536. # Write outgoing data to the socket.
  537. try:
  538. self.send_data()
  539. except Exception as exc:
  540. if self.debug:
  541. self.logger.debug("error while sending data", exc_info=True)
  542. # While the only expected exception here is OSError,
  543. # other exceptions would be treated identically.
  544. wait_for_close = False
  545. raise_close_exc = True
  546. original_exc = exc
  547. else: # self.protocol.state is not expected_state
  548. # Minor layering violation: we assume that the connection
  549. # will be closing soon if it isn't in the expected state.
  550. wait_for_close = True
  551. raise_close_exc = True
  552. # To avoid a deadlock, release the connection lock by exiting the
  553. # context manager before waiting for recv_events() to terminate.
  554. # If the connection is expected to close soon and the close timeout
  555. # elapses, close the socket to terminate the connection.
  556. if wait_for_close:
  557. if self.close_deadline is None:
  558. timeout = self.close_timeout
  559. else:
  560. # Thread.join() returns immediately if timeout is negative.
  561. timeout = self.close_deadline.timeout(raise_if_elapsed=False)
  562. self.recv_events_thread.join(timeout)
  563. if self.recv_events_thread.is_alive():
  564. # There's no risk to overwrite another error because
  565. # original_exc is never set when wait_for_close is True.
  566. assert original_exc is None
  567. original_exc = TimeoutError("timed out while closing connection")
  568. # Set recv_events_exc before closing the socket in order to get
  569. # proper exception reporting.
  570. raise_close_exc = True
  571. with self.protocol_mutex:
  572. self.set_recv_events_exc(original_exc)
  573. # If an error occurred, close the socket to terminate the connection and
  574. # raise an exception.
  575. if raise_close_exc:
  576. self.close_socket()
  577. self.recv_events_thread.join()
  578. raise self.protocol.close_exc from original_exc
  579. def send_data(self) -> None:
  580. """
  581. Send outgoing data.
  582. This method requires holding protocol_mutex.
  583. Raises:
  584. OSError: When a socket operations fails.
  585. """
  586. assert self.protocol_mutex.locked()
  587. for data in self.protocol.data_to_send():
  588. if data:
  589. if self.close_deadline is not None:
  590. self.socket.settimeout(self.close_deadline.timeout())
  591. self.socket.sendall(data)
  592. else:
  593. try:
  594. self.socket.shutdown(socket.SHUT_WR)
  595. except OSError: # socket already closed
  596. pass
  597. def set_recv_events_exc(self, exc: Optional[BaseException]) -> None:
  598. """
  599. Set recv_events_exc, if not set yet.
  600. This method requires holding protocol_mutex.
  601. """
  602. assert self.protocol_mutex.locked()
  603. if self.recv_events_exc is None:
  604. self.recv_events_exc = exc
  605. def close_socket(self) -> None:
  606. """
  607. Shutdown and close socket. Close message assembler.
  608. Calling close_socket() guarantees that recv_events() terminates. Indeed,
  609. recv_events() may block only on socket.recv() or on recv_messages.put().
  610. """
  611. # shutdown() is required to interrupt recv() on Linux.
  612. try:
  613. self.socket.shutdown(socket.SHUT_RDWR)
  614. except OSError:
  615. pass # socket is already closed
  616. self.socket.close()
  617. self.recv_messages.close()