Xbox Cloud Gaming app for PS5 Homebrew
C
Keep private data out of logs and reports; sturdier network, updater, sign-out
Rafael Abud Ferreira43e3ed48773c
diff --git a/src/app/price_loop.cpp b/src/app/price_loop.cppindex ddbd49c..be9bf21 100644--- a/src/app/price_loop.cpp+++ b/src/app/price_loop.cpp@@ -11,6 +11,7 @@#include "xcloud/catalog.h"#include "xcloud/prices.h"+#include <algorithm>#include <ctime>#include <map>@@ -67,7 +68,9 @@ void priceLoop() {}cache = kept;if (!shown.empty()) g_ui->setPrices(shown);+ uint64_t pauseMs = 0; // after failed requests: 2 s, doubling to a minutewhile (!g_stopPrices) {+ for (uint64_t slept = 0; slept < pauseMs && !g_stopPrices; slept += 300) platform::sleepMs(300);std::string market, language;{std::lock_guard<std::mutex> lock(g_priceMutex);@@ -93,7 +96,18 @@ void priceLoop() {}std::map<std::string, xcloud::Price> got;std::string err;- if (!xcloud::fetchPrices(ids, market, language, got, err)) XC_LOGW("%s", err.c_str());+ if (xcloud::fetchPrices(ids, market, language, got, err)) {+ pauseMs = 0;+ } else {+ // Those without a price are asked for again, after a pause (not+ // every game to buy marked asked in seconds while offline).+ std::vector<std::string> again;+ for (const auto& id : ids)+ if (!got.count(id)) again.push_back(id);+ g_ui->pricesFailed(again);+ pauseMs = pauseMs ? std::min<uint64_t>(pauseMs * 2, 60000) : 2000;+ XC_LOGW("%s (next try in %llu s)", err.c_str(), static_cast<unsigned long long>(pauseMs / 1000));+ }std::map<std::string, ui::PriceInfo> texts;now = static_cast<int64_t>(std::time(nullptr));for (const auto& [id, p] : got) {@@ -107,7 +121,7 @@ void priceLoop() {}if (!texts.empty()) {g_ui->setPrices(texts);- platform::writeFileAtomic(pricesPath(), cache.dump());+ if (!platform::writeFileAtomic(pricesPath(), cache.dump())) XC_LOGW("prices: could not save the cache");}}}diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex 2093ebd..61e49d1 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -24,8 +24,11 @@#include <algorithm>#include <cmath>+#include <cstdio>#include <cstdlib>#include <memory>+#include <sys/stat.h>+#include <unistd.h>#include <mutex>#include <string>#include <thread>@@ -73,9 +76,10 @@ void openReport(const std::string& what, bool previousSession, const std::stringplatform::readFile(platform::dataDir() + "/xcloud.log", logText);std::vector<std::string> privateWords = {g_ui->gamertag()};for (int i = 0; i < input::kMaxPads; ++i) privateWords.push_back(input::padUserName(i));+ for (auto& name : g_ui->consoleNames()) privateWords.push_back(std::move(name));report::Info info;info.what = report::sanitize(what.empty() ? "Reported from Settings" : what, privateWords);- info.title = what.empty() ? "Problem report" : info.what.substr(0, 70);+ info.title = what.empty() ? "Problem report" : report::shorten(info.what, 70);info.release = XC_APP_VERSION;info.firmware = platform::firmwareVersion();info.log = report::sanitize(report::logExcerpt(logText, previousSession), privateWords);@@ -117,7 +121,7 @@ bool saveSettings(const ui::SettingsChoice& choice) {g_settings.sharpness = choice.sharpness;g_settings.deband = choice.deband;g_settings.upscaler = choice.upscaler;- if (!g_settings.save(settingsPath())) XC_LOGW("could not save settings");+ g_settings.save(settingsPath()); // warns itselfXC_LOGI("settings saved: language %s, %s, region %s", code.c_str(), g_settings.resolution.c_str(),g_settings.region.empty() ? "auto" : g_settings.region.c_str());}@@ -170,7 +174,13 @@ int main(int argc, char** argv) {// An update cut short: the old files went back, and the old eboot.bin// is the one to run.if (recoverUpdate(platform::dataDir())) platform::restartApp();- g_settings.load(settingsPath());+ struct stat settingsStat;+ if (!g_settings.load(settingsPath()) && ::stat(settingsPath().c_str(), &settingsStat) == 0) {+ // Unreadable (cut short?): kept aside, not overwritten by the defaults.+ std::string bad = settingsPath() + ".bad";+ std::rename(settingsPath().c_str(), bad.c_str());+ XC_LOGW("settings: %s could not be read; defaults used, the file kept as %s", settingsPath().c_str(), bad.c_str());+ }ui::setLanguage(ui::languageFromCode(g_settings.language));XC_LOGI("settings: language %s, %s, region %s", g_settings.language.c_str(), g_settings.resolution.c_str(),g_settings.region.empty() ? "auto" : g_settings.region.c_str());@@ -278,7 +288,10 @@ int main(int argc, char** argv) {// It couldn't start again by itself: closed, the next start is the new version.platform::notify(ui::tr(ui::Str::UpdateReopen), "update installed, restart failed: closing");platform::sleepMs(2000);- std::exit(0);+ // Not std::exit: its destructors would free what the background+ // threads still use (a crash, then a false "closed unexpectedly").+ // The log is already on disk (flushed by line).+ _exit(0);}input::poll(pad);autoplayPad(pad);@@ -446,7 +459,7 @@ int main(int argc, char** argv) {g_settings.librarySort = ev.librarySort == ui::LibrarySort::AZ ? "az": ev.librarySort == ui::LibrarySort::Console ? "console": "recent";- if (!g_settings.save(settingsPath())) XC_LOGW("could not save settings");+ g_settings.save(settingsPath()); // warns itselfXC_LOGI("prefs saved: %zu hidden, sort %s", g_settings.hidden.size(), g_settings.librarySort.c_str());break;}@@ -460,7 +473,7 @@ int main(int argc, char** argv) {g_settings.perGame.erase(key);XC_LOGI("per-game profile reset to default for %s (%s)", ev.game.name.c_str(), key.c_str());}- if (!g_settings.save(settingsPath())) XC_LOGW("could not save settings");+ g_settings.save(settingsPath()); // warns itselfbreak;}case ui::Action::SettingsChanged:diff --git a/src/app/report.cpp b/src/app/report.cppindex 5cbc80d..293959b 100644--- a/src/app/report.cpp+++ b/src/app/report.cpp@@ -20,7 +20,7 @@ std::string encode(const std::string& s) {static const char* hex = "0123456789ABCDEF";std::string out;for (unsigned char c : s) {- if (std::isalnum(c) || std::strchr("-_.~:/@!$'()*,;", c)) out += static_cast<char>(c);+ if (std::isalnum(c) || (c && std::strchr("-_.~:/@!$'()*,;", c))) out += static_cast<char>(c);else if (c == ' ') out += '+';else out += '%', out += hex[c >> 4], out += hex[c & 15];}@@ -143,4 +143,11 @@ std::string issueUrl(const Info& info, size_t maxLength) {}}+std::string shorten(const std::string& text, size_t maxBytes) {+ if (text.size() <= maxBytes) return text;+ size_t n = maxBytes;+ while (n > 0 && (static_cast<unsigned char>(text[n]) & 0xC0) == 0x80) --n; // a continuation byte+ return text.substr(0, n);+}+} // namespace xc::app::reportdiff --git a/src/app/report.h b/src/app/report.hindex d69a426..90e52e3 100644--- a/src/app/report.h+++ b/src/app/report.h@@ -34,4 +34,7 @@ std::string logExcerpt(const std::string& logText, bool previousSession, size_t// hexadecimal ids as <id>.std::string sanitize(const std::string& text, const std::vector<std::string>& privateWords);+// `text` cut to `maxBytes` at most, not inside a UTF-8 character.+std::string shorten(const std::string& text, size_t maxBytes);+} // namespace xc::app::reportdiff --git a/src/app/settings.cpp b/src/app/settings.cppindex 0143199..da5c4dc 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -179,7 +179,9 @@ bool Settings::save(const std::string& path) const {}v.set("perGame", pg);v.set("settingsVersion", 2);- return platform::writeFileAtomic(path, v.dump());+ if (platform::writeFileAtomic(path, v.dump())) return true;+ XC_LOGW("settings: could not save %s", path.c_str()); // every caller's warning+ return false;}} // namespace xc::appdiff --git a/src/app/updater.cpp b/src/app/updater.cppindex ed5f76c..53c031c 100644--- a/src/app/updater.cpp+++ b/src/app/updater.cpp@@ -136,13 +136,18 @@ bool download(const std::string& url, long size, std::string& out, const std::fureturn true;}-// The files in place go back where they were (an update cut short).-bool rollBack(const std::string& dir) {+// The files in place go back where they were (an update cut short). True+// when there were some; `complete` false when one couldn't go back (then+// update.old and the journal must stay, for the next start to try again).+bool rollBack(const std::string& dir, bool& complete) {std::vector<std::string> old;listFiles(dir + "/update.old", "", old);+ complete = true;for (const auto& rel : old)- if (!makeParents(dir + "/" + rel) || ::rename((dir + "/update.old/" + rel).c_str(), (dir + "/" + rel).c_str()) != 0)+ if (!makeParents(dir + "/" + rel) || ::rename((dir + "/update.old/" + rel).c_str(), (dir + "/" + rel).c_str()) != 0) {XC_LOGE("update: could not put back %s (errno %d)", rel.c_str(), errno);+ complete = false;+ }return !old.empty();}@@ -202,6 +207,7 @@ bool unzip(const std::string& zip, const std::string& prefix, std::vector<ZipEnt}size_t count = le16(zip, eocd + 10), at = le32(zip, eocd + 16);size_t total = 0;+ std::set<std::string> seen;for (size_t n = 0; n < count; ++n) {if (at + 46 > zip.size() || le32(zip, at) != 0x02014b50) {err = "damaged zip directory";@@ -221,6 +227,10 @@ bool unzip(const std::string& zip, const std::string& prefix, std::vector<ZipEnterr = "unexpected file in the archive: " + name;return false;}+ if (!seen.insert(name).second) { // twice: the second would replace the first's backup+ err = "file twice in the archive: " + name;+ return false;+ }if (local + 30 > zip.size() || le32(zip, local) != 0x04034b50) {err = "damaged zip entry " + name;return false;@@ -295,6 +305,10 @@ bool installRelease(const Release& release, const std::string& dir, const std::sreport(UpdateStep::Installing, -1);recoverUpdate(dir); // leftovers of an earlier try+ if (exists(dir + "/update.journal")) { // its old files couldn't all go back: not over them+ err = "an earlier update could not be undone";+ return false;+ }const std::string staged = dir + "/update.new", old = dir + "/update.old";for (const auto& f : files) {std::string p = staged + "/" + f.path;@@ -320,7 +334,9 @@ bool installRelease(const Release& release, const std::string& dir, const std::s::rename(target.c_str(), (old + "/" + f.path).c_str()) == 0);if (!moved || !makeParents(target) || ::rename((staged + "/" + f.path).c_str(), target.c_str()) != 0) {err = "could not put " + f.path + " in place (errno " + std::to_string(errno) + ")";- rollBack(dir);+ bool complete;+ rollBack(dir, complete);+ if (!complete) return false; // the journal stays: the next start tries again::unlink((dir + "/update.journal").c_str());removeTree(staged);removeTree(old);@@ -337,7 +353,13 @@ bool recoverUpdate(const std::string& dir) {bool rolledBack = false;if (exists(dir + "/update.journal")) {XC_LOGW("update: the last one was cut short; the old files go back");- rolledBack = rollBack(dir);+ bool complete;+ rolledBack = rollBack(dir, complete);+ if (!complete) {+ // What is left of the old files stays where it is, for the next try.+ XC_LOGE("update: the old files could not all go back; trying again at the next start");+ return rolledBack;+ }::unlink((dir + "/update.journal").c_str());}removeTree(dir + "/update.new");diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 9e11074..d0eeaa7 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -22,6 +22,7 @@#include <cstdlib>#include <map>#include <sys/stat.h>+#include <unistd.h>#include <memory>#include <thread>#include <vector>@@ -211,7 +212,7 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Gameconst std::string& regionName = {}) {failed = true;// A home session's id is the console's: only its start in the log.- XC_LOGI("starting %s (%s)", game.name.c_str(),+ XC_LOGI("starting %s (%s)", gssv.isHome() ? "own Xbox" : game.name.c_str(), // not the console's namegssv.isHome() ? (game.titleId.substr(0, 4) + "...").c_str() : game.titleId.c_str());g_ui->showLaunching(game, regionName.empty() ? ui::tr(ui::Str::Connecting): ui::trf(ui::Str::TryingRegion, ui::prettyRegion(regionName)));@@ -617,9 +618,21 @@ void worker() {case kUpdate: runUpdate(); break;case kReloadLibrary: loadLibrary(gssv); break; // e.g. after a language changecase kSignOut:+ // Nothing of this account stays for the next one: its library+ // stops loading, its cache goes, the lists empty.+ stopHydration();am.signOut();+ ::unlink((platform::dataDir() + "/library.json").c_str());+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ g_xblAuth.clear();+ }g_ui->setProfile({}, {});g_ui->setConsoles({}, false);+ g_ui->setRows({});+ g_ui->setOwned({}, {}, false);+ g_ui->setSearchPools({}, {});+ XC_LOGI("signed out: library and its cache cleared");signInAndLoad(am, gssv);loadConsoles(am, home);break;diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cppindex 69e16d5..74ec96e 100644--- a/src/auth/auth_manager.cpp+++ b/src/auth/auth_manager.cpp@@ -7,6 +7,7 @@#include "util/json.h"#include "util/log.h"+#include <algorithm>#include <cstdio>namespace xc::auth {@@ -87,7 +88,7 @@ bool AuthManager::deviceCodeSignIn(const DeviceCodeCallback& onCode, std::stringcase PollResult::Pending:if (!pollErr.empty()) XC_LOGW("device code poll: %s", pollErr.c_str());break;- case PollResult::SlowDown: interval += 5; break;+ case PollResult::SlowDown: interval = std::min(interval + 5, 60); break;case PollResult::Expired: err = "the sign-in code expired; try again"; return false;case PollResult::Denied: err = "sign-in was declined"; return false;case PollResult::Error: err = pollErr; return false;diff --git a/src/auth/msa.cpp b/src/auth/msa.cppindex ad6d079..3a67195 100644--- a/src/auth/msa.cpp+++ b/src/auth/msa.cpp@@ -6,6 +6,7 @@#include "util/json.h"#include "util/log.h"+#include <algorithm>#include <ctime>namespace xc::auth {@@ -58,8 +59,8 @@ bool MsaClient::startDeviceCode(DeviceCode& out, std::string& err) const {out.userCode = (*j)["user_code"].str();out.deviceCode = (*j)["device_code"].str();out.verificationUri = (*j)["verification_uri"].str("https://www.microsoft.com/link");- out.intervalSec = static_cast<int>((*j)["interval"].asInt(5));- out.expiresInSec = static_cast<int>((*j)["expires_in"].asInt(900));+ out.intervalSec = static_cast<int>(std::clamp<int64_t>((*j)["interval"].asInt(5), 1, 60));+ out.expiresInSec = static_cast<int>(std::clamp<int64_t>((*j)["expires_in"].asInt(900), 60, 3600));if (out.userCode.empty() || out.deviceCode.empty()) {err = "device code response missing fields";return false;@@ -71,9 +72,13 @@ PollResult MsaClient::pollDeviceCode(const DeviceCode& dc, MsaTokens& out, std::auto r = postForm(kTokenUrl, {{"client_id", cfg_.clientId},{"device_code", dc.deviceCode},{"grant_type", "urn:ietf:params:oauth:grant-type:device_code"}});- if (r.status == 0) {- err = r.error;- return PollResult::Pending; // transient network error: keep polling+ if (r.status == 0 || r.status >= 500) {+ err = describe(r);+ return PollResult::Pending; // the network or the service, for now: keep polling+ }+ if (r.status == 429) {+ err = describe(r);+ return PollResult::SlowDown; // too many requests}auto j = json::parse(r.body);if (r.ok() && j && readTokens(*j, out)) return PollResult::Success;@@ -92,7 +97,8 @@ bool MsaClient::refresh(const std::string& refreshToken, MsaTokens& out, std::st{"grant_type", "refresh_token"},{"refresh_token", refreshToken},{"scope", scope.empty() ? cfg_.scope : scope}});- if (networkError) *networkError = r.status == 0 || r.status >= 500;+ // Throttled or timed out isn't a sign-in gone bad: the stored one stays.+ if (networkError) *networkError = r.status == 0 || r.status >= 500 || r.status == 429 || r.status == 408;auto j = json::parse(r.body);if (!r.ok() || !j || !readTokens(*j, out)) {err = "token refresh failed: " + describe(r);diff --git a/src/net/http.cpp b/src/net/http.cppindex 4a9add7..9bf16db 100644--- a/src/net/http.cpp+++ b/src/net/http.cpp@@ -121,23 +121,31 @@ int connectTcp(const std::string& host, int port, int timeoutMs, std::string& erreturn fd;}-// Decodes a chunked body in place. Returns false on malformed framing.+std::function<Response(const Request&)> g_testTransport;++} // namespace+bool dechunk(const std::string& in, std::string& out) {size_t pos = 0;out.clear();for (;;) {size_t eol = in.find("\r\n", pos);if (eol == std::string::npos) return false;- size_t size = std::strtoul(in.substr(pos, eol - pos).c_str(), nullptr, 16);+ std::string line = in.substr(pos, eol - pos);+ char* end = nullptr;+ unsigned long long size = std::strtoull(line.c_str(), &end, 16);+ // A hexadecimal size, then nothing or an extension (";...").+ if (end == line.c_str() || (*end && *end != ';' && *end != ' ')) return false;pos = eol + 2;if (size == 0) return true;- if (pos + size > in.size()) return false;+ if (size > in.size() - pos || in.size() - pos - size < 2 || in.compare(pos + size, 2, "\r\n") != 0)+ return false;out.append(in, pos, size);- pos += size + 2; // skip trailing CRLF+ pos += size + 2;}}-} // namespace+void setTestTransport(std::function<Response(const Request&)> transport) { g_testTransport = std::move(transport); }bool Url::parse(const std::string& url, Url& out) {size_t s = url.find("://");@@ -381,14 +389,27 @@ Response performOnce(const Request& req) {if (headerEnd == std::string::npos) return finish("no HTTP response from " + url.host);if (streaming) {- if (contentLength >= 0 && streamed < static_cast<size_t>(contentLength)) return finish("download cut short");+ if (contentLength >= 0 && streamed < static_cast<size_t>(contentLength)) {+ resp.status = 0;+ return finish("download cut short");+ }return finish({});}std::string body = raw.substr(headerEnd + 4);if (chunked) {- if (!dechunk(body, resp.body)) return finish("malformed chunked body");+ if (!dechunk(body, resp.body)) {+ resp.status = 0; // not an answer (Response::ok() false)+ resp.body.clear();+ return finish("malformed chunked body");+ }} else {resp.body = std::move(body);+ // The connection closed before all of it came: not an answer.+ if (contentLength >= 0 && resp.body.size() < static_cast<size_t>(contentLength)) {+ resp.status = 0;+ resp.body.clear();+ return finish("response cut short");+ }if (contentLength >= 0 && resp.body.size() > static_cast<size_t>(contentLength))resp.body.resize(static_cast<size_t>(contentLength));}@@ -414,6 +435,7 @@ Response performRetrying(const Request& req) {} // namespaceResponse perform(const Request& req) {+ if (g_testTransport) return g_testTransport(req);Response resp = performRetrying(req);Request next = req;for (int hops = 0; req.followRedirects && hops < 5; ++hops) {diff --git a/src/net/http.h b/src/net/http.hindex 567159d..a737536 100644--- a/src/net/http.h+++ b/src/net/http.h@@ -67,6 +67,12 @@ void shutdownTls();Response perform(const Request& req);+// --- For the tests -------------------------------------------------------------+// Answers every perform() instead of the network; empty: the network again.+void setTestTransport(std::function<Response(const Request&)> transport);+// A chunked body decoded; false on malformed framing.+bool dechunk(const std::string& in, std::string& out);+// Helpers.std::string urlEncode(const std::string& s);std::string formEncode(const std::vector<std::pair<std::string, std::string>>& fields);diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex e649122..8a3222d 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -266,6 +266,14 @@ std::string AppUi::gamertag() const {return gamertag_;}+std::vector<std::string> AppUi::consoleNames() const {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<std::string> out;+ for (const auto& c : consoles_)+ if (!c.name.empty()) out.push_back(c.name);+ return out;+}+void AppUi::showReport(const std::string& url, const std::string& heading) {std::lock_guard<std::mutex> lock(mutex_);reportOpen_ = true;@@ -532,6 +540,11 @@ void AppUi::setPrices(const std::map<std::string, PriceInfo>& prices) {dirty_ = true;}+void AppUi::pricesFailed(const std::vector<std::string>& productIds) {+ std::lock_guard<std::mutex> lock(mutex_);+ for (const auto& id : productIds) pricesAsked_.erase(id);+}+std::vector<std::string> AppUi::pricesWanted(size_t max, bool background) {std::lock_guard<std::mutex> lock(mutex_);std::vector<std::string> out;diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 9efabce..258bcc9 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -171,6 +171,7 @@ public:// The signed-in account, top right; `gamerscore` (digits) under the name.void setProfile(const std::string& gamertag, const std::string& gamerpicUrl, const std::string& gamerscore = {});std::string gamertag() const; // for keeping it out of reports+ std::vector<std::string> consoleNames() const; // the same: the user's names for their consoles// "Report a problem": a QR code of `url` (the GitHub bug form, filled// in) over whatever is on screen, with `heading`; Circle closes it.void showReport(const std::string& url, const std::string& heading);@@ -197,6 +198,8 @@ public:// for yet; with `background`, any other game to buy once those are done// (never while streaming). Marks them asked.std::vector<std::string> pricesWanted(size_t max, bool background = false);+ // Their request failed (offline...): asked for again later.+ void pricesFailed(const std::vector<std::string>& productIds);// The game whose page is open, if its description or hero art hasn't// arrived; asked again every 5 s while missing (empty otherwise).std::string detailWanted(uint64_t nowMs);diff --git a/src/ui/image_cache.cpp b/src/ui/image_cache.cppindex 85e4260..8758ba5 100644--- a/src/ui/image_cache.cpp+++ b/src/ui/image_cache.cpp@@ -16,6 +16,7 @@#define STB_IMAGE_RESIZE_STATIC#include "stb_image_resize2.h"+#include <atomic>#include <dirent.h>#include <sys/stat.h>#include <unistd.h>@@ -95,7 +96,7 @@ std::shared_ptr<const Image> ImageCache::get(const std::string& url, int w, intstd::lock_guard<std::mutex> lock(mutex_);Entry& e = entries_[key];e.lastUse = ++clock_;- if (!e.image && !e.loading && !e.failed) {+ if (!e.image && !e.loading && (!e.failed || (e.retryAt && platform::nowMs() >= e.retryAt))) {e.loading = true;jobs_.push_front({key, url, w, h});cv_.notify_one();@@ -182,7 +183,9 @@ void ImageCache::loop() {} else {r = net::perform(req);if (r.ok() && !path.empty() && decodeImage(r.body, decoded)) {- platform::writeFileAtomic(path, r.body);+ static std::atomic<bool> warned{false}; // once: a full disk would say it for every image+ if (!platform::writeFileAtomic(path, r.body) && !warned.exchange(true))+ XC_LOGW("image cache: could not save to %s", diskDir_.c_str());} else if (r.ok()) {decodeImage(r.body, decoded);}@@ -205,6 +208,8 @@ void ImageCache::loop() {evict();} else {e.failed = true;+ bool passing = r.status == 0 || r.status >= 500;+ e.retryAt = passing && ++e.failures <= 3 ? platform::nowMs() + 30000u * e.failures : 0;}}if (result && onReady_) onReady_();diff --git a/src/ui/image_cache.h b/src/ui/image_cache.hindex 6cd9e89..65b7059 100644--- a/src/ui/image_cache.h+++ b/src/ui/image_cache.h@@ -42,6 +42,10 @@ private:struct Entry {std::shared_ptr<const Image> image;bool loading = false, failed = false;+ // A failure that may pass (no answer, 5xx) is tried again from+ // retryAt (ms), three times at most; a 4xx isn't.+ int failures = 0;+ uint64_t retryAt = 0;uint64_t lastUse = 0;};struct Job {diff --git a/src/util/json.h b/src/util/json.hindex c73c801..f48c551 100644--- a/src/util/json.h+++ b/src/util/json.h@@ -46,7 +46,10 @@ public:bool asBool(bool def = false) const { return isBool() ? bool_ : def; }double asNumber(double def = 0) const { return isNumber() ? num_ : def; }- int64_t asInt(int64_t def = 0) const { return isNumber() ? static_cast<int64_t>(num_) : def; }+ // `def` too for a number no int64_t holds (1e400 is infinity).+ int64_t asInt(int64_t def = 0) const {+ return isNumber() && num_ > -9.2e18 && num_ < 9.2e18 ? static_cast<int64_t>(num_) : def;+ }const std::string& asString() const;std::string str(std::string def = {}) const { return isString() ? str_ : def; }diff --git a/src/util/log.cpp b/src/util/log.cppindex 2c71536..6f93ab6 100644--- a/src/util/log.cpp+++ b/src/util/log.cpp@@ -2,6 +2,7 @@// Copyright (C) 2026 RafaelNGP#include "util/log.h"+#include <atomic>#include <cstdio>#include <ctime>#include <mutex>@@ -10,7 +11,7 @@ namespace xc::log {namespace {std::mutex g_mutex;-Level g_level = Level::Info;+std::atomic<Level> g_level{Level::Info};FILE* g_file = nullptr;const char* tag(Level l) {@@ -41,8 +42,10 @@ void write(Level level, const char* fmt, ...) {va_end(ap);std::time_t now = std::time(nullptr);+ std::tm local{};+ localtime_r(&now, &local); // std::localtime's result is shared by every threadchar ts[32];- std::strftime(ts, sizeof ts, "%H:%M:%S", std::localtime(&now));+ std::strftime(ts, sizeof ts, "%H:%M:%S", &local);std::lock_guard<std::mutex> lock(g_mutex);std::fprintf(stderr, "%s [%s] %s\n", ts, tag(level), msg);diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cppindex 9f21fa3..238eb43 100644--- a/src/xcloud/gssv.cpp+++ b/src/xcloud/gssv.cpp@@ -155,7 +155,8 @@ const std::string& deviceInfo(Resolution res) {std::string describe(const net::Response& r) {if (r.status == 0) return r.error;std::string s = "HTTP " + std::to_string(r.status);- if (!r.body.empty()) s += ": " + r.body.substr(0, 300);+ std::string fields = errorFields(r.body);+ if (!fields.empty()) s += ": " + fields;return s;}@@ -216,6 +217,22 @@ static net::Request authed(Resolution res, const GssvLogin& l, std::string methoreturn req;}+std::string errorFields(const std::string& body) {+ auto j = json::parse(body);+ if (!j || !j->isObject()) return {};+ std::string out;+ auto add = [&](const json::Value& v) {+ for (const char* key : {"status", "code", "errorCode", "message", "errorMessage", "reason"}) {+ const auto& f = v[key];+ std::string text = f.isString() ? f.str() : f.isNumber() ? std::to_string(f.asInt()) : std::string();+ if (!text.empty()) out += (out.empty() ? "" : ", ") + std::string(key) + "=" + text.substr(0, 200);+ }+ };+ add(*j);+ add((*j)["errorDetails"]);+ return out;+}+const char* loginCountryAddress(const std::string& country) {static const struct {const char* country;@@ -284,6 +301,7 @@ bool GssvClient::listTitles(std::vector<Title>& out, std::string& err, bool receout.clear();uint64_t started = platform::nowMs();std::string continuation;+ int pages = 0;do {std::string path = recentOnly ? "/v2/titles/mru?mr=25" : "/v2/titles?mr=200";if (!continuation.empty()) path += "&ct=" + net::urlEncode(continuation);@@ -310,7 +328,15 @@ bool GssvClient::listTitles(std::vector<Title>& out, std::string& err, bool receif (program.str() != "F2P") title.viaSubscription = true;if (!title.titleId.empty() && !isNonGameAddon(title.titleId)) out.push_back(std::move(title));}- continuation = recentOnly ? std::string() : (*j)["continuationToken"].str();+ // The next page; a token that repeats, an empty page or too many+ // pages end the list (a server that always says "more" can't loop).+ std::string next = recentOnly ? std::string() : (*j)["continuationToken"].str();+ ++pages;+ if (!next.empty() && (next == continuation || (*j)["results"].items().empty() || pages >= 50)) {+ XC_LOGW("title list: stopped paging after %d page(s), %zu titles", pages, out.size());+ next.clear();+ }+ continuation = next;} while (!continuation.empty() && out.size() < 5000);XC_LOGI("title list%s: %zu titles in %llu ms", recentOnly ? " (recent)" : "", out.size(),static_cast<unsigned long long>(platform::nowMs() - started));@@ -426,7 +452,7 @@ bool GssvClient::startSession(const std::string& titleId, const std::string& locreturn false;}sessionPath_ = (*j)["sessionPath"].str();- XC_LOGI("session created: %s", sessionPath_.c_str());+ XC_LOGI("session created"); // not its idreturn true;}@@ -511,7 +537,7 @@ bool GssvClient::pollSdpAnswer(std::string& answer, std::string& err) {auto payload = exchangePayload(*j);if (!payload) return true;if ((*payload)["status"].str("success") != "success") {- err = "SDP negotiation rejected: " + payload->dump();+ err = "SDP negotiation rejected: " + errorFields(payload->dump());return false;}answer = (*payload)["sdp"].str();@@ -571,7 +597,7 @@ bool GssvClient::keepalive(std::string& err) {void GssvClient::stopSession() {if (sessionPath_.empty()) return;auto r = net::perform(authed(resolution_, login_, "DELETE", sessionUrl("")));- XC_LOGI("session stopped: %s (%s)", sessionPath_.c_str(), r.ok() ? "ok" : describe(r).c_str());+ XC_LOGI("session stopped (%s)", r.ok() ? "ok" : describe(r).c_str());sessionPath_.clear();}diff --git a/src/xcloud/gssv.h b/src/xcloud/gssv.hindex 69637dc..2d68ee8 100644--- a/src/xcloud/gssv.h+++ b/src/xcloud/gssv.h@@ -84,6 +84,10 @@ enum class Resolution { P1080, P720, P1440, P1080HQ };// unknown one.const char* loginCountryAddress(const std::string& country);+// For errors (and so the log): an answer's code and message fields only,+// never the rest of its body (it may echo ids, addresses, SDP).+std::string errorFields(const std::string& body);+class GssvClient {public:// `offering` is "xgpuweb" (Game Pass cloud) or "xhome" (own console).diff --git a/src/xcloud/titlehub.cpp b/src/xcloud/titlehub.cppindex 42fd44e..a311b8c 100644--- a/src/xcloud/titlehub.cpp+++ b/src/xcloud/titlehub.cpp@@ -13,8 +13,10 @@ namespace {// One request. A single id titlehub doesn't know fails the whole batch with// HTTP 404: then the batch is split until the bad id is alone (and dropped).+// `unknownLeft`: how many such ids a batch may have; more is a request the+// service refuses whatever it holds, not bad ids (an error, nothing kept).bool fetchBatch(const std::string& auth, const std::vector<std::string>& ids, std::map<std::string, std::string>& out,- std::string& err) {+ std::string& err, int& unknownLeft) {json::Value list = json::Value::array();for (const auto& id : ids) list.push(id);json::Value body = json::Value::object();@@ -31,13 +33,17 @@ bool fetchBatch(const std::string& auth, const std::vector<std::string>& ids, stauto r = net::perform(req);if (r.status == 404 || r.status == 400) {if (ids.size() == 1) { // that id is unknown: remembered as such, no badge+ if (--unknownLeft < 0) {+ err = "titlehub: HTTP " + std::to_string(r.status) + " for every id";+ return false;+ }out[ids[0]] = "";return true;}size_t half = ids.size() / 2;std::vector<std::string> a(ids.begin(), ids.begin() + static_cast<long>(half));std::vector<std::string> b(ids.begin() + static_cast<long>(half), ids.end());- return fetchBatch(auth, a, out, err) && fetchBatch(auth, b, out, err);+ return fetchBatch(auth, a, out, err, unknownLeft) && fetchBatch(auth, b, out, err, unknownLeft);}auto j = json::parse(r.body);if (!r.ok() || !j) {@@ -74,7 +80,8 @@ bool fetchPlatforms(const std::string& auth, const std::vector<std::string>& xbofor (size_t i = 0; i < xboxTitleIds.size(); i += kBatch) {std::vector<std::string> batch(xboxTitleIds.begin() + static_cast<long>(i),xboxTitleIds.begin() + static_cast<long>(std::min(xboxTitleIds.size(), i + kBatch)));- if (!fetchBatch(auth, batch, out, err)) return false;+ int unknownLeft = 8;+ if (!fetchBatch(auth, batch, out, err, unknownLeft)) return false;}return true;}diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 901b852..d600b07 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -18,7 +18,10 @@#include "ui/stream_menu.h"#include "ui/strings.h"#include "util/json.h"+#include "auth/msa.h"+#include "ui/image_cache.h"#include "xcloud/gssv.h"+#include "xcloud/titlehub.h"#include "xcloud/prices.h"#include "xcloud/regions.h"@@ -600,6 +603,120 @@ static void testBuiltinCa() {xc::net::shutdownTls();}+static void testPrivacyAndRobustness() {+ // Error answers: their code and message only, never the rest.+ std::string sdp = R"({"status":"failed","code":"Rejected","sdp":"c=IN IP4 203.0.113.7","candidate":"a=candidate:1"})";+ std::string fields = xcloud::errorFields(sdp);+ CHECK(fields.find("Rejected") != std::string::npos && fields.find("failed") != std::string::npos);+ CHECK(fields.find("IP4") == std::string::npos && fields.find("candidate") == std::string::npos);+ CHECK(xcloud::errorFields(R"({"errorDetails":{"code":"NoEntitlement","message":"m"}})").find("NoEntitlement") !=+ std::string::npos);+ CHECK(xcloud::errorFields("<html>203.0.113.7</html>").empty() && xcloud::errorFields("").empty());++ // Numbers no int64_t holds: the default, not undefined behaviour.+ CHECK(json::parse("1e400")->asInt(7) == 7 && json::parse("-1e30")->asInt(7) == 7 && json::parse("42")->asInt() == 42);++ // Chunked bodies: well formed, and every kind of broken one refused.+ std::string body;+ CHECK(net::dechunk("4\r\nWiki\r\n5;x=1\r\npedia\r\n0\r\n\r\n", body) && body == "Wikipedia");+ CHECK(!net::dechunk("zz\r\nab\r\n0\r\n\r\n", body));+ CHECK(!net::dechunk("ffffffffffffffff\r\nab\r\n0\r\n\r\n", body));+ CHECK(!net::dechunk("2\r\nabXX0\r\n\r\n", body));+ CHECK(!net::dechunk("4\r\nWi", body));++ // Report titles aren't cut inside a character; a NUL is encoded.+ CHECK(app::report::shorten("Configura\xC3\xA7\xC3\xB5" "es", 11) == "Configura\xC3\xA7");+ CHECK(app::report::shorten("Configura\xC3\xA7\xC3\xB5" "es", 10) == "Configura");+ CHECK(app::report::shorten("short", 70) == "short");+ app::report::Info info{"t", std::string("a\0b", 3), "1", "13.00", ""};+ CHECK(app::report::issueUrl(info).find("a%00b") != std::string::npos);++ // Sign-in: the service busy or throttling keeps the code polling and+ // the stored sign-in; only a refused token drops it.+ int status = 0;+ std::string answer;+ int calls = 0;+ net::setTestTransport([&](const net::Request&) {+ ++calls;+ net::Response r;+ r.status = status;+ r.body = answer;+ return r;+ });+ auth::MsaClient msa;+ auth::DeviceCode dc;+ dc.deviceCode = "code";+ auth::MsaTokens tokens;+ std::string err;+ status = 503, answer = "<html>busy</html>";+ CHECK(msa.pollDeviceCode(dc, tokens, err) == auth::PollResult::Pending);+ status = 429;+ CHECK(msa.pollDeviceCode(dc, tokens, err) == auth::PollResult::SlowDown);+ status = 400, answer = R"({"error":"authorization_pending"})";+ CHECK(msa.pollDeviceCode(dc, tokens, err) == auth::PollResult::Pending);+ bool networkError = false;+ status = 429, answer = "";+ CHECK(!msa.refresh("r", tokens, err, {}, &networkError) && networkError);+ status = 400, answer = R"({"error":"invalid_grant"})";+ CHECK(!msa.refresh("r", tokens, err, {}, &networkError) && !networkError);++ // A title list whose server always says "more" with the same token ends.+ status = 200, answer = R"({"results":[{"titleId":"GAME1","details":{"productId":"P1"}}],"continuationToken":"same"})";+ calls = 0;+ xcloud::GssvClient gssv;+ std::vector<xcloud::Title> titles;+ CHECK(gssv.listTitles(titles, err) && calls == 2);+ status = 200, answer = R"({"results":[],"continuationToken":"other"})";+ calls = 0;+ CHECK(gssv.listTitles(titles, err) && calls == 1);++ // titlehub refusing every batch: an error after a few requests, not+ // ~200 of them and every id marked unknown.+ status = 400, answer = "{}";+ calls = 0;+ std::vector<std::string> ids;+ for (int i = 0; i < 100; ++i) ids.push_back(std::to_string(1000 + i));+ std::map<std::string, std::string> platforms;+ CHECK(!xcloud::fetchPlatforms("auth", ids, platforms, err) && calls < 60 && platforms.size() <= 8);+ net::setTestTransport({});++ // Prices whose request failed are asked for again.+ ui::Fonts fonts;+ ui::ImageCache images([] {});+ ui::AppUi app(fonts, images);+ std::vector<ui::GameTile> toBuy(3);+ for (int i = 0; i < 3; ++i) toBuy[i].productId = "BUY" + std::to_string(i), toBuy[i].purchasable = true, toBuy[i].playable = false;+ app.setOwned({}, toBuy, true);+ app.showHome();+ auto first = app.pricesWanted(20, true);+ CHECK(first.size() == 3 && app.pricesWanted(20, true).empty());+ app.pricesFailed(first);+ CHECK(app.pricesWanted(20, true).size() == 3);+ // The user's console names, for keeping them out of reports.+ ui::ConsoleTile console;+ console.serverId = "F4000000AAAA";+ console.name = "Living Room Xbox";+ app.setConsoles({console}, true);+ auto names = app.consoleNames();+ CHECK(names.size() == 1 && names[0] == "Living Room Xbox");+ CHECK(app::report::sanitize("starting Living Room Xbox", names).find("Living Room") == std::string::npos);++ // An update whose old files can't all go back keeps them, and its+ // journal, for the next start.+ std::string dir = "/tmp/xcloud-rollback-test";+ std::system(("rm -rf " + dir + " && mkdir -p " + dir + "/update.old " + dir + "/eboot.bin/busy").c_str());+ xc::platform::writeFileAtomic(dir + "/update.old/eboot.bin", "old");+ xc::platform::writeFileAtomic(dir + "/update.journal", "swapping\n");+ app::recoverUpdate(dir);+ std::string text;+ CHECK(xc::platform::readFile(dir + "/update.old/eboot.bin", text) && text == "old");+ CHECK(xc::platform::readFile(dir + "/update.journal", text));+ std::system(("rm -rf " + dir).c_str());+ // The same file twice in a package: refused.+ std::vector<app::ZipEntry> files;+ CHECK(!app::unzip(storedZip({{"PPSA99810/eboot.bin", "a"}, {"PPSA99810/eboot.bin", "b"}}), "PPSA99810/", files, err));+}+static void testAutoDeband() {using xc::app::debandForMbps;CHECK(debandForMbps(0.3, 1) == -1); // starting or standing still: no measure@@ -647,6 +764,7 @@ int main() {testCrashGuard();testBuiltinCa();testLoginCountry();+ testPrivacyAndRobustness();testAudioEncoder();testAutoDeband();testControllerTuning();