Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
274 changes: 268 additions & 6 deletions tests/test_tcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand All @@ -3072,20 +3125,229 @@ 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.fromfd(
sock.fileno(), socket.AF_INET, socket.SOCK_STREAM)
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()
Expand Down
2 changes: 2 additions & 0 deletions uvloop/sslproto.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading