Initial commit
This commit is contained in:
commit
a583c17916
56 files changed
+11025
No files matched your search
@@ -0,0 +1,813 @@
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include "boost/beast/core/buffers_to_string.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <boost/beast/http/field.hpp>
|
||||
#include <format>
|
||||
#include <algorithm>
|
||||
#include <glaze/glaze.hpp>
|
||||
|
||||
|
||||
// Boost.Beast for HTTP with proxy support
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/asio/ssl.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/ssl.hpp>
|
||||
#include <boost/url.hpp>
|
||||
|
||||
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 {
|
||||
static const std::string chars =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
std::string encode(const std::string& input) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
if (valb > -6) {
|
||||
encoded.push_back(chars[((val << 8) >> (valb + 8)) & 0x3F]);
|
||||
}
|
||||
|
||||
while (encoded.size() % 4) {
|
||||
encoded.push_back('=');
|
||||
}
|
||||
|
||||
return encoded;
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
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<UrlComponents> parseUrl(std::string_view url) {
|
||||
try {
|
||||
auto result = urls::parse_uri(url);
|
||||
if (!result) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
NetworkClient::NetworkClient() = default;
|
||||
|
||||
NetworkClient::~NetworkClient() {
|
||||
shutdown();
|
||||
}
|
||||
|
||||
Api::Result<void> NetworkClient::initialize(const std::optional<Api::ProxyConfig>& proxy) {
|
||||
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<Api::Result<Api::HttpResponse>()> task;
|
||||
{
|
||||
std::unique_lock<std::mutex> 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"));
|
||||
return {};
|
||||
}
|
||||
|
||||
void NetworkClient::shutdown() {
|
||||
stopThreads_ = true;
|
||||
taskCv_.notify_all();
|
||||
for (auto& thread : threadPool_) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
threadPool_.clear();
|
||||
initialized_ = false;
|
||||
ECHOION_LOG_INFO("NetworkClient shutdown");
|
||||
}
|
||||
|
||||
Api::Result<Api::HttpResponse> NetworkClient::get(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers) {
|
||||
|
||||
Api::HttpRequest req;
|
||||
req.url = std::string(url);
|
||||
req.method = Api::HttpMethod::GET;
|
||||
req.headers = addDefaultHeaders(headers);
|
||||
req.proxy = proxy_;
|
||||
return request(req);
|
||||
}
|
||||
|
||||
Api::Result<Api::HttpResponse> NetworkClient::post(std::string_view url, std::string_view body,
|
||||
const std::vector<Api::HttpHeader>& headers) {
|
||||
|
||||
Api::HttpRequest req;
|
||||
req.url = std::string(url);
|
||||
req.method = Api::HttpMethod::POST;
|
||||
req.headers = addDefaultHeaders(headers);
|
||||
req.body = std::vector<uint8_t>(body.begin(), body.end());
|
||||
req.proxy = proxy_;
|
||||
return request(req);
|
||||
}
|
||||
|
||||
Api::Result<Api::HttpResponse> NetworkClient::request(const Api::HttpRequest& req) {
|
||||
if (!initialized_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"NetworkClient not initialized"));
|
||||
}
|
||||
return executeWithRetry(req);
|
||||
}
|
||||
|
||||
std::future<Api::Result<Api::HttpResponse>> NetworkClient::getAsync(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers) {
|
||||
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, urlStr = std::string(url), headers] {
|
||||
return get(urlStr, headers);
|
||||
});
|
||||
auto future = task.get_future();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(taskMutex_);
|
||||
taskQueue_.push(std::move(task));
|
||||
}
|
||||
taskCv_.notify_one();
|
||||
return future;
|
||||
}
|
||||
|
||||
std::future<Api::Result<Api::HttpResponse>> NetworkClient::postAsync(std::string_view url,
|
||||
std::string_view body, const std::vector<Api::HttpHeader>& headers) {
|
||||
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, urlStr = std::string(url),
|
||||
bodyStr = std::string(body), headers] {
|
||||
return post(urlStr, bodyStr, headers);
|
||||
});
|
||||
auto future = task.get_future();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(taskMutex_);
|
||||
taskQueue_.push(std::move(task));
|
||||
}
|
||||
taskCv_.notify_one();
|
||||
return future;
|
||||
}
|
||||
|
||||
std::future<Api::Result<Api::HttpResponse>> NetworkClient::requestAsync(const Api::HttpRequest& req) {
|
||||
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, req] {
|
||||
return request(req);
|
||||
});
|
||||
auto future = task.get_future();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(taskMutex_);
|
||||
taskQueue_.push(std::move(task));
|
||||
}
|
||||
taskCv_.notify_one();
|
||||
return future;
|
||||
}
|
||||
|
||||
std::vector<Api::Result<Api::HttpResponse>> NetworkClient::requestBatch(
|
||||
const std::vector<Api::HttpRequest>& requests) {
|
||||
std::vector<std::future<Api::Result<Api::HttpResponse>>> futures;
|
||||
futures.reserve(requests.size());
|
||||
|
||||
for (const auto& req : requests) {
|
||||
futures.push_back(requestAsync(req));
|
||||
}
|
||||
|
||||
std::vector<Api::Result<Api::HttpResponse>> results;
|
||||
results.reserve(requests.size());
|
||||
|
||||
for (auto& future : futures) {
|
||||
results.push_back(future.get());
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
void NetworkClient::setProxy(const std::optional<Api::ProxyConfig>& proxy) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
proxy_ = proxy;
|
||||
ECHOION_LOG_INFO(std::format("Proxy {}", proxy.has_value() ? "configured" : "cleared"));
|
||||
}
|
||||
|
||||
std::optional<Api::ProxyConfig> NetworkClient::getProxy() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return proxy_;
|
||||
}
|
||||
|
||||
void NetworkClient::clearProxy() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
proxy_.reset();
|
||||
ECHOION_LOG_INFO("Proxy cleared");
|
||||
}
|
||||
|
||||
void NetworkClient::setRetryConfig(const Api::RetryConfig& config) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
retryConfig_ = config;
|
||||
}
|
||||
|
||||
Api::RetryConfig NetworkClient::getRetryConfig() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return retryConfig_;
|
||||
}
|
||||
|
||||
Api::Result<Api::HttpResponse> NetworkClient::executeWithRetry(const Api::HttpRequest& req) {
|
||||
auto delay = retryConfig_.initialDelay;
|
||||
|
||||
for (uint32_t attempt = 0; attempt <= retryConfig_.maxRetries; ++attempt) {
|
||||
auto result = executeRequest(req);
|
||||
|
||||
if (result) {
|
||||
// Check if we should retry based on status code
|
||||
if (result->isError() && attempt < retryConfig_.maxRetries) {
|
||||
auto it = std::find(retryConfig_.retryableStatusCodes.begin(),
|
||||
retryConfig_.retryableStatusCodes.end(),
|
||||
result->statusCode);
|
||||
if (it != retryConfig_.retryableStatusCodes.end()) {
|
||||
ECHOION_LOG_WARNING(std::format("Request failed with status {}, retrying (attempt {}/{})",
|
||||
result->statusCode, attempt + 1, retryConfig_.maxRetries));
|
||||
std::this_thread::sleep_for(delay);
|
||||
delay = std::min(std::chrono::milliseconds(static_cast<uint32_t>(
|
||||
delay.count() * retryConfig_.backoffMultiplier)), retryConfig_.maxDelay);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} else if (attempt < retryConfig_.maxRetries) {
|
||||
ECHOION_LOG_WARNING(std::format("Request error: {}, retrying (attempt {}/{})",
|
||||
result.error().message, attempt + 1, retryConfig_.maxRetries));
|
||||
std::this_thread::sleep_for(delay);
|
||||
delay = std::min(std::chrono::milliseconds(static_cast<uint32_t>(
|
||||
delay.count() * retryConfig_.backoffMultiplier)), retryConfig_.maxDelay);
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
||||
"Max retries exceeded"));
|
||||
}
|
||||
|
||||
// Execute HTTP request using Boost.Beast with proxy support
|
||||
Api::Result<Api::HttpResponse> 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<Api::ProxyConfig> 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();
|
||||
|
||||
// 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<std::chrono::milliseconds>(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<http::string_body> 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<http::empty_body> 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<int>(connect_res.result())));
|
||||
}
|
||||
|
||||
// Upgrade socket to SSL
|
||||
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
|
||||
stream.set_verify_mode(ssl::verify_peer);
|
||||
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
|
||||
|
||||
// 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<uint8_t> 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<uint8_t> 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<uint8_t> authRequest;
|
||||
authRequest.push_back(0x01); // Auth version
|
||||
authRequest.push_back(static_cast<uint8_t>(proxy.username->size()));
|
||||
authRequest.insert(authRequest.end(), proxy.username->begin(), proxy.username->end());
|
||||
authRequest.push_back(static_cast<uint8_t>(proxy.password->size()));
|
||||
authRequest.insert(authRequest.end(), proxy.password->begin(), proxy.password->end());
|
||||
|
||||
asio::write(socket, asio::buffer(authRequest));
|
||||
|
||||
// Read auth response
|
||||
std::vector<uint8_t> 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<int>(response[1])));
|
||||
}
|
||||
|
||||
// Step 4: Send connection request
|
||||
std::vector<uint8_t> 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<uint16_t>(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<uint8_t>(urlComp.host.size()));
|
||||
connectRequest.insert(connectRequest.end(), urlComp.host.begin(), urlComp.host.end());
|
||||
}
|
||||
|
||||
// Port in network byte order
|
||||
connectRequest.push_back(static_cast<uint8_t>((targetPort >> 8) & 0xFF));
|
||||
connectRequest.push_back(static_cast<uint8_t>(targetPort & 0xFF));
|
||||
|
||||
asio::write(socket, asio::buffer(connectRequest));
|
||||
|
||||
// Step 5: Receive connection response
|
||||
std::vector<uint8_t> 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<int>(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<uint8_t> 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<uint8_t> 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<asio::ip::tcp::socket> stream(std::move(socket), ctx);
|
||||
stream.set_verify_mode(ssl::verify_peer);
|
||||
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
|
||||
|
||||
// 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<asio::ip::tcp::socket> 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<http::string_body> request = buildBeastRequest(urlComp, req);
|
||||
|
||||
http::write(socket, request);
|
||||
|
||||
beast::flat_buffer buffer;
|
||||
http::response<http::dynamic_body> 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<http::string_body> 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<http::dynamic_body> response;
|
||||
http::read(socket, buffer, response);
|
||||
|
||||
return convertBeastResponse(response);
|
||||
}
|
||||
|
||||
// Build Beast HTTP request
|
||||
http::request<http::string_body> 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<http::string_body> 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<http::dynamic_body>& beastResponse) {
|
||||
|
||||
Api::HttpResponse response;
|
||||
response.statusCode = static_cast<uint16_t>(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<Api::HttpHeader> NetworkClient::addDefaultHeaders(const std::vector<Api::HttpHeader>& headers) {
|
||||
std::vector<Api::HttpHeader> 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
|
||||
Reference in new issue
Block a user