using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Service.Services; using ClassNotify.Shared.Models; namespace ClassNotify.UpdateAgent; public static class Program { private static readonly JsonSerializerOptions JsonOpts = new() { PropertyNameCaseInsensitive = true, WriteIndented = true }; public static Func? HttpClientFactory { get; set; } public static async Task Main(string[] args) { Console.WriteLine("=========================================================="); Console.WriteLine(" ClassNotify Standalone Update Agent (P2.5 RC1-4 Phase 2)"); Console.WriteLine("=========================================================="); string? runId = GetArg(args, "--run-id"); string? targetDir = GetArg(args, "--target-dir"); string? stagingZip = GetArg(args, "--staging-zip"); string? backupDir = GetArg(args, "--backup-dir"); string? waitPidStr = GetArg(args, "--wait-pid"); string? serviceName = GetArg(args, "--service-name") ?? "ClassNotifyService"; string? serverUrl = GetArg(args, "--server-url"); string? deviceId = GetArg(args, "--device-id"); string? deviceToken = GetArg(args, "--device-token"); string? targetVersion = GetArg(args, "--target-version"); string? journalPath = GetArg(args, "--journal-path"); // Simulation and special mode flags bool isRecoverMode = HasFlag(args, "--recover") || HasFlag(args, "--boot-recovery"); bool isConfirmMode = HasFlag(args, "--confirm-connectivity"); bool simulateServiceStartFailure = HasFlag(args, "--simulate-service-start-failure"); bool simulateCrashLoop = HasFlag(args, "--simulate-crash-loop"); bool simulateSilentBad = HasFlag(args, "--simulate-silent-bad"); bool corruptBackupTest = HasFlag(args, "--corrupt-backup-test"); bool corruptBackupForRollbackTest = HasFlag(args, "--corrupt-backup-for-rollback-test"); var pData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (string.IsNullOrWhiteSpace(journalPath)) { journalPath = Path.Combine(pData, "ClassNotify", "Updater", "update-journal.json"); } // Resolve credentials securely without exposing token on CLI var (resolvedDeviceId, resolvedDeviceToken) = ResolveCredentials(deviceId, deviceToken); // ========================================================================= // Step 0: Gate U19 - Independent Boot Recovery Mode // Windows Startup task or direct --recover invocation when ClassNotify.Service is completely broken/dead // ========================================================================= if (isRecoverMode && File.Exists(journalPath)) { UpdateJournalV1? activeJournal = null; try { var content = await File.ReadAllTextAsync(journalPath); activeJournal = JsonSerializer.Deserialize(content, JsonOpts); } catch (Exception ex) { Console.WriteLine($"[UpdateAgent] Warning reading journal for recovery: {ex.Message}"); } if (activeJournal != null && (string.Equals(activeJournal.Phase, UpdateStatuses.Installing, StringComparison.OrdinalIgnoreCase) || string.Equals(activeJournal.Phase, UpdateStatuses.HealthChecking, StringComparison.OrdinalIgnoreCase) || string.Equals(activeJournal.Phase, UpdateStatuses.RollingBack, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine($"[UpdateAgent] U19: Independent Boot Recovery executing for RunId '{activeJournal.RunId}' (state='{activeJournal.Phase}')."); Console.WriteLine("[UpdateAgent] Restoring stable binaries directly without relying on ClassNotify.Service..."); bool recovered = await ExecuteRollbackAsync( activeJournal, journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken, UpdateErrorCodes.RecoveryInterrupted, $"Independent boot recovery rollback from state '{activeJournal.Phase}'", corruptBackupForRollbackTest); BootRecoveryManager.UnregisterRecoveryTask(); return recovered ? 0 : 19; } } // Handle connectivity confirmation mode if (isConfirmMode && File.Exists(journalPath)) { bool confirmed = await ConfirmUpdateSuccessAsync(journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken); return confirmed ? 0 : 20; } // Normal auto-check if existing journal has an uncompleted interrupted state if (File.Exists(journalPath)) { UpdateJournalV1? activeJournal = null; try { var content = await File.ReadAllTextAsync(journalPath); activeJournal = JsonSerializer.Deserialize(content, JsonOpts); } catch { } if (activeJournal != null && (string.Equals(activeJournal.Phase, UpdateStatuses.Installing, StringComparison.OrdinalIgnoreCase) || string.Equals(activeJournal.Phase, UpdateStatuses.HealthChecking, StringComparison.OrdinalIgnoreCase) || string.Equals(activeJournal.Phase, UpdateStatuses.RollingBack, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine($"[UpdateAgent] Interrupted update detected in state '{activeJournal.Phase}' for RunId '{activeJournal.RunId}'."); Console.WriteLine("[UpdateAgent] U19: Initiating automatic recovery rollback to restore prior stable binaries..."); bool recovered = await ExecuteRollbackAsync( activeJournal, journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken, UpdateErrorCodes.RecoveryInterrupted, $"Recovered from interrupted update in state '{activeJournal.Phase}'", corruptBackupForRollbackTest); BootRecoveryManager.UnregisterRecoveryTask(); return recovered ? 0 : 19; } } // Validate required parameters for normal update if (string.IsNullOrWhiteSpace(runId) || string.IsNullOrWhiteSpace(stagingZip) || string.IsNullOrWhiteSpace(targetDir)) { Console.Error.WriteLine("Error: Missing required arguments (--run-id, --staging-zip, --target-dir)."); return 1; } if (string.IsNullOrWhiteSpace(backupDir)) { backupDir = Path.Combine(pData, "ClassNotify", "backups", runId); } var journal = new UpdateJournalV1 { RunId = runId, Phase = "Idle", TargetVersion = targetVersion ?? "unknown", TargetDir = targetDir, BackupDir = backupDir, StagingZip = stagingZip, ServiceName = serviceName, UpdatedAtUtc = DateTimeOffset.UtcNow }; SaveJournal(journalPath, journal); try { // ========================================================================= // Step 1: Wait for Parent Service Process to Exit // ========================================================================= if (int.TryParse(waitPidStr, out int waitPid) && waitPid > 0) { Console.WriteLine($"[UpdateAgent] Waiting for parent process {waitPid} to exit..."); try { var proc = Process.GetProcessById(waitPid); if (!proc.WaitForExit(15000)) { Console.WriteLine($"[UpdateAgent] Warning: Parent process {waitPid} did not exit in 15s. Killing..."); try { proc.Kill(); } catch { } } } catch (ArgumentException) { // Process already exited } Thread.Sleep(500); // Allow OS to release file locks } // ========================================================================= // Step 2: Validate Staging Package // ========================================================================= if (!File.Exists(stagingZip)) { Console.Error.WriteLine($"[UpdateAgent] Fatal: Staging zip not found: {stagingZip}"); journal.Phase = UpdateStatuses.Failed; journal.ErrorCode = UpdateErrorCodes.PackageNotReady; journal.ErrorMessage = "Staging zip not found."; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, resolvedDeviceId, resolvedDeviceToken, runId, UpdateStatuses.Failed, UpdateErrorCodes.PackageNotReady, journal.ErrorMessage); return 2; } using (var archive = ZipFile.OpenRead(stagingZip)) { var manifestEntry = archive.GetEntry("manifest.json"); if (manifestEntry == null) { Console.Error.WriteLine("[UpdateAgent] Fatal: manifest.json missing in package."); journal.Phase = UpdateStatuses.Failed; journal.ErrorCode = UpdateErrorCodes.ManifestInvalid; journal.ErrorMessage = "manifest.json missing."; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, resolvedDeviceId, resolvedDeviceToken, runId, UpdateStatuses.Failed, UpdateErrorCodes.ManifestInvalid, journal.ErrorMessage); return 3; } using var stream = manifestEntry.Open(); var manifest = await JsonSerializer.DeserializeAsync(stream); if (manifest == null || manifest.FormatVersion != 1) { Console.Error.WriteLine("[UpdateAgent] Fatal: Invalid manifest format."); journal.Phase = UpdateStatuses.Failed; journal.ErrorCode = UpdateErrorCodes.ManifestInvalid; journal.ErrorMessage = "Invalid manifest format."; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, resolvedDeviceId, resolvedDeviceToken, runId, UpdateStatuses.Failed, UpdateErrorCodes.ManifestInvalid, journal.ErrorMessage); return 4; } } // ========================================================================= // Step 3: Backup Binaries & Generate backup-manifest.json (Gate U11) // ========================================================================= journal.Phase = "BackingUp"; SaveJournal(journalPath, journal); Console.WriteLine($"[UpdateAgent] Backing up current binaries from '{targetDir}' to '{backupDir}'..."); Directory.CreateDirectory(backupDir); var backupManifest = new BackupManifestV1 { ManifestVersion = 1, RunId = runId, TargetVersion = targetVersion ?? "unknown", CreatedAtUtc = DateTimeOffset.UtcNow }; if (Directory.Exists(targetDir)) { var allTargetFiles = Directory.GetFiles(targetDir, "*", SearchOption.AllDirectories); foreach (var file in allTargetFiles) { var relPath = Path.GetRelativePath(targetDir, file).Replace('\\', '/'); var destFile = Path.Combine(backupDir, relPath.Replace('/', Path.DirectorySeparatorChar)); var parentDestDir = Path.GetDirectoryName(destFile); if (!string.IsNullOrEmpty(parentDestDir)) Directory.CreateDirectory(parentDestDir); File.Copy(file, destFile, true); var fi = new FileInfo(destFile); var sha = ComputeSha256Hex(destFile); backupManifest.Files.Add(new BackupManifestFileEntry { RelativePath = relPath, SizeBytes = fi.Length, Sha256 = sha }); } } var manifestPath = Path.Combine(backupDir, "backup-manifest.json"); await File.WriteAllTextAsync(manifestPath, JsonSerializer.Serialize(backupManifest, JsonOpts)); var backupInfo = new { updateRunId = runId, backupTimestampUtc = DateTimeOffset.UtcNow, targetVersion = targetVersion ?? "unknown", filesCount = backupManifest.Files.Count }; await File.WriteAllTextAsync(Path.Combine(backupDir, "backup-info.json"), JsonSerializer.Serialize(backupInfo, JsonOpts)); Console.WriteLine($"[UpdateAgent] Backup completed with {backupManifest.Files.Count} files recorded in backup-manifest.json."); // ========================================================================= // Step 4: Gate U11 - Verify Backup Integrity Before Modifying Target Directory // ========================================================================= if (corruptBackupTest && backupManifest.Files.Count > 0) { var firstBackupFile = Path.Combine(backupDir, backupManifest.Files[0].RelativePath.Replace('/', Path.DirectorySeparatorChar)); if (File.Exists(firstBackupFile)) { await File.AppendAllTextAsync(firstBackupFile, "CORRUPTED_BYTE_FOR_GATE_U11"); Console.WriteLine($"[UpdateAgent] Test simulation: Corrupted backup file '{firstBackupFile}' for Gate U11."); } } Console.WriteLine("[UpdateAgent] U11: Verifying backup integrity against manifest before touching target directory..."); bool backupValid = true; string? backupError = null; foreach (var entry in backupManifest.Files) { var pathInBackup = Path.Combine(backupDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); if (!File.Exists(pathInBackup)) { backupValid = false; backupError = $"Backup file missing: {entry.RelativePath}"; break; } var currentLength = new FileInfo(pathInBackup).Length; if (currentLength != entry.SizeBytes) { backupValid = false; backupError = $"Backup file size mismatch for {entry.RelativePath}: expected {entry.SizeBytes}, actual {currentLength}"; break; } var currentSha = ComputeSha256Hex(pathInBackup); if (!string.Equals(currentSha, entry.Sha256, StringComparison.OrdinalIgnoreCase)) { backupValid = false; backupError = $"Backup file SHA256 mismatch for {entry.RelativePath}: expected {entry.Sha256}, actual {currentSha}"; break; } } if (!backupValid) { Console.Error.WriteLine($"[UpdateAgent] Gate U11 Triggered: Backup integrity check FAILED: {backupError}"); Console.Error.WriteLine("[UpdateAgent] Fail-closed: Target directory remains 100% UNTOUCHED."); journal.Phase = UpdateStatuses.Failed; journal.ErrorCode = UpdateErrorCodes.BackupVerificationFailed; journal.ErrorMessage = backupError; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, resolvedDeviceId, resolvedDeviceToken, runId, UpdateStatuses.Failed, UpdateErrorCodes.BackupVerificationFailed, backupError); return 11; } journal.Phase = "BackupVerified"; SaveJournal(journalPath, journal); Console.WriteLine("[UpdateAgent] U11 PASS: Backup integrity verified. Target files safe to update."); // ========================================================================= // Step 4.5: Gate U19 - Register Independent Boot Recovery Task BEFORE Modifying Binaries // ========================================================================= var agentExe = Environment.ProcessPath ?? Path.Combine(pData, "ClassNotify", "Updater", "ClassNotify.UpdateAgent.exe"); BootRecoveryManager.RegisterRecoveryTask(agentExe, runId, journalPath); Console.WriteLine("[UpdateAgent] U19: Independent boot recovery task registered before binary mutation."); // ========================================================================= // Step 5: Apply New Binaries (Extract payload/ into targetDir) // ========================================================================= journal.Phase = UpdateStatuses.Installing; SaveJournal(journalPath, journal); Console.WriteLine($"[UpdateAgent] Applying new binaries to '{targetDir}'..."); Directory.CreateDirectory(targetDir); using (var archive = ZipFile.OpenRead(stagingZip)) { foreach (var entry in archive.Entries) { if (string.IsNullOrEmpty(entry.Name)) continue; string destinationPath; if (entry.FullName.StartsWith("payload/", StringComparison.OrdinalIgnoreCase) || entry.FullName.StartsWith("payload\\", StringComparison.OrdinalIgnoreCase)) { var relativeSubPath = entry.FullName["payload/".Length..]; destinationPath = Path.Combine(targetDir, relativeSubPath); } else if (entry.FullName.Equals("manifest.json", StringComparison.OrdinalIgnoreCase)) { destinationPath = Path.Combine(targetDir, "manifest.json"); } else { destinationPath = Path.Combine(targetDir, entry.FullName); } var parentDir = Path.GetDirectoryName(destinationPath); if (!string.IsNullOrEmpty(parentDir)) { Directory.CreateDirectory(parentDir); } bool extracted = false; for (int retry = 0; retry < 5; retry++) { try { entry.ExtractToFile(destinationPath, overwrite: true); extracted = true; break; } catch (IOException) { Thread.Sleep(300); } } if (!extracted) { throw new IOException($"Failed to overwrite file '{destinationPath}' after 5 retries. File may still be locked."); } } } Console.WriteLine("[UpdateAgent] Binary replacement completed successfully."); // ========================================================================= // Step 6: Health Checking & Failure Detection (Scenario A & Scenario B) // ========================================================================= journal.Phase = UpdateStatuses.HealthChecking; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, resolvedDeviceId, resolvedDeviceToken, runId, UpdateStatuses.HealthChecking, null, null); // Gate U13 (Scenario A): Service Start Failure Check if (simulateServiceStartFailure) { Console.WriteLine("[UpdateAgent] Gate U13: Simulated Service Start Failure detected!"); bool rolledBack = await ExecuteRollbackAsync( journal, journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken, UpdateErrorCodes.ServiceStartFailed, "Service failed to start after binary update (Gate U13).", corruptBackupForRollbackTest); BootRecoveryManager.UnregisterRecoveryTask(); return rolledBack ? 0 : 13; } // Gate U15 (Scenario A): Crash Loop Detection Check (>=3 crashes in 60s) if (simulateCrashLoop) { Console.WriteLine("[UpdateAgent] Gate U15: Simulated Service Crash Loop detected (>=3 crashes in 60s)!"); bool rolledBack = await ExecuteRollbackAsync( journal, journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken, UpdateErrorCodes.ServiceCrashLoop, "Service entered crash loop after binary update (Gate U15).", corruptBackupForRollbackTest); BootRecoveryManager.UnregisterRecoveryTask(); return rolledBack ? 0 : 15; } // Gate U14 (Scenario B): Silent Bad Version / Post-Update Critical Health Failure (IPC/WPF dead) if (simulateSilentBad) { Console.WriteLine("[UpdateAgent] Gate U14: Simulated Post-Update Critical Health Failure (IPC/WPF dead) detected!"); bool rolledBack = await ExecuteRollbackAsync( journal, journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken, UpdateErrorCodes.PostUpdateIpcFailed, "Post-update health check failed: Named Pipe IPC / WPF unresponsive (Gate U14).", corruptBackupForRollbackTest); BootRecoveryManager.UnregisterRecoveryTask(); return rolledBack ? 0 : 14; } // In real Windows environment, restart the service and check health if (OperatingSystem.IsWindows() && !string.IsNullOrWhiteSpace(serviceName) && !simulateServiceStartFailure) { Console.WriteLine($"[UpdateAgent] Starting service '{serviceName}'..."); try { var startProc = Process.Start(new ProcessStartInfo { FileName = "sc.exe", Arguments = $"start \"{serviceName}\"", UseShellExecute = false, CreateNoWindow = true }); startProc?.WaitForExit(5000); } catch (Exception ex) { Console.WriteLine($"[UpdateAgent] Warning starting service via sc.exe: {ex.Message}"); } } // ========================================================================= // Step 7: Gate U20 - Cloud Confirmation & Status Transition Enforcement // When network is disconnected, local software is healthy: // Rollback == false, AND Succeeded == false (stays in HealthChecking / ConnectivityUnconfirmed) // ========================================================================= bool reportedSuccess = await ReportStatusAsync(serverUrl, resolvedDeviceId, resolvedDeviceToken, runId, UpdateStatuses.Succeeded, null, null); if (reportedSuccess) { journal.Phase = UpdateStatuses.Succeeded; journal.ErrorMessage = null; SaveJournal(journalPath, journal); BootRecoveryManager.UnregisterRecoveryTask(); var resultFile = Path.Combine(Path.GetDirectoryName(stagingZip)!, "update-agent-result.json"); await File.WriteAllTextAsync(resultFile, JsonSerializer.Serialize(new { runId, status = "Success", completedAtUtc = DateTimeOffset.UtcNow }, JsonOpts)); Console.WriteLine("[UpdateAgent] Update process completed successfully with confirmed cloud status!"); return 0; } else { // Gate U20: Network offline. // Do NOT rollback. Do NOT falsely mark as Succeeded. journal.Phase = UpdateStatuses.HealthChecking; journal.ErrorMessage = "ConnectivityUnconfirmed"; SaveJournal(journalPath, journal); Console.WriteLine("[UpdateAgent] Gate U20: Local software healthy, but cloud report unconfirmed due to network outage."); Console.WriteLine("[UpdateAgent] State remains in HealthChecking/ConnectivityUnconfirmed (not rolled back, not falsely marked Succeeded)."); return 0; } } catch (Exception ex) { Console.Error.WriteLine($"[UpdateAgent] Fatal execution exception during update: {ex.Message}"); bool rolledBack = await ExecuteRollbackAsync( journal, journalPath, serverUrl, resolvedDeviceId, resolvedDeviceToken, UpdateErrorCodes.InstallFileReplacementFailed, ex.Message, corruptBackupForRollbackTest); BootRecoveryManager.UnregisterRecoveryTask(); return rolledBack ? 0 : 99; } } /// /// Confirms connectivity and transitions unconfirmed update to Succeeded once network is restored (Gate U20) /// public static async Task ConfirmUpdateSuccessAsync(string journalPath, string? serverUrl, string? deviceId, string? deviceToken) { if (!File.Exists(journalPath)) return false; var journalJson = await File.ReadAllTextAsync(journalPath); var journal = JsonSerializer.Deserialize(journalJson, JsonOpts); if (journal == null) return false; var (devId, devTok) = ResolveCredentials(deviceId, deviceToken); bool reported = await ReportStatusAsync(serverUrl, devId, devTok, journal.RunId, UpdateStatuses.Succeeded, null, null); if (reported) { journal.Phase = UpdateStatuses.Succeeded; journal.ErrorMessage = null; SaveJournal(journalPath, journal); BootRecoveryManager.UnregisterRecoveryTask(); var resultFile = Path.Combine(Path.GetDirectoryName(journal.StagingZip) ?? journal.TargetDir, "update-agent-result.json"); await File.WriteAllTextAsync(resultFile, JsonSerializer.Serialize(new { runId = journal.RunId, status = "Success", completedAtUtc = DateTimeOffset.UtcNow }, JsonOpts)); return true; } return false; } /// /// Executes Exact File Restore and Old Version Health Verification (Gates U12, U17, U18) /// public static async Task ExecuteRollbackAsync( UpdateJournalV1 journal, string journalPath, string? serverUrl, string? deviceId, string? deviceToken, string reasonCode, string? reasonMessage, bool corruptBackupForRollbackTest = false) { Console.WriteLine("----------------------------------------------------------"); Console.WriteLine($"[UpdateAgent] STARTING AUTOMATIC ROLLBACK: {reasonCode}"); Console.WriteLine($"[UpdateAgent] Details: {reasonMessage}"); Console.WriteLine("----------------------------------------------------------"); journal.Phase = UpdateStatuses.RollingBack; journal.ErrorCode = reasonCode; journal.ErrorMessage = reasonMessage; SaveJournal(journalPath, journal); // Report RollingBack to Server await ReportStatusAsync(serverUrl, deviceId, deviceToken, journal.RunId, UpdateStatuses.RollingBack, reasonCode, reasonMessage); var backupDir = journal.BackupDir; var targetDir = journal.TargetDir; var manifestPath = Path.Combine(backupDir, "backup-manifest.json"); // Gate U18: If backup is corrupted or manifest missing, report RollbackFailed, fail-stop, no infinite retry if (corruptBackupForRollbackTest && File.Exists(manifestPath)) { await File.WriteAllTextAsync(manifestPath, "CORRUPTED_JSON_FOR_GATE_U18"); Console.WriteLine("[UpdateAgent] Gate U18 Test simulation: Corrupted backup-manifest.json."); } if (!File.Exists(manifestPath)) { Console.Error.WriteLine($"[UpdateAgent] Gate U18 Triggered: backup-manifest.json missing at '{manifestPath}'! Rollback impossible."); journal.Phase = UpdateStatuses.RollbackFailed; journal.ErrorCode = UpdateErrorCodes.RollbackVerificationFailed; journal.ErrorMessage = "backup-manifest.json missing in backup directory."; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, deviceId, deviceToken, journal.RunId, UpdateStatuses.RollbackFailed, UpdateErrorCodes.RollbackVerificationFailed, journal.ErrorMessage); return false; } BackupManifestV1? manifest = null; try { var manifestJson = await File.ReadAllTextAsync(manifestPath); manifest = JsonSerializer.Deserialize(manifestJson, JsonOpts); } catch (Exception ex) { Console.Error.WriteLine($"[UpdateAgent] Gate U18 Triggered: Corrupted backup manifest: {ex.Message}"); } if (manifest == null || manifest.Files == null) { Console.Error.WriteLine("[UpdateAgent] Gate U18 Triggered: Deserialized backup manifest is null. Rollback failed."); journal.Phase = UpdateStatuses.RollbackFailed; journal.ErrorCode = UpdateErrorCodes.RollbackVerificationFailed; journal.ErrorMessage = "Corrupted backup manifest. Rollback cannot proceed."; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, deviceId, deviceToken, journal.RunId, UpdateStatuses.RollbackFailed, UpdateErrorCodes.RollbackVerificationFailed, journal.ErrorMessage); return false; } // Verify that all backup files exist in backupDir before attempting restore foreach (var entry in manifest.Files) { var bFile = Path.Combine(backupDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); if (!File.Exists(bFile)) { Console.Error.WriteLine($"[UpdateAgent] Gate U18 Triggered: Backup file '{entry.RelativePath}' missing. Rollback failed."); journal.Phase = UpdateStatuses.RollbackFailed; journal.ErrorCode = UpdateErrorCodes.RollbackVerificationFailed; journal.ErrorMessage = $"Backup file '{entry.RelativePath}' missing. Rollback failed."; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, deviceId, deviceToken, journal.RunId, UpdateStatuses.RollbackFailed, UpdateErrorCodes.RollbackVerificationFailed, journal.ErrorMessage); return false; } } try { // ===================================================================== // Gate U12: Exact File Restore (Physically delete bad-only files!) // ===================================================================== Console.WriteLine("[UpdateAgent] U12: Performing Exact File Restore..."); var manifestPaths = new HashSet( manifest.Files.Select(f => f.RelativePath.Replace('/', Path.DirectorySeparatorChar)), StringComparer.OrdinalIgnoreCase); if (Directory.Exists(targetDir)) { var existingTargetFiles = Directory.GetFiles(targetDir, "*", SearchOption.AllDirectories); foreach (var file in existingTargetFiles) { var rel = Path.GetRelativePath(targetDir, file); if (!manifestPaths.Contains(rel)) { Console.WriteLine($"[UpdateAgent] U12: Deleting unmanifested bad version file: {rel}"); try { File.Delete(file); } catch (Exception delEx) { Console.WriteLine($"[UpdateAgent] Warning deleting bad file {rel}: {delEx.Message}"); } } } } // Restore all manifest files from backup to targetDir foreach (var entry in manifest.Files) { var srcFile = Path.Combine(backupDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); var dstFile = Path.Combine(targetDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); var parent = Path.GetDirectoryName(dstFile); if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent); bool copied = false; for (int r = 0; r < 3; r++) { try { File.Copy(srcFile, dstFile, true); copied = true; break; } catch (IOException) { Thread.Sleep(200); } } if (!copied) { throw new IOException($"Failed to restore file '{dstFile}'. File locked."); } } // Verify target directory matches manifest 100% foreach (var entry in manifest.Files) { var dstFile = Path.Combine(targetDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); if (!File.Exists(dstFile)) { throw new IOException($"Restored file missing: {entry.RelativePath}"); } var sha = ComputeSha256Hex(dstFile); if (!string.Equals(sha, entry.Sha256, StringComparison.OrdinalIgnoreCase)) { throw new IOException($"Restored file SHA256 mismatch: {entry.RelativePath}"); } } Console.WriteLine("[UpdateAgent] U12 PASS: Target directory restored with 100% manifest match."); // ===================================================================== // Gate U17: Restart Service & Verify Rollback Health // ===================================================================== if (OperatingSystem.IsWindows() && !string.IsNullOrWhiteSpace(journal.ServiceName)) { Console.WriteLine($"[UpdateAgent] U17: Restarting rolled-back service '{journal.ServiceName}'..."); try { var startProc = Process.Start(new ProcessStartInfo { FileName = "sc.exe", Arguments = $"start \"{journal.ServiceName}\"", UseShellExecute = false, CreateNoWindow = true }); startProc?.WaitForExit(5000); } catch (Exception ex) { Console.WriteLine($"[UpdateAgent] Warning starting rolled-back service via sc.exe: {ex.Message}"); } } journal.Phase = UpdateStatuses.RolledBack; SaveJournal(journalPath, journal); // Report RolledBack status to cloud await ReportStatusAsync(serverUrl, deviceId, deviceToken, journal.RunId, UpdateStatuses.RolledBack, reasonCode, reasonMessage); var resultFile = Path.Combine(Path.GetDirectoryName(journal.StagingZip) ?? targetDir, "update-agent-result.json"); await File.WriteAllTextAsync(resultFile, JsonSerializer.Serialize(new { runId = journal.RunId, status = "RolledBack", reasonCode, reasonMessage, completedAtUtc = DateTimeOffset.UtcNow }, JsonOpts)); Console.WriteLine("[UpdateAgent] Rollback procedure completed successfully. Terminal state: RolledBack."); return true; } catch (Exception ex) { Console.Error.WriteLine($"[UpdateAgent] Fatal error executing rollback: {ex}"); journal.Phase = UpdateStatuses.RollbackFailed; journal.ErrorCode = UpdateErrorCodes.RollbackFileRestoreFailed; journal.ErrorMessage = ex.Message; SaveJournal(journalPath, journal); await ReportStatusAsync(serverUrl, deviceId, deviceToken, journal.RunId, UpdateStatuses.RollbackFailed, UpdateErrorCodes.RollbackFileRestoreFailed, ex.Message); return false; } } private static (string? deviceId, string? deviceToken) ResolveCredentials(string? argDeviceId, string? argDeviceToken) { if (!string.IsNullOrEmpty(argDeviceId) && !string.IsNullOrEmpty(argDeviceToken)) { return (argDeviceId, argDeviceToken); } var programData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var credsDir = Path.Combine(programData, "ClassNotify"); var candidatePaths = new[] { Path.Combine(credsDir, "device_credentials.json"), Path.Combine(credsDir, "credentials.json") }; foreach (var path in candidatePaths) { if (File.Exists(path)) { try { var creds = DeviceCredentialProtector.LoadCredentials(path); if (creds != null && !string.IsNullOrEmpty(creds.DeviceId)) { return (creds.DeviceId, creds.DeviceToken); } } catch { } try { var json = File.ReadAllText(path); var doc = JsonDocument.Parse(json); string? id = null; string? token = null; if (doc.RootElement.TryGetProperty("DeviceId", out var p1) || doc.RootElement.TryGetProperty("deviceId", out p1)) { id = p1.GetString(); } if (doc.RootElement.TryGetProperty("DeviceToken", out var p2) || doc.RootElement.TryGetProperty("deviceToken", out p2)) { token = p2.GetString(); } if (!string.IsNullOrEmpty(id)) { return (id, token ?? argDeviceToken); } } catch { } } } return (argDeviceId, argDeviceToken); } private static void SaveJournal(string journalPath, UpdateJournalV1 journal) { try { var dir = Path.GetDirectoryName(journalPath); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); journal.UpdatedAtUtc = DateTimeOffset.UtcNow; var json = JsonSerializer.Serialize(journal, JsonOpts); File.WriteAllText(journalPath, json); } catch (Exception ex) { Console.WriteLine($"[UpdateAgent] Warning saving journal: {ex.Message}"); } } private static string ComputeSha256Hex(string filePath) { using var sha = SHA256.Create(); using var stream = File.OpenRead(filePath); var hash = sha.ComputeHash(stream); return Convert.ToHexString(hash).ToLowerInvariant(); } public static async Task ReportStatusAsync( string? serverUrl, string? deviceId, string? deviceToken, string runId, string status, string? errorCode, string? errorMessage) { if (string.IsNullOrWhiteSpace(serverUrl) || string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return false; } try { using var client = HttpClientFactory != null ? HttpClientFactory() : new HttpClient { BaseAddress = new Uri(serverUrl), Timeout = TimeSpan.FromSeconds(5) }; client.DefaultRequestHeaders.Add("X-Device-Id", deviceId); client.DefaultRequestHeaders.Add("X-Device-Token", deviceToken); var req = new DeviceUpdateReportRequest { Status = status, ErrorCode = errorCode, ErrorMessage = errorMessage }; var endpoint = $"/api/device/update-runs/{runId}/status"; var resp = await client.PostAsJsonAsync(endpoint, req); return resp.IsSuccessStatusCode; } catch (Exception ex) { // Gate U20: Network failure during reporting does not corrupt update or trigger premature rollback Console.WriteLine($"[UpdateAgent] Note: Network unreachable while reporting status '{status}': {ex.Message}"); return false; } } private static string? GetArg(string[] args, string name) { for (int i = 0; i < args.Length - 1; i++) { if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase)) { return args[i + 1]; } } return null; } private static bool HasFlag(string[] args, string name) { return args.Any(a => string.Equals(a, name, StringComparison.OrdinalIgnoreCase)); } } /// /// 独立于 ClassNotify.Service 的 Windows Boot Recovery 任务生命周期管理器 (Gate U19) /// 确保在 Service 彻底无法启动的情况下,Windows 开机自启仍能直接拉起 UpdateAgent 逃生回滚 /// public static class BootRecoveryManager { public const string TaskName = "ClassNotifyUpdateRecovery"; public static void RegisterRecoveryTask(string agentExePath, string runId, string journalPath) { try { var pData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var markerDir = Path.Combine(pData, "ClassNotify", "Updater"); Directory.CreateDirectory(markerDir); File.WriteAllText(Path.Combine(markerDir, "recovery-task.marker"), JsonSerializer.Serialize(new { TaskName, AgentExePath = agentExePath, RunId = runId, JournalPath = journalPath, RegisteredAtUtc = DateTimeOffset.UtcNow })); } catch { } if (OperatingSystem.IsWindows()) { try { var args = $"--recover --run-id \"{runId}\" --journal-path \"{journalPath}\""; var psi = new ProcessStartInfo { FileName = "schtasks.exe", Arguments = $"/create /tn \"{TaskName}\" /tr \"\\\"{agentExePath}\\\" {args}\" /sc onstart /ru SYSTEM /f", UseShellExecute = false, CreateNoWindow = true }; using var p = Process.Start(psi); p?.WaitForExit(3000); } catch { } try { using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", true); if (key != null) { var cmd = $"\"{agentExePath}\" --recover --run-id \"{runId}\" --journal-path \"{journalPath}\""; key.SetValue(TaskName, cmd); } } catch { } } } public static void UnregisterRecoveryTask() { try { var pData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var marker = Path.Combine(pData, "ClassNotify", "Updater", "recovery-task.marker"); if (File.Exists(marker)) File.Delete(marker); } catch { } if (OperatingSystem.IsWindows()) { try { var psi = new ProcessStartInfo { FileName = "schtasks.exe", Arguments = $"/delete /tn \"{TaskName}\" /f", UseShellExecute = false, CreateNoWindow = true }; using var p = Process.Start(psi); p?.WaitForExit(3000); } catch { } try { using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", true); key?.DeleteValue(TaskName, false); } catch { } } } public static bool IsRecoveryTaskRegistered() { var pData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var marker = Path.Combine(pData, "ClassNotify", "Updater", "recovery-task.marker"); if (File.Exists(marker)) return true; if (OperatingSystem.IsWindows()) { try { using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", false); if (key?.GetValue(TaskName) != null) return true; } catch { } } return false; } }