Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.24 LANGUAGES CXX)
project(native_streaming VERSION 1.0.25 LANGUAGES CXX)

if (NOT CMAKE_MESSAGE_CONTEXT)
set(CMAKE_MESSAGE_CONTEXT ${PROJECT_NAME})
Expand Down
17 changes: 17 additions & 0 deletions changelog
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@
## v1.0.15
- Fix issue with retrieving connection endpoint name on server app resuming in debug mode

## v1.0.16
- Fix MSVC 2017 warning

## v1.0.17
- Provide connection endpoint address and port separately

## v1.0.18
- Use unsigned short as type for endpoint port number

## v1.0.19
- Fix MSVC 32 bit debug configuration runtime crash
- Increase read message size limit to 256 MB to align it with the native transport protocol

## v1.0.20
- Bump boost version to 1.90.0

Expand All @@ -72,3 +85,7 @@
- Add a Client constructor taking a ClientTlsConfig, with an optional callback for TLS handshake failures
- Make the Session constructor take the transport-neutral IWsStream instead of WebsocketStream
- Return address_in_use when the server is asked to listen on a port it already listens on

## v1.0.25
- Reply with HTTP 401 when server rejects authentication
- Pass server's handshake reply to the client's handshake failure callback
27 changes: 20 additions & 7 deletions include/native_streaming/client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ struct ClientTlsConfig

#endif

/// @brief HTTP response sent by the server in reply to the websocket upgrade request
using HandshakeResponse = boost::beast::websocket::response_type;

/// @brief callback called when the websocket handshake fails
/// @param ec error_code object indicates handshake failure
/// @param response the server's reply when it declined the upgrade (ec == websocket::error::upgrade_declined),
/// e.g. 401 Unauthorized on rejected authentication; nullptr otherwise
using OnHandshakeFailCallback =
std::function<void(const boost::system::error_code& ec, const std::shared_ptr<const HandshakeResponse>& response)>;

/// @brief Connects to specified server address, creates and returns new Session via callback when connection established
class Client : public std::enable_shared_from_this<Client>
{
Expand All @@ -66,7 +76,7 @@ class Client : public std::enable_shared_from_this<Client>
OnNewSessionCallback onNewSessionCallback,
OnCompleteCallback onResolveFailCallback,
OnCompleteCallback onConnectFailCallback,
OnCompleteCallback onHandshakeFailCallback,
OnHandshakeFailCallback onWsHandshakeFailCallback,
std::shared_ptr<boost::asio::io_context> ioContextPtr,
LogCallback logCallback);

Expand All @@ -77,7 +87,7 @@ class Client : public std::enable_shared_from_this<Client>
/// @param onTlsHandshakeFailCallback callback to be called if a handshake fails with an error
/// raised by the TLS layer, which means the server was reached but the two could not agree on
/// trust - unlike the other failures, retrying such a connection with the same secrets is
/// pointless. If not set, such failures are reported through onHandshakeFailCallback
/// pointless. If not set, such failures are reported through onWsHandshakeFailCallback
/// @throw std::invalid_argument tlsConfig is inconsistent, e.g. it names a client certificate
/// without a key
/// @throw boost::system::system_error a certificate or key file named by tlsConfig is missing or
Expand All @@ -89,7 +99,7 @@ class Client : public std::enable_shared_from_this<Client>
OnNewSessionCallback onNewSessionCallback,
OnCompleteCallback onResolveFailCallback,
OnCompleteCallback onConnectFailCallback,
OnCompleteCallback onHandshakeFailCallback,
OnHandshakeFailCallback onWsHandshakeFailCallback,
std::shared_ptr<boost::asio::io_context> ioContextPtr,
LogCallback logCallback,
const ClientTlsConfig& tlsConfig,
Expand Down Expand Up @@ -152,13 +162,16 @@ class Client : public std::enable_shared_from_this<Client>

/// @brief reports a failed handshake to the caller
/// @param ec error_code object describing the failure
void reportHandshakeFailure(const boost::system::error_code& ec);
void reportHandshakeFailure(const boost::system::error_code& ec, const std::shared_ptr<const HandshakeResponse>& response);

/// @brief callback called when web-socket handshake finished for new connection
/// @param ec error_code object indicates handshake failure
/// @param wsStream websocket stream object associated with connection
/// @param response the server's reply to the upgrade request
template <typename Stream>
void onUpgradeConnection(const boost::system::error_code& ec, std::shared_ptr<Stream> wsStream);
void onUpgradeConnection(const boost::system::error_code& ec,
std::shared_ptr<Stream> wsStream,
const std::shared_ptr<const HandshakeResponse>& response);

/// @brief creates a connection Session using provided web-socket stream object
/// @param wsStream web-socket stream object which provides as a R/W interface for connection
Expand Down Expand Up @@ -221,12 +234,12 @@ class Client : public std::enable_shared_from_this<Client>
OnCompleteCallback onConnectFailCallback;

/// @brief callback to be called if handshake with a remote server is failed
OnCompleteCallback onHandshakeFailCallback;
OnHandshakeFailCallback onWsHandshakeFailCallback;

#if NATIVE_STREAMING_ENABLE_TLS

/// @brief callback to be called if a handshake fails with an error raised by the TLS layer.
/// May be unset, in which case such failures are reported through onHandshakeFailCallback
/// May be unset, in which case such failures are reported through onWsHandshakeFailCallback
OnCompleteCallback onTlsHandshakeFailCallback;

#endif
Expand Down
7 changes: 7 additions & 0 deletions include/native_streaming/server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,13 @@ class Server : public std::enable_shared_from_this<Server>
template <typename Stream>
void startReadAcceptRequest(std::shared_ptr<AcceptOp<Stream>> acceptOp);

/// @brief replies to a rejected upgrade request with HTTP 401 Unauthorized and closes the connection,
/// so the client can tell rejected authentication apart from other connection failures
/// @param wsStream web-socket stream object of the rejected connection
/// @param httpVersion HTTP version of the rejected upgrade request
template <typename Stream>
void rejectUnauthorized(const std::shared_ptr<Stream>& wsStream, unsigned httpVersion);

/// @brief creates a connection Session using provided web-socket stream object
/// @param wsStream web-socket stream object which provides as a R/W interface for connection
/// @param user context, usualy a pointer to the authenticated user object
Expand Down
2 changes: 2 additions & 0 deletions include/native_streaming/utils/boost_compatibility_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ namespace boost_compatibility_utils
using WriteCallback = std::function<void(boost::beast::error_code ec, std::size_t written)>;

void async_handshake(WebsocketStream& stream,
boost::beast::websocket::response_type& response,
const std::string& host,
const std::string& target,
const BoostHandler& handler);

#if NATIVE_STREAMING_ENABLE_TLS

void async_handshake(TlsWebsocketStream& stream,
boost::beast::websocket::response_type& response,
const std::string& host,
const std::string& target,
const BoostHandler& handler);
Expand Down
43 changes: 30 additions & 13 deletions src/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Client::Client(const std::string& host,
OnNewSessionCallback onNewSessionCallback,
OnCompleteCallback onResolveFailCallback,
OnCompleteCallback onConnectFailCallback,
OnCompleteCallback onHandshakeFailCallback,
OnHandshakeFailCallback onWsHandshakeFailCallback,
std::shared_ptr<boost::asio::io_context> ioContextPtr,
LogCallback logCallback)
: ioContextPtr(ioContextPtr)
Expand All @@ -35,7 +35,7 @@ Client::Client(const std::string& host,
, onNewSessionCallback(onNewSessionCallback)
, onResolveFailCallback(onResolveFailCallback)
, onConnectFailCallback(onConnectFailCallback)
, onHandshakeFailCallback(onHandshakeFailCallback)
, onWsHandshakeFailCallback(onWsHandshakeFailCallback)
{
}

Expand All @@ -48,7 +48,7 @@ Client::Client(const std::string& host,
OnNewSessionCallback onNewSessionCallback,
OnCompleteCallback onResolveFailCallback,
OnCompleteCallback onConnectFailCallback,
OnCompleteCallback onHandshakeFailCallback,
OnHandshakeFailCallback onWsHandshakeFailCallback,
std::shared_ptr<boost::asio::io_context> ioContextPtr,
LogCallback logCallback,
const ClientTlsConfig& tlsConfig,
Expand All @@ -60,7 +60,7 @@ Client::Client(const std::string& host,
onNewSessionCallback,
onResolveFailCallback,
onConnectFailCallback,
onHandshakeFailCallback,
onWsHandshakeFailCallback,
ioContextPtr,
logCallback)
{
Expand Down Expand Up @@ -262,7 +262,7 @@ void Client::onTlsHandshake(const boost::system::error_code& ec, std::shared_ptr
// the server answered but is not trusted: check its certificate against the configured
// certificate authority, and the client certificate if the server requires one
NS_LOG_E("TLS handshake operation failed {}", ec.message());
reportHandshakeFailure(ec);
reportHandshakeFailure(ec, nullptr);
}
return;
}
Expand All @@ -287,17 +287,22 @@ void Client::startTlsHandshake(std::shared_ptr<Stream> wsStream)
template <typename Stream>
void Client::startWebsocketHandshake(std::shared_ptr<Stream> wsStream)
{
// Kept so a declined upgrade can be reported together with the server's reply (e.g. 401 Unauthorized).
// The server closes the connection right after its reply. This client sends nothing after the upgrade
// request (RFC 6455), so the close arrives after the reply as an orderly FIN and the reply is read in full.
auto response = std::make_shared<HandshakeResponse>();

auto onHandshakeDone =
[this, weak_self = weak_from_this(), wsStream](const boost::system::error_code& ec)
[this, weak_self = weak_from_this(), wsStream, response](const boost::system::error_code& ec)
{
if (auto shared_self = weak_self.lock())
onUpgradeConnection(ec, wsStream);
onUpgradeConnection(ec, wsStream, response);
};

boost_compatibility_utils::async_handshake(*wsStream, host, path, onHandshakeDone);
boost_compatibility_utils::async_handshake(*wsStream, *response, host, path, onHandshakeDone);
}

void Client::reportHandshakeFailure(const boost::system::error_code& ec)
void Client::reportHandshakeFailure(const boost::system::error_code& ec, const std::shared_ptr<const HandshakeResponse>& response)
{
#if NATIVE_STREAMING_ENABLE_TLS
// routing by the category of the error rather than by the step that raised it: under TLS 1.3 the
Expand All @@ -310,25 +315,37 @@ void Client::reportHandshakeFailure(const boost::system::error_code& ec)
}
#endif

onHandshakeFailCallback(ec);
onWsHandshakeFailCallback(ec, response);
}

template <typename Stream>
void Client::onUpgradeConnection(const boost::system::error_code& ec, std::shared_ptr<Stream> wsStream)
void Client::onUpgradeConnection(const boost::system::error_code& ec,
std::shared_ptr<Stream> wsStream,
const std::shared_ptr<const HandshakeResponse>& response)
{
connectionTimeoutTimer.cancel();

if (ec)
{
if (ec.value() == boost::asio::error::operation_aborted)
if (ec == boost::asio::error::operation_aborted)
{
NS_LOG_T("Handshake operation cancelled: {}", ec.message());
onConnectFailCallback(ec);
}
else if (ec == boost::beast::websocket::error::upgrade_declined)
{
// The server replied with a status other than 101 Switching Protocols (e.g. 401 Unauthorized)
NS_LOG_E("Handshake operation failed {}: server replied {} {}", ec.message(), response->result_int(), std::string(response->reason()));
reportHandshakeFailure(ec, response);
}
else
{
// No reply with a status to act on: either the connection failed before a reply was read
// (closed/reset, not an HTTP service, or an older server that closes the connection on rejected
// authentication without replying), so the response is still default-constructed (200 OK),
// or the server replied 101 but the reply failed Beast's websocket header checks
NS_LOG_E("Handshake operation failed {}", ec.message());
reportHandshakeFailure(ec);
reportHandshakeFailure(ec, nullptr);
}
return;
}
Expand Down
40 changes: 39 additions & 1 deletion src/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <boost/asio/ip/v6_only.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/http/parser.hpp>
#include <boost/beast/http/write.hpp>
#include <native_streaming/utils/boost_compatibility_utils.hpp>
#include "ws_stream_impl.hpp"

Expand All @@ -27,6 +28,9 @@ constexpr auto acceptRequestTimeout = std::chrono::seconds(5);
constexpr auto rejectedConnectionDrainTimeout = std::chrono::seconds(1);
#endif

/// Value of the Server header in every reply to an upgrade request, accepted (101) or rejected (401)
static constexpr const char* SERVER_IDENTITY = BOOST_BEAST_VERSION_STRING " openDAQ-streaming-server";

}

Server::Server(OnNewSessionCallback onNewSessionCallback,
Expand Down Expand Up @@ -360,13 +364,14 @@ void Server::onReadAcceptRequest(const boost::system::error_code& ec, const std:
if (!onAuthenticateCallback(authentication, userContext))
{
NS_LOG_I("Websocket authenticaiton failed");
rejectUnauthorized(wsStream, request.version());
return;
}

// Set a decorator to change the Server-Agent of the handshake
wsStream->set_option(boost::beast::websocket::stream_base::decorator(
[](boost::beast::websocket::response_type& res)
{ res.set(boost::beast::http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " openDAQ-streaming-server"); }));
{ res.set(boost::beast::http::field::server, SERVER_IDENTITY); }));

// Accept the upgrade request
boost_compatibility_utils::async_accept(*wsStream,
Expand All @@ -378,6 +383,39 @@ void Server::onReadAcceptRequest(const boost::system::error_code& ec, const std:
});
}

template <typename Stream>
void Server::rejectUnauthorized(const std::shared_ptr<Stream>& wsStream, unsigned httpVersion)
{
auto response = std::make_shared<boost::beast::http::response<boost::beast::http::string_body>>(
boost::beast::http::status::unauthorized, httpVersion);
response->set(boost::beast::http::field::server, SERVER_IDENTITY);
response->set(boost::beast::http::field::www_authenticate, "Basic");
response->keep_alive(false);
response->prepare_payload();

// Bound the write so a client that stops reading cannot keep the rejected connection open.
boost::beast::get_lowest_layer(*wsStream).expires_after(std::chrono::seconds(5));

boost::beast::http::async_write(wsStream->next_layer(),
*response,
[this, weak_self = weak_from_this(), wsStream, response](const boost::system::error_code& ec, size_t /*size*/)
{
if (auto sharedSelf = weak_self.lock())
{
if (ec)
NS_LOG_W("Failed to send authentication rejection response: {}", ec.message());

// A graceful close sends the 401 first and only then the FIN, so the client
// reads the full response before it sees the connection closed.
// Compliant websocket clients send nothing after the upgrade request until
// they get the response (RFC 6455), so no unread data is pending here.
// A non-compliant client that already sent more data gets a reset instead
// of FIN and may miss the 401 - accepted, the extra bytes are not drained.
boost::beast::get_lowest_layer(*wsStream).close();
}
});
}

template <typename Stream>
void Server::onUpgradeConnection(const boost::system::error_code& ec,
std::shared_ptr<Stream> wsStream,
Expand Down
6 changes: 4 additions & 2 deletions src/utils/boost_compatibility_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,23 @@ BEGIN_NAMESPACE_STREAM_UTILS
namespace boost_compatibility_utils
{
void async_handshake(WebsocketStream& stream,
boost::beast::websocket::response_type& response,
const std::string& host,
const std::string& target,
const BoostHandler& handler)
{
stream.async_handshake(host, target, handler);
stream.async_handshake(response, host, target, handler);
}

#if NATIVE_STREAMING_ENABLE_TLS

void async_handshake(TlsWebsocketStream& stream,
boost::beast::websocket::response_type& response,
const std::string& host,
const std::string& target,
const BoostHandler& handler)
{
stream.async_handshake(host, target, handler);
stream.async_handshake(response, host, target, handler);
}

#endif
Expand Down
Loading
Loading