404 lines
11 KiB
C++
404 lines
11 KiB
C++
#include "echoion/core/Socks5HttpBridge.hpp"
|
|
|
|
#include <Void/Log/Log.hpp>
|
|
|
|
#include <boost/asio/read.hpp>
|
|
#include <boost/asio/read_until.hpp>
|
|
#include <boost/asio/write.hpp>
|
|
|
|
#include <array>
|
|
#include <charconv>
|
|
#include <format>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
|
|
#ifndef _WIN32
|
|
#include <sys/socket.h>
|
|
#include <sys/time.h>
|
|
#endif
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
namespace
|
|
{
|
|
namespace asio = boost::asio;
|
|
using tcp = boost::asio::ip::tcp;
|
|
|
|
// SO_RCVTIMEO/SO_SNDTIMEO for the blocking upstream dial + handshake,
|
|
// so a dead SOCKS5 proxy cannot hang a tunnel thread until stop().
|
|
// Cleared (0) again for the relay phase — a paused stream may
|
|
// legitimately sit idle far longer than any sane handshake timeout.
|
|
void setSocketTimeouts(tcp::socket& socket, long seconds)
|
|
{
|
|
#ifdef _WIN32
|
|
DWORD ms = static_cast<DWORD>(seconds * 1000);
|
|
setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO,
|
|
reinterpret_cast<const char*>(&ms), sizeof(ms));
|
|
setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO,
|
|
reinterpret_cast<const char*>(&ms), sizeof(ms));
|
|
#else
|
|
timeval tv{.tv_sec = seconds, .tv_usec = 0};
|
|
setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv,
|
|
sizeof(tv));
|
|
setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv,
|
|
sizeof(tv));
|
|
#endif
|
|
}
|
|
|
|
// One direction of the tunnel; runs until either side closes.
|
|
void pump(tcp::socket& from, tcp::socket& to)
|
|
{
|
|
std::array<char, 16 * 1024> buf;
|
|
boost::system::error_code ec;
|
|
while (true) {
|
|
const std::size_t n = from.read_some(asio::buffer(buf), ec);
|
|
if (ec || n == 0) {
|
|
break;
|
|
}
|
|
asio::write(to, asio::buffer(buf.data(), n), ec);
|
|
if (ec) {
|
|
break;
|
|
}
|
|
}
|
|
// Half-close so the peer's read loop terminates too.
|
|
to.shutdown(tcp::socket::shutdown_send, ec);
|
|
}
|
|
|
|
// "CONNECT host:port HTTP/1.1" -> {host, port}. Handles the bracketed
|
|
// IPv6 authority form ("[::1]:443").
|
|
std::optional<std::pair<std::string, uint16_t>>
|
|
parseConnectTarget(std::string_view requestLine)
|
|
{
|
|
if (!requestLine.starts_with("CONNECT ")) {
|
|
return std::nullopt;
|
|
}
|
|
requestLine.remove_prefix(8);
|
|
const auto space = requestLine.find(' ');
|
|
if (space == std::string_view::npos) {
|
|
return std::nullopt;
|
|
}
|
|
std::string_view authority = requestLine.substr(0, space);
|
|
|
|
std::string_view host;
|
|
std::string_view portStr;
|
|
if (authority.starts_with('[')) {
|
|
const auto close = authority.find(']');
|
|
if (close == std::string_view::npos ||
|
|
close + 1 >= authority.size() ||
|
|
authority[close + 1] != ':') {
|
|
return std::nullopt;
|
|
}
|
|
host = authority.substr(1, close - 1);
|
|
portStr = authority.substr(close + 2);
|
|
} else {
|
|
const auto colon = authority.rfind(':');
|
|
if (colon == std::string_view::npos) {
|
|
return std::nullopt;
|
|
}
|
|
host = authority.substr(0, colon);
|
|
portStr = authority.substr(colon + 1);
|
|
}
|
|
|
|
uint16_t port = 0;
|
|
const auto [ptr, ec] = std::from_chars(
|
|
portStr.data(), portStr.data() + portStr.size(), port);
|
|
if (ec != std::errc{} || ptr != portStr.data() + portStr.size() ||
|
|
host.empty() || port == 0) {
|
|
return std::nullopt;
|
|
}
|
|
return std::make_pair(std::string(host), port);
|
|
}
|
|
|
|
void writeAll(tcp::socket& socket, std::string_view data)
|
|
{
|
|
boost::system::error_code ec;
|
|
asio::write(socket, asio::buffer(data), ec);
|
|
}
|
|
} // namespace
|
|
|
|
Socks5HttpBridge::~Socks5HttpBridge() { stop(); }
|
|
|
|
Api::Result<uint16_t>
|
|
Socks5HttpBridge::start(const Void::Net::ProxyConfig& socks5)
|
|
{
|
|
stop();
|
|
|
|
try {
|
|
acceptor_.emplace(io_,
|
|
tcp::endpoint(asio::ip::make_address("127.0.0.1"),
|
|
0));
|
|
port_ = acceptor_->local_endpoint().port();
|
|
} catch (const std::exception& e) {
|
|
acceptor_.reset();
|
|
return Api::fail(
|
|
Api::ErrorCode::NetworkError,
|
|
std::format("Failed to bind SOCKS5 bridge: {}", e.what()));
|
|
}
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
upstream_ = socks5;
|
|
}
|
|
running_ = true;
|
|
acceptThread_ = std::thread([this]() { acceptLoop(); });
|
|
|
|
Void::Log::info(
|
|
"Socks5HttpBridge", "{}",
|
|
std::format("HTTP->SOCKS5 bridge on 127.0.0.1:{} (upstream {}:{})",
|
|
port_, socks5.host, socks5.port));
|
|
return port_;
|
|
}
|
|
|
|
void Socks5HttpBridge::stop()
|
|
{
|
|
if (!running_.exchange(false)) {
|
|
return;
|
|
}
|
|
|
|
boost::system::error_code ec;
|
|
if (acceptor_) {
|
|
acceptor_->close(ec);
|
|
}
|
|
if (acceptThread_.joinable()) {
|
|
acceptThread_.join();
|
|
}
|
|
acceptor_.reset();
|
|
|
|
std::vector<std::unique_ptr<Connection>> connections;
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
connections.swap(connections_);
|
|
upstream_.reset();
|
|
}
|
|
for (auto& conn : connections) {
|
|
conn->client.close(ec);
|
|
conn->upstream.close(ec);
|
|
}
|
|
for (auto& conn : connections) {
|
|
if (conn->worker.joinable()) {
|
|
conn->worker.join();
|
|
}
|
|
}
|
|
port_ = 0;
|
|
}
|
|
|
|
std::optional<Void::Net::ProxyConfig> Socks5HttpBridge::upstream() const
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
return upstream_;
|
|
}
|
|
|
|
void Socks5HttpBridge::acceptLoop()
|
|
{
|
|
while (running_.load()) {
|
|
auto conn = std::make_unique<Connection>(io_);
|
|
boost::system::error_code ec;
|
|
acceptor_->accept(conn->client, ec);
|
|
if (ec) {
|
|
// close() from stop() lands here.
|
|
break;
|
|
}
|
|
|
|
Connection* raw = conn.get();
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
pruneFinished();
|
|
connections_.push_back(std::move(conn));
|
|
}
|
|
raw->worker = std::thread([this, raw]() {
|
|
serve(*raw);
|
|
raw->done = true;
|
|
});
|
|
}
|
|
}
|
|
|
|
void Socks5HttpBridge::pruneFinished()
|
|
{
|
|
// Caller holds mutex_.
|
|
std::erase_if(connections_, [](const std::unique_ptr<Connection>& c) {
|
|
if (!c->done.load()) {
|
|
return false;
|
|
}
|
|
if (c->worker.joinable()) {
|
|
c->worker.join();
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
|
|
void Socks5HttpBridge::serve(Connection& conn)
|
|
{
|
|
boost::system::error_code ec;
|
|
|
|
// Read the request head; ffmpeg sends a single CONNECT for https
|
|
// targets. Bound the handshake so a stuck client can't pin the thread.
|
|
setSocketTimeouts(conn.client, 15);
|
|
|
|
asio::streambuf head;
|
|
asio::read_until(conn.client, head, "\r\n\r\n", ec);
|
|
if (ec) {
|
|
conn.client.close(ec);
|
|
return;
|
|
}
|
|
std::istream stream(&head);
|
|
std::string requestLine;
|
|
std::getline(stream, requestLine);
|
|
if (!requestLine.empty() && requestLine.back() == '\r') {
|
|
requestLine.pop_back();
|
|
}
|
|
|
|
const auto target = parseConnectTarget(requestLine);
|
|
if (!target) {
|
|
Void::Log::warn(
|
|
"Socks5HttpBridge", "{}",
|
|
std::format("Rejected non-CONNECT request: '{}'", requestLine));
|
|
writeAll(conn.client,
|
|
"HTTP/1.1 405 Method Not Allowed\r\n\r\n");
|
|
conn.client.close(ec);
|
|
return;
|
|
}
|
|
|
|
std::optional<Void::Net::ProxyConfig> proxy = upstream();
|
|
if (!proxy) {
|
|
writeAll(conn.client, "HTTP/1.1 502 Bad Gateway\r\n\r\n");
|
|
conn.client.close(ec);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setSocketTimeouts(conn.upstream, 15);
|
|
tcp::resolver resolver(io_);
|
|
asio::connect(conn.upstream,
|
|
resolver.resolve(proxy->host,
|
|
std::to_string(proxy->port)));
|
|
socks5Connect(conn.upstream, target->first, target->second,
|
|
*proxy);
|
|
} catch (const std::exception& e) {
|
|
Void::Log::warn(
|
|
"Socks5HttpBridge", "{}",
|
|
std::format("Tunnel to {}:{} failed: {}", target->first,
|
|
target->second, e.what()));
|
|
writeAll(conn.client, "HTTP/1.1 502 Bad Gateway\r\n\r\n");
|
|
conn.client.close(ec);
|
|
conn.upstream.close(ec);
|
|
return;
|
|
}
|
|
|
|
writeAll(conn.client, "HTTP/1.1 200 Connection established\r\n\r\n");
|
|
|
|
// Relay phase: no timeouts — a paused stream may idle for minutes.
|
|
setSocketTimeouts(conn.client, 0);
|
|
setSocketTimeouts(conn.upstream, 0);
|
|
|
|
std::thread downstream(
|
|
[&conn]() { pump(conn.upstream, conn.client); });
|
|
pump(conn.client, conn.upstream);
|
|
downstream.join();
|
|
|
|
conn.client.close(ec);
|
|
conn.upstream.close(ec);
|
|
}
|
|
|
|
void Socks5HttpBridge::socks5Connect(tcp::socket& upstream,
|
|
const std::string& host,
|
|
uint16_t targetPort,
|
|
const Void::Net::ProxyConfig& proxy)
|
|
{
|
|
// Greeting: no-auth, plus user/pass when credentials are configured.
|
|
std::vector<uint8_t> greeting{0x05};
|
|
if (proxy.has_auth()) {
|
|
greeting.insert(greeting.end(), {0x02, 0x00, 0x02});
|
|
} else {
|
|
greeting.insert(greeting.end(), {0x01, 0x00});
|
|
}
|
|
asio::write(upstream, asio::buffer(greeting));
|
|
|
|
std::array<uint8_t, 2> sel{};
|
|
asio::read(upstream, asio::buffer(sel));
|
|
if (sel[0] != 0x05) {
|
|
throw std::runtime_error("SOCKS5: invalid version");
|
|
}
|
|
if (sel[1] == 0x02) {
|
|
if (!proxy.has_auth()) {
|
|
throw std::runtime_error("SOCKS5: auth required");
|
|
}
|
|
std::vector<uint8_t> auth{0x01};
|
|
auth.push_back(static_cast<uint8_t>(proxy.username->size()));
|
|
auth.insert(auth.end(), proxy.username->begin(),
|
|
proxy.username->end());
|
|
auth.push_back(static_cast<uint8_t>(proxy.password->size()));
|
|
auth.insert(auth.end(), proxy.password->begin(),
|
|
proxy.password->end());
|
|
asio::write(upstream, asio::buffer(auth));
|
|
std::array<uint8_t, 2> authReply{};
|
|
asio::read(upstream, asio::buffer(authReply));
|
|
if (authReply[0] != 0x01 || authReply[1] != 0x00) {
|
|
throw std::runtime_error("SOCKS5: authentication failed");
|
|
}
|
|
} else if (sel[1] != 0x00) {
|
|
throw std::runtime_error("SOCKS5: no acceptable auth method");
|
|
}
|
|
|
|
// CONNECT request: literal IPs as ATYP 1/4, otherwise the domain form
|
|
// (ATYP 3) so the proxy resolves — important when googlevideo DNS is
|
|
// poisoned or blocked locally.
|
|
std::vector<uint8_t> connectReq{0x05, 0x01, 0x00};
|
|
boost::system::error_code addrEc;
|
|
const auto addr = asio::ip::make_address(host, addrEc);
|
|
if (!addrEc) {
|
|
if (addr.is_v4()) {
|
|
connectReq.push_back(0x01);
|
|
for (auto b : addr.to_v4().to_bytes()) {
|
|
connectReq.push_back(b);
|
|
}
|
|
} else {
|
|
connectReq.push_back(0x04);
|
|
for (auto b : addr.to_v6().to_bytes()) {
|
|
connectReq.push_back(b);
|
|
}
|
|
}
|
|
} else {
|
|
connectReq.push_back(0x03);
|
|
connectReq.push_back(static_cast<uint8_t>(host.size()));
|
|
connectReq.insert(connectReq.end(), host.begin(), host.end());
|
|
}
|
|
connectReq.push_back(static_cast<uint8_t>((targetPort >> 8) & 0xFF));
|
|
connectReq.push_back(static_cast<uint8_t>(targetPort & 0xFF));
|
|
asio::write(upstream, asio::buffer(connectReq));
|
|
|
|
std::array<uint8_t, 4> reply{};
|
|
asio::read(upstream, asio::buffer(reply));
|
|
if (reply[0] != 0x05) {
|
|
throw std::runtime_error("SOCKS5: invalid connect reply");
|
|
}
|
|
if (reply[1] != 0x00) {
|
|
throw std::runtime_error(std::format(
|
|
"SOCKS5: connect failed (code {})", int(reply[1])));
|
|
}
|
|
// Drain the bound address the proxy reports.
|
|
switch (reply[3]) {
|
|
case 0x01: {
|
|
std::array<uint8_t, 6> bound{};
|
|
asio::read(upstream, asio::buffer(bound));
|
|
break;
|
|
}
|
|
case 0x03: {
|
|
std::array<uint8_t, 1> len{};
|
|
asio::read(upstream, asio::buffer(len));
|
|
std::vector<uint8_t> bound(len[0] + 2u);
|
|
asio::read(upstream, asio::buffer(bound));
|
|
break;
|
|
}
|
|
case 0x04: {
|
|
std::array<uint8_t, 18> bound{};
|
|
asio::read(upstream, asio::buffer(bound));
|
|
break;
|
|
}
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
} // namespace Echoion::Core
|