From 15bfe6693f7d0c97835efb529de95b4c5b9cd0a5 Mon Sep 17 00:00:00 2001 From: Andrew Stelmach <236404138+andrew-stelmach-fleet@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:54:23 -0500 Subject: [PATCH 1/2] Deliver buffered TLS data before acting on a TCP EOF When the peer closed the TCP connection while received data had not been delivered to the application yet - e.g. because reading was paused - SSLProtocol.eof_received() closed the transport right away and the data was lost, with connection_lost(None) reported. This happened both with and without a close_notify in front of the EOF. The EOF is the last thing in the incoming stream, so only record it in eof_received() and let the regular read path run into the end of the incoming data in order: after the remaining data, SSLObject.read() reports either the close_notify, or that it wants more data than will ever come, and the shutdown starts from there. The transport is kept open until then. A TCP EOF without close_notify is still not reported to the application as eof_received(). Fixes #792. Co-Authored-By: Claude Fable 5.2 --- tests/test_tcp.py | 273 +++++++++++++++++++++++++++++++++++++++++++- uvloop/sslproto.pxd | 2 + uvloop/sslproto.pyx | 64 +++++++++-- 3 files changed, 321 insertions(+), 18 deletions(-) diff --git a/tests/test_tcp.py b/tests/test_tcp.py index f60fb2e9..9468d40a 100644 --- a/tests/test_tcp.py +++ b/tests/test_tcp.py @@ -53,6 +53,56 @@ def connection_lost(self, exc): self.done.set_result(None) +class SlowReaderMixin: + # Pauses reading as soon as it is connected and after each piece of + # data, so that the incoming data piles up in the transport. + + def __init__(self, loop, greeting=None): + self.loop = loop + self.greeting = greeting + self.nbytes = 0 + self.eof = False + self.lost = loop.create_future() + + def connection_made(self, transport): + self.transport = transport + if self.greeting: + transport.write(self.greeting) + # long enough for the peer to send everything and close + self.pause(0.2) + + def pause(self, delay): + self.transport.pause_reading() + self.loop.call_later(delay, self.transport.resume_reading) + + def received(self, nbytes): + assert not self.lost.done() + self.nbytes += nbytes + self.pause(0.001) + + def eof_received(self): + self.eof = True + + def connection_lost(self, exc): + self.lost.set_result(exc) + + +class SlowReader(SlowReaderMixin, asyncio.Protocol): + def data_received(self, data): + self.received(len(data)) + + +class SlowBufferedReader(SlowReaderMixin, asyncio.BufferedProtocol): + def get_buffer(self, sizehint): + return bytearray(65536) + + def buffer_updated(self, nbytes): + self.received(nbytes) + + +SLOW_READERS = (SlowReader, SlowBufferedReader) + + class _TestTCP: def test_create_server_1(self): CNT = 0 # number of clients that were successful @@ -3045,13 +3095,15 @@ def server(sock): sock.send(b'extra bytes') # sending EOF here sock.shutdown(socket.SHUT_WR) - # make sure we have enough time to reproduce the issue - self.assertEqual(sock.recv(1024), b'') + # wait for the client to close the connection + while sock.recv(1024): + pass sock.close() class Protocol(asyncio.Protocol): def __init__(self): self.fut = asyncio.Future(loop=loop) + self.paused = asyncio.Future(loop=loop) self.transport = None def connection_made(self, transport): @@ -3062,6 +3114,7 @@ def data_received(self, data): self.transport.write(b'world') # pause reading would make incoming data stay in the sslobj self.transport.pause_reading() + self.paused.set_result(None) else: nonlocal extra extra = data @@ -3072,20 +3125,228 @@ def connection_lost(self, exc): else: self.fut.set_exception(exc) - def eof_received(self): - self.transport.resume_reading() - async def client(addr): ctx = self._create_client_ssl_context() tr, pr = await loop.create_connection(Protocol, *addr, ssl=ctx) - await pr.fut + await pr.paused + # Let the EOF arrive while reading is paused: the connection + # stays open, because the extra data is not delivered yet. + await asyncio.sleep(0.2) + self.assertFalse(pr.fut.done()) + # Closing must not wait for a close_notify that cannot come. tr.close() + await asyncio.wait_for(pr.fut, 5) # extra data received after transport.close() should be ignored self.assertIsNone(extra) with self.tcp_server(server) as srv: loop.run_until_complete(client(srv.addr)) + def _test_eof_while_reading_paused(self, server, size, client=None): + # Run `server` against slow readers that are expected to receive + # `size` bytes before the connection is lost, even though the server + # is done long before they read anything. Return the readers. + loop = self.loop + client_sslctx = self._create_client_ssl_context() + + async def run(addr, factory): + tr, proto = await loop.create_connection( + lambda: factory(loop, b'go'), *addr, ssl=client_sslctx) + if client is not None: + await client(tr, proto) + exc = await asyncio.wait_for(proto.lost, 10) + self.assertIsNone(exc) + self.assertEqual(proto.nbytes, size) + return proto + + protos = [] + for factory in SLOW_READERS: + with self.subTest(protocol=factory.__name__, size=size): + with self.tcp_server(server, max_clients=1) as srv: + protos.append( + loop.run_until_complete(run(srv.addr, factory))) + return protos + + # Sizes of the data to test with: + # 1) everything is received before reading is resumed, and + # 2) more than the read buffer can hold, so that the EOF arrives + # in the middle of reading. + EOF_TEST_SIZES = (20_000, 2_000_000) + + def _eof_test_server(self, size, finish=None): + sslctx = self._create_server_ssl_context(self.ONLYCERT, self.ONLYKEY) + + def server(sock): + sock.starttls(sslctx, server_side=True) + self.assertEqual(sock.recv_all(2), b'go') + sock.sendall(b'x' * size) + if finish is not None: + finish(sock) + sock.close() + + return server + + def test_eof_without_close_notify_while_reading_paused(self): + if self.implementation == 'asyncio': + raise unittest.SkipTest() + + for size in self.EOF_TEST_SIZES: + for proto in self._test_eof_while_reading_paused( + self._eof_test_server(size), size): + # not a graceful shutdown + self.assertFalse(proto.eof) + + def test_close_notify_and_eof_while_reading_paused(self): + if self.implementation == 'asyncio': + raise unittest.SkipTest() + + def finish(sock): + # send close_notify without waiting for the reply + sock.settimeout(0) + with self.assertRaises(ssl.SSLWantReadError): + sock.unwrap() + + for size in self.EOF_TEST_SIZES: + for proto in self._test_eof_while_reading_paused( + self._eof_test_server(size, finish), size): + self.assertTrue(proto.eof) + + def test_truncated_record_and_eof_while_reading_paused(self): + if self.implementation == 'asyncio': + raise unittest.SkipTest() + + size = 20_000 + sslctx = self._create_server_ssl_context(self.ONLYCERT, self.ONLYKEY) + + def server(sock): + # SSLSocket doesn't let us send a part of a record + incoming = ssl.MemoryBIO() + outgoing = ssl.MemoryBIO() + sslobj = sslctx.wrap_bio(incoming, outgoing, server_side=True) + + def do(func, *args): + while True: + try: + rv = func(*args) + break + except ssl.SSLWantReadError: + if outgoing.pending: + sock.sendall(outgoing.read()) + incoming.write(sock.recv(65536)) + if outgoing.pending: + sock.sendall(outgoing.read()) + return rv + + do(sslobj.do_handshake) + self.assertEqual(do(sslobj.read, 2), b'go') + sslobj.write(b'x' * size) + complete = outgoing.read() + sslobj.write(b'y' * 100) + truncated = outgoing.read()[:-1] + sock.sendall(complete + truncated) + sock.close() + + for proto in self._test_eof_while_reading_paused(server, size): + self.assertFalse(proto.eof) + + def test_write_after_eof_while_reading_paused(self): + if self.implementation == 'asyncio': + raise unittest.SkipTest() + + size = 20_000 + + def finish(sock): + # Half-close the TCP connection, keeping the TLS session to + # read what the client has to say. + dup = socket.socket(fileno=os.dup(sock.fileno())) + dup.shutdown(socket.SHUT_WR) + dup.close() + self.assertEqual(sock.recv_all(3), b'ack') + + async def client(tr, proto): + # the EOF is received by now, and reading is still paused + await asyncio.sleep(0.1) + self.assertEqual(proto.nbytes, 0) + tr.write(b'ack') + + self._test_eof_while_reading_paused( + self._eof_test_server(size, finish), size, client=client) + + def test_close_while_reading_after_eof(self): + if self.implementation == 'asyncio': + raise unittest.SkipTest() + + # The application closes the connection while it is being given + # the data received before the EOF: the rest must be discarded. + size = 200_000 + loop = self.loop + client_sslctx = self._create_client_ssl_context() + + async def client(addr, factory, how): + calls = 0 + + class Proto(factory): + def received(self, nbytes): + nonlocal calls + calls += 1 + getattr(self.transport, how)() + + _, proto = await loop.create_connection( + lambda: Proto(loop, b'go'), *addr, ssl=client_sslctx) + self.assertIsNone(await asyncio.wait_for(proto.lost, 5)) + # let any stray callback run + await asyncio.sleep(0.05) + self.assertEqual(calls, 1) + + for factory in SLOW_READERS: + for how in ('close', 'abort'): + with self.subTest(protocol=factory.__name__, how=how): + with self.tcp_server(self._eof_test_server(size), + max_clients=1) as srv: + loop.run_until_complete( + client(srv.addr, factory, how)) + + def test_server_eof_without_close_notify_while_reading_paused(self): + if self.implementation == 'asyncio': + raise unittest.SkipTest() + + loop = self.loop + sslctx = self._create_server_ssl_context(self.ONLYCERT, self.ONLYKEY) + client_sslctx = self._create_client_ssl_context() + + async def run(factory, size): + proto = factory(loop) + srv = await loop.create_server( + lambda: proto, '127.0.0.1', 0, ssl=sslctx) + addr = srv.sockets[0].getsockname() + + def prog(sock): + sock.connect(addr) + sock.starttls(client_sslctx) + sock.sendall(b'x' * size) + # Send EOF without close_notify, and wait for the server + # to close: closing first, with the data from the server + # left unread, would reset the connection. + sock.shutdown(socket.SHUT_WR) + while sock.recv(65536): + pass + sock.close() + + try: + with self.tcp_client(prog): + exc = await asyncio.wait_for(proto.lost, 10) + finally: + srv.close() + await srv.wait_closed() + self.assertIsNone(exc) + self.assertEqual(proto.nbytes, size) + self.assertFalse(proto.eof) + + for factory in SLOW_READERS: + for size in self.EOF_TEST_SIZES: + with self.subTest(protocol=factory.__name__, size=size): + loop.run_until_complete(run(factory, size)) + def test_shutdown_while_pause_reading(self): if self.implementation == 'asyncio': raise unittest.SkipTest() diff --git a/uvloop/sslproto.pxd b/uvloop/sslproto.pxd index edc0f502..4eeb38d2 100644 --- a/uvloop/sslproto.pxd +++ b/uvloop/sslproto.pxd @@ -66,6 +66,7 @@ cdef class SSLProtocol: bint _ssl_writing_paused bint _app_reading_paused + bint _eof_received size_t _incoming_high_water size_t _incoming_low_water @@ -123,6 +124,7 @@ cdef class SSLProtocol: cdef inline _do_read(self) cdef inline _do_read__buffered(self) cdef inline _do_read__copied(self) + cdef inline _on_eof_without_close_notify(self) cdef inline _call_eof_received(self, object context=*) # Flow control for writes from APP socket diff --git a/uvloop/sslproto.pyx b/uvloop/sslproto.pyx index f76474e6..0db85c3f 100644 --- a/uvloop/sslproto.pyx +++ b/uvloop/sslproto.pyx @@ -262,6 +262,7 @@ cdef class SSLProtocol: self._outgoing = ssl_MemoryBIO() self._outgoing_read = self._outgoing.read self._state = UNWRAPPED + self._eof_received = False self._conn_lost = 0 # Set when connection_lost called if call_connection_made: self._app_state = STATE_INIT @@ -411,12 +412,23 @@ cdef class SSLProtocol: if self._state == DO_HANDSHAKE: self._on_handshake_complete(ConnectionResetError) - elif self._state == WRAPPED or self._state == FLUSHING: - # We treat a low-level EOF as a critical situation similar to a - # broken connection - just send whatever is in the buffer and - # close. No application level eof_received() is called - - # because we don't want the user to think that this is a - # graceful shutdown triggered by SSL "close_notify". + elif self._state == WRAPPED: + # The EOF comes after everything the peer has sent, some of + # which may not have been decrypted or delivered yet - e.g. + # when the application has paused reading. Only record the + # EOF here and let the regular read path run into the end + # of the incoming data in order, so that everything received + # before the EOF is delivered first. + self._eof_received = True + self._do_read() + # Keep the transport open while we still have data to + # deliver or to flush; we close it once that is done. + return self._state == WRAPPED or self._state == FLUSHING + + elif self._state == FLUSHING: + # The application has already closed the connection and is + # not interested in the incoming data - just send whatever + # is in the buffer and close. self._set_state(SHUTDOWN) self._on_shutdown_complete(None) @@ -633,7 +645,10 @@ cdef class SSLProtocol: # we must skip all application data (if any) before unwrap self._do_read_into_void(context) try: - self._sslobj.unwrap() + # close_notify cannot be exchanged after the peer has + # closed the connection, only flush what we have. + if not self._eof_received: + self._sslobj.unwrap() except ssl_SSLAgainErrors as exc: self._process_outgoing() else: @@ -748,6 +763,7 @@ cdef class SSLProtocol: Py_ssize_t total_bytes_read = 0 Py_buffer pybuf bint pybuf_initialized = False + bint eof = False try: # SSLObject.read may not return all available data in one go. @@ -773,9 +789,13 @@ cdef class SSLProtocol: # self._sslobj.pending() means how much data has been already # decrypted and can be directly read with SSLObject.read. + # Once the transport has reached EOF, nothing more will arrive, + # so we keep reading to find out how the stream ends: with a + # close_notify, or with SSLWantReadError when there is none. + # Run test_create_server_ssl_over_ssl to reproduce different cases # for this method. - while total_pending > 0: + while total_pending > 0 or self._eof_received: if total_bytes_read > 0: if not pybuf_initialized: PyObject_GetBuffer(app_buffer, &pybuf, PyBUF_WRITABLE) @@ -806,7 +826,7 @@ cdef class SSLProtocol: total_pending = (self._incoming.pending + self._sslobj_pending()) except ssl_SSLAgainErrors as exc: - pass + eof = self._eof_received finally: if pybuf_initialized: PyBuffer_Release(&pybuf) @@ -820,16 +840,21 @@ cdef class SSLProtocol: # close_notify self._call_eof_received() self._start_shutdown() + elif eof: + self._on_eof_without_close_notify() cdef _do_read__copied(self): cdef: list data bytes first, chunk = b'1' bint zero = True, one = False + bint eof = False try: + # See _do_read__buffered() for why EOF keeps the loop going. while (self._incoming.pending > 0 or - self._sslobj_pending() > 0): + self._sslobj_pending() > 0 or + self._eof_received): chunk = self._sslobj_read(SSL_READ_MAX_SIZE) if not chunk: break @@ -843,7 +868,7 @@ cdef class SSLProtocol: else: data.append(chunk) except ssl_SSLAgainErrors as exc: - pass + eof = self._eof_received if one: self._app_protocol.data_received(first) elif not zero: @@ -852,6 +877,17 @@ cdef class SSLProtocol: # close_notify self._call_eof_received() self._start_shutdown() + elif eof: + self._on_eof_without_close_notify() + + cdef _on_eof_without_close_notify(self): + # The peer closed the connection without sending close_notify, and + # all the data it had sent before that is now delivered. We treat + # this as a critical situation similar to a broken connection - just + # send whatever is in the buffer and close. No application level + # eof_received() is called - because we don't want the user to think + # that this is a graceful shutdown triggered by SSL "close_notify". + self._start_shutdown() cdef _call_eof_received(self, object context=None): if self._app_state == STATE_CON_MADE: @@ -946,7 +982,11 @@ cdef class SSLProtocol: # Flow control for reads from SSL socket cdef _control_ssl_reading(self): - cdef size_t size = self._get_read_buffer_size() + cdef size_t size + if self._eof_received: + # Nothing more to read from the transport. + return + size = self._get_read_buffer_size() if size >= self._incoming_high_water and not self._ssl_reading_paused: self._ssl_reading_paused = True self._transport.pause_reading() From 285dce2561c29e260338270a227a594262aa7410 Mon Sep 17 00:00:00 2001 From: Andrew Stelmach <236404138+andrew-stelmach-fleet@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:27:05 -0500 Subject: [PATCH 2/2] Use socket.fromfd for the half-close in the EOF test os.dup() does not work on socket handles on Windows. Co-Authored-By: Claude Fable 5.2 --- tests/test_tcp.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_tcp.py b/tests/test_tcp.py index 9468d40a..d3187e48 100644 --- a/tests/test_tcp.py +++ b/tests/test_tcp.py @@ -3258,7 +3258,8 @@ def test_write_after_eof_while_reading_paused(self): def finish(sock): # Half-close the TCP connection, keeping the TLS session to # read what the client has to say. - dup = socket.socket(fileno=os.dup(sock.fileno())) + dup = socket.fromfd( + sock.fileno(), socket.AF_INET, socket.SOCK_STREAM) dup.shutdown(socket.SHUT_WR) dup.close() self.assertEqual(sock.recv_all(3), b'ack')