Skip to content

Commit 6c695bf

Browse files
scrievevstinner
andauthored
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>
1 parent 926b0bf commit 6c695bf

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎Lib/socket.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,11 @@ 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:
578+
close(nfd)
579+
raise
576580

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

‎Lib/test/test_socket.py‎

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

3198+
def testFromFdError(self):
3199+
# Make sure that the fromfd() duplicated socket is closed on error.
3200+
fd = self.cli_conn.fileno()
3201+
fd_count_before = os_helper.fd_count()
3202+
3203+
with self.assertRaises(TypeError):
3204+
socket.fromfd(fd, "not-a-valid-family", socket.SOCK_STREAM)
3205+
with self.assertRaises(TypeError):
3206+
socket.fromfd(fd, socket.AF_INET, "not-a-valid-type")
3207+
with self.assertRaises(OverflowError):
3208+
socket.fromfd(fd, socket.AF_INET, 1 << 100)
3209+
3210+
self.assertEqual(os_helper.fd_count(), fd_count_before)
3211+
3212+
def _testFromFdError(self):
3213+
pass
3214+
31983215
def testDup(self):
31993216
# Testing dup()
32003217
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)