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
44 changes: 30 additions & 14 deletions Lib/asyncio/base_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -1020,8 +1020,12 @@ def _check_sendfile_params(self, sock, file, offset, count):
"offset must be a non-negative integer (got {!r})".format(
offset))

async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
"""Create, bind and connect one socket."""
async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None,
connected_sockets=None):
"""Create, bind and connect one socket.

If *connected_sockets* is a list, the connected socket is appended to it.
"""
my_exceptions = []
exceptions.append(my_exceptions)
family, type_, proto, _, address = addr_info
Expand Down Expand Up @@ -1051,6 +1055,8 @@ async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
else:
raise OSError(f"no matching local address with {family=} found")
await self.sock_connect(sock, address)
if connected_sockets is not None:
connected_sockets.append(sock)
return sock
except OSError as exc:
my_exceptions.append(exc)
Expand Down Expand Up @@ -1157,18 +1163,28 @@ async def create_connection(
except OSError:
continue
else: # using happy eyeballs
sock = (await staggered.staggered_race(
(
# can't use functools.partial as it keeps a reference
# to exceptions
lambda addrinfo=addrinfo: self._connect_sock(
exceptions, addrinfo, laddr_infos
)
for addrinfo in infos
),
happy_eyeballs_delay,
loop=self,
))[0] # can't use sock, _, _ as it keeks a reference to exceptions
# Sockets connected by the attempts, so that the winner is
# closed if the race is cancelled before it returns.
connected = []
try:
sock = (await staggered.staggered_race(
(
# can't use functools.partial as it keeps a
# reference to exceptions
lambda addrinfo=addrinfo: self._connect_sock(
exceptions, addrinfo, laddr_infos, connected
)
for addrinfo in infos
),
happy_eyeballs_delay,
loop=self,
))[0] # can't use sock, _, _ as it keeks a reference to exceptions
except BaseException:
for connected_sock in connected:
connected_sock.close()
raise
finally:
connected = None

if sock is None:
exceptions = [exc for sub in exceptions for exc in sub]
Expand Down
29 changes: 29 additions & 0 deletions Lib/test/test_asyncio/test_base_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,35 @@ async def mock_race(coro_fns, delay, loop):
with self.assertRaisesRegex(TimeoutError, "create_connection failed"):
self.loop.run_until_complete(coro)

def test_create_connection_happy_eyeballs_cancelled_closes_winner(self):
# A socket that wins the race must not leak if create_connection()
# is cancelled before the race returns it.
sock = mock.Mock()
connected = False

async def getaddrinfo(*args, **kw):
return [(socket.AF_INET, socket.SOCK_STREAM, 0, '', ('192.0.2.1', 80))]

async def connect_sock(exceptions, addr_info, local_addr_infos=None,
connected_sockets=None):
nonlocal connected
connected = True
connected_sockets.append(sock)
return sock

self.loop.getaddrinfo = getaddrinfo
self.loop._connect_sock = connect_sock

task = self.loop.create_task(self.loop.create_connection(
MyProto, 'example.com', 80, happy_eyeballs_delay=0.1))
while not connected:
test_utils.run_once(self.loop)
task.cancel()
with self.assertRaises(asyncio.CancelledError):
self.loop.run_until_complete(task)

sock.close.assert_called_once_with()

def test_create_connection_host_port_sock(self):
coro = self.loop.create_connection(
MyProto, 'example.com', 80, sock=object())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a socket leak in :meth:`asyncio.loop.create_connection` with
*happy_eyeballs_delay*: if the call is cancelled after an attempt connects but
before the race returns, the connected socket is now closed.
Loading