Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
feat(linux): port transactional installer upgrade mode and in-app updater to Filee 2.0.0
Alenbosh75ddcc2fd4b4
diff --git a/installer/linux/INSTALL.txt b/installer/linux/INSTALL.txtindex 2852fddb..e2b5d4c5 100644--- a/installer/linux/INSTALL.txt+++ b/installer/linux/INSTALL.txt@@ -2,10 +2,28 @@ Run ./Filee to test the extracted app, or ./filee-cli help for the command line.Run ./install.sh to install for the current user. It requires Python 3, createsan application launcher and ~/.local/bin/filee, and does not require root.+Run ./install.sh --upgrade to safely upgrade an existing installation in place+without uninstalling. Your settings, presets, history, and downloaded conversion+engines are kept. Running without --upgrade refuses to overwrite an existing installation.Run ./uninstall.sh to remove this installation and Filee-downloaded engines.Your settings and converted files are kept. If integration cleanup fails, theinstallation is kept so you can fix the error and run the uninstaller again.-An existing installation is never overwritten; uninstall it before replacing it.++Upgrade reliability and crash recovery:+The upgrade procedure prepares files on the same filesystem and replaces the+installation using atomic rename steps with an automatic rollback trap. If an error+or signal interruption occurs during the swap, the previous version is restored.+Note: While each individual directory rename is atomic in POSIX, the two-step swap+(moving the old installation aside, then moving the new version into place) is not+a single atomic transaction. In the event of uncatchable termination (SIGKILL) or+sudden hardware power loss during the brief window between steps, automatic traps+cannot execute; the previous installation is safely preserved in .backup-<pid>.+To recover manually:+- If the application directory does not exist:+ mv ~/.local/share/filee/.backup-<pid> ~/.local/share/filee/application+- If a partial or invalid application directory already exists:+ Inspect and remove or rename ~/.local/share/filee/application first, then run:+ mv ~/.local/share/filee/.backup-<pid> ~/.local/share/filee/applicationFilee runs on Ubuntu 22.04 or newer and other distributions with glibc 2.35 ornewer. The .NET runtime is bundled; its native system libraries are stilldiff --git a/installer/linux/install.sh b/installer/linux/install.shold mode 100644new mode 100755index 2a3cec01..f23bca4c--- a/installer/linux/install.sh+++ b/installer/linux/install.sh@@ -1,30 +1,298 @@#!/bin/shset -eu-source_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)+# Filee Linux standalone installer.+# Supports first-time installation and in-place upgrade (--upgrade).+# Preserves downloaded conversion engines (~/.local/share/Filee/engines) and user settings (~/.config/Filee).++upgrade=0+restart=0++for arg do+ case "$arg" in+ --upgrade|-u)+ upgrade=1+ ;;+ --restart)+ restart=1+ ;;+ --help|-h)+ printf '%s\n' "Usage: $0 [--upgrade|-u] [--restart]"+ exit 0+ ;;+ *)+ printf '%s\n' "Unknown option: $arg" >&2+ printf '%s\n' "Usage: $0 [--upgrade|-u] [--restart]" >&2+ exit 1+ ;;+ esac+done++source_dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)data_dir=${XDG_DATA_HOME:-"$HOME/.local/share"}install_dir="$data_dir/filee/application"bin_dir="$HOME/.local/bin"desktop_file="$data_dir/applications/com.filee.app.desktop"-if [ -e "$install_dir" ] || [ -L "$install_dir" ]; then- printf '%s\n' "An installation already exists at $install_dir. Run its uninstall.sh first."++# Validate required tools and incoming payload files before doing anything.+command -v python3 >/dev/null 2>&1 || {+ printf '%s\n' "Python 3 is required to install Filee." >&2exit 1+}++# Only enable internal test failure hooks if explicitly requested by the test harness+# AND executing within an isolated temporary test directory.+test_hooks_enabled=0+if [ "${_FILEE_TEST_HARNESS:-}" = "com.filee.test.harness" ]; then+ case "$data_dir" in+ /tmp/*|/var/tmp/*|*/filee-installer-test-*)+ test_hooks_enabled=1+ ;;+ esacfi-if [ -e "$bin_dir/filee" ] || [ -L "$bin_dir/filee" ]; then- printf '%s\n' "$bin_dir/filee already exists. Remove or rename it before installing Filee."++if [ ! -f "$source_dir/Filee" ] || [ ! -x "$source_dir/Filee" ]; then+ printf '%s\n' "Payload validation failed: $source_dir/Filee is missing or not executable." >&2exit 1fi-if [ -e "$desktop_file" ] || [ -L "$desktop_file" ]; then- printf '%s\n' "$desktop_file already exists. Remove or rename it before installing Filee."++if [ ! -f "$source_dir/filee-cli" ] || [ ! -x "$source_dir/filee-cli" ]; then+ printf '%s\n' "Payload validation failed: $source_dir/filee-cli is missing or not executable." >&2exit 1fi-command -v python3 >/dev/null-test -x "$source_dir/Filee"-test -x "$source_dir/filee-cli"-mkdir -p "$data_dir/filee" "$bin_dir" "$data_dir/applications"-cp -R "$source_dir" "$install_dir"-printf '%s\n' 'com.filee.app' > "$install_dir/.filee-package"-ln -s "$install_dir/filee-cli" "$bin_dir/filee"++if [ "$upgrade" -eq 0 ]; then+ # First-time installation: refuse to overwrite an existing installation or files.+ if [ -e "$install_dir" ] || [ -L "$install_dir" ]; then+ printf '%s\n' "An installation already exists at $install_dir. Run its uninstall.sh first."+ exit 1+ fi+ if [ -e "$bin_dir/filee" ] || [ -L "$bin_dir/filee" ]; then+ printf '%s\n' "$bin_dir/filee already exists. Remove or rename it before installing Filee."+ exit 1+ fi+ if [ -e "$desktop_file" ] || [ -L "$desktop_file" ]; then+ printf '%s\n' "$desktop_file already exists. Remove or rename it before installing Filee."+ exit 1+ fi++ mkdir -p "$data_dir/filee" "$bin_dir" "$data_dir/applications"+ cp -R "$source_dir" "$install_dir"+ printf '%s\n' 'com.filee.app' > "$install_dir/.filee-package"+ rm -f "$install_dir/.filee-upgrade-token"+ ln -s "$install_dir/filee-cli" "$bin_dir/filee"+else+ # Upgrade existing installation: verify it is genuine and safely swap in place.+ if [ ! -d "$install_dir" ] || [ -L "$install_dir" ]; then+ printf '%s\n' "No existing installation found at $install_dir to upgrade." >&2+ exit 1+ fi++ marker_file="$install_dir/.filee-package"+ if [ ! -f "$marker_file" ]; then+ printf '%s\n' "Cannot upgrade: $install_dir is missing the .filee-package marker." >&2+ exit 1+ fi++ marker=$(tr -d '\r\n' < "$marker_file" 2>/dev/null || true)+ if [ "$marker" != "com.filee.app" ]; then+ printf '%s\n' "Cannot upgrade: $install_dir was not installed by Filee." >&2+ exit 1+ fi++ # Tell running instance to save and exit cleanly before touching files (skipped during in-app updates).+ if [ "${FILEE_IN_APP_UPDATE:-0}" != "1" ]; then+ if [ -x "$install_dir/Filee" ]; then+ if ! "$install_dir/Filee" --quit; then+ printf '%s\n' "Could not gracefully shut down the running Filee instance. Please exit Filee and try again." >&2+ exit 1+ fi+ fi+ fi++ # Generate a unique transaction ID for this upgrade session using PID and random bytes.+ # This prevents collisions with any concurrent installer or pre-existing backup artifacts.+ token_rand=$(od -vN 8 -An -tx1 /dev/urandom 2>/dev/null | tr -d ' \n' || true)+ tx_id="$$-${token_rand:-$(date +%s)}"+ staging_dir="$data_dir/filee/.staging-$tx_id"+ backup_dir="$data_dir/filee/.backup-$tx_id"+ failed_dir="$data_dir/filee/.failed-$tx_id"+ upgrade_token="filee-upgrade-$tx_id"+ activated=0++ # Ensure transaction paths are completely distinct and do not collide with pre-existing files.+ if [ -e "$staging_dir" ] || [ -e "$backup_dir" ] || [ -e "$failed_dir" ]; then+ printf '%s\n' "Transaction path conflict detected at $data_dir/filee. Please retry." >&2+ exit 1+ fi++ mkdir -p "$data_dir/filee" "$bin_dir" "$data_dir/applications"+ mkdir "$staging_dir"++ # Copy incoming payload into staging (preserves source_dir without moving/deleting it).+ cp -R "$source_dir/." "$staging_dir/"+ printf '%s\n' 'com.filee.app' > "$staging_dir/.filee-package"+ printf '%s\n' "$upgrade_token" > "$staging_dir/.filee-upgrade-token"+ chmod +x "$staging_dir/Filee" "$staging_dir/filee-cli"++ # Validate the staged files before moving the existing installation aside.+ if [ ! -x "$staging_dir/Filee" ] || [ ! -x "$staging_dir/filee-cli" ]; then+ rm -rf "$staging_dir"+ printf '%s\n' "Staged payload validation failed." >&2+ exit 1+ fi++ # Rollback trap: handles catchable signals and script aborts.+ # Ensures $backup_dir is restored if anything fails during replacement.+ rollback_and_cleanup() {+ exit_code=$?+ if [ -d "$backup_dir" ]; then+ # If new files were activated into $install_dir, verify that $install_dir+ # actually contains this run's upgrade token before moving it aside.+ # This prevents another process or symlink swap from causing cleanup+ # to remove anything other than this process's failed payload.+ if [ "$activated" -eq 1 ] && [ -d "$install_dir" ] && [ ! -L "$install_dir" ]; then+ token_file="$install_dir/.filee-upgrade-token"+ if [ -f "$token_file" ] && [ ! -L "$token_file" ]; then+ token=$(tr -d '\r\n' < "$token_file" 2>/dev/null || true)+ if [ "$token" = "$upgrade_token" ]; then+ # Token verified: safely move the failed payload aside to quarantine.+ # Ensure $failed_dir does not already exist so mv performs a clean rename,+ # and never fall back to recursive deletion if quarantine move fails.+ if [ ! -e "$failed_dir" ] && mv "$install_dir" "$failed_dir" 2>/dev/null; then+ # Re-verify token inside quarantined directory before deletion (TOCTOU mitigation).+ # If ownership, symlink checks, or token match fail, keep $failed_dir intact.+ q_token_file="$failed_dir/.filee-upgrade-token"+ if [ -d "$failed_dir" ] && [ ! -L "$failed_dir" ] && [ -f "$q_token_file" ] && [ ! -L "$q_token_file" ]; then+ q_token=$(tr -d '\r\n' < "$q_token_file" 2>/dev/null || true)+ if [ "$q_token" = "$upgrade_token" ]; then+ rm -rf "$failed_dir" 2>/dev/null || true+ fi+ fi+ fi+ fi+ fi+ fi++ if [ ! -d "$install_dir" ] && mv "$backup_dir" "$install_dir" 2>/dev/null; then+ printf '%s\n' "Update failed. Restored the previous Filee installation." >&2+ if [ -d "$failed_dir" ]; then+ printf '%s\n' "Quarantined failed update files preserved at: $failed_dir" >&2+ fi+ else+ printf '%s\n' "CRITICAL: Update failed and automatic rollback could not complete." >&2+ printf '%s\n' "Your previous installation is preserved at: $backup_dir" >&2+ if [ -d "$install_dir" ]; then+ printf '%s\n' "A partial or invalid directory exists at: $install_dir" >&2+ printf '%s\n' "To restore manually, inspect and remove or rename '$install_dir', then run:" >&2+ printf '%s\n' " mv '$backup_dir' '$install_dir'" >&2+ else+ printf '%s\n' "To restore manually, run: mv '$backup_dir' '$install_dir'" >&2+ fi+ if [ -d "$failed_dir" ]; then+ printf '%s\n' "Quarantined failed update files preserved at: $failed_dir" >&2+ fi+ fi+ fi+ rm -rf "$staging_dir" 2>/dev/null || true+ exit "$exit_code"+ }+ trap rollback_and_cleanup EXIT INT TERM HUP++ # Note on atomicity and crash recovery:+ # Individual filesystem renames (rename syscall) are atomic in POSIX.+ # However, replacing a non-empty directory on Linux requires two renames:+ # 1. mv "$install_dir" "$backup_dir"+ # 2. mv "$staging_dir" "$install_dir"+ # The two-step sequence as a whole is not a single atomic transaction.+ # There is a brief window between step 1 and step 2 where $install_dir does+ # not exist. Catchable signals (SIGINT, SIGTERM, SIGHUP) and script errors+ # are handled by the rollback trap above, which immediately restores $backup_dir.+ # If uncatchable termination (SIGKILL) or sudden hardware power loss occurs+ # during this brief window, automatic traps cannot run; the previous installation+ # remains safe in $backup_dir and can be restored manually.++ # Move active installation to backup.+ mv "$install_dir" "$backup_dir"++ # Test hook: simulate failure after backup but before activation.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_ACTIVATION:-0}" = "1" ]; then+ rm -rf "$staging_dir"+ fi++ # Test hook: simulate activation destination conflict.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_ACTIVATION_OCCUPIED:-0}" = "1" ]; then+ mkdir -p "$install_dir"+ touch "$install_dir/conflict"+ chmod 555 "$install_dir"+ fi++ # Activate new installation from staging.+ if ! mv "$staging_dir" "$install_dir"; then+ exit 1+ fi+ activated=1++ # Test hook: simulate failure during post-swap validation.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_POST_VALIDATION:-0}" = "1" ]; then+ rm -f "$install_dir/.filee-package"+ fi++ # Test hook: simulate failure during post-swap validation where failed_dir cleanup will fail.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_CLEANUP_FAILED_DIR:-0}" = "1" ]; then+ mkdir -p "$install_dir/locked-folder"+ touch "$install_dir/locked-folder/file"+ chmod 555 "$install_dir/locked-folder"+ rm -f "$install_dir/.filee-package"+ fi++ # Test hook: simulate quarantine move failure during rollback.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_QUARANTINE:-0}" = "1" ]; then+ mkdir -p "$failed_dir"+ touch "$failed_dir/conflict"+ exit 1+ fi++ # Test hook: simulate replacement of install_dir by a foreign directory before rollback.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_FOREIGN_DESTINATION:-0}" = "1" ]; then+ rm -rf "$install_dir"+ mkdir -p "$install_dir"+ echo "important-foreign-data" > "$install_dir/important.txt"+ exit 1+ fi++ # Test hook: simulate failure during rollback with occupied destination.+ if [ "$test_hooks_enabled" -eq 1 ] && { [ "${_FILEE_TEST_FAIL_ROLLBACK_OCCUPIED:-0}" = "1" ] || [ "${_FILEE_TEST_FAIL_ROLLBACK:-0}" = "1" ]; }; then+ rm -rf "$install_dir"+ mkdir -p "$install_dir"+ touch "$install_dir/conflict"+ chmod 555 "$install_dir"+ exit 1+ fi++ # Test hook: simulate failure during rollback with absent destination.+ if [ "$test_hooks_enabled" -eq 1 ] && [ "${_FILEE_TEST_FAIL_ROLLBACK_ABSENT:-0}" = "1" ]; then+ rm -rf "$install_dir"+ chmod 555 "$data_dir/filee"+ exit 1+ fi++ # Post-swap validation: ensure new installation is active and healthy.+ if [ ! -x "$install_dir/Filee" ] || [ ! -x "$install_dir/filee-cli" ] || [ ! -f "$install_dir/.filee-package" ]; then+ printf '%s\n' "Activated installation failed post-swap validation. Rolling back..." >&2+ exit 1+ fi++ # Success: disarm the rollback trap before removing the old version backup.+ trap - EXIT INT TERM HUP+ rm -rf "$backup_dir"+ rm -f "$install_dir/.filee-upgrade-token"++ # Refresh launcher symlink (using -f to overwrite existing link atomically).+ ln -sf "$install_dir/filee-cli" "$bin_dir/filee"+fi++# Update desktop launcher.python3 - "$install_dir" "$desktop_file" <<'PY'import pathlibimport sys@@ -46,7 +314,17 @@ desktop.write_text(f'Icon={desktop_value(app / "filee.png")}\n''Terminal=false\nCategories=Utility;\nX-Filee-Managed=true\n', encoding='utf-8')PY+if command -v update-desktop-database >/dev/null 2>&1; then- update-desktop-database "$data_dir/applications"+ update-desktop-database "$data_dir/applications" 2>/dev/null || true+fi++if [ "$upgrade" -eq 1 ]; then+ printf '%s\n' "Upgraded Filee at $install_dir."+ if [ "$restart" -eq 1 ] && [ "${FILEE_IN_APP_UPDATE:-0}" != "1" ]; then+ nohup "$install_dir/Filee" </dev/null >/dev/null 2>&1 &+ printf '%s\n' "Restarted Filee."+ fi+else+ printf '%s\n' "Installed Filee at $install_dir" "CLI: $bin_dir/filee (add $bin_dir to PATH if needed)."fi-printf '%s\n' "Installed Filee at $install_dir" "CLI: $bin_dir/filee (add $bin_dir to PATH if needed)."diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex 618e0d55..51e67161 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -200,6 +200,8 @@ public partial class App : Applicationprivate static void WatchForUpdates(UserDataStore store){var updates = AppHost.Get<UpdateService>();+ updates.RequestApplicationShutdown = () =>+ (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();// Required: the card every time Filee starts (UpdateFound fires once per run). Recommended: once per version.// Optional: no card, the sidebar button only. Frequent releases no longer ask every day.updates.UpdateFound += (_, version) =>diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.csindex 12d5d617..35fe4747 100644--- a/src/Filee.App/Services/UpdateService.cs+++ b/src/Filee.App/Services/UpdateService.cs@@ -5,8 +5,11 @@using System.ComponentModel;using System.Diagnostics;+using System.Formats.Tar;+using System.IO.Compression;using System.Net.Http.Headers;using System.Reflection;+using System.Runtime.InteropServices;using System.Security.Cryptography;using System.Text.Json;using Avalonia.Threading;@@ -84,15 +87,72 @@ public sealed partial class UpdateService : ObservableObjectpublic const string WebsiteUrl = "https://filee.sh/";/// <summary>- /// True when this copy was installed by Setup, which puts its uninstaller next to Filee.exe (uninstall.exe; the- /// Inno Setup installer of 1.x put unins000.exe there). Only then can the new installer update it in place; the- /// portable zip and a copy run from source have no uninstaller.+ /// True when this copy was installed by Setup on Windows (uninstall.exe; the Inno Setup installer of 1.x put unins000.exe there)+ /// or by install.sh on Linux (.filee-package marker containing com.filee.app).+ /// Only then can the new installer update it in place; the portable zip and a copy run from source have no uninstaller./// </summary>- public static bool IsInstalled { get; } = OperatingSystem.IsWindows() && IsInstalledIn(AppContext.BaseDirectory);+ public static bool IsInstalled { get; } =+ OperatingSystem.IsWindows() && IsInstalledIn(AppContext.BaseDirectory)+ || OperatingSystem.IsLinux() && IsLinuxInstalled(AppContext.BaseDirectory);internal static bool IsInstalledIn(string folder) =>File.Exists(Path.Combine(folder, "uninstall.exe")) || File.Exists(Path.Combine(folder, "unins000.exe"));+ internal static bool IsLinuxInstalled(string baseDirectory)+ {+ var marker = Path.Combine(baseDirectory, ".filee-package");+ try+ {+ return File.Exists(marker) && File.ReadAllText(marker).Trim() == "com.filee.app";+ }+ catch (Exception)+ {+ return false;+ }+ }++ /// <summary>Returns the RID for the current Linux process architecture ("linux-x64" or "linux-arm64").</summary>+ internal static string GetLinuxRid() => GetLinuxRid(RuntimeInformation.ProcessArchitecture);++ /// <summary>Maps <paramref name="architecture"/> to supported Linux RIDs or throws <see cref="PlatformNotSupportedException"/>.</summary>+ internal static string GetLinuxRid(Architecture architecture) =>+ architecture switch+ {+ Architecture.X64 => "linux-x64",+ Architecture.Arm64 => "linux-arm64",+ var arch => throw new PlatformNotSupportedException($"Unsupported Linux architecture: {arch}"),+ };++ /// <summary>Target platform for release assets ("win", "linux-x64", "linux-arm64"). Tests can override this.</summary>+ internal string TargetPlatform { get; set; } = DefaultTargetPlatform();++ private static string DefaultTargetPlatform()+ {+ if (OperatingSystem.IsWindows())+ return "win";+ if (OperatingSystem.IsLinux())+ {+ try+ {+ return GetLinuxRid();+ }+ catch (PlatformNotSupportedException)+ {+ return "unsupported";+ }+ }+ return "unsupported";+ }++ /// <summary>Starts an external process. Tests can override this to intercept installer execution.</summary>+ internal Func<ProcessStartInfo, Process?> StartProcess { get; set; } = psi => Process.Start(psi);++ /// <summary>Invoked after a successful in-app update to gracefully exit the running application.</summary>+ internal Action? RequestApplicationShutdown { get; set; }++ /// <summary>Allows tests to redirect Linux installation target directory to an isolated temporary folder.</summary>+ internal string? LinuxInstallDirectoryOverride { get; set; }+/// <summary>Whether <see cref="UpdateAsync"/> installs by itself (<see cref="IsInstalled"/>; tests set it).</summary>internal bool InstallsItself { get; init; } = IsInstalled;@@ -163,7 +223,9 @@ public sealed partial class UpdateService : ObservableObjectusing var json = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);var tag = json.RootElement.TryGetProperty("tag_name", out var value) ? value.GetString() : null;var newer = IsNewer(tag, CurrentVersion) ? Normalize(tag!) : null;- (_installer, _checksums) = FindFiles(json.RootElement);+ (_installer, _checksums) = TargetPlatform != "unsupported"+ ? FindFiles(json.RootElement, TargetPlatform)+ : (null, null);IReadOnlyList<ReleaseNote> notes = [];if (newer is not null){@@ -264,14 +326,17 @@ public sealed partial class UpdateService : ObservableObject}string installer;+ string? workspace = null;try{+ workspace = CreateSecureWorkspace();var progress = new Progress<int>(percent => DownloadPercent = percent);- installer = await DownloadInstallerAsync(Path.Combine(Path.GetTempPath(), "Filee-update"), progress);+ installer = await DownloadInstallerAsync(workspace, progress);}catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOExceptionor InvalidDataException or UnauthorizedAccessException){+ DeleteSecureWorkspace(workspace);Fail("download", ex);return;}@@ -279,16 +344,53 @@ public sealed partial class UpdateService : ObservableObjectProcess? setup;try{- setup = Process.Start(new ProcessStartInfo(installer, InstallerArguments) { UseShellExecute = true });+ if (TargetPlatform == "win")+ {+ setup = StartProcess(new ProcessStartInfo(installer, InstallerArguments) { UseShellExecute = true });+ }+ else if (TargetPlatform.StartsWith("linux-", StringComparison.OrdinalIgnoreCase))+ {+ var stagingDir = Path.Combine(workspace, "payload");+ string payloadDir;+ try+ {+ Directory.CreateDirectory(stagingDir);+ payloadDir = ExtractLinuxArchive(installer, stagingDir);+ }+ catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)+ {+ DeleteSecureWorkspace(workspace);+ Fail("extract", ex);+ return;+ }++ var scriptPath = Path.Combine(payloadDir, "install.sh");+ var startInfo = new ProcessStartInfo("/bin/sh")+ {+ WorkingDirectory = payloadDir,+ UseShellExecute = false,+ };+ startInfo.ArgumentList.Add(scriptPath);+ startInfo.ArgumentList.Add("--upgrade");+ startInfo.ArgumentList.Add("--restart");+ startInfo.Environment["FILEE_IN_APP_UPDATE"] = "1";+ setup = StartProcess(startInfo);+ }+ else+ {+ throw new PlatformNotSupportedException("In-app update is only supported on Windows and Linux");+ }}- catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)+ catch (Win32Exception ex) when (TargetPlatform == "win" && ex.NativeErrorCode == ErrorCancelled){_log.LogInformation("Update cancelled at the administrator prompt");Step = UpdateStep.Cancelled;+ DeleteSecureWorkspace(workspace);return;}- catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException){+ DeleteSecureWorkspace(workspace);Fail("start", ex);return;}@@ -299,11 +401,78 @@ public sealed partial class UpdateService : ObservableObjectreturn;// A successful update closes Filee before Setup exits, so getting here means Setup ended without updating:- // the administrator prompt was declined (Setup asks for it itself), or the user cancelled.+ // the administrator prompt was declined (Setup asks for it itself), or the user cancelled, or an error occurred.using (setup)+ {await setup.WaitForExitAsync();- _log.LogInformation("Installer ended with exit code {Code}", setup.ExitCode);- Step = setup.ExitCode == 0 ? UpdateStep.Idle : UpdateStep.Cancelled;+ _log.LogInformation("Installer ended with exit code {Code}", setup.ExitCode);+ if (setup.ExitCode == 0)+ {+ if (TargetPlatform.StartsWith("linux-", StringComparison.OrdinalIgnoreCase))+ {+ var targetInstallDir = LinuxInstallDirectoryOverride ?? GetLinuxInstallDirectory();+ var expectedVersion = LatestVersion;+ if (string.IsNullOrWhiteSpace(expectedVersion))+ {+ var fileName = Path.GetFileName(installer);+ var parts = fileName.Split('-');+ if (parts.Length >= 2 && TryParse(parts[1], out var parsedVer))+ expectedVersion = parsedVer.ToString(3);+ expectedVersion ??= "";+ }+ if (!VerifyInstalledVersion(targetInstallDir, expectedVersion, out var actualVersion))+ {+ var recovery = FindLinuxRecoveryInfo(targetInstallDir);+ var message = $"Update verification failed: installed version '{actualVersion ?? "unknown"}' does not match expected version '{expectedVersion}'. {recovery}";+ _log.LogError("{Message}", message);+ DeleteSecureWorkspace(workspace);+ Fail("verify", new InvalidOperationException(message));+ return;+ }+ // Success on Linux: spawn detached restart watcher and shut down current instance.+ try+ {+ var newExe = Path.Combine(targetInstallDir, "Filee");+ var currentPid = Environment.ProcessId;+ var restartWatcher = new ProcessStartInfo("/bin/sh")+ {+ WorkingDirectory = targetInstallDir,+ UseShellExecute = false,+ };+ restartWatcher.ArgumentList.Add("-c");+ restartWatcher.ArgumentList.Add("for _ in $(seq 1 600); do if ! kill -0 \"$1\" 2>/dev/null; then exec \"$2\"; fi; sleep 0.1; done; exit 1");+ restartWatcher.ArgumentList.Add("_");+ restartWatcher.ArgumentList.Add(currentPid.ToString());+ restartWatcher.ArgumentList.Add(newExe);+ restartWatcher.Environment.Remove("FILEE_IN_APP_UPDATE");+ StartProcess(restartWatcher);+ }+ catch (Exception ex)+ {+ _log.LogWarning(ex, "Failed to launch restart watcher for {Version}", expectedVersion);+ }+ RequestApplicationShutdown?.Invoke();+ }+ Step = UpdateStep.Idle;+ DeleteSecureWorkspace(workspace);+ }+ else if (TargetPlatform == "win")+ {+ Step = UpdateStep.Cancelled;+ DeleteSecureWorkspace(workspace);+ }+ else+ {+ var targetInstallDir = LinuxInstallDirectoryOverride ?? GetLinuxInstallDirectory();+ var recovery = FindLinuxRecoveryInfo(targetInstallDir);+ var message = string.IsNullOrEmpty(recovery)+ ? $"Installer ended with exit code {setup.ExitCode}"+ : $"Installer ended with exit code {setup.ExitCode}. {recovery}";+ _log.LogError("{Message}", message);+ DeleteSecureWorkspace(workspace);+ Fail("install", new InvalidOperationException(message));+ }+ }}/// <summary>@@ -333,6 +502,7 @@ public sealed partial class UpdateService : ObservableObjectTryDelete(old);var partial = target + ".part";+ TryDelete(partial);await DownloadAsync(installer, partial, progress, cancellationToken);var actual = await Sha256Async(partial, cancellationToken);if (actual != expected)@@ -396,6 +566,9 @@ public sealed partial class UpdateService : ObservableObject}}+ /// <summary>Last error encountered by <see cref="UpdateAsync"/>.</summary>+ internal Exception? LastError { get; private set; }+/// <summary>/// Raised on the UI thread when an installed copy could not download or start the new installer. The app says so/// and, once the user presses OK, opens <see cref="WebsiteUrl"/> (<see cref="OpenDownloadPage"/>).@@ -404,6 +577,7 @@ public sealed partial class UpdateService : ObservableObjectprivate void Fail(string stage, Exception ex){+ LastError = ex;_log.LogWarning(ex, "In-app update failed ({Stage})", stage);Step = UpdateStep.Failed;UpdateFailed?.Invoke(this, EventArgs.Empty);@@ -423,12 +597,18 @@ public sealed partial class UpdateService : ObservableObject/// <summary>A file attached to a release.</summary>internal sealed record ReleaseFile(string Name, string Url, long Size);- /// <summary>Picks the Windows installer and the checksum file from a GitHub release (null when missing).</summary>- internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonElement release)+ /// <summary>Picks the installer/archive and checksum file matching the target platform from a GitHub release (null when missing).</summary>+ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonElement release, string? target = "win"){+ target ??= "win";ReleaseFile? installer = null, checksums = null;if (!release.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array)return (null, null);++ var isLinux = target.StartsWith("linux-", StringComparison.OrdinalIgnoreCase);+ var expectedInstallerSuffix = isLinux ? $"-{target}.tar.gz" : "-win-Setup.exe";+ var expectedChecksumsSuffix = isLinux ? $"-{target}-SHA256SUMS.txt" : "-SHA256SUMS.txt";+foreach (var asset in assets.EnumerateArray()){var name = asset.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";@@ -436,14 +616,256 @@ public sealed partial class UpdateService : ObservableObjectvar size = asset.TryGetProperty("size", out var s) && s.TryGetInt64(out var bytes) ? bytes : 0;if (name.Length == 0 || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))continue;- if (name.EndsWith("-win-Setup.exe", StringComparison.OrdinalIgnoreCase))++ if (name.EndsWith(expectedInstallerSuffix, StringComparison.OrdinalIgnoreCase))+ {installer = new ReleaseFile(name, url, size);- else if (name.EndsWith("-SHA256SUMS.txt", StringComparison.OrdinalIgnoreCase))+ }+ else if (name.EndsWith(expectedChecksumsSuffix, StringComparison.OrdinalIgnoreCase))+ {+ // When targeting Windows, exclude platform-specific checksum files (e.g. -linux-x64-SHA256SUMS.txt, -osx-...)+ if (!isLinux && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) || name.Contains("-osx-", StringComparison.OrdinalIgnoreCase)))+ continue;+checksums = new ReleaseFile(name, url, size);+ }}return (installer, checksums);}+ /// <summary>+ /// Extracts a Linux release archive (.tar.gz) into <paramref name="destinationDirectory"/> with security validation+ /// (rejecting path traversal, absolute paths, unsafe entry types, directory symlinks, and escaping/component symlinks).+ /// Returns the path to the extracted payload folder containing <c>install.sh</c>.+ /// </summary>+ internal static string ExtractLinuxArchive(string archivePath, string destinationDirectory)+ {+ if (!File.Exists(archivePath))+ throw new FileNotFoundException("Archive file not found", archivePath);++ var fullDestRoot = Path.GetFullPath(destinationDirectory);+ if (!fullDestRoot.EndsWith(Path.DirectorySeparatorChar))+ fullDestRoot += Path.DirectorySeparatorChar;++ Directory.CreateDirectory(fullDestRoot);++ using (var fileStream = File.OpenRead(archivePath))+ using (var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress))+ using (var tarReader = new TarReader(gzipStream))+ {+ while (tarReader.GetNextEntry() is { } entry)+ {+ if (entry.EntryType is TarEntryType.GlobalExtendedAttributes or TarEntryType.ExtendedAttributes)+ continue;++ if (string.IsNullOrWhiteSpace(entry.Name))+ throw new InvalidDataException("Archive contains an entry with an empty name.");++ if (Path.IsPathRooted(entry.Name) || entry.Name.StartsWith('/') || entry.Name.StartsWith('\\') || entry.Name.Contains('\\'))+ throw new InvalidDataException($"Archive entry '{entry.Name}' has an invalid or rooted path.");++ var destinationPath = Path.GetFullPath(Path.Combine(fullDestRoot, entry.Name));+ if (!destinationPath.StartsWith(fullDestRoot, StringComparison.Ordinal))+ throw new InvalidDataException($"Archive entry '{entry.Name}' attempts path traversal outside destination.");++ // Validate that no ancestor directory component between fullDestRoot and destinationPath is a symlink on disk+ ValidateNoSymlinkComponents(fullDestRoot, destinationPath);++ switch (entry.EntryType)+ {+ case TarEntryType.Directory:+ if (Path.Exists(destinationPath))+ {+ var info = new DirectoryInfo(destinationPath);+ if (info.LinkTarget is not null || info.Attributes.HasFlag(FileAttributes.ReparsePoint))+ throw new InvalidDataException($"Archive entry '{entry.Name}' conflicts with an existing symbolic link.");+ }+ Directory.CreateDirectory(destinationPath);+ break;++ case TarEntryType.RegularFile:+ case TarEntryType.V7RegularFile:+ if (Directory.Exists(destinationPath))+ throw new InvalidDataException($"Archive entry '{entry.Name}' conflicts with an existing directory.");++ var parentDir = Path.GetDirectoryName(destinationPath);+ if (!string.IsNullOrEmpty(parentDir))+ Directory.CreateDirectory(parentDir);++ // If destinationPath already exists and is a symlink, delete it rather than writing through it+ if (Path.Exists(destinationPath))+ {+ var existingInfo = new FileInfo(destinationPath);+ if (existingInfo.LinkTarget is not null || existingInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))+ File.Delete(destinationPath);+ }++ entry.ExtractToFile(destinationPath, overwrite: true);++ if (OperatingSystem.IsLinux())+ {+ var mode = entry.Mode;+ mode |= UnixFileMode.UserRead | UnixFileMode.UserWrite;+ File.SetUnixFileMode(destinationPath, mode);+ }+ break;++ case TarEntryType.SymbolicLink:+ if (string.IsNullOrWhiteSpace(entry.LinkName)+ || Path.IsPathRooted(entry.LinkName)+ || entry.LinkName.StartsWith('/')+ || entry.LinkName.StartsWith('\\')+ || entry.LinkName.Contains('\\'))+ {+ throw new InvalidDataException($"Tar symlink '{entry.Name}' has an invalid target '{entry.LinkName}'.");+ }++ var linkParent = Path.GetDirectoryName(destinationPath)!;+ var linkTarget = Path.GetFullPath(Path.Combine(linkParent, entry.LinkName));+ if (!linkTarget.StartsWith(fullDestRoot, StringComparison.Ordinal))+ {+ throw new InvalidDataException($"Tar symlink '{entry.Name}' points outside destination directory: '{entry.LinkName}'.");+ }++ // Directory symlinks are disallowed to prevent symlink-component traversal and link-order attacks+ if (Directory.Exists(linkTarget))+ {+ throw new InvalidDataException($"Tar symlink '{entry.Name}' points to a directory, which is prohibited.");+ }++ if (Directory.Exists(destinationPath))+ throw new InvalidDataException($"Archive symlink '{entry.Name}' conflicts with an existing directory.");++ if (!string.IsNullOrEmpty(linkParent))+ Directory.CreateDirectory(linkParent);++ if (Path.Exists(destinationPath))+ File.Delete(destinationPath);++ File.CreateSymbolicLink(destinationPath, entry.LinkName);+ break;++ case TarEntryType.HardLink:+ if (string.IsNullOrWhiteSpace(entry.LinkName)+ || Path.IsPathRooted(entry.LinkName)+ || entry.LinkName.StartsWith('/')+ || entry.LinkName.StartsWith('\\')+ || entry.LinkName.Contains('\\'))+ {+ throw new InvalidDataException($"Tar hard link '{entry.Name}' has an invalid target '{entry.LinkName}'.");+ }++ var hardTarget = Path.GetFullPath(Path.Combine(fullDestRoot, entry.LinkName));+ if (!hardTarget.StartsWith(fullDestRoot, StringComparison.Ordinal))+ {+ throw new InvalidDataException($"Tar hard link '{entry.Name}' points outside destination directory: '{entry.LinkName}'.");+ }++ if (Directory.Exists(hardTarget))+ {+ throw new InvalidDataException($"Tar hard link '{entry.Name}' points to a directory, which is prohibited.");+ }++ if (!File.Exists(hardTarget))+ {+ throw new InvalidDataException($"Tar hard link '{entry.Name}' target '{entry.LinkName}' does not exist.");+ }++ if (Directory.Exists(destinationPath))+ throw new InvalidDataException($"Archive hard link '{entry.Name}' conflicts with an existing directory.");++ var hardParent = Path.GetDirectoryName(destinationPath);+ if (!string.IsNullOrEmpty(hardParent))+ Directory.CreateDirectory(hardParent);++ if (Path.Exists(destinationPath))+ File.Delete(destinationPath);++ File.Copy(hardTarget, destinationPath, overwrite: true);+ break;++ default:+ throw new InvalidDataException($"Unsupported or unsafe tar entry type '{entry.EntryType}' for entry '{entry.Name}'.");+ }+ }+ }++ var rootTrimmed = Path.TrimEndingDirectorySeparator(fullDestRoot);+ string payloadDir;+ if (File.Exists(Path.Combine(rootTrimmed, "install.sh")))+ {+ payloadDir = rootTrimmed;+ }+ else+ {+ var candidates = Directory.GetDirectories(rootTrimmed)+ .Where(d => File.Exists(Path.Combine(d, "install.sh")))+ .ToList();+ if (candidates.Count == 1)+ {+ payloadDir = candidates[0];+ }+ else+ {+ throw new InvalidDataException("Archive does not contain a single valid Filee payload with install.sh");+ }+ }++ var installSh = Path.Combine(payloadDir, "install.sh");+ var fileeExe = Path.Combine(payloadDir, "Filee");+ if (!File.Exists(installSh) || !File.Exists(fileeExe))+ {+ throw new InvalidDataException("Archive is missing install.sh or Filee executable in the payload directory.");+ }++ if (OperatingSystem.IsLinux())+ {+ EnsureExecutable(installSh);+ EnsureExecutable(fileeExe);+ var cli = Path.Combine(payloadDir, "filee-cli");+ if (File.Exists(cli))+ EnsureExecutable(cli);+ var uninstall = Path.Combine(payloadDir, "uninstall.sh");+ if (File.Exists(uninstall))+ EnsureExecutable(uninstall);+ }++ return payloadDir;+ }++ /// <summary>+ /// Verifies that no intermediate directory component between <paramref name="rootPath"/> and <paramref name="targetPath"/> is a symbolic link.+ /// </summary>+ private static void ValidateNoSymlinkComponents(string rootPath, string targetPath)+ {+ var current = rootPath.TrimEnd(Path.DirectorySeparatorChar);+ var relative = Path.GetRelativePath(current, targetPath);+ var segments = relative.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);++ for (var i = 0; i < segments.Length - 1; i++)+ {+ current = Path.Combine(current, segments[i]);+ if (Path.Exists(current))+ {+ var dirInfo = new DirectoryInfo(current);+ if (dirInfo.LinkTarget is not null || dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))+ {+ throw new InvalidDataException($"Archive path component '{segments[i]}' in '{relative}' is a symbolic link.");+ }+ }+ }+ }++ private static void EnsureExecutable(string path)+ {+ if (OperatingSystem.IsLinux() && File.Exists(path))+ {+ var mode = File.GetUnixFileMode(path);+ mode |= UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;+ File.SetUnixFileMode(path, mode);+ }+ }+/// <summary>Finds the hash for <paramref name="fileName"/> in a <c>sha256sum</c>-style file ("hash name" lines).</summary>internal static string? ParseChecksum(string sums, string fileName){@@ -477,6 +899,195 @@ public sealed partial class UpdateService : ObservableObject}}+ /// <summary>+ /// Creates a private, dedicated temporary workspace for this update instance.+ /// Mode 0700 on Unix, inaccessible to other local users, non-predictable, and never reusing pre-existing paths.+ /// </summary>+ internal static string CreateSecureWorkspace(string? baseDir = null)+ {+ if (string.IsNullOrWhiteSpace(baseDir))+ {+ baseDir = Path.GetTempPath();+ if (OperatingSystem.IsLinux())+ {+ var runtimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");+ if (!string.IsNullOrWhiteSpace(runtimeDir) && Directory.Exists(runtimeDir))+ baseDir = runtimeDir;+ }+ }++ for (var attempt = 0; attempt < 100; attempt++)+ {+ var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();+ var candidate = Path.Combine(baseDir, $"filee-update-{Environment.ProcessId}-{token}");+ if (Path.Exists(candidate))+ continue;++ if (OperatingSystem.IsLinux())+ {+ Directory.CreateDirectory(candidate, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ File.SetUnixFileMode(candidate, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ }+ else+ {+ Directory.CreateDirectory(candidate);+ }++ var dirInfo = new DirectoryInfo(candidate);+ if (dirInfo.LinkTarget is not null || dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))+ {+ throw new InvalidOperationException($"Secure workspace candidate '{candidate}' is a symbolic link.");+ }++ return candidate;+ }++ throw new IOException("Failed to create a unique secure workspace directory after multiple attempts.");+ }++ /// <summary>Safely deletes a secure workspace directory created by this update, refusing to follow symlinks.</summary>+ internal static void DeleteSecureWorkspace(string? workspacePath)+ {+ if (string.IsNullOrWhiteSpace(workspacePath) || !Path.Exists(workspacePath))+ return;++ var dirInfo = new DirectoryInfo(workspacePath);+ if (dirInfo.LinkTarget is not null || dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))+ return;++ try+ {+ Directory.Delete(workspacePath, recursive: true);+ }+ catch+ {+ // Best effort cleanup+ }+ }++ /// <summary>Locates the installation directory on Linux.</summary>+ internal static string GetLinuxInstallDirectory()+ {+ var overrideDir = Environment.GetEnvironmentVariable("FILEE_INSTALL_DIR");+ if (!string.IsNullOrWhiteSpace(overrideDir))+ return overrideDir;+ if (IsLinuxInstalled(AppContext.BaseDirectory))+ return AppContext.BaseDirectory;+ return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "filee", "application");+ }++ /// <summary>Reads the installed Filee version from the specified installation folder.</summary>+ internal static string? GetInstalledVersion(string installDir)+ {+ var dll = Path.Combine(installDir, "Filee.dll");+ if (File.Exists(dll))+ {+ try+ {+ var info = FileVersionInfo.GetVersionInfo(dll);+ if (!string.IsNullOrWhiteSpace(info.ProductVersion))+ return info.ProductVersion.Split('+')[0].Trim();+ if (!string.IsNullOrWhiteSpace(info.FileVersion))+ return info.FileVersion.Trim();+ }+ catch+ {+ // Fall through+ }+ }++ var exe = Path.Combine(installDir, "Filee");+ if (File.Exists(exe))+ {+ try+ {+ var info = FileVersionInfo.GetVersionInfo(exe);+ if (!string.IsNullOrWhiteSpace(info.ProductVersion))+ return info.ProductVersion.Split('+')[0].Trim();+ if (!string.IsNullOrWhiteSpace(info.FileVersion))+ return info.FileVersion.Trim();+ }+ catch+ {+ // Fall through+ }+ }++ var cli = Path.Combine(installDir, "filee-cli");+ if (File.Exists(cli))+ {+ try+ {+ using var proc = Process.Start(new ProcessStartInfo(cli, "version")+ {+ RedirectStandardOutput = true,+ UseShellExecute = false,+ });+ if (proc is not null && proc.WaitForExit(3000) && proc.ExitCode == 0)+ {+ var line = proc.StandardOutput.ReadLine()?.Trim();+ if (line?.StartsWith("filee ", StringComparison.OrdinalIgnoreCase) == true)+ return line["filee ".Length..].Trim();+ }+ }+ catch+ {+ // Fall through+ }+ }++ var marker = Path.Combine(installDir, ".filee-version");+ if (File.Exists(marker))+ {+ try+ {+ return File.ReadAllText(marker).Trim();+ }+ catch+ {+ // Fall through+ }+ }++ return null;+ }++ /// <summary>Verifies that the version installed in <paramref name="installDir"/> matches <paramref name="expectedVersion"/>.</summary>+ internal static bool VerifyInstalledVersion(string installDir, string expectedVersion, out string? actualVersion)+ {+ actualVersion = GetInstalledVersion(installDir);+ if (actualVersion is null)+ return false;++ if (TryParse(expectedVersion, out var expected) && TryParse(actualVersion, out var actual))+ return expected == actual;++ return string.Equals(actualVersion.Trim(), expectedVersion.Trim(), StringComparison.OrdinalIgnoreCase);+ }++ private static string FindLinuxRecoveryInfo(string installDir)+ {+ var parent = Path.GetDirectoryName(installDir);+ if (string.IsNullOrWhiteSpace(parent) || !Directory.Exists(parent))+ return "";++ try+ {+ var backups = Directory.GetDirectories(parent, ".backup-*");+ if (backups.Length > 0)+ {+ var latestBackup = backups.OrderByDescending(Directory.GetCreationTimeUtc).First();+ return $"Previous installation retained at '{latestBackup}'. To recover manually: mv '{latestBackup}' '{installDir}'";+ }+ }+ catch+ {+ // Ignore directory enumeration failures+ }++ return "No backup directory found.";+ }+/// <summary>True when release tag <paramref name="tag"/> ("v1.2.0") is a higher version than <paramref name="current"/>.</summary>internal static bool IsNewer(string? tag, string current) =>TryParse(tag, out var latest) && TryParse(current, out var installed) && latest > installed;diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.csindex 68aa84d1..6ef958ad 100644--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs@@ -17,6 +17,8 @@// * Its ZIP reader refuses some containers other readers open (Tencent Docs exports, issue #141), saying only "source// file could not be loaded": an Office Open XML / OpenDocument file is tried once more as a repacked copy.+using System.Collections.Concurrent;+using System.Diagnostics;using Filee.Core.Conversion;using Filee.Core.Formats;using Filee.Engines.Infrastructure;@@ -96,11 +98,50 @@ public sealed class LibreOfficeConverter : IConverterreturn _soffice is null? EngineStatus.Unavailable("engine.reason.not_installed"): !EngineEnvironment.UsesFileesCopy("libreoffice")- ? EngineStatus.Available(_soffice, _hasHwpFilter ? "H2Orestart" : null)+ ? EngineStatus.Available(_soffice, VersionOf(_soffice) + (_hasHwpFilter ? " · H2Orestart" : "")): EngineStatus.Available(_soffice, EngineVersions.Component("libreoffice")+ (_hasHwpFilter ? $" · H2Orestart {EngineVersions.Component("h2orestart")}" : ""));}+ private static readonly ConcurrentDictionary<string, string> Versions = new();++ private static string VersionOf(string soffice) =>+ Versions.GetOrAdd($"{soffice}|{SafeLastWriteTicks(soffice)}", _ =>+ {+ try+ {+ using var process = Process.Start(new ProcessStartInfo(soffice, "--version")+ {+ UseShellExecute = false,+ CreateNoWindow = true,+ RedirectStandardOutput = true,+ RedirectStandardError = true,+ });+ if (process is null) return "LibreOffice";+ if (!process.WaitForExit(3000))+ {+ process.Kill(entireProcessTree: true);+ return "LibreOffice";+ }+ if (process.ExitCode != 0) return "LibreOffice";+ var line = process.StandardOutput.ReadLine()?.Trim();+ if (string.IsNullOrWhiteSpace(line)) return "LibreOffice";+ return line.StartsWith("LibreOffice", StringComparison.OrdinalIgnoreCase)+ ? line+ : (char.IsDigit(line[0]) || line.StartsWith('v') || line.StartsWith('V') ? $"LibreOffice {line}" : "LibreOffice");+ }+ catch+ {+ return "LibreOffice";+ }+ });++ private static long SafeLastWriteTicks(string path)+ {+ try { return File.GetLastWriteTimeUtc(path).Ticks; }+ catch { return 0; }+ }+public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken){var soffice = _soffice ?? throw new InvalidOperationException("LibreOffice was not found.");diff --git a/src/Filee.Engines/Vector/GhostscriptConverter.cs b/src/Filee.Engines/Vector/GhostscriptConverter.csindex 06f06f5a..35c8fde8 100644--- a/src/Filee.Engines/Vector/GhostscriptConverter.cs+++ b/src/Filee.Engines/Vector/GhostscriptConverter.cs@@ -4,6 +4,8 @@// SVG → EPS, …) is planned through PDF or PNG by the route planner. "Compress PDF" may also run a PDF through pdfwrite// (PdfSharpConverter calls CompressPdfAsync; there is no PDF → PDF edge here, so routes don't change).+using System.Collections.Concurrent;+using System.Diagnostics;using Filee.Core.Conversion;using Filee.Core.Presets;using Filee.Engines.Infrastructure;@@ -48,10 +50,52 @@ public sealed class GhostscriptConverter : IConverter, IImageTransformernew("ps", "png"),];+ private static readonly ConcurrentDictionary<string, string> Versions = new();+public EngineStatus GetStatus(){_executable = Locate();- return _executable is null ? EngineStatus.Unavailable("engine.reason.not_installed") : EngineStatus.Available(_executable, EngineEnvironment.UsesFileesCopy("ghostscript") ? EngineVersions.Component("ghostscript") : null);+ return _executable is null+ ? EngineStatus.Unavailable("engine.reason.not_installed")+ : EngineStatus.Available(_executable, EngineEnvironment.UsesFileesCopy("ghostscript")+ ? EngineVersions.Component("ghostscript")+ : VersionOf(_executable));+ }++ private static string? VersionOf(string gs) =>+ Versions.GetOrAdd($"{gs}|{SafeLastWriteTicks(gs)}", _ =>+ {+ try+ {+ using var process = Process.Start(new ProcessStartInfo(gs, "--version")+ {+ UseShellExecute = false,+ CreateNoWindow = true,+ RedirectStandardOutput = true,+ RedirectStandardError = true,+ });+ if (process is null) return "Ghostscript";+ if (!process.WaitForExit(3000))+ {+ process.Kill(entireProcessTree: true);+ return "Ghostscript";+ }+ if (process.ExitCode != 0) return "Ghostscript";+ var line = process.StandardOutput.ReadLine()?.Trim();+ return !string.IsNullOrWhiteSpace(line) && (char.IsDigit(line[0]) || line.StartsWith('v') || line.StartsWith('V'))+ ? $"Ghostscript {line}"+ : "Ghostscript";+ }+ catch+ {+ return "Ghostscript";+ }+ });++ private static long SafeLastWriteTicks(string path)+ {+ try { return File.GetLastWriteTimeUtc(path).Ticks; }+ catch { return 0; }}public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.csindex 137abb56..d4ccd96b 100644--- a/tests/Filee.App.Tests/UpdateServiceTests.cs+++ b/tests/Filee.App.Tests/UpdateServiceTests.cs@@ -1,5 +1,9 @@+using System.Diagnostics;+using System.Formats.Tar;+using System.IO.Compression;using System.Net;using System.Net.Sockets;+using System.Runtime.InteropServices;using System.Security.Cryptography;using System.Text;using System.Text.Json;@@ -247,7 +251,7 @@ public class UpdateServiceTestspublic async Task Update_installs_the_release_that_is_latest_now_not_the_one_found_earlier(){// An earlier check found 9.9.9; 9.9.10 came out before Update was pressed.- var updates = new UpdateService(NullLogger<UpdateService>.Instance, new LatestRelease("v9.9.10"));+ var updates = new UpdateService(NullLogger<UpdateService>.Instance, new LatestRelease("v9.9.10")) { TargetPlatform = "win" };updates.UseRelease(new UpdateService.ReleaseFile("Filee-9.9.9-win-Setup.exe", Base + "Filee-9.9.9-win-Setup.exe", 1),new UpdateService.ReleaseFile("Filee-9.9.9-SHA256SUMS.txt", Base + "Filee-9.9.9-SHA256SUMS.txt", 1));var announced = 0;@@ -283,4 +287,510 @@ public class UpdateServiceTestsAssert.EndsWith("/releases/latest", UpdateService.LatestReleaseUrl);Assert.StartsWith(UpdateService.RepositoryUrl.TrimEnd('/'), UpdateService.LatestReleaseUrl);}++ [Theory]+ [InlineData(Architecture.X64, "linux-x64")]+ [InlineData(Architecture.Arm64, "linux-arm64")]+ public void Architecture_maps_to_linux_rid(Architecture arch, string expectedRid) =>+ Assert.Equal(expectedRid, UpdateService.GetLinuxRid(arch));++ [Theory]+ [InlineData(Architecture.Arm)]+ [InlineData(Architecture.S390x)]+ [InlineData(Architecture.Wasm)]+ public void Architecture_unsupported_throws(Architecture arch) =>+ Assert.Throws<PlatformNotSupportedException>(() => UpdateService.GetLinuxRid(arch));++ [Fact]+ public void IsLinuxInstalled_checks_marker_file()+ {+ var folder = TempFolder();+ Assert.False(UpdateService.IsLinuxInstalled(folder));++ var marker = Path.Combine(folder, ".filee-package");+ File.WriteAllText(marker, "com.filee.app\n");+ Assert.True(UpdateService.IsLinuxInstalled(folder));++ File.WriteAllText(marker, "org.other.app");+ Assert.False(UpdateService.IsLinuxInstalled(folder));+ }++ [Fact]+ public void FindFiles_selects_linux_assets_for_specific_rid()+ {+ using var release = JsonDocument.Parse($$"""+ {"tag_name": "v1.2.3", "assets": [+ {"name": "Filee-1.2.3-SHA256SUMS.txt", "size": 100, "browser_download_url": "{{Base}}Filee-1.2.3-SHA256SUMS.txt"},+ {"name": "Filee-1.2.3-win-Setup.exe", "size": 1200, "browser_download_url": "{{Base}}Filee-1.2.3-win-Setup.exe"},+ {"name": "Filee-1.2.3-linux-x64.tar.gz", "size": 2000, "browser_download_url": "{{Base}}Filee-1.2.3-linux-x64.tar.gz"},+ {"name": "Filee-1.2.3-linux-x64-SHA256SUMS.txt", "size": 90, "browser_download_url": "{{Base}}Filee-1.2.3-linux-x64-SHA256SUMS.txt"},+ {"name": "Filee-1.2.3-linux-arm64.tar.gz", "size": 1900, "browser_download_url": "{{Base}}Filee-1.2.3-linux-arm64.tar.gz"},+ {"name": "Filee-1.2.3-linux-arm64-SHA256SUMS.txt", "size": 92, "browser_download_url": "{{Base}}Filee-1.2.3-linux-arm64-SHA256SUMS.txt"}+ ]}+ """);++ var (installerX64, sumsX64) = UpdateService.FindFiles(release.RootElement, "linux-x64");+ Assert.Equal("Filee-1.2.3-linux-x64.tar.gz", installerX64?.Name);+ Assert.Equal("Filee-1.2.3-linux-x64-SHA256SUMS.txt", sumsX64?.Name);++ var (installerArm64, sumsArm64) = UpdateService.FindFiles(release.RootElement, "linux-arm64");+ Assert.Equal("Filee-1.2.3-linux-arm64.tar.gz", installerArm64?.Name);+ Assert.Equal("Filee-1.2.3-linux-arm64-SHA256SUMS.txt", sumsArm64?.Name);++ var (installerWin, sumsWin) = UpdateService.FindFiles(release.RootElement, "win");+ Assert.Equal("Filee-1.2.3-win-Setup.exe", installerWin?.Name);+ Assert.Equal("Filee-1.2.3-SHA256SUMS.txt", sumsWin?.Name);+ }++ [Fact]+ public async Task Checksum_file_for_different_artifact_is_rejected()+ {+ var installerData = RandomNumberGenerator.GetBytes(1000);+ var hash = Sha256(installerData);+ var folder = TempFolder();++ var updates = new UpdateService(NullLogger<UpdateService>.Instance, new FakeLinuxRelease(+ installerData, hash, sumsArtifact: "Filee-1.2.3-linux-arm64.tar.gz"));+ updates.UseRelease(+ new UpdateService.ReleaseFile("Filee-1.2.3-linux-x64.tar.gz", Base + "Filee-1.2.3-linux-x64.tar.gz", installerData.Length),+ new UpdateService.ReleaseFile("Filee-1.2.3-linux-x64-SHA256SUMS.txt", Base + "Filee-1.2.3-linux-x64-SHA256SUMS.txt", 100));++ await Assert.ThrowsAsync<InvalidDataException>(() =>+ updates.DownloadInstallerAsync(folder, null, TestContext.Current.CancellationToken));+ }++ [Fact]+ public void ExtractLinuxArchive_valid_payload_extracts_and_sets_permissions()+ {+ var folder = TempFolder();+ var archiveFile = Path.Combine(folder, "package.tar.gz");+ var destFolder = Path.Combine(folder, "extracted");++ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "Filee-1.0.0-linux-x64/Filee", "#!/bin/sh\necho app\n");+ AddFileEntry(writer, "Filee-1.0.0-linux-x64/install.sh", "#!/bin/sh\necho installer\n");+ AddFileEntry(writer, "Filee-1.0.0-linux-x64/filee.png", "fake png data");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ var payloadDir = UpdateService.ExtractLinuxArchive(archiveFile, destFolder);++ Assert.Equal(Path.Combine(destFolder, "Filee-1.0.0-linux-x64"), payloadDir);+ var installSh = Path.Combine(payloadDir, "install.sh");+ var fileeExe = Path.Combine(payloadDir, "Filee");+ Assert.True(File.Exists(installSh));+ Assert.True(File.Exists(fileeExe));++ if (OperatingSystem.IsLinux())+ {+ var installMode = File.GetUnixFileMode(installSh);+ Assert.True((installMode & UnixFileMode.UserExecute) != 0, "install.sh must be executable");+ var fileeMode = File.GetUnixFileMode(fileeExe);+ Assert.True((fileeMode & UnixFileMode.UserExecute) != 0, "Filee must be executable");+ }+ }++ [Fact]+ public void ExtractLinuxArchive_rejects_path_traversal()+ {+ var folder = TempFolder();+ var archiveFile = Path.Combine(folder, "traversal.tar.gz");+ var destFolder = Path.Combine(folder, "extracted");++ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "../evil.sh", "#!/bin/sh\n");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ Assert.Throws<InvalidDataException>(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder));+ }++ [Fact]+ public void ExtractLinuxArchive_rejects_absolute_path()+ {+ var folder = TempFolder();+ var archiveFile = Path.Combine(folder, "absolute.tar.gz");+ var destFolder = Path.Combine(folder, "extracted");++ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "/tmp/evil.sh", "#!/bin/sh\n");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ Assert.Throws<InvalidDataException>(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder));+ }++ [Fact]+ public void ExtractLinuxArchive_rejects_escaping_symlink()+ {+ var folder = TempFolder();+ var archiveFile = Path.Combine(folder, "symlink.tar.gz");+ var destFolder = Path.Combine(folder, "extracted");++ var tarBytes = CreateTarGz(writer =>+ {+ AddSymlinkEntry(writer, "Filee-1.0.0/escape_link", "/etc/passwd");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ Assert.Throws<InvalidDataException>(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder));+ }++ [Fact]+ public void ExtractLinuxArchive_rejects_missing_payload_files()+ {+ var folder = TempFolder();+ var archiveFile = Path.Combine(folder, "missing.tar.gz");+ var destFolder = Path.Combine(folder, "extracted");++ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "Filee-1.0.0/filee.png", "png data");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ Assert.Throws<InvalidDataException>(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder));+ }++ [AvaloniaFact]+ public async Task UpdateAsync_on_linux_downloads_extracts_and_invokes_installer_with_upgrade_and_restart()+ {+ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/Filee", "#!/bin/sh\nexit 0\n");+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/install.sh", "#!/bin/sh\nexit 0\n");+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/filee.png", "png data");+ });+ var hash = Sha256(tarBytes);+ var network = new FakeLinuxRelease(tarBytes, hash, "Filee-9.9.9-linux-x64.tar.gz", "9.9.9");++ var mockInstallDir = TempFolder();+ File.WriteAllText(Path.Combine(mockInstallDir, ".filee-version"), "9.9.9");++ var updates = new UpdateService(NullLogger<UpdateService>.Instance, network)+ {+ InstallsItself = true,+ TargetPlatform = "linux-x64",+ LinuxInstallDirectoryOverride = mockInstallDir,+ };+ updates.UseRelease(+ new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64.tar.gz", Base + "Filee-9.9.9-linux-x64.tar.gz", tarBytes.Length),+ new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64-SHA256SUMS.txt", Base + "Filee-9.9.9-linux-x64-SHA256SUMS.txt", 100));++ var processes = new List<ProcessStartInfo>();+ var shutdownRequested = false;+ updates.RequestApplicationShutdown = () => shutdownRequested = true;+ updates.StartProcess = psi =>+ {+ processes.Add(psi);+ return Process.Start(new ProcessStartInfo("true") { UseShellExecute = false });+ };++ await updates.UpdateAsync();++ Assert.Equal(UpdateStep.Idle, updates.Step);+ Assert.True(processes.Count >= 2);++ var installerPsi = processes[0];+ Assert.Equal("/bin/sh", installerPsi.FileName);+ Assert.Equal(3, installerPsi.ArgumentList.Count);+ Assert.EndsWith("install.sh", installerPsi.ArgumentList[0]);+ Assert.Equal("--upgrade", installerPsi.ArgumentList[1]);+ Assert.Equal("--restart", installerPsi.ArgumentList[2]);+ Assert.Equal("1", installerPsi.Environment["FILEE_IN_APP_UPDATE"]);+ Assert.Equal(installerPsi.WorkingDirectory, Path.GetDirectoryName(installerPsi.ArgumentList[0]));++ var restartPsi = processes[1];+ Assert.Equal("/bin/sh", restartPsi.FileName);+ Assert.Equal("-c", restartPsi.ArgumentList[0]);+ Assert.Contains("kill -0", restartPsi.ArgumentList[1]);+ Assert.Equal(Environment.ProcessId.ToString(), restartPsi.ArgumentList[3]);+ Assert.Equal(Path.Combine(mockInstallDir, "Filee"), restartPsi.ArgumentList[4]);+ Assert.Equal(mockInstallDir, restartPsi.WorkingDirectory);+ Assert.False(restartPsi.Environment.ContainsKey("FILEE_IN_APP_UPDATE"));++ Assert.True(shutdownRequested, "Application shutdown must be requested after verified installation");+ }++ [AvaloniaFact]+ public async Task UpdateAsync_on_linux_handles_installer_failure()+ {+ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/Filee", "#!/bin/sh\nexit 0\n");+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/install.sh", "#!/bin/sh\nexit 0\n");+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/filee.png", "png data");+ });+ var hash = Sha256(tarBytes);+ var network = new FakeLinuxRelease(tarBytes, hash, "Filee-9.9.9-linux-x64.tar.gz", "9.9.9");++ var mockInstallDir = TempFolder();+ var backupDir = Path.Combine(Path.GetDirectoryName(mockInstallDir)!, ".backup-123");+ Directory.CreateDirectory(backupDir);++ var updates = new UpdateService(NullLogger<UpdateService>.Instance, network)+ {+ InstallsItself = true,+ TargetPlatform = "linux-x64",+ LinuxInstallDirectoryOverride = mockInstallDir,+ };+ updates.UseRelease(+ new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64.tar.gz", Base + "Filee-9.9.9-linux-x64.tar.gz", tarBytes.Length),+ new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64-SHA256SUMS.txt", Base + "Filee-9.9.9-linux-x64-SHA256SUMS.txt", 100));++ var failedCount = 0;+ updates.UpdateFailed += (_, _) => failedCount++;++ var shutdownRequested = false;+ updates.RequestApplicationShutdown = () => shutdownRequested = true;++ updates.StartProcess = psi =>+ Process.Start(new ProcessStartInfo("false") { UseShellExecute = false });++ await updates.UpdateAsync();++ Assert.Equal(UpdateStep.Failed, updates.Step);+ Assert.Equal(1, failedCount);+ Assert.NotNull(updates.LastError);+ Assert.Contains("Installer ended with exit code 1", updates.LastError.Message);+ Assert.Contains("mv '" + backupDir + "' '" + mockInstallDir + "'", updates.LastError.Message);+ Assert.False(shutdownRequested, "Application shutdown must not be requested when installer fails");+ }++ [Fact]+ public void ExtractLinuxArchive_rejects_symlink_component_traversal()+ {+ var outsideFolder = TempFolder();+ var sentinelFile = Path.Combine(outsideFolder, "sentinel.txt");+ File.WriteAllText(sentinelFile, "SENTINEL_UNTOUCHED");++ var stagingFolder = TempFolder();+ var archiveFile = Path.Combine(stagingFolder, "evil-traversal.tar.gz");+ var destFolder = Path.Combine(stagingFolder, "dest");++ var tarBytes = CreateTarGz(writer =>+ {+ // Adversarial entry 1: directory symlink pointing outside to outsideFolder+ AddSymlinkEntry(writer, "payload/escape", outsideFolder);+ // Adversarial entry 2: file inside escape pointing to sentinel.txt+ AddFileEntry(writer, "payload/escape/sentinel.txt", "MALICIOUS_OVERWRITE");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ Assert.Throws<InvalidDataException>(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder));+ Assert.Equal("SENTINEL_UNTOUCHED", File.ReadAllText(sentinelFile));+ }++ [Fact]+ public void ExtractLinuxArchive_rejects_link_order_attack()+ {+ var stagingFolder = TempFolder();+ var archiveFile = Path.Combine(stagingFolder, "evil-link-order.tar.gz");+ var destFolder = Path.Combine(stagingFolder, "dest");++ var tarBytes = CreateTarGz(writer =>+ {+ // Entry 1: regular directory+ var dirEntry = new PaxTarEntry(TarEntryType.Directory, "payload/sub");+ writer.WriteEntry(dirEntry);+ // Entry 2: attempt to replace directory with a symlink+ AddSymlinkEntry(writer, "payload/sub", "other");+ });+ File.WriteAllBytes(archiveFile, tarBytes);++ Assert.Throws<InvalidDataException>(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder));+ }++ [Fact]+ public void CreateSecureWorkspace_creates_private_unshared_directory()+ {+ var workspace = UpdateService.CreateSecureWorkspace();+ try+ {+ Assert.True(Directory.Exists(workspace));+ var dirInfo = new DirectoryInfo(workspace);+ Assert.Null(dirInfo.LinkTarget);+ Assert.False(dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint));++ if (OperatingSystem.IsLinux())+ {+ var mode = File.GetUnixFileMode(workspace);+ Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute, mode);+ }+ }+ finally+ {+ UpdateService.DeleteSecureWorkspace(workspace);+ Assert.False(Directory.Exists(workspace));+ }+ }++ [Fact]+ public void DeleteSecureWorkspace_refuses_to_follow_symlink()+ {+ var realDir = TempFolder();+ var targetFile = Path.Combine(realDir, "important.txt");+ File.WriteAllText(targetFile, "CRITICAL_DATA");++ var linkContainer = TempFolder();+ var symlinkPath = Path.Combine(linkContainer, "link-to-real");+ File.CreateSymbolicLink(symlinkPath, realDir);++ UpdateService.DeleteSecureWorkspace(symlinkPath);++ Assert.True(Directory.Exists(realDir), "Real directory must not be deleted when DeleteSecureWorkspace is called on a symlink");+ Assert.True(File.Exists(targetFile), "File inside real directory must survive");+ }++ [Fact]+ public async Task Concurrent_secure_workspaces_are_isolated()+ {+ var tasks = Enumerable.Range(0, 5).Select(_ => Task.Run(() => UpdateService.CreateSecureWorkspace())).ToArray();+ var workspaces = await Task.WhenAll(tasks);++ try+ {+ Assert.Equal(5, workspaces.Distinct().Count());+ Assert.All(workspaces, w => Assert.True(Directory.Exists(w)));+ }+ finally+ {+ foreach (var w in workspaces)+ UpdateService.DeleteSecureWorkspace(w);+ }+ }++ [Fact]+ public void VerifyInstalledVersion_detects_mismatch()+ {+ var folder = TempFolder();+ File.WriteAllText(Path.Combine(folder, ".filee-version"), "1.0.0");++ Assert.True(UpdateService.VerifyInstalledVersion(folder, "1.0.0", out var actual));+ Assert.Equal("1.0.0", actual);++ Assert.False(UpdateService.VerifyInstalledVersion(folder, "1.0.2", out actual));+ Assert.Equal("1.0.0", actual);++ var emptyFolder = TempFolder();+ Assert.False(UpdateService.VerifyInstalledVersion(emptyFolder, "1.0.0", out actual));+ Assert.Null(actual);+ }++ [AvaloniaFact]+ public async Task UpdateAsync_on_linux_fails_when_installed_version_does_not_match()+ {+ var tarBytes = CreateTarGz(writer =>+ {+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/Filee", "#!/bin/sh\nexit 0\n");+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/install.sh", "#!/bin/sh\nexit 0\n");+ AddFileEntry(writer, "Filee-9.9.9-linux-x64/filee.png", "png data");+ });+ var hash = Sha256(tarBytes);+ var network = new FakeLinuxRelease(tarBytes, hash, "Filee-9.9.9-linux-x64.tar.gz", "9.9.9");++ var mockInstallDir = TempFolder();+ File.WriteAllText(Path.Combine(mockInstallDir, ".filee-version"), "1.0.0"); // Mismatch: expecting 9.9.9++ var updates = new UpdateService(NullLogger<UpdateService>.Instance, network)+ {+ InstallsItself = true,+ TargetPlatform = "linux-x64",+ LinuxInstallDirectoryOverride = mockInstallDir,+ };+ updates.UseRelease(+ new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64.tar.gz", Base + "Filee-9.9.9-linux-x64.tar.gz", tarBytes.Length),+ new UpdateService.ReleaseFile("Filee-9.9.9-linux-x64-SHA256SUMS.txt", Base + "Filee-9.9.9-linux-x64-SHA256SUMS.txt", 100));++ var failedCount = 0;+ updates.UpdateFailed += (_, _) => failedCount++;++ var shutdownRequested = false;+ updates.RequestApplicationShutdown = () => shutdownRequested = true;++ updates.StartProcess = psi =>+ Process.Start(new ProcessStartInfo("true") { UseShellExecute = false });++ await updates.UpdateAsync();++ Assert.Equal(UpdateStep.Failed, updates.Step);+ Assert.Equal(1, failedCount);+ Assert.NotNull(updates.LastError);+ Assert.Contains("Update verification failed", updates.LastError.Message);+ Assert.False(shutdownRequested, "Application shutdown must not be requested when version verification fails");+ }++ private static byte[] CreateTarGz(Action<TarWriter> populate)+ {+ using var mem = new MemoryStream();+ using (var gzip = new GZipStream(mem, CompressionMode.Compress, leaveOpen: true))+ using (var writer = new TarWriter(gzip, TarEntryFormat.Pax, leaveOpen: true))+ {+ populate(writer);+ }+ return mem.ToArray();+ }++ private static void AddFileEntry(TarWriter writer, string name, string content, UnixFileMode mode = UnixFileMode.UserRead | UnixFileMode.UserWrite)+ {+ var bytes = Encoding.UTF8.GetBytes(content);+ var entry = new PaxTarEntry(TarEntryType.RegularFile, name)+ {+ DataStream = new MemoryStream(bytes),+ Mode = mode,+ };+ writer.WriteEntry(entry);+ }++ private static void AddSymlinkEntry(TarWriter writer, string name, string target)+ {+ var entry = new PaxTarEntry(TarEntryType.SymbolicLink, name)+ {+ LinkName = target,+ };+ writer.WriteEntry(entry);+ }++ private sealed class FakeLinuxRelease(byte[] archive, string hash, string sumsArtifact = "Filee-9.9.9-linux-x64.tar.gz", string version = "9.9.9") : HttpMessageHandler+ {+ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)+ {+ var url = request.RequestUri!.ToString();+ if (url.EndsWith("/releases/latest", StringComparison.Ordinal))+ {+ var json = $$"""+ {"tag_name":"v{{version}}","assets":[+ {"name":"Filee-{{version}}-linux-x64.tar.gz","browser_download_url":"{{Base}}Filee-{{version}}-linux-x64.tar.gz","size":{{archive.Length}}},+ {"name":"Filee-{{version}}-linux-x64-SHA256SUMS.txt","browser_download_url":"{{Base}}Filee-{{version}}-linux-x64-SHA256SUMS.txt","size":100}]}+ """;+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)+ {+ Content = new StringContent(json, Encoding.UTF8, "application/json"),+ });+ }+ if (url.Contains("/releases?per_page=", StringComparison.Ordinal) || url.EndsWith("/releases", StringComparison.Ordinal))+ {+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)+ {+ Content = new StringContent("[]", Encoding.UTF8, "application/json"),+ });+ }+ if (url.EndsWith("SHA256SUMS.txt", StringComparison.Ordinal))+ {+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)+ {+ Content = new StringContent($"{hash} {sumsArtifact}\n", Encoding.ASCII),+ });+ }+ if (url.EndsWith(".tar.gz", StringComparison.Ordinal))+ {+ Assert.Contains("application/octet-stream", request.Headers.Accept.ToString());+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(archive) });+ }+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound));+ }+ }}diff --git a/tests/Filee.Platform.Tests/LinuxInstallerTests.cs b/tests/Filee.Platform.Tests/LinuxInstallerTests.csnew file mode 100644index 00000000..5d49b342--- /dev/null+++ b/tests/Filee.Platform.Tests/LinuxInstallerTests.cs@@ -0,0 +1,734 @@+using System.Diagnostics;+using System.Runtime.Versioning;++namespace Filee.Platform.Tests;++[SupportedOSPlatform("linux")]+public sealed class LinuxInstallerTests : IDisposable+{+ private readonly string _root = Path.Combine(Path.GetTempPath(), "filee-installer-test-" + Guid.NewGuid().ToString("N"));+ private readonly string _installScriptPath;++ public LinuxInstallerTests()+ {+ Directory.CreateDirectory(_root);++ // Find the repository root containing installer/linux/install.sh+ var dir = AppContext.BaseDirectory;+ while (!File.Exists(Path.Combine(dir, "Filee.slnx")))+ {+ dir = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException("Repository root not found.");+ }+ _installScriptPath = Path.Combine(dir, "installer", "linux", "install.sh");+ }++ [Fact]+ public void First_time_installation_succeeds_in_isolated_environment()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");++ var (exitCode, output, error) = RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ Assert.True(exitCode == 0, $"Install failed with code {exitCode}. Output: {output}. Error: {error}");+ Assert.Contains("Installed Filee at", output);++ var installDir = Path.Combine(env.DataDir, "filee", "application");+ Assert.True(File.Exists(Path.Combine(installDir, "Filee")));+ Assert.True(File.Exists(Path.Combine(installDir, "filee-cli")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());++ var markerPath = Path.Combine(installDir, ".filee-package");+ Assert.True(File.Exists(markerPath));+ Assert.Equal("com.filee.app", File.ReadAllText(markerPath).Trim());+ Assert.False(File.Exists(Path.Combine(installDir, ".filee-upgrade-token")));++ var launcherPath = Path.Combine(env.HomeDir, ".local", "bin", "filee");+ Assert.True(File.Exists(launcherPath));+ Assert.Equal(Path.Combine(installDir, "filee-cli"), File.ResolveLinkTarget(launcherPath, true)?.FullName);++ var desktopPath = Path.Combine(env.DataDir, "applications", "com.filee.app.desktop");+ Assert.True(File.Exists(desktopPath));+ Assert.Contains("X-Filee-Managed=true", File.ReadAllText(desktopPath));+ }++ [Fact]+ public void First_time_installation_fails_if_already_installed()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");++ var (exitCode1, _, _) = RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);+ Assert.Equal(0, exitCode1);++ // Second run without --upgrade must fail and refuse to overwrite+ var (exitCode2, output2, error2) = RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);+ Assert.NotEqual(0, exitCode2);+ Assert.Contains("An installation already exists", output2 + error2);+ }++ [Fact]+ public void Upgrade_succeeds_and_replaces_binaries_while_preserving_engine_folder_and_settings()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");++ var (exitCode1, _, _) = RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);+ Assert.Equal(0, exitCode1);++ var installDir = Path.Combine(env.DataDir, "filee", "application");++ // Simulate user downloaded engines in ~/.local/share/Filee/engines+ var engineDir = Path.Combine(env.DataDir, "Filee", "engines", "ffmpeg");+ Directory.CreateDirectory(engineDir);+ var mockEngineBinary = Path.Combine(engineDir, "ffmpeg");+ File.WriteAllText(mockEngineBinary, "ffmpeg-binary-data");++ // Simulate user settings in ~/.config/Filee+ var configDir = Path.Combine(env.HomeDir, ".config", "Filee");+ Directory.CreateDirectory(configDir);+ var mockSettings = Path.Combine(configDir, "settings.json");+ File.WriteAllText(mockSettings, "{\"custom\": true}");++ // Now prepare a v2.0.0 payload in another directory+ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Run upgrade+ var (exitCode2, output2, error2) = RunInstaller(v2Source, env.DataDir, env.HomeDir, "--upgrade");+ Assert.True(exitCode2 == 0, $"Upgrade failed with code {exitCode2}. Output: {output2}. Error: {error2}");+ Assert.Contains("Upgraded Filee at", output2);++ // Verify application was updated to v2.0.0+ Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());++ // Verify downloaded engines are STILL PRESERVED!+ Assert.True(File.Exists(mockEngineBinary));+ Assert.Equal("ffmpeg-binary-data", File.ReadAllText(mockEngineBinary));++ // Verify settings are STILL PRESERVED!+ Assert.True(File.Exists(mockSettings));+ Assert.Equal("{\"custom\": true}", File.ReadAllText(mockSettings));++ // Verify launcher symlink, package marker, and token cleanup+ var launcherPath = Path.Combine(env.HomeDir, ".local", "bin", "filee");+ Assert.Equal(Path.Combine(installDir, "filee-cli"), File.ResolveLinkTarget(launcherPath, true)?.FullName);+ Assert.Equal("com.filee.app", File.ReadAllText(Path.Combine(installDir, ".filee-package")).Trim());+ Assert.False(File.Exists(Path.Combine(installDir, ".filee-upgrade-token")));+ }++ [Fact]+ public void Upgrade_fails_if_not_already_installed()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");++ // Running with --upgrade when no installation exists must fail cleanly+ var (exitCode, output, error) = RunInstaller(env.SourceDir, env.DataDir, env.HomeDir, "--upgrade");+ Assert.NotEqual(0, exitCode);+ Assert.Contains("No existing installation found", output + error);+ }++ [Fact]+ public void Upgrade_fails_if_marker_is_invalid_and_preserves_original_install()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var installDir = Path.Combine(env.DataDir, "filee", "application");+ var markerPath = Path.Combine(installDir, ".filee-package");+ File.WriteAllText(markerPath, "alien.app");++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir, "--upgrade");+ Assert.NotEqual(0, exitCode);+ Assert.Contains("not installed by Filee", output + error);++ // Original installation must be untouched+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ }++ [Fact]+ public void Upgrade_fails_if_payload_is_missing_executables_and_preserves_original_install()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var installDir = Path.Combine(env.DataDir, "filee", "application");++ // Broken v2 source: missing filee-cli+ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");+ File.Delete(Path.Combine(v2Source, "filee-cli"));++ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir, "--upgrade");+ Assert.NotEqual(0, exitCode);+ Assert.Contains("Payload validation failed", output + error);++ // Original installation must still be intact+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ }++ [Fact]+ public void Upgrade_invokes_quit_on_running_filee_instance()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var installDir = Path.Combine(env.DataDir, "filee", "application");+ var quitLog = Path.Combine(env.DataDir, "quit.log");++ // Replace Filee with a mock script that records --quit+ var fileeScript = Path.Combine(installDir, "Filee");+ File.WriteAllText(fileeScript, $"#!/bin/sh\nif [ \"$1\" = \"--quit\" ]; then echo \"quit-called\" >> \"{quitLog}\"; exit 0; fi\nexit 0\n");+ File.SetUnixFileMode(fileeScript, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir, "--upgrade");+ Assert.True(exitCode == 0, $"Upgrade with quit failed with code {exitCode}. Output: {output}. Error: {error}");+ Assert.True(File.Exists(quitLog));+ Assert.Contains("quit-called", File.ReadAllText(quitLog));+ }++ [Fact]+ public void Upgrade_rolls_back_if_activation_move_fails()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var installDir = Path.Combine(env.DataDir, "filee", "application");++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate failure during activation move: _FILEE_TEST_FAIL_ACTIVATION=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("Restored the previous Filee installation", output + error);++ // Original installation must be safely restored+ Assert.True(File.Exists(Path.Combine(installDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ Assert.Equal("com.filee.app", File.ReadAllText(Path.Combine(installDir, ".filee-package")).Trim());+ }++ [Fact]+ public void Upgrade_rolls_back_if_post_swap_validation_fails()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var installDir = Path.Combine(env.DataDir, "filee", "application");++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate failure during post-swap validation: _FILEE_TEST_FAIL_POST_VALIDATION=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_POST_VALIDATION"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("Activated installation failed post-swap validation", output + error);+ Assert.Contains("Restored the previous Filee installation", output + error);++ // Original installation must be safely restored+ Assert.True(File.Exists(Path.Combine(installDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ Assert.Equal("com.filee.app", File.ReadAllText(Path.Combine(installDir, ".filee-package")).Trim());+ }++ [Fact]+ public void Upgrade_reports_critical_error_and_preserves_backup_if_rollback_destination_is_occupied()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate failure during rollback where destination is occupied: _FILEE_TEST_FAIL_ROLLBACK_OCCUPIED=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ROLLBACK_OCCUPIED"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);+ Assert.Contains("Your previous installation is preserved at", output + error);+ Assert.Contains("A partial or invalid directory exists at:", output + error);+ Assert.Contains("inspect and remove or rename", output + error);++ // Verify that the backup directory still exists and holds the original installation+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var backupDirs = Directory.GetDirectories(fileeDir, ".backup-*");+ Assert.NotEmpty(backupDirs);+ var backupDir = backupDirs[0];+ Assert.True(File.Exists(Path.Combine(backupDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(backupDir, "version.txt")).Trim());++ // Verify that the occupied conflict file was preserved and not overwritten+ var installDir = Path.Combine(env.DataDir, "filee", "application");+ Assert.True(File.Exists(Path.Combine(installDir, "conflict")));+ }++ [Fact]+ public void Upgrade_reports_critical_error_if_destination_occupied_during_activation()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate destination conflict during activation: _FILEE_TEST_FAIL_ACTIVATION_OCCUPIED=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION_OCCUPIED"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);+ Assert.Contains("Your previous installation is preserved at", output + error);+ Assert.Contains("A partial or invalid directory exists at:", output + error);+ Assert.Contains("inspect and remove or rename", output + error);++ // Verify that the backup directory still exists and holds the original installation+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var backupDirs = Directory.GetDirectories(fileeDir, ".backup-*");+ Assert.NotEmpty(backupDirs);+ var backupDir = backupDirs[0];+ Assert.True(File.Exists(Path.Combine(backupDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(backupDir, "version.txt")).Trim());++ // Verify that the unmanaged conflict was not touched+ var installDir = Path.Combine(env.DataDir, "filee", "application");+ Assert.True(File.Exists(Path.Combine(installDir, "conflict")));+ }++ [Fact]+ public void Upgrade_reports_critical_error_and_preserves_backup_if_rollback_destination_is_absent_but_move_fails()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate failure during rollback when install_dir is absent: _FILEE_TEST_FAIL_ROLLBACK_ABSENT=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ROLLBACK_ABSENT"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);+ Assert.Contains("Your previous installation is preserved at", output + error);+ Assert.Contains("To restore manually, run: mv", output + error);+ Assert.DoesNotContain("A partial or invalid directory exists at:", output + error);++ // Verify that the backup directory still exists and holds the original installation+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var backupDirs = Directory.GetDirectories(fileeDir, ".backup-*");+ Assert.NotEmpty(backupDirs);+ var backupDir = backupDirs[0];+ Assert.True(File.Exists(Path.Combine(backupDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(backupDir, "version.txt")).Trim());++ var installDir = Path.Combine(fileeDir, "application");+ Assert.False(Directory.Exists(installDir));+ Assert.Contains($"To restore manually, run: mv '{backupDir}' '{installDir}'", output + error);+ }++ [Fact]+ public void Upgrade_preserves_destination_and_backup_if_quarantine_fails()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate quarantine failure during rollback: _FILEE_TEST_FAIL_QUARANTINE=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_QUARANTINE"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);+ Assert.Contains("Your previous installation is preserved at", output + error);+ Assert.Contains("A partial or invalid directory exists at:", output + error);+ Assert.Contains("inspect and remove or rename", output + error);++ // Verify that the destination was NOT deleted or removed via fallback+ var installDir = Path.Combine(env.DataDir, "filee", "application");+ Assert.True(File.Exists(Path.Combine(installDir, "Filee")));++ // Verify that the backup directory still exists and holds the original installation+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var backupDirs = Directory.GetDirectories(fileeDir, ".backup-*");+ Assert.NotEmpty(backupDirs);+ var backupDir = backupDirs[0];+ Assert.True(File.Exists(Path.Combine(backupDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(backupDir, "version.txt")).Trim());+ }++ [Fact]+ public void Upgrade_restores_backup_and_reports_quarantine_if_quarantine_cleanup_fails()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate quarantine cleanup failure: _FILEE_TEST_FAIL_CLEANUP_FAILED_DIR=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_CLEANUP_FAILED_DIR"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("Update failed. Restored the previous Filee installation", output + error);+ Assert.Contains("Quarantined failed update files preserved at:", output + error);++ // Verify that the old installation was successfully restored to application directory+ var installDir = Path.Combine(env.DataDir, "filee", "application");+ Assert.True(File.Exists(Path.Combine(installDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());++ // Verify that the quarantined failed directory still exists on disk and was preserved+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var failedDirs = Directory.GetDirectories(fileeDir, ".failed-*");+ Assert.NotEmpty(failedDirs);+ var failedDir = failedDirs[0];+ Assert.True(Directory.Exists(Path.Combine(failedDir, "locked-folder")));++ // Verify backup was safely restored into installDir (not abandoned in backup)+ var backupDirs = Directory.GetDirectories(fileeDir, ".backup-*");+ Assert.Empty(backupDirs);+ }++ [Fact]+ public void Upgrade_preserves_preexisting_backup_and_failed_directories_from_earlier_runs()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ // Create a pre-existing backup and failed directory from earlier interrupted runs+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var oldBackupDir = Path.Combine(fileeDir, ".backup-earlier-crash-999");+ Directory.CreateDirectory(oldBackupDir);+ var oldVersionFile = Path.Combine(oldBackupDir, "version.txt");+ File.WriteAllText(oldVersionFile, "v0.9.0-backup-preserved");++ var oldFailedDir = Path.Combine(fileeDir, ".failed-earlier-crash-888");+ Directory.CreateDirectory(oldFailedDir);+ var oldFailedFile = Path.Combine(oldFailedDir, "failed.txt");+ File.WriteAllText(oldFailedFile, "v0.9.0-failed-preserved");++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Run upgrade+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir, "--upgrade");+ Assert.True(exitCode == 0, $"Upgrade failed with code {exitCode}. Output: {output}. Error: {error}");++ var installDir = Path.Combine(fileeDir, "application");+ Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());++ // Verify the pre-existing backup and failed directories from earlier crash were NOT erased!+ Assert.True(Directory.Exists(oldBackupDir));+ Assert.True(File.Exists(oldVersionFile));+ Assert.Equal("v0.9.0-backup-preserved", File.ReadAllText(oldVersionFile).Trim());++ Assert.True(Directory.Exists(oldFailedDir));+ Assert.True(File.Exists(oldFailedFile));+ Assert.Equal("v0.9.0-failed-preserved", File.ReadAllText(oldFailedFile).Trim());+ }++ [Fact]+ public void Upgrade_preserves_foreign_directory_if_destination_was_replaced_before_rollback()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Simulate replacement of install_dir by a foreign directory before rollback: _FILEE_TEST_FAIL_FOREIGN_DESTINATION=1+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_FOREIGN_DESTINATION"] = "1" }, "--upgrade");++ Assert.NotEqual(0, exitCode);+ Assert.Contains("CRITICAL: Update failed and automatic rollback could not complete", output + error);+ Assert.Contains("Your previous installation is preserved at", output + error);+ Assert.Contains("A partial or invalid directory exists at:", output + error);+ Assert.Contains("inspect and remove or rename", output + error);++ // Verify that the foreign directory and its contents were NOT deleted+ var installDir = Path.Combine(env.DataDir, "filee", "application");+ var foreignFile = Path.Combine(installDir, "important.txt");+ Assert.True(File.Exists(foreignFile));+ Assert.Equal("important-foreign-data", File.ReadAllText(foreignFile).Trim());++ // Verify that the backup directory still exists and holds the original installation+ var fileeDir = Path.Combine(env.DataDir, "filee");+ var backupDirs = Directory.GetDirectories(fileeDir, ".backup-*");+ Assert.NotEmpty(backupDirs);+ var backupDir = backupDirs[0];+ Assert.True(File.Exists(Path.Combine(backupDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(backupDir, "version.txt")).Trim());+ }++ [Fact]+ public void Test_hooks_are_ignored_in_normal_environment_even_if_environment_variable_is_set()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");+ RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);++ var v2Source = Path.Combine(_root, "source-v2");+ CreateMockPayload(v2Source, "v2.0.0");++ // Set failure hook variable, but do NOT pass _FILEE_TEST_HARNESS+ var (exitCode, output, error) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1" }, passTestHarness: false, "--upgrade");++ // The upgrade MUST succeed because test hooks are locked down and ignored without harness token+ Assert.True(exitCode == 0, $"Upgrade failed unexpectedly. Output: {output}. Error: {error}");+ Assert.Contains("Upgraded Filee at", output);++ var installDir = Path.Combine(env.DataDir, "filee", "application");+ Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());++ // Second check: set failure hook variable with an INVALID test harness token+ var (exitCode2, output2, error2) = RunInstaller(v2Source, env.DataDir, env.HomeDir,+ new Dictionary<string, string> { ["_FILEE_TEST_FAIL_ACTIVATION"] = "1", ["_FILEE_TEST_HARNESS"] = "bogus-token" }, passTestHarness: false, "--upgrade");++ Assert.True(exitCode2 == 0, $"Upgrade failed unexpectedly with bogus token. Output: {output2}. Error: {error2}");+ Assert.Contains("Upgraded Filee at", output2);+ }++ [Fact]+ public void Installation_and_upgrade_succeed_with_spaces_and_special_characters_in_paths()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var id = Guid.NewGuid().ToString("N");+ var sourceDir = Path.Combine(_root, "source path with spaces " + id);+ var dataDir = Path.Combine(_root, "data path with spaces " + id);+ var homeDir = Path.Combine(_root, "home path with spaces " + id);+ Directory.CreateDirectory(sourceDir);+ Directory.CreateDirectory(dataDir);+ Directory.CreateDirectory(homeDir);++ CreateMockPayload(sourceDir, "v1.0.0");++ // Fresh install with spaces+ var (exitCode1, output1, error1) = RunInstaller(sourceDir, dataDir, homeDir);+ Assert.True(exitCode1 == 0, $"Fresh install failed. Output: {output1}. Error: {error1}");+ Assert.Contains("Installed Filee at", output1);++ var installDir = Path.Combine(dataDir, "filee", "application");+ Assert.True(File.Exists(Path.Combine(installDir, "Filee")));+ Assert.Equal("v1.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());++ // Upgrade with spaces+ var v2Source = Path.Combine(_root, "source-v2 spaces " + id);+ CreateMockPayload(v2Source, "v2.0.0");++ var (exitCode2, output2, error2) = RunInstaller(v2Source, dataDir, homeDir, "--upgrade");+ Assert.True(exitCode2 == 0, $"Upgrade failed. Output: {output2}. Error: {error2}");+ Assert.Contains("Upgraded Filee at", output2);+ Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ }++ private (string SourceDir, string DataDir, string HomeDir) CreateEnvironment()+ {+ var id = Guid.NewGuid().ToString("N");+ var sourceDir = Path.Combine(_root, "source-" + id);+ var dataDir = Path.Combine(_root, "data-" + id);+ var homeDir = Path.Combine(_root, "home-" + id);+ Directory.CreateDirectory(sourceDir);+ Directory.CreateDirectory(dataDir);+ Directory.CreateDirectory(homeDir);+ return (sourceDir, dataDir, homeDir);+ }++ [Fact]+ public void Upgrade_with_in_app_update_env_var_skips_Filee_quit_and_restart()+ {+ if (!OperatingSystem.IsLinux())+ return;++ var env = CreateEnvironment();+ CreateMockPayload(env.SourceDir, "v1.0.0");++ var (exitCode1, _, _) = RunInstaller(env.SourceDir, env.DataDir, env.HomeDir);+ Assert.Equal(0, exitCode1);++ var installDir = Path.Combine(env.DataDir, "filee", "application");+ var activeFilee = Path.Combine(installDir, "Filee");++ // Make the installed Filee binary fail if --quit is invoked+ File.WriteAllText(activeFilee, "#!/bin/sh\nif [ \"$1\" = \"--quit\" ]; then exit 42; fi\nexit 0\n");+ File.SetUnixFileMode(activeFilee, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);++ // Prepare v2 payload+ var v2Dir = Path.Combine(_root, "source-v2-" + Guid.NewGuid().ToString("N")[..8]);+ CreateMockPayload(v2Dir, "v2.0.0");++ // 1. Without FILEE_IN_APP_UPDATE, upgrade calls Filee --quit, which fails with code 42+ var (failCode, failOut, failErr) = RunInstaller(v2Dir, env.DataDir, env.HomeDir, args: ["--upgrade"]);+ Assert.NotEqual(0, failCode);+ Assert.Contains("Could not gracefully shut down", failOut + failErr);++ // 2. With FILEE_IN_APP_UPDATE=1, upgrade skips Filee --quit and succeeds+ var inAppEnv = new Dictionary<string, string> { ["FILEE_IN_APP_UPDATE"] = "1" };+ var (succCode, succOut, succErr) = RunInstaller(v2Dir, env.DataDir, env.HomeDir, inAppEnv, "--upgrade", "--restart");+ Assert.True(succCode == 0, $"Expected upgrade to succeed. Output: {succOut}. Error: {succErr}");+ Assert.Equal("v2.0.0", File.ReadAllText(Path.Combine(installDir, "version.txt")).Trim());+ }++ private void CreateMockPayload(string dir, string version)+ {+ Directory.CreateDirectory(dir);+ var filee = Path.Combine(dir, "Filee");+ var cli = Path.Combine(dir, "filee-cli");+ var icon = Path.Combine(dir, "filee.png");+ var ver = Path.Combine(dir, "version.txt");+ var script = Path.Combine(dir, "install.sh");++ File.WriteAllText(filee, "#!/bin/sh\nexit 0\n");+ File.WriteAllText(cli, "#!/bin/sh\nexit 0\n");+ File.WriteAllText(icon, "dummy-png");+ File.WriteAllText(ver, version);+ File.Copy(_installScriptPath, script, overwrite: true);++ File.SetUnixFileMode(filee, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ File.SetUnixFileMode(cli, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ File.SetUnixFileMode(script, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ }++ private static (int ExitCode, string Output, string Error) RunInstaller(+ string sourceDir, string dataDir, string homeDir, params string[] args) =>+ RunInstaller(sourceDir, dataDir, homeDir, null, passTestHarness: true, args);++ private static (int ExitCode, string Output, string Error) RunInstaller(+ string sourceDir, string dataDir, string homeDir, IDictionary<string, string>? extraEnv, params string[] args) =>+ RunInstaller(sourceDir, dataDir, homeDir, extraEnv, passTestHarness: true, args);++ private static (int ExitCode, string Output, string Error) RunInstaller(+ string sourceDir, string dataDir, string homeDir, IDictionary<string, string>? extraEnv, bool passTestHarness, params string[] args)+ {+ var script = Path.Combine(sourceDir, "install.sh");+ var psi = new ProcessStartInfo("/bin/sh")+ {+ UseShellExecute = false,+ RedirectStandardOutput = true,+ RedirectStandardError = true,+ WorkingDirectory = sourceDir,+ };+ psi.ArgumentList.Add(script);+ foreach (var arg in args)+ psi.ArgumentList.Add(arg);++ psi.Environment["XDG_DATA_HOME"] = dataDir;+ psi.Environment["HOME"] = homeDir;+ psi.Environment["PATH"] = Environment.GetEnvironmentVariable("PATH") ?? "/bin:/usr/bin";+ if (passTestHarness)+ psi.Environment["_FILEE_TEST_HARNESS"] = "com.filee.test.harness";++ if (extraEnv is not null)+ {+ foreach (var (k, v) in extraEnv)+ psi.Environment[k] = v;+ }++ using var process = Process.Start(psi)!;+ var output = process.StandardOutput.ReadToEnd();+ var error = process.StandardError.ReadToEnd();+ process.WaitForExit(10000);++ return (process.ExitCode, output, error);+ }++ public void Dispose()+ {+ try+ {+ // Reset write permissions on any created conflict folders so Directory.Delete succeeds+ foreach (var dir in Directory.GetDirectories(_root, "*", SearchOption.AllDirectories))+ {+ try { File.SetUnixFileMode(dir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); } catch { }+ }+ if (Directory.Exists(_root))+ Directory.Delete(_root, recursive: true);+ }+ catch+ {+ // Ignore temporary cleanup errors+ }+ }+}