Files
Library/src/Net/Http.cpp
T

1524 lines
46 KiB
C++

#include <Void/Net/Http.hpp>
#include <Void/Net/Url.hpp>
#include <Void/Text/Base64.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/write.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/http/buffer_body.hpp>
#include <boost/beast/ssl.hpp>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#if !defined(_WIN32)
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <sys/stat.h>
#endif
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <format>
#include <limits>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <stop_token>
#include <thread>
#include <vector>
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<std::uint64_t> g_dl_temp_seq{0};
#if defined(_WIN32)
// Win32 paths above MAX_PATH must use the extended-length prefix, and
// forward slashes are not accepted by the wide file APIs.
[[nodiscard]] std::filesystem::path
extended_path(const std::filesystem::path& path)
{
std::error_code ec;
const auto absolute = std::filesystem::absolute(path, ec);
std::wstring text = (ec ? path : absolute).wstring();
std::replace(text.begin(), text.end(), L'/', L'\\');
if (text.rfind(L"\\\\?\\", 0) == 0 || text.size() < MAX_PATH) {
return std::filesystem::path{text};
}
if (text.rfind(L"\\\\", 0) == 0) {
return std::filesystem::path{L"\\\\?\\UNC\\" + text.substr(2)};
}
return std::filesystem::path{L"\\\\?\\" + text};
}
#endif
[[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<unsigned char>(x)) ==
std::tolower(static_cast<unsigned char>(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<std::string_view>
find_header_ci(const std::vector<Header>& 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 += "<redacted>@";
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<Header>& headers)
{
std::erase_if(headers, [](const Header& h) {
return is_sensitive_header(h.name);
});
}
template <typename RequestMsg>
void populate_common_headers(RequestMsg& rq, const Url& url,
const std::vector<Header>& 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<http::string_body>
build_request(const Url& url, Method method,
const std::vector<Header>& headers,
const std::optional<std::string>& body,
std::string_view default_ua, std::string_view target)
{
http::request<http::string_body> 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<Header> extract_headers(const http::fields& fields)
{
std::vector<Header> 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<http::dynamic_body>& src)
{
Response out;
out.status = static_cast<std::uint16_t>(src.result_int());
out.body = beast::buffers_to_string(src.body().data());
out.headers = extract_headers(src.base());
return out;
}
template <typename Stream>
Response write_read(Stream& stream, http::request<http::string_body>& rq,
std::uint64_t max_body)
{
http::write(stream, rq);
beast::flat_buffer buffer;
http::response_parser<http::dynamic_body> parser;
if (rq.method() == http::verb::head) {
parser.skip(true);
}
parser.body_limit(max_body == 0
? std::numeric_limits<std::uint64_t>::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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> a{0x01};
a.push_back(static_cast<std::uint8_t>(proxy.username->size()));
a.insert(a.end(), proxy.username->begin(),
proxy.username->end());
a.push_back(static_cast<std::uint8_t>(proxy.password->size()));
a.insert(a.end(), proxy.password->begin(),
proxy.password->end());
asio::write(socket, asio::buffer(a));
std::vector<std::uint8_t> 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<std::uint8_t> 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::uint16_t>(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<std::uint8_t>(url.host.size()));
creq.insert(creq.end(), url.host.begin(), url.host.end());
}
creq.push_back(static_cast<std::uint8_t>((port >> 8) & 0xFF));
creq.push_back(static_cast<std::uint8_t>(port & 0xFF));
asio::write(socket, asio::buffer(creq));
std::vector<std::uint8_t> 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<std::uint8_t> b(6);
asio::read(socket, asio::buffer(b));
break;
}
case 0x03: {
std::vector<std::uint8_t> len(1);
asio::read(socket, asio::buffer(len));
std::vector<std::uint8_t> b(len[0] + 2u);
asio::read(socket, asio::buffer(b));
break;
}
case 0x04: {
std::vector<std::uint8_t> 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<http::empty_body> 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<http::empty_body> 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<tcp::socket>& 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<bool>* 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<bool> m_timed_out{false};
std::atomic<bool> m_cancelled{false};
std::stop_token m_stop{};
std::stop_callback<StopShutdown> m_stop_cb;
};
Response finish(tcp::socket& socket,
std::optional<ssl::stream<tcp::socket>>& tls,
ssl::context& ctx, const Url& url, Method method,
const std::vector<Header>& headers,
const std::optional<std::string>& 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<OwnedTempFile>
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-{}-{}",
#if defined(_WIN32)
static_cast<long long>(::_getpid()),
#else
static_cast<long long>(::getpid()),
#endif
g_dl_temp_seq.fetch_add(
1, std::memory_order_relaxed));
#if defined(_WIN32)
// Create exclusively next to the destination: an existing entry
// (including a reparse point) is never followed or truncated.
const int fd = ::_wopen(
extended_path(tmp_path).c_str(),
_O_WRONLY | _O_CREAT | _O_EXCL | _O_BINARY | _O_NOINHERIT,
_S_IREAD | _S_IWRITE);
#else
const int fd = ::open(
tmp_path.c_str(),
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW,
0644);
#endif
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<void>
write_all(std::span<const std::byte> data)
{
std::size_t off = 0;
while (off < data.size()) {
#if defined(_WIN32)
const int w = ::_write(
m_fd,
reinterpret_cast<const char*>(data.data()) + off,
static_cast<unsigned int>(data.size() - off));
#else
const ssize_t w = ::write(
m_fd,
reinterpret_cast<const char*>(data.data()) + off,
data.size() - off);
#endif
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<std::size_t>(w);
}
return {};
}
[[nodiscard]] Void::Result::Result<void> commit()
{
#if defined(_WIN32)
if (::_commit(m_fd) != 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: flush 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()})};
}
// Never replace a reparse point: a hostile workspace entry
// could redirect the completed download outside the target.
const DWORD attributes =
::GetFileAttributesW(extended_path(m_dest).c_str());
if (attributes != INVALID_FILE_ATTRIBUTES &&
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
discard();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net: refusing to replace a reparse-point "
"download destination")};
}
if (::MoveFileExW(extended_path(m_tmp).c_str(),
extended_path(m_dest).c_str(),
MOVEFILE_REPLACE_EXISTING |
MOVEFILE_WRITE_THROUGH) == 0) {
const DWORD error = ::GetLastError();
discard();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net: replace download file failed: "
"win32={}",
error),
std::error_code{static_cast<int>(error),
std::system_category()})};
}
#else
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)};
}
#endif
m_committed = true;
return {};
}
void discard() noexcept
{
if (m_fd >= 0) {
#if defined(_WIN32)
(void)::_close(m_fd);
#else
(void)::close(m_fd);
#endif
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 <typename Stream>
DownloadResult read_stream_to_file(
Stream& stream, const Url& url, const std::vector<Header>& 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<http::buffer_body> parser;
parser.body_limit(std::numeric_limits<std::uint64_t>::max());
http::read_header(stream, rx_buf, parser);
const auto status =
static_cast<std::uint16_t>(parser.get().result_int());
auto resp_headers = extract_headers(parser.get().base());
const auto boost_cl = parser.content_length();
const std::optional<std::uint64_t> declared_total =
boost_cl.has_value()
? std::optional<std::uint64_t>{*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<std::byte> 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<std::uint64_t>(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<const std::byte>{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 <typename Stream>
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<http::buffer_body> 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<http::buffer_body> sr{rq};
http::write_header(stream, sr);
if (file_size > 0) {
std::array<std::byte, 64 * 1024> 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::size_t>(
std::min<std::uint64_t>(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<std::uint64_t>(r);
rq.body().data = buf.data();
rq.body().size = static_cast<std::size_t>(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<http::dynamic_body> parser;
parser.body_limit(
max_response_body == 0
? std::numeric_limits<std::uint64_t>::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<std::string_view>
Response::header(std::string_view name) const
{
return find_header_ci(headers, name);
}
std::optional<std::string_view>
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) ? "<redacted>" : h.value;
}
return out;
}
Void::Result::Result<Response, Void::Result::Error>
HttpClient::send(const Request& req) const
{
std::string target_url = req.url;
Method active_method = req.method;
std::optional<std::string> active_body = req.body;
std::vector<Header> active_headers = req.headers;
int redirects = 0;
const auto overall_start = std::chrono::steady_clock::now();
const bool has_deadline = req.timeout > std::chrono::seconds::zero();
const auto overall_deadline = overall_start + req.timeout;
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)))};
}
std::chrono::seconds remaining_timeout = req.timeout;
if (has_deadline) {
const auto now = std::chrono::steady_clock::now();
if (now >= overall_deadline) {
return std::unexpected{make_net_error(
NetErrorCode::timeout,
std::format("Net: request to '{}' timed out across "
"redirects",
sanitize_url_for_log(target_url)))};
}
const auto rem_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
overall_deadline - now);
remaining_timeout = std::chrono::seconds{
std::max<long long>(1, (rem_ms.count() + 999) / 1000)};
}
bool cancelled = false;
bool timed_out = false;
try {
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<ssl::stream<tcp::socket>> tls;
if (m_proxy.enabled()) {
asio::connect(socket, resolver.resolve(
m_proxy.host,
std::to_string(m_proxy.port)));
DeadlineGuard deadline{socket, remaining_timeout};
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
socks5_connect(socket, *url, m_proxy);
response = finish(socket, tls, ctx, *url, active_method,
active_headers, active_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,
active_method, active_headers,
active_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, active_method,
active_headers, active_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, remaining_timeout};
response =
finish(socket, tls, ctx, *url, active_method,
active_headers, active_body, m_user_agent,
m_max_body, m_verify_tls);
timed_out = deadline.timed_out();
cancelled = deadline.cancelled();
}
const bool is_redirect_status =
response.status == 301 || response.status == 302 ||
response.status == 303 || response.status == 307 ||
response.status == 308;
if (m_max_redirects > 0 && is_redirect_status &&
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);
}
// RFC 9110 §15.4.4: 303 changes non-HEAD to GET and
// drops body + representation headers.
if (response.status == 303 &&
active_method != Method::Head) {
active_method = Method::Get;
active_body.reset();
std::erase_if(active_headers, [](const Header& h) {
return equal_ascii_ci(h.name,
"Content-Length") ||
equal_ascii_ci(h.name,
"Content-Type") ||
equal_ascii_ci(h.name,
"Transfer-Encoding");
});
}
target_url = next_url;
++redirects;
continue;
}
}
response.elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - overall_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<DownloadResult, Void::Result::Error>
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<Header> 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<ssl::stream<tcp::socket>> 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::milliseconds>(
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<Response, Void::Result::Error>
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<std::uint64_t>(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<ssl::stream<tcp::socket>> 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::milliseconds>(
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::milliseconds>(
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<Response, Void::Result::Error>
HttpClient::get(std::string_view url, std::vector<Header> headers) const
{
Request r;
r.method = Method::Get;
r.url = std::string{url};
r.headers = std::move(headers);
return send(r);
}
Void::Result::Result<Response, Void::Result::Error>
HttpClient::post(std::string_view url, std::string body,
std::vector<Header> 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<Response, Void::Result::Error>
HttpClient::put_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> 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<Response, Void::Result::Error>
HttpClient::post_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> 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