544 lines
16 KiB
C++
544 lines
16 KiB
C++
#include <Void/Log/Log.hpp>
|
|
#include "echoion/core/RpcServer.hpp"
|
|
#include <Void/Data/Json.hpp>
|
|
#include <Void/Data/Reflect.hpp>
|
|
#include <algorithm>
|
|
#include <format>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
|
|
RpcServer::RpcServer() = default;
|
|
|
|
RpcServer::~RpcServer() { stop(); }
|
|
|
|
Api::Result<void> RpcServer::start(uint16_t port)
|
|
{
|
|
if (running_.exchange(true)) {
|
|
return Api::fail(Api::ErrorCode::AlreadyExists,
|
|
"RPC server already running");
|
|
}
|
|
|
|
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());
|
|
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
|
acceptor_->bind(endpoint);
|
|
acceptor_->listen();
|
|
|
|
clientPool_ = std::make_unique<Void::Concurrency::ThreadPool>(
|
|
CLIENT_POOL_SIZE);
|
|
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
|
|
|
|
Void::Log::info("RpcServer", "{}",
|
|
std::format("RPC server started on port {}", port));
|
|
return {};
|
|
} catch (const std::exception& e) {
|
|
running_ = false;
|
|
return Api::fail(
|
|
Api::ErrorCode::ServiceUnavailable,
|
|
std::format("Failed to start RPC server: {}", e.what()));
|
|
}
|
|
}
|
|
|
|
void RpcServer::stop()
|
|
{
|
|
if (!running_.exchange(false)) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Cancel any pending async operations
|
|
if (acceptor_.has_value()) {
|
|
boost::system::error_code ec;
|
|
acceptor_->cancel(ec);
|
|
}
|
|
|
|
ioContext_.stop();
|
|
|
|
// Close all client connections
|
|
{
|
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
for (auto& [id, ws] : clients_) {
|
|
if (ws->is_open()) {
|
|
beast::error_code ec;
|
|
ws->close(websocket::close_code::normal, ec);
|
|
}
|
|
}
|
|
clients_.clear();
|
|
}
|
|
|
|
// Drain and join the client handlers. Their sockets were just
|
|
// closed, so each handleClient read() fails and the task returns;
|
|
// ~ThreadPool then joins every worker.
|
|
clientPool_.reset();
|
|
|
|
// The acceptor was cancelled and ioContext_ stopped above, so the
|
|
// accept loop exits promptly. Join unconditionally: detaching
|
|
// here let the thread outlive ioContext_ (use-after-free when the
|
|
// core library unloads).
|
|
if (serverThread_.joinable()) {
|
|
serverThread_.join();
|
|
}
|
|
|
|
if (acceptor_.has_value()) {
|
|
boost::system::error_code ec;
|
|
acceptor_->close(ec);
|
|
}
|
|
|
|
Void::Log::info("RpcServer", "{}", "RPC server stopped");
|
|
} catch (const std::exception& e) {
|
|
Void::Log::error("RpcServer", "{}",
|
|
std::format("Error stopping RPC server: {}", e.what()));
|
|
}
|
|
}
|
|
|
|
void RpcServer::acceptLoop()
|
|
{
|
|
Void::Log::info("RpcServer", "{}", "RPC server accept loop started");
|
|
|
|
// 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 {
|
|
ioContext_.run();
|
|
break; // returned normally: acceptor cancelled, no more work
|
|
} catch (const std::exception& e) {
|
|
// 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::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)
|
|
{
|
|
beast::flat_buffer buffer;
|
|
|
|
while (running_.load() && ws->is_open()) {
|
|
try {
|
|
beast::error_code ec;
|
|
ws->read(buffer, ec);
|
|
|
|
if (ec) {
|
|
// 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;
|
|
}
|
|
|
|
std::string message = beast::buffers_to_string(buffer.data());
|
|
buffer.consume(buffer.size());
|
|
|
|
// Find client ID
|
|
uint64_t clientId = 0;
|
|
{
|
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
for (const auto& [id, clientWs] : clients_) {
|
|
if (clientWs.get() == ws.get()) {
|
|
clientId = id;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (clientId != 0) {
|
|
processMessage(clientId, message);
|
|
}
|
|
|
|
} catch (const std::exception& e) {
|
|
Void::Log::error("RpcServer", "{}",
|
|
std::format("Client handling error: {}", e.what()));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void RpcServer::processMessage(uint64_t clientId,
|
|
const std::string& message)
|
|
{
|
|
try {
|
|
Api::RpcRequest request;
|
|
bool decoded = false;
|
|
if (auto parsed = Void::Json::parse(message)) {
|
|
if (auto req = Void::Json::from_json<Api::RpcRequest>(*parsed)) {
|
|
request = std::move(*req);
|
|
decoded = true;
|
|
}
|
|
}
|
|
if (!decoded) {
|
|
Api::RpcResponse response;
|
|
response.requestId = 0;
|
|
response.success = false;
|
|
response.error = "{\"code\":5,\"message\":\"Invalid "
|
|
"JSON\",\"source\":\"RpcServer\"}";
|
|
response.success = false;
|
|
sendResponse(clientId, response);
|
|
return;
|
|
}
|
|
|
|
// 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;
|
|
response.success = false;
|
|
response.error =
|
|
"{\"code\":10,\"message\":\"Not "
|
|
"authenticated\",\"source\":\"RpcServer\"}";
|
|
response.success = false;
|
|
sendResponse(clientId, response);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Record the (authorized) invocation in the bounded audit ring.
|
|
{
|
|
std::lock_guard<std::mutex> lock(auditMutex_);
|
|
auditLog_.push_back(AuditEntry{
|
|
.clientId = clientId,
|
|
.method = static_cast<int>(request.method),
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
if (auditLog_.size() > MAX_AUDIT_ENTRIES) {
|
|
auditLog_.pop_front();
|
|
}
|
|
}
|
|
|
|
// Find handler
|
|
std::string methodName =
|
|
std::to_string(static_cast<int>(request.method));
|
|
CommandHandler handler;
|
|
{
|
|
std::lock_guard<std::mutex> lock(handlersMutex_);
|
|
auto it = handlers_.find(methodName);
|
|
if (it != handlers_.end()) {
|
|
handler = it->second;
|
|
}
|
|
}
|
|
|
|
Api::RpcResponse response;
|
|
response.requestId = request.id;
|
|
response.timestamp = std::chrono::system_clock::now();
|
|
|
|
if (handler) {
|
|
auto result = handler(request.params.value_or(""), clientId);
|
|
if (result) {
|
|
response.success = true;
|
|
response.result = *result;
|
|
} else {
|
|
response.success = false;
|
|
// Error text can include quoted TeamSpeak permission names
|
|
// or other protocol detail. Serialize it as JSON instead of
|
|
// interpolating it into JSON syntax so the browser always
|
|
// receives a decodable error.
|
|
response.error = Void::Json::serialize(Void::Json::object(
|
|
{{"code", Void::Json::Value{static_cast<long long>(
|
|
result.error().code)}},
|
|
{"message", Void::Json::Value{result.error().message}},
|
|
{"source",
|
|
Void::Json::Value{result.error().source}}}));
|
|
}
|
|
} else {
|
|
response.success = false;
|
|
response.error = "{\"code\":2,\"message\":\"Unknown "
|
|
"method\",\"source\":\"RpcServer\"}";
|
|
}
|
|
|
|
sendResponse(clientId, response);
|
|
|
|
} catch (const std::exception& e) {
|
|
Void::Log::error("RpcServer", "{}",
|
|
std::format("Message processing error: {}", e.what()));
|
|
}
|
|
}
|
|
|
|
void RpcServer::sendResponse(uint64_t clientId,
|
|
const Api::RpcResponse& response)
|
|
{
|
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
auto it = clients_.find(clientId);
|
|
if (it == clients_.end() || !it->second->is_open()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const std::string json =
|
|
Void::Json::serialize(Void::Json::to_json(response));
|
|
it->second->write(asio::buffer(json));
|
|
} catch (const std::exception& e) {
|
|
Void::Log::error("RpcServer", "{}", std::format("Send response error: {}", e.what()));
|
|
}
|
|
}
|
|
|
|
void RpcServer::sendNotification(uint64_t clientId,
|
|
const Api::RpcNotification& notification)
|
|
{
|
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
auto it = clients_.find(clientId);
|
|
if (it == clients_.end() || !it->second->is_open()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const std::string json =
|
|
Void::Json::serialize(Void::Json::to_json(notification));
|
|
it->second->write(asio::buffer(json));
|
|
} catch (const std::exception& e) {
|
|
Void::Log::error("RpcServer", "{}",
|
|
std::format("Send notification error: {}", e.what()));
|
|
}
|
|
}
|
|
|
|
void RpcServer::broadcastEvent(const std::string& event,
|
|
const std::string& data)
|
|
{
|
|
Api::RpcNotification notification;
|
|
notification.event = event;
|
|
notification.data = data;
|
|
notification.timestamp = std::chrono::system_clock::now();
|
|
|
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
for (const auto& [clientId, ws] : clients_) {
|
|
if (ws->is_open() && isClientAuthenticated(clientId)) {
|
|
try {
|
|
const std::string json = Void::Json::serialize(
|
|
Void::Json::to_json(notification));
|
|
ws->write(asio::buffer(json));
|
|
} catch (const std::exception& e) {
|
|
Void::Log::error("RpcServer", "{}",
|
|
std::format("Broadcast error: {}", e.what()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void RpcServer::sendEvent(uint64_t clientId, const std::string& event,
|
|
const std::string& data)
|
|
{
|
|
Api::RpcNotification notification;
|
|
notification.event = event;
|
|
notification.data = data;
|
|
notification.timestamp = std::chrono::system_clock::now();
|
|
sendNotification(clientId, notification);
|
|
}
|
|
|
|
void RpcServer::registerHandler(const std::string& method,
|
|
CommandHandler handler)
|
|
{
|
|
std::lock_guard<std::mutex> lock(handlersMutex_);
|
|
handlers_[method] = std::move(handler);
|
|
}
|
|
|
|
void RpcServer::unregisterHandler(const std::string& method)
|
|
{
|
|
std::lock_guard<std::mutex> lock(handlersMutex_);
|
|
handlers_.erase(method);
|
|
}
|
|
|
|
std::vector<RpcServer::AuditEntry> RpcServer::getAuditLog() const
|
|
{
|
|
std::lock_guard<std::mutex> lock(auditMutex_);
|
|
return {auditLog_.begin(), auditLog_.end()};
|
|
}
|
|
|
|
size_t RpcServer::getClientCount() const
|
|
{
|
|
std::lock_guard<std::mutex> lock(clientsMutex_);
|
|
return clients_.size();
|
|
}
|
|
|
|
std::chrono::seconds RpcServer::getUptime() const
|
|
{
|
|
return std::chrono::duration_cast<std::chrono::seconds>(
|
|
std::chrono::steady_clock::now() - startTime_);
|
|
}
|
|
|
|
void RpcServer::setAuthToken(const std::string& token)
|
|
{
|
|
std::lock_guard<std::mutex> lock(authMutex_);
|
|
authToken_ = token;
|
|
}
|
|
|
|
bool RpcServer::authenticate(const std::string& token)
|
|
{
|
|
std::lock_guard<std::mutex> lock(authMutex_);
|
|
return authToken_.empty() || token == authToken_;
|
|
}
|
|
|
|
void RpcServer::addAuthenticatedClient(uint64_t clientId)
|
|
{
|
|
std::lock_guard<std::mutex> lock(authMutex_);
|
|
authenticatedClients_.insert(clientId);
|
|
}
|
|
|
|
void RpcServer::removeAuthenticatedClient(uint64_t clientId)
|
|
{
|
|
std::lock_guard<std::mutex> lock(authMutex_);
|
|
authenticatedClients_.erase(clientId);
|
|
}
|
|
|
|
bool RpcServer::isClientAuthenticated(uint64_t clientId)
|
|
{
|
|
std::lock_guard<std::mutex> lock(authMutex_);
|
|
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
|