diff --git a/controller/app/src/main/java/org/iiab/controller/TarExtractor.java b/controller/app/src/main/java/org/iiab/controller/TarExtractor.java index f2653c832..434479f8d 100644 --- a/controller/app/src/main/java/org/iiab/controller/TarExtractor.java +++ b/controller/app/src/main/java/org/iiab/controller/TarExtractor.java @@ -113,6 +113,28 @@ public void startExtraction(Context context, String archivePath, String destDir, // bail out (without extracting anything) if any member is absolute // or climbs out of destDir via "..". An imported/restored backup is // untrusted, so this runs for every extraction. + // K2GO-372: identity before the listing pass. The listing below is irreducible — + // the traversal guard has to see every member name — but it costs a full pass over + // the archive, and a wrong-ABI or non-rootfs file used to be rejected only after + // paying for it. The manifest that answers identity is packed first, so reading it + // here refuses the same files in about a second, and leaves the long pass for + // archives that are actually going to be extracted. + // K2GO-372: DeepOpService runs this same check on the picked stream before it copies, + // purely to avoid paying for a copy it will throw away. This one is not a duplicate of + // it: this is the fail-closed gate every caller shares (import, install, restore), it + // judges the artifact actually about to be extracted, and both delegate to the one rule + // in RootfsIdentity. Deleting either does not make the other cover it. + if (validateRootfs) { + org.iiab.controller.deploy.data.RootfsArchiveValidator.Result early = + org.iiab.controller.deploy.data.RootfsArchiveValidator.identityRejection( + org.iiab.controller.deploy.data.RootfsManifest.read(archivePath)); + String why = org.iiab.controller.deploy.data.RootfsArchiveValidator + .rejectionMessage(context, early); + if (why != null) { + throw new Exception(why); + } + } + List entries = listEntries(tarBinary, archivePath, isGzip, listener); for (String entry : entries) { if (ArchiveEntry.escapesRoot(entry)) { @@ -132,11 +154,10 @@ public void startExtraction(Context context, String archivePath, String destDir, org.iiab.controller.deploy.data.RootfsArchiveValidator.Result vr = org.iiab.controller.deploy.data.RootfsArchiveValidator .validateWithEntries(context, archivePath, isGzip, tarBinary, entries); - if (vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.NOT_A_ROOTFS) { - throw new Exception(context.getString(R.string.install_error_not_rootfs)); - } - if (vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.WRONG_ARCH) { - throw new Exception(context.getString(R.string.install_error_wrong_arch)); + String why = org.iiab.controller.deploy.data.RootfsArchiveValidator + .rejectionMessage(context, vr); + if (why != null) { + throw new Exception(why); } } diff --git a/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java b/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java index eb9ac8abb..f8ad73001 100644 --- a/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java +++ b/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java @@ -19,10 +19,11 @@ * ServerController never both own the proot container. * * Job shapes: - * BACKUP (EXTRA_URI = SAF dest) : stop services -> stream tar|gzip -> post terminal. - * RESTORE (EXTRA_PATH = temp file) : stop services -> extract over the rootfs -> terminal. - * For restore the caller (UI) has already copied + validated the archive and shown the - * destructive confirm; the service owns the kill-sensitive extract and sets InstallGuard. + * BACKUP (EXTRA_URI = SAF dest) : stop services -> stream tar|gzip -> post terminal. + * RESTORE (EXTRA_URI = SAF source) : stage the file -> stop services -> extract -> terminal. + * K2GO-372: the caller now only shows the destructive confirm (which needs the file's name, + * not its bytes); every read of the archive belongs to the service, so it is measured, it + * survives backgrounding, and the user can walk away as soon as they have answered. * Backup is cancellable from the notification (read-only); restore is not (hard gate). * ============================================================================ */ @@ -50,12 +51,16 @@ import org.iiab.controller.R; import org.iiab.controller.TarExtractor; import org.iiab.controller.backup.domain.BackupEngine; +import org.iiab.controller.deploy.data.RootfsArchiveValidator; +import org.iiab.controller.deploy.data.RootfsManifest; import org.iiab.controller.env.EnvironmentControl; import org.iiab.controller.env.EnvironmentLock; import org.iiab.controller.redesign.LibraryActivity; import org.iiab.controller.util.AppExecutors; import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; public final class DeepOpService extends Service { @@ -67,8 +72,14 @@ public final class DeepOpService extends Service { public static final String ACTION_BACKUP = "org.iiab.controller.DEEPOP_BACKUP"; public static final String ACTION_RESTORE = "org.iiab.controller.DEEPOP_RESTORE"; public static final String ACTION_CANCEL = "org.iiab.controller.DEEPOP_CANCEL"; - public static final String EXTRA_URI = "uri"; // backup: SAF dest content:// uri - public static final String EXTRA_PATH = "path"; // restore: already-validated temp file path + public static final String EXTRA_URI = "uri"; // backup: SAF dest; restore: SAF source + + /** K2GO-372: a restore is one run of three passes — stage the file, verify it, extract it — so they + * share one bar instead of each filling it and sending it back to zero. */ + private static final int RESTORE_PASSES = 3; + private static final int COPY_PASS = 0; + private static final int VERIFY_PASS = 1; + private static final int EXTRACT_PASS = 2; private final Handler main = new Handler(Looper.getMainLooper()); private PowerManager.WakeLock wakeLock; @@ -85,9 +96,9 @@ public static void startBackup(Context ctx, Uri dest) { startFg(ctx, i); } - /** Start a restore: extract the already-validated temp archive over the rootfs (destructive). */ - public static void startRestore(Context ctx, String validatedTempPath) { - Intent i = new Intent(ctx, DeepOpService.class).setAction(ACTION_RESTORE).putExtra(EXTRA_PATH, validatedTempPath); + /** Start a restore: stage the picked archive, then extract it over the rootfs (destructive). */ + public static void startRestore(Context ctx, Uri source) { + Intent i = new Intent(ctx, DeepOpService.class).setAction(ACTION_RESTORE).putExtra(EXTRA_URI, source.toString()); startFg(ctx, i); } @@ -111,21 +122,23 @@ public int onStartCommand(Intent intent, int flags, int startId) { started = true; owner = ACTION_RESTORE.equals(action) ? EnvironmentLock.Owner.RESTORE : EnvironmentLock.Owner.BACKUP; - stepText = getString(R.string.k2go_br_status_stopping); + final boolean restoring = owner == EnvironmentLock.Owner.RESTORE; + // K2GO-372: a restore now begins by staging the picked file, so it opens on a different step. + // Taking the lock here also sends the box down (RESTORE is a STOPPED-class holder, so desired + // goes DOWN on the next reconciler tick) — which is what the confirm the user just answered + // promised, and it means the explicit stop below has little left to wait for. + stepText = getString(restoring ? R.string.k2go_br_status_copying : R.string.k2go_br_status_stopping); startForeground(NOTIFICATION_ID, buildNotification(stepText)); acquireHardwareLocks(); EnvironmentLock.acquire(this, owner); - if (owner == EnvironmentLock.Owner.RESTORE) InstallGuard.begin(this); // damage recovery for a killed extract + // Indeterminate until a pass reports a percent it measured: a source whose size the provider + // will not tell us has no honest bar, and one pinned at 0 reads as a stall. post(stepText, -1); - if (owner == EnvironmentLock.Owner.RESTORE) { - final String path = intent.getStringExtra(EXTRA_PATH); - EnvironmentControl.stop(this, this::log, () -> runRestore(path)); - } else { - final String uriStr = intent.getStringExtra(EXTRA_URI); - EnvironmentControl.stop(this, this::log, () -> runBackup(uriStr)); - } + final String uriStr = intent.getStringExtra(EXTRA_URI); + if (restoring) stageThenRestore(uriStr); + else EnvironmentControl.stop(this, this::log, () -> runBackup(uriStr)); return START_NOT_STICKY; } @@ -148,20 +161,160 @@ private void runBackup(final String uriStr) { } // ---- RESTORE (destructive) ---- + + /** + * K2GO-372: copy the picked archive out of the SAF provider, then run the restore. + * + *

The copy used to run in the fragment, before the confirm, with no progress and no foreground + * service behind it. It is the same copy; it just belongs here, where it is measured and where + * leaving the screen cannot strand it. It runs before the damage marker is planted, because nothing + * is written yet — see the marker comment in {@link #runRestore}. + */ + private void stageThenRestore(final String uriStr) { + final File temp = new File(getCacheDir(), "restore.tar.gz"); + final Uri src = Uri.parse(uriStr); + AppExecutors.get().io().execute(() -> { + final long compressed = sourceSize(src); + String failure = rejectBeforeCopy(src); + if (failure == null) { + failure = rejectForSpace(compressed); + } + if (failure == null) { + failure = stageArchive(src, temp, compressed); + } + final String outcome = failure; + main.post(() -> { + if (done) { + // Unreachable while a restore is uncancellable, but a staged archive is gigabytes: + // whoever reaches a terminal first must not leave it in the cache. + //noinspection ResultOfMethodCallIgnored + temp.delete(); + return; + } + if (outcome != null) { + endRestore(temp.getAbsolutePath(), false, outcome); + return; + } + setStep(getString(R.string.k2go_br_status_stopping), -1); + EnvironmentControl.stop(this, this::log, () -> runRestore(temp.getAbsolutePath())); + }); + }); + } + + /** + * K2GO-372: judge the picked file before paying to copy it. + * + *

The identity manifest is the archive's first member, so this reads a few KB of the SAF stream + * and refuses a wrong-ABI or non-rootfs file in about a second, instead of after a multi-gigabyte + * copy the user then watches be thrown away. An archive with no manifest is not judged here — the + * extractor's structural check still has the last word, on the copy. + * + * @return the reason to show, or {@code null} when nothing here rejects it. + */ + private String rejectBeforeCopy(Uri src) { + RootfsManifest.Identity id; + try (InputStream raw = getContentResolver().openInputStream(src)) { + if (raw == null) return getString(R.string.k2go_br_restore_unreadable); + // A SAF uri carries no filename to read an extension from, so ask the bytes: gzip's two + // magic bytes. Honest for any source, and it drops the naming assumption the old + // path-based caller could afford. + java.io.BufferedInputStream buf = new java.io.BufferedInputStream(raw); + buf.mark(2); + final boolean isGzip = buf.read() == 0x1f && buf.read() == 0x8b; + buf.reset(); + id = RootfsManifest.read(buf, isGzip); + } catch (Exception e) { + Log.w(TAG, "Could not read the picked file's manifest", e); + return null; // unreadable here is not a verdict; the copy below will say so properly + } + return RootfsArchiveValidator.rejectionMessage(this, RootfsArchiveValidator.identityRejection(id)); + } + + /** The picked file's length, or {@code -1} when the provider will not report one. */ + private long sourceSize(Uri src) { + try (android.os.ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(src, "r")) { + return pfd == null ? -1L : pfd.getStatSize(); + } catch (Exception ignored) { + return -1L; // the copy below is what has to work; the size only sharpens it + } + } + + /** + * K2GO-372: refuse before copying when the copy and the tree it expands into plainly cannot both + * fit. The guard was only ever asked about the expansion, and only once the copy was already on + * disk, so a device with room for neither filled up mid-copy and reported it as an unreadable file. + * + *

{@link #runRestore} keeps the authoritative check on the real staged file — this one cannot run + * when the provider will not report a length, and free space can change in between. + * + * @return the reason to show, or {@code null} when there is room (or nothing to judge with). + */ + private String rejectForSpace(long compressedBytes) { + if (compressedBytes <= 0L) { + return null; + } + org.iiab.controller.storage.FreeSpacePreflight.Result pf = + org.iiab.controller.storage.FreeSpacePreflight.check(this, + org.iiab.controller.storage.SpaceEstimate.peakForRestore(compressedBytes)); + return pf.ok ? null : noStorageMessage(pf); + } + + /** One shape for "it does not fit", used before the copy and again before the extraction. */ + private String noStorageMessage(org.iiab.controller.storage.FreeSpacePreflight.Result pf) { + return getString(R.string.install_error_no_storage) + " (" + + org.iiab.controller.util.ByteFormatter.toHuman(pf.amountToReport()) + ")"; + } + + /** + * Copy {@code src} to {@code temp}, reporting percent as it goes. + * + * @param size the source's length, or {@code -1}: an unknown length is copied with an indeterminate + * percent rather than a made-up one. + * @return {@code null} on success, otherwise the message to show the user. + */ + private String stageArchive(Uri src, File temp, long size) { + try (InputStream in = getContentResolver().openInputStream(src); + OutputStream out = new java.io.FileOutputStream(temp)) { + if (in == null) throw new IOException("The picked file could not be opened"); + byte[] buf = new byte[1 << 16]; + long copied = 0L, lastEmit = 0L; + int n; + while ((n = in.read(buf)) != -1) { // a 0-length read is not end of stream + out.write(buf, 0, n); + copied += n; + long now = android.os.SystemClock.elapsedRealtime(); + if (size > 0L && now - lastEmit >= 200L) { + lastEmit = now; + final int pct = org.iiab.controller.deploy.domain.ExtractProgress + .unifiedPercent(org.iiab.controller.deploy.domain.ExtractProgress + .percent(copied, size), COPY_PASS, RESTORE_PASSES); + main.post(() -> setStep(getString(R.string.k2go_br_status_copying), pct)); + } + } + out.flush(); + return null; + } catch (Exception e) { + Log.e(TAG, "Staging the picked archive failed", e); + //noinspection ResultOfMethodCallIgnored + temp.delete(); + return getString(R.string.k2go_br_restore_unreadable); + } + } + private void runRestore(final String path) { if (done) return; // ADFA-5105: the restore overwrites the rootfs with the backup's contents. Refuse before // anything is touched when the uncompressed backup plainly won't fit (fail-safe on UNKNOWN // free space too). The "needed" is estimated from the backup archive already on disk. + // K2GO-372: the second of two gates. rejectForSpace() asked the same question before the copy, + // where the copy still counted toward what has to fit; here the copy is already spent, so the + // free space it reads is that much lower and the expansion alone is what is left to cover — + // the same inequality, asked again in case the length was unknown or the disk moved under us. long needed = org.iiab.controller.storage.SpaceEstimate.fromCompressed(new File(path).length()); org.iiab.controller.storage.FreeSpacePreflight.Result pf = org.iiab.controller.storage.FreeSpacePreflight.check(this, needed); if (!pf.ok) { - File tmp = new File(path); - if (tmp.exists()) tmp.delete(); - finishJob(false, getString(R.string.k2go_br_restore_done), - getString(R.string.install_error_no_storage) + " (" - + org.iiab.controller.util.ByteFormatter.toHuman(pf.amountToReport()) + ")"); + endRestore(path, false, noStorageMessage(pf)); return; } // ADFA-5070: stop the downloads before the tar starts overwriting the rootfs @@ -170,17 +323,49 @@ private void runRestore(final String path) { // thrown away what the user asked for over an operation that never happened. org.iiab.controller.system.data.ContentStateInvalidator.replacementStarting(this, org.iiab.controller.system.domain.SystemReplacement.Cause.RESTORE); - setStep(getString(R.string.k2go_br_status_restoring), -1); + setStep(getString(R.string.k2go_br_status_checking), 0); final File destParent = new File(getFilesDir(), "rootfs"); new TarExtractor().startExtraction(this, path, destParent.getAbsolutePath(), true, new TarExtractor.ExtractionListener() { - @Override public void onComplete(String destDir) { main.post(() -> endRestore(path, true)); } - @Override public void onError(String error) { main.post(() -> endRestore(path, false)); } + @Override public void onComplete(String destDir) { main.post(() -> endRestore(path, true, null)); } + @Override public void onError(String error) { main.post(() -> endRestore(path, false, error)); } @Override public void onProgress(String line) { } + + /** + * K2GO-372: a restore reads the whole archive three times — the copy above, the + * safety listing pass and the extraction pass — and reported all of it as an + * indeterminate spinner, so a multi-minute wait was indistinguishable from a hang. + * The byte-based bar already existed for the rootfs install (ADFA-5118); this + * consumes the same callback and maps every pass onto one 0-100 bar, so no pass + * can look like a whole run. + */ + @Override + public void onExtractPhase(TarExtractor.Phase phase, int passPercent, + long etaSeconds, String line) { + final boolean extracting = phase == TarExtractor.Phase.EXTRACT; + // K2GO-372: the destructive window opens here, at the first byte written over the + // rootfs. The marker used to be planted when the service started, which also + // covered the copy and the whole verify pass — phases where a kill damages + // nothing, so an ungraceful exit in them declared a false DAMAGED, and an archive + // the extractor rejects would have left the system marked damaged untouched. + // isLive() reads the marker itself, so knowing it is already planted needs no + // second flag here. + if (extracting && !InstallGuard.isLive(DeepOpService.this)) { + InstallGuard.begin(DeepOpService.this); + } + final int unified = org.iiab.controller.deploy.domain.ExtractProgress + .unifiedPercent(passPercent, extracting ? EXTRACT_PASS : VERIFY_PASS, + RESTORE_PASSES); + final String label = getString(extracting + ? R.string.k2go_br_status_restoring + : R.string.k2go_br_status_checking); + main.post(() -> setStep(label, unified)); + } }); } - private void endRestore(String tempPath, boolean ok) { + /** @param failMessage why it failed, when the failure knows; {@code null} falls back to the generic. */ + private void endRestore(String tempPath, boolean ok, String failMessage) { if (ok) { // ADFA-5070: the rootfs really was replaced, and the content that arrived // is the backup's — so the orders placed against the old one are stale. @@ -189,7 +374,11 @@ private void endRestore(String tempPath, boolean ok) { } File temp = new File(tempPath); if (temp.exists()) temp.delete(); - finishJob(ok, getString(R.string.k2go_br_restore_done), getString(R.string.k2go_br_restore_failed)); + // K2GO-372: the extractor already produces the exact reason (wrong architecture, not a rootfs); + // it used to be discarded here and replaced by a generic "Restore failed". + finishJob(ok, getString(R.string.k2go_br_restore_done), + failMessage == null || failMessage.trim().isEmpty() + ? getString(R.string.k2go_br_restore_failed) : failMessage); } // ---- single terminal path (natural completion OR cancel), run once ---- diff --git a/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsArchiveValidator.java b/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsArchiveValidator.java index 19bb604de..2f9aebcab 100644 --- a/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsArchiveValidator.java +++ b/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsArchiveValidator.java @@ -16,15 +16,12 @@ import org.iiab.controller.deploy.domain.ElfClass; import org.iiab.controller.deploy.domain.RootfsArchive; -import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; -import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; -import java.util.Locale; import java.util.zip.GZIPInputStream; /** @@ -53,22 +50,49 @@ private RootfsArchiveValidator() { // Static utility; not instantiable. } - /** Validate from a file path (lists the archive itself; use for the import gate). */ - public static Result validate(Context context, String archivePath) { - try { - String tarBinary = resolveTar(context); - boolean isGzip = archivePath.toLowerCase(Locale.US).endsWith(".gz"); - List entries = listEntries(tarBinary, archivePath, isGzip); - if (entries.isEmpty()) { - return Result.UNREADABLE; - } - return validateWithEntries(context, archivePath, isGzip, tarBinary, entries, true); - } catch (Exception e) { - Log.e(TAG, "Validation error", e); - return Result.UNREADABLE; + /** + * K2GO-372: the manifest's rejection, if any — a thin adapter over the pure rule in + * {@link org.iiab.controller.deploy.domain.RootfsIdentity}, which is where the decision lives + * and where it is tested. This half supplies the two things the rule cannot know on its own: + * the running app's ABI, and how a domain verdict maps onto {@link Result}. + * + *

Worth calling before the listing pass: the manifest is packed first, so this reads a few + * KB, while the listing reads the whole archive. + * + * @return the rejecting {@link Result}, or {@code null} when the manifest does not reject. + */ + public static Result identityRejection(RootfsManifest.Identity id) { + org.iiab.controller.deploy.domain.RootfsIdentity.Verdict v = + org.iiab.controller.deploy.domain.RootfsIdentity.check( + id != null && id.present, + id == null ? null : id.kind, + id == null ? null : id.arch, + RootfsManifest.appAbiId()); + switch (v) { + case NOT_A_ROOTFS: return Result.NOT_A_ROOTFS; + case WRONG_ARCH: return Result.WRONG_ARCH; + default: return null; } } + /** + * K2GO-372: the reason to show for a rejecting {@link Result}, or {@code null} when it does not + * reject. Both extractor gates and the restore's pre-copy check spell the same verdicts, and they + * used to each carry their own if-chain of strings. + * + *

Note it rejects {@link Result#CORRUPT} too, which the extractor's two inline chains did not: + * failing closed on a failed integrity check is the right direction, and it is inert on today's + * callers (the extractor validates with {@code checkIntegrity=false}, where CORRUPT cannot arise). + * {@link Result#UNREADABLE} is deliberately NOT a rejection here — see the callers; that gap + * predates this method. + */ + public static String rejectionMessage(Context ctx, Result r) { + if (r == Result.NOT_A_ROOTFS) return ctx.getString(org.iiab.controller.R.string.install_error_not_rootfs); + if (r == Result.WRONG_ARCH) return ctx.getString(org.iiab.controller.R.string.install_error_wrong_arch); + if (r == Result.CORRUPT) return ctx.getString(org.iiab.controller.R.string.install_error_corrupt); + return null; + } + /** * Validate when the caller already has the entry listing (e.g. {@code TarExtractor} * lists once for the D11 traversal guard — reuse it here, no second listing). @@ -93,14 +117,11 @@ public static Result validateWithEntries(Context context, String archivePath, // (installed-rootfs/iiab/.iiab-rootfs.json, packed first). See // docs/ROOTFS_MANIFEST.md. When present it decides kind + arch. RootfsManifest.Identity id = RootfsManifest.read(archivePath); + Result rejection = identityRejection(id); + if (rejection != null) { + return rejection; + } if (id.present) { - if (!"iiab-rootfs".equals(id.kind)) { - return Result.NOT_A_ROOTFS; - } - if (id.arch != null && !id.arch.isEmpty() - && !id.arch.equals(RootfsManifest.appAbiId())) { - return Result.WRONG_ARCH; - } // Identity is authoritative for kind+arch. Now decide integrity. if ("device-backup".equals(id.origin)) { // App-made backup: no checksum by design (we don't turn the @@ -148,38 +169,6 @@ public static Result validateWithEntries(Context context, String archivePath, } } - private static String resolveTar(Context context) { - File staticTar = new File(context.getApplicationInfo().nativeLibraryDir, "libtar.so"); - return staticTar.exists() ? staticTar.getAbsolutePath() : "/system/bin/tar"; - } - - private static List listEntries(String tarBinary, String archivePath, boolean isGzip) throws Exception { - List names = new ArrayList<>(); - List cmd = new ArrayList<>(); - cmd.add(tarBinary); - if (isGzip) { - cmd.add("-t"); - cmd.add("-f"); - cmd.add("-"); - } else { - cmd.add("-tf"); - cmd.add(archivePath); - } - Process p = new ProcessBuilder(cmd).start(); - Thread feeder = isGzip ? startGzipFeeder(archivePath, p.getOutputStream()) : null; - try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) { - String line; - while ((line = r.readLine()) != null) { - names.add(line); - } - } - p.waitFor(); - if (feeder != null) { - feeder.join(); - } - return names; - } - private static byte[] readMemberHeader(String tarBinary, String archivePath, boolean isGzip, String member, int n) throws Exception { List cmd = new ArrayList<>(); diff --git a/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsManifest.java b/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsManifest.java index 6654ee97d..7f4965976 100644 --- a/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsManifest.java +++ b/controller/app/src/main/java/org/iiab/controller/deploy/data/RootfsManifest.java @@ -68,8 +68,21 @@ public static String appAbiId() { /** Read the identity manifest from {@code archivePath}, or {@link Identity#absent()}. */ public static Identity read(String archivePath) { boolean isGzip = archivePath.toLowerCase(Locale.US).endsWith(".gz"); - try (InputStream raw = new FileInputStream(archivePath); - InputStream in = isGzip ? new GZIPInputStream(raw) : new BufferedInputStream(raw)) { + try (InputStream raw = new FileInputStream(archivePath)) { + return read(raw, isGzip); + } catch (Exception e) { + Log.w(TAG, "Could not read identity manifest: " + e.getMessage()); + return Identity.absent(); + } + } + + /** + * K2GO-372: the same read from an already-open stream, so a file can be judged before it is copied + * anywhere. Only the first few KB are consumed — the manifest is the first member — but the stream + * is closed here either way, since a caller that has its verdict has no use for the rest. + */ + public static Identity read(InputStream raw, boolean isGzip) { + try (InputStream in = isGzip ? new GZIPInputStream(raw) : new BufferedInputStream(raw)) { byte[] header = new byte[512]; for (int i = 0; i < MAX_HEADERS; i++) { diff --git a/controller/app/src/main/java/org/iiab/controller/deploy/domain/ExtractProgress.java b/controller/app/src/main/java/org/iiab/controller/deploy/domain/ExtractProgress.java index 247343a95..0eb7bd364 100644 --- a/controller/app/src/main/java/org/iiab/controller/deploy/domain/ExtractProgress.java +++ b/controller/app/src/main/java/org/iiab/controller/deploy/domain/ExtractProgress.java @@ -49,16 +49,33 @@ public static long etaSeconds(long done, long total, long ratePerSec) { } /** - * ADFA-5118: map a single pass's percent onto the unified two-pass bar. Verify owns - * [0,50), extract owns [50,100). {@code passPercent} is that pass's own 0..100; it is - * clamped, halved, and offset by 50 for the second pass. The result is capped at 99 so - * only true completion (set by the caller) reaches 100. This keeps the bar monotone - * across the handoff: verify ends near 49, extract starts at 50. + * ADFA-5118: map a single pass's percent onto the unified two-pass bar — the shape the rootfs + * install runs. Verify owns [0,50), extract owns [50,100). The result is capped at 99 so only + * true completion (set by the caller) reaches 100, which keeps the bar monotone across the + * handoff: verify ends near 49, extract starts at 50. */ public static int unifiedPercent(int passPercent, boolean secondPass) { + return unifiedPercent(passPercent, secondPass ? 1 : 0, 2); + } + + /** + * K2GO-372: the same rule for a run of any number of passes, because a restore has three — it + * stages the picked file before it verifies and extracts it. Each pass owns an equal slice of the + * bar, so no pass can fill the bar and send it back to zero, which is the whole point of a unified + * percent. Slices are equal, not time-weighted: the passes' durations depend on the device and the + * archive, and a bar that lies about which slice is long is worse than one that moves unevenly. + * + * @param passPercent this pass's own 0-100 progress. + * @param passIndex which pass is running, from 0. + * @param passCount how many passes the whole run has. + */ + public static int unifiedPercent(int passPercent, int passIndex, int passCount) { + if (passCount < 1) passCount = 1; + if (passIndex < 0) passIndex = 0; + if (passIndex > passCount - 1) passIndex = passCount - 1; if (passPercent < 0) passPercent = 0; if (passPercent > 100) passPercent = 100; - int v = (secondPass ? 50 : 0) + passPercent / 2; + int v = (passIndex * 100 + passPercent) / passCount; return v > 99 ? 99 : v; } diff --git a/controller/app/src/main/java/org/iiab/controller/deploy/domain/RootfsIdentity.java b/controller/app/src/main/java/org/iiab/controller/deploy/domain/RootfsIdentity.java new file mode 100644 index 000000000..8da780758 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/deploy/domain/RootfsIdentity.java @@ -0,0 +1,67 @@ +/* + * ============================================================================ + * Name : RootfsIdentity.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-372. Is this archive a rootfs, and is it ours to unpack? + * ============================================================================ + */ +package org.iiab.controller.deploy.domain; + +/** + * The identity half of the archive verdict: what the manifest alone can settle. + * + *

Separate from the rest of validation because it is answerable from a few KB — the manifest is + * packed first — while the structural checks need the whole archive listed. Splitting it lets a + * caller reject the wrong file before paying for a full decompression pass, which on a phone is + * the difference between a one-second refusal and a five-minute one. + * + *

Pure: the ABI to compare against is passed in rather than read from {@code android.os}, so the + * rule is unit-tested on the JVM instead of only on a device. + */ +public final class RootfsIdentity { + + /** What the manifest says about whether this archive may be unpacked here. */ + public enum Verdict { + /** Nothing to reject: identity checks out, or there is no manifest to ask. */ + OK, + /** The manifest says this is not a rootfs at all. */ + NOT_A_ROOTFS, + /** A rootfs, but built for a different ABI than this app runs. */ + WRONG_ARCH + } + + /** The kind every rootfs manifest declares; anything else is a different sort of archive. */ + private static final String KIND_ROOTFS = "iiab-rootfs"; + + private RootfsIdentity() { + } + + /** + * Decide whether the manifest rejects this archive. + * + *

An absent manifest is {@link Verdict#OK} rather than a rejection: older archives predate + * it, and refusing them here would turn a missing hint into a hard failure. The structural + * fallback decides those. + * + *

An empty or absent {@code arch} is likewise not a rejection — the manifest simply does not + * claim one, so there is nothing to contradict. + * + * @param present whether the archive carried a manifest at all. + * @param kind the manifest's declared kind. + * @param arch the manifest's declared ABI. + * @param appAbi the ABI this app runs as; the archive must match it to be unpackable. + */ + public static Verdict check(boolean present, String kind, String arch, String appAbi) { + if (!present) { + return Verdict.OK; + } + if (!KIND_ROOTFS.equals(kind)) { + return Verdict.NOT_A_ROOTFS; + } + if (arch != null && !arch.isEmpty() && appAbi != null && !arch.equals(appAbi)) { + return Verdict.WRONG_ARCH; + } + return Verdict.OK; + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BackupJobFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/BackupJobFragment.java index bf546dc0d..57ab41a6d 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BackupJobFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BackupJobFragment.java @@ -42,13 +42,8 @@ import org.iiab.controller.deepop.DeepOpState; import org.iiab.controller.env.EnvironmentLock; import org.iiab.controller.ui.dialog.BrandDialog; -import org.iiab.controller.util.AppExecutors; import org.iiab.controller.util.Snackbars; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; - public class BackupJobFragment extends Fragment { private static final String ARG_MODE = "mode"; @@ -67,6 +62,11 @@ public static BackupJobFragment newInstance(String mode) { private String mode; private LottieAnimationView anim; private TextView title, sub, status, finish; + private View waitCard; // "this can take a while" — only true while it is still running + /** K2GO-372: determinate progress, hidden until the op reports a percent it can stand behind. */ + private View progressRow; + private com.google.android.material.progressindicator.LinearProgressIndicator progress; + private TextView progressPct; private org.iiab.controller.util.EllipsisAnimator statusDots; private boolean running = false; private long lastSeq = -1L; @@ -99,8 +99,14 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c title = v.findViewById(R.id.k2go_bj_title); sub = v.findViewById(R.id.k2go_bj_sub); status = v.findViewById(R.id.k2go_bj_status); + progressRow = v.findViewById(R.id.k2go_bj_progress_row); + progress = v.findViewById(R.id.k2go_bj_progress); + progressPct = v.findViewById(R.id.k2go_bj_progress_pct); finish = v.findViewById(R.id.k2go_bj_finish); - statusDots = new org.iiab.controller.util.EllipsisAnimator(status); + waitCard = v.findViewById(R.id.k2go_bj_wait_card); + // ADFA-4947 fixed-width mode: this status line is centred, so variable-width dots slide the + // whole label left and right as they grow. Same choice LibraryActivity's boot lines make. + statusDots = new org.iiab.controller.util.EllipsisAnimator(status, true); title.setText(getString(isRestore() ? R.string.k2go_br_restore_title : R.string.k2go_br_backup_title)); sub.setText(getString(isRestore() ? R.string.k2go_br_restore_sub : R.string.k2go_br_backup_sub)); @@ -166,61 +172,63 @@ private void startBackup(Uri uri) { DeepOpService.startBackup(requireContext(), uri); } - // ---- RESTORE: copy + validate + destructive confirm HERE (pre-extract), then the service ---- - private void prepareRestore(Uri uri) { - if (!isAdded()) return; - beginRunning(); - setStatusAnimated(getString(R.string.k2go_br_status_checking)); - AppExecutors.get().io().execute(() -> { - File temp = new File(requireContext().getCacheDir(), "restore.tar.gz"); - boolean copied = false; - try (InputStream in = requireContext().getContentResolver().openInputStream(uri); - OutputStream out = new java.io.FileOutputStream(temp)) { - if (in != null) { - byte[] b = new byte[1 << 16]; int n; - while ((n = in.read(b)) > 0) out.write(b, 0, n); - out.flush(); copied = true; - } - } catch (Exception ignored) { } - org.iiab.controller.deploy.data.RootfsArchiveValidator.Result vr = !copied - ? org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.UNREADABLE - : org.iiab.controller.deploy.data.RootfsArchiveValidator.validate(requireContext(), temp.getAbsolutePath()); - main.post(() -> onValidated(temp, vr)); - }); - } + // ---- RESTORE: destructive confirm FIRST, then the service does every slow read ---- - private void onValidated(File temp, org.iiab.controller.deploy.data.RootfsArchiveValidator.Result vr) { + /** + * K2GO-372: ask before reading, not after. + * + *

This used to copy the picked file into the cache and fully validate it — two complete reads of + * a multi-gigabyte archive, three silent minutes — and only then show the destructive confirm. That + * forced the user to stay and watch a motionless screen for the one question the archive's content + * does not answer: do you want to replace your system? The confirm needs the file's name, not its + * bytes, so it is asked here and everything slow happens afterwards, in {@link DeepOpService}, with + * progress and a notification to come back to. + * + *

Confirming is still not the point of no return: the extractor checks identity, then the whole + * listing, and fails closed before it writes anything ({@code TarExtractor}). A rejected archive + * leaves the current system untouched, which is what made the pre-flight pass safe to delete rather + * than merely move — it was a second place answering a question the extractor already answers. + */ + private void prepareRestore(Uri uri) { if (!isAdded()) return; - boolean ok = vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.OK - || vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.OK_NO_MANIFEST - || vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.OK_NO_CHECKSUM; - if (!ok) { - if (temp.exists()) temp.delete(); - int msg = vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.WRONG_ARCH ? R.string.install_error_wrong_arch - : vr == org.iiab.controller.deploy.data.RootfsArchiveValidator.Result.CORRUPT ? R.string.install_error_corrupt - : R.string.install_error_not_rootfs; - showTerminal(false, getString(msg)); - return; - } new BrandDialog(requireContext()) .setTitle(getString(R.string.k2go_br_restore_title)) .setMessage(getString(R.string.k2go_br_restore_warn)) .setPositive(R.string.k2go_br_restore_confirm, BrandDialog.Role.DESTRUCTIVE, () -> { - setStatusAnimated(getString(R.string.k2go_br_status_stopping)); - DeepOpService.startRestore(requireContext(), temp.getAbsolutePath()); + beginRunning(); + setStatusAnimated(getString(R.string.k2go_br_status_copying)); + DeepOpService.startRestore(requireContext(), uri); }) - .setNegative(R.string.cancel, () -> { if (temp.exists()) temp.delete(); popToIntro(false); }) + .setNegative(R.string.cancel, () -> popToIntro(false)) .show(); } + /** + * K2GO-372: show the bar only for a percent the op actually measured. + * + *

A negative percent means the step cannot say how far along it is, and a bar frozen at zero + * reads as a stall — worse than no bar. Those steps keep the animation above instead. + */ + private void showProgress(int percent) { + if (progressRow == null) return; + final boolean measurable = percent >= 0; + progressRow.setVisibility(measurable ? View.VISIBLE : View.GONE); + if (measurable) { + progress.setProgressCompat(percent, true); + progressPct.setText(percent + "%"); // matches the module-install and maps screens + } + } + // ---- observe the app-scoped op state (DeepOpService is the writer) ---- private void onDeepOpState(DeepOpState st) { if (st == null || !isAdded() || st.owner != myOwner()) return; if (st.isRunning()) { if (!running) beginRunning(); setStatusAnimated(st.step); + showProgress(st.percent); } else if (st.isTerminal() && st.seq > lastSeq) { lastSeq = st.seq; + showProgress(-1); // K2GO-372: a finished op has no bar to keep filling showTerminal(st.phase == DeepOpState.Phase.SUCCESS, st.message); } } @@ -230,6 +238,7 @@ private void beginRunning() { leaveWarned = false; // ADFA-4971: each op's first Back re-warns before backgrounding if (backGate != null) backGate.setEnabled(true); finish.setVisibility(View.GONE); + if (waitCard != null) waitCard.setVisibility(View.VISIBLE); if (anim != null) anim.playAnimation(); } @@ -241,6 +250,9 @@ private void showTerminal(boolean ok, String message) { title.setText(getString(ok ? R.string.k2go_br_done_title : R.string.k2go_br_failed_title)); status.setText(message); status.setTextColor(ContextCompat.getColor(requireContext(), ok ? R.color.k2go_leaf : R.color.k2go_amber_text)); + // The card asks the user to keep the app open because the op is still running; once it has + // finished it is telling them to wait for something that already happened. + if (waitCard != null) waitCard.setVisibility(View.GONE); finish.setVisibility(View.VISIBLE); } diff --git a/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java b/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java index bb5cc9731..a4df4a122 100644 --- a/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java +++ b/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java @@ -26,6 +26,23 @@ private SpaceEstimate() {} public static final int UNCOMPRESSED_NUMERATOR = 22; public static final int UNCOMPRESSED_DENOMINATOR = 10; + /** + * K2GO-372: what a restore needs free at once, in bytes — the staged copy of the picked + * archive plus the tree it expands into, because both are on disk together: the copy is not deleted + * until the extraction has finished. + * + *

The guard used to be asked only about the expansion, and only once the copy was already + * written, so the copy itself was never covered: a device with room for neither filled up mid-copy + * and reported it as an unreadable file. Ask this before copying; the post-copy check still asks + * {@link #fromCompressed} on the real staged file, where the copy is already spent. + */ + public static long peakForRestore(long compressedBytes) { + long c = Math.max(0L, compressedBytes); + long expanded = fromCompressed(c); + long peak = c + expanded; + return peak < expanded ? Long.MAX_VALUE : peak; // saturate on overflow + } + /** Conservative uncompressed-size estimate from a compressed size, in bytes. */ public static long fromCompressed(long compressedBytes) { long c = Math.max(0L, compressedBytes); diff --git a/controller/app/src/main/res/layout/fragment_k2go_backup_job.xml b/controller/app/src/main/res/layout/fragment_k2go_backup_job.xml index a0e072199..5d9870461 100644 --- a/controller/app/src/main/res/layout/fragment_k2go_backup_job.xml +++ b/controller/app/src/main/res/layout/fragment_k2go_backup_job.xml @@ -105,6 +105,39 @@ android:textAppearance="?attr/textAppearanceBodyMedium" android:textColor="@color/k2go_ink" /> + + + + + + + + فشل النسخ الاحتياطي. يرجى المحاولة مرة أخرى. تم حدث خطأ ما + جارٍ نسخ الملف جارٍ التحقّق من الملف جارٍ الاستعادة يستبدل هذا نظامك الحالي بالنسخة الاحتياطية المختارة. لا يمكن التراجع عن ذلك، ويتوقّف الخادم أثناء التنفيذ. استبدال النظام تمت استعادة النظام فشلت الاستعادة + تعذّرت قراءة الملف المحدد، لذا لم يتغيّر أي شيء. النسخ الاحتياطي والاستعادة يُبقي عملية نسخ احتياطي أو استعادة قيد التشغيل بأمان في الخلفية النسخ الاحتياطي والاستعادة diff --git a/controller/app/src/main/res/values-az/strings.xml b/controller/app/src/main/res/values-az/strings.xml index 17c99e0f0..6a4eea780 100644 --- a/controller/app/src/main/res/values-az/strings.xml +++ b/controller/app/src/main/res/values-az/strings.xml @@ -651,12 +651,14 @@ Ehtiyat nüsxə alınmadı. Zəhmət olmasa yenidən cəhd et. Hazır Nə isə səhv getdi + Fayl kopyalanır Fayl yoxlanılır Bərpa olunur Bu, cari sisteminizi seçilmiş ehtiyat nüsxə ilə əvəz edir. Geri qaytarıla bilməz və icra olunarkən server dayanır. Sistemi əvəz et Sistem bərpa olundu Bərpa alınmadı + Seçilmiş fayl oxuna bilmədi, ona görə heç nə dəyişdirilmədi. Ehtiyat nüsxə & bərpa Ehtiyat nüsxə və ya bərpanı arxa planda təhlükəsiz işlədir Ehtiyat nüsxə & bərpa diff --git a/controller/app/src/main/res/values-bg/strings.xml b/controller/app/src/main/res/values-bg/strings.xml index 94e400637..97c89c41e 100644 --- a/controller/app/src/main/res/values-bg/strings.xml +++ b/controller/app/src/main/res/values-bg/strings.xml @@ -638,12 +638,14 @@ Резервното копие е неуспешно. Опитайте отново. Готово Нещо се обърка + Копиране на файла Проверка на файла Възстановяване Това заменя текущата ви система с избраното резервно копие. Действието е необратимо, а сървърът спира, докато се изпълнява. Замени системата Системата е възстановена Неуспешно възстановяване + Избраният файл не можа да бъде прочетен, затова нищо не беше променено. Резервно копие и възстановяване Поддържа безопасното изпълнение на резервно копие или възстановяване във фонов режим Резервно копие и възстановяване diff --git a/controller/app/src/main/res/values-bn/strings.xml b/controller/app/src/main/res/values-bn/strings.xml index c3470aa06..519a93cd0 100644 --- a/controller/app/src/main/res/values-bn/strings.xml +++ b/controller/app/src/main/res/values-bn/strings.xml @@ -644,12 +644,14 @@ ব্যাকআপ ব্যর্থ হয়েছে। আবার চেষ্টা করুন। সম্পন্ন কিছু একটা ভুল হয়েছে + ফাইল কপি করা হচ্ছে ফাইল পরীক্ষা করা হচ্ছে পুনরুদ্ধার হচ্ছে এটি আপনার বর্তমান সিস্টেমকে নির্বাচিত ব্যাকআপ দিয়ে প্রতিস্থাপন করে। এটি বাতিল করা যায় না, এবং চলার সময় সার্ভার বন্ধ থাকে। সিস্টেম প্রতিস্থাপন করুন সিস্টেম পুনরুদ্ধার হয়েছে পুনরুদ্ধার ব্যর্থ হয়েছে + নির্বাচিত ফাইলটি পড়া যায়নি, তাই কিছুই পরিবর্তন করা হয়নি। ব্যাকআপ ও পুনরুদ্ধার ব্যাকআপ বা পুনরুদ্ধার ব্যাকগ্রাউন্ডে নিরাপদে চালু রাখে ব্যাকআপ ও পুনরুদ্ধার diff --git a/controller/app/src/main/res/values-cs/strings.xml b/controller/app/src/main/res/values-cs/strings.xml index c9a8fb28f..ad9b84d1f 100644 --- a/controller/app/src/main/res/values-cs/strings.xml +++ b/controller/app/src/main/res/values-cs/strings.xml @@ -638,12 +638,14 @@ Zálohování selhalo. Zkus to znovu. Hotovo Něco se pokazilo + Kopírování souboru Kontrola souboru Obnovování Tímto nahradíte aktuální systém vybranou zálohou. Nelze to vrátit zpět a během operace se server zastaví. Nahradit systém Systém obnoven Obnova selhala + Vybraný soubor se nepodařilo přečíst, takže se nic nezměnilo. Záloha & obnova Udržuje zálohu nebo obnovu bezpečně spuštěnou na pozadí Záloha & obnova diff --git a/controller/app/src/main/res/values-de/strings.xml b/controller/app/src/main/res/values-de/strings.xml index cf48991a4..c44a1e83c 100644 --- a/controller/app/src/main/res/values-de/strings.xml +++ b/controller/app/src/main/res/values-de/strings.xml @@ -631,12 +631,14 @@ Sicherung fehlgeschlagen. Bitte versuche es erneut. Fertig Etwas ist schiefgelaufen + Datei wird kopiert Datei wird geprüft Wird wiederhergestellt Das ersetzt dein aktuelles System durch das gewählte Backup. Es kann nicht rückgängig gemacht werden, und der Server stoppt währenddessen. System ersetzen System wiederhergestellt Wiederherstellung fehlgeschlagen + Die ausgewählte Datei konnte nicht gelesen werden, daher wurde nichts geändert. Sichern & wiederherstellen Hält ein Backup oder eine Wiederherstellung sicher im Hintergrund am Laufen Sichern & wiederherstellen diff --git a/controller/app/src/main/res/values-el/strings.xml b/controller/app/src/main/res/values-el/strings.xml index d6b9a272f..1ff6cd2d6 100644 --- a/controller/app/src/main/res/values-el/strings.xml +++ b/controller/app/src/main/res/values-el/strings.xml @@ -638,12 +638,14 @@ Η δημιουργία αντιγράφου ασφαλείας απέτυχε. Δοκιμάστε ξανά. Ολοκληρώθηκε Κάτι πήγε στραβά + Αντιγραφή του αρχείου Έλεγχος του αρχείου Επαναφορά Αυτό αντικαθιστά το τρέχον σύστημά σας με το επιλεγμένο αντίγραφο ασφαλείας. Δεν μπορεί να αναιρεθεί και ο διακομιστής σταματά όσο εκτελείται. Αντικατάσταση συστήματος Το σύστημα επαναφέρθηκε Αποτυχία επαναφοράς + Δεν ήταν δυνατή η ανάγνωση του επιλεγμένου αρχείου, επομένως δεν άλλαξε τίποτα. Αντίγραφο ασφαλείας & επαναφορά Διατηρεί ένα αντίγραφο ασφαλείας ή μια επαναφορά σε ασφαλή εκτέλεση στο παρασκήνιο Αντίγραφο ασφαλείας & επαναφορά diff --git a/controller/app/src/main/res/values-es/strings.xml b/controller/app/src/main/res/values-es/strings.xml index 7b3294ef6..0bbcbce4b 100644 --- a/controller/app/src/main/res/values-es/strings.xml +++ b/controller/app/src/main/res/values-es/strings.xml @@ -707,12 +707,14 @@ La copia de seguridad falló. Inténtalo de nuevo. Listo Algo salió mal + Copiando el archivo Comprobando el archivo Restaurando Esto reemplaza tu sistema actual con la copia elegida. No se puede deshacer, y el servidor se detiene mientras se ejecuta. Reemplazar sistema Sistema restaurado La restauración falló + No se pudo leer el archivo seleccionado, así que no se cambió nada. Copia de seguridad y restauración Mantiene una copia o restauración ejecutándose de forma segura en segundo plano Copia de seguridad y restauración diff --git a/controller/app/src/main/res/values-fa/strings.xml b/controller/app/src/main/res/values-fa/strings.xml index 518391709..f776ef99f 100644 --- a/controller/app/src/main/res/values-fa/strings.xml +++ b/controller/app/src/main/res/values-fa/strings.xml @@ -631,12 +631,14 @@ پشتیبان‌گیری ناموفق بود. لطفاً دوباره تلاش کنید. انجام شد مشکلی پیش آمد + در حال کپی کردن فایل در حال بررسی فایل در حال بازیابی این کار سیستم فعلی شما را با پشتیبان انتخاب‌شده جایگزین می‌کند. قابل بازگردانی نیست و در حین اجرا سرور متوقف می‌شود. جایگزینی سیستم سیستم بازیابی شد بازیابی ناموفق بود + فایل انتخاب‌شده خوانده نشد، بنابراین چیزی تغییر نکرد. پشتیبان‌گیری و بازیابی پشتیبان‌گیری یا بازیابی را با ایمنی در پس‌زمینه اجرا نگه می‌دارد پشتیبان‌گیری و بازیابی diff --git a/controller/app/src/main/res/values-fr/strings.xml b/controller/app/src/main/res/values-fr/strings.xml index aaf4da689..cdd0a6b83 100644 --- a/controller/app/src/main/res/values-fr/strings.xml +++ b/controller/app/src/main/res/values-fr/strings.xml @@ -709,12 +709,14 @@ La sauvegarde a échoué. Veuillez réessayer. Terminé Une erreur s\'est produite + Copie du fichier Vérification du fichier Restauration en cours Cela remplace votre système actuel par la sauvegarde choisie. C\'est irréversible, et le serveur s\'arrête pendant l\'opération. Remplacer le système Système restauré Échec de la restauration + Le fichier sélectionné n\'a pas pu être lu, donc rien n\'a été modifié. Sauvegarde & restauration Maintient une sauvegarde ou une restauration en cours en toute sécurité en arrière-plan Sauvegarde & restauration diff --git a/controller/app/src/main/res/values-gu/strings.xml b/controller/app/src/main/res/values-gu/strings.xml index ebc379317..5910254c3 100644 --- a/controller/app/src/main/res/values-gu/strings.xml +++ b/controller/app/src/main/res/values-gu/strings.xml @@ -644,12 +644,14 @@ બૅકઅપ નિષ્ફળ થયું. કૃપા કરીને ફરી પ્રયાસ કરો. થઈ ગયું કંઈક ખોટું થયું + ફાઇલ કૉપિ થઈ રહી છે ફાઇલ તપાસાઈ રહી છે રિસ્ટોર થઈ રહ્યું છે આ તમારી વર્તમાન સિસ્ટમને પસંદ કરેલા બૅકઅપ વડે બદલે છે. તે પાછું લઈ શકાતું નથી, અને તે ચાલે ત્યારે સર્વર બંધ થાય છે. સિસ્ટમ બદલો સિસ્ટમ રિસ્ટોર થઈ રિસ્ટોર નિષ્ફળ + પસંદ કરેલી ફાઇલ વાંચી શકાઈ નહીં, તેથી કંઈ બદલાયું નથી. બૅકઅપ & રિસ્ટોર બૅકઅપ કે રિસ્ટોરને બૅકગ્રાઉન્ડમાં સુરક્ષિત રીતે ચાલુ રાખે છે બૅકઅપ & રિસ્ટોર diff --git a/controller/app/src/main/res/values-hi/strings.xml b/controller/app/src/main/res/values-hi/strings.xml index d1259b8a4..bef121504 100644 --- a/controller/app/src/main/res/values-hi/strings.xml +++ b/controller/app/src/main/res/values-hi/strings.xml @@ -708,12 +708,14 @@ बैकअप विफल रहा। कृपया पुनः प्रयास करें। हो गया कुछ गड़बड़ हो गई + फ़ाइल कॉपी की जा रही है फ़ाइल जाँची जा रही है पुनर्स्थापित हो रहा है यह आपके मौजूदा सिस्टम को चुने गए बैकअप से बदल देता है। इसे पूर्ववत नहीं किया जा सकता, और चलने के दौरान सर्वर रुक जाता है। सिस्टम बदलें सिस्टम पुनर्स्थापित हुआ पुनर्स्थापना विफल + चुनी गई फ़ाइल पढ़ी नहीं जा सकी, इसलिए कुछ भी नहीं बदला गया। बैकअप और पुनर्स्थापना बैकअप या पुनर्स्थापना को बैकग्राउंड में सुरक्षित रूप से चलाए रखता है बैकअप और पुनर्स्थापना diff --git a/controller/app/src/main/res/values-hu/strings.xml b/controller/app/src/main/res/values-hu/strings.xml index b3c82f592..25086dc46 100644 --- a/controller/app/src/main/res/values-hu/strings.xml +++ b/controller/app/src/main/res/values-hu/strings.xml @@ -631,12 +631,14 @@ A biztonsági mentés sikertelen. Próbáld újra. Kész Valami hiba történt + Fájl másolása A fájl ellenőrzése Visszaállítás folyamatban Ez lecseréli a jelenlegi rendszered a kiválasztott mentésre. Nem vonható vissza, és a szerver leáll, amíg fut. Rendszer cseréje A rendszer visszaállítva A visszaállítás nem sikerült + A kiválasztott fájlt nem sikerült beolvasni, ezért semmi sem változott. Biztonsági mentés & visszaállítás Biztonságosan futtatja a mentést vagy visszaállítást a háttérben Biztonsági mentés & visszaállítás diff --git a/controller/app/src/main/res/values-in/strings.xml b/controller/app/src/main/res/values-in/strings.xml index 6ecdaeb28..78212ef13 100644 --- a/controller/app/src/main/res/values-in/strings.xml +++ b/controller/app/src/main/res/values-in/strings.xml @@ -638,12 +638,14 @@ Pencadangan gagal. Silakan coba lagi. Selesai Terjadi kesalahan + Menyalin berkas Memeriksa berkas Memulihkan Ini mengganti sistem Anda saat ini dengan cadangan yang dipilih. Tidak bisa dibatalkan, dan server berhenti selama berjalan. Ganti sistem Sistem dipulihkan Pemulihan gagal + Berkas yang dipilih tidak dapat dibaca, jadi tidak ada yang diubah. Cadangkan & pulihkan Menjaga pencadangan atau pemulihan berjalan aman di latar belakang Cadangkan & pulihkan diff --git a/controller/app/src/main/res/values-it/strings.xml b/controller/app/src/main/res/values-it/strings.xml index aafcbdc2b..9a3742507 100644 --- a/controller/app/src/main/res/values-it/strings.xml +++ b/controller/app/src/main/res/values-it/strings.xml @@ -631,12 +631,14 @@ Backup non riuscito. Riprova. Fatto Qualcosa è andato storto + Copia del file Verifica del file Ripristino in corso Questo sostituisce il sistema attuale con il backup scelto. Non può essere annullato e il server si arresta durante l\'operazione. Sostituisci sistema Sistema ripristinato Ripristino non riuscito + Non è stato possibile leggere il file selezionato, quindi non è stato modificato nulla. Backup & ripristino Mantiene un backup o ripristino in esecuzione in modo sicuro in background Backup & ripristino diff --git a/controller/app/src/main/res/values-ja/strings.xml b/controller/app/src/main/res/values-ja/strings.xml index 65b1d0373..52d23e2a1 100644 --- a/controller/app/src/main/res/values-ja/strings.xml +++ b/controller/app/src/main/res/values-ja/strings.xml @@ -632,12 +632,14 @@ バックアップに失敗しました。もう一度お試しください。 完了 問題が発生しました + ファイルをコピー中 ファイルを確認中 復元中 これにより現在のシステムが選択したバックアップに置き換えられます。元に戻すことはできず、実行中はサーバーが停止します。 システムを置き換え システムを復元しました 復元に失敗しました + 選択したファイルを読み取れなかったため、何も変更されていません。 バックアップと復元 バックアップや復元をバックグラウンドで安全に実行し続けます バックアップと復元 diff --git a/controller/app/src/main/res/values-ko/strings.xml b/controller/app/src/main/res/values-ko/strings.xml index ee3083c9c..1182265d1 100644 --- a/controller/app/src/main/res/values-ko/strings.xml +++ b/controller/app/src/main/res/values-ko/strings.xml @@ -632,12 +632,14 @@ 백업에 실패했습니다. 다시 시도하세요. 완료 문제가 발생했습니다 + 파일 복사 중 파일 확인 중 복원 중 이렇게 하면 현재 시스템이 선택한 백업으로 대체됩니다. 실행 취소할 수 없으며 실행 중에는 서버가 중지됩니다. 시스템 대체 시스템 복원됨 복원 실패 + 선택한 파일을 읽을 수 없어 아무것도 변경되지 않았습니다. 백업 및 복원 백업 또는 복원을 백그라운드에서 안전하게 계속 실행합니다 백업 및 복원 diff --git a/controller/app/src/main/res/values-lt/strings.xml b/controller/app/src/main/res/values-lt/strings.xml index f5b4ec50f..49181473a 100644 --- a/controller/app/src/main/res/values-lt/strings.xml +++ b/controller/app/src/main/res/values-lt/strings.xml @@ -639,12 +639,14 @@ Atsarginė kopija nepavyko. Bandykite dar kartą. Atlikta Kažkas nepavyko + Kopijuojamas failas Tikrinamas failas Atkuriama Tai pakeičia dabartinę sistemą pasirinkta atsargine kopija. To atšaukti negalima, o serveris sustoja, kol tai vyksta. Pakeisti sistemą Sistema atkurta Nepavyko atkurti + Nepavyko perskaityti pasirinkto failo, todėl niekas nebuvo pakeista. Atsarginė kopija ir atkūrimas Saugiai vykdo atsarginės kopijos kūrimą ar atkūrimą fone Atsarginė kopija ir atkūrimas diff --git a/controller/app/src/main/res/values-nl/strings.xml b/controller/app/src/main/res/values-nl/strings.xml index 9fc5300bf..7d567ce64 100644 --- a/controller/app/src/main/res/values-nl/strings.xml +++ b/controller/app/src/main/res/values-nl/strings.xml @@ -631,12 +631,14 @@ Back-up mislukt. Probeer het opnieuw. Klaar Er ging iets mis + Bestand kopiëren Bestand controleren Herstellen Hiermee wordt je huidige systeem vervangen door de gekozen back-up. Dit kan niet ongedaan worden gemaakt en de server stopt terwijl het loopt. Systeem vervangen Systeem hersteld Herstel mislukt + Het geselecteerde bestand kon niet worden gelezen, dus er is niets gewijzigd. Back-up & herstel Houdt een back-up of herstel veilig actief op de achtergrond Back-up & herstel diff --git a/controller/app/src/main/res/values-no/strings.xml b/controller/app/src/main/res/values-no/strings.xml index 890b7bb47..98ad8d6d6 100644 --- a/controller/app/src/main/res/values-no/strings.xml +++ b/controller/app/src/main/res/values-no/strings.xml @@ -632,12 +632,14 @@ Sikkerhetskopieringen mislyktes. Prøv igjen. Ferdig Noe gikk galt + Kopierer filen Sjekker filen Gjenoppretter Dette erstatter det gjeldende systemet med den valgte sikkerhetskopien. Det kan ikke angres, og serveren stopper mens det kjører. Erstatt system System gjenopprettet Gjenoppretting mislyktes + Den valgte filen kunne ikke leses, så ingenting ble endret. Sikkerhetskopiering & gjenoppretting Holder en sikkerhetskopiering eller gjenoppretting trygt i gang i bakgrunnen Sikkerhetskopiering & gjenoppretting diff --git a/controller/app/src/main/res/values-pl/strings.xml b/controller/app/src/main/res/values-pl/strings.xml index 68fe1e48b..520ac3fb8 100644 --- a/controller/app/src/main/res/values-pl/strings.xml +++ b/controller/app/src/main/res/values-pl/strings.xml @@ -632,12 +632,14 @@ Kopia zapasowa nie powiodła się. Spróbuj ponownie. Gotowe Coś poszło nie tak + Kopiowanie pliku Sprawdzanie pliku Przywracanie To zastępuje bieżący system wybraną kopią zapasową. Nie można tego cofnąć, a serwer zatrzymuje się na czas operacji. Zastąp system System przywrócony Przywracanie nie powiodło się + Nie udało się odczytać wybranego pliku, więc nic nie zostało zmienione. Kopia zapasowa & przywracanie Utrzymuje bezpieczne działanie kopii lub przywracania w tle Kopia zapasowa & przywracanie diff --git a/controller/app/src/main/res/values-pt/strings.xml b/controller/app/src/main/res/values-pt/strings.xml index e9fc3b8c5..9c096defb 100644 --- a/controller/app/src/main/res/values-pt/strings.xml +++ b/controller/app/src/main/res/values-pt/strings.xml @@ -710,12 +710,14 @@ A cópia de segurança falhou. Tenta novamente. Concluído Algo correu mal + A copiar o ficheiro A verificar o ficheiro A restaurar Isto substitui o seu sistema atual pela cópia escolhida. Não pode ser anulado e o servidor para enquanto decorre. Substituir sistema Sistema restaurado O restauro falhou + Não foi possível ler o ficheiro selecionado, por isso nada foi alterado. Cópia de segurança & restauro Mantém uma cópia de segurança ou restauro a decorrer com segurança em segundo plano Cópia de segurança & restauro diff --git a/controller/app/src/main/res/values-ro/strings.xml b/controller/app/src/main/res/values-ro/strings.xml index 7e4ff45a2..fb65528ae 100644 --- a/controller/app/src/main/res/values-ro/strings.xml +++ b/controller/app/src/main/res/values-ro/strings.xml @@ -631,12 +631,14 @@ Copia de rezervă a eșuat. Încearcă din nou. Gata Ceva nu a mers bine + Se copiază fișierul Se verifică fișierul Se restaurează Aceasta înlocuiește sistemul curent cu copia aleasă. Nu poate fi anulată, iar serverul se oprește cât timp rulează. Înlocuiește sistemul Sistem restaurat Restaurarea a eșuat + Fișierul selectat nu a putut fi citit, așa că nu s-a schimbat nimic. Copie de rezervă & restaurare Menține o copie de rezervă sau o restaurare rulând în siguranță în fundal Copie de rezervă & restaurare diff --git a/controller/app/src/main/res/values-ru-rRU/strings.xml b/controller/app/src/main/res/values-ru-rRU/strings.xml index 0da53b39e..48b5b77f6 100644 --- a/controller/app/src/main/res/values-ru-rRU/strings.xml +++ b/controller/app/src/main/res/values-ru-rRU/strings.xml @@ -707,12 +707,14 @@ Резервное копирование не удалось. Повторите попытку. Готово Что-то пошло не так + Копирование файла Проверка файла Восстановление Это заменяет текущую систему выбранной резервной копией. Отменить нельзя, и на время операции сервер останавливается. Заменить систему Система восстановлена Не удалось восстановить + Не удалось прочитать выбранный файл, поэтому ничего не изменилось. Резервное копирование и восстановление Позволяет безопасно выполнять резервное копирование или восстановление в фоне Резервное копирование и восстановление diff --git a/controller/app/src/main/res/values-sk/strings.xml b/controller/app/src/main/res/values-sk/strings.xml index db482b0d8..436692126 100644 --- a/controller/app/src/main/res/values-sk/strings.xml +++ b/controller/app/src/main/res/values-sk/strings.xml @@ -638,12 +638,14 @@ Zálohovanie zlyhalo. Skús to znova. Hotovo Niečo sa pokazilo + Kopírovanie súboru Kontroluje sa súbor Obnovuje sa Toto nahradí váš aktuálny systém vybranou zálohou. Nedá sa to vrátiť späť a počas behu sa server zastaví. Nahradiť systém Systém obnovený Obnova zlyhala + Vybraný súbor sa nepodarilo prečítať, takže sa nič nezmenilo. Zálohovanie & obnova Udržiava zálohovanie alebo obnovu bezpečne bežiace na pozadí Zálohovanie & obnova diff --git a/controller/app/src/main/res/values-sr/strings.xml b/controller/app/src/main/res/values-sr/strings.xml index b1ccea642..f5ca66b36 100644 --- a/controller/app/src/main/res/values-sr/strings.xml +++ b/controller/app/src/main/res/values-sr/strings.xml @@ -644,12 +644,14 @@ Прављење резервне копије није успело. Покушајте поново. Готово Нешто је пошло по злу + Копирање датотеке Провера датотеке Враћање Ово замењује тренутни систем изабраном резервном копијом. Не може се опозвати, а сервер се зауставља током поступка. Замени систем Систем враћен Враћање није успело + Изабрана датотека није могла да се прочита, па ништа није промењено. Резервна копија и враћање Одржава прављење резервне копије или враћање безбедно у позадини Резервна копија и враћање diff --git a/controller/app/src/main/res/values-sw/strings.xml b/controller/app/src/main/res/values-sw/strings.xml index b3d163d8e..a1afb6349 100644 --- a/controller/app/src/main/res/values-sw/strings.xml +++ b/controller/app/src/main/res/values-sw/strings.xml @@ -651,12 +651,14 @@ Uhifadhi nakala umeshindwa. Tafadhali jaribu tena. Imekamilika Kuna hitilafu + Inanakili faili Inakagua faili Inarejesha Hii hubadilisha mfumo wako wa sasa na nakala rudufu iliyochaguliwa. Haiwezi kutenduliwa, na seva husimama wakati inaendelea. Badilisha mfumo Mfumo umerejeshwa Urejeshaji umeshindwa + Faili uliyochagua haikuweza kusomwa, kwa hivyo hakuna kilichobadilishwa. Hifadhi & rejesha Huweka nakala rudufu au urejeshaji ukiendelea kwa usalama chinichini Hifadhi & rejesha diff --git a/controller/app/src/main/res/values-ta/strings.xml b/controller/app/src/main/res/values-ta/strings.xml index 7c98e22c8..a73022fe1 100644 --- a/controller/app/src/main/res/values-ta/strings.xml +++ b/controller/app/src/main/res/values-ta/strings.xml @@ -651,12 +651,14 @@ காப்புப்பிரதி தோல்வியடைந்தது. மீண்டும் முயற்சிக்கவும். முடிந்தது ஏதோ தவறு நடந்தது + கோப்பு நகலெடுக்கப்படுகிறது கோப்பு சரிபார்க்கப்படுகிறது மீட்டமைக்கப்படுகிறது இது உங்கள் தற்போதைய அமைப்பைத் தேர்ந்தெடுத்த காப்புப்பிரதியால் மாற்றுகிறது. இதை மாற்ற முடியாது, இயங்கும்போது சர்வர் நிற்கும். அமைப்பை மாற்று அமைப்பு மீட்டமைக்கப்பட்டது மீட்பு தோல்வியடைந்தது + தேர்ந்தெடுத்த கோப்பைப் படிக்க முடியவில்லை, எனவே எதுவும் மாற்றப்படவில்லை. காப்புப்பிரதி & மீட்பு காப்புப்பிரதி அல்லது மீட்பை பின்னணியில் பாதுகாப்பாக இயக்கி வைக்கிறது காப்புப்பிரதி & மீட்பு diff --git a/controller/app/src/main/res/values-tr/strings.xml b/controller/app/src/main/res/values-tr/strings.xml index 4a47ea247..49e0a07ea 100644 --- a/controller/app/src/main/res/values-tr/strings.xml +++ b/controller/app/src/main/res/values-tr/strings.xml @@ -631,12 +631,14 @@ Yedekleme başarısız oldu. Lütfen tekrar dene. Bitti Bir şeyler ters gitti + Dosya kopyalanıyor Dosya denetleniyor Geri yükleniyor Bu, mevcut sisteminizi seçilen yedekle değiştirir. Geri alınamaz ve işlem sürerken sunucu durur. Sistemi değiştir Sistem geri yüklendi Geri yükleme başarısız + Seçilen dosya okunamadı, bu yüzden hiçbir şey değiştirilmedi. Yedekle & geri yükle Bir yedekleme veya geri yüklemeyi arka planda güvenle çalışır durumda tutar Yedekle & geri yükle diff --git a/controller/app/src/main/res/values-uk/strings.xml b/controller/app/src/main/res/values-uk/strings.xml index 1c41e2b57..87523cba3 100644 --- a/controller/app/src/main/res/values-uk/strings.xml +++ b/controller/app/src/main/res/values-uk/strings.xml @@ -631,12 +631,14 @@ Не вдалося створити резервну копію. Повторіть спробу. Готово Щось пішло не так + Копіювання файлу Перевірка файлу Відновлення Це замінює поточну систему обраною резервною копією. Це не можна скасувати, і сервер зупиняється на час виконання. Замінити систему Систему відновлено Помилка відновлення + Не вдалося прочитати вибраний файл, тому нічого не змінено. Резервне копіювання та відновлення Безпечно виконує резервне копіювання чи відновлення у фоні Резервне копіювання та відновлення diff --git a/controller/app/src/main/res/values-vi/strings.xml b/controller/app/src/main/res/values-vi/strings.xml index e0aab1f2f..f8309551e 100644 --- a/controller/app/src/main/res/values-vi/strings.xml +++ b/controller/app/src/main/res/values-vi/strings.xml @@ -631,12 +631,14 @@ Sao lưu thất bại. Vui lòng thử lại. Xong Đã xảy ra sự cố + Đang sao chép tệp Đang kiểm tra tệp Đang khôi phục Thao tác này thay thế hệ thống hiện tại của bạn bằng bản sao lưu đã chọn. Không thể hoàn tác, và máy chủ dừng trong khi thực hiện. Thay thế hệ thống Đã khôi phục hệ thống Khôi phục thất bại + Không thể đọc tệp đã chọn, nên không có gì bị thay đổi. Sao lưu & khôi phục Giữ quá trình sao lưu hoặc khôi phục chạy an toàn ở chế độ nền Sao lưu & khôi phục diff --git a/controller/app/src/main/res/values-yo/strings.xml b/controller/app/src/main/res/values-yo/strings.xml index 8514d3f1b..49ca6957b 100644 --- a/controller/app/src/main/res/values-yo/strings.xml +++ b/controller/app/src/main/res/values-yo/strings.xml @@ -651,12 +651,14 @@ Ìfìdí-ọ̀rọ̀ kùnà. Jọ̀wọ́ gbìyànjú lẹ́ẹ̀kansi. Ó ti parí Nkan kan ṣàṣìṣe + Ń da fáìlì náà kọ Ń ṣàyẹ̀wò fáìlì Ń mú padà Èyí fi àfẹ̀yìntì tí a yàn rọ́pò ẹ̀rọ ìsinsìnyí rẹ. A kò lè yí i padà, sáà sì ń dúró nígbà tí ó bá ń ṣiṣẹ́. Rọ́pò ẹ̀rọ A ti mú ẹ̀rọ padà Ìmúpadà kùnà + A kò lè ka fáìlì tí a yàn, nítorí náà kò sí ohun tí ó yípadà. Àfẹ̀yìntì & ìmúpadà Ń jẹ́ kí àfẹ̀yìntì tàbí ìmúpadà máa ṣiṣẹ́ láìséwu lẹ́yìn ẹ̀rọ Àfẹ̀yìntì & ìmúpadà diff --git a/controller/app/src/main/res/values-zh-rCN/strings.xml b/controller/app/src/main/res/values-zh-rCN/strings.xml index 7758d8023..0cb5387ad 100644 --- a/controller/app/src/main/res/values-zh-rCN/strings.xml +++ b/controller/app/src/main/res/values-zh-rCN/strings.xml @@ -632,12 +632,14 @@ 备份失败。请重试。 完成 出错了 + 正在复制文件 正在检查文件 正在恢复 这会用所选备份替换您当前的系统。此操作无法撤销,运行期间服务器会停止。 替换系统 系统已恢复 恢复失败 + 无法读取所选文件,因此未做任何更改。 备份与恢复 使备份或恢复在后台安全运行 备份与恢复 diff --git a/controller/app/src/main/res/values/strings.xml b/controller/app/src/main/res/values/strings.xml index d2f373147..a144ec895 100644 --- a/controller/app/src/main/res/values/strings.xml +++ b/controller/app/src/main/res/values/strings.xml @@ -775,12 +775,14 @@ Backup failed. Please try again. Done Something went wrong + Copying the file Checking the file Restoring This replaces your current system with the chosen backup. It can\'t be undone, and the server stops while it runs. Replace system System restored Restore failed + The selected file could not be read, so nothing was changed. Backup & restore Keeps a backup or restore running safely in the background Backup & restore diff --git a/controller/app/src/test/java/org/iiab/controller/deploy/domain/ExtractProgressTest.java b/controller/app/src/test/java/org/iiab/controller/deploy/domain/ExtractProgressTest.java index bc47033c0..fc533cf57 100644 --- a/controller/app/src/test/java/org/iiab/controller/deploy/domain/ExtractProgressTest.java +++ b/controller/app/src/test/java/org/iiab/controller/deploy/domain/ExtractProgressTest.java @@ -119,4 +119,37 @@ public void anythingUnrecognisedIsStillShown() { assertTrue("handoff stays monotone", ExtractProgress.unifiedPercent(0, true) >= ExtractProgress.unifiedPercent(99, false)); } + + // ---- K2GO-372: a restore is one run of three passes (copy, verify, extract) ---- + + @Test public void threePassesShareOneBarInOrder() { + assertEquals(0, ExtractProgress.unifiedPercent(0, 0, 3)); // copy starts the run + assertEquals(16, ExtractProgress.unifiedPercent(50, 0, 3)); // copy half + assertEquals(33, ExtractProgress.unifiedPercent(0, 1, 3)); // verify picks up where copy ended + assertEquals(66, ExtractProgress.unifiedPercent(0, 2, 3)); // extract picks up after verify + assertEquals(83, ExtractProgress.unifiedPercent(50, 2, 3)); // extract half + assertEquals(99, ExtractProgress.unifiedPercent(100, 2, 3)); // capped until completion + } + + @Test public void noPassCanFillTheBarAndSendItBack() { + // The reason the mapping exists: the end of one pass must never exceed the start of the next. + for (int pass = 0; pass < 2; pass++) { + assertTrue("pass " + pass + " must hand over without regressing", + ExtractProgress.unifiedPercent(100, pass, 3) + <= ExtractProgress.unifiedPercent(0, pass + 1, 3)); + } + } + + @Test public void twoPassOverloadIsTheSameRuleWithTwoPasses() { + for (int p = 0; p <= 100; p += 5) { + assertEquals(ExtractProgress.unifiedPercent(p, 0, 2), ExtractProgress.unifiedPercent(p, false)); + assertEquals(ExtractProgress.unifiedPercent(p, 1, 2), ExtractProgress.unifiedPercent(p, true)); + } + } + + @Test public void outOfRangePassesAreClampedNotWrapped() { + assertEquals(ExtractProgress.unifiedPercent(0, 2, 3), ExtractProgress.unifiedPercent(0, 9, 3)); + assertEquals(ExtractProgress.unifiedPercent(0, 0, 3), ExtractProgress.unifiedPercent(0, -1, 3)); + assertEquals(50, ExtractProgress.unifiedPercent(50, 0, 0)); // a run of no passes is one pass + } } diff --git a/controller/app/src/test/java/org/iiab/controller/deploy/domain/RootfsIdentityTest.java b/controller/app/src/test/java/org/iiab/controller/deploy/domain/RootfsIdentityTest.java new file mode 100644 index 000000000..ebbcfb13b --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/deploy/domain/RootfsIdentityTest.java @@ -0,0 +1,79 @@ +package org.iiab.controller.deploy.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * Unit tests for {@link RootfsIdentity} — K2GO-372. + * + *

This rule now runs before the archive is listed, so it is the first thing that can + * refuse a restore. The cases that matter most are the ones where it must stay silent: a rejection + * here costs the user their restore, and an over-eager rule would refuse archives that the + * structural fallback would have accepted. + */ +public class RootfsIdentityTest { + + private static final String ARM64 = "arm64-v8a"; + private static final String ARM32 = "armeabi-v7a"; + private static final String ROOTFS = "iiab-rootfs"; + + @Test + public void aMatchingRootfsIsNotRejected() { + assertEquals(RootfsIdentity.Verdict.OK, + RootfsIdentity.check(true, ROOTFS, ARM64, ARM64)); + } + + @Test + public void theWrongAbiIsRejected() { + // The ABI policy is strict both ways: 64-bit content never runs on a 32-bit app, and a + // 32-bit rootfs on a 64-bit app is the mismatch the import guard exists for. + assertEquals(RootfsIdentity.Verdict.WRONG_ARCH, + RootfsIdentity.check(true, ROOTFS, ARM32, ARM64)); + assertEquals(RootfsIdentity.Verdict.WRONG_ARCH, + RootfsIdentity.check(true, ROOTFS, ARM64, ARM32)); + } + + @Test + public void somethingThatIsNotARootfsIsRejected() { + assertEquals(RootfsIdentity.Verdict.NOT_A_ROOTFS, + RootfsIdentity.check(true, "backup-of-something-else", ARM64, ARM64)); + assertEquals(RootfsIdentity.Verdict.NOT_A_ROOTFS, + RootfsIdentity.check(true, null, ARM64, ARM64)); + } + + @Test + public void noManifestIsNotARejection() { + // Archives predate the manifest. Turning a missing hint into a hard failure here would + // refuse files the structural fallback still accepts — the whole point of the soft path. + assertEquals(RootfsIdentity.Verdict.OK, + RootfsIdentity.check(false, null, null, ARM64)); + assertEquals(RootfsIdentity.Verdict.OK, + RootfsIdentity.check(false, "anything", ARM32, ARM64)); + } + + @Test + public void aManifestThatClaimsNoArchIsNotARejection() { + // The manifest declares kind but leaves arch out: there is nothing to contradict, so the + // ABI question falls through to the probe rather than being answered by silence. + assertEquals(RootfsIdentity.Verdict.OK, + RootfsIdentity.check(true, ROOTFS, null, ARM64)); + assertEquals(RootfsIdentity.Verdict.OK, + RootfsIdentity.check(true, ROOTFS, "", ARM64)); + } + + @Test + public void anUnknownAppAbiNeverRejects() { + // If we cannot say what we are, we are in no position to refuse what the archive says. + assertEquals(RootfsIdentity.Verdict.OK, + RootfsIdentity.check(true, ROOTFS, ARM32, null)); + } + + @Test + public void kindIsCheckedBeforeArch() { + // A non-rootfs of the wrong ABI is reported as what it is, not as an ABI mismatch -- + // otherwise the message sends the user hunting for the wrong build. + assertEquals(RootfsIdentity.Verdict.NOT_A_ROOTFS, + RootfsIdentity.check(true, "not-a-rootfs", ARM32, ARM64)); + } +} diff --git a/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java b/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java index db629c29b..b601d6e53 100644 --- a/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java +++ b/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java @@ -11,6 +11,7 @@ package org.iiab.controller.storage; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -37,4 +38,26 @@ public void zeroAndNegativeAreZero() { public void saturatesInsteadOfOverflowing() { assertEquals(Long.MAX_VALUE, SpaceEstimate.fromCompressed(Long.MAX_VALUE)); } + + // ---- K2GO-372: the copy and the tree it expands into share the disk ---- + + @Test public void peakCoversTheCopyAndTheExpansion() { + // 1 GB archive: 1 GB staged + 2.2 GB expanded must both fit at once. + assertEquals(1_000_000_000L + SpaceEstimate.fromCompressed(1_000_000_000L), + SpaceEstimate.peakForRestore(1_000_000_000L)); + } + + @Test public void peakIsAlwaysMoreThanTheExpansionAlone() { + // The bug it closes: asking only about the expansion left the copy unaccounted for. + for (long c : new long[]{1L, 1024L, 1_000_000L, 2_400_000_000L}) { + assertTrue("peak must exceed the expansion for " + c, + SpaceEstimate.peakForRestore(c) > SpaceEstimate.fromCompressed(c)); + } + } + + @Test public void peakIsZeroForNothingAndSaturatesInsteadOfWrapping() { + assertEquals(0L, SpaceEstimate.peakForRestore(0L)); + assertEquals(0L, SpaceEstimate.peakForRestore(-5L)); + assertEquals(Long.MAX_VALUE, SpaceEstimate.peakForRestore(Long.MAX_VALUE)); + } }