diff --git a/Lib/socketserver.py b/Lib/socketserver.py index 3d58590d27b..f1b0e4a6203 100644 --- a/Lib/socketserver.py +++ b/Lib/socketserver.py @@ -439,8 +439,12 @@ class TCPServer(BaseServer): self.socket = socket.socket(self.address_family, self.socket_type) if bind_and_activate: - self.server_bind() - self.server_activate() + try: + self.server_bind() + self.server_activate() + except: + self.server_close() + raise def server_bind(self): """Called by constructor to bind the socket. diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py index 8e0fde497ca..f5d8d524ac9 100644 --- a/Lib/test/test_socketserver.py +++ b/Lib/test/test_socketserver.py @@ -270,6 +270,16 @@ class SocketServerTest(unittest.TestCase): t.join() s.server_close() + def test_tcpserver_bind_leak(self): + # Issue #22435: the server socket wouldn't be closed if bind()/listen() + # failed. + # Create many servers for which bind() will fail, to see if this result + # in FD exhaustion. + for i in range(1024): + with self.assertRaises(OverflowError): + socketserver.TCPServer((HOST, -1), + socketserver.StreamRequestHandler) + def test_main(): if imp.lock_held(): diff --git a/Misc/NEWS b/Misc/NEWS index 1453637d01e..2408aeae04c 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -174,6 +174,8 @@ Core and Builtins Library ------- +- Issue #22435: Fix a file descriptor leak when SocketServer bind fails. + - Issue #13096: Fixed segfault in CTypes POINTER handling of large values.