Skip to content
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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})
Expand Down
6 changes: 0 additions & 6 deletions include/native_streaming/server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,6 @@ class Server : public std::enable_shared_from_this<Server>

/// 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<boost::beast::http::string_body> acceptRequest;
};

END_NAMESPACE_NATIVE_STREAMING
36 changes: 30 additions & 6 deletions src/server.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#include <native_streaming/server.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/http/parser.hpp>
#include <native_streaming/utils/boost_compatibility_utils.hpp>
#include <chrono>

BEGIN_NAMESPACE_NATIVE_STREAMING

Expand Down Expand Up @@ -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<WebsocketStream>(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<boost::beast::flat_buffer>(16 * 1024);
auto parser = std::make_shared<boost::beast::http::request_parser<boost::beast::http::string_body>>();
// 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());
}
});
}
Expand All @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion test/test_authentication.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,10 @@ TEST_F(AuthenticationTest, UserContext)
onNewServerSessionCallback = [this, &userContextStr](std::shared_ptr<Session> session)
{
serverSession = session;
serverConnectedPromise.set_value();
auto userContext = session->getUserContext();
userContextStr = *std::static_pointer_cast<std::string>(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<void>& userContextOut)
Expand Down
12 changes: 7 additions & 5 deletions test/test_messages.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "test_connection.hpp"

#include <future>
#include <atomic>

using namespace daq::native_streaming;

Expand Down Expand Up @@ -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<std::atomic<size_t>>(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<char>(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));
};
Expand Down Expand Up @@ -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)
Expand Down
231 changes: 231 additions & 0 deletions test/test_server_accept.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
#include <native_streaming/server.hpp>
#include <gtest/gtest.h>
#include <native_streaming/logging.hpp>
#include "test_base.hpp"
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/write.hpp>
#include <array>
#include <future>
#include <ostream>
#include <string>

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<std::array<char, 4096>>();
auto readPromise = std::make_shared<std::promise<std::pair<boost::system::error_code, size_t>>>();
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<Session>) {};

/// Everyone is authenticated by default
const OnAuthenticateCallback onAuthenticateCallback = [](const Authentication& authentication, std::shared_ptr<void>& userContextOut)
{ return true; };

void SetUp() override
{
server = std::make_shared<Server>(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> 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);
}
Loading