From 0f4f048fa5ff06438a4624bc1dc02aa458a79748 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Charles-Fran=C3=A7ois=20Natali?= Date: Mon, 13 Oct 2014 19:19:26 +0100 Subject: [PATCH] Issue #22435: Fix a file descriptor leak when SocketServer bind fails. --- Lib/socketserver.py | 8 ++++++-- Lib/test/test_socketserver.py | 10 ++++++++++ Misc/NEWS | 2 ++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Lib/socketserver.py b/Lib/socketserver.py index 2f395fac242..73399115b6a 100644 --- a/Lib/socketserver.py +++ b/Lib/socketserver.py @@ -426,8 +426,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 0617b30a69e..0276f993f97 100644 --- a/Lib/test/test_socketserver.py +++ b/Lib/test/test_socketserver.py @@ -302,6 +302,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 ab5a4cb3789..e5030cd5d81 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -27,6 +27,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.