Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:48 +03:00
1 parent 639362fbf5
commit bdd69f0aad
101 files changed
+22691 -531

No files matched your search

+199 -39
View File
@@ -12,6 +12,10 @@
#include <sstream>
#include <string_view>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/socket.h>
#endif
namespace Echoion::Web
{
namespace websocket = beast::websocket;
@@ -114,19 +118,77 @@ namespace Echoion::Web
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<std::string>& 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<std::string>& 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_.exchange(true)) {
if (running_.load()) {
return false;
}
config_ = config;
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(
@@ -272,26 +334,79 @@ namespace Echoion::Web
{
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)) {
// 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<http::string_body> 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<http::string_body> 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<http::string_body>& req) const
{
boost::system::error_code error;
const auto endpoint = socket.remote_endpoint(error);
if (error) {
return {};
}
std::optional<std::string_view> 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<asio::ip::tcp::socket> browser,
@@ -315,25 +430,10 @@ namespace Echoion::Web
// 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.
// 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");
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();
}
}
const std::string clientIp = clientAddress(*browser, req);
if (!clientIp.empty()) {
req.set("X-Echoion-Client-Ip", clientIp);
}
@@ -373,7 +473,8 @@ namespace Echoion::Web
}
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req)
const http::request<http::string_body>& req,
std::string_view requestAddress)
{
beast::error_code ec;
const bool isHead = req.method() == http::verb::head;
@@ -398,7 +499,7 @@ namespace Echoion::Web
if (!location.empty()) {
res.set(http::field::location, location);
}
res.keep_alive(req.keep_alive());
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());
@@ -468,6 +569,65 @@ namespace Echoion::Web
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<http::string_body> 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