Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Reuse CDN connections and DNS lookups

Leonardo Lobato15ba7d15afbd
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index bf23845..1221cf4 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -187,6 +187,10 @@ function(playden_register_steam_backend_tests)
if(TARGET playden_steam_http)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
+ add_executable(native_resolution_cache_test "${CMAKE_SOURCE_DIR}/tests/native_resolution_cache_test.cpp")
+ target_link_libraries(native_resolution_cache_test PRIVATE playden_steam_http)
+ add_test(NAME native_resolution_cache COMMAND native_resolution_cache_test)
+
add_executable(http_client_test "${CMAKE_SOURCE_DIR}/tests/http_client_test.cpp")
target_link_libraries(http_client_test PRIVATE playden_steam_http)
add_test(NAME http_client
diff --git a/src/steam/backend/depot_installer.h b/src/steam/backend/depot_installer.h
index 6c9df7c..89b4cf9 100644
--- a/src/steam/backend/depot_installer.h
+++ b/src/steam/backend/depot_installer.h
@@ -47,7 +47,7 @@ struct InstallStats : CdnStats {
std::uint64_t chunks_done = 0, chunks_skipped = 0, compressed_bytes = 0, original_bytes = 0;
std::uint64_t files_created = 0, folders_created = 0, chunk_retries = 0, corrupt_retries = 0;
std::uint64_t files_total = 0, download_total = 0, chunks_pending = 0, files_pending = 0, bytes_pending = 0;
- std::uint32_t slots = 1, reuse = 0;
+ std::uint32_t slots = 1, reuse = 1;
};
struct InstallOutcome {
diff --git a/src/steam/backend/http_client.cpp b/src/steam/backend/http_client.cpp
index aae4042..68f5bf8 100644
--- a/src/steam/backend/http_client.cpp
+++ b/src/steam/backend/http_client.cpp
@@ -3,6 +3,7 @@
#include <strings.h>
#include "steam/backend/native_network.h"
+#include "steam/backend/native_resolution_cache.h"
#include <curl/curl.h>
@@ -210,10 +211,16 @@ class HttpClient::Impl {
explicit Impl(std::string ca_bundle) : ca_bundle_(std::move(ca_bundle)) {
native_ready_ = internal::InitializeNativeNetwork();
curl_ready_ = native_ready_ && GlobalCurl().ready;
+ if (curl_ready_) multi_ = internal::NativeResolutionCache::CreateTransport();
+ }
+
+ ~Impl() {
+ if (multi_) curl_multi_cleanup(multi_);
+ curl_slist_free_all(resolve_entries_);
}
HttpResponse Perform(const HttpRequest& request, const std::atomic<bool>& cancel) {
- if (!curl_ready_ || ca_bundle_.empty())
+ if (!curl_ready_ || !multi_ || ca_bundle_.empty())
return {HttpError::kInitializationFailed, 0, {}, {}};
if (!ValidRequest(request)) return {HttpError::kInvalidRequest, 0, {}, {}};
if (cancel.load(std::memory_order_acquire)) return {HttpError::kCanceled, 0, {}, {}};
@@ -221,10 +228,10 @@ class HttpClient::Impl {
const auto deadline = request_start + std::chrono::milliseconds(request.timeout_ms);
CURL* easy = curl_easy_init();
- CURLM* multi = curl_multi_init();
+ CURLM* multi = multi_;
curl_slist* request_headers = nullptr;
- curl_slist* resolve_entries = nullptr;
- TransferBuffer transfer;
+ auto transfer_buffer = std::make_unique<TransferBuffer>();
+ auto& transfer = *transfer_buffer;
transfer.body_limit = request.max_response_bytes;
CURLcode result = CURLE_FAILED_INIT;
internal::NativeResolveError resolve_error = internal::NativeResolveError::kFailed;
@@ -265,6 +272,11 @@ class HttpClient::Impl {
PLAYDEN_SETOPT(CURLOPT_PROTOCOLS_STR, "https");
PLAYDEN_SETOPT(CURLOPT_REDIR_PROTOCOLS_STR, "https");
PLAYDEN_SETOPT(CURLOPT_NOSIGNAL, 1L);
+ PLAYDEN_SETOPT(CURLOPT_TCP_KEEPALIVE, 1L);
+ if (request.method != HttpMethod::kGet) {
+ PLAYDEN_SETOPT(CURLOPT_FRESH_CONNECT, 1L);
+ PLAYDEN_SETOPT(CURLOPT_FORBID_REUSE, 1L);
+ }
PLAYDEN_SETOPT(CURLOPT_WRITEFUNCTION, WriteBody);
PLAYDEN_SETOPT(CURLOPT_WRITEDATA, &transfer);
PLAYDEN_SETOPT(CURLOPT_HEADERFUNCTION, WriteHeader);
@@ -284,8 +296,8 @@ class HttpClient::Impl {
{
const auto start = Clock::now();
- resolve_error = internal::AttachNativeResolution(easy, request.url, request.timeout_ms, cancel,
- &resolve_entries);
+ resolve_error = resolution_cache_.Attach(easy, request.url, request.timeout_ms, cancel,
+ &resolve_entries_, Clock::now());
#if PLAYDEN_PLATFORM_PS5
transfer.response.timing.resolve_ms = static_cast<std::uint32_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count());
@@ -369,12 +381,13 @@ class HttpClient::Impl {
}
transfer.response.timing.body_bytes = transfer.response.body.size();
if (added) curl_multi_remove_handle(multi, easy);
- curl_slist_free_all(resolve_entries);
- curl_slist_free_all(request_headers);
- if (multi) curl_multi_cleanup(multi);
if (easy) curl_easy_cleanup(easy);
+ curl_slist_free_all(request_headers);
transfer.response.error = MapError(result, transfer, canceled);
if (!transfer.response.ok()) {
+ // Clearing both caches covers transport failure and abandonment before curl consumes
+ // staged DNS removals. Successful GETs retain their multi connection and DNS caches.
+ resolution_cache_.ResetTransport(multi_);
transfer.response.status_code = 0;
transfer.response.headers.clear();
transfer.response.body.clear();
@@ -384,6 +397,9 @@ class HttpClient::Impl {
private:
std::string ca_bundle_;
+ CURLM* multi_ = nullptr;
+ curl_slist* resolve_entries_ = nullptr;
+ internal::NativeResolutionCache resolution_cache_;
bool native_ready_ = false;
bool curl_ready_ = false;
};
diff --git a/src/steam/backend/native_resolution_cache.h b/src/steam/backend/native_resolution_cache.h
new file mode 100644
index 0000000..389cf81
--- /dev/null
+++ b/src/steam/backend/native_resolution_cache.h
@@ -0,0 +1,131 @@
+#pragma once
+
+#include "steam/backend/native_network.h"
+
+#include <algorithm>
+#include <charconv>
+#include <chrono>
+#include <string>
+#include <vector>
+
+namespace playden::steam::internal {
+
+// Single-thread-owned native DNS cache. The caller owns the CURLOPT_RESOLVE list and must
+// retain it until the easy handle has been cleaned up, before calling Attach again.
+class NativeResolutionCache {
+ public:
+ using Clock = std::chrono::steady_clock;
+ using Resolver = decltype(&AttachNativeResolution);
+ explicit NativeResolutionCache(Resolver resolver = AttachNativeResolution) : resolver_(resolver) {}
+
+ static CURLM* CreateTransport() {
+ CURLM* multi = curl_multi_init();
+ if (multi && curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, 4L) != CURLM_OK) {
+ curl_multi_cleanup(multi);
+ return nullptr;
+ }
+ return multi;
+ }
+
+ // Call only after removing/cleaning the easy handle. CURLOPT_RESOLVE entries are permanent
+ // in the multi DNS cache; invalidation or unconsumed removal lists require discarding that
+ // cache as well as our native results. A failed recreation leaves the client unavailable.
+ void ResetTransport(CURLM*& multi) {
+ if (multi) curl_multi_cleanup(multi);
+ multi = CreateTransport();
+ entries_.clear();
+ }
+
+ static std::string Key(const std::string& url) {
+ CURLU* parsed = curl_url();
+ if (!parsed) return {};
+ char* host = nullptr;
+ char* port = nullptr;
+ const bool valid = curl_url_set(parsed, CURLUPART_URL, url.c_str(), 0) == CURLUE_OK &&
+ curl_url_get(parsed, CURLUPART_HOST, &host, 0) == CURLUE_OK &&
+ curl_url_get(parsed, CURLUPART_PORT, &port, CURLU_DEFAULT_PORT) == CURLUE_OK;
+ std::string key;
+ if (valid && host && port) {
+ unsigned int number = 0;
+ const char* end = port + std::char_traits<char>::length(port);
+ const auto converted = std::from_chars(port, end, number);
+ if (converted.ec == std::errc{} && converted.ptr == end) {
+ key = host;
+ for (char& c : key)
+ if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
+ key += ":" + std::to_string(number);
+ }
+ }
+ curl_free(host);
+ curl_free(port);
+ curl_url_cleanup(parsed);
+ return key;
+ }
+
+ NativeResolveError Attach(CURL* easy, const std::string& url, std::uint32_t timeout_ms,
+ const std::atomic<bool>& cancel, curl_slist** active,
+ Clock::time_point now) {
+ if (!easy || !active) return NativeResolveError::kFailed;
+ curl_slist_free_all(*active);
+ *active = nullptr;
+ const auto key = Key(url);
+ if (key.empty()) return NativeResolveError::kFailed;
+ std::vector<std::string> removals;
+ for (const auto& entry : entries_)
+ if (now >= entry.expires) removals.push_back("-" + entry.key);
+ auto cached = std::find_if(entries_.begin(), entries_.end(),
+ [&](const Entry& entry) { return entry.key == key && now < entry.expires; });
+ std::string replacement;
+ std::string evicted_key;
+ const bool cache_miss = cached == entries_.end();
+ if (cached != entries_.end()) {
+ replacement = cached->resolution;
+ } else {
+ const auto error = resolver_(easy, url, timeout_ms, cancel, active);
+ if (error != NativeResolveError::kNone) return error;
+ // Host builds deliberately leave the list null and use curl's normal resolver.
+ if (!*active) return NativeResolveError::kNone;
+ const std::string native = (*active)->data;
+ const auto colon = native.rfind(':');
+ if (colon == std::string::npos) return NativeResolveError::kFailed;
+ replacement = key + native.substr(colon);
+ if (entries_.size() == kCapacity && removals.empty()) {
+ evicted_key = entries_.front().key;
+ removals.push_back("-" + evicted_key);
+ }
+ }
+ // Native entries are permanent in curl's multi DNS cache. Explicit removal before every
+ // replacement also handles an address change, expired entries and capacity eviction.
+ removals.push_back("-" + key);
+ curl_slist* updated = nullptr;
+ for (const auto& removal : removals) {
+ auto* appended = curl_slist_append(updated, removal.c_str());
+ if (!appended) { curl_slist_free_all(updated); return NativeResolveError::kFailed; }
+ updated = appended;
+ }
+ auto* appended = curl_slist_append(updated, replacement.c_str());
+ if (!appended) { curl_slist_free_all(updated); return NativeResolveError::kFailed; }
+ updated = appended;
+ if (curl_easy_setopt(easy, CURLOPT_RESOLVE, updated) != CURLE_OK) {
+ curl_slist_free_all(updated);
+ return NativeResolveError::kFailed;
+ }
+ curl_slist_free_all(*active);
+ *active = updated;
+ // Commit pruning only after the removal list is attached. A resolver failure must not lose
+ // the expired names that still need removal from curl's DNS cache on the next request.
+ entries_.erase(std::remove_if(entries_.begin(), entries_.end(), [&](const Entry& entry) {
+ return now >= entry.expires || entry.key == evicted_key;
+ }), entries_.end());
+ if (cache_miss) entries_.push_back({key, replacement, now + std::chrono::minutes(5)});
+ return NativeResolveError::kNone;
+ }
+
+ private:
+ struct Entry { std::string key, resolution; Clock::time_point expires; };
+ static constexpr std::size_t kCapacity = 32;
+ Resolver resolver_;
+ std::vector<Entry> entries_;
+};
+
+} // namespace playden::steam::internal
diff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cpp
index 7024d93..4753cc3 100644
--- a/tests/depot_installer_test.cpp
+++ b/tests/depot_installer_test.cpp
@@ -239,7 +239,7 @@ void StatsAndRemovalLogs(const std::filesystem::path& root) {
stats.files_total = 48000; stats.files_created = 48000;
const auto line = FormatInstallStats("end", stats);
CHECK(line.size() < 480);
- CHECK(line.find("dl_ms=300000") != std::string::npos && line.find("reuse=0") != std::string::npos);
+ CHECK(line.find("dl_ms=300000") != std::string::npos && line.find("reuse=1") != std::string::npos);
CmClient cm(CmClientHooks{}, cm::DeviceIdentity{});
CdnClient cdn([](const HttpRequest&, const std::atomic<bool>&) { return HttpResponse{}; });
SteamInstallRunner runner(cm, cdn);
@@ -295,7 +295,7 @@ void RunStats(const std::filesystem::path& base) {
auto target = Target(base / std::to_string(mode));
const auto outcome = installer.Run({}, target, cancel);
CHECK(ends == 1 && shapes == 1 && last.requests == static_cast<std::uint64_t>(world.chunk_calls));
- CHECK(last.slots == 1 && last.reuse == 0);
+ CHECK(last.slots == 1 && last.reuse == 1);
if (mode == 0) {
CHECK(outcome.error == InstallError::kNone && last.chunks_done == 3 && last.files_created == 2);
CHECK(last.fetch_ms >= 1); // sub-millisecond chunks accumulate before conversion
diff --git a/tests/http_client_test.cpp b/tests/http_client_test.cpp
index 9aac3b0..80d98fc 100644
--- a/tests/http_client_test.cpp
+++ b/tests/http_client_test.cpp
@@ -15,6 +15,7 @@ using playden::steam::HttpClient;
using playden::steam::HttpError;
using playden::steam::HttpMethod;
using playden::steam::HttpRequest;
+using playden::steam::HttpResponse;
void Check(bool condition, const char* message) {
if (!condition) {
@@ -27,6 +28,12 @@ std::string Text(const std::vector<std::uint8_t>& bytes) {
return std::string(bytes.begin(), bytes.end());
}
+std::string Header(const HttpResponse& response, const std::string& name) {
+ for (const auto& header : response.headers)
+ if (header.first == name) return header.second;
+ return {};
+}
+
} // namespace
int main(int argc, char** argv) {
@@ -37,6 +44,82 @@ int main(int argc, char** argv) {
std::atomic<bool> cancel{false};
HttpClient client(ca_bundle);
+ {
+ HttpClient persistent(ca_bundle);
+ HttpRequest keep;
+ keep.url = base_url + "/keep/marked";
+ auto first = persistent.Perform(keep, cancel);
+ Check(first.ok() && first.timing.new_connections == 1, "first keepalive GET opens connection");
+ Check(Header(first, "X-Fixture-Accepted") == "1", "server accepts first connection");
+ const auto connection = Header(first, "X-Fixture-Connection");
+ keep.url = base_url + "/keep/ok";
+ auto second = persistent.Perform(keep, cancel);
+ Check(second.ok() && Text(second.body) == "fixture-ok", "second keepalive GET succeeds");
+ Check(second.timing.new_connections == 0 && second.timing.tls_ms == 0,
+ "second keepalive GET reuses connection without TLS handshake");
+ Check(Header(second, "X-Fixture-Connection") == connection &&
+ Header(second, "X-Fixture-Accepted") == "1", "server sees one connection for two GETs");
+ Check(Header(second, "X-Fixture-Marker").empty(), "response headers do not leak");
+
+ HttpRequest other = keep;
+ other.url.replace(other.url.find("localhost"), 9, "127.0.0.1");
+ auto different = persistent.Perform(other, cancel);
+ Check(different.ok() && different.timing.new_connections == 1 &&
+ Header(different, "X-Fixture-Connection") != connection, "different origins do not share connections");
+
+ keep.url = base_url + "/keep/close";
+ Check(persistent.Perform(keep, cancel).ok(), "server closes idle connection after a reply");
+ std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ keep.url = base_url + "/keep/ok";
+ auto reconnected = persistent.Perform(keep, cancel);
+ Check(reconnected.ok() && reconnected.timing.new_connections == 1 &&
+ Text(reconnected.body) == "fixture-ok", "stale idle connection reconnects");
+
+ const auto check_recovery = [&] {
+ auto recovered = persistent.Perform(keep, cancel);
+ Check(recovered.ok() && Text(recovered.body) == "fixture-ok" &&
+ Header(recovered, "X-Fixture-Marker").empty() && recovered.timing.new_connections == 1,
+ "failed half-read connection is closed and next GET has clean body and headers");
+ };
+ HttpRequest slow = keep;
+ slow.url = base_url + "/keep/slow";
+ slow.timeout_ms = 100;
+ Check(persistent.Perform(slow, cancel).error == HttpError::kTimeout, "keepalive partial body times out");
+ check_recovery();
+ slow.timeout_ms = 3000;
+ std::thread cancel_keep([&] {
+ std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ cancel.store(true);
+ });
+ auto canceled_keep = persistent.Perform(slow, cancel);
+ cancel_keep.join();
+ Check(canceled_keep.error == HttpError::kCanceled, "keepalive partial body cancels");
+ cancel.store(false);
+ check_recovery();
+ HttpRequest large = keep;
+ large.url = base_url + "/keep/large";
+ large.max_response_bytes = 64;
+ Check(persistent.Perform(large, cancel).error == HttpError::kResponseTooLarge, "keepalive body limit enforced");
+ check_recovery();
+
+ for (auto method : {HttpMethod::kPost, HttpMethod::kPut}) {
+ HttpRequest upload;
+ upload.method = method;
+ upload.url = base_url + "/keep/echo";
+ upload.body = {'x'};
+ std::string previous = Header(persistent.Perform(keep, cancel), "X-Fixture-Connection");
+ for (int attempt = 0; attempt < 2; ++attempt) {
+ auto sent = persistent.Perform(upload, cancel);
+ Check(sent.ok() && Text(sent.body) == ":x" && sent.timing.new_connections == 1 &&
+ Header(sent, "X-Fixture-Connection") != previous, "POST and PUT always open fresh connections");
+ previous = Header(sent, "X-Fixture-Connection");
+ }
+ auto after = persistent.Perform(keep, cancel);
+ Check(after.ok() && Text(after.body) == "fixture-ok" &&
+ Header(after, "X-Fixture-Connection") != previous, "GET after upload does not reuse upload connection");
+ }
+ }
+
HttpRequest get;
get.url = base_url + "/ok";
auto response = client.Perform(get, cancel);
diff --git a/tests/http_fixture_server.py b/tests/http_fixture_server.py
index 9231ba8..691446d 100644
--- a/tests/http_fixture_server.py
+++ b/tests/http_fixture_server.py
@@ -9,24 +9,56 @@ import threading
import time
+class Server(http.server.ThreadingHTTPServer):
+ accepted_connections = 0
+
+ def get_request(self):
+ connection, address = super().get_request()
+ self.accepted_connections += 1
+ connection.fixture_id = self.accepted_connections
+ return connection, address
+
+
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, _format, *_args):
pass
- def _reply(self, status, body):
+ def _reply(self, status, body, keep=False, marker=None, slow=False):
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
- self.send_header("Connection", "close")
+ self.send_header("Connection", "keep-alive" if keep else "close")
+ self.send_header("X-Fixture-Connection", str(self.connection.fixture_id))
+ self.send_header("X-Fixture-Accepted", str(self.server.accepted_connections))
+ if marker:
+ self.send_header("X-Fixture-Marker", marker)
self.end_headers()
try:
+ if slow:
+ self.wfile.write(body[:1])
+ self.wfile.flush()
+ time.sleep(2.0)
+ body = body[1:]
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError, ssl.SSLEOFError):
pass
def do_GET(self):
- if self.path == "/ok":
+ if self.path.startswith("/keep/"):
+ if self.path == "/keep/slow":
+ self._reply(200, b"late", keep=True, marker="slow", slow=True)
+ elif self.path == "/keep/large":
+ self._reply(200, b"x" * 4096, keep=True, marker="large")
+ elif self.path == "/keep/close":
+ self._reply(200, b"fixture-ok", keep=True)
+ self.close_connection = True
+ else:
+ self._reply(200, b"fixture-ok", keep=True,
+ marker="first" if self.path == "/keep/marked" else None)
+ elif self.path == "/stats/connections":
+ self._reply(200, str(self.server.accepted_connections).encode("ascii"), keep=True)
+ elif self.path == "/ok":
body = b"fixture-ok"
self.send_response(200)
self.send_header("X-ErEsUlT", "42")
@@ -57,14 +89,16 @@ class Handler(http.server.BaseHTTPRequestHandler):
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
marker = self.headers.get("X-Playden-Test", "").encode("ascii")
- self._reply(201, marker + b":" + body)
+ self._reply(201, marker + b":" + body, keep=self.path.startswith("/keep/"))
+
+ do_PUT = do_POST
def main():
if len(sys.argv) != 3:
raise SystemExit("usage: http_fixture_server.py TEST_BINARY FIXTURE_DIR")
fixture_dir = pathlib.Path(sys.argv[2]).resolve()
- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server = Server(("127.0.0.1", 0), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(fixture_dir / "server.pem", fixture_dir / "server-key.pem")
server.socket = context.wrap_socket(server.socket, server_side=True)
diff --git a/tests/native_resolution_cache_test.cpp b/tests/native_resolution_cache_test.cpp
new file mode 100644
index 0000000..d8ac639
--- /dev/null
+++ b/tests/native_resolution_cache_test.cpp
@@ -0,0 +1,253 @@
+#include "steam/backend/native_resolution_cache.h"
+
+#include <atomic>
+#include <chrono>
+#include <cstdlib>
+#include <iostream>
+#include <string>
+#include <string_view>
+
+namespace {
+using namespace playden::steam::internal;
+int calls = 0;
+NativeResolveError next_error = NativeResolveError::kNone;
+std::string address = "127.0.0.1";
+void Check(bool condition, const char* message) {
+ if (!condition) { std::cerr << message << '\n'; std::exit(1); }
+}
+NativeResolveError Resolve(CURL* easy, const std::string& url, std::uint32_t,
+ const std::atomic<bool>&, curl_slist** entries) {
+ ++calls;
+ if (next_error != NativeResolveError::kNone) return next_error;
+ const std::string entry = NativeResolutionCache::Key(url) + ":" + address;
+ *entries = curl_slist_append(nullptr, entry.c_str());
+ return *entries && curl_easy_setopt(easy, CURLOPT_RESOLVE, *entries) == CURLE_OK
+ ? NativeResolveError::kNone : NativeResolveError::kFailed;
+}
+void CheckList(curl_slist* list, const std::string& key,
+ const std::string& expected_address) {
+ bool removal = false, replacement = false;
+ for (; list; list = list->next) {
+ if (list->data == "-" + key) removal = true;
+ if (list->data == key + ":" + expected_address) {
+ Check(removal, "curl DNS removal precedes replacement");
+ replacement = true;
+ }
+ }
+ Check(replacement, "resolve list retains numeric replacement");
+}
+struct Probe {
+ int cache_hits = 0;
+ int socket_attempts = 0;
+};
+int Debug(CURL*, curl_infotype type, char* bytes, std::size_t size, void* context) {
+ if (type == CURLINFO_TEXT && std::string_view(bytes, size).find("was found in DNS cache") != std::string_view::npos)
+ ++static_cast<Probe*>(context)->cache_hits;
+ return 0;
+}
+curl_socket_t BlockSocket(void* context, curlsocktype, curl_sockaddr*) {
+ ++static_cast<Probe*>(context)->socket_attempts;
+ return CURL_SOCKET_BAD; // Exercise curl DNS consumption without contacting a server.
+}
+CURL* Easy(const std::string& url, Probe& probe) {
+ CURL* easy = curl_easy_init();
+ Check(easy != nullptr, "DNS probe easy initializes");
+ Check(curl_easy_setopt(easy, CURLOPT_URL, url.c_str()) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_PROXY, "") == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_TIMEOUT_MS, 100L) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_NOSIGNAL, 1L) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_DEBUGFUNCTION, Debug) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_DEBUGDATA, &probe) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_OPENSOCKETFUNCTION, BlockSocket) == CURLE_OK &&
+ curl_easy_setopt(easy, CURLOPT_OPENSOCKETDATA, &probe) == CURLE_OK,
+ "DNS probe options configure");
+ return easy;
+}
+void Perform(CURLM* multi, CURL* easy) {
+ Check(curl_multi_add_handle(multi, easy) == CURLM_OK, "DNS probe joins persistent multi");
+ int running = 0;
+ do {
+ Check(curl_multi_perform(multi, &running) == CURLM_OK, "DNS probe multi performs");
+ if (running) Check(curl_multi_poll(multi, nullptr, 0, 10, nullptr) == CURLM_OK, "DNS probe polls");
+ } while (running);
+ int messages = 0;
+ while (curl_multi_info_read(multi, &messages)) {}
+ Check(curl_multi_remove_handle(multi, easy) == CURLM_OK, "DNS probe leaves persistent multi");
+ curl_easy_cleanup(easy);
+}
+void NoCachedAddress(CURLM* multi, const std::string& url) {
+ Probe probe;
+ Perform(multi, Easy(url, probe));
+ Check(probe.cache_hits == 0 && probe.socket_attempts == 0,
+ "failed origin must not retain a permanent address in curl DNS cache");
+}
+} // namespace
+int main() {
+ Check(curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK, "curl initializes");
+ std::atomic<bool> cancel{false};
+ const auto start = NativeResolutionCache::Clock::time_point{};
+ const std::string first = "https://CDN.EXAMPLE/chunk";
+ Check(NativeResolutionCache::Key(first) == "cdn.example:443", "hostname normalized with default port");
+ Check(NativeResolutionCache::Key("https://cdn.example:00443/other") == "cdn.example:443",
+ "explicit default port shares normalized key");
+ Check(NativeResolutionCache::Key("https://cdn.example:444/other") == "cdn.example:444",
+ "different ports have different keys");
+ Check(NativeResolutionCache::Key("invalid").empty(), "invalid URL has no cache key");
+ {
+ NativeResolutionCache cache(Resolve);
+ CURLM* multi = NativeResolutionCache::CreateTransport();
+ Check(multi != nullptr, "cache test transport initializes");
+ curl_slist* entries = nullptr;
+ auto attach = [&](const std::string& url, auto now) {
+ CURL* easy = curl_easy_init();
+ Check(easy != nullptr, "easy initializes");
+ auto result = cache.Attach(easy, url, 1000, cancel, &entries, now);
+ curl_easy_cleanup(easy); // caller retains the resolve list until the next request
+ return result;
+ };
+ Check(attach(first, start) == NativeResolveError::kNone && calls == 1, "initial cache miss resolves");
+ CheckList(entries, "cdn.example:443", address);
+ Check(attach("https://cdn.example:443/other", start + std::chrono::minutes(4)) == NativeResolveError::kNone && calls == 1,
+ "cached result skips resolver and does not refresh TTL");
+ address = "127.0.0.2";
+ Check(attach(first, start + std::chrono::minutes(5)) == NativeResolveError::kNone && calls == 2,
+ "entry expires exactly at five minutes");
+ CheckList(entries, "cdn.example:443", address);
+ cache.ResetTransport(multi);
+ Check(attach(first, start + std::chrono::minutes(5)) == NativeResolveError::kNone && calls == 3,
+ "failure invalidation forces a new resolution");
+ for (auto error : {NativeResolveError::kFailed, NativeResolveError::kTimeout,
+ NativeResolveError::kCanceled}) {
+ next_error = error;
+ cache.ResetTransport(multi);
+ const auto before_failure = calls;
+ Check(attach(first, start + std::chrono::minutes(5)) == error && calls == before_failure + 1,
+ "native resolver failure, timeout and cancel propagate");
+ next_error = NativeResolveError::kNone;
+ Check(attach(first, start + std::chrono::minutes(5)) == NativeResolveError::kNone && calls == before_failure + 2,
+ "native failure, timeout and cancel are never cached");
+ }
+ next_error = NativeResolveError::kFailed;
+ cache.ResetTransport(multi);
+ Check(attach(first, start + std::chrono::minutes(5)) == NativeResolveError::kFailed, "resolution failure propagates");
+ next_error = NativeResolveError::kNone;
+ const auto before_retry = calls;
+ Check(attach(first, start + std::chrono::minutes(5)) == NativeResolveError::kNone && calls == before_retry + 1,
+ "failed resolutions are never cached");
+ for (int i = 0; i < 32; ++i)
+ Check(attach("https://host" + std::to_string(i) + ".example/", start + std::chrono::minutes(5)) == NativeResolveError::kNone,
+ "bounded cache insertion succeeds");
+ bool removed_evicted = false;
+ for (auto* entry = entries; entry; entry = entry->next)
+ removed_evicted |= entry->data == std::string("-cdn.example:443");
+ Check(removed_evicted, "capacity eviction removes the old key from curl DNS cache");
+ const auto before_evicted = calls;
+ Check(attach(first, start + std::chrono::minutes(5)) == NativeResolveError::kNone && calls == before_evicted + 1,
+ "cache bound evicts oldest entry");
+ CheckList(entries, "cdn.example:443", address);
+ curl_multi_cleanup(multi);
+ curl_slist_free_all(entries);
+ }
+ {
+ NativeResolutionCache cache(Resolve);
+ curl_slist* entries = nullptr;
+ const auto attach = [&](const std::string& url, auto now) {
+ CURL* easy = curl_easy_init();
+ const auto result = cache.Attach(easy, url, 1000, cancel, &entries, now);
+ curl_easy_cleanup(easy);
+ return result;
+ };
+ Check(attach(first, start) == NativeResolveError::kNone, "expired cache test seeds a name");
+ next_error = NativeResolveError::kTimeout;
+ Check(attach("https://other.example/", start + std::chrono::minutes(5)) == NativeResolveError::kTimeout,
+ "failure during expiry propagates");
+ next_error = NativeResolveError::kNone;
+ Check(attach("https://other.example/", start + std::chrono::minutes(5)) == NativeResolveError::kNone,
+ "resolution after expiry failure recovers");
+ bool removed_expired = false;
+ for (auto* entry = entries; entry; entry = entry->next)
+ removed_expired |= entry->data == std::string("-cdn.example:443");
+ Check(removed_expired, "expiry failure retains old curl DNS name for removal on recovery");
+ curl_slist_free_all(entries);
+ }
+ {
+ NativeResolutionCache cache(Resolve);
+ CURLM* multi = NativeResolutionCache::CreateTransport();
+ Check(multi != nullptr, "real DNS cache multi initializes");
+ curl_slist* entries = nullptr;
+ const std::string failed = "https://permanent-dns.invalid/";
+ Probe seed;
+ CURL* easy = Easy(failed, seed);
+ Check(cache.Attach(easy, failed, 1000, cancel, &entries, start) == NativeResolveError::kNone,
+ "real curl cache seeds native address");
+ Perform(multi, easy);
+ Check(seed.socket_attempts == 1, "curl consumed numeric native address before connection failure");
+ cache.ResetTransport(multi);
+ Check(multi != nullptr, "failed transport recreates bounded multi");
+ NoCachedAddress(multi, failed);
+
+ // Expiry builds a removal list, but cancellation/deadline before perform never consumes it.
+ Probe expired_seed;
+ easy = Easy(failed, expired_seed);
+ Check(cache.Attach(easy, failed, 1000, cancel, &entries, start) == NativeResolveError::kNone,
+ "recreated transport seeds address after failure");
+ Perform(multi, easy);
+ Probe abandoned;
+ const std::string other = "https://prepared-dns.invalid/";
+ easy = Easy(other, abandoned);
+ Check(cache.Attach(easy, other, 1000, cancel, &entries, start + std::chrono::minutes(5)) == NativeResolveError::kNone,
+ "expired address stages a DNS removal");
+ bool pending_removal = false;
+ for (auto* entry = entries; entry; entry = entry->next)
+ pending_removal |= entry->data == std::string("-permanent-dns.invalid:443");
+ Check(pending_removal, "abandoned request has not consumed expired DNS removal");
+ curl_easy_cleanup(easy); // Model cancellation/deadline immediately after resolution attachment.
+ cache.ResetTransport(multi);
+ NoCachedAddress(multi, failed);
+
+ // Repeated failed origins cannot accumulate permanent DNS entries or native resolver results.
+ const auto before_failures = calls;
+ for (int i = 0; i < 40; ++i) {
+ const std::string origin = "https://failed" + std::to_string(i) + ".invalid/";
+ Probe failure;
+ easy = Easy(origin, failure);
+ Check(cache.Attach(easy, origin, 1000, cancel, &entries, start) == NativeResolveError::kNone,
+ "distinct failed origin attaches native address");
+ Perform(multi, easy);
+ Check(failure.socket_attempts == 1, "failed-origin numeric DNS entry was consumed");
+ cache.ResetTransport(multi);
+ }
+ Check(calls == before_failures + 40, "failed origins do not retain native cache results");
+ NoCachedAddress(multi, "https://failed0.invalid/");
+ NoCachedAddress(multi, "https://failed39.invalid/");
+
+ // Repeated abandonments also clear successfully resolved native results before the next request.
+ const auto before_abandoned = calls;
+ for (int i = 0; i < 40; ++i) {
+ Probe before_start;
+ easy = Easy(other, before_start);
+ Check(cache.Attach(easy, other, 1000, cancel, &entries, start) == NativeResolveError::kNone,
+ "pre-start request attaches native result");
+ if (i % 2 == 0) {
+ Check(curl_multi_add_handle(multi, easy) == CURLM_OK, "abandoned request joins multi without performing");
+ Check(curl_multi_remove_handle(multi, easy) == CURLM_OK, "abandoned request leaves multi before perform");
+ }
+ curl_easy_cleanup(easy);
+ cache.ResetTransport(multi);
+ }
+ Check(calls == before_abandoned + 40, "pre-perform abandonment clears native cache every time");
+ NoCachedAddress(multi, other);
+ curl_multi_cleanup(multi);
+ curl_slist_free_all(entries);
+ }
+ {
+ NativeResolutionCache host;
+ CURL* easy = curl_easy_init();
+ curl_slist* entries = nullptr;
+ Check(host.Attach(easy, first, 1000, cancel, &entries, start) == NativeResolveError::kNone && !entries,
+ "host resolver remains no-op with no synthetic curl DNS entries");
+ curl_easy_cleanup(easy);
+ }
+ curl_global_cleanup();
+}