Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a9fa266

Browse files
committed
Issue #21119: asyncio: Make sure that socketpair() close sockets on error
Close the listening socket if sock.bind() raises an exception.
1 parent 223a624 commit a9fa266

2 files changed

Lines changed: 26 additions & 15 deletions

File tree

Lib/asyncio/windows_utils.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -51,23 +51,25 @@ def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
5151
# We create a connected TCP socket. Note the trick with setblocking(0)
5252
# that prevents us from having to create a thread.
5353
lsock = socket.socket(family, type, proto)
54-
lsock.bind((host, 0))
55-
lsock.listen(1)
56-
# On IPv6, ignore flow_info and scope_id
57-
addr, port = lsock.getsockname()[:2]
58-
csock = socket.socket(family, type, proto)
59-
csock.setblocking(False)
6054
try:
61-
csock.connect((addr, port))
62-
except (BlockingIOError, InterruptedError):
63-
pass
64-
except Exception:
55+
lsock.bind((host, 0))
56+
lsock.listen(1)
57+
# On IPv6, ignore flow_info and scope_id
58+
addr, port = lsock.getsockname()[:2]
59+
csock = socket.socket(family, type, proto)
60+
try:
61+
csock.setblocking(False)
62+
try:
63+
csock.connect((addr, port))
64+
except (BlockingIOError, InterruptedError):
65+
pass
66+
ssock, _ = lsock.accept()
67+
csock.setblocking(True)
68+
except:
69+
csock.close()
70+
raise
71+
finally:
6572
lsock.close()
66-
csock.close()
67-
raise
68-
ssock, _ = lsock.accept()
69-
csock.setblocking(True)
70-
lsock.close()
7173
return (ssock, csock)
7274

7375

Lib/test/test_asyncio/test_windows_utils.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ def test_winsocketpair_invalid_args(self):
5151
self.assertRaises(ValueError,
5252
windows_utils.socketpair, proto=1)
5353

54+
@mock.patch('asyncio.windows_utils.socket')
55+
def test_winsocketpair_close(self, m_socket):
56+
m_socket.AF_INET = socket.AF_INET
57+
m_socket.SOCK_STREAM = socket.SOCK_STREAM
58+
sock = mock.Mock()
59+
m_socket.socket.return_value = sock
60+
sock.bind.side_effect = OSError
61+
self.assertRaises(OSError, windows_utils.socketpair)
62+
self.assertTrue(sock.close.called)
5463

5564

5665
class PipeTests(unittest.TestCase):

0 commit comments

Comments
 (0)