#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(_WIN32) #include #include #include #include #include #endif #include #include #include #include #include #include #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; std::atomic g_dl_temp_seq{0}; [[nodiscard]] bool equal_ascii_ci(std::string_view a, std::string_view b) noexcept { return a.size() == b.size() && std::ranges::equal(a, b, [](char x, char y) { return std::tolower(static_cast(x)) == std::tolower(static_cast(y)); }); } [[nodiscard]] bool is_sensitive_header(std::string_view name) noexcept { return equal_ascii_ci(name, "Authorization") || equal_ascii_ci(name, "Proxy-Authorization") || equal_ascii_ci(name, "Cookie") || equal_ascii_ci(name, "Set-Cookie") || equal_ascii_ci(name, "X-Api-Key"); } [[nodiscard]] std::optional find_header_ci(const std::vector
& headers, std::string_view name) noexcept { for (const auto& h : headers) { if (equal_ascii_ci(h.name, name)) { return h.value; } } return std::nullopt; } [[nodiscard]] std::string sanitize_url_for_log(std::string_view raw) { const std::size_t scheme_end = raw.find("://"); if (scheme_end == std::string_view::npos) { return std::string{raw}; } const std::size_t auth_start = scheme_end + 3U; const std::size_t slash = raw.find('/', auth_start); const std::size_t at = raw.find('@', auth_start); if (at != std::string_view::npos && (slash == std::string_view::npos || at < slash)) { std::string out{raw.substr(0, auth_start)}; out += "@"; out += raw.substr(at + 1U); return out; } return std::string{raw}; } [[nodiscard]] std::string_view method_to_str(Method m) noexcept { switch (m) { case Method::Get: return "GET"; case Method::Post: return "POST"; case Method::Put: return "PUT"; case Method::Delete: return "DELETE"; case Method::Patch: return "PATCH"; case Method::Head: return "HEAD"; case Method::Options: return "OPTIONS"; } return "GET"; } [[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; } [[nodiscard]] bool same_origin(const Url& a, const Url& b) noexcept { return equal_ascii_ci(a.scheme, b.scheme) && equal_ascii_ci(a.host, b.host) && a.port == b.port; } void strip_sensitive_headers(std::vector
& headers) { std::erase_if(headers, [](const Header& h) { return is_sensitive_header(h.name); }); } template void populate_common_headers(RequestMsg& rq, const Url& url, const std::vector
& headers, std::string_view default_ua) { const bool std_port = (url.is_tls && url.port == "443") || (!url.is_tls && url.port == "80") || url.port.empty(); if (std_port) { rq.set(http::field::host, url.host); } else { rq.set(http::field::host, url.host + ":" + url.port); } bool has_ua = false; for (const auto& h : headers) { rq.set(h.name, h.value); if (!has_ua && equal_ascii_ci(h.name, "User-Agent")) { has_ua = true; } } if (!has_ua) { rq.set(http::field::user_agent, std::string{default_ua}); } } http::request build_request(const Url& url, Method method, const std::vector
& headers, const std::optional& body, std::string_view default_ua, std::string_view target) { http::request r{to_verb(method), std::string{target}, 11}; populate_common_headers(r, url, headers, default_ua); if (body) { r.body() = *body; r.prepare_payload(); } return r; } std::vector
extract_headers(const http::fields& fields) { std::vector
out; for (const auto& f : fields) { out.push_back( {std::string{f.name_string()}, std::string{f.value()}}); } return out; } Response convert(const http::response& src) { Response out; out.status = static_cast(src.result_int()); out.body = beast::buffers_to_string(src.body().data()); out.headers = extract_headers(src.base()); return out; } template Response write_read(Stream& stream, http::request& rq, std::uint64_t max_body) { http::write(stream, rq); beast::flat_buffer buffer; http::response_parser parser; if (rq.method() == http::verb::head) { parser.skip(true); } parser.body_limit(max_body == 0 ? std::numeric_limits::max() : max_body); http::read(stream, buffer, parser); return convert(parser.get()); } 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]))); } 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; } } 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; 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()))); } } struct TlsError : std::runtime_error { using std::runtime_error::runtime_error; }; struct QuotaError : std::runtime_error { using std::runtime_error::runtime_error; }; struct CancelledError : std::runtime_error { using std::runtime_error::runtime_error; }; ssl::context make_ssl_context(bool verify_tls, const std::string& ca_file) { ssl::context ctx{ssl::context::tls_client}; (void)SSL_CTX_set_min_proto_version(ctx.native_handle(), TLS1_2_VERSION); if (verify_tls) { if (!ca_file.empty()) { boost::system::error_code ec; ctx.load_verify_file(ca_file, ec); if (ec) { throw TlsError(std::format( "TLS: failed to load CA file '{}': {}", ca_file, ec.message())); } } else { ctx.set_default_verify_paths(); } ctx.set_verify_mode(ssl::verify_peer | ssl::verify_fail_if_no_peer_cert); } else { ctx.set_verify_mode(ssl::verify_none); } return ctx; } void tls_handshake(ssl::stream& stream, const Url& url, bool verify_tls) { std::string clean_host = url.host; if (clean_host.size() >= 2 && clean_host.front() == '[' && clean_host.back() == ']') { clean_host = clean_host.substr(1, clean_host.size() - 2); } boost::system::error_code ip_ec; (void)asio::ip::make_address(clean_host, ip_ec); const bool is_ip = !ip_ec; if (!is_ip && !SSL_set_tlsext_host_name(stream.native_handle(), clean_host.c_str())) { throw TlsError("TLS: failed to set SNI hostname"); } if (verify_tls) { X509_VERIFY_PARAM* param = SSL_get0_param(stream.native_handle()); if (param == nullptr) { throw TlsError("TLS: X509_VERIFY_PARAM unavailable"); } if (is_ip) { if (X509_VERIFY_PARAM_set1_ip_asc( param, clean_host.c_str()) != 1) { throw TlsError( "TLS: failed to set peer IP verification target"); } } else { X509_VERIFY_PARAM_set_hostflags( param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); if (X509_VERIFY_PARAM_set1_host(param, clean_host.c_str(), clean_host.size()) != 1) { throw TlsError( "TLS: failed to set peer hostname verification"); } } } boost::system::error_code hs_ec; stream.handshake(ssl::stream_base::client, hs_ec); if (hs_ec) { throw TlsError(std::format("TLS handshake failed: {}", hs_ec.message())); } } class DeadlineGuard { public: DeadlineGuard(tcp::socket& socket, std::chrono::seconds timeout, std::stop_token stop = {}) : m_stop(std::move(stop)), m_stop_cb(socket.is_open() ? m_stop : std::stop_token{}, StopShutdown{ &m_cancelled, socket.is_open() ? socket.native_handle() : tcp::socket::native_handle_type{}, socket.is_open()}) { if (!socket.is_open() || timeout <= std::chrono::seconds::zero()) { 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.store(true, std::memory_order_release); } }); } 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.load(std::memory_order_acquire); } [[nodiscard]] bool cancelled() const noexcept { return m_cancelled.load(std::memory_order_acquire); } private: struct StopShutdown { std::atomic* cancelled{nullptr}; tcp::socket::native_handle_type fd{}; bool has_fd{false}; void operator()() const noexcept { if (cancelled != nullptr) { cancelled->store(true, std::memory_order_release); } if (has_fd) { #if defined(_WIN32) ::shutdown(fd, SD_BOTH); #else ::shutdown(fd, SHUT_RDWR); #endif } } }; std::thread m_worker; std::mutex m_mutex; std::condition_variable m_cv; bool m_done{false}; std::atomic m_timed_out{false}; std::atomic m_cancelled{false}; std::stop_token m_stop{}; std::stop_callback m_stop_cb; }; Response finish(tcp::socket& socket, std::optional>& tls, ssl::context& ctx, const Url& url, Method method, const std::vector
& headers, const std::optional& body, std::string_view ua, std::uint64_t max_body, bool verify_tls) { if (url.is_tls) { tls.emplace(std::move(socket), ctx); tls_handshake(*tls, url, verify_tls); auto rq = build_request(url, method, headers, body, ua, url.target); return write_read(*tls, rq, max_body); } auto rq = build_request(url, method, headers, body, ua, url.target); return write_read(socket, rq, max_body); } class OwnedTempFile { public: static Void::Result::Result create(const std::filesystem::path& destination) { std::filesystem::path parent = destination.parent_path(); if (parent.empty()) { parent = "."; } std::error_code ec; std::filesystem::create_directories(parent, ec); if (ec) { return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: create_directories failed: {}", ec.message()), ec)}; } const std::filesystem::path tmp_path = parent / std::format(".void-dl-{}-{}", static_cast(::getpid()), g_dl_temp_seq.fetch_add( 1, std::memory_order_relaxed)); const int fd = ::open( tmp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0644); if (fd < 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: create temp download file failed: " "{}", std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } return OwnedTempFile{fd, tmp_path, destination}; } OwnedTempFile(OwnedTempFile&& o) noexcept : m_fd(std::exchange(o.m_fd, -1)), m_tmp(std::move(o.m_tmp)), m_dest(std::move(o.m_dest)), m_committed(std::exchange(o.m_committed, true)) { } OwnedTempFile& operator=(OwnedTempFile&&) = delete; OwnedTempFile(const OwnedTempFile&) = delete; OwnedTempFile& operator=(const OwnedTempFile&) = delete; ~OwnedTempFile() noexcept { discard(); } [[nodiscard]] Void::Result::Result write_all(std::span data) { std::size_t off = 0; while (off < data.size()) { const ssize_t w = ::write( m_fd, reinterpret_cast(data.data()) + off, data.size() - off); if (w < 0 && errno == EINTR) { continue; } if (w <= 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: write download file failed: " "{}", std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } off += static_cast(w); } return {}; } [[nodiscard]] Void::Result::Result commit() { if (::fsync(m_fd) != 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: fsync download file failed: {}", std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } const int raw = std::exchange(m_fd, -1); if (::close(raw) != 0) { discard(); return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: close download file failed: {}", std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } std::error_code ec; std::filesystem::rename(m_tmp, m_dest, ec); if (ec) { discard(); return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: rename download file failed: {}", ec.message()), ec)}; } m_committed = true; return {}; } void discard() noexcept { if (m_fd >= 0) { (void)::close(m_fd); m_fd = -1; } if (!m_committed && !m_tmp.empty()) { std::error_code ec; std::filesystem::remove(m_tmp, ec); } m_committed = true; } private: OwnedTempFile(int fd, std::filesystem::path tmp, std::filesystem::path dest) : m_fd(fd), m_tmp(std::move(tmp)), m_dest(std::move(dest)) { } int m_fd{-1}; std::filesystem::path m_tmp{}; std::filesystem::path m_dest{}; bool m_committed{false}; }; template DownloadResult read_stream_to_file( Stream& stream, const Url& url, const std::vector
& headers, std::string_view ua, std::string_view target, const std::filesystem::path& destination, const DownloadOptions& options) { auto rq = build_request(url, Method::Get, headers, std::nullopt, ua, target); http::write(stream, rq); beast::flat_buffer rx_buf; http::response_parser parser; parser.body_limit(std::numeric_limits::max()); http::read_header(stream, rx_buf, parser); const auto status = static_cast(parser.get().result_int()); auto resp_headers = extract_headers(parser.get().base()); const auto boost_cl = parser.content_length(); const std::optional declared_total = boost_cl.has_value() ? std::optional{*boost_cl} : std::nullopt; if (options.max_bytes > 0 && declared_total.has_value() && *declared_total > options.max_bytes) { throw QuotaError(std::format( "Net: Content-Length {} exceeds max_bytes quota {}", *declared_total, options.max_bytes)); } auto tmp = OwnedTempFile::create(destination); if (!tmp.has_value()) { throw std::runtime_error(tmp.error().message()); } std::vector chunk(64ULL * 1024U); std::uint64_t total_written = 0; while (!parser.is_done()) { if (options.stop.stop_requested()) { throw CancelledError("Net: download cancelled"); } parser.get().body().data = chunk.data(); parser.get().body().size = chunk.size(); beast::error_code ec; (void)http::read_some(stream, rx_buf, parser, ec); const bool eof_ok = (ec == http::error::end_of_stream && !declared_total.has_value()); if (ec && ec != http::error::need_buffer && !eof_ok) { throw boost::system::system_error{ec}; } const std::size_t got = chunk.size() - parser.get().body().size; if (got > 0) { const auto amt = static_cast(got); if (options.max_bytes > 0 && amt > options.max_bytes - total_written) { throw QuotaError(std::format( "Net: download exceeded max_bytes quota {}", options.max_bytes)); } const auto slice = std::span{chunk.data(), got}; if (auto wr = tmp->write_all(slice); !wr.has_value()) { throw std::runtime_error(wr.error().message()); } total_written += amt; if (options.on_chunk) { options.on_chunk(slice); } if (options.on_progress) { options.on_progress(TransferProgress{ .bytes_transferred = total_written, .total_bytes = declared_total}); } } if (eof_ok) { break; } } if (auto cm = tmp->commit(); !cm.has_value()) { throw std::runtime_error(cm.error().message()); } return DownloadResult{ .status = status, .headers = std::move(resp_headers), .bytes_written = total_written, .elapsed = {}, }; } template Response stream_file_request(Stream& stream, const Url& url, std::string_view target, int file_fd, std::uint64_t file_size, const UploadOptions& options, std::string_view default_ua, std::uint64_t max_response_body) { http::request rq{to_verb(options.method), std::string{target}, 11}; populate_common_headers(rq, url, options.headers, default_ua); if (!find_header_ci(options.headers, "Content-Type").has_value() && !options.content_type.empty()) { rq.set(http::field::content_type, options.content_type); } rq.content_length(file_size); rq.body().data = nullptr; rq.body().size = 0; rq.body().more = (file_size > 0); http::request_serializer sr{rq}; http::write_header(stream, sr); if (file_size > 0) { std::array buf{}; std::uint64_t sent_total = 0; while (sent_total < file_size) { if (options.stop.stop_requested()) { throw CancelledError("Net: upload cancelled"); } const std::size_t want = static_cast( std::min(buf.size(), file_size - sent_total)); const ssize_t r = ::read(file_fd, buf.data(), want); if (r < 0 && errno == EINTR) { continue; } if (r <= 0) { throw std::runtime_error( "Net: source file shrunk or read failed during " "upload"); } const auto amt = static_cast(r); rq.body().data = buf.data(); rq.body().size = static_cast(r); rq.body().more = (sent_total + amt < file_size); beast::error_code ec; (void)http::write(stream, sr, ec); if (ec == http::error::need_buffer) { ec = {}; } if (ec) { throw boost::system::system_error{ec}; } sent_total += amt; if (options.on_progress) { options.on_progress(TransferProgress{ .bytes_transferred = sent_total, .total_bytes = file_size}); } } } else { beast::error_code ec; (void)http::write(stream, sr, ec); if (ec && ec != http::error::need_buffer) { throw boost::system::system_error{ec}; } } beast::flat_buffer rx_buf; http::response_parser parser; parser.body_limit( max_response_body == 0 ? std::numeric_limits::max() : max_response_body); http::read(stream, rx_buf, parser); return convert(parser.get()); } 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 std::optional Response::header(std::string_view name) const { return find_header_ci(headers, name); } std::optional DownloadResult::header(std::string_view name) const { return find_header_ci(headers, name); } HttpClient::HttpClient(HttpClientOptions options) : m_proxy(std::move(options.proxy)), m_user_agent(std::move(options.user_agent)), m_verify_tls(options.verify_tls), m_ca_file(std::move(options.ca_file)), m_max_body(options.max_body_size), m_max_redirects(options.max_redirects), m_allow_insecure_redirects(options.allow_insecure_redirects) { } HttpClient HttpClient::secure(ProxyConfig proxy) { return HttpClient{HttpClientOptions{ .proxy = std::move(proxy), .verify_tls = true, }}; } std::string HttpClient::format_request_diagnostics(const Request& req) { std::string out = std::format("{} {}", method_to_str(req.method), sanitize_url_for_log(req.url)); for (const auto& h : req.headers) { out += "\n "; out += h.name; out += ": "; out += is_sensitive_header(h.name) ? "" : h.value; } return out; } Void::Result::Result HttpClient::send(const Request& req) const { std::string target_url = req.url; std::vector
active_headers = req.headers; int redirects = 0; while (true) { const auto url = Url::parse(target_url); if (!url) { return std::unexpected{make_net_error( NetErrorCode::invalid_url, std::format("Net: invalid URL '{}'", sanitize_url_for_log(target_url)))}; } bool cancelled = false; bool timed_out = false; try { const auto start = std::chrono::steady_clock::now(); asio::io_context ioc; ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); Response response; tcp::resolver resolver{ioc}; 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.method, active_headers, req.body, m_user_agent, m_max_body, m_verify_tls); } else { if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); response = finish(socket, tls, ctx, *url, req.method, active_headers, req.body, m_user_agent, m_max_body, m_verify_tls); } else { const std::string absolute = std::format( "{}://{}{}", url->scheme, url->host, url->target); auto rq = build_request(*url, req.method, active_headers, req.body, 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); } } timed_out = deadline.timed_out(); cancelled = deadline.cancelled(); } else { asio::connect(socket, resolver.resolve(url->host, url->port)); DeadlineGuard deadline{socket, req.timeout}; response = finish(socket, tls, ctx, *url, req.method, active_headers, req.body, m_user_agent, m_max_body, m_verify_tls); timed_out = deadline.timed_out(); cancelled = deadline.cancelled(); } if (m_max_redirects > 0 && response.status >= 300 && response.status < 400 && redirects < m_max_redirects) { if (auto loc = response.header("location")) { const std::string next_url = resolve_redirect(*url, *loc); const auto next_parsed = Url::parse(next_url); if (!next_parsed) { return std::unexpected{make_net_error( NetErrorCode::invalid_url, "Net: invalid redirect Location URL")}; } if (url->is_tls && !next_parsed->is_tls && m_verify_tls && !m_allow_insecure_redirects) { return std::unexpected{make_net_error( NetErrorCode::redirect_blocked, "Net: blocked HTTPS to HTTP downgrade " "redirect")}; } if (!same_origin(*url, *next_parsed)) { strip_sensitive_headers(active_headers); } target_url = next_url; ++redirects; continue; } } response.elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return response; } catch (const TlsError& e) { return std::unexpected{make_net_error( NetErrorCode::tls_error, std::format("Net: TLS request to '{}' failed: {}", sanitize_url_for_log(target_url), e.what()))}; } catch (const std::exception& e) { if (cancelled) { return std::unexpected{make_net_error( NetErrorCode::cancelled, std::format("Net: request to '{}' cancelled", sanitize_url_for_log(target_url)))}; } if (timed_out) { return std::unexpected{make_net_error( NetErrorCode::timeout, std::format("Net: request to '{}' timed out: {}", sanitize_url_for_log(target_url), e.what()))}; } return std::unexpected{make_net_error( NetErrorCode::connect_failed, std::format("Net: request to '{}' failed: {}", sanitize_url_for_log(target_url), e.what()))}; } } } Void::Result::Result HttpClient::download_to_file(std::string_view url_str, const std::filesystem::path& destination, const DownloadOptions& options) const { if (options.stop.stop_requested()) { return std::unexpected{make_net_error( NetErrorCode::cancelled, "Net: download cancelled")}; } std::string target_url{url_str}; std::vector
active_headers = options.headers; int redirects = 0; while (true) { if (options.stop.stop_requested()) { return std::unexpected{make_net_error( NetErrorCode::cancelled, "Net: download cancelled")}; } const auto url = Url::parse(target_url); if (!url) { return std::unexpected{make_net_error( NetErrorCode::invalid_url, std::format("Net: invalid URL '{}'", sanitize_url_for_log(target_url)))}; } bool timed_out = false; bool cancelled = false; try { const auto start = std::chrono::steady_clock::now(); asio::io_context ioc; ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); tcp::resolver resolver{ioc}; 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))); } else { asio::connect(socket, resolver.resolve(url->host, url->port)); } DeadlineGuard deadline{socket, options.timeout, options.stop}; DownloadResult result; const auto finish_stream = [&]() { if (m_proxy.enabled()) { if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); } else if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); } else { const std::string absolute = std::format( "{}://{}{}", url->scheme, url->host, url->target); auto h = active_headers; if (m_proxy.has_auth()) { const auto enc = Void::Encoding::Base64::encode( *m_proxy.username + ":" + *m_proxy.password); h.push_back(Header{"Proxy-Authorization", "Basic " + enc}); } result = read_stream_to_file( socket, *url, h, m_user_agent, absolute, destination, options); return; } } if (url->is_tls) { tls.emplace(std::move(socket), ctx); tls_handshake(*tls, *url, m_verify_tls); result = read_stream_to_file( *tls, *url, active_headers, m_user_agent, url->target, destination, options); } else { result = read_stream_to_file( socket, *url, active_headers, m_user_agent, url->target, destination, options); } }; finish_stream(); timed_out = deadline.timed_out(); cancelled = deadline.cancelled(); if (m_max_redirects > 0 && result.status >= 300 && result.status < 400 && redirects < m_max_redirects) { if (auto loc = result.header("location")) { const std::string next_url = resolve_redirect(*url, *loc); const auto next_parsed = Url::parse(next_url); if (!next_parsed) { return std::unexpected{make_net_error( NetErrorCode::invalid_url, "Net: invalid redirect Location URL")}; } if (url->is_tls && !next_parsed->is_tls && m_verify_tls && !m_allow_insecure_redirects) { return std::unexpected{make_net_error( NetErrorCode::redirect_blocked, "Net: blocked HTTPS to HTTP downgrade " "redirect")}; } if (!same_origin(*url, *next_parsed)) { strip_sensitive_headers(active_headers); } std::error_code rm_ec; std::filesystem::remove(destination, rm_ec); target_url = next_url; ++redirects; continue; } } result.elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return result; } catch (const QuotaError& e) { return std::unexpected{ make_net_error(NetErrorCode::quota_exceeded, e.what())}; } catch (const CancelledError& e) { return std::unexpected{ make_net_error(NetErrorCode::cancelled, e.what())}; } catch (const TlsError& e) { return std::unexpected{make_net_error( NetErrorCode::tls_error, std::format("Net: TLS download '{}' failed: {}", sanitize_url_for_log(target_url), e.what()))}; } catch (const std::exception& e) { if (cancelled || options.stop.stop_requested()) { return std::unexpected{make_net_error( NetErrorCode::cancelled, "Net: download cancelled")}; } if (timed_out) { return std::unexpected{make_net_error( NetErrorCode::timeout, std::format("Net: download '{}' timed out: {}", sanitize_url_for_log(target_url), e.what()))}; } return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: download '{}' failed: {}", sanitize_url_for_log(target_url), e.what()))}; } } } Void::Result::Result HttpClient::upload_file(std::string_view url_str, const std::filesystem::path& source_path, const UploadOptions& options) const { if (options.stop.stop_requested()) { return std::unexpected{ make_net_error(NetErrorCode::cancelled, "Net: upload cancelled")}; } const int raw_fd = ::open(source_path.c_str(), O_RDONLY | O_CLOEXEC); if (raw_fd < 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: cannot open upload file '{}': {}", source_path.string(), std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } struct FdClose { int fd; ~FdClose() noexcept { if (fd >= 0) (void)::close(fd); } } fd_guard{raw_fd}; struct stat st{}; if (::fstat(raw_fd, &st) != 0 || !S_ISREG(st.st_mode)) { return std::unexpected{make_net_error( NetErrorCode::invalid_argument, std::format("Net: upload source '{}' is not a regular file", source_path.string()))}; } const auto file_size = static_cast(st.st_size); if (options.max_upload_bytes > 0 && file_size > options.max_upload_bytes) { return std::unexpected{make_net_error( NetErrorCode::quota_exceeded, std::format("Net: upload file size {} exceeds limit {}", file_size, options.max_upload_bytes))}; } const auto url = Url::parse(url_str); if (!url) { return std::unexpected{make_net_error( NetErrorCode::invalid_url, std::format("Net: invalid URL '{}'", sanitize_url_for_log(url_str)))}; } bool timed_out = false; bool cancelled = false; try { const auto start = std::chrono::steady_clock::now(); asio::io_context ioc; ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); tcp::resolver resolver{ioc}; 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))); } else { asio::connect(socket, resolver.resolve(url->host, url->port)); } DeadlineGuard deadline{socket, options.timeout, options.stop}; Response response; if (m_proxy.enabled()) { if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); } else if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); } else { const std::string absolute = std::format( "{}://{}{}", url->scheme, url->host, url->target); response = stream_file_request( socket, *url, absolute, raw_fd, file_size, options, m_user_agent, m_max_body); timed_out = deadline.timed_out(); cancelled = deadline.cancelled(); response.elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return response; } } if (url->is_tls) { tls.emplace(std::move(socket), ctx); tls_handshake(*tls, *url, m_verify_tls); response = stream_file_request( *tls, *url, url->target, raw_fd, file_size, options, m_user_agent, m_max_body); } else { response = stream_file_request( socket, *url, url->target, raw_fd, file_size, options, m_user_agent, m_max_body); } timed_out = deadline.timed_out(); cancelled = deadline.cancelled(); response.elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return response; } catch (const CancelledError& e) { return std::unexpected{ make_net_error(NetErrorCode::cancelled, e.what())}; } catch (const TlsError& e) { return std::unexpected{make_net_error( NetErrorCode::tls_error, std::format("Net: TLS upload '{}' failed: {}", sanitize_url_for_log(url_str), e.what()))}; } catch (const std::exception& e) { if (cancelled || options.stop.stop_requested()) { return std::unexpected{make_net_error( NetErrorCode::cancelled, "Net: upload cancelled")}; } if (timed_out) { return std::unexpected{make_net_error( NetErrorCode::timeout, std::format("Net: upload '{}' timed out: {}", sanitize_url_for_log(url_str), e.what()))}; } return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net: upload '{}' failed: {}", sanitize_url_for_log(url_str), 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); } Void::Result::Result HttpClient::put_file(std::string_view url, const std::filesystem::path& source_path, std::vector
headers, std::string content_type) const { UploadOptions opts; opts.method = Method::Put; opts.headers = std::move(headers); opts.content_type = std::move(content_type); return upload_file(url, source_path, opts); } Void::Result::Result HttpClient::post_file(std::string_view url, const std::filesystem::path& source_path, std::vector
headers, std::string content_type) const { UploadOptions opts; opts.method = Method::Post; opts.headers = std::move(headers); opts.content_type = std::move(content_type); return upload_file(url, source_path, opts); } } // namespace Void::Net