Skip to content

Commit 06cb5dc

Browse files
committed
gh-160561: Close the duplicated descriptor when fromfd() is rejected
1 parent 457ba33 commit 06cb5dc

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎Lib/socket.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,13 @@ def fromfd(fd, family, type, proto=0):
572572
descriptor. The remaining arguments are the same as for socket().
573573
"""
574574
nfd = dup(fd)
575-
return socket(family, type, proto, nfd)
575+
try:
576+
return socket(family, type, proto, nfd)
577+
except BaseException:
578+
# socket() rejected the arguments; the dup()'d descriptor would
579+
# otherwise leak, since nothing holds a reference to it.
580+
close(nfd)
581+
raise
576582

577583
if hasattr(_socket.socket, "sendmsg"):
578584
def send_fds(sock, buffers, fds, flags=0, address=None):

‎Lib/test/test_socket.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3195,6 +3195,21 @@ def testFromFd(self):
31953195
def _testFromFd(self):
31963196
self.serv_conn.send(MSG)
31973197

3198+
def testFromFdInvalidArgsDoesNotLeak(self):
3199+
# fromfd() dup()s the descriptor before socket() validates its
3200+
# arguments; a rejected call must not leave the duplicate open.
3201+
fddir = '/proc/self/fd'
3202+
if not os.path.isdir(fddir):
3203+
self.skipTest('test needs /proc/self/fd')
3204+
fd = self.cli_conn.fileno()
3205+
before = len(os.listdir(fddir))
3206+
with self.assertRaises(OverflowError):
3207+
socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM, 1 << 100)
3208+
self.assertEqual(len(os.listdir(fddir)), before)
3209+
3210+
def _testFromFdInvalidArgsDoesNotLeak(self):
3211+
pass
3212+
31983213
def testDup(self):
31993214
# Testing dup()
32003215
sock = self.cli_conn.dup()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a descriptor leak in :func:`socket.fromfd` when the socket constructor rejects its arguments. The duplicated descriptor was never closed.

0 commit comments

Comments
 (0)