Skip to content

Commit b6aeaf9

Browse files
committed
gh-162059: Close the winning socket when happy eyeballs is cancelled
When create_connection() runs with happy_eyeballs_delay and is cancelled after an attempt connects but before staggered_race() returns, the race re-raises CancelledError and drops the connected socket. Record the sockets the attempts connect and close them if the race raises.
1 parent 369d8bc commit b6aeaf9

3 files changed

Lines changed: 57 additions & 12 deletions

File tree

‎Lib/asyncio/base_events.py‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,18 +1157,33 @@ async def create_connection(
11571157
except OSError:
11581158
continue
11591159
else: # using happy eyeballs
1160-
sock = (await staggered.staggered_race(
1161-
(
1162-
# can't use functools.partial as it keeps a reference
1163-
# to exceptions
1164-
lambda addrinfo=addrinfo: self._connect_sock(
1165-
exceptions, addrinfo, laddr_infos
1166-
)
1167-
for addrinfo in infos
1168-
),
1169-
happy_eyeballs_delay,
1170-
loop=self,
1171-
))[0] # can't use sock, _, _ as it keeks a reference to exceptions
1160+
# Sockets connected by the attempts, so that the winner is
1161+
# closed if the race is cancelled before it returns.
1162+
connected = []
1163+
1164+
async def connect_sock(addrinfo):
1165+
sock = await self._connect_sock(
1166+
exceptions, addrinfo, laddr_infos)
1167+
connected.append(sock)
1168+
return sock
1169+
1170+
try:
1171+
sock = (await staggered.staggered_race(
1172+
(
1173+
# can't use functools.partial as it keeps a
1174+
# reference to exceptions
1175+
lambda addrinfo=addrinfo: connect_sock(addrinfo)
1176+
for addrinfo in infos
1177+
),
1178+
happy_eyeballs_delay,
1179+
loop=self,
1180+
))[0] # can't use sock, _, _ as it keeks a reference to exceptions
1181+
except BaseException:
1182+
for connected_sock in connected:
1183+
connected_sock.close()
1184+
raise
1185+
finally:
1186+
connected = None
11721187

11731188
if sock is None:
11741189
exceptions = [exc for sub in exceptions for exc in sub]

‎Lib/test/test_asyncio/test_base_events.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,33 @@ async def mock_race(coro_fns, delay, loop):
14121412
with self.assertRaisesRegex(TimeoutError, "create_connection failed"):
14131413
self.loop.run_until_complete(coro)
14141414

1415+
def test_create_connection_happy_eyeballs_cancelled_closes_winner(self):
1416+
# A socket that wins the race must not leak if create_connection()
1417+
# is cancelled before the race returns it.
1418+
sock = mock.Mock()
1419+
connected = False
1420+
1421+
async def getaddrinfo(*args, **kw):
1422+
return [(socket.AF_INET, socket.SOCK_STREAM, 0, '', ('192.0.2.1', 80))]
1423+
1424+
async def connect_sock(exceptions, addr_info, local_addr_infos=None):
1425+
nonlocal connected
1426+
connected = True
1427+
return sock
1428+
1429+
self.loop.getaddrinfo = getaddrinfo
1430+
self.loop._connect_sock = connect_sock
1431+
1432+
task = self.loop.create_task(self.loop.create_connection(
1433+
MyProto, 'example.com', 80, happy_eyeballs_delay=0.1))
1434+
while not connected:
1435+
test_utils.run_once(self.loop)
1436+
task.cancel()
1437+
with self.assertRaises(asyncio.CancelledError):
1438+
self.loop.run_until_complete(task)
1439+
1440+
sock.close.assert_called_once_with()
1441+
14151442
def test_create_connection_host_port_sock(self):
14161443
coro = self.loop.create_connection(
14171444
MyProto, 'example.com', 80, sock=object())
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a socket leak in :meth:`asyncio.loop.create_connection` with
2+
*happy_eyeballs_delay*: if the call is cancelled after an attempt connects but
3+
before the race returns, the connected socket is now closed.

0 commit comments

Comments
 (0)