Play your Steam library's Windows games on a jailbroken PS5.
C++
Download over plain HTTP when Steam lists no HTTPS CDN
Leonardo Lobato3b2b817de942
diff --git a/src/steam/backend/cdn_client.cpp b/src/steam/backend/cdn_client.cppindex 0cfc476..15bf676 100644--- a/src/steam/backend/cdn_client.cpp+++ b/src/steam/backend/cdn_client.cpp@@ -16,6 +16,8 @@ CdnError FromHttp(const HttpResponse& response) {return CdnError::kNone;}+std::string Scheme(const ContentServer& server) { return server.https ? "https://" : "http://"; }+} // namespacebool ValidCdnHost(const std::string& host) {@@ -30,9 +32,10 @@ CdnClient::CdnClient(Perform perform) : perform_(std::move(perform)) {}CdnClient::~CdnClient() = default;CdnError CdnClient::Get(const std::string& url, std::size_t max_bytes, std::uint32_t timeout_ms,- const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out) {+ const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out, bool plain_http) {HttpRequest request;request.url = url;+ request.allow_plain_http = plain_http;request.headers = {{"User-Agent", "Valve/Steam HTTP Client 1.0"}};request.timeout_ms = timeout_ms;request.max_response_bytes = max_bytes;@@ -75,26 +78,36 @@ CdnError CdnClient::Servers(std::uint32_t cell_id, const std::atomic<bool>& cancconst auto root = json::Parse(text, json::Limits{512 * 1024, 8, 8192, 4096});const auto* response = root ? root->Find("response") : nullptr;const auto* servers = response ? response->Find("servers") : nullptr;- if (!servers || !servers->is_array()) return CdnError::kProtocol;- std::vector<ContentServer> usable;+ if (!servers || !servers->is_array()) {+ last_failure_ = "servers=malformed";+ return CdnError::kProtocol;+ }+ std::vector<ContentServer> usable, plain;+ std::size_t listed = 0;for (const auto& server : servers->array()) {+ ++listed;const auto* type = server.Find("type");const auto* host = server.Find("host");const auto* vhost = server.Find("vhost");const auto* https = server.Find("https_support");const auto* load = server.Find("load");if (!type || !type->is_string() || (type->text() != "SteamCache" && type->text() != "CDN")) continue;- if (https && https->is_string() && https->text() == "unavailable") continue;if (!host || !host->is_string() || !ValidCdnHost(host->text())) continue;ContentServer entry;entry.host = host->text();entry.vhost = vhost && vhost->is_string() && ValidCdnHost(vhost->text()) ? vhost->text() : entry.host;+ entry.https = !(https && https->is_string() && https->text() == "unavailable");if (load) {if (const auto value = load->AsUint64(); value && *value < 100000) entry.load = static_cast<int>(*value);}- usable.push_back(std::move(entry));+ (entry.https ? usable : plain).push_back(std::move(entry));+ }+ // Plain HTTP only when the directory offers nothing better.+ if (usable.empty()) usable = std::move(plain);+ if (usable.empty()) {+ last_failure_ = "servers=" + std::to_string(listed) + " usable=0";+ return CdnError::kProtocol;}- if (usable.empty()) return CdnError::kProtocol;std::stable_sort(usable.begin(), usable.end(),[](const ContentServer& left, const ContentServer& right) { return left.load < right.load; });*out = std::move(usable);@@ -105,9 +118,9 @@ CdnError CdnClient::Manifest(const ContentServer& server, std::uint32_t depot_idstd::uint64_t request_code, const std::atomic<bool>& cancel,std::vector<std::uint8_t>* out) {if (!ValidCdnHost(server.vhost)) return CdnError::kProtocol;- return Get("https://" + server.vhost + "/depot/" + std::to_string(depot_id) + "/manifest/" ++ return Get(Scheme(server) + server.vhost + "/depot/" + std::to_string(depot_id) + "/manifest/" +std::to_string(gid) + "/5/" + std::to_string(request_code),- kMaxManifestDownloadBytes, 60'000, cancel, out);+ kMaxManifestDownloadBytes, 60'000, cancel, out, !server.https);}CdnError CdnClient::Chunk(const ContentServer& server, std::uint32_t depot_id, const std::string& sha_hex,@@ -116,8 +129,8 @@ CdnError CdnClient::Chunk(const ContentServer& server, std::uint32_t depot_id, cif (!ValidCdnHost(server.vhost) || sha_hex.size() != 40 ||!std::all_of(sha_hex.begin(), sha_hex.end(), [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }))return CdnError::kProtocol;- return Get("https://" + server.vhost + "/depot/" + std::to_string(depot_id) + "/chunk/" + sha_hex,- max_bytes, 30'000, cancel, out);+ return Get(Scheme(server) + server.vhost + "/depot/" + std::to_string(depot_id) + "/chunk/" + sha_hex,+ max_bytes, 30'000, cancel, out, !server.https);}} // namespace playden::steamdiff --git a/src/steam/backend/cdn_client.h b/src/steam/backend/cdn_client.hindex 6f01950..daf936f 100644--- a/src/steam/backend/cdn_client.h+++ b/src/steam/backend/cdn_client.h@@ -16,6 +16,7 @@ struct ContentServer {std::string host;std::string vhost; // the name used in URLs and TLSint load = 100;+ bool https = true; // false for a server the directory lists as plain HTTP only};struct CdnStats {@@ -27,8 +28,12 @@ struct CdnStats {enum class CdnError { kNone, kCanceled, kNetwork, kNotFound, kProtocol };// Steam CDN access over the verified HTTPS client: the content server list for the account's-// cell, manifests and chunks. Only HTTPS-capable SteamCache/CDN servers are used. One worker-// thread owns each instance.+// cell, manifests and chunks. HTTPS-capable SteamCache/CDN servers are used when the directory+// lists any. Some regions (China) only get plain-HTTP caches; those are then used over http://.+// Chunks stay safe there: they are encrypted with the depot key from the CM and checked after+// decryption. The manifest signature is not verified, so a plain-HTTP manifest is trusted as+// received: someone on the path could drop files or move genuine chunks to other genuine paths,+// but could not add content of their own. One worker thread owns each instance.class CdnClient {public:using Perform = std::function<HttpResponse(const HttpRequest&, const std::atomic<bool>&)>;@@ -36,7 +41,8 @@ class CdnClient {explicit CdnClient(Perform perform); // tests~CdnClient();- // Servers sorted by load, from IContentServerDirectoryService/GetServersForSteamPipe.+ // Servers sorted by load, from IContentServerDirectoryService/GetServersForSteamPipe. When the+ // list holds no usable server, last_failure() says how many were listed and why none fit.CdnError Servers(std::uint32_t cell_id, const std::atomic<bool>& cancel, std::vector<ContentServer>* out);CdnError Manifest(const ContentServer& server, std::uint32_t depot_id, std::uint64_t gid,std::uint64_t request_code, const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out);@@ -52,7 +58,7 @@ class CdnClient {private:CdnError Get(const std::string& url, std::size_t max_bytes, std::uint32_t timeout_ms,- const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out);+ const std::atomic<bool>& cancel, std::vector<std::uint8_t>* out, bool plain_http = false);std::string ca_bundle_;Perform perform_;std::unique_ptr<HttpClient> http_;diff --git a/src/steam/backend/depot_installer.cpp b/src/steam/backend/depot_installer.cppindex 12e12c2..243e3e7 100644--- a/src/steam/backend/depot_installer.cpp+++ b/src/steam/backend/depot_installer.cpp@@ -246,11 +246,13 @@ DepotInstaller::DepotInstaller(CmClient& cm, CdnClient& cdn) {const std::vector<DepotRequest>& depots, const std::atomic<bool>& cancel) {return cm.FetchDepotAccess(session, app_id, depots, cancel);};- hooks_.servers = [&cdn](std::uint32_t cell, const std::atomic<bool>& cancel, std::vector<ContentServer>* out) {- return cdn.Servers(cell, cancel, out);- };// Which check a manifest that arrived failed, for the install log; empty after a network failure.auto manifest_problem = std::make_shared<std::string>();+ hooks_.servers = [&cdn, manifest_problem](std::uint32_t cell, const std::atomic<bool>& cancel,+ std::vector<ContentServer>* out) {+ manifest_problem->clear(); // a manifest problem from an earlier run must not hide why this list failed+ return cdn.Servers(cell, cancel, out);+ };hooks_.manifest = [&cdn, manifest_problem](const ContentServer& server, const DepotGrant& grant,const std::atomic<bool>& cancel, DepotManifest* out) {manifest_problem->clear();@@ -368,7 +370,12 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTastd::vector<ContentServer> servers;const auto listed = hooks_.servers(session.cell_id.value_or(0), cancel, &servers);if (listed == CdnError::kCanceled) return fail(InstallError::kCanceled, "canceled");- if (listed != CdnError::kNone || servers.empty()) return fail(InstallError::kNetwork, "no content servers");+ if (listed != CdnError::kNone || servers.empty()) {+ outcome.error = InstallError::kNetwork;+ outcome.detail = "no content servers";+ if (hooks_.last_failure) outcome.detail += " " + hooks_.last_failure();+ return outcome;+ }stats.servers_ms = Milliseconds(Clock::now() - phase_start);phase_start = Clock::now();diff --git a/src/steam/backend/http_client.cpp b/src/steam/backend/http_client.cppindex 68f5bf8..2fdab10 100644--- a/src/steam/backend/http_client.cpp+++ b/src/steam/backend/http_client.cpp@@ -120,7 +120,7 @@ bool ValidRequestHeader(const std::pair<std::string, std::string>& header) {return true;}-bool ValidUrl(const std::string& url) {+bool ValidUrl(const std::string& url, bool allow_plain_http) {if (url.empty() || url.size() > 8192 || url.find('\0') != std::string::npos) return false;CURLU* parsed = curl_url();if (!parsed) return false;@@ -130,7 +130,8 @@ bool ValidUrl(const std::string& url) {bool valid = set == CURLUE_OK &&curl_url_get(parsed, CURLUPART_SCHEME, &scheme, 0) == CURLUE_OK &&curl_url_get(parsed, CURLUPART_HOST, &host, 0) == CURLUE_OK &&- scheme && std::strcmp(scheme, "https") == 0 && host && *host;+ scheme && (std::strcmp(scheme, "https") == 0 || (allow_plain_http && std::strcmp(scheme, "http") == 0)) &&+ host && *host;curl_free(scheme);curl_free(host);curl_url_cleanup(parsed);@@ -138,7 +139,7 @@ bool ValidUrl(const std::string& url) {}bool ValidRequest(const HttpRequest& request) {- if (!ValidUrl(request.url) || request.timeout_ms == 0 ||+ if (!ValidUrl(request.url, request.allow_plain_http) || request.timeout_ms == 0 ||request.timeout_ms > kMaxHttpTimeoutMs || request.max_response_bytes == 0 ||request.max_response_bytes > kMaxHttpResponseBytes ||request.body.size() > kMaxHttpResponseBytes ||@@ -269,7 +270,7 @@ class HttpClient::Impl {PLAYDEN_SETOPT(CURLOPT_PROXY, "");PLAYDEN_SETOPT(CURLOPT_FOLLOWLOCATION, 0L);PLAYDEN_SETOPT(CURLOPT_MAXREDIRS, 0L);- PLAYDEN_SETOPT(CURLOPT_PROTOCOLS_STR, "https");+ PLAYDEN_SETOPT(CURLOPT_PROTOCOLS_STR, request.allow_plain_http ? "http,https" : "https");PLAYDEN_SETOPT(CURLOPT_REDIR_PROTOCOLS_STR, "https");PLAYDEN_SETOPT(CURLOPT_NOSIGNAL, 1L);PLAYDEN_SETOPT(CURLOPT_TCP_KEEPALIVE, 1L);diff --git a/src/steam/backend/http_client.h b/src/steam/backend/http_client.hindex 3fd18ea..dda3987 100644--- a/src/steam/backend/http_client.h+++ b/src/steam/backend/http_client.h@@ -44,6 +44,8 @@ struct HttpRequest {std::vector<std::uint8_t> body;std::uint32_t timeout_ms = 10'000;std::size_t max_response_bytes = 1024 * 1024;+ // Also accept an http:// URL. Only for content checked by other means, such as Steam CDN chunks.+ bool allow_plain_http = false;};struct HttpTiming {diff --git a/tests/cdn_client_test.cpp b/tests/cdn_client_test.cppindex 75435de..418274b 100644--- a/tests/cdn_client_test.cpp+++ b/tests/cdn_client_test.cpp@@ -47,10 +47,43 @@ void ServersFilterAndSortByLoad() {std::atomic<bool> cancel{false};std::vector<ContentServer> servers;assert(client.Servers(42, cancel, &servers) == CdnError::kNone);+ // The plain-HTTP server is left out while HTTPS servers are listed, even with the lowest load.assert(servers.size() == 2);- assert(servers[0].host == "a.example.invalid" && servers[0].vhost == "a.example.invalid");- assert(servers[1].vhost == "vb.example.invalid");+ assert(servers[0].host == "a.example.invalid" && servers[0].vhost == "a.example.invalid" && servers[0].https);+ assert(servers[1].vhost == "vb.example.invalid" && servers[1].https);assert(urls[0].find("GetServersForSteamPipe/v1/?cell_id=42") != std::string::npos);+ assert(urls[0].rfind("https://", 0) == 0);+}++void PlainHttpServersWhenNoHttpsIsListed() {+ bool plain_allowed = true;+ CdnClient client([&](const HttpRequest& request, const std::atomic<bool>&) {+ plain_allowed = request.allow_plain_http;+ return Body(200, R"({"response":{"servers":[+ {"type":"CDN","host":"b.example.invalid","load":20,"https_support":"unavailable"},+ {"type":"CDN","host":"a.example.invalid","vhost":"va.example.invalid","load":5,"https_support":"unavailable"},+ {"type":"OpenCache","host":"c.example.invalid","load":0,"https_support":"mandatory"}]}})");+ });+ std::atomic<bool> cancel{false};+ std::vector<ContentServer> servers;+ assert(client.Servers(7, cancel, &servers) == CdnError::kNone);+ assert(!plain_allowed); // the directory itself stays HTTPS-only+ assert(servers.size() == 2);+ assert(servers[0].vhost == "va.example.invalid" && !servers[0].https);+ assert(servers[1].host == "b.example.invalid" && !servers[1].https);+}++void EmptyServerListSaysWhy() {+ std::string body = R"({"response":{"servers":[+ {"type":"OpenCache","host":"a.example.invalid"},{"type":"CDN","host":"bad host/x"}]}})";+ CdnClient client([&](const HttpRequest&, const std::atomic<bool>&) { return Body(200, body); });+ std::atomic<bool> cancel{false};+ std::vector<ContentServer> servers;+ assert(client.Servers(7, cancel, &servers) == CdnError::kProtocol && servers.empty());+ assert(client.last_failure() == "servers=2 usable=0");+ body = R"({"response":{}})";+ assert(client.Servers(7, cancel, &servers) == CdnError::kProtocol);+ assert(client.last_failure() == "servers=malformed");}void ManifestAndChunkUrlsAndErrors() {@@ -76,10 +109,35 @@ void ManifestAndChunkUrlsAndErrors() {assert(client.Manifest({"h", "bad host", 1}, 1, 1, 1, cancel, &out) == CdnError::kProtocol);}+void PlainHttpServerUrls() {+ std::vector<HttpRequest> requests;+ CdnClient client([&](const HttpRequest& request, const std::atomic<bool>&) {+ requests.push_back(request);+ return Body(200, "payload");+ });+ std::atomic<bool> cancel{false};+ const ContentServer plain{"h.example.invalid", "v.example.invalid", 1, false};+ const ContentServer secure{"h.example.invalid", "v.example.invalid", 1};+ std::vector<std::uint8_t> out;+ const std::string sha(40, 'b');+ assert(client.Manifest(plain, 441, 11, 99, cancel, &out) == CdnError::kNone);+ assert(requests.back().url == "http://v.example.invalid/depot/441/manifest/11/5/99");+ assert(requests.back().allow_plain_http);+ assert(client.Chunk(plain, 441, sha, 1024, cancel, &out) == CdnError::kNone);+ assert(requests.back().url == "http://v.example.invalid/depot/441/chunk/" + sha);+ assert(requests.back().allow_plain_http);+ assert(client.Chunk(secure, 441, sha, 1024, cancel, &out) == CdnError::kNone);+ assert(requests.back().url == "https://v.example.invalid/depot/441/chunk/" + sha);+ assert(!requests.back().allow_plain_http);+}+} // namespaceint main() {TotalsIncludeFailedRequests();ServersFilterAndSortByLoad();+ PlainHttpServersWhenNoHttpsIsListed();+ EmptyServerListSaysWhy();ManifestAndChunkUrlsAndErrors();+ PlainHttpServerUrls();}diff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cppindex f8a9303..d82636c 100644--- a/tests/depot_installer_test.cpp+++ b/tests/depot_installer_test.cpp@@ -968,6 +968,18 @@ void BusyCdnIsRetriedAfterAWait(const std::filesystem::path& root) {CHECK((waits == std::vector<int>{1000, 2000, 4000}));}+void NoContentServersSaysWhy(const std::filesystem::path& root) {+ auto world = MakeWorld();+ auto hooks = world.Hooks();+ hooks.servers = [](std::uint32_t, const std::atomic<bool>&, std::vector<ContentServer>*) { return CdnError::kProtocol; };+ hooks.last_failure = [] { return std::string("servers=3 usable=0"); };+ DepotInstaller installer(std::move(hooks));+ std::atomic<bool> cancel{false};+ const auto outcome = installer.Run({}, Target(root), cancel);+ CHECK(outcome.error == InstallError::kNetwork && outcome.detail == "no content servers servers=3 usable=0");+ CHECK(world.chunk_calls == 0);+}+void BrokenManifestIsFetchedAgainElsewhere(const std::filesystem::path& root) {// A busy CDN answers 502 or sends a cut-off manifest: the next server is asked after a wait.auto world = MakeWorld();@@ -1076,6 +1088,7 @@ int main() {DefaultSpaceQueryFailurePreventsDownload(base / "space-default-query");CorruptChunksFailAfterRetries(base / "corrupt");BusyCdnIsRetriedAfterAWait(base / "busy");+ NoContentServersSaysWhy(base / "no-servers");BrokenManifestIsFetchedAgainElsewhere(base / "manifest");RemovesOnlyManagedFolders(base);std::filesystem::remove_all(base);diff --git a/tests/http_client_test.cpp b/tests/http_client_test.cppindex cbff009..1abbd4f 100644--- a/tests/http_client_test.cpp+++ b/tests/http_client_test.cpp@@ -37,10 +37,11 @@ std::string Header(const HttpResponse& response, const std::string& name) {} // namespaceint main(int argc, char** argv) {- Check(argc == 4, "expected BASE_URL CA_BUNDLE WRONG_CA_BUNDLE");+ Check(argc == 5, "expected BASE_URL CA_BUNDLE WRONG_CA_BUNDLE PLAIN_URL");const std::string base_url = argv[1];const std::string ca_bundle = argv[2];const std::string wrong_ca_bundle = argv[3];+ const std::string plain_url = argv[4];std::atomic<bool> cancel{false};HttpClient client(ca_bundle);@@ -187,6 +188,18 @@ int main(int argc, char** argv) {malformed.url = "http://localhost/not-https";response = client.Perform(malformed, cancel);Check(response.error == HttpError::kInvalidRequest, "non-HTTPS URL should be rejected");+ malformed.url = plain_url + "/ok";+ response = client.Perform(malformed, cancel);+ Check(response.error == HttpError::kInvalidRequest, "plain HTTP needs the request's opt-in");+ HttpRequest plain;+ plain.url = plain_url + "/ok";+ plain.allow_plain_http = true;+ response = client.Perform(plain, cancel);+ Check(response.ok() && response.status_code == 200 && Text(response.body) == "fixture-ok",+ "an opted-in request reaches a plain HTTP server");+ plain.url = "ftp://localhost/ok";+ response = client.Perform(plain, cancel);+ Check(response.error == HttpError::kInvalidRequest, "the opt-in allows http only, not other schemes");malformed.url = base_url + std::string("/ok\0ignored", 11);response = client.Perform(malformed, cancel);Check(response.error == HttpError::kInvalidRequest, "embedded NUL in URL should be rejected");diff --git a/tests/http_fixture_server.py b/tests/http_fixture_server.pyindex 691446d..5b8932b 100644--- a/tests/http_fixture_server.py+++ b/tests/http_fixture_server.py@@ -104,15 +104,19 @@ def main():server.socket = context.wrap_socket(server.socket, server_side=True)thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()+ plain = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ plain_thread = threading.Thread(target=plain.serve_forever, daemon=True)+ plain_thread.start()try:base_url = f"https://localhost:{server.server_port}"+ plain_url = f"http://localhost:{plain.server_port}"environment = os.environ.copy()environment["HTTPS_PROXY"] = "http://127.0.0.1:1"environment["ALL_PROXY"] = "http://127.0.0.1:1"environment["NO_PROXY"] = ""result = subprocess.run([sys.argv[1], base_url, str(fixture_dir / "ca.pem"),- str(fixture_dir / "wrong-ca.pem")],+ str(fixture_dir / "wrong-ca.pem"), plain_url],env=environment,check=False,)@@ -121,6 +125,9 @@ def main():server.shutdown()server.server_close()thread.join()+ plain.shutdown()+ plain.server_close()+ plain_thread.join()if __name__ == "__main__":