diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a56309dc..ea9a00009 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ What's new in ps5upload, written for humans. ## Unreleased +**Games** +- **Games that vanished from the home screen after Rebuild Database can be put back (#961).** A fake package game still on its drive but no longer on the PS5's home screen now shows **Not on the PS5's home screen** on its page, with **Restore to home screen**; **Restore all** in Games does every such game. The PS5's own installer takes the package back from the drive, so nothing is downloaded. Your database is backed up first, and if the PS5 won't take a game, its files are put back where they were. It needs room for one more copy of the game while it runs. +- **Pressing Play on such a game no longer unsettles the console.** It used to try harder and harder ways to start a game the PS5 no longer knows, which could restart the PS5's menu. It now stops within seconds and points you to Restore. + +**Extract on the console** +- **Password-protected RAR archives can be extracted on the PS5 (#958).** In Files on the console page and in the app's file screen, Extract now asks for the password of a `.rar` the way it does for `.zip` and `.7z`. This covers new and old RAR archives, multi-part sets (pick part 1), and archives whose file list is hidden behind the password. A wrong password is said plainly and leaves no files behind. + +## 12.6.37 + **Activity** - **An upload still going after you closed the page shows as running when you come back (#954).** The upload itself always carried on, but Activity listed it as "Interrupted" next to a second, running copy. It now picks up the same entry. diff --git a/FAQ.md b/FAQ.md index 103de0a34..be432ad5b 100644 --- a/FAQ.md +++ b/FAQ.md @@ -2215,6 +2215,29 @@ whose title ID can't be read) are counted in a line under the grid; **Show them* with the same actions. To dump an installed game to a drive, open it and use **Dump this game** under **On **. +**Q: After Rebuild Database my games installed from fake packages are gone from the home screen. Do I have to download them again?** +No. Rebuild Database (Safe Mode) removes games installed from fake packages from the home screen +and from Settings › Storage, but their files stay on the drive. With the helper running and +fake-package support (kstuff) loaded, open such a game in **Games**: instead of **Play** it says +it is not on the PS5's home screen and offers **Restore to home screen**. When several are +missing, **Games** shows **Restore all** above the grid. + +Restore installs the game again from the package that is already on the PS5, with the PS5's own +installer, the same way as the first install. Nothing is downloaded. What happens, in order: a +copy of the PS5's game database is saved in `/data/ps5upload/backup/restore/`; the package +(`…/user/app//app.pkg`) is moved into a `ps5upload/restore` folder on the same drive; +the PS5 installs it from there, writing a new copy where **Settings › Storage › Installation +Location** says (so that drive needs room for one more copy while it runs); then the moved copy +is deleted. If the install fails, the package is put back where it was. The game's update file +is kept aside during the install and put back afterwards as a file; install the update package +again to update the game. Don't start the game or turn the PS5 off while it runs. + +A game that the PS5 still lists, a retail game, and a game added from a folder are never +touched. Pressing **Play** on a game that is not on the home screen no longer tries to start it: +nothing on the PS5 knows the game until it is restored. If a restore was interrupted (the app or +the PS5 was closed), the game's page says so and offers **Finish** (when the game is back on the +home screen) or **Put back** (when it is not). + **Q: What is the Collection?** It is what the **Games** grid shows of this computer: every game you keep on its drives and saved servers, grouped by game: its full copies, its updates and DLC, the duplicates and the @@ -3401,8 +3424,10 @@ The PS5Upload helper serves it on port 9180. It has seven sections, on the left: - **Files**: browse, copy, move, rename, delete, view, verify and search; set permissions, make and edit text files. **Network shares** adds an SMB share (a PC or NAS) you can browse like a drive and copy to and from. **Extract** unpacks a `.zip`, `.7z`, `.rar` (multi-part too) or - `.tar` on the console into a folder there (password-protected `.zip` and `.7z` work, - password-protected `.rar` does not). Pick a `.pkg` on internal storage or USB to see its icon, + `.tar` on the console into a folder there. Password-protected `.zip`, `.7z` and `.rar` work: it + asks for the password, also when a `.rar` hides its file list behind it. For a multi-part + `.rar`, pick the first part (`.part1.rar`, or the `.rar` of an old `.r00` set) with the others in + the same folder. Pick a `.pkg` on internal storage or USB to see its icon, title, version and type and **Install** it (a USB package is copied to internal storage first, then the copy removed). **Load payload** sends an `.elf` or `.bin` on the console to the payload loader, after a confirm. diff --git a/MCP.md b/MCP.md index 078d7fba5..3c566dba4 100644 --- a/MCP.md +++ b/MCP.md @@ -294,7 +294,8 @@ clients let you allow tools one by one, so keep these on "ask". | `share_cancel` | Stop a share and its transfers | | `api_request` | Anything the API can do | -Some tools aren't marked destructive but still matter: `install_pkg`, `games_launch`, +Some tools aren't marked destructive but still matter: `install_pkg`, `games_launch`, `games_restore`, +`games_restore_finish`, `rp_input`, `rp_start`, `together_invite`, `together_decide`, `settings_set`, `console_settings_set`. diff --git a/Makefile b/Makefile index 5a3219a62..76a2be80c 100644 --- a/Makefile +++ b/Makefile @@ -1381,6 +1381,12 @@ test-payload: payload $(PAYLOAD_DIR)/tests/trophy_fix_selftest.c $(PAYLOAD_DIR)/src/trophy_fix.c $(PAYLOAD_DIR)/src/app_dump_sha256.c @$(RUN_LIMITED) $(SELFTEST_DIR)/ps5upload-trophy-fix-selftest @echo "✓ trophy files: only the exact old account id is replaced (both byte orders, hashes written again), links never followed, a dry run changes nothing, a backup is kept first and puts the file back" + @echo "Running home-screen restore self-test (host build)..." + @cc -O2 -Wall -Wextra -Werror -pthread -I$(PAYLOAD_DIR)/include \ + -o $(SELFTEST_DIR)/ps5upload-title-restore-selftest \ + $(PAYLOAD_DIR)/tests/title_restore_selftest.c $(PAYLOAD_DIR)/src/title_restore.c + @$(RUN_LIMITED) $(SELFTEST_DIR)/ps5upload-title-restore-selftest + @echo "✓ restore: only a package no database knows is moved aside (same drive, databases backed up first); a failed install puts it back into a free place, a finished one deletes only the copy aside" @echo "Running console clean-up rules self-test (host build)..." @cc -O2 -Wall -Wextra -Werror -I$(PAYLOAD_DIR)/include \ -o $(SELFTEST_DIR)/ps5upload-cleanup-rules-selftest \ diff --git a/VERSION b/VERSION index 2cc141768..c82752ae3 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -12.6.36 +12.6.37 diff --git a/client/package-lock.json b/client/package-lock.json index 8c3fa4bf3..2e6cae6a8 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1,12 +1,12 @@ { "name": "ps5upload-client", - "version": "12.6.36", + "version": "12.6.37", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ps5upload-client", - "version": "12.6.36", + "version": "12.6.37", "dependencies": { "@tauri-apps/api": "^2.12.5", "@tauri-apps/plugin-dialog": "^2.8.4", diff --git a/client/package.json b/client/package.json index 9e078fcce..2b5cfbc3b 100644 --- a/client/package.json +++ b/client/package.json @@ -2,7 +2,7 @@ "name": "ps5upload-client", "private": true, "type": "module", - "version": "12.6.36", + "version": "12.6.37", "description": "The all-in-one PS5 companion app.", "homepage": "https://github.com/phantomptr/ps5upload", "author": "PhantomPtr <phantomptr@gmail.com>", diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index 74f8ae4ab..c540be181 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -4743,7 +4743,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.36" +version = "12.6.37" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4752,14 +4752,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.36" +version = "12.6.37" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.36" +version = "12.6.37" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -4768,7 +4768,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.36" +version = "12.6.37" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -4777,7 +4777,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.36" +version = "12.6.37" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -4788,7 +4788,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "crc32fast", @@ -4798,7 +4798,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "ava1", @@ -4817,7 +4817,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.36" +version = "12.6.37" dependencies = [ "blake3", "libc", @@ -4834,7 +4834,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4868,7 +4868,7 @@ dependencies = [ [[package]] name = "ps5upload-desktop" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "ava1", @@ -4910,7 +4910,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.2", "aes-gcm 0.11.0", @@ -4974,7 +4974,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.2", "crc32fast", @@ -4997,7 +4997,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.36" +version = "12.6.37" dependencies = [ "axum", "base64 0.23.1", @@ -5011,7 +5011,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.2", "blake3", @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.36" +version = "12.6.37" dependencies = [ "cc", ] diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 06fa954a7..0a0779862 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ps5upload-desktop" -version = "12.6.36" +version = "12.6.37" description = "The all-in-one PS5 companion app." license = "GPL-3.0-or-later" edition = "2021" diff --git a/client/src-tauri/src/commands/ps5_engine.rs b/client/src-tauri/src/commands/ps5_engine.rs index adfb8daea..b7cffe9f1 100644 --- a/client/src-tauri/src/commands/ps5_engine.rs +++ b/client/src-tauri/src/commands/ps5_engine.rs @@ -1924,6 +1924,63 @@ pub struct AppUnregisterReq { pub registration_only: bool, } +/// Restore to home screen (#961): one command for the engine's `/api/ps5/app/restore*` routes. +/// `op` is `check`, `candidates` or `status` (GET, `addr` and `title_id` in the query), `start` +/// or `finish` (POST, `req` is the body). +#[derive(Debug, Deserialize)] +pub struct AppRestoreReq { + pub addr: String, + #[serde(default)] + pub title_id: Option<String>, + #[serde(default)] + pub title_ids: Option<Vec<String>>, + #[serde(default)] + pub rollback: bool, + #[serde(default)] + pub install_ended: bool, +} + +#[tauri::command] +pub async fn ps5_app_restore(op: String, req: AppRestoreReq) -> Result<JsonValue, String> { + let base = engine::url(); + let query = |path: &str| { + let mut url = format!("{base}{path}?addr={}", urlencoding(&req.addr)); + if let Some(t) = &req.title_id { + url.push_str(&format!("&title_id={}", urlencoding(t))); + } + url + }; + match op.as_str() { + "check" => get_json(&query("/api/ps5/app/restore/check")).await, + "candidates" => get_json(&query("/api/ps5/app/restore/candidates")).await, + "status" => get_json(&query("/api/ps5/app/restore/status")).await, + "start" => { + post_json_long( + &format!("{base}/api/ps5/app/restore"), + &serde_json::json!({ + "addr": req.addr, + "title_id": req.title_id, + "title_ids": req.title_ids, + }), + ) + .await + } + "finish" => { + post_json( + &format!("{base}/api/ps5/app/restore/finish"), + &serde_json::json!({ + "addr": req.addr, + "title_id": req.title_id, + "rollback": req.rollback, + "install_ended": req.install_ended, + }), + ) + .await + } + other => Err(format!("unknown restore step {other:?}")), + } +} + #[tauri::command] pub async fn ps5_app_unregister(req: AppUnregisterReq) -> Result<JsonValue, String> { let base = engine::url(); diff --git a/client/src-tauri/src/lib.rs b/client/src-tauri/src/lib.rs index 1a644f024..7066794ae 100644 --- a/client/src-tauri/src/lib.rs +++ b/client/src-tauri/src/lib.rs @@ -474,6 +474,7 @@ pub fn run() { commands::ps5_app_launch, commands::ps5_app_register, commands::ps5_app_unregister, + commands::ps5_app_restore, commands::fpkg_inspect, commands::game_inspect, commands::game_inspect_image, diff --git a/client/src-tauri/tauri.conf.json b/client/src-tauri/tauri.conf.json index 0905db668..16a725f5f 100644 --- a/client/src-tauri/tauri.conf.json +++ b/client/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PS5Upload", - "version": "12.6.36", + "version": "12.6.37", "identifier": "com.phantomptr.ps5upload", "build": { "beforeDevCommand": "npm run dev:vite", diff --git a/client/src/api/titleRestore.ts b/client/src/api/titleRestore.ts new file mode 100644 index 000000000..881d02aa7 --- /dev/null +++ b/client/src/api/titleRestore.ts @@ -0,0 +1,116 @@ +// Restore to home screen (#961): the engine's /api/ps5/app/restore* routes, through the +// `ps5_app_restore` command (desktop) or the same routes over HTTP (browser build). +// +// A game installed from a package whose home-screen record is gone (Settings › Rebuild Database +// drops games installed from fake packages; their files stay) is put back by installing the +// package that is already on the console again, with the console's own installer. + +import { mgmtAddr } from "../lib/addr"; +import { invoke } from "../lib/invokeLogged"; + +/** The helper's answer (`app.restore`), as the engine passes it on. */ +export interface RestoreReply { + ok: boolean; + err?: string; + title_id: string; + /** check: restorable | registered | record_elsewhere | not_installed | pending | + * folder_registration | ambiguous | retail | no_room | aside_cross_device | db_unreadable | + * invalid_title | system_title. finish: restored | rolled_back | nothing_pending | waiting | + * unsettled. */ + state: string; + reason?: string; + /** internal | m2 | usb | extended */ + where?: string; + volume?: string; + aside?: string; + pkg?: string; + size?: number; + kind?: string; + patch?: string; + patch_size?: number; + free_volume?: number; + free_internal?: number; + install_path?: string; + patch_aside?: string; + backup?: string; + installed?: string; + installed_where?: string; + patch_kept?: string; + kept?: string; +} + +export interface RestoreCandidate { + title_id: string; + title_name: string; + check: RestoreReply; +} + +/** queued | installing | finishing | restored | rolled_back | pending | failed */ +export type RestorePhase = + | "queued" + | "installing" + | "finishing" + | "restored" + | "rolled_back" + | "pending" + | "failed"; + +export interface RestoreRun { + title_id: string; + phase: RestorePhase; + job?: string; + prepared?: RestoreReply; + result?: RestoreReply; + install_verdict?: string; + install_hint?: string; + error?: string; + /** The install job's status while it runs (metrics.served_bytes / total_bytes). */ + install?: { phase?: string; metrics?: { total_bytes?: number; served_bytes?: number } }; +} + +function call<T>( + op: "check" | "candidates" | "status" | "start" | "finish", + host: string, + req: { title_id?: string; title_ids?: string[]; rollback?: boolean; install_ended?: boolean }, +): Promise<T> { + return invoke<T>("ps5_app_restore", { op, req: { addr: mgmtAddr(host), ...req } }); +} + +/** Read-only: can this title be put back on the home screen. Rejects when the helper is too old + * (`restore_unsupported`) or the console could not answer. */ +export function restoreCheck(host: string, titleId: string): Promise<RestoreReply> { + return call<RestoreReply>("check", host, { title_id: titleId }); +} + +/** Every game the console has the package of but no home-screen record for. Read-only. */ +export async function restoreCandidates(host: string): Promise<RestoreCandidate[]> { + const r = await call<{ titles?: RestoreCandidate[] }>("candidates", host, {}); + return r.titles ?? []; +} + +/** Start restoring one or more titles (one install after the other). */ +export function restoreStart( + host: string, + titleIds: string[], +): Promise<{ ok: boolean; job: string; prepared: RestoreReply; queued: string[] }> { + return call("start", host, { title_ids: titleIds }); +} + +/** How this engine's restore of a title stands. Rejects (404) when it ran none. */ +export function restoreStatus(host: string, titleId: string): Promise<RestoreRun> { + return call<RestoreRun>("status", host, { title_id: titleId }); +} + +/** Finish a restore left pending: `installEnded` deletes the copy aside once the game is on the + * home screen; `rollback` puts the package back where it was. */ +export function restoreFinish( + host: string, + titleId: string, + opts: { rollback?: boolean; installEnded?: boolean }, +): Promise<RestoreReply> { + return call<RestoreReply>("finish", host, { + title_id: titleId, + rollback: opts.rollback === true, + install_ended: opts.installEnded === true, + }); +} diff --git a/client/src/i18n/locales/en.ts b/client/src/i18n/locales/en.ts index 433ee0468..4216eeae2 100644 --- a/client/src/i18n/locales/en.ts +++ b/client/src/i18n/locales/en.ts @@ -9794,6 +9794,57 @@ two_panes_move_files_only: "Move takes files only here: the app can't check ever two_panes_moved: "Moved {count} items to {place}", two_panes_unverified: "Copied, but the original was kept: the copy could not be checked", two_panes_not_removed: "Copied, but the original could not be deleted", +err_launch_not_in_database: "This game is not on the PS5's home screen, so it can't be started. Rebuild Database removes games installed from fake packages but leaves their files: open the game's page and choose Restore to home screen.", +restore_action: "Restore to home screen", +restore_all_action: "Restore all", +restore_all_body: "The PS5 installs each game again from the package already on its drive, one after the other ({size} in all), so they come back on the home screen. Nothing is downloaded. Each package is moved aside on its own drive while it installs, a copy of the PS5's game database is saved first, and a package whose install fails is put back where it was. The drive set under Settings › Storage › Installation Location needs room for one game at a time. Fake-package support (kstuff) must be loaded. Don't start these games or turn the PS5 off until it is done.", +restore_all_found: "{count} games are installed on this PS5 but are not on its home screen (Rebuild Database removes games installed from fake packages but leaves their files). They can be put back without downloading them again.", +restore_all_running: "Games are being restored to the home screen of {console}, one after the other. Each game's page shows how far it is.", +restore_all_title: "Restore {count} games to the home screen?", +restore_already: "{name} is on the home screen already.", +restore_backup_failed: "The PS5's game database could not be copied first, so nothing was changed.", +restore_busy: "The PS5 is installing something else. Try again when that install has finished.", +restore_confirm_body: "The PS5 installs {name} again from the package already on {where} ({size}), the same way as the first install, so it comes back on the home screen and in Settings › Storage. Nothing is downloaded.", +restore_confirm_kstuff: "Fake-package support (kstuff) must be loaded, as for any fake-package install. Don't start the game or turn the PS5 off until it is done.", +restore_confirm_patch: "Its update ({patch_size}) is kept aside during the install and put back afterwards as a file; to update the game again, install the update package.", +restore_confirm_steps: "First a copy of the PS5's game database is saved. Then the package is moved into a PS5Upload folder on the same drive, and the PS5 writes a new copy where Settings › Storage › Installation Location says, so that drive needs {size} free. When the game is back, the moved copy is deleted. If the install fails, the package is put back where it was.", +restore_confirm_title: "Restore {name} to the home screen?", +restore_done: "{name} is back on the home screen.", +restore_done_patch_kept: "{name} is back on the home screen. Its update file could not go back to its place and is kept in {path}.", +restore_finish: "Finish", +restore_finish_body: "When the game shows on the PS5's home screen and its install has finished, the copy PS5Upload moved aside is deleted. If the PS5 does not list the game yet, nothing is deleted.", +restore_finish_title: "Is {name} back on the home screen?", +restore_finishing: "The PS5 has installed {name}; checking that it is back on the home screen.", +restore_home_only: "Restoring a game needs this device on the same network as the PS5.", +restore_install_failed: "the PS5 did not install it.", +restore_installing: "The PS5 is installing {name} again from its package. Don't start the game or turn the PS5 off until it is done.", +restore_installing_progress: "The PS5 is installing {name} again from its package: {done} of {total}. Don't start the game or turn the PS5 off until it is done.", +restore_missing_title: "{name} is not on the PS5's home screen", +restore_move_failed: "The package could not be moved aside on its drive, so nothing was changed.", +restore_not_applicable: "{name} can't be restored this way: the PS5 still knows it, or it was not installed from a package. Nothing was changed.", +restore_not_yet: "{name} is not on the home screen yet, so nothing was deleted. Wait for the PS5 to finish, or put the package back.", +restore_nothing_pending: "There was nothing left to finish for {name}.", +restore_pending: "{name}: the restore has not finished. The package is kept on the PS5. Check its home screen, then open the game's page to finish.", +restore_pending_title: "The restore of {name} did not finish", +restore_play_blocked: "Not on the PS5's home screen: restore it first (below)", +restore_put_back: "{name}'s package is back where it was.", +restore_queued: "{name} is waiting for the restore before it.", +restore_rollback: "Put back", +restore_rollback_body: "The package goes back to where it was before the restore, and the game stays off the home screen. Only do this when the PS5 shows no download or install of this game in progress.", +restore_rollback_title: "Put {name}'s package back?", +restore_rolled_back: "{name} could not be restored: {why} Its package is back where it was; nothing else changed.", +restore_running_title: "Restoring {name} to the home screen", +restore_state_ambiguous: "{name} has an installed package on two drives, so PS5Upload can't tell which one to use. Nothing was changed.", +restore_state_cross_device: "{name} is not on the PS5's home screen. PS5Upload could not move its package aside on its own drive, so it can't restore it. Nothing was changed.", +restore_state_no_room: "{name} is not on the PS5's home screen. Restoring it needs {size} free while the PS5 writes a new copy, on {where} or on the console's storage. Free up space, then open this page again.", +restore_state_pending: "A restore of {name} did not finish. Its package is kept in {aside}. If the game is back on the PS5's home screen, choose Finish; if not, Put back returns the package to where it was.", +restore_state_restorable: "{name} is installed on {where} but is not on the PS5's home screen, so it can't be started. This happens after Rebuild Database, which removes games installed from fake packages but leaves their files. Restore installs it again from the package already on the PS5: nothing is downloaded.", +restore_state_retail: "{name} is not on the PS5's home screen, and its package is not a fake package, so PS5Upload leaves it alone. Delete it in Settings › Storage and download it again from the Game Library.", +restore_unsupported: "The PS5's helper is an older version that can't restore games. Send the helper again, then try once more.", +restore_where_extended: "extended storage", +restore_where_internal: "the console's storage", +restore_where_m2: "the M.2 drive", +restore_where_usb: "USB extended storage", }; export default en; diff --git a/client/src/lib/browserInvoke.test.ts b/client/src/lib/browserInvoke.test.ts index 14853bbc7..88732bdd5 100644 --- a/client/src/lib/browserInvoke.test.ts +++ b/client/src/lib/browserInvoke.test.ts @@ -155,6 +155,38 @@ describe("loader-port commands the DPI fallback depends on", () => { expect(res).toEqual({ ok: true, job: "17-1" }); }); + it("sends each Restore to home screen step to its engine route, as the desktop command does (#961)", async () => { + const calls = captureFetch({ ok: true }); + const req = { addr: "192.168.1.50", title_id: "PPSA01234" }; + await browserInvoke("ps5_app_restore", { op: "check", req }); + await browserInvoke("ps5_app_restore", { op: "status", req }); + await browserInvoke("ps5_app_restore", { op: "candidates", req: { addr: "192.168.1.50" } }); + await browserInvoke("ps5_app_restore", { + op: "start", + req: { addr: "192.168.1.50", title_ids: ["PPSA01234", "CUSA00900"] }, + }); + await browserInvoke("ps5_app_restore", { op: "finish", req: { ...req, rollback: true } }); + expect(calls.map((c) => c.url)).toEqual([ + "http://engine.test:19113/api/ps5/app/restore/check?addr=192.168.1.50&title_id=PPSA01234", + "http://engine.test:19113/api/ps5/app/restore/status?addr=192.168.1.50&title_id=PPSA01234", + "http://engine.test:19113/api/ps5/app/restore/candidates?addr=192.168.1.50", + "http://engine.test:19113/api/ps5/app/restore", + "http://engine.test:19113/api/ps5/app/restore/finish", + ]); + expect(JSON.parse(calls[3].init.body as string)).toEqual({ + addr: "192.168.1.50", + title_id: null, + title_ids: ["PPSA01234", "CUSA00900"], + }); + expect(JSON.parse(calls[4].init.body as string)).toEqual({ + addr: "192.168.1.50", + title_id: "PPSA01234", + rollback: true, + install_ended: false, + }); + await expect(browserInvoke("ps5_app_restore", { op: "nope", req })).rejects.toThrow("unknown restore step"); + }); + it("passes registration_only on to the engine's unregister, as the desktop app does", async () => { const calls = captureFetch({ ok: true }); await browserInvoke("ps5_app_unregister", { diff --git a/client/src/lib/browserInvoke.ts b/client/src/lib/browserInvoke.ts index dc32aa118..e14f2cf71 100644 --- a/client/src/lib/browserInvoke.ts +++ b/client/src/lib/browserInvoke.ts @@ -550,6 +550,42 @@ export async function browserInvoke<T>( ); } + // Restore to home screen (#961): the same routes the desktop command calls. + case "ps5_app_restore": { + const op = args["op"] as string; + const req = args["req"] as { + addr: string; + title_id?: string | null; + title_ids?: string[] | null; + rollback?: boolean; + install_ended?: boolean; + }; + const q = `?addr=${uenc(req.addr)}${req.title_id ? `&title_id=${uenc(req.title_id)}` : ""}`; + switch (op) { + case "check": + return getJson<T>(`/api/ps5/app/restore/check${q}`); + case "candidates": + return getJson<T>(`/api/ps5/app/restore/candidates${q}`); + case "status": + return getJson<T>(`/api/ps5/app/restore/status${q}`); + case "start": + return postJson<T>( + "/api/ps5/app/restore", + { addr: req.addr, title_id: req.title_id ?? null, title_ids: req.title_ids ?? null }, + /*long=*/ true, + ); + case "finish": + return postJson<T>("/api/ps5/app/restore/finish", { + addr: req.addr, + title_id: req.title_id, + rollback: req.rollback === true, + install_ended: req.install_ended === true, + }); + default: + throw new Error(`unknown restore step ${op}`); + } + } + case "ps5_app_unregister": { // registration_only as the desktop command forwards it: without it the engine runs a // full uninstall, and a console-installed game sharing the title id is not protected. diff --git a/client/src/lib/humanizeError.ts b/client/src/lib/humanizeError.ts index 389d93e41..19e01c4ba 100644 --- a/client/src/lib/humanizeError.ts +++ b/client/src/lib/humanizeError.ts @@ -367,6 +367,13 @@ export function humanizePs5Error( return te("err_launch_no_user"); } + // #961: the console's database has no record of the title (Rebuild Database drops games + // installed from fake packages, their files stay). The helper stops there instead of trying the + // other launch routes; the game's page offers Restore to home screen. + if (/launch_not_in_database/i.test(raw)) { + return te("err_launch_not_in_database"); + } + // ─── Sony launcher error codes (after 2.2.32 auto-retry) ────────── // launch_title surfaces sceLncUtilLaunchApp's return value as // `launch_sony_error_0xNNNNNNNN`. The codes below are the ones we diff --git a/client/src/lib/installErrorDoc.ts b/client/src/lib/installErrorDoc.ts index 6078218dc..746731108 100644 --- a/client/src/lib/installErrorDoc.ts +++ b/client/src/lib/installErrorDoc.ts @@ -26,9 +26,11 @@ export const DOC_ANCHORS = { wontLaunch: "won't launch", matrix: "support matrix", declined1104: "0x80B21104", + restoreHomeScreen: "Restore to home screen", } as const; const RULES: Array<[RegExp, string]> = [ + [/launch_not_in_database/i, DOC_ANCHORS.restoreHomeScreen], [/0x80b21104/i, DOC_ANCHORS.declined1104], [/0x80b2116f|0x80b2150f|staged route|refused this package from its own storage/i, DOC_ANCHORS.stagedRefused], [/0x80431084|proxy server|proxy setting/i, DOC_ANCHORS.proxy], diff --git a/client/src/lib/titleRestore.test.ts b/client/src/lib/titleRestore.test.ts new file mode 100644 index 000000000..9bad60ec0 --- /dev/null +++ b/client/src/lib/titleRestore.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest"; + +import type { RestoreReply } from "../api/titleRestore"; +import { humanizePs5Error } from "./humanizeError"; +import { installErrorDoc, DOC_ANCHORS } from "./installErrorDoc"; +import { + restoreConfirmText, + restoreEnded, + restoreErrorText, + restoreNeeded, + restoreOutcome, + restoreStateText, +} from "./titleRestore"; + +const reply = (state: string, extra: Partial<RestoreReply> = {}): RestoreReply => ({ + ok: true, + title_id: "PPSA01234", + state, + ...extra, +}); + +describe("Restore to home screen (#961)", () => { + it("replaces Play only for a game on a drive that the home screen does not list", () => { + for (const s of ["restorable", "pending", "no_room", "retail", "aside_cross_device", "ambiguous"]) { + expect(restoreNeeded(reply(s)), s).toBe(true); + } + for (const s of ["registered", "not_installed", "record_elsewhere", "folder_registration", "db_unreadable", "system_title"]) { + expect(restoreNeeded(reply(s)), s).toBe(false); + } + expect(restoreNeeded(null)).toBe(false); + // A refusal from prepare is not a check answer. + expect(restoreNeeded({ ...reply("restorable"), ok: false })).toBe(false); + }); + + it("names where the game is and why it can or can't come back", () => { + expect(restoreStateText(reply("restorable", { where: "m2" }), "Astro")).toContain("the M.2 drive"); + expect(restoreStateText(reply("restorable", { where: "m2" }), "Astro")).toContain("nothing is downloaded"); + expect(restoreStateText(reply("pending", { aside: "/mnt/ext1/ps5upload/restore/PPSA01234" }), "Astro")).toContain( + "/mnt/ext1/ps5upload/restore/PPSA01234", + ); + expect(restoreStateText(reply("no_room", { size: 2 * 1024 ** 3 }), "Astro")).toContain("2"); + expect(restoreStateText(reply("retail"), "Astro")).toContain("download it again"); + expect(restoreStateText(reply("registered"), "Astro")).toBeNull(); + expect(restoreStateText(null, "Astro")).toBeNull(); + }); + + it("says what a restore does before it starts, the update included", () => { + const text = restoreConfirmText(reply("restorable", { where: "usb", size: 1024 ** 3 }), "Astro"); + expect(text).toContain("USB extended storage"); + expect(text).toContain("Nothing is downloaded"); + expect(text).toContain("put back where it was"); + expect(text).not.toContain("update ("); + const withPatch = restoreConfirmText( + reply("restorable", { where: "m2", size: 10, patch: "/mnt/ext1/user/patch/PPSA01234/patch.pkg", patch_size: 5 }), + "Astro", + ); + expect(withPatch).toContain("Its update"); + }); + + it("tells each ending apart", () => { + expect(restoreEnded("installing")).toBe(false); + expect(restoreEnded("queued")).toBe(false); + expect(restoreEnded("finishing")).toBe(false); + for (const p of ["restored", "rolled_back", "pending", "failed"]) expect(restoreEnded(p)).toBe(true); + + expect(restoreOutcome({ phase: "restored" }, "Astro")).toEqual({ + level: "success", + body: "Astro is back on the home screen.", + }); + const kept = restoreOutcome( + { phase: "restored", result: reply("restored", { patch_kept: "/x/patch.pkg" }) }, + "Astro", + ); + expect(kept.body).toContain("/x/patch.pkg"); + const back = restoreOutcome({ phase: "rolled_back", install_hint: "the PS5 refused it (0x80B2116F)." }, "Astro"); + expect(back.level).toBe("error"); + expect(back.body).toContain("0x80B2116F"); + expect(back.body).toContain("back where it was"); + expect(restoreOutcome({ phase: "pending" }, "Astro").level).toBe("info"); + expect(restoreOutcome({ phase: "failed", error: "restore_unsupported: old" }, "Astro").body).toContain( + "older version", + ); + }); + + it("words the engine's refusals", () => { + expect(restoreErrorText("busy", "Astro")).toContain("installing something else"); + expect(restoreErrorText("restore_registered", "Astro")).toContain("on the home screen already"); + expect(restoreErrorText("restore_backup_failed", "Astro")).toContain("nothing was changed"); + expect(restoreErrorText("restore_move_failed", "Astro")).toContain("nothing was changed"); + expect(restoreErrorText("something else", "Astro")).toBe("something else"); + }); + + it("turns the helper's refused launch into the way out, with its FAQ entry", () => { + const raw = "payload rejected APP_LAUNCH: launch_not_in_database: rc=0x80940005"; + expect(humanizePs5Error(raw)).toContain("Restore to home screen"); + expect(installErrorDoc(raw)).toEqual({ query: DOC_ANCHORS.restoreHomeScreen }); + }); +}); diff --git a/client/src/lib/titleRestore.ts b/client/src/lib/titleRestore.ts new file mode 100644 index 000000000..0bbe5c916 --- /dev/null +++ b/client/src/lib/titleRestore.ts @@ -0,0 +1,215 @@ +// Restore to home screen (#961): the words and decisions around the helper's answers. Pure +// functions (no React), so they are tested on their own. +// +// After Settings › Rebuild Database, games installed from fake packages are gone from the PS5's +// home screen and from Settings › Storage, but their files stay on the drive. Pressing Play on one +// cannot work (nothing on the console knows the title), so the game's page offers Restore instead: +// the package already on the console is installed again by the PS5's own installer. + +import type { RestoreReply, RestoreRun } from "../api/titleRestore"; +import { formatBytes } from "./format"; +import { trStatic } from "./trStatic"; + +/** Check states that mean "installed on a drive, but not on the home screen": Play is replaced by + * Restore (or by why it can't be restored). */ +const MISSING_STATES = new Set([ + "restorable", + "pending", + "no_room", + "retail", + "aside_cross_device", + "ambiguous", +]); + +/** Whether the check says this game is on a drive but not on the home screen. */ +export function restoreNeeded(reply: RestoreReply | null | undefined): boolean { + return !!reply && reply.ok && MISSING_STATES.has(reply.state); +} + +/** Whether a restore phase has ended (nothing more will change without the user). */ +export function restoreEnded(phase: string | undefined): boolean { + return phase === "restored" || phase === "rolled_back" || phase === "pending" || phase === "failed"; +} + +export function restoreWhereLabel(where: string | undefined): string { + switch (where) { + case "internal": + return trStatic("restore_where_internal", "the console's storage"); + case "m2": + return trStatic("restore_where_m2", "the M.2 drive"); + case "usb": + return trStatic("restore_where_usb", "USB extended storage"); + default: + return trStatic("restore_where_extended", "extended storage"); + } +} + +function size(n: number | undefined): string { + return typeof n === "number" && n > 0 ? formatBytes(n) : "?"; +} + +/** One sentence for the game page: what the check found, or null when there is nothing to say + * (the game is on the home screen, not installed, or the console could not tell). */ +export function restoreStateText(reply: RestoreReply | null | undefined, name: string): string | null { + if (!reply || !reply.ok) return null; + const where = restoreWhereLabel(reply.where); + switch (reply.state) { + case "restorable": + return trStatic( + "restore_state_restorable", + "{name} is installed on {where} but is not on the PS5's home screen, so it can't be started. This happens after Rebuild Database, which removes games installed from fake packages but leaves their files. Restore installs it again from the package already on the PS5: nothing is downloaded.", + { name, where }, + ); + case "pending": + return trStatic( + "restore_state_pending", + "A restore of {name} did not finish. Its package is kept in {aside}. If the game is back on the PS5's home screen, choose Finish; if not, Put back returns the package to where it was.", + { name, aside: reply.aside ?? "" }, + ); + case "no_room": + return trStatic( + "restore_state_no_room", + "{name} is not on the PS5's home screen. Restoring it needs {size} free while the PS5 writes a new copy, on {where} or on the console's storage. Free up space, then open this page again.", + { name, where, size: size(reply.size) }, + ); + case "retail": + return trStatic( + "restore_state_retail", + "{name} is not on the PS5's home screen, and its package is not a fake package, so PS5Upload leaves it alone. Delete it in Settings › Storage and download it again from the Game Library.", + { name }, + ); + case "aside_cross_device": + return trStatic( + "restore_state_cross_device", + "{name} is not on the PS5's home screen. PS5Upload could not move its package aside on its own drive, so it can't restore it. Nothing was changed.", + { name }, + ); + case "ambiguous": + return trStatic( + "restore_state_ambiguous", + "{name} has an installed package on two drives, so PS5Upload can't tell which one to use. Nothing was changed.", + { name }, + ); + default: + return null; + } +} + +/** The confirmation before a restore: what will happen, in order. */ +export function restoreConfirmText(reply: RestoreReply, name: string): string { + const where = restoreWhereLabel(reply.where); + const parts = [ + trStatic( + "restore_confirm_body", + "The PS5 installs {name} again from the package already on {where} ({size}), the same way as the first install, so it comes back on the home screen and in Settings › Storage. Nothing is downloaded.", + { name, where, size: size(reply.size) }, + ), + trStatic( + "restore_confirm_steps", + "First a copy of the PS5's game database is saved. Then the package is moved into a PS5Upload folder on the same drive, and the PS5 writes a new copy where Settings › Storage › Installation Location says, so that drive needs {size} free. When the game is back, the moved copy is deleted. If the install fails, the package is put back where it was.", + { size: size(reply.size) }, + ), + trStatic( + "restore_confirm_kstuff", + "Fake-package support (kstuff) must be loaded, as for any fake-package install. Don't start the game or turn the PS5 off until it is done.", + ), + ]; + if (reply.patch) { + parts.push( + trStatic( + "restore_confirm_patch", + "Its update ({patch_size}) is kept aside during the install and put back afterwards as a file; to update the game again, install the update package.", + { patch_size: size(reply.patch_size) }, + ), + ); + } + return parts.join("\n\n"); +} + +/** What a finished restore says: the notification's level and words. */ +export function restoreOutcome( + run: Pick<RestoreRun, "phase" | "result" | "error" | "install_hint">, + name: string, +): { level: "success" | "info" | "error"; body: string } { + switch (run.phase) { + case "restored": + return { + level: "success", + body: run.result?.patch_kept + ? trStatic( + "restore_done_patch_kept", + "{name} is back on the home screen. Its update file could not go back to its place and is kept in {path}.", + { name, path: run.result.patch_kept }, + ) + : trStatic("restore_done", "{name} is back on the home screen.", { name }), + }; + case "rolled_back": + return { + level: "error", + body: trStatic( + "restore_rolled_back", + "{name} could not be restored: {why} Its package is back where it was; nothing else changed.", + { name, why: run.install_hint?.trim() || trStatic("restore_install_failed", "the PS5 did not install it.") }, + ), + }; + case "pending": + return { + level: "info", + body: trStatic( + "restore_pending", + "{name}: the restore has not finished. The package is kept on the PS5. Check its home screen, then open the game's page to finish.", + { name }, + ), + }; + default: + return { + level: "error", + body: restoreErrorText(run.error ?? run.result?.err ?? "", name), + }; + } +} + +/** A failed start or finish in words. Unknown text passes through. */ +export function restoreErrorText(raw: string, name: string): string { + if (/restore_unsupported/i.test(raw)) { + return trStatic( + "restore_unsupported", + "The PS5's helper is an older version that can't restore games. Send the helper again, then try once more.", + ); + } + if (/\bbusy\b/i.test(raw)) { + return trStatic( + "restore_busy", + "The PS5 is installing something else. Try again when that install has finished.", + ); + } + if (/tailnet_home_only/i.test(raw)) { + return trStatic( + "restore_home_only", + "Restoring a game needs this device on the same network as the PS5.", + ); + } + if (/restore_backup_failed/i.test(raw)) { + return trStatic( + "restore_backup_failed", + "The PS5's game database could not be copied first, so nothing was changed.", + ); + } + if (/restore_move_failed|restore_aside_busy/i.test(raw)) { + return trStatic( + "restore_move_failed", + "The package could not be moved aside on its drive, so nothing was changed.", + ); + } + if (/restore_registered/i.test(raw)) { + return trStatic("restore_already", "{name} is on the home screen already.", { name }); + } + if (/restore_(record_elsewhere|db_unreadable|not_installed|folder_registration)/i.test(raw)) { + return trStatic( + "restore_not_applicable", + "{name} can't be restored this way: the PS5 still knows it, or it was not installed from a package. Nothing was changed.", + { name }, + ); + } + return raw; +} diff --git a/client/src/screens/Collection/RestoreAllBanner.tsx b/client/src/screens/Collection/RestoreAllBanner.tsx new file mode 100644 index 000000000..2869b2e2c --- /dev/null +++ b/client/src/screens/Collection/RestoreAllBanner.tsx @@ -0,0 +1,109 @@ +import { useEffect, useState } from "react"; +import { RotateCcw } from "lucide-react"; + +import { restoreCandidates, type RestoreCandidate } from "../../api/titleRestore"; +import { Button } from "../../components"; +import { useConfirm } from "../../components/ConfirmDialog"; +import { hostOf } from "../../lib/addr"; +import { formatBytes } from "../../lib/format"; +import { useTr } from "../../state/lang"; +import { pushNotification } from "../../state/notifications"; +import { withConsolePrefix } from "../../state/roster"; +import { useRestoreBusy, useTitleRestoreStore } from "../../state/titleRestore"; + +/** + * Restore to home screen for every game at once (#961): the games the connected PS5 has installed + * on a drive but no longer lists (Rebuild Database drops games installed from fake packages). Read + * once per console with the helper's read-only checks; nothing shows when there are none, when the + * console could not answer, or when its helper is too old. + */ +export function RestoreAllBanner({ host, helperUp }: { host: string; helperUp: boolean }) { + const tr = useTr(); + const { confirm, dialog } = useConfirm(); + const start = useTitleRestoreStore((s) => s.start); + const busy = useRestoreBusy(host); + const [found, setFound] = useState<RestoreCandidate[]>([]); + const [starting, setStarting] = useState(false); + + useEffect(() => { + let cancelled = false; + setFound([]); + if (!helperUp || !host.trim() || busy) return; + restoreCandidates(host) + .then((list) => { + if (!cancelled) setFound(list.filter((c) => c.check.state === "restorable")); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [host, helperUp, busy]); + + if (found.length === 0 && !busy) return null; + + const onRestoreAll = async () => { + const total = found.reduce((n, c) => n + (c.check.size ?? 0), 0); + const ok = await confirm({ + title: tr( + "restore_all_title", + { count: found.length }, + "Restore {count} games to the home screen?", + ), + message: tr( + "restore_all_body", + { size: formatBytes(total) }, + "The PS5 installs each game again from the package already on its drive, one after the other ({size} in all), so they come back on the home screen. Nothing is downloaded. Each package is moved aside on its own drive while it installs, a copy of the PS5's game database is saved first, and a package whose install fails is put back where it was. The drive set under Settings › Storage › Installation Location needs room for one game at a time. Fake-package support (kstuff) must be loaded. Don't start these games or turn the PS5 off until it is done.", + ), + details: found.map( + (c) => `${c.title_name} (${c.title_id}) — ${formatBytes(c.check.size ?? 0)}`, + ), + confirmLabel: tr("restore_all_action", undefined, "Restore all"), + }); + if (!ok) return; + setStarting(true); + try { + await start( + host, + found.map((c) => ({ titleId: c.title_id, name: c.title_name })), + ); + } catch (e) { + pushNotification("error", withConsolePrefix(host, tr("restore_all_action", undefined, "Restore all")), { + body: e instanceof Error ? e.message : String(e), + }); + } finally { + setStarting(false); + } + }; + + return ( + <div + className="mb-4 flex flex-wrap items-center gap-3 rounded-2xl border border-[var(--color-warn)]/30 bg-[var(--color-warn)]/10 px-3 py-2 text-xs" + data-testid="restore-all-banner" + > + {dialog} + <span className="min-w-0 flex-1"> + {busy + ? tr( + "restore_all_running", + { console: hostOf(host) }, + "Games are being restored to the home screen of {console}, one after the other. Each game's page shows how far it is.", + ) + : tr( + "restore_all_found", + { count: found.length }, + "{count} games are installed on this PS5 but are not on its home screen (Rebuild Database removes games installed from fake packages but leaves their files). They can be put back without downloading them again.", + )} + </span> + {!busy && ( + <Button + size="sm" + leftIcon={<RotateCcw size={13} />} + loading={starting} + onClick={() => void onRestoreAll()} + > + {tr("restore_all_action", undefined, "Restore all")} + </Button> + )} + </div> + ); +} diff --git a/client/src/screens/Collection/index.tsx b/client/src/screens/Collection/index.tsx index 43bff533f..6de540f0a 100644 --- a/client/src/screens/Collection/index.tsx +++ b/client/src/screens/Collection/index.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { RestoreAllBanner } from "./RestoreAllBanner"; import { CheckSquare, FolderPlus, @@ -681,6 +682,8 @@ export default function CollectionScreen({ embedded = false }: { embedded?: bool return ( <div className={pageClass}> {header} + {/* #961: games on the PS5's drives that its home screen lost (Rebuild Database). */} + <RestoreAllBanner host={host} helperUp={helperUp} /> {s.error && ( <div className="mb-4"> <ErrorCard diff --git a/client/src/screens/GameHub/RestoreHomeScreen.tsx b/client/src/screens/GameHub/RestoreHomeScreen.tsx new file mode 100644 index 000000000..a407a27fc --- /dev/null +++ b/client/src/screens/GameHub/RestoreHomeScreen.tsx @@ -0,0 +1,222 @@ +import { useCallback, useEffect, useState } from "react"; +import { RotateCcw, Undo2, CheckCircle2 } from "lucide-react"; + +import { restoreCheck, restoreFinish, type RestoreReply } from "../../api/titleRestore"; +import { Button, WarningCard } from "../../components"; +import { useConfirm } from "../../components/ConfirmDialog"; +import { formatBytes } from "../../lib/format"; +import { + restoreConfirmText, + restoreEnded, + restoreErrorText, + restoreNeeded, + restoreStateText, +} from "../../lib/titleRestore"; +import { useTr } from "../../state/lang"; +import { pushNotification } from "../../state/notifications"; +import { withConsolePrefix } from "../../state/roster"; +import { useRestoreRun, useTitleRestoreStore } from "../../state/titleRestore"; + +/** + * Restore to home screen (#961): what the console says about a game that is installed on one of + * its drives but missing from its home screen (Rebuild Database drops games installed from fake + * packages), read with the helper's read-only check. The page's Play is replaced by this. + * + * `null` while unknown, or when the console could not answer or its helper is too old: then + * nothing is shown and Play stays as it was (the helper refuses a launch of a title its database + * does not know, so Play cannot unsettle the console either way). + */ +export function useRestoreCheck( + host: string, + titleId: string | undefined, +): { reply: RestoreReply | null; refresh: () => void } { + const [reply, setReply] = useState<RestoreReply | null>(null); + const [tick, setTick] = useState(0); + const run = useRestoreRun(host, titleId ?? ""); + const phase = run?.phase; + useEffect(() => { + let cancelled = false; + setReply(null); + if (!host.trim() || !titleId || !/^[A-Za-z]{4}\d{5}$/.test(titleId)) return; + restoreCheck(host, titleId) + .then((r) => { + if (!cancelled) setReply(r); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + // A finished restore changes the answer: read it again then. + }, [host, titleId, tick, phase]); + const refresh = useCallback(() => setTick((n) => n + 1), []); + return { reply, refresh }; +} + +export function RestoreHomeScreenCard({ + host, + titleId, + name, + reply, + onChanged, +}: { + host: string; + titleId: string; + name: string; + reply: RestoreReply | null; + onChanged: () => void; +}) { + const tr = useTr(); + const { confirm, dialog } = useConfirm(); + const start = useTitleRestoreStore((s) => s.start); + const run = useRestoreRun(host, titleId); + const [busy, setBusy] = useState<"start" | "finish" | "rollback" | null>(null); + + const running = !!run && !restoreEnded(run.phase); + if (!running && !restoreNeeded(reply)) return null; + + const onRestore = async () => { + if (!reply) return; + const ok = await confirm({ + title: tr("restore_confirm_title", { name }, "Restore {name} to the home screen?"), + message: restoreConfirmText(reply, name), + confirmLabel: tr("restore_action", undefined, "Restore to home screen"), + }); + if (!ok) return; + setBusy("start"); + try { + await start(host, [{ titleId, name }]); + } catch (e) { + pushNotification("error", withConsolePrefix(host, name), { + body: e instanceof Error ? e.message : String(e), + }); + } finally { + setBusy(null); + } + }; + + const onFinish = async (rollback: boolean) => { + const ok = await confirm( + rollback + ? { + title: tr("restore_rollback_title", { name }, "Put {name}'s package back?"), + message: tr( + "restore_rollback_body", + undefined, + "The package goes back to where it was before the restore, and the game stays off the home screen. Only do this when the PS5 shows no download or install of this game in progress.", + ), + confirmLabel: tr("restore_rollback", undefined, "Put back"), + } + : { + title: tr("restore_finish_title", { name }, "Is {name} back on the home screen?"), + message: tr( + "restore_finish_body", + undefined, + "When the game shows on the PS5's home screen and its install has finished, the copy PS5Upload moved aside is deleted. If the PS5 does not list the game yet, nothing is deleted.", + ), + confirmLabel: tr("restore_finish", undefined, "Finish"), + }, + ); + if (!ok) return; + setBusy(rollback ? "rollback" : "finish"); + try { + const r = await restoreFinish(host, titleId, rollback ? { rollback: true } : { installEnded: true }); + const body = + r.state === "restored" + ? tr("restore_done", { name }, "{name} is back on the home screen.") + : r.state === "rolled_back" + ? tr("restore_put_back", { name }, "{name}'s package is back where it was.") + : r.state === "nothing_pending" + ? tr("restore_nothing_pending", { name }, "There was nothing left to finish for {name}.") + : tr( + "restore_not_yet", + { name }, + "{name} is not on the home screen yet, so nothing was deleted. Wait for the PS5 to finish, or put the package back.", + ); + pushNotification(r.state === "restored" || r.state === "rolled_back" ? "success" : "info", withConsolePrefix(host, name), { + body, + }); + onChanged(); + } catch (e) { + pushNotification("error", withConsolePrefix(host, name), { + body: restoreErrorText(e instanceof Error ? e.message : String(e), name), + }); + } finally { + setBusy(null); + } + }; + + let detail: string | null; + if (running) { + const m = run?.install?.metrics; + const done = m?.total_bytes ? Math.min(m.served_bytes ?? 0, m.total_bytes) : 0; + detail = + run?.phase === "queued" + ? tr("restore_queued", { name }, "{name} is waiting for the restore before it.") + : run?.phase === "finishing" + ? tr("restore_finishing", { name }, "The PS5 has installed {name}; checking that it is back on the home screen.") + : m?.total_bytes + ? tr( + "restore_installing_progress", + { name, done: formatBytes(done), total: formatBytes(m.total_bytes) }, + "The PS5 is installing {name} again from its package: {done} of {total}. Don't start the game or turn the PS5 off until it is done.", + ) + : tr( + "restore_installing", + { name }, + "The PS5 is installing {name} again from its package. Don't start the game or turn the PS5 off until it is done.", + ); + } else { + detail = restoreStateText(reply, name); + } + const state = reply?.state; + return ( + <div className="mb-3" data-testid="restore-home-screen"> + {dialog} + <WarningCard + title={ + running + ? tr("restore_running_title", { name }, "Restoring {name} to the home screen") + : state === "pending" + ? tr("restore_pending_title", { name }, "The restore of {name} did not finish") + : tr("restore_missing_title", { name }, "{name} is not on the PS5's home screen") + } + detail={detail ?? undefined} + action={ + running ? undefined : state === "restorable" ? ( + <Button + size="sm" + leftIcon={<RotateCcw size={13} />} + loading={busy === "start"} + disabled={busy !== null} + onClick={() => void onRestore()} + > + {tr("restore_action", undefined, "Restore to home screen")} + </Button> + ) : state === "pending" ? ( + <div className="flex flex-wrap gap-2"> + <Button + size="sm" + leftIcon={<CheckCircle2 size={13} />} + loading={busy === "finish"} + disabled={busy !== null} + onClick={() => void onFinish(false)} + > + {tr("restore_finish", undefined, "Finish")} + </Button> + <Button + size="sm" + variant="secondary" + leftIcon={<Undo2 size={13} />} + loading={busy === "rollback"} + disabled={busy !== null} + onClick={() => void onFinish(true)} + > + {tr("restore_rollback", undefined, "Put back")} + </Button> + </div> + ) : undefined + } + /> + </div> + ); +} diff --git a/client/src/screens/GameHub/index.tsx b/client/src/screens/GameHub/index.tsx index e856dbb5f..b613ebbcc 100644 --- a/client/src/screens/GameHub/index.tsx +++ b/client/src/screens/GameHub/index.tsx @@ -87,6 +87,8 @@ import { CoverFrame, PlatformTag } from "../../components/GameIconFrame"; import { ConsolesCard } from "./ConsolesCard"; import { DrivesCard } from "./DrivesCard"; import { OnThisPs5Card } from "./OnThisPs5Card"; +import { RestoreHomeScreenCard, useRestoreCheck } from "./RestoreHomeScreen"; +import { restoreNeeded } from "../../lib/titleRestore"; import { Ps5DrivesCard } from "./Ps5DrivesCard"; import { installedKindOf } from "./installedKind"; import { useSmpState } from "./SmpNeeded"; @@ -140,6 +142,10 @@ export default function GameHubScreen() { const connectedEntry = gv.view?.consoles.find( (c) => c.host === connectedHost, ); + // #961: installed on a drive but missing from the home screen (Rebuild Database drops games + // installed from fake packages): Play is replaced by Restore to home screen. + const restore = useRestoreCheck(connectedHost, title_id); + const notOnHomeScreen = restoreNeeded(restore.reply); // Back to wherever the page was opened from; Games when it was opened directly. const goBack = () => { const idx = (window.history.state as { idx?: number } | null)?.idx ?? 0; @@ -572,15 +578,33 @@ export default function GameHubScreen() { setSendHost(h); }} playBlocked={ - disc && smp.absent + notOnHomeScreen ? tr( - "installed_play_needs_smp", + "restore_play_blocked", undefined, - "Needs ShadowMount+ running to mount and launch", + "Not on the PS5's home screen: restore it first (below)", ) - : undefined + : disc && smp.absent + ? tr( + "installed_play_needs_smp", + undefined, + "Needs ShadowMount+ running to mount and launch", + ) + : undefined } /> + {connectedHost && title_id && ( + <RestoreHomeScreenCard + host={connectedHost} + titleId={title_id.toUpperCase()} + name={game?.name ?? title_id} + reply={restore.reply} + onChanged={() => { + restore.refresh(); + onConsoleChanged(); + }} + /> + )} {connectedHost && installedHere && ( <OnThisPs5Card host={connectedHost} diff --git a/client/src/state/titleRestore.ts b/client/src/state/titleRestore.ts new file mode 100644 index 000000000..b9e147f51 --- /dev/null +++ b/client/src/state/titleRestore.ts @@ -0,0 +1,115 @@ +import { create } from "zustand"; + +import { restoreStart, restoreStatus, type RestoreRun } from "../api/titleRestore"; +import { hostOf } from "../lib/addr"; +import { restoreEnded, restoreErrorText, restoreOutcome } from "../lib/titleRestore"; +import { pushNotification } from "./notifications"; +import { withConsolePrefix } from "./roster"; + +/** + * Restores to the home screen (#961) this app started, per console and title, so the game page and + * the Games list show the same progress, and the result is told once even after the page that + * started it was closed. In memory only: the engine keeps the run, and the console keeps an + * unfinished one (the game page's check then says `pending`). + */ + +export interface RestoreItem { + titleId: string; + name: string; +} + +interface Entry extends RestoreItem { + host: string; + run: RestoreRun | null; +} + +interface TitleRestoreState { + /** `<host>/<TITLE>` → the latest known run. */ + entries: Record<string, Entry>; + /** Start restoring `items` on `host` (one install after the other) and follow them. Rejects with + * the start's error (nothing was changed on the console then). */ + start: (host: string, items: RestoreItem[]) => Promise<void>; +} + +const POLL_MS = 3_000; +/** A restore of a big game is a whole install: follow it for up to a day. */ +const FOLLOW_MAX_MS = 24 * 60 * 60 * 1000; + +export function restoreKey(host: string, titleId: string): string { + return `${hostOf(host)}/${titleId.toUpperCase()}`; +} + +export const useTitleRestoreStore = create<TitleRestoreState>((set) => { + const put = (host: string, item: RestoreItem, run: RestoreRun | null) => + set((s) => ({ + entries: { ...s.entries, [restoreKey(host, item.titleId)]: { ...item, host, run } }, + })); + + const tell = (host: string, item: RestoreItem, run: RestoreRun) => { + const o = restoreOutcome(run, item.name); + pushNotification(o.level, withConsolePrefix(host, item.name), { body: o.body }); + }; + + async function follow(host: string, items: RestoreItem[]) { + const open = new Map(items.map((i) => [i.titleId.toUpperCase(), i])); + const until = Date.now() + FOLLOW_MAX_MS; + let misses = 0; + while (open.size > 0 && Date.now() < until) { + await new Promise((r) => setTimeout(r, POLL_MS)); + for (const [id, item] of [...open]) { + try { + const run = await restoreStatus(host, id); + misses = 0; + put(host, item, run); + if (restoreEnded(run.phase)) { + open.delete(id); + tell(host, item, run); + } + } catch { + // The engine restarted or is busy: its runs are gone after a restart, and the game's + // page then reads where the console stands. Give up after a while. + if (++misses > 40) return; + } + } + } + } + + return { + entries: {}, + start: async (host, items) => { + if (items.length === 0) return; + for (const item of items) { + put(host, item, { title_id: item.titleId, phase: "queued" }); + } + try { + const r = await restoreStart( + host, + items.map((i) => i.titleId), + ); + put(host, items[0], { title_id: items[0].titleId, phase: "installing", job: r.job, prepared: r.prepared }); + } catch (e) { + const raw = e instanceof Error ? e.message : String(e); + for (const item of items) { + put(host, item, { title_id: item.titleId, phase: "failed", error: raw }); + } + const wrapped = new Error(restoreErrorText(raw, items[0].name)); + // The target is ES2020 (no Error cause option); attach it by hand (preserve-caught-error). + (wrapped as Error & { cause?: unknown }).cause = e; + throw wrapped; + } + void follow(host, items); + }, + }; +}); + +/** The run this app knows for a title on a console, or null. */ +export function useRestoreRun(host: string, titleId: string): RestoreRun | null { + return useTitleRestoreStore((s) => s.entries[restoreKey(host, titleId)]?.run ?? null); +} + +/** Whether a restore this app started is still going on the console. */ +export function useRestoreBusy(host: string): boolean { + return useTitleRestoreStore((s) => + Object.values(s.entries).some((e) => hostOf(e.host) === hostOf(host) && e.run && !restoreEnded(e.run.phase)), + ); +} diff --git a/engine/Cargo.lock b/engine/Cargo.lock index fafabc9b7..3626a6b43 100644 --- a/engine/Cargo.lock +++ b/engine/Cargo.lock @@ -2561,7 +2561,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-exfat" -version = "12.6.36" +version = "12.6.37" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2570,14 +2570,14 @@ dependencies = [ [[package]] name = "ps5-dump-forge-patch" -version = "12.6.36" +version = "12.6.37" dependencies = [ "crc32fast", ] [[package]] name = "ps5-dump-forge-pfs" -version = "12.6.36" +version = "12.6.37" dependencies = [ "flate2", "ps5-dump-forge-patch", @@ -2587,7 +2587,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-ufs2" -version = "12.6.36" +version = "12.6.37" dependencies = [ "ps5-dump-forge-patch", "ps5upload-fpkg", @@ -2597,7 +2597,7 @@ dependencies = [ [[package]] name = "ps5-dump-forge-zstd" -version = "12.6.36" +version = "12.6.37" dependencies = [ "crc32fast", "getrandom 0.4.3", @@ -2608,7 +2608,7 @@ dependencies = [ [[package]] name = "ps5upload-apidoc" -version = "12.6.36" +version = "12.6.37" dependencies = [ "proc-macro2", "quote", @@ -2618,7 +2618,7 @@ dependencies = [ [[package]] name = "ps5upload-archive" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "crc32fast", @@ -2628,7 +2628,7 @@ dependencies = [ [[package]] name = "ps5upload-ava1" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "ava1", @@ -2651,7 +2651,7 @@ dependencies = [ [[package]] name = "ps5upload-convert" -version = "12.6.36" +version = "12.6.37" dependencies = [ "libc", "ps5upload-archive", @@ -2666,7 +2666,7 @@ dependencies = [ [[package]] name = "ps5upload-convert-core" -version = "12.6.36" +version = "12.6.37" dependencies = [ "blake3", "flate2", @@ -2686,7 +2686,7 @@ dependencies = [ [[package]] name = "ps5upload-core" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2720,7 +2720,7 @@ dependencies = [ [[package]] name = "ps5upload-ctest" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "ava1", @@ -2736,7 +2736,7 @@ dependencies = [ [[package]] name = "ps5upload-engine" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.4", "aes-gcm 0.11.1", @@ -2804,7 +2804,7 @@ dependencies = [ [[package]] name = "ps5upload-fpkg" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.4", "blake3", @@ -2828,7 +2828,7 @@ dependencies = [ [[package]] name = "ps5upload-hub" -version = "12.6.36" +version = "12.6.37" dependencies = [ "axum", "base64 0.23.1", @@ -2843,7 +2843,7 @@ dependencies = [ [[package]] name = "ps5upload-lab" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "ava1", @@ -2861,7 +2861,7 @@ dependencies = [ [[package]] name = "ps5upload-pkg" -version = "12.6.36" +version = "12.6.37" dependencies = [ "aes 0.9.4", "blake3", @@ -2873,14 +2873,14 @@ dependencies = [ [[package]] name = "ps5upload-tailnet" -version = "12.6.36" +version = "12.6.37" dependencies = [ "cc", ] [[package]] name = "ps5upload-tests" -version = "12.6.36" +version = "12.6.37" dependencies = [ "anyhow", "ava1", @@ -2898,7 +2898,7 @@ dependencies = [ [[package]] name = "ps5upload-unrar" -version = "12.6.36" +version = "12.6.37" dependencies = [ "serde", "serde_json", diff --git a/engine/Cargo.toml b/engine/Cargo.toml index 8bd6ed716..45417414d 100644 --- a/engine/Cargo.toml +++ b/engine/Cargo.toml @@ -32,7 +32,7 @@ resolver = "2" [workspace.package] edition = "2021" license = "GPL-3.0-or-later" -version = "12.6.36" +version = "12.6.37" [workspace.dependencies] # AVA1 (github.com/phantomptr/ava1): the Rust crate from crates.io; the payload builds the C side diff --git a/engine/crates/ps5upload-ava1/src/app_gen.rs b/engine/crates/ps5upload-ava1/src/app_gen.rs index a75683c8a..ce95936d4 100644 --- a/engine/crates/ps5upload-ava1/src/app_gen.rs +++ b/engine/crates/ps5upload-ava1/src/app_gen.rs @@ -151,6 +151,7 @@ pub const METHOD_TAILNET: u16 = 198; pub const METHOD_SAVE_OWNER: u16 = 199; pub const METHOD_NODE_UNINSTALL: u16 = 200; pub const METHOD_TROPHY_FIX: u16 = 201; +pub const METHOD_APP_RESTORE: u16 = 202; pub const JOB_OP_DELETE: u8 = 1; pub const JOB_OP_CHMOD_R: u8 = 2; pub const JOB_OP_HASH: u8 = 3; diff --git a/engine/crates/ps5upload-core/src/lib.rs b/engine/crates/ps5upload-core/src/lib.rs index daadb0725..7e6fcfe89 100644 --- a/engine/crates/ps5upload-core/src/lib.rs +++ b/engine/crates/ps5upload-core/src/lib.rs @@ -69,6 +69,7 @@ pub mod sys_time; pub mod system_control; pub mod tailnet; pub mod tar_archive; +pub mod title_restore; pub mod transfer; pub mod units; pub mod users; diff --git a/engine/crates/ps5upload-core/src/mgmt.rs b/engine/crates/ps5upload-core/src/mgmt.rs index ece2faa6c..ecae1a16c 100644 --- a/engine/crates/ps5upload-core/src/mgmt.rs +++ b/engine/crates/ps5upload-core/src/mgmt.rs @@ -207,6 +207,7 @@ methods! { (SAVE_OWNER, 199, "SAVE_OWNER"), (NODE_UNINSTALL, 200, "NODE_UNINSTALL"), (TROPHY_FIX, 201, "TROPHY_FIX"), + (APP_RESTORE, 202, "APP_RESTORE"), } /// A management call the payload refused. diff --git a/engine/crates/ps5upload-core/src/title_restore.rs b/engine/crates/ps5upload-core/src/title_restore.rs new file mode 100644 index 000000000..c1266031c --- /dev/null +++ b/engine/crates/ps5upload-core/src/title_restore.rs @@ -0,0 +1,243 @@ +//! Putting a game installed from a package back on the home screen (#961). +//! +//! After Settings › Rebuild Database (Safe Mode, where no fake-package support is loaded), games +//! installed from fake packages disappear from the home screen and from Settings › Storage, while +//! their files stay (`<drive>/user/app/<id>/app.pkg`). The helper's `app.restore` +//! (`payload/src/title_restore.c`) checks a title, moves its package aside on the same drive +//! (`prepare`, after backing up app.db and appinfo.db), and after the engine has installed that +//! copy through the installer daemon, deletes the copy or puts it back (`finish`). The helper +//! never writes either database; the console's installer does, as for any install. +//! +//! A refusal from `prepare` is an `Ok` reply with `ok: false` and `err` (`restore_<state>`); an +//! older helper answers ERR_UNKNOWN_METHOD, turned into `restore_unsupported: ...` here. + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; + +use crate::mgmt::{self, m}; + +/// What the helper answered. Fields a state does not use are absent. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct RestoreReply { + #[serde(default)] + pub ok: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub err: Option<String>, + #[serde(default)] + pub title_id: String, + /// check: restorable | registered | record_elsewhere | not_installed | pending | + /// folder_registration | ambiguous | retail | no_room | aside_cross_device | db_unreadable | + /// invalid_title | system_title. prepare: prepared. finish: restored | rolled_back | + /// nothing_pending | waiting | unsettled. + #[serde(default)] + pub state: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option<String>, + /// internal | m2 | usb | extended: the drive the package is (or was) on. + #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] + pub where_: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub volume: Option<String>, + /// The folder the package is moved into while it is installed again. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aside: Option<String>, + /// The installed package's place: `<drive>/user/app/<id>/app.pkg`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pkg: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option<u64>, + /// fake | ps4 | unknown (a retail PS5 package is refused). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option<String>, + /// The title's update, when one sits on the same drive. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub patch: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub patch_size: Option<u64>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub free_volume: Option<u64>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub free_internal: Option<u64>, + /// prepare: the copy aside to install. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub install_path: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub patch_aside: Option<String>, + /// The folder with the copies of app.db and appinfo.db taken before the move. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backup: Option<String>, + /// finish: where the console installed the game. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub installed: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub installed_where: Option<String>, + /// finish: the update kept aside because its place was taken. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub patch_kept: Option<String>, + /// finish: the copy aside, kept. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kept: Option<String>, +} + +impl RestoreReply { + /// The check answered "this title can be put back". + pub fn restorable(&self) -> bool { + self.ok && self.state == "restorable" + } +} + +/// The request body. +pub fn body(op: &str, title_id: &str, rollback: bool, install_ended: bool) -> serde_json::Value { + let mut b = serde_json::json!({ "op": op, "title_id": title_id }); + if rollback { + b["rollback"] = serde_json::Value::Bool(true); + } + if install_ended { + b["install_ended"] = serde_json::Value::Bool(true); + } + b +} + +/// How an older helper's refusal starts (its text follows the colon). +pub const UNSUPPORTED: &str = "restore_unsupported:"; + +/// A title id the helper accepts: 4 letters and 5 digits. +pub fn valid_title_id(id: &str) -> bool { + let b = id.as_bytes(); + b.len() == 9 + && b[..4].iter().all(|c| c.is_ascii_alphabetic()) + && b[4..].iter().all(|c| c.is_ascii_digit()) +} + +fn call( + addr: &str, + op: &str, + title_id: &str, + rollback: bool, + install_ended: bool, +) -> Result<RestoreReply> { + let id = title_id.trim().to_ascii_uppercase(); + if !valid_title_id(&id) { + anyhow::bail!("restore_invalid_title: {title_id:?} is not a title id"); + } + let req = serde_json::to_vec(&body(op, &id, rollback, install_ended))?; + let bytes = mgmt::call(addr, m::APP_RESTORE, &req).map_err(|e| { + if crate::console_files::is_unsupported(&e) { + anyhow::anyhow!( + "{UNSUPPORTED} the PS5 helper is an older version; send the helper again" + ) + } else { + e + } + })?; + let r: RestoreReply = serde_json::from_slice(&bytes).context("parse APP_RESTORE reply")?; + crate::clog!( + Info, + "install", + "{op} {id} on {addr}: ok={} state={} err={:?} reason={:?}", + r.ok, + r.state, + r.err, + r.reason + ); + Ok(r) +} + +/// Read-only: can this title be put back, and why not. +pub fn check(addr: &str, title_id: &str) -> Result<RestoreReply> { + call(addr, "check", title_id, false, false) +} + +/// Back up the databases and move the package aside. `ok: false` with `err` is a refusal +/// (nothing was changed). +pub fn prepare(addr: &str, title_id: &str) -> Result<RestoreReply> { + call(addr, "prepare", title_id, false, false) +} + +/// After the install: `install_ended` when it is known to have ended (its job reached a +/// verdict, or the user saw the game start), `rollback` when it ended without putting the game +/// back (implies ended). +pub fn finish( + addr: &str, + title_id: &str, + rollback: bool, + install_ended: bool, +) -> Result<RestoreReply> { + call( + addr, + "finish", + title_id, + rollback, + install_ended || rollback, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn method_number_is_the_schemas() { + assert_eq!(m::APP_RESTORE.id, 202); + assert_eq!(m::APP_RESTORE.label, "APP_RESTORE"); + } + + #[test] + fn body_sends_flags_only_when_set() { + assert_eq!( + body("check", "PPSA01234", false, false), + serde_json::json!({"op":"check","title_id":"PPSA01234"}) + ); + assert_eq!( + body("finish", "PPSA01234", true, true), + serde_json::json!({"op":"finish","title_id":"PPSA01234","rollback":true,"install_ended":true}) + ); + } + + #[test] + fn title_ids_are_checked_before_asking() { + assert!(valid_title_id("PPSA01234")); + assert!(valid_title_id("cusa00900")); + for bad in [ + "", + "PPSA0123", + "PPSA012345", + "PPSA0123A", + "../x", + "PPSA 1234", + ] { + assert!(!valid_title_id(bad), "{bad}"); + } + let e = check("127.0.0.1:1", "../etc").unwrap_err().to_string(); + assert!(e.starts_with("restore_invalid_title"), "{e}"); + } + + #[test] + fn replies_parse_with_every_shape() { + let r: RestoreReply = serde_json::from_str( + r#"{"ok":true,"title_id":"PPSA01234","state":"restorable","where":"m2","volume":"/mnt/ext1", + "aside":"/mnt/ext1/ps5upload/restore/PPSA01234","pkg":"/mnt/ext1/user/app/PPSA01234/app.pkg", + "size":4096,"kind":"fake","patch":"/mnt/ext1/user/patch/PPSA01234/patch.pkg","patch_size":10, + "free_volume":1,"free_internal":2}"#, + ) + .unwrap(); + assert!(r.restorable()); + assert_eq!(r.where_.as_deref(), Some("m2")); + assert_eq!(r.size, Some(4096)); + let back = serde_json::to_value(&r).unwrap(); + assert_eq!(back["where"], "m2"); + assert!(back.get("err").is_none()); + + let r: RestoreReply = serde_json::from_str( + r#"{"ok":false,"err":"restore_registered","title_id":"PPSA01234","state":"registered"}"#, + ) + .unwrap(); + assert!(!r.restorable()); + assert_eq!(r.err.as_deref(), Some("restore_registered")); + + let r: RestoreReply = + serde_json::from_str(r#"{"ok":true,"state":"system_title"}"#).unwrap(); + assert_eq!(r.state, "system_title"); + assert!(r.title_id.is_empty()); + } +} diff --git a/engine/crates/ps5upload-engine/api/openapi.json b/engine/crates/ps5upload-engine/api/openapi.json index 2135da6d5..a8e188ba2 100644 --- a/engine/crates/ps5upload-engine/api/openapi.json +++ b/engine/crates/ps5upload-engine/api/openapi.json @@ -12628,6 +12628,183 @@ ], "type": "object" }, + "RestoreFinish": { + "properties": { + "addr": { + "type": "string", + "x-aliases": [ + "console", + "host", + "ps5_addr" + ] + }, + "install_ended": { + "description": "The install has ended (the user saw the game on the home screen): the copy aside may go.", + "type": "boolean" + }, + "rollback": { + "description": "Put the package and its update back where they were (when the game is not on the home\nscreen). Only once nothing installs on the console.", + "type": "boolean" + }, + "title_id": { + "type": "string" + } + }, + "required": [ + "addr", + "title_id" + ], + "type": "object" + }, + "RestoreReply": { + "description": "What the helper answered. Fields a state does not use are absent.", + "properties": { + "aside": { + "description": "The folder the package is moved into while it is installed again.", + "type": [ + "string", + "null" + ] + }, + "backup": { + "description": "The folder with the copies of app.db and appinfo.db taken before the move.", + "type": [ + "string", + "null" + ] + }, + "err": { + "type": [ + "string", + "null" + ] + }, + "free_internal": { + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "free_volume": { + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "install_path": { + "description": "prepare: the copy aside to install.", + "type": [ + "string", + "null" + ] + }, + "installed": { + "description": "finish: where the console installed the game.", + "type": [ + "string", + "null" + ] + }, + "installed_where": { + "type": [ + "string", + "null" + ] + }, + "kept": { + "description": "finish: the copy aside, kept.", + "type": [ + "string", + "null" + ] + }, + "kind": { + "description": "fake | ps4 | unknown (a retail PS5 package is refused).", + "type": [ + "string", + "null" + ] + }, + "ok": { + "type": "boolean" + }, + "patch": { + "description": "The title's update, when one sits on the same drive.", + "type": [ + "string", + "null" + ] + }, + "patch_aside": { + "type": [ + "string", + "null" + ] + }, + "patch_kept": { + "description": "finish: the update kept aside because its place was taken.", + "type": [ + "string", + "null" + ] + }, + "patch_size": { + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "pkg": { + "description": "The installed package's place: `<drive>/user/app/<id>/app.pkg`.", + "type": [ + "string", + "null" + ] + }, + "reason": { + "type": [ + "string", + "null" + ] + }, + "size": { + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "state": { + "description": "check: restorable | registered | record_elsewhere | not_installed | pending |\nfolder_registration | ambiguous | retail | no_room | aside_cross_device | db_unreadable |\ninvalid_title | system_title. prepare: prepared. finish: restored | rolled_back |\nnothing_pending | waiting | unsettled.", + "type": "string" + }, + "title_id": { + "type": "string" + }, + "volume": { + "type": [ + "string", + "null" + ] + }, + "where": { + "description": "internal | m2 | usb | extended: the drive the package is (or was) on.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "ok", + "title_id", + "state" + ], + "type": "object" + }, "RestoreReq": { "properties": { "addr": { @@ -12649,6 +12826,115 @@ ], "type": "object" }, + "RestoreRun": { + "description": "One title's restore as this engine ran it.", + "properties": { + "addr": { + "type": "string" + }, + "error": { + "type": [ + "string", + "null" + ] + }, + "install_hint": { + "type": [ + "string", + "null" + ] + }, + "install_verdict": { + "anyOf": [ + { + "$ref": "#/components/schemas/Verdict" + }, + { + "type": "null" + } + ] + }, + "job": { + "description": "The install job (`/api/pkg/install/status?job=`).", + "type": [ + "string", + "null" + ] + }, + "phase": { + "description": "queued | installing | finishing | restored | rolled_back | pending | failed", + "type": "string" + }, + "prepared": { + "anyOf": [ + { + "$ref": "#/components/schemas/RestoreReply" + }, + { + "type": "null" + } + ] + }, + "result": { + "anyOf": [ + { + "$ref": "#/components/schemas/RestoreReply" + }, + { + "type": "null" + } + ], + "description": "The helper's last finish answer." + }, + "title_id": { + "type": "string" + }, + "updated_at": { + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "title_id", + "addr", + "phase", + "updated_at" + ], + "type": "object" + }, + "RestoreStart": { + "properties": { + "addr": { + "type": "string", + "x-aliases": [ + "console", + "host", + "ps5_addr" + ] + }, + "title_id": { + "description": "One title.", + "type": [ + "string", + "null" + ] + }, + "title_ids": { + "description": "Several, restored one after the other (\"Restore all\").", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + } + }, + "required": [ + "addr" + ], + "type": "object" + }, "RestoreToUserBody": { "properties": { "addr": { @@ -31721,6 +32007,438 @@ } } }, + "/api/ps5/app/restore": { + "post": { + "description": "`POST /api/ps5/app/restore {addr, title_id | title_ids}`: put games installed from a package\nback on the home screen by installing the package already on the console again (no\ndownload). The first title is checked and prepared before this answers: a refusal is 409 with\nthe helper's `restore` answer and nothing changed; another install on the console is 409\n`busy`. Then `{ok, job, prepared, queued}`: `job` is the first title's install\n(`/api/pkg/install/status`); the others follow one after the other. Each title's progress:\n`GET /api/ps5/app/restore/status`.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RestoreStart" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "job": {}, + "ok": { + "type": "boolean" + }, + "prepared": {}, + "queued": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + } + } + }, + "description": "Success." + }, + "400": { + "$ref": "#/components/responses/Error", + "description": "Bad request" + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "409": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Error" + }, + { + "properties": { + "error": { + "type": "string" + }, + "ok": { + "type": "boolean" + }, + "reason": { + "type": "string" + } + }, + "type": "object" + }, + { + "properties": { + "error": {}, + "ok": { + "type": "boolean" + }, + "restore": {} + }, + "type": "object" + }, + { + "properties": { + "error": { + "type": "string" + }, + "job": {}, + "ok": { + "type": "boolean" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "Conflict" + }, + "500": { + "$ref": "#/components/responses/Error", + "description": "Engine error" + }, + "502": { + "$ref": "#/components/responses/Error", + "description": "The console or remote end failed" + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "Put games installed from a package back on the home screen by installing the package already on the console again (no download)", + "tags": [ + "games" + ], + "x-ps5upload": { + "access": "loopback", + "console": { + "aliases": [ + "console", + "host", + "ps5_addr" + ], + "in": "body", + "name": "addr", + "required": true + }, + "response_schema": "literal" + } + } + }, + "/api/ps5/app/restore/candidates": { + "get": { + "description": "`GET /api/ps5/app/restore/candidates?addr=`: every title with an app folder on the internal\ndrive, USB extended storage or M.2 that app.db does not list, with the helper's check of each\n(`check.state` `restorable` can be put back; `pending` has a restore to finish). Read-only.\napp.db must answer in full: a partial list could make a listed game look missing.", + "parameters": [ + { + "in": "query", + "name": "addr", + "required": true, + "schema": { + "type": "string" + }, + "x-aliases": [ + "console", + "host", + "ps5_addr" + ] + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "ok": { + "type": "boolean" + }, + "titles": {} + }, + "type": "object" + } + } + }, + "description": "Success." + }, + "400": { + "$ref": "#/components/responses/Error", + "description": "Bad request" + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "409": { + "$ref": "#/components/responses/Error", + "description": "Conflict" + }, + "500": { + "$ref": "#/components/responses/Error", + "description": "Engine error" + }, + "502": { + "$ref": "#/components/responses/Error", + "description": "The console or remote end failed" + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "tags": [ + "games" + ], + "x-ps5upload": { + "access": "loopback", + "console": { + "aliases": [ + "console", + "host", + "ps5_addr" + ], + "in": "query", + "name": "addr", + "required": true + }, + "response_schema": "literal" + } + } + }, + "/api/ps5/app/restore/check": { + "get": { + "description": "`GET /api/ps5/app/restore/check?addr=&title_id=`: whether a game installed from a package can\nbe put back on the home screen, read-only. The helper's answer: `state` is `restorable`, or\nwhy not (`registered`: it is on the home screen; `record_elsewhere`: the console still has a\nrecord of it; `not_installed`, `pending` (an earlier restore did not finish),\n`folder_registration`, `ambiguous`, `retail`, `no_room`, `aside_cross_device`, `db_unreadable`,\n`invalid_title`, `system_title`), with `pkg`, `size`, `where`, `kind`, `patch` and the free\nspace. A helper without the method answers 409 `restore_unsupported`.", + "parameters": [ + { + "in": "query", + "name": "addr", + "required": true, + "schema": { + "type": "string" + }, + "x-aliases": [ + "console", + "host", + "ps5_addr" + ] + }, + { + "in": "query", + "name": "title_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RestoreReply" + } + } + }, + "description": "Success." + }, + "400": { + "$ref": "#/components/responses/Error", + "description": "Bad request" + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "409": { + "$ref": "#/components/responses/Error", + "description": "Conflict" + }, + "500": { + "$ref": "#/components/responses/Error", + "description": "Engine error" + }, + "502": { + "$ref": "#/components/responses/Error", + "description": "The console or remote end failed" + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "Whether a game installed from a package can be put back on the home screen, read-only", + "tags": [ + "games" + ], + "x-ps5upload": { + "access": "loopback", + "console": { + "aliases": [ + "console", + "host", + "ps5_addr" + ], + "in": "query", + "name": "addr", + "required": true + }, + "response_schema": "struct" + } + } + }, + "/api/ps5/app/restore/finish": { + "post": { + "description": "`POST /api/ps5/app/restore/finish {addr, title_id, rollback, install_ended}`: finish a restore\nleft `pending` (an engine restart, a slow database). With `install_ended` the copy aside is\ndeleted once app.db lists the game and a package is in place; with `rollback` the package and\nupdate go back where they were, only while app.db does not list the game and the place is\nfree; with neither, nothing changes and the answer says where it stands. Refused (409 `busy`)\nwhile an install or a restore runs on that console. The helper's `finish` answer.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RestoreFinish" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RestoreReply" + } + } + }, + "description": "Success." + }, + "400": { + "$ref": "#/components/responses/Error", + "description": "Bad request" + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "409": { + "$ref": "#/components/responses/Error", + "description": "Conflict" + }, + "500": { + "$ref": "#/components/responses/Error", + "description": "Engine error" + }, + "502": { + "$ref": "#/components/responses/Error", + "description": "The console or remote end failed" + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "Finish a restore left `pending` (an engine restart, a slow database)", + "tags": [ + "games" + ], + "x-ps5upload": { + "access": "loopback", + "console": { + "aliases": [ + "console", + "host", + "ps5_addr" + ], + "in": "body", + "name": "addr", + "required": true + }, + "response_schema": "struct" + } + } + }, + "/api/ps5/app/restore/status": { + "get": { + "description": "`GET /api/ps5/app/restore/status?addr=&title_id=`: how this engine's restore of a title stands.\n`phase`: `queued`, `installing` (with `job`, the install's id for `/api/pkg/install/status`;\n`install` is that status), `finishing`, `restored`, `rolled_back` (the install did not take, the\npackage is back where it was), `pending` (the console may still be working on it, or the\ndatabase did not list the game in time: nothing was deleted; finish it later), `failed`\n(refused before anything moved: `error`, and the helper's `result`). 404 when this engine ran\nnone (after a restart: the check's `pending` state says an unfinished one is on the console).", + "parameters": [ + { + "in": "query", + "name": "addr", + "required": true, + "schema": { + "type": "string" + }, + "x-aliases": [ + "console", + "host", + "ps5_addr" + ] + }, + { + "in": "query", + "name": "title_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RestoreRun" + } + } + }, + "description": "Success." + }, + "400": { + "$ref": "#/components/responses/Error", + "description": "Bad request" + }, + "403": { + "$ref": "#/components/responses/Error", + "description": "Refused by the engine's address, Origin or Host guards." + }, + "404": { + "$ref": "#/components/responses/Error", + "description": "Not found" + }, + "default": { + "$ref": "#/components/responses/Error", + "description": "Any other failure, in the same shape." + } + }, + "summary": "How this engine's restore of a title stands", + "tags": [ + "games" + ], + "x-ps5upload": { + "access": "loopback", + "console": { + "aliases": [ + "console", + "host", + "ps5_addr" + ], + "in": "query", + "name": "addr", + "required": true + }, + "response_schema": "struct" + } + } + }, "/api/ps5/app/unregister": { "post": { "requestBody": { diff --git a/engine/crates/ps5upload-engine/src/install/mod.rs b/engine/crates/ps5upload-engine/src/install/mod.rs index 679744c64..43b3decfc 100644 --- a/engine/crates/ps5upload-engine/src/install/mod.rs +++ b/engine/crates/ps5upload-engine/src/install/mod.rs @@ -140,6 +140,18 @@ impl JobStore { self.finish(job); } + /// Give back a slot reserved with `begin` for an install that never started (a home-screen + /// restore the helper refused after the slot was taken, #961): the job ends failed with `hint`. + pub fn release_unstarted(&self, job: &str, hint: &str) { + self.update(job, |st| { + st.phase = Phase::Failed; + st.verdict = Some(Verdict::Failed); + st.reason = Some(FailReason::BadRequest); + st.hint = Some(hint.to_string()); + }); + self.finish(job); + } + /// Whether `ps5_addr` has an install running. pub fn active_for(&self, ps5_addr: &str) -> bool { lock(&self.active).contains_key(&slot_key(ps5_addr)) @@ -1365,6 +1377,14 @@ pub async fn install_handler( Json(serde_json::json!({"ok":true,"job":job})).into_response() } +/// Run an install in the slot `job` reserved with [`JobStore::begin`]; resolves when the job has +/// ended, with the slot released. A home-screen restore (#961) reserves the slot before it moves +/// the package aside, so no other install can start on that console in between. +pub(crate) async fn run_reserved(state: PkgInstallStateHandle, job: String, req: InstallRequest) { + let _slot = SlotRelease::new(state.clone(), job.clone()); + run_install(state, job, req).await; +} + #[derive(Debug, Deserialize)] pub struct JobQuery { pub job: String, diff --git a/engine/crates/ps5upload-engine/src/join_net/join_tests.rs b/engine/crates/ps5upload-engine/src/join_net/join_tests.rs index f74419bfc..b14690ed3 100644 --- a/engine/crates/ps5upload-engine/src/join_net/join_tests.rs +++ b/engine/crates/ps5upload-engine/src/join_net/join_tests.rs @@ -141,6 +141,8 @@ async fn an_internet_guest_joins_over_webrtc_plays_and_gets_the_picture() { let hub_host = crate::join_net::hub_host(&hub.url).unwrap(); let url = net["url"].as_str().unwrap(); let (link, lan) = url.split_once("&lan=").unwrap_or((url, "")); + // A computer on Tailscale adds its tailnet page after the home one (`&ts=`): not this test's. + let lan = lan.split_once("&ts=").map_or(lan, |(home, _)| home); assert_eq!( link, format!( diff --git a/engine/crates/ps5upload-engine/src/lib.rs b/engine/crates/ps5upload-engine/src/lib.rs index dffe591ea..0e914294a 100644 --- a/engine/crates/ps5upload-engine/src/lib.rs +++ b/engine/crates/ps5upload-engine/src/lib.rs @@ -138,6 +138,7 @@ mod tailnet_discover; pub(crate) mod tailnet_engine; pub(crate) mod tailnet_system; mod telemetry; +mod title_restore_api; mod trophy_fix_routes; mod unpack_packs; mod vinput_api; diff --git a/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs b/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs index 6f065d803..02ebd3d57 100644 --- a/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs +++ b/engine/crates/ps5upload-engine/src/mcp/catalog_routes.rs @@ -529,6 +529,11 @@ pub(crate) const ROUTES: &[(&str, &str)] = &[ ("POST", "/api/ps5/app/launch"), ("POST", "/api/ps5/app/lifecycle"), ("POST", "/api/ps5/app/register"), + ("POST", "/api/ps5/app/restore"), + ("GET", "/api/ps5/app/restore/candidates"), + ("GET", "/api/ps5/app/restore/check"), + ("POST", "/api/ps5/app/restore/finish"), + ("GET", "/api/ps5/app/restore/status"), ("POST", "/api/ps5/app/unregister"), ("GET", "/api/ps5/appdb"), ("GET", "/api/ps5/appinfo"), diff --git a/engine/crates/ps5upload-engine/src/mcp/tests.rs b/engine/crates/ps5upload-engine/src/mcp/tests.rs index 8b721670c..1f098b57c 100644 --- a/engine/crates/ps5upload-engine/src/mcp/tests.rs +++ b/engine/crates/ps5upload-engine/src/mcp/tests.rs @@ -2618,6 +2618,42 @@ async fn each_post_tool_sends_what_its_route_reads() { assert_eq!(asked["path"], "/api/ps5/app/unregister"); reads_as::<crate::AppUnregisterReq>(&asked["body"]); + let asked = route_of( + &server, + "games_restore", + json!({"console": c, "title_ids": ["PPSA00001", "CUSA00002"]}), + ) + .await; + assert_eq!(asked["path"], "/api/ps5/app/restore"); + reads_as::<crate::title_restore_api::RestoreStart>(&asked["body"]); + + let asked = route_of( + &server, + "games_restore_finish", + json!({"console": c, "title_id": "PPSA00001", "rollback": true}), + ) + .await; + assert_eq!(asked["path"], "/api/ps5/app/restore/finish"); + reads_as::<crate::title_restore_api::RestoreFinish>(&asked["body"]); + + for (tool, path) in [ + ("games_restore_check", "/api/ps5/app/restore/check"), + ("games_restore_status", "/api/ps5/app/restore/status"), + ] { + let asked = route_of( + &server, + tool, + json!({"console": c, "title_id": "PPSA00001"}), + ) + .await; + assert_eq!(asked["path"], path); + assert_eq!(asked["query"]["addr"], c); + assert_eq!(asked["query"]["title_id"], "PPSA00001"); + } + let asked = route_of(&server, "games_restore_list", json!({"console": c})).await; + assert_eq!(asked["path"], "/api/ps5/app/restore/candidates"); + assert_eq!(asked["query"]["addr"], c); + let asked = route_of(&server, "processes_kill", json!({"console": c, "pid": 77})).await; assert_eq!(asked["path"], "/api/ps5/process/kill"); reads_as::<crate::ProcessKillReq>(&asked["body"]); diff --git a/engine/crates/ps5upload-engine/src/mcp/tools/games.rs b/engine/crates/ps5upload-engine/src/mcp/tools/games.rs index c091550a3..d2e1fadd9 100644 --- a/engine/crates/ps5upload-engine/src/mcp/tools/games.rs +++ b/engine/crates/ps5upload-engine/src/mcp/tools/games.rs @@ -1,5 +1,7 @@ //! Running and starting things on a console: `processes_list`, `processes_kill`, `shell_run`, -//! `games_installed`, `games_launch`, `games_stop`, `games_register`, `games_unregister`. +//! `games_installed`, `games_launch`, `games_stop`, `games_register`, `games_unregister`, and +//! Restore to home screen (#961): `games_restore_list`, `games_restore_check`, `games_restore`, +//! `games_restore_status`, `games_restore_finish`. use serde_json::{json, Value}; @@ -126,6 +128,123 @@ pub(super) fn tools() -> Vec<ToolDef> { done: "Asked the console to remove the title.", ), }, + ToolDef { + name: "games_restore_list", + title: "Games missing from the home screen", + description: "Games a console has the installed package of (internal drive, USB \ + extended storage or M.2) but no home-screen record for, as after \ + Settings > Rebuild Database, which drops games installed from fake \ + packages. Each title's `check.state`: `restorable` (games_restore can \ + put it back), `pending` (an earlier restore to finish with \ + games_restore_finish), or why not (`record_elsewhere`, `retail`, \ + `no_room`, `ambiguous`, `folder_registration`, `db_unreadable`...). \ + Changes nothing. Such a game cannot be started with games_launch.", + kind: Kind::Read, + schema: object(json!({ "console": console_required() }), &["console"]), + run: route!( + method: "GET", + path: "/api/ps5/app/restore/candidates", + done: "The games the console has but does not list.", + ), + }, + ToolDef { + name: "games_restore_check", + title: "Check a game for Restore to home screen", + description: "Whether one title can be put back on the home screen (`state` \ + `restorable`) and why not otherwise; also its package (`pkg`, `size`, \ + `where`), its update (`patch`) and the free space. Changes nothing.", + kind: Kind::Read, + schema: object( + json!({ + "console": console_required(), + "title_id": text("The title's id, like PPSA01234."), + }), + &["console", "title_id"], + ), + run: route!( + method: "GET", + path: "/api/ps5/app/restore/check", + done: "Checked the title.", + ), + }, + ToolDef { + name: "games_restore", + title: "Restore games to the home screen", + description: "Puts games that games_restore_list shows as `restorable` back on the \ + home screen: the console's own installer installs the package that is \ + already on the drive again (no download; it needs free space for one \ + more copy while it runs). The helper first copies the console's app \ + databases aside and moves the package aside on the same drive; a \ + failed install puts it back. One install per console: titles go one \ + after the other. Confirm with the user first. Follow each title with \ + games_restore_status (`job` is also an install_wait job).", + kind: Kind::Write { idempotent: false }, + schema: object( + json!({ + "console": console_required(), + "title_id": text("One title, like PPSA01234."), + "title_ids": { + "type": "array", + "items": { "type": "string" }, + "description": "Several titles, restored one after the other.", + }, + }), + &["console"], + ), + run: route!( + method: "POST", + path: "/api/ps5/app/restore", + done: "Started the restore.", + ), + }, + ToolDef { + name: "games_restore_status", + title: "How a restore stands", + description: "This engine's restore of one title: `phase` queued, installing (with \ + the install's `job` and status), finishing, restored, rolled_back (the \ + install did not take; the package is back where it was), pending \ + (the console may still be working on it: finish it later with \ + games_restore_finish), or failed (refused before anything moved).", + kind: Kind::Read, + schema: object( + json!({ + "console": console_required(), + "title_id": text("The title's id, like PPSA01234."), + }), + &["console", "title_id"], + ), + run: route!( + method: "GET", + path: "/api/ps5/app/restore/status", + done: "How the restore stands.", + ), + }, + ToolDef { + name: "games_restore_finish", + title: "Finish a restore", + description: "Finishes a restore left pending. `install_ended`: the user saw the \ + game on the home screen, so the copy aside is deleted (only once the \ + console lists the game and has its package in place). `rollback`: the \ + game did not come back, so the package and its update go back where \ + they were (only while the console does not list it). With neither, \ + it only says where the restore stands. Refused while an install runs \ + on the console. Ask the user which one first.", + kind: Kind::Write { idempotent: true }, + schema: object( + json!({ + "console": console_required(), + "title_id": text("The title's id, like PPSA01234."), + "install_ended": flag("The install has ended and the game shows on the home screen."), + "rollback": flag("Put the package back where it was."), + }), + &["console", "title_id"], + ), + run: route!( + method: "POST", + path: "/api/ps5/app/restore/finish", + done: "Asked the console to finish the restore.", + ), + }, ToolDef { name: "shell_run", title: "Run a console command", diff --git a/engine/crates/ps5upload-engine/src/pkg_install.rs b/engine/crates/ps5upload-engine/src/pkg_install.rs index b0f11f5b4..a59e8abcc 100644 --- a/engine/crates/ps5upload-engine/src/pkg_install.rs +++ b/engine/crates/ps5upload-engine/src/pkg_install.rs @@ -1053,6 +1053,27 @@ pub fn api_router(state: PkgInstallStateHandle) -> Router { post(crate::install::install_stop_handler), ) .route("/api/pkg/install/sessions", get(install_sessions_handler)) + // Restore to home screen (#961): the package already on the console installed again. + .route( + "/api/ps5/app/restore", + post(crate::title_restore_api::start_handler), + ) + .route( + "/api/ps5/app/restore/check", + get(crate::title_restore_api::check_handler), + ) + .route( + "/api/ps5/app/restore/candidates", + get(crate::title_restore_api::candidates_handler), + ) + .route( + "/api/ps5/app/restore/status", + get(crate::title_restore_api::status_handler), + ) + .route( + "/api/ps5/app/restore/finish", + post(crate::title_restore_api::finish_handler), + ) .route( "/api/pkg/links", get(links_list_handler).post(link_create_handler), diff --git a/engine/crates/ps5upload-engine/src/title_restore_api.rs b/engine/crates/ps5upload-engine/src/title_restore_api.rs new file mode 100644 index 000000000..9491f170c --- /dev/null +++ b/engine/crates/ps5upload-engine/src/title_restore_api.rs @@ -0,0 +1,765 @@ +//! Restore to home screen (#961): a game installed from a package whose home-screen record is +//! gone (Settings › Rebuild Database drops fake packages; the files stay on the drive) is put +//! back by installing the package that is already on the console again, through the console's +//! own installer, without a download. +//! +//! The steps (each helper step is `app.restore`, `payload/src/title_restore.c`): +//! 1. check: read-only, the helper says whether the title is restorable and why not. +//! 2. this console's install slot is reserved (one install per console), then `prepare`: the +//! helper backs up app.db and appinfo.db and moves the package (and its update) aside on the +//! same drive. +//! 3. the copy aside is installed like any package on the console (`install::run_reserved`). +//! 4. `finish`: after a verdict of installed, the copy aside is deleted once app.db has the title +//! and a package is in place again (the database can lag: it is asked again for a while); +//! after a failure the console never took (refused, unreachable, bad request), the package +//! and update go back where they were; after anything that may still be running on the +//! console (stalled, cancelled, reply lost, unverified), nothing is touched and the restore +//! stays pending: the game page offers Finish or Put back later. +//! +//! Nothing here writes app.db or appinfo.db; the console's installer does, as for any install. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::Duration; + +use axum::{ + extract::{Query, State}, + http::StatusCode, + response::{IntoResponse, Response}, + Json, +}; +use ps5upload_core::title_restore::{self as tr, RestoreReply}; +use serde::{Deserialize, Serialize}; + +use crate::install::deliver::Source; +use crate::install::status::{FailReason, InstallStatus, Phase, Verdict}; +use crate::install::{self, InstallOptions, InstallRequest}; +use crate::pkg_install::PkgInstallStateHandle; + +/// The most titles one request restores (each is one install, one after the other). +const MAX_TITLES: usize = 50; +/// How long a finished install waits for app.db to list the title before the restore is left +/// pending (the database lags the files, both ways). +const SETTLE_TRIES: u32 = 36; +const SETTLE_EVERY: Duration = Duration::from_secs(5); + +/// What to do once the install of the copy aside has ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AfterInstall { + /// Installed: confirm with the helper and delete the copy aside. + Finish, + /// The console never took it: put the package back. + Rollback, + /// The console may still be working on it: touch nothing. + Leave, +} + +/// The decision, from the install job's last status (None: the job is unknown). +pub fn after_install(st: Option<&InstallStatus>) -> AfterInstall { + let Some(st) = st else { + return AfterInstall::Leave; + }; + match (st.phase, st.verdict) { + (_, Some(Verdict::Installed)) | (_, Some(Verdict::MayNotLaunch)) => AfterInstall::Finish, + (_, Some(Verdict::Unverified)) => AfterInstall::Leave, + (Phase::Failed, _) | (_, Some(Verdict::Failed)) => match st.reason { + // Sony may have accepted it and go on pulling or writing: a package put back now + // could be written over, or pulled from under the console. + Some(FailReason::Stalled) + | Some(FailReason::Cancelled) + | Some(FailReason::ReplyLost) => AfterInstall::Leave, + _ => AfterInstall::Rollback, + }, + // Not ended. + _ => AfterInstall::Leave, + } +} + +/// One title's restore as this engine ran it. +#[derive(Debug, Clone, Serialize)] +pub struct RestoreRun { + pub title_id: String, + pub addr: String, + /// queued | installing | finishing | restored | rolled_back | pending | failed + pub phase: String, + /// The install job (`/api/pkg/install/status?job=`). + #[serde(skip_serializing_if = "Option::is_none")] + pub job: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub prepared: Option<RestoreReply>, + /// The helper's last finish answer. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option<RestoreReply>, + #[serde(skip_serializing_if = "Option::is_none")] + pub install_verdict: Option<Verdict>, + #[serde(skip_serializing_if = "Option::is_none")] + pub install_hint: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option<String>, + pub updated_at: u64, +} + +impl RestoreRun { + fn new(addr: &str, title_id: &str, phase: &str) -> Self { + RestoreRun { + title_id: title_id.to_string(), + addr: addr.to_string(), + phase: phase.to_string(), + job: None, + prepared: None, + result: None, + install_verdict: None, + install_hint: None, + error: None, + updated_at: install::status::now_unix(), + } + } + + fn active(&self) -> bool { + matches!(self.phase.as_str(), "queued" | "installing" | "finishing") + } +} + +static RUNS: Mutex<Option<HashMap<String, RestoreRun>>> = Mutex::new(None); + +fn key(addr: &str, title_id: &str) -> String { + format!("{}/{}", install::console_id(addr), title_id) +} + +fn with_runs<T>(f: impl FnOnce(&mut HashMap<String, RestoreRun>) -> T) -> T { + let mut g = RUNS.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(HashMap::new)) +} + +fn set_run(run: RestoreRun) { + let mut run = run; + run.updated_at = install::status::now_unix(); + with_runs(|m| m.insert(key(&run.addr, &run.title_id), run)); +} + +fn update_run(addr: &str, title_id: &str, f: impl FnOnce(&mut RestoreRun)) { + with_runs(|m| { + if let Some(r) = m.get_mut(&key(addr, title_id)) { + f(r); + r.updated_at = install::status::now_unix(); + } + }); +} + +fn get_run(addr: &str, title_id: &str) -> Option<RestoreRun> { + with_runs(|m| m.get(&key(addr, title_id)).cloned()) +} + +fn console_busy(addr: &str) -> bool { + let cid = install::console_id(addr); + with_runs(|m| { + m.values() + .any(|r| r.active() && install::console_id(&r.addr) == cid) + }) +} + +fn fail(status: StatusCode, error: impl Into<String>) -> Response { + ( + status, + Json(serde_json::json!({"ok": false, "error": error.into()})), + ) + .into_response() +} + +/// The HTTP status for a helper call that failed. +fn helper_failure(e: &anyhow::Error) -> Response { + let text = format!("{e:#}"); + let status = if text.starts_with("restore_invalid_title") { + StatusCode::BAD_REQUEST + } else if text.starts_with(tr::UNSUPPORTED) { + StatusCode::CONFLICT + } else { + StatusCode::BAD_GATEWAY + }; + fail(status, text) +} + +fn normalized_id(title_id: &str) -> Option<String> { + let id = title_id.trim().to_ascii_uppercase(); + tr::valid_title_id(&id).then_some(id) +} + +#[derive(Debug, Deserialize)] +pub struct RestoreQuery { + #[serde(alias = "console", alias = "host", alias = "ps5_addr")] + pub addr: String, + pub title_id: String, +} + +/// `GET /api/ps5/app/restore/check?addr=&title_id=`: whether a game installed from a package can +/// be put back on the home screen, read-only. The helper's answer: `state` is `restorable`, or +/// why not (`registered`: it is on the home screen; `record_elsewhere`: the console still has a +/// record of it; `not_installed`, `pending` (an earlier restore did not finish), +/// `folder_registration`, `ambiguous`, `retail`, `no_room`, `aside_cross_device`, `db_unreadable`, +/// `invalid_title`, `system_title`), with `pkg`, `size`, `where`, `kind`, `patch` and the free +/// space. A helper without the method answers 409 `restore_unsupported`. +pub async fn check_handler(Query(q): Query<RestoreQuery>) -> Response { + let Some(id) = normalized_id(&q.title_id) else { + return fail(StatusCode::BAD_REQUEST, "title_id is not a title id"); + }; + let mgmt = crate::pkg_install::normalize_mgmt_addr(&q.addr); + match tokio::task::spawn_blocking(move || tr::check(&mgmt, &id)).await { + Ok(Ok(r)) => Json(r).into_response(), + Ok(Err(e)) => helper_failure(&e), + Err(e) => fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[derive(Debug, Deserialize)] +pub struct CandidatesQuery { + #[serde(alias = "console", alias = "host", alias = "ps5_addr")] + pub addr: String, +} + +/// One game the console has a package of but no home-screen record for. +#[derive(Debug, Clone, Serialize)] +pub struct Candidate { + pub title_id: String, + pub title_name: String, + pub check: RestoreReply, +} + +/// `GET /api/ps5/app/restore/candidates?addr=`: every title with an app folder on the internal +/// drive, USB extended storage or M.2 that app.db does not list, with the helper's check of each +/// (`check.state` `restorable` can be put back; `pending` has a restore to finish). Read-only. +/// app.db must answer in full: a partial list could make a listed game look missing. +pub async fn candidates_handler(Query(q): Query<CandidatesQuery>) -> Response { + let mgmt = crate::pkg_install::normalize_mgmt_addr(&q.addr); + let r = tokio::task::spawn_blocking(move || -> anyhow::Result<Vec<Candidate>> { + let db = ps5upload_core::diagnostics::appdb_query(&mgmt)?; + if db.truncated || db.err.is_some() { + anyhow::bail!( + "app.db could not be read in full{}", + db.err.map(|e| format!(": {e}")).unwrap_or_default() + ); + } + let known: std::collections::HashSet<String> = + db.apps.iter().map(|a| a.title_id.clone()).collect(); + let mut ids: Vec<String> = Vec::new(); + for root in crate::APP_FOLDER_ROOTS { + // A drive that is not there lists nothing. + if let Ok((entries, _)) = crate::list_dir_whole(&mgmt, root) { + ids.extend( + entries + .into_iter() + .map(|e| e.name) + .filter(|n| crate::looks_like_title_id(n) && !n.starts_with("NPXS")), + ); + } + } + ids.sort(); + ids.dedup(); + ids.retain(|id| !known.contains(id) && !crate::is_console_webui_tile(id)); + let mut out = Vec::new(); + for id in ids.into_iter().take(MAX_TITLES * 2) { + let check = tr::check(&mgmt, &id)?; + if matches!(check.state.as_str(), "not_installed" | "registered") { + continue; + } + let title_name = crate::title_name(&mgmt, &id).unwrap_or_else(|| id.clone()); + out.push(Candidate { + title_id: id, + title_name, + check, + }); + } + Ok(out) + }) + .await; + match r { + Ok(Ok(list)) => Json(serde_json::json!({"ok": true, "titles": list})).into_response(), + Ok(Err(e)) => helper_failure(&e), + Err(e) => fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[derive(Debug, Deserialize)] +pub struct RestoreStart { + #[serde(alias = "console", alias = "host", alias = "ps5_addr")] + pub addr: String, + /// One title. + #[serde(default)] + pub title_id: Option<String>, + /// Several, restored one after the other ("Restore all"). + #[serde(default)] + pub title_ids: Option<Vec<String>>, +} + +/// The titles a start names, normalized and without repeats, or why not. +pub fn start_titles(req: &RestoreStart) -> Result<Vec<String>, String> { + let mut raw: Vec<String> = req.title_ids.clone().unwrap_or_default(); + if let Some(t) = &req.title_id { + raw.insert(0, t.clone()); + } + if raw.is_empty() { + return Err("title_id or title_ids is required".into()); + } + let mut out: Vec<String> = Vec::new(); + for t in raw { + let Some(id) = normalized_id(&t) else { + return Err(format!("{t:?} is not a title id")); + }; + if !out.contains(&id) { + out.push(id); + } + } + if out.len() > MAX_TITLES { + return Err(format!("at most {MAX_TITLES} titles at a time")); + } + Ok(out) +} + +/// `POST /api/ps5/app/restore {addr, title_id | title_ids}`: put games installed from a package +/// back on the home screen by installing the package already on the console again (no +/// download). The first title is checked and prepared before this answers: a refusal is 409 with +/// the helper's `restore` answer and nothing changed; another install on the console is 409 +/// `busy`. Then `{ok, job, prepared, queued}`: `job` is the first title's install +/// (`/api/pkg/install/status`); the others follow one after the other. Each title's progress: +/// `GET /api/ps5/app/restore/status`. +pub async fn start_handler( + State(state): State<PkgInstallStateHandle>, + Json(req): Json<RestoreStart>, +) -> Response { + if install::console_id(&req.addr).is_empty() { + return fail(StatusCode::BAD_REQUEST, "addr is required"); + } + let titles = match start_titles(&req) { + Ok(t) => t, + Err(e) => return fail(StatusCode::BAD_REQUEST, e), + }; + { + let ip = install::console_id(&req.addr); + let away = + tokio::task::spawn_blocking(move || ps5upload_core::route::via(&ip).is_tailnet()) + .await + .unwrap_or(false); + if away { + return ( + StatusCode::CONFLICT, + Json(serde_json::json!({ + "ok": false, + "reason": "tailnet_home_only", + "error": ps5upload_core::route::home_only("Restoring a game"), + })), + ) + .into_response(); + } + } + if console_busy(&req.addr) { + return fail( + StatusCode::CONFLICT, + "busy: a restore is already running on this console", + ); + } + let addr = req.addr.clone(); + let first = titles[0].clone(); + let (job, prepared) = match begin_one(&state, &addr, &first).await { + Ok(v) => v, + Err(resp) => return resp, + }; + for t in titles.iter().skip(1) { + set_run(RestoreRun::new(&addr, t, "queued")); + } + let queued: Vec<String> = titles.iter().skip(1).cloned().collect(); + let st = state.clone(); + let (job2, prepared2, rest) = (job.clone(), prepared.clone(), queued.clone()); + tokio::spawn(async move { + run_one(st.clone(), &addr, &first, job2, prepared2).await; + for t in rest { + // A refusal is recorded by begin_one; the next title still goes. + if let Ok((job, prepared)) = begin_one(&st, &addr, &t).await { + run_one(st.clone(), &addr, &t, job, prepared).await; + } + } + }); + Json(serde_json::json!({"ok": true, "job": job, "prepared": prepared, "queued": queued})) + .into_response() +} + +/// Check, reserve the console's install slot, prepare. On a refusal the run records why and the +/// response to send is returned. +#[allow(clippy::result_large_err)] +async fn begin_one( + state: &PkgInstallStateHandle, + addr: &str, + id: &str, +) -> Result<(String, RestoreReply), Response> { + let mgmt = crate::pkg_install::normalize_mgmt_addr(addr); + let refused = |run_phase: &str, error: String, reply: Option<RestoreReply>| { + let mut run = RestoreRun::new(addr, id, run_phase); + run.error = Some(error.clone()); + run.result = reply.clone(); + set_run(run); + ( + StatusCode::CONFLICT, + Json(serde_json::json!({"ok": false, "error": error, "restore": reply})), + ) + .into_response() + }; + // Read-only first, so a refusal never takes the install slot. + let (m, i) = (mgmt.clone(), id.to_string()); + let check = match tokio::task::spawn_blocking(move || tr::check(&m, &i)).await { + Ok(Ok(r)) => r, + Ok(Err(e)) => { + set_run({ + let mut r = RestoreRun::new(addr, id, "failed"); + r.error = Some(format!("{e:#}")); + r + }); + return Err(helper_failure(&e)); + } + Err(e) => return Err(fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), + }; + if !check.restorable() { + let state_word = check.state.clone(); + return Err(refused( + "failed", + format!("restore_{state_word}"), + Some(check), + )); + } + let job = match state.jobs.begin(addr) { + Ok(j) => j, + Err(active) => { + set_run({ + let mut r = RestoreRun::new(addr, id, "failed"); + r.error = Some(format!("busy: install {active} is running on this console")); + r + }); + return Err(( + StatusCode::CONFLICT, + Json(serde_json::json!({"ok": false, "error": "busy", "job": active})), + ) + .into_response()); + } + }; + let (m, i) = (mgmt.clone(), id.to_string()); + let prepared = match tokio::task::spawn_blocking(move || tr::prepare(&m, &i)).await { + Ok(Ok(r)) => r, + Ok(Err(e)) => { + // The helper may or may not have moved it: the next check says (`pending`). + state + .jobs + .release_unstarted(&job, "the restore could not be prepared"); + set_run({ + let mut r = RestoreRun::new(addr, id, "failed"); + r.error = Some(format!("{e:#}")); + r + }); + return Err(helper_failure(&e)); + } + Err(e) => { + state + .jobs + .release_unstarted(&job, "the restore could not be prepared"); + return Err(fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())); + } + }; + let Some(path) = prepared.install_path.clone().filter(|_| prepared.ok) else { + state + .jobs + .release_unstarted(&job, "the console refused to prepare the restore"); + let err = prepared + .err + .clone() + .unwrap_or_else(|| "restore_not_prepared".into()); + return Err(refused("failed", err, Some(prepared))); + }; + crate::log_at!( + Info, + "install", + "restore {id} on {addr}: {} moved aside to {path}; installing it (job {job})", + prepared.pkg.as_deref().unwrap_or("?") + ); + let mut run = RestoreRun::new(addr, id, "installing"); + run.job = Some(job.clone()); + run.prepared = Some(prepared.clone()); + set_run(run); + Ok((job, prepared)) +} + +/// Install the copy aside in the reserved slot, then finish by the install's verdict. +async fn run_one( + state: PkgInstallStateHandle, + addr: &str, + id: &str, + job: String, + prepared: RestoreReply, +) { + let Some(path) = prepared.install_path.clone() else { + return; + }; + let req = InstallRequest { + ps5_addr: addr.to_string(), + source: Source::ConsolePath(path), + content_id: String::new(), + title_id: Some(id.to_string()), + package_app_ver: None, + category: None, + options: InstallOptions::default(), + }; + install::run_reserved(state.clone(), job.clone(), req).await; + let st = state.jobs.get(&job); + let decision = after_install(st.as_ref()); + update_run(addr, id, |r| { + r.phase = "finishing".into(); + r.install_verdict = st.as_ref().and_then(|s| s.verdict); + r.install_hint = st.as_ref().and_then(|s| s.hint.clone()); + }); + let mgmt = crate::pkg_install::normalize_mgmt_addr(addr); + let mut result: anyhow::Result<RestoreReply> = Err(anyhow::anyhow!("not asked")); + match decision { + AfterInstall::Finish => { + for _ in 0..SETTLE_TRIES { + let (m, i) = (mgmt.clone(), id.to_string()); + result = tokio::task::spawn_blocking(move || tr::finish(&m, &i, false, true)) + .await + .map_err(anyhow::Error::from) + .and_then(|r| r); + let waiting = matches!(&result, Ok(r) if r.state == "waiting"); + if !waiting { + break; + } + tokio::time::sleep(SETTLE_EVERY).await; + } + } + AfterInstall::Rollback => { + let (m, i) = (mgmt.clone(), id.to_string()); + result = tokio::task::spawn_blocking(move || tr::finish(&m, &i, true, true)) + .await + .map_err(anyhow::Error::from) + .and_then(|r| r); + } + AfterInstall::Leave => { + // Only reads where it stands: with neither flag the helper touches nothing. + let (m, i) = (mgmt.clone(), id.to_string()); + result = tokio::task::spawn_blocking(move || tr::finish(&m, &i, false, false)) + .await + .map_err(anyhow::Error::from) + .and_then(|r| r); + } + } + let phase = match &result { + Ok(r) if r.state == "restored" => "restored", + Ok(r) if r.state == "rolled_back" => "rolled_back", + _ => "pending", + }; + crate::log_at!( + Info, + "install", + "restore {id} on {addr}: install {:?}, {decision:?}: {phase} ({})", + st.as_ref().and_then(|s| s.verdict), + match &result { + Ok(r) => format!("{} {}", r.state, r.reason.as_deref().unwrap_or("")), + Err(e) => format!("{e:#}"), + } + ); + update_run(addr, id, |r| { + r.phase = phase.into(); + match result { + Ok(reply) => r.result = Some(reply), + Err(e) => r.error = Some(format!("{e:#}")), + } + }); +} + +/// `GET /api/ps5/app/restore/status?addr=&title_id=`: how this engine's restore of a title stands. +/// `phase`: `queued`, `installing` (with `job`, the install's id for `/api/pkg/install/status`; +/// `install` is that status), `finishing`, `restored`, `rolled_back` (the install did not take, the +/// package is back where it was), `pending` (the console may still be working on it, or the +/// database did not list the game in time: nothing was deleted; finish it later), `failed` +/// (refused before anything moved: `error`, and the helper's `result`). 404 when this engine ran +/// none (after a restart: the check's `pending` state says an unfinished one is on the console). +pub async fn status_handler( + State(state): State<PkgInstallStateHandle>, + Query(q): Query<RestoreQuery>, +) -> Response { + let Some(id) = normalized_id(&q.title_id) else { + return fail(StatusCode::BAD_REQUEST, "title_id is not a title id"); + }; + match get_run(&q.addr, &id) { + Some(run) => { + let install = run.job.as_deref().and_then(|j| state.jobs.get(j)); + let mut v = serde_json::to_value(&run).unwrap_or_default(); + v["ok"] = serde_json::Value::Bool(true); + if let Some(st) = install { + v["install"] = serde_json::to_value(st).unwrap_or_default(); + } + Json(v).into_response() + } + None => fail( + StatusCode::NOT_FOUND, + "no restore of that title is known to this engine", + ), + } +} + +#[derive(Debug, Deserialize)] +pub struct RestoreFinish { + #[serde(alias = "console", alias = "host", alias = "ps5_addr")] + pub addr: String, + pub title_id: String, + /// Put the package and its update back where they were (when the game is not on the home + /// screen). Only once nothing installs on the console. + #[serde(default)] + pub rollback: bool, + /// The install has ended (the user saw the game on the home screen): the copy aside may go. + #[serde(default)] + pub install_ended: bool, +} + +/// `POST /api/ps5/app/restore/finish {addr, title_id, rollback, install_ended}`: finish a restore +/// left `pending` (an engine restart, a slow database). With `install_ended` the copy aside is +/// deleted once app.db lists the game and a package is in place; with `rollback` the package and +/// update go back where they were, only while app.db does not list the game and the place is +/// free; with neither, nothing changes and the answer says where it stands. Refused (409 `busy`) +/// while an install or a restore runs on that console. The helper's `finish` answer. +pub async fn finish_handler( + State(state): State<PkgInstallStateHandle>, + Json(req): Json<RestoreFinish>, +) -> Response { + let Some(id) = normalized_id(&req.title_id) else { + return fail(StatusCode::BAD_REQUEST, "title_id is not a title id"); + }; + if install::console_id(&req.addr).is_empty() { + return fail(StatusCode::BAD_REQUEST, "addr is required"); + } + if state.jobs.active_for(&req.addr) || console_busy(&req.addr) { + return fail( + StatusCode::CONFLICT, + "busy: an install is running on this console; finish the restore after it ends", + ); + } + let mgmt = crate::pkg_install::normalize_mgmt_addr(&req.addr); + let (i, rollback, ended) = (id.clone(), req.rollback, req.install_ended); + match tokio::task::spawn_blocking(move || tr::finish(&mgmt, &i, rollback, ended)).await { + Ok(Ok(r)) => { + let phase = match r.state.as_str() { + "restored" => Some("restored"), + "rolled_back" => Some("rolled_back"), + "nothing_pending" => None, + _ => Some("pending"), + }; + if let Some(phase) = phase { + let mut run = get_run(&req.addr, &id) + .unwrap_or_else(|| RestoreRun::new(&req.addr, &id, phase)); + run.phase = phase.into(); + run.result = Some(r.clone()); + set_run(run); + } + Json(r).into_response() + } + Ok(Err(e)) => helper_failure(&e), + Err(e) => fail(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn status(phase: Phase, verdict: Option<Verdict>, reason: Option<FailReason>) -> InstallStatus { + let mut st = InstallStatus::new("j", "192.168.1.2", ""); + st.phase = phase; + st.verdict = verdict; + st.reason = reason; + st + } + + #[test] + fn only_an_install_the_console_never_took_is_put_back() { + assert_eq!(after_install(None), AfterInstall::Leave); + assert_eq!( + after_install(Some(&status(Phase::Done, Some(Verdict::Installed), None))), + AfterInstall::Finish + ); + assert_eq!( + after_install(Some(&status( + Phase::Done, + Some(Verdict::MayNotLaunch), + None + ))), + AfterInstall::Finish + ); + assert_eq!( + after_install(Some(&status(Phase::Done, Some(Verdict::Unverified), None))), + AfterInstall::Leave + ); + for r in [ + FailReason::SonyRefused, + FailReason::StreamUnreachable, + FailReason::StagedRefused, + FailReason::BadRequest, + FailReason::Busy, + ] { + assert_eq!( + after_install(Some(&status(Phase::Failed, Some(Verdict::Failed), Some(r)))), + AfterInstall::Rollback, + "{r:?}" + ); + } + for r in [ + FailReason::Stalled, + FailReason::Cancelled, + FailReason::ReplyLost, + ] { + assert_eq!( + after_install(Some(&status(Phase::Failed, Some(Verdict::Failed), Some(r)))), + AfterInstall::Leave, + "{r:?}" + ); + } + // Still running: never acted on. + assert_eq!( + after_install(Some(&status(Phase::Deliver, None, None))), + AfterInstall::Leave + ); + } + + #[test] + fn start_names_titles_once_and_checks_them() { + let req = |one: Option<&str>, many: Option<Vec<&str>>| RestoreStart { + addr: "192.168.1.2".into(), + title_id: one.map(str::to_string), + title_ids: many.map(|v| v.into_iter().map(str::to_string).collect()), + }; + assert_eq!( + start_titles(&req(Some("ppsa01234"), None)).unwrap(), + vec!["PPSA01234"] + ); + assert_eq!( + start_titles(&req( + Some("PPSA01234"), + Some(vec!["CUSA00900", "ppsa01234"]) + )) + .unwrap(), + vec!["PPSA01234", "CUSA00900"] + ); + assert!(start_titles(&req(None, None)).is_err()); + assert!(start_titles(&req(Some("../x"), None)).is_err()); + let many: Vec<String> = (0..=MAX_TITLES).map(|i| format!("PPSA{i:05}")).collect(); + let r = RestoreStart { + addr: "x".into(), + title_id: None, + title_ids: Some(many), + }; + assert!(start_titles(&r).is_err()); + } + + #[test] + fn runs_are_kept_per_console_and_title() { + let a = "10.9.8.7:8000"; + set_run(RestoreRun::new(a, "PPSA77777", "installing")); + assert!(console_busy("10.9.8.7")); + assert!(!console_busy("10.9.8.6")); + update_run("10.9.8.7", "PPSA77777", |r| r.phase = "restored".into()); + assert_eq!(get_run(a, "PPSA77777").unwrap().phase, "restored"); + assert!(!console_busy(a)); + with_runs(|m| m.remove(&key(a, "PPSA77777"))); + } +} diff --git a/payload/Makefile b/payload/Makefile index 105091e10..0fc139f04 100644 --- a/payload/Makefile +++ b/payload/Makefile @@ -259,7 +259,7 @@ SRCS := src/main.c src/runtime.c src/shell_builtin.c src/takeover.c src/takeover src/pkg_info.c src/webui_pkg.c $(WEBUI_INSTALLER_C) \ src/webui_smb.c src/smb_shares.c src/smb_client.c smb/smbd_json.c smb/smbd_path.c $(SMBD_ELF_C) \ src/tailnet_node.c \ - src/save_sfo.c src/save_owner.c src/trophy_fix.c \ + src/save_sfo.c src/save_owner.c src/trophy_fix.c src/title_restore.c \ src/helper_uninstall.c \ src/file_compare.c \ $(WEBUI_PAGE_C) $(WEBUI_STRINGS_C) $(WEBUI_OFFLINE_C) \ diff --git a/payload/extractor/Makefile b/payload/extractor/Makefile index 77064e371..92e0bd23a 100644 --- a/payload/extractor/Makefile +++ b/payload/extractor/Makefile @@ -61,7 +61,7 @@ LIBARCHIVE_C := archive_acl.c archive_entry_sparse.c archive_entry_xattr.c archi archive_read_support_format_rar.c archive_read_support_format_rar5.c archive_string.c archive_string_sprintf.c \ archive_time.c archive_util.c archive_virtual.c -OWN_C := src/xmain.c src/xsink.c src/xrun.c src/xreq.c src/xrar.c +OWN_C := src/xmain.c src/xsink.c src/xrun.c src/xreq.c src/xrar.c src/xrarc.c src/xrcrypt.c OWN_CPP := src/x7z.cpp src/xguids.cpp # Z7_ST: single-threaded (bounded memory, no MT decoders). Z7_EXTRACT_ONLY: no update side. diff --git a/payload/extractor/README.md b/payload/extractor/README.md index b688e3375..7a7775bcd 100644 --- a/payload/extractor/README.md +++ b/payload/extractor/README.md @@ -59,8 +59,20 @@ into an existing folder, the files already written stay. 7z AES, zip AES and ZipCrypto passwords. - libarchive 3.8.10, RAR readers only (`../third_party/libarchive`, BSD-2): RAR 1.5–4 and RAR5, single and multi-volume. 7-Zip's own RAR decoders come from UnRAR, whose license this GPL build - cannot take (see `LICENSES/UnRAR-exception.md`). libarchive cannot decrypt RAR, so a - password-protected RAR is refused with `fs_extract_rar_encrypted` and the apps say so. + cannot take (see `LICENSES/UnRAR-exception.md`). +- Password-protected RAR (#958): libarchive cannot decrypt RAR, so `src/xrarc.c` reads the + volumes and hands libarchive the same archive decrypted, as a stream: encrypted headers + (`-hp`) and file data, RAR 3/4 (AES-128) and RAR5 (AES-256), split across volumes or not. + `src/xrcrypt.c` has the key derivations (RAR 3's SHA-1 rounds, RAR5's PBKDF2-HMAC-SHA256) on + 7-Zip's AES and SHA-256; written from the format, not from UnRAR. Nothing decrypted is written + anywhere but the extracted files. A missing or wrong password is found before anything is + made (`fs_extract_password_required`, `fs_extract_wrong_password`), except for RAR 3/4 with + only the data encrypted, which has no password check: its first file fails its CRC and is + dropped. RAR5 keys the checksums of encrypted files with the password; libarchive cannot check + those, so `xrar.c` checks each file as it is written. RAR 1.5/2.0's own encryption is refused + (`fs_extract_unsupported_method`). An archive whose first volume shows no encryption is read by + libarchive directly, as before; one that starts encrypting after its first 4096 headers is + still refused with `fs_extract_rar_encrypted`. ## Building and testing @@ -71,5 +83,7 @@ make -C payload/extractor host-test # host build + tests/run.py (python3; 7zz o `tests/run.py` covers name traversal, links (in the archive and already in the destination), multi-volume sets (7z, RAR4, RAR5) and a missing volume, passwords (7z with and without header -encryption, zip AES, ZipCrypto, a non-ASCII password), encrypted RAR, truncated and damaged -archives, out of space before and while writing, conflicts and Stop. +encryption, zip AES, ZipCrypto, a non-ASCII password), password-protected RAR (RAR 3/4 and RAR5: +data or headers encrypted, stored, BLAKE2, multi-part, solid multi-part, wrong and missing +passwords, listing, a missing volume, damage; fixtures from `tests/make_encrypted_rar.py`), +truncated and damaged archives, out of space before and while writing, conflicts and Stop. diff --git a/payload/extractor/src/xrar.c b/payload/extractor/src/xrar.c index ef3b0849e..913727c6c 100644 --- a/payload/extractor/src/xrar.c +++ b/payload/extractor/src/xrar.c @@ -3,8 +3,9 @@ * Why not 7-Zip's RAR decoders, which the rest of the extractor uses: those are derived from the * UnRAR source, whose license adds a restriction the GPL does not allow, and this ELF also links * GPL-3.0 code that is not ours to relicense (the payload SDK's startup code). libarchive's RAR and - * RAR5 readers are independent implementations under the BSD license. They do not decrypt: an - * encrypted RAR is refused with fs_extract_rar_encrypted, which the apps explain. + * RAR5 readers are independent implementations under the BSD license. They do not decrypt, so a + * password-protected RAR (RAR 3/4 or RAR5, data or headers encrypted) is read through xrarc.c, which + * hands libarchive the archive decrypted. Only RAR 1.5/2.0's own encryption is refused. * * Progress is in archive bytes read. Free space is checked per file from its header, and, for an * archive that is not solid, for all of it before anything is written (#869: a 150 GB set ran for @@ -19,9 +20,13 @@ #include <string.h> #include <sys/stat.h> +#include "../C/7zCrc.h" #include "archive.h" +#include "archive_blake2.h" #include "archive_entry.h" #include "archive_name.h" +#include "xrarc.h" +#include "xrcrypt.h" #define XRAR_BLOCK (256u << 10) @@ -53,6 +58,27 @@ static int rar_fail(xjob_t *j, struct archive *a, const xrar_vols_t *v) { return xj_fail(j, "fs_extract_corrupt: %s", msg); } +/* A failure while reading through xrarc: its own cause first; then, for an encrypted file whose + * password nothing confirmed (RAR 3/4 with only the data encrypted), damaged data is the wrong + * password; else as rar_fail. */ +static int xrc_fail(xjob_t *j, struct archive *a, const xrar_vols_t *v, const xrarc_t *xt, const xrarc_ent_t *ent) { + const char *next = strrchr(v->next, '/'); + if (xj_failed(j)) return -1; + switch (xt ? xrarc_error(xt) : XRC_OK) { + case XRC_OK: break; + case XRC_E_PASSWORD_REQUIRED: return xj_fail(j, "fs_extract_password_required"); + case XRC_E_WRONG_PASSWORD: return xj_fail(j, "fs_extract_wrong_password"); + case XRC_E_MISSING_VOLUME: return xj_fail(j, "fs_extract_missing_volume: %s", next ? next + 1 : v->next); + case XRC_E_TRUNCATED: return xj_fail(j, "fs_extract_truncated"); + case XRC_E_UNSUPPORTED: return xj_fail(j, "fs_extract_unsupported_method: RAR 1.5/2.0 encryption"); + case XRC_E_NOMEM: return xj_fail(j, "fs_extract_no_memory"); + case XRC_E_OPEN: return xj_fail(j, "fs_extract_open_failed"); + default: return xj_fail(j, "fs_extract_corrupt: %s", archive_error_string(a) ? archive_error_string(a) : ""); + } + if (xt && ent && ent->encrypted && !xrarc_confirmed(xt)) return xj_fail(j, "fs_extract_wrong_password"); + return rar_fail(j, a, v); +} + static uint64_t vint(const unsigned char *p, size_t n, size_t *at, int *ok) { uint64_t v = 0; for (int shift = 0; shift < 64 && *at < n; shift += 7) { @@ -95,22 +121,36 @@ static int xrar_solid(const unsigned char *p, size_t n) { /* The unpacked size of every file in a set that is not solid, or 0 when it is not known: a solid * or unreadable archive, a file without a size, a cancel. Never sets the job's cause: whatever is * wrong with the archive, the extraction itself says so. */ -static uint64_t rar_total(xjob_t *j, char **vols) { - unsigned char head[64]; +static uint64_t rar_total(xjob_t *j, char **vols, const xrarc_t *enc) { struct archive *a; struct archive_entry *ae; + xrarc_t *xt = NULL; uint64_t total = 0; - size_t n; - FILE *f = fopen(vols[0], "rb"); - if (!f) return 0; - n = fread(head, 1, sizeof head, f); - fclose(f); - if (xrar_solid(head, n) != 0) return 0; + if (enc) { + /* Encrypted: the main header (solid or not) was read through xrarc, and the headers are + * read through a second one (the keys are cached; data is skipped, not decrypted). */ + int err; + if (xrarc_solid(enc) != 0) return 0; + xt = xrarc_open(vols, j->has_password ? j->password : NULL, &err); + if (!xt) return 0; + } else { + unsigned char head[64]; + size_t n; + FILE *f = fopen(vols[0], "rb"); + if (!f) return 0; + n = fread(head, 1, sizeof head, f); + fclose(f); + if (xrar_solid(head, n) != 0) return 0; + } a = archive_read_new(); - if (!a) return 0; + if (!a) { + xrarc_close(xt); + return 0; + } archive_read_support_format_rar(a); archive_read_support_format_rar5(a); - if (archive_read_open_filenames(a, (const char **)vols, XRAR_BLOCK) != ARCHIVE_OK) goto unknown; + if ((xt ? xrarc_attach(xt, a) : archive_read_open_filenames(a, (const char **)vols, XRAR_BLOCK)) != ARCHIVE_OK) + goto unknown; for (;;) { int r = archive_read_next_header(a, &ae); if (r == ARCHIVE_EOF) break; @@ -124,10 +164,12 @@ static uint64_t rar_total(xjob_t *j, char **vols) { } archive_read_close(a); archive_read_free(a); + xrarc_close(xt); return total; unknown: archive_read_close(a); archive_read_free(a); + xrarc_close(xt); return 0; } @@ -140,13 +182,68 @@ static int kind_of(struct archive_entry *e) { } } + +/* The checksum of an encrypted file the caller checks (xrarc.h), taken as it is written: only the + * kind the archive holds when that is known already (a split file's last part is read later). */ +typedef struct { + int on, crc_on, blake_on; + uint32_t crc; + blake2sp_state blake; +} xsum_t; + +static void sum_start(xsum_t *s, const xrarc_ent_t *ent) { + s->on = ent && ent->check; + s->crc_on = s->on && (!ent->complete || ent->have_crc); + s->blake_on = s->on && (!ent->complete || ent->have_blake); + s->crc = CRC_INIT_VAL; + if (s->blake_on) blake2sp_init(&s->blake, 32); +} + +static void sum_add(xsum_t *s, const void *p, size_t n) { + if (s->crc_on) s->crc = CrcUpdate(s->crc, p, n); + if (s->blake_on) blake2sp_update(&s->blake, p, n); +} + +/* 0 when the file matches (or there is nothing to check), else -1 with the cause set. */ +static int sum_check(xjob_t *j, xsum_t *s, const xrarc_ent_t *ent, const xrarc_t *xt) { + int ok = 1; + if (!s->on) return 0; + if (!ent->complete) return xj_fail(j, "fs_extract_corrupt: no checksum"); + if (ent->have_crc && s->crc_on) + ok = (ent->keyed ? xrc_mac_crc(ent->hashkey, CRC_GET_DIGEST(s->crc)) : CRC_GET_DIGEST(s->crc)) == ent->crc; + if (ok && ent->have_blake && s->blake_on) { + uint8_t d[32], m[32]; + blake2sp_final(&s->blake, d, 32); + xrc_mac_blake(ent->hashkey, d, m); + ok = memcmp(m, ent->blake, 32) == 0; + } + if (ok) return 0; + if (!xrarc_confirmed(xt)) return xj_fail(j, "fs_extract_wrong_password"); + return xj_fail(j, "fs_extract_corrupt: checksum"); +} + +/* xrarc_open's failures that end the extraction (the rest go to libarchive, which names them). */ +static int open_fail(xjob_t *j, int err, const xrar_vols_t *v) { + const char *next = strrchr(v->next, '/'); + switch (err) { + case XRC_E_PASSWORD_REQUIRED: return xj_fail(j, "fs_extract_password_required"); + case XRC_E_WRONG_PASSWORD: return xj_fail(j, "fs_extract_wrong_password"); + case XRC_E_MISSING_VOLUME: return xj_fail(j, "fs_extract_missing_volume: %s", next ? next + 1 : v->next); + case XRC_E_UNSUPPORTED: return xj_fail(j, "fs_extract_unsupported_method: RAR 1.5/2.0 encryption"); + case XRC_E_NOMEM: return xj_fail(j, "fs_extract_no_memory"); + default: return 0; + } +} + int xrar_extract(xjob_t *j) { char **vols = xj_rar_volumes(j->archive); struct archive *a = NULL; struct archive_entry *ae; + xrarc_t *xt = NULL; + xrarc_ent_t *ent = NULL; xrar_vols_t vi; size_t at, len; - int rc = -1, opened_dest = 0; + int rc = -1, opened_dest = 0, err; if (!vols) return xj_fail(j, "fs_extract_no_memory"); memset(&vi, 0, sizeof vi); for (char **v = vols; *v; v++) { @@ -157,37 +254,67 @@ int xrar_extract(xjob_t *j) { } vi.is_set = vi.count > 1 || archive_rar_part(j->archive, &at, &len); if (xj_rar_volume_name(j->archive, (unsigned)vi.count, vi.next, sizeof vi.next) != 0) vi.next[0] = 0; + /* Encrypted (the headers, or the first file's data): read through xrarc. A missing or wrong + * password shows here, before anything is made. */ + xt = xrarc_open(vols, j->has_password ? j->password : NULL, &err); + if (!xt) { + if (open_fail(j, err, &vi) != 0) goto out; + } else if (!xrarc_encrypted(xt)) { + xrarc_close(xt); + xt = NULL; + } else if (!j->has_password && !j->list) { + xj_fail(j, "fs_extract_password_required"); + goto out; + } /* All of it has to fit, before the folder is made (a merge may skip files it already has, so * it keeps the per-file check only). */ - if (vi.count && !j->merge) { - uint64_t total = rar_total(j, vols); - if (total && xs_check_space(j, total) != 0) { - xj_free_list(vols); - return -1; - } + if (vi.count && !j->merge && !j->list) { + uint64_t total = rar_total(j, vols, xt); + if (total && xs_check_space(j, total) != 0) goto out; } a = archive_read_new(); if (!a) { - xj_free_list(vols); - return xj_fail(j, "fs_extract_no_memory"); + xj_fail(j, "fs_extract_no_memory"); + goto out; } archive_read_support_format_rar(a); archive_read_support_format_rar5(a); - if (archive_read_open_filenames(a, (const char **)vols, XRAR_BLOCK) != ARCHIVE_OK) { - rar_fail(j, a, &vi); + if ((xt ? xrarc_attach(xt, a) : archive_read_open_filenames(a, (const char **)vols, XRAR_BLOCK)) != ARCHIVE_OK) { + xrc_fail(j, a, &vi, xt, NULL); goto out; } for (;;) { - int r = archive_read_next_header(a, &ae); + int r; + xsum_t sum; + xrarc_release(xt, ent); + ent = NULL; + r = archive_read_next_header(a, &ae); + if (r == ARCHIVE_EOF && xt && xrarc_error(xt)) { + /* libarchive takes a failed read where a header starts for the end. */ + xrc_fail(j, a, &vi, xt, NULL); + goto out; + } if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK && r != ARCHIVE_WARN) { /* No reader took it: not a RAR at all. */ const char *msg = archive_error_string(a); if (!opened_dest && msg && strstr(msg, "Unrecognized")) xj_fail(j, "fs_extract_not_archive"); - rar_fail(j, a, &vi); + xrc_fail(j, a, &vi, xt, NULL); goto out; } - if (archive_entry_is_encrypted(ae)) { + if (xt) { + /* xrarc's note of this file: libarchive returns them in the same order. */ + ent = xrarc_take(xt); + if (!ent) { + xj_fail(j, "fs_extract_corrupt: entries"); + goto out; + } + if (ent->encrypted && !j->has_password && !j->list) { + xj_fail(j, "fs_extract_password_required"); + goto out; + } + } else if (archive_entry_is_encrypted(ae)) { + /* Encryption that starts after the first file: not read through xrarc. */ xj_fail(j, "fs_extract_rar_encrypted"); goto out; } @@ -211,12 +338,14 @@ int xrar_extract(xjob_t *j) { if (b == XS_FAIL) goto out; if (b == XS_SKIP) { if (archive_read_data_skip(a) != ARCHIVE_OK) { - rar_fail(j, a, &vi); + xrc_fail(j, a, &vi, xt, ent); goto out; } j->bytes_done = (uint64_t)archive_filter_bytes(a, -1); + if (j->bytes_done > j->bytes_total) j->bytes_done = j->bytes_total; continue; } + sum_start(&sum, ent); for (;;) { const void *buf; size_t len; @@ -224,7 +353,7 @@ int xrar_extract(xjob_t *j) { r = archive_read_data_block(a, &buf, &len, &off); if (r == ARCHIVE_EOF) break; if (r != ARCHIVE_OK && r != ARCHIVE_WARN) { - rar_fail(j, a, &vi); + xrc_fail(j, a, &vi, xt, ent); xs_end(j, &e, 0); goto out; } @@ -232,16 +361,24 @@ int xrar_extract(xjob_t *j) { while ((uint64_t)off > e.written) { static const char zeros[4096]; uint64_t gap = (uint64_t)off - e.written; - if (xs_write(j, &e, zeros, gap < sizeof zeros ? (size_t)gap : sizeof zeros) != 0) { + size_t step = gap < sizeof zeros ? (size_t)gap : sizeof zeros; + if (xs_write(j, &e, zeros, step) != 0) { xs_end(j, &e, 0); goto out; } + sum_add(&sum, zeros, step); } if (len && xs_write(j, &e, buf, len) != 0) { xs_end(j, &e, 0); goto out; } + sum_add(&sum, buf, len); j->bytes_done = (uint64_t)archive_filter_bytes(a, -1); + if (j->bytes_done > j->bytes_total) j->bytes_done = j->bytes_total; + } + if (sum_check(j, &sum, ent, xt) != 0) { + xs_end(j, &e, 0); + goto out; } if (xs_end(j, &e, 1) != 0) goto out; } @@ -257,6 +394,10 @@ int xrar_extract(xjob_t *j) { archive_read_close(a); archive_read_free(a); } + if (xt) { + xrarc_release(xt, ent); + xrarc_close(xt); + } xj_free_list(vols); if (rc != 0 && !xj_failed(j)) xj_fail(j, "fs_extract_corrupt"); return rc; diff --git a/payload/extractor/src/xrarc.c b/payload/extractor/src/xrarc.c new file mode 100644 index 000000000..d8382b712 --- /dev/null +++ b/payload/extractor/src/xrarc.c @@ -0,0 +1,1115 @@ +/* Password-protected RAR as a plain RAR stream for libarchive (see xrarc.h). + * + * The stream is built as a queue of segments, one header at a time, as libarchive asks for more: + * MEM bytes held here (a header that was decrypted or changed); + * RAW a range of a volume, as it is (a header left alone, data that is not encrypted); + * DEC a range of a volume holding encrypted file data, decrypted on the way. + * Lengths do not change except in headers: AES-CBC keeps the data's size, so every size in the + * headers stays true. Encrypted data is padded to whole 16-byte blocks: at the end of a stored + * (uncompressed) file the padding is cut off and the header's size lowered to match; an empty + * file's one block of padding is dropped and the file marked stored; after a compressed file it is + * left, and libarchive's RAR5 reader ends the file at its last block (a PS5Upload change there; the + * RAR 3/4 reader already does). + * + * A file's encrypted data is one AES-CBC stream even when it is split over volumes, and the split + * falls anywhere, not on a 16-byte block. A block that straddles two volumes is decrypted when the + * first volume's part ends, with the bytes it needs read ahead from the next part (whose headers are + * read then); its plaintext tail is handed out at the start of that next part. + * + * The format, as the parts used here: RAR5 (rar 5.0+): a header is CRC32, size (vint), type, flags, + * [extra size], [data size], fields, extra records. With encrypted headers, an encryption header + * (type 4: version, flags, KDF count, salt, check value) follows the signature, and every later + * header is a 16-byte IV then the header encrypted with AES-256-CBC, padded to 16. A file's data is + * encrypted when its header has an encryption record (extra type 1: version, flags, KDF count, salt, + * IV, check value). RAR 3/4: a block is CRC16, type, flags, size [, data size]; a file block with + * flag 0x04 has its data encrypted with AES-128-CBC (key and IV from the password and the block's + * salt); a main block with flag 0x80 means every later block is an 8-byte salt then the block + * encrypted the same way, padded to 16. */ +#include "xrarc.h" + +#include <errno.h> +#include <fcntl.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +#include "../C/7zCrc.h" +#include "xrcrypt.h" + +#define BUF_SIZE (256u << 10) +#define HDR_MAX (2u << 20) /* RAR5's largest header; RAR 3/4 headers are under 64 KiB */ +#define SFX_SCAN (4u << 20) +#define OPEN_SCAN_MAX 4096 +/* An extra record type no reader knows, written over the encryption record's type (libarchive skips + * records it does not know). */ +#define NEUTRAL_TYPE 0x7f + +enum { SEG_MEM, SEG_RAW, SEG_DEC }; + +typedef struct fstream { + xrc_aes_t aes; /* first: aligned (the struct is allocated aligned) */ + int refs; + uint64_t packed; /* bytes of data in the parts before this one */ + xrarc_ent_t *ent; + void *raw; /* the allocation */ +} fstream_t; + +typedef struct { + int kind; + unsigned vol; + uint64_t off, len; /* RAW, DEC: in the volume; MEM: len */ + uint64_t out_len; /* bytes handed out: len, less the cut padding (DEC) */ + uint8_t *mem; + fstream_t *fs; + int last; /* DEC: the file's last part */ + uint64_t skip; /* DEC: bytes at its start already decrypted (read ahead) ... */ + uint8_t pend[16]; /* ... and their plaintext, handed out first */ + unsigned pend_n; +} seg_t; + +struct xrarc { + char **vols; + size_t nvols; + const char *pw; + int fmt; /* 4 or 5 */ + int err; + int any_enc, confirmed, solid; + int hdr_ok; /* an encrypted header decrypted with a good checksum */ + + /* Reading the headers. */ + unsigned scan_vol; + int vol_open; /* the signature of scan_vol was handled */ + int hdr_enc; /* this volume's headers are encrypted */ + uint8_t hkey[32]; /* RAR5: their key */ + uint64_t scan_pos, scan_size; + int scan_done; + fstream_t *split_fs; /* the encrypted file that goes on in the next volume */ + + seg_t *segs; + size_t nseg, cap, at; /* `at`: the one being handed out */ + uint64_t pos, outp; /* in segs[at]: input (bytes of it read) and output so far */ + int pend_done; + + xrarc_ent_t *q_head, *q_tail; + + int fd[2]; + unsigned fd_vol[2]; + unsigned fd_next; + + uint8_t *buf, *hb; /* aligned: BUF_SIZE, HDR_MAX + 64 */ + void *buf_raw, *hb_raw; +}; + +/* ---- small helpers ---- */ + +static void *amalloc(size_t n, void **raw) { + uint8_t *p = malloc(n + 16); + if (!p) return NULL; + *raw = p; + return (void *)(((uintptr_t)p + 15) & ~(uintptr_t)15); +} + +static int fail(xrarc_t *t, int e) { + if (!t->err) t->err = e; + return -1; +} + +static uint16_t le16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); } +static uint32_t le32(const uint8_t *p) { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +static void put16(uint8_t *p, uint32_t v) { + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); +} +static void put32(uint8_t *p, uint32_t v) { + put16(p, v); + put16(p + 2, v >> 16); +} + +static int vget(const uint8_t *p, size_t n, size_t *at, uint64_t *v) { + uint64_t r = 0; + for (unsigned sh = 0; sh < 70 && *at < n; sh += 7) { + uint8_t c = p[(*at)++]; + if (sh < 64) r |= (uint64_t)(c & 0x7f) << sh; + if (!(c & 0x80)) { + *v = r; + return 0; + } + } + return -1; +} + +static size_t vput(uint8_t *p, uint64_t v) { + size_t n = 0; + do { + uint8_t b = (uint8_t)(v & 0x7f); + v >>= 7; + p[n++] = (uint8_t)(b | (v ? 0x80 : 0)); + } while (v); + return n; +} + +static int vol_fd(xrarc_t *t, unsigned v) { + for (unsigned i = 0; i < 2; i++) + if (t->fd[i] >= 0 && t->fd_vol[i] == v) return t->fd[i]; + { + unsigned i = t->fd_next++ % 2; + if (t->fd[i] >= 0) close(t->fd[i]); + t->fd[i] = open(t->vols[v], O_RDONLY); + t->fd_vol[i] = v; + if (t->fd[i] < 0) fail(t, XRC_E_OPEN); + return t->fd[i]; + } +} + +/* Exactly `n` bytes at `off` of volume `v`, else -1 (truncated, or a read error). */ +static int rd(xrarc_t *t, unsigned v, uint64_t off, void *dst, size_t n) { + int fd = vol_fd(t, v); + uint8_t *d = dst; + if (fd < 0) return -1; + while (n) { + ssize_t r = pread(fd, d, n, (off_t)off); + if (r < 0 && errno == EINTR) continue; + if (r < 0) return fail(t, XRC_E_OPEN); + if (r == 0) return fail(t, XRC_E_TRUNCATED); + d += r; + off += (uint64_t)r; + n -= (size_t)r; + } + return 0; +} + +/* ---- entries and file streams ---- */ + +void xrarc_release(xrarc_t *t, xrarc_ent_t *e) { + (void)t; + if (e && --e->refs <= 0) { + xrc_wipe(e, sizeof *e); + free(e); + } +} + +xrarc_ent_t *xrarc_take(xrarc_t *t) { + xrarc_ent_t *e = t->q_head; + if (!e) return NULL; + t->q_head = e->next; + if (!t->q_head) t->q_tail = NULL; + e->next = NULL; + return e; +} + +static void fs_unref(xrarc_t *t, fstream_t *fs) { + if (fs && --fs->refs <= 0) { + void *raw = fs->raw; + xrarc_release(t, fs->ent); + xrc_wipe(fs, sizeof *fs); + free(raw); + } +} + +static fstream_t *fs_new(xrarc_t *t) { + void *raw; + fstream_t *fs = amalloc(sizeof *fs, &raw); + if (!fs) { + fail(t, XRC_E_NOMEM); + return NULL; + } + memset(fs, 0, sizeof *fs); + fs->raw = raw; + return fs; +} + +/* ---- segments ---- */ + +static seg_t *seg_add(xrarc_t *t, int kind) { + seg_t *s; + if (t->nseg == t->cap) { + size_t nc = t->cap ? t->cap * 2 : 64; + seg_t *g = realloc(t->segs, nc * sizeof *g); + if (!g) { + fail(t, XRC_E_NOMEM); + return NULL; + } + t->segs = g; + t->cap = nc; + } + s = &t->segs[t->nseg++]; + memset(s, 0, sizeof *s); + s->kind = kind; + return s; +} + +static int add_mem(xrarc_t *t, const uint8_t *p, size_t n) { + seg_t *s; + uint8_t *m = malloc(n ? n : 1); + if (!m) return fail(t, XRC_E_NOMEM); + memcpy(m, p, n); + s = seg_add(t, SEG_MEM); + if (!s) { + free(m); + return -1; + } + s->mem = m; + s->len = s->out_len = n; + return 0; +} + +static int add_raw(xrarc_t *t, unsigned vol, uint64_t off, uint64_t len) { + seg_t *s; + if (!len) return 0; + s = seg_add(t, SEG_RAW); + if (!s) return -1; + s->vol = vol; + s->off = off; + s->len = s->out_len = len; + return 0; +} + +static int add_dec(xrarc_t *t, unsigned vol, uint64_t off, uint64_t len, uint64_t cut, fstream_t *fs, int last) { + seg_t *s; + if (!len) return 0; + s = seg_add(t, SEG_DEC); + if (!s) return -1; + s->vol = vol; + s->off = off; + s->len = len; + s->out_len = len - cut; + s->fs = fs; + s->last = last; + fs->refs++; + return 0; +} + +static void seg_free(xrarc_t *t, seg_t *s) { + if (s->mem) { + xrc_wipe(s->mem, (size_t)s->len); + free(s->mem); + } + if (s->fs) fs_unref(t, s->fs); + xrc_wipe(s, sizeof *s); +} + +/* ---- headers: RAR5 ---- */ + +static uint32_t crc32(const void *p, size_t n) { return CrcCalc(p, n); } + +/* Reads the header at scan_pos into t->hb (decrypted when the volume's headers are). Sets its size + * and the bytes it takes in the volume. */ +static int read_hdr5(xrarc_t *t, size_t *hsize, uint64_t *raw_len) { + uint8_t *hb = t->hb; + uint64_t pos = t->scan_pos, size; + size_t at = 4; + if (t->hdr_enc) { + uint8_t iv[16]; + xrc_aes_t aes; + size_t enc; + if (rd(t, t->scan_vol, pos, iv, 16) != 0 || rd(t, t->scan_vol, pos + 16, hb, 16) != 0) return -1; + xrc_aes_init(&aes, t->hkey, 32, iv); + xrc_aes_dec(&aes, hb, 1); + if (vget(hb, 16, &at, &size) != 0 || size == 0 || size > HDR_MAX - at) + return fail(t, t->hdr_ok ? XRC_E_CORRUPT : XRC_E_WRONG_PASSWORD); + *hsize = at + (size_t)size; + enc = (*hsize + 15) & ~(size_t)15; + if (rd(t, t->scan_vol, pos + 16, hb, enc) != 0) return -1; + xrc_aes_init(&aes, t->hkey, 32, iv); + xrc_aes_dec(&aes, hb, enc / 16); + xrc_wipe(&aes, sizeof aes); + *raw_len = 16 + enc; + if (crc32(hb + 4, *hsize - 4) != le32(hb)) return fail(t, t->hdr_ok ? XRC_E_CORRUPT : XRC_E_WRONG_PASSWORD); + t->hdr_ok = 1; + return 0; + } + { + uint64_t left = t->scan_size - pos; + size_t first = left < 7 ? (size_t)left : 7; + if (first < 5 || rd(t, t->scan_vol, pos, hb, first) != 0) return fail(t, XRC_E_TRUNCATED); + if (vget(hb, first, &at, &size) != 0 || size == 0 || size > HDR_MAX - at) return fail(t, XRC_E_CORRUPT); + *hsize = at + (size_t)size; + if (rd(t, t->scan_vol, pos, hb, *hsize) != 0) return -1; + if (crc32(hb + 4, *hsize - 4) != le32(hb)) return fail(t, XRC_E_CORRUPT); + *raw_len = *hsize; + return 0; + } +} + +/* Emits the header in t->hb as it is: a copy when it was decrypted, else the volume's bytes. */ +static int emit_hdr(xrarc_t *t, size_t hsize) { + if (t->hdr_enc) return add_mem(t, t->hb, hsize); + return add_raw(t, t->scan_vol, t->scan_pos, hsize); +} + +typedef struct { + size_t type_at; /* the record's type field, in hb */ + size_t data, end; +} xrec_t; + +static int scan_file5(xrarc_t *t, size_t hsize, uint64_t raw_len, uint64_t type, uint64_t hflags, size_t at, + uint64_t extra_size, uint64_t data_size) { + const uint8_t *hb = t->hb; + uint64_t ff, unp, attr, comp, host, nlen; + size_t at_ff = at, at_comp, ex0; + uint32_t stored_crc = 0; + int have_crc, is_file = type == 2, split_before = (hflags & 0x08) != 0, split_after = (hflags & 0x10) != 0; + xrec_t crypt = {0, 0, 0}, hash = {0, 0, 0}; + int has_crypt = 0, has_hash = 0, mac = 0; + uint64_t data_off = t->scan_pos + raw_len, cut = 0; + fstream_t *fs = NULL; + xrarc_ent_t *ent = NULL; + uint8_t key[32], hashkey[32], check[8]; + + if (vget(hb, hsize, &at, &ff) || vget(hb, hsize, &at, &unp) || vget(hb, hsize, &at, &attr)) + return fail(t, XRC_E_CORRUPT); + if (ff & 0x02) at += 4; + have_crc = (ff & 0x04) != 0; + if (have_crc) { + if (at + 4 > hsize) return fail(t, XRC_E_CORRUPT); + stored_crc = le32(hb + at); + at += 4; + } + at_comp = at; + if (vget(hb, hsize, &at, &comp) || vget(hb, hsize, &at, &host) || vget(hb, hsize, &at, &nlen) || + nlen > hsize - at || extra_size > hsize - at - nlen) + return fail(t, XRC_E_CORRUPT); + ex0 = hsize - (size_t)extra_size; + for (size_t p = ex0; p < hsize;) { + uint64_t rsize, rtype; + size_t q = p, tat; + if (vget(hb, hsize, &q, &rsize) || rsize > hsize - q) return fail(t, XRC_E_CORRUPT); + tat = q; + if (vget(hb, q + (size_t)rsize, &q, &rtype)) return fail(t, XRC_E_CORRUPT); + if (rtype == 1 && !has_crypt) { + crypt.type_at = tat; + crypt.data = q; + crypt.end = tat + (size_t)rsize; + has_crypt = 1; + } else if (rtype == 2 && !has_hash) { + hash.type_at = tat; + hash.data = q; + hash.end = tat + (size_t)rsize; + has_hash = 1; + } + p = tat + (size_t)rsize; + } + if (!has_crypt) { + /* Not encrypted: as it is. */ + if (emit_hdr(t, hsize) != 0) return -1; + if (is_file && !split_before) { + ent = calloc(1, sizeof *ent); + if (!ent) return fail(t, XRC_E_NOMEM); + ent->refs = 1; + ent->complete = 1; + if (t->q_tail) t->q_tail->next = ent; + else t->q_head = ent; + t->q_tail = ent; + } + return add_raw(t, t->scan_vol, data_off, data_size); + } + + /* The encryption record: version, flags, KDF count, salt, IV, [check]. */ + t->any_enc = 1; + { + size_t q = crypt.data; + uint64_t ver, cflags; + const uint8_t *salt, *iv; + unsigned lg2; + if (vget(hb, crypt.end, &q, &ver) || vget(hb, crypt.end, &q, &cflags) || q + 33 > crypt.end) + return fail(t, XRC_E_CORRUPT); + if (ver != 0) return fail(t, XRC_E_UNSUPPORTED); + lg2 = hb[q]; + salt = hb + q + 1; + iv = hb + q + 17; + q += 33; + mac = (cflags & 0x02) != 0; + /* Only files: a service header's data (a comment, the quick-open copy of the headers) is + * skipped by libarchive, and RAR's check value in it does not follow the files' rule. */ + if (t->pw && is_file) { + if (xrc_kdf5(t->pw, salt, lg2, key, hashkey, check) != 0) return fail(t, XRC_E_UNSUPPORTED); + if ((cflags & 0x01) && q + 12 <= crypt.end && xrc_check5_valid(hb + q)) { + if (memcmp(hb + q, check, 8) != 0) return fail(t, XRC_E_WRONG_PASSWORD); + t->confirmed = 1; + } + if (split_before && t->split_fs) { + fs = t->split_fs; + } else { + fs = fs_new(t); + if (!fs) return -1; + xrc_aes_init(&fs->aes, key, 32, iv); + } + } + } + + if (is_file && !split_before) { + ent = calloc(1, sizeof *ent); + if (!ent) { + if (fs && fs != t->split_fs && fs->refs == 0) fs_unref(t, (fs->refs = 1, fs)); + return fail(t, XRC_E_NOMEM); + } + ent->refs = 1; + ent->encrypted = 1; + ent->check = ent->keyed = mac; + if (t->q_tail) t->q_tail->next = ent; + else t->q_head = ent; + t->q_tail = ent; + if (fs) { + fs->ent = ent; + ent->refs++; + } + } + if (!split_after) { + /* The last part: the file's checksum. */ + xrarc_ent_t *e = ent ? ent : (fs ? fs->ent : NULL); + if (e) { + if (mac && t->pw) { + memcpy(e->hashkey, hashkey, 32); + if (have_crc) { + e->have_crc = 1; + e->crc = stored_crc; + } + if (has_hash) { + size_t q = hash.data; + uint64_t htype; + if (!vget(hb, hash.end, &q, &htype) && htype == 0 && q + 32 <= hash.end) { + e->have_blake = 1; + memcpy(e->blake, hb + q, 32); + } + } + } + e->complete = 1; + } + /* A stored file: its padding to whole AES blocks is cut (libarchive copies every byte). */ + if (fs && ((comp >> 7) & 7) == 0 && !(ff & 0x08)) { + uint64_t total = fs->packed + data_size; + if (total > unp && total - unp < 16 && total - unp <= data_size) cut = total - unp; + } + /* An empty file still has one block of encrypted padding, which libarchive would take for + * compressed data: none is handed on. */ + if (fs && unp == 0 && !(ff & 0x08) && !split_before) cut = data_size; + } + xrc_wipe(key, sizeof key); + xrc_wipe(check, sizeof check); + xrc_wipe(hashkey, sizeof hashkey); + + /* The header again, without the encryption: the record's type made unknown (skipped), and a + * keyed checksum made 0, which libarchive takes as "none" (the caller checks it). The CRC field + * itself stays: a split file's first parts hold a CRC of their packed bytes, and libarchive only + * sums the file's data while the CRC it holds is not 0. */ + { + uint8_t *nb = malloc(hsize + 32); + size_t n = 0, body0, tail; + uint8_t sz[10]; + size_t szn; + if (!nb) { + if (fs && fs->refs == 0 && fs != t->split_fs) { + fs->refs = 1; + fs_unref(t, fs); + } + return fail(t, XRC_E_NOMEM); + } + n = 4 + 3; /* room for the CRC and up to a 3-byte size, moved down below */ + body0 = n; + n += vput(nb + n, type); + n += vput(nb + n, hflags); + if (hflags & 0x01) n += vput(nb + n, extra_size); + if (hflags & 0x02) n += vput(nb + n, data_size - cut); + n += vput(nb + n, ff); + n += vput(nb + n, unp); + n += vput(nb + n, attr); + if (ff & 0x02) { + size_t m = at_ff; + uint64_t dummy; + vget(hb, hsize, &m, &dummy); + vget(hb, hsize, &m, &dummy); + vget(hb, hsize, &m, &dummy); + memcpy(nb + n, hb + m, 4); + n += 4; + } + if (have_crc) { + put32(nb + n, mac ? 0 : stored_crc); + n += 4; + } + tail = n; + memcpy(nb + n, hb + at_comp, hsize - at_comp); + n += hsize - at_comp; + nb[tail + (crypt.type_at - at_comp)] = (uint8_t)((nb[tail + (crypt.type_at - at_comp)] & 0x80) | NEUTRAL_TYPE); + if (mac && has_hash) nb[tail + (hash.type_at - at_comp)] = (uint8_t)((nb[tail + (hash.type_at - at_comp)] & 0x80) | NEUTRAL_TYPE); + /* No data left (an empty file): stored, or libarchive would look for a compressed block. + * The method is bits 7-9 of the compression field, the low bits of its second byte. */ + if (cut && cut == data_size && (nb[tail] & 0x80)) nb[tail + 1] &= (uint8_t)~0x07; + szn = vput(sz, n - body0); + memcpy(nb + body0 - szn, sz, szn); + put32(nb + body0 - szn - 4, crc32(nb + body0 - szn, n - body0 + szn)); + if (add_mem(t, nb + body0 - szn - 4, n - body0 + szn + 4) != 0) { + free(nb); + return -1; + } + free(nb); + } + + /* The data. A service header's (a comment, a recovery record) is skipped by libarchive. */ + if (fs) { + int r = 0; + if (data_size) r = add_dec(t, t->scan_vol, data_off, data_size, cut, fs, !split_after); + fs->packed += data_size; + if (r == 0) { + if (split_after) { + if (t->split_fs != fs) { + fs_unref(t, t->split_fs); + t->split_fs = fs; + fs->refs++; + } + } else if (t->split_fs == fs) { + t->split_fs = NULL; + fs_unref(t, fs); + fs = NULL; + } + } + if (fs && fs->refs == 0) { + fs->refs = 1; + fs_unref(t, fs); + } + return r; + } + return add_raw(t, t->scan_vol, data_off, data_size); +} + +/* 1 a header read, -1 failure. Sets *end at the end of the volume's archive. */ +static int scan5(xrarc_t *t, int *end) { + size_t hsize, at = 4; + uint64_t raw_len, size, type, hflags, extra_size = 0, data_size = 0; + if (read_hdr5(t, &hsize, &raw_len) != 0) return -1; + if (vget(t->hb, hsize, &at, &size) || vget(t->hb, hsize, &at, &type) || vget(t->hb, hsize, &at, &hflags)) + return fail(t, XRC_E_CORRUPT); + if ((hflags & 0x01) && vget(t->hb, hsize, &at, &extra_size)) return fail(t, XRC_E_CORRUPT); + if ((hflags & 0x02) && vget(t->hb, hsize, &at, &data_size)) return fail(t, XRC_E_CORRUPT); + if (type == 4) { + /* Encryption header: version, flags, KDF count, salt, [check]. Everything after it is + * encrypted. */ + uint64_t ver, cflags; + uint8_t hashkey[32], check[8]; + t->any_enc = 1; + if (vget(t->hb, hsize, &at, &ver) || vget(t->hb, hsize, &at, &cflags) || at + 17 > hsize) + return fail(t, XRC_E_CORRUPT); + if (ver != 0) return fail(t, XRC_E_UNSUPPORTED); + if (!t->pw) return fail(t, XRC_E_PASSWORD_REQUIRED); + if (xrc_kdf5(t->pw, t->hb + at + 1, t->hb[at], t->hkey, hashkey, check) != 0) return fail(t, XRC_E_UNSUPPORTED); + if ((cflags & 0x01) && at + 29 <= hsize && xrc_check5_valid(t->hb + at + 17)) { + if (memcmp(t->hb + at + 17, check, 8) != 0) return fail(t, XRC_E_WRONG_PASSWORD); + t->confirmed = 1; + } + xrc_wipe(hashkey, sizeof hashkey); + xrc_wipe(check, sizeof check); + t->scan_pos += raw_len + data_size; + t->hdr_enc = 1; + return 1; + } + if (type == 1) { + uint64_t aflags; + if (!vget(t->hb, hsize, &at, &aflags)) t->solid = (aflags & 0x04) ? 1 : 0; + } + if (type == 2 || type == 3) { + if (scan_file5(t, hsize, raw_len, type, hflags, at, extra_size, data_size) != 0) return -1; + } else { + if (emit_hdr(t, hsize) != 0 || add_raw(t, t->scan_vol, t->scan_pos + raw_len, data_size) != 0) return -1; + } + if (type == 5) *end = 1; + t->scan_pos += raw_len + data_size; + return 1; +} + +/* ---- headers: RAR 3/4 ---- */ + +static uint16_t crc16(const uint8_t *h, size_t size) { return (uint16_t)(crc32(h + 2, size - 2) & 0xffff); } + +static int read_hdr4(xrarc_t *t, size_t *size, uint64_t *raw_len) { + uint8_t *hb = t->hb; + uint64_t pos = t->scan_pos; + if (t->hdr_enc) { + uint8_t salt[8], key[16], iv[16]; + xrc_aes_t aes; + size_t enc; + if (rd(t, t->scan_vol, pos, salt, 8) != 0 || rd(t, t->scan_vol, pos + 8, hb, 16) != 0) return -1; + xrc_kdf3(t->pw, salt, key, iv); + xrc_aes_init(&aes, key, 16, iv); + xrc_aes_dec(&aes, hb, 1); + *size = le16(hb + 5); + if (*size < 7) return fail(t, t->hdr_ok ? XRC_E_CORRUPT : XRC_E_WRONG_PASSWORD); + enc = (*size + 15) & ~(size_t)15; + if (rd(t, t->scan_vol, pos + 8, hb, enc) != 0) return -1; + xrc_aes_init(&aes, key, 16, iv); + xrc_aes_dec(&aes, hb, enc / 16); + xrc_wipe(&aes, sizeof aes); + xrc_wipe(key, sizeof key); + if (crc16(hb, *size) != le16(hb)) return fail(t, t->hdr_ok ? XRC_E_CORRUPT : XRC_E_WRONG_PASSWORD); + t->hdr_ok = 1; + t->confirmed = 1; + *raw_len = 8 + enc; + return 0; + } + if (t->scan_size - pos < 7 || rd(t, t->scan_vol, pos, hb, 7) != 0) return fail(t, XRC_E_TRUNCATED); + *size = le16(hb + 5); + if (*size < 7) return fail(t, XRC_E_CORRUPT); + if (rd(t, t->scan_vol, pos, hb, *size) != 0) return -1; + *raw_len = *size; + return 0; +} + +static int scan4(xrarc_t *t, int *end) { + uint8_t *hb = t->hb; + size_t size; + uint64_t raw_len, data_size = 0, data_off; + unsigned type, flags; + int decrypted = t->hdr_enc; + if (read_hdr4(t, &size, &raw_len) != 0) return -1; + type = hb[2]; + flags = le16(hb + 3); + if (flags & 0x8000) { + if (size < 11) return fail(t, XRC_E_CORRUPT); + data_size = le32(hb + 7); + if ((type == 0x74 || type == 0x7a) && (flags & 0x100)) { + if (size < 40) return fail(t, XRC_E_CORRUPT); + data_size |= (uint64_t)le32(hb + 32) << 32; + } + } + data_off = t->scan_pos + raw_len; + if (type == 0x73) { + t->solid = (flags & 0x0008) ? 1 : 0; + if (flags & 0x0080) { + t->any_enc = 1; + if (!t->pw) return fail(t, XRC_E_PASSWORD_REQUIRED); + put16(hb + 3, flags & ~0x0080u); + put16(hb, crc16(hb, size)); + if (add_mem(t, hb, size) != 0) return -1; + t->hdr_enc = 1; + t->scan_pos += raw_len; + return 1; + } + } else if (type == 0x74 && (flags & 0x04)) { + unsigned name_size, name_off = (flags & 0x100) ? 40 : 32; + int split_before = (flags & 0x01) != 0, split_after = (flags & 0x02) != 0; + const uint8_t *salt = NULL; + fstream_t *fs = NULL; + xrarc_ent_t *ent = NULL; + uint64_t cut = 0; + if (size < name_off) return fail(t, XRC_E_CORRUPT); + name_size = le16(hb + 26); + if (flags & 0x400) { + if (name_off + name_size + 8 > size) return fail(t, XRC_E_CORRUPT); + salt = hb + name_off + name_size; + } + t->any_enc = 1; + if (t->pw) { + uint8_t key[16], iv[16]; + if (hb[24] < 29) return fail(t, XRC_E_UNSUPPORTED); /* RAR 1.5/2.0 encryption */ + if (split_before && t->split_fs) { + fs = t->split_fs; + } else { + fs = fs_new(t); + if (!fs) return -1; + xrc_kdf3(t->pw, salt, key, iv); + xrc_aes_init(&fs->aes, key, 16, iv); + xrc_wipe(key, sizeof key); + } + } + if (!split_before) { + ent = calloc(1, sizeof *ent); + if (!ent) { + if (fs && fs != t->split_fs) { + fs->refs = 1; + fs_unref(t, fs); + } + return fail(t, XRC_E_NOMEM); + } + ent->refs = 1; + ent->encrypted = 1; + ent->check = 1; + if (t->q_tail) t->q_tail->next = ent; + else t->q_head = ent; + t->q_tail = ent; + if (fs) { + fs->ent = ent; + ent->refs++; + } + } + if (!split_after) { + /* The last part holds the file's CRC. */ + xrarc_ent_t *e = ent ? ent : (fs ? fs->ent : NULL); + if (e) { + e->have_crc = 1; + e->crc = le32(hb + 16); + e->complete = 1; + } + } + /* A stored file's padding is cut (see scan_file5). */ + if (fs && !split_after && hb[25] == 0x30) { + uint64_t unp = le32(hb + 11), total = fs->packed + data_size; + if (flags & 0x100) unp |= (uint64_t)le32(hb + 36) << 32; + if (total > unp && total - unp < 16 && total - unp <= data_size) cut = total - unp; + } + put16(hb + 3, flags & ~0x04u); + if (cut) { + put32(hb + 7, (uint32_t)(data_size - cut)); + if (flags & 0x100) put32(hb + 32, (uint32_t)((data_size - cut) >> 32)); + } + put16(hb, crc16(hb, size)); + if (add_mem(t, hb, size) != 0) return -1; + if (fs) { + int r = add_dec(t, t->scan_vol, data_off, data_size, cut, fs, !split_after); + fs->packed += data_size; + if (r == 0) { + if (split_after) { + if (t->split_fs != fs) { + fs_unref(t, t->split_fs); + t->split_fs = fs; + fs->refs++; + } + } else if (t->split_fs == fs) { + t->split_fs = NULL; + fs_unref(t, fs); + fs = NULL; + } + } + if (fs && fs->refs == 0) { + fs->refs = 1; + fs_unref(t, fs); + } + if (r != 0) return -1; + } else if (add_raw(t, t->scan_vol, data_off, data_size) != 0) { + return -1; + } + t->scan_pos = data_off + data_size; + return 1; + } else if (type == 0x74) { + if (!(flags & 0x01)) { + xrarc_ent_t *ent = calloc(1, sizeof *ent); + if (!ent) return fail(t, XRC_E_NOMEM); + ent->refs = 1; + ent->complete = 1; + if (t->q_tail) t->q_tail->next = ent; + else t->q_head = ent; + t->q_tail = ent; + } + } + if (decrypted ? add_mem(t, hb, size) : add_raw(t, t->scan_vol, t->scan_pos, size)) return -1; + if (add_raw(t, t->scan_vol, data_off, data_size) != 0) return -1; + if (type == 0x7b) *end = 1; + t->scan_pos = data_off + data_size; + return 1; +} + +/* ---- volumes ---- */ + +/* The signature of volume scan_vol (the first may be a self-extractor: searched for). */ +static int open_vol(xrarc_t *t) { + static const uint8_t sig[6] = {'R', 'a', 'r', '!', 0x1a, 0x07}; + struct stat st; + int fd = vol_fd(t, t->scan_vol); + uint64_t limit, off = 0; + int fmt = 0; + if (fd < 0) return -1; + if (fstat(fd, &st) != 0) return fail(t, XRC_E_OPEN); + t->scan_size = (uint64_t)st.st_size; + limit = t->scan_vol == 0 ? SFX_SCAN : 1; + while (off < limit && off + 8 <= t->scan_size && !fmt) { + size_t n = (size_t)((t->scan_size - off) < BUF_SIZE ? (t->scan_size - off) : BUF_SIZE); + if (rd(t, t->scan_vol, off, t->buf, n) != 0) return -1; + for (size_t i = 0; i + 8 <= n && off + i < limit; i++) { + if (memcmp(t->buf + i, sig, 6) != 0) continue; + if (t->buf[i + 6] == 0x00) fmt = 4; + else if (t->buf[i + 6] == 0x01 && t->buf[i + 7] == 0x00) fmt = 5; + else continue; + off += i; + break; + } + if (!fmt) off += n > 7 ? n - 7 : n; + } + if (!fmt) return fail(t, t->scan_vol == 0 ? XRC_E_NOT_RAR : XRC_E_CORRUPT); + if (t->fmt && fmt != t->fmt) return fail(t, XRC_E_CORRUPT); + t->fmt = fmt; + if (add_raw(t, t->scan_vol, off, fmt == 5 ? 8 : 7) != 0) return -1; + t->scan_pos = off + (fmt == 5 ? 8 : 7); + t->hdr_enc = 0; + t->vol_open = 1; + return 0; +} + +/* Reads one more header (segments added). 1, 0 at the end of the last volume, -1 failure. */ +static int scan_one(xrarc_t *t) { + int end = 0, r; + if (t->err) return -1; + if (t->scan_done) return 0; + if (!t->vol_open && open_vol(t) != 0) return -1; + if (t->scan_pos >= t->scan_size) { + end = 1; + r = 1; + } else { + r = t->fmt == 5 ? scan5(t, &end) : scan4(t, &end); + if (r < 0) return -1; + } + if (end) { + t->vol_open = 0; + if (++t->scan_vol >= t->nvols) { + t->scan_done = 1; + if (t->split_fs) return fail(t, XRC_E_MISSING_VOLUME); + } + } + return 1; +} + +/* ---- handing the stream out ---- */ + +/* Decrypts the last `r` (< 16) bytes of DEC segment `i` with the bytes the block needs from the + * file's next parts; their plaintext is kept for those parts. Writes the first `r` bytes to `out`. */ +static int straddle(xrarc_t *t, size_t i, unsigned r, uint8_t *out) { + _Alignas(16) uint8_t blk[16]; + size_t j = i + 1, took[16], from[16]; + unsigned nt = 0, have = r, need = 16 - r; + fstream_t *fs = t->segs[i].fs; + if (t->segs[i].last) return fail(t, XRC_E_CORRUPT); /* not a whole number of blocks */ + if (rd(t, t->segs[i].vol, t->segs[i].off + t->segs[i].len - r, blk, r) != 0) return -1; + while (need) { + seg_t *s; + unsigned take; + while (j >= t->nseg) { + int k = scan_one(t); + if (k < 0) return -1; + if (k == 0) return fail(t, XRC_E_MISSING_VOLUME); + } + s = &t->segs[j]; + if (s->kind != SEG_DEC || s->fs != fs) { + j++; + continue; + } + take = s->len < need ? (unsigned)s->len : need; + if (rd(t, s->vol, s->off, blk + have, take) != 0) return -1; + s->skip = take; + took[nt] = take; + from[nt] = j; + nt++; + have += take; + need -= take; + if (need && s->last) return fail(t, XRC_E_CORRUPT); + j++; + } + xrc_aes_dec(&fs->aes, blk, 1); + memcpy(out, blk, r); + have = r; + for (unsigned k = 0; k < nt; k++) { + seg_t *s = &t->segs[from[k]]; + memcpy(s->pend, blk + have, took[k]); + s->pend_n = (unsigned)took[k]; + have += (unsigned)took[k]; + } + xrc_wipe(blk, 16); + return 0; +} + +/* Up to BUF_SIZE bytes of segment `at` into *out. >0 bytes, 0 the segment is done, -1 failure. */ +static la_ssize_t serve(xrarc_t *t, const void **out) { + seg_t *s = &t->segs[t->at]; + if (s->kind == SEG_MEM) { + size_t n = (size_t)(s->len - t->pos); + *out = s->mem + t->pos; + t->pos += n; + return (la_ssize_t)n; + } + if (s->kind == SEG_RAW) { + uint64_t left = s->len - t->pos; + size_t n = left < BUF_SIZE ? (size_t)left : BUF_SIZE; + if (!n) return 0; + if (rd(t, s->vol, s->off + t->pos, t->buf, n) != 0) return -1; + t->pos += n; + *out = t->buf; + return (la_ssize_t)n; + } + if (!t->pend_done) { + t->pend_done = 1; + t->pos = s->skip; + if (s->pend_n) { + uint64_t n = s->pend_n < s->out_len - t->outp ? s->pend_n : s->out_len - t->outp; + memcpy(t->buf, s->pend, (size_t)n); + xrc_wipe(s->pend, sizeof s->pend); + t->outp += n; + if (n) { + *out = t->buf; + return (la_ssize_t)n; + } + } + } + for (;;) { + uint64_t left = s->len - t->pos, give; + size_t n; + if (!left) return 0; + if (left >= 16) { + n = left < BUF_SIZE ? (size_t)(left & ~(uint64_t)15) : BUF_SIZE; + if (rd(t, s->vol, s->off + t->pos, t->buf, n) != 0) return -1; + xrc_aes_dec(&s->fs->aes, t->buf, n / 16); + } else { + uint8_t tail[16]; + size_t at = t->at; + n = (size_t)left; + if (straddle(t, at, (unsigned)n, tail) != 0) return -1; + s = &t->segs[at]; /* the scan may have moved the array */ + memcpy(t->buf, tail, n); + xrc_wipe(tail, sizeof tail); + } + t->pos += n; + give = s->out_len - t->outp < n ? s->out_len - t->outp : n; + t->outp += give; + if (give) { + *out = t->buf; + return (la_ssize_t)give; + } + } +} + +/* Done with segment `at`: on to the next (older ones are dropped now and then). */ +static void next_seg(xrarc_t *t) { + seg_free(t, &t->segs[t->at]); + t->at++; + t->pos = t->outp = 0; + t->pend_done = 0; + if (t->at == t->nseg) { + t->at = t->nseg = 0; + } else if (t->at >= 256 && t->at * 2 >= t->nseg) { + memmove(t->segs, t->segs + t->at, (t->nseg - t->at) * sizeof *t->segs); + t->nseg -= t->at; + t->at = 0; + } +} + +static const char *err_text(int e) { + switch (e) { + case XRC_E_PASSWORD_REQUIRED: return "password required"; + case XRC_E_WRONG_PASSWORD: return "wrong password"; + case XRC_E_MISSING_VOLUME: return "a volume is missing"; + case XRC_E_TRUNCATED: return "truncated"; + case XRC_E_UNSUPPORTED: return "unsupported encryption"; + case XRC_E_NOMEM: return "out of memory"; + case XRC_E_OPEN: return "read error"; + case XRC_E_NOT_RAR: return "not a RAR archive"; + default: return "damaged"; + } +} + +static la_ssize_t read_cb(struct archive *a, void *ud, const void **out) { + xrarc_t *t = ud; + for (;;) { + la_ssize_t n; + if (t->err) break; + if (t->at == t->nseg) { + int k = scan_one(t); + if (k < 0) break; + if (k == 0) return 0; + continue; + } + n = serve(t, out); + if (n < 0) break; + if (n > 0) return n; + next_seg(t); + } + if (a) archive_set_error(a, EIO, "RAR decryption: %s", err_text(t->err)); + return -1; +} + +/* Skips within the current segment; never into the middle of encrypted data that goes on (its + * chaining would be lost): libarchive then reads instead. */ +static la_int64_t skip_cb(struct archive *a, void *ud, la_int64_t req) { + xrarc_t *t = ud; + (void)a; + for (;;) { + seg_t *s; + if (t->err || req <= 0) return 0; + if (t->at == t->nseg) { + if (scan_one(t) <= 0) return 0; + continue; + } + s = &t->segs[t->at]; + if (s->kind != SEG_DEC) { + uint64_t left = s->len - t->pos, n = (uint64_t)req < left ? (uint64_t)req : left; + if (!n) { + next_seg(t); + continue; + } + t->pos += n; + return (la_int64_t)n; + } + if (t->pend_done && t->pos >= s->len) { + next_seg(t); + continue; + } + if (s->last && (uint64_t)req >= s->out_len - t->outp) { + uint64_t n = s->out_len - t->outp; + t->pend_done = 1; + t->pos = s->len; + t->outp = s->out_len; + if (!n) { + next_seg(t); + continue; + } + return (la_int64_t)n; + } + return 0; + } +} + +/* ---- the handle ---- */ + +xrarc_t *xrarc_open(char **vols, const char *password, int *err) { + xrarc_t *t = calloc(1, sizeof *t); + *err = XRC_E_NOMEM; + if (!t) return NULL; + xrc_init(); + CrcGenerateTable(); + t->vols = vols; + while (vols[t->nvols]) t->nvols++; + t->pw = password; + t->solid = -1; + t->fd[0] = t->fd[1] = -1; + t->buf = amalloc(BUF_SIZE, &t->buf_raw); + t->hb = amalloc(HDR_MAX + 64, &t->hb_raw); + if (!t->buf || !t->hb || !t->nvols) { + if (t->nvols) fail(t, XRC_E_NOMEM); + else fail(t, XRC_E_OPEN); + goto bad; + } + /* The first volume's headers, up to the first encrypted one: a missing or wrong password + * shows now, before anything is written (an archive may start with files that have none). */ + for (int n = 0; n < OPEN_SCAN_MAX && !t->any_enc && t->scan_vol == 0 && !t->scan_done; n++) { + int k = scan_one(t); + if (k < 0) goto bad; + if (k == 0) break; + } + if (t->err) goto bad; + *err = XRC_OK; + return t; +bad: + *err = t->err ? t->err : XRC_E_CORRUPT; + xrarc_close(t); + return NULL; +} + +int xrarc_encrypted(const xrarc_t *t) { return t->any_enc; } +int xrarc_confirmed(const xrarc_t *t) { return t->confirmed; } +int xrarc_solid(const xrarc_t *t) { return t->solid; } +int xrarc_error(const xrarc_t *t) { return t->err; } + +int xrarc_attach(xrarc_t *t, struct archive *a) { return archive_read_open2(a, t, NULL, read_cb, skip_cb, NULL); } + +void xrarc_close(xrarc_t *t) { + if (!t) return; + for (size_t i = t->at; i < t->nseg; i++) seg_free(t, &t->segs[i]); + free(t->segs); + fs_unref(t, t->split_fs); + while (t->q_head) xrarc_release(t, xrarc_take(t)); + for (unsigned i = 0; i < 2; i++) + if (t->fd[i] >= 0) close(t->fd[i]); + if (t->buf) xrc_wipe(t->buf, BUF_SIZE); + if (t->hb) xrc_wipe(t->hb, HDR_MAX + 64); + xrc_wipe(t->hkey, sizeof t->hkey); + free(t->buf_raw); + free(t->hb_raw); + free(t); +} + diff --git a/payload/extractor/src/xrarc.h b/payload/extractor/src/xrarc.h new file mode 100644 index 000000000..0ececb5cd --- /dev/null +++ b/payload/extractor/src/xrarc.h @@ -0,0 +1,81 @@ +/* Password-protected RAR (RAR 3/4 and RAR5, encrypted data and encrypted headers, single or + * multi-volume) for libarchive's RAR readers, which cannot decrypt. + * + * The volumes are read here and handed to libarchive as one stream (its read callback) that is the + * same archive without the encryption: encrypted headers decrypted, file data decrypted, the + * "encrypted" marks taken off the headers (and their checksums redone). libarchive then decodes it as + * it decodes any RAR. Nothing decrypted is written to disk. + * + * Two things cannot be handed over as they are and are left to the caller (xrar.c): + * - RAR5 usually stores the checksums of an encrypted file keyed with the password (so they give + * nothing away). libarchive cannot check those, so they are made 0 (none) in the stream, and + * the caller checks the file it wrote against them (xrarc_ent_t); + * - RAR 3/4 with only the data encrypted has no password check: a wrong password shows as damaged + * data, which the caller reports as a wrong password. libarchive does not check a stored + * (uncompressed) file's CRC once it has its size, so the caller checks every encrypted RAR 3/4 + * file too. */ +#ifndef PS5UPLOAD_XRARC_H +#define PS5UPLOAD_XRARC_H + +#include <stddef.h> +#include <stdint.h> + +#include "archive.h" + +enum { + XRC_OK = 0, + XRC_E_PASSWORD_REQUIRED, + XRC_E_WRONG_PASSWORD, + XRC_E_MISSING_VOLUME, + XRC_E_TRUNCATED, + XRC_E_CORRUPT, + XRC_E_UNSUPPORTED, /* RAR 1.5/2.0 encryption, an unknown RAR5 encryption version */ + XRC_E_NOMEM, + XRC_E_OPEN, + XRC_E_NOT_RAR, +}; + +/* One file entry (a FILE header that starts a file), in archive order, as libarchive returns them. */ +typedef struct xrarc_ent { + struct xrarc_ent *next; + int refs; + int encrypted; /* its data is encrypted */ + int check; /* the caller checks the file it writes against the checksum below */ + int keyed; /* that checksum is keyed with `hashkey` (RAR5) */ + int complete; /* the header of its last part was read: the checksum below is final */ + int have_crc; + uint32_t crc; /* CRC32 of the unpacked data */ + int have_blake; + uint8_t blake[32]; /* BLAKE2sp of the unpacked data (keyed) */ + uint8_t hashkey[32]; +} xrarc_ent_t; + +typedef struct xrarc xrarc_t; + +/* Opens the volumes (`vols`, NULL-terminated, kept by the caller) and reads the first volume's + * headers up to the first encrypted one. `password` may be NULL; it is kept by the caller and must outlive the handle. NULL + * with *err set on failure (XRC_E_PASSWORD_REQUIRED: the headers are encrypted and there is no + * password; XRC_E_WRONG_PASSWORD: a password check failed). */ +xrarc_t *xrarc_open(char **vols, const char *password, int *err); + +/* Whether anything was found encrypted so far (headers, or a file's data); whether the password + * was confirmed by the archive's own check value (RAR5) or by decrypting headers (RAR 3/4 -hp); + * whether the archive is solid (1, 0, -1 unknown). */ +int xrarc_encrypted(const xrarc_t *t); +int xrarc_confirmed(const xrarc_t *t); +int xrarc_solid(const xrarc_t *t); + +/* The first failure (XRC_*), 0 when none. */ +int xrarc_error(const xrarc_t *t); + +/* Hands the stream to `a` (archive_read_open2 with our callbacks). ARCHIVE_OK or an error. */ +int xrarc_attach(xrarc_t *t, struct archive *a); + +/* The next file entry, in order; the caller owns one reference (xrarc_release). NULL: none read. */ +xrarc_ent_t *xrarc_take(xrarc_t *t); +void xrarc_release(xrarc_t *t, xrarc_ent_t *e); + +/* Closes the files and frees everything (the keys too). */ +void xrarc_close(xrarc_t *t); + +#endif diff --git a/payload/extractor/src/xrcrypt.c b/payload/extractor/src/xrcrypt.c new file mode 100644 index 000000000..80b206bfe --- /dev/null +++ b/payload/extractor/src/xrcrypt.c @@ -0,0 +1,363 @@ +/* RAR encryption (see xrcrypt.h). */ +#include "xrcrypt.h" + +#include <string.h> + +#include "../C/Aes.h" +#include "../C/Sha256.h" + +/* RAR caps a password at 127 characters. */ +#define XRC_PW_CHARS 127 + +void xrc_wipe(void *p, size_t n) { + volatile uint8_t *v = (volatile uint8_t *)p; + while (n--) *v++ = 0; +} + +void xrc_init(void) { + static int done; + if (done) return; + AesGenTables(); + Sha256Prepare(); + done = 1; +} + +void xrc_aes_init(xrc_aes_t *c, const uint8_t *key, unsigned keylen, const uint8_t iv[16]) { + Aes_SetKey_Dec(c->w + 4, key, keylen); + AesCbc_Init(c->w, iv); +} + +void xrc_aes_dec(xrc_aes_t *c, uint8_t *data, size_t nblocks) { + if (nblocks) g_AesCbc_Decode(c->w, data, nblocks); +} + +/* ---- SHA-1, as RAR 3 uses it ---- + * + * RAR 3's key derivation hashes the same buffer 2^18 times, and the SHA-1 it was written with + * stores its message schedule back into the caller's buffer whenever an update call hashes a + * second (or later) whole block straight from that buffer: the 16 words left after the 80 rounds, + * little-endian, over the 64 bytes just hashed. Later rounds then hash the changed bytes. Every + * RAR 3/4 archive with a password of 28 or more characters depends on this, so it is kept. */ + +typedef struct { + uint32_t h[5]; + uint32_t w[16]; /* the block being filled, as big-endian words; after a transform, W[64..79] */ + uint64_t count; +} rsha1_t; + +#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + +static void rsha1_init(rsha1_t *s) { + s->h[0] = 0x67452301u; + s->h[1] = 0xEFCDAB89u; + s->h[2] = 0x98BADCFEu; + s->h[3] = 0x10325476u; + s->h[4] = 0xC3D2E1F0u; + s->count = 0; +} + +/* One block from s->w, expanding the schedule in place (s->w ends as W[64..79]). */ +static void rsha1_block(rsha1_t *s) { + uint32_t a = s->h[0], b = s->h[1], c = s->h[2], d = s->h[3], e = s->h[4], *w = s->w; + for (unsigned i = 0; i < 80; i++) { + uint32_t f, k, t; + if (i >= 16) w[i & 15] = ROL(w[(i + 13) & 15] ^ w[(i + 8) & 15] ^ w[(i + 2) & 15] ^ w[i & 15], 1); + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5A827999u; + } else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ED9EBA1u; + } else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8F1BBCDCu; + } else { + f = b ^ c ^ d; + k = 0xCA62C1D6u; + } + t = ROL(a, 5) + f + e + k + w[i & 15]; + e = d; + d = c; + c = ROL(b, 30); + b = a; + a = t; + } + s->h[0] += a; + s->h[1] += b; + s->h[2] += c; + s->h[3] += d; + s->h[4] += e; +} + +/* `rar`: write the schedule back over whole blocks after the first in this call (see above). */ +static void rsha1_update(rsha1_t *s, uint8_t *data, size_t n, int rar) { + unsigned pos = (unsigned)(s->count & 63); + int blocks = 0; + s->count += n; + for (size_t i = 0; i < n; i++) { + unsigned sh = 8 * (3 - (pos & 3)); + if ((pos & 3) == 0) s->w[pos >> 2] = (uint32_t)data[i] << sh; + else s->w[pos >> 2] |= (uint32_t)data[i] << sh; + if (++pos == 64) { + pos = 0; + rsha1_block(s); + if (rar && blocks++ > 0) { + uint8_t *blk = data + i + 1 - 64; + for (unsigned k = 0; k < 16; k++) { + blk[4 * k] = (uint8_t)s->w[k]; + blk[4 * k + 1] = (uint8_t)(s->w[k] >> 8); + blk[4 * k + 2] = (uint8_t)(s->w[k] >> 16); + blk[4 * k + 3] = (uint8_t)(s->w[k] >> 24); + } + } + } + } +} + +static void rsha1_final(rsha1_t *s, uint32_t out[5]) { + uint64_t bits = s->count * 8; + uint8_t pad[72]; + unsigned pos = (unsigned)(s->count & 63), n = (pos < 56 ? 56 : 120) - pos; + memset(pad, 0, sizeof pad); + pad[0] = 0x80; + for (unsigned i = 0; i < 8; i++) pad[n + i] = (uint8_t)(bits >> (56 - 8 * i)); + rsha1_update(s, pad, n + 8, 0); + memcpy(out, s->h, 20); +} + +/* ---- the caches: the derivations are deliberately slow, and an archive reuses its salt ---- */ + +typedef struct { + int used; + uint8_t salt[16]; + unsigned lg2; /* RAR5 */ + int salted; /* RAR 3 */ + uint8_t key[32], iv_or_hash[32], check[8]; +} kcache_t; + +static kcache_t g_k3[4], g_k5[4]; +static unsigned g_k3_next, g_k5_next; + +void xrc_forget(void) { + xrc_wipe(g_k3, sizeof g_k3); + xrc_wipe(g_k5, sizeof g_k5); +} + +/* UTF-8 to UTF-16LE (at most XRC_PW_CHARS units); bad bytes count as U+FFFD. Returns the bytes. */ +static size_t utf16le(const char *s, uint8_t *out) { + const unsigned char *p = (const unsigned char *)s; + size_t n = 0; + while (*p && n < XRC_PW_CHARS) { + uint32_t c = *p++; + int more = 0; + if (c >= 0xF0 && c < 0xF8) { + c &= 7; + more = 3; + } else if (c >= 0xE0) { + c &= 15; + more = 2; + } else if (c >= 0xC0) { + c &= 31; + more = 1; + } else if (c >= 0x80) { + c = 0xFFFD; + } + while (more-- > 0) { + if ((*p & 0xC0) != 0x80) { + c = 0xFFFD; + break; + } + c = (c << 6) | (*p++ & 0x3F); + } + if (c > 0xFFFF) { + if (n + 2 > XRC_PW_CHARS) break; + c -= 0x10000; + out[2 * n] = (uint8_t)((0xD800 | (c >> 10)) & 0xFF); + out[2 * n + 1] = (uint8_t)((0xD800 | (c >> 10)) >> 8); + n++; + c = 0xDC00 | (c & 0x3FF); + } + out[2 * n] = (uint8_t)c; + out[2 * n + 1] = (uint8_t)(c >> 8); + n++; + } + return 2 * n; +} + +int xrc_kdf3(const char *password, const uint8_t *salt8, uint8_t key[16], uint8_t iv[16]) { + enum { ROUNDS = 1 << 18 }; + uint8_t buf[2 * XRC_PW_CHARS + 8]; + uint32_t d[5]; + rsha1_t s; + size_t len; + for (unsigned i = 0; i < 4; i++) { + kcache_t *k = &g_k3[i]; + if (k->used && k->salted == (salt8 != NULL) && (!salt8 || memcmp(k->salt, salt8, 8) == 0)) { + memcpy(key, k->key, 16); + memcpy(iv, k->iv_or_hash, 16); + return 0; + } + } + len = utf16le(password, buf); + if (salt8) { + memcpy(buf + len, salt8, 8); + len += 8; + } + rsha1_init(&s); + for (uint32_t i = 0; i < ROUNDS; i++) { + uint8_t num[3] = {(uint8_t)i, (uint8_t)(i >> 8), (uint8_t)(i >> 16)}; + rsha1_update(&s, buf, len, 1); + rsha1_update(&s, num, 3, 0); + if (i % (ROUNDS / 16) == 0) { + rsha1_t t = s; + rsha1_final(&t, d); + iv[i / (ROUNDS / 16)] = (uint8_t)d[4]; + xrc_wipe(&t, sizeof t); + } + } + rsha1_final(&s, d); + for (unsigned i = 0; i < 4; i++) + for (unsigned j = 0; j < 4; j++) key[i * 4 + j] = (uint8_t)(d[i] >> (8 * j)); + { + kcache_t *k = &g_k3[g_k3_next++ % 4]; + k->used = 1; + k->salted = salt8 != NULL; + if (salt8) memcpy(k->salt, salt8, 8); + memcpy(k->key, key, 16); + memcpy(k->iv_or_hash, iv, 16); + } + xrc_wipe(buf, sizeof buf); + xrc_wipe(&s, sizeof s); + xrc_wipe(d, sizeof d); + return 0; +} + +/* ---- HMAC-SHA256 and RAR5's PBKDF2 ---- */ + +typedef struct { + CSha256 in, out; +} hmac_t; + +static void hmac_init(hmac_t *h, const uint8_t *key, size_t n) { + uint8_t k[64], pad[64]; + memset(k, 0, sizeof k); + if (n > 64) { + CSha256 s; + Sha256_Init(&s); + Sha256_Update(&s, key, n); + Sha256_Final(&s, k); + } else if (n) { + memcpy(k, key, n); + } + for (unsigned i = 0; i < 64; i++) pad[i] = k[i] ^ 0x36; + Sha256_Init(&h->in); + Sha256_Update(&h->in, pad, 64); + for (unsigned i = 0; i < 64; i++) pad[i] = k[i] ^ 0x5c; + Sha256_Init(&h->out); + Sha256_Update(&h->out, pad, 64); + xrc_wipe(k, sizeof k); + xrc_wipe(pad, sizeof pad); +} + +static void hmac_run(const hmac_t *h, const uint8_t *msg, size_t n, uint8_t out[32]) { + CSha256 s = h->in; + uint8_t inner[32]; + Sha256_Update(&s, msg, n); + Sha256_Final(&s, inner); + s = h->out; + Sha256_Update(&s, inner, 32); + Sha256_Final(&s, out); +} + +/* The UTF-8 password, cut at XRC_PW_CHARS characters. */ +static size_t pw5_len(const char *pw) { + size_t n = 0, chars = 0; + while (pw[n] && chars < XRC_PW_CHARS) { + n++; + while (((unsigned char)pw[n] & 0xC0) == 0x80) n++; + chars++; + } + return n; +} + +int xrc_kdf5(const char *password, const uint8_t salt[16], unsigned lg2, uint8_t key[32], uint8_t hashkey[32], + uint8_t check[8]) { + uint8_t s1[20], u[32], f[32], v[3][32]; + hmac_t h; + uint32_t counts[3]; + if (lg2 > 24) return -1; + for (unsigned i = 0; i < 4; i++) { + kcache_t *k = &g_k5[i]; + if (k->used && k->lg2 == lg2 && memcmp(k->salt, salt, 16) == 0) { + memcpy(key, k->key, 32); + memcpy(hashkey, k->iv_or_hash, 32); + memcpy(check, k->check, 8); + return 0; + } + } + /* PBKDF2-HMAC-SHA256, one block; RAR5 then runs the same chain on for 16 more iterations for the + * checksum key and 16 more for the password check. */ + hmac_init(&h, (const uint8_t *)password, pw5_len(password)); + memcpy(s1, salt, 16); + s1[16] = 0; + s1[17] = 0; + s1[18] = 0; + s1[19] = 1; + hmac_run(&h, s1, sizeof s1, u); + memcpy(f, u, 32); + counts[0] = (1u << lg2) - 1; + counts[1] = 16; + counts[2] = 16; + for (unsigned r = 0; r < 3; r++) { + for (uint32_t i = 0; i < counts[r]; i++) { + hmac_run(&h, u, 32, u); + for (unsigned b = 0; b < 32; b++) f[b] ^= u[b]; + } + memcpy(v[r], f, 32); + } + memcpy(key, v[0], 32); + memcpy(hashkey, v[1], 32); + memset(check, 0, 8); + for (unsigned b = 0; b < 32; b++) check[b % 8] ^= v[2][b]; + { + kcache_t *k = &g_k5[g_k5_next++ % 4]; + k->used = 1; + k->lg2 = lg2; + memcpy(k->salt, salt, 16); + memcpy(k->key, key, 32); + memcpy(k->iv_or_hash, hashkey, 32); + memcpy(k->check, check, 8); + } + xrc_wipe(&h, sizeof h); + xrc_wipe(u, sizeof u); + xrc_wipe(f, sizeof f); + xrc_wipe(v, sizeof v); + return 0; +} + +int xrc_check5_valid(const uint8_t stored[12]) { + uint8_t d[32]; + CSha256 s; + Sha256_Init(&s); + Sha256_Update(&s, stored, 8); + Sha256_Final(&s, d); + return memcmp(d, stored + 8, 4) == 0; +} + +uint32_t xrc_mac_crc(const uint8_t hashkey[32], uint32_t crc) { + uint8_t raw[4] = {(uint8_t)crc, (uint8_t)(crc >> 8), (uint8_t)(crc >> 16), (uint8_t)(crc >> 24)}, d[32]; + uint32_t r = 0; + hmac_t h; + hmac_init(&h, hashkey, 32); + hmac_run(&h, raw, 4, d); + for (unsigned i = 0; i < 32; i++) r ^= (uint32_t)d[i] << ((i & 3) * 8); + xrc_wipe(&h, sizeof h); + return r; +} + +void xrc_mac_blake(const uint8_t hashkey[32], const uint8_t digest[32], uint8_t out[32]) { + hmac_t h; + hmac_init(&h, hashkey, 32); + hmac_run(&h, digest, 32, out); + xrc_wipe(&h, sizeof h); +} diff --git a/payload/extractor/src/xrcrypt.h b/payload/extractor/src/xrcrypt.h new file mode 100644 index 000000000..4e7d42c24 --- /dev/null +++ b/payload/extractor/src/xrcrypt.h @@ -0,0 +1,48 @@ +/* RAR encryption: the key derivations and the AES-CBC decryption that password-protected RAR 3/4 + * (AES-128) and RAR5 (AES-256) archives use. Written from the RAR format's description, not from + * UnRAR (whose license the extractor cannot take, see xrar.c); the primitives are 7-Zip's AES and + * SHA-256 (C code, LGPL) plus a SHA-1 of our own, which RAR 3's key derivation needs in a form no + * library offers (below). */ +#ifndef PS5UPLOAD_XRCRYPT_H +#define PS5UPLOAD_XRCRYPT_H + +#include <stddef.h> +#include <stdint.h> + +/* Once, before the rest (idempotent). */ +void xrc_init(void); + +/* AES-CBC decryption; the chaining value carries over between calls. 16-byte aligned. */ +typedef struct { + _Alignas(16) uint32_t w[(1 + 1 + 15) * 4]; +} xrc_aes_t; +void xrc_aes_init(xrc_aes_t *c, const uint8_t *key, unsigned keylen, const uint8_t iv[16]); +/* `data` 16-byte aligned, `nblocks` blocks of 16, in place. */ +void xrc_aes_dec(xrc_aes_t *c, uint8_t *data, size_t nblocks); + +/* RAR 3/4: the AES-128 key and IV from a password (UTF-8, used as UTF-16LE) and an 8-byte salt + * (NULL: no salt). 0, or -1 when the password is too long. Results are cached. */ +int xrc_kdf3(const char *password, const uint8_t *salt8, uint8_t key[16], uint8_t iv[16]); + +/* RAR5: from the password (UTF-8), a 16-byte salt and log2 of the iteration count, the AES-256 key, + * the key for checksums (`hashkey`) and the 8-byte password check. 0, or -1 (count out of range). + * Results are cached. */ +int xrc_kdf5(const char *password, const uint8_t salt[16], unsigned lg2, uint8_t key[32], uint8_t hashkey[32], + uint8_t check[8]); + +/* RAR5's stored check value (12 bytes: check, then the first 4 bytes of its SHA-256): 1 when its + * own checksum holds (the check can be trusted), else 0. */ +int xrc_check5_valid(const uint8_t stored[12]); + +/* RAR5 files whose checksums are keyed ("tweaked"): the stored CRC32 / BLAKE2sp digest is this + * function of the real one. */ +uint32_t xrc_mac_crc(const uint8_t hashkey[32], uint32_t crc); +void xrc_mac_blake(const uint8_t hashkey[32], const uint8_t digest[32], uint8_t out[32]); + +/* Clears the cached keys (they derive from the password). */ +void xrc_forget(void); + +/* Zeroes memory in a way the compiler keeps. */ +void xrc_wipe(void *p, size_t n); + +#endif diff --git a/payload/extractor/tests/fixtures/README.md b/payload/extractor/tests/fixtures/README.md index ee312254a..663cdabce 100644 --- a/payload/extractor/tests/fixtures/README.md +++ b/payload/extractor/tests/fixtures/README.md @@ -10,3 +10,6 @@ uudecoded and renamed: | rar5-symlink.rar | test_read_format_rar5_symlink.rar | | rar5-solid.part01-04.rar | test_read_format_rar5_multiarchive_solid.part01-04.rar | | rar4-multi.part1-6.rar | test_rar_multivolume_multiple_files.part1-6.rar | + +`pw-*.rar` (#958, password-protected RAR) were made by `../make_encrypted_rar.py` with RAR 7.23 +(RAR5) and RAR 6.24 (RAR 4, `-ma4`) from files that script makes; the passwords are in it. diff --git a/payload/extractor/tests/fixtures/pw-rar4-data.rar b/payload/extractor/tests/fixtures/pw-rar4-data.rar new file mode 100644 index 000000000..ea9fb07bb Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar4-data.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar4-headers.rar b/payload/extractor/tests/fixtures/pw-rar4-headers.rar new file mode 100644 index 000000000..0e98903b6 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar4-headers.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar4-multi.part1.rar b/payload/extractor/tests/fixtures/pw-rar4-multi.part1.rar new file mode 100644 index 000000000..75209557f Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar4-multi.part1.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar4-multi.part2.rar b/payload/extractor/tests/fixtures/pw-rar4-multi.part2.rar new file mode 100644 index 000000000..b9328eec4 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar4-multi.part2.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar4-multi.part3.rar b/payload/extractor/tests/fixtures/pw-rar4-multi.part3.rar new file mode 100644 index 000000000..00715b17d Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar4-multi.part3.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar4-stored.rar b/payload/extractor/tests/fixtures/pw-rar4-stored.rar new file mode 100644 index 000000000..7d54dcfac Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar4-stored.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-blake2.rar b/payload/extractor/tests/fixtures/pw-rar5-blake2.rar new file mode 100644 index 000000000..587bed60f Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-blake2.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-data.rar b/payload/extractor/tests/fixtures/pw-rar5-data.rar new file mode 100644 index 000000000..e01670a3a Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-data.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-headers.rar b/payload/extractor/tests/fixtures/pw-rar5-headers.rar new file mode 100644 index 000000000..aa296aa45 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-headers.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-multi.part1.rar b/payload/extractor/tests/fixtures/pw-rar5-multi.part1.rar new file mode 100644 index 000000000..6ccae3309 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-multi.part1.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-multi.part2.rar b/payload/extractor/tests/fixtures/pw-rar5-multi.part2.rar new file mode 100644 index 000000000..89d2951e1 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-multi.part2.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-multi.part3.rar b/payload/extractor/tests/fixtures/pw-rar5-multi.part3.rar new file mode 100644 index 000000000..8f5b6aa3e Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-multi.part3.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part1.rar b/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part1.rar new file mode 100644 index 000000000..3267e2a5a Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part1.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part2.rar b/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part2.rar new file mode 100644 index 000000000..2ca3e0c59 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part2.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part3.rar b/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part3.rar new file mode 100644 index 000000000..9132ca19f Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-solid-multi.part3.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part1.rar b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part1.rar new file mode 100644 index 000000000..8c6c5ff23 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part1.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part2.rar b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part2.rar new file mode 100644 index 000000000..f9f260d04 Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part2.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part3.rar b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part3.rar new file mode 100644 index 000000000..e6ffa40ef Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part3.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part4.rar b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part4.rar new file mode 100644 index 000000000..582d7e8af Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-stored-multi.part4.rar differ diff --git a/payload/extractor/tests/fixtures/pw-rar5-stored.rar b/payload/extractor/tests/fixtures/pw-rar5-stored.rar new file mode 100644 index 000000000..d5124102b Binary files /dev/null and b/payload/extractor/tests/fixtures/pw-rar5-stored.rar differ diff --git a/payload/extractor/tests/make_encrypted_rar.py b/payload/extractor/tests/make_encrypted_rar.py new file mode 100644 index 000000000..5e541662a --- /dev/null +++ b/payload/extractor/tests/make_encrypted_rar.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Makes the password-protected RAR fixtures (tests/fixtures/pw-*.rar). + +Needs RAR itself (rarlab.com): RAR 7 for the RAR5 ones and RAR 6 for the RAR 3/4 ones (RAR 7 no +longer writes RAR 4). Run once; the archives are committed and run.py checks what they hold +against the same files, made by encrypted_rar_files() below. + + python3 make_encrypted_rar.py /path/to/rar7 /path/to/rar6 +""" +import hashlib +import os +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +FIXTURES = os.path.join(HERE, "fixtures") + +# RAR5 takes the password as UTF-8; the RAR 4 one is 46 characters, which takes RAR 3's key +# derivation through its long-password quirk. +PW5 = "pässwörd RAR5" +PW4 = "this is a long RAR 4 password, 46 characters!!" + + +def encrypted_rar_files(): + """The files in every pw-* fixture: name -> bytes.""" + noise, h = b"", b"seed" + while len(noise) < 40000: + h = hashlib.sha256(h).digest() + noise += h + return { + "a.txt": b"hello\n", + "sub/b.bin": noise[:40000], + "sub/deep/c.txt": b"deep " * 3000, + "sub/empty.txt": b"", + "sub/odd.bin": noise[:1001], + } + + +# name, rar binary (5 or 4), switches +CASES = [ + ("pw-rar5-data.rar", 5, ["-p" + PW5]), + ("pw-rar5-headers.rar", 5, ["-hp" + PW5]), + ("pw-rar5-stored.rar", 5, ["-m0", "-p" + PW5]), + ("pw-rar5-blake2.rar", 5, ["-htb", "-p" + PW5]), + ("pw-rar5-multi.rar", 5, ["-hp" + PW5, "-v17k"]), + ("pw-rar5-solid-multi.rar", 5, ["-s", "-p" + PW5, "-v17k"]), + ("pw-rar5-stored-multi.rar", 5, ["-m0", "-p" + PW5, "-v17k"]), + ("pw-rar4-data.rar", 4, ["-ma4", "-p" + PW4]), + ("pw-rar4-headers.rar", 4, ["-ma4", "-hp" + PW4]), + ("pw-rar4-stored.rar", 4, ["-ma4", "-m0", "-p" + PW4]), + ("pw-rar4-multi.rar", 4, ["-ma4", "-hp" + PW4, "-v17k"]), +] + + +def main(): + rar5, rar4 = sys.argv[1], sys.argv[2] + src = tempfile.mkdtemp(prefix="pw-rar-src-") + try: + for name, data in encrypted_rar_files().items(): + p = os.path.join(src, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + for name, ver, sw in CASES: + for old in os.listdir(FIXTURES): + if old == name or old.startswith(name[:-4] + ".part"): + os.unlink(os.path.join(FIXTURES, old)) + exe = rar5 if ver == 5 else rar4 + subprocess.run([exe, "a", "-idq", "-r", "-ep1", *sw, os.path.join(FIXTURES, name), "a.txt", "sub"], + cwd=src, check=True) + finally: + shutil.rmtree(src) + + +if __name__ == "__main__": + main() diff --git a/payload/extractor/tests/run.py b/payload/extractor/tests/run.py index 2501dba05..2c5cdc0f3 100644 --- a/payload/extractor/tests/run.py +++ b/payload/extractor/tests/run.py @@ -368,11 +368,107 @@ def test_rar_multivolume(root): check("rar missing volume", s["state"] == "failed" and s["message"].startswith(("fs_extract_missing_volume", "fs_extract_truncated")), s) -def test_rar_encrypted(root): +def test_rar_mixed_passwords(root): + # libarchive's own fixtures: a.txt and c.txt have no password, b.txt has "password", d.txt + # another one. The files the password opens are written; d.txt is a wrong password. copy_fixtures(root, ["rar4-encrypted.rar", "rar5-encrypted.rar"]) for n in ("rar4-encrypted.rar", "rar5-encrypted.rar"): - s = run(root, os.path.join(root, n), os.path.join(root, "o-" + n), password="password") - check(n, s["message"] == "fs_extract_rar_encrypted", s) + out = os.path.join(root, "o-" + n) + s = run(root, os.path.join(root, n), out, password="password") + check(n, s["state"] == "failed" and s["message"] == "fs_extract_wrong_password", s) + check(n, "d.txt" not in tree(out), "a file was kept under a wrong password") + s = run(root, os.path.join(root, n), os.path.join(root, "none-" + n)) + check(n + " none", s["message"] == "fs_extract_password_required", s) + + +# #958: password-protected RAR, made by tests/make_encrypted_rar.py (RAR 7 and RAR 6). +sys.path.insert(0, HERE) +import make_encrypted_rar as pwrar # noqa: E402 + +PW_RAR = { + "pw-rar5-data.rar": 1, "pw-rar5-headers.rar": 1, "pw-rar5-stored.rar": 1, "pw-rar5-blake2.rar": 1, + "pw-rar5-multi.part1.rar": 3, "pw-rar5-solid-multi.part1.rar": 3, "pw-rar5-stored-multi.part1.rar": 4, + "pw-rar4-data.rar": 1, "pw-rar4-headers.rar": 1, "pw-rar4-stored.rar": 1, "pw-rar4-multi.part1.rar": 3, +} + + +def pw_rar_copy(root, first): + n = PW_RAR[first] + names = [first] if n == 1 else [first.replace(".part1.", f".part{i}.") for i in range(1, n + 1)] + copy_fixtures(root, names) + return os.path.join(root, first), names + + +def pw_of(name): + return pwrar.PW5 if "rar5" in name else pwrar.PW4 + + +def files_in(top): + return {k.replace(os.sep, "/"): v for k, v in tree(top).items()} if os.path.exists(top) else {} + + +def test_rar_passwords(root): + want = pwrar.encrypted_rar_files() + for first in PW_RAR: + arc, _ = pw_rar_copy(root, first) + out = os.path.join(root, "ok-" + first) + s = run(root, arc, out, password=pw_of(first)) + got = files_in(out) + check(first, s["state"] == "done" and got == want, (s, sorted(got))) + check(first, s["files"] == len(want), s) + # No password: refused before the folder is made. + out = os.path.join(root, "none-" + first) + s = run(root, arc, out) + check(first + " none", s["message"] == "fs_extract_password_required", s) + check(first + " none", not os.path.exists(out), "a folder was made without the password") + # A wrong one: refused, nothing written. RAR 3/4 with only the data encrypted has no + # password check, so its first file is decoded (and dropped) first; the helper then removes + # the folder this run made. + out = os.path.join(root, "bad-" + first) + s = run(root, arc, out, password="not the password") + check(first + " wrong", s["state"] == "failed" and s["message"] == "fs_extract_wrong_password", s) + check(first + " wrong", not files_in(out), files_in(out)) + if first not in ("pw-rar4-data.rar", "pw-rar4-stored.rar"): + check(first + " wrong", not os.path.exists(out), "a folder was made under a wrong password") + + +def test_rar_password_list_and_volumes(root): + # Listing: the names are readable without the password unless the headers are encrypted. + arc, _ = pw_rar_copy(root, "pw-rar5-data.rar") + s = run(root, arc, os.path.join(root, "l1"), list_only=True) + check("list data-only", s["state"] == "done" and sorted(s["top"].split("/")) == ["a.txt", "sub"], s) + arc, _ = pw_rar_copy(root, "pw-rar4-headers.rar") + s = run(root, arc, os.path.join(root, "l2"), list_only=True) + check("list headers none", s["message"] == "fs_extract_password_required", s) + s = run(root, arc, os.path.join(root, "l3"), list_only=True, password=pwrar.PW4) + check("list headers", s["state"] == "done" and sorted(s["top"].split("/")) == ["a.txt", "sub"], s) + # A volume missing in the middle of an encrypted file. + arc, names = pw_rar_copy(root, "pw-rar5-multi.part1.rar") + os.unlink(os.path.join(root, names[1])) + s = run(root, arc, os.path.join(root, "m1"), password=pwrar.PW5) + check("missing volume", s["state"] == "failed" + and s["message"].startswith(("fs_extract_missing_volume", "fs_extract_truncated")), s) + # Not enough room: known before anything is made (the sizes come from the decrypted headers). + arc, _ = pw_rar_copy(root, "pw-rar4-headers.rar") + s = run(root, arc, os.path.join(root, "sp"), password=pwrar.PW4, env={"XTEST_FREE": str(1 << 20)}) + check("space", s["message"].startswith("fs_extract_no_space: needs"), s) + check("space", not os.path.exists(os.path.join(root, "sp")), "made the folder anyway") + + +def test_rar_password_damaged(root): + # Damaged encrypted data under the right password (RAR5 checks the password itself): damage, + # not a wrong password, and the damaged file is not kept. + arc, _ = pw_rar_copy(root, "pw-rar5-data.rar") + data = bytearray(open(arc, "rb").read()) + at = data.find(b"b.bin") + for i in range(at + 2000, at + 2016): + data[i] ^= 0x5A + with open(arc, "wb") as f: + f.write(data) + out = os.path.join(root, "o") + s = run(root, arc, out, password=pwrar.PW5) + check("damaged", s["state"] == "failed" and s["message"].startswith("fs_extract_corrupt"), s) + check("damaged", "sub/b.bin" not in files_in(out), "the damaged file was kept") # ---- damage ---- diff --git a/payload/gen/ava1_app_gen.h b/payload/gen/ava1_app_gen.h index fe15cb63d..c02d74d59 100644 --- a/payload/gen/ava1_app_gen.h +++ b/payload/gen/ava1_app_gen.h @@ -153,6 +153,7 @@ #define AVA1_METHOD_SAVE_OWNER 199ULL #define AVA1_METHOD_NODE_UNINSTALL 200ULL #define AVA1_METHOD_TROPHY_FIX 201ULL +#define AVA1_METHOD_APP_RESTORE 202ULL #define AVA1_JOB_OP_DELETE 1ULL #define AVA1_JOB_OP_CHMOD_R 2ULL #define AVA1_JOB_OP_HASH 3ULL diff --git a/payload/include/config.h b/payload/include/config.h index 8e93c957c..f6a5e5062 100644 --- a/payload/include/config.h +++ b/payload/include/config.h @@ -5,7 +5,7 @@ * UI tell apart an old payload still running from a build that includes * a particular fix, without having to boot the console. Keep in sync * with the desktop app's package.json during releases. */ -#define PS5UPLOAD2_VERSION "12.6.36" +#define PS5UPLOAD2_VERSION "12.6.37" /* Author credit — embedded in the startup toast so anyone looking at * the console screen knows who wrote the software that just loaded. * Kept separate from VERSION so release scripts can bump the version diff --git a/payload/include/content_db.h b/payload/include/content_db.h index 5bb78f11b..9eb3a51dc 100644 --- a/payload/include/content_db.h +++ b/payload/include/content_db.h @@ -168,6 +168,20 @@ int content_db_appinfo_json(const char *title_id, const char *keys, */ int content_db_appinfo_get(const char *title_id, const char *key, char *out, size_t cap); +/* + * Whether appinfo.db has any row for `title_id` (Settings > Storage's record of the title). + * Read-only. 1 / 0, or -1 when appinfo.db could not be read or the id is not a title id. + */ +int content_db_appinfo_has_title(const char *title_id); + +/* + * A consistent copy of the database at `src_path` into a NEW file `dst_path`, through SQLite's + * backup API (safe while the shell has the database open; nothing is written to the source). + * `dst_path` must not exist yet: an existing file is never replaced. 0, or -1 with a short reason + * in `err` (a half-written copy is removed). + */ +int content_db_backup_file(const char *src_path, const char *dst_path, char *err, size_t errcap); + /* * Set one appinfo.db value. This writes to a live system database. * diff --git a/payload/include/cross_device.h b/payload/include/cross_device.h index 819a867fa..5d84d591e 100644 --- a/payload/include/cross_device.h +++ b/payload/include/cross_device.h @@ -66,6 +66,9 @@ * src/webui_files.c 2 dir text save and upload: .ps5u-<hex>.part beside the target -> target * (the device is compared too, same_device_as, failing closed) * src/trophy_fix.c 1 dir a trophy file fixed or put back: <file>.ps5upload-tmp -> file (same folder) + * src/title_restore.c 2 1 guard (an installed game's app.pkg / patch.pkg moved aside to + * <drive>/ps5upload/restore/<id> and back: safe_move, only on + * XDEV_SAME and never over an entry, #961), 1 dir (restore.txt: tmp -> final) * ava1/ava1_events.c 1 dir events.log -> events.log.old * ava1/ava1_apply.c 3 guard file and folder commit (same_device hook, only a definite 1 renames); * held param.json/param.sfo: name.ava-hold -> name, same dir diff --git a/payload/include/title_restore.h b/payload/include/title_restore.h new file mode 100644 index 000000000..e3ecec8d4 --- /dev/null +++ b/payload/include/title_restore.h @@ -0,0 +1,92 @@ +/* Putting an installed package game back on the home screen (#961). + * + * What happens to the user: after Settings › Rebuild Database (Safe Mode, where no fake-package + * support is loaded), every game installed from a fake package disappears from the home screen + * and from Settings › Storage, but its files stay: <volume>/user/app/<id>/app.pkg (internal, USB + * extended storage /mnt/ext0, M.2 /mnt/ext1). Only a full reinstall brought them back. + * + * What this does instead: hand the package that is already on the console to the console's own + * installer again, the same as installing it the first time, so Sony's code writes every record. + * Nothing here writes app.db or appinfo.db. + * + * The package cannot be installed from where it sits: the installer writes <volume>/user/app/<id> + * while it reads its source, and it clears an old install before writing the new one (the engine + * refuses an install whose source is an installed game's own file for that reason). So: + * + * check read-only: is this title restorable, and why not if not. + * prepare back up app.db and appinfo.db, then MOVE app.pkg (and the title's update, patch.pkg, + * if it is on the same drive) aside on the SAME drive: <volume>/ps5upload/restore/<id>/ + * (/user/ps5upload/restore/<id> for the internal drive). A same-device rename only + * (cross_device.h: a rename across devices panics this kernel), so no copy and no extra + * space. A record (restore.txt) is written there first, so an interrupted restore is + * found again. The engine then installs <aside>/app.pkg. + * finish after the install ended (TITLE_RESTORE_INSTALL_ENDED). When app.db has the title and + * an app.pkg exists in a <volume>/user/app/<id> again: the copy aside is deleted and the + * update put back where it was. With TITLE_RESTORE_ROLLBACK (the install failed): the + * package and the update go back where they were, only if the title is still not in + * app.db and the place is still free. + * Anything else (the install still running, the database unreadable, the place taken) + * keeps every file and says so. + * + * Refused, before anything is touched: a title id that is not one, a system app, a title app.db + * knows (it IS on the home screen: never touched), a title appinfo.db has a record for (the + * console knows it somewhere: never touched), a folder registration (mount.lnk: not a package), + * the same title's app.pkg on two drives, a package whose header says retail-signed, no drive with + * room for the copy the installer writes, an aside folder on another device, or a database that + * could not be read ("can't tell" is never "not there"). + * + * The file operations and the decisions are here; the database answers come through callbacks so + * the host self-test runs the whole flow on a scratch folder (payload/tests/title_restore_selftest.c). */ +#ifndef PS5UPLOAD_TITLE_RESTORE_H +#define PS5UPLOAD_TITLE_RESTORE_H + +#include <stddef.h> +#include <stdint.h> + +#define TITLE_RESTORE_BACKUP_ROOT "/data/ps5upload/backup/restore" +#define TITLE_RESTORE_RECORD "restore.txt" +/* At most this many volumes are looked at: internal, ext0, ext1 and the mount table's others. */ +#define TITLE_RESTORE_MAX_VOLUMES 12 + +typedef struct { + /* Prepended to every console path for file operations ("" or NULL on the console; a scratch + * folder in the host test). Replies always name console paths. */ + const char *prefix; + /* NULL: TITLE_RESTORE_BACKUP_ROOT (the prefix applies). */ + const char *backup_root; + /* Mount points from the mount table; only /mnt/ext<N> ones count, ext0/ext1 are always looked at. */ + const char *const *extra_volumes; + int nextra; + /* app.db / appinfo.db: 1 the title has a row, 0 none, -1 could not be read. */ + int (*appdb_has)(const char *title_id); + int (*appinfo_has)(const char *title_id); + /* Copy the database `which` ("app.db" or "appinfo.db") to the new file `dst` (prefix applied + * already). 0, or -1 with a reason in err. */ + int (*backup_db)(const char *which, const char *dst, char *err, size_t errcap); + /* Free bytes for a writer under `dir` (prefix applied). NULL: statvfs. 0, or -1. */ + int (*free_bytes)(const char *dir, uint64_t *out); +} title_restore_env_t; + +/* finish's flags. INSTALL_ENDED: the caller knows the install of the copy aside has ended (the + * engine's install job reached its verdict, or the user saw the game start); only then is the copy + * aside deleted. ROLLBACK: it ended without putting the game back, so the files go back where they + * were (implies the install ended: a running install could write into the place). */ +#define TITLE_RESTORE_ROLLBACK 1 +#define TITLE_RESTORE_INSTALL_ENDED 2 + +/* op "check" | "prepare" | "finish" (with `flags`). `stamp` names the backup folder (prepare; + * "20261126-101500"). Writes one JSON object into out and returns its length, or -1 when it did + * not fit. + * + * Every reply has "ok" and "state": + * check: restorable | registered | record_elsewhere | not_installed | pending | + * folder_registration | ambiguous | retail | no_room | aside_cross_device | + * db_unreadable | invalid_title | system_title (ok:true: an answer, not a failure) + * prepare: prepared (ok:true), else ok:false with err "restore_<check state>" or + * restore_backup_failed / restore_move_failed / restore_aside_busy + * finish: restored | rolled_back | nothing_pending (ok:true); + * waiting | unsettled (ok:true, files kept; "reason" says why) */ +int title_restore_run(const title_restore_env_t *env, const char *op, const char *title_id, + int flags, const char *stamp, char *out, size_t cap); + +#endif /* PS5UPLOAD_TITLE_RESTORE_H */ diff --git a/payload/src/content_db.c b/payload/src/content_db.c index 0c8e57df4..de225a6a3 100644 --- a/payload/src/content_db.c +++ b/payload/src/content_db.c @@ -686,6 +686,61 @@ int content_db_appinfo_get(const char *title_id, const char *key, char *out, siz return found; } +int content_db_appinfo_has_title(const char *title_id) { + if (!cdb_valid_title_id(title_id)) return -1; + sqlite3 *db = NULL; + if (cdb_open_ro(CONTENT_DB_APPINFO, &db, NULL) != SQLITE_OK || !db) return -1; + sqlite3_stmt *st = NULL; + if (sqlite3_prepare_v2(db, "SELECT 1 FROM tbl_appinfo WHERE titleId = ? LIMIT 1", -1, &st, + NULL) != SQLITE_OK) { + sqlite3_close(db); + return -1; + } + sqlite3_bind_text(st, 1, title_id, -1, SQLITE_STATIC); + int rc = sqlite3_step(st); + int found = rc == SQLITE_ROW ? 1 : rc == SQLITE_DONE ? 0 : -1; + sqlite3_finalize(st); + sqlite3_close(db); + return found; +} + +int content_db_backup_file(const char *src_path, const char *dst_path, char *err, size_t errcap) { + if (!err || errcap == 0) return -1; + err[0] = '\0'; + if (!src_path || !dst_path || !src_path[0] || !dst_path[0]) { + snprintf(err, errcap, "backup: no path"); + return -1; + } + if (access(dst_path, F_OK) == 0) { + snprintf(err, errcap, "backup: the copy already exists"); + return -1; + } + sqlite3 *src = NULL; + if (cdb_open_ro(src_path, &src, NULL) != SQLITE_OK || !src) { + snprintf(err, errcap, "backup: cannot read %s", src_path); + return -1; + } + sqlite3 *dst = NULL; + int ok = 0; + if (sqlite3_open_v2(dst_path, &dst, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) == + SQLITE_OK && + dst) { + sqlite3_backup *b = sqlite3_backup_init(dst, "main", src, "main"); + if (b) { + ok = sqlite3_backup_step(b, -1) == SQLITE_DONE; + sqlite3_backup_finish(b); + } + } + if (dst) sqlite3_close(dst); + sqlite3_close(src); + if (!ok) { + unlink(dst_path); + snprintf(err, errcap, "backup: could not copy %s", src_path); + return -1; + } + return 0; +} + int content_db_appinfo_set(const char *title_id, const char *key, const char *val, char *err, size_t errcap) { #define CDB_FAIL(msg) do { snprintf(err, errcap, "%s", (msg)); goto fail; } while (0) diff --git a/payload/src/mgmt_table.def b/payload/src/mgmt_table.def index e2d1b99f9..64ea305d6 100644 --- a/payload/src/mgmt_table.def +++ b/payload/src/mgmt_table.def @@ -155,6 +155,8 @@ MGMT_H1(AVA1_METHOD_SAVE_OWNER, MGMT_FRAME_SAVE_OWNER, MGMT_FRAME_SAVE_OWNER_ACK MGMT_H1(AVA1_METHOD_NODE_UNINSTALL, MGMT_FRAME_NODE_UNINSTALL, MGMT_FRAME_NODE_UNINSTALL_ACK, MGMT_SONY, handle_node_uninstall, mgmt_call_text_keep) /* trophy files that still name an old account id (trophy_fix.c, #853): file reads and writes only */ MGMT_H1(AVA1_METHOD_TROPHY_FIX, MGMT_FRAME_TROPHY_FIX, MGMT_FRAME_TROPHY_FIX_ACK, 0, mgmt_w_trophy_fix, mgmt_call_text_keep) +/* an installed package game back on the home screen after Rebuild Database (title_restore.c, #961): file moves on one drive, read-only database queries */ +MGMT_H1(AVA1_METHOD_APP_RESTORE, MGMT_FRAME_TITLE_RESTORE, MGMT_FRAME_TITLE_RESTORE_ACK, 0, mgmt_w_title_restore, mgmt_call_text_keep) /* ---- console file manager (PC side): shared pinned/recent folders, Show on TV / Show on PC ---- */ MGMT_H0(AVA1_METHOD_FILES_PREFS_GET, MGMT_FRAME_FILES_PREFS_GET, MGMT_FRAME_FILES_PREFS_GET_ACK, 0, handle_files_prefs_get, mgmt_call_text) MGMT_H1(AVA1_METHOD_FILES_PREFS_SET, MGMT_FRAME_FILES_PREFS_SET, MGMT_FRAME_FILES_PREFS_SET_ACK, 0, handle_files_prefs_set, mgmt_call_text) diff --git a/payload/src/register.c b/payload/src/register.c index 6c8a6d934..b320e2ae3 100644 --- a/payload/src/register.c +++ b/payload/src/register.c @@ -2220,6 +2220,37 @@ int launch_title(const char *title_id, const char **err_reason_out, int rc_ss = launch_via_system_service(title_id, fg_user); if (launch_sys_ok(rc_ss)) return 0; + /* #961: a title app.db has no row for cannot be started by any route, and the routes below + * for a refused launch are the ShellUI ptrace call (twice) and three more launcher calls. For + * a game whose record Rebuild Database dropped (its package still on the drive), that ladder + * left the console unsettled: the system UI restarted back to the home screen and homebrew + * running inside it stopped (the #961 report). So when app.db, read successfully, does not + * know the title, and still does not after a short wait (a register that just ran may not be + * written yet), the launch ends here with launch_not_in_database: the app then offers to put + * the game back on the home screen instead. An unreadable app.db (-1) keeps the old ladder. */ + if (register_appdb_has_title(title_id) == 0) { + int known = 0; + for (int i = 0; i < 6 && !known; i++) { + usleep(500 * 1000); + /* A refused-looking call that started the title after all (launch_took_effect). */ + if (proc_find_pid_by_title_id(title_id) > 0) return 0; + known = register_appdb_has_title(title_id) != 0; + } + if (!known) { + fprintf(stderr, + "[payload2] launch %s: not in app.db (launcher rc=0x%x): not trying the other " + "routes\n", + title_id, (unsigned)rc_ss); + if (reason_buf && reason_cap > 0) { + snprintf(reason_buf, reason_cap, "launch_not_in_database: rc=0x%08x", (unsigned int)rc_ss); + if (err_reason_out) *err_reason_out = reason_buf; + } else if (err_reason_out) { + *err_reason_out = "launch_not_in_database"; + } + return -1; + } + } + (void)shellui_rpc_init(); if (shellui_rpc_ready()) { /* rc > 0 means "Sony's function ran and refused"; the code it gave is diff --git a/payload/src/runtime.c b/payload/src/runtime.c index ecb794d58..9e1fa051c 100644 --- a/payload/src/runtime.c +++ b/payload/src/runtime.c @@ -104,6 +104,7 @@ #include "tailnet_node.h" #include "save_owner.h" #include "trophy_fix.h" +#include "title_restore.h" #include "game_fps.h" #include "ava1_server.h" #include "ava1_data.h" @@ -396,6 +397,9 @@ /* trophy files that still name an old account id (trophy_fix.c, #853) */ #define MGMT_FRAME_TROPHY_FIX 374u #define MGMT_FRAME_TROPHY_FIX_ACK 375u +/* an installed package game back on the home screen after Rebuild Database (title_restore.c, #961) */ +#define MGMT_FRAME_TITLE_RESTORE 376u +#define MGMT_FRAME_TITLE_RESTORE_ACK 377u #define MGMT_FRAME_SDK_SCAN 214u #define MGMT_FRAME_SDK_SCAN_ACK 215u #define MGMT_FRAME_SDK_PATCH 216u @@ -10167,6 +10171,76 @@ static int handle_trophy_fix(const char *body) { return rc; } +/* app.restore (title_restore.c, #961). Body {"op":"check"|"prepare"|"finish","title_id":"PPSA01234", + * "rollback":b,"install_ended":b}. File operations only (stat, mkdir, a same-device rename checked with + * cross_device.h, unlink of our own copy) plus read-only app.db / appinfo.db queries and SQLite backup + * copies of both: no Sony call, so no sony_api_lock. The install between prepare and finish is the + * engine's (installer daemon). */ +static int restore_appdb_has(const char *id) { return content_db_has_title(id); } +static int restore_appinfo_has(const char *id) { return content_db_appinfo_has_title(id); } +static int restore_backup_db(const char *which, const char *dst, char *err, size_t cap) { + const char *src = strcmp(which, "app.db") == 0 ? CONTENT_DB_APP + : strcmp(which, "appinfo.db") == 0 ? CONTENT_DB_APPINFO + : NULL; + if (!src) { + snprintf(err, cap, "backup: unknown database"); + return -1; + } + return content_db_backup_file(src, dst, err, cap); +} + +#define TITLE_RESTORE_OUT_MAX 4096u +static int handle_title_restore(const char *body) { + char op[16] = {0}, title_id[16] = {0}; + extract_json_string_field(body, "op", op, sizeof(op)); + extract_json_string_field(body, "title_id", title_id, sizeof(title_id)); + int rollback = 0, ended = 0; + (void)extract_json_bool_field(body, "rollback", &rollback); + (void)extract_json_bool_field(body, "install_ended", &ended); + /* The extended drives the mount table shows (/mnt/ext<N>), besides ext0 and ext1. */ + char vols[TITLE_RESTORE_MAX_VOLUMES][32]; + const char *extra[TITLE_RESTORE_MAX_VOLUMES]; + int nextra = 0; + { + struct statfs *mnts = NULL; + int n = mntinfo_snapshot(&mnts); + for (int i = 0; i < n && nextra < TITLE_RESTORE_MAX_VOLUMES; i++) { + if (!install_guard_is_ext_volume(mnts[i].f_mntonname) || strlen(mnts[i].f_mntonname) >= sizeof vols[0]) + continue; + snprintf(vols[nextra], sizeof vols[nextra], "%s", mnts[i].f_mntonname); + extra[nextra] = vols[nextra]; + nextra++; + } + free(mnts); + } + title_restore_env_t env; + memset(&env, 0, sizeof env); + env.extra_volumes = extra; + env.nextra = nextra; + env.appdb_has = restore_appdb_has; + env.appinfo_has = restore_appinfo_has; + env.backup_db = restore_backup_db; + char stamp[32]; + { + time_t now = time(NULL); + struct tm tmv; + if (!gmtime_r(&now, &tmv)) memset(&tmv, 0, sizeof(tmv)); + strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", &tmv); + } + int flags = (rollback ? TITLE_RESTORE_ROLLBACK : 0) | (ended ? TITLE_RESTORE_INSTALL_ENDED : 0); + char *out = malloc(TITLE_RESTORE_OUT_MAX); + if (!out) { + static const char oom[] = "{\"ok\":false,\"err\":\"no_memory\"}"; + return mgmt_reply(MGMT_FRAME_TITLE_RESTORE_ACK, oom, sizeof(oom) - 1); + } + int n = title_restore_run(&env, op[0] ? op : "check", title_id, flags, stamp, out, TITLE_RESTORE_OUT_MAX); + if (n < 0) n = snprintf(out, TITLE_RESTORE_OUT_MAX, "{\"ok\":false,\"err\":\"reply_too_large\"}"); + PLOG(PLOG_INFO, PLOG_INSTALL, "[restore] %s %s: %.*s", op[0] ? op : "check", title_id, n > 300 ? 300 : n, out); + int rc = mgmt_reply(MGMT_FRAME_TITLE_RESTORE_ACK, out, (uint64_t)n); + free(out); + return rc; +} + static int handle_profile_apply_avatar(const char *body) { uint32_t uid = (uint32_t)extract_json_uint64_field(body, "uid"); if (uid == 0) { @@ -10532,6 +10606,11 @@ static int mgmt_w_trophy_fix(runtime_state_t *st, const char *b, uint64_t l) { (void)l; return handle_trophy_fix(b); } +static int mgmt_w_title_restore(runtime_state_t *st, const char *b, uint64_t l) { + (void)st; + (void)l; + return handle_title_restore(b); +} static int mgmt_w_profile_activate(runtime_state_t *st, const char *b, uint64_t l) { (void)st; (void)l; diff --git a/payload/src/title_restore.c b/payload/src/title_restore.c new file mode 100644 index 000000000..d92439d5f --- /dev/null +++ b/payload/src/title_restore.c @@ -0,0 +1,645 @@ +/* ps5upload — putting an installed package game back on the home screen (#961). See title_restore.h. + * + * Only file operations: stat, mkdir, a same-device rename (checked first with cross_device.h), + * unlink of our own copy, and the small record file. No Sony call (the install itself is the + * engine's, through the installer daemon), so no sony_api_lock. One restore operation at a time + * (g_restore_lock): two finishes of one title must not both move its package. */ + +#include <errno.h> +#include <fcntl.h> +#include <pthread.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <sys/statvfs.h> +#include <unistd.h> + +#include "cross_device.h" +#include "install_guard.h" +#include "statvfs_avail.h" +#include "title_restore.h" + +#define TR_PATH 640 + +static pthread_mutex_t g_restore_lock = PTHREAD_MUTEX_INITIALIZER; + +typedef struct { + char vol[32]; /* "" internal, else /mnt/ext<N> */ + char app_dir[96]; /* <vol>/user/app/<id> (internal: /user/app/<id>) */ + char pkg[128]; /* <app_dir>/app.pkg */ + char patch[128]; /* <vol>/user/patch/<id>/patch.pkg */ + char aside[128]; /* <vol>/ps5upload/restore/<id> (internal: /user/ps5upload/restore/<id>) */ + char root[32]; /* the volume's root, for free space: <vol> or /user */ +} tr_vol_t; + +typedef struct { + const char *state; + const char *reason; /* a word for logs and the UI, may be NULL */ + int vol; /* index of the volume with the package (or the pending record), -1 none */ + uint64_t size, patch_size, free_volume, free_internal; + int have_patch; /* a patch.pkg on the package's drive */ + const char *kind; /* "fake" | "ps4" | "unknown" */ + int free_known; +} tr_info_t; + +static const char *pfx(const title_restore_env_t *env) { + return env && env->prefix ? env->prefix : ""; +} + +/* <prefix><path> into buf; 0, or -1 when it does not fit. */ +static int real_path(const title_restore_env_t *env, const char *path, char *buf, size_t cap) { + int n = snprintf(buf, cap, "%s%s", pfx(env), path); + return (n > 0 && (size_t)n < cap) ? 0 : -1; +} + +static int exists(const title_restore_env_t *env, const char *path, struct stat *st) { + char p[TR_PATH]; + struct stat local; + if (real_path(env, path, p, sizeof p) != 0) return 0; + return lstat(p, st ? st : &local) == 0; +} + +/* The volumes: internal, ext0, ext1, then the mount table's other /mnt/ext<N>. */ +static int tr_volumes(const title_restore_env_t *env, const char *id, tr_vol_t *v, int max) { + const char *names[TITLE_RESTORE_MAX_VOLUMES]; + int n = 0; + names[n++] = ""; + names[n++] = "/mnt/ext0"; + names[n++] = "/mnt/ext1"; + for (int i = 0; env && env->extra_volumes && i < env->nextra && n < TITLE_RESTORE_MAX_VOLUMES; i++) { + const char *e = env->extra_volumes[i]; + if (!install_guard_is_ext_volume(e) || strlen(e) >= sizeof v[0].vol) continue; + int dup = 0; + for (int k = 0; k < n; k++) + if (strcmp(names[k], e) == 0) dup = 1; + if (!dup) names[n++] = e; + } + if (n > max) n = max; + for (int i = 0; i < n; i++) { + const char *vol = names[i]; + snprintf(v[i].vol, sizeof v[i].vol, "%s", vol); + snprintf(v[i].app_dir, sizeof v[i].app_dir, "%s/user/app/%s", vol, id); + snprintf(v[i].pkg, sizeof v[i].pkg, "%s/app.pkg", v[i].app_dir); + snprintf(v[i].patch, sizeof v[i].patch, "%s/user/patch/%s/patch.pkg", vol, id); + if (vol[0]) + snprintf(v[i].aside, sizeof v[i].aside, "%s/ps5upload/restore/%s", vol, id); + else + snprintf(v[i].aside, sizeof v[i].aside, "/user/ps5upload/restore/%s", id); + snprintf(v[i].root, sizeof v[i].root, "%s", vol[0] ? vol : "/user"); + } + return n; +} + +static int free_of(const title_restore_env_t *env, const char *dir, uint64_t *out) { + char p[TR_PATH]; + *out = 0; + if (real_path(env, dir, p, sizeof p) != 0) return -1; + if (env && env->free_bytes) return env->free_bytes(p, out); + struct statvfs sv; + if (statvfs(p, &sv) != 0) return -1; + *out = statvfs_avail_bytes(&sv); + return 0; +} + +/* What the package's first bytes say: "fake" (a PS5 package signed for debug), "retail" (a PS5 + * package with the retail byte: refused), "ps4" (a PS4 package: its header does not tell), or + * "unknown" (the installed file starts some other way; the installer decides). */ +static const char *pkg_kind(const title_restore_env_t *env, const char *pkg) { + char p[TR_PATH]; + unsigned char h[8] = {0}; + if (real_path(env, pkg, p, sizeof p) != 0) return "unknown"; + int fd = open(p, O_RDONLY); + if (fd < 0) return "unknown"; + ssize_t got = read(fd, h, sizeof h); + close(fd); + if (got < 8) return "unknown"; + if (h[0] == 0x7F && h[1] == 'F' && h[2] == 'I' && h[3] == 'H') return h[5] == 0x00 ? "fake" : "retail"; + if (h[0] == 0x7F && h[1] == 'C' && h[2] == 'N' && h[3] == 'T') return "ps4"; + return "unknown"; +} + +static int record_path(const tr_vol_t *v, char *buf, size_t cap) { + int n = snprintf(buf, cap, "%s/%s", v->aside, TITLE_RESTORE_RECORD); + return (n > 0 && (size_t)n < cap) ? 0 : -1; +} + +/* The volume holding a pending restore of this title (its record), or -1. */ +static int find_pending(const title_restore_env_t *env, const tr_vol_t *v, int nv) { + char rec[TR_PATH]; + for (int i = 0; i < nv; i++) + if (record_path(&v[i], rec, sizeof rec) == 0 && exists(env, rec, NULL)) return i; + return -1; +} + +/* The deepest existing ancestor of `path` (console path), for a device comparison before the + * folders exist. */ +static int nearest_dev(const title_restore_env_t *env, const char *path, unsigned long long *dev) { + char p[TR_PATH]; + if (real_path(env, path, p, sizeof p) != 0) return -1; + size_t floor = strlen(pfx(env)); + for (;;) { + struct stat st; + if (stat(p, &st) == 0) { + *dev = (unsigned long long)st.st_dev; + return 0; + } + char *s = strrchr(p, '/'); + if (!s || (size_t)(s - p) < floor) return -1; + if ((size_t)(s - p) == floor) { + /* the root itself */ + if (floor == 0) snprintf(p, sizeof p, "/"); + else *s = '\0'; + if (stat(p, &st) != 0) return -1; + *dev = (unsigned long long)st.st_dev; + return 0; + } + *s = '\0'; + } +} + +static void inspect(const title_restore_env_t *env, const char *id, tr_vol_t *v, int nv, tr_info_t *in) { + memset(in, 0, sizeof *in); + in->vol = -1; + in->kind = "unknown"; + int pending = find_pending(env, v, nv); + if (pending >= 0) { + in->vol = pending; + in->state = "pending"; + return; + } + int hits = 0; + for (int i = 0; i < nv; i++) { + struct stat st; + if (exists(env, v[i].pkg, &st)) { + if (hits++ == 0) { + in->vol = i; + in->size = (uint64_t)st.st_size; + } + } + } + if (hits == 0) { + in->state = "not_installed"; + return; + } + if (hits > 1) { + in->state = "ambiguous"; + in->reason = "the same title's app.pkg is on two drives"; + return; + } + const tr_vol_t *pv = &v[in->vol]; + { + struct stat st; + if (!exists(env, pv->pkg, &st) || !S_ISREG(st.st_mode)) { + in->state = "not_installed"; + in->reason = "app.pkg is not a file"; + return; + } + } + /* A folder registration (ours or ShadowMount+'s) is not a package install. */ + if (install_guard_has_tracker(pfx(env), id)) { + in->state = "folder_registration"; + return; + } + int db = env && env->appdb_has ? env->appdb_has(id) : -1; + if (db < 0) { + in->state = "db_unreadable"; + in->reason = "app.db"; + return; + } + if (db > 0) { + in->state = "registered"; + return; + } + int info = env && env->appinfo_has ? env->appinfo_has(id) : -1; + if (info < 0) { + in->state = "db_unreadable"; + in->reason = "appinfo.db"; + return; + } + if (info > 0) { + in->state = "record_elsewhere"; + return; + } + in->kind = pkg_kind(env, pv->pkg); + if (strcmp(in->kind, "retail") == 0) { + in->state = "retail"; + return; + } + { + struct stat st; + if (exists(env, pv->patch, &st) && S_ISREG(st.st_mode)) { + in->have_patch = 1; + in->patch_size = (uint64_t)st.st_size; + } + } + /* The installer writes a whole new copy where Settings › Storage › Installation location says: + * the package's own drive or the console's. One of them needs the room. */ + int fv = free_of(env, pv->root, &in->free_volume); + int fi = free_of(env, "/user", &in->free_internal); + in->free_known = fv == 0 || fi == 0; + if (in->free_known && !((fv == 0 && in->free_volume >= in->size) || (fi == 0 && in->free_internal >= in->size))) { + in->state = "no_room"; + return; + } + /* The move aside must stay on the package's device. */ + { + unsigned long long dpkg = 0, daside = 0; + char p[TR_PATH]; + struct stat st; + if (real_path(env, pv->pkg, p, sizeof p) != 0 || lstat(p, &st) != 0 || + nearest_dev(env, pv->aside, &daside) != 0) { + in->state = "aside_cross_device"; + in->reason = "the drive could not be checked"; + return; + } + dpkg = (unsigned long long)st.st_dev; + if (dpkg != daside) { + in->state = "aside_cross_device"; + return; + } + } + in->state = "restorable"; +} + +/* ---- JSON out ---- */ + +typedef struct { + char *b; + size_t cap, n; + int over; +} tr_out_t; + +static void put(tr_out_t *o, const char *fmt, ...) { + if (o->over) return; + va_list ap; + va_start(ap, fmt); + int k = vsnprintf(o->b + o->n, o->cap - o->n, fmt, ap); + va_end(ap); + if (k < 0 || (size_t)k >= o->cap - o->n) { + o->over = 1; + return; + } + o->n += (size_t)k; +} + +static int done(tr_out_t *o) { return o->over ? -1 : (int)o->n; } + +static const char *where_word(const tr_vol_t *v) { + return install_guard_word(install_guard_where_of(v->vol)); +} + +static void put_info(tr_out_t *o, const char *id, const tr_vol_t *v, const tr_info_t *in) { + put(o, "\"title_id\":\"%s\",\"state\":\"%s\"", id, in->state); + if (in->reason) put(o, ",\"reason\":\"%s\"", in->reason); + if (in->vol < 0) return; + const tr_vol_t *pv = &v[in->vol]; + put(o, ",\"where\":\"%s\",\"volume\":\"%s\",\"aside\":\"%s\"", where_word(pv), pv->root, pv->aside); + if (strcmp(in->state, "pending") == 0) return; + put(o, ",\"pkg\":\"%s\",\"size\":%llu,\"kind\":\"%s\"", pv->pkg, (unsigned long long)in->size, in->kind); + if (in->have_patch) + put(o, ",\"patch\":\"%s\",\"patch_size\":%llu", pv->patch, (unsigned long long)in->patch_size); + if (in->free_known) + put(o, ",\"free_volume\":%llu,\"free_internal\":%llu", (unsigned long long)in->free_volume, + (unsigned long long)in->free_internal); +} + +/* ---- the record ---- */ + +typedef struct { + int app; /* app.pkg was moved aside */ + int patch; /* patch.pkg was moved aside */ + char backup[256]; +} tr_record_t; + +static int write_record(const title_restore_env_t *env, const tr_vol_t *v, const tr_record_t *r) { + char rec[TR_PATH], p[TR_PATH]; + if (record_path(v, rec, sizeof rec) != 0 || real_path(env, rec, p, sizeof p) != 0) return -1; + char tmp[TR_PATH + 8]; + snprintf(tmp, sizeof tmp, "%s.tmp", p); + FILE *f = fopen(tmp, "w"); + if (!f) return -1; + int ok = fprintf(f, "app=%d\npatch=%d\nbackup=%s\n", r->app, r->patch, r->backup) > 0; + ok = fflush(f) == 0 && ok; + fsync(fileno(f)); + ok = fclose(f) == 0 && ok; + /* our own tmp file into its name in the same folder */ + if (!ok || rename(tmp, p) != 0) { + unlink(tmp); + return -1; + } + return 0; +} + +static int read_record(const title_restore_env_t *env, const tr_vol_t *v, tr_record_t *r) { + char rec[TR_PATH], p[TR_PATH], line[256]; + memset(r, 0, sizeof *r); + if (record_path(v, rec, sizeof rec) != 0 || real_path(env, rec, p, sizeof p) != 0) return -1; + FILE *f = fopen(p, "r"); + if (!f) return -1; + while (fgets(line, sizeof line, f)) { + line[strcspn(line, "\r\n")] = '\0'; + if (strncmp(line, "app=", 4) == 0) r->app = atoi(line + 4) == 1; + else if (strncmp(line, "patch=", 6) == 0) r->patch = atoi(line + 6) == 1; + else if (strncmp(line, "backup=", 7) == 0 && !strchr(line + 7, '"') && !strchr(line + 7, '\\')) + snprintf(r->backup, sizeof r->backup, "%s", line + 7); + } + fclose(f); + return 0; +} + +static void remove_record(const title_restore_env_t *env, const tr_vol_t *v) { + char rec[TR_PATH], p[TR_PATH]; + if (record_path(v, rec, sizeof rec) == 0 && real_path(env, rec, p, sizeof p) == 0) unlink(p); + /* The folder only when empty: rmdir never removes anything else. */ + if (real_path(env, v->aside, p, sizeof p) == 0) rmdir(p); +} + +/* mkdir -p of a console path (prefix applied), 0 when it exists as a folder afterwards. */ +static int mkdirs(const title_restore_env_t *env, const char *path) { + char p[TR_PATH]; + if (real_path(env, path, p, sizeof p) != 0) return -1; + size_t floor = strlen(pfx(env)); + for (char *s = p + floor + 1; *s; s++) { + if (*s != '/') continue; + *s = '\0'; + if (mkdir(p, 0777) != 0 && errno != EEXIST) { + *s = '/'; + return -1; + } + *s = '/'; + } + if (mkdir(p, 0777) != 0 && errno != EEXIST) return -1; + struct stat st; + return stat(p, &st) == 0 && S_ISDIR(st.st_mode) ? 0 : -1; +} + +/* A rename that this kernel survives: only when both ends are proven to be on one device + * (cross_device.h; anything but XDEV_SAME is refused), and never over an existing entry. */ +static int safe_move(const title_restore_env_t *env, const char *from, const char *to) { + char f[TR_PATH], t[TR_PATH]; + struct stat st; + if (real_path(env, from, f, sizeof f) != 0 || real_path(env, to, t, sizeof t) != 0) return -1; + if (lstat(t, &st) == 0) return -1; + if (!xdev_rename_is_safe(xdev_rename_crosses_l(f, t, xdev_lstat_dev, xdev_stat_dev))) return -1; + return rename(f, t) == 0 ? 0 : -1; +} + +static void aside_file(const tr_vol_t *v, const char *name, char *buf, size_t cap) { + snprintf(buf, cap, "%s/%s", v->aside, name); +} + +/* ---- the three operations ---- */ + +static int op_check(const title_restore_env_t *env, const char *id, tr_out_t *o) { + tr_vol_t v[TITLE_RESTORE_MAX_VOLUMES]; + tr_info_t in; + int nv = tr_volumes(env, id, v, TITLE_RESTORE_MAX_VOLUMES); + inspect(env, id, v, nv, &in); + put(o, "{\"ok\":true,"); + put_info(o, id, v, &in); + put(o, "}"); + return done(o); +} + +static int op_prepare(const title_restore_env_t *env, const char *id, const char *stamp, tr_out_t *o) { + tr_vol_t v[TITLE_RESTORE_MAX_VOLUMES]; + tr_info_t in; + int nv = tr_volumes(env, id, v, TITLE_RESTORE_MAX_VOLUMES); + inspect(env, id, v, nv, &in); + if (strcmp(in.state, "restorable") != 0) { + put(o, "{\"ok\":false,\"err\":\"restore_%s\",", in.state); + put_info(o, id, v, &in); + put(o, "}"); + return done(o); + } + const tr_vol_t *pv = &v[in.vol]; + char aside_pkg[TR_PATH], aside_patch[TR_PATH]; + aside_file(pv, "app.pkg", aside_pkg, sizeof aside_pkg); + aside_file(pv, "patch.pkg", aside_patch, sizeof aside_patch); + + /* 1. The databases, copied aside before anything changes (the installer writes them next). */ + tr_record_t rec; + memset(&rec, 0, sizeof rec); + { + const char *root = env && env->backup_root ? env->backup_root : TITLE_RESTORE_BACKUP_ROOT; + char dir[200], dst[TR_PATH], err[160] = {0}; + int ok = stamp && stamp[0] && !strchr(stamp, '/') && !strstr(stamp, ".."); + /* A folder of its own: an earlier restore's backup (the same second) is never written into. */ + for (int k = 1; ok; k++) { + int n = k == 1 ? snprintf(dir, sizeof dir, "%s/%s-%s", root, id, stamp) + : snprintf(dir, sizeof dir, "%s/%s-%s-%d", root, id, stamp, k); + if (n <= 0 || n >= (int)sizeof dir || k > 50) ok = 0; + else if (!exists(env, dir, NULL)) break; + } + int made = ok && mkdirs(env, dir) == 0; + ok = ok && made; + static const char *const dbs[] = {"app.db", "appinfo.db"}; + for (size_t i = 0; ok && i < sizeof dbs / sizeof dbs[0]; i++) { + char con[TR_PATH]; + snprintf(con, sizeof con, "%s/%s", dir, dbs[i]); + ok = real_path(env, con, dst, sizeof dst) == 0 && env && env->backup_db && + env->backup_db(dbs[i], dst, err, sizeof err) == 0; + } + if (!ok) { + /* A half backup is no backup: its files and its (our own, new) folder go. */ + for (size_t i = 0; made && i < sizeof dbs / sizeof dbs[0]; i++) { + char con[TR_PATH]; + snprintf(con, sizeof con, "%s/%s", dir, dbs[i]); + if (real_path(env, con, dst, sizeof dst) == 0) unlink(dst); + } + if (made && real_path(env, dir, dst, sizeof dst) == 0) rmdir(dst); + fprintf(stderr, "[restore] %s: database backup failed (%s): nothing moved\n", id, err); + put(o, "{\"ok\":false,\"err\":\"restore_backup_failed\","); + put_info(o, id, v, &in); + put(o, "}"); + return done(o); + } + snprintf(rec.backup, sizeof rec.backup, "%s", dir); + } + + /* 2. The aside folder, empty of packages, and the record (written before any move, so an + * interruption is found again by the next check). */ + if (mkdirs(env, pv->aside) != 0 || exists(env, aside_pkg, NULL) || exists(env, aside_patch, NULL)) { + put(o, "{\"ok\":false,\"err\":\"restore_aside_busy\","); + put_info(o, id, v, &in); + put(o, "}"); + return done(o); + } + rec.app = 1; + rec.patch = in.have_patch; + if (write_record(env, pv, &rec) != 0) { + remove_record(env, pv); + put(o, "{\"ok\":false,\"err\":\"restore_move_failed\",\"reason\":\"record\","); + put_info(o, id, v, &in); + put(o, "}"); + return done(o); + } + + /* 3. The package aside: a same-device rename, nothing copied. */ + if (safe_move(env, pv->pkg, aside_pkg) != 0) { + int e = errno; + remove_record(env, pv); + fprintf(stderr, "[restore] %s: moving %s aside failed (errno %d): nothing changed\n", id, pv->pkg, e); + put(o, "{\"ok\":false,\"err\":\"restore_move_failed\","); + put_info(o, id, v, &in); + put(o, "}"); + return done(o); + } + /* 4. The update too, so the installer cannot clear it; when it will not move, it stays + * where it is and the record says so. */ + if (rec.patch && safe_move(env, pv->patch, aside_patch) != 0) { + rec.patch = 0; + (void)write_record(env, pv, &rec); + } + fprintf(stderr, "[restore] %s: %s moved aside to %s%s; databases backed up in %s\n", id, pv->pkg, aside_pkg, + rec.patch ? " with its update" : "", rec.backup); + put(o, "{\"ok\":true,\"title_id\":\"%s\",\"state\":\"prepared\",\"where\":\"%s\",\"volume\":\"%s\"," + "\"aside\":\"%s\",\"pkg\":\"%s\",\"install_path\":\"%s\",\"size\":%llu,\"kind\":\"%s\",\"backup\":\"%s\"", + id, where_word(pv), pv->root, pv->aside, pv->pkg, aside_pkg, (unsigned long long)in.size, in.kind, rec.backup); + if (rec.patch) put(o, ",\"patch\":\"%s\",\"patch_aside\":\"%s\"", pv->patch, aside_patch); + put(o, "}"); + return done(o); +} + +/* An app.pkg in any <volume>/user/app/<id>: where the installer put the game. -1 none. */ +static int installed_somewhere(const title_restore_env_t *env, const tr_vol_t *v, int nv) { + for (int i = 0; i < nv; i++) { + struct stat st; + if (exists(env, v[i].pkg, &st) && S_ISREG(st.st_mode)) return i; + } + return -1; +} + +/* The update back where it was: only into a free place. 1 put back, 0 kept aside (or none). */ +static int patch_back(const title_restore_env_t *env, const tr_vol_t *pv, const char *aside_patch) { + if (!exists(env, aside_patch, NULL)) return 0; + char dir[TR_PATH]; + xdev_parent_dir(pv->patch, dir, sizeof dir); + if (mkdirs(env, dir) != 0) return 0; + return safe_move(env, aside_patch, pv->patch) == 0; +} + +static int op_finish(const title_restore_env_t *env, const char *id, int flags, tr_out_t *o) { + tr_vol_t v[TITLE_RESTORE_MAX_VOLUMES]; + int nv = tr_volumes(env, id, v, TITLE_RESTORE_MAX_VOLUMES); + int at = find_pending(env, v, nv); + if (at < 0) { + put(o, "{\"ok\":true,\"title_id\":\"%s\",\"state\":\"nothing_pending\"}", id); + return done(o); + } + const tr_vol_t *pv = &v[at]; + tr_record_t rec; + (void)read_record(env, pv, &rec); + char aside_pkg[TR_PATH], aside_patch[TR_PATH]; + aside_file(pv, "app.pkg", aside_pkg, sizeof aside_pkg); + aside_file(pv, "patch.pkg", aside_patch, sizeof aside_patch); + int have_aside = exists(env, aside_pkg, NULL); + int have_patch_aside = exists(env, aside_patch, NULL); + put(o, "{\"ok\":true,\"title_id\":\"%s\",\"where\":\"%s\",\"volume\":\"%s\",\"aside\":\"%s\",\"pkg\":\"%s\"", + id, where_word(pv), pv->root, pv->aside, pv->pkg); + if (rec.backup[0]) put(o, ",\"backup\":\"%s\"", rec.backup); + + if (!have_aside) { + /* Interrupted before the move (only the record was written), or already finished. */ + int back = have_patch_aside ? patch_back(env, pv, aside_patch) : 0; + if (!have_patch_aside || back) remove_record(env, pv); + put(o, ",\"state\":\"nothing_pending\"}"); + return done(o); + } + int db = env && env->appdb_has ? env->appdb_has(id) : -1; + int landed = installed_somewhere(env, v, nv); + if ((flags & TITLE_RESTORE_ROLLBACK) && db == 1) { + /* Asked to put it back, but the console has a record of the title now: its files are never + * moved by us, and the copy aside is not deleted on a put-back either. */ + put(o, ",\"state\":\"unsettled\",\"reason\":\"%s\",\"kept\":\"%s\"}", + landed >= 0 ? "on_home_screen" : "recorded_without_package", aside_pkg); + return done(o); + } + if (db == 1 && landed >= 0 && !(flags & TITLE_RESTORE_INSTALL_ENDED)) { + /* Recorded, with a package in place, but nobody said the install ended: the installer may + * still be reading our copy. Nothing is deleted. */ + put(o, ",\"state\":\"waiting\",\"reason\":\"install_may_be_running\",\"installed\":\"%s\",\"kept\":\"%s\"}", + v[landed].pkg, aside_pkg); + return done(o); + } + if (db == 1 && landed >= 0) { + /* Restored: the console has its record and its own copy. Ours goes. */ + char p[TR_PATH]; + int gone = real_path(env, aside_pkg, p, sizeof p) == 0 && unlink(p) == 0; + int back = have_patch_aside ? patch_back(env, pv, aside_patch) : 0; + if (gone && (!have_patch_aside || back)) remove_record(env, pv); + fprintf(stderr, "[restore] %s: restored (installed at %s)%s\n", id, v[landed].pkg, + have_patch_aside && !back ? "; its update kept aside" : ""); + put(o, ",\"state\":\"restored\",\"installed\":\"%s\",\"installed_where\":\"%s\"", v[landed].pkg, + where_word(&v[landed])); + if (have_patch_aside) put(o, back ? ",\"patch\":\"%s\"" : ",\"patch_kept\":\"%s\"", back ? pv->patch : aside_patch); + if (!gone) put(o, ",\"kept\":\"%s\"", aside_pkg); + put(o, "}"); + return done(o); + } + if (db < 0) { + put(o, ",\"state\":\"unsettled\",\"reason\":\"db_unreadable\",\"kept\":\"%s\"}", aside_pkg); + return done(o); + } + if (!(flags & TITLE_RESTORE_ROLLBACK)) { + /* Not (yet) on the home screen and not asked to put it back: an install may still be + * writing. Nothing is touched. */ + put(o, ",\"state\":\"waiting\",\"reason\":\"%s\",\"kept\":\"%s\"}", + db == 1 ? "recorded_without_package" : "not_on_home_screen", aside_pkg); + return done(o); + } + if (db == 1) { + /* The console has a record of the title: its files are never moved by us. */ + put(o, ",\"state\":\"unsettled\",\"reason\":\"recorded_without_package\",\"kept\":\"%s\"}", aside_pkg); + return done(o); + } + /* Roll back: the package goes back only into a free place. */ + if (exists(env, pv->pkg, NULL)) { + put(o, ",\"state\":\"unsettled\",\"reason\":\"place_taken\",\"kept\":\"%s\"}", aside_pkg); + return done(o); + } + if (mkdirs(env, pv->app_dir) != 0 || safe_move(env, aside_pkg, pv->pkg) != 0) { + put(o, ",\"state\":\"unsettled\",\"reason\":\"move_back_failed\",\"kept\":\"%s\"}", aside_pkg); + return done(o); + } + int back = have_patch_aside ? patch_back(env, pv, aside_patch) : 0; + if (!have_patch_aside || back) remove_record(env, pv); + fprintf(stderr, "[restore] %s: not restored; %s put back\n", id, pv->pkg); + put(o, ",\"state\":\"rolled_back\""); + if (have_patch_aside) put(o, back ? ",\"patch\":\"%s\"" : ",\"patch_kept\":\"%s\"", back ? pv->patch : aside_patch); + put(o, "}"); + return done(o); +} + +int title_restore_run(const title_restore_env_t *env, const char *op, const char *title_id, int flags, + const char *stamp, char *out, size_t cap) { + if (!out || cap < 64) return -1; + tr_out_t o = {out, cap, 0, 0}; + out[0] = '\0'; + const char *refused = install_guard_register_id_refusal(title_id); + if (refused) { + const char *st = strcmp(refused, "register_system_title") == 0 ? "system_title" : "invalid_title"; + if (!op || !op[0] || strcmp(op, "check") == 0) + put(&o, "{\"ok\":true,\"state\":\"%s\"}", st); + else + put(&o, "{\"ok\":false,\"err\":\"restore_%s\",\"state\":\"%s\"}", st, st); + return done(&o); + } + char id[16]; + snprintf(id, sizeof id, "%s", title_id); + for (char *c = id; *c; c++) + if (*c >= 'a' && *c <= 'z') *c = (char)(*c - 'a' + 'A'); + if (!op || !op[0] || strcmp(op, "check") == 0) return op_check(env, id, &o); + pthread_mutex_lock(&g_restore_lock); + int n; + if (strcmp(op, "prepare") == 0) n = op_prepare(env, id, stamp, &o); + else if (strcmp(op, "finish") == 0) n = op_finish(env, id, flags, &o); + else { + put(&o, "{\"ok\":false,\"err\":\"bad_request\"}"); + n = done(&o); + } + pthread_mutex_unlock(&g_restore_lock); + return n; +} diff --git a/payload/tests/content_db_selftest.c b/payload/tests/content_db_selftest.c index 2cba6f539..70b4eddc2 100644 --- a/payload/tests/content_db_selftest.c +++ b/payload/tests/content_db_selftest.c @@ -376,6 +376,31 @@ int main(void) { printf("✓ one appinfo value read by title and key\n"); } + /* any appinfo row for a title, and a backup copy of a database (#961) */ + { + assert(content_db_appinfo_has_title("PPSA03595") == 1); + assert(content_db_appinfo_has_title("PPSA99999") == 0); + assert(content_db_appinfo_has_title("nope") == -1); + char bk[512], e[160]; + snprintf(bk, sizeof bk, "%s.restore-backup", CONTENT_DB_APPINFO); + unlink(bk); + assert(content_db_backup_file(CONTENT_DB_APPINFO, bk, e, sizeof e) == 0); + sqlite3 *b = NULL; + assert(sqlite3_open_v2(bk, &b, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK); + sqlite3_stmt *q = NULL; + assert(sqlite3_prepare_v2(b, "SELECT val FROM tbl_appinfo WHERE titleId='PPSA03595' AND key='_org_path'", -1, &q, NULL) == SQLITE_OK); + assert(sqlite3_step(q) == SQLITE_ROW); + assert(strcmp((const char *)sqlite3_column_text(q, 0), "/mnt/ext1/user/app/PPSA03595") == 0); + sqlite3_finalize(q); + sqlite3_close(b); + /* never over an existing file, and a source that is not there leaves nothing behind */ + assert(content_db_backup_file(CONTENT_DB_APPINFO, bk, e, sizeof e) == -1 && contains(e, "already exists")); + unlink(bk); + assert(content_db_backup_file("/nonexistent/x.db", bk, e, sizeof e) == -1); + assert(access(bk, F_OK) != 0); + printf("✓ appinfo presence by title, and a database copied aside (never over a file)\n"); + } + /* ── appinfo.db writes ───────────────────────────────────────────── */ char err[256]; diff --git a/payload/tests/install_guard_selftest.c b/payload/tests/install_guard_selftest.c index a5d2054b0..d1cfc39b2 100644 --- a/payload/tests/install_guard_selftest.c +++ b/payload/tests/install_guard_selftest.c @@ -230,6 +230,20 @@ int main(void) { } printf("✓ register, re-bind and a registration-only unregister check before touching anything\n"); + /* #961: a launch of a title app.db does not know ends before the ShellUI ptrace route and the + * in-process retry ladder (the console's system UI restarted when it ran for such a game). */ + { + const char *body = fn_body("int launch_title(const char *title_id, const char **err_reason_out,"); + long primary = pos_in(body, "int rc_ss = launch_via_system_service("); + long db = pos_in(body, "register_appdb_has_title(title_id) == 0"); + long refuse = pos_in(body, "\"launch_not_in_database: rc="); + long ptrace = pos_in(body, "shellui_rpc_launch_app("); + long ladder = pos_in(body, "rc = g_reg.launch_app(title_id, NULL, (void *)¶m);"); + assert(primary >= 0 && db > primary && refuse > db); + assert(ptrace > refuse && ladder > refuse); + } + printf("✓ a launch of a title not in app.db stops before the ShellUI and fallback routes\n"); + free(g_src); rm_rf(g_root); return 0; diff --git a/payload/tests/title_restore_selftest.c b/payload/tests/title_restore_selftest.c new file mode 100644 index 000000000..0df7742af --- /dev/null +++ b/payload/tests/title_restore_selftest.c @@ -0,0 +1,325 @@ +/* Host self-test of putting an installed package game back on the home screen (title_restore.c, #961). + * + * cc -pthread -Ipayload/include payload/tests/title_restore_selftest.c payload/src/title_restore.c + * + * Runs check / prepare / finish on a scratch folder laid out like a console (internal /user, USB + * extended storage /mnt/ext0, M.2 /mnt/ext1), with app.db / appinfo.db answers set by the test. + * The scratch folder is removed at the end. */ +#include "title_restore.h" + +#include <dirent.h> +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +static int failures; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #c); \ + failures++; \ + } \ + } while (0) + +static char root[512]; +static int g_appdb, g_appinfo, g_backup_ok = 1; +static uint64_t g_free = 1ull << 40; +static int g_backups; + +static int appdb_has(const char *id) { + (void)id; + return g_appdb; +} +static int appinfo_has(const char *id) { + (void)id; + return g_appinfo; +} +static int backup_db(const char *which, const char *dst, char *err, size_t cap) { + if (!g_backup_ok) { + snprintf(err, cap, "test refuses"); + return -1; + } + FILE *f = fopen(dst, "wx"); + if (!f) return -1; + fprintf(f, "copy of %s\n", which); + fclose(f); + g_backups++; + return 0; +} +static int free_bytes(const char *dir, uint64_t *out) { + (void)dir; + *out = g_free; + return 0; +} + +static void at(char *buf, size_t cap, const char *path) { snprintf(buf, cap, "%s%s", root, path); } + +static void mkdirs(const char *path) { + char p[1024]; + at(p, sizeof p, path); + for (char *s = p + strlen(root) + 1; *s; s++) { + if (*s == '/') { + *s = 0; + mkdir(p, 0777); + *s = '/'; + } + } + mkdir(p, 0777); +} + +static void put_file(const char *path, const unsigned char *head, size_t n, size_t total) { + char p[1024], dir[1024]; + snprintf(dir, sizeof dir, "%s", path); + *strrchr(dir, '/') = 0; + mkdirs(dir); + at(p, sizeof p, path); + FILE *f = fopen(p, "wb"); + fwrite(head, 1, n, f); + for (size_t i = n; i < total; i++) fputc(0x5A, f); + fclose(f); +} + +static int has(const char *path) { + char p[1024]; + struct stat st; + at(p, sizeof p, path); + return lstat(p, &st) == 0; +} + +static long size_of(const char *path) { + char p[1024]; + struct stat st; + at(p, sizeof p, path); + return lstat(p, &st) == 0 ? (long)st.st_size : -1; +} + +static void rm(const char *path) { + char p[1024]; + at(p, sizeof p, path); + unlink(p); +} + +static void rm_tree(const char *p) { + DIR *d = opendir(p); + if (d) { + struct dirent *e; + while ((e = readdir(d))) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + char c[1024]; + snprintf(c, sizeof c, "%s/%s", p, e->d_name); + struct stat st; + if (lstat(c, &st) == 0 && S_ISDIR(st.st_mode)) rm_tree(c); + else unlink(c); + } + closedir(d); + } + rmdir(p); +} + +static const unsigned char FAKE[8] = {0x7F, 'F', 'I', 'H', 0x01, 0x00, 0x03, 0x00}; +static const unsigned char RETAIL[8] = {0x7F, 'F', 'I', 'H', 0x01, 0x80, 0x03, 0x00}; +static const unsigned char PS4[8] = {0x7F, 'C', 'N', 'T', 0x80, 0x00, 0x00, 0x01}; + +#define ID "PPSA01234" +#define PKG "/mnt/ext1/user/app/" ID "/app.pkg" +#define PATCH "/mnt/ext1/user/patch/" ID "/patch.pkg" +#define ASIDE "/mnt/ext1/ps5upload/restore/" ID +#define REC ASIDE "/restore.txt" + +static title_restore_env_t env; +static char out[8192]; + +static int run(const char *op, const char *id, int flags) { + return title_restore_run(&env, op, id, flags, "20261126-101500", out, sizeof out); +} + +static int says(const char *s) { return strstr(out, s) != NULL; } + +static void fresh(void) { + rm_tree(root); + mkdir(root, 0777); + mkdirs("/user/app"); + mkdirs("/mnt/ext0/user"); + mkdirs("/mnt/ext1/user/app"); + put_file(PKG, FAKE, sizeof FAKE, 4096); + put_file(PATCH, FAKE, sizeof FAKE, 1024); + g_appdb = 0; + g_appinfo = 0; + g_backup_ok = 1; + g_free = 1ull << 40; + g_backups = 0; +} + +int main(void) { + const char *tmp = getenv("TMPDIR"); + snprintf(root, sizeof root, "%s/ps5u-title-restore-%d", tmp && tmp[0] ? tmp : "/tmp", (int)getpid()); + memset(&env, 0, sizeof env); + env.prefix = root; + env.appdb_has = appdb_has; + env.appinfo_has = appinfo_has; + env.backup_db = backup_db; + env.free_bytes = free_bytes; + + /* ---- check: what each console state answers, read-only ---- */ + fresh(); + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"restorable\"") && says("\"kind\":\"fake\"") && + says("\"where\":\"m2\"") && says("\"pkg\":\"" PKG "\"") && says("\"patch\":\"" PATCH "\"") && + says("\"aside\":\"" ASIDE "\"") && says("\"size\":4096")); + CHECK(has(PKG) && !has(ASIDE)); + CHECK(run("check", "ppsa01234", 0) > 0 && says("\"title_id\":\"PPSA01234\"") && says("restorable")); + g_appdb = 1; + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"registered\"")); + g_appdb = -1; + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"db_unreadable\"") && says("\"reason\":\"app.db\"")); + g_appdb = 0; + g_appinfo = 1; + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"record_elsewhere\"")); + g_appinfo = -1; + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"db_unreadable\"") && says("appinfo.db")); + g_appinfo = 0; + g_free = 100; + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"no_room\"")); + g_free = 1ull << 40; + put_file(PKG, RETAIL, sizeof RETAIL, 4096); + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"retail\"")); + put_file(PKG, PS4, sizeof PS4, 4096); + CHECK(run("check", ID, 0) > 0 && says("restorable") && says("\"kind\":\"ps4\"")); + put_file(PKG, (const unsigned char *)"\0\0\0\0\0\0\0\0", 8, 4096); + CHECK(run("check", ID, 0) > 0 && says("restorable") && says("\"kind\":\"unknown\"")); + put_file(PKG, FAKE, sizeof FAKE, 4096); + put_file("/user/app/" ID "/mount.lnk", (const unsigned char *)"/data/x", 7, 7); + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"folder_registration\"")); + rm("/user/app/" ID "/mount.lnk"); + put_file("/user/app/" ID "/app.pkg", FAKE, sizeof FAKE, 64); + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"ambiguous\"")); + rm("/user/app/" ID "/app.pkg"); + CHECK(run("check", "PPSA99999", 0) > 0 && says("\"state\":\"not_installed\"")); + CHECK(run("check", "NPXS20001", 0) > 0 && says("\"state\":\"system_title\"")); + CHECK(run("check", "../etc/x", 0) > 0 && says("\"state\":\"invalid_title\"")); + CHECK(run("prepare", "NPXS20001", 0) > 0 && says("\"ok\":false") && says("restore_system_title")); + printf("✓ check: restorable only for a package on a drive that no database knows; every other state named\n"); + + /* ---- prepare refusals touch nothing ---- */ + g_appdb = 1; + CHECK(run("prepare", ID, 0) > 0 && says("\"ok\":false") && says("\"err\":\"restore_registered\"")); + CHECK(has(PKG) && !has(ASIDE) && g_backups == 0); + g_appdb = 0; + g_backup_ok = 0; + CHECK(run("prepare", ID, 0) > 0 && says("restore_backup_failed")); + CHECK(has(PKG) && has(PATCH) && !has(ASIDE)); + g_backup_ok = 1; + printf("✓ prepare refuses a registered title and a failed database backup before anything moves\n"); + + /* ---- prepare, then an install that failed: rolled back ---- */ + CHECK(run("prepare", ID, 0) > 0 && says("\"ok\":true") && says("\"state\":\"prepared\"") && + says("\"install_path\":\"" ASIDE "/app.pkg\"") && says("\"patch_aside\":\"" ASIDE "/patch.pkg\"") && + says("\"backup\":\"/data/ps5upload/backup/restore/" ID "-20261126-101500\"")); + CHECK(!has(PKG) && !has(PATCH) && size_of(ASIDE "/app.pkg") == 4096 && size_of(ASIDE "/patch.pkg") == 1024 && + has(REC)); + CHECK(has("/data/ps5upload/backup/restore/" ID "-20261126-101500/app.db") && + has("/data/ps5upload/backup/restore/" ID "-20261126-101500/appinfo.db") && g_backups == 2); + CHECK(run("check", ID, 0) > 0 && says("\"state\":\"pending\"")); + CHECK(run("prepare", ID, 0) > 0 && says("restore_pending")); + /* not asked to put it back, not on the home screen: nothing moves */ + CHECK(run("finish", ID, 0) > 0 && says("\"state\":\"waiting\"") && says("not_on_home_screen")); + CHECK(!has(PKG) && has(ASIDE "/app.pkg")); + /* the place taken (a half-written install): kept */ + put_file(PKG, FAKE, sizeof FAKE, 16); + CHECK(run("finish", ID, TITLE_RESTORE_ROLLBACK) > 0 && says("\"state\":\"unsettled\"") && says("place_taken")); + CHECK(size_of(PKG) == 16 && has(ASIDE "/app.pkg")); + rm(PKG); + /* recorded without a package: never moved by us */ + g_appdb = 1; + CHECK(run("finish", ID, TITLE_RESTORE_ROLLBACK) > 0 && says("unsettled") && says("recorded_without_package")); + CHECK(!has(PKG) && has(ASIDE "/app.pkg")); + g_appdb = -1; + CHECK(run("finish", ID, TITLE_RESTORE_ROLLBACK) > 0 && says("db_unreadable")); + g_appdb = 0; + /* the installer may have removed the title's folder: made again */ + { + char p[1024]; + at(p, sizeof p, "/mnt/ext1/user/app/" ID); + rmdir(p); + } + CHECK(run("finish", ID, TITLE_RESTORE_ROLLBACK) > 0 && says("\"state\":\"rolled_back\"") && + says("\"patch\":\"" PATCH "\"")); + CHECK(size_of(PKG) == 4096 && size_of(PATCH) == 1024 && !has(ASIDE)); + CHECK(run("finish", ID, 0) > 0 && says("nothing_pending")); + CHECK(run("check", ID, 0) > 0 && says("restorable")); + printf("✓ a failed restore puts the package and its update back, only into a free place, never over a record\n"); + + /* ---- prepare, then an install that put it back on the same drive ---- */ + CHECK(run("prepare", ID, 0) > 0 && says("prepared")); + put_file(PKG, FAKE, sizeof FAKE, 3000); /* the installer's own copy (it may differ in size) */ + g_appdb = 1; + CHECK(run("finish", ID, 0) > 0 && says("\"state\":\"waiting\"") && says("install_may_be_running")); + CHECK(has(ASIDE "/app.pkg")); + /* "Put back" while the console lists the game: nothing moves, nothing is deleted */ + CHECK(run("finish", ID, TITLE_RESTORE_ROLLBACK | TITLE_RESTORE_INSTALL_ENDED) > 0 && says("unsettled") && + says("on_home_screen")); + CHECK(size_of(PKG) == 3000 && has(ASIDE "/app.pkg") && !has(PATCH)); + CHECK(run("finish", ID, TITLE_RESTORE_INSTALL_ENDED) > 0 && says("\"state\":\"restored\"") && + says("\"installed\":\"" PKG "\"") && says("\"patch\":\"" PATCH "\"")); + CHECK(size_of(PKG) == 3000 && size_of(PATCH) == 1024 && !has(ASIDE)); + CHECK(run("check", ID, 0) > 0 && says("registered")); + printf("✓ a restore that worked deletes only the copy aside, after the install ended, and puts the update back\n"); + + /* ---- the installer chose the console's own drive ---- */ + fresh(); + CHECK(run("prepare", ID, 0) > 0 && says("prepared")); + put_file("/user/app/" ID "/app.pkg", FAKE, sizeof FAKE, 4096); + g_appdb = 1; + CHECK(run("finish", ID, TITLE_RESTORE_INSTALL_ENDED) > 0 && says("restored") && + says("\"installed_where\":\"internal\"")); + CHECK(has("/user/app/" ID "/app.pkg") && !has(ASIDE "/app.pkg") && has(PATCH)); + printf("✓ the game installed on another drive counts as restored\n"); + + /* ---- the update already back in its place: kept aside, reported ---- */ + fresh(); + CHECK(run("prepare", ID, 0) > 0 && says("prepared")); + put_file(PKG, FAKE, sizeof FAKE, 4096); + put_file(PATCH, FAKE, sizeof FAKE, 77); + g_appdb = 1; + CHECK(run("finish", ID, TITLE_RESTORE_INSTALL_ENDED) > 0 && says("restored") && + says("\"patch_kept\":\"" ASIDE "/patch.pkg\"")); + CHECK(size_of(PATCH) == 77 && has(ASIDE "/patch.pkg") && has(REC)); + printf("✓ an update never replaces a file in its place; the record stays while one is kept aside\n"); + + /* ---- internal drive: the aside folder is on /user ---- */ + fresh(); + rm(PKG); + rm(PATCH); + put_file("/user/app/" ID "/app.pkg", FAKE, sizeof FAKE, 512); + CHECK(run("prepare", ID, 0) > 0 && says("prepared") && says("\"where\":\"internal\"") && + says("\"install_path\":\"/user/ps5upload/restore/" ID "/app.pkg\"")); + CHECK(!has("/user/app/" ID "/app.pkg") && size_of("/user/ps5upload/restore/" ID "/app.pkg") == 512); + CHECK(run("finish", ID, TITLE_RESTORE_ROLLBACK) > 0 && says("rolled_back")); + CHECK(size_of("/user/app/" ID "/app.pkg") == 512); + printf("✓ the internal drive's package moves within /user and back\n"); + + /* ---- a record without a moved package (interrupted before the move) is cleared ---- */ + fresh(); + put_file(REC, (const unsigned char *)"app=1\npatch=0\nbackup=\n", 22, 22); + CHECK(run("finish", ID, 0) > 0 && says("nothing_pending")); + CHECK(!has(REC) && has(PKG)); + CHECK(run("finish", ID, 0) > 0 && says("nothing_pending")); + CHECK(run("bogus", ID, 0) > 0 && says("bad_request")); + printf("✓ an interrupted prepare leaves nothing to undo\n"); + + /* ---- a reply that does not fit is -1, not a cut JSON ---- */ + { + char small[80]; + CHECK(title_restore_run(&env, "check", ID, 0, "x", small, sizeof small) == -1); + } + + rm_tree(root); + if (failures) { + fprintf(stderr, "title_restore_selftest: %d failure(s)\n", failures); + return 1; + } + printf("title_restore_selftest: ok\n"); + return 0; +} diff --git a/payload/third_party/libarchive/README.md b/payload/third_party/libarchive/README.md index 719e95538..a83e7ee53 100644 --- a/payload/third_party/libarchive/README.md +++ b/payload/third_party/libarchive/README.md @@ -6,8 +6,8 @@ there). Only the RAR (1.5–4.x) and RAR5 readers and what they need are kept, built with the hand-written `config.h` (no zlib, iconv or crypto library). These readers are independent implementations, not -derived from UnRAR, so they carry no field-of-use restriction. They cannot decrypt: an encrypted -RAR is refused by the extractor (`fs_extract_rar_encrypted`). +derived from UnRAR, so they carry no field-of-use restriction. They cannot decrypt: the extractor +hands them password-protected archives already decrypted (`payload/extractor/src/xrarc.c`). The RAR test archives in `payload/extractor/tests/fixtures` come from libarchive's own test suite (`libarchive/test/*.rar.uu`, decoded). `rar5-dict128m*.rar` were made with RAR 7.23 (`-md128m`) for #801. @@ -27,6 +27,9 @@ One file is changed, `archive_read_support_format_rar5.c` (#801), each change ma - `copy_string` copies a match in blocks (memmove, or doubling memcpy runs for a repeat shorter than the match) when neither run wraps around the window, instead of byte by byte (#826). Checked against the byte loop on 3 million random cases. +- `rar5_read_data` ends a file at its last compressed block, with up to 15 bytes of its data left, + and passes over them (#958): the extractor's decrypted stream keeps the padding that + encryption adds to whole 16-byte AES blocks. Keep these when updating. diff --git a/payload/third_party/libarchive/archive_read_support_format_rar5.c b/payload/third_party/libarchive/archive_read_support_format_rar5.c index cd11d6439..6204343ba 100644 --- a/payload/third_party/libarchive/archive_read_support_format_rar5.c +++ b/payload/third_party/libarchive/archive_read_support_format_rar5.c @@ -4555,7 +4555,15 @@ static int rar5_read_data(struct archive_read *a, const void **buff, return ret; } - if(rar5->file.bytes_remaining == 0 && + /* PS5Upload (#958): the extractor hands this reader password-protected + * archives decrypted (payload/extractor/src/xrarc.c), and encrypted data + * is padded to whole 16-byte AES blocks: after the file's last block, + * up to 15 bytes of padding are left. They are not data (the next + * header skips them), so the file ends there. */ + if((rar5->file.bytes_remaining == 0 || + (rar5->file.bytes_remaining < 16 && + rar5->cstate.block_parsing_finished && + bf_is_last_block(&rar5->last_block_hdr))) && rar5->cstate.last_write_ptr == rar5->file.unpacked_size) { /* If all bytes of current file were processed, run @@ -4566,6 +4574,15 @@ static int rar5_read_data(struct archive_read *a, const void **buff, * value in the last `archive_read_data` call to signal an error * to the user. */ + /* PS5Upload (#958): the padding is passed over now; skipping + * it later would mean decoding it in a solid archive. */ + if(rar5->file.bytes_remaining > 0) { + if(ARCHIVE_OK != consume(a, + rar5->file.bytes_remaining)) + return ARCHIVE_FATAL; + rar5->file.bytes_remaining = 0; + } + rar5->file.eof = 1; return verify_global_checksums(a); } diff --git a/protocol/ps5upload-ava1/MGMT_METHODS.md b/protocol/ps5upload-ava1/MGMT_METHODS.md index ea402f090..fd06247c9 100644 --- a/protocol/ps5upload-ava1/MGMT_METHODS.md +++ b/protocol/ps5upload-ava1/MGMT_METHODS.md @@ -157,6 +157,7 @@ table-wide ones (`ps5upload-ctest/tests/mgmt*.rs`, `ps5upload-ava1/tests/mgmt*.r | VinputReport 344 | 187 `vinput.report` | `MgmtText` {id, r: hex of 1-64 16-byte reports} -> {ok, applied, err?} | `src/runtime.c` `handle_vinput_report` (`src/vinput.c`) | `ps5upload-core/src/vinput.rs` | the report layout is in `payload/include/vinput.h` (the page's Remote Play binary kind 8 carries the same 16 bytes); a report is also a heartbeat; `payload/tests/vinput_selftest.c` | | VpadOpen 346 | 188 `vpad.open` | `MgmtText` {slot 2-4, token: 32 hex, user?, bind_user?, bind_owner?} -> {ok, slot, handle, user, resumed, bound?, bind_code?, owner?}: make Player N's virtual DualSense (Play Together, #641) | `src/runtime.c` `handle_vpad_open` (`src/vpad.c`) | engine Play Together link (not through the passthrough) | user absent or 0: the foreground user (under `sony_api_lock`), else the lowest `/user/home` id; the same token on a live slot resumes (nothing made again, seq starts over); `err` `vpad_busy`, `vpad_no_user`, `vpad_unsupported`, `vpad_failed` (+`code` -errno), `vpad_stopping`, `bad_request`, kept as the call's error cause (`mgmt_call_text_keep`); `bind_user` (Play Together's "Guests play as"): the pad is made for that user and seated in it at once by the vinput companion (`sceMbusBindDeviceWithUserId`, `payload/vinput/README.md`), never the foreground user instead; refused with no pad made: `vpad_bind_starting` (ask again), `vpad_bind_unavailable` (+`companion`), `vpad_bind_signed_out`, `vpad_bind_unknown`, `vpad_bind_owner` (the user in front, without `bind_owner` true); a bind that fails keeps the pad with `bound` false and `bind_code`; `payload/tests/vpad_selftest.c` | | VpadState 348 | 189 `vpad.state` | `MgmtText` {slot, token, seq, buttons?, lx? ly? rx? ry? l2? r2?, touch?: [{id, x, y}] (<= 2), gyro?: [3], accel?: [3]} -> {ok, applied} | `src/runtime.c` `handle_vpad_state` (`src/vpad.c`) | engine Play Together link | the whole controller state (absent fields at rest), inserted at once; a seq not above the last applied one answers applied false; also a heartbeat; `err` `vpad_not_open`, `vpad_not_owner`, `vpad_failed`; button bits in `payload/include/vpad.h`; `payload/tests/vpad_selftest.c` | +| TitleRestore 376 | 202 `app.restore` | `MgmtText` {op: check\|prepare\|finish, title_id, rollback, install_ended} -> {ok, title_id, state, reason, where, volume, aside, pkg, size, kind: fake\|ps4\|unknown, patch, patch_size, free_volume, free_internal}; check state: restorable\|registered\|record_elsewhere\|not_installed\|pending\|folder_registration\|ambiguous\|retail\|no_room\|aside_cross_device\|db_unreadable\|invalid_title\|system_title; prepare: {ok, state: prepared, install_path, aside, pkg, patch, patch_aside, backup} or {ok:false, err: restore_<check state>\|restore_backup_failed\|restore_move_failed\|restore_aside_busy}; finish: {ok, state: restored\|rolled_back\|nothing_pending\|waiting\|unsettled, reason, installed, installed_where, patch, patch_kept, kept, backup} | `src/runtime.c` `handle_title_restore` (`src/title_restore.c`) | `ps5upload-core/src/title_restore.rs` | a game installed from a package whose home-screen record is gone (Rebuild Database drops fake packages, #961): check is read-only; prepare copies app.db and appinfo.db to /data/ps5upload/backup/restore/<id>-<UTC stamp>/ (SQLite backup), then renames <drive>/user/app/<id>/app.pkg (and the update, patch.pkg, on the same drive) into <drive>/ps5upload/restore/<id>/ (/user/ps5upload/restore/<id> for the internal drive), only on a proven same device (cross_device.h), with restore.txt written first; the engine then installs the copy aside through the installer daemon; finish deletes the copy aside only with install_ended and the title in app.db with an app.pkg in a user/app again, and with rollback puts the files back only into a free place and only while app.db does not have the title. Refuses a title app.db or appinfo.db knows, a folder registration, a retail-signed PS5 package, an unreadable database. Never writes app.db or appinfo.db; no Sony call. An older helper answers unknown method; `payload/tests/title_restore_selftest.c` | | VpadStates 350 | 190 `vpad.states` | `MgmtText` {items: [vpad.state bodies] (<= 16)} -> {ok, applied, stale, failed: [{slot, err}]} | `src/runtime.c` `handle_vpad_states` (`src/vpad.c`) | engine Play Together link | one call for every player; a malformed item refuses the whole batch (`bad_request`); `payload/tests/vpad_selftest.c` | | VpadHb 352 | 191 `vpad.hb` | `MgmtText` {slot, token, live?} -> {ok, neutral}; or {companion: true} -> {ok, companion, bind} | `src/runtime.c` `handle_vpad_hb` (`src/vpad.c`) | engine Play Together link | keeps the pad (removed after 90 s with no state or hb); `live` true also holds the last state (otherwise it is put at rest after 400 ms with no state); `{companion: true}` (no slot) keeps the vinput companion up for 60 s for Play Together's binds (`companion`: running, starting, no_bind, unavailable, off); `payload/tests/vpad_selftest.c` | | VpadClose 354 | 192 `vpad.close` | `MgmtText` {slot, token} -> {ok} | `src/runtime.c` `handle_vpad_close` (`src/vpad.c`) | engine Play Together link | at rest, then removed; a free slot is ok; `err` `vpad_not_owner`; the helper stopping removes every pad; `payload/tests/vpad_selftest.c` | diff --git a/protocol/ps5upload-ava1/app.toml b/protocol/ps5upload-ava1/app.toml index 36a8b26db..d7fba31cc 100644 --- a/protocol/ps5upload-ava1/app.toml +++ b/protocol/ps5upload-ava1/app.toml @@ -593,6 +593,11 @@ value = 200 name = "METHOD_TROPHY_FIX" ty = "u16" value = 201 +# An installed package game back on the home screen after Rebuild Database (payload/src/title_restore.c; MGMT_METHODS.md) +[[const]] +name = "METHOD_APP_RESTORE" +ty = "u16" +value = 202 [[const]] name = "JOB_OP_DELETE" ty = "u8" diff --git a/scripts/i18n-known-missing.json b/scripts/i18n-known-missing.json index be11cac4a..6afe2a842 100644 --- a/scripts/i18n-known-missing.json +++ b/scripts/i18n-known-missing.json @@ -1,6 +1,58 @@ { "ar": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -16,7 +68,59 @@ ] }, "bn": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -36,7 +140,59 @@ ] }, "de": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -65,7 +221,59 @@ ] }, "es": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -88,7 +296,59 @@ ] }, "fa": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -106,7 +366,59 @@ ] }, "fr": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -128,7 +440,59 @@ ] }, "hi": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -148,7 +512,59 @@ ] }, "hu": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -174,7 +590,59 @@ ] }, "id": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -202,7 +670,59 @@ ] }, "it": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -230,7 +750,59 @@ ] }, "ja": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -247,7 +819,59 @@ ] }, "ko": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -266,7 +890,59 @@ ] }, "pl": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -289,7 +965,59 @@ ] }, "pt-BR": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -312,7 +1040,59 @@ ] }, "ru": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -334,7 +1114,59 @@ ] }, "th": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -355,7 +1187,59 @@ ] }, "tr": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -380,7 +1264,59 @@ ] }, "vi": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -404,7 +1340,59 @@ ] }, "zh-CN": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", @@ -422,7 +1410,59 @@ ] }, "zh-TW": { - "missing": [], + "missing": [ + "err_launch_not_in_database", + "restore_action", + "restore_all_action", + "restore_all_body", + "restore_all_found", + "restore_all_running", + "restore_all_title", + "restore_already", + "restore_backup_failed", + "restore_busy", + "restore_confirm_body", + "restore_confirm_kstuff", + "restore_confirm_patch", + "restore_confirm_steps", + "restore_confirm_title", + "restore_done", + "restore_done_patch_kept", + "restore_finish", + "restore_finish_body", + "restore_finish_title", + "restore_finishing", + "restore_home_only", + "restore_install_failed", + "restore_installing", + "restore_installing_progress", + "restore_missing_title", + "restore_move_failed", + "restore_not_applicable", + "restore_not_yet", + "restore_nothing_pending", + "restore_pending", + "restore_pending_title", + "restore_play_blocked", + "restore_put_back", + "restore_queued", + "restore_rollback", + "restore_rollback_body", + "restore_rollback_title", + "restore_rolled_back", + "restore_running_title", + "restore_state_ambiguous", + "restore_state_cross_device", + "restore_state_no_room", + "restore_state_pending", + "restore_state_restorable", + "restore_state_retail", + "restore_unsupported", + "restore_where_extended", + "restore_where_internal", + "restore_where_m2", + "restore_where_usb" + ], "stale": [], "untranslated": [ "about_feat_minion_title", diff --git a/scripts/i18n-source-hashes.json b/scripts/i18n-source-hashes.json index a149dc7d9..0d44d2fc2 100644 --- a/scripts/i18n-source-hashes.json +++ b/scripts/i18n-source-hashes.json @@ -3173,6 +3173,7 @@ "err_launch_homebrew_refused": "026767d5 Zjr-82_fUKSI0HY37w6E37eqfRDOaqZ9O3TUTENCOCnsp1pmMZg5XziGPjSZ", "err_launch_no_profile": "a75f1aa2 QICj0KzIIVhaDxT0MnN5UmONi9OlLNM_C5UHhtacMnli_7YwQZt7Xdj_GPPl", "err_launch_no_user": "0c0edca9 AO6TKLwQEDN_Nu4JCaGjfvoG4jZVwYEjp3tNYop-2gw39sYVLC_u5sbp0JYi", + "err_launch_not_in_database": "179fe2d8 ------------------------------------------------------------", "err_launch_not_registered": "589d1b57 -PyXj9vlj4nZZkjcdztW5O_tuE9a82akzfyF4sf2iY6n0TN8MYBy8WeB1jeW", "err_launch_title_id_invalid": "9159905c Jo-srl8cbkSxC2j0jdFvbvAF_FsNsfD76gmHhEiT6TPlYsDMOU7k_UeILJAm", "err_launch_unknown": "95a0ad26 DC6oRrdYrX6aVSqIxP4eypa6vViEBNNXoM4tEqhq1r43cfADaBQWD3Ec-AtP", @@ -7138,6 +7139,56 @@ "reset_mobile_finish_body": "62ccda7c rqVqs-kQVB30COeFeprqNlEOcvlCEs2cTmvlli4NQC6FQsG1m2mlErXQfoMI", "reset_mobile_finish_title": "7d9346b6 GJDKzLBixFdXCwTrIInw1d14CA704OrwPziTzKLnsnWfBWuOdT77JF4utv-c", "resolving": "f2548279 swCdi8mz6HGO3e7WCAgs9KKujgNpa4aqODkI3y9RRNHc76_x9ecnUOSZcSZc", + "restore_action": "c3f6dacc ------------------------------------------------------------", + "restore_all_action": "a9c39ca5 ------------------------------------------------------------", + "restore_all_body": "48f3fbfc ------------------------------------------------------------", + "restore_all_found": "0b891519 ------------------------------------------------------------", + "restore_all_running": "a0974f80 ------------------------------------------------------------", + "restore_all_title": "90fab6d2 ------------------------------------------------------------", + "restore_already": "03c08d25 ------------------------------------------------------------", + "restore_backup_failed": "57526f88 ------------------------------------------------------------", + "restore_busy": "5ee4b601 ------------------------------------------------------------", + "restore_confirm_body": "e71a9313 ------------------------------------------------------------", + "restore_confirm_kstuff": "2e34ae1b ------------------------------------------------------------", + "restore_confirm_patch": "daf455ff ------------------------------------------------------------", + "restore_confirm_steps": "b2ba5a9e ------------------------------------------------------------", + "restore_confirm_title": "4cff49c7 ------------------------------------------------------------", + "restore_done": "78ecbae0 ------------------------------------------------------------", + "restore_done_patch_kept": "4dfea116 ------------------------------------------------------------", + "restore_finish": "a6c7a84b ------------------------------------------------------------", + "restore_finish_body": "68e6a94b ------------------------------------------------------------", + "restore_finish_title": "95744f56 ------------------------------------------------------------", + "restore_finishing": "1bc937ee ------------------------------------------------------------", + "restore_home_only": "b49e0889 ------------------------------------------------------------", + "restore_install_failed": "de2016ea ------------------------------------------------------------", + "restore_installing": "2d3c52ee ------------------------------------------------------------", + "restore_installing_progress": "46317b13 ------------------------------------------------------------", + "restore_missing_title": "d7b3a6ec ------------------------------------------------------------", + "restore_move_failed": "fe3a4b41 ------------------------------------------------------------", + "restore_not_applicable": "ea0249e8 ------------------------------------------------------------", + "restore_not_yet": "92b5133f ------------------------------------------------------------", + "restore_nothing_pending": "de0bf777 ------------------------------------------------------------", + "restore_pending": "ac10f313 ------------------------------------------------------------", + "restore_pending_title": "0ff7339f ------------------------------------------------------------", + "restore_play_blocked": "efb40de1 ------------------------------------------------------------", + "restore_put_back": "98111499 ------------------------------------------------------------", + "restore_queued": "ded7f118 ------------------------------------------------------------", + "restore_rollback": "4a0ee41d ------------------------------------------------------------", + "restore_rollback_body": "481bf8f1 ------------------------------------------------------------", + "restore_rollback_title": "55c0e3b9 ------------------------------------------------------------", + "restore_rolled_back": "543f30d5 ------------------------------------------------------------", + "restore_running_title": "1efad067 ------------------------------------------------------------", + "restore_state_ambiguous": "92988e2d ------------------------------------------------------------", + "restore_state_cross_device": "fdc951ff ------------------------------------------------------------", + "restore_state_no_room": "50be3758 ------------------------------------------------------------", + "restore_state_pending": "8e2b29ba ------------------------------------------------------------", + "restore_state_restorable": "7bd3ab29 ------------------------------------------------------------", + "restore_state_retail": "2fdc989e ------------------------------------------------------------", + "restore_unsupported": "bb309388 ------------------------------------------------------------", + "restore_where_extended": "8f5b07a6 ------------------------------------------------------------", + "restore_where_internal": "c2cb9e9f ------------------------------------------------------------", + "restore_where_m2": "e2a7a4ab ------------------------------------------------------------", + "restore_where_usb": "f4746cdc ------------------------------------------------------------", "retry": "942087cc FNViuElIZqSVvpurycyvIS5k6HxILX-2zGWhvjmueEUYkDlGHzDxY0uHhfln", "roster_manage": "92759d52 XJMpkFRvqt8SLVFSMXgbZWzS85fdCqpjAm_xs9zQFQUNdL-wLENcN0Q-RQ-R", "roster_manage_title": "92759d52 XJMpkFRvqt8SLVFSMXgbZWzS85fdCqpjAm_xs9zQFQUNdL-wLENcN0Q-RQ-R",