// Copyright (c) 2016-2024 The Hush developers // Distributed under the GPLv3 software license, see the accompanying // file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html #include #include #include #include #include "net.h" #include "util/sock.h" // Regression test for the wolfSSL CloseSocket macro (see net.h): closing a CNode's socket must invalidate // hSocket, so neither a repeated CloseSocketDisconnect nor ~CNode can close that fd number again once another // owner (the wallet's BDB files, a block file, an RPC socket) has been handed it. TEST(NetCloseSocket, ClosedNodeNeverClosesAReusedFdNumber) { int pair[2]; ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, pair)); const int number = pair[0]; CNode* node = new CNode(number, CAddress(), "", true); // inbound: sends no version message node->CloseSocketDisconnect(); EXPECT_EQ(INVALID_SOCKET, node->hSocket) << "CloseSocketDisconnect left the closed fd number in hSocket"; EXPECT_EQ(-1, fcntl(number, F_GETFD)) << "the node's socket wasn't closed"; // Another owner gets the freed number, as the kernel's lowest-free-fd rule does in a busy node. const int other = open("/dev/null", O_RDONLY); ASSERT_GE(other, 0); ASSERT_EQ(number, dup2(other, number)); node->CloseSocketDisconnect(); // e.g. a send error after the disconnect was already handled delete node; // ~CNode EXPECT_NE(-1, fcntl(number, F_GETFD)) << "a closed CNode closed the fd number's new owner"; close(number); close(other); close(pair[1]); } // util/sock.cpp's CloseSocket is the one that must be called: it closes once and invalidates. TEST(NetCloseSocket, CloseSocketInvalidates) { int pair[2]; ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, pair)); SOCKET s = pair[0]; EXPECT_TRUE(CloseSocket(s)); EXPECT_EQ(INVALID_SOCKET, s); EXPECT_FALSE(CloseSocket(s)) << "a second close of an invalidated handle must be a no-op"; close(pair[1]); }