diff --git a/Lib/asyncio/sslproto.py b/Lib/asyncio/sslproto.py index fba0911c2aa3b8..adf8d478553a9c 100644 --- a/Lib/asyncio/sslproto.py +++ b/Lib/asyncio/sslproto.py @@ -344,6 +344,10 @@ def __init__(self, loop, app_protocol, sslcontext, waiter, self._incoming_low_water = 0 self._set_read_buffer_limits() self._eof_received = False + # Set when a peer EOF could not be flushed yet because the app had + # paused reading; the flush completes when reading resumes or when + # the app closes the transport. + self._flush_deferred = False self._app_writing_paused = False self._outgoing_high_water = 0 @@ -489,6 +493,10 @@ def eof_received(self): elif self._state == SSLProtocolState.WRAPPED: self._set_state(SSLProtocolState.FLUSHING) if self._app_reading_paused: + # Flushing would drop the data that arrived before the + # EOF, and the app cannot receive it while reading is + # paused. Resume reading later, or finish from close(). + self._flush_deferred = True return True else: self._do_flush() @@ -636,20 +644,25 @@ def _on_handshake_complete(self, handshake_exc): # Shutdown flow def _start_shutdown(self): - if ( - self._state in ( - SSLProtocolState.FLUSHING, - SSLProtocolState.SHUTDOWN, - SSLProtocolState.UNWRAPPED - ) + if self._state in ( + SSLProtocolState.SHUTDOWN, + SSLProtocolState.UNWRAPPED ): return + if self._state == SSLProtocolState.FLUSHING: + if not self._flush_deferred: + return + # A peer EOF deferred the flush while reading was paused. The + # app has now closed the transport, so the buffered data will + # not be read after all: finish the shutdown instead of waiting + # for a resume_reading() that may never come. if self._app_transport is not None: self._app_transport._closed = True if self._state == SSLProtocolState.DO_HANDSHAKE: self._abort(None) else: - self._set_state(SSLProtocolState.FLUSHING) + if self._state != SSLProtocolState.FLUSHING: + self._set_state(SSLProtocolState.FLUSHING) self._shutdown_timeout_handle = self._loop.call_later( self._ssl_shutdown_timeout, self._check_shutdown_timeout @@ -667,6 +680,7 @@ def _check_shutdown_timeout(self): exceptions.TimeoutError('SSL shutdown timed out')) def _do_flush(self): + self._flush_deferred = False self._do_read() self._set_state(SSLProtocolState.SHUTDOWN) self._do_shutdown() diff --git a/Lib/test/test_asyncio/test_ssl.py b/Lib/test/test_asyncio/test_ssl.py index 76374a85b05cba..e6fa5b8c0bdb2f 100644 --- a/Lib/test/test_asyncio/test_ssl.py +++ b/Lib/test/test_asyncio/test_ssl.py @@ -1741,6 +1741,65 @@ async def client(addr): with self.tcp_server(server) as srv: loop.run_until_complete(client(srv.addr)) + def test_close_after_eof_while_reading_paused(self): + # gh-161560: a peer that sends EOF while the app has paused reading + # must not leave close() and wait_closed() hanging. + loop = self.loop + sslctx = self._create_server_ssl_context( + test_utils.ONLYCERT, + test_utils.ONLYKEY + ) + + async def main(): + handler_done = loop.create_future() + + async def handler(reader, writer): + try: + proto = writer.transport._ssl_protocol + async with asyncio.timeout(support.SHORT_TIMEOUT): + while not proto._eof_received: + await asyncio.sleep(0) + # The reader buffer is above the limit, so the transport + # paused reading when the peer's EOF arrived. + self.assertFalse(writer.transport.is_reading()) + writer.close() + await writer.wait_closed() + except BaseException as exc: + if not handler_done.done(): + handler_done.set_exception(exc) + raise + else: + handler_done.set_result(None) + + server = await asyncio.start_server( + handler, '127.0.0.1', 0, ssl=sslctx, limit=1024) + try: + port = server.sockets[0].getsockname()[1] + + def client(): + ctx = self._create_client_ssl_context() + with socket.create_connection(('127.0.0.1', port)) as raw: + with ctx.wrap_socket(raw) as s: + s.sendall(b'x' * 8192) + # Take in the TLS 1.3 session tickets so that + # closing sends a FIN rather than a reset. + s.settimeout(0.2) + try: + s.recv(1) + except TimeoutError: + pass + # Give the server time to pause reading before + # the FIN makes the EOF visible. + time.sleep(0.1) + + await asyncio.to_thread(client) + await asyncio.wait_for(handler_done, support.SHORT_TIMEOUT) + finally: + server.close() + await server.wait_closed() + + loop.run_until_complete(main()) + def test_shutdown_timeout_after_eof_from_not_reading_peer(self): # ssl_shutdown_timeout also applies when the peer has sent EOF, # before or after close(), but does not read what is still queued. diff --git a/Lib/test/test_asyncio/test_sslproto.py b/Lib/test/test_asyncio/test_sslproto.py index d6ec0df0f27c78..8521cfcb16f4e1 100644 --- a/Lib/test/test_asyncio/test_sslproto.py +++ b/Lib/test/test_asyncio/test_sslproto.py @@ -126,6 +126,29 @@ def test_eof_received_waiter(self): test_utils.run_briefly(self.loop) self.assertIsInstance(waiter.exception(), ConnectionResetError) + def test_close_after_eof_while_reading_paused(self): + # gh-161560: when the peer has sent EOF while the app paused + # reading, a later close() must finish the shutdown instead of + # leaving the transport parked in FLUSHING forever. + waiter = self.loop.create_future() + ssl_proto = self.ssl_protocol(waiter=waiter) + transport = self.connection_made( + ssl_proto, + do_handshake=mock.Mock() + ) + self.assertEqual(ssl_proto._state, sslproto.SSLProtocolState.WRAPPED) + + ssl_proto._pause_reading() + # EOF is deferred until the app reads; the transport must stay open. + self.assertTrue(ssl_proto.eof_received()) + self.assertEqual(ssl_proto._state, sslproto.SSLProtocolState.FLUSHING) + transport.close.assert_not_called() + + ssl_proto._start_shutdown() + self.assertEqual(ssl_proto._state, sslproto.SSLProtocolState.SHUTDOWN) + test_utils.run_briefly(self.loop) + transport.close.assert_called_once_with() + def test_fatal_error_no_name_error(self): # From issue #363. # _fatal_error() generates a NameError if sslproto.py diff --git a/Misc/NEWS.d/next/Library/2026-11-21-02-20-00.gh-issue-161560.Qv7RmT.rst b/Misc/NEWS.d/next/Library/2026-11-21-02-20-00.gh-issue-161560.Qv7RmT.rst new file mode 100644 index 00000000000000..9521fe428e9543 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-21-02-20-00.gh-issue-161560.Qv7RmT.rst @@ -0,0 +1,4 @@ +Fix :meth:`asyncio.StreamWriter.wait_closed` never returning when the transport +was closed after the TLS peer had already sent EOF while the protocol had paused +reading. The deferred SSL shutdown is now completed by ``close()`` instead of +waiting for a ``resume_reading()`` that may never come.