1 parent
d146f11f02
commit
5c036d91fb
72 files changed
+5875
-1243
No files matched your search
+163
-89
@@ -22,6 +22,10 @@ namespace Echoion::Core
|
||||
port_ = port;
|
||||
|
||||
try {
|
||||
// A prior stop() left the io_context in the stopped state; reset
|
||||
// it so acceptLoop()'s run() actually processes work.
|
||||
ioContext_.restart();
|
||||
|
||||
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
|
||||
acceptor_.emplace(ioContext_);
|
||||
acceptor_->open(endpoint.protocol());
|
||||
@@ -99,98 +103,142 @@ namespace Echoion::Core
|
||||
void RpcServer::acceptLoop()
|
||||
{
|
||||
Void::Log::info("RpcServer", "{}", "RPC server accept loop started");
|
||||
while (running_.load()) {
|
||||
|
||||
// Arm the first async accept, then let the io_context drive re-arming
|
||||
// from the completion handler. This model is cleanly interruptible:
|
||||
// stop() cancels the acceptor (the pending accept completes with
|
||||
// operation_aborted and does not re-arm) and calls ioContext_.stop(),
|
||||
// so run() returns promptly. A blocking synchronous accept, by
|
||||
// contrast, cannot be reliably woken from another thread on Linux.
|
||||
doAccept();
|
||||
|
||||
for (;;) {
|
||||
try {
|
||||
asio::ip::tcp::socket socket(ioContext_);
|
||||
Void::Log::debug("RpcServer", "{}", "RPC server waiting for connection...");
|
||||
|
||||
// Use async accept with cancellation support
|
||||
std::atomic<bool> acceptComplete{false};
|
||||
boost::system::error_code acceptEc;
|
||||
|
||||
acceptor_->async_accept(
|
||||
socket, [&](const boost::system::error_code& ec) {
|
||||
acceptEc = ec;
|
||||
acceptComplete = true;
|
||||
});
|
||||
|
||||
// Block until the accept completes or we're stopped. stop()
|
||||
// clears running_, cancels the acceptor and calls
|
||||
// ioContext_.stop(), so run_one() returns promptly instead of
|
||||
// the previous 10ms busy-poll.
|
||||
while (!acceptComplete.load() && running_.load()) {
|
||||
if (ioContext_.stopped()) {
|
||||
break;
|
||||
}
|
||||
ioContext_.run_one();
|
||||
}
|
||||
|
||||
// Cancel pending operation if we're stopping
|
||||
if (!running_.load()) {
|
||||
acceptor_->cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
if (acceptEc) {
|
||||
throw std::runtime_error(acceptEc.message());
|
||||
}
|
||||
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("RPC server accepted TCP connection from {}:{}",
|
||||
socket.remote_endpoint().address().to_string(),
|
||||
socket.remote_endpoint().port()));
|
||||
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(socket));
|
||||
ws->accept();
|
||||
Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed");
|
||||
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
}
|
||||
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("RPC client {} connected", clientId));
|
||||
|
||||
// Handle the client on the worker pool (drained/joined by
|
||||
// ~ThreadPool on stop).
|
||||
if (clientPool_) {
|
||||
clientPool_->submit([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
// Cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_.erase(clientId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
Void::Log::debug("RpcServer", "{}", std::format(
|
||||
"RPC client {} disconnected", clientId));
|
||||
});
|
||||
}
|
||||
|
||||
ioContext_.run();
|
||||
break; // returned normally: acceptor cancelled, no more work
|
||||
} catch (const std::exception& e) {
|
||||
// If we're shutting down, exit gracefully
|
||||
// A handler threw (should not happen: the accept path uses
|
||||
// error_code overloads). Never re-arm into a tight spin --
|
||||
// bail if we're stopping, otherwise resume the event loop.
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("RPC accept loop error: {}", e.what()));
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("RPC accept error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
Void::Log::info("RpcServer", "{}", "RPC server accept loop stopped");
|
||||
}
|
||||
|
||||
void RpcServer::doAccept()
|
||||
{
|
||||
auto socket = std::make_shared<asio::ip::tcp::socket>(ioContext_);
|
||||
acceptor_->async_accept(
|
||||
*socket,
|
||||
[this, socket](const boost::system::error_code& ec) {
|
||||
// Cancelled by stop(): tear-down, do not re-arm.
|
||||
if (ec == asio::error::operation_aborted ||
|
||||
!running_.load()) {
|
||||
return;
|
||||
}
|
||||
if (ec) {
|
||||
// Transient accept error (peer vanished mid-handshake,
|
||||
// fd pressure, ...). Log once and re-arm -- the loop is
|
||||
// event-driven, so this cannot busy-spin the way the old
|
||||
// run_one() loop did.
|
||||
Void::Log::warn("RpcServer", "{}",
|
||||
std::format("RPC accept failed: {}", ec.message()));
|
||||
} else {
|
||||
onAccept(std::move(*socket));
|
||||
}
|
||||
if (running_.load()) {
|
||||
doAccept();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void RpcServer::onAccept(asio::ip::tcp::socket socket)
|
||||
{
|
||||
// Non-throwing remote_endpoint: on a torn-down socket this would
|
||||
// otherwise throw "Bad file descriptor" -- the original spam source.
|
||||
boost::system::error_code epc;
|
||||
std::string peerAddress;
|
||||
bool peerIsLoopback = false;
|
||||
if (auto ep = socket.remote_endpoint(epc); !epc) {
|
||||
peerAddress = ep.address().to_string();
|
||||
peerIsLoopback = ep.address().is_loopback();
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("RPC server accepted TCP connection from {}:{}",
|
||||
peerAddress, ep.port()));
|
||||
}
|
||||
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(socket));
|
||||
|
||||
// Read the upgrade request explicitly so handshake headers are
|
||||
// visible: the web server's /rpc bridge forwards the browser's real
|
||||
// address in X-Echoion-Client-Ip (trusted from loopback only).
|
||||
beast::error_code wsEc;
|
||||
beast::flat_buffer handshakeBuffer;
|
||||
beast::http::request<beast::http::string_body> upgradeReq;
|
||||
beast::http::read(ws->next_layer(), handshakeBuffer, upgradeReq, wsEc);
|
||||
if (wsEc || !websocket::is_upgrade(upgradeReq)) {
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("WebSocket handshake failed: {}",
|
||||
wsEc ? wsEc.message() : "not an upgrade"));
|
||||
return;
|
||||
}
|
||||
std::string clientAddress = peerAddress;
|
||||
if (peerIsLoopback) {
|
||||
if (auto fwd = upgradeReq.find("X-Echoion-Client-Ip");
|
||||
fwd != upgradeReq.end() && !fwd->value().empty()) {
|
||||
clientAddress = std::string(fwd->value());
|
||||
}
|
||||
}
|
||||
|
||||
// error_code overload: a failed handshake is a normal client-side
|
||||
// event, not an "RPC accept error".
|
||||
ws->accept(upgradeReq, wsEc);
|
||||
if (wsEc) {
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("WebSocket handshake failed: {}", wsEc.message()));
|
||||
return;
|
||||
}
|
||||
Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed");
|
||||
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
clientAddresses_[clientId] = clientAddress;
|
||||
}
|
||||
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("RPC client {} connected", clientId));
|
||||
|
||||
// Handle the client on the worker pool (drained/joined by ~ThreadPool
|
||||
// on stop).
|
||||
if (clientPool_) {
|
||||
clientPool_->submit([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
// Cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_.erase(clientId);
|
||||
clientAddresses_.erase(clientId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
Void::Log::debug("RpcServer", "{}", std::format(
|
||||
"RPC client {} disconnected", clientId));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::handleClient(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
|
||||
{
|
||||
@@ -201,12 +249,26 @@ namespace Echoion::Core
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
|
||||
if (ec == websocket::error::closed) {
|
||||
break;
|
||||
}
|
||||
if (ec) {
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("WebSocket read error: {}", ec.message()));
|
||||
// Browsers reach us through the HttpServer /rpc TCP tunnel;
|
||||
// closing a tab tears the upstream socket down abruptly, so
|
||||
// the read fails with ENOTCONN/eof/reset rather than a clean
|
||||
// WebSocket close frame. These are all normal disconnects —
|
||||
// log them at debug so routine tab churn doesn't spam errors.
|
||||
const bool cleanDisconnect =
|
||||
ec == websocket::error::closed ||
|
||||
ec == asio::error::eof ||
|
||||
ec == asio::error::connection_reset ||
|
||||
ec == asio::error::not_connected ||
|
||||
ec == asio::error::broken_pipe ||
|
||||
ec == asio::error::operation_aborted;
|
||||
if (cleanDisconnect) {
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("WebSocket closed: {}", ec.message()));
|
||||
} else {
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("WebSocket read error: {}", ec.message()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -260,8 +322,9 @@ namespace Echoion::Core
|
||||
return;
|
||||
}
|
||||
|
||||
// Check authentication (except for Authenticate method)
|
||||
if (request.method != Api::RpcMethod::Authenticate) {
|
||||
// Check authentication (except for the sign-in methods)
|
||||
if (request.method != Api::RpcMethod::Authenticate &&
|
||||
request.method != Api::RpcMethod::AuthenticateByAddress) {
|
||||
if (!isClientAuthenticated(clientId)) {
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
@@ -461,4 +524,15 @@ namespace Echoion::Core
|
||||
return authenticatedClients_.contains(clientId);
|
||||
}
|
||||
|
||||
std::optional<std::string>
|
||||
RpcServer::getClientAddress(uint64_t clientId) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
auto it = clientAddresses_.find(clientId);
|
||||
if (it == clientAddresses_.end() || it->second.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Reference in new issue
Block a user