Files
EchoionWeb/src/HttpServer.cpp
T
faumaray e80dbc2fda Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:50:44 +03:00

556 lines
16 KiB
C++

#include "echoion/web/HttpServer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <boost/beast/websocket.hpp>
#include <array>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <sstream>
#include <string_view>
namespace Echoion::Web
{
namespace websocket = beast::websocket;
namespace
{
std::string_view contentType(const std::filesystem::path& path)
{
const std::string ext = path.extension().string();
if (ext == ".html") {
return "text/html; charset=utf-8";
}
if (ext == ".js") {
return "text/javascript; charset=utf-8";
}
if (ext == ".css") {
return "text/css; charset=utf-8";
}
if (ext == ".json") {
return "application/json; charset=utf-8";
}
if (ext == ".svg") {
return "image/svg+xml";
}
if (ext == ".png") {
return "image/png";
}
if (ext == ".ico") {
return "image/x-icon";
}
if (ext == ".woff2") {
return "font/woff2";
}
return "application/octet-stream";
}
std::optional<std::string> readFile(const std::filesystem::path& path)
{
std::ifstream file(path, std::ios::binary);
if (!file) {
return std::nullopt;
}
std::ostringstream ss;
ss << file.rdbuf();
return ss.str();
}
// Percent-decode one URL path segment (TeamSpeak uids are base64 and
// carry '+', '/', '=' — the browser sends them encoded).
std::string urlDecode(std::string_view in)
{
std::string out;
out.reserve(in.size());
for (std::size_t i = 0; i < in.size(); ++i) {
if (in[i] == '%' && i + 2 < in.size()) {
const auto hex = [](char c) -> int {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
};
const int hi = hex(in[i + 1]);
const int lo = hex(in[i + 2]);
if (hi >= 0 && lo >= 0) {
out += static_cast<char>(hi * 16 + lo);
i += 2;
continue;
}
}
out += in[i];
}
return out;
}
// One direction of a raw TCP tunnel. On any error both sockets are
// shut down so the opposite pump unblocks too.
void pumpBytes(boost::asio::ip::tcp::socket& from,
boost::asio::ip::tcp::socket& to)
{
std::array<char, 8192> buf;
boost::system::error_code ec;
for (;;) {
const std::size_t n =
from.read_some(boost::asio::buffer(buf), ec);
if (ec || n == 0) {
break;
}
boost::asio::write(to, boost::asio::buffer(buf.data(), n), ec);
if (ec) {
break;
}
}
boost::system::error_code ignore;
from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
}
} // namespace
HttpServer::HttpServer() = default;
HttpServer::~HttpServer() { stop(); }
bool HttpServer::start(const Config& config)
{
if (running_.exchange(true)) {
return false;
}
config_ = config;
try {
ioContext_.restart();
asio::ip::tcp::endpoint endpoint(
asio::ip::make_address(config_.bindAddress), config_.port);
acceptor_.emplace(ioContext_);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen();
pool_ = std::make_unique<Void::Concurrency::ThreadPool>(POOL_SIZE);
serverThread_ = std::thread(&HttpServer::acceptLoop, this);
// A wrong webRoot only surfaces as bare 404s in the browser —
// call it out at startup instead.
const auto indexPath =
std::filesystem::path(config_.webRoot) / "index.html";
std::error_code fsEc;
if (!std::filesystem::exists(indexPath, fsEc)) {
Void::Log::warn(
"HttpServer", "{}",
std::format("webRoot '{}' has no index.html — the web UI "
"will return 404; copy the shipped web/ "
"assets (build/bin/web) there",
config_.webRoot));
}
Void::Log::info("HttpServer", "{}",
std::format("Web interface listening on {}:{}",
config_.bindAddress, config_.port));
return true;
} catch (const std::exception& e) {
running_ = false;
Void::Log::error(
"HttpServer", "{}",
std::format("Failed to start web interface: {}", e.what()));
return false;
}
}
void HttpServer::stop()
{
if (!running_.exchange(false)) {
return;
}
try {
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->cancel(ec);
}
ioContext_.stop();
// Unblock every /rpc bridge pump so the pool workers can return.
{
std::lock_guard<std::mutex> lock(bridgesMutex_);
for (auto& [id, pair] : bridges_) {
boost::system::error_code ec;
pair.first->shutdown(asio::ip::tcp::socket::shutdown_both,
ec);
pair.second->shutdown(asio::ip::tcp::socket::shutdown_both,
ec);
}
bridges_.clear();
}
// Closed sockets make each handler's read() fail and return, then
// ~ThreadPool joins every worker.
pool_.reset();
if (serverThread_.joinable()) {
serverThread_.join();
}
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->close(ec);
}
Void::Log::info("HttpServer", "{}", "Web interface stopped");
} catch (const std::exception& e) {
Void::Log::error(
"HttpServer", "{}",
std::format("Error stopping web interface: {}", e.what()));
}
}
void HttpServer::acceptLoop()
{
// Same interruptible async re-arm model as the RPC server: stop()
// cancels the acceptor (pending accept completes with operation_aborted
// and does not re-arm) and stops the context, so run() returns.
doAccept();
for (;;) {
try {
ioContext_.run();
break;
} catch (const std::exception& e) {
Void::Log::error(
"HttpServer", "{}",
std::format("Web accept loop error: {}", e.what()));
if (!running_.load()) {
break;
}
}
}
}
void HttpServer::doAccept()
{
auto socket = std::make_shared<asio::ip::tcp::socket>(ioContext_);
acceptor_->async_accept(
*socket, [this, socket](const boost::system::error_code& ec) {
if (ec == asio::error::operation_aborted || !running_.load()) {
return;
}
if (ec) {
Void::Log::warn(
"HttpServer", "{}",
std::format("Web accept failed: {}", ec.message()));
} else {
onAccept(std::move(*socket));
}
if (running_.load()) {
doAccept();
}
});
}
void HttpServer::onAccept(asio::ip::tcp::socket socket)
{
// Hand off to the pool: reading the request (and any subsequent
// WebSocket loop) is blocking and must not stall the accept thread.
auto held = std::make_shared<asio::ip::tcp::socket>(std::move(socket));
if (pool_) {
pool_->submit([this, held]() { handleConnection(held); });
}
}
void HttpServer::handleConnection(
std::shared_ptr<asio::ip::tcp::socket> socket)
{
beast::error_code ec;
beast::flat_buffer buffer;
// Serve requests on this connection until the peer closes, an error
// occurs, or the request asks not to keep the connection alive.
while (running_.load()) {
http::request<http::string_body> req;
http::read(*socket, buffer, req, ec);
if (ec) {
return;
}
if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") {
bridgeRpc(socket, req, buffer);
}
return;
}
if (!serveHttp(*socket, req)) {
return;
}
}
}
void HttpServer::bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
http::request<http::string_body>& req,
beast::flat_buffer& residual)
{
boost::system::error_code ec;
auto upstream = std::make_shared<asio::ip::tcp::socket>(ioContext_);
upstream->connect(
asio::ip::tcp::endpoint(asio::ip::make_address("127.0.0.1"),
config_.rpcPort),
ec);
if (ec) {
Void::Log::warn(
"HttpServer", "{}",
std::format("RPC bridge: cannot reach RPC server on "
"127.0.0.1:{}: {}",
config_.rpcPort, ec.message()));
return;
}
// Forward the browser's effective IP so the RPC server can offer
// address-based autologin. Never trust a client-supplied value; a
// reverse proxy's X-Forwarded-For (first hop) wins over the socket
// address because the proxy connects from its own host.
req.erase("X-Echoion-Client-Ip");
std::string clientIp;
if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) {
clientIp = std::string(xff->value());
if (auto comma = clientIp.find(','); comma != std::string::npos) {
clientIp = clientIp.substr(0, comma);
}
while (!clientIp.empty() && clientIp.front() == ' ') {
clientIp.erase(clientIp.begin());
}
}
if (clientIp.empty()) {
boost::system::error_code epEc;
if (auto ep = browser->remote_endpoint(epEc); !epEc) {
clientIp = ep.address().to_string();
}
}
if (!clientIp.empty()) {
req.set("X-Echoion-Client-Ip", clientIp);
}
// Replay the browser's upgrade request (plus any bytes already read
// past it) so the real WebSocket handshake happens against the RPC
// server itself.
http::write(*upstream, req, ec);
if (!ec && residual.size() > 0) {
asio::write(*upstream, residual.data(), ec);
}
if (ec) {
return;
}
const uint64_t connId = nextConnId_++;
{
std::lock_guard<std::mutex> lock(bridgesMutex_);
bridges_[connId] = {browser, upstream};
}
Void::Log::debug("HttpServer", "{}",
std::format("RPC bridge {} opened", connId));
// Each direction owns its socket's read side; either side failing
// shuts both down, unblocking the other pump.
std::thread down(
[browser, upstream]() { pumpBytes(*upstream, *browser); });
pumpBytes(*browser, *upstream);
down.join();
{
std::lock_guard<std::mutex> lock(bridgesMutex_);
bridges_.erase(connId);
}
Void::Log::debug("HttpServer", "{}",
std::format("RPC bridge {} closed", connId));
}
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req)
{
beast::error_code ec;
const bool isHead = req.method() == http::verb::head;
auto respond = [&](http::status status, std::string_view type,
std::string body, std::string_view cacheControl = {},
std::string_view lastModified = {},
std::string_view etag = {},
std::string_view location = {}) {
http::response<http::string_body> res{status, req.version()};
res.set(http::field::server, "Echoion");
res.set(http::field::content_type, type);
if (!cacheControl.empty()) {
res.set(http::field::cache_control, cacheControl);
}
if (!lastModified.empty()) {
res.set(http::field::last_modified, lastModified);
}
if (!etag.empty()) {
res.set(http::field::etag, etag);
}
if (!location.empty()) {
res.set(http::field::location, location);
}
res.keep_alive(req.keep_alive());
// HEAD advertises the real Content-Length but carries no body.
res.content_length(
status == http::status::not_modified ? 0 : body.size());
if (!isHead && status != http::status::not_modified) {
res.body() = std::move(body);
}
http::write(socket, res, ec);
};
if (req.method() != http::verb::get && !isHead) {
respond(http::status::method_not_allowed, "text/plain",
"Method Not Allowed");
return !ec && req.keep_alive();
}
std::string target(req.target());
if (auto q = target.find('?'); q != std::string::npos) {
target = target.substr(0, q);
}
// Tells the browser where the RPC server lives. By default it is the
// same-origin /rpc bridge, so only the web port needs exposing; an
// explicitly configured rpcUrl still overrides.
if (target == "/config.json") {
using Void::Json::Value;
const std::string rpcUrl =
config_.rpcUrl.empty() ? "/rpc" : config_.rpcUrl;
respond(
http::status::ok, "application/json",
Void::Json::serialize(Void::Json::object(
{{"rpcUrl", Value{rpcUrl}},
{"rpcPort",
Value{static_cast<long long>(config_.rpcPort)}},
{"watchUrl", Value{config_.watchUrl}},
{"nowPlayingVideo", Value{config_.nowPlayingVideo}}})));
return !ec && req.keep_alive();
}
if (target == "/api/public/dashboard") {
DashboardProvider provider;
{
std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
provider = dashboardProvider_;
}
if (!provider) {
respond(http::status::service_unavailable, "application/json",
R"({"error":"Dashboard snapshot unavailable"})",
"no-cache");
return !ec && req.keep_alive();
}
auto snapshot = provider();
if (auto current = req.find(http::field::if_none_match);
current != req.end() && current->value() == snapshot.etag) {
respond(http::status::not_modified, "application/json", "",
"no-cache", {}, snapshot.etag);
return !ec && req.keep_alive();
}
respond(http::status::ok, "application/json",
std::move(snapshot.body), "no-cache", {}, snapshot.etag);
return !ec && req.keep_alive();
}
if ((target == "/watch" || target == "/watch/") &&
!config_.watchUrl.empty()) {
respond(http::status::temporary_redirect, "text/plain", "",
"no-store", {}, {}, config_.watchUrl);
return !ec && req.keep_alive();
}
// User avatar images, resolved through Core's provider (TeamSpeak
// avatar cache). Best-effort: 404 lets the UI fall back to its
// initial-letter avatars; short private caching keeps reloads cheap
// without pinning stale avatars for long.
constexpr std::string_view kAvatarPrefix = "/avatar/";
if (target.starts_with(kAvatarPrefix)) {
// The query string (the web UI appends ?v=N to bypass the browser's
// negative cache when retrying) is already stripped from `target`
// above, so the remainder is just the encoded uid.
const std::string uid =
urlDecode(target.substr(kAvatarPrefix.size()));
AvatarProvider provider;
{
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
provider = avatarProvider_;
}
Void::Log::info("HttpServer", "{}",
std::format("GET /avatar uid='{}' provider={}", uid,
provider ? "set" : "none"));
if (!uid.empty() && provider) {
if (auto image = provider(uid)) {
Void::Log::info(
"HttpServer", "{}",
std::format("avatar 200 uid='{}' type={} bytes={}", uid,
image->contentType, image->bytes.size()));
respond(http::status::ok, image->contentType,
std::move(image->bytes), "private, max-age=300");
return !ec && req.keep_alive();
}
}
Void::Log::info("HttpServer", "{}",
std::format("avatar 404 uid='{}'", uid));
respond(http::status::not_found, "text/plain", "Not Found",
"private, max-age=60");
return !ec && req.keep_alive();
}
if (target.empty() || target == "/") {
target = "/index.html";
}
// Reject path traversal outright.
if (target.find("..") != std::string::npos) {
respond(http::status::bad_request, "text/plain", "Bad Request");
return !ec && req.keep_alive();
}
std::filesystem::path path =
std::filesystem::path(config_.webRoot) / target.substr(1);
auto contents = readFile(path);
if (!contents) {
respond(http::status::not_found, "text/plain", "Not Found");
return !ec && req.keep_alive();
}
// Fonts and Vite's content-hashed bundle assets (/assets/*, e.g.
// index-Bq3KBlm7.js) are immutable-forever — a content change mints a
// new filename. Everything else (index.html, /config.json, fonts.css)
// revalidates cheaply via Last-Modified.
const bool immutable =
path.extension() == ".woff2" || target.starts_with("/assets/");
const std::string_view cache =
immutable ? "public, max-age=31536000, immutable" : "no-cache";
std::string lastModified;
std::error_code fsEc;
if (auto ftime = std::filesystem::last_write_time(path, fsEc); !fsEc) {
const auto sys =
std::chrono::clock_cast<std::chrono::system_clock>(ftime);
lastModified =
std::format("{:%a, %d %b %Y %H:%M:%S} GMT",
std::chrono::floor<std::chrono::seconds>(sys));
}
if (!lastModified.empty()) {
if (auto ims = req.find(http::field::if_modified_since);
ims != req.end() && ims->value() == lastModified) {
respond(http::status::not_modified, contentType(path), "",
cache, lastModified);
return !ec && req.keep_alive();
}
}
respond(http::status::ok, contentType(path), std::move(*contents),
cache, lastModified);
return !ec && req.keep_alive();
}
} // namespace Echoion::Web