Xbox Cloud Gaming app for PS5 Homebrew
C
Add in-app updates, signed by the project's key
Rafael Abud Ferreira9d593047a475
diff --git a/CMakeLists.txt b/CMakeLists.txtindex fee9da5..afd8b3d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -70,6 +70,7 @@ add_library(xcloud_ui STATICsrc/app/library.cppsrc/app/settings.cppsrc/app/update_check.cpp+ src/app/updater.cppsrc/app/auto_deband.cppextern/qrcodegen/qrcodegen.c)diff --git a/README.md b/README.mdindex 0d71a32..690100f 100644--- a/README.md+++ b/README.md@@ -45,8 +45,10 @@ No building needed: download `PPSA99810.zip` from the3. Sign in: open <https://www.microsoft.com/link> on your phone or computer(or scan the QR code) and enter the code shown on the TV.-To update, close the app and copy the new folder over the old one; your-sign-in is kept. The sign-in lives in `PPSA99810/account.json`: never share+New versions install from inside the app (it asks after sign-in, and+Settings > Updates): only a package signed with the project's key is+accepted, and your sign-in is kept. By hand: close the app and copy the new+folder over the old one. The sign-in lives in `PPSA99810/account.json`: never sharethat file. More details, controls and troubleshooting are in the`README.txt` inside the folder.@@ -91,8 +93,9 @@ tools/ps5/link.sh build-ps5 # -> build-ps5/eboot.bintools/ps5/package.sh build-ps5 # -> build-ps5/pkg/PPSA99810/```-A release is built and checked with `tools/release.sh <X.Y.Z>` (see the-script's header); it publishes nothing.+A release is built, signed and checked with `tools/release.sh <X.Y.Z>`+(see the script's header); it publishes nothing. The signing key stays with+the maintainer: the app trusts only its public half (`src/app/updater.cpp`).## Licensediff --git a/ROADMAP.md b/ROADMAP.mdindex 0657fdc..3a44eb3 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -111,6 +111,15 @@ screen's loop), `worker.cpp` (sign-in, library, consoles, playing),`price_loop.cpp`, `autoplay.cpp` (the unattended tests) and`auto_deband.cpp`, whose "auto" block smoothing now has unit tests.+### In-app updates — done+After sign-in the app asks for the latest release and offers a newer one+(a pop-up with "Update now" / "Not now", and Settings > Updates). The zip+must be signed (ECDSA P-256) with the maintainer's key, which+`tools/release.sh` uses; a package that isn't that version or isn't newer+is refused. Files are swapped in place with a backup (an update cut short+is rolled back at the next start), then the app restarts itself+(`sceSystemServiceLoadExec`, from the main thread).+## Next| Item | Why | Size |diff --git a/ps5/release/README.txt b/ps5/release/README.txtindex 3b48201..87fe0df 100644--- a/ps5/release/README.txt+++ b/ps5/release/README.txt@@ -30,8 +30,11 @@ Installation2. Wait for the loader (e.g. ShadowMountPlus) to add the"PSBox Cloud Gaming" icon to the Home screen, then launch it.-Updating: close the app and copy the new @TITLE_ID@ folder over the old-one. Your sign-in is kept.+Updating: when a new version is out, the app offers it after sign-in+("Update now" / "Not now"; also in Settings > Updates). It downloads it,+checks that it was signed by this project, installs it and restarts by+itself; your sign-in and settings are kept. By hand: close the app and+copy the new @TITLE_ID@ folder over the old one.First launch@@ -105,7 +108,6 @@ the light bar in the colour of the game in focus, and the confirm button (Cross,then acts as Xbox A in games too). Saved in/data/homebrew/@TITLE_ID@/settings.json.-When a new version is out, a notification says so after sign-in.My consoles (Remote Play)diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex 7cde3e8..bb3314d 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -26,15 +26,16 @@ bool uiSaved = false;bool settingsShot = false; // "settingstest": save the screen nowuint64_t homeSince = 0, launchSince = 0;bool launchSaved = false;+bool acceptUpdate = false; // "updatetest": Cross on the pop-up, next pass ("updateskip": Circle)} // namespacevoid loadAutoplay() {std::string text;if (!platform::readFile(platform::dataDir() + "/autoplay.txt", text)) return;char title[128] = {};- char option[64] = {};+ char option[512] = {};int seconds = 0;- if (std::sscanf(text.c_str(), "%127s %d %63s", title, &seconds, option) < 1) return;+ if (std::sscanf(text.c_str(), "%127s %d %511s", title, &seconds, option) < 1) return;std::string options = option; // comma-separatedfor (size_t start = 0; start <= options.size();) {size_t comma = options.find(',', start);@@ -69,6 +70,12 @@ void loadAutoplay() {if (opt.rfind("res=", 0) == 0) g_autoplay.resolution = opt.substr(4);if (opt.rfind("sharp=", 0) == 0) g_autoplay.sharpness = std::atoi(opt.c_str() + 6);if (opt.rfind("deband=", 0) == 0) g_autoplay.deband = std::atoi(opt.c_str() + 7);+ if (opt.rfind("updatefeed=", 0) == 0) g_autoplay.updateFeed = opt.substr(11);+ if (opt == "testca") g_autoplay.testCa = true;+ if (opt == "updatetest") g_autoplay.updateTest = true;+ if (opt == "updateskip") g_autoplay.updateSkip = true;+ if (opt == "settingsupdate") g_autoplay.settingsUpdate = true;+ if (opt == "norestart") g_autoplay.noRestart = true;if (opt.rfind("threads=", 0) == 0) g_autoplay.decodeThreads = std::atoi(opt.c_str() + 8);}g_autoplay.title = title;@@ -141,6 +148,26 @@ void autoplayPad(input::ControllerState& pad) {}void autoplayNav(ui::NavInput& nav, bool& menuCombo, uint64_t now) {+ if (g_autoplay.settingsUpdate && uiSaved && !g_ui->updateOffered()) {+ // Settings, down to Updates (the last row), Cross.+ static uint64_t since = 0;+ static int step = 0;+ if (!since) since = now;+ if (step < 10 && now - since >= 500u + 300u * static_cast<unsigned>(step)) {+ nav = ui::NavInput{};+ if (step == 0) nav.options = true;+ if (step >= 1 && step <= 8) nav.down = true;+ if (step == 9) nav.accept = true;+ XC_LOGI("autoplay: settings update step %d", step);+ ++step;+ }+ }+ if (acceptUpdate) {+ acceptUpdate = false;+ nav = ui::NavInput{};+ (g_autoplay.updateSkip ? nav.back : nav.accept) = true;+ XC_LOGI("autoplay: update %s", g_autoplay.updateSkip ? "not now" : "now");+ }if (g_autoplay.menuTest && g_ui->screen() == ui::Screen::Streaming) {// Menu, down five times to the resolution, left to 720p, accept; at// 35 s right (back to 1080p) and accept.@@ -301,6 +328,30 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {saveCanvas("ui.ppm");}}+ if (g_autoplay.title == "UPDATE") {+ // The update test: the pop-up saved and accepted, the progress+ // saved; the run ends on the home screen without one (the new+ // version, or none offered).+ static uint64_t offeredAt = 0, updatingAt = 0, plainHomeAt = 0;+ bool offered = g_ui->updateOffered();+ if (offered && !offeredAt) offeredAt = now;+ if (offered && (g_autoplay.updateTest || g_autoplay.updateSkip) && now - offeredAt > 2500 && !acceptUpdate) {+ saveCanvas("update.ppm");+ acceptUpdate = true;+ }+ if (g_ui->screen() == ui::Screen::Updating && !updatingAt) updatingAt = now;+ if (updatingAt && updatingAt != 1 && now - updatingAt > 1500) {+ saveCanvas("updating.ppm");+ updatingAt = 1;+ }+ bool plainHome = g_ui->screen() == ui::Screen::Home && !offered;+ if (!plainHome) plainHomeAt = 0;+ else if (!plainHomeAt) plainHomeAt = now;+ else if (plainHomeAt != 1 && now - plainHomeAt > 25000) {+ plainHomeAt = 1;+ XC_LOGI("AUTOPLAY END: update test, running v%s", XC_APP_VERSION);+ }+ }}} // namespace xc::appdiff --git a/src/app/autoplay.h b/src/app/autoplay.hindex c481b9c..3e6418e 100644--- a/src/app/autoplay.h+++ b/src/app/autoplay.h@@ -13,7 +13,9 @@// 720p, back to 1080p), res=720p|1080p|1080p-hq|1440p, sharp=0..3 and// deband=0..3 and ai (Anime4K) instead of the settings.// The title "BENCH" decodes <dataDir>/sample.h264 instead; "XHOME" plays-// the account's first own console.+// the account's first own console; "UPDATE" stays on the home screen (the+// update test: updatefeed=<url> of a release, testca to trust+// <dataDir>/test-ca.pem, updatetest to accept the pop-up, norestart).#pragma once#include "input/controller.h"@@ -53,6 +55,12 @@ struct Autoplay {int deband = -1; // deband=0..3: instead of the settingint sharpness = -1; // sharp=0..3: instead of the settingstd::string resolution; // res=720p|1080p|1440p: instead of the setting+ std::string updateFeed; // updatefeed=<url>: the release JSON instead of GitHub's+ bool testCa = false; // testca: also trust <dataDir>/test-ca.pem (the feed's server)+ bool updateTest = false; // updatetest: accept the update pop-up, save update.ppm / updating.ppm+ bool updateSkip = false; // updateskip: "Not now" on the update pop-up+ bool settingsUpdate = false; // settingsupdate: Settings > Updates, Cross+ bool noRestart = false; // norestart: after an update, close instead of restarting};extern Autoplay g_autoplay;extern std::atomic<bool> g_syntheticA; // A held down for the gamediff --git a/src/app/cli_main.cpp b/src/app/cli_main.cppindex 119321f..64bcf67 100644--- a/src/app/cli_main.cpp+++ b/src/app/cli_main.cpp@@ -17,6 +17,7 @@// the PS5 home-screen icon (icon0.png: 512)// xcloud-cli logout#include "app/library.h"+#include "app/updater.h"#include "auth/auth_manager.h"#include "media/decoder.h"#include "net/http.h"@@ -536,6 +537,27 @@ int main(int argc, char** argv) {for (const auto& [e, n] : errors) std::printf(" %3d x %s\n", n, e.c_str());return failed ? 1 : 0;}+ if (cmd == "self-update" && argi + 1 < argc) {+ // The updater against a release feed, into a folder:+ // self-update <feed url> <dir> [extra CA .pem] [current version].+ if (argi + 2 < argc && !net::addTrustedCa(argv[argi + 2])) return 1;+ std::string current = argi + 3 < argc ? argv[argi + 3] : XC_APP_VERSION, err;+ app::Release release;+ if (!app::findLatestRelease(release, err, argv[argi])) {+ std::fprintf(stderr, "release: %s\n", err.c_str());+ return 1;+ }+ std::printf("release %s: %s (%ld bytes), %s\n", release.tag.c_str(), release.zipUrl.c_str(), release.zipSize,+ release.sigUrl.c_str());+ bool ok = app::installRelease(release, argv[argi + 1], current, [](app::UpdateStep step, double f) {+ static int last = -2;+ int pct = f < 0 ? -1 : static_cast<int>(f * 10) * 10;+ if (pct != last) std::printf(" step %d: %d%%\n", static_cast<int>(step), pct);+ last = pct;+ }, err);+ std::printf("%s\n", ok ? "installed" : ("failed: " + err).c_str());+ return ok ? 0 : 1;+ }auth::AuthManager am(platform::dataDir() + "/account.json");int rc;diff --git a/src/app/ps5_app.h b/src/app/ps5_app.hindex c0eb37e..7631d0e 100644--- a/src/app/ps5_app.h+++ b/src/app/ps5_app.h@@ -30,12 +30,14 @@ std::string settingsPath();bool allow1440Locked();// --- Worker commands (worker.cpp) -----------------------------------------------enum Command { kNone, kSignIn, kPlay, kSignOut, kReloadLibrary, kConsoles };+enum Command { kNone, kSignIn, kPlay, kSignOut, kReloadLibrary, kConsoles, kUpdate };extern std::atomic<int> g_command;extern std::atomic<bool> g_cancel;extern std::mutex g_argMutex;extern ui::GameTile g_playTile; // what kPlay playsvoid worker();+// The update pop-up's "Not now": that release isn't offered again on start.+void skipOfferedUpdate();// The running stream, for the input thread.extern std::mutex g_playerMutex;@@ -48,6 +50,9 @@ extern std::atomic<uint32_t> g_infoSeq;extern std::atomic<bool> g_playingHome; // the stream is the user's own Xboxextern std::atomic<bool> g_tierPicked; // the game menu chose a tier: the probe leaves itextern std::atomic<uint64_t> g_xboxButtonUntil; // the Xbox button, held until then (ms)+// An update is in place: the main thread starts the app again (the system+// call that does it takes the app down when made from another thread).+extern std::atomic<bool> g_restartWanted;// --- Store prices (price_loop.cpp) -----------------------------------------------void startPriceLoop();diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex c2e51e2..203d1e4 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -9,6 +9,7 @@#include "app/ps5_app.h"#include "app/settings.h"#include "app/stream_screen.h"+#include "app/updater.h"#include "display/display.h"#include "display/gpu.h"#include "input/controller.h"@@ -19,6 +20,7 @@#include "util/log.h"#include <cmath>+#include <cstdlib>#include <memory>#include <mutex>#include <string>@@ -45,6 +47,7 @@ std::atomic<uint32_t> g_infoSeq{0};std::atomic<bool> g_playingHome{false};std::atomic<bool> g_tierPicked{false};std::atomic<uint64_t> g_xboxButtonUntil{0};+std::atomic<bool> g_restartWanted{false};} // namespace xc::app@@ -72,6 +75,29 @@ void applyControllerSettings() {if (g_ui) g_ui->setCircleConfirms(g_settings.circleConfirms);}+// Saves what Settings edits (and applies the controller's part); true when+// the language changed.+bool saveSettings(const ui::SettingsChoice& choice) {+ bool languageChanged;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ std::string code = ui::languageCode(static_cast<ui::Language>(choice.language));+ languageChanged = code != g_settings.language;+ g_settings.language = code;+ g_settings.resolution = choice.resolution == 1 ? "720p" : choice.resolution == 2 ? "1440p" : "1080p";+ g_settings.region = choice.region;+ g_settings.deadzone = ui::kDeadzonePercent[choice.deadzone];+ g_settings.triggerRumble = choice.triggerRumble;+ g_settings.circleConfirms = choice.circleConfirms;+ g_settings.lightBar = choice.lightBar;+ if (!g_settings.save(settingsPath())) XC_LOGW("could not save settings");+ XC_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());+ }+ applyControllerSettings();+ return languageChanged;+}+// --- Input ---------------------------------------------------------------------// D-pad / left stick with key repeat: first press, then every 110 ms after@@ -109,6 +135,9 @@ int main(int argc, char** argv) {log::setFile((platform::dataDir() + "/xcloud.log").c_str());XC_LOGI("=== PSBox Cloud Gaming starting ===");loadAutoplay();+ // 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());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(),@@ -159,6 +188,7 @@ int main(int argc, char** argv) {platform::dataDir() + "/xcloud.log");if (g_autoplay.badCa) XC_LOGI("AUTOPLAY END: TLS setup error shown");} else {+ if (g_autoplay.testCa) net::addTrustedCa(platform::dataDir() + "/test-ca.pem");std::thread(worker).detach();}@@ -171,6 +201,14 @@ int main(int argc, char** argv) {uint64_t lightBarAt = 0;bool lightBarSet = false; // false from the menu/keyboard until the buttons are let gofor (;;) {+ if (g_restartWanted) {+ // After an update: the new version, started in place of this one.+ if (!g_autoplay.noRestart) platform::restartApp();+ // 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);+ }input::poll(pad);autoplayPad(pad);uint64_t now = platform::nowMs();@@ -261,31 +299,18 @@ int main(int argc, char** argv) {XC_LOGI("prefs saved: %zu hidden, sort %s", g_settings.hidden.size(), g_settings.librarySort.c_str());break;}- case ui::Action::SettingsChanged: {- bool languageChanged;- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- std::string code = ui::languageCode(static_cast<ui::Language>(ev.settings.language));- languageChanged = code != g_settings.language;- g_settings.language = code;- g_settings.resolution = ev.settings.resolution == 1 ? "720p"- : ev.settings.resolution == 2 ? "1440p"- : "1080p";- g_settings.region = ev.settings.region;- g_settings.deadzone = ui::kDeadzonePercent[ev.settings.deadzone];- g_settings.triggerRumble = ev.settings.triggerRumble;- g_settings.circleConfirms = ev.settings.circleConfirms;- g_settings.lightBar = ev.settings.lightBar;- if (!g_settings.save(settingsPath())) XC_LOGW("could not save settings");- XC_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());- }- applyControllerSettings();+ case ui::Action::SettingsChanged:// Row titles and game details come from the catalog in the// chosen language.- if (languageChanged) g_command = kReloadLibrary;+ if (saveSettings(ev.settings)) g_command = kReloadLibrary;+ break;+ case ui::Action::UpdateNow: {+ if (g_ui->screen() == ui::Screen::Settings) saveSettings(ev.settings);+ int idle = kNone;+ if (!g_command.compare_exchange_strong(idle, kUpdate)) XC_LOGW("update: the worker is busy");break;}+ case ui::Action::UpdateLater: skipOfferedUpdate(); break;case ui::Action::None: break;}diff --git a/src/app/settings.cpp b/src/app/settings.cppindex 0d5c4de..ef17237 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -32,6 +32,7 @@ bool Settings::load(const std::string& path) {circleConfirms = (*j)["circleConfirms"].asBool(circleConfirms);lightBar = (*j)["lightBar"].asBool(lightBar);gestureHints = static_cast<int>((*j)["gestureHints"].asInt(gestureHints));+ skippedUpdate = (*j)["skippedUpdate"].str();maxHeightCloud = static_cast<int>((*j)["maxHeightCloud"].asInt(0));maxHeightHome = static_cast<int>((*j)["maxHeightHome"].asInt(0));probedCloud = (*j)["probedCloud"].asInt(0);@@ -71,6 +72,7 @@ bool Settings::save(const std::string& path) const {v.set("circleConfirms", circleConfirms);v.set("lightBar", lightBar);v.set("gestureHints", gestureHints);+ v.set("skippedUpdate", skippedUpdate);v.set("maxHeightCloud", maxHeightCloud);v.set("maxHeightHome", maxHeightHome);v.set("probedCloud", probedCloud);diff --git a/src/app/settings.h b/src/app/settings.hindex 2413ae5..b9de523 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -37,6 +37,8 @@ struct Settings {// The DualSense light bar takes the colour of the game in focus.bool lightBar = true;int gestureHints = 0;+ // The release the user said "Not now" to: not offered again on start.+ std::string skippedUpdate;// The tallest picture each kind of stream delivered when asked for its// top tier, and when (unix s): 1440p is only offered once one did.int maxHeightCloud = 0, maxHeightHome = 0;diff --git a/src/app/update_check.cpp b/src/app/update_check.cppindex b9ff74c..cd74719 100644--- a/src/app/update_check.cpp+++ b/src/app/update_check.cpp@@ -5,6 +5,7 @@#include "net/http.h"#include "util/json.h"+#include <cstdio>#include <vector>namespace xc::app {@@ -34,15 +35,42 @@ bool isNewerVersion(const std::string& tag, const std::string& current) {return !a.empty() && !b.empty() && a > b;}-std::string latestReleaseTag() {+std::string contentVersionOf(const std::string& version) {+ auto p = parts(version);+ if (p.empty() || p[0] > 99 || p[1] > 9 || p[2] > 99) return {};+ char out[16];+ std::snprintf(out, sizeof out, "%02d.%d%02d.000", p[0], p[1], p[2]);+ return out;+}++bool findLatestRelease(Release& out, std::string& err, const std::string& feedUrl) {net::Request req;- req.url = kLatestRelease;+ req.url = feedUrl.empty() ? kLatestRelease : feedUrl;req.headers = {{"Accept", "application/vnd.github+json"}, {"User-Agent", "PSBox-Cloud-Gaming"}};req.timeoutMs = 10000;auto r = net::perform(req);- if (!r.ok()) return {};+ if (!r.ok()) {+ err = r.status ? "HTTP " + std::to_string(r.status) : r.error;+ return false;+ }auto j = json::parse(r.body);- return j ? (*j)["tag_name"].str() : std::string();+ if (!j || (*j)["tag_name"].str().empty()) {+ err = "no release in the answer";+ return false;+ }+ out = {};+ out.tag = (*j)["tag_name"].str();+ const auto& assets = (*j)["assets"];+ for (size_t i = 0; i < assets.size(); ++i) {+ const auto& a = assets[i];+ if (a["name"].str() == "PPSA99810.zip") {+ out.zipUrl = a["browser_download_url"].str();+ out.zipSize = static_cast<long>(a["size"].asInt(-1));+ } else if (a["name"].str() == "PPSA99810.zip.sig") {+ out.sigUrl = a["browser_download_url"].str();+ }+ }+ return true;}} // namespace xc::appdiff --git a/src/app/update_check.h b/src/app/update_check.hindex 8d9495b..a6a8dde 100644--- a/src/app/update_check.h+++ b/src/app/update_check.h@@ -11,7 +11,22 @@ namespace xc::app {// aren't versions are never newer.bool isNewerVersion(const std::string& tag, const std::string& current);-// The tag of the latest GitHub release, or empty (no network, rate limit).-std::string latestReleaseTag();+// The package's contentVersion (sce_sys/param.json) for a version:+// "0.8.1" -> "00.801.000", as tools/release.sh writes it; empty when it+// isn't one.+std::string contentVersionOf(const std::string& version);++// A release and the files the updater needs from it.+struct Release {+ std::string tag; // "v0.9.0"+ std::string zipUrl; // PPSA99810.zip+ std::string sigUrl; // PPSA99810.zip.sig, its signature+ long zipSize = -1;+};++// The latest GitHub release, or the release `feedUrl` describes (the same+// JSON; the update test's local server). False with `err` when there is+// none or it can't be asked (no network, rate limit).+bool findLatestRelease(Release& out, std::string& err, const std::string& feedUrl = {});} // namespace xc::appdiff --git a/src/app/updater.cpp b/src/app/updater.cppnew file mode 100644index 0000000..ed5f76c--- /dev/null+++ b/src/app/updater.cpp@@ -0,0 +1,348 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/updater.h"++#include "net/http.h"+#include "platform/platform.h"+#include "util/json.h"+#include "util/log.h"++#include <mbedtls/pk.h>+#include <mbedtls/sha256.h>+#if defined(MBEDTLS_PSA_CRYPTO_C)+#include <psa/crypto.h>+#endif++// stb_image's inflate, for the deflated entries (its own static copy).+#define STB_IMAGE_IMPLEMENTATION+#define STB_IMAGE_STATIC+#define STBI_ONLY_PNG+#define STBI_NO_STDIO+#if defined(__clang__)+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wunused-function"+#endif+#include "stb_image.h"+#if defined(__clang__)+#pragma clang diagnostic pop+#endif++#include <algorithm>+#include <cerrno>+#include <cstdio>+#include <cstring>+#include <dirent.h>+#include <set>+#include <sys/stat.h>+#include <unistd.h>++namespace xc::app {++const char* const kReleaseKey =+ "-----BEGIN PUBLIC KEY-----\n"+ "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGyPKcF2L65xh03F1ZRzfhv48LOWS\n"+ "OBKQ55SVLod7HOZZiViUTbY47qETC8l9A1ez1RflBTH94WILhlHhC4xTeQ==\n"+ "-----END PUBLIC KEY-----\n";++namespace {++constexpr size_t kMaxUnpacked = 256u << 20; // far above a release (~50 MB)++uint32_t le16(const std::string& s, size_t at) {+ return static_cast<uint8_t>(s[at]) | static_cast<uint8_t>(s[at + 1]) << 8;+}+uint32_t le32(const std::string& s, size_t at) {+ return le16(s, at) | le16(s, at + 2) << 16;+}++bool isDir(const std::string& path) {+ struct stat st {};+ return ::stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);+}+bool exists(const std::string& path) {+ struct stat st {};+ return ::stat(path.c_str(), &st) == 0;+}++// mkdir -p of the folder holding `file`.+bool makeParents(const std::string& file) {+ for (size_t at = file.find('/', 1); at != std::string::npos; at = file.find('/', at + 1)) {+ std::string d = file.substr(0, at);+ if (!isDir(d) && ::mkdir(d.c_str(), 0777) != 0 && errno != EEXIST) return false;+ }+ return true;+}++void removeTree(const std::string& path) {+ if (DIR* d = ::opendir(path.c_str())) {+ while (dirent* e = ::readdir(d)) {+ std::string name = e->d_name;+ if (name == "." || name == "..") continue;+ std::string p = path + "/" + name;+ if (isDir(p))+ removeTree(p);+ else+ ::unlink(p.c_str());+ }+ ::closedir(d);+ ::rmdir(path.c_str());+ }+}++// Every file under `root`, relative to it.+void listFiles(const std::string& root, const std::string& rel, std::vector<std::string>& out) {+ DIR* d = ::opendir((root + (rel.empty() ? "" : "/" + rel)).c_str());+ if (!d) return;+ while (dirent* e = ::readdir(d)) {+ std::string name = e->d_name;+ if (name == "." || name == "..") continue;+ std::string r = rel.empty() ? name : rel + "/" + name;+ if (isDir(root + "/" + r))+ listFiles(root, r, out);+ else+ out.push_back(r);+ }+ ::closedir(d);+}++bool download(const std::string& url, long size, std::string& out, const std::function<void(double)>& progress,+ std::string& err) {+ net::Request req;+ req.url = url;+ req.followRedirects = true; // GitHub hands the files out from another host+ req.timeoutMs = 30000;+ req.headers = {{"Accept", "application/octet-stream"}, {"User-Agent", "PSBox-Cloud-Gaming"}};+ out.clear();+ if (size > 0) out.reserve(static_cast<size_t>(size));+ req.onBody = [&](const char* data, size_t len) {+ if (out.size() + len > kMaxUnpacked) return false;+ out.append(data, len);+ return true;+ };+ if (progress)+ req.onProgress = [&](size_t got, long total) {+ if (total <= 0) total = size;+ progress(total > 0 ? std::min(1.0, static_cast<double>(got) / static_cast<double>(total)) : -1);+ };+ auto r = net::perform(req);+ if (!r.ok()) {+ err = "download " + url + ": " + (r.status ? "HTTP " + std::to_string(r.status) : r.error);+ return false;+ }+ if (size > 0 && static_cast<long>(out.size()) != size) {+ err = "download " + url + ": " + std::to_string(out.size()) + " bytes, " + std::to_string(size) + " expected";+ return false;+ }+ return true;+}++// The files in place go back where they were (an update cut short).+bool rollBack(const std::string& dir) {+ std::vector<std::string> old;+ listFiles(dir + "/update.old", "", old);+ for (const auto& rel : old)+ 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);+ return !old.empty();+}++} // namespace++bool verifySignature(const std::string& data, const std::string& sigDer, const char* publicKeyPem, std::string& err) {+#if defined(MBEDTLS_PSA_CRYPTO_C)+ psa_crypto_init(); // once per process; the TLS setup did it already in the app+#endif+ unsigned char hash[32];+ mbedtls_sha256(reinterpret_cast<const unsigned char*>(data.data()), data.size(), hash, 0);+ mbedtls_pk_context pk;+ mbedtls_pk_init(&pk);+ int rc = mbedtls_pk_parse_public_key(&pk, reinterpret_cast<const unsigned char*>(publicKeyPem),+ std::strlen(publicKeyPem) + 1);+ if (rc == 0)+ rc = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, hash, sizeof hash,+ reinterpret_cast<const unsigned char*>(sigDer.data()), sigDer.size());+ mbedtls_pk_free(&pk);+ if (rc != 0) {+ char buf[32];+ std::snprintf(buf, sizeof buf, "-0x%04x", static_cast<unsigned>(-rc));+ err = std::string("the signature doesn't match (") + buf + ")";+ }+ return rc == 0;+}++bool updatablePath(const std::string& path) {+ if (path.empty() || path[0] == '/' || path.find('\\') != std::string::npos ||+ path.find(':') != std::string::npos || path.find('\0') != std::string::npos)+ return false;+ for (size_t start = 0;;) {+ size_t slash = path.find('/', start);+ std::string part = path.substr(start, slash == std::string::npos ? std::string::npos : slash - start);+ if (part.empty() || part == "." || part == "..") return false;+ if (slash == std::string::npos) break;+ start = slash + 1;+ }+ static const std::set<std::string> kUsers = {"account.json", "settings.json", "library.json", "prices.json",+ "xcloud.log", "autoplay.txt", "update.journal"};+ std::string top = path.substr(0, path.find('/'));+ return !kUsers.count(path) && top != "imgcache" && top.rfind("update.", 0) != 0 && path.find(".ppm") == std::string::npos;+}++bool unzip(const std::string& zip, const std::string& prefix, std::vector<ZipEntry>& out, std::string& err) {+ out.clear();+ // The end of central directory record: within the last 64 KiB + 22.+ size_t eocd = std::string::npos;+ for (size_t back = 22; back <= std::min<size_t>(zip.size(), 65557); ++back)+ if (le32(zip, zip.size() - back) == 0x06054b50) {+ eocd = zip.size() - back;+ break;+ }+ if (eocd == std::string::npos) {+ err = "not a zip archive";+ return false;+ }+ size_t count = le16(zip, eocd + 10), at = le32(zip, eocd + 16);+ size_t total = 0;+ for (size_t n = 0; n < count; ++n) {+ if (at + 46 > zip.size() || le32(zip, at) != 0x02014b50) {+ err = "damaged zip directory";+ return false;+ }+ uint32_t method = le16(zip, at + 10), packed = le32(zip, at + 20), size = le32(zip, at + 24);+ size_t nameLen = le16(zip, at + 28), extraLen = le16(zip, at + 30), commentLen = le16(zip, at + 32);+ size_t local = le32(zip, at + 42);+ if (at + 46 + nameLen > zip.size()) {+ err = "damaged zip directory";+ return false;+ }+ std::string name = zip.substr(at + 46, nameLen);+ at += 46 + nameLen + extraLen + commentLen;+ if (!name.empty() && name.back() == '/') continue; // a folder+ if (name.rfind(prefix, 0) != 0 || !updatablePath(name.substr(prefix.size()))) {+ err = "unexpected file in the archive: " + name;+ return false;+ }+ if (local + 30 > zip.size() || le32(zip, local) != 0x04034b50) {+ err = "damaged zip entry " + name;+ return false;+ }+ size_t data = local + 30 + le16(zip, local + 26) + le16(zip, local + 28);+ total += size;+ if (data + packed > zip.size() || total > kMaxUnpacked) {+ err = "damaged zip entry " + name;+ return false;+ }+ ZipEntry e;+ e.path = name.substr(prefix.size());+ if (method == 0 && packed == size) {+ e.data = zip.substr(data, size);+ } else if (method == 8) {+ e.data.resize(size);+ int got = stbi_zlib_decode_noheader_buffer(e.data.data(), static_cast<int>(size), zip.data() + data,+ static_cast<int>(packed));+ if (got != static_cast<int>(size)) {+ err = "could not unpack " + name;+ return false;+ }+ } else {+ err = "unsupported compression in " + name;+ return false;+ }+ out.push_back(std::move(e));+ }+ return true;+}++bool installRelease(const Release& release, const std::string& dir, const std::string& currentVersion,+ const UpdateProgress& progress, std::string& err) {+ auto report = [&](UpdateStep step, double f) {+ if (progress) progress(step, f);+ };+ if (!isNewerVersion(release.tag, currentVersion)) {+ err = release.tag + " is not newer than " + currentVersion;+ return false;+ }+ if (release.zipUrl.empty() || release.sigUrl.empty()) {+ err = release.tag + " has no signed package";+ return false;+ }+ report(UpdateStep::Downloading, 0);+ std::string sig, zip;+ if (!download(release.sigUrl, -1, sig, nullptr, err)) return false;+ if (!download(release.zipUrl, release.zipSize, zip, [&](double f) { report(UpdateStep::Downloading, f); }, err))+ return false;+ XC_LOGI("update: %s downloaded, %zu bytes", release.tag.c_str(), zip.size());++ report(UpdateStep::Verifying, -1);+ if (!verifySignature(zip, sig, kReleaseKey, err)) return false;+ std::vector<ZipEntry> files;+ if (!unzip(zip, "PPSA99810/", files, err)) return false;+ zip.clear();+ zip.shrink_to_fit();+ // The package must be that version: an older signed one can't be+ // offered again under a new tag.+ std::string wanted = contentVersionOf(release.tag), packaged;+ bool hasEboot = false;+ for (const auto& f : files) {+ hasEboot |= f.path == "eboot.bin";+ if (f.path == "sce_sys/param.json")+ if (auto j = json::parse(f.data)) packaged = (*j)["contentVersion"].str();+ }+ if (!hasEboot || wanted.empty() || packaged != wanted) {+ err = "the package is not " + release.tag + " (contentVersion " + (packaged.empty() ? "?" : packaged) + ")";+ return false;+ }+ XC_LOGI("update: signature ok, %zu files, contentVersion %s", files.size(), packaged.c_str());++ report(UpdateStep::Installing, -1);+ recoverUpdate(dir); // leftovers of an earlier try+ const std::string staged = dir + "/update.new", old = dir + "/update.old";+ for (const auto& f : files) {+ std::string p = staged + "/" + f.path;+ // As the console's FTP servers leave a package's files: without the+ // execute bit, eboot.bin doesn't start (the restart then fails).+ if (!makeParents(p) || !platform::writeFileAtomic(p, f.data) || ::chmod(p.c_str(), 0777) != 0) {+ err = "could not write " + p;+ removeTree(staged);+ return false;+ }+ }+ // eboot.bin last: until then, a failure leaves the old app whole.+ std::stable_sort(files.begin(), files.end(),+ [](const ZipEntry& a, const ZipEntry& b) { return a.path != "eboot.bin" && b.path == "eboot.bin"; });+ if (!platform::writeFileAtomic(dir + "/update.journal", "swapping\n")) {+ err = "could not write the update journal";+ removeTree(staged);+ return false;+ }+ for (const auto& f : files) {+ std::string target = dir + "/" + f.path;+ bool moved = !exists(target) || (makeParents(old + "/" + f.path) &&+ ::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);+ ::unlink((dir + "/update.journal").c_str());+ removeTree(staged);+ removeTree(old);+ return false;+ }+ }+ ::unlink((dir + "/update.journal").c_str());+ removeTree(staged);+ XC_LOGI("update: %s installed", release.tag.c_str());+ return true;+}++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);+ ::unlink((dir + "/update.journal").c_str());+ }+ removeTree(dir + "/update.new");+ removeTree(dir + "/update.old");+ return rolledBack;+}++} // namespace xc::appdiff --git a/src/app/updater.h b/src/app/updater.hnew file mode 100644index 0000000..ade2df2--- /dev/null+++ b/src/app/updater.h@@ -0,0 +1,59 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// Updates the app in place from a release (update_check.h).+//+// The release's PPSA99810.zip must carry a signature (PPSA99810.zip.sig,+// ECDSA P-256 over SHA-256) by the project's own key, which tools/release.sh+// makes and only the maintainer holds: kReleaseKey here is its public half.+// Nothing is changed without it, nor for a version that isn't newer.+//+// The files are unpacked into <dir>/update.new, then each one in place is+// moved to <dir>/update.old and the new one put there (eboot.bin last); the+// running app keeps its old eboot.bin until it restarts. <dir>/update.journal+// is there while files move: a start that finds it puts the old ones back.+// The user's files (sign-in, settings, caches, log) are never touched.+#pragma once++#include "app/update_check.h"++#include <functional>+#include <string>+#include <vector>++namespace xc::app {++// The project's release signing key (public).+extern const char* const kReleaseKey;++enum class UpdateStep { Downloading, Verifying, Installing };+// `fraction` 0..1 within the step (downloading), -1 when unknown.+using UpdateProgress = std::function<void(UpdateStep step, double fraction)>;++// Downloads `release`, checks it and puts it in place in `dir` (the app's+// folder). `currentVersion` as XC_APP_VERSION. False with `err` (in English,+// for the log) when nothing was changed.+bool installRelease(const Release& release, const std::string& dir, const std::string& currentVersion,+ const UpdateProgress& progress, std::string& err);++// At start: puts back the old files of an update cut short (true when it+// did), and removes what updates left behind.+bool recoverUpdate(const std::string& dir);++// --- The parts, for the tests ---------------------------------------------------++// True when `sigDer` is a valid signature of `data` by `publicKeyPem`.+bool verifySignature(const std::string& data, const std::string& sigDer, const char* publicKeyPem, std::string& err);++struct ZipEntry {+ std::string path; // inside the archive, without `prefix`+ std::string data;+};+// The files of a zip archive (stored or deflated) under `prefix` ("PPSA99810/").+// False on a damaged archive, an entry outside `prefix` or an unsafe path.+bool unzip(const std::string& zip, const std::string& prefix, std::vector<ZipEntry>& out, std::string& err);++// A path an update may write: relative, no "..", and not one of the user's+// files or the updater's own.+bool updatablePath(const std::string& path);++} // namespace xc::appdiff --git a/src/app/worker.cpp b/src/app/worker.cppindex cba2944..9d40ed2 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -8,6 +8,7 @@#include "app/ps5_app.h"#include "app/stream_player.h"#include "app/update_check.h"+#include "app/updater.h"#include "auth/auth_manager.h"#include "platform/platform.h"#include "ui/strings.h"@@ -16,7 +17,9 @@#include "xcloud/gssv.h"#include "xcloud/regions.h"+#include <cstdlib>#include <map>+#include <sys/stat.h>#include <memory>#include <thread>#include <vector>@@ -315,6 +318,92 @@ void loadLibrary(xcloud::GssvClient& gssv);// Profile token for titlehub (memory only).std::string g_xblAuth;+// --- Updates -------------------------------------------------------------------++// The newer release found at start (empty tag: none).+std::mutex g_releaseMutex;+Release g_release;++// Asks for the latest release; a newer one with a signed package is offered+// (the pop-up, unless the user said "Not now" to it) and shown in Settings.+void checkForUpdate() {+ g_ui->setUpdateState(XC_APP_VERSION, {}, true);+ Release r;+ std::string err;+ bool found = findLatestRelease(r, err, g_autoplay.updateFeed);+ XC_LOGI("latest release: %s (this is %s)", found ? r.tag.c_str() : err.c_str(), XC_APP_VERSION);+ bool offer = found && isNewerVersion(r.tag, XC_APP_VERSION) && !r.zipUrl.empty() && !r.sigUrl.empty();+ if (found && isNewerVersion(r.tag, XC_APP_VERSION) && !offer) XC_LOGW("%s has no signed package", r.tag.c_str());+ {+ std::lock_guard<std::mutex> lock(g_releaseMutex);+ g_release = offer ? r : Release{};+ }+ g_ui->setUpdateState(XC_APP_VERSION, offer ? r.tag : std::string(), false);+ bool skipped;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ skipped = g_settings.skippedUpdate == r.tag;+ }+ if (offer && !skipped) g_ui->offerUpdate();+}++// The update itself, then the restart into the new version. A failure+// changes nothing and goes back to the home screen.+void runUpdate() {+ Release r;+ {+ std::lock_guard<std::mutex> lock(g_releaseMutex);+ r = g_release;+ }+ if (r.tag.empty()) return;+ XC_LOGI("update to %s: starting", r.tag.c_str());+ g_ui->showUpdating(r.tag);+ // Only where the app runs from (/app0 is the data folder): installed+ // elsewhere, it would write next to the wrong eboot.bin.+ std::string dir = platform::dataDir(), err;+ struct stat here {}, running {};+ bool ok = ::stat((dir + "/eboot.bin").c_str(), &here) == 0 && ::stat("/app0/eboot.bin", &running) == 0 &&+ here.st_ino == running.st_ino;+ if (!ok) err = "the app doesn't run from " + dir;+ int lastPct = -1;+ ok = ok && installRelease(r, dir, XC_APP_VERSION, [&](UpdateStep step, double f) {+ if (step == UpdateStep::Downloading) {+ int pct = f < 0 ? 0 : static_cast<int>(f * 100);+ if (pct == lastPct) return;+ lastPct = pct;+ g_ui->setUpdateStatus(ui::trf(ui::Str::UpdateDownloading, std::to_string(pct) + " %"), static_cast<float>(f));+ } else {+ g_ui->setUpdateStatus(ui::tr(step == UpdateStep::Verifying ? ui::Str::UpdateVerifying : ui::Str::UpdateInstalling), -1);+ }+ }, err);+ if (!ok) {+ XC_LOGE("update to %s failed: %s", r.tag.c_str(), err.c_str());+ g_ui->showHome(ui::tr(ui::Str::UpdateFailed));+ if (!g_autoplay.title.empty()) XC_LOGI("AUTOPLAY END: update failed");+ return;+ }+ g_ui->setUpdateStatus(ui::tr(ui::Str::UpdateRestarting), 1);+ platform::sleepMs(1500);+ XC_LOGI("update to %s: restarting", r.tag.c_str());+ g_restartWanted = true;+}++} // namespace++void skipOfferedUpdate() {+ std::string tag;+ {+ std::lock_guard<std::mutex> lock(g_releaseMutex);+ tag = g_release.tag;+ }+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ g_settings.skippedUpdate = tag;+ g_settings.save(settingsPath());+ XC_LOGI("update %s: not now", tag.c_str());+}++namespace {+// The note on the home screen after a stream: who ended it, when known.std::string endedToast(const std::string& result) {if (result.find("KickForStopCommand") != std::string::npos) return ui::tr(ui::Str::EndedOnXbox);@@ -386,13 +475,9 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {}platform::notify(ui::trf(ui::Str::SignedInAs, am.profile().gamertag), "signed in (notification)");static bool updateChecked = false;- if (!updateChecked && g_autoplay.title.empty()) {+ if (!updateChecked && (g_autoplay.title.empty() || !g_autoplay.updateFeed.empty())) {updateChecked = true;- std::thread([] {- std::string tag = app::latestReleaseTag();- XC_LOGI("latest release: %s (this is %s)", tag.empty() ? "unknown" : tag.c_str(), XC_APP_VERSION);- if (app::isNewerVersion(tag, XC_APP_VERSION)) platform::notify(ui::trf(ui::Str::UpdateAvailable, tag));- }).detach();+ std::thread(checkForUpdate).detach();}std::vector<std::string> regions;for (const auto& r : gssv.session().regions) regions.push_back(r.name);@@ -448,7 +533,7 @@ void loadLibrary(xcloud::GssvClient& gssv) {library->loadPlatforms(xblAuth, changed, &g_stopHydration);library->hydrate(changed, &g_stopHydration);});- if (!g_autoplay.title.empty() && g_autoplay.title != "BENCH" && !g_autoplay.detailTest && !g_autoplay.libraryTest &&+ if (!g_autoplay.title.empty() && g_autoplay.title != "BENCH" && g_autoplay.title != "UPDATE" && !g_autoplay.detailTest && !g_autoplay.libraryTest &&!g_autoplay.consolesTab && !g_autoplay.settingsTest &&!g_autoplay.imeTest && !g_autoplay.vibeTest) {platform::sleepMs(6000); // leave the home screen up for ui.ppm@@ -484,6 +569,7 @@ void worker() {loadConsoles(am, home); // empty when the sign-in failedbreak;case kConsoles: loadConsoles(am, home); break;+ case kUpdate: runUpdate(); break;case kReloadLibrary: loadLibrary(gssv); break; // e.g. after a language changecase kSignOut:am.signOut();diff --git a/src/net/http.cpp b/src/net/http.cppindex 7224e0c..049e4d7 100644--- a/src/net/http.cpp+++ b/src/net/http.cpp@@ -191,6 +191,14 @@ bool initTls(const std::string& caBundlePath) {return true;}+bool addTrustedCa(const std::string& pemPath) {+ std::lock_guard<std::mutex> lock(g.mutex);+ if (!g.ready) return false;+ int rc = mbedtls_x509_crt_parse_file(&g.ca, pemPath.c_str());+ XC_LOGI("extra CA %s: %s", pemPath.c_str(), rc == 0 ? "trusted" : tlsError(rc).c_str());+ return rc == 0;+}+void shutdownTls() {std::lock_guard<std::mutex> lock(g.mutex);if (!g.ready) return;@@ -288,6 +296,8 @@ Response performOnce(const Request& req) {size_t headerEnd = std::string::npos;long contentLength = -1;bool chunked = false;+ bool streaming = false; // the body goes to req.onBody+ size_t streamed = 0;unsigned char buf[16384];for (;;) {rc = mbedtls_ssl_read(&ssl, buf, sizeof buf);@@ -300,6 +310,13 @@ Response performOnce(const Request& req) {if (headerEnd != std::string::npos && contentLength < 0 && !chunked) break; // EOF-delimitedreturn finish("TLS read: " + tlsError(rc));}+ if (streaming) {+ if (!req.onBody(reinterpret_cast<char*>(buf), static_cast<size_t>(rc))) return finish("download stopped");+ streamed += static_cast<size_t>(rc);+ if (req.onProgress) req.onProgress(streamed, contentLength);+ if (contentLength >= 0 && streamed >= static_cast<size_t>(contentLength)) break;+ continue;+ }raw.append(reinterpret_cast<char*>(buf), static_cast<size_t>(rc));if (headerEnd == std::string::npos) {@@ -325,6 +342,16 @@ Response performOnce(const Request& req) {if (resp.headers.count("content-length")) contentLength = std::atol(resp.headers["content-length"].c_str());chunked = lower(resp.header("transfer-encoding")).find("chunked") != std::string::npos;if (req.method == "HEAD" || resp.status == 204 || resp.status == 304) contentLength = 0;+ if (req.onBody && resp.ok() && !chunked) {+ // What came with the headers, then each read as it arrives.+ streaming = true;+ streamed = raw.size() - (headerEnd + 4);+ if (streamed && !req.onBody(raw.data() + headerEnd + 4, streamed)) return finish("download stopped");+ raw.resize(headerEnd + 4);+ if (req.onProgress) req.onProgress(streamed, contentLength);+ if (contentLength >= 0 && streamed >= static_cast<size_t>(contentLength)) break;+ continue;+ }}size_t bodyLen = raw.size() - (headerEnd + 4);if (contentLength >= 0 && bodyLen >= static_cast<size_t>(contentLength)) break;@@ -333,6 +360,10 @@ Response performOnce(const Request& req) {mbedtls_ssl_close_notify(&ssl);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");+ return finish({});+ }std::string body = raw.substr(headerEnd + 4);if (chunked) {if (!dechunk(body, resp.body)) return finish("malformed chunked body");@@ -344,9 +375,7 @@ Response performOnce(const Request& req) {return finish({});}-} // namespace--Response perform(const Request& req) {+Response performRetrying(const Request& req) {Response resp = performOnce(req);// A GET that got no answer at all (the connection or the handshake// failed, or timed out) is asked once more: they are seldom and@@ -362,6 +391,35 @@ Response perform(const Request& req) {return resp;}+} // namespace++Response perform(const Request& req) {+ Response resp = performRetrying(req);+ Request next = req;+ for (int hops = 0; req.followRedirects && hops < 5; ++hops) {+ int s = resp.status;+ std::string location = resp.header("location");+ if ((s != 301 && s != 302 && s != 303 && s != 307 && s != 308) || location.empty()) break;+ Url from, to;+ Url::parse(next.url, from);+ if (location[0] == '/') {+ bool defaultPort = from.port == (from.scheme == "https" ? 443 : 80);+ location = from.scheme + "://" + from.host + (defaultPort ? "" : ":" + std::to_string(from.port)) + location;+ }+ if (!Url::parse(location, to)) break;+ if (to.host != from.host)+ for (auto it = next.headers.begin(); it != next.headers.end();)+ it = lower(it->first) == "authorization" ? next.headers.erase(it) : it + 1;+ if (s == 303) {+ next.method = "GET";+ next.body.clear();+ }+ next.url = location;+ resp = performRetrying(next);+ }+ return resp;+}+std::string urlEncode(const std::string& s) {static const char* hex = "0123456789ABCDEF";std::string out;diff --git a/src/net/http.h b/src/net/http.hindex 49d70d8..973f1d8 100644--- a/src/net/http.h+++ b/src/net/http.h@@ -7,6 +7,8 @@// nor the console's libSceHttp/libSceSsl is required.#pragma once+#include <cstddef>+#include <functional>#include <map>#include <string>#include <utility>@@ -20,6 +22,14 @@ struct Request {std::vector<std::pair<std::string, std::string>> headers;std::string body;int timeoutMs = 20000;+ // Follows 301/302/303/307/308 (five at most), without the Authorization+ // header once on another host.+ bool followRedirects = false;+ // A successful (2xx) body goes here as it arrives instead of into+ // Response::body (a large download); returning false stops it. With+ // `onProgress`: bytes so far, and the total (-1 unknown).+ std::function<bool(const char* data, size_t len)> onBody;+ std::function<void(size_t got, long total)> onProgress;};struct Response {@@ -44,6 +54,9 @@ struct Url {// Loads trusted roots from a PEM bundle. Must be called once before any// request; returns false when the file is missing or holds no certificates.bool initTls(const std::string& caBundlePath);+// Trusts the certificates in this PEM file too (the update test's local+// server); false when it holds none.+bool addTrustedCa(const std::string& pemPath);// Why initTls() failed (the step and Mbed TLS's message); empty otherwise.std::string tlsInitError();void shutdownTls();diff --git a/src/platform/host/platform_host.cpp b/src/platform/host/platform_host.cppindex 8fcbc60..7b3c65a 100644--- a/src/platform/host/platform_host.cpp+++ b/src/platform/host/platform_host.cpp@@ -92,4 +92,6 @@ bool systemKeyboardAvailable() { return false; }bool openSystemKeyboard(const std::string&, const std::string&, size_t, KeyboardKind) { return false; }KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed; }+bool restartApp() { return false; }+} // namespace xc::platformdiff --git a/src/platform/platform.h b/src/platform/platform.hindex 4639877..0cc524d 100644--- a/src/platform/platform.h+++ b/src/platform/platform.h@@ -62,6 +62,10 @@ bool openSystemKeyboard(const std::string& title, const std::string& text, size_// Accepted/Cancelled once, when the player closes it; `text` (UTF-8) on Accepted.KeyboardStatus pollSystemKeyboard(std::string& text);+// Starts the app again from its eboot.bin (after an update); returns only+// when it can't (false; the host never can).+bool restartApp();+bool readFile(const std::string& path, std::string& out);bool writeFileAtomic(const std::string& path, const std::string& data);diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cppindex 5889b5d..7ccc61d 100644--- a/src/platform/ps5/platform_ps5.cpp+++ b/src/platform/ps5/platform_ps5.cpp@@ -17,6 +17,7 @@#include <sys/socket.h>extern "C" {+int sceSystemServiceLoadExec(const char* path, char* const argv[]);int sceKernelSendNotificationRequest(int device, void* request, size_t size, int blocking);int sceNetInit(void);int sceNetPoolCreate(const char* name, int size, int flags);@@ -109,6 +110,15 @@ extern "C" int xc_resolve_ipv4(const char* host, uint32_t* addr) {namespace xc::platform {+bool restartApp() {+ // Replaces this process with /app0/eboot.bin (the console showed it+ // takes under a second, and the new eboot.bin is the one that starts).+ char* argv[] = {nullptr};+ int rc = sceSystemServiceLoadExec("/app0/eboot.bin", argv);+ XC_LOGE("restart: sceSystemServiceLoadExec returned 0x%08x", static_cast<unsigned>(rc));+ return false;+}+void notify(const std::string& text) { notify(text, text); }void notify(const std::string& text, const std::string& forLog) {diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 3afe928..f2d4d35 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -666,6 +666,43 @@ void AppUi::showPlayError(const std::string& message, const GameTile& game) {dirty_ = true;}+void AppUi::setUpdateState(const std::string& current, const std::string& available, bool checking) {+ std::lock_guard<std::mutex> lock(mutex_);+ updateCurrent_ = current;+ updateAvailable_ = available;+ updateChecking_ = checking;+ dirty_ = true;+}++void AppUi::offerUpdate() {+ std::lock_guard<std::mutex> lock(mutex_);+ updatePrompt_ = true;+ promptFocus_ = 0;+ dirty_ = true;+}++bool AppUi::updateOffered() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return updatePrompt_ && screen_ == Screen::Home;+}++void AppUi::showUpdating(const std::string& version) {+ std::lock_guard<std::mutex> lock(mutex_);+ screen_ = Screen::Updating;+ updatePrompt_ = false;+ updatingTo_ = version;+ updateStatus_.clear();+ updateFraction_ = -1;+ dirty_ = true;+}++void AppUi::setUpdateStatus(const std::string& status, float fraction) {+ std::lock_guard<std::mutex> lock(mutex_);+ updateStatus_ = status;+ updateFraction_ = fraction;+ dirty_ = true;+}+void AppUi::setSettings(const SettingsChoice& choice) {std::lock_guard<std::mutex> lock(mutex_);settings_ = choice;@@ -752,6 +789,8 @@ std::vector<std::string> AppUi::settingOptions(int row) const {out = {tr(Str::ButtonCross), tr(Str::ButtonCircle)};} else if (row == 6) {out = {tr(Str::Activated), tr(Str::Deactivated)};+ } else if (row == 7) {+ // Updates: Cross acts, no list.} else {// Automatic first, then the regions in the login's order.out.push_back(withMs(trf(Str::RegionAuto, defaultRegion_.empty() ? "-" : prettyRegion(defaultRegion_)),@@ -773,6 +812,7 @@ int AppUi::settingSelected(int row) const {if (row == 4) return settings_.triggerRumble ? 0 : 1;if (row == 5) return settings_.circleConfirms ? 1 : 0;if (row == 6) return settings_.lightBar ? 0 : 1;+ if (row == 7) return 0;for (size_t i = 0; i < regions_.size(); ++i)if (regions_[i] == settings_.region) return static_cast<int>(i) + 1;return 0;@@ -793,6 +833,7 @@ void AppUi::applySetting(int row, int index) {settings_.circleConfirms = index == 1;} else if (row == 6) {settings_.lightBar = index == 0;+ } else if (row == 7) {} else {settings_.region = index == 0 ? std::string() : regions_[static_cast<size_t>(index - 1)];}@@ -1122,6 +1163,16 @@ void AppUi::handleSearchKeys(const NavInput& in) {UiEvent AppUi::handle(const NavInput& in) {std::lock_guard<std::mutex> lock(mutex_);UiEvent ev;+ if (screen_ == Screen::Home && updatePrompt_) {+ // The update pop-up has the pad: left / right, Cross picks, Circle is "Not now".+ if (in.left || in.right) promptFocus_ = 1 - promptFocus_, dirty_ = true;+ if (in.accept || in.back) {+ ev.action = in.accept && promptFocus_ == 0 ? Action::UpdateNow : Action::UpdateLater;+ updatePrompt_ = false;+ dirty_ = true;+ }+ return ev;+ }switch (screen_) {case Screen::Home: handleHome(in, ev); break;case Screen::Settings:@@ -1139,7 +1190,13 @@ UiEvent AppUi::handle(const NavInput& in) {if (in.up && settingsRow_ > 0) --settingsRow_, dirty_ = true;if (in.right) changeSetting(+1);if (in.left) changeSetting(-1);- if (in.accept) {+ if (in.accept && settingsRow_ == 7) {+ // Updates: a newer version is installed (the settings saved first).+ if (!updateAvailable_.empty() && !updateChecking_) {+ ev.action = Action::UpdateNow;+ ev.settings = settings_;+ }+ } else if (in.accept) {dropdownOpen_ = true;dropdownIndex_ = settingSelected(settingsRow_);dropdownTop_ = 0;@@ -1211,7 +1268,8 @@ bool AppUi::needsRedraw(uint64_t nowMs) const {if (screen_ == Screen::Streaming) return false;if (dirty_ || animating_) return true;// Spinners keep moving (about 30 fps is enough).- bool spinner = screen_ == Screen::Splash || screen_ == Screen::SignIn || screen_ == Screen::Launching;+ bool spinner = screen_ == Screen::Splash || screen_ == Screen::SignIn || screen_ == Screen::Launching ||+ screen_ == Screen::Updating;return spinner && nowMs - lastRender_ >= 33;}@@ -2009,8 +2067,8 @@ void AppUi::drawSettings(Canvas& c) {fonts_.bold.draw(c, tr(Str::Settings), kMargin, 170, 60, kWhite);const char* labels[kSettingRows] = {tr(Str::Language), tr(Str::Resolution), tr(Str::Region),tr(Str::Deadzone), tr(Str::TriggerRumble), tr(Str::ConfirmButton),- tr(Str::LightBar)};- constexpr int kRowW = 1200, kRowH = 70;+ tr(Str::LightBar), tr(Str::Updates)};+ constexpr int kRowW = 1200, kRowH = 66;Rect rows[kSettingRows];int y = 262;for (int i = 0; i < kSettingRows; ++i) {@@ -2021,6 +2079,17 @@ void AppUi::drawSettings(Canvas& c) {if (focused && !dropdownOpen_) c.strokeRect({r.x - 5, r.y - 5, r.w + 10, r.h + 10}, kWhite, 3, 20);int ty = fonts_.semibold.centeredY(r.y, r.h, 30);fonts_.semibold.draw(c, labels[i], r.x + 36, ty, 30, kWhite);+ if (i == 7) {+ // Updates: the state; Cross updates when there is a newer version.+ std::string value = updateChecking_ ? tr(Str::UpdateChecking)+ : !updateAvailable_.empty() ? trf(Str::UpdateReady, updateAvailable_)+ : trf(Str::UpToDate, "v" + updateCurrent_);+ Color color = !updateAvailable_.empty() && !updateChecking_ ? rgba(120, 220, 120) : focused ? kWhite : kGray;+ int w = fonts_.regular.measure(value, 30);+ fonts_.regular.draw(c, value, r.x + r.w - 44 - w, fonts_.regular.centeredY(r.y, r.h, 30), 30, color);+ y += kRowH + 10;+ continue;+ }// The value, then a chevron: this opens a list.auto options = settingOptions(i);int sel = settingSelected(i);@@ -2031,7 +2100,7 @@ void AppUi::drawSettings(Canvas& c) {int w = fonts_.regular.measure(value, 30);fonts_.regular.draw(c, value, r.x + r.w - 76 - w, fonts_.regular.centeredY(r.y, r.h, 30), 30,focused ? kWhite : kGray);- y += kRowH + 14;+ y += kRowH + 10;}for (const auto& line : fonts_.regular.wrap(tr(Str::SettingsNote), 24, kRowW, 2)) {fonts_.regular.draw(c, line, kMargin, y + 20, 24, kDim);@@ -2085,6 +2154,46 @@ void AppUi::drawSettings(Canvas& c) {}}+void AppUi::drawUpdatePrompt(Canvas& c) {+ c.fillRect({0, 0, kW, kH}, rgba(0, 0, 0, 160));+ constexpr int kPanelW = 960, kPanelH = 340, kButtonW = 360, kButtonH = 72;+ Rect panel{(kW - kPanelW) / 2, (kH - kPanelH) / 2 - 40, kPanelW, kPanelH};+ c.fillRect({panel.x + 8, panel.y + 12, panel.w, panel.h}, rgba(0, 0, 0, 120), 26); // shadow+ c.fillRect(panel, kPanel, 24);+ c.strokeRect(panel, rgba(255, 255, 255, 50), 2, 24);+ fonts_.bold.draw(c, trf(Str::UpdateAvailable, updateAvailable_), panel.x + 56, panel.y + 48, 44, kWhite);+ auto lines = fonts_.regular.wrap(tr(Str::UpdatePrompt), 26, kPanelW - 112, 2);+ for (size_t i = 0; i < lines.size(); ++i)+ fonts_.regular.draw(c, lines[i], panel.x + 56, panel.y + 124 + static_cast<int>(i) * 36, 26, kGray);+ const char* labels[2] = {tr(Str::UpdateNow), tr(Str::NotNow)};+ for (int i = 0; i < 2; ++i) {+ Rect b{panel.x + 56 + i * (kButtonW + 24), panel.y + panel.h - kButtonH - 44, kButtonW, kButtonH};+ bool on = i == promptFocus_;+ c.fillRect(b, on ? kWhite : rgba(255, 255, 255, 30), 14);+ int tw = fonts_.semibold.measure(labels[i], 28);+ fonts_.semibold.draw(c, labels[i], b.x + (b.w - tw) / 2, fonts_.semibold.centeredY(b.y, b.h, 28), 28,+ on ? kBg : kWhite);+ }+ c.fillRect({0, kH - 80, kW, 80}, kBg); // the home screen's hints, under the pop-up's+ drawPads(c);+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconCircle, tr(Str::NotNow)}});+}++void AppUi::drawUpdating(Canvas& c, uint64_t nowMs) {+ drawBackground(c);+ drawLogo(c, kW / 2.0f, 330, 56);+ drawCentered(c, fonts_.bold, trf(Str::UpdatingTo, updatingTo_), 440, 48, kWhite);+ drawCentered(c, fonts_.regular, updateStatus_, 520, 28, kGray);+ if (updateFraction_ >= 0) {+ constexpr int kBarW = 720;+ Rect bar{(kW - kBarW) / 2, 590, kBarW, 12};+ c.fillRect(bar, rgba(255, 255, 255, 40), 6);+ c.fillRect({bar.x, bar.y, static_cast<int>(kBarW * std::min(1.0f, updateFraction_)), bar.h}, kGreen, 6);+ } else {+ drawSpinner(c, kW / 2.0f, 610, 24, nowMs);+ }+}+void AppUi::drawSignOutHold(Canvas& c, uint64_t nowMs) {if (!signOutHoldStart_) return;float progress = std::min(1.0f, static_cast<float>(nowMs - signOutHoldStart_) / kSignOutHoldMs);@@ -2122,9 +2231,11 @@ void AppUi::render(Canvas& c, uint64_t nowMs) {case Screen::Launching: drawLaunching(c, nowMs); break;case Screen::Error: drawError(c); break;case Screen::Settings: drawSettings(c); break;+ case Screen::Updating: drawUpdating(c, nowMs); break;case Screen::Streaming: break;}- if (screen_ == Screen::Home || screen_ == Screen::Error) drawSignOutHold(c, nowMs);+ if (screen_ == Screen::Home && updatePrompt_) drawUpdatePrompt(c);+ if ((screen_ == Screen::Home && !updatePrompt_) || screen_ == Screen::Error) drawSignOutHold(c, nowMs);if (!toast_.empty()) animating_ = true; // to expire it}diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 7766985..2aa4955 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -58,7 +58,7 @@ struct GameRow {bool gamePassBadges = true;};-enum class Screen { Splash, SignIn, Home, Details, Launching, Streaming, Error, Settings };+enum class Screen { Splash, SignIn, Home, Details, Launching, Streaming, Error, Settings, Updating };// The home screen's tabs (L1 / R1). Triangle searches the current one.enum class Tab { GamePass, Library, Consoles };@@ -85,10 +85,14 @@ struct SettingsChoice {// The stick dead zones Settings offers, in percent of the travel.constexpr int kDeadzonePercent[] = {0, 5, 10, 15, 20, 25};-constexpr int kSettingRows = 7; // language, resolution, region, dead zone, triggers, confirm, light bar+constexpr int kSettingRows = 8; // language, resolution, region, dead zone, triggers, confirm, light bar, updates-// ConsolesShown: "My consoles" opened (its list is refreshed).-enum class Action { None, Play, SignOut, Retry, CancelLaunch, SettingsChanged, PrefsChanged, ConsolesShown };+// ConsolesShown: "My consoles" opened (its list is refreshed). UpdateNow+// (with the settings, saved first when it came from Settings) / UpdateLater:+// the answer to the update pop-up, or Updates in Settings.+enum class Action {+ None, Play, SignOut, Retry, CancelLaunch, SettingsChanged, PrefsChanged, ConsolesShown, UpdateNow, UpdateLater+};// How "Your games" is sorted (R3).enum class LibrarySort { Recent, AZ, Console, Count };@@ -176,6 +180,15 @@ public:// Regions offered by the account's xCloud login; `defaultRegion` is the// one "Automatic" picks.void setRegions(std::vector<std::string> regions, const std::string& defaultRegion);+ // Updates: this version, and the newer one (empty: up to date);+ // `checking` while it is being asked (Settings shows it).+ void setUpdateState(const std::string& current, const std::string& available, bool checking);+ // The pop-up offering the newer version, over the home screen.+ void offerUpdate();+ bool updateOffered() const;+ // The screen while it updates: `status` and, 0..1, how far (-1: a spinner).+ void showUpdating(const std::string& version);+ void setUpdateStatus(const std::string& status, float fraction);Screen screen() const;Tab tab() const;// Switches the home screen's tab (autoplay tests).@@ -248,6 +261,8 @@ private:void drawLaunching(Canvas& c, uint64_t nowMs);void drawError(Canvas& c);void drawSettings(Canvas& c);+ void drawUpdatePrompt(Canvas& c);+ void drawUpdating(Canvas& c, uint64_t nowMs);void changeSetting(int delta);// Settings drop-downs: the choices of a row, the chosen one, choosing.std::vector<std::string> settingOptions(int row) const;@@ -316,6 +331,12 @@ private:std::vector<std::string> categories;};std::map<std::string, DetailInfo> detailInfo_; // fetched on demand, by product id+ std::string updateCurrent_, updateAvailable_;+ bool updateChecking_ = false;+ bool updatePrompt_ = false; // the pop-up is up (on the home screen)+ int promptFocus_ = 0; // 0 Update now, 1 Not now+ std::string updatingTo_, updateStatus_;+ float updateFraction_ = -1;int settingsRow_ = 0;bool dropdownOpen_ = false; // the list of the focused settings rowint dropdownIndex_ = 0, dropdownTop_ = 0;diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex ecfbbb0..47e083a 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -139,7 +139,7 @@ constexpr Column kEnglish = {"Off", // Deactivated"Cross", // ButtonCross"Circle", // ButtonCircle- "PSBox Cloud Gaming %s is out: get it on GitHub (RafaelNGP/xbox-cloud-gaming-ps5)",// UpdateAvailable+ "Version %s available", // UpdateAvailable"Controllers", // Controllers"Controller %s connected", // PadConnected"Controller %s disconnected", // PadDisconnected@@ -179,6 +179,20 @@ constexpr Column kEnglish = {"FSR + clean-up", // UpscalerFsrClean"AI + clean-up", // UpscalerAiClean"Auto (%s)", // DebandAuto+ "Update now? The app restarts by itself when it's done.", // UpdatePrompt+ "Update now", // UpdateNow+ "Not now", // NotNow+ "Updates", // Updates+ "Up to date (%s)", // UpToDate+ "%s available: update", // UpdateReady+ "Checking...", // UpdateChecking+ "Updating to %s", // UpdatingTo+ "Downloading... %s", // UpdateDownloading+ "Checking the signature...", // UpdateVerifying+ "Installing...", // UpdateInstalling+ "Updated. Restarting...", // UpdateRestarting+ "PSBox updated: open the app again", // UpdateReopen+ "Update failed: nothing was changed", // UpdateFailed};constexpr Column kPortugueseBR = {@@ -288,7 +302,7 @@ constexpr Column kPortugueseBR = {"Desativada","Xis","Círculo",- "Saiu o PSBox Cloud Gaming %s: baixe no GitHub (RafaelNGP/xbox-cloud-gaming-ps5)",+ "Versão %s disponível","Controles","Controle %s conectado","Controle %s desconectado",@@ -328,6 +342,20 @@ constexpr Column kPortugueseBR = {"FSR + limpeza","IA + limpeza","Auto (%s)",+ "Atualizar agora? O app reinicia sozinho ao terminar.",+ "Atualizar agora",+ "Agora não",+ "Atualizações",+ "Atualizado (%s)",+ "%s disponível: atualizar",+ "Verificando...",+ "Atualizando para %s",+ "Baixando... %s",+ "Conferindo a assinatura...",+ "Instalando...",+ "Atualizado. Reiniciando...",+ "PSBox atualizado: abra o app de novo",+ "A atualização falhou: nada foi alterado",};constexpr Column kSpanish = {@@ -437,7 +465,7 @@ constexpr Column kSpanish = {"Desactivada","Equis","Círculo",- "Ya está disponible PSBox Cloud Gaming %s: descárgalo en GitHub (RafaelNGP/xbox-cloud-gaming-ps5)",+ "Versión %s disponible","Mandos","Mando %s conectado","Mando %s desconectado",@@ -477,6 +505,20 @@ constexpr Column kSpanish = {"FSR + limpieza","IA + limpieza","Auto (%s)",+ "¿Actualizar ahora? La app se reinicia sola al terminar.",+ "Actualizar ahora",+ "Ahora no",+ "Actualizaciones",+ "Al día (%s)",+ "%s disponible: actualizar",+ "Comprobando...",+ "Actualizando a %s",+ "Descargando... %s",+ "Comprobando la firma...",+ "Instalando...",+ "Actualizado. Reiniciando...",+ "PSBox actualizado: abre la app de nuevo",+ "La actualización falló: no se cambió nada",};constexpr Column kFrench = {@@ -586,7 +628,7 @@ constexpr Column kFrench = {"Désactivée","Croix","Rond",- "PSBox Cloud Gaming %s est disponible : téléchargez-le sur GitHub (RafaelNGP/xbox-cloud-gaming-ps5)",+ "Version %s disponible","Manettes","Manette %s connectée","Manette %s déconnectée",@@ -626,6 +668,20 @@ constexpr Column kFrench = {"FSR + nettoyage","IA + nettoyage","Auto (%s)",+ "Mettre à jour maintenant ? L'app redémarre toute seule à la fin.",+ "Mettre à jour",+ "Plus tard",+ "Mises à jour",+ "À jour (%s)",+ "%s disponible : mettre à jour",+ "Vérification...",+ "Mise à jour vers %s",+ "Téléchargement... %s",+ "Vérification de la signature...",+ "Installation...",+ "Mis à jour. Redémarrage...",+ "PSBox mis à jour : rouvrez l'app",+ "Échec de la mise à jour : rien n'a changé",};constexpr Column kGerman = {@@ -735,7 +791,7 @@ constexpr Column kGerman = {"Aus","Kreuz","Kreis",- "PSBox Cloud Gaming %s ist da: auf GitHub herunterladen (RafaelNGP/xbox-cloud-gaming-ps5)",+ "Version %s verfügbar","Controller","Controller %s verbunden","Controller %s getrennt",@@ -775,6 +831,20 @@ constexpr Column kGerman = {"FSR + Bereinigung","KI + Bereinigung","Auto (%s)",+ "Jetzt aktualisieren? Die App startet danach von selbst neu.",+ "Jetzt aktualisieren",+ "Nicht jetzt",+ "Updates",+ "Aktuell (%s)",+ "%s verfügbar: aktualisieren",+ "Wird geprüft...",+ "Aktualisierung auf %s",+ "Wird geladen... %s",+ "Signatur wird geprüft...",+ "Wird installiert...",+ "Aktualisiert. Neustart...",+ "PSBox aktualisiert: App erneut öffnen",+ "Update fehlgeschlagen: nichts wurde geändert",};constexpr Column kItalian = {@@ -884,7 +954,7 @@ constexpr Column kItalian = {"Disattivata","Croce","Cerchio",- "È disponibile PSBox Cloud Gaming %s: scaricalo da GitHub (RafaelNGP/xbox-cloud-gaming-ps5)",+ "Versione %s disponibile","Controller","Controller %s connesso","Controller %s disconnesso",@@ -924,6 +994,20 @@ constexpr Column kItalian = {"FSR + pulizia","IA + pulizia","Auto (%s)",+ "Aggiornare ora? L'app si riavvia da sola alla fine.",+ "Aggiorna ora",+ "Non ora",+ "Aggiornamenti",+ "Aggiornato (%s)",+ "%s disponibile: aggiorna",+ "Verifica...",+ "Aggiornamento a %s",+ "Download... %s",+ "Verifica della firma...",+ "Installazione...",+ "Aggiornato. Riavvio...",+ "PSBox aggiornato: riapri l'app",+ "Aggiornamento non riuscito: nulla è cambiato",};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex b8f5398..55d4e3c 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -116,7 +116,7 @@ enum class Str {Deactivated,ButtonCross,ButtonCircle,- UpdateAvailable, // "%s" = the new version+ UpdateAvailable, // the update pop-up's title; "%s" = the new versionControllers, // in-game menu: the pads in usePadConnected, // "%s" = "2 (user name)"PadDisconnected, // "%s" = "2 (user name)"@@ -156,6 +156,20 @@ enum class Str {UpscalerFsrClean, // game menu: FSR after Anime4K Restore (cleans compression artefacts)UpscalerAiClean, // Anime4K upscale after Anime4K RestoreDebandAuto, // "%s" = the level in use now; block smoothing follows the bitrate+ UpdatePrompt, // the update pop-up's text+ UpdateNow, // button+ NotNow, // button+ Updates, // Settings row+ UpToDate, // "%s" = this version+ UpdateReady, // "%s" = the new version: Settings, Cross updates+ UpdateChecking, // Settings, while it asks+ UpdatingTo, // "%s" = the new version+ UpdateDownloading, // "%s" = percent+ UpdateVerifying,+ UpdateInstalling,+ UpdateRestarting,+ UpdateReopen, // notification when it couldn't restart+ UpdateFailed, // toast; nothing was changedCount};diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 974e76e..1cf93b1 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -4,6 +4,7 @@#include "app/auto_deband.h"#include "app/settings.h"#include "app/update_check.h"+#include "app/updater.h"#include "net/http.h"#include "platform/platform.h"#include "stream/input_packet.h"@@ -17,6 +18,8 @@#include "xcloud/regions.h"#include <cstdio>+#include <cstdlib>+#include <vector>#include <string>using namespace xc;@@ -292,6 +295,81 @@ static void testStreamMenu() {CHECK(menu.resolution() == 0); // back to 1080p, never 1440p}+// A zip archive of stored (uncompressed) files, as the test needs one.+static std::string storedZip(const std::vector<std::pair<std::string, std::string>>& files) {+ auto le = [](std::string& s, uint32_t v, int bytes) {+ for (int i = 0; i < bytes; ++i) s += static_cast<char>((v >> (8 * i)) & 0xFF);+ };+ std::string out, dir;+ for (const auto& [name, data] : files) {+ uint32_t at = static_cast<uint32_t>(out.size()), n = static_cast<uint32_t>(data.size());+ le(out, 0x04034b50, 4), le(out, 20, 2), le(out, 0, 2), le(out, 0, 2), le(out, 0, 4), le(out, 0, 4);+ le(out, n, 4), le(out, n, 4), le(out, static_cast<uint32_t>(name.size()), 2), le(out, 0, 2);+ out += name + data;+ le(dir, 0x02014b50, 4), le(dir, 20, 2), le(dir, 20, 2), le(dir, 0, 2), le(dir, 0, 2), le(dir, 0, 4), le(dir, 0, 4);+ le(dir, n, 4), le(dir, n, 4), le(dir, static_cast<uint32_t>(name.size()), 2), le(dir, 0, 2), le(dir, 0, 2);+ le(dir, 0, 2), le(dir, 0, 2), le(dir, 0, 4), le(dir, at, 4);+ dir += name;+ }+ uint32_t dirAt = static_cast<uint32_t>(out.size());+ out += dir;+ le(out, 0x06054b50, 4), le(out, 0, 2), le(out, 0, 2), le(out, static_cast<uint32_t>(files.size()), 2);+ le(out, static_cast<uint32_t>(files.size()), 2), le(out, static_cast<uint32_t>(dir.size()), 4), le(out, dirAt, 4);+ le(out, 0, 2);+ return out;+}++static void testUpdater() {+ using namespace xc::app;+ CHECK(contentVersionOf("v0.8.1") == "00.801.000" && contentVersionOf("1.10.0").empty());+ CHECK(updatablePath("eboot.bin") && updatablePath("sce_sys/param.json") && updatablePath("assets/fonts/a.ttf"));+ CHECK(!updatablePath("../eboot.bin") && !updatablePath("/data/x") && !updatablePath("a//b") && !updatablePath("a/./b"));+ CHECK(!updatablePath("account.json") && !updatablePath("settings.json") && !updatablePath("imgcache/x"));+ CHECK(!updatablePath("update.old/eboot.bin") && !updatablePath("update.journal") && !updatablePath("frame.ppm"));++ // A signature by a throwaway key (made for this test only).+ const char* pub =+ "-----BEGIN PUBLIC KEY-----\n"+ "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAETaRKE8e1bXOEYcQDqc3yvrCF4reo\n"+ "nn1S6x6D3sFYl8eHLd7qogQNmh7Nseqx41gMcXh5TVqOjvMS+7mpqk0Wxg==\n"+ "-----END PUBLIC KEY-----\n";+ const char* hex =+ "3045022021a9fa17a6717284e6d5989fcffb6363d371f97ea00b4e9ecec4adaa11a01a050221008053381afe913f3071594281868a44"+ "cd57589796b296b1818b37a6e3c8880514";+ std::string sig;+ for (size_t i = 0; hex[i] && hex[i + 1]; i += 2) sig += static_cast<char>(std::stoi(std::string(hex + i, 2), nullptr, 16));+ std::string err;+ CHECK(verifySignature("PSBox test", sig, pub, err));+ CHECK(!verifySignature("PSBox tesT", sig, pub, err));+ CHECK(!verifySignature("PSBox test", sig, kReleaseKey, err)); // another key++ std::vector<ZipEntry> files;+ CHECK(unzip(storedZip({{"PPSA99810/eboot.bin", "elf"}, {"PPSA99810/sce_sys/param.json", "{}"}}), "PPSA99810/", files,+ err));+ CHECK(files.size() == 2 && files[0].path == "eboot.bin" && files[0].data == "elf" && files[1].path == "sce_sys/param.json");+ CHECK(!unzip(storedZip({{"PPSA99810/../evil", "x"}}), "PPSA99810/", files, err));+ CHECK(!unzip(storedZip({{"PPSA99810/account.json", "x"}}), "PPSA99810/", files, err));+ CHECK(!unzip(storedZip({{"other/eboot.bin", "x"}}), "PPSA99810/", files, err));+ CHECK(!unzip("not a zip", "PPSA99810/", files, err));++ // An update cut short while files moved: the old ones go back.+ std::string dir = "/tmp/xcloud-updater-test";+ std::system(("rm -rf " + dir + " && mkdir -p " + dir + "/update.old/sce_sys").c_str());+ xc::platform::writeFileAtomic(dir + "/eboot.bin", "new");+ xc::platform::writeFileAtomic(dir + "/update.old/eboot.bin", "old");+ xc::platform::writeFileAtomic(dir + "/update.old/sce_sys/param.json", "old param");+ xc::platform::writeFileAtomic(dir + "/account.json", "mine");+ xc::platform::writeFileAtomic(dir + "/update.journal", "swapping\n");+ CHECK(recoverUpdate(dir));+ std::string text;+ CHECK(xc::platform::readFile(dir + "/eboot.bin", text) && text == "old");+ CHECK(xc::platform::readFile(dir + "/sce_sys/param.json", text) && text == "old param");+ CHECK(xc::platform::readFile(dir + "/account.json", text) && text == "mine");+ CHECK(!xc::platform::readFile(dir + "/update.journal", text) && !xc::platform::readFile(dir + "/update.old/eboot.bin", text));+ CHECK(!recoverUpdate(dir)); // nothing left to do+ std::system(("rm -rf " + dir).c_str());+}+static void testAutoDeband() {using xc::app::debandForMbps;CHECK(debandForMbps(0.3, 1) == -1); // starting or standing still: no measure@@ -318,6 +396,7 @@ static void testAutoDeband() {int main() {testAutoDeband();+ testUpdater();testAccentColor();testVersions();testStreamMenu();diff --git a/tools/release.sh b/tools/release.shindex 16ca534..293fa23 100755--- a/tools/release.sh+++ b/tools/release.sh@@ -9,11 +9,16 @@# CMakeLists.txt and ps5/sce_sys/param.json (contentVersion 0X.YZZ.000, above# the last release's), no tag yet, and no token or private file in the# changes since the last release. Then: PS5 build -> link -> package WITHOUT-# the account -> zip + sha256, and checks inside the zip (no private files,+# the account -> zip + sha256 + signature, and checks inside the zip (no private files,# README.txt and param.json at this version, no token in eboot.bin, the# version compiled in, the licenses). With --console (PS5_HOST set), a cloud# and an own-Xbox stream on the console. Last, it prints the commands that# publish the release and the catalog record.+#+# The in-app updater installs only a zip signed by the project's key:+# PSBOX_SIGNING_KEY (default ~/.config/psbox-release/signing-key.pem, kept+# by the maintainer, never in the repository) signs it, and must be the key+# whose public half src/app/updater.cpp carries.set -euo pipefailroot=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)cd "$root"@@ -29,6 +34,7 @@ for a in "$@"; doesacdoneout=${out:-$root/build-ps5/release-v$version}+key=${PSBOX_SIGNING_KEY:-$HOME/.config/psbox-release/signing-key.pem}tag=v$versionfail() { echo "release: $*" >&2; exit 1; }ok() { echo " ok $*"; }@@ -57,6 +63,12 @@ if [[ -n $last ]]; thenfiif git ls-files | grep -nE "$private"; then fail "private files are tracked"; fiok "no private file tracked"+[[ -r $key ]] || fail "no signing key at $key (PSBOX_SIGNING_KEY)"+pub=$(openssl pkey -in "$key" -pubout 2>/dev/null) || fail "$key is not a private key"+while read -r line; do+ [[ $line == -----* ]] || grep -qF "\"$line\n\"" src/app/updater.cpp || fail "$key is not the key src/app/updater.cpp trusts"+done <<<"$pub"+ok "signing key matches the app's"echo "== build"buildlog=$(mktemp)@@ -70,6 +82,10 @@ env -u XC_INCLUDE_ACCOUNT XC_VERSION="$tag" tools/ps5/package.sh build-ps5 "$out(cd "$out" && zip -qr PPSA99810.zip PPSA99810 && sha256sum PPSA99810.zip > PPSA99810.zip.sha256)sha=$(cut -d' ' -f1 "$out/PPSA99810.zip.sha256")ok "$out/PPSA99810.zip ($(du -h "$out/PPSA99810.zip" | cut -f1)), sha256 $sha"+openssl dgst -sha256 -sign "$key" -out "$out/PPSA99810.zip.sig" "$out/PPSA99810.zip"+openssl dgst -sha256 -verify <(echo "$pub") -signature "$out/PPSA99810.zip.sig" "$out/PPSA99810.zip" >/dev/null ||+ fail "the signature doesn't verify"+ok "signed: $out/PPSA99810.zip.sig"echo "== checks in the package"zip=$out/PPSA99810.zip@@ -100,7 +116,7 @@ if [[ $console == 1 ]]; thenfiecho "== all checks passed; to publish (with release notes in notes.md):"-echo " gh release create $tag \"$zip\" \"$out/PPSA99810.zip.sha256\" --target $(git rev-parse HEAD) --title \"PSBox Cloud Gaming $tag\" --notes-file notes.md"+echo " gh release create $tag \"$zip\" \"$out/PPSA99810.zip.sha256\" \"$out/PPSA99810.zip.sig\" --target $(git rev-parse HEAD) --title \"PSBox Cloud Gaming $tag\" --notes-file notes.md"echo "== catalog record (apps/PPSA99810.json):"echo " \"version\": \"$version\","echo " \"artifact_url\": \"https://github.com/RafaelNGP/xbox-cloud-gaming-ps5/releases/download/$tag/PPSA99810.zip\","