#include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(_WIN32) #include #include #endif #include #include #include #include #include #include #include #include #include #include #include namespace Void::Net { namespace { namespace asio = boost::asio; namespace beast = boost::beast; namespace http = boost::beast::http; namespace ssl = boost::asio::ssl; using tcp = boost::asio::ip::tcp; [[nodiscard]] http::verb to_verb(Method m) { switch (m) { case Method::Get: return http::verb::get; case Method::Post: return http::verb::post; case Method::Put: return http::verb::put; case Method::Delete: return http::verb::delete_; case Method::Patch: return http::verb::patch; case Method::Head: return http::verb::head; case Method::Options: return http::verb::options; } return http::verb::get; } // Build the Beast request for an origin-form target (direct / tunnelled). http::request build_request(const Url& url, const Request& req, std::string_view default_ua, std::string_view target) { http::request r{to_verb(req.method), std::string{target}, 11}; r.set(http::field::host, url.host); bool has_ua = false; for (const auto& h : req.headers) { r.set(h.name, h.value); if (!has_ua && h.name == "User-Agent") has_ua = true; } if (!has_ua) { r.set(http::field::user_agent, std::string{default_ua}); } if (req.body) { r.body() = *req.body; r.prepare_payload(); } return r; } Response convert(const http::response& src) { Response out; out.status = static_cast(src.result_int()); out.body = beast::buffers_to_string(src.body().data()); for (const auto& f : src.base()) { out.headers.push_back( {std::string{f.name_string()}, std::string{f.value()}}); } return out; } template Response write_read(Stream& stream, http::request& rq, std::uint64_t max_body) { http::write(stream, rq); beast::flat_buffer buffer; // Use a parser so the body limit is configurable. Beast's default // (~1 MiB) is too small for binary downloads (release artifacts); // max_body == 0 means unlimited. http::response_parser parser; parser.body_limit(max_body == 0 ? std::numeric_limits::max() : max_body); http::read(stream, buffer, parser); return convert(parser.get()); } // SOCKS5 CONNECT handshake on an already-connected socket. void socks5_connect(tcp::socket& socket, const Url& url, const ProxyConfig& proxy) { std::vector greeting{0x05}; if (proxy.has_auth()) { greeting.insert(greeting.end(), {0x02, 0x00, 0x02}); } else { greeting.insert(greeting.end(), {0x01, 0x00}); } asio::write(socket, asio::buffer(greeting)); std::vector sel(2); asio::read(socket, 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 a{0x01}; a.push_back(static_cast(proxy.username->size())); a.insert(a.end(), proxy.username->begin(), proxy.username->end()); a.push_back(static_cast(proxy.password->size())); a.insert(a.end(), proxy.password->begin(), proxy.password->end()); asio::write(socket, asio::buffer(a)); std::vector ar(2); asio::read(socket, asio::buffer(ar)); if (ar[0] != 0x01 || ar[1] != 0x00) { throw std::runtime_error("SOCKS5: authentication failed"); } } else if (sel[1] != 0x00) { throw std::runtime_error("SOCKS5: no acceptable auth method"); } std::vector creq{0x05, 0x01, 0x00}; boost::system::error_code ec; const auto addr = asio::ip::make_address(url.host, ec); const auto port = static_cast(std::stoi(url.port)); if (!ec) { if (addr.is_v4()) { creq.push_back(0x01); for (auto b : addr.to_v4().to_bytes()) creq.push_back(b); } else { creq.push_back(0x04); for (auto b : addr.to_v6().to_bytes()) creq.push_back(b); } } else { creq.push_back(0x03); creq.push_back(static_cast(url.host.size())); creq.insert(creq.end(), url.host.begin(), url.host.end()); } creq.push_back(static_cast((port >> 8) & 0xFF)); creq.push_back(static_cast(port & 0xFF)); asio::write(socket, asio::buffer(creq)); std::vector cres(4); asio::read(socket, asio::buffer(cres)); if (cres[0] != 0x05) { throw std::runtime_error("SOCKS5: invalid connect reply"); } if (cres[1] != 0x00) { throw std::runtime_error(std::format( "SOCKS5: connect failed (code {})", int(cres[1]))); } // Drain the bound address. switch (cres[3]) { case 0x01: { std::vector b(6); asio::read(socket, asio::buffer(b)); break; } case 0x03: { std::vector len(1); asio::read(socket, asio::buffer(len)); std::vector b(len[0] + 2u); asio::read(socket, asio::buffer(b)); break; } case 0x04: { std::vector b(18); asio::read(socket, asio::buffer(b)); break; } default: break; } } // HTTP CONNECT tunnel for TLS targets on a connected proxy socket. void http_connect_tunnel(tcp::socket& socket, const Url& url, const ProxyConfig& proxy) { const std::string target = url.host + ":" + url.port; http::request creq{http::verb::connect, target, 11}; creq.set(http::field::host, target); if (proxy.has_auth()) { const auto enc = Void::Encoding::Base64::encode( *proxy.username + ":" + *proxy.password); creq.set(http::field::proxy_authorization, "Basic " + enc); } http::write(socket, creq); beast::flat_buffer buffer; // A 2xx CONNECT reply has no body; the socket then becomes a raw // tunnel. Some proxies attach a body to non-2xx replies, which an // empty_body reader rejects ("unexpected body") before we can even // read the status. skip(true) + read_header reads only the headers. http::response_parser cparser; cparser.skip(true); http::read_header(socket, buffer, cparser); if (cparser.get().result() != http::status::ok) { throw std::runtime_error(std::format( "Proxy CONNECT failed: {}", int(cparser.get().result_int()))); } } void tls_handshake(ssl::stream& stream, const Url& url) { if (!SSL_set_tlsext_host_name(stream.native_handle(), url.host.c_str())) { throw std::runtime_error("TLS: failed to set SNI host"); } stream.handshake(ssl::stream_base::client); } // Bounds every sync operation on an open socket with the request // timeout. Asio's synchronous ops cannot be bounded any other way // short of going fully async: SO_RCVTIMEO merely makes recv return // EAGAIN, which the sync emulation treats as would-block and then // poll()s without a deadline. On expiry the watchdog ::shutdown()s // the descriptor — shutdown (unlike close) is safe against a // concurrent blocked op and wakes it with EOF, so the op fails and // the request errors out instead of hanging the calling thread // forever. The descriptor must stay open for the guard's lifetime // (declare the guard after the connected socket, in the same scope). // Name resolution and connect() are not covered (kernel defaults). class DeadlineGuard { public: DeadlineGuard(tcp::socket& socket, std::chrono::seconds timeout) { if (timeout <= std::chrono::seconds::zero() || !socket.is_open()) { return; } const auto fd = socket.native_handle(); m_worker = std::thread([this, fd, timeout] { std::unique_lock lock{m_mutex}; if (!m_cv.wait_for(lock, timeout, [this] { return m_done; })) { #if defined(_WIN32) ::shutdown(fd, SD_BOTH); #else ::shutdown(fd, SHUT_RDWR); #endif m_timed_out = true; } }); } DeadlineGuard(const DeadlineGuard&) = delete; DeadlineGuard& operator=(const DeadlineGuard&) = delete; ~DeadlineGuard() { if (!m_worker.joinable()) { return; } { std::lock_guard lock{m_mutex}; m_done = true; } m_cv.notify_all(); m_worker.join(); } [[nodiscard]] bool timed_out() const noexcept { return m_timed_out; } private: std::thread m_worker; std::mutex m_mutex; std::condition_variable m_cv; bool m_done{false}; bool m_timed_out{false}; }; // Perform the request over an already-connected plain socket, doing a // TLS upgrade in place when the target is https. The TLS stream is an // out-parameter declared in the caller's scope so the descriptor // outlives the caller's DeadlineGuard (declaration order there is // socket, stream, guard — the guard is destroyed first). Response finish(tcp::socket& socket, std::optional>& tls, ssl::context& ctx, const Url& url, const Request& req, std::string_view ua, std::uint64_t max_body) { if (url.is_tls) { tls.emplace(std::move(socket), ctx); tls_handshake(*tls, url); auto rq = build_request(url, req, ua, url.target); return write_read(*tls, rq, max_body); } auto rq = build_request(url, req, ua, url.target); return write_read(socket, rq, max_body); } } // namespace std::optional Response::header(std::string_view name) const { for (const auto& h : headers) { if (h.name.size() == name.size()) { bool eq = true; for (std::size_t i = 0; i < name.size(); ++i) { const char a = static_cast(std::tolower(h.name[i])); const char b = static_cast(std::tolower(name[i])); if (a != b) { eq = false; break; } } if (eq) return h.value; } } return std::nullopt; } namespace { // Resolve a redirect Location against the URL it came from. Handles // absolute URLs and host-relative ("/path") and bare-relative targets. std::string resolve_redirect(const Url& base, std::string_view location) { if (location.starts_with("http://") || location.starts_with("https://")) { return std::string(location); } std::string origin = std::format("{}://{}", base.scheme, base.host); const bool standard_port = (base.scheme == "https" && base.port == "443") || (base.scheme == "http" && base.port == "80"); if (!base.port.empty() && !standard_port) { origin += ":" + base.port; } if (location.starts_with("/")) { return origin + std::string(location); } return origin + "/" + std::string(location); } } // namespace Void::Result::Result HttpClient::send(const Request& req) const { std::string target_url = req.url; int redirects = 0; while (true) { const auto url = Url::parse(target_url); if (!url) { return Void::Result::fail( std::format("Net: invalid URL '{}'", target_url)); } try { const auto start = std::chrono::steady_clock::now(); asio::io_context ioc; ssl::context ctx{ssl::context::tlsv12_client}; ctx.set_default_verify_paths(); ctx.set_verify_mode(m_verify_tls ? ssl::verify_peer : ssl::verify_none); Response response; tcp::resolver resolver{ioc}; // Declaration order matters: the DeadlineGuard must be // destroyed (and its watchdog joined) BEFORE the objects // that own the descriptor it may shut down. tcp::socket socket{ioc}; std::optional> tls; if (m_proxy.enabled()) { asio::connect(socket, resolver.resolve( m_proxy.host, std::to_string(m_proxy.port))); DeadlineGuard deadline{socket, req.timeout}; if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } else { // Http proxy if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } else { // Plain HTTP through proxy: absolute-form target. const std::string absolute = std::format( "{}://{}{}", url->scheme, url->host, url->target); auto rq = build_request(*url, req, m_user_agent, absolute); if (m_proxy.has_auth()) { const auto enc = Void::Encoding::Base64::encode( *m_proxy.username + ":" + *m_proxy.password); rq.set(http::field::proxy_authorization, "Basic " + enc); } response = write_read(socket, rq, m_max_body); } } } else { asio::connect(socket, resolver.resolve(url->host, url->port)); DeadlineGuard deadline{socket, req.timeout}; response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } // Transparently follow redirects when enabled. if (m_max_redirects > 0 && response.status >= 300 && response.status < 400 && redirects < m_max_redirects) { if (auto loc = response.header("location")) { target_url = resolve_redirect(*url, *loc); ++redirects; continue; } } response.elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return response; } catch (const std::exception& e) { return Void::Result::fail( std::format("Net: request to '{}' failed: {}", target_url, e.what())); } } } Void::Result::Result HttpClient::get(std::string_view url, std::vector
headers) const { Request r; r.method = Method::Get; r.url = std::string{url}; r.headers = std::move(headers); return send(r); } Void::Result::Result HttpClient::post(std::string_view url, std::string body, std::vector
headers) const { Request r; r.method = Method::Post; r.url = std::string{url}; r.body = std::move(body); r.headers = std::move(headers); return send(r); } } // namespace Void::Net