diff --git a/CMakeLists.txt b/CMakeLists.txt index 8994002..866d2e4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ set(CMAKE_POLICY_VERSION_MINIMUM 3.5) cmake_minimum_required(VERSION 3.24) -project(native_streaming VERSION 1.0.21 LANGUAGES CXX) +project(native_streaming VERSION 1.0.22 LANGUAGES CXX) if (NOT CMAKE_MESSAGE_CONTEXT) set(CMAKE_MESSAGE_CONTEXT ${PROJECT_NAME}) diff --git a/include/native_streaming/server.hpp b/include/native_streaming/server.hpp index a14f007..a2dabcd 100644 --- a/include/native_streaming/server.hpp +++ b/include/native_streaming/server.hpp @@ -108,12 +108,6 @@ class Server : public std::enable_shared_from_this /// Tcp connection acceptor binded to IPv6 boost::asio::ip::tcp::acceptor tcpAcceptorV6; - - /// Buffer for reading request headers during accept step - boost::asio::streambuf acceptBuffer; - - /// Object for holding request parameters during accept step - boost::beast::http::request acceptRequest; }; END_NAMESPACE_NATIVE_STREAMING diff --git a/src/server.cpp b/src/server.cpp index e4bd1d9..6483208 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1,7 +1,10 @@ #include #include #include +#include +#include #include +#include BEGIN_NAMESPACE_NATIVE_STREAMING @@ -134,20 +137,40 @@ void Server::onAcceptTcpConnection(boost::asio::ip::tcp::acceptor& tcpAcceptor, NS_LOG_T("server accepting new connection"); + // Re-arm the acceptor immediately: each connection is independent and must not + // wait for this one's upgrade request to arrive (a silent client must not block others). + // Safe because the transport io_context is single-threaded; add a strand here if that changes. + startTcpAccept(tcpAcceptor); + auto wsStream = std::make_shared(std::move(socket)); wsStream->write_buffer_bytes(65536); // 256 MB - one byte bigger than max payload size within native transport protocol used above websocket connection wsStream->read_message_max(0x10000000); + // Per-connection accept state (not shared members): prevents stale bytes from poisoning + // later connections and avoids overlapping reads corrupting a shared buffer. + // The raw read buffer is capped too; the parser's header limit (8 KB) keeps a valid request well below it. + auto buffer = std::make_shared(16 * 1024); + auto parser = std::make_shared>(); + // An upgrade request is a GET without a body, so a request with a body is rejected instead of buffered. + // Without this, the parser's default request body limit (1 MB) would let any client make the server + // hold up to 1 MB per pending connection until the pre-upgrade read times out. + parser->body_limit(0); + + // Bound the pre-upgrade read so a client that connects but never sends a request + // cannot park the socket (and its buffers) indefinitely. + boost::beast::get_lowest_layer(*wsStream).expires_after(std::chrono::seconds(5)); + boost::beast::http::async_read(wsStream->next_layer(), - acceptBuffer, - acceptRequest, - [this, weak_self = weak_from_this(), &tcpAcceptor, wsStream](const boost::system::error_code& ec, size_t /*size*/) + *buffer, + *parser, + [this, weak_self = weak_from_this(), wsStream, buffer, parser](const boost::system::error_code& ec, size_t /*size*/) { if (auto sharedSelf = weak_self.lock()) { - onReadAcceptRequest(ec, wsStream, acceptRequest); - startTcpAccept(tcpAcceptor); + // The websocket layer manages its own timeouts after upgrade. + boost::beast::get_lowest_layer(*wsStream).expires_never(); + onReadAcceptRequest(ec, wsStream, parser->get()); } }); } @@ -158,7 +181,8 @@ void Server::onReadAcceptRequest(const boost::system::error_code& ec, { if (ec) { - NS_LOG_E("Failed to read connect request headers {}", ec.message()); + // Any client can trigger this (malformed, oversized or silent request), so it is logged at debug level only + NS_LOG_D("Failed to read connect request headers {}", ec.message()); return; } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 00cc0bb..cc401e2 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -5,6 +5,7 @@ set(TEST_HEADERS test_base.hpp ) set(TEST_SOURCES test_server.cpp + test_server_accept.cpp test_client.cpp test_tasks.cpp test_connection.cpp diff --git a/test/test_authentication.cpp b/test/test_authentication.cpp index 8a70886..694e411 100644 --- a/test/test_authentication.cpp +++ b/test/test_authentication.cpp @@ -174,9 +174,10 @@ TEST_F(AuthenticationTest, UserContext) onNewServerSessionCallback = [this, &userContextStr](std::shared_ptr session) { serverSession = session; - serverConnectedPromise.set_value(); auto userContext = session->getUserContext(); userContextStr = *std::static_pointer_cast(userContext); + // signal only after the context is stored, the test thread reads it right after the wait + serverConnectedPromise.set_value(); }; auto authCallback = [this](const Authentication& authentication, std::shared_ptr& userContextOut) diff --git a/test/test_messages.cpp b/test/test_messages.cpp index f53e55c..e4c0c96 100644 --- a/test/test_messages.cpp +++ b/test/test_messages.cpp @@ -6,6 +6,7 @@ #include "test_connection.hpp" #include +#include using namespace daq::native_streaming; @@ -499,15 +500,16 @@ TEST_P(WriteTimeoutTestP, WriteTimeout) }; serverSession->setWriteTimedOutHandler(onWriteTimeoutCallback); - size_t actualCompletedWrites = 0; + // Shared ownership: write handlers queued past the deadline may still run after the test body returns + auto actualCompletedWrites = std::make_shared>(0); // Create the write task with a delay and increment actualCompletedWrites when it finishes - auto createWriteTask = [&actualCompletedWrites](PromisePtr writePromise, size_t delayMs, char symbol) + auto createWriteTask = [actualCompletedWrites](PromisePtr writePromise, size_t delayMs, char symbol) { auto data = std::make_shared(symbol); - auto writeHandler = [data, writePromise, delayMs, &actualCompletedWrites]() + auto writeHandler = [data, writePromise, delayMs, actualCompletedWrites]() { - actualCompletedWrites++; + (*actualCompletedWrites)++; writePromise->set_value(); std::this_thread::sleep_for(std::chrono::milliseconds(delayMs)); }; @@ -536,7 +538,7 @@ TEST_P(WriteTimeoutTestP, WriteTimeout) } // Verify that the actual completed writes match the expected number - EXPECT_EQ(actualCompletedWrites, expectedCompletedWrites); + EXPECT_EQ(actualCompletedWrites->load(), expectedCompletedWrites); // If fewer writes were completed than scheduled, verify that the timeout occurred if (expectedCompletedWrites < numBatchedWrites) diff --git a/test/test_server_accept.cpp b/test/test_server_accept.cpp new file mode 100644 index 0000000..5368479 --- /dev/null +++ b/test/test_server_accept.cpp @@ -0,0 +1,231 @@ +#include +#include +#include +#include "test_base.hpp" +#include +#include +#include +#include +#include +#include +#include + +using namespace daq::native_streaming; + +namespace raw_connection +{ + +enum class RawConnectionResult +{ + /// TCP connection to the server could not be established + ConnectFailed, + /// Server sent response bytes + Responded, + /// Server closed or reset the connection without sending a response + DroppedByServer, + /// Server neither responded nor closed the connection - the client's timeout reached instead + TimedOut +}; + +std::ostream& operator<<(std::ostream& os, RawConnectionResult result) +{ + switch (result) + { + case RawConnectionResult::ConnectFailed: + return os << "ConnectFailed"; + case RawConnectionResult::Responded: + return os << "Responded"; + case RawConnectionResult::DroppedByServer: + return os << "DroppedByServer"; + case RawConnectionResult::TimedOut: + return os << "TimedOut"; + } + return os; +} + +/// Pre-upgrade accept phase is exercised with a plain TCP socket so arbitrary bytes can be sent. +/// Async reads are completed by an io_context already running on another thread. +class RawTcpConnection +{ +public: + RawTcpConnection(boost::asio::io_context& ioContext, const boost::asio::ip::tcp::endpoint& endpoint) + : socket(ioContext) + { + socket.connect(endpoint, connectError); + } + + bool isConnected() const + { + return !connectError; + } + + /// Sends the payload and waits for the server's reaction + RawConnectionResult exchange(const std::string& payload, std::chrono::milliseconds ioTimeout) + { + if (connectError) + return RawConnectionResult::ConnectFailed; + + boost::system::error_code writeError; + boost::asio::write(socket, boost::asio::buffer(payload), writeError); + if (writeError) + return RawConnectionResult::DroppedByServer; + + return readFromServer(ioTimeout); + } + + /// Tries read bytes from server response + RawConnectionResult readFromServer(std::chrono::milliseconds ioTimeout) + { + if (connectError) + return RawConnectionResult::ConnectFailed; + + // The buffer is owned by the handler too, so a read still pending after a give-up never writes to freed memory + auto responseData = std::make_shared>(); + auto readPromise = std::make_shared>>(); + auto readFuture = readPromise->get_future(); + socket.async_read_some(boost::asio::buffer(*responseData), + [readPromise, responseData](const boost::system::error_code& ec, size_t size) + { readPromise->set_value({ec, size}); }); + + if (readFuture.wait_for(ioTimeout) != std::future_status::ready) + { + // close on the io thread to cancel the pending read, then give its handler a bounded time to complete; + // never wait unbounded - a cancellation that does not complete must fail the test, not hang it + boost::asio::post(socket.get_executor(), + [this]() + { + boost::system::error_code ignored; + socket.close(ignored); + }); + readFuture.wait_for(ioTimeout); + return RawConnectionResult::TimedOut; + } + + const auto [readError, bytesRead] = readFuture.get(); + if (readError || bytesRead == 0) + return RawConnectionResult::DroppedByServer; + + const std::string response(responseData->data(), bytesRead); + firstResponseLine = response.substr(0, response.find("\r\n")); + return RawConnectionResult::Responded; + } + + std::string firstResponseLine; + +private: + boost::asio::ip::tcp::socket socket; + boost::system::error_code connectError; +}; + +} // namespace raw_connection + +using namespace raw_connection; + +class ServerAcceptTest : public TestBase +{ +public: + /// Drops created session + const OnNewSessionCallback onUnusedSessionCallback = [](std::shared_ptr) {}; + + /// Everyone is authenticated by default + const OnAuthenticateCallback onAuthenticateCallback = [](const Authentication& authentication, std::shared_ptr& userContextOut) + { return true; }; + + void SetUp() override + { + server = std::make_shared(onUnusedSessionCallback, onAuthenticateCallback, ioContextPtrServer, logCallback); + ASSERT_EQ(server->start(CONNECTION_PORT), boost::system::error_code()); + } + + void TearDown() override + { + server->stop(); + } + + std::string upgradeToWebsocketRequest() const + { + return "GET / HTTP/1.1\r\n" + "Host: " + CONNECTION_HOST + "\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + "Sec-WebSocket-Version: 13\r\n" + "\r\n"; + } + + /// Bytes which are not a valid HTTP request; the parser consumes none of them and fails + std::string malformedRequest() const + { + using namespace std::string_literals; + return "\x00\x01\x02not-http garbage\r\n\r\n"s; + } + + boost::asio::ip::tcp::endpoint serverEndpoint() const + { + return {boost::asio::ip::make_address(CONNECTION_HOST), CONNECTION_PORT}; + } + + const std::chrono::milliseconds TEST_TIMEOUT = std::chrono::milliseconds(2000); + + /// Status line of the server's response to a successful websocket upgrade request + const std::string UPGRADE_RESPONSE_STATUS_LINE = "HTTP/1.1 101 Switching Protocols"; + + std::shared_ptr server; +}; + +// A client sending a malformed non-HTTP request must not affect the upgrade of the connections following it +TEST_F(ServerAcceptTest, MalformedRequestDoesNotPoisonLaterConnections) +{ + { + RawTcpConnection valid(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(valid.isConnected()); + ASSERT_EQ(valid.exchange(upgradeToWebsocketRequest(), TEST_TIMEOUT), RawConnectionResult::Responded); + ASSERT_EQ(valid.firstResponseLine, UPGRADE_RESPONSE_STATUS_LINE); + } + + { + RawTcpConnection poison(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(poison.isConnected()); + ASSERT_EQ(poison.exchange(malformedRequest(), TEST_TIMEOUT), RawConnectionResult::DroppedByServer); + } + + { + RawTcpConnection retest(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(retest.isConnected()); + ASSERT_EQ(retest.exchange(upgradeToWebsocketRequest(), TEST_TIMEOUT), RawConnectionResult::Responded); + ASSERT_EQ(retest.firstResponseLine, UPGRADE_RESPONSE_STATUS_LINE); + } +} + +// A request announcing a body must be dropped right after its headers, without the server waiting to buffer the body +TEST_F(ServerAcceptTest, RequestWithBodyIsDropped) +{ + std::string request = upgradeToWebsocketRequest(); + // Announce a 1 MB body after the headers, but send none of it + request.insert(request.size() - 2, "Content-Length: 1048576\r\n"); + + RawTcpConnection withBody(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(withBody.isConnected()); + // Well below the 5 s pre-upgrade read timeout: only an immediate rejection passes + ASSERT_EQ(withBody.exchange(request, TEST_TIMEOUT), RawConnectionResult::DroppedByServer); +} + +// A client connecting without sending a request must not block the upgrade of other connections +TEST_F(ServerAcceptTest, SilentClientDoesNotBlockOtherConnections) +{ + RawTcpConnection silent(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(silent.isConnected()); + + RawTcpConnection other(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(other.isConnected()); + ASSERT_EQ(other.exchange(upgradeToWebsocketRequest(), TEST_TIMEOUT), RawConnectionResult::Responded); + ASSERT_EQ(other.firstResponseLine, UPGRADE_RESPONSE_STATUS_LINE); +} + +// A client connecting without sending a request must be disconnected by the server eventually +TEST_F(ServerAcceptTest, SilentClientIsDisconnected) +{ + RawTcpConnection silent(*ioContextPtrClient, serverEndpoint()); + ASSERT_TRUE(silent.isConnected()); + ASSERT_EQ(silent.readFromServer(std::chrono::seconds(10)), RawConnectionResult::DroppedByServer); +}