#include "echoion/web/HttpServer.hpp" #include #include #include #include #include #include #include #include #include #include #if defined(__unix__) || defined(__APPLE__) #include #endif 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 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(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 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(); } HttpServer::TrustedProxyUpdate HttpServer::validateTrustedProxyCidrs( const std::vector& cidrs) { try { auto parsed = Security::parseTrustedProxyCidrs(cidrs); if (!parsed) { return std::unexpected(std::move(parsed.error())); } return {}; } catch (const std::exception& exception) { return std::unexpected( std::format("failed to validate trusted proxy CIDRs: {}", exception.what())); } } HttpServer::TrustedProxyUpdate HttpServer::setTrustedProxyCidrs(const std::vector& cidrs) { try { auto parsed = Security::parseTrustedProxyCidrs(cidrs); if (!parsed) { return std::unexpected(std::move(parsed.error())); } { std::unique_lock lock(trustedProxyMutex_); // A trust-policy change changes the peer identity used by the // limiter. Reset while new address calculations are blocked, // then publish the already-parsed policy with a no-throw swap. shortLinkRateLimiter_.reset(); trustedProxyNetworks_.swap(*parsed); } return {}; } catch (const std::exception& exception) { return std::unexpected(std::format( "failed to update trusted proxy CIDRs: {}", exception.what())); } } bool HttpServer::start(const Config& config) { if (running_.load()) { return false; } try { auto trustedProxies = Security::parseTrustedProxyCidrs(config.trustedProxyCidrs); if (!trustedProxies) { Void::Log::error( "HttpServer", "{}", std::format("Failed to start web interface: {}", trustedProxies.error())); return false; } bool expected = false; if (!running_.compare_exchange_strong(expected, true)) { return false; } config_ = config; { std::unique_lock lock(trustedProxyMutex_); trustedProxyNetworks_ = std::move(*trustedProxies); } shortLinkRateLimiter_.reset(); 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(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 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(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(std::move(socket)); if (pool_) { pool_->submit([this, held]() { handleConnection(held); }); } } void HttpServer::handleConnection( std::shared_ptr socket) { beast::error_code ec; beast::flat_buffer buffer; // Bound slow clients and parser memory. Every accepted connection // serves exactly one request; browsers simply open another connection. #if defined(__unix__) || defined(__APPLE__) timeval timeout{.tv_sec = 5, .tv_usec = 0}; (void)::setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); #endif http::request_parser parser; parser.header_limit(32 * 1024); parser.body_limit(0); http::read(*socket, buffer, parser, ec); if (ec) { return; } auto req = parser.release(); for (const auto& field : req) { if (field.name_string().size() + field.value().size() > 8 * 1024) { http::response response{ http::status::request_header_fields_too_large, req.version()}; response.set(http::field::server, "Echoion"); response.body() = "Request Header Fields Too Large"; response.prepare_payload(); response.keep_alive(false); http::write(*socket, response, ec); return; } } if (websocket::is_upgrade(req)) { if (req.target() == "/rpc") { bridgeRpc(socket, req, buffer); } return; } (void)serveHttp(*socket, req, clientAddress(*socket, req)); } std::string HttpServer::clientAddress( const asio::ip::tcp::socket& socket, const http::request& req) const { boost::system::error_code error; const auto endpoint = socket.remote_endpoint(error); if (error) { return {}; } std::optional forwardedFor; for (const auto& field : req) { if (!beast::iequals(field.name_string(), "X-Forwarded-For")) { continue; } // Multiple field-lines have ambiguous intermediary semantics. // Ignore all of them instead of choosing an attacker-controlled // value. if (forwardedFor) { forwardedFor.reset(); break; } forwardedFor = std::string_view{field.value().data(), field.value().size()}; } std::shared_lock lock(trustedProxyMutex_); return Security::effectiveClientAddress( endpoint.address(), forwardedFor, trustedProxyNetworks_); } bool HttpServer::allowShortLinkRequest(std::string_view peer) { return shortLinkRateLimiter_.allow(peer); } void HttpServer::bridgeRpc(std::shared_ptr browser, http::request& req, beast::flat_buffer& residual) { boost::system::error_code ec; auto upstream = std::make_shared(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 // X-Forwarded-For is accepted only from configured proxies and walked // from right to left, stopping at the nearest untrusted hop. req.erase("X-Echoion-Client-Ip"); const std::string clientIp = clientAddress(*browser, req); 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 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 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& req, std::string_view requestAddress) { 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 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(false); // 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(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 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(); } constexpr std::string_view kShortPrefix = "/s/"; if (target.starts_with(kShortPrefix)) { const std::string key = target.substr(kShortPrefix.size()); if (!Security::validShortSlug(key)) { respond(http::status::not_found, "text/plain", "Not Found", "no-store"); return false; } if (!allowShortLinkRequest(requestAddress)) { respond(http::status::too_many_requests, "text/plain", "Too Many Requests", "no-store"); return false; } ShortLinkResolver resolver; { std::lock_guard lock(shortLinkResolverMutex_); resolver = shortLinkResolver_; } const auto resolution = resolver ? resolver(key) : ShortLinkResolution{.status = ShortLinkStatus::unavailable, .location = {}}; http::status status = http::status::not_found; switch (resolution.status) { case ShortLinkStatus::found: status = http::status::found; break; case ShortLinkStatus::gone: status = http::status::gone; break; case ShortLinkStatus::rateLimited: status = http::status::too_many_requests; break; case ShortLinkStatus::unavailable: status = http::status::service_unavailable; break; case ShortLinkStatus::notFound: break; } http::response response{status, req.version()}; response.set(http::field::server, "Echoion"); response.set(http::field::cache_control, "no-store"); response.set("Referrer-Policy", "no-referrer"); response.set("X-Robots-Tag", "noindex, nofollow"); response.set("X-Content-Type-Options", "nosniff"); response.set("Content-Security-Policy", "default-src 'none'"); if (status == http::status::found && Security::validRedirectLocation(resolution.location)) { response.set(http::field::location, resolution.location); } else if (status == http::status::found) { response.result(http::status::service_unavailable); } response.content_length(0); response.keep_alive(false); http::write(socket, response, ec); return false; } // 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 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(ftime); lastModified = std::format("{:%a, %d %b %Y %H:%M:%S} GMT", std::chrono::floor(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