#include "echoion/web/HttpServer.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace Echoion::Web { 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; } struct ProxyUrl { std::string url; std::string scheme; std::string host; }; std::optional parseProxyUrl(std::string url) { const auto schemeEnd = url.find("://"); if (schemeEnd == std::string::npos) { return std::nullopt; } const std::string scheme = url.substr(0, schemeEnd); if (scheme != "https" && scheme != "http") { return std::nullopt; } const auto authorityStart = schemeEnd + 3; const auto authorityEnd = url.find_first_of("/?#", authorityStart); std::string authority = url.substr(authorityStart, authorityEnd == std::string::npos ? std::string::npos : authorityEnd - authorityStart); if (authority.empty() || authority.find('@') != std::string::npos) { return std::nullopt; } if (const auto colon = authority.rfind(':'); colon != std::string::npos) { authority.resize(colon); } for (char& c : authority) { c = static_cast(std::tolower(c)); } const auto domain = [&](std::string_view base) { return authority == base || (authority.size() > base.size() && authority.ends_with(base) && authority[authority.size() - base.size() - 1] == '.'); }; const bool allowed = domain("kodik.info") || domain("kodik.cc") || domain("kodik.biz") || domain("kodik.online") || domain("kodikplayer.com") || domain("alloha.tv") || domain("alloha.video") || domain("alloha.online") || domain("allarknow.online"); if (!allowed) { return std::nullopt; } return ProxyUrl{std::move(url), scheme, std::move(authority)}; } bool isPrivateAddress(const asio::ip::address& address) { if (address.is_loopback() || address.is_unspecified() || address.is_multicast()) { return true; } if (address.is_v4()) { const auto bytes = address.to_v4().to_bytes(); return bytes[0] == 10 || bytes[0] == 127 || (bytes[0] == 169 && bytes[1] == 254) || (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) || (bytes[0] == 192 && bytes[1] == 168) || bytes[0] == 0; } const auto bytes = address.to_v6().to_bytes(); return (bytes[0] & 0xfe) == 0xfc || (bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80); } void absolutizeRootReferences(std::string& html, std::string_view origin) { // Kodik uses root-relative URLs both in tag attributes and inline // JavaScript. A element cannot affect fetch("/...") and was // observed to be ignored for already-tokenized tags, so rewrite // every quoted single-slash reference before returning the // document. for (std::size_t i = 0; i + 2 < html.size(); ++i) { if ((html[i] != '\'' && html[i] != '"') || html[i + 1] != '/' || html[i + 2] == '/') { continue; } html.insert(i + 1, origin); i += origin.size(); } } constexpr std::string_view kPlayerBridge = R"JS()JS"; // 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(); } 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(POOL_SIZE); watch_.setSender([this](uint64_t connId, const std::string& json) { sendToWatcher(connId, json); }); serverThread_ = std::thread(&HttpServer::acceptLoop, this); syncThread_ = std::jthread([this](std::stop_token st) { syncLoop(st); }); // 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(); // Stop the heartbeat first so it can't write to sockets we close. syncThread_ = std::jthread{}; { std::lock_guard lock(watchersMutex_); for (auto& [id, ws] : watchers_) { // Leave rooms properly so they pause/persist instead of // keeping ghost participants across a stop()/start(). watch_.onDisconnect(id); if (ws->is_open()) { beast::error_code ec; ws->close(websocket::close_code::normal, ec); } } watchers_.clear(); } // 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; // 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 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 (req.target() != "/ws") { return; // /ws (watch) and /rpc (bridge) only } auto ws = std::make_shared>( std::move(*socket)); ws->accept(req, ec); if (ec) { Void::Log::debug("HttpServer", "{}", std::format("Watch handshake failed: {}", ec.message())); return; } handleWatch(ws); return; } if (!serveHttp(*socket, req)) { return; } } } 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 // 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 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)); } void HttpServer::handleWatch( std::shared_ptr> ws) { const uint64_t connId = nextConnId_++; { std::lock_guard lock(watchersMutex_); watchers_[connId] = ws; } watch_.onConnect(connId); beast::flat_buffer buffer; while (running_.load() && ws->is_open()) { beast::error_code ec; ws->read(buffer, ec); if (ec == websocket::error::closed || ec) { break; } std::string message = beast::buffers_to_string(buffer.data()); buffer.consume(buffer.size()); watch_.onMessage(connId, message); } watch_.onDisconnect(connId); { std::lock_guard lock(watchersMutex_); watchers_.erase(connId); } } bool HttpServer::serveHttp(asio::ip::tcp::socket& socket, const http::request& 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 = {}) { 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); } 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(config_.rpcPort)}}, {"nowPlayingVideo", Value{config_.nowPlayingVideo}}}))); 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 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(); } // Custom emoji images, resolved through Core's provider (emoji DB). constexpr std::string_view kEmojiPrefix = "/emoji/"; if (target.starts_with(kEmojiPrefix)) { const std::string name = urlDecode(target.substr(kEmojiPrefix.size())); EmojiProvider provider; { std::lock_guard lock(avatarProviderMutex_); provider = emojiProvider_; } if (!name.empty() && provider) { if (auto image = provider(name)) { respond(http::status::ok, image->contentType, std::move(image->bytes), "public, max-age=86400"); return !ec && req.keep_alive(); } } 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(); } bool HttpServer::serveWatchProxy(asio::ip::tcp::socket& socket, const http::request& req) { beast::error_code ec; auto fail = [&](http::status status, std::string body) { http::response res{status, req.version()}; res.set(http::field::server, "Echoion"); res.set(http::field::content_type, "text/plain; charset=utf-8"); res.set(http::field::cache_control, "no-store"); res.keep_alive(req.keep_alive()); res.body() = std::move(body); res.prepare_payload(); http::write(socket, res, ec); return !ec && req.keep_alive(); }; if (req.method() != http::verb::get && req.method() != http::verb::head) { return fail(http::status::method_not_allowed, "Method Not Allowed"); } const std::string target(req.target()); const auto marker = target.find("url="); if (marker == std::string::npos) { return fail(http::status::bad_request, "Missing upstream URL"); } std::string encoded = target.substr(marker + 4); if (const auto amp = encoded.find('&'); amp != std::string::npos) { encoded.resize(amp); } auto upstream = parseProxyUrl(urlDecode(encoded)); if (!upstream) { return fail(http::status::forbidden, "Provider is not allowlisted"); } // Resolve and inspect every address before connecting. Redirects are // not followed; the browser must request the validated destination // anew. asio::io_context resolverContext; asio::ip::tcp::resolver resolver(resolverContext); boost::system::error_code resolveEc; const auto endpoints = resolver.resolve( upstream->host, upstream->scheme == "https" ? "443" : "80", resolveEc); if (resolveEc || endpoints.empty()) { return fail(http::status::bad_gateway, "Provider lookup failed"); } for (const auto& endpoint : endpoints) { if (isPrivateAddress(endpoint.endpoint().address())) { return fail(http::status::forbidden, "Private upstream denied"); } } Void::Net::HttpClient client; client.set_verify_tls(true); client.set_max_redirects(0); client.set_max_body_size(32ull * 1024 * 1024); Void::Net::Request upstreamReq; upstreamReq.method = req.method() == http::verb::head ? Void::Net::Method::Head : Void::Net::Method::Get; upstreamReq.url = upstream->url; upstreamReq.timeout = std::chrono::seconds{15}; if (const auto range = req.find(http::field::range); range != req.end()) { upstreamReq.headers.push_back( {"Range", std::string(range->value())}); } upstreamReq.headers.push_back({"Access-Control-Allow-Origin", "*"}); auto fetched = client.send(upstreamReq); if (!fetched) { return fail(http::status::bad_gateway, "Provider request failed"); } if (fetched->status >= 300 && fetched->status < 400) { return fail(http::status::bad_gateway, "Provider redirect requires allowlist validation"); } std::string body = std::move(fetched->body); std::string contentType = fetched->header("Content-Type") .transform([](std::string_view value) { return std::string(value); }) .value_or("application/octet-stream"); if (contentType.starts_with("text/html")) { const std::string origin = std::format("{}://{}", upstream->scheme, upstream->host); absolutizeRootReferences(body, origin); const std::string base = std::format("", upstream->url); // The base must precede provider CSS/JS tags. Appending it at // is too late: the HTML parser has already resolved // /assets/* against Echoion, producing 404s and leaving the player // unstyled/unbooted. if (const auto openHead = body.find("', openHead); body.insert(end == std::string::npos ? openHead : end + 1, base); } else { body.insert(0, base); } const auto closeHead = body.find(""); body.insert(closeHead == std::string::npos ? 0 : closeHead, std::string(kPlayerBridge)); } http::response res{ static_cast(fetched->status), req.version()}; res.set(http::field::server, "Echoion"); res.set(http::field::content_type, contentType); res.set(http::field::cache_control, "no-store"); res.set("X-Content-Type-Options", "nosniff"); for (const auto name : {"Accept-Ranges", "Content-Range"}) { if (auto value = fetched->header(name)) { res.set(name, *value); } } res.keep_alive(req.keep_alive()); const auto bodySize = body.size(); if (req.method() != http::verb::head) { res.body() = std::move(body); } res.content_length(bodySize); http::write(socket, res, ec); return !ec && req.keep_alive(); } void HttpServer::sendToWatcher(uint64_t connId, const std::string& json) { std::lock_guard lock(watchersMutex_); auto it = watchers_.find(connId); if (it == watchers_.end() || !it->second->is_open()) { return; } beast::error_code ec; it->second->text(true); it->second->write(asio::buffer(json), ec); } void HttpServer::syncLoop(std::stop_token stopToken) { using namespace std::chrono_literals; while (!stopToken.stop_requested() && running_.load()) { // Sleep in short slices so stop() is prompt. for (int i = 0; i < 30 && !stopToken.stop_requested() && running_.load(); ++i) { std::this_thread::sleep_for(100ms); } if (stopToken.stop_requested() || !running_.load()) { break; } watch_.broadcastSync(); } } } // namespace Echoion::Web