From 397a169e70e01550b3d23f552062d14ca4c85980 Mon Sep 17 00:00:00 2001 From: Roxanne Rubin Date: Tue, 21 Oct 2025 19:54:27 +0000 Subject: [PATCH] Fix file descriptor leak on connection failure When ::connect() fails, the socket file descriptor was not closed before throwing an exception, leading to a file descriptor leak. This fix ensures the socket is properly closed on connection failure. The issue occurs in the Connection::with() factory method where a socket is created with ::socket() but not cleaned up if the subsequent ::connect() call fails. --- src/TCP/connection.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/TCP/connection.cpp b/src/TCP/connection.cpp index 34bcb2a..8d6fbd7 100644 --- a/src/TCP/connection.cpp +++ b/src/TCP/connection.cpp @@ -204,8 +204,10 @@ Connection Connection::with(std::string addr, int port) { server.sin_port = ::htons(port); server.sin_addr = {inet_addr(addr.c_str())}; - if (::connect(sock, reinterpret_cast(&server), sizeof(server)) < 0) + if (::connect(sock, reinterpret_cast(&server), sizeof(server)) < 0) { + ::close(sock); throw std::runtime_error("Cannot connect, errno = " + std::to_string(errno)); + } return Connection(sock); }