gh-160561: Close the duplicated descriptor when socket.fromfd() fails (#160579)

Co-authored-by: wlkr73 <86650480+wlkr73@users.noreply.github.com>
Co-authored-by: lumenyr <86650480+lumenyr@users.noreply.github.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
This commit is contained in:
authored and GitHub committed 2026-10-27 22:56:42 +00:00
1 parent 926b0bf311
commit 6c695bfad4
3 files changed
+23 -1

No files matched your search

+5 -1
View File
@@ -572,7 +572,11 @@ def fromfd(fd, family, type, proto=0):
descriptor. The remaining arguments are the same as for socket().
"""
nfd = dup(fd)
return socket(family, type, proto, nfd)
try:
return socket(family, type, proto, nfd)
except:
close(nfd)
raise
if hasattr(_socket.socket, "sendmsg"):
def send_fds(sock, buffers, fds, flags=0, address=None):
+17
View File
@@ -3195,6 +3195,23 @@ class BasicTCPTest(SocketConnectedTest):
def _testFromFd(self):
self.serv_conn.send(MSG)
def testFromFdError(self):
# Make sure that the fromfd() duplicated socket is closed on error.
fd = self.cli_conn.fileno()
fd_count_before = os_helper.fd_count()
with self.assertRaises(TypeError):
socket.fromfd(fd, "not-a-valid-family", socket.SOCK_STREAM)
with self.assertRaises(TypeError):
socket.fromfd(fd, socket.AF_INET, "not-a-valid-type")
with self.assertRaises(OverflowError):
socket.fromfd(fd, socket.AF_INET, 1 << 100)
self.assertEqual(os_helper.fd_count(), fd_count_before)
def _testFromFdError(self):
pass
def testDup(self):
# Testing dup()
sock = self.cli_conn.dup()
@@ -0,0 +1 @@
Fix a descriptor leak in :func:`socket.fromfd` when the socket constructor rejects its arguments. The duplicated descriptor was never closed.