Add Void::Net — HTTP client + URL parser + SOCKS5/CONNECT proxies
New SHARED module built on Boost.Beast/Asio + OpenSSL (all generic, no application coupling): - Void::Net::Url — RFC 3986 parse into scheme/host/port/path/query/target (Boost.URL), with scheme-default ports and TLS detection. - Void::Net::HttpClient — synchronous GET/POST/send with TLS (SNI), configurable User-Agent and TLS verification, request/response types. - Proxy support: HTTP CONNECT tunnelling for TLS targets, plain-HTTP forwarding, and a full SOCKS5 handshake (auth, IPv4/IPv6/domain). - Reuses Void::Encoding::Base64 for proxy auth. Build wiring: Dependencies.cmake resolves Boost (headers + url) and OpenSSL + Threads via find_package (system Boost/OpenSSL). Tests cover URL parsing and live localhost HTTP GET/POST round-trips (full suite 1136 pass). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
fb0506581f
commit
c92dff6ff7
8 files changed
+718
-5
No files matched your search
@@ -2,17 +2,21 @@ include(FetchContent)
|
||||
|
||||
function(void_fetch_dependency DEP_NAME)
|
||||
if(DEP_NAME STREQUAL "Boost")
|
||||
if(TARGET Boost::stacktrace_backtrace)
|
||||
# Components Void uses across modules: stacktrace_backtrace (Stacktrace),
|
||||
# url + system (Net; beast/asio are header-only and come via Boost::headers).
|
||||
if(TARGET Boost::stacktrace_backtrace AND TARGET Boost::url)
|
||||
return()
|
||||
endif()
|
||||
|
||||
find_package(Boost QUIET COMPONENTS stacktrace_backtrace)
|
||||
if(TARGET Boost::stacktrace_backtrace)
|
||||
# On modern Boost (1.85+) system/asio/beast are header-only and folded
|
||||
# into Boost::headers; only stacktrace_backtrace and url are components.
|
||||
find_package(Boost QUIET COMPONENTS stacktrace_backtrace url)
|
||||
if(TARGET Boost::stacktrace_backtrace AND TARGET Boost::url)
|
||||
return()
|
||||
endif()
|
||||
|
||||
message(STATUS "[Void] Boost::stacktrace_backtrace not found — falling back to FetchContent")
|
||||
set(BOOST_INCLUDE_LIBRARIES stacktrace CACHE STRING "" FORCE)
|
||||
message(STATUS "[Void] Boost (stacktrace/url) not found — falling back to FetchContent")
|
||||
set(BOOST_INCLUDE_LIBRARIES "stacktrace;url;system;beast;asio" CACHE STRING "" FORCE)
|
||||
set(BOOST_ENABLE_CMAKE ON CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(Boost
|
||||
URL https://github.com/boostorg/boost/releases/download/boost-1.84.0/boost-1.84.0.tar.xz
|
||||
@@ -26,6 +30,21 @@ function(void_fetch_dependency DEP_NAME)
|
||||
endif()
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(DEP_NAME STREQUAL "OpenSSL")
|
||||
if(NOT TARGET OpenSSL::SSL)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
endif()
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(DEP_NAME STREQUAL "Threads")
|
||||
if(NOT TARGET Threads::Threads)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG ON)
|
||||
find_package(Threads REQUIRED)
|
||||
endif()
|
||||
return()
|
||||
endif()
|
||||
# FIXME: Add if needed external
|
||||
# if(DEP_NAME STREQUAL "glaze")
|
||||
# if(NOT glaze_POPULATED)
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
|
||||
enum class Method { Get, Post, Put, Delete, Patch, Head, Options };
|
||||
|
||||
struct Header {
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct Request {
|
||||
Method method = Method::Get;
|
||||
std::string url;
|
||||
std::vector<Header> headers;
|
||||
std::optional<std::string> body;
|
||||
std::chrono::seconds timeout{30};
|
||||
};
|
||||
|
||||
struct Response {
|
||||
std::uint16_t status = 0;
|
||||
std::vector<Header> headers;
|
||||
std::string body;
|
||||
std::chrono::milliseconds elapsed{0};
|
||||
|
||||
[[nodiscard]] bool ok() const noexcept
|
||||
{
|
||||
return status >= 200 && status < 300;
|
||||
}
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const;
|
||||
};
|
||||
|
||||
/// Proxy configuration. `None` connects directly. `Http` uses CONNECT
|
||||
/// tunnelling for TLS targets (and request forwarding for plain HTTP).
|
||||
/// `Socks5` performs a full SOCKS5 handshake (with optional auth).
|
||||
struct ProxyConfig {
|
||||
enum class Kind { None, Http, Socks5 };
|
||||
Kind kind = Kind::None;
|
||||
std::string host;
|
||||
std::uint16_t port = 0;
|
||||
std::optional<std::string> username;
|
||||
std::optional<std::string> password;
|
||||
|
||||
[[nodiscard]] bool enabled() const noexcept
|
||||
{
|
||||
return kind != Kind::None && !host.empty() && port != 0;
|
||||
}
|
||||
[[nodiscard]] bool has_auth() const noexcept
|
||||
{
|
||||
return username.has_value() && password.has_value();
|
||||
}
|
||||
};
|
||||
|
||||
/// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
|
||||
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
|
||||
/// Generic: no application-specific defaults beyond a configurable
|
||||
/// User-Agent. Thread-safe for concurrent independent calls (each request
|
||||
/// uses its own io_context).
|
||||
class HttpClient
|
||||
{
|
||||
public:
|
||||
|
||||
HttpClient() = default;
|
||||
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {}
|
||||
|
||||
void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
|
||||
[[nodiscard]] const ProxyConfig& proxy() const noexcept
|
||||
{
|
||||
return m_proxy;
|
||||
}
|
||||
|
||||
/// Default User-Agent applied when a request sets none.
|
||||
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
|
||||
|
||||
/// Verify TLS peer certificates (default: false, matching common
|
||||
/// scraping/proxy use; enable for security-sensitive callers).
|
||||
void set_verify_tls(bool on) noexcept { m_verify_tls = on; }
|
||||
|
||||
/// Execute a request. A per-request `Request::proxy` is not modelled;
|
||||
/// the client-level proxy applies. Returns an Error only on transport
|
||||
/// failure — a non-2xx HTTP response is a successful Result.
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
send(const Request& req) const;
|
||||
|
||||
// Convenience wrappers.
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
get(std::string_view url,
|
||||
std::vector<Header> headers = {}) const;
|
||||
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
|
||||
post(std::string_view url, std::string body,
|
||||
std::vector<Header> headers = {}) const;
|
||||
|
||||
private:
|
||||
|
||||
ProxyConfig m_proxy{};
|
||||
std::string m_user_agent = "Void.Net/1.0";
|
||||
bool m_verify_tls = false;
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
|
||||
/// Parsed components of a URL. `target` is the request-target
|
||||
/// (path + "?" + query) ready for an HTTP request line; `port` is filled
|
||||
/// with the scheme default (80/443) when absent.
|
||||
struct Url {
|
||||
std::string scheme;
|
||||
std::string host;
|
||||
std::string port;
|
||||
std::string path; ///< encoded path (defaults to "/")
|
||||
std::string query; ///< encoded query (no leading '?')
|
||||
std::string target; ///< path + ("?" + query)
|
||||
bool is_tls = false; ///< scheme is https/wss
|
||||
|
||||
/// Parse `url` (RFC 3986) into components. Returns nullopt on a
|
||||
/// malformed URL. Backed by Boost.URL.
|
||||
[[nodiscard]] static std::optional<Url> parse(std::string_view url);
|
||||
};
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,339 @@
|
||||
#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/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/ssl.hpp>
|
||||
|
||||
#include <openssl/ssl.h>
|
||||
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
#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;
|
||||
|
||||
[[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<http::string_body>
|
||||
build_request(const Url& url, const Request& req,
|
||||
std::string_view default_ua, std::string_view target)
|
||||
{
|
||||
http::request<http::string_body> 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<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());
|
||||
for (const auto& f : src.base()) {
|
||||
out.headers.push_back(
|
||||
{std::string{f.name_string()}, std::string{f.value()}});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename Stream>
|
||||
Response write_read(Stream& stream, http::request<http::string_body>& rq)
|
||||
{
|
||||
http::write(stream, rq);
|
||||
beast::flat_buffer buffer;
|
||||
http::response<http::dynamic_body> res;
|
||||
http::read(stream, buffer, res);
|
||||
return convert(res);
|
||||
}
|
||||
|
||||
// SOCKS5 CONNECT handshake on an already-connected socket.
|
||||
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])));
|
||||
}
|
||||
// Drain the bound address.
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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<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<http::empty_body> cres;
|
||||
http::read(socket, buffer, cres);
|
||||
if (cres.result() != http::status::ok) {
|
||||
throw std::runtime_error(std::format(
|
||||
"Proxy CONNECT failed: {}", int(cres.result_int())));
|
||||
}
|
||||
}
|
||||
|
||||
void tls_handshake(ssl::stream<tcp::socket>& 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);
|
||||
}
|
||||
|
||||
// Perform the request over an already-connected plain socket, doing a
|
||||
// TLS upgrade in place when the target is https.
|
||||
Response finish(tcp::socket socket, ssl::context& ctx, const Url& url,
|
||||
const Request& req, std::string_view ua)
|
||||
{
|
||||
if (url.is_tls) {
|
||||
ssl::stream<tcp::socket> stream{std::move(socket), ctx};
|
||||
tls_handshake(stream, url);
|
||||
auto rq = build_request(url, req, ua, url.target);
|
||||
return write_read(stream, rq);
|
||||
}
|
||||
auto rq = build_request(url, req, ua, url.target);
|
||||
return write_read(socket, rq);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string_view>
|
||||
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<char>(std::tolower(h.name[i]));
|
||||
const char b = static_cast<char>(std::tolower(name[i]));
|
||||
if (a != b) { eq = false; break; }
|
||||
}
|
||||
if (eq) return h.value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Void::Result::Result<Response, Void::Result::Error>
|
||||
HttpClient::send(const Request& req) const
|
||||
{
|
||||
const auto url = Url::parse(req.url);
|
||||
if (!url) {
|
||||
return Void::Result::fail(
|
||||
std::format("Net: invalid URL '{}'", req.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};
|
||||
|
||||
if (m_proxy.enabled()) {
|
||||
tcp::socket socket{ioc};
|
||||
asio::connect(socket, resolver.resolve(
|
||||
m_proxy.host,
|
||||
std::to_string(m_proxy.port)));
|
||||
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
||||
socks5_connect(socket, *url, m_proxy);
|
||||
response = finish(std::move(socket), ctx, *url, req,
|
||||
m_user_agent);
|
||||
} else { // Http proxy
|
||||
if (url->is_tls) {
|
||||
http_connect_tunnel(socket, *url, m_proxy);
|
||||
response = finish(std::move(socket), ctx, *url, req,
|
||||
m_user_agent);
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tcp::socket socket{ioc};
|
||||
asio::connect(socket,
|
||||
resolver.resolve(url->host, url->port));
|
||||
response = finish(std::move(socket), ctx, *url, req,
|
||||
m_user_agent);
|
||||
}
|
||||
|
||||
response.elapsed =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - start);
|
||||
return response;
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(
|
||||
std::format("Net: request to '{}' failed: {}", req.url,
|
||||
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);
|
||||
}
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,47 @@
|
||||
#include <Void/Net/Url.hpp>
|
||||
|
||||
#include <boost/url/parse.hpp>
|
||||
#include <boost/url/url_view.hpp>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
|
||||
std::optional<Url> Url::parse(std::string_view url)
|
||||
{
|
||||
namespace urls = boost::urls;
|
||||
auto parsed = urls::parse_uri(url);
|
||||
if (!parsed) {
|
||||
// Some callers pass scheme-relative or relative refs; try the
|
||||
// looser reference parser before giving up.
|
||||
parsed = urls::parse_uri_reference(url);
|
||||
if (!parsed) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
const auto& uri = *parsed;
|
||||
|
||||
Url out;
|
||||
out.scheme = std::string{uri.scheme()};
|
||||
out.host = std::string{uri.host()};
|
||||
out.is_tls = (out.scheme == "https" || out.scheme == "wss");
|
||||
|
||||
if (uri.has_port()) {
|
||||
out.port = std::string{uri.port()};
|
||||
} else {
|
||||
out.port = out.is_tls ? "443" : "80";
|
||||
}
|
||||
|
||||
out.path = std::string{uri.encoded_path()};
|
||||
if (out.path.empty()) {
|
||||
out.path = "/";
|
||||
}
|
||||
out.target = out.path;
|
||||
if (uri.has_query()) {
|
||||
out.query = std::string{uri.encoded_query()};
|
||||
out.target += "?";
|
||||
out.target += out.query;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Net
|
||||
@@ -0,0 +1,9 @@
|
||||
void_add_module(Net
|
||||
INTERNAL_DEPS Functional Text
|
||||
EXTERNAL_DEPS
|
||||
Boost::headers
|
||||
Boost::url
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
Threads::Threads
|
||||
)
|
||||
@@ -0,0 +1,112 @@
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <netinet/in.h>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
// Minimal one-shot HTTP/1.1 server on a chosen loopback port. Accepts one
|
||||
// connection, reads the request (ignored beyond headers), and replies with
|
||||
// a fixed 200 body. Runs on a detached helper thread; the test joins it.
|
||||
struct OneShotServer {
|
||||
int fd = -1;
|
||||
std::uint16_t port = 0;
|
||||
std::thread worker;
|
||||
std::string last_request;
|
||||
std::atomic<bool> served{false};
|
||||
|
||||
explicit OneShotServer(std::string body)
|
||||
{
|
||||
fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int yes = 1;
|
||||
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0; // ephemeral
|
||||
::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
|
||||
socklen_t len = sizeof(addr);
|
||||
::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &len);
|
||||
port = ntohs(addr.sin_port);
|
||||
::listen(fd, 1);
|
||||
|
||||
worker = std::thread([this, body = std::move(body)] {
|
||||
int conn = ::accept(fd, nullptr, nullptr);
|
||||
if (conn < 0) return;
|
||||
char buf[4096];
|
||||
const auto n = ::read(conn, buf, sizeof(buf));
|
||||
if (n > 0) last_request.assign(buf, buf + n);
|
||||
const std::string resp =
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: " +
|
||||
std::to_string(body.size()) +
|
||||
"\r\nConnection: close\r\n\r\n" + body;
|
||||
[[maybe_unused]] auto w =
|
||||
::write(conn, resp.data(), resp.size());
|
||||
::close(conn);
|
||||
served = true;
|
||||
});
|
||||
}
|
||||
|
||||
~OneShotServer()
|
||||
{
|
||||
if (worker.joinable()) worker.join();
|
||||
if (fd >= 0) ::close(fd);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test http_client_get_localhost_round_trip()
|
||||
{
|
||||
OneShotServer server{"hello from void"};
|
||||
const std::string url =
|
||||
"http://127.0.0.1:" + std::to_string(server.port) + "/ping";
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const auto resp = client.get(url);
|
||||
|
||||
Void::Testing::expect(resp.has_value());
|
||||
Void::Testing::expect_eq(resp->status, static_cast<std::uint16_t>(200));
|
||||
Void::Testing::expect_eq(resp->body, std::string{"hello from void"});
|
||||
Void::Testing::expect(resp->ok());
|
||||
// Request line reached the server with the right target.
|
||||
Void::Testing::expect(server.last_request.find("GET /ping HTTP/1.1") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test http_client_post_sends_body()
|
||||
{
|
||||
OneShotServer server{"ok"};
|
||||
const std::string url =
|
||||
"http://127.0.0.1:" + std::to_string(server.port) + "/submit";
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const auto resp = client.post(url, "payload=42");
|
||||
|
||||
Void::Testing::expect(resp.has_value());
|
||||
Void::Testing::expect_eq(resp->status, static_cast<std::uint16_t>(200));
|
||||
Void::Testing::expect(server.last_request.find("POST /submit") !=
|
||||
std::string::npos);
|
||||
Void::Testing::expect(server.last_request.find("payload=42") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test http_client_invalid_url_is_error()
|
||||
{
|
||||
Void::Net::HttpClient client;
|
||||
const auto resp = client.get("not a url");
|
||||
Void::Testing::expect(!resp.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test http_client_connection_refused_is_error()
|
||||
{
|
||||
Void::Net::HttpClient client;
|
||||
// Port 1 on loopback: nothing listening.
|
||||
const auto resp = client.get("http://127.0.0.1:1/");
|
||||
Void::Testing::expect(!resp.has_value());
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#include <Void/Net/Url.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test url_parse_https_defaults_port()
|
||||
{
|
||||
const auto u = Void::Net::Url::parse("https://example.com/path?q=1");
|
||||
Void::Testing::expect(u.has_value());
|
||||
Void::Testing::expect_eq(u->scheme, std::string{"https"});
|
||||
Void::Testing::expect_eq(u->host, std::string{"example.com"});
|
||||
Void::Testing::expect_eq(u->port, std::string{"443"});
|
||||
Void::Testing::expect(u->is_tls);
|
||||
Void::Testing::expect_eq(u->path, std::string{"/path"});
|
||||
Void::Testing::expect_eq(u->query, std::string{"q=1"});
|
||||
Void::Testing::expect_eq(u->target, std::string{"/path?q=1"});
|
||||
}
|
||||
|
||||
Void::Testing::Test url_parse_http_explicit_port()
|
||||
{
|
||||
const auto u = Void::Net::Url::parse("http://localhost:8080/x");
|
||||
Void::Testing::expect(u.has_value());
|
||||
Void::Testing::expect_eq(u->port, std::string{"8080"});
|
||||
Void::Testing::expect(!u->is_tls);
|
||||
Void::Testing::expect_eq(u->target, std::string{"/x"});
|
||||
}
|
||||
|
||||
Void::Testing::Test url_parse_root_path_defaults()
|
||||
{
|
||||
const auto u = Void::Net::Url::parse("http://example.com");
|
||||
Void::Testing::expect(u.has_value());
|
||||
Void::Testing::expect_eq(u->path, std::string{"/"});
|
||||
Void::Testing::expect_eq(u->target, std::string{"/"});
|
||||
Void::Testing::expect_eq(u->port, std::string{"80"});
|
||||
}
|
||||
|
||||
Void::Testing::Test url_parse_preserves_encoded_query()
|
||||
{
|
||||
const auto u = Void::Net::Url::parse("https://h/s?q=a%20b&x=1");
|
||||
Void::Testing::expect(u.has_value());
|
||||
Void::Testing::expect_eq(u->query, std::string{"q=a%20b&x=1"});
|
||||
}
|
||||
|
||||
Void::Testing::Test url_parse_rejects_garbage()
|
||||
{
|
||||
Void::Testing::expect(!Void::Net::Url::parse("ht tp://bad url").has_value());
|
||||
}
|
||||
Reference in new issue
Block a user