Skip to content

Commit 99263a1

Browse files
scrievevstinner
authored andcommitted
gh-160561: Close the duplicated descriptor when socket.fromfd() fails (GH-160579)
(cherry picked from commit 6c695bf) Co-authored-by: scrieve <86650480+scrieve@users.noreply.github.com> 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 48b1e60 commit 99263a1

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
@@ -552,7 +552,11 @@ def fromfd(fd, family, type, proto=0):
552552
descriptor. The remaining arguments are the same as for socket().
553553
"""
554554
nfd = dup(fd)
555-
return socket(family, type, proto, nfd)
555+
try:
556+
return socket(family, type, proto, nfd)
557+
except:
558+
close(nfd)
559+
raise
556560

557561
if hasattr(_socket.socket, "sendmsg"):
558562
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
@@ -3090,6 +3090,23 @@ def testFromFd(self):
30903090
def _testFromFd(self):
30913091
self.serv_conn.send(MSG)
30923092

3093+
def testFromFdError(self):
3094+
# Make sure that the fromfd() duplicated socket is closed on error.
3095+
fd = self.cli_conn.fileno()
3096+
fd_count_before = os_helper.fd_count()
3097+
3098+
with self.assertRaises(TypeError):
3099+
socket.fromfd(fd, "not-a-valid-family", socket.SOCK_STREAM)
3100+
with self.assertRaises(TypeError):
3101+
socket.fromfd(fd, socket.AF_INET, "not-a-valid-type")
3102+
with self.assertRaises(OverflowError):
3103+
socket.fromfd(fd, socket.AF_INET, 1 << 100)
3104+
3105+
self.assertEqual(os_helper.fd_count(), fd_count_before)
3106+
3107+
def _testFromFdError(self):
3108+
pass
3109+
30933110
def testDup(self):
30943111
# Testing dup()
30953112
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)