From 914eb0a2328f7b4fab4d0d3bfb408ef2588c17b2 Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 22 Jun 2026 16:35:11 +0300 Subject: [PATCH] Rewrite NetworkClient as a Void::Net::HttpClient adapter Replace the ~700-line hand-rolled HTTP stack (Boost.Beast/Asio client, URL parsing, HTTP-CONNECT + SOCKS5 proxy handshakes, a bespoke 4-thread packaged_task pool) with a thin adapter over Void::Net::HttpClient that still implements Api::INetworkClient. Translates Api::HttpRequest/Response/ ProxyConfig <-> Void::Net types; retry/backoff stays on Void::Retry; async methods use std::async. Link Void::Net. Co-Authored-By: Claude Opus 4.8 --- CMakeLists.txt | 1 + include/echoion/core/NetworkClient.hpp | 144 +--- src/NetworkClient.cpp | 938 ++++--------------------- 3 files changed, 143 insertions(+), 940 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 42c5cc3..6d07387 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -105,6 +105,7 @@ target_link_libraries(EchoionCore Void::Text Void::Time Void::Math + Void::Net PRIVATE Threads::Threads qjs diff --git a/include/echoion/core/NetworkClient.hpp b/include/echoion/core/NetworkClient.hpp index a3f7817..71ffd58 100644 --- a/include/echoion/core/NetworkClient.hpp +++ b/include/echoion/core/NetworkClient.hpp @@ -1,28 +1,24 @@ #pragma once -#include "boost/asio/ssl/context.hpp" #include #include #include #include #include #include -#include +#include #include #include -#include -#include - -// Boost.Beast includes needed for template function -#include -#include +#include +#include +#include namespace Echoion::Core { - // Forward declaration for URL parsing - struct UrlComponents; - + // HTTP client implementing Api::INetworkClient. A thin adapter over + // Void::Net::HttpClient (HTTP/HTTPS, TLS, SOCKS5 + HTTP-CONNECT proxies); + // retry/backoff is layered here via Void::Retry. class NetworkClient : public Api::INetworkClient { public: @@ -30,7 +26,6 @@ namespace Echoion::Core NetworkClient(); ~NetworkClient() override; - // Initialize with optional proxy Api::Result initialize( const std::optional& proxy = std::nullopt); void shutdown(); @@ -86,9 +81,17 @@ namespace Echoion::Core return parseJson(response->bodyAsString()); } + // Proxy configuration + void setProxy(const std::optional& proxy); + [[nodiscard]] std::optional getProxy() const; + void clearProxy(); + + // Retry configuration + void setRetryConfig(const Api::RetryConfig& config); + [[nodiscard]] Api::RetryConfig getRetryConfig() const; + private: - // Parse a response body into a reflectable type T via Void::Json. template [[nodiscard]] static Api::Result parseJson(const std::string& body) @@ -111,128 +114,17 @@ namespace Echoion::Core return std::move(*value); } - public: - - // Proxy configuration - void setProxy(const std::optional& proxy); - [[nodiscard]] std::optional getProxy() const; - void clearProxy(); - - // Retry configuration - void setRetryConfig(const Api::RetryConfig& config); - [[nodiscard]] Api::RetryConfig getRetryConfig() const; - - private: - - // Request execution + // Execute with retry/backoff (Void::Retry); single attempt via + // Void::Net::HttpClient. [[nodiscard]] Api::Result executeWithRetry(const Api::HttpRequest& req); [[nodiscard]] Api::Result executeRequest(const Api::HttpRequest& req); - // Proxy and direct execution methods - [[nodiscard]] Api::HttpResponse - executeWithProxy(boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout); - - [[nodiscard]] Api::HttpResponse - executeWithHttpProxy(boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout); - - [[nodiscard]] Api::HttpResponse - executeWithSocks5Proxy(boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout); - - [[nodiscard]] Api::HttpResponse - executeDirect(boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - std::chrono::seconds timeout); - - // HTTP request methods - // Note: sendHttpsRequest is a template, implemented in header below - template - [[nodiscard]] Api::HttpResponse - sendHttpsRequest(Stream& stream, - const UrlComponents& urlComp, - const Api::HttpRequest& req); - - [[nodiscard]] Api::HttpResponse - sendHttpRequest(boost::asio::ip::tcp::socket& socket, - const UrlComponents& urlComp, - const Api::HttpRequest& req); - - [[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy( - boost::asio::ip::tcp::socket& socket, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy); - - // Request/Response building - [[nodiscard]] boost::beast::http::request< - boost::beast::http::string_body> - buildBeastRequest(const UrlComponents& urlComp, - const Api::HttpRequest& req); - - [[nodiscard]] Api::HttpResponse convertBeastResponse( - const boost::beast::http::response< - boost::beast::http::dynamic_body>& beastResponse); - - [[nodiscard]] std::vector - addDefaultHeaders(const std::vector& headers); - std::optional proxy_; Api::RetryConfig retryConfig_; mutable std::mutex mutex_; std::atomic initialized_{false}; - std::atomic requestId_{0}; - - // Thread pool for async operations - std::vector threadPool_; - std::queue()>> - taskQueue_; - std::mutex taskMutex_; - std::condition_variable taskCv_; - std::atomic stopThreads_{false}; - static constexpr size_t THREAD_POOL_SIZE = 4; }; - // Template implementation for sendHttpsRequest - template - Api::HttpResponse - NetworkClient::sendHttpsRequest(Stream& stream, - const UrlComponents& urlComp, - const Api::HttpRequest& req) - { - namespace http = boost::beast::http; - - // Build request - http::request request = - buildBeastRequest(urlComp, req); - - // Send - http::write(stream, request); - - // Read response - boost::beast::flat_buffer buffer; - http::response response; - http::read(stream, buffer, response); - - // Convert to Api::HttpResponse - return convertBeastResponse(response); - } - } // namespace Echoion::Core diff --git a/src/NetworkClient.cpp b/src/NetworkClient.cpp index d2d0a88..954ec4d 100644 --- a/src/NetworkClient.cpp +++ b/src/NetworkClient.cpp @@ -1,129 +1,58 @@ -#include "boost/beast/core/buffers_to_string.hpp" #include "echoion/core/Logger.hpp" #include "echoion/core/NetworkClient.hpp" #include +#include #include -#include #include -// Boost.Beast for HTTP with proxy support -#include -#include -#include -#include -#include - namespace Echoion::Core { - - namespace asio = boost::asio; - namespace beast = boost::beast; - namespace http = boost::beast::http; - namespace ssl = boost::asio::ssl; - namespace urls = boost::urls; - - // Simple base64 encoding for proxy authentication - namespace base64 + namespace { - static const std::string chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - std::string encode(const std::string& input) + [[nodiscard]] Void::Net::Method to_void_method(Api::HttpMethod m) { - std::string encoded; - encoded.reserve(((input.size() + 2) / 3) * 4); - - int val = 0, valb = -6; - for (unsigned char c : input) { - val = (val << 8) + c; - valb += 8; - while (valb >= 0) { - encoded.push_back(chars[(val >> valb) & 0x3F]); - valb -= 6; - } + switch (m) { + case Api::HttpMethod::GET: return Void::Net::Method::Get; + case Api::HttpMethod::POST: return Void::Net::Method::Post; + case Api::HttpMethod::PUT: return Void::Net::Method::Put; + case Api::HttpMethod::DELETE: return Void::Net::Method::Delete; + case Api::HttpMethod::PATCH: return Void::Net::Method::Patch; + case Api::HttpMethod::HEAD: return Void::Net::Method::Head; + case Api::HttpMethod::OPTIONS: return Void::Net::Method::Options; } - - if (valb > -6) { - encoded.push_back(chars[((val << 8) >> (valb + 8)) & 0x3F]); - } - - while (encoded.size() % 4) { - encoded.push_back('='); - } - - return encoded; + return Void::Net::Method::Get; } - } // namespace base64 - // Helper to perform URL encoding - std::string urlEncode(std::string_view value) - { - std::string encoded; - encoded.reserve(value.size() * 3); - for (unsigned char c : value) { - if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || - c == '~') { - encoded += c; - } else { - encoded += std::format("%{:02X}", c); - } + [[nodiscard]] Void::Net::ProxyConfig + to_void_proxy(const Api::ProxyConfig& p) + { + Void::Net::ProxyConfig out; + out.kind = p.isSocks5() ? Void::Net::ProxyConfig::Kind::Socks5 + : Void::Net::ProxyConfig::Kind::Http; + out.host = p.host; + out.port = p.port; + out.username = p.username; + out.password = p.password; + return out; } - return encoded; - } - // Helper to parse URL into components - struct UrlComponents { - std::string protocol; - std::string host; - std::string port; - std::string path; - std::string query; - bool isHttps; - }; - - std::optional parseUrl(std::string_view url) - { - try { - auto result = urls::parse_uri(url); - if (!result) { - return std::nullopt; + [[nodiscard]] Api::HttpResponse + to_api_response(Void::Net::Response&& r) + { + Api::HttpResponse out; + out.statusCode = static_cast(r.status); + out.responseTime = r.elapsed; + out.body = std::move(r.body); + out.headers.reserve(r.headers.size()); + for (auto& h : r.headers) { + out.headers.emplace_back(std::move(h.name), + std::move(h.value)); } - - const auto& uri = *result; - UrlComponents comp; - comp.protocol = std::string(uri.scheme()); - comp.host = std::string(uri.host()); - comp.isHttps = (comp.protocol == "https"); - - // Set default port - if (uri.port().empty()) { - comp.port = comp.isHttps ? "443" : "80"; - } else { - comp.port = std::string(uri.port()); - } - - // Build path (use encoded path to preserve percent-encoding) - comp.path = std::string(uri.encoded_path()); - if (comp.path.empty()) { - comp.path = "/"; - } - - // Add query if present (use encoded query to preserve - // percent-encoding) - if (!uri.query().empty()) { - comp.query = std::string(uri.encoded_query()); - comp.path += "?" + comp.query; - } - - return comp; - } catch (const std::exception& e) { - ECHOION_LOG_ERROR(std::format("URL parse error: {}", e.what())); - return std::nullopt; + return out; } - } + } // namespace NetworkClient::NetworkClient() = default; - NetworkClient::~NetworkClient() { shutdown(); } Api::Result @@ -131,58 +60,90 @@ namespace Echoion::Core { proxy_ = proxy; initialized_ = true; - - // Initialize thread pool - for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) { - threadPool_.emplace_back([this] { - while (!stopThreads_.load()) { - std::packaged_task()> task; - { - std::unique_lock lock(taskMutex_); - taskCv_.wait(lock, [this] { - return !taskQueue_.empty() || stopThreads_.load(); - }); - if (stopThreads_.load() && taskQueue_.empty()) { - return; - } - task = std::move(taskQueue_.front()); - taskQueue_.pop(); - } - task(); - } - }); - } - - ECHOION_LOG_INFO( - std::format("NetworkClient initialized (proxy: {})", - proxy.has_value() ? "enabled" : "disabled")); + ECHOION_LOG_INFO(std::format("NetworkClient initialized (proxy: {})", + proxy.has_value() ? "enabled" : "disabled")); return {}; } - void NetworkClient::shutdown() + void NetworkClient::shutdown() { initialized_ = false; } + + Api::Result NetworkClient::executeRequest( + const Api::HttpRequest& req) { - stopThreads_ = true; - taskCv_.notify_all(); - for (auto& thread : threadPool_) { - if (thread.joinable()) { - thread.join(); - } + Void::Net::HttpClient client; + const auto active = req.proxy.has_value() ? req.proxy : proxy_; + if (active && active->isValid()) { + client.set_proxy(to_void_proxy(*active)); } - threadPool_.clear(); - initialized_ = false; - ECHOION_LOG_INFO("NetworkClient shutdown"); + + Void::Net::Request vreq; + vreq.method = to_void_method(req.method); + vreq.url = req.url; + vreq.timeout = + std::chrono::duration_cast(req.timeout); + for (const auto& h : req.headers) { + vreq.headers.push_back({h.name, h.value}); + } + if (req.body) { + vreq.body = std::string(req.body->begin(), req.body->end()); + } + + auto result = client.send(vreq); + if (!result) { + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + result.error().message())); + } + return to_api_response(std::move(*result)); + } + + Api::Result NetworkClient::executeWithRetry( + const Api::HttpRequest& req) + { + const Void::Retry::Policy policy{ + .max_attempts = + static_cast(retryConfig_.maxRetries) + 1, + .backoff = Void::Retry::ExponentialBackoff{ + .base = retryConfig_.initialDelay, + .max = retryConfig_.maxDelay, + .multiplier = + static_cast(retryConfig_.backoffMultiplier)}}; + + return Void::Retry::retry_while( + policy, [&] { return executeRequest(req); }, + [this](const Api::Result& result) { + if (!result) { + ECHOION_LOG_WARNING(std::format( + "Request error: {}, retrying", result.error().message)); + return true; + } + if (result->isError()) { + const auto& codes = retryConfig_.retryableStatusCodes; + if (std::find(codes.begin(), codes.end(), + result->statusCode) != codes.end()) { + ECHOION_LOG_WARNING(std::format( + "Request failed with status {}, retrying", + result->statusCode)); + return true; + } + } + return false; + }); + } + + Api::Result + NetworkClient::request(const Api::HttpRequest& req) + { + return executeWithRetry(req); } Api::Result NetworkClient::get(std::string_view url, const std::vector& headers) { - Api::HttpRequest req; req.url = std::string(url); req.method = Api::HttpMethod::GET; - req.headers = addDefaultHeaders(headers); - req.proxy = proxy_; + req.headers = headers; return request(req); } @@ -190,91 +151,56 @@ namespace Echoion::Core NetworkClient::post(std::string_view url, std::string_view body, const std::vector& headers) { - Api::HttpRequest req; req.url = std::string(url); req.method = Api::HttpMethod::POST; - req.headers = addDefaultHeaders(headers); + req.headers = headers; req.body = std::vector(body.begin(), body.end()); - req.proxy = proxy_; return request(req); } - Api::Result - NetworkClient::request(const Api::HttpRequest& req) - { - if (!initialized_) { - return std::unexpected( - Api::Error(Api::ErrorCode::ServiceUnavailable, - "NetworkClient not initialized")); - } - return executeWithRetry(req); - } - std::future> NetworkClient::getAsync(std::string_view url, const std::vector& headers) { - std::packaged_task()> task( - [this, urlStr = std::string(url), headers] { - return get(urlStr, headers); - }); - auto future = task.get_future(); - { - std::lock_guard lock(taskMutex_); - taskQueue_.push(std::move(task)); - } - taskCv_.notify_one(); - return future; + return std::async(std::launch::async, + [this, u = std::string(url), headers] { + return get(u, headers); + }); } std::future> NetworkClient::postAsync(std::string_view url, std::string_view body, const std::vector& headers) { - std::packaged_task()> task( - [this, urlStr = std::string(url), bodyStr = std::string(body), - headers] { return post(urlStr, bodyStr, headers); }); - auto future = task.get_future(); - { - std::lock_guard lock(taskMutex_); - taskQueue_.push(std::move(task)); - } - taskCv_.notify_one(); - return future; + return std::async(std::launch::async, + [this, u = std::string(url), + b = std::string(body), headers] { + return post(u, b, headers); + }); } std::future> NetworkClient::requestAsync(const Api::HttpRequest& req) { - std::packaged_task()> task( - [this, req] { return request(req); }); - auto future = task.get_future(); - { - std::lock_guard lock(taskMutex_); - taskQueue_.push(std::move(task)); - } - taskCv_.notify_one(); - return future; + return std::async(std::launch::async, + [this, req] { return request(req); }); } - std::vector> NetworkClient::requestBatch( - const std::vector& requests) + std::vector> + NetworkClient::requestBatch( + const std::vector& requests) { std::vector>> futures; futures.reserve(requests.size()); - for (const auto& req : requests) { futures.push_back(requestAsync(req)); } - std::vector> results; results.reserve(requests.size()); - - for (auto& future : futures) { - results.push_back(future.get()); + for (auto& f : futures) { + results.push_back(f.get()); } - return results; } @@ -282,8 +208,6 @@ namespace Echoion::Core { std::lock_guard lock(mutex_); proxy_ = proxy; - ECHOION_LOG_INFO(std::format( - "Proxy {}", proxy.has_value() ? "configured" : "cleared")); } std::optional NetworkClient::getProxy() const @@ -295,8 +219,7 @@ namespace Echoion::Core void NetworkClient::clearProxy() { std::lock_guard lock(mutex_); - proxy_.reset(); - ECHOION_LOG_INFO("Proxy cleared"); + proxy_ = std::nullopt; } void NetworkClient::setRetryConfig(const Api::RetryConfig& config) @@ -311,617 +234,4 @@ namespace Echoion::Core return retryConfig_; } - Api::Result - NetworkClient::executeWithRetry(const Api::HttpRequest& req) - { - // Total attempts = the initial try plus maxRetries follow-ups. - // ExponentialBackoff.delay(n) == initialDelay * multiplier^n (capped at - // maxDelay), matching the previous hand-rolled backoff exactly. - const Void::Retry::Policy policy{ - .max_attempts = - static_cast(retryConfig_.maxRetries) + 1, - .backoff = Void::Retry::ExponentialBackoff{ - .base = retryConfig_.initialDelay, - .max = retryConfig_.maxDelay, - .multiplier = - static_cast(retryConfig_.backoffMultiplier)}}; - - return Void::Retry::retry_while( - policy, [&] { return executeRequest(req); }, - [this](const Api::Result& result) { - if (!result) { - // Transport-level failure — always retry. - ECHOION_LOG_WARNING(std::format( - "Request error: {}, retrying", result.error().message)); - return true; - } - // Successful round-trip but a retryable HTTP status. - if (result->isError()) { - const auto& codes = retryConfig_.retryableStatusCodes; - if (std::find(codes.begin(), codes.end(), - result->statusCode) != codes.end()) { - ECHOION_LOG_WARNING( - std::format("Request failed with status {}, retrying", - result->statusCode)); - return true; - } - } - return false; - }); - } - - // Execute HTTP request using Boost.Beast with proxy support - Api::Result - NetworkClient::executeRequest(const Api::HttpRequest& req) - { - try { - auto start = std::chrono::steady_clock::now(); - - // Parse target URL - auto urlComp = parseUrl(req.url); - if (!urlComp) { - return std::unexpected(Api::Error(Api::ErrorCode::InvalidUrl, - "Failed to parse URL")); - } - - // Determine which proxy to use (request-specific or global) - std::optional activeProxy = - req.proxy.has_value() ? req.proxy : proxy_; - bool useProxy = activeProxy.has_value() && activeProxy->isValid(); - - // Setup IO context - asio::io_context ioc; - ssl::context ctx(ssl::context::tlsv12_client); - ctx.set_default_verify_paths(); - ctx.set_verify_mode(ssl::verify_none); - // Resolve timeout - auto timeout = std::chrono::seconds(req.timeout.count()); - - Api::HttpResponse response; - - if (useProxy) { - // Route to appropriate proxy handler based on proxy type - const auto& proxy = *activeProxy; - if (proxy.isSocks5()) { - response = executeWithSocks5Proxy(ioc, ctx, *urlComp, req, - proxy, timeout); - } else { - response = executeWithHttpProxy(ioc, ctx, *urlComp, req, - proxy, timeout); - } - } else { - // Direct connection - response = executeDirect(ioc, ctx, *urlComp, req, timeout); - } - - auto end = std::chrono::steady_clock::now(); - response.responseTime = - std::chrono::duration_cast(end - - start); - - return response; - - } catch (const std::exception& e) { - return std::unexpected( - Api::Error(Api::ErrorCode::NetworkError, - std::format("HTTP request failed: {}", e.what()))); - } - } - - // Execute request through HTTP proxy using CONNECT tunneling - Api::HttpResponse - NetworkClient::executeWithProxy(asio::io_context& ioc, - ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout) - { - // Dispatch to appropriate proxy handler - if (proxy.isSocks5()) { - return executeWithSocks5Proxy(ioc, ctx, urlComp, req, proxy, - timeout); - } else { - return executeWithHttpProxy(ioc, ctx, urlComp, req, proxy, timeout); - } - } - - // Execute request through HTTP proxy using CONNECT tunneling - Api::HttpResponse - NetworkClient::executeWithHttpProxy(asio::io_context& ioc, - ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout) - { - - // Create TCP socket for proxy connection - asio::ip::tcp::socket socket(ioc); - - // Resolve proxy address - asio::ip::tcp::resolver resolver(ioc); - auto proxyResults = - resolver.resolve(proxy.host, std::to_string(proxy.port)); - - // Connect to proxy - asio::connect(socket, proxyResults); - - std::string target = urlComp.host + ":" + urlComp.port; - - if (urlComp.isHttps) { - // For HTTPS: Send CONNECT request to establish tunnel - http::request connect_req(http::verb::connect, - target, 11); - connect_req.set(http::field::host, target); - - // Add proxy authentication if needed - if (proxy.requiresAuth()) { - std::string auth = - std::format("{}:{}", *proxy.username, *proxy.password); - std::string encoded = base64::encode(auth); - connect_req.set(http::field::proxy_authorization, - "Basic " + encoded); - } - - // Send CONNECT request - http::write(socket, connect_req); - - // Read CONNECT response - beast::flat_buffer buffer; - http::response connect_res; - http::read(socket, buffer, connect_res); - - if (connect_res.result() != http::status::ok) { - throw std::runtime_error( - std::format("Proxy CONNECT failed: {}", - static_cast(connect_res.result()))); - } - - // Upgrade socket to SSL - ssl::stream stream(std::move(socket), ctx); - // SSL verification mode is already set in ctx (verify_none) - - // Perform SSL handshake - stream.handshake(ssl::stream_base::client); - - // Send actual HTTPS request through tunnel - return sendHttpsRequest(stream, urlComp, req); - - } else { - // For HTTP: Proxy forwards the request - // Some proxies require absolute URL in the request line - return sendHttpRequestThroughProxy(socket, urlComp, req, proxy); - } - } - - // Execute request through SOCKS5 proxy - Api::HttpResponse - NetworkClient::executeWithSocks5Proxy(asio::io_context& ioc, - ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout) - { - - // Create TCP socket for proxy connection - asio::ip::tcp::socket socket(ioc); - - // Resolve proxy address - asio::ip::tcp::resolver resolver(ioc); - auto proxyResults = - resolver.resolve(proxy.host, std::to_string(proxy.port)); - - // Connect to SOCKS5 proxy - asio::connect(socket, proxyResults); - - // SOCKS5 handshake - // Step 1: Send greeting - std::vector greeting; - greeting.push_back(0x05); // SOCKS version 5 - - if (proxy.requiresAuth()) { - greeting.push_back(0x02); // 2 auth methods - greeting.push_back(0x00); // No auth - greeting.push_back(0x02); // Username/password auth - } else { - greeting.push_back(0x01); // 1 auth method - greeting.push_back(0x00); // No auth - } - - asio::write(socket, asio::buffer(greeting)); - - // Step 2: Receive server response - std::vector response(2); - asio::read(socket, asio::buffer(response)); - - if (response[0] != 0x05) { - throw std::runtime_error("SOCKS5 proxy: Invalid version"); - } - - // Step 3: Handle authentication if required - if (response[1] == 0x02) { - // Username/password authentication - if (!proxy.requiresAuth()) { - throw std::runtime_error( - "SOCKS5 proxy: Auth required but no credentials provided"); - } - - // Build auth request - std::vector authRequest; - authRequest.push_back(0x01); // Auth version - authRequest.push_back(static_cast(proxy.username->size())); - authRequest.insert(authRequest.end(), proxy.username->begin(), - proxy.username->end()); - authRequest.push_back(static_cast(proxy.password->size())); - authRequest.insert(authRequest.end(), proxy.password->begin(), - proxy.password->end()); - - asio::write(socket, asio::buffer(authRequest)); - - // Read auth response - std::vector authResponse(2); - asio::read(socket, asio::buffer(authResponse)); - - if (authResponse[0] != 0x01 || authResponse[1] != 0x00) { - throw std::runtime_error("SOCKS5 proxy: Authentication failed"); - } - } else if (response[1] != 0x00) { - throw std::runtime_error( - std::format("SOCKS5 proxy: Auth method {} not accepted", - static_cast(response[1]))); - } - - // Step 4: Send connection request - std::vector connectRequest; - connectRequest.push_back(0x05); // SOCKS version 5 - connectRequest.push_back(0x01); // CONNECT command - connectRequest.push_back(0x00); // Reserved - - // Check if target is IP address or domain name - asio::ip::address ipAddr; - bool isIp = false; - try { - ipAddr = asio::ip::make_address(urlComp.host); - isIp = true; - } catch (...) { - isIp = false; - } - - uint16_t targetPort = static_cast(std::stoi(urlComp.port)); - - if (isIp) { - if (ipAddr.is_v4()) { - connectRequest.push_back(0x01); // IPv4 - auto bytes = ipAddr.to_v4().to_bytes(); - connectRequest.insert(connectRequest.end(), bytes.begin(), - bytes.end()); - } else { - connectRequest.push_back(0x04); // IPv6 - auto bytes = ipAddr.to_v6().to_bytes(); - connectRequest.insert(connectRequest.end(), bytes.begin(), - bytes.end()); - } - } else { - connectRequest.push_back(0x03); // Domain name - connectRequest.push_back(static_cast(urlComp.host.size())); - connectRequest.insert(connectRequest.end(), urlComp.host.begin(), - urlComp.host.end()); - } - - // Port in network byte order - connectRequest.push_back( - static_cast((targetPort >> 8) & 0xFF)); - connectRequest.push_back(static_cast(targetPort & 0xFF)); - - asio::write(socket, asio::buffer(connectRequest)); - - // Step 5: Receive connection response - std::vector connectResponse(4); - asio::read(socket, asio::buffer(connectResponse)); - - if (connectResponse[0] != 0x05) { - throw std::runtime_error( - "SOCKS5 proxy: Invalid version in connect response"); - } - - if (connectResponse[1] != 0x00) { - std::string errorMsg; - switch (connectResponse[1]) { - case 0x01: - errorMsg = "General SOCKS server failure"; - break; - case 0x02: - errorMsg = "Connection not allowed by ruleset"; - break; - case 0x03: - errorMsg = "Network unreachable"; - break; - case 0x04: - errorMsg = "Host unreachable"; - break; - case 0x05: - errorMsg = "Connection refused"; - break; - case 0x06: - errorMsg = "TTL expired"; - break; - case 0x07: - errorMsg = "Command not supported"; - break; - case 0x08: - errorMsg = "Address type not supported"; - break; - default: - errorMsg = - std::format("Unknown error code {}", - static_cast(connectResponse[1])); - } - throw std::runtime_error( - std::format("SOCKS5 proxy connection failed: {}", errorMsg)); - } - - // Read the bind address from response (variable length) - uint8_t addrType = connectResponse[3]; - std::vector bindAddr; - - if (addrType == 0x01) { - // IPv4: 4 bytes + 2 bytes port - bindAddr.resize(6); - asio::read(socket, asio::buffer(bindAddr)); - } else if (addrType == 0x03) { - // Domain name: 1 byte length + domain + 2 bytes port - std::vector domainLen(1); - asio::read(socket, asio::buffer(domainLen)); - bindAddr.resize(domainLen[0] + 2); - asio::read(socket, asio::buffer(bindAddr)); - } else if (addrType == 0x04) { - // IPv6: 16 bytes + 2 bytes port - bindAddr.resize(18); - asio::read(socket, asio::buffer(bindAddr)); - } - - // SOCKS5 tunnel established, now send HTTP request - if (urlComp.isHttps) { - // Upgrade socket to SSL for HTTPS - ssl::stream stream(std::move(socket), ctx); - // SSL verification mode is already set in ctx (verify_none) - - // Perform SSL handshake - stream.handshake(ssl::stream_base::client); - - // Send HTTPS request through tunnel - return sendHttpsRequest(stream, urlComp, req); - } else { - // Send HTTP request through tunnel - return sendHttpRequest(socket, urlComp, req); - } - } - - // Execute direct request without proxy - Api::HttpResponse NetworkClient::executeDirect(asio::io_context& ioc, - ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - std::chrono::seconds timeout) - { - - if (urlComp.isHttps) { - // HTTPS direct connection - ssl::stream stream(ioc, ctx); - - // Set SNI hostname - if (!SSL_set_tlsext_host_name(stream.native_handle(), - urlComp.host.c_str())) { - throw std::runtime_error("Failed to set SNI hostname"); - } - - // Resolve and connect - asio::ip::tcp::resolver resolver(ioc); - auto results = resolver.resolve(urlComp.host, urlComp.port); - asio::connect(stream.next_layer(), results); - - // SSL handshake - stream.handshake(ssl::stream_base::client); - - return sendHttpsRequest(stream, urlComp, req); - - } else { - // HTTP direct connection - asio::ip::tcp::socket socket(ioc); - asio::ip::tcp::resolver resolver(ioc); - auto results = resolver.resolve(urlComp.host, urlComp.port); - asio::connect(socket, results); - - return sendHttpRequest(socket, urlComp, req); - } - } - - // Send HTTP request through socket - Api::HttpResponse - NetworkClient::sendHttpRequest(asio::ip::tcp::socket& socket, - const UrlComponents& urlComp, - const Api::HttpRequest& req) - { - - http::request request = - buildBeastRequest(urlComp, req); - - http::write(socket, request); - - beast::flat_buffer buffer; - http::response response; - http::read(socket, buffer, response); - - return convertBeastResponse(response); - } - - // Send HTTP request through proxy (for non-HTTPS) - Api::HttpResponse NetworkClient::sendHttpRequestThroughProxy( - asio::ip::tcp::socket& socket, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy) - { - - // Build request with absolute URL - std::string absoluteUrl = std::format("{}://{}{}", urlComp.protocol, - urlComp.host, urlComp.path); - - http::verb method = http::verb::get; - switch (req.method) { - case Api::HttpMethod::GET: - method = http::verb::get; - break; - case Api::HttpMethod::POST: - method = http::verb::post; - break; - case Api::HttpMethod::PUT: - method = http::verb::put; - break; - case Api::HttpMethod::DELETE: - method = http::verb::delete_; - break; - case Api::HttpMethod::PATCH: - method = http::verb::patch; - break; - case Api::HttpMethod::HEAD: - method = http::verb::head; - break; - case Api::HttpMethod::OPTIONS: - method = http::verb::options; - break; - } - - http::request request(method, absoluteUrl, 11); - request.set(http::field::host, urlComp.host); - request.set(http::field::user_agent, "EchoionBot/1.0"); - - // Add headers - for (const auto& header : req.headers) { - request.set(header.name, header.value); - } - - // Add proxy auth - if (proxy.requiresAuth()) { - std::string auth = - std::format("{}:{}", *proxy.username, *proxy.password); - std::string encoded = base64::encode(auth); - request.set(http::field::proxy_authorization, "Basic " + encoded); - } - - // Add body - if (req.body.has_value()) { - request.body() = std::string(req.body->begin(), req.body->end()); - request.prepare_payload(); - } - - http::write(socket, request); - - beast::flat_buffer buffer; - http::response response; - http::read(socket, buffer, response); - - return convertBeastResponse(response); - } - - // Build Beast HTTP request - http::request - NetworkClient::buildBeastRequest(const UrlComponents& urlComp, - const Api::HttpRequest& req) - { - - http::verb method = http::verb::get; - switch (req.method) { - case Api::HttpMethod::GET: - method = http::verb::get; - break; - case Api::HttpMethod::POST: - method = http::verb::post; - break; - case Api::HttpMethod::PUT: - method = http::verb::put; - break; - case Api::HttpMethod::DELETE: - method = http::verb::delete_; - break; - case Api::HttpMethod::PATCH: - method = http::verb::patch; - break; - case Api::HttpMethod::HEAD: - method = http::verb::head; - break; - case Api::HttpMethod::OPTIONS: - method = http::verb::options; - break; - } - - http::request request(method, urlComp.path, 11); - request.set(http::field::host, urlComp.host); - request.set(http::field::user_agent, "EchoionBot/1.0"); - - // Add custom headers - for (const auto& header : req.headers) { - request.set(header.name, header.value); - } - - // Add body if present - if (req.body.has_value()) { - request.body() = std::string(req.body->begin(), req.body->end()); - request.prepare_payload(); - } - - return request; - } - - // Convert Beast response to Api::HttpResponse - Api::HttpResponse NetworkClient::convertBeastResponse( - const http::response& beastResponse) - { - - Api::HttpResponse response; - response.statusCode = static_cast(beastResponse.result_int()); - - // Extract body - response.body = - boost::beast::buffers_to_string(beastResponse.body().data()); - - // Extract headers (use push_back to preserve multiple headers with same - // name) - for (const auto& field : beastResponse.base()) { - response.headers.push_back( - {std::string(field.name_string()), std::string(field.value())}); - } - - return response; - } - - std::vector NetworkClient::addDefaultHeaders( - const std::vector& headers) - { - std::vector result = headers; - - // Check if User-Agent is already present - bool hasUserAgent = - std::any_of(headers.begin(), headers.end(), - [](const auto& h) { return h.name == "User-Agent"; }); - - if (!hasUserAgent) { - result.push_back({"User-Agent", "Mozilla/5.0 (Windows NT 10.0; " - "Win64; x64) AppleWebKit/537.36"}); - } - - // Check if Accept is already present - bool hasAccept = - std::any_of(headers.begin(), headers.end(), - [](const auto& h) { return h.name == "Accept"; }); - - if (!hasAccept) { - result.push_back({"Accept", "application/json, */*"}); - } - - return result; - } - } // namespace Echoion::Core