1 parent
1c96d5973b
commit
e80dbc2fda
38 files changed
+1352
-6335
No files matched your search
+44
-348
@@ -2,10 +2,9 @@
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
@@ -15,6 +14,8 @@
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
namespace websocket = beast::websocket;
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string_view contentType(const std::filesystem::path& path)
|
||||
@@ -91,105 +92,6 @@ namespace Echoion::Web
|
||||
return out;
|
||||
}
|
||||
|
||||
struct ProxyUrl {
|
||||
std::string url;
|
||||
std::string scheme;
|
||||
std::string host;
|
||||
};
|
||||
|
||||
std::optional<ProxyUrl> 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<char>(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 <base> 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(<script data-echoion-bridge>
|
||||
(()=>{if(window.__echoionBridge)return;window.__echoionBridge=1;
|
||||
const send=(event,answer)=>parent.postMessage({event,answer},'*');
|
||||
const label=e=>(e.getAttribute('aria-label')||e.name||e.id||e.closest('label')?.textContent||'').toLowerCase();
|
||||
const kind=e=>{const s=label(e);if(/quality|качест/.test(s))return'qualities';if(/audio|voice|озвуч|перевод/.test(s))return'audiotracks';if(/subtitle|субтит/.test(s))return'subtitles';if(/episode|сер/.test(s))return'episodes';return''};
|
||||
const scan=()=>document.querySelectorAll('select').forEach(e=>{const k=kind(e);if(!k)return;send(k,[...e.options].map((o,i)=>({value:o.value||String(i),label:o.textContent||o.value})));if(!e.dataset.echoionBound){e.dataset.echoionBound='1';e.addEventListener('change',()=>send(k.replace(/ies$/,'y').replace(/s$/,''),e.value))}});
|
||||
const video=()=>document.querySelector('video');
|
||||
addEventListener('message',e=>{const m=e.data||{};if(!m.api)return;const v=video();if(m.api==='play')v?.play();else if(m.api==='pause')v?.pause();else if(m.api==='seek'&&v)v.currentTime=Number(m.set)||0;else if(m.api==='volume'&&v)v.volume=Math.max(0,Math.min(1,Number(m.set)));else if(m.api==='speed'&&v)v.playbackRate=Number(m.set)||1;else{document.querySelectorAll('select').forEach(s=>{const k=kind(s);const id=k==='qualities'?'quality':k==='audiotracks'?'audiotrack':k==='subtitles'?'subtitle':k==='episodes'?'episode':'';if(id===m.api){s.value=String(m.set);s.dispatchEvent(new Event('change',{bubbles:true}))}})}});
|
||||
const bind=()=>{const v=video();if(!v||v.dataset.echoionBound)return;v.dataset.echoionBound='1';v.addEventListener('play',()=>send('play'));v.addEventListener('pause',()=>send('pause'));v.addEventListener('ended',()=>send('ended'));v.addEventListener('timeupdate',()=>send('time',v.currentTime));send('duration',v.duration)};
|
||||
new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subtree:true,childList:true});setInterval(()=>{bind();scan()},1500);send('ready');})();
|
||||
</script>)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,
|
||||
@@ -237,13 +139,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
|
||||
pool_ = std::make_unique<Void::Concurrency::ThreadPool>(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.
|
||||
@@ -285,23 +181,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
}
|
||||
ioContext_.stop();
|
||||
|
||||
// Stop the heartbeat first so it can't write to sockets we close.
|
||||
syncThread_ = std::jthread{};
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lock(bridgesMutex_);
|
||||
@@ -405,22 +284,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
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<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(*socket));
|
||||
ws->accept(req, ec);
|
||||
if (ec) {
|
||||
Void::Log::debug("HttpServer", "{}",
|
||||
std::format("Watch handshake failed: {}",
|
||||
ec.message()));
|
||||
return;
|
||||
}
|
||||
handleWatch(ws);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -508,35 +372,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
std::format("RPC bridge {} closed", connId));
|
||||
}
|
||||
|
||||
void HttpServer::handleWatch(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
|
||||
{
|
||||
const uint64_t connId = nextConnId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lock(watchersMutex_);
|
||||
watchers_.erase(connId);
|
||||
}
|
||||
}
|
||||
|
||||
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req)
|
||||
{
|
||||
@@ -545,7 +380,9 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
|
||||
auto respond = [&](http::status status, std::string_view type,
|
||||
std::string body, std::string_view cacheControl = {},
|
||||
std::string_view lastModified = {}) {
|
||||
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);
|
||||
@@ -555,6 +392,12 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
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(
|
||||
@@ -589,10 +432,42 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
{{"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
|
||||
@@ -630,28 +505,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
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<std::mutex> 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";
|
||||
}
|
||||
@@ -699,161 +552,4 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
|
||||
return !ec && req.keep_alive();
|
||||
}
|
||||
|
||||
bool
|
||||
HttpServer::serveWatchProxy(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req)
|
||||
{
|
||||
beast::error_code ec;
|
||||
auto fail = [&](http::status status, std::string body) {
|
||||
http::response<http::string_body> 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("<base href=\"{}\">", upstream->url);
|
||||
// The base must precede provider CSS/JS tags. Appending it at
|
||||
// </head> 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("<head");
|
||||
openHead != std::string::npos) {
|
||||
const auto end = body.find('>', openHead);
|
||||
body.insert(end == std::string::npos ? openHead : end + 1,
|
||||
base);
|
||||
} else {
|
||||
body.insert(0, base);
|
||||
}
|
||||
const auto closeHead = body.find("</head>");
|
||||
body.insert(closeHead == std::string::npos ? 0 : closeHead,
|
||||
std::string(kPlayerBridge));
|
||||
}
|
||||
|
||||
http::response<http::string_body> res{
|
||||
static_cast<http::status>(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<std::mutex> 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
|
||||
Reference in new issue
Block a user