diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 92d4b025..03848a4b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,7 @@ jobs: run: | dotnet test tests/CoreTest/CoreTest.csproj -c Release --no-build --filter "FullyQualifiedName!~ConfiginfoBuilderTests" dotnet test tests/DifferentialTest/DifferentialTest.csproj -c Release --no-build + dotnet test tests/DrivelutionTest/DrivelutionTest.csproj -c Release --no-build --filter "FullyQualifiedName!~Acceptance" aot-verify: strategy: diff --git a/scripts/acceptance/run-windows-acceptance.ps1 b/scripts/acceptance/run-windows-acceptance.ps1 new file mode 100644 index 00000000..731d89f5 --- /dev/null +++ b/scripts/acceptance/run-windows-acceptance.ps1 @@ -0,0 +1,135 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + GeneralUpdate.Drivelution Windows acceptance gate. + Runs REAL driver-store install/rollback tests on a DISPOSABLE Windows machine (VM/snapshot). + +.DESCRIPTION + Preconditions: + 1. Run from an ELEVATED PowerShell (admin). + 2. Run on a disposable VM / restore-point snapshot — the tests install and delete driver + packages in the real driver store. + 3. Provide a TEST driver package: a directory whose INF (+ catalog) is test-signed or + otherwise approved for this machine. Unsigned packages will be rejected by pnputil + with 0x800B0100. For a self-made package enable test signing first: + bcdedit /set testsigning on (then reboot) + and sign the package with your own catalog (Inf2Cat + Signtool from the WDK). + 4. dotnet SDK available on PATH (tests are built and run with `dotnet test`). + + What it runs: + - Acceptance_Install_ThenRollback_RoundTrip : fresh install -> installed inventory contains + the package -> rollback deletes exactly the package recorded in install_state.json. + - Acceptance_InstalledBackupHook_ExportsStorePackage : second install must back up the + previously installed package via `pnputil /export-driver` (manifest Source=installed). + + All other Drivelution tests (unit + non-destructive smoke) run as well. + + Exit codes: + 0 the gate was exercised and passed + 1 a test failed, or the gate could not be exercised although -InfPath was given + 2 only the non-destructive tests ran (-InfPath omitted): they passed, but the gate was + NOT evaluated and is not cleared + +.PARAMETER InfPath + Path to the test package INF (inside its package directory). Optional; when omitted only + the non-destructive tests run, the destructive ones are reported as skipped, and the script + exits with code 2. + +.EXAMPLE + .\run-windows-acceptance.ps1 -InfPath C:\testpkg\sample.inf +#> +[CmdletBinding()] +param( + [string]$InfPath = "", + [string]$RepoRoot = "" +) + +$ErrorActionPreference = "Stop" + +# ── Preconditions ───────────────────────────────────────────────────── +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = New-Object Security.Principal.WindowsPrincipal($identity) +if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + Write-Error "Must run elevated (administrator). Aborting." + exit 1 +} + +if ([string]::IsNullOrEmpty($RepoRoot)) { + $RepoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) # scripts/acceptance -> repo root +} +$testProject = Join-Path $RepoRoot "tests/DrivelutionTest/DrivelutionTest.csproj" +if (-not (Test-Path $testProject)) { + Write-Error "Test project not found: $testProject" + exit 1 +} + +Write-Host "== Drivelution Windows acceptance gate ==" -ForegroundColor Cyan +Write-Host "Machine : $env:COMPUTERNAME ($([Environment]::OSVersion.VersionString))" +Write-Host "Elevated : yes" +Write-Host "Test signing: $((bcdedit /enum '{current}' | Select-String 'testsigning') -join ' ')" +Write-Host "" + +# The destructive tests need a package; whether one was given decides what this run can certify. +$destructive = -not [string]::IsNullOrEmpty($InfPath) +if ($destructive) { + if (-not (Test-Path $InfPath)) { Write-Error "INF not found: $InfPath"; exit 1 } + $InfPath = (Resolve-Path $InfPath).Path + if (-not (Test-Path (Join-Path (Split-Path -Parent $InfPath) '*.cat'))) { + Write-Warning "No .cat file next to the INF — pnputil may reject an unsigned package (0x800B0100)." + } + $env:DRIVELUTION_ACCEPTANCE_INF = $InfPath + Write-Host "Test INF : $InfPath" +} +else { + # An INF inherited from the environment would arm the destructive tests, although this + # branch announces that they skip. + Remove-Item Env:DRIVELUTION_ACCEPTANCE_INF -ErrorAction SilentlyContinue + Write-Host "Test INF : (none) — destructive acceptance tests are reported as skipped" +} + +$env:DRIVELUTION_ACCEPTANCE = "1" + +# ── Build & run ─────────────────────────────────────────────────────── +Push-Location $RepoRoot +$testOutput = @() +$exit = 1 +try { + Write-Host "`n== Building test project ==" -ForegroundColor Cyan + dotnet build $testProject -f net10.0 -c Release --nologo + if ($LASTEXITCODE -ne 0) { Write-Error "Build failed"; exit 1 } + + Write-Host "`n== Running acceptance + smoke + unit tests ==" -ForegroundColor Cyan + $testOutput = @(dotnet test $testProject -f net10.0 -c Release --no-build --nologo ` + --filter "FullyQualifiedName~DrivelutionTest") + $exit = $LASTEXITCODE + $testOutput | ForEach-Object { Write-Host $_ } +} +finally { + Remove-Item Env:DRIVELUTION_ACCEPTANCE -ErrorAction SilentlyContinue + Remove-Item Env:DRIVELUTION_ACCEPTANCE_INF -ErrorAction SilentlyContinue + Pop-Location +} + +if ($exit -ne 0) { + Write-Host "`nRESULT: FAILED — do not release." -ForegroundColor Red + exit $exit +} + +# The destructive tests report themselves as skipped when they could not run. A skipped gate +# test is a green run, but not a passed gate. +$skippedGate = @($testOutput | Select-String -Pattern 'Skipped\s+DrivelutionTest\.Acceptance\.') +if ($destructive) { + if ($skippedGate.Count -gt 0) { + Write-Host "`nRESULT: NOT CLEARED — the install/rollback acceptance tests were skipped although a test INF was given:" -ForegroundColor Red + $skippedGate | ForEach-Object { Write-Host " $($_.Line.Trim())" -ForegroundColor Red } + Write-Host "Do not release: the acceptance gate was not exercised." -ForegroundColor Red + exit 1 + } + + Write-Host "`nRESULT: PASSED — Windows install/rollback gate cleared." -ForegroundColor Green + exit 0 +} + +Write-Host "`nRESULT: PASSED (non-destructive) — the unit and smoke tests passed, but the install/rollback acceptance gate was NOT evaluated: no -InfPath was given." -ForegroundColor Yellow +Write-Host "Run again with -InfPath on a disposable machine to clear the gate. Exit code 2 means: not cleared." -ForegroundColor Yellow +exit 2 diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs b/src/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs index c1f7b5cb..6db3d9df 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs @@ -7,16 +7,20 @@ namespace GeneralUpdate.Drivelution.Abstractions.Configuration; public class DrivelutionOptions { /// - /// 默认备份路径 - /// Default backup path + /// 默认备份路径(UpdateStrategy.BackupPath 为空时使用) + /// Default backup root (used when UpdateStrategy.BackupPath is empty) /// public string DefaultBackupPath { get; set; } = "./DriverBackups"; - + /// + /// 下载保存目录(Download 步骤将驱动包下载到这里) + /// Download directory (the Download step stores driver packages here) + /// + public string DownloadDirectory { get; set; } = "./DriverDownloads"; /// - /// 默认重试次数 - /// Default retry count + /// 默认重试次数(UpdateStrategy.RetryCount 为 0 时使用) + /// Default retry count (used when UpdateStrategy.RetryCount is 0) /// public int DefaultRetryCount { get; set; } = 3; @@ -33,26 +37,38 @@ public class DrivelutionOptions public int DefaultTimeoutSeconds { get; set; } = 300; /// - /// 是否在调试模式下跳过签名验证 - /// Skip signature validation in debug mode + /// 重试时是否使用指数退避(每次重试延迟翻倍) + /// Whether to use exponential backoff for retries (doubles delay each retry) + /// + public bool UseExponentialBackoff { get; set; } = false; + + /// + /// 指数退避时是否叠加随机抖动(避免重试风暴;仅 UseExponentialBackoff=true 时生效) + /// Whether to add random jitter to exponential backoff (only effective with UseExponentialBackoff=true) + /// + public bool UseRetryJitter { get; set; } = false; + + /// + /// 允许在调试会话中跳过签名验证(需同时满足:策略 SkipSignatureValidation=true 且当前处于调试器下,否则忽略并记录警告) + /// Allows skipping signature validation in a debug session (requires strategy.SkipSignatureValidation AND an attached debugger; otherwise ignored with a warning) /// public bool DebugModeSkipSignature { get; set; } = false; /// - /// 是否在调试模式下跳过哈希验证 - /// Skip hash validation in debug mode + /// 允许在调试会话中跳过哈希验证(需同时满足:策略 SkipHashValidation=true 且当前处于调试器下,否则忽略并记录警告) + /// Allows skipping hash validation in a debug session (requires strategy.SkipHashValidation AND an attached debugger; otherwise ignored with a warning) /// public bool DebugModeSkipHash { get; set; } = false; /// - /// 权限校验失败时是否强制终止 - /// Force terminate on permission check failure + /// 权限校验失败时是否强制终止(true=管道失败;false=记录警告并继续尝试,由安装阶段给出最终结果) + /// Force terminate on permission check failure (true=pipe fails; false=warn and continue, install stage gives the final verdict) /// public bool ForceTerminateOnPermissionFailure { get; set; } = true; /// - /// 是否自动清理旧备份(保留最近N个) - /// Auto cleanup old backups (keep recent N) + /// 更新成功后是否自动清理旧备份(保留最近 BackupsToKeep 个) + /// Auto cleanup old backups after a successful update (keep the most recent BackupsToKeep) /// public bool AutoCleanupBackups { get; set; } = true; @@ -63,20 +79,32 @@ public class DrivelutionOptions public int BackupsToKeep { get; set; } = 5; /// - /// 重试时是否使用指数退避(每次重试延迟翻倍) - /// Whether to use exponential backoff for retries (doubles delay each retry) + /// 信任的证书指纹列表(Windows 签名验证时除发布者外额外接受这些指纹) + /// Trusted certificate thumbprints (Windows signature validation additionally accepts these) /// - public bool UseExponentialBackoff { get; set; } = false; + public List TrustedCertificateThumbprints { get; set; } = new(); /// - /// 信任的证书指纹列表(用于签名验证) - /// Trusted certificate thumbprints (for signature validation) + /// 信任的 GPG 公钥指纹或公钥文件路径(Linux 签名验证;40/16 位十六进制视为指纹做强校验) + /// Trusted GPG key fingerprints or key file paths (Linux signature validation; 40/16-char hex values are treated as fingerprints for strict validation) /// - public List TrustedCertificateThumbprints { get; set; } = new(); + public List TrustedGpgKeys { get; set; } = new(); /// - /// 信任的GPG公钥列表(Linux用) - /// Trusted GPG public keys (for Linux) + /// 网络代理(下载用;如 http://127.0.0.1:1080、socks5://127.0.0.1:10808、socks5h://...;空=直连) + /// Network proxy for downloads (e.g. http://127.0.0.1:1080, socks5://127.0.0.1:10808, socks5h://...; empty = direct) /// - public List TrustedGpgKeys { get; set; } = new(); + public string NetworkProxy { get; set; } = string.Empty; + + /// + /// 重启回调:执行系统重启(参数为延迟秒数;返回是否已发起重启)。Immediate/Delayed 重启模式必须提供。 + /// Restart callback: performs the system restart (parameter = delay seconds; returns whether restart was initiated). Required for Immediate/Delayed restart modes. + /// + public Func>? RestartCallback { get; set; } + + /// + /// 重启询问回调:询问用户是否重启(参数为提示消息;返回用户选择)。Prompt 重启模式使用;未配置时仅记录 RestartRequired。 + /// Restart prompt callback: asks the user whether to restart (parameter = prompt message; returns the user's choice). Used by Prompt restart mode; when absent only RestartRequired is recorded. + /// + public Func>? RestartPromptCallback { get; set; } } diff --git a/src/GeneralUpdate.Drivelution/Abstractions/IDriverBackup.cs b/src/GeneralUpdate.Drivelution/Abstractions/IDriverBackup.cs index 01567195..a39e75c0 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/IDriverBackup.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/IDriverBackup.cs @@ -7,23 +7,39 @@ namespace GeneralUpdate.Drivelution.Abstractions; public interface IDriverBackup { /// - /// 异步备份驱动 - /// Backs up driver asynchronously + /// 异步备份驱动包。备份的单位是驱动包:源路径是目录时为该目录,是驱动文件(INF、内核模块等)时为它所在的目录, + /// 整棵目录树被复制到备份目录中(Linux 的 .deb/.rpm 是自包含的,按单文件复制)。备份目录不能与驱动包目录相互包含。 + /// Backs up the driver package. The unit is the package: the directory + /// names, or — for a driver file such as an INF or a kernel module — the directory holding it. + /// The whole tree is copied into , which must not overlap the + /// package (a Linux .deb/.rpm file is self-contained and is copied as that single file). /// /// 源路径 / Source path - /// 备份路径 / Backup path + /// 备份路径(目录)/ Backup directory /// 取消令牌 / Cancellation token /// 备份结果 / Backup result + /// + /// 源不存在,或备份目录与驱动包目录重叠时抛出(两者均不可重试)/ The source is missing, or the + /// backup directory overlaps the package (neither is retryable). + /// Task BackupAsync(string sourcePath, string backupPath, CancellationToken cancellationToken = default); /// - /// 异步恢复驱动 - /// Restores driver asynchronously + /// 异步恢复驱动。备份目录中的内容被放回目标:目标是目录时恢复整棵包树;目标是文件时恢复该文件的备份副本。 + /// 旧版本产生的单文件备份按文件恢复。确定要写什么之前不会改动目标;目标文件被移到“.old”后若复制失败,会放回原处。 + /// Restores a backup to : a directory target receives the package + /// tree, a file target receives the backup's copy of that file, and a single-file backup made + /// by an older version is restored as a file. Nothing at the target is touched before it is + /// established what goes there, and a target moved aside as ".old" is put back when the copy fails. /// /// 备份路径 / Backup path /// 目标路径 / Target path /// 取消令牌 / Cancellation token /// 恢复结果 / Restore result + /// + /// 备份不存在、没有可恢复的文件,或恢复失败时抛出 / The backup is missing, holds nothing to + /// restore, or the restore failed. + /// Task RestoreAsync(string backupPath, string targetPath, CancellationToken cancellationToken = default); /// diff --git a/src/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs b/src/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs index d8c798dc..a7af7d4a 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs @@ -25,9 +25,14 @@ public interface IDriverValidator /// /// 文件路径 / File path /// 信任的发布者列表 / Trusted publishers list + /// 信任的证书指纹列表(匹配任一即通过)/ Trusted certificate thumbprints (any match passes) /// 取消令牌 / Cancellation token /// 验证是否通过 / Validation result - Task ValidateSignatureAsync(string filePath, IEnumerable trustedPublishers, CancellationToken cancellationToken = default); + Task ValidateSignatureAsync( + string filePath, + IEnumerable trustedPublishers, + IEnumerable? trustedThumbprints = null, + CancellationToken cancellationToken = default); /// /// 异步验证驱动兼容性 diff --git a/src/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs b/src/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs index 13c2d048..ec619456 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs @@ -7,6 +7,21 @@ namespace GeneralUpdate.Drivelution.Abstractions; /// public interface IGeneralDrivelution { + /// + /// Raised when a pipeline step starts executing (parameter = step name). + /// + event Action? OnStepStarted; + + /// + /// Raised when a pipeline step completes successfully (parameter = step name). + /// + event Action? OnStepCompleted; + + /// + /// Raised when the entire update process completes. + /// + event Action? OnUpdateCompleted; + /// /// Updates driver asynchronously /// @@ -21,6 +36,21 @@ Task UpdateAsync( IProgress? progress = null, CancellationToken cancellationToken = default); + /// + /// 仅当新版本比已安装版本新时才更新(等价于 Incremental 模式的便捷入口) + /// Updates only when the new version is newer than the installed one (convenience entry for Incremental mode) + /// + /// Driver information + /// Update strategy (optional) + /// Optional progress reporter. + /// Cancellation token. + /// Update result (Status=Skipped when no newer version is available) + Task UpdateIfNeededAsync( + DriverInfo driverInfo, + UpdateStrategy? strategy = null, + IProgress? progress = null, + CancellationToken cancellationToken = default); + /// /// Validates driver asynchronously /// @@ -46,6 +76,33 @@ Task UpdateAsync( /// Rollback result Task RollbackAsync(string backupPath, CancellationToken cancellationToken = default); + /// + /// 枚举当前系统已安装的驱动 + /// Enumerates drivers currently installed on the system + /// + /// Cancellation token. + /// Installed driver list. + Task> GetInstalledDriversAsync(CancellationToken cancellationToken = default); + + /// + /// 列出备份根目录下的全部备份(读取 backup_manifest.json;无清单的目录会被跳过) + /// Lists all backups under a backup root (reads backup_manifest.json; directories without one are skipped) + /// + /// 备份根目录(空 = 使用配置默认值)/ Backup root (empty = configured default) + /// Cancellation token. + /// 备份清单列表(按创建时间倒序)。 + Task> ListBackupsAsync(string? backupRoot = null, CancellationToken cancellationToken = default); + + /// + /// 清理旧备份:仅删除带清单的备份,保留最近 个(null = 使用 BackupsToKeep 配置)。 + /// Purges old backups: only manifest-backed ones are removed, keeping the most recent (null = BackupsToKeep). + /// + /// 备份根目录(空 = 使用配置默认值)/ Backup root (empty = configured default) + /// 保留数量 / Number of backups to keep + /// Cancellation token. + /// 删除的备份数量。 + Task PurgeBackupsAsync(string? backupRoot = null, int? keep = null, CancellationToken cancellationToken = default); + /// /// Reads driver information from local directory /// @@ -60,7 +117,7 @@ Task UpdateAsync( /// /// Drivers to update. /// Update strategy applied to each driver. - /// Execution mode: Sequential or Parallel. + /// Execution mode: Sequential or Parallel (concurrency is capped by UpdateStrategy.MaxDegreeOfParallelism). /// Optional progress reporter. /// Cancellation token. /// Aggregated batch result with per-driver outcomes. diff --git a/src/GeneralUpdate.Drivelution/Abstractions/INetworkDownloader.cs b/src/GeneralUpdate.Drivelution/Abstractions/INetworkDownloader.cs index 2f758816..b00bfce4 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/INetworkDownloader.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/INetworkDownloader.cs @@ -1,29 +1,72 @@ namespace GeneralUpdate.Drivelution.Abstractions; /// -/// 网络下载器接口(扩展点) -/// Network downloader interface (extension point) +/// 网络下载器接口:负责把驱动包从远端取回本地。 +/// Network downloader abstraction: fetches driver packages to local storage. /// -/// -/// 该接口预留用于未来扩展网络下载功能 -/// This interface is reserved for future network download functionality -/// public interface INetworkDownloader { /// - /// 异步下载驱动文件 - /// Downloads driver file asynchronously + /// 异步下载驱动文件(支持镜像回退与断点续传),返回本地文件完整路径。 + /// Downloads a driver file asynchronously (mirror fallback + resume support); returns the local file path. /// - /// 下载地址 / Download URL - /// 目标路径 / Target path - /// 下载进度回调 / Download progress callback + /// 下载请求 / Download request + /// 下载进度回调(0-100)/ Download progress callback (0-100) /// 取消令牌 / Cancellation token - /// 下载结果 / Download result - Task DownloadAsync(string url, string targetPath, IProgress? progress = null, CancellationToken cancellationToken = default); + /// 本地文件路径 / Local file path + /// 所有地址都下载失败时抛出 / Thrown when all URLs fail + Task DownloadAsync( + NetworkDownloadRequest request, + IProgress? progress = null, + CancellationToken cancellationToken = default); /// - /// 取消下载 - /// Cancels download + /// 取消当前下载 + /// Cancels the current download /// void CancelDownload(); } + +/// +/// 下载请求描述 +/// Download request descriptor +/// +public class NetworkDownloadRequest +{ + /// + /// 主下载地址 + /// Primary download URL + /// + public string Url { get; set; } = string.Empty; + + /// + /// 镜像地址列表(主地址失败时按顺序尝试) + /// Mirror URLs (tried in order when the primary fails) + /// + public IList? MirrorUrls { get; set; } + + /// + /// 本地保存目录 + /// Local target directory + /// + public string TargetDirectory { get; set; } = string.Empty; + + /// + /// 期望的 SHA256(下载完成后校验,不匹配则抛出异常) + /// Expected SHA256 (verified after download; mismatch throws) + /// + public string? ExpectedSha256 { get; set; } + + /// + /// 是否允许断点续传(默认 true) + /// Whether resuming a partial download is allowed (default true) + /// + public bool Resume { get; set; } = true; + + /// + /// 附加请求头(随主地址与镜像地址一起发送;用于 Token/BasicAuth 等鉴权场景) + /// Extra request headers sent with the primary URL and every mirror (e.g. Bearer tokens, + /// Basic auth credentials) + /// + public IDictionary? Headers { get; set; } +} diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Models/BackupManifest.cs b/src/GeneralUpdate.Drivelution/Abstractions/Models/BackupManifest.cs new file mode 100644 index 00000000..00d877b2 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Abstractions/Models/BackupManifest.cs @@ -0,0 +1,98 @@ +namespace GeneralUpdate.Drivelution.Abstractions.Models; + +/// +/// 备份清单:描述一次驱动备份的完整内容,随备份一起写入 backup_manifest.json。 +/// 回滚与备份清理都以清单为准。 +/// Backup manifest describing one driver backup; written as backup_manifest.json next to the +/// backup. Rollback and backup maintenance both rely on it. +/// +public class BackupManifest +{ + /// + /// 驱动名称 + /// Driver name + /// + public string DriverName { get; set; } = string.Empty; + + /// + /// 备份时的驱动版本 + /// Driver version at backup time + /// + public string DriverVersion { get; set; } = string.Empty; + + /// + /// 备份来源(installed=驱动仓库中已安装包的导出;package=本地包目录/文件拷贝) + /// Backup source (installed=exported from the driver store; package=copy of the local package) + /// + public string Source { get; set; } = SourcePackage; + + /// + /// “来源=本地包”常量 / Constant for : local package copy + /// + public const string SourcePackage = "package"; + + /// + /// “来源=已安装驱动导出”常量 / Constant for : exported installed driver + /// + public const string SourceInstalled = "installed"; + + /// + /// 备份时间(UTC) + /// Backup creation time (UTC) + /// + public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow; + + /// + /// 被替换的驱动原始文件路径 + /// Original file path of the driver that was replaced + /// + public string OriginalFilePath { get; set; } = string.Empty; + + /// + /// 平台(Windows / Linux) + /// Platform (Windows / Linux) + /// + public string Platform { get; set; } = string.Empty; + + /// + /// 备份包含的文件清单(相对备份目录的路径 + 哈希) + /// Files contained in the backup (paths relative to the backup directory + hashes) + /// + public List Files { get; set; } = new(); + + /// + /// 备份所在目录(加载时填充,不参与序列化也可) + /// Directory holding this backup (filled when loaded) + /// + public string BackupDirectory { get; set; } = string.Empty; + + /// + /// 备份清单文件名 / Manifest file name + /// + public const string ManifestFileName = "backup_manifest.json"; +} + +/// +/// 备份中的单个文件条目 +/// Single file entry inside a backup +/// +public class BackupFileEntry +{ + /// + /// 相对备份目录的路径 + /// Path relative to the backup directory + /// + public string RelativePath { get; set; } = string.Empty; + + /// + /// 文件 SHA256(小写十六进制) + /// File SHA256 (lowercase hex) + /// + public string Sha256 { get; set; } = string.Empty; + + /// + /// 文件大小(字节) + /// File size in bytes + /// + public long Size { get; set; } +} diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Models/DriverInfo.cs b/src/GeneralUpdate.Drivelution/Abstractions/Models/DriverInfo.cs index 3c44ec3a..49c8209e 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/Models/DriverInfo.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/Models/DriverInfo.cs @@ -19,11 +19,23 @@ public class DriverInfo public string Version { get; set; } = string.Empty; /// - /// 驱动文件路径 - /// Driver file path + /// 驱动文件路径(本地路径;为空且设置了 DownloadUrl 时由管道先下载) + /// Driver file path (local; when empty with DownloadUrl set, the pipeline downloads first) /// public string FilePath { get; set; } = string.Empty; + /// + /// 驱动包下载地址(可选;设置后管道会在安装前先下载) + /// Driver package download URL (optional; the pipeline downloads before install when set) + /// + public string DownloadUrl { get; set; } = string.Empty; + + /// + /// 镜像下载地址列表(主地址失败时按顺序尝试) + /// Mirror download URLs (tried in order when the primary URL fails) + /// + public List MirrorUrls { get; set; } = new(); + /// /// 适配操作系统 /// Supported operating system diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Models/InstallState.cs b/src/GeneralUpdate.Drivelution/Abstractions/Models/InstallState.cs new file mode 100644 index 00000000..449191c5 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Abstractions/Models/InstallState.cs @@ -0,0 +1,62 @@ +namespace GeneralUpdate.Drivelution.Abstractions.Models; + +/// +/// 安装状态快照:安装步骤成功后写入备份目录(install_state.json), +/// 回滚时用它精确定位刚安装的驱动包,避免按名字匹配误删。 +/// Install-state snapshot: written by the install step into the backup directory +/// (install_state.json) so rollback can target exactly the package that was installed. +/// +public class InstallState +{ + /// + /// 安装状态文件名 / Install state file name + /// + public const string InstallStateFileName = "install_state.json"; + + /// + /// 新安装的驱动包发布名(Windows: oemXX.inf) + /// Published name of the newly installed package (Windows: oemXX.inf) + /// + public string PublishedName { get; set; } = string.Empty; + + /// + /// 原始 INF 名 / Original INF name + /// + public string OriginalName { get; set; } = string.Empty; + + /// + /// Linux:内核版本(模块安装到 /lib/modules/{release}/updates) + /// Linux: kernel release (module installed under /lib/modules/{release}/updates) + /// + public string KernelRelease { get; set; } = string.Empty; + + /// + /// Linux:安装后的模块文件路径 + /// Linux: installed module file path + /// + public string ModuleTargetPath { get; set; } = string.Empty; + + /// + /// DKMS 模块名(DKMS 安装时填充) + /// DKMS module name (set for DKMS installs) + /// + public string DkmsModule { get; set; } = string.Empty; + + /// + /// DKMS 模块版本 + /// DKMS module version + /// + public string DkmsVersion { get; set; } = string.Empty; + + /// + /// 安装时间(UTC) + /// Installation time (UTC) + /// + public DateTime InstalledAtUtc { get; set; } = DateTime.UtcNow; + + /// + /// 平台(Windows / Linux) + /// Platform (Windows / Linux) + /// + public string Platform { get; set; } = string.Empty; +} diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Models/InstalledDriverInfo.cs b/src/GeneralUpdate.Drivelution/Abstractions/Models/InstalledDriverInfo.cs new file mode 100644 index 00000000..3691133d --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Abstractions/Models/InstalledDriverInfo.cs @@ -0,0 +1,72 @@ +namespace GeneralUpdate.Drivelution.Abstractions.Models; + +/// +/// 已安装驱动信息(由 GetInstalledDriversAsync 返回) +/// Installed driver information (returned by GetInstalledDriversAsync) +/// +public class InstalledDriverInfo +{ + /// + /// 驱动名称(Windows=INF 原始名(不含扩展名);Linux=内核模块名) + /// Driver name (Windows=original INF name without extension; Linux=kernel module name) + /// + public string Name { get; set; } = string.Empty; + + /// + /// 发布名(Windows=oemXX.inf;Linux 为空) + /// Published name (Windows=oemXX.inf; empty on Linux) + /// + public string PublishedName { get; set; } = string.Empty; + + /// + /// 提供者(如厂商名) + /// Provider (e.g. vendor name) + /// + public string Provider { get; set; } = string.Empty; + + /// + /// 驱动版本(尽量为 SemVer 兼容字符串) + /// Driver version (SemVer-compatible when possible) + /// + public string Version { get; set; } = string.Empty; + + /// + /// 设备类别 + /// Device class + /// + public string ClassName { get; set; } = string.Empty; + + /// + /// 签名者 + /// Signer + /// + public string SignerName { get; set; } = string.Empty; + + /// + /// 驱动文件路径 + /// Driver file path + /// + public string FilePath { get; set; } = string.Empty; + + /// + /// 驱动日期(解析失败时为 null) + /// Driver date (null when unparseable) + /// + public DateTime? Date { get; set; } + + /// + /// 原始日期文本(供本地化输出排查) + /// Raw date text as reported by the system + /// + public string RawDate { get; set; } = string.Empty; + + /// + /// 设备状态(仅 /enum-devices 枚举设备时填充,如 Started/Error;含问题码) + /// Device status (populated only by /enum-devices listings, e.g. Started/Error; includes problem codes) + /// + public string Status { get; set; } = string.Empty; + + /// + public override string ToString() => + $"{Name} v{Version}{(string.IsNullOrEmpty(PublishedName) ? string.Empty : $" ({PublishedName})")}"; +} diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateResult.cs b/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateResult.cs index 7bf38fdb..519ce664 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateResult.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateResult.cs @@ -54,6 +54,30 @@ public class UpdateResult /// public bool RolledBack { get; set; } + /// + /// 更新前已安装的驱动版本(当版本检查发现已安装驱动时记录) + /// Previously installed driver version (recorded when an installed driver was found) + /// + public string? PreviousVersion { get; set; } + + /// + /// 更新后驱动版本(当前为输入的新版本号) + /// Driver version after the update (currently the incoming target version) + /// + public string? InstalledVersion { get; set; } + + /// + /// 是否需要重启系统才能完成本次更新 + /// Whether a system restart is required to complete the update + /// + public bool RestartRequired { get; set; } + + /// + /// 本次运行是否为 DryRun(只做检查,不做任何系统变更) + /// Whether this run was a dry run (checks only, no system changes) + /// + public bool IsDryRun { get; set; } + /// /// 附加消息 /// Additional message @@ -75,6 +99,8 @@ public enum UpdateStatus { /// 未开始 / Not started NotStarted, + /// 下载中 / Downloading + Downloading, /// 验证中 / Validating Validating, /// 备份中 / Backing up @@ -88,5 +114,13 @@ public enum UpdateStatus /// 失败 / Failed Failed, /// 已回滚 / Rolled back - RolledBack + RolledBack, + /// 已跳过(版本检查判定无需更新)/ Skipped (version check decided no update needed) + Skipped, + /// 已取消(用户取消)/ Cancelled by user + Cancelled, + /// 需要重启 / Restart required + RestartRequired, + /// 演练完成(DryRun)/ Dry run completed + DryRunCompleted } diff --git a/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateStrategy.cs b/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateStrategy.cs index c55c5461..1844dbc2 100644 --- a/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateStrategy.cs +++ b/src/GeneralUpdate.Drivelution/Abstractions/Models/UpdateStrategy.cs @@ -7,14 +7,14 @@ namespace GeneralUpdate.Drivelution.Abstractions.Models; public class UpdateStrategy { /// - /// 更新模式(全量更新/增量更新) - /// Update mode (Full/Incremental) + /// 更新模式(Full=无条件安装;Incremental=先与已安装驱动做版本比较,不比已装版本新则跳过) + /// Update mode (Full=always install; Incremental=compare with installed driver version and skip when not newer) /// public UpdateMode Mode { get; set; } = UpdateMode.Full; /// - /// 是否强制更新(强制更新不允许用户取消) - /// Force update (forced update cannot be cancelled by user) + /// 是否强制更新(强制更新期间不响应用户取消令牌;超时仍然生效) + /// Force update (user cancellation is ignored while running; timeout still applies) /// public bool ForceUpdate { get; set; } = false; @@ -25,26 +25,26 @@ public class UpdateStrategy public bool RequireBackup { get; set; } = true; /// - /// 备份路径 - /// Backup path + /// 备份路径(目录;为空时回落到 DrivelutionOptions.DefaultBackupPath) + /// Backup root directory (empty = fall back to DrivelutionOptions.DefaultBackupPath) /// public string BackupPath { get; set; } = string.Empty; /// - /// 失败重试次数 - /// Retry count on failure + /// 失败重试次数(0 = 使用 DrivelutionOptions.DefaultRetryCount) + /// Retry count on failure (0 = use DrivelutionOptions.DefaultRetryCount) /// - public int RetryCount { get; set; } = 3; + public int RetryCount { get; set; } = 0; /// - /// 重试间隔(秒) - /// Retry interval (seconds) + /// 重试间隔(秒;0 = 使用 DrivelutionOptions.DefaultRetryIntervalSeconds) + /// Retry interval in seconds (0 = use DrivelutionOptions.DefaultRetryIntervalSeconds) /// - public int RetryIntervalSeconds { get; set; } = 5; + public int RetryIntervalSeconds { get; set; } = 0; /// - /// 更新优先级(用于分批更新) - /// Update priority (for batch updates) + /// 更新优先级(用于分批更新:BatchUpdate 时按优先级从高到低排序) + /// Update priority (BatchUpdate processes higher priority first) /// public int Priority { get; set; } = 0; @@ -55,22 +55,42 @@ public class UpdateStrategy public RestartMode RestartMode { get; set; } = RestartMode.Prompt; /// - /// 是否跳过签名验证(仅调试模式) - /// Skip signature validation (debug mode only) + /// 是否跳过签名验证(仅调试会话中生效,见 DrivelutionOptions.DebugModeSkipSignature) + /// Skip signature validation (only honored inside a debug session, see DrivelutionOptions.DebugModeSkipSignature) /// public bool SkipSignatureValidation { get; set; } = false; /// - /// 是否跳过哈希验证(仅调试模式) - /// Skip hash validation (debug mode only) + /// 是否跳过哈希验证(仅调试会话中生效,见 DrivelutionOptions.DebugModeSkipHash) + /// Skip hash validation (only honored inside a debug session, see DrivelutionOptions.DebugModeSkipHash) /// public bool SkipHashValidation { get; set; } = false; /// - /// 超时时间(秒) - /// Timeout (seconds) + /// 超时时间(秒;0 = 使用 DrivelutionOptions.DefaultTimeoutSeconds) + /// Timeout in seconds (0 = use DrivelutionOptions.DefaultTimeoutSeconds) /// - public int TimeoutSeconds { get; set; } = 300; + public int TimeoutSeconds { get; set; } = 0; + + /// + /// 演练模式:只执行权限/兼容性/签名/哈希/版本检查,不做任何系统变更 + /// Dry run: runs permission/compatibility/signature/hash/version checks only, no system changes + /// + public bool DryRun { get; set; } = false; + + /// + /// 安装后验证失败时是否判定更新失败并触发回滚(默认 false:仅记录警告) + /// Whether a failed post-install verification fails the update and triggers rollback + /// (default false: only a warning is logged) + /// + public bool FailOnVerificationFailure { get; set; } = false; + + /// + /// 并行批更新时的最大并发数(Parallel 模式生效;1 等价于顺序执行。驱动安装涉及全局锁,默认保守) + /// Max concurrency for parallel batch updates (Parallel mode; 1 = sequential. Driver installs + /// contend on global locks, so the default is conservative) + /// + public int MaxDegreeOfParallelism { get; set; } = 1; } /// @@ -79,9 +99,9 @@ public class UpdateStrategy /// public enum UpdateMode { - /// 全量更新 / Full update + /// 全量更新(不做版本比较)/ Full update (no version comparison) Full, - /// 增量更新 / Incremental update + /// 增量更新(与已安装版本比较,不更新则跳过)/ Incremental update (compare with installed version, skip when not newer) Incremental } @@ -93,7 +113,7 @@ public enum RestartMode { /// 不需要重启 / No restart required None, - /// 提示用户重启 / Prompt user to restart + /// 提示用户重启(通过 RestartPromptCallback 回调,结果记录在 UpdateResult.RestartRequired)/ Prompt user to restart (via RestartPromptCallback; outcome recorded in UpdateResult.RestartRequired) Prompt, /// 延迟重启 / Delayed restart Delayed, diff --git a/src/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs b/src/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs index a1ef2712..84426a7d 100644 --- a/src/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs +++ b/src/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs @@ -3,14 +3,14 @@ using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Core.Execution; +using GeneralUpdate.Drivelution.Core.Network; using GeneralUpdate.Drivelution.Windows.Implementation; using GeneralUpdate.Drivelution.Linux.Implementation; -using GeneralUpdate.Drivelution.MacOS.Implementation; namespace GeneralUpdate.Drivelution.Core; /// -/// 驱动更新器工厂类 - 自动检测平台并创建相应的实现 +/// 驱动更新器工厂类 - 自动检测平台并创建相应的实现(Windows / Linux) /// Driver updater factory - Automatically detects platform and creates appropriate implementation /// public static class DrivelutionFactory @@ -21,9 +21,11 @@ public static class DrivelutionFactory /// /// 配置选项(可选)/ Configuration options (optional) /// 平台特定的驱动更新器实现 / Platform-specific driver updater implementation - /// 当前平台不支持时抛出 / Thrown when current platform is not supported + /// 当前平台不支持时抛出(支持 Windows、Linux)/ Thrown when current platform is not supported (Windows and Linux are supported) public static IGeneralDrivelution Create(DrivelutionOptions? options = null) { + var downloader = new HttpNetworkDownloader(options?.NetworkProxy ?? string.Empty); + // Detect platform and create appropriate implementation if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -31,23 +33,15 @@ public static IGeneralDrivelution Create(DrivelutionOptions? options = null) var validator = new WindowsDriverValidator(); var backup = new WindowsDriverBackup(); var commandRunner = new CommandRunner(); - return new WindowsGeneralDrivelution(validator, backup, commandRunner, options); + return new WindowsGeneralDrivelution(validator, backup, commandRunner, options, downloader); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { GeneralTracer.Info("Detected Linux platform, creating LinuxGeneralDrivelution"); - var validator = new LinuxDriverValidator(); + var validator = new LinuxDriverValidator(new CommandRunner(), options); var backup = new LinuxDriverBackup(); var commandRunner = new CommandRunner(); - return new LinuxGeneralDrivelution(validator, backup, commandRunner, options); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - GeneralTracer.Info("Detected macOS platform, creating MacOsGeneralDrivelution"); - var validator = new MacOSDriverValidator(); - var backup = new MacOSDriverBackup(); - var commandRunner = new CommandRunner(); - return new MacOsGeneralDrivelution(validator, backup, commandRunner, options); + return new LinuxGeneralDrivelution(validator, backup, commandRunner, options, downloader); } else { @@ -55,7 +49,7 @@ public static IGeneralDrivelution Create(DrivelutionOptions? options = null) GeneralTracer.Error($"Unsupported platform detected: {osDescription}"); throw new PlatformNotSupportedException( $"Current platform '{osDescription}' is not supported. " + - "Supported platforms: Windows, Linux, macOS."); + "Supported platforms: Windows, Linux."); } } @@ -64,7 +58,7 @@ public static IGeneralDrivelution Create(DrivelutionOptions? options = null) /// Creates a driver validator suitable for the current platform /// /// 平台特定的驱动验证器实现 / Platform-specific driver validator implementation - public static IDriverValidator CreateValidator() + public static IDriverValidator CreateValidator(DrivelutionOptions? options = null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -72,11 +66,7 @@ public static IDriverValidator CreateValidator() } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - return new LinuxDriverValidator(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return new MacOSDriverValidator(new CommandRunner()); + return new LinuxDriverValidator(new CommandRunner(), options); } else { @@ -99,10 +89,6 @@ public static IDriverBackup CreateBackup() { return new LinuxDriverBackup(); } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return new MacOSDriverBackup(); - } else { throw new PlatformNotSupportedException($"Platform not supported: {RuntimeInformation.OSDescription}"); @@ -127,14 +113,13 @@ public static string GetCurrentPlatform() } /// - /// 检查当前平台是否支持 - /// Checks if the current platform is supported + /// 检查当前平台是否支持(Windows / Linux;macOS 已不再支持) + /// Checks if the current platform is supported (Windows / Linux; macOS is no longer supported) /// /// 是否支持 / Whether supported public static bool IsPlatformSupported() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || - RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || - RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + RuntimeInformation.IsOSPlatform(OSPlatform.Linux); } } diff --git a/src/GeneralUpdate.Drivelution/Core/Execution/CommandExecutionException.cs b/src/GeneralUpdate.Drivelution/Core/Execution/CommandExecutionException.cs new file mode 100644 index 00000000..fc12d4a5 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Core/Execution/CommandExecutionException.cs @@ -0,0 +1,49 @@ +namespace GeneralUpdate.Drivelution.Core.Execution; + +/// +/// Thrown when an external command exits with a non-zero exit code. +/// Marked retryable: command failures are usually transient (locks, races with other installers), +/// and the retry policy's default predicate consults this flag. +/// +public class CommandExecutionException : Exception +{ + /// + /// The executable that failed. + /// + public string Command { get; } + + /// + /// Process exit code. + /// + public int ExitCode { get; } + + /// + /// Standard output captured before the failure. + /// + public string StandardOutput { get; } + + /// + /// Standard error captured before the failure. + /// + public string StandardError { get; } + + /// + /// Whether retrying the command may help (default true). + /// + public bool CanRetry { get; } + + public CommandExecutionException( + string command, + int exitCode, + string standardOutput, + string standardError, + bool canRetry = true) + : base($"Command '{command}' failed with exit code {exitCode}. Error: {standardError.Trim()}") + { + Command = command; + ExitCode = exitCode; + StandardOutput = standardOutput; + StandardError = standardError; + CanRetry = canRetry; + } +} diff --git a/src/GeneralUpdate.Drivelution/Core/Execution/CommandRunner.cs b/src/GeneralUpdate.Drivelution/Core/Execution/CommandRunner.cs index 89ee806c..f04163d4 100644 --- a/src/GeneralUpdate.Drivelution/Core/Execution/CommandRunner.cs +++ b/src/GeneralUpdate.Drivelution/Core/Execution/CommandRunner.cs @@ -15,7 +15,8 @@ public class CommandRunner : ICommandRunner public async Task RunAsync( string command, string[] arguments, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default, + TimeSpan? timeout = null) { var psi = new ProcessStartInfo { @@ -34,18 +35,21 @@ public async Task RunAsync( using var process = new Process { StartInfo = psi }; + // stdout/stderr events arrive on separate thread-pool threads; guard all appends + // (StringBuilder is not thread-safe). + var outputLock = new object(); var stdout = new StringBuilder(); var stderr = new StringBuilder(); process.OutputDataReceived += (_, e) => { - if (e.Data is not null) - stdout.AppendLine(e.Data); + if (e.Data is null) return; + lock (outputLock) stdout.AppendLine(e.Data); }; process.ErrorDataReceived += (_, e) => { - if (e.Data is not null) - stderr.AppendLine(e.Data); + if (e.Data is null) return; + lock (outputLock) stderr.AppendLine(e.Data); }; if (!process.Start()) @@ -54,25 +58,50 @@ public async Task RunAsync( process.BeginOutputReadLine(); process.BeginErrorReadLine(); + using var timeoutCts = timeout is { TotalMilliseconds: > 0 } + ? new CancellationTokenSource(timeout.Value) + : null; + using var linkedCts = timeoutCts is not null + ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token) + : null; + var waitToken = linkedCts?.Token ?? cancellationToken; + // Ensure the process is killed if the caller cancels the wait - await using (cancellationToken.Register(() => + await using (waitToken.Register(() => { try { process.Kill(entireProcessTree: true); } catch { /* already exited */ } })) { - await process.WaitForExitAsync(cancellationToken); + try + { + await process.WaitForExitAsync(waitToken); + } + catch (OperationCanceledException) + { + // Which token fired decides between the exceptions (see ThrowIfPreempted). + ThrowIfPreempted(cancellationToken, timeoutCts, command, timeout); + throw; + } } - // The kill-vs-exit observation is racy: WaitForExitAsync can return normally - // for a process that was just killed by cancellation. A cancelled wait always - // means "preempted" — surface it as OperationCanceledException deterministically. - cancellationToken.ThrowIfCancellationRequested(); + // How the wait ended says nothing about why: the kill callback above can make + // WaitForExitAsync return normally for a process that was just killed, just as it can + // make it throw OperationCanceledException. The token states are the reliable signal — + // surface the preemption deterministically, caller cancellation first. + ThrowIfPreempted(cancellationToken, timeoutCts, command, timeout); + + string outText, errText; + lock (outputLock) + { + outText = stdout.ToString(); + errText = stderr.ToString(); + } return new CommandResult { ExitCode = process.ExitCode, - StandardOutput = stdout.ToString(), - StandardError = stderr.ToString() + StandardOutput = outText, + StandardError = errText }; } @@ -80,17 +109,47 @@ public async Task RunAsync( public async Task RunOrThrowAsync( string command, string[] arguments, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default, + TimeSpan? timeout = null) { - var result = await RunAsync(command, arguments, cancellationToken); + var result = await RunAsync(command, arguments, cancellationToken, timeout); if (!result.Success) { - throw new InvalidOperationException( - $"Command '{command}' failed with exit code {result.ExitCode}. " + - $"Error: {result.StandardError.Trim()}"); + throw new CommandExecutionException( + command, + result.ExitCode, + result.StandardOutput, + result.StandardError); } return result; } + + /// + /// Throws for a wait that was preempted and returns otherwise: with + /// when the caller cancelled, which takes precedence, + /// and with when the per-command timeout elapsed (the process + /// tree has been killed by then). + /// + /// The caller's token. + /// The timeout's source; null when no timeout applies. + /// The command, for the message and the trace. + /// The per-command timeout, for the message. + internal static void ThrowIfPreempted( + CancellationToken cancellationToken, + CancellationTokenSource? timeoutCts, + string command, + TimeSpan? timeout) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (timeoutCts is { IsCancellationRequested: true }) + { + var seconds = timeout?.TotalSeconds ?? 0; + GeneralTracer.Warn($"CommandRunner: command '{command}' timed out after {seconds:F0}s (process tree killed)."); + throw new TimeoutException( + $"Command '{command}' timed out after {seconds:F0} seconds."); + } + } } diff --git a/src/GeneralUpdate.Drivelution/Core/Execution/ICommandRunner.cs b/src/GeneralUpdate.Drivelution/Core/Execution/ICommandRunner.cs index d7af088f..e1b18fd2 100644 --- a/src/GeneralUpdate.Drivelution/Core/Execution/ICommandRunner.cs +++ b/src/GeneralUpdate.Drivelution/Core/Execution/ICommandRunner.cs @@ -12,23 +12,30 @@ public interface ICommandRunner /// Executable name or path. /// Arguments passed individually (not shell-parsed). /// Cancellation token. + /// Optional per-command timeout. When it elapses the process tree is killed + /// and a is thrown. The overall pipeline timeout still applies. /// A containing exit code, stdout, and stderr. /// Thrown when the process cannot be started. + /// Thrown when the per-command timeout elapses. Task RunAsync( string command, string[] arguments, - CancellationToken cancellationToken = default); + CancellationToken cancellationToken = default, + TimeSpan? timeout = null); /// - /// Runs a command and throws if the exit code is non-zero. + /// Runs a command and throws a if the exit code is non-zero. /// /// Executable name or path. /// Arguments passed individually. /// Cancellation token. + /// Optional per-command timeout. /// A successful . - /// Thrown when the process exits with a non-zero code. + /// Thrown when the process exits with a non-zero code. + /// Thrown when the per-command timeout elapses. Task RunOrThrowAsync( string command, string[] arguments, - CancellationToken cancellationToken = default); + CancellationToken cancellationToken = default, + TimeSpan? timeout = null); } diff --git a/src/GeneralUpdate.Drivelution/Core/Network/HttpNetworkDownloader.cs b/src/GeneralUpdate.Drivelution/Core/Network/HttpNetworkDownloader.cs new file mode 100644 index 00000000..170b988f --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Core/Network/HttpNetworkDownloader.cs @@ -0,0 +1,310 @@ +using System.Net; +using System.Net.Http; +using System.Security.Cryptography; +using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution; + +namespace GeneralUpdate.Drivelution.Core.Network; + +/// +/// Default based on HttpClient. +/// Features: mirror fallback (primary URL first, mirrors in order), resume of partial downloads +/// via HTTP Range, proxy support (http/https/socks5/socks5h), post-download SHA256 verification, +/// and cancellation (token or CancelDownload()). +/// +public class HttpNetworkDownloader : INetworkDownloader +{ + private readonly HttpClient _httpClient; + private readonly bool _ownsHttpClient; + private CancellationTokenSource _cancelCts = new(); + + /// + /// Creates a downloader with a fresh HttpClient. + /// + /// Proxy address: http://host:port, https://host:port, socks5://host:port or + /// socks5h://host:port (remote DNS). Empty = direct connection. + public HttpNetworkDownloader(string proxy = "") + : this(CreateHttpClient(proxy), ownsHttpClient: true) + { + } + + /// + /// Creates a downloader over a caller-supplied HttpClient (not disposed by this instance). + /// + public HttpNetworkDownloader(HttpClient httpClient) + : this(httpClient, ownsHttpClient: false) + { + } + + private HttpNetworkDownloader(HttpClient httpClient, bool ownsHttpClient) + { + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _ownsHttpClient = ownsHttpClient; + } + + /// + public void CancelDownload() + { + try + { + _cancelCts.Cancel(); + } + catch (ObjectDisposedException) + { + // A download already finished and reset the CTS — nothing to cancel. + } + } + + /// + public async Task DownloadAsync( + NetworkDownloadRequest request, + IProgress? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + + if (string.IsNullOrWhiteSpace(request.Url)) + throw new ArgumentException("Download URL must not be empty.", nameof(request)); + + if (string.IsNullOrWhiteSpace(request.TargetDirectory)) + throw new ArgumentException("Target directory must not be empty.", nameof(request)); + + ValidateUrlSecurity(request.Url); + if (request.MirrorUrls is not null) + { + foreach (var mirror in request.MirrorUrls) + ValidateUrlSecurity(mirror); + } + + Directory.CreateDirectory(request.TargetDirectory); + + var urls = new List { request.Url }; + if (request.MirrorUrls is not null) + urls.AddRange(request.MirrorUrls); + + Exception? lastError = null; + foreach (var url in urls) + { + // Fresh cancellation scope per attempt; user cancellation still flows through. + _cancelCts.Dispose(); + _cancelCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + try + { + var path = await DownloadSingleAsync(request, url, progress, _cancelCts.Token); + return path; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; // user cancellation or CancelDownload during shutdown — do not try mirrors + } + catch (Exception ex) + { + lastError = ex; + GeneralTracer.Warn($"HttpNetworkDownloader: download failed from '{url}'. {ex.Message}"); + } + } + + throw new InvalidOperationException( + $"All download URLs failed ({urls.Count} attempted). Last error: {lastError?.Message}", lastError); + } + + private async Task DownloadSingleAsync( + NetworkDownloadRequest request, + string url, + IProgress? progress, + CancellationToken cancellationToken) + { + var fileName = GetTargetFileName(url, request.ExpectedSha256); + var targetPath = Path.Combine(request.TargetDirectory, fileName); + var partPath = targetPath + ".part"; + + long existingLength = 0; + if (request.Resume && File.Exists(partPath)) + { + existingLength = new FileInfo(partPath).Length; + GeneralTracer.Info($"HttpNetworkDownloader: resuming '{url}' from {existingLength} bytes."); + } + else if (File.Exists(partPath)) + { + File.Delete(partPath); + } + + using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url); + if (existingLength > 0) + requestMessage.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(existingLength, null); + + // Caller-supplied headers (auth tokens etc.) apply to the primary URL and every mirror. + if (request.Headers is not null) + { + foreach (var (name, value) in request.Headers) + { + if (!string.IsNullOrWhiteSpace(name)) + requestMessage.Headers.TryAddWithoutValidation(name, value); + } + } + + using var response = await _httpClient.SendAsync( + requestMessage, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken); + + long totalBytes; + bool appending; + + if (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && existingLength > 0) + { + // The partial file already covers the full content. + FinalizeDownload(partPath, targetPath, request.ExpectedSha256, progress); + return targetPath; + } + + if ((int)response.StatusCode >= 300) + throw new InvalidOperationException($"HTTP {(int)response.StatusCode} {response.ReasonPhrase} from '{url}'."); + + if (response.Content.Headers.ContentRange is { } range && range.Length.HasValue) + { + totalBytes = range.Length.Value; + appending = existingLength > 0 && range.From is > 0; + } + else + { + totalBytes = response.Content.Headers.ContentLength ?? -1; + appending = false; + // Server ignored the Range header — start over. + if (existingLength > 0) + { + existingLength = 0; + File.Delete(partPath); + } + } + + await using (var contentStream = await response.Content.ReadAsStreamAsync(cancellationToken)) + await using (var fileStream = new FileStream( + partPath, + appending ? FileMode.Append : FileMode.Create, + FileAccess.Write, + FileShare.None, + bufferSize: 81920, + useAsync: true)) + { + var buffer = new byte[81920]; + long written = appending ? existingLength : 0; + int read; + + while ((read = await contentStream.ReadAsync(buffer, cancellationToken)) > 0) + { + await fileStream.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + written += read; + + if (progress is not null && totalBytes > 0) + progress.Report(Math.Min(written * 100.0 / totalBytes, 100.0)); + } + } + + FinalizeDownload(partPath, targetPath, request.ExpectedSha256, progress); + GeneralTracer.Info($"HttpNetworkDownloader: downloaded '{url}' -> '{targetPath}'."); + return targetPath; + } + + private static void FinalizeDownload( + string partPath, + string targetPath, + string? expectedSha256, + IProgress? progress) + { + if (expectedSha256 is not null) + { + var actual = ComputeSha256(partPath); + if (!string.Equals(actual, expectedSha256.Trim(), StringComparison.OrdinalIgnoreCase)) + { + File.Delete(partPath); + throw new DriverValidationException( + $"Downloaded file hash mismatch. Expected {expectedSha256}, actual {actual}.", + "Integrity"); + } + } + + File.Move(partPath, targetPath, overwrite: true); + progress?.Report(100.0); + } + + private static string ComputeSha256(string filePath) + { + using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); + } + + private static string GetTargetFileName(string url, string? expectedSha256) + { + string? name = null; + if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) + name = uri.Segments is { Length: > 0 } && uri.Segments[^1] != "/" ? Uri.UnescapeDataString(uri.Segments[^1]) : null; + + if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) + { + // No usable file name in the URL — derive a stable one. + var suffix = string.IsNullOrEmpty(expectedSha256) ? "package" : expectedSha256[..Math.Min(12, expectedSha256.Length)]; + name = $"driver_{suffix}.bin"; + } + + return name; + } + + private static void ValidateUrlSecurity(string url) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || + (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + throw new ArgumentException($"Download URL must be an absolute http(s) URL: '{url}'."); + } + + if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6) + { + // Allow public IPs implicitly; block obvious loopback/link-local targets to avoid SSRF-style misuse. + var ip = IPAddress.Parse(uri.Host); + if (IPAddress.IsLoopback(ip) || ip.Equals(IPAddress.IPv6Loopback)) + throw new ArgumentException($"Download URL must not point to a loopback address: '{url}'."); + } + } + + private static HttpClient CreateHttpClient(string proxy) + { + var handler = new SocketsHttpHandler + { + AllowAutoRedirect = true, + AutomaticDecompression = DecompressionMethods.All + }; + + if (!string.IsNullOrWhiteSpace(proxy)) + { + handler.Proxy = CreateProxy(proxy); + handler.UseProxy = true; + } + + var client = new HttpClient(handler, disposeHandler: true) + { + Timeout = TimeSpan.FromMinutes(30) + }; + return client; + } + + private static IWebProxy CreateProxy(string proxy) + { + // socks5h means "resolve DNS remotely" — .NET's socks support already does remote + // resolution, so normalize the scheme for WebProxy. + var normalized = proxy.Trim(); + if (normalized.StartsWith("socks5h://", StringComparison.OrdinalIgnoreCase)) + normalized = "socks5://" + normalized["socks5h://".Length..]; + + if (!Uri.TryCreate(normalized, UriKind.Absolute, out var proxyUri) || + (proxyUri.Scheme != "http" && proxyUri.Scheme != "https" && proxyUri.Scheme != "socks5" && proxyUri.Scheme != "socks4")) + { + throw new ArgumentException( + $"Invalid proxy address '{proxy}'. Supported: http://, https://, socks4://, socks5:// (socks5h:// accepted as socks5://)."); + } + + return new WebProxy(proxyUri); + } +} diff --git a/src/GeneralUpdate.Drivelution/Core/Pipeline/BaseDriverUpdater.cs b/src/GeneralUpdate.Drivelution/Core/Pipeline/BaseDriverUpdater.cs index b7e5d88f..02b60421 100644 --- a/src/GeneralUpdate.Drivelution/Core/Pipeline/BaseDriverUpdater.cs +++ b/src/GeneralUpdate.Drivelution/Core/Pipeline/BaseDriverUpdater.cs @@ -3,13 +3,18 @@ using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Abstractions.Exceptions; using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Execution; +using GeneralUpdate.Drivelution.Core.Utilities; namespace GeneralUpdate.Drivelution.Core.Pipeline; /// /// Abstract base class for platform-specific driver updaters. -/// Provides the unified update pipeline with retry, timeout, progress reporting, and automatic rollback. -/// Subclasses only need to implement . +/// Provides the unified update pipeline with download, version check, retry, timeout, progress +/// reporting, automatic rollback, restart orchestration, and backup maintenance. The rollback +/// runs whenever an update fails, is interrupted or cancelled after its install step began. +/// Subclasses implement , +/// and optionally override verify/backup/rollback hooks. /// public abstract class BaseDriverUpdater : IGeneralDrivelution { @@ -23,8 +28,15 @@ public abstract class BaseDriverUpdater : IGeneralDrivelution /// protected readonly IDriverBackup _backup; - private readonly DrivelutionOptions _options; - private readonly RetryPolicy _retryPolicy; + /// + /// Resolved configuration options (never null). + /// + protected readonly DrivelutionOptions _options; + + /// + /// Optional network downloader (required only when DownloadUrl is used). + /// + protected readonly INetworkDownloader? _downloader; /// /// Initializes a new instance of the class. @@ -32,19 +44,30 @@ public abstract class BaseDriverUpdater : IGeneralDrivelution /// Driver validator for integrity, signature, and compatibility checks. /// Driver backup manager. /// Configuration options (optional). + /// Network downloader for DownloadUrl scenarios (optional). protected BaseDriverUpdater( IDriverValidator validator, IDriverBackup backup, - DrivelutionOptions? options = null) + DrivelutionOptions? options = null, + INetworkDownloader? downloader = null) { _validator = validator ?? throw new ArgumentNullException(nameof(validator)); _backup = backup ?? throw new ArgumentNullException(nameof(backup)); _options = options ?? new DrivelutionOptions(); - _retryPolicy = RetryPolicy.FromOptions(_options); + _downloader = downloader; } // ─── IGeneralDrivelution Implementation ──────────────────────────── + /// + public event Action? OnStepStarted; + + /// + public event Action? OnStepCompleted; + + /// + public event Action? OnUpdateCompleted; + /// public async Task UpdateAsync( DriverInfo driverInfo, @@ -55,36 +78,58 @@ public async Task UpdateAsync( var result = new UpdateResult { StartTime = DateTime.UtcNow, - Status = UpdateStatus.NotStarted + Status = UpdateStatus.NotStarted, + IsDryRun = strategy.DryRun }; result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Starting driver update for {driverInfo.Name} v{driverInfo.Version}"); - var context = new PipelineContext(driverInfo, strategy, result); + var context = new PipelineContext(driverInfo, strategy, result, _options, progress) + { + BackupInstalledDriverHook = (driver, dir, ct) => TryBackupInstalledDriverAsync(driver, dir, ct) + }; - // Linked token: user cancellation + timeout + // Timeout: strategy wins, otherwise options default. var timeoutSeconds = strategy.TimeoutSeconds > 0 ? strategy.TimeoutSeconds : _options.DefaultTimeoutSeconds; using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)); - using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( - cancellationToken, timeoutCts.Token); + + // ForceUpdate: the user cancellation token is deliberately not linked — timeout still applies. + var honorUserCancellation = !strategy.ForceUpdate; + using var linkedCts = honorUserCancellation + ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token) + : CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token); + + if (strategy.ForceUpdate && cancellationToken.IsCancellationRequested) + { + // Already cancelled before the run started — respect it, nothing has happened yet. + result.Success = false; + result.Status = UpdateStatus.Cancelled; + result.Error = BuildCancelError(timeoutSeconds); + result.EndTime = DateTime.UtcNow; + return result; + } + + // Per-call retry policy: strategy values win, options provide defaults. + var retryPolicy = RetryPolicy.FromStrategy(strategy, _options); int stepCount = 0; try { GeneralTracer.Info($"Starting driver update: {driverInfo.Name} v{driverInfo.Version} " + - $"(timeout={timeoutSeconds}s, retries={_retryPolicy.MaxRetries})"); + $"(timeout={timeoutSeconds}s, retries={retryPolicy.MaxRetries}, mode={strategy.Mode}, dryRun={strategy.DryRun})"); var steps = GetPipelineSteps(strategy) .Where(s => s.ShouldExecute(context)) .ToList(); stepCount = steps.Count; - var totalSteps = stepCount; int stepIndex = 0; + int executedSteps = 0; PipelineResult? lastStepResult = null; + var skipped = false; foreach (var step in steps) { @@ -95,7 +140,7 @@ public async Task UpdateAsync( { CurrentStatus = UpdateStatus.Updating, StepName = step.StepName, - Percentage = (int)((float)(stepIndex - 1) / totalSteps * 100), + Percentage = (int)((float)(stepIndex - 1) / Math.Max(totalSteps, 1) * 100), Message = $"Running: {step.StepName}", StepIndex = stepIndex - 1, TotalSteps = totalSteps @@ -104,27 +149,53 @@ public async Task UpdateAsync( // Execute step with retry on transient failures try { - lastStepResult = await _retryPolicy.ExecuteAsync( + lastStepResult = await retryPolicy.ExecuteAsync( ct => step.ExecuteAsync(context, ct), linkedCts.Token); } catch (OperationCanceledException) { + var userCancelled = honorUserCancellation && cancellationToken.IsCancellationRequested; result.Success = false; - result.Status = UpdateStatus.Failed; - result.Error = new ErrorInfo + result.Status = userCancelled ? UpdateStatus.Cancelled : UpdateStatus.Failed; + + if (userCancelled) { - Type = ErrorType.Timeout, - Code = "ERR_TIMEOUT", - Message = $"Driver update timed out after {timeoutSeconds} seconds.", - CanRetry = true, - Timestamp = DateTime.UtcNow - }; - result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] TIMEOUT: operation exceeded {timeoutSeconds}s"); + result.Error = BuildCancelError(timeoutSeconds); + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] CANCELLED by user at step '{step.StepName}'"); + GeneralTracer.Info($"Driver update cancelled by user: {driverInfo.Name}"); + } + else + { + result.Error = BuildTimeoutError(timeoutSeconds); + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] TIMEOUT: operation exceeded {timeoutSeconds}s"); + GeneralTracer.Error($"Driver update timed out: {driverInfo.Name}"); + } + + // The step was cut short; what the update had changed so far is undone. + await TryRollbackAsync(context, result, strategy); + result.EndTime = DateTime.UtcNow; - GeneralTracer.Error($"Driver update timed out: {driverInfo.Name}"); return result; } + catch (Exception ex) + { + // A step that throws failed just like one that returns Fail, and gets the + // same rollback. The exception itself still reaches the handler below, so + // the error it carries is what gets reported. + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] FAILED at step '{step.StepName}': {ex.Message}"); + await TryRollbackAsync(context, result, strategy); + throw; + } + + executedSteps++; + + if (lastStepResult.Skipped) + { + skipped = true; + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] SKIPPED at step '{step.StepName}': {lastStepResult.ErrorMessage}"); + break; + } if (!lastStepResult.Success) { @@ -136,14 +207,46 @@ public async Task UpdateAsync( OnStepCompleted?.Invoke(step.StepName); } - // Check if all steps passed - if (lastStepResult?.Success == true) + if (skipped) + { + result.Success = true; + result.Status = UpdateStatus.Skipped; + result.Message = lastStepResult?.ErrorMessage ?? "Update skipped"; + result.InstalledVersion = driverInfo.Version; + GeneralTracer.Info($"Driver update skipped: {driverInfo.Name}. {result.Message}"); + } + else if (executedSteps == 0) + { + // No steps ran at all (e.g. everything filtered) — nothing happened. + result.Success = true; + result.Status = strategy.DryRun + ? UpdateStatus.DryRunCompleted + : UpdateStatus.Succeeded; + result.Message = "No pipeline steps were executed"; + } + else if (lastStepResult?.Success == true) { result.Success = true; - result.Status = UpdateStatus.Succeeded; + result.InstalledVersion = driverInfo.Version; result.Message = "Driver update completed successfully"; result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Update completed successfully"); GeneralTracer.Info($"Driver update completed successfully: {driverInfo.Name}"); + + if (strategy.DryRun) + { + result.Status = UpdateStatus.DryRunCompleted; + result.Message = "Dry run completed - no changes were made"; + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Dry run completed - no changes were made"); + } + else + { + result.RestartRequired = GetRestartRequired(context) || strategy.RestartMode == RestartMode.Immediate; + + await HandleRestartAsync(strategy, result); + await CleanupBackupsAsync(context, result); + + result.Status = result.RestartRequired ? UpdateStatus.RestartRequired : UpdateStatus.Succeeded; + } } else { @@ -163,29 +266,16 @@ public async Task UpdateAsync( }; } - // Attempt rollback if backup exists - var backupPath = result.BackupPath; - context.Bag.TryGetValue("BackupPath", out var bagPath); - backupPath ??= bagPath?.ToString(); - - if (!string.IsNullOrEmpty(backupPath)) + // A failed step gets the update rolled back from its backup. + if (await TryRollbackAsync(context, result, strategy)) { - result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Attempting rollback"); - - // Use a fresh CancellationToken for rollback — the linked token may be cancelled by timeout - var rolledBack = await TryRollbackAsync(backupPath, CancellationToken.None); - if (rolledBack) - { - result.RolledBack = true; - result.Status = UpdateStatus.RolledBack; - result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Rollback completed"); - } + result.Status = UpdateStatus.RolledBack; } } } catch (Exception ex) { - GeneralTracer.Error($"Unexpected error during driver update: {ex}", ex); + GeneralTracer.Error($"Driver update failed at a pipeline step: {ex}", ex); result.Success = false; result.Status = UpdateStatus.Failed; result.Error = MapExceptionToErrorInfo(ex); @@ -193,15 +283,19 @@ public async Task UpdateAsync( } finally { + // The update is over, whatever its outcome: retention may take the backup again. + context.BackupRetention?.Dispose(); + context.BackupRetention = null; + result.EndTime = DateTime.UtcNow; - GeneralTracer.Info($"Driver update finished. Duration={result.DurationMs}ms, Success={result.Success}"); + GeneralTracer.Info($"Driver update finished. Duration={result.DurationMs}ms, Success={result.Success}, Status={result.Status}"); progress?.Report(new UpdateProgress { CurrentStatus = result.Status, StepName = result.Success ? "Completed" : "Failed", Percentage = 100, - Message = result.Success ? "Driver update completed successfully" : result.Error?.Message ?? "Failed", + Message = result.Success ? result.Message : result.Error?.Message ?? "Failed", StepIndex = stepCount, TotalSteps = stepCount }); @@ -212,6 +306,18 @@ public async Task UpdateAsync( return result; } + /// + public virtual async Task UpdateIfNeededAsync( + DriverInfo driverInfo, + UpdateStrategy? strategy = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + { + strategy ??= new UpdateStrategy(); + strategy.Mode = UpdateMode.Incremental; + return await UpdateAsync(driverInfo, strategy, progress, cancellationToken); + } + /// public async Task ValidateAsync( DriverInfo driverInfo, @@ -234,10 +340,13 @@ public async Task ValidateAsync( } } - if (driverInfo.TrustedPublishers.Count > 0) + if (DefaultPipelineSteps.HasTrustedSigners(driverInfo, _options)) { if (!await _validator.ValidateSignatureAsync( - driverInfo.FilePath, driverInfo.TrustedPublishers, cancellationToken)) + driverInfo.FilePath, + driverInfo.TrustedPublishers, + _options.TrustedCertificateThumbprints, + cancellationToken)) { return false; } @@ -260,7 +369,21 @@ public async Task BackupAsync( { try { - return await _backup.BackupAsync(driverInfo.FilePath, backupPath, cancellationToken); + var ok = await _backup.BackupAsync(driverInfo.FilePath, backupPath, cancellationToken); + if (ok) + { + var manifest = new BackupManifest + { + DriverName = driverInfo.Name, + DriverVersion = driverInfo.Version, + Source = BackupManifest.SourcePackage, + OriginalFilePath = driverInfo.FilePath, + Platform = CompatibilityChecker.GetCurrentOS() + }; + BackupManifestStore.Save(manifest, backupPath); + } + + return ok; } catch (Exception ex) { @@ -274,7 +397,67 @@ public virtual async Task RollbackAsync( string backupPath, CancellationToken cancellationToken = default) { - return await TryRollbackAsync(backupPath, cancellationToken); + try + { + GeneralTracer.Info($"Rolling back from: {backupPath}"); + + if (!Directory.Exists(backupPath)) + { + GeneralTracer.Error($"Backup directory not found: {backupPath}"); + return false; + } + + // Generic manifest-driven restore: copy each backed-up file back to its original + // location. Platform updaters override this for driver-store aware rollback. + var manifest = BackupManifestStore.Load(backupPath); + if (manifest is null) + { + GeneralTracer.Warn($"No backup manifest found in: {backupPath}"); + return false; + } + + var originalDir = Path.GetDirectoryName(manifest.OriginalFilePath); + if (string.IsNullOrEmpty(originalDir)) + { + GeneralTracer.Error($"Cannot determine restore target from '{manifest.OriginalFilePath}'."); + return false; + } + + foreach (var entry in manifest.Files) + { + var sourcePath = Path.Combine(backupPath, entry.RelativePath); + var targetPath = Path.Combine(originalDir, entry.RelativePath); + + Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!); + File.Copy(sourcePath, targetPath, overwrite: true); + GeneralTracer.Info($"Restored {entry.RelativePath}"); + } + + return true; + } + catch (Exception ex) + { + GeneralTracer.Error("Rollback failed", ex); + return false; + } + } + + /// + public abstract Task> GetInstalledDriversAsync(CancellationToken cancellationToken = default); + + /// + public virtual Task> ListBackupsAsync(string? backupRoot = null, CancellationToken cancellationToken = default) + { + var root = Path.GetFullPath(backupRoot ?? _options.DefaultBackupPath); + return Task.Run(() => BackupManifestStore.List(root), cancellationToken); + } + + /// + public virtual Task PurgeBackupsAsync(string? backupRoot = null, int? keep = null, CancellationToken cancellationToken = default) + { + var root = Path.GetFullPath(backupRoot ?? _options.DefaultBackupPath); + var keepCount = keep ?? _options.BackupsToKeep; + return Task.Run(() => BackupManifestStore.Purge(root, keepCount), cancellationToken); } /// @@ -322,55 +505,29 @@ public virtual async Task BatchUpdateAsync( IProgress? progress = null, CancellationToken cancellationToken = default) { - var driverList = drivers.ToList(); + // Higher priority first; OrderBy is stable so equal priorities keep input order. + var driverList = drivers + .Select((driver, index) => (Driver: driver, Index: index)) + .OrderByDescending(x => strategy.Priority + (x.Driver.Metadata.TryGetValue("Priority", out var p) && int.TryParse(p, out var pi) ? pi : 0)) + .ThenBy(x => x.Index) + .Select(x => x.Driver) + .ToList(); + var result = new BatchUpdateResult { Results = new List(driverList.Count) }; var startTime = DateTime.UtcNow; int completed = 0; - GeneralTracer.Info($"Starting batch update: {driverList.Count} driver(s), mode={mode}"); + var maxDop = Math.Max(1, strategy.MaxDegreeOfParallelism); + if (mode == BatchMode.Sequential) + maxDop = 1; - if (mode == BatchMode.Parallel) - { - var tasks = driverList.Select(async (driver, index) => - { - progress?.Report(new UpdateProgress - { - CurrentStatus = UpdateStatus.NotStarted, - StepName = $"Batch [{index + 1}/{driverList.Count}]", - Percentage = 0, - Message = $"Starting: {driver.Name}", - StepIndex = index, - TotalSteps = driverList.Count - }); - - var updateResult = await UpdateAsync(driver, strategy, cancellationToken: cancellationToken); - - var currentCompleted = Interlocked.Increment(ref completed); - progress?.Report(new UpdateProgress - { - CurrentStatus = updateResult.Status, - StepName = $"Batch [{index + 1}/{driverList.Count}]", - Percentage = (int)((float)currentCompleted / driverList.Count * 100), - Message = updateResult.Success ? $"OK: {driver.Name}" : $"FAIL: {driver.Name}", - StepIndex = index, - TotalSteps = driverList.Count - }); - - return new DriverUpdateEntry - { - DriverInfo = driver, - Success = updateResult.Success, - Result = updateResult - }; - }).ToList(); + GeneralTracer.Info($"Starting batch update: {driverList.Count} driver(s), mode={mode}, maxDop={maxDop}"); - var entries = await Task.WhenAll(tasks); - result.Results.AddRange(entries); - } - else + if (maxDop == 1) { for (int i = 0; i < driverList.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var driver = driverList[i]; progress?.Report(new UpdateProgress @@ -404,6 +561,43 @@ public virtual async Task BatchUpdateAsync( }); } } + else + { + using var gate = new SemaphoreSlim(maxDop); + var tasks = driverList.Select(async (driver, index) => + { + await gate.WaitAsync(cancellationToken); + try + { + var updateResult = await UpdateAsync(driver, strategy, cancellationToken: cancellationToken); + + var currentCompleted = Interlocked.Increment(ref completed); + progress?.Report(new UpdateProgress + { + CurrentStatus = updateResult.Status, + StepName = $"Batch [{currentCompleted}/{driverList.Count}]", + Percentage = (int)((float)currentCompleted / driverList.Count * 100), + Message = updateResult.Success ? $"OK: {driver.Name}" : $"FAIL: {driver.Name}", + StepIndex = index, + TotalSteps = driverList.Count + }); + + return new DriverUpdateEntry + { + DriverInfo = driver, + Success = updateResult.Success, + Result = updateResult + }; + } + finally + { + gate.Release(); + } + }).ToList(); + + var entries = await Task.WhenAll(tasks); + result.Results.AddRange(entries); + } result.SucceededCount = result.Results.Count(r => r.Success); result.FailedCount = result.Results.Count(r => !r.Success); @@ -420,14 +614,13 @@ public virtual async Task BatchUpdateAsync( /// /// Platform-specific driver installation logic. Subclasses must implement this. + /// Steps communicate through the context bag (e.g. set RestartRequired). /// - /// Driver information. - /// Update strategy. + /// Pipeline context. /// Cancellation token. /// Thrown when installation fails. protected abstract Task InstallCoreAsync( - DriverInfo driverInfo, - UpdateStrategy strategy, + PipelineContext context, CancellationToken cancellationToken); /// @@ -438,6 +631,10 @@ protected abstract Task InstallCoreAsync( /// Ordered pipeline steps. protected virtual IEnumerable GetPipelineSteps(UpdateStrategy strategy) { + if (_downloader is not null) + yield return DefaultPipelineSteps.CreateDownloadStep(_downloader); + + yield return DefaultPipelineSteps.CreateVersionCheckStep(GetInstalledDriversAsync); yield return DefaultPipelineSteps.CreateValidateStep(_validator); yield return DefaultPipelineSteps.CreateBackupStep(_backup); yield return DefaultPipelineSteps.CreateInstallStep(InstallCoreAsync); @@ -449,12 +646,25 @@ protected virtual IEnumerable GetPipelineSteps(UpdateStrategy str /// Subclasses can override to provide platform-specific verification. /// protected virtual Task VerifyInstallationAsync( - DriverInfo driverInfo, + PipelineContext context, CancellationToken cancellationToken) { return Task.FromResult(true); } + /// + /// Platform hook invoked by the backup step: exports the currently installed driver package + /// into the given directory. Returns false when unsupported or no installed driver matches — + /// the pipeline then backs up the local package files instead. + /// + protected virtual Task TryBackupInstalledDriverAsync( + DriverInfo driverInfo, + string backupDirectory, + CancellationToken cancellationToken) + { + return Task.FromResult(false); + } + /// /// Returns the default file search pattern for the current platform. /// @@ -462,6 +672,8 @@ protected virtual Task VerifyInstallationAsync( /// /// Parses driver information from a file. Subclasses should override for platform-specific formats. + /// Note: the returned DriverInfo must NOT set from the file itself — + /// self-computed hashes validate nothing. Use if needed. /// protected virtual DriverInfo? ParseDriverFromFile(string filePath) { @@ -476,48 +688,150 @@ protected virtual Task VerifyInstallationAsync( // ─── Events ──────────────────────────────────────────────────────── /// - /// Raised when a pipeline step starts executing. + /// Raises . /// - public event Action? OnStepStarted; + protected virtual void RaiseStepStarted(string stepName) => OnStepStarted?.Invoke(stepName); /// - /// Raised when a pipeline step completes successfully. + /// Raises . /// - public event Action? OnStepCompleted; + protected virtual void RaiseStepCompleted(string stepName) => OnStepCompleted?.Invoke(stepName); /// - /// Raised when the entire update process completes. + /// Raises . /// - public event Action? OnUpdateCompleted; + protected virtual void RaiseUpdateCompleted(UpdateResult result) => OnUpdateCompleted?.Invoke(result); // ─── Helpers ─────────────────────────────────────────────────────── + private bool GetRestartRequired(PipelineContext context) + { + return context.Bag.TryGetValue("RestartRequired", out var value) && value is true; + } + + private async Task HandleRestartAsync(UpdateStrategy strategy, UpdateResult result) + { + if (strategy.RestartMode == RestartMode.None) + return; + + try + { + var restarted = await RestartHelper.HandleRestartAsync( + strategy.RestartMode, + _options.RestartCallback, + _options.RestartPromptCallback, + delaySeconds: 30, + message: result.RestartRequired + ? "Driver update requires a system restart to complete." + : $"Driver update completed; restart configured for {driverModeName(strategy.RestartMode)}.", + CancellationToken.None); + + if (restarted) + { + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Restart initiated ({strategy.RestartMode})"); + } + else if (strategy.RestartMode == RestartMode.Prompt && _options.RestartPromptCallback is not null) + { + // The consumer asked the user and the user postponed — keep the flag set so the + // application can surface a "restart pending" banner later. + result.RestartRequired = true; + } + } + catch (Exception ex) + { + GeneralTracer.Warn($"Restart handling failed: {ex.Message}"); + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] WARNING: restart handling failed - {ex.Message}"); + } + } + + private static string driverModeName(RestartMode mode) => mode.ToString(); + /// - /// Attempts to roll back the driver to the given backup path. + /// Undoes an update that failed, was interrupted or cancelled once its install step had + /// begun, from the backup the update made. Returns whether the rollback succeeded; a + /// rollback that itself throws is traced and reported as a failed one, so it never hides + /// the failure that caused it. /// - protected virtual async Task TryRollbackAsync( - string backupPath, - CancellationToken cancellationToken) + private async Task TryRollbackAsync(PipelineContext context, UpdateResult result, UpdateStrategy strategy) { - try + if (strategy.DryRun || !context.InstallStarted) + return false; + + var backupPath = result.BackupPath; + if (string.IsNullOrEmpty(backupPath) && context.Bag.TryGetValue("BackupPath", out var bagPath)) + backupPath = bagPath?.ToString(); + if (string.IsNullOrEmpty(backupPath)) { - GeneralTracer.Info($"Rolling back from: {backupPath}"); + GeneralTracer.Warn($"Cannot roll back the driver update of {context.DriverInfo.Name}: no backup was made."); + return false; + } - if (!Directory.Exists(backupPath)) + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Attempting rollback"); + GeneralTracer.Warn($"Rolling back the driver update of {context.DriverInfo.Name} from {backupPath}."); + + try + { + // A fresh token: the linked one may be cancelled by the very timeout being handled. + if (await RollbackAsync(backupPath, CancellationToken.None)) { - GeneralTracer.Error($"Backup directory not found: {backupPath}"); - return false; + result.RolledBack = true; + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Rollback completed"); + GeneralTracer.Info($"Rollback of the driver update of {context.DriverInfo.Name} completed."); + return true; } - return true; + GeneralTracer.Error( + $"Rollback of the driver update of {context.DriverInfo.Name} failed; the system may be left with a partially applied update."); } catch (Exception ex) { - GeneralTracer.Error("Rollback failed", ex); - return false; + GeneralTracer.Error($"Rollback of the driver update of {context.DriverInfo.Name} threw an exception.", ex); + } + + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Rollback failed"); + return false; + } + + private async Task CleanupBackupsAsync(PipelineContext context, UpdateResult result) + { + if (!_options.AutoCleanupBackups) + return; + + try + { + var root = DefaultPipelineSteps.ResolveBackupRoot(context); + var purged = BackupManifestStore.Purge(root, _options.BackupsToKeep); + if (purged > 0) + result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Cleaned up {purged} old backup(s)"); + } + catch (Exception ex) + { + GeneralTracer.Warn($"Backup cleanup failed: {ex.Message}"); } + + await Task.CompletedTask; } + private static ErrorInfo BuildTimeoutError(int timeoutSeconds) => new() + { + Type = ErrorType.Timeout, + Code = "ERR_TIMEOUT", + Message = $"Driver update timed out after {timeoutSeconds} seconds.", + CanRetry = true, + SuggestedResolution = "Increase the timeout value in UpdateStrategy.TimeoutSeconds or in DrivelutionOptions.DefaultTimeoutSeconds.", + Timestamp = DateTime.UtcNow + }; + + private static ErrorInfo BuildCancelError(int timeoutSeconds) => new() + { + Type = ErrorType.UserCancelled, + Code = "ERR_CANCELLED", + Message = "Driver update was cancelled by the user.", + CanRetry = true, + SuggestedResolution = "The operation was cancelled; start it again if this was not intended.", + Timestamp = DateTime.UtcNow + }; + /// /// Maps an exception to a structured object. /// @@ -532,7 +846,8 @@ protected virtual ErrorInfo MapExceptionToErrorInfo(Exception ex) DriverInstallationException dex => dex.CanRetry ? "ERR_INSTALL_RETRY" : "ERR_INSTALL", DriverBackupException => "ERR_BACKUP", DriverRollbackException => "ERR_ROLLBACK", - OperationCanceledException => "ERR_TIMEOUT", + TimeoutException => "ERR_TIMEOUT", + OperationCanceledException => "ERR_CANCELLED", _ => "ERR_UNKNOWN" }, Type = ex switch @@ -541,14 +856,21 @@ protected virtual ErrorInfo MapExceptionToErrorInfo(Exception ex) DriverValidationException => ErrorType.HashValidationFailed, DriverBackupException => ErrorType.BackupFailed, DriverRollbackException => ErrorType.RollbackFailed, - OperationCanceledException => ErrorType.Timeout, + TimeoutException => ErrorType.Timeout, + OperationCanceledException => ErrorType.UserCancelled, _ => ErrorType.Unknown }, Message = ex.Message, Details = ex.ToString(), StackTrace = ex.StackTrace, Timestamp = DateTime.UtcNow, - CanRetry = ex is DriverInstallationException die && die.CanRetry, + CanRetry = ex switch + { + DriverInstallationException die => die.CanRetry, + CommandExecutionException cex => cex.CanRetry, + OperationCanceledException => true, + _ => false + }, SuggestedResolution = GetSuggestedResolution(ex) }; } @@ -560,7 +882,8 @@ private static string GetSuggestedResolution(Exception ex) DriverPermissionException => "Restart the application with administrator/root privileges.", DriverValidationException dv => $"Check the driver file integrity and retry. Details: {dv.Message}", DriverInstallationException => "Verify the driver is compatible with your system and try again.", - OperationCanceledException => "Increase the timeout value in UpdateStrategy.TimeoutSeconds.", + TimeoutException => "Increase the timeout value in UpdateStrategy.TimeoutSeconds or in DrivelutionOptions.DefaultTimeoutSeconds.", + OperationCanceledException => "The operation was cancelled; start it again if this was not intended.", _ => "Check logs for details and retry." }; } diff --git a/src/GeneralUpdate.Drivelution/Core/Pipeline/DefaultPipelineSteps.cs b/src/GeneralUpdate.Drivelution/Core/Pipeline/DefaultPipelineSteps.cs index 6cdf788c..e793f30f 100644 --- a/src/GeneralUpdate.Drivelution/Core/Pipeline/DefaultPipelineSteps.cs +++ b/src/GeneralUpdate.Drivelution/Core/Pipeline/DefaultPipelineSteps.cs @@ -1,6 +1,9 @@ +using System.Diagnostics; using GeneralUpdate.Drivelution; using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Network; using GeneralUpdate.Drivelution.Core.Utilities; namespace GeneralUpdate.Drivelution.Core.Pipeline; @@ -10,8 +13,142 @@ namespace GeneralUpdate.Drivelution.Core.Pipeline; /// internal static class DefaultPipelineSteps { + /// + /// Creates the download step: fetches the driver package when only a DownloadUrl is supplied. + /// + public static IPipelineStep CreateDownloadStep(INetworkDownloader downloader) + { + return new DelegateStep("Download", + shouldExecute: context => + !context.Strategy.DryRun && + (string.IsNullOrEmpty(context.DriverInfo.FilePath) || !File.Exists(context.DriverInfo.FilePath)) && + (!string.IsNullOrEmpty(context.DriverInfo.DownloadUrl) || context.DriverInfo.MirrorUrls.Count > 0), + execute: async (context, ct) => + { + context.Result.Status = UpdateStatus.Downloading; + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Downloading driver package"); + + var driver = context.DriverInfo; + var request = new NetworkDownloadRequest + { + Url = driver.DownloadUrl, + MirrorUrls = driver.MirrorUrls.Count > 0 ? driver.MirrorUrls : null, + TargetDirectory = Path.GetFullPath(context.Options.DownloadDirectory), + // Server-supplied hash validates the downloaded package (self-computed hashes are ignored). + ExpectedSha256 = IsSha256(driver.HashAlgorithm) && !string.IsNullOrWhiteSpace(driver.Hash) + ? driver.Hash + : null, + Resume = true + }; + + var progress = context.Progress; + IProgress? downloadProgress = null; + if (progress is not null) + { + downloadProgress = new Progress(fraction => + progress.Report(new UpdateProgress + { + CurrentStatus = UpdateStatus.Downloading, + StepName = "Download", + Percentage = (int)fraction, + Message = $"Downloading {Path.GetFileName(driver.DownloadUrl)}: {fraction:F0}%", + StepIndex = 0, + TotalSteps = 0 + })); + } + + var downloadedPath = await downloader.DownloadAsync(request, downloadProgress, ct); + driver.FilePath = downloadedPath; + context.Bag["DownloadedFilePath"] = downloadedPath; + + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Downloaded to {downloadedPath}"); + return PipelineResult.Ok(); + }); + } + + /// + /// Creates the version check step: in Incremental mode, skips the update when the installed + /// driver version is equal or newer. + /// + public static IPipelineStep CreateVersionCheckStep( + Func>> installedLookup) + { + return new DelegateStep("CheckVersion", + shouldExecute: context => context.Strategy.Mode == UpdateMode.Incremental, + execute: async (context, ct) => + { + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Checking installed driver version"); + + var driver = context.DriverInfo; + var installed = await installedLookup(ct); + var match = FindInstalledMatch(installed, driver); + + if (match is null) + { + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] No installed driver matches '{driver.Name}' — proceeding with install"); + return PipelineResult.Ok(); + } + + context.Result.PreviousVersion = match.Version; + context.Bag["PreviousVersion"] = match.Version; + context.Bag["PreviousInstalled"] = match; + + if (!Semver.TryParse(driver.Version, out var newVersion) || !Semver.TryParse(match.Version, out var installedVersion)) + { + // Unparseable versions: fall through and update (safe default — version info is unreliable). + context.Result.StepLogs.Add( + $"[{DateTime.Now:HH:mm:ss}] Version compare unavailable (new='{driver.Version}', installed='{match.Version}') — proceeding with install"); + return PipelineResult.Ok(); + } + + if (newVersion > installedVersion) + { + context.Result.StepLogs.Add( + $"[{DateTime.Now:HH:mm:ss}] New version {newVersion} > installed {installedVersion} — proceeding with install"); + return PipelineResult.Ok(); + } + + GeneralTracer.Info($"Version check: installed {installedVersion} is equal/newer than {newVersion}; skipping."); + context.Result.StepLogs.Add( + $"[{DateTime.Now:HH:mm:ss}] Installed version {installedVersion} >= {newVersion} — update skipped"); + return PipelineResult.Skip($"Installed version {installedVersion} is equal or newer than {newVersion}."); + }); + } + + /// + /// Wraps a platform permission check with the ForceTerminateOnPermissionFailure policy: + /// fail the pipeline when forced, warn and continue otherwise. + /// + /// Step name for logs/progress. + /// Returns an error message when the permission check fails, null when it passes. + public static IPipelineStep CreatePermissionCheckStep( + string stepName, + Func check) + { + return new DelegateStep(stepName, + execute: (context, ct) => + { + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Running permission check ({stepName})"); + + var error = check(); + if (error is null) + return Task.FromResult(PipelineResult.Ok()); + + if (context.Options.ForceTerminateOnPermissionFailure) + { + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Permission check failed: {error}"); + return Task.FromResult(PipelineResult.Fail(error)); + } + + GeneralTracer.Warn($"Permission check failed but ForceTerminateOnPermissionFailure=false — continuing. {error}"); + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] WARNING: permission check failed (continuing): {error}"); + return Task.FromResult(PipelineResult.Ok()); + }); + } + /// /// Creates the validate step: checks file existence, hash integrity, signature, and compatibility. + /// Debug-only skip switches are honored only inside a debug session. /// public static IPipelineStep CreateValidateStep(IDriverValidator validator) { @@ -23,15 +160,25 @@ public static IPipelineStep CreateValidateStep(IDriverValidator validator) context.Result.Status = UpdateStatus.Validating; context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Validating driver"); - // File existence check + // File existence check (a downloaded package has already been placed at FilePath). if (!File.Exists(driver.FilePath)) { GeneralTracer.Error($"Driver file not found: {driver.FilePath}"); return PipelineResult.Fail($"Driver file not found: {driver.FilePath}"); } - // Hash validation (skip if configured) - if (!strategy.SkipHashValidation && !string.IsNullOrEmpty(driver.Hash)) + // Hash validation. The skip switch is debug-session-only. + var skipHash = strategy.SkipHashValidation && context.Options.DebugModeSkipHash && Debugger.IsAttached; + if (strategy.SkipHashValidation && !skipHash) + { + var reason = !context.Options.DebugModeSkipHash + ? "DrivelutionOptions.DebugModeSkipHash is disabled" + : "no debugger is attached"; + GeneralTracer.Warn($"SkipHashValidation ignored ({reason})."); + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] WARNING: SkipHashValidation ignored ({reason})"); + } + + if (!skipHash && !string.IsNullOrEmpty(driver.Hash)) { if (!await validator.ValidateIntegrityAsync( driver.FilePath, driver.Hash, driver.HashAlgorithm, ct)) @@ -40,11 +187,34 @@ public static IPipelineStep CreateValidateStep(IDriverValidator validator) } } - // Signature validation (skip if configured) - if (!strategy.SkipSignatureValidation && driver.TrustedPublishers.Count > 0) + // Signature validation. The skip switch is debug-session-only. + var skipSignature = strategy.SkipSignatureValidation && context.Options.DebugModeSkipSignature && Debugger.IsAttached; + if (strategy.SkipSignatureValidation && !skipSignature) + { + var reason = !context.Options.DebugModeSkipSignature + ? "DrivelutionOptions.DebugModeSkipSignature is disabled" + : "no debugger is attached"; + GeneralTracer.Warn($"SkipSignatureValidation ignored ({reason})."); + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] WARNING: SkipSignatureValidation ignored ({reason})"); + } + + // Signature validation runs whenever signer trust is configured for the driver — in + // its own publisher list, or in the options for this platform. Trust that is + // configured but never consulted would silently accept every package. + var trustOnlyInOptions = driver.TrustedPublishers.Count == 0 && HasTrustedSigners(driver, context.Options); + if (!skipSignature && HasTrustedSigners(driver, context.Options)) { + if (trustOnlyInOptions) + { + GeneralTracer.Info("Signature validation uses the signer trust from DrivelutionOptions; the driver lists no publishers of its own."); + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Signature validation uses the trust configured in the options"); + } + if (!await validator.ValidateSignatureAsync( - driver.FilePath, driver.TrustedPublishers, ct)) + driver.FilePath, + driver.TrustedPublishers, + context.Options.TrustedCertificateThumbprints, + ct)) { return PipelineResult.Fail("Driver signature validation failed"); } @@ -64,71 +234,199 @@ public static IPipelineStep CreateValidateStep(IDriverValidator validator) } /// - /// Creates the backup step: backs up the current driver before installation. + /// Creates the backup step: backs up the current (installed when supported, otherwise local) + /// driver and writes a manifest describing the backup contents. /// public static IPipelineStep CreateBackupStep(IDriverBackup backup) { - return new DelegateStep("Backup", async (context, ct) => - { - context.Result.Status = UpdateStatus.BackingUp; - context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Creating backup"); + return new DelegateStep("Backup", + shouldExecute: context => context.Strategy.RequireBackup && !context.Strategy.DryRun, + execute: async (context, ct) => + { + context.Result.Status = UpdateStatus.BackingUp; + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Creating backup"); - var backupPath = Path.Combine( - context.Strategy.BackupPath, - $"backup_{context.DriverInfo.Name}_{DateTime.Now:yyyyMMddHHmmss}"); + var root = ResolveBackupRoot(context); + var backupDirectory = Path.Combine( + root, + $"backup_{SanitizeFileName(context.DriverInfo.Name)}_{DateTime.Now:yyyyMMddHHmmss}"); + Directory.CreateDirectory(backupDirectory); - if (await backup.BackupAsync(context.DriverInfo.FilePath, backupPath, ct)) - { - context.Result.BackupPath = backupPath; - context.Bag["BackupPath"] = backupPath; - GeneralTracer.Info($"Backup created at: {backupPath}"); - return PipelineResult.Ok(); - } + // Prefer an export of the currently installed driver (full package from the driver + // store); fall back to copying the local package files. + var exportedInstalled = await (context.BackupInstalledDriverHook?.Invoke( + context.DriverInfo, backupDirectory, ct) ?? Task.FromResult(false)); + bool backedUp; + string source; + + if (exportedInstalled) + { + backedUp = true; + source = BackupManifest.SourceInstalled; + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Exported currently installed driver package"); + } + else + { + backedUp = await backup.BackupAsync(context.DriverInfo.FilePath, backupDirectory, ct); + source = BackupManifest.SourcePackage; + } + + if (!backedUp) + { + return PipelineResult.Fail("Failed to create driver backup"); + } + + // From here on a rollback may need this backup, so retention must leave it alone + // while the update runs. Pinned before the manifest goes in — the manifest is + // what makes a backup eligible for a purge — so there is no gap in between. + context.BackupRetention = BackupManifestStore.Pin(backupDirectory); + + WriteManifest(context, backupDirectory, source); - return PipelineResult.Fail("Failed to create driver backup"); - }, - shouldExecute: context => context.Strategy.RequireBackup); + context.Result.BackupPath = backupDirectory; + context.Bag["BackupPath"] = backupDirectory; + context.Bag["BackupSource"] = source; + GeneralTracer.Info($"Backup created at: {backupDirectory} (source={source})"); + return PipelineResult.Ok(); + }); } /// /// Creates the install step: delegates to the platform-specific InstallCoreAsync method. /// public static IPipelineStep CreateInstallStep( - Func installCore) + Func installCore) { - return new DelegateStep("Install", async (context, ct) => - { - context.Result.Status = UpdateStatus.Updating; - context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Installing driver"); + return new DelegateStep("Install", + shouldExecute: context => !context.Strategy.DryRun, + execute: async (context, ct) => + { + context.Result.Status = UpdateStatus.Updating; + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Installing driver"); + context.InstallStarted = true; - await installCore(context.DriverInfo, context.Strategy, ct); + await installCore(context, ct); - return PipelineResult.Ok(); - }); + return PipelineResult.Ok(); + }); } /// - /// Creates the verify step: confirms the driver was installed correctly. + /// Creates the verify step. When is set, + /// a failed verification fails the update (triggering rollback); otherwise it only logs a warning. /// public static IPipelineStep CreateVerifyStep( - Func> verifyCore) + Func> verifyCore) { - return new DelegateStep("Verify", async (context, ct) => - { - context.Result.Status = UpdateStatus.Verifying; - context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Verifying installation"); + return new DelegateStep("Verify", + shouldExecute: context => !context.Strategy.DryRun, + execute: async (context, ct) => + { + context.Result.Status = UpdateStatus.Verifying; + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Verifying installation"); - var verified = await verifyCore(context.DriverInfo, ct); + var verified = await verifyCore(context, ct); + + if (verified) + return PipelineResult.Ok(); + + if (context.Strategy.FailOnVerificationFailure) + { + GeneralTracer.Error("Driver installation verification failed (FailOnVerificationFailure=true)"); + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Verification failed"); + return PipelineResult.Fail("Driver installation verification failed"); + } - if (!verified) - { // Non-fatal: log warning but don't fail the whole update GeneralTracer.Warn("Driver installation verification returned false"); context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] WARNING: Verification inconclusive"); - } + return PipelineResult.Ok(); + }); + } - return PipelineResult.Ok(); - }); + // ─── Helpers ─────────────────────────────────────────────────────── + + private static bool IsSha256(string hashAlgorithm) => + hashAlgorithm.Equals("SHA256", StringComparison.OrdinalIgnoreCase) || + hashAlgorithm.Equals("SHA-256", StringComparison.OrdinalIgnoreCase); + + /// + /// Whether any signer trust is configured for a driver: its own publisher list, or the trust + /// the options hold for the current platform — certificate thumbprints on Windows, GPG keys + /// on Linux. Signature validation has nothing to check against otherwise. + /// + internal static bool HasTrustedSigners(DriverInfo driver, DrivelutionOptions options) => + driver.TrustedPublishers.Count > 0 + || (OperatingSystem.IsWindows() && options.TrustedCertificateThumbprints.Count > 0) + || (OperatingSystem.IsLinux() && options.TrustedGpgKeys.Count > 0); + + internal static InstalledDriverInfo? FindInstalledMatch(List installed, DriverInfo driver) + { + InstalledDriverInfo? byName = installed.FirstOrDefault(d => + d.Name.Equals(driver.Name, StringComparison.OrdinalIgnoreCase) || + (!string.IsNullOrEmpty(d.PublishedName) && + (d.PublishedName.Equals(Path.GetFileName(driver.FilePath), StringComparison.OrdinalIgnoreCase) || + d.PublishedName.Equals(Path.GetFileNameWithoutExtension(driver.FilePath), StringComparison.OrdinalIgnoreCase)))); + + return byName; + } + + internal static string ResolveBackupRoot(PipelineContext context) + { + var root = !string.IsNullOrWhiteSpace(context.Strategy.BackupPath) + ? context.Strategy.BackupPath + : context.Options.DefaultBackupPath; + return Path.GetFullPath(root); + } + + internal static string SanitizeFileName(string name) + { + var invalid = Path.GetInvalidFileNameChars(); + var sanitized = new string(name.Select(c => invalid.Contains(c) ? '_' : c).ToArray()); + return string.IsNullOrWhiteSpace(sanitized) ? "driver" : sanitized; + } + + private static void WriteManifest(PipelineContext context, string backupDirectory, string source) + { + try + { + var manifest = new BackupManifest + { + DriverName = context.DriverInfo.Name, + DriverVersion = context.DriverInfo.Version, + Source = source, + OriginalFilePath = context.DriverInfo.FilePath, + Platform = CompatibilityChecker.GetCurrentOS(), + Files = EnumerateManifestFiles(backupDirectory) + }; + + BackupManifestStore.Save(manifest, backupDirectory); + } + catch (Exception ex) + { + // The backup files exist; a missing manifest must not fail the update. + GeneralTracer.Warn($"Backup step: failed to write manifest. {ex.Message}"); + } + } + + private static List EnumerateManifestFiles(string backupDirectory) + { + var files = new List(); + foreach (var file in Directory.GetFiles(backupDirectory, "*.*", SearchOption.AllDirectories)) + { + if (Path.GetFileName(file).Equals(BackupManifest.ManifestFileName, StringComparison.OrdinalIgnoreCase)) + continue; + + using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + files.Add(new BackupFileEntry + { + RelativePath = Path.GetRelativePath(backupDirectory, file), + Sha256 = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(stream)).ToLowerInvariant(), + Size = stream.Length + }); + } + + return files; } } diff --git a/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineContext.cs b/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineContext.cs index a4a2ea29..db814427 100644 --- a/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineContext.cs +++ b/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineContext.cs @@ -1,10 +1,12 @@ +using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Abstractions.Models; namespace GeneralUpdate.Drivelution.Core.Pipeline; /// /// Mutable context object that flows through the driver update pipeline. -/// Carries driver information, strategy configuration, and the accumulating result. +/// Carries driver information, strategy configuration, the accumulating result, +/// resolved options, and the progress reporter. /// public class PipelineContext { @@ -14,11 +16,20 @@ public class PipelineContext /// Driver information for the update. /// Update strategy configuration. /// Accumulating update result (mutated by each step). - public PipelineContext(DriverInfo driverInfo, UpdateStrategy strategy, UpdateResult result) + /// Resolved library options. + /// Optional progress reporter for fine-grained progress (e.g. download). + public PipelineContext( + DriverInfo driverInfo, + UpdateStrategy strategy, + UpdateResult result, + DrivelutionOptions? options = null, + IProgress? progress = null) { DriverInfo = driverInfo ?? throw new ArgumentNullException(nameof(driverInfo)); Strategy = strategy ?? throw new ArgumentNullException(nameof(strategy)); Result = result ?? throw new ArgumentNullException(nameof(result)); + Options = options ?? new DrivelutionOptions(); + Progress = progress; } /// @@ -36,6 +47,37 @@ public PipelineContext(DriverInfo driverInfo, UpdateStrategy strategy, UpdateRes /// public UpdateResult Result { get; } + /// + /// Resolved library options (never null). + /// + public DrivelutionOptions Options { get; } + + /// + /// Optional progress reporter for steps that have sub-progress (e.g. downloads). + /// + public IProgress? Progress { get; } + + /// + /// 平台钩子:把当前已安装的驱动导出到指定备份目录(Windows 用 pnputil /export-driver)。 + /// 返回 false 表示平台不支持或未找到已安装驱动,回退为本地包拷贝。由 BaseDriverUpdater 注入。 + /// Platform hook: exports the currently installed driver into the given backup directory + /// (Windows uses pnputil /export-driver). Returns false when unsupported or not found; the + /// pipeline then falls back to copying the local package. Injected by BaseDriverUpdater. + /// + public Func>? BackupInstalledDriverHook { get; set; } + + /// + /// Keeps the backup of this update safe from retention while the update runs, so that a + /// rollback still finds it. Set by the backup step once the backup exists; disposed by + /// when the update has ended, whatever its outcome. + /// + public IDisposable? BackupRetention { get; set; } + + /// + /// Set when the install step begins: from there on an update has something to roll back. + /// + public bool InstallStarted { get; set; } + /// /// A mutable bag of key-value pairs for steps to share intermediate data. /// Example: the backup step stores the backup path here, the rollback step reads it. diff --git a/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineResult.cs b/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineResult.cs index 53a21c8f..6ecf50e1 100644 --- a/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineResult.cs +++ b/src/GeneralUpdate.Drivelution/Core/Pipeline/PipelineResult.cs @@ -6,10 +6,15 @@ namespace GeneralUpdate.Drivelution.Core.Pipeline; public class PipelineResult { /// - /// Whether the step executed successfully. + /// Whether the step executed successfully (skipped counts as success). /// public bool Success { get; init; } + /// + /// Whether the step decided the whole update should be skipped (e.g. version check). + /// + public bool Skipped { get; init; } + /// /// Error message if the step failed (null when successful). /// @@ -25,6 +30,16 @@ public class PipelineResult /// public static PipelineResult Ok() => new() { Success = true }; + /// + /// Creates a skip result: the update is aborted cleanly (no failure, no rollback). + /// + public static PipelineResult Skip(string reason) => new() + { + Success = true, + Skipped = true, + ErrorMessage = reason + }; + /// /// Creates a failed result with an error message. /// diff --git a/src/GeneralUpdate.Drivelution/Core/Pipeline/RetryPolicy.cs b/src/GeneralUpdate.Drivelution/Core/Pipeline/RetryPolicy.cs index 6b128039..7443005e 100644 --- a/src/GeneralUpdate.Drivelution/Core/Pipeline/RetryPolicy.cs +++ b/src/GeneralUpdate.Drivelution/Core/Pipeline/RetryPolicy.cs @@ -1,10 +1,19 @@ +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Execution; + namespace GeneralUpdate.Drivelution.Core.Pipeline; /// /// Configurable retry policy for pipeline step execution. +/// Retries are only performed for failures considered transient (see ), +/// unless a custom shouldRetry predicate is supplied. /// public class RetryPolicy { + private readonly Func? _shouldRetry; + /// /// Maximum number of retry attempts. /// @@ -20,6 +29,11 @@ public class RetryPolicy /// public bool UseExponentialBackoff { get; } + /// + /// Whether to add random jitter (0–25% of the computed delay) to backoff delays. + /// + public bool UseJitter { get; } + /// /// Creates a retry policy from defaults (3 retries, 5s interval, no backoff). /// @@ -36,17 +50,27 @@ public class RetryPolicy /// Maximum retry attempts. /// Delay between retries. /// Whether to double delay each retry. - public RetryPolicy(int maxRetries, TimeSpan delay, bool useExponentialBackoff = false) + /// Whether to add random jitter to backoff delays. + /// Optional predicate deciding which exceptions are retryable. + /// When null, is used. + public RetryPolicy( + int maxRetries, + TimeSpan delay, + bool useExponentialBackoff = false, + bool useJitter = false, + Func? shouldRetry = null) { MaxRetries = maxRetries; Delay = delay; UseExponentialBackoff = useExponentialBackoff; + UseJitter = useJitter; + _shouldRetry = shouldRetry; } /// /// Creates a RetryPolicy from . /// - public static RetryPolicy FromOptions(Abstractions.Configuration.DrivelutionOptions? options) + public static RetryPolicy FromOptions(DrivelutionOptions? options) { if (options is null) return Default; @@ -54,12 +78,58 @@ public static RetryPolicy FromOptions(Abstractions.Configuration.DrivelutionOpti return new RetryPolicy( options.DefaultRetryCount > 0 ? options.DefaultRetryCount : 3, TimeSpan.FromSeconds(options.DefaultRetryIntervalSeconds > 0 ? options.DefaultRetryIntervalSeconds : 5), - useExponentialBackoff: options.UseExponentialBackoff); + useExponentialBackoff: options.UseExponentialBackoff, + useJitter: options.UseRetryJitter); + } + + /// + /// Creates a RetryPolicy for a specific call. Per-strategy values win when set (> 0); + /// otherwise the options defaults are used. + /// + public static RetryPolicy FromStrategy(UpdateStrategy? strategy, DrivelutionOptions? options) + { + if (strategy is null) + return FromOptions(options); + + var optionsPolicy = FromOptions(options); + var retries = strategy.RetryCount > 0 ? strategy.RetryCount : optionsPolicy.MaxRetries; + var delay = strategy.RetryIntervalSeconds > 0 + ? TimeSpan.FromSeconds(strategy.RetryIntervalSeconds) + : optionsPolicy.Delay; + + return new RetryPolicy( + retries, + delay, + useExponentialBackoff: optionsPolicy.UseExponentialBackoff, + useJitter: optionsPolicy.UseJitter); + } + + /// + /// Default transient-failure predicate. Retryable: + /// + /// (external command failures; its CanRetry is honored) + /// / (their CanRetry is honored) + /// (transient file/device contention) + /// + /// Deterministic failures (validation, permissions, bad arguments) are never retried. + /// + public static bool IsTransient(Exception ex) + { + return ex switch + { + CommandExecutionException cex => cex.CanRetry, + DriverInstallationException die => die.CanRetry, + DriverBackupException dbe => dbe.CanRetry, + IOException => true, + _ => false + }; } /// /// Executes an asynchronous operation with retry logic. - /// When all retries are exhausted, the last exception propagates to the caller unchanged. + /// Only transient failures (per the configured predicate) are retried; all others and + /// cancellations propagate immediately. When retries are exhausted, the last exception + /// propagates to the caller unchanged. /// /// The operation to execute. /// Cancellation token. @@ -80,13 +150,14 @@ public async Task ExecuteAsync( { throw; // Never retry cancellations } - catch (Exception) when (attempt < MaxRetries) + catch (Exception ex) when (attempt < MaxRetries && ShouldRetry(ex)) { attempt++; + GeneralTracer.Warn($"RetryPolicy: attempt {attempt}/{MaxRetries} failed with a transient error, retrying. {ex.Message}"); await DelayAsync(attempt, cancellationToken); } } - // If we exhaust retries, the last exception propagates via the catch-when fallthrough + // Non-retryable exceptions and exhausted retries fall through to the caller unchanged } /// @@ -110,7 +181,7 @@ public async Task ExecuteWithRetryAsync( { throw; } - catch (Exception ex) + catch (Exception ex) when (ShouldRetry(ex)) { // Transient failure — will retry if we have attempts left GeneralTracer.Warn($"RetryPolicy: attempt {attempt + 1}/{MaxRetries + 1} failed. {ex.Message}"); @@ -124,8 +195,16 @@ public async Task ExecuteWithRetryAsync( } } + private bool ShouldRetry(Exception ex) + { + if (_shouldRetry is not null) + return _shouldRetry(ex); + + return IsTransient(ex); + } + /// - /// Calculates the delay for a given retry attempt, applying exponential backoff if configured. + /// Calculates the delay for a given retry attempt, applying exponential backoff and jitter if configured. /// private async Task DelayAsync(int attempt, CancellationToken cancellationToken) { @@ -133,6 +212,12 @@ private async Task DelayAsync(int attempt, CancellationToken cancellationToken) ? TimeSpan.FromMilliseconds(Delay.TotalMilliseconds * Math.Pow(2, attempt - 1)) : Delay; + if (UseJitter && UseExponentialBackoff && delay > TimeSpan.Zero) + { + var jitterFactor = Random.Shared.NextDouble() * 0.25; // 0% – 25% + delay = TimeSpan.FromMilliseconds(delay.TotalMilliseconds * (1 + jitterFactor)); + } + if (delay > TimeSpan.Zero) await Task.Delay(delay, cancellationToken); } diff --git a/src/GeneralUpdate.Drivelution/Core/ServiceCollectionExtensions.cs b/src/GeneralUpdate.Drivelution/Core/ServiceCollectionExtensions.cs index 82e8b3d9..1d5ac48e 100644 --- a/src/GeneralUpdate.Drivelution/Core/ServiceCollectionExtensions.cs +++ b/src/GeneralUpdate.Drivelution/Core/ServiceCollectionExtensions.cs @@ -1,10 +1,11 @@ using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Core.Execution; +using GeneralUpdate.Drivelution.Core.Network; using GeneralUpdate.Drivelution.Windows.Implementation; using GeneralUpdate.Drivelution.Linux.Implementation; -using GeneralUpdate.Drivelution.MacOS.Implementation; namespace GeneralUpdate.Drivelution.Core; @@ -49,27 +50,55 @@ public static IServiceCollection AddDrivelution( // Infrastructure services.AddSingleton(); + services.AddSingleton(sp => + new HttpNetworkDownloader(sp.GetRequiredService().NetworkProxy)); - // Platform-specific registrations + // Platform-specific registrations. Resolving IGeneralDrivelution also bridges + // GeneralTracer to the application's ILoggerFactory when one is registered. if (OperatingSystem.IsWindows()) { services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(sp => + { + BridgeTracerToLogger(sp); + return new WindowsGeneralDrivelution( + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetService()); + }); } else if (OperatingSystem.IsLinux()) { - services.AddSingleton(); + services.AddSingleton(sp => + new LinuxDriverValidator( + sp.GetRequiredService(), + sp.GetRequiredService())); services.AddSingleton(); - services.AddSingleton(); - } - else if (OperatingSystem.IsMacOS()) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(sp => + { + BridgeTracerToLogger(sp); + return new LinuxGeneralDrivelution( + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetService()); + }); } + // macOS is no longer supported: nothing is registered on other platforms. return services; } + + private static void BridgeTracerToLogger(IServiceProvider serviceProvider) + { + var loggerFactory = serviceProvider.GetService(); + if (loggerFactory is not null) + { + GeneralTracer.SetExternalLogger(loggerFactory.CreateLogger("GeneralUpdate.Drivelution")); + } + } } diff --git a/src/GeneralUpdate.Drivelution/Core/Utilities/BackupManifestStore.cs b/src/GeneralUpdate.Drivelution/Core/Utilities/BackupManifestStore.cs new file mode 100644 index 00000000..88c55953 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Core/Utilities/BackupManifestStore.cs @@ -0,0 +1,233 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.Json.Serialization; +using GeneralUpdate.Drivelution.Abstractions.Models; + +namespace GeneralUpdate.Drivelution.Core.Utilities; + +/// +/// AOT-friendly (source-generated) JSON serializer context for backup manifests and install state. +/// +[JsonSourceGenerationOptions(WriteIndented = true)] +[JsonSerializable(typeof(BackupManifest))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(InstallState))] +internal sealed partial class DrivelutionJsonContext : JsonSerializerContext; + +/// +/// Reads and writes files, lists backups under a root, and purges old ones. +/// A backup is recognized by the presence of in its directory; +/// directories without a manifest are never touched by purge operations. A backup that a running +/// update still depends on () is not purged either. +/// +public static class BackupManifestStore +{ + /// + /// The backups a running update may still roll back to: canonical directory → number of + /// owners. Process-wide, because the parallel updates that contend for a root share it. + /// + private static readonly ConcurrentDictionary InUse = + new(StringComparer.FromComparison(BackupPaths.Comparison)); + + /// + /// Keeps a backup from being purged while a running update may still roll back to it. Dispose + /// the returned handle when the update has ended. + /// + /// The backup directory. + /// The handle that ends the protection. + public static IDisposable Pin(string backupDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(backupDirectory); + + var key = BackupPaths.Canonicalize(backupDirectory); + InUse.AddOrUpdate(key, 1, static (_, owners) => owners + 1); + return new BackupPin(key); + } + + /// + /// Whether a is currently held for the backup directory. + /// + public static bool IsPinned(string backupDirectory) => + InUse.ContainsKey(BackupPaths.Canonicalize(backupDirectory)); + + private static void Release(string key) + { + while (InUse.TryGetValue(key, out var owners)) + { + // Each step is conditional on the count it read, so concurrent holders cannot race. + if (owners <= 1) + { + if (InUse.TryRemove(new KeyValuePair(key, owners))) + break; + } + else if (InUse.TryUpdate(key, owners - 1, owners)) + { + break; + } + } + } + + private sealed class BackupPin(string key) : IDisposable + { + private bool _released; + + public void Dispose() + { + if (_released) + return; + _released = true; + Release(key); + } + } + + /// + /// Writes a manifest into the backup directory. + /// + public static void Save(BackupManifest manifest, string backupDirectory) + { + ArgumentNullException.ThrowIfNull(manifest); + manifest.BackupDirectory = backupDirectory; + Directory.CreateDirectory(backupDirectory); + var path = Path.Combine(backupDirectory, BackupManifest.ManifestFileName); + File.WriteAllText(path, JsonSerializer.Serialize(manifest, DrivelutionJsonContext.Default.BackupManifest)); + } + + /// + /// Loads a manifest from a backup directory; returns null when the directory has no manifest. + /// + public static BackupManifest? Load(string backupDirectory) + { + var path = Path.Combine(backupDirectory, BackupManifest.ManifestFileName); + if (!File.Exists(path)) + return null; + + try + { + var manifest = JsonSerializer.Deserialize( + File.ReadAllText(path), + DrivelutionJsonContext.Default.BackupManifest); + + if (manifest is not null) + manifest.BackupDirectory = backupDirectory; + + return manifest; + } + catch (Exception ex) + { + GeneralTracer.Warn($"BackupManifestStore: failed to read manifest in '{backupDirectory}'. {ex.Message}"); + return null; + } + } + + /// + /// Lists all manifest-backed backups under (non-recursively), + /// newest first. + /// + public static List List(string backupRoot) + { + var result = new List(); + + if (string.IsNullOrWhiteSpace(backupRoot) || !Directory.Exists(backupRoot)) + return result; + + foreach (var dir in Directory.GetDirectories(backupRoot)) + { + var manifest = Load(dir); + if (manifest is not null) + result.Add(manifest); + } + + return result.OrderByDescending(m => m.CreatedAtUtc).ToList(); + } + + /// + /// Deletes the oldest manifest-backed backups, keeping the most recent . + /// A backup that is pinned for a running update is left alone, whatever its age. + /// Returns the number of deleted backups. + /// + public static int Purge(string backupRoot, int keep) + { + if (keep <= 0) + throw new ArgumentOutOfRangeException(nameof(keep), "Must keep at least one backup."); + + var backups = List(backupRoot); + var deleted = 0; + + foreach (var manifest in backups.Skip(keep)) + { + if (IsPinned(manifest.BackupDirectory)) + { + // The update that made it may still roll back to it; the next purge after that + // update ends takes it. + GeneralTracer.Info($"BackupManifestStore: keeping backup '{manifest.BackupDirectory}' ({manifest.DriverName}); a running update may still roll back to it."); + continue; + } + + try + { + if (Directory.Exists(manifest.BackupDirectory)) + { + Directory.Delete(manifest.BackupDirectory, recursive: true); + deleted++; + GeneralTracer.Info($"BackupManifestStore: purged old backup '{manifest.BackupDirectory}' ({manifest.DriverName})."); + } + } + catch (Exception ex) + { + GeneralTracer.Warn($"BackupManifestStore: failed to purge '{manifest.BackupDirectory}'. {ex.Message}"); + } + } + + return deleted; + } +} + +/// +/// Reads and writes snapshots (install_state.json) inside backup +/// directories. Rollback uses them to target exactly the package that was installed. +/// +public static class InstallStateStore +{ + /// + /// Writes an install state snapshot into the backup directory (best-effort: failures are + /// logged and never break the install). + /// + public static void TrySave(InstallState state, string backupDirectory) + { + try + { + if (string.IsNullOrEmpty(backupDirectory) || !Directory.Exists(backupDirectory)) + { + GeneralTracer.Warn("InstallStateStore: backup directory does not exist; install state not persisted."); + return; + } + + var path = Path.Combine(backupDirectory, InstallState.InstallStateFileName); + File.WriteAllText(path, JsonSerializer.Serialize(state, DrivelutionJsonContext.Default.InstallState)); + } + catch (Exception ex) + { + GeneralTracer.Warn($"InstallStateStore: failed to persist install state. {ex.Message}"); + } + } + + /// + /// Loads the install state snapshot from a backup directory; null when absent. + /// + public static InstallState? Load(string backupDirectory) + { + var path = Path.Combine(backupDirectory, InstallState.InstallStateFileName); + if (!File.Exists(path)) + return null; + + try + { + return JsonSerializer.Deserialize(File.ReadAllText(path), DrivelutionJsonContext.Default.InstallState); + } + catch (Exception ex) + { + GeneralTracer.Warn($"InstallStateStore: failed to read install state. {ex.Message}"); + return null; + } + } +} diff --git a/src/GeneralUpdate.Drivelution/Core/Utilities/BackupPaths.cs b/src/GeneralUpdate.Drivelution/Core/Utilities/BackupPaths.cs new file mode 100644 index 00000000..1b7f7893 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Core/Utilities/BackupPaths.cs @@ -0,0 +1,39 @@ +namespace GeneralUpdate.Drivelution.Core.Utilities; + +/// +/// How backup directory paths are compared and normalized. +/// +internal static class BackupPaths +{ + /// + /// Windows file systems do not distinguish case; the others this library runs on do. + /// + public static StringComparison Comparison { get; } = + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// + /// The absolute form of a directory path, without trailing separators — a file-system root + /// ("C:\", "/") keeps the one it consists of. + /// + public static string Canonicalize(string path) + { + var full = Path.GetFullPath(path); + return string.Equals(Path.GetPathRoot(full), full, Comparison) + ? full + : full.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + } + + /// + /// Whether is itself or lies beneath it. + /// + public static bool IsSameOrBeneath(string path, string directory) + { + var candidate = Canonicalize(path); + var root = Canonicalize(directory); + if (string.Equals(candidate, root, Comparison)) + return true; + + var prefix = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar; + return candidate.StartsWith(prefix, Comparison); + } +} diff --git a/src/GeneralUpdate.Drivelution/Core/Utilities/DriverBackupFiles.cs b/src/GeneralUpdate.Drivelution/Core/Utilities/DriverBackupFiles.cs new file mode 100644 index 00000000..3936feec --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Core/Utilities/DriverBackupFiles.cs @@ -0,0 +1,195 @@ +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Abstractions.Models; + +namespace GeneralUpdate.Drivelution.Core.Utilities; + +/// +/// The file operations behind , shared by the platform implementations. +/// A backup is a copy of a driver package — the tree a driver file lives in, since an INF or a +/// kernel module is reinstalled together with what sits next to it — and a restore puts that copy +/// back where it came from. +/// +internal static class DriverBackupFiles +{ + /// + /// What the pipeline stores at the top level of a backup directory besides the driver files. + /// + private static readonly HashSet MetadataFiles = new(StringComparer.FromComparison(BackupPaths.Comparison)) + { + BackupManifest.ManifestFileName, + InstallState.InstallStateFileName + }; + + /// + /// The root of the package a source path belongs to: the directory itself, or the directory + /// that holds the file. + /// + public static string GetPackageRoot(string sourcePath) => Directory.Exists(sourcePath) + ? Path.GetFullPath(sourcePath) + : Path.GetDirectoryName(Path.GetFullPath(sourcePath))!; + + /// + /// Rejects a backup directory that overlaps the package tree — inside it, or around it. A + /// copy inside the tree enumerates its own output and grows until the disk or the path limit + /// gives; a copy around the tree writes package files over their own directory. This is a + /// configuration error, so it is not retryable. + /// + public static void EnsureBackupIsSeparate(string backupPath, string packageRoot) + { + if (BackupPaths.IsSameOrBeneath(backupPath, packageRoot) || BackupPaths.IsSameOrBeneath(packageRoot, backupPath)) + { + throw new DriverBackupException( + $"The backup directory '{backupPath}' overlaps the driver package '{packageRoot}': neither may contain the other. " + + "Choose a backup location outside of the package.") + { + CanRetry = false + }; + } + } + + /// + /// Copies every file beneath to the same relative position + /// beneath , replacing what exists there, and returns how many + /// files were copied. leaves out files by full path. + /// + public static Task CopyTreeAsync( + string sourceRoot, + string targetRoot, + CancellationToken cancellationToken, + Func? skip = null) + { + var source = Path.GetFullPath(sourceRoot); + var target = Path.GetFullPath(targetRoot); + + return Task.Run(() => + { + var copied = 0; + foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (skip?.Invoke(file) == true) + continue; + + var destination = Path.Combine(target, Path.GetRelativePath(source, file)); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + ReplaceFile(file, destination); + copied++; + } + + return copied; + }, cancellationToken); + } + + /// + /// Copies one file into the backup directory, as the self-contained package it is. + /// + public static Task CopyFileAsync(string source, string target, CancellationToken cancellationToken) => + Task.Run(() => + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(target))!); + ReplaceFile(source, target); + }, cancellationToken); + + /// + /// Restores a backup to . is a + /// directory — the form backups take, holding the package tree — or, for backups made by + /// older versions, a single file. A directory target receives the tree; a file target + /// receives the backup's copy of that file. Nothing at the target is touched before it is + /// established what goes there. + /// + public static async Task RestoreAsync(string backupPath, string targetPath, CancellationToken cancellationToken) + { + // Absolute forms, so that the paths compared below match what the enumeration returns. + backupPath = BackupPaths.Canonicalize(backupPath); + var target = Path.GetFullPath(targetPath); + + if (Directory.Exists(backupPath)) + { + if (Directory.Exists(target)) + { + // The package directory as a whole; the pipeline's own metadata is not part of it. + var restored = await CopyTreeAsync(backupPath, target, cancellationToken, + file => IsMetadata(file, backupPath)); + if (restored == 0) + throw new DriverRollbackException($"The backup '{backupPath}' holds no driver files to restore."); + return; + } + + // A file inside its package: the backup holds its copy at the top level. + var copy = Path.Combine(backupPath, Path.GetFileName(target)); + if (!File.Exists(copy)) + { + throw new DriverRollbackException( + $"The backup '{backupPath}' holds no copy of '{Path.GetFileName(target)}' for '{target}'."); + } + + await ReplaceWithAsync(copy, target, cancellationToken); + return; + } + + if (File.Exists(backupPath)) + { + await ReplaceWithAsync(backupPath, target, cancellationToken); + return; + } + + throw new FileNotFoundException($"Backup not found: {backupPath}"); + } + + private static bool IsMetadata(string file, string backupPath) => + string.Equals(Path.GetDirectoryName(file), backupPath, BackupPaths.Comparison) + && MetadataFiles.Contains(Path.GetFileName(file)); + + /// + /// Puts a copy of at . An existing target + /// is moved to ".old" first; when the copy then fails, the partial copy is removed and + /// the previous file returns to its place. + /// + private static async Task ReplaceWithAsync(string source, string target, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + + var previous = target + ".old"; + var hadTarget = File.Exists(target); + if (hadTarget) + { + File.Move(target, previous, overwrite: true); + GeneralTracer.Info($"Moved existing file to temporary backup: {previous}"); + } + + try + { + cancellationToken.ThrowIfCancellationRequested(); + await using var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, useAsync: true); + await input.CopyToAsync(output, cancellationToken); + } + catch + { + try + { + if (File.Exists(target)) + File.Delete(target); + if (hadTarget) + File.Move(previous, target); + } + catch (Exception cleanupFailure) + { + GeneralTracer.Error( + $"The previous file is still at '{previous}' and must be moved back to '{target}' by hand.", cleanupFailure); + } + + throw; + } + } + + /// + /// Copies a file over one that may exist: a read-only target refuses that on Windows. + /// + private static void ReplaceFile(string source, string target) + { + if (File.Exists(target)) + File.SetAttributes(target, FileAttributes.Normal); + File.Copy(source, target, overwrite: true); + } +} diff --git a/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs b/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs index 4977c451..b87c56b2 100644 --- a/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs +++ b/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs @@ -5,20 +5,31 @@ namespace GeneralUpdate.Drivelution.Core.Utilities; /// -/// 重启助手工具类 -/// Restart helper utility +/// 重启助手:执行重启的入口由调用方注入(回调),库本身不做交互(不读控制台、不弹窗)。 +/// Restart helper: the actual restart is delegated to caller-supplied callbacks; the library +/// itself never interacts with the console or GUI. /// public static class RestartHelper { /// - /// 根据重启模式执行重启操作 - /// Executes restart operation based on restart mode + /// 根据重启模式执行重启流程。 + /// 执行重启必须提供 ;Prompt 模式必须提供 , + /// 未提供时返回 false 并记录警告。 /// /// 重启模式 / Restart mode - /// 延迟秒数(仅用于延迟重启)/ Delay seconds (only for delayed restart) + /// 执行重启的回调(参数:延迟秒数)/ Restart callback (parameter: delay seconds) + /// 询问用户的回调(参数:消息;返回用户选择)/ Prompt callback (parameter: message; returns user choice) + /// 延迟秒数(仅用于延迟重启)/ Delay seconds (Delayed mode only) /// 提示消息 / Prompt message - /// 是否成功 / Whether successful - public static async Task HandleRestartAsync(RestartMode mode, int delaySeconds = 30, string message = "") + /// 取消令牌 / Cancellation token + /// 是否已发起(或用户确认)重启 / Whether a restart was initiated (or confirmed by the user) + public static async Task HandleRestartAsync( + RestartMode mode, + Func>? restartCallback, + Func>? promptCallback = null, + int delaySeconds = 30, + string message = "", + CancellationToken cancellationToken = default) { switch (mode) { @@ -26,14 +37,36 @@ public static async Task HandleRestartAsync(RestartMode mode, int delaySec return true; case RestartMode.Prompt: - return PromptUserForRestart(message); + if (promptCallback is null) + { + GeneralTracer.Warn("RestartHelper: Prompt restart requested but no prompt callback is configured."); + return false; + } + + var promptMessage = string.IsNullOrWhiteSpace(message) + ? "Driver update requires a system restart to complete." + : message; + + return await promptCallback(promptMessage); case RestartMode.Delayed: - await Task.Delay(TimeSpan.FromSeconds(delaySeconds)); - return await RestartSystemAsync(); + if (restartCallback is null) + { + GeneralTracer.Warn("RestartHelper: Delayed restart requested but no restart callback is configured."); + return false; + } + + await Task.Delay(TimeSpan.FromSeconds(delaySeconds), cancellationToken); + return await restartCallback(delaySeconds, cancellationToken); case RestartMode.Immediate: - return await RestartSystemAsync(); + if (restartCallback is null) + { + GeneralTracer.Warn("RestartHelper: Immediate restart requested but no restart callback is configured."); + return false; + } + + return await restartCallback(0, cancellationToken); default: return false; @@ -41,43 +74,22 @@ public static async Task HandleRestartAsync(RestartMode mode, int delaySec } /// - /// 提示用户重启 - /// Prompts user for restart + /// 异步重启系统(使用系统 shutdown 命令;一般应优先通过注入回调走 RestartHelper.HandleRestartAsync) + /// Restarts the system via the platform shutdown command (prefer injected callbacks through + /// in application code) /// - /// 提示消息 / Prompt message - /// 用户是否选择重启 / Whether user chose to restart - public static bool PromptUserForRestart(string message = "") - { - var promptMessage = string.IsNullOrWhiteSpace(message) - ? "Driver update requires system restart. Do you want to restart now? (Y/N)" - : message; - - Console.WriteLine(promptMessage); - // This is a simplified implementation. In a real application, you might use a GUI dialog. - // For now, we'll just log the message and return false (user needs to manually restart) - return false; - } - - /// - /// 异步重启系统 - /// Restarts system asynchronously - /// - /// 是否成功启动重启命令 / Whether restart command was successfully initiated + /// 是否成功启动重启命令 / Whether the restart command was successfully initiated public static async Task RestartSystemAsync() { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return await RestartWindowsAsync(); + return await RunShutdownAsync("/r", "/t", "0"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - return await RestartLinuxAsync(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return await RestartMacOSAsync(); + return await RunShutdownAsync("-r", "now"); } else { @@ -86,81 +98,28 @@ public static async Task RestartSystemAsync() } catch (Exception ex) { - Console.WriteLine($"Failed to restart system: {ex.Message}"); + GeneralTracer.Error($"RestartHelper: failed to restart system. {ex.Message}", ex); return false; } } - /// - /// 重启Windows系统 - /// Restarts Windows system - /// - private static async Task RestartWindowsAsync() + private static async Task RunShutdownAsync(params string[] args) { var startInfo = new ProcessStartInfo { FileName = "shutdown", - Arguments = "/r /t 0", UseShellExecute = false, CreateNoWindow = true }; + foreach (var arg in args) + startInfo.ArgumentList.Add(arg); using var process = Process.Start(startInfo); - if (process != null) - { - await process.WaitForExitAsync(); - return process.ExitCode == 0; - } - - return false; - } - - /// - /// 重启Linux系统 - /// Restarts Linux system - /// - private static async Task RestartLinuxAsync() - { - var startInfo = new ProcessStartInfo - { - FileName = "shutdown", - Arguments = "-r now", - UseShellExecute = false, - CreateNoWindow = true - }; - - using var process = Process.Start(startInfo); - if (process != null) - { - await process.WaitForExitAsync(); - return process.ExitCode == 0; - } - - return false; - } - - /// - /// 重启MacOS系统 - /// Restarts MacOS system - /// - private static async Task RestartMacOSAsync() - { - var startInfo = new ProcessStartInfo - { - FileName = "shutdown", - Arguments = "-r now", - UseShellExecute = false, - CreateNoWindow = true - }; - - using var process = Process.Start(startInfo); - if (process != null) - { - await process.WaitForExitAsync(); - return process.ExitCode == 0; - } + if (process == null) + return false; - return false; + await process.WaitForExitAsync(); + return process.ExitCode == 0; } /// diff --git a/src/GeneralUpdate.Drivelution/Core/Utilities/SignerTrust.cs b/src/GeneralUpdate.Drivelution/Core/Utilities/SignerTrust.cs new file mode 100644 index 00000000..fdd4ffc2 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Core/Utilities/SignerTrust.cs @@ -0,0 +1,44 @@ +using System.Security.Cryptography.X509Certificates; + +namespace GeneralUpdate.Drivelution.Core.Utilities; + +/// +/// Decides whether a package's signer is trusted. +/// +internal static class SignerTrust +{ + /// + /// 判断包的签名者是否受信任:指纹或发布者匹配即通过;只有在两个信任列表都为空时才接受任意有效签名—— + /// 配置了白名单却不匹配,不能被当作“未配置”放行。 + /// Decides whether a package's signer is trusted: a listed thumbprint or a matching publisher + /// entry accepts it. Any valid signature is accepted only when both allowlists are empty — + /// an allowlist that merely does not match never does. + /// + /// 签名者证书 / The signer certificate + /// 信任的发布者(主题片段或指纹)/ Trusted publishers (subject fragments or thumbprints) + /// 信任的证书指纹 / Trusted certificate thumbprints + public static bool IsTrusted( + X509Certificate2 certificate, + IReadOnlyCollection trustedPublishers, + IReadOnlyCollection trustedThumbprints) + { + // Thumbprint match: an exact fingerprint match is accepted before any publisher check. + if (trustedThumbprints.Any(t => certificate.Thumbprint.Equals(t, StringComparison.OrdinalIgnoreCase))) + { + // Signed by a certificate with a trusted thumbprint + return true; + } + + // Only accept an arbitrary signer when no trust is configured at all + if (trustedPublishers.Count == 0 && trustedThumbprints.Count == 0) + { + // No trusted publishers or thumbprints specified, accepting any valid signature + return true; + } + + // Check if the certificate subject or thumbprint matches any trusted publisher + return trustedPublishers.Any(publisher => + certificate.Subject.Contains(publisher, StringComparison.OrdinalIgnoreCase) || + certificate.Thumbprint.Equals(publisher, StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/src/GeneralUpdate.Drivelution/GeneralDrivelution.cs b/src/GeneralUpdate.Drivelution/GeneralDrivelution.cs index 3d65ff11..359189a9 100644 --- a/src/GeneralUpdate.Drivelution/GeneralDrivelution.cs +++ b/src/GeneralUpdate.Drivelution/GeneralDrivelution.cs @@ -16,7 +16,7 @@ namespace GeneralUpdate.Drivelution; /// // Simple usage - automatic platform detection /// var updater = GeneralDrivelution.Create(); /// var result = await updater.UpdateAsync(driverInfo, strategy); -/// +/// /// // With configuration /// var options = new DrivelutionOptions { }; /// var updater = GeneralDrivelution.Create(options); @@ -116,6 +116,51 @@ public static PlatformInfo GetPlatformInfo() return info; } + /// + /// Gets the drivers currently installed on this system. + /// + /// Cancellation token + /// Installed driver list + public static async Task> GetInstalledDriversAsync( + CancellationToken cancellationToken = default) + { + GeneralTracer.Info("GeneralDrivelution.GetInstalledDriversAsync: enumerating installed drivers."); + var updater = Create(); + var drivers = await updater.GetInstalledDriversAsync(cancellationToken); + GeneralTracer.Info($"GeneralDrivelution.GetInstalledDriversAsync: found {drivers.Count} installed driver(s)"); + return drivers ?? new List(); + } + + /// + /// Lists backups under a backup root (manifest-backed ones only). + /// + /// Backup root (null = configured default) + /// Cancellation token + /// Backup manifests, newest first + public static async Task> ListBackupsAsync( + string? backupRoot = null, + CancellationToken cancellationToken = default) + { + var updater = Create(); + return await updater.ListBackupsAsync(backupRoot, cancellationToken); + } + + /// + /// Purges old manifest-backed backups, keeping the most recent ones. + /// + /// Backup root (null = configured default) + /// Backups to keep (null = configured default) + /// Cancellation token + /// Number of deleted backups + public static async Task PurgeBackupsAsync( + string? backupRoot = null, + int? keep = null, + CancellationToken cancellationToken = default) + { + var updater = Create(); + return await updater.PurgeBackupsAsync(backupRoot, keep, cancellationToken); + } + /// /// Reads driver information from local directory /// @@ -140,7 +185,7 @@ public static async Task> GetDriversFromDirectoryAsync( /// /// Drivers to update /// Update strategy - /// Execution mode (Sequential or Parallel) + /// Execution mode (Sequential or Parallel; concurrency capped by UpdateStrategy.MaxDegreeOfParallelism) /// Optional progress reporter /// Cancellation token /// Aggregated batch result diff --git a/src/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj b/src/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj index 9cb96358..2da3fe91 100644 --- a/src/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj +++ b/src/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj @@ -1,7 +1,7 @@ - net10.0 + net8.0;net10.0 enable enable @@ -15,7 +15,7 @@ JusterZhu juster.zhu GeneralUpdate.Drivelution - A cross-platform driver update management system with support for Windows, Linux, and macOS. Provides driver backup, validation, version comparison, and automatic rollback capabilities. + A cross-platform driver update management system with support for Windows and Linux. Provides driver download, backup, validation, installed-driver inventory, version comparison, automatic rollback, and restart orchestration capabilities. Copyright © 2020-2026 JusterZhu. All rights reserved. https://github.com/GeneralLibrary/GeneralUpdate Apache-2.0 @@ -24,8 +24,8 @@ GeneralUpdate.png https://github.com/GeneralLibrary/GeneralUpdate public - driver,update,upgrade,backup,validation,cross-platform,linux,windows,macos - Cross-platform driver update management with backup, validation, and rollback support for Windows, Linux, and macOS platforms. + driver,update,upgrade,backup,validation,cross-platform,linux,windows + Cross-platform driver update management with download, backup, validation, installed-driver inventory, and rollback support for Windows and Linux platforms. true @@ -54,6 +54,7 @@ + diff --git a/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs b/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs index 0d330b48..fb79cc99 100644 --- a/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs +++ b/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs @@ -1,29 +1,38 @@ -using System.Diagnostics; using System.Runtime.Versioning; +using GeneralUpdate.Drivelution; +using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; - +using GeneralUpdate.Drivelution.Core.Execution; namespace GeneralUpdate.Drivelution.Linux.Helpers; /// -/// Linux签名验证助手 -/// Linux signature validation helper +/// Linux签名验证助手:基于 gpg 的签名验证。 +/// 支持两类信任项:公钥文件路径(自动 --import)与密钥指纹(40/16 位十六进制,做强校验—— +/// 签名密钥指纹必须与之一致,避免“信任链上任意密钥都放行”的问题)。不再自动从 keyserver 拉取密钥。 +/// Linux signature validation helper based on gpg. Trusted entries are either key file paths +/// (imported automatically) or key fingerprints (40/16-char hex, strictly enforced: the signing +/// key's fingerprint must match). Keys are never fetched from a keyserver automatically. /// [SupportedOSPlatform("linux")] public static class LinuxSignatureHelper { /// - /// 验证GPG签名 - /// Validates GPG signature + /// 验证 GPG 签名 + /// Validates a GPG signature /// + /// 命令执行器 / Command runner /// 文件路径 / File path /// 签名文件路径 / Signature file path - /// 信任的GPG公钥列表 / Trusted GPG public keys + /// 信任项(指纹或公钥文件路径)/ Trusted entries (fingerprints or key file paths) + /// 取消令牌 / Cancellation token /// 是否验证通过 / Whether validation succeeded public static async Task ValidateGpgSignatureAsync( + ICommandRunner commandRunner, string filePath, string signaturePath, - IEnumerable trustedKeys) + IEnumerable trustedKeys, + CancellationToken cancellationToken = default) { if (!File.Exists(filePath)) { @@ -38,50 +47,66 @@ public static async Task ValidateGpgSignatureAsync( try { - // Validating GPG signature for file: {FilePath} - - // Import trusted keys if provided - if (trustedKeys.Any()) + var keys = trustedKeys? + .Where(k => !string.IsNullOrWhiteSpace(k)) + .Select(k => k.Trim()) + .Distinct() + .ToList() ?? new List(); + + // Import key files; fingerprints/identifiers must already exist in the keyring. + foreach (var key in keys.Where(File.Exists)) { - foreach (var key in trustedKeys) + if (!await ImportGpgKeyAsync(commandRunner, key, cancellationToken)) { - await ImportGpgKeyAsync(key); + GeneralTracer.Warn($"LinuxSignatureHelper: failed to import key file '{key}'."); } } - // Verify signature - var startInfo = new ProcessStartInfo + foreach (var key in keys.Where(k => !File.Exists(k))) { - FileName = "gpg", - Arguments = $"--verify \"{signaturePath}\" \"{filePath}\"", - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; - - using var process = Process.Start(startInfo); - if (process != null) + if (!await KeyExistsInKeyringAsync(commandRunner, key, cancellationToken)) + { + GeneralTracer.Warn( + $"LinuxSignatureHelper: trusted key '{key}' is not in the keyring. " + + "Import it manually (gpg --import) or provide a key file path."); + } + } + + // Cryptographic verification (gpg writes its human output to stderr). + // --trust-model always: the Web-of-Trust check is not meaningful in minimal + // environments and would fail signatures from imported vendor keys; the actual + // trust decision is the explicit fingerprint match below. + var verify = await commandRunner.RunAsync( + "gpg", + new[] { "--verify", "--trust-model", "always", "--with-colons", "--with-fingerprint", signaturePath, filePath }, + cancellationToken); + + if (!verify.Success) { - var output = await process.StandardOutput.ReadToEndAsync(); - var error = await process.StandardError.ReadToEndAsync(); - await process.WaitForExitAsync(); + GeneralTracer.Warn($"LinuxSignatureHelper: signature verification failed. {verify.StandardError.Trim()}"); + return false; + } - // GPG verification output: {Output} // GPG outputs to stderr + // Fingerprint enforcement: when any fingerprint-form trusted entry is present, + // the signing key fingerprint must match one of them. + var fingerprints = keys.Where(IsFingerprint).ToList(); + if (fingerprints.Count > 0) + { + var signingFingerprints = ExtractFingerprints(verify.StandardOutput + verify.StandardError); + var matched = fingerprints.Any(f => signingFingerprints.Any(s => + s.Equals(f, StringComparison.OrdinalIgnoreCase) || + (f.Length == 16 && s.EndsWith(f, StringComparison.OrdinalIgnoreCase)))); - if (process.ExitCode == 0) - { - // GPG signature validation succeeded - return true; - } - else + if (!matched) { - // GPG signature validation failed + GeneralTracer.Warn( + "LinuxSignatureHelper: signature is valid but the signing key fingerprint " + + "does not match any trusted fingerprint."); return false; } } - return false; + return true; } catch (Exception ex) { @@ -94,44 +119,62 @@ public static async Task ValidateGpgSignatureAsync( } /// - /// 导入GPG公钥 - /// Imports GPG public key + /// 检查文件是否有GPG签名 + /// Checks if file has GPG signature /// - /// 公钥ID或文件路径 / Key ID or file path - private static async Task ImportGpgKeyAsync(string keyId) + /// 文件路径 / File path + /// 是否有签名 / Whether has signature + public static bool HasGpgSignature(string filePath) { - try + if (!File.Exists(filePath)) { - string arguments; - if (File.Exists(keyId)) - { - // Import from file - arguments = $"--import \"{keyId}\""; - } - else - { - // Import from keyserver - arguments = $"--keyserver keyserver.ubuntu.com --recv-keys {keyId}"; - } + return false; + } - var startInfo = new ProcessStartInfo - { - FileName = "gpg", - Arguments = arguments, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; - - using var process = Process.Start(startInfo); - if (process != null) - { - await process.WaitForExitAsync(); - return process.ExitCode == 0; - } + // Check for common signature file extensions + var signatureExtensions = new[] { ".sig", ".asc", ".sign" }; + return signatureExtensions.Any(ext => File.Exists(filePath + ext)); + } - return false; + /// + /// 判断信任项是否为密钥指纹(40 位完整指纹或 16 位短指纹,纯十六进制) + /// Checks whether a trusted entry looks like a key fingerprint (40 or 16 hex chars) + /// + public static bool IsFingerprint(string value) => + (value.Length == 40 || value.Length == 16) && + value.All(char.IsAsciiHexDigit); + + /// + /// 从 gpg --with-colons --with-fingerprint 输出中提取 fpr 行的指纹 + /// Extracts fingerprints from fpr: lines of colon-listing gpg output + /// + public static List ExtractFingerprints(string gpgOutput) + { + var result = new List(); + foreach (var line in gpgOutput.Split('\n')) + { + var trimmed = line.Trim(); + if (!trimmed.StartsWith("fpr:", StringComparison.Ordinal)) + continue; + + var parts = trimmed.Split(':'); + if (parts.Length > 9 && !string.IsNullOrEmpty(parts[9])) + result.Add(parts[9]); + } + + return result; + } + + private static async Task ImportGpgKeyAsync( + ICommandRunner commandRunner, + string keyFilePath, + CancellationToken cancellationToken) + { + try + { + var result = await commandRunner.RunAsync( + "gpg", new[] { "--import", keyFilePath }, cancellationToken); + return result.Success; } catch (Exception ex) { @@ -142,21 +185,21 @@ private static async Task ImportGpgKeyAsync(string keyId) } } - /// - /// 检查文件是否有GPG签名 - /// Checks if file has GPG signature - /// - /// 文件路径 / File path - /// 是否有签名 / Whether has signature - public static bool HasGpgSignature(string filePath) + private static async Task KeyExistsInKeyringAsync( + ICommandRunner commandRunner, + string keyIdentifier, + CancellationToken cancellationToken) { - if (!File.Exists(filePath)) + try + { + var result = await commandRunner.RunAsync( + "gpg", new[] { "--list-keys", keyIdentifier }, cancellationToken); + return result.Success; + } + catch (Exception ex) { + GeneralTracer.Warn($"LinuxSignatureHelper.KeyExistsInKeyringAsync: check failed. {ex.Message}"); return false; } - - // Check for common signature file extensions - var signatureExtensions = new[] { ".sig", ".asc", ".sign" }; - return signatureExtensions.Any(ext => File.Exists(filePath + ext)); } } diff --git a/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs b/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs index 98c380a8..bb894542 100644 --- a/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs +++ b/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs @@ -1,13 +1,14 @@ using System.Runtime.Versioning; -using GeneralUpdate.Drivelution; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Core.Utilities; namespace GeneralUpdate.Drivelution.Linux.Implementation; /// -/// Linux驱动备份实现 -/// Linux driver backup implementation +/// Linux驱动备份实现:备份驱动包(.deb/.rpm 单文件;.ko 及其所在目录下全部文件,含子目录;或 DKMS 源码树)。 +/// Linux driver backup: copies the driver package — a .deb/.rpm file as it is, a kernel module +/// together with every file and subdirectory next to it, or a DKMS source tree. /// [SupportedOSPlatform("linux")] public class LinuxDriverBackup : IDriverBackup @@ -22,35 +23,43 @@ public async Task BackupAsync( string backupPath, CancellationToken cancellationToken = default) { + GeneralTracer.Info($"Backing up driver package of {sourcePath} to {backupPath}"); + try { - if (!File.Exists(sourcePath)) + if (!File.Exists(sourcePath) && !Directory.Exists(sourcePath)) { - throw new FileNotFoundException($"Source file not found: {sourcePath}"); + throw new DriverBackupException($"Failed to backup driver: source not found: {sourcePath}") { CanRetry = false }; } - var backupDir = Path.GetDirectoryName(backupPath); - if (!string.IsNullOrEmpty(backupDir) && !Directory.Exists(backupDir)) + // A .deb/.rpm package installs on its own: it is backed up as the single file it is. + var isPackageFile = !Directory.Exists(sourcePath) + && Path.GetExtension(sourcePath).ToLowerInvariant() is ".deb" or ".rpm"; + if (isPackageFile) { - Directory.CreateDirectory(backupDir); + await DriverBackupFiles.CopyFileAsync( + sourcePath, Path.Combine(backupPath, Path.GetFileName(sourcePath)), cancellationToken); + GeneralTracer.Info($"Backup completed: {backupPath} ({Path.GetFileName(sourcePath)})"); + return true; } - var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); - var fileName = Path.GetFileNameWithoutExtension(backupPath); - var extension = Path.GetExtension(backupPath); - var backupPathWithTimestamp = Path.Combine( - backupDir ?? string.Empty, - $"{fileName}_{timestamp}{extension}"); - - using (var sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - using (var destinationStream = new FileStream(backupPathWithTimestamp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true)) - { - await sourceStream.CopyToAsync(destinationStream, cancellationToken); - } - - GeneralTracer.Info($"Backup completed: {backupPathWithTimestamp}"); + // A kernel module is loaded with the files it ships with, a source tree needs all of + // itself: the package around the source is backed up. + var packageRoot = DriverBackupFiles.GetPackageRoot(sourcePath); + DriverBackupFiles.EnsureBackupIsSeparate(backupPath, packageRoot); + var files = await DriverBackupFiles.CopyTreeAsync(packageRoot, backupPath, cancellationToken); + GeneralTracer.Info($"Backup completed: {backupPath} ({files} file(s))"); return true; } + catch (OperationCanceledException) + { + throw; + } + catch (DriverBackupException) + { + // Already what callers expect; a configuration error keeps its non-retryable verdict. + throw; + } catch (Exception ex) { GeneralTracer.Error("Failed to backup driver", ex); @@ -64,33 +73,19 @@ public async Task RestoreAsync( string targetPath, CancellationToken cancellationToken = default) { + GeneralTracer.Info($"Restoring driver from {backupPath} to {targetPath}"); + try { - if (!File.Exists(backupPath)) - { - throw new FileNotFoundException($"Backup file not found: {backupPath}"); - } - - var targetDir = Path.GetDirectoryName(targetPath); - if (!string.IsNullOrEmpty(targetDir) && !Directory.Exists(targetDir)) - { - Directory.CreateDirectory(targetDir); - } - - if (File.Exists(targetPath)) - { - File.Move(targetPath, $"{targetPath}.old", true); - } - - using (var sourceStream = new FileStream(backupPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - using (var destinationStream = new FileStream(targetPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true)) - { - await sourceStream.CopyToAsync(destinationStream, cancellationToken); - } + await DriverBackupFiles.RestoreAsync(backupPath, targetPath, cancellationToken); GeneralTracer.Info("Restore completed"); return true; } + catch (OperationCanceledException) + { + throw; + } catch (Exception ex) { GeneralTracer.Error("Failed to restore driver", ex); @@ -107,11 +102,18 @@ public async Task DeleteBackupAsync( { try { + if (Directory.Exists(backupPath)) + { + Directory.Delete(backupPath, recursive: true); + return true; + } + if (File.Exists(backupPath)) { File.Delete(backupPath); return true; } + return false; } catch (Exception ex) diff --git a/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs b/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs index f6e1c1d9..d2769174 100644 --- a/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs +++ b/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs @@ -1,7 +1,9 @@ using System.Runtime.Versioning; using GeneralUpdate.Drivelution; using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Execution; using GeneralUpdate.Drivelution.Core.Utilities; using GeneralUpdate.Drivelution.Linux.Helpers; @@ -14,10 +16,25 @@ namespace GeneralUpdate.Drivelution.Linux.Implementation; [SupportedOSPlatform("linux")] public class LinuxDriverValidator : IDriverValidator { + private readonly ICommandRunner _commandRunner; + private readonly DrivelutionOptions? _options; + public LinuxDriverValidator() + : this(new CommandRunner()) { } + /// + /// Initializes a new validator with a command runner and optional options. + /// Options' are merged with per-driver + /// trusted publishers during signature validation. + /// + public LinuxDriverValidator(ICommandRunner commandRunner, DrivelutionOptions? options = null) + { + _commandRunner = commandRunner ?? throw new ArgumentNullException(nameof(commandRunner)); + _options = options; + } + /// public async Task ValidateIntegrityAsync( string filePath, @@ -32,8 +49,17 @@ public async Task ValidateIntegrityAsync( public async Task ValidateSignatureAsync( string filePath, IEnumerable trustedPublishers, + IEnumerable? trustedThumbprints = null, CancellationToken cancellationToken = default) { + // The certificate-thumbprint concept is Windows-only; on Linux the trusted GPG entries + // from options are merged with the per-driver publishers. + var trustedKeys = trustedPublishers + .Concat(_options?.TrustedGpgKeys ?? Enumerable.Empty()) + .Where(k => !string.IsNullOrWhiteSpace(k)) + .Distinct() + .ToList(); + // Check for GPG signature file var signaturePath = filePath + ".sig"; if (!File.Exists(signaturePath)) @@ -43,11 +69,12 @@ public async Task ValidateSignatureAsync( if (File.Exists(signaturePath)) { - return await LinuxSignatureHelper.ValidateGpgSignatureAsync(filePath, signaturePath, trustedPublishers); + return await LinuxSignatureHelper.ValidateGpgSignatureAsync( + _commandRunner, filePath, signaturePath, trustedKeys, cancellationToken); } GeneralTracer.Warn($"No signature file found for: {filePath}"); - return !trustedPublishers.Any(); // If no trusted publishers specified, accept unsigned + return trustedKeys.Count == 0; // If no trusted publishers specified, accept unsigned } /// diff --git a/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs b/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs index 4ee57e3b..cabc559d 100644 --- a/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs +++ b/src/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs @@ -14,8 +14,14 @@ namespace GeneralUpdate.Drivelution.Linux.Implementation; /// /// Linux driver updater implementation. /// Inherits the unified pipeline from and adds Linux-specific -/// sudo permission check, kernel module / .deb / .rpm installation, and module parsing. +/// root permission check, kernel module installation through /lib/modules (+depmod) with +/// DKMS support, .deb/.rpm package installation with dependency repair, and module parsing. /// +/// +/// Rollback semantics: backups produced from the installed module (Source=installed) are restored +/// into /lib/modules followed by depmod+modprobe; package-based backups of fresh installs remove +/// the newly installed module/package instead. +/// [SupportedOSPlatform("linux")] public class LinuxGeneralDrivelution : BaseDriverUpdater { @@ -28,12 +34,14 @@ public class LinuxGeneralDrivelution : BaseDriverUpdater /// Driver backup manager. /// Command runner for Linux operations. /// Configuration options (optional). + /// Network downloader for DownloadUrl scenarios (optional). public LinuxGeneralDrivelution( IDriverValidator validator, IDriverBackup backup, ICommandRunner commandRunner, - DrivelutionOptions? options = null) - : base(validator, backup, options) + DrivelutionOptions? options = null, + INetworkDownloader? downloader = null) + : base(validator, backup, options, downloader) { _commandRunner = commandRunner ?? throw new ArgumentNullException(nameof(commandRunner)); } @@ -43,7 +51,12 @@ public LinuxGeneralDrivelution( /// protected override IEnumerable GetPipelineSteps(UpdateStrategy strategy) { - yield return CreateSudoCheckStep(); + yield return DefaultPipelineSteps.CreatePermissionCheckStep( + "CheckRoot", + () => LinuxPermissionHelper.IsRoot() + ? null + : "Root privileges are required for driver updates. " + + "Please run this application with sudo or as root."); foreach (var step in base.GetPipelineSteps(strategy)) yield return step; @@ -51,35 +64,78 @@ protected override IEnumerable GetPipelineSteps(UpdateStrategy st /// protected override async Task InstallCoreAsync( - DriverInfo driverInfo, - UpdateStrategy strategy, + PipelineContext context, CancellationToken cancellationToken) { + var driverInfo = context.DriverInfo; GeneralTracer.Info($"Installing Linux driver: {driverInfo.FilePath}"); - var extension = Path.GetExtension(driverInfo.FilePath).ToLowerInvariant(); - - switch (extension) + if (Directory.Exists(driverInfo.FilePath) && + File.Exists(Path.Combine(driverInfo.FilePath, "dkms.conf"))) + { + await InstallDriverUsingDkmsAsync(context, driverInfo.FilePath, cancellationToken); + } + else { - case ".ko": - await InstallKernelModuleAsync(driverInfo.FilePath, cancellationToken); - break; - case ".deb": - await InstallDebPackageAsync(driverInfo.FilePath, cancellationToken); - break; - case ".rpm": - await InstallRpmPackageAsync(driverInfo.FilePath, cancellationToken); - break; - default: - GeneralTracer.Warn($"Unknown driver format: {extension}. Attempting generic installation."); - await InstallKernelModuleAsync(driverInfo.FilePath, cancellationToken); - break; + var extension = Path.GetExtension(driverInfo.FilePath).ToLowerInvariant(); + + switch (extension) + { + case ".ko": + await InstallKernelModuleAsync(context, driverInfo.FilePath, cancellationToken); + break; + case ".deb": + await InstallDebPackageAsync(driverInfo.FilePath, cancellationToken); + break; + case ".rpm": + await InstallRpmPackageAsync(driverInfo.FilePath, cancellationToken); + break; + default: + throw new DriverInstallationException( + $"Unsupported Linux driver format: '{extension}'. " + + "Supported formats: .ko, .deb, .rpm, and DKMS source trees (dkms.conf)."); + } } GeneralTracer.Info("Linux driver installation completed"); } - // ─── Rollback override ───────────────────────────────────────────── + // ─── Backup hook: preserve the currently installed module file ───── + + /// + protected override async Task TryBackupInstalledDriverAsync( + DriverInfo driverInfo, + string backupDirectory, + CancellationToken cancellationToken) + { + try + { + var extension = Path.GetExtension(driverInfo.FilePath).ToLowerInvariant(); + if (extension != ".ko") + return false; + + var release = await GetKernelReleaseAsync(cancellationToken); + var updatesDir = $"/lib/modules/{release}/updates"; + var moduleFileName = Path.GetFileName(driverInfo.FilePath); + var installedModulePath = Path.Combine(updatesDir, moduleFileName); + + if (!File.Exists(installedModulePath)) + return false; // fresh install; caller falls back to copying the local package + + Directory.CreateDirectory(backupDirectory); + var target = Path.Combine(backupDirectory, moduleFileName); + File.Copy(installedModulePath, target, overwrite: true); + GeneralTracer.Info($"Exported installed module '{installedModulePath}' for backup."); + return true; + } + catch (Exception ex) + { + GeneralTracer.Warn($"Failed to export installed module: {ex.Message}"); + return false; + } + } + + // ─── Rollback: restore the previous module / remove fresh installs ── /// public override async Task RollbackAsync( @@ -96,43 +152,174 @@ public override async Task RollbackAsync( return false; } - var koFiles = Directory.GetFiles(backupPath, "*.ko", SearchOption.AllDirectories); + var manifest = BackupManifestStore.Load(backupPath); + var installState = InstallStateStore.Load(backupPath); + var backupFiles = Directory.GetFiles(backupPath, "*.*", SearchOption.AllDirectories) + .Where(f => !Path.GetFileName(f).Equals(BackupManifest.ManifestFileName, StringComparison.OrdinalIgnoreCase) && + !Path.GetFileName(f).Equals(InstallState.InstallStateFileName, StringComparison.OrdinalIgnoreCase)) + .ToList(); - if (koFiles.Length == 0) + if (backupFiles.Count == 0) { - GeneralTracer.Warn($"No kernel module backups found in: {backupPath}"); + GeneralTracer.Warn($"No backup files found in: {backupPath}"); return false; } - foreach (var koFile in koFiles) + var source = manifest?.Source ?? BackupManifest.SourcePackage; + + // ── DKMS install: remove the built/installed module set first ── + if (!string.IsNullOrEmpty(installState?.DkmsModule)) { try { - var moduleName = Path.GetFileNameWithoutExtension(koFile); - GeneralTracer.Info($"Restoring kernel module: {moduleName}"); + GeneralTracer.Info($"Removing DKMS module: {installState.DkmsModule} {installState.DkmsVersion}"); + await _commandRunner.RunOrThrowAsync( + "dkms", + new[] { "remove", "-m", installState.DkmsModule, "-v", installState.DkmsVersion, "--all" }, + cancellationToken); + + var dkmsSourceDir = $"/usr/src/{installState.DkmsModule}-{installState.DkmsVersion}"; + if (Directory.Exists(dkmsSourceDir)) + { + Directory.Delete(dkmsSourceDir, recursive: true); + } + + return true; + } + catch (Exception ex) + { + GeneralTracer.Error($"DKMS rollback failed: {ex.Message}"); + return false; + } + } + var release = await GetKernelReleaseAsync(cancellationToken); + var updatesDir = $"/lib/modules/{release}/updates"; + var failures = new List(); + + // ── .deb backup: reinstall the old package (downgrade) or remove the fresh one ── + foreach (var debFile in backupFiles.Where(f => f.EndsWith(".deb", StringComparison.OrdinalIgnoreCase))) + { + try + { + if (source == BackupManifest.SourceInstalled) + { + GeneralTracer.Info($"Downgrading to backed-up package: {debFile}"); + await _commandRunner.RunOrThrowAsync("dpkg", new[] { "-i", debFile }, cancellationToken); + } + else + { + var packageName = await GetDebPackageNameAsync(debFile, cancellationToken); + if (!string.IsNullOrEmpty(packageName)) + { + GeneralTracer.Info($"Removing freshly installed package: {packageName}"); + await RunQuietAsync("dpkg", new[] { "-r", packageName }, cancellationToken); + } + } + } + catch (Exception ex) + { + failures.Add($"{Path.GetFileName(debFile)}: {ex.Message}"); + } + } - // Unload current module first + // ── .rpm backup ── + foreach (var rpmFile in backupFiles.Where(f => f.EndsWith(".rpm", StringComparison.OrdinalIgnoreCase))) + { + try + { + if (source == BackupManifest.SourceInstalled) + { + GeneralTracer.Info($"Downgrading to backed-up package: {rpmFile}"); + await _commandRunner.RunOrThrowAsync( + "rpm", new[] { "-Uvh", "--oldpackage", rpmFile }, cancellationToken); + } + else + { + var packageName = await GetRpmPackageNameAsync(rpmFile, cancellationToken); + if (!string.IsNullOrEmpty(packageName)) + { + GeneralTracer.Info($"Removing freshly installed package: {packageName}"); + await RunQuietAsync("rpm", new[] { "-e", packageName }, cancellationToken); + } + } + } + catch (Exception ex) + { + failures.Add($"{Path.GetFileName(rpmFile)}: {ex.Message}"); + } + } + + // ── .ko backup: restore into /lib/modules + depmod + modprobe, or remove fresh install ── + var koFiles = backupFiles.Where(f => f.EndsWith(".ko", StringComparison.OrdinalIgnoreCase)).ToList(); + if (koFiles.Count > 0) + { + foreach (var koFile in koFiles) + { + var moduleName = Path.GetFileNameWithoutExtension(koFile); try { - await _commandRunner.RunOrThrowAsync("modprobe", new[] { "-r", moduleName }, cancellationToken); + // Unload the module first; being not loaded is fine. + await RunQuietAsync("modprobe", new[] { "-r", moduleName }, cancellationToken); + + if (source == BackupManifest.SourceInstalled) + { + Directory.CreateDirectory(updatesDir); + var targetPath = Path.Combine(updatesDir, Path.GetFileName(koFile)); + File.Copy(koFile, targetPath, overwrite: true); + GeneralTracer.Info($"Restored module file: {targetPath}"); + } + else + { + // Fresh install: the backup holds a copy of the incoming module — remove it. + var installedPath = !string.IsNullOrEmpty(installState?.ModuleTargetPath) + ? installState.ModuleTargetPath + : Path.Combine(updatesDir, Path.GetFileName(koFile)); + if (File.Exists(installedPath)) + { + File.Delete(installedPath); + GeneralTracer.Info($"Removed freshly installed module: {installedPath}"); + } + } } - catch + catch (Exception ex) { - // Module might not be loaded — ignore + failures.Add($"{moduleName}: {ex.Message}"); } + } - // Reload the backed-up module - await _commandRunner.RunOrThrowAsync("insmod", new[] { koFile }, cancellationToken); - GeneralTracer.Info($"Restored module: {moduleName}"); + // Rebuild module dependencies and reload the restored modules. + try + { + await _commandRunner.RunOrThrowAsync("depmod", new[] { "-a" }, cancellationToken); + + if (source == BackupManifest.SourceInstalled) + { + foreach (var koFile in koFiles) + { + var moduleName = Path.GetFileNameWithoutExtension(koFile); + await _commandRunner.RunOrThrowAsync("modprobe", new[] { moduleName }, cancellationToken); + GeneralTracer.Info($"Reloaded module: {moduleName}"); + } + } } catch (Exception ex) { - GeneralTracer.Warn($"Failed to restore module: {koFile} - {ex.Message}"); + failures.Add($"depmod/modprobe: {ex.Message}"); } } + if (failures.Count > 0) + { + GeneralTracer.Error($"Linux rollback finished with failures: {string.Join("; ", failures)}"); + return false; + } + return true; } + catch (OperationCanceledException) + { + throw; + } catch (Exception ex) { GeneralTracer.Error("Linux driver rollback failed", ex); @@ -140,6 +327,79 @@ public override async Task RollbackAsync( } } + // ─── Installed driver inventory ──────────────────────────────────── + + /// + public override async Task> GetInstalledDriversAsync( + CancellationToken cancellationToken = default) + { + var drivers = new List(); + + // Loaded kernel modules first. + var lsmod = await RunQuietAsync("lsmod", Array.Empty(), cancellationToken); + if (string.IsNullOrEmpty(lsmod)) + return drivers; + + var moduleNames = lsmod + .Split('\n') + .Skip(1) // first line is the header + .Select(line => line.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries)) + .Where(columns => columns.Length > 0 && !string.IsNullOrEmpty(columns[0])) + .Select(columns => columns[0]) + .Distinct() + .ToList(); + + // Enrich with modinfo in parallel (bounded) — hundreds of modules would make a + // sequential enumeration painfully slow. + using var gate = new SemaphoreSlim(4); + var enrichTasks = moduleNames.Select(async moduleName => + { + await gate.WaitAsync(cancellationToken); + try + { + var driver = new InstalledDriverInfo + { + Name = moduleName, + Version = "unknown", + Provider = "kernel" + }; + + var info = await RunQuietAsync("modinfo", new[] { moduleName }, cancellationToken); + if (!string.IsNullOrEmpty(info)) + { + foreach (var infoLine in info.Split('\n')) + { + var trimmed = infoLine.Trim(); + if (trimmed.StartsWith("version:", StringComparison.OrdinalIgnoreCase) && + trimmed.Length > 8) + { + driver.Version = trimmed[8..].Trim(); + } + else if (trimmed.StartsWith("description:", StringComparison.OrdinalIgnoreCase) && + trimmed.Length > 12) + { + driver.Provider = trimmed[12..].Trim(); + } + } + + var modPath = await RunQuietAsync("modinfo", new[] { "-n", moduleName }, cancellationToken); + driver.FilePath = modPath.Trim(); + } + + return driver; + } + finally + { + gate.Release(); + } + }).ToList(); + + var enriched = await Task.WhenAll(enrichTasks); + drivers.AddRange(enriched); + + return drivers; + } + // ─── Driver discovery overrides ──────────────────────────────────── /// @@ -205,54 +465,119 @@ public override async Task> GetDriversFromDirectoryAsync( return drivers; } - // ─── Private: Pipeline steps ──────────────────────────────────────── + // ─── Private: Format-specific installers ─────────────────────────── /// - /// Creates a sudo privilege check as the first pipeline step. + /// Installs a kernel module the standard way: copy into /lib/modules/{release}/updates, + /// rebuild module dependencies (depmod), then load by name (modprobe). Falls back to a + /// direct insmod when the standard tree is not writable. + /// Never falls back to `modprobe <name>` after a failed insmod — that would silently load + /// an older module of the same name from the standard paths. /// - private static IPipelineStep CreateSudoCheckStep() + private async Task InstallKernelModuleAsync( + PipelineContext context, + string modulePath, + CancellationToken cancellationToken) { - return new DelegateStep("CheckSudo", - execute: async (context, ct) => - { - context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Checking Linux root privileges"); + GeneralTracer.Info($"Installing kernel module: {modulePath}"); - try - { - await LinuxPermissionHelper.EnsureSudoAsync(); - return PipelineResult.Ok(); - } - catch (Exception ex) + string release; + try + { + release = await GetKernelReleaseAsync(cancellationToken); + var updatesDir = $"/lib/modules/{release}/updates"; + Directory.CreateDirectory(updatesDir); + + var targetPath = Path.Combine(updatesDir, Path.GetFileName(modulePath)); + File.Copy(modulePath, targetPath, overwrite: true); + GeneralTracer.Info($"Module copied to {targetPath}"); + + // Persist for rollback: install_state.json in the backup dir (when one exists). + var backupDirectory = context.Result.BackupPath; + if (!string.IsNullOrEmpty(backupDirectory)) + { + InstallStateStore.TrySave(new InstallState { - return PipelineResult.Fail( - $"Root privileges are required for driver updates. {ex.Message}"); - } - }); - } + KernelRelease = release, + ModuleTargetPath = targetPath, + Platform = "Linux" + }, backupDirectory); + } - // ─── Private: Format-specific installers ─────────────────────────── + // Rebuild module dependency tables so modprobe resolves the new module. + await _commandRunner.RunOrThrowAsync("depmod", new[] { "-a" }, cancellationToken); + var moduleName = Path.GetFileNameWithoutExtension(modulePath); + await _commandRunner.RunOrThrowAsync("modprobe", new[] { moduleName }, cancellationToken); + GeneralTracer.Info($"Module loaded via modprobe: {moduleName}"); + return; + } + catch (OperationCanceledException) + { + throw; + } + catch (DriverInstallationException) + { + throw; + } + catch (Exception ex) + { + // The standard /lib/modules flow failed (read-only tree, unusual layout, ...). + GeneralTracer.Warn($"InstallKernelModuleAsync: standard flow failed ({ex.Message}); falling back to direct insmod."); + } - private async Task InstallKernelModuleAsync( - string modulePath, + // Fallback: load directly from the given path. On failure there is no safe fallback — + // surfacing the error avoids silently loading a different module version. + await _commandRunner.RunOrThrowAsync("insmod", new[] { modulePath }, cancellationToken); + GeneralTracer.Info("Module loaded via insmod"); + } + + /// + /// Installs a DKMS source tree (directory containing dkms.conf): copies it to + /// /usr/src/{name}-{version}, then dkms add/build/install. + /// + private async Task InstallDriverUsingDkmsAsync( + PipelineContext context, + string sourceDirectory, CancellationToken cancellationToken) { - GeneralTracer.Info($"Installing kernel module: {modulePath}"); + GeneralTracer.Info($"Installing driver via DKMS: {sourceDirectory}"); - try + var (moduleName, moduleVersion) = ParseDkmsConf(Path.Combine(sourceDirectory, "dkms.conf")); + + if (string.IsNullOrEmpty(moduleName) || string.IsNullOrEmpty(moduleVersion)) { - await _commandRunner.RunOrThrowAsync("insmod", new[] { modulePath }, cancellationToken); - GeneralTracer.Info("Module loaded via insmod"); + throw new DriverInstallationException( + "dkms.conf is missing PACKAGE_NAME or PACKAGE_VERSION; cannot install via DKMS."); } - catch (Exception ex) when (ex is not OperationCanceledException) + + var targetDir = $"/usr/src/{moduleName}-{moduleVersion}"; + if (Directory.Exists(targetDir)) { - // Fallback: modprobe with the module name. Keep the insmod failure reason — - // if modprobe also fails, the root cause must not be lost. Cancellation - // propagates instead of triggering the fallback. - GeneralTracer.Warn($"InstallKernelModuleAsync: insmod failed ({ex.Message}), falling back to modprobe."); - var moduleName = Path.GetFileNameWithoutExtension(modulePath); - await _commandRunner.RunOrThrowAsync("modprobe", new[] { moduleName }, cancellationToken); - GeneralTracer.Info("Module loaded via modprobe"); + Directory.Delete(targetDir, recursive: true); + } + + CopyDirectory(sourceDirectory, targetDir); + + await _commandRunner.RunOrThrowAsync("dkms", new[] { "add", "-m", moduleName, "-v", moduleVersion }, cancellationToken); + await _commandRunner.RunOrThrowAsync("dkms", new[] { "build", "-m", moduleName, "-v", moduleVersion }, cancellationToken); + await _commandRunner.RunOrThrowAsync("dkms", new[] { "install", "-m", moduleName, "-v", moduleVersion, "--force" }, cancellationToken); + + context.Bag["DkmsModuleName"] = moduleName; + context.Bag["DkmsModuleVersion"] = moduleVersion; + + // Persist for rollback: install_state.json in the backup dir (when one exists). + var backupDirectory = context.Result.BackupPath; + if (!string.IsNullOrEmpty(backupDirectory)) + { + InstallStateStore.TrySave(new InstallState + { + DkmsModule = moduleName, + DkmsVersion = moduleVersion, + Platform = "Linux" + }, backupDirectory); } + + GeneralTracer.Info($"DKMS module installed: {moduleName} {moduleVersion}"); } private async Task InstallDebPackageAsync( @@ -260,7 +585,38 @@ private async Task InstallDebPackageAsync( CancellationToken cancellationToken) { GeneralTracer.Info($"Installing Debian package: {packagePath}"); - await _commandRunner.RunOrThrowAsync("dpkg", new[] { "-i", packagePath }, cancellationToken); + + try + { + await _commandRunner.RunOrThrowAsync("dpkg", new[] { "-i", packagePath }, cancellationToken); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + // Most common dpkg failure is unsatisfied dependencies; repair them via apt and + // re-run the install. Keep the original failure for diagnosis when repair also fails. + GeneralTracer.Warn($"InstallDebPackageAsync: dpkg -i failed ({ex.Message}); attempting apt-get -f install."); + + try + { + await _commandRunner.RunOrThrowAsync("apt-get", new[] { "install", "-f", "-y" }, cancellationToken); + await _commandRunner.RunOrThrowAsync("dpkg", new[] { "-i", packagePath }, cancellationToken); + GeneralTracer.Info("Debian package installed after dependency repair"); + return; + } + catch (Exception repairEx) + { + throw new DriverInstallationException( + $"dpkg -i failed and dependency repair did not help. " + + $"Original error: {ex.Message}; repair error: {repairEx.Message}", + innerException: repairEx, + canRetry: false); + } + } + GeneralTracer.Info("Debian package installed"); } @@ -274,18 +630,122 @@ private async Task InstallRpmPackageAsync( { await _commandRunner.RunOrThrowAsync("rpm", new[] { "-ivh", packagePath }, cancellationToken); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (OperationCanceledException) { - // Fallback to dnf/yum. Log the rpm failure first — if dnf also fails the - // propagated dnf exception would otherwise mask the original cause. - // Cancellation propagates instead of triggering the fallback. + throw; + } + catch (Exception ex) + { + // Fallback to dnf. Keep the rpm failure reason — if dnf also fails the propagated + // dnf exception would otherwise mask the original cause. GeneralTracer.Warn($"InstallRpmPackageAsync: rpm -ivh failed ({ex.Message}), falling back to dnf."); - await _commandRunner.RunOrThrowAsync("dnf", new[] { "install", "-y", packagePath }, cancellationToken); + + try + { + await _commandRunner.RunOrThrowAsync("dnf", new[] { "install", "-y", packagePath }, cancellationToken); + } + catch (Exception dnfEx) + { + throw new DriverInstallationException( + $"rpm -ivh failed and dnf fallback failed. " + + $"Original error: {ex.Message}; dnf error: {dnfEx.Message}", + innerException: dnfEx, + canRetry: false); + } } GeneralTracer.Info("RPM package installed"); } + // ─── Private: Helpers ────────────────────────────────────────────── + + private async Task GetKernelReleaseAsync(CancellationToken cancellationToken) + { + var result = await _commandRunner.RunOrThrowAsync("uname", new[] { "-r" }, cancellationToken); + return result.StandardOutput.Trim(); + } + + /// + /// Runs a command ignoring failures; returns stdout on success, empty string otherwise. + /// + private async Task RunQuietAsync( + string command, + string[] arguments, + CancellationToken cancellationToken) + { + try + { + var result = await _commandRunner.RunAsync(command, arguments, cancellationToken); + return result.Success ? result.StandardOutput : string.Empty; + } + catch (Exception ex) + { + GeneralTracer.Debug($"RunQuietAsync: {command} failed: {ex.Message}"); + return string.Empty; + } + } + + private async Task GetDebPackageNameAsync(string debPath, CancellationToken cancellationToken) + { + var output = await RunQuietAsync("dpkg-deb", new[] { "-f", debPath, "Package" }, cancellationToken); + return output.Trim(); + } + + private async Task GetRpmPackageNameAsync(string rpmPath, CancellationToken cancellationToken) + { + var output = await RunQuietAsync("rpm", new[] { "-q", "--qf", "%{NAME}", "-p", rpmPath }, cancellationToken); + return output.Trim(); + } + + /// + /// Parses PACKAGE_NAME / PACKAGE_VERSION from a dkms.conf file (shell-style assignments). + /// + private static (string Name, string Version) ParseDkmsConf(string dkmsConfPath) + { + string? name = null; + string? version = null; + + try + { + foreach (var rawLine in File.ReadAllLines(dkmsConfPath)) + { + var line = rawLine.Trim(); + if (line.StartsWith('#') || !line.Contains('=')) + continue; + + var eq = line.IndexOf('='); + var key = line[..eq].Trim(); + var value = line[(eq + 1)..].Trim().Trim('"', '\''); + + if (key.Equals("PACKAGE_NAME", StringComparison.OrdinalIgnoreCase)) + name = value; + else if (key.Equals("PACKAGE_VERSION", StringComparison.OrdinalIgnoreCase)) + version = value; + } + } + catch (Exception ex) + { + GeneralTracer.Warn($"ParseDkmsConf failed for '{dkmsConfPath}': {ex.Message}"); + } + + return (name ?? string.Empty, version ?? string.Empty); + } + + private static void CopyDirectory(string sourceDir, string targetDir) + { + Directory.CreateDirectory(targetDir); + + foreach (var file in Directory.GetFiles(sourceDir)) + { + File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), overwrite: true); + } + + foreach (var dir in Directory.GetDirectories(sourceDir)) + { + CopyDirectory(dir, Path.Combine(targetDir, Path.GetFileName(dir))); + } + } + // ─── Private: File parsing ───────────────────────────────────────── private async Task ParseLinuxDriverFileAsync( @@ -317,10 +777,10 @@ private async Task InstallRpmPackageAsync( break; } - // Compute file hash for integrity validation - driverInfo.Hash = await HashValidator.ComputeHashAsync( + // Record the computed hash as diagnostics only — never as an integrity expectation + // (self-computed hashes validate nothing). + driverInfo.Metadata["ComputedSHA256"] = await HashValidator.ComputeHashAsync( filePath, "SHA256", cancellationToken); - driverInfo.HashAlgorithm = "SHA256"; return driverInfo; } diff --git a/src/GeneralUpdate.Drivelution/MacOS/Helpers/MacOSPermissionHelper.cs b/src/GeneralUpdate.Drivelution/MacOS/Helpers/MacOSPermissionHelper.cs deleted file mode 100644 index 3dcccb81..00000000 --- a/src/GeneralUpdate.Drivelution/MacOS/Helpers/MacOSPermissionHelper.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using GeneralUpdate.Drivelution.Abstractions.Exceptions; - -namespace GeneralUpdate.Drivelution.MacOS.Helpers; - -/// -/// macOS权限助手 -/// macOS permission helper -/// -[SupportedOSPlatform("macos")] -public static class MacOSPermissionHelper -{ - [DllImport("libc", EntryPoint = "geteuid", SetLastError = true)] - private static extern uint _geteuid(); - - /// - /// 检查当前用户是否具有root权限 - /// Checks if current user has root privileges (euid == 0) - /// - /// 是否具有root权限 / Whether has root privileges - public static bool IsRoot() - { - try - { - return _geteuid() == 0; - } - catch - { - // Failed to check root privileges via P/Invoke - return false; - } - } - - /// - /// 确保root权限,如无则抛出异常 - /// Ensures root privileges, throws exception if not - /// - public static void EnsureRoot() - { - if (!IsRoot()) - { - throw new DriverPermissionException( - "Root privileges are required to perform driver updates on macOS. " + - "Please run this application with sudo or as root user."); - } - } -} diff --git a/src/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs b/src/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs deleted file mode 100644 index 509bff0c..00000000 --- a/src/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs +++ /dev/null @@ -1,596 +0,0 @@ -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using GeneralUpdate.Drivelution; -using GeneralUpdate.Drivelution.Abstractions; -using GeneralUpdate.Drivelution.Abstractions.Configuration; -using GeneralUpdate.Drivelution.Abstractions.Exceptions; -using GeneralUpdate.Drivelution.Abstractions.Models; -using GeneralUpdate.Drivelution.Core.Execution; -using GeneralUpdate.Drivelution.Core.Pipeline; -using GeneralUpdate.Drivelution.Core.Utilities; -using GeneralUpdate.Drivelution.MacOS.Helpers; - -namespace GeneralUpdate.Drivelution.MacOS.Implementation; - -/// -/// macOS driver updater implementation. -/// Inherits the unified pipeline from and supports -/// .kext, .dext, and .pkg driver formats via command-line tools. -/// -/// -/// Current limitations: -/// - .kext installation requires SIP to be disabled on Apple Silicon (kextload is deprecated) -/// - .dext (DriverKit) requires user approval in System Preferences → Security & Privacy -/// -[SupportedOSPlatform("macos")] -public class MacOsGeneralDrivelution : BaseDriverUpdater -{ - private readonly ICommandRunner _commandRunner; - - /// - /// Initializes a new instance. - /// - public MacOsGeneralDrivelution( - IDriverValidator validator, - IDriverBackup backup, - ICommandRunner commandRunner, - DrivelutionOptions? options = null) - : base(validator, backup, options) - { - _commandRunner = commandRunner ?? throw new ArgumentNullException(nameof(commandRunner)); - } - - // ─── Pipeline overrides ──────────────────────────────────────────── - - /// - protected override IEnumerable GetPipelineSteps(UpdateStrategy strategy) - { - yield return CreateSudoCheckStep(); - - foreach (var step in base.GetPipelineSteps(strategy)) - yield return step; - } - - /// - protected override async Task InstallCoreAsync( - DriverInfo driverInfo, - UpdateStrategy strategy, - CancellationToken cancellationToken) - { - var extension = Path.GetExtension(driverInfo.FilePath).ToLowerInvariant(); - - switch (extension) - { - case ".kext": - await InstallKextAsync(driverInfo.FilePath, cancellationToken); - break; - case ".dext": - await InstallDextAsync(driverInfo.FilePath, cancellationToken); - break; - case ".pkg": - await InstallPkgAsync(driverInfo.FilePath, cancellationToken); - break; - default: - GeneralTracer.Warn($"Unknown macOS driver format: {extension}"); - throw new DriverInstallationException( - $"Unsupported macOS driver format: {extension}. " + - "Supported formats: .kext, .dext, .pkg"); - } - - GeneralTracer.Info("macOS driver installation completed"); - } - - // ─── Rollback override ───────────────────────────────────────────── - - /// - public override async Task RollbackAsync( - string backupPath, - CancellationToken cancellationToken = default) - { - try - { - GeneralTracer.Info($"Rolling back macOS driver from backup: {backupPath}"); - - if (!Directory.Exists(backupPath)) - { - GeneralTracer.Error($"Backup directory not found: {backupPath}"); - return false; - } - - // Restore backed-up kext files - var kextFiles = Directory.GetFiles(backupPath, "*.kext", SearchOption.AllDirectories); - foreach (var kextFile in kextFiles) - { - try - { - var kextName = Path.GetFileName(kextFile); - GeneralTracer.Info($"Restoring kext: {kextName}"); - - // Copy back to /Library/Extensions/ - var targetPath = $"/Library/Extensions/{kextName}"; - if (File.Exists(targetPath)) - File.Delete(targetPath); - - Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!); - CopyDirectory(kextFile, targetPath); - - // Reload the kext - await _commandRunner.RunAsync("kextload", new[] { targetPath }, cancellationToken); - GeneralTracer.Info($"Restored kext: {kextName}"); - } - catch (Exception ex) - { - GeneralTracer.Warn($"Failed to restore kext: {kextFile} - {ex.Message}"); - } - } - - return true; - } - catch (Exception ex) - { - GeneralTracer.Error("macOS driver rollback failed", ex); - return false; - } - } - - // ─── Driver discovery overrides ──────────────────────────────────── - - /// - protected override string GetDefaultSearchPattern() => "*.kext"; - - /// - public override async Task> GetDriversFromDirectoryAsync( - string directoryPath, - string? searchPattern = null, - CancellationToken cancellationToken = default) - { - var drivers = new List(); - - try - { - GeneralTracer.Info($"Reading macOS drivers from directory: {directoryPath}"); - - if (!Directory.Exists(directoryPath)) - { - GeneralTracer.Warn($"Directory not found: {directoryPath}"); - return drivers; - } - - // Collect .kext, .dext, and .pkg files - var files = new List(); - if (searchPattern is not null) - { - files.AddRange(Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories)); - } - else - { - files.AddRange(Directory.GetFiles(directoryPath, "*.kext", SearchOption.AllDirectories)); - files.AddRange(Directory.GetFiles(directoryPath, "*.dext", SearchOption.AllDirectories)); - files.AddRange(Directory.GetFiles(directoryPath, "*.pkg", SearchOption.AllDirectories)); - } - - GeneralTracer.Info($"Found {files.Count} macOS driver file(s)"); - - foreach (var filePath in files) - { - if (cancellationToken.IsCancellationRequested) - break; - - try - { - var info = await ParseMacOSDriverFileAsync(filePath, cancellationToken); - if (info is not null) - drivers.Add(info); - } - catch (Exception ex) - { - GeneralTracer.Warn($"Failed to parse driver file: {filePath} - {ex.Message}"); - } - } - - GeneralTracer.Info($"Loaded {drivers.Count} macOS driver(s) from directory"); - } - catch (Exception ex) - { - GeneralTracer.Error($"Error reading macOS drivers: {ex.Message}", ex); - } - - return drivers; - } - - // ─── Private: Pipeline steps ─────────────────────────────────────── - - private static IPipelineStep CreateSudoCheckStep() - { - return new DelegateStep("CheckSudo", - execute: (context, ct) => - { - context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Checking macOS root privileges"); - try - { - MacOSPermissionHelper.EnsureRoot(); - return Task.FromResult(PipelineResult.Ok()); - } - catch (DriverPermissionException ex) - { - return Task.FromResult(PipelineResult.Fail(ex.Message)); - } - }); - } - - // ─── Private: Format-specific installers ─────────────────────────── - - private async Task InstallKextAsync( - string kextPath, - CancellationToken cancellationToken) - { - GeneralTracer.Info($"Installing kernel extension: {kextPath}"); - - var kextName = Path.GetFileName(kextPath); - var targetPath = $"/Library/Extensions/{kextName}"; - - // Copy kext to Extensions directory - if (Directory.Exists(kextPath)) - { - // kext is a bundle (directory) - if (Directory.Exists(targetPath)) - Directory.Delete(targetPath, recursive: true); - - CopyDirectory(kextPath, targetPath); - } - else - { - File.Copy(kextPath, targetPath, overwrite: true); - } - - // Fix permissions (kexts must be owned by root:wheel) - await _commandRunner.RunAsync("chown", new[] { "-R", "root:wheel", targetPath }, cancellationToken); - await _commandRunner.RunAsync("chmod", new[] { "-R", "755", targetPath }, cancellationToken); - - // Load the kext - await _commandRunner.RunOrThrowAsync("kextload", new[] { targetPath }, cancellationToken); - - // Update kext cache - await _commandRunner.RunAsync("kextcache", new[] { "-i", "/" }, cancellationToken); - - GeneralTracer.Info($"Kernel extension installed: {kextName}"); - } - - private async Task InstallDextAsync( - string dextPath, - CancellationToken cancellationToken) - { - GeneralTracer.Info($"Installing DriverKit extension: {dextPath}"); - - // Copy to standard SystemExtensions location - var dextName = Path.GetFileName(dextPath); - var targetPath = $"/Library/SystemExtensions/{dextName}"; - - if (!Directory.Exists("/Library/SystemExtensions")) - Directory.CreateDirectory("/Library/SystemExtensions"); - - File.Copy(dextPath, targetPath, overwrite: true); - - // System extensions are managed by sysextd — registration happens automatically - // User must approve in System Preferences → Security & Privacy - GeneralTracer.Info($"DriverKit extension registered. User approval may be required via System Preferences."); - - // Attempt to register via systemextensionsctl - try - { - await _commandRunner.RunAsync("systemextensionsctl", new[] { "reset" }, cancellationToken); - } - catch - { - // Non-fatal: systemextensionctl may not be available in all versions - } - - GeneralTracer.Info($"DriverKit extension installed: {dextName}"); - } - - private async Task InstallPkgAsync( - string pkgPath, - CancellationToken cancellationToken) - { - GeneralTracer.Info($"Installing macOS package: {pkgPath}"); - - await _commandRunner.RunOrThrowAsync( - "/usr/sbin/installer", - new[] { "-pkg", pkgPath, "-target", "/" }, - cancellationToken); - - GeneralTracer.Info("macOS package installed"); - } - - // ─── Private: File parsing ───────────────────────────────────────── - - private static async Task ParseMacOSDriverFileAsync( - string filePath, - CancellationToken cancellationToken) - { - try - { - var driverInfo = new DriverInfo - { - Name = Path.GetFileNameWithoutExtension(filePath), - FilePath = filePath, - TargetOS = "MacOS", - Architecture = RuntimeInformation.ProcessArchitecture.ToString() - }; - - var extension = Path.GetExtension(filePath).ToLowerInvariant(); - string? versionFromFile = null; - - switch (extension) - { - case ".kext": - versionFromFile = await ParseKextVersionAsync(filePath, cancellationToken); - break; - case ".pkg": - versionFromFile = await ParsePkgVersionAsync(filePath, cancellationToken); - break; - } - - driverInfo.Version = versionFromFile ?? "1.0.0"; - - // Compute file hash - driverInfo.Hash = await HashValidator.ComputeHashAsync(filePath, "SHA256", cancellationToken); - driverInfo.HashAlgorithm = "SHA256"; - - return driverInfo; - } - catch (Exception ex) - { - GeneralTracer.Warn($"Failed to parse driver file: {filePath} - {ex.Message}"); - return null; - } - } - - private static async Task ParseKextVersionAsync( - string kextPath, - CancellationToken cancellationToken) - { - // Try to read Info.plist inside the kext bundle - var plistPath = Path.Combine(kextPath, "Contents", "Info.plist"); - if (!File.Exists(plistPath)) - plistPath = Path.Combine(kextPath, "Info.plist"); - - if (!File.Exists(plistPath)) - return null; - - try - { - var content = await File.ReadAllTextAsync(plistPath, cancellationToken); - - // Simple key-based extraction (no XML library dependency) - var versionKey = "CFBundleVersion"; - var versionIdx = content.IndexOf(versionKey, StringComparison.Ordinal); - if (versionIdx < 0) return null; - - var valueStart = content.IndexOf("", versionIdx, StringComparison.Ordinal); - if (valueStart < 0) return null; - - var valueEnd = content.IndexOf("", valueStart, StringComparison.Ordinal); - if (valueEnd < 0) return null; - - return content.Substring(valueStart + 8, valueEnd - valueStart - 8).Trim(); - } - catch - { - return null; - } - } - - private static Task ParsePkgVersionAsync( - string pkgPath, - CancellationToken cancellationToken) - { - // .pkg files don't have a standard easy-to-parse version format - // without xar/cpio extraction — return null and let caller use default - return Task.FromResult(null); - } - - // ─── Private: Helpers ────────────────────────────────────────────── - - private static void CopyDirectory(string sourceDir, string targetDir) - { - if (!Directory.Exists(targetDir)) - Directory.CreateDirectory(targetDir); - - foreach (var file in Directory.GetFiles(sourceDir)) - { - var dest = Path.Combine(targetDir, Path.GetFileName(file)); - File.Copy(file, dest, overwrite: true); - } - - foreach (var dir in Directory.GetDirectories(sourceDir)) - { - var dest = Path.Combine(targetDir, Path.GetFileName(dir)); - CopyDirectory(dir, dest); - } - } - -} - -/// -/// macOS driver validator — uses file I/O for hash validation and the codesign tool for signatures. -/// -[SupportedOSPlatform("macos")] -public class MacOSDriverValidator : IDriverValidator -{ - private readonly ICommandRunner _commandRunner; - - /// Command runner for codesign operations. - public MacOSDriverValidator(ICommandRunner commandRunner) - { - _commandRunner = commandRunner; - } - - // For factory/DI use - public MacOSDriverValidator() : this(new CommandRunner()) { } - - /// - public Task ValidateIntegrityAsync( - string filePath, - string expectedHash, - string hashAlgorithm = "SHA256", - CancellationToken cancellationToken = default) - { - return HashValidator.ValidateHashAsync(filePath, expectedHash, hashAlgorithm, cancellationToken); - } - - /// - public async Task ValidateSignatureAsync( - string filePath, - IEnumerable trustedPublishers, - CancellationToken cancellationToken = default) - { - try - { - GeneralTracer.Info($"Validating macOS code signature for: {filePath}"); - - var result = await _commandRunner.RunAsync( - "codesign", - new[] { "-v", filePath }, - cancellationToken); - - if (!result.Success) - { - // Try deep verification - result = await _commandRunner.RunAsync( - "codesign", - new[] { "-v", "--deep", filePath }, - cancellationToken); - } - - if (!result.Success) - return false; - - // If trusted publishers specified, verify against them - foreach (var publisher in trustedPublishers) - { - result = await _commandRunner.RunAsync( - "codesign", - new[] { "-dvv", filePath }, - cancellationToken); - - if (result.StandardOutput.Contains(publisher, StringComparison.OrdinalIgnoreCase)) - return true; - } - - // No trusted publishers specified — any valid signature is accepted - return !trustedPublishers.Any(); - } - catch (Exception ex) - { - GeneralTracer.Error($"macOS signature validation failed: {ex.Message}", ex); - return false; - } - } - - /// - public Task ValidateCompatibilityAsync( - DriverInfo driverInfo, - CancellationToken cancellationToken = default) - { - return CompatibilityChecker.CheckCompatibilityAsync(driverInfo, cancellationToken); - } -} - -/// -/// macOS driver backup — file-level copy using pure .NET I/O. -/// No macOS-specific APIs required for backup/restore operations. -/// -[SupportedOSPlatform("macos")] -public class MacOSDriverBackup : IDriverBackup -{ - /// - public async Task BackupAsync( - string sourcePath, - string backupPath, - CancellationToken cancellationToken = default) - { - try - { - GeneralTracer.Info($"Backing up macOS driver: {sourcePath} -> {backupPath}"); - - if (!File.Exists(sourcePath) && !Directory.Exists(sourcePath)) - { - GeneralTracer.Error($"Source not found: {sourcePath}"); - return false; - } - - var backupDir = Path.GetDirectoryName(backupPath); - if (!string.IsNullOrEmpty(backupDir) && !Directory.Exists(backupDir)) - Directory.CreateDirectory(backupDir); - - if (Directory.Exists(sourcePath)) - { - // Copy directory recursively - await Task.Run(() => CopyDirectory(sourcePath, backupPath), cancellationToken); - } - else - { - File.Copy(sourcePath, backupPath, overwrite: true); - } - - GeneralTracer.Info($"Backup completed: {backupPath}"); - return true; - } - catch (Exception ex) - { - GeneralTracer.Error($"macOS backup failed: {ex.Message}", ex); - return false; - } - } - - /// - public Task RestoreAsync( - string backupPath, - string targetPath, - CancellationToken cancellationToken = default) - { - return BackupAsync(backupPath, targetPath, cancellationToken); - } - - /// - public Task DeleteBackupAsync( - string backupPath, - CancellationToken cancellationToken = default) - { - try - { - GeneralTracer.Info($"Deleting macOS backup: {backupPath}"); - - if (Directory.Exists(backupPath)) - Directory.Delete(backupPath, recursive: true); - else if (File.Exists(backupPath)) - File.Delete(backupPath); - - return Task.FromResult(true); - } - catch (Exception ex) - { - GeneralTracer.Error($"Failed to delete backup: {ex.Message}", ex); - return Task.FromResult(false); - } - } - - private static void CopyDirectory(string sourceDir, string targetDir) - { - if (!Directory.Exists(targetDir)) - Directory.CreateDirectory(targetDir); - - foreach (var file in Directory.GetFiles(sourceDir)) - { - var dest = Path.Combine(targetDir, Path.GetFileName(file)); - File.Copy(file, dest, overwrite: true); - } - - foreach (var dir in Directory.GetDirectories(sourceDir)) - { - var dest = Path.Combine(targetDir, Path.GetFileName(dir)); - CopyDirectory(dir, dest); - } - } -} diff --git a/src/GeneralUpdate.Drivelution/Tracer/GeneralTracer.cs b/src/GeneralUpdate.Drivelution/Tracer/GeneralTracer.cs index d2bffcc6..8e5024ff 100644 --- a/src/GeneralUpdate.Drivelution/Tracer/GeneralTracer.cs +++ b/src/GeneralUpdate.Drivelution/Tracer/GeneralTracer.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; +using Microsoft.Extensions.Logging; namespace GeneralUpdate.Drivelution; @@ -82,6 +83,11 @@ public static void Fatal(string message, Exception ex) WriteTraceMessage(TraceLevel.Off, fullMessage); } + /// + /// Turns the built-in trace listeners (console, log file, debugger output) on or off. + /// A logger set through keeps receiving every message either + /// way, which is what an application that only wants that logger relies on. + /// public static void SetTracingEnabled(bool enabled) { lock (_lockObj) @@ -95,6 +101,30 @@ public static void SetTracingEnabled(bool enabled) } } + private static Microsoft.Extensions.Logging.ILogger? _externalLogger; + + private static Microsoft.Extensions.Logging.ILogger? GetExternalLogger() + { + lock (_lockObj) + { + return _externalLogger; + } + } + + /// + /// 桥接到 Microsoft.Extensions.Logging:设置后所有跟踪消息会同时写入该 ILogger + /// (内置的 Console/文件监听不受影响,可用 (false)关闭)。 + /// Bridges to Microsoft.Extensions.Logging: once set, all trace messages are also written to + /// this ILogger (built-in console/file listeners are unaffected; disable them via SetTracingEnabled(false)). + /// + public static void SetExternalLogger(Microsoft.Extensions.Logging.ILogger? logger) + { + lock (_lockObj) + { + _externalLogger = logger; + } + } + public static bool IsTracingEnabled() { lock (_lockObj) @@ -105,10 +135,15 @@ public static bool IsTracingEnabled() private static void WriteTraceMessage(TraceLevel level, string message) { - if(!IsTracingEnabled()) + // Turning the built-in listeners off is how an application keeps the console and the log + // file quiet; the external logger is not one of them and is written to regardless. + var traceEnabled = IsTracingEnabled(); + if (!traceEnabled && GetExternalLogger() is null) return; - - InitializeFileListener(); + + if (traceEnabled) + InitializeFileListener(); + var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); var levelName = GetLevelName(level); var fullMessage = string.Empty; @@ -128,7 +163,37 @@ private static void WriteTraceMessage(TraceLevel level, string message) fullMessage = $"[{timestamp}] [{levelName}] : {message}"; } - Trace.WriteLine(fullMessage); + if (traceEnabled) + { + Trace.WriteLine(fullMessage); + } + + WriteToExternalLogger(level, fullMessage); + } + + private static void WriteToExternalLogger(TraceLevel level, string fullMessage) + { + var logger = GetExternalLogger(); + + if (logger is null) + return; + + try + { + logger.Log(level switch + { + TraceLevel.Verbose => LogLevel.Debug, + TraceLevel.Info => LogLevel.Information, + TraceLevel.Warning => LogLevel.Warning, + TraceLevel.Error => LogLevel.Error, + TraceLevel.Off => LogLevel.Critical, + _ => LogLevel.Information + }, fullMessage); + } + catch + { + // Logging must never break the driver update flow. + } } private static string GetLevelName(TraceLevel level) => level switch diff --git a/src/GeneralUpdate.Drivelution/Windows/Helpers/PnpUtilHelper.cs b/src/GeneralUpdate.Drivelution/Windows/Helpers/PnpUtilHelper.cs new file mode 100644 index 00000000..e4f1e6ae --- /dev/null +++ b/src/GeneralUpdate.Drivelution/Windows/Helpers/PnpUtilHelper.cs @@ -0,0 +1,344 @@ +using System.Globalization; +using System.Runtime.Versioning; +using GeneralUpdate.Drivelution.Abstractions.Models; + +namespace GeneralUpdate.Drivelution.Windows.Helpers; + +/// +/// PnPUtil output parsing helpers. +/// pnputil output is localized (labels differ between e.g. en-US and zh-CN Windows), so labels +/// are matched against a small alias table; unrecognized lines are ignored gracefully. +/// +[SupportedOSPlatform("windows")] +public static partial class PnpUtilHelper +{ + // Label aliases for pnputil /enum-drivers and /enum-devices (en-US, zh-CN). + private static readonly Dictionary FieldAliases = new(StringComparer.Ordinal) + { + ["PublishedName"] = ["Published Name", "发布名称"], + ["OriginalName"] = ["Original Name", "原始名称"], + ["Provider"] = ["Provider Name", "提供程序名称", "提供者名称"], + ["ClassName"] = ["Class Name", "类名称", "类名"], + ["ClassGuid"] = ["Class GUID", "类 GUID"], + ["Version"] = ["Driver Version", "驱动程序版本", "驱动版本"], + ["SignerName"] = ["Signer Name", "签名者", "签名者名称"], + ["FilePath"] = ["File Path", "文件路径"], + ["Date"] = ["Date", "日期"], + ["InstanceId"] = ["Instance ID", "实例 ID", "实例标识符"], + ["Description"] = ["Device Description", "设备描述"], + ["Status"] = ["Status", "状态"], + ["ProblemCode"] = ["Problem Code", "问题代码"], + ["DriverName"] = ["Driver Name", "驱动程序名称", "驱动名称"], + ["HardwareIds"] = ["Hardware ID", "硬件 ID", "硬件标识"] + }; + + /// + /// Exit code reported by pnputil when an operation succeeded but requires a reboot + /// (ERROR_SUCCESS_REBOOT_REQUIRED). + /// + public const int ExitCodeRebootRequired = 3010; + + /// + /// Marker substrings (en-US / zh-CN) indicating a restart is required, found in pnputil output. + /// + private static readonly string[] RestartMarkers = + [ + "restart your computer", + "restart the computer", + "must be restarted", + "重新启动计算机", + "重新启动电脑", + "重启计算机", + "重启电脑" + ]; + + /// + /// Parses `pnputil /enum-drivers` output into installed-driver entries. + /// Win11 renders the "Driver Version" field as "<date> <version>" in one line + /// (e.g. "03/19/2019 1.0.0.8656"); older builds may provide a separate "Date" line — both + /// shapes are handled. + /// + public static List ParseEnumDrivers(string output) + { + var drivers = new List(); + + foreach (var block in SplitBlocks(output)) + { + var fields = ParseBlock(block); + + var publishedName = Get(fields, "PublishedName"); + var originalName = Get(fields, "OriginalName"); + + // Locale fallback: on Windows locales outside the alias table the labels do not + // match, so derive the block positionally. pnputil driver blocks always start with + // the published name (oemXX.inf) followed by the original name. + if (string.IsNullOrEmpty(publishedName) && string.IsNullOrEmpty(originalName)) + { + (publishedName, originalName) = ParseDriverBlockPositional(block); + if (string.IsNullOrEmpty(publishedName) && string.IsNullOrEmpty(originalName)) + continue; // not a driver block + } + + // "Driver Version" is " " on Win11; split the trailing dot-separated + // token off as the version and keep the rest as the date. + var (version, dateFromVersion) = SplitDriverVersion(Get(fields, "Version")); + + if (string.IsNullOrEmpty(version)) + { + // Locale fallback: scan the whole block for a dot-separated numeric version token. + version = ExtractVersionPositional(block); + } + + var explicitDate = TryParseDate(Get(fields, "Date")) ?? dateFromVersion; + + drivers.Add(new InstalledDriverInfo + { + PublishedName = publishedName, + Name = string.IsNullOrEmpty(originalName) + ? Path.GetFileNameWithoutExtension(publishedName) + : Path.GetFileNameWithoutExtension(originalName), + Provider = Get(fields, "Provider"), + Version = version, + ClassName = Get(fields, "ClassName"), + SignerName = Get(fields, "SignerName"), + FilePath = Get(fields, "FilePath"), + RawDate = Get(fields, "Date") is { Length: > 0 } raw ? raw : dateFromVersion?.ToString("yyyy-MM-dd") ?? string.Empty, + Date = explicitDate + }); + } + + return drivers; + } + + /// + /// Parses `pnputil /enum-devices [/connected]` output. Returns entries with the fields that + /// were present; missing fields stay empty (output shape varies across Windows versions). + /// + public static List ParseEnumDevices(string output) + { + var devices = new List(); + + foreach (var block in SplitBlocks(output)) + { + var fields = ParseBlock(block); + if (fields.Count == 0) + continue; + + var instanceId = Get(fields, "InstanceId"); + var driverName = Get(fields, "DriverName"); + if (string.IsNullOrEmpty(instanceId) && string.IsNullOrEmpty(driverName)) + continue; // not a device block + + var status = Get(fields, "Status"); + var problemCode = Get(fields, "ProblemCode"); + var statusText = string.IsNullOrEmpty(problemCode) ? status : $"{status} ({problemCode})"; + + devices.Add(new InstalledDriverInfo + { + Name = Path.GetFileNameWithoutExtension(driverName), + PublishedName = driverName, + ClassName = Get(fields, "ClassName"), + Provider = Get(fields, "Provider"), + Version = string.Empty, + SignerName = Get(fields, "SignerName"), + FilePath = instanceId, // reuse FilePath for the instance id on device listings + Status = statusText, + RawDate = statusText + }); + } + + return devices; + } + + /// + /// Determines whether pnputil output or an exit code indicates a required restart. + /// + public static bool IsRebootRequired(int exitCode, string output) + { + if (exitCode == ExitCodeRebootRequired) + return true; + + return RestartMarkers.Any(m => output.Contains(m, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Extracts published driver names (oemXX.inf) mentioned in pnputil output lines such as + /// "Published Name: oem12.inf" — used to find which package was just added. + /// + public static string? ExtractPublishedName(string output) + { + foreach (var block in SplitBlocks(output)) + { + var fields = ParseBlock(block); + var published = Get(fields, "PublishedName"); + if (!string.IsNullOrEmpty(published)) + return published; + } + + return null; + } + + // ─── Internals ───────────────────────────────────────────────────── + + /// + /// Locale-independent positional fallback for a driver block: the first two label/value lines + /// ending with ".inf" carry the published name and the original name. Labels are stripped by + /// taking the value after the last colon. Returns empty strings when the block does not look + /// like a driver block. + /// + private static (string PublishedName, string OriginalName) ParseDriverBlockPositional(string block) + { + var infLines = block + .Split('\n') + .Select(l => + { + var trimmed = l.Trim(); + var colonIdx = trimmed.LastIndexOf(':'); + return colonIdx >= 0 && colonIdx + 1 < trimmed.Length ? trimmed[(colonIdx + 1)..].Trim() : trimmed; + }) + .Where(l => l.EndsWith(".inf", StringComparison.OrdinalIgnoreCase) && !l.Contains(':')) + .ToList(); + + if (infLines.Count < 2) + return (string.Empty, string.Empty); + + return (infLines[0], infLines[1]); + } + + /// + /// Locale-independent version extraction: finds the first dot-separated numeric token that + /// looks like a driver version (2+ components) anywhere in the block. + /// + private static string ExtractVersionPositional(string block) + { + foreach (var rawLine in block.Split('\n')) + { + var line = rawLine.Trim(); + var colonIdx = line.IndexOf(':'); + if (colonIdx >= 0 && colonIdx + 1 < line.Length) + line = line[(colonIdx + 1)..].Trim(); + + foreach (var token in line.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + var parts = token.Split('.'); + if (parts.Length >= 2 && parts.All(p => p.Length > 0 && p.All(char.IsAsciiDigit) && p.Length <= 10)) + { + return token; + } + } + } + + return string.Empty; + } + + private static IEnumerable SplitBlocks(string output) + { + var current = new List(); + foreach (var rawLine in output.Split('\n')) + { + var line = rawLine.TrimEnd('\r'); + if (string.IsNullOrWhiteSpace(line)) + { + if (current.Count > 0) + { + yield return string.Join('\n', current); + current.Clear(); + } + + continue; + } + + current.Add(line); + } + + if (current.Count > 0) + yield return string.Join('\n', current); + } + + private static Dictionary ParseBlock(string block) + { + var fields = new Dictionary(StringComparer.Ordinal); + + foreach (var rawLine in block.Split('\n')) + { + var colonIdx = rawLine.IndexOf(':'); + if (colonIdx <= 0) + continue; + + var label = rawLine[..colonIdx].Trim(); + var value = rawLine[(colonIdx + 1)..].Trim(); + + foreach (var (canonical, aliases) in FieldAliases) + { + if (aliases.Any(a => label.Equals(a, StringComparison.OrdinalIgnoreCase)) && + !fields.ContainsKey(canonical)) + { + fields[canonical] = value; + break; + } + } + } + + return fields; + } + + private static string Get(Dictionary fields, string key) => + fields.TryGetValue(key, out var value) ? value : string.Empty; + + /// + /// Splits a "Driver Version" field value into (version, date). Win11 renders it as + /// "<locale date> <a.b.c.d>"; older builds render just "<a.b.c.d>". + /// The version is the last whitespace-separated token consisting of digits and dots. + /// + private static (string Version, DateTime? Date) SplitDriverVersion(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) + return (string.Empty, null); + + var tokens = raw.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var version = string.Empty; + DateTime? date = null; + var dateParts = new List(); + + foreach (var token in tokens) + { + if (version.Length == 0 && IsDotSeparatedNumbers(token)) + { + version = token; + } + else + { + dateParts.Add(token); + } + } + + if (dateParts.Count > 0 && TryParseDate(string.Join(' ', dateParts)) is { } parsed) + date = parsed; + + return (version, date); + } + + private static bool IsDotSeparatedNumbers(string token) + { + if (string.IsNullOrEmpty(token) || !char.IsAsciiDigit(token[0])) + return false; + + return token.Split('.').All(part => + part.Length > 0 && part.All(char.IsAsciiDigit) && part.Length <= 10); + } + + private static DateTime? TryParseDate(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) + return null; + + // pnputil renders dates in the user locale ("9/22/2023" / "2023/9/22" / "2023-09-22"). + if (DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var invariant)) + return invariant; + + if (DateTime.TryParse(raw, CultureInfo.CurrentCulture, DateTimeStyles.None, out var current)) + return current; + + return null; + } +} diff --git a/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs b/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs index 5a3f995b..ff1a7c3b 100644 --- a/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs +++ b/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs @@ -2,6 +2,7 @@ using System.Runtime.Versioning; using System.Security.Cryptography.X509Certificates; using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Core.Utilities; namespace GeneralUpdate.Drivelution.Windows.Helpers; @@ -18,10 +19,14 @@ public static class WindowsSignatureHelper /// /// 文件路径 / File path /// 信任的发布者列表 / Trusted publishers list + /// 信任的证书指纹列表(匹配任一即通过)/ Trusted certificate thumbprints (any match passes) /// 是否验证通过 / Whether validation succeeded - public static async Task ValidateAuthenticodeSignatureAsync(string filePath, IEnumerable trustedPublishers) + public static async Task ValidateAuthenticodeSignatureAsync( + string filePath, + IEnumerable trustedPublishers, + IEnumerable? trustedThumbprints = null) { - return await Task.Run(() => ValidateAuthenticodeSignature(filePath, trustedPublishers)); + return await Task.Run(() => ValidateAuthenticodeSignature(filePath, trustedPublishers, trustedThumbprints)); } /// @@ -30,8 +35,12 @@ public static async Task ValidateAuthenticodeSignatureAsync(string filePat /// /// 文件路径 / File path /// 信任的发布者列表 / Trusted publishers list + /// 信任的证书指纹列表 / Trusted certificate thumbprints /// 是否验证通过 / Whether validation succeeded - public static bool ValidateAuthenticodeSignature(string filePath, IEnumerable trustedPublishers) + public static bool ValidateAuthenticodeSignature( + string filePath, + IEnumerable trustedPublishers, + IEnumerable? trustedThumbprints = null) { if (!File.Exists(filePath)) { @@ -68,33 +77,41 @@ public static bool ValidateAuthenticodeSignature(string filePath, IEnumerable cert2.NotAfter) { // Certificate is not within its validity period + GeneralTracer.Warn( + $"Authenticode signature rejected for '{filePath}': the signer certificate '{cert2.Subject}' " + + $"is not within its validity period ({cert2.NotBefore:yyyy-MM-dd} – {cert2.NotAfter:yyyy-MM-dd})."); return false; } - // If trustedPublishers is empty, accept any valid signature - if (!trustedPublishers.Any()) - { - // No trusted publishers specified, accepting any valid signature - return true; - } + var thumbprints = trustedThumbprints? + .Where(t => !string.IsNullOrWhiteSpace(t)) + .Select(t => t.Trim()) + .ToList() ?? new List(); + var publishers = trustedPublishers? + .Where(p => !string.IsNullOrWhiteSpace(p)) + .Select(p => p.Trim()) + .ToList() ?? new List(); - // Check if the certificate subject or thumbprint matches any trusted publisher - foreach (var publisher in trustedPublishers) + if (SignerTrust.IsTrusted(cert2, publishers, thumbprints)) { - if (cert2.Subject.Contains(publisher, StringComparison.OrdinalIgnoreCase) || - cert2.Thumbprint.Equals(publisher, StringComparison.OrdinalIgnoreCase)) - { - // File is signed by trusted publisher - return true; - } + // File is signed by a trusted publisher or certificate + var reason = thumbprints.Count == 0 && publishers.Count == 0 + ? "no signer trust is configured, any valid signature is accepted" + : "matches a trusted publisher or thumbprint"; + GeneralTracer.Info($"Authenticode signature accepted for '{filePath}': signer '{cert2.Subject}' ({reason})."); + return true; } // File is signed but not by a trusted publisher + GeneralTracer.Warn( + $"Authenticode signature rejected for '{filePath}': signer '{cert2.Subject}' (thumbprint {cert2.Thumbprint}) " + + "matches none of the trusted publishers or thumbprints."); return false; } catch (System.Security.Cryptography.CryptographicException) { // File is not signed or signature is invalid + GeneralTracer.Warn($"Authenticode signature rejected for '{filePath}': the file is not signed or its signature is invalid."); return false; } } diff --git a/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs b/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs index 2b114cb5..b17c2562 100644 --- a/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs +++ b/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs @@ -1,13 +1,15 @@ using System.Runtime.Versioning; -using GeneralUpdate.Drivelution; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Core.Utilities; namespace GeneralUpdate.Drivelution.Windows.Implementation; /// -/// Windows驱动备份实现 -/// Windows driver backup implementation +/// Windows驱动备份实现:备份整个驱动包目录(INF 及其所在目录下的全部文件,含子目录中的 .sys/.cat/.dll 等), +/// 回滚时由平台回滚逻辑配合 pnputil 重新安装备份包。 +/// Windows driver backup: copies the whole driver package directory (the INF plus every file +/// and subdirectory next to it); rollback reinstalls the backed-up package via pnputil. /// [SupportedOSPlatform("windows")] public class WindowsDriverBackup : IDriverBackup @@ -22,41 +24,33 @@ public async Task BackupAsync( string backupPath, CancellationToken cancellationToken = default) { - GeneralTracer.Info($"Backing up driver from {sourcePath} to {backupPath}"); + GeneralTracer.Info($"Backing up driver package of {sourcePath} to {backupPath}"); try { - if (!File.Exists(sourcePath)) + if (!File.Exists(sourcePath) && !Directory.Exists(sourcePath)) { - throw new FileNotFoundException($"Source file not found: {sourcePath}"); + throw new DriverBackupException($"Failed to backup driver: source not found: {sourcePath}") { CanRetry = false }; } - // Ensure backup directory exists - var backupDir = Path.GetDirectoryName(backupPath); - if (!string.IsNullOrEmpty(backupDir) && !Directory.Exists(backupDir)) - { - Directory.CreateDirectory(backupDir); - GeneralTracer.Info($"Created backup directory: {backupDir}"); - } - - // Add timestamp to backup filename to avoid conflicts - var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); - var fileName = Path.GetFileNameWithoutExtension(backupPath); - var extension = Path.GetExtension(backupPath); - var backupPathWithTimestamp = Path.Combine( - backupDir ?? string.Empty, - $"{fileName}_{timestamp}{extension}"); - - // Copy file asynchronously - using (var sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - using (var destinationStream = new FileStream(backupPathWithTimestamp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true)) - { - await sourceStream.CopyToAsync(destinationStream, cancellationToken); - } + // An INF on its own cannot reinstall a driver: the package around it is backed up. + var packageRoot = DriverBackupFiles.GetPackageRoot(sourcePath); + DriverBackupFiles.EnsureBackupIsSeparate(backupPath, packageRoot); + Directory.CreateDirectory(backupPath); - GeneralTracer.Info($"Driver backup completed successfully: {backupPathWithTimestamp}"); + var files = await DriverBackupFiles.CopyTreeAsync(packageRoot, backupPath, cancellationToken); + GeneralTracer.Info($"Driver backup completed successfully: {backupPath} ({files} file(s))"); return true; } + catch (OperationCanceledException) + { + throw; + } + catch (DriverBackupException) + { + // Already what callers expect; a configuration error keeps its non-retryable verdict. + throw; + } catch (Exception ex) { GeneralTracer.Error("Failed to backup driver", ex); @@ -74,37 +68,15 @@ public async Task RestoreAsync( try { - if (!File.Exists(backupPath)) - { - throw new FileNotFoundException($"Backup file not found: {backupPath}"); - } - - // Ensure target directory exists - var targetDir = Path.GetDirectoryName(targetPath); - if (!string.IsNullOrEmpty(targetDir) && !Directory.Exists(targetDir)) - { - Directory.CreateDirectory(targetDir); - GeneralTracer.Info($"Created target directory: {targetDir}"); - } - - // Backup existing target file if it exists - if (File.Exists(targetPath)) - { - var tempBackup = $"{targetPath}.old"; - File.Move(targetPath, tempBackup, true); - GeneralTracer.Info($"Moved existing file to temporary backup: {tempBackup}"); - } - - // Copy backup file to target location - using (var sourceStream = new FileStream(backupPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - using (var destinationStream = new FileStream(targetPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true)) - { - await sourceStream.CopyToAsync(destinationStream, cancellationToken); - } + await DriverBackupFiles.RestoreAsync(backupPath, targetPath, cancellationToken); GeneralTracer.Info("Driver restore completed successfully"); return true; } + catch (OperationCanceledException) + { + throw; + } catch (Exception ex) { GeneralTracer.Error("Failed to restore driver", ex); @@ -123,17 +95,22 @@ public async Task DeleteBackupAsync( { try { - if (File.Exists(backupPath)) + if (Directory.Exists(backupPath)) { - File.Delete(backupPath); + Directory.Delete(backupPath, recursive: true); GeneralTracer.Info("Backup deleted successfully"); return true; } - else + + if (File.Exists(backupPath)) { - GeneralTracer.Warn($"Backup file not found: {backupPath}"); - return false; + File.Delete(backupPath); + GeneralTracer.Info("Backup deleted successfully"); + return true; } + + GeneralTracer.Warn($"Backup not found: {backupPath}"); + return false; } catch (Exception ex) { diff --git a/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs b/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs index d836f1d7..0e9110fd 100644 --- a/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs +++ b/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs @@ -57,13 +57,14 @@ public async Task ValidateIntegrityAsync( public async Task ValidateSignatureAsync( string filePath, IEnumerable trustedPublishers, + IEnumerable? trustedThumbprints = null, CancellationToken cancellationToken = default) { GeneralTracer.Info($"Validating driver signature: {filePath}"); try { - var isValid = await WindowsSignatureHelper.ValidateAuthenticodeSignatureAsync(filePath, trustedPublishers); + var isValid = await WindowsSignatureHelper.ValidateAuthenticodeSignatureAsync(filePath, trustedPublishers, trustedThumbprints); if (isValid) { diff --git a/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs b/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs index 90b4ba66..f0f9af3d 100644 --- a/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs +++ b/src/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Runtime.Versioning; using GeneralUpdate.Drivelution; using GeneralUpdate.Drivelution.Abstractions; @@ -14,7 +15,8 @@ namespace GeneralUpdate.Drivelution.Windows.Implementation; /// /// Windows driver updater implementation. /// Inherits the unified pipeline from and adds Windows-specific -/// permission checks, PnPUtil-based installation, and INF file parsing. +/// permission checks, PnPUtil-based installation with driver-store aware backup and rollback, +/// device enumeration, and INF file parsing. /// [SupportedOSPlatform("windows")] public class WindowsGeneralDrivelution : BaseDriverUpdater @@ -28,12 +30,14 @@ public class WindowsGeneralDrivelution : BaseDriverUpdater /// Driver backup manager. /// Command runner for PnPUtil operations. /// Configuration options (optional). + /// Network downloader for DownloadUrl scenarios (optional). public WindowsGeneralDrivelution( IDriverValidator validator, IDriverBackup backup, ICommandRunner commandRunner, - DrivelutionOptions? options = null) - : base(validator, backup, options) + DrivelutionOptions? options = null, + INetworkDownloader? downloader = null) + : base(validator, backup, options, downloader) { _commandRunner = commandRunner ?? throw new ArgumentNullException(nameof(commandRunner)); } @@ -44,7 +48,12 @@ public WindowsGeneralDrivelution( protected override IEnumerable GetPipelineSteps(UpdateStrategy strategy) { // Prepend Windows permission check before the default pipeline - yield return CreatePermissionCheckStep(); + yield return DefaultPipelineSteps.CreatePermissionCheckStep( + "CheckPermissions", + () => WindowsPermissionHelper.IsAdministrator() + ? null + : "Administrator privileges are required for driver updates. " + + "Please restart the application as administrator."); foreach (var step in base.GetPipelineSteps(strategy)) yield return step; @@ -52,23 +61,86 @@ protected override IEnumerable GetPipelineSteps(UpdateStrategy st /// protected override async Task InstallCoreAsync( - DriverInfo driverInfo, - UpdateStrategy strategy, + PipelineContext context, CancellationToken cancellationToken) { + var driverInfo = context.DriverInfo; GeneralTracer.Info($"Installing Windows driver via PnPUtil: {driverInfo.FilePath}"); - await InstallDriverUsingPnPUtilAsync(driverInfo.FilePath, cancellationToken); + + // Detect devices currently bound to this driver package before replacing it. + var boundDevices = await FindBoundDevicesAsync(driverInfo, cancellationToken); + if (boundDevices.Count > 0) + { + context.Result.StepLogs.Add( + $"[{DateTime.Now:HH:mm:ss}] {boundDevices.Count} connected device(s) use this driver package"); + GeneralTracer.Info($"WindowsGeneralDrivelution: {boundDevices.Count} connected device(s) reference this driver."); + } + + var result = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/add-driver", driverInfo.FilePath, "/install" }, + cancellationToken); + + GeneralTracer.Info($"PnPUtil output: {result.StandardOutput.Trim()}"); + + // 3010 (ERROR_SUCCESS_REBOOT_REQUIRED) = success, restart needed. + if (result.ExitCode != 0 && result.ExitCode != PnpUtilHelper.ExitCodeRebootRequired) + { + GeneralTracer.Error($"PnPUtil failed (exit {result.ExitCode}): {result.StandardError}"); + throw new DriverInstallationException( + $"PnPUtil failed with exit code {result.ExitCode}: {result.StandardError}"); + } + + // Track the newly added driver package for rollback. + var publishedName = PnpUtilHelper.ExtractPublishedName(result.StandardOutput) + ?? await FindPublishedNameForFileAsync(driverInfo.FilePath, cancellationToken); + if (!string.IsNullOrEmpty(publishedName)) + { + context.Bag["InstalledPublishedName"] = publishedName; + + // Persist for precise rollback: install_state.json in the backup dir (when one exists). + var backupDirectory = context.Result.BackupPath; + if (!string.IsNullOrEmpty(backupDirectory)) + { + InstallStateStore.TrySave(new InstallState + { + PublishedName = publishedName, + OriginalName = Path.GetFileName(driverInfo.FilePath), + Platform = "Windows" + }, backupDirectory); + } + } + + if (PnpUtilHelper.IsRebootRequired(result.ExitCode, result.StandardOutput + result.StandardError)) + { + context.Bag["RestartRequired"] = true; + context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] A system restart is required to complete the installation"); + } + + // Re-enumerate devices so upgraded drivers bind without waiting for the next plug event. + await RunPnputilQuietAsync(new[] { "/scan-devices" }, cancellationToken); } /// protected override async Task VerifyInstallationAsync( - DriverInfo driverInfo, + PipelineContext context, CancellationToken cancellationToken) { + var driverInfo = context.DriverInfo; try { GeneralTracer.Info($"Verifying Windows driver installation for: {driverInfo.FilePath}"); + // Prefer device-level verification: connected devices bound to this driver package. + var boundDevices = await FindBoundDevicesAsync(driverInfo, cancellationToken); + if (boundDevices.Count > 0) + { + var allOk = boundDevices.All(d => !LooksLikeProblem(d)); + GeneralTracer.Info($"Device-level verification: {boundDevices.Count} device(s), all healthy={allOk}"); + return allOk; + } + + // Fall back to driver-store presence verification. var result = await _commandRunner.RunAsync( "pnputil.exe", new[] { "/enum-drivers" }, @@ -82,11 +154,13 @@ protected override async Task VerifyInstallationAsync( return true; } + var drivers = PnpUtilHelper.ParseEnumDrivers(result.StandardOutput); var driverFileName = Path.GetFileName(driverInfo.FilePath); var driverName = Path.GetFileNameWithoutExtension(driverInfo.FilePath); - bool isInstalled = result.StandardOutput.Contains(driverFileName, StringComparison.OrdinalIgnoreCase) - || result.StandardOutput.Contains(driverName, StringComparison.OrdinalIgnoreCase); + var isInstalled = drivers.Any(d => + d.PublishedName.Equals(driverFileName, StringComparison.OrdinalIgnoreCase) || + d.Name.Equals(driverName, StringComparison.OrdinalIgnoreCase)); GeneralTracer.Info($"Driver verification result: {isInstalled}"); return isInstalled; @@ -98,7 +172,58 @@ protected override async Task VerifyInstallationAsync( } } - // ─── Rollback override ───────────────────────────────────────────── + // ─── Backup hook: export the currently installed driver package ──── + + /// + protected override async Task TryBackupInstalledDriverAsync( + DriverInfo driverInfo, + string backupDirectory, + CancellationToken cancellationToken) + { + try + { + var installed = await GetInstalledDriversAsync(cancellationToken); + var incomingName = Path.GetFileNameWithoutExtension(driverInfo.FilePath); + var match = installed.FirstOrDefault(d => + (!string.IsNullOrEmpty(d.Name) && d.Name.Equals(incomingName, StringComparison.OrdinalIgnoreCase)) || + (!string.IsNullOrEmpty(d.PublishedName) && + d.PublishedName.Equals(Path.GetFileName(driverInfo.FilePath), StringComparison.OrdinalIgnoreCase))); + + if (match is null || string.IsNullOrEmpty(match.PublishedName)) + { + // No match by name — nothing (relevant) installed yet; caller falls back to + // copying the local package. + return false; + } + + var publishedName = match.PublishedName; + GeneralTracer.Info($"Exporting installed driver '{publishedName}' for backup."); + + var export = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/export-driver", publishedName, backupDirectory }, + cancellationToken); + + if (!export.Success) + { + GeneralTracer.Warn($"pnputil /export-driver failed (exit {export.ExitCode}): {export.StandardError.Trim()}"); + return false; + } + + return Directory.GetFiles(backupDirectory, "*.*", SearchOption.AllDirectories).Length > 0; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + GeneralTracer.Warn($"Failed to export installed driver: {ex.Message}"); + return false; + } + } + + // ─── Rollback: remove the new package, reinstall the backed-up one ─ /// public override async Task RollbackAsync( @@ -115,32 +240,100 @@ public override async Task RollbackAsync( return false; } - var backupFiles = Directory.GetFiles(backupPath, "*.*", SearchOption.AllDirectories); - if (backupFiles.Length == 0) + var manifest = BackupManifestStore.Load(backupPath); + var backupFiles = Directory.GetFiles(backupPath, "*.*", SearchOption.AllDirectories) + .Where(f => !Path.GetFileName(f).Equals(BackupManifest.ManifestFileName, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + if (backupFiles.Count == 0) { GeneralTracer.Warn($"No backup files found in: {backupPath}"); return false; } - GeneralTracer.Info($"Found {backupFiles.Length} backup files"); + var backupInfFiles = backupFiles + .Where(f => f.EndsWith(".inf", StringComparison.OrdinalIgnoreCase)) + .ToList(); - // Reinstall backed-up INF drivers via PnPUtil - foreach (var infFile in backupFiles.Where( - f => f.EndsWith(".inf", StringComparison.OrdinalIgnoreCase))) + if (manifest is null && backupInfFiles.Count == 0) { - try + GeneralTracer.Warn("No INF files or manifest found in backup — nothing to reinstall."); + return false; + } + + // The original name shared by old and new packages (from the manifest or the backup INF). + var originalInfName = manifest is not null && !string.IsNullOrEmpty(manifest.OriginalFilePath) + ? Path.GetFileName(manifest.OriginalFilePath) + : Path.GetFileName(backupInfFiles[0]); + + var installState = InstallStateStore.Load(backupPath); + + var source = manifest?.Source ?? BackupManifest.SourcePackage; + var failures = new List(); + + // Step 1: remove the newly installed package(s). Prefer the exact published name + // captured at install time (install_state.json); fall back to original-name matching. + if (!string.IsNullOrEmpty(installState?.PublishedName)) + { + GeneralTracer.Info($"Deleting newly installed package: {installState.PublishedName}"); + await RunPnputilQuietAsync(new[] { "/delete-driver", installState.PublishedName, "/force" }, cancellationToken); + } + else + { + await DeleteMatchingDriverPackagesAsync(originalInfName, cancellationToken); + } + + if (source == BackupManifest.SourceInstalled) + { + // Step 2 (update scenario): reinstall the exported previous package so the old + // driver binds again. + var restoredAny = false; + + foreach (var infFile in backupInfFiles) { - GeneralTracer.Info($"Restoring driver from: {infFile}"); - await InstallDriverUsingPnPUtilAsync(infFile, cancellationToken); + try + { + GeneralTracer.Info($"Restoring driver from: {infFile}"); + var install = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/add-driver", infFile, "/install" }, + cancellationToken); + + if (install.Success || install.ExitCode == PnpUtilHelper.ExitCodeRebootRequired) + restoredAny = true; + else + failures.Add($"{Path.GetFileName(infFile)}: exit {install.ExitCode} {install.StandardError.Trim()}"); + } + catch (Exception ex) + { + failures.Add($"{Path.GetFileName(infFile)}: {ex.Message}"); + } } - catch (Exception ex) + + if (backupInfFiles.Count > 0 && !restoredAny) { - GeneralTracer.Warn($"Failed to restore driver from {infFile}: {ex.Message}"); + GeneralTracer.Error($"Windows rollback failed to reinstall any backup package: {string.Join("; ", failures)}"); + return false; } + + if (failures.Count > 0) + { + GeneralTracer.Error($"Windows rollback finished with partial failures: {string.Join("; ", failures)}"); + return false; + } + + return true; } + // Fresh-install scenario: the backup holds a copy of the incoming package; deleting + // the newly added package (step 1) fully undoes the update. + GeneralTracer.Info("Fresh-install rollback: newly added package removed."); return true; } + catch (OperationCanceledException) + { + throw; + } catch (Exception ex) { GeneralTracer.Error("Windows driver rollback failed", ex); @@ -148,6 +341,26 @@ public override async Task RollbackAsync( } } + // ─── Installed driver inventory ──────────────────────────────────── + + /// + public override async Task> GetInstalledDriversAsync( + CancellationToken cancellationToken = default) + { + var result = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/enum-drivers" }, + cancellationToken); + + if (!result.Success) + { + GeneralTracer.Warn($"pnputil /enum-drivers failed (exit {result.ExitCode}): {result.StandardError.Trim()}"); + return new List(); + } + + return PnpUtilHelper.ParseEnumDrivers(result.StandardOutput); + } + // ─── Driver discovery overrides ──────────────────────────────────── /// @@ -181,7 +394,7 @@ public override async Task> GetDriversFromDirectoryAsync( try { - var info = await ParseWindowsDriverFileAsync(filePath, cancellationToken); + var info = ParseWindowsDriverFile(filePath); if (info is not null) drivers.Add(info); } @@ -203,57 +416,148 @@ public override async Task> GetDriversFromDirectoryAsync( // ─── Private helpers ──────────────────────────────────────────────── + private async Task RunPnputilQuietAsync(string[] arguments, CancellationToken cancellationToken) + { + try + { + await _commandRunner.RunAsync("pnputil.exe", arguments, cancellationToken); + } + catch (Exception ex) + { + // Auxiliary command — never fail the pipeline because of it. + GeneralTracer.Debug($"pnputil {string.Join(' ', arguments)} failed: {ex.Message}"); + } + } + /// - /// Creates a Windows admin-privilege check as the first pipeline step. + /// Finds connected devices bound to the driver package that owns 's + /// original INF name. /// - private static IPipelineStep CreatePermissionCheckStep() + private async Task> FindBoundDevicesAsync( + DriverInfo driverInfo, + CancellationToken cancellationToken) { - return new DelegateStep("CheckPermissions", - execute: (context, ct) => - { - context.Result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Checking Windows administrator privileges"); + try + { + var devicesResult = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/enum-devices", "/connected" }, + cancellationToken); - if (!WindowsPermissionHelper.IsAdministrator()) - { - return Task.FromResult(PipelineResult.Fail( - "Administrator privileges are required for driver updates. " + - "Please restart the application as administrator.")); - } + if (!devicesResult.Success) + return new List(); + + var devices = PnpUtilHelper.ParseEnumDevices(devicesResult.StandardOutput); + var originalName = Path.GetFileName(driverInfo.FilePath); + + var driversResult = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/enum-drivers" }, + cancellationToken); + + if (!driversResult.Success) + return new List(); + + var publishedNames = PnpUtilHelper + .ParseEnumDrivers(driversResult.StandardOutput) + .Where(d => d.PublishedName.Equals(originalName, StringComparison.OrdinalIgnoreCase) || + d.Name.Equals(Path.GetFileNameWithoutExtension(originalName), StringComparison.OrdinalIgnoreCase)) + .Select(d => d.PublishedName) + .Where(p => !string.IsNullOrEmpty(p)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + return devices + .Where(d => !string.IsNullOrEmpty(d.PublishedName) && publishedNames.Contains(d.PublishedName)) + .ToList(); + } + catch (Exception ex) + { + GeneralTracer.Debug($"FindBoundDevicesAsync failed: {ex.Message}"); + return new List(); + } + } + + private static bool LooksLikeProblem(InstalledDriverInfo device) + { + var status = device.Status; + return status.Contains("Error", StringComparison.OrdinalIgnoreCase) || + status.Contains("Problem", StringComparison.OrdinalIgnoreCase) || + status.Contains("Degraded", StringComparison.OrdinalIgnoreCase) || + status.Contains("错误", StringComparison.Ordinal) || + status.Contains("问题", StringComparison.Ordinal); + } - return Task.FromResult(PipelineResult.Ok()); - }); + private async Task FindPublishedNameForFileAsync( + string filePath, + CancellationToken cancellationToken) + { + try + { + var result = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/enum-drivers" }, + cancellationToken); + + if (!result.Success) + return null; + + var originalName = Path.GetFileName(filePath); + var match = PnpUtilHelper.ParseEnumDrivers(result.StandardOutput).FirstOrDefault(d => + d.PublishedName.Equals(originalName, StringComparison.OrdinalIgnoreCase) || + d.Name.Equals(Path.GetFileNameWithoutExtension(originalName), StringComparison.OrdinalIgnoreCase)); + + return match?.PublishedName; + } + catch (Exception ex) + { + GeneralTracer.Debug($"FindPublishedNameForFileAsync failed: {ex.Message}"); + return null; + } } /// - /// Installs a driver using the Windows PnPUtil command-line tool (via ICommandRunner). + /// Deletes all driver-store packages whose original INF name matches, so the previous driver + /// (reinstalled afterwards) can bind again. /// - private async Task InstallDriverUsingPnPUtilAsync( - string driverPath, + private async Task DeleteMatchingDriverPackagesAsync( + string originalInfName, CancellationToken cancellationToken) { - GeneralTracer.Info($"PnPUtil installing: {driverPath}"); + try + { + var enumResult = await _commandRunner.RunAsync( + "pnputil.exe", + new[] { "/enum-drivers" }, + cancellationToken); - var result = await _commandRunner.RunAsync( - "pnputil.exe", - new[] { "/add-driver", driverPath, "/install" }, - cancellationToken); + if (!enumResult.Success) + return; - GeneralTracer.Info($"PnPUtil output: {result.StandardOutput.Trim()}"); + var publishedNames = PnpUtilHelper + .ParseEnumDrivers(enumResult.StandardOutput) + .Where(d => d.PublishedName.Equals(originalInfName, StringComparison.OrdinalIgnoreCase)) + .Select(d => d.PublishedName) + .ToList(); - if (!result.Success) + foreach (var publishedName in publishedNames) + { + GeneralTracer.Info($"Deleting newly added driver package: {publishedName}"); + await RunPnputilQuietAsync(new[] { "/delete-driver", publishedName, "/force" }, cancellationToken); + } + } + catch (Exception ex) { - GeneralTracer.Error($"PnPUtil failed (exit {result.ExitCode}): {result.StandardError}"); - throw new DriverInstallationException( - $"PnPUtil failed with exit code {result.ExitCode}: {result.StandardError}"); + // Rollback proceeds to reinstalling the backup even if deletion fails. + GeneralTracer.Warn($"DeleteMatchingDriverPackagesAsync failed: {ex.Message}"); } } /// - /// Parses a Windows driver file (INF) and extracts metadata, hash, and signature info. + /// Parses a Windows driver file (INF) and extracts metadata and signature info. + /// Note: the file's own hash is NOT stored in — self-computed + /// hashes validate nothing. It is recorded in Metadata for diagnostics only. /// - private async Task ParseWindowsDriverFileAsync( - string filePath, - CancellationToken cancellationToken) + private DriverInfo? ParseWindowsDriverFile(string filePath) { try { @@ -268,12 +572,12 @@ private async Task InstallDriverUsingPnPUtilAsync( // Parse INF metadata if (filePath.EndsWith(".inf", StringComparison.OrdinalIgnoreCase)) { - await ParseInfFileAsync(filePath, driverInfo, cancellationToken); + ParseInfFile(filePath, driverInfo); } - // Compute file hash - driverInfo.Hash = await HashValidator.ComputeHashAsync(filePath, "SHA256", cancellationToken); - driverInfo.HashAlgorithm = "SHA256"; + // Record the computed hash as diagnostics only — never as an integrity expectation. + driverInfo.Metadata["ComputedSHA256"] = HashValidator + .ComputeHashAsync(filePath, "SHA256").GetAwaiter().GetResult(); // Extract signature info ExtractSignatureInfo(filePath, driverInfo); @@ -322,46 +626,81 @@ private static void ExtractSignatureInfo(string filePath, DriverInfo driverInfo) /// /// Parses a Windows INF file to extract DriverVer, DriverDesc, and HardwareId. + /// INF semantics: DriverVer lives in the [Version] section; DriverDesc and HardwareId live in + /// model/install sections. %key% references are resolved against the [Strings] section and + /// DriverVer dates are parsed with InvariantCulture first (INF dates are "MM/DD/YYYY"). /// - private static async Task ParseInfFileAsync( - string infPath, - DriverInfo driverInfo, - CancellationToken cancellationToken) + private static void ParseInfFile(string infPath, DriverInfo driverInfo) { try { - var content = await File.ReadAllTextAsync(infPath, cancellationToken); + var content = File.ReadAllText(infPath); var lines = content.Split('\n'); - foreach (var line in lines) + string? currentSection = null; + var strings = new Dictionary(StringComparer.OrdinalIgnoreCase); + + // Pass 1: collect the [Strings] section so %key% references resolve everywhere. + foreach (var rawLine in lines) { - var trimmed = line.Trim(); + var trimmed = rawLine.Trim(); + if (trimmed.Length == 0 || trimmed.StartsWith(';')) + continue; - if (trimmed.StartsWith("DriverVer", StringComparison.OrdinalIgnoreCase)) + if (trimmed.StartsWith('[') && trimmed.EndsWith(']')) { - var parts = trimmed.Split('='); - if (parts.Length > 1) - { - var verParts = parts[1].Split(','); - if (verParts.Length > 1) - driverInfo.Version = verParts[1].Trim(); - if (verParts.Length > 0 - && DateTime.TryParse(verParts[0].Trim(), out var releaseDate)) - driverInfo.ReleaseDate = releaseDate; - } + currentSection = trimmed[1..^1].Trim(); + continue; } - else if (trimmed.StartsWith("DriverDesc", StringComparison.OrdinalIgnoreCase)) + + if (currentSection is not null && + currentSection.Equals("Strings", StringComparison.OrdinalIgnoreCase) && + TrySplitKeyValue(trimmed, out var stringKey, out var stringValue)) { - var parts = trimmed.Split('='); - if (parts.Length > 1) - driverInfo.Description = parts[1].Trim().Trim('"', '%'); + strings[stringKey] = stringValue.Trim('"'); } - else if (trimmed.StartsWith("HardwareId", StringComparison.OrdinalIgnoreCase) - || trimmed.Contains("HW_ID", StringComparison.OrdinalIgnoreCase)) + } + + // Pass 2: DriverVer (Version section only), DriverDesc and HardwareId (any section). + currentSection = null; + foreach (var rawLine in lines) + { + var trimmed = rawLine.Trim(); + if (trimmed.Length == 0 || trimmed.StartsWith(';')) + continue; + + if (trimmed.StartsWith('[') && trimmed.EndsWith(']')) { - var parts = trimmed.Split('='); + currentSection = trimmed[1..^1].Trim(); + continue; + } + + if (!TrySplitKeyValue(trimmed, out var key, out var value)) + continue; + + var inVersionSection = currentSection is not null && + currentSection.Equals("Version", StringComparison.OrdinalIgnoreCase); + + if (inVersionSection && key.StartsWith("DriverVer", StringComparison.OrdinalIgnoreCase)) + { + // Format: DriverVer=MM/DD/YYYY[,a.b.c.d] + var parts = value.Split(','); if (parts.Length > 1) - driverInfo.HardwareId = parts[1].Trim().Trim('"'); + driverInfo.Version = parts[1].Trim(); + + if (parts.Length > 0) + driverInfo.ReleaseDate = ParseDriverVerDate(parts[0].Trim()); + } + else if (string.IsNullOrEmpty(driverInfo.Description) && + key.StartsWith("DriverDesc", StringComparison.OrdinalIgnoreCase)) + { + driverInfo.Description = ResolveStringReference(value, strings); + } + else if (string.IsNullOrEmpty(driverInfo.HardwareId) && + (key.StartsWith("HardwareId", StringComparison.OrdinalIgnoreCase) || + key.Contains("HW_ID", StringComparison.OrdinalIgnoreCase))) + { + driverInfo.HardwareId = ResolveStringReference(value, strings).Trim('"'); } } @@ -373,4 +712,51 @@ private static async Task ParseInfFileAsync( GeneralTracer.Debug($"Could not parse INF file: {infPath} - {ex.Message}"); } } + + private static bool TrySplitKeyValue(string line, out string key, out string value) + { + var eqIdx = line.IndexOf('='); + if (eqIdx <= 0) + { + key = string.Empty; + value = string.Empty; + return false; + } + + key = line[..eqIdx].Trim(); + value = line[(eqIdx + 1)..].Trim(); + return true; + } + + private static DateTime ParseDriverVerDate(string raw) + { + // INF DriverVer dates are "MM/DD/YYYY" (US format), regardless of the OS locale. + if (DateTime.TryParseExact(raw, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + return date; + + if (DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var invariant)) + return invariant; + + if (DateTime.TryParse(raw, CultureInfo.CurrentCulture, DateTimeStyles.None, out var current)) + return current; + + return default; + } + + /// + /// Resolves "%key%" string references using the [Strings] section values; plain values are + /// returned with quotes stripped. + /// + private static string ResolveStringReference(string value, Dictionary strings) + { + var trimmed = value.Trim(); + if (trimmed.StartsWith('%') && trimmed.EndsWith('%') && trimmed.Length > 2) + { + var key = trimmed[1..^1]; + if (strings.TryGetValue(key, out var resolved)) + return resolved; + } + + return trimmed.Trim('"'); + } } diff --git a/tests/DrivelutionTest/Acceptance/AcceptanceGate.cs b/tests/DrivelutionTest/Acceptance/AcceptanceGate.cs new file mode 100644 index 00000000..0f8e8e0c --- /dev/null +++ b/tests/DrivelutionTest/Acceptance/AcceptanceGate.cs @@ -0,0 +1,79 @@ +using System.Security.Principal; + +namespace DrivelutionTest.Acceptance; + +/// +/// The switch of the driver-store acceptance tests. They install and delete packages in the real +/// driver store, so they run only when everything they need is in place; otherwise they are +/// reported as skipped, with the reason, instead of passing without having done anything. +/// scripts/acceptance/run-windows-acceptance.ps1 arms them. +/// +internal static class AcceptanceGate +{ + /// + /// Why the acceptance tests must not run here; null when they may. + /// + public static string? SkipReason { get; } = EvaluateSkipReason(); + + /// + /// The INF of the test package; meaningful once the gate is armed. + /// + public static string InfPath => + Path.GetFullPath(Environment.GetEnvironmentVariable("DRIVELUTION_ACCEPTANCE_INF")!); + + private static string? EvaluateSkipReason() + { + if (!OperatingSystem.IsWindows()) + { + return "Installs packages into the Windows driver store; runs on Windows only."; + } + + if (Environment.GetEnvironmentVariable("DRIVELUTION_ACCEPTANCE") != "1") + { + return "Destructive: set DRIVELUTION_ACCEPTANCE=1 on a disposable machine to run " + + "(scripts/acceptance/run-windows-acceptance.ps1 does it)."; + } + + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DRIVELUTION_ACCEPTANCE_INF"))) + { + return "Needs a test driver package: DRIVELUTION_ACCEPTANCE_INF must point to its INF."; + } + + if (!IsElevated()) + { + return "Needs an elevated (administrator) process."; + } + + return null; + } + + private static bool IsElevated() + { + try + { + using var identity = WindowsIdentity.GetCurrent(); + return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator); + } + catch + { + return false; + } + } +} + +/// +/// A driver-store acceptance test. It is reported as skipped — with the reason — unless +/// is armed, so that a run which could not perform its installs +/// never looks like a passed gate. +/// +[AttributeUsage(AttributeTargets.Method)] +public sealed class WindowsAcceptanceFactAttribute : FactAttribute +{ + public WindowsAcceptanceFactAttribute() + { + if (AcceptanceGate.SkipReason is { } reason) + { + Skip = reason; + } + } +} diff --git a/tests/DrivelutionTest/Acceptance/WindowsInstallAcceptanceTests.cs b/tests/DrivelutionTest/Acceptance/WindowsInstallAcceptanceTests.cs new file mode 100644 index 00000000..5ff8d114 --- /dev/null +++ b/tests/DrivelutionTest/Acceptance/WindowsInstallAcceptanceTests.cs @@ -0,0 +1,209 @@ +using GeneralUpdate.Drivelution; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Execution; +using GeneralUpdate.Drivelution.Core.Utilities; +using GeneralUpdate.Drivelution.Windows.Implementation; +using System.Diagnostics; + +namespace DrivelutionTest.Acceptance; + +/// +/// REAL driver-store acceptance tests for disposable VMs: they perform actual installs and +/// rollbacks via pnputil, so they run only when is armed — see the +/// conditions there and the preconditions in scripts/acceptance/run-windows-acceptance.ps1. +/// Install/rollback runs against a caller-provided test driver package passed via +/// DRIVELUTION_ACCEPTANCE_INF (an INF inside a package directory; use a test-signed or +/// otherwise approved package). Otherwise the tests are reported as skipped, with the reason: +/// normal CI stays green without ever passing a gate that was not exercised. +/// +public class WindowsInstallAcceptanceTests +{ + private static string InfPath => AcceptanceGate.InfPath; + + private static readonly List TempRoots = new(); + + [WindowsAcceptanceFact] + public async Task Acceptance_Install_ThenRollback_RoundTrip() + { + var originalName = Path.GetFileName(InfPath); + var updater = CreateUpdater(); + await CleanupLeftoversAsync(originalName); + + try + { + var driver = BuildDriver(); + var strategy = new UpdateStrategy + { + RequireBackup = true, + BackupPath = NewTempRoot(), + FailOnVerificationFailure = false + }; + + // ── Fresh install ── + var install = await updater.UpdateAsync(driver, strategy); + Assert.True(install.Success, string.Join(Environment.NewLine, install.StepLogs)); + Assert.Contains( + install.StepLogs, + l => l.Contains("completed", StringComparison.OrdinalIgnoreCase) || l.Contains("restart", StringComparison.OrdinalIgnoreCase)); + + var installedAfterInstall = await updater.GetInstalledDriversAsync(); + Assert.Contains(installedAfterInstall, + d => d.Name.Equals(Path.GetFileNameWithoutExtension(originalName), StringComparison.OrdinalIgnoreCase)); + + // Install state must have been persisted for precise rollback. + Assert.NotNull(install.BackupPath); + var state = InstallStateStore.Load(install.BackupPath!); + Assert.NotNull(state); + Assert.False(string.IsNullOrEmpty(state!.PublishedName)); + + // ── Rollback (fresh install: removes the newly added package) ── + var rollback = await updater.RollbackAsync(install.BackupPath!); + Assert.True(rollback); + + var installedAfterRollback = await updater.GetInstalledDriversAsync(); + Assert.DoesNotContain(installedAfterRollback, + d => d.PublishedName.Equals(state.PublishedName, StringComparison.OrdinalIgnoreCase)); + } + finally + { + await CleanupLeftoversAsync(originalName); + CleanupTempRoots(); + } + } + + [WindowsAcceptanceFact] + public async Task Acceptance_InstalledBackupHook_ExportsStorePackage() + { + var originalName = Path.GetFileName(InfPath); + await CleanupLeftoversAsync(originalName); + + try + { + var updater = CreateUpdater(); + + // Install first so a matching package exists in the driver store. + var strategy = new UpdateStrategy { RequireBackup = true, BackupPath = NewTempRoot() }; + var install = await updater.UpdateAsync(BuildDriver(), strategy); + Assert.True(install.Success, string.Join(Environment.NewLine, install.StepLogs)); + + // A second install now finds the installed package; the backup hook must export it + // from the driver store (full package with catalog) instead of copying local files. + var strategy2 = new UpdateStrategy { RequireBackup = true, BackupPath = NewTempRoot() }; + var update = await updater.UpdateAsync(BuildDriver(), strategy2); + Assert.True(update.Success, string.Join(Environment.NewLine, update.StepLogs)); + Assert.NotNull(update.BackupPath); + + var manifest = BackupManifestStore.Load(update.BackupPath!); + Assert.NotNull(manifest); + Assert.Equal(BackupManifest.SourceInstalled, manifest!.Source); + Assert.NotEmpty(manifest.Files); + } + finally + { + await CleanupLeftoversAsync(originalName); + CleanupTempRoots(); + } + } + + // ─── Helpers ─────────────────────────────────────────────────────── + + private static WindowsGeneralDrivelution CreateUpdater() + { + var options = new DrivelutionOptions + { + DefaultBackupPath = NewTempRoot(), + DefaultTimeoutSeconds = 120 + }; + return new WindowsGeneralDrivelution( + new WindowsDriverValidator(), + new WindowsDriverBackup(), + new CommandRunner(), + options); + } + + private static DriverInfo BuildDriver() + { + return new DriverInfo + { + Name = Path.GetFileNameWithoutExtension(InfPath), + Version = "1.0.0", + FilePath = InfPath, + TargetOS = "Windows", + Architecture = Environment.Is64BitOperatingSystem ? "x64" : "x86" + }; + } + + private static async Task CleanupLeftoversAsync(string originalName) + { + try + { + var updater = CreateUpdater(); + var installed = await updater.GetInstalledDriversAsync(); + var leftovers = installed + .Where(d => d.Name.Equals(Path.GetFileNameWithoutExtension(originalName), StringComparison.OrdinalIgnoreCase)) + .Select(d => d.PublishedName) + .ToList(); + + foreach (var published in leftovers) + { + await DeleteDriverPackageAsync(published); + } + } + catch + { + // Cleanup is best-effort. + } + } + + private static async Task DeleteDriverPackageAsync(string publishedName) + { + var psi = new ProcessStartInfo + { + FileName = "pnputil.exe", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + psi.ArgumentList.Add("/delete-driver"); + psi.ArgumentList.Add(publishedName); + psi.ArgumentList.Add("/force"); + + using var process = Process.Start(psi); + if (process is not null) + await process.WaitForExitAsync(); + } + + private static string NewTempRoot() + { + var root = Path.Combine(Path.GetTempPath(), $"drivelution_accept_{Guid.NewGuid():N}"); + Directory.CreateDirectory(root); + lock (TempRoots) + { + TempRoots.Add(root); + } + return root; + } + + private static void CleanupTempRoots() + { + lock (TempRoots) + { + foreach (var root in TempRoots) + { + try + { + if (Directory.Exists(root)) + Directory.Delete(root, recursive: true); + } + catch + { + // best-effort + } + } + + TempRoots.Clear(); + } + } +} diff --git a/tests/DrivelutionTest/DrivelutionTest.csproj b/tests/DrivelutionTest/DrivelutionTest.csproj index bec554f3..615b514f 100644 --- a/tests/DrivelutionTest/DrivelutionTest.csproj +++ b/tests/DrivelutionTest/DrivelutionTest.csproj @@ -1,7 +1,7 @@ - net10.0 + net8.0;net10.0 enable enable diff --git a/tests/DrivelutionTest/DriverBackup/DriverBackupTests.cs b/tests/DrivelutionTest/DriverBackup/DriverBackupTests.cs new file mode 100644 index 00000000..4d03b8a5 --- /dev/null +++ b/tests/DrivelutionTest/DriverBackup/DriverBackupTests.cs @@ -0,0 +1,241 @@ +using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Linux.Implementation; +using GeneralUpdate.Drivelution.Windows.Implementation; + +namespace DrivelutionTest.DriverBackup; + +/// +/// The driver backup of the current platform on a real file system: the package tree is what +/// gets backed up, a backup location that overlaps the package is refused, and the directory a +/// backup is restores to both kinds of target. +/// +public class DriverBackupTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"drivelution_backup_{Guid.NewGuid():N}"); + private readonly IDriverBackup _backup = CreatePlatformBackup(); + + /// The package directory, holding the driver file, its catalog and a subdirectory. + private string Package { get; } + + /// The driver file: an INF on Windows, a kernel module on Linux. + private string DriverFile { get; } + + private static string DriverFileName => OperatingSystem.IsWindows() ? "driver.inf" : "driver.ko"; + + public DriverBackupTests() + { + Package = Path.Combine(_root, "package"); + Directory.CreateDirectory(Path.Combine(Package, "x64")); + DriverFile = Path.Combine(Package, DriverFileName); + File.WriteAllText(DriverFile, "driver"); + File.WriteAllText(Path.Combine(Package, OperatingSystem.IsWindows() ? "driver.cat" : "modules.dep"), "catalog"); + File.WriteAllText(Path.Combine(Package, "x64", "helper"), "helper"); + } + + [Fact] + public async Task BackupAsync_DriverFile_CopiesTheWholePackageTree() + { + // A driver file is reinstalled together with everything next to it, subdirectories included. + var backup = Path.Combine(_root, "backups", "one"); + + Assert.True(await _backup.BackupAsync(DriverFile, backup, CancellationToken.None)); + + AssertContent(Path.Combine(backup, DriverFileName), "driver"); + AssertContent(Path.Combine(backup, "x64", "helper"), "helper"); + Assert.Equal(3, Directory.GetFiles(backup, "*", SearchOption.AllDirectories).Length); + } + + [Fact] + public async Task BackupAsync_Directory_CopiesTheTree() + { + var backup = Path.Combine(_root, "backups", "one"); + + Assert.True(await _backup.BackupAsync(Package, backup, CancellationToken.None)); + + AssertContent(Path.Combine(backup, "x64", "helper"), "helper"); + } + + [Fact] + public async Task BackupAsync_BackupInsideThePackage_IsRefusedBeforeAnythingIsCopied() + { + // The copy would enumerate its own output and grow until the disk or the path limit gives. + var backup = Path.Combine(Package, "backups", "one"); + + var error = await Assert.ThrowsAsync(() => _backup.BackupAsync(DriverFile, backup)); + + Assert.False(error.CanRetry); // a configuration error does not get better by retrying + Assert.Contains("overlaps the driver package", error.Message); + Assert.False(Directory.Exists(backup)); + Assert.Equal(3, Directory.GetFiles(Package, "*", SearchOption.AllDirectories).Length); + } + + [Theory] + [InlineData("relative")] + [InlineData("absolute")] + public async Task BackupAsync_BackupInsideThePackageInAnotherSpelling_IsRefusedToo(string kind) + { + // The same location spelled differently: with a "." segment and a trailing separator — + // and on Windows, in another case. + var target = Path.Combine(Package, "backups", "one"); + var relative = Path.GetRelativePath(Environment.CurrentDirectory, target); + if (kind == "relative" && Path.IsPathRooted(relative)) + { + return; // the working directory and the temp directory are on different drives (CI): no relative spelling exists + } + + var backup = kind == "relative" + ? Path.Combine(".", relative) + : Path.Combine(Path.GetDirectoryName(Package)!, Path.GetFileName(Package), ".", "backups", "one"); + backup += Path.DirectorySeparatorChar; + if (OperatingSystem.IsWindows()) + backup = backup.ToUpperInvariant(); + + var error = await Assert.ThrowsAsync(() => _backup.BackupAsync(DriverFile, backup)); + + Assert.False(error.CanRetry); + Assert.False(Directory.Exists(Path.Combine(Package, "backups"))); + } + + [Fact] + public async Task BackupAsync_PackageInsideTheBackup_IsRefusedToo() + { + // Backing a package up "around" itself would write package files over their own directory. + var error = await Assert.ThrowsAsync(() => _backup.BackupAsync(DriverFile, _root)); + + Assert.False(error.CanRetry); + Assert.Equal(3, Directory.GetFiles(Package, "*", SearchOption.AllDirectories).Length); + } + + [Fact] + public async Task BackupAsync_MissingSource_FailsWithoutRetry() + { + var missing = Path.Combine(Package, "missing" + Path.GetExtension(DriverFile)); + + var error = await Assert.ThrowsAsync( + () => _backup.BackupAsync(missing, Path.Combine(_root, "backups", "one"))); + + Assert.False(error.CanRetry); + } + + [Fact] + public async Task RestoreAsync_DirectoryBackup_ToTheDriverFile_PutsItsCopyBack() + { + var backup = Path.Combine(_root, "backups", "one"); + await _backup.BackupAsync(DriverFile, backup); + var installed = Path.Combine(_root, "installed", DriverFileName); + Directory.CreateDirectory(Path.GetDirectoryName(installed)!); + await File.WriteAllTextAsync(installed, "replaced"); + + Assert.True(await _backup.RestoreAsync(backup, installed)); + + AssertContent(installed, "driver"); + AssertContent(installed + ".old", "replaced"); // what was there is kept aside + } + + [Fact] + public async Task RestoreAsync_FileNotInTheBackup_FailsBeforeTouchingTheTarget() + { + var backup = Path.Combine(_root, "backups", "one"); + await _backup.BackupAsync(DriverFile, backup); + var target = Path.Combine(_root, "installed", "unrelated" + Path.GetExtension(DriverFile)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + await File.WriteAllTextAsync(target, "still here"); + + await Assert.ThrowsAsync(() => _backup.RestoreAsync(backup, target)); + + AssertContent(target, "still here"); + Assert.False(File.Exists(target + ".old")); + } + + [Fact] + public async Task RestoreAsync_DirectoryBackup_ToThePackageDirectory_RestoresTheTree() + { + var backup = Path.Combine(_root, "backups", "one"); + await _backup.BackupAsync(DriverFile, backup); + // As the pipeline leaves it: its metadata next to the driver files. + await File.WriteAllTextAsync(Path.Combine(backup, "backup_manifest.json"), "{}"); + await File.WriteAllTextAsync(Path.Combine(backup, "install_state.json"), "{}"); + + // The installed package lost a file, its driver file is damaged and read-only. + File.Delete(Path.Combine(Package, "x64", "helper")); + await File.WriteAllTextAsync(DriverFile, "damaged"); + File.SetAttributes(DriverFile, FileAttributes.ReadOnly); + + Assert.True(await _backup.RestoreAsync(backup, Package)); + + AssertContent(DriverFile, "driver"); + AssertContent(Path.Combine(Package, "x64", "helper"), "helper"); + Assert.False(File.Exists(Path.Combine(Package, "backup_manifest.json"))); + Assert.False(File.Exists(Path.Combine(Package, "install_state.json"))); + Assert.Equal(3, Directory.GetFiles(Package, "*", SearchOption.AllDirectories).Length); + } + + [Fact] + public async Task RestoreAsync_SingleFileBackup_RestoresTheFile() + { + // Backups made by older versions are a lone file. + var legacy = Path.Combine(_root, "legacy", DriverFileName); + Directory.CreateDirectory(Path.GetDirectoryName(legacy)!); + await File.WriteAllTextAsync(legacy, "previous driver"); + var target = Path.Combine(_root, "installed", DriverFileName); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + + Assert.True(await _backup.RestoreAsync(legacy, target)); + + AssertContent(target, "previous driver"); + Assert.False(File.Exists(target + ".old")); + } + + [Fact] + public async Task RestoreAsync_MissingBackup_Fails() + { + await Assert.ThrowsAsync( + () => _backup.RestoreAsync(Path.Combine(_root, "nowhere"), Path.Combine(_root, "installed", DriverFileName))); + } + + [Fact] + public async Task RestoreAsync_InterruptedAfterTheTargetWasMovedAside_LeavesTheTargetAsItWas() + { + var backup = Path.Combine(_root, "backups", "one"); + await _backup.BackupAsync(DriverFile, backup); + var target = Path.Combine(_root, "installed", DriverFileName); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + await File.WriteAllTextAsync(target, "the driver in place"); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + + // The copy gives up only after the target had been moved to ".old". + await Assert.ThrowsAnyAsync(() => _backup.RestoreAsync(backup, target, cancelled.Token)); + + AssertContent(target, "the driver in place"); + Assert.False(File.Exists(target + ".old")); + } + + private static void AssertContent(string path, string expected) => Assert.Equal(expected, File.ReadAllText(path)); + + private static IDriverBackup CreatePlatformBackup() + { + if (OperatingSystem.IsWindows()) + return new WindowsDriverBackup(); + if (OperatingSystem.IsLinux()) + return new LinuxDriverBackup(); + + throw new PlatformNotSupportedException("The driver backup implementations exist for Windows and Linux."); + } + + public void Dispose() + { + try + { + // Read-only files would make the recursive delete fail on Windows. + foreach (var file in Directory.EnumerateFiles(_root, "*", SearchOption.AllDirectories)) + File.SetAttributes(file, FileAttributes.Normal); + Directory.Delete(_root, recursive: true); + } + catch + { + // best effort + } + } +} diff --git a/tests/DrivelutionTest/Execution/CommandRunnerTests.cs b/tests/DrivelutionTest/Execution/CommandRunnerTests.cs index 97d27797..5949da54 100644 --- a/tests/DrivelutionTest/Execution/CommandRunnerTests.cs +++ b/tests/DrivelutionTest/Execution/CommandRunnerTests.cs @@ -4,7 +4,9 @@ namespace DrivelutionTest.Execution; /// /// Unit tests for following AAAT pattern. -/// Tests constructor, interface contract, and RunOrThrowAsync behaviour. +/// Tests constructor, interface contract, RunOrThrowAsync behaviour, output capture, and preemption +/// by cancellation and by the per-command timeout. The commands run through the interpreter of the +/// platform (), so the tests pass on Windows and on Unix alike. /// public class CommandRunnerTests { @@ -38,7 +40,7 @@ public async Task RunAsync_SuccessfulCommand_ReturnsSuccessResult() var runner = new CommandRunner(); // Use a simple built-in command that always succeeds - var result = await runner.RunAsync("cmd", new[] { "/c", "exit 0" }); + var result = await runner.RunAsync(TestShell.FileName, TestShell.Exit(0)); Assert.NotNull(result); Assert.Equal(0, result.ExitCode); @@ -50,7 +52,7 @@ public async Task RunAsync_FailingCommand_ReturnsNonZeroExitCode() { var runner = new CommandRunner(); - var result = await runner.RunAsync("cmd", new[] { "/c", "exit 42" }); + var result = await runner.RunAsync(TestShell.FileName, TestShell.Exit(42)); Assert.NotNull(result); Assert.Equal(42, result.ExitCode); @@ -62,19 +64,48 @@ public async Task RunAsync_CapturesStandardOutput() { var runner = new CommandRunner(); - var result = await runner.RunAsync("cmd", new[] { "/c", "echo HelloWorld" }); + var result = await runner.RunAsync(TestShell.FileName, TestShell.Echo("HelloWorld")); Assert.Contains("HelloWorld", result.StandardOutput); } + #endregion + + #region RunAsync — output capture + + [Fact] + public async Task RunAsync_LargeOutput_IsCapturedCompletely() + { + // A long output must arrive whole, up to its last line. + var runner = new CommandRunner(); + var fileName = $"gu-large-output-{Guid.NewGuid():N}.txt"; + File.WriteAllLines(fileName, Enumerable.Range(1, 50_000).Select(i => $"line {i}")); + try + { + var result = await runner.RunAsync(TestShell.FileName, TestShell.PrintFileThen(fileName, "LAST-LINE")); + + Assert.Equal(0, result.ExitCode); + var lines = result.StandardOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries); + Assert.Equal(50_001, lines.Length); + Assert.Equal("line 1", lines[0].TrimEnd('\r')); + Assert.Equal("line 50000", lines[49_999].TrimEnd('\r')); + Assert.Equal("LAST-LINE", lines[50_000].TrimEnd('\r')); + } + finally + { + File.Delete(fileName); + } + } + [Fact] - public async Task RunAsync_WithEmptyArguments_DoesNotThrow() + public async Task RunAsync_OutputWrittenRightBeforeExit_IsCaptured() { var runner = new CommandRunner(); - var result = await runner.RunAsync("cmd", new[] { "/c", "exit 0" }); + var result = await runner.RunAsync(TestShell.FileName, TestShell.EchoJustBeforeExit(1, "LAST-LINE")); - Assert.True(result.Success); + Assert.Equal(0, result.ExitCode); + Assert.Equal("LAST-LINE", result.StandardOutput.Trim()); } #endregion @@ -86,21 +117,23 @@ public async Task RunOrThrowAsync_SuccessfulCommand_ReturnsResult() { var runner = new CommandRunner(); - var result = await runner.RunOrThrowAsync("cmd", new[] { "/c", "exit 0" }); + var result = await runner.RunOrThrowAsync(TestShell.FileName, TestShell.Exit(0)); Assert.True(result.Success); Assert.Equal(0, result.ExitCode); } [Fact] - public async Task RunOrThrowAsync_FailingCommand_ThrowsInvalidOperationException() + public async Task RunOrThrowAsync_FailingCommand_ThrowsCommandExecutionException() { var runner = new CommandRunner(); - var ex = await Assert.ThrowsAsync( - () => runner.RunOrThrowAsync("cmd", new[] { "/c", "exit 1" })); + var ex = await Assert.ThrowsAsync( + () => runner.RunOrThrowAsync(TestShell.FileName, TestShell.Exit(1))); Assert.Contains("failed with exit code 1", ex.Message); + Assert.Equal(1, ex.ExitCode); + Assert.True(ex.CanRetry); } #endregion @@ -117,7 +150,88 @@ public async Task RunAsync_WithCancellation_PreemptsExecution() cts.CancelAfter(50); await Assert.ThrowsAnyAsync( - () => runner.RunAsync("cmd", new[] { "/c", "ping -n 10 127.0.0.1 > nul" }, cts.Token)); + () => runner.RunAsync(TestShell.FileName, TestShell.Sleep(10), cts.Token)); + } + + [Fact] + public async Task RunAsync_CallerCancelsWhileTimeoutPending_ReportsCancellation() + { + // Both the caller and the timeout are armed: the caller's decision is the one to report. + var runner = new CommandRunner(); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + await Assert.ThrowsAnyAsync( + () => runner.RunAsync(TestShell.FileName, TestShell.Sleep(10), cts.Token, TimeSpan.FromHours(1))); + } + + #endregion + + #region RunAsync — per-command timeout + + [Fact] + public async Task RunAsync_WithTimeout_KillsProcessAndThrowsTimeoutException() + { + var runner = new CommandRunner(); + + var ex = await Assert.ThrowsAsync( + () => runner.RunAsync( + TestShell.FileName, + TestShell.Sleep(10), + CancellationToken.None, + TimeSpan.FromMilliseconds(300))); + + Assert.Contains("timed out", ex.Message); + } + + [Fact] + public async Task RunAsync_WithTimeout_CompletesBeforeTimeout_ReturnsResult() + { + var runner = new CommandRunner(); + + var result = await runner.RunAsync( + TestShell.FileName, + TestShell.Exit(0), + CancellationToken.None, + TimeSpan.FromSeconds(30)); + + Assert.True(result.Success); + } + + [Theory] + [InlineData(false, false, null)] + [InlineData(true, false, typeof(OperationCanceledException))] + [InlineData(false, true, typeof(TimeoutException))] + [InlineData(true, true, typeof(OperationCanceledException))] + public void ThrowIfPreempted_ReportsTheCauseOfThePreemption(bool callerCancelled, bool timedOut, Type? expected) + { + // The kill callback can make the wait end in either direction — normally or with an + // OperationCanceledException — so the outcome is decided by the token states alone, and + // the caller's cancellation outranks the timeout. + using var caller = new CancellationTokenSource(); + using var timeout = new CancellationTokenSource(); + if (callerCancelled) caller.Cancel(); + if (timedOut) timeout.Cancel(); + + Exception? actual = Record.Exception(() => CommandRunner.ThrowIfPreempted( + caller.Token, timeout, "tool", TimeSpan.FromSeconds(3))); + + if (expected is null) + Assert.Null(actual); + else + Assert.IsType(expected, actual); + } + + [Fact] + public void ThrowIfPreempted_WithoutTimeout_OnlyKnowsCallerCancellation() + { + Assert.Null(Record.Exception(() => CommandRunner.ThrowIfPreempted(CancellationToken.None, null, "tool", null))); + + using var caller = new CancellationTokenSource(); + caller.Cancel(); + + Assert.IsType( + Record.Exception(() => CommandRunner.ThrowIfPreempted(caller.Token, null, "tool", null))); } #endregion @@ -129,7 +243,7 @@ public async Task RunAsync_ResultProperties_ArePopulated() { var runner = new CommandRunner(); - var result = await runner.RunAsync("cmd", new[] { "/c", "echo test-output" }); + var result = await runner.RunAsync(TestShell.FileName, TestShell.Echo("test-output")); Assert.NotNull(result.StandardOutput); Assert.NotNull(result.StandardError); diff --git a/tests/DrivelutionTest/Features/NewFeaturesTests.cs b/tests/DrivelutionTest/Features/NewFeaturesTests.cs new file mode 100644 index 00000000..fa962c8f --- /dev/null +++ b/tests/DrivelutionTest/Features/NewFeaturesTests.cs @@ -0,0 +1,826 @@ +using GeneralUpdate.Drivelution; +using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Execution; +using GeneralUpdate.Drivelution.Core.Network; +using GeneralUpdate.Drivelution.Core.Pipeline; +using GeneralUpdate.Drivelution.Core.Utilities; +using GeneralUpdate.Drivelution.Linux.Helpers; +using Moq; + +namespace DrivelutionTest.Features; + +/// +/// Tests for the new pipeline capabilities: cancel/timeout distinction, dry-run, +/// real rollback, incremental skip, batch concurrency/priority, backup manifests, +/// restart orchestration, and the HTTP downloader's request validation. +/// +public class NewFeaturesTests +{ + private readonly Mock _validatorMock; + private readonly Mock _backupMock; + private readonly DrivelutionOptions _options; + + public NewFeaturesTests() + { + _validatorMock = new Mock(); + _backupMock = new Mock(); + _options = new DrivelutionOptions { DefaultTimeoutSeconds = 10 }; + + _validatorMock.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + _validatorMock.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())) + .ReturnsAsync(true); + _validatorMock.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + _backupMock.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + } + + private static DriverInfo CreateDriver(string name = "test", string? version = "1.0.0") + { + var path = Path.Combine(Path.GetTempPath(), $"drivelution_{Guid.NewGuid():N}", $"{name}.sys"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, "test content"); + return new DriverInfo { Name = name, Version = version ?? string.Empty, FilePath = path }; + } + + #region Cancel vs timeout + + [Fact] + public async Task UpdateAsync_UserCancellation_ReportsCancelledNotTimeout() + { + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + async ct => await Task.Delay(Timeout.Infinite, ct)); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy { RequireBackup = false, TimeoutSeconds = 30 }; + using var cts = new CancellationTokenSource(200); + + var result = await updater.UpdateAsync(driver.Driver, strategy, cancellationToken: cts.Token); + + Assert.False(result.Success); + Assert.Equal(UpdateStatus.Cancelled, result.Status); + Assert.Equal(ErrorType.UserCancelled, result.Error?.Type); + Assert.Equal("ERR_CANCELLED", result.Error?.Code); + } + + [Fact] + public async Task UpdateAsync_Timeout_ReportsTimeoutWithRetryHint() + { + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + async ct => await Task.Delay(Timeout.Infinite, ct)); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy { RequireBackup = false, TimeoutSeconds = 1 }; + + var result = await updater.UpdateAsync(driver.Driver, strategy); + + Assert.False(result.Success); + Assert.Equal(ErrorType.Timeout, result.Error?.Type); + Assert.Equal("ERR_TIMEOUT", result.Error?.Code); + Assert.Contains("TimeoutSeconds", result.Error?.SuggestedResolution); + } + + [Fact] + public async Task UpdateAsync_ForceUpdate_IgnoresUserCancellationDuringRun() + { + // Install ignores its token and finishes quickly; the user cancels meanwhile. + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + ct => Task.Delay(300, CancellationToken.None)); + using var driver = new TempDriver(CreateDriver()); + using var cts = new CancellationTokenSource(50); + var strategy = new UpdateStrategy + { + RequireBackup = false, + ForceUpdate = true, + TimeoutSeconds = 30 + }; + + var result = await updater.UpdateAsync(driver.Driver, strategy, cancellationToken: cts.Token); + + // Cancellation must not preempt a forced update; timeout still applies. + Assert.True(result.Success); + Assert.Equal(UpdateStatus.Succeeded, result.Status); + } + + [Fact] + public async Task UpdateAsync_ForceUpdate_PreCancelledBeforeStart_ReportsCancelled() + { + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, _ => Task.CompletedTask); + using var driver = new TempDriver(CreateDriver()); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + var strategy = new UpdateStrategy { RequireBackup = false, ForceUpdate = true }; + + var result = await updater.UpdateAsync(driver.Driver, strategy, cancellationToken: cts.Token); + + Assert.False(result.Success); + Assert.Equal(UpdateStatus.Cancelled, result.Status); + } + + #endregion + + #region Dry run + + [Fact] + public async Task UpdateAsync_DryRun_ChecksOnly_NoInstallNoBackup() + { + var installCount = 0; + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + _ => { Interlocked.Increment(ref installCount); return Task.CompletedTask; }); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy { RequireBackup = true, DryRun = true, BackupPath = Path.GetTempPath() }; + + var result = await updater.UpdateAsync(driver.Driver, strategy); + + Assert.True(result.Success); + Assert.Equal(UpdateStatus.DryRunCompleted, result.Status); + Assert.True(result.IsDryRun); + Assert.Equal(0, installCount); + _backupMock.Verify(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + Assert.Null(result.BackupPath); + } + + #endregion + + #region Incremental / version check + + [Fact] + public async Task UpdateAsync_IncrementalMode_InstalledEqualOrNewer_Skips() + { + var installCount = 0; + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + _ => { Interlocked.Increment(ref installCount); return Task.CompletedTask; }, + installed => new List { new() { Name = "test", Version = "2.0.0" } }); + using var driver = new TempDriver(CreateDriver(version: "1.0.0")); + var strategy = new UpdateStrategy { RequireBackup = false, Mode = UpdateMode.Incremental }; + + var result = await updater.UpdateAsync(driver.Driver, strategy); + + Assert.True(result.Success); + Assert.Equal(UpdateStatus.Skipped, result.Status); + Assert.Equal("2.0.0", result.PreviousVersion); + Assert.Equal(0, installCount); + } + + [Fact] + public async Task UpdateIfNeededAsync_NewerVersion_ProceedsToUpdate() + { + var installCount = 0; + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + _ => { Interlocked.Increment(ref installCount); return Task.CompletedTask; }, + installed => new List { new() { Name = "test", Version = "1.0.0" } }); + using var driver = new TempDriver(CreateDriver(version: "2.0.0")); + + var result = await updater.UpdateIfNeededAsync(driver.Driver); + + Assert.True(result.Success); + Assert.NotEqual(UpdateStatus.Skipped, result.Status); + Assert.Equal(1, installCount); + Assert.Equal("1.0.0", result.PreviousVersion); + } + + #endregion + + #region Real rollback + + [Fact] + public async Task UpdateAsync_VerificationFails_StrictMode_PerformsRealRollback() + { + // The backup mock writes a marker file into the backup dir; the generic manifest-driven + // rollback must copy it back next to the original driver file. + _backupMock.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync((string source, string backupPath, CancellationToken ct) => + { + Directory.CreateDirectory(backupPath); + File.WriteAllText(Path.Combine(backupPath, "rollback_marker.inf"), "previous package"); + return true; + }); + + var verifier = new RollbackTestUpdater(_validatorMock.Object, _backupMock.Object, _options); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy + { + RequireBackup = true, + BackupPath = Path.Combine(Path.GetTempPath(), $"drivelution_rollback_{Guid.NewGuid():N}"), + FailOnVerificationFailure = true + }; + + try + { + var result = await verifier.UpdateAsync(driver.Driver, strategy); + + Assert.False(result.Success); + Assert.Equal(UpdateStatus.RolledBack, result.Status); + Assert.True(result.RolledBack); + + // The backed-up marker must have been restored to the original driver directory — + // proving the pipeline invoked the real restore, not just a directory check. + var restoredMarker = Path.Combine(Path.GetDirectoryName(driver.Driver.FilePath)!, "rollback_marker.inf"); + Assert.True(File.Exists(restoredMarker)); + } + finally + { + if (Directory.Exists(strategy.BackupPath)) + Directory.Delete(strategy.BackupPath, recursive: true); + } + } + + #endregion + + #region Batch concurrency & priority + + [Fact] + public async Task BatchUpdateAsync_Priority_SortsHigherPriorityFirst() + { + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, _ => Task.CompletedTask); + + var low = CreateDriver("low"); + low.Metadata["Priority"] = "0"; + var high = CreateDriver("high"); + high.Metadata["Priority"] = "10"; + var mid = CreateDriver("mid"); + mid.Metadata["Priority"] = "5"; + + var strategy = new UpdateStrategy { RequireBackup = false }; + var result = await updater.BatchUpdateAsync(new[] { low, mid, high }, strategy, BatchMode.Sequential); + + var order = result.Results.Select(r => r.DriverInfo.Name).ToList(); + Assert.Equal(new[] { "high", "mid", "low" }, order); + } + + [Fact] + public async Task BatchUpdateAsync_Parallel_RespectsMaxDegreeOfParallelism() + { + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, + _ => Task.Delay(100, CancellationToken.None)); + + var drivers = Enumerable.Range(0, 6).Select(_ => CreateDriver($"drv_{Guid.NewGuid():N}")).ToList(); + var strategy = new UpdateStrategy + { + RequireBackup = false, + MaxDegreeOfParallelism = 2 + }; + + int current = 0, max = 0; + updater.OnStepStarted += _ => + { + var now = Interlocked.Increment(ref current); + int seen; + do + { + seen = Volatile.Read(ref max); + if (now <= seen) break; + } + while (Interlocked.CompareExchange(ref max, now, seen) != seen); + + Thread.Sleep(50); // hold the slot so overlap is observable + Interlocked.Decrement(ref current); + }; + + try + { + var result = await updater.BatchUpdateAsync(drivers, strategy, BatchMode.Parallel); + Assert.True(result.AllSucceeded); + Assert.True(max <= 2, $"Observed concurrency {max} exceeded MaxDegreeOfParallelism 2"); + } + finally + { + foreach (var d in drivers) + TempDriver.Cleanup(d.FilePath); + } + } + + #endregion + + #region Backup manifest store + + [Fact] + public void BackupManifestStore_SaveLoadListPurge_RoundTrip() + { + var root = Path.Combine(Path.GetTempPath(), $"drivelution_manifest_{Guid.NewGuid():N}"); + try + { + var dir1 = Path.Combine(root, "backup_a"); + var dir2 = Path.Combine(root, "backup_b"); + var dir3 = Path.Combine(root, "not_a_backup"); // no manifest — must never be purged + + Directory.CreateDirectory(dir1); + Directory.CreateDirectory(dir2); + Directory.CreateDirectory(dir3); + File.WriteAllText(Path.Combine(dir3, "keep.txt"), "keep"); + + BackupManifestStore.Save(new BackupManifest + { + DriverName = "a", + DriverVersion = "1.0.0", + OriginalFilePath = @"C:\drivers\a.sys", + Platform = "Windows", + Files = new List { new() { RelativePath = "a.sys", Sha256 = "ab", Size = 2 } } + }, dir1); + BackupManifestStore.Save(new BackupManifest + { + DriverName = "b", + DriverVersion = "2.0.0", + OriginalFilePath = @"C:\drivers\b.sys", + Platform = "Windows" + }, dir2); + + var loaded = BackupManifestStore.Load(dir1); + Assert.NotNull(loaded); + Assert.Equal("a", loaded!.DriverName); + Assert.Single(loaded.Files); + Assert.Equal(dir1, loaded.BackupDirectory); + + var list = BackupManifestStore.List(root); + Assert.Equal(2, list.Count); + Assert.Equal("b", list[0].DriverName); // newest first + + var deleted = BackupManifestStore.Purge(root, keep: 1); + Assert.Equal(1, deleted); + Assert.True(Directory.Exists(dir3), "directories without a manifest must never be purged"); + Assert.True(Directory.Exists(dir2), "the newest backup (b) must be kept"); + Assert.False(Directory.Exists(dir1), "the oldest backup (a) must be purged"); + } + finally + { + if (Directory.Exists(root)) + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public async Task ListAndPurgeBackups_FallBackToConfiguredDefaultRoot() + { + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, + new DrivelutionOptions { DefaultBackupPath = Path.Combine(Path.GetTempPath(), $"drivelution_root_{Guid.NewGuid():N}") }, + _ => Task.CompletedTask); + + var backups = await updater.ListBackupsAsync(); + Assert.NotNull(backups); + + var purged = await updater.PurgeBackupsAsync(keep: 3); + Assert.Equal(0, purged); + } + + #endregion + + #region Restart orchestration + + [Fact] + public async Task UpdateAsync_RestartModeImmediate_WithCallback_RestartsAndReports() + { + var restarts = 0; + var options = new DrivelutionOptions + { + DefaultTimeoutSeconds = 10, + RestartCallback = (_, _) => { Interlocked.Increment(ref restarts); return Task.FromResult(true); } + }; + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, options, _ => Task.CompletedTask); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy { RequireBackup = false, RestartMode = RestartMode.Immediate }; + + var result = await updater.UpdateAsync(driver.Driver, strategy); + + Assert.True(result.Success); + Assert.True(result.RestartRequired); + Assert.Equal(1, restarts); + } + + [Fact] + public async Task UpdateAsync_RestartModePrompt_UserDeclines_RecordsRestartRequired() + { + var options = new DrivelutionOptions + { + DefaultTimeoutSeconds = 10, + RestartPromptCallback = _ => Task.FromResult(false) + }; + var updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, options, _ => Task.CompletedTask); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy { RequireBackup = false, RestartMode = RestartMode.Prompt }; + + var result = await updater.UpdateAsync(driver.Driver, strategy); + + Assert.True(result.Success); + Assert.Equal(UpdateStatus.RestartRequired, result.Status); + Assert.True(result.RestartRequired); + } + + #endregion + + #region Events on the interface + + [Fact] + public async Task IGeneralDrivelution_ExposesEvents() + { + IGeneralDrivelution updater = new TestUpdater(_validatorMock.Object, _backupMock.Object, _options, _ => Task.CompletedTask); + using var driver = new TempDriver(CreateDriver()); + var strategy = new UpdateStrategy { RequireBackup = false }; + + var completed = new List(); + updater.OnUpdateCompleted += r => completed.Add(r); + + await updater.UpdateAsync(driver.Driver, strategy); + + Assert.Single(completed); + Assert.True(completed[0].Success); + } + + #endregion + + #region Downloader request validation + + [Fact] + public async Task HttpNetworkDownloader_RejectsInvalidUrls() + { + var downloader = new HttpNetworkDownloader(); + var target = Path.Combine(Path.GetTempPath(), $"drivelution_dl_{Guid.NewGuid():N}"); + + await Assert.ThrowsAsync(() => + downloader.DownloadAsync(new NetworkDownloadRequest { Url = "file:///C:/x", TargetDirectory = target })); + + await Assert.ThrowsAsync(() => + downloader.DownloadAsync(new NetworkDownloadRequest { Url = "http://127.0.0.1/x", TargetDirectory = target })); + + await Assert.ThrowsAsync(() => + downloader.DownloadAsync(new NetworkDownloadRequest { Url = "", TargetDirectory = target })); + + await Assert.ThrowsAsync(() => + downloader.DownloadAsync(new NetworkDownloadRequest { Url = "https://example.com/x", TargetDirectory = "" })); + } + + #endregion + + #region Helper APIs + +#pragma warning disable CA1416 // IsFingerprint/ExtractFingerprints are pure string helpers + [Fact] + public void LinuxSignatureHelper_FingerprintDetection() + { + Assert.True(LinuxSignatureHelper.IsFingerprint("ABCDEF0123456789ABCDEF0123456789ABCDEF01")); // 40 hex + Assert.True(LinuxSignatureHelper.IsFingerprint("ABCDEF0123456789")); // 16 hex + Assert.False(LinuxSignatureHelper.IsFingerprint("not-a-fingerprint")); + Assert.False(LinuxSignatureHelper.IsFingerprint("user@example.com")); + Assert.False(LinuxSignatureHelper.IsFingerprint("12345")); // too short + } + + [Fact] + public void LinuxSignatureHelper_ExtractsFingerprintsFromColonOutput() + { + const string output = """ + pub:-:4096:1:ABCDEF0123456789:1600000000:::-:::scESC: + fpr:::::::::ABCDEF0123456789ABCDEF0123456789ABCDEF01: + grp:::::::::0123456789ABCDEF0123456789ABCDEF012345678: + uid:-::::1600000000::USER :: + fpr:::::::::1111111111111111111111111111111111111112: + """; + + var fingerprints = LinuxSignatureHelper.ExtractFingerprints(output); + + Assert.Equal(2, fingerprints.Count); + Assert.Contains("ABCDEF0123456789ABCDEF0123456789ABCDEF01", fingerprints); + Assert.Contains("1111111111111111111111111111111111111112", fingerprints); + } +#pragma warning restore CA1416 + + [Fact] + public void CommandExecutionException_CarriesContextAndDefaultsToRetryable() + { + var ex = new CommandExecutionException("modprobe", 22, "stdout", "some error"); + + Assert.Equal("modprobe", ex.Command); + Assert.Equal(22, ex.ExitCode); + Assert.True(ex.CanRetry); + Assert.Contains("exit code 22", ex.Message); + } + + [Fact] + public void RetryPolicy_IsTransient_ClassifiesFailures() + { + Assert.True(RetryPolicy.IsTransient(new CommandExecutionException("cmd", 1, "", ""))); + Assert.True(RetryPolicy.IsTransient(new DriverInstallationException("install failed", canRetry: true))); + Assert.False(RetryPolicy.IsTransient(new DriverInstallationException("install failed", canRetry: false))); + Assert.False(RetryPolicy.IsTransient(new DriverValidationException("bad", "Integrity"))); + Assert.True(RetryPolicy.IsTransient(new IOException("locked"))); + Assert.False(RetryPolicy.IsTransient(new ArgumentException("bad arg"))); + + // A backup failure is retryable by default, and a backup implementation can rule that out. + Assert.True(RetryPolicy.IsTransient(new DriverBackupException("copy failed"))); + Assert.False(RetryPolicy.IsTransient(new DriverBackupException("backup location misconfigured") { CanRetry = false })); + } + + #endregion + + #region pnputil parsing (Windows only) + + [Fact] + public void PnpUtilHelper_ParsesEnumDriversOutput() + { + if (!OperatingSystem.IsWindows()) + return; + + const string enOutput = """ + + Published Name: oem12.inf + Original Name: nvlt.inf + Provider Name: NVIDIA + Class Name: Display adapters + Class GUID: {4d36e968-e325-11ce-bfc1-08002be10318} + Driver Version: 31.0.15.3623 + Signer Name: Microsoft Windows Hardware Compatibility Publisher + File Path: C:\Windows\INF\nvlt.inf + Date: 9/22/2023 + + + Published Name: oem7.inf + Original Name: e1d.inf + Provider Name: Intel + Class Name: Net + Driver Version: 12.15.31.4 + Signer Name: Microsoft Windows Hardware Compatibility Publisher + File Path: C:\Windows\INF\e1d.inf + Date: 2/14/2022 + + """; + + var drivers = GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.ParseEnumDrivers(enOutput); + + Assert.Equal(2, drivers.Count); + Assert.Equal("oem12.inf", drivers[0].PublishedName); + Assert.Equal("nvlt", drivers[0].Name); + Assert.Equal("NVIDIA", drivers[0].Provider); + Assert.Equal("31.0.15.3623", drivers[0].Version); + Assert.NotNull(drivers[0].Date); + } + + [Fact] + public void PnpUtilHelper_ParsesWin11CombinedVersionFormat() + { + if (!OperatingSystem.IsWindows()) + return; + + // Verbatim sample captured from `pnputil /enum-drivers` on Windows 11 (build 22631): + // "Driver Version" carries " " and there are no separate Date/File Path lines. + const string win11Output = """ + + Published Name: oem92.inf + Original Name: alexahpconfigrtk2.inf + Provider Name: Realtek + Class Name: Extension + Class GUID: {e2f84ce7-8efa-411c-aa69-97454ca4cb57} + Extension ID: {7f7901fa-ea73-4a95-bada-55bf89f37009} + Driver Version: 03/19/2019 1.0.0.8656 + Signer Name: Microsoft Windows Hardware Compatibility Publisher + + Published Name: oem161.inf + Original Name: appleusb.inf + Provider Name: Apple, Inc. + Class Name: USBDevice + Class GUID: {88bae032-5a81-49f0-bc3d-a4ff138216d6} + Driver Version: 04/25/2025 552.0.0.0 + Signer Name: Microsoft Windows Hardware Compatibility Publisher + + Published Name: oem15.inf + Original Name: cannonlake-lpsystem.inf + Provider Name: INTEL + Class Name: System + Class GUID: {4d36e97d-e325-11ce-bfc1-08002be10318} + Driver Version: 07/18/1968 10.1.15.3 + Signer Name: Microsoft Windows Hardware Compatibility Publisher + + """; + + var drivers = GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.ParseEnumDrivers(win11Output); + + Assert.Equal(3, drivers.Count); + Assert.Equal("oem92.inf", drivers[0].PublishedName); + Assert.Equal("alexahpconfigrtk2", drivers[0].Name); + Assert.Equal("Realtek", drivers[0].Provider); + // The version token is split off the combined field and stays SemVer-comparable. + Assert.Equal("1.0.0.8656", drivers[0].Version); + Assert.True(Semver.TryParse(drivers[0].Version, out _)); + Assert.NotNull(drivers[0].Date); + Assert.Equal("552.0.0.0", drivers[1].Version); + Assert.Equal(2025, drivers[1].Date!.Value.Year); + Assert.Equal("10.1.15.3", drivers[2].Version); + } + + [Fact] + public void PnpUtilHelper_ParsesLocalizedOutput() + { + if (!OperatingSystem.IsWindows()) + return; + + const string zhOutput = """ + + 发布名称: oem3.inf + 原始名称: hdaudio.inf + 提供程序名称: Microsoft + 类名称: 媒体类 + 驱动程序版本: 10.0.19041.1 + 签名者: Microsoft Windows + 文件路径: C:\Windows\INF\hdaudio.inf + 日期: 2006/6/21 + + """; + + var drivers = GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.ParseEnumDrivers(zhOutput); + + Assert.Single(drivers); + Assert.Equal("oem3.inf", drivers[0].PublishedName); + Assert.Equal("hdaudio", drivers[0].Name); + Assert.Equal("10.0.19041.1", drivers[0].Version); + } + + [Fact] + public void PnpUtilHelper_ParsesEnumDevicesOutput() + { + if (!OperatingSystem.IsWindows()) + return; + + // Verbatim sample captured from `pnputil /enum-devices /connected` on Windows 11. + const string devicesOutput = """ + + Instance ID: ACPI\INT0E0C\2&daba3ff&0 + Device Description: Intel(R) Software Guard Extensions Device + Class Name: System + Class GUID: {4d36e97d-e325-11ce-bfc1-08002be10318} + Manufacturer Name: Intel + Status: Started + Driver Name: oem100.inf + + Instance ID: ROOT\DISPLAY\0000 + Device Description: OrayIddDriver Device + Class Name: Display + Status: Error + Problem Code: CM_PROB_FAILED_POST_START + Driver Name: oem101.inf + + """; + + var devices = GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.ParseEnumDevices(devicesOutput); + + Assert.Equal(2, devices.Count); + Assert.Equal("oem100.inf", devices[0].PublishedName); + Assert.Equal("Started", devices[0].Status); + Assert.Equal(@"ACPI\INT0E0C\2&daba3ff&0", devices[0].FilePath); + Assert.Contains("Error", devices[1].Status); + Assert.Contains("CM_PROB_FAILED_POST_START", devices[1].Status); + } + + [Fact] + public void PnpUtilHelper_ParsesUnknownLocalePositionally() + { + if (!OperatingSystem.IsWindows()) + return; + + // Simulated pnputil output in a locale outside the alias table: labels are garbage but + // the block structure (published name, original name, " ", provider) holds. + const string unknownLocaleOutput = """ + + XXXX: oem55.inf + YYYY: foobar.inf + ZZZZ: Widget Corp + WWWWW: Devices + VVVV: 5/6/2021 1.2.3.4 + UUUU: Some Signer + + """; + + var drivers = GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.ParseEnumDrivers(unknownLocaleOutput); + + Assert.Single(drivers); + Assert.Equal("oem55.inf", drivers[0].PublishedName); + Assert.Equal("foobar", drivers[0].Name); + Assert.Equal("1.2.3.4", drivers[0].Version); + } + + [Fact] + public void InstallStateStore_TrySaveLoad_RoundTrip() + { + var dir = Path.Combine(Path.GetTempPath(), $"drivelution_state_{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + try + { + InstallStateStore.TrySave(new InstallState + { + PublishedName = "oem99.inf", + OriginalName = "sample.inf", + DkmsModule = "sample", + DkmsVersion = "1.0", + Platform = "Windows" + }, dir); + + var state = InstallStateStore.Load(dir); + Assert.NotNull(state); + Assert.Equal("oem99.inf", state!.PublishedName); + Assert.Equal("sample.inf", state.OriginalName); + Assert.Equal("sample", state.DkmsModule); + + // Missing state file -> null (never throws). + var empty = Path.Combine(Path.GetTempPath(), $"drivelution_state_{Guid.NewGuid():N}"); + Directory.CreateDirectory(empty); + Assert.Null(InstallStateStore.Load(empty)); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public void PnpUtilHelper_DetectsRebootRequirement() + { + if (!OperatingSystem.IsWindows()) + return; + + var helperType = GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.ExitCodeRebootRequired; + Assert.True(GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.IsRebootRequired(3010, string.Empty)); + Assert.True(GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.IsRebootRequired(0, "You must restart your computer to complete the operation.")); + Assert.True(GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.IsRebootRequired(0, "必须重新启动计算机才能完成此操作。")); + Assert.False(GeneralUpdate.Drivelution.Windows.Helpers.PnpUtilHelper.IsRebootRequired(0, "Driver package added successfully.")); + Assert.Equal(3010, helperType); + } + + #endregion + + #region Test helpers + + /// + /// Concrete updater with configurable install behavior and installed-driver inventory. + /// + private class TestUpdater : BaseDriverUpdater + { + private readonly Func _installAction; + private readonly Func>? _installedLookup; + + public TestUpdater( + IDriverValidator validator, + IDriverBackup backup, + DrivelutionOptions? options, + Func installAction, + Func>? installedLookup = null) + : base(validator, backup, options) + { + _installAction = installAction; + _installedLookup = installedLookup; + } + + protected override Task InstallCoreAsync(PipelineContext context, CancellationToken cancellationToken) + => _installAction(cancellationToken); + + public override Task> GetInstalledDriversAsync(CancellationToken cancellationToken = default) + => Task.FromResult(_installedLookup?.Invoke(cancellationToken) ?? new List()); + } + + /// + /// Updater whose post-install verification always fails — used to prove real rollback. + /// + private class RollbackTestUpdater : TestUpdater + { + public RollbackTestUpdater( + IDriverValidator validator, + IDriverBackup backup, + DrivelutionOptions? options) + : base(validator, backup, options, _ => Task.CompletedTask) + { + } + + protected override Task VerifyInstallationAsync(PipelineContext context, CancellationToken cancellationToken) + => Task.FromResult(false); + } + + /// + /// Temp driver file + directory cleaned up on disposal. + /// + private sealed class TempDriver : IDisposable + { + public TempDriver(DriverInfo driver) => Driver = driver; + + public DriverInfo Driver { get; } + + public void Dispose() => Cleanup(Driver.FilePath); + + public static void Cleanup(string filePath) + { + try + { + var dir = Path.GetDirectoryName(filePath); + if (Directory.Exists(dir) && + Path.GetFileName(dir)?.StartsWith("drivelution_", StringComparison.Ordinal) == true) + { + Directory.Delete(dir, recursive: true); + } + } + catch + { + // best-effort cleanup + } + } + } + + #endregion +} diff --git a/tests/DrivelutionTest/GeneralDrivelutionTests.cs b/tests/DrivelutionTest/GeneralDrivelutionTests.cs index 5417db24..9656caf9 100644 --- a/tests/DrivelutionTest/GeneralDrivelutionTests.cs +++ b/tests/DrivelutionTest/GeneralDrivelutionTests.cs @@ -382,8 +382,10 @@ public async Task GetDriversFromDirectoryAsync_WithDriverFiles_ReturnsDriverInfo Assert.NotEmpty(driver.FilePath); Assert.NotNull(driver.Version); Assert.NotEmpty(driver.Version); - Assert.NotNull(driver.Hash); - Assert.NotEmpty(driver.Hash); + // Self-computed hashes are diagnostics only — DriverInfo.Hash must stay empty + // so the pipeline never validates a file against itself. + Assert.True(string.IsNullOrEmpty(driver.Hash)); + Assert.True(driver.Metadata.ContainsKey("ComputedSHA256")); } } finally diff --git a/tests/DrivelutionTest/Linux/Implementation/LinuxGeneralDrivelutionTests.cs b/tests/DrivelutionTest/Linux/Implementation/LinuxGeneralDrivelutionTests.cs index 45b9c095..14defa4c 100644 --- a/tests/DrivelutionTest/Linux/Implementation/LinuxGeneralDrivelutionTests.cs +++ b/tests/DrivelutionTest/Linux/Implementation/LinuxGeneralDrivelutionTests.cs @@ -31,7 +31,7 @@ public LinuxGeneralDrivelutionTests() It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); _validatorMock.Setup(v => v.ValidateSignatureAsync( - It.IsAny(), It.IsAny>(), It.IsAny())) + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())) .ReturnsAsync(true); _validatorMock.Setup(v => v.ValidateCompatibilityAsync( It.IsAny(), It.IsAny())) diff --git a/tests/DrivelutionTest/MacOSImplementations/MacOSDriverBackupTests.cs b/tests/DrivelutionTest/MacOSImplementations/MacOSDriverBackupTests.cs deleted file mode 100644 index 627be41f..00000000 --- a/tests/DrivelutionTest/MacOSImplementations/MacOSDriverBackupTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -using GeneralUpdate.Drivelution.MacOS.Implementation; - -namespace DrivelutionTest.MacOSImplementations; - -public class MacOSDriverBackupTests : IDisposable -{ - private readonly string _tempDir; - private readonly MacOSDriverBackup _backup; - - public MacOSDriverBackupTests() - { - _tempDir = Path.Combine(Path.GetTempPath(), $"macos_drv_test_{Guid.NewGuid():N}"); - Directory.CreateDirectory(_tempDir); - _backup = new MacOSDriverBackup(); - } - - public void Dispose() - { - try { if (Directory.Exists(_tempDir)) Directory.Delete(_tempDir, true); } - catch { } - } - - [Fact(DisplayName = "MacOSDriverBackup_BackupAsync_源不存在_返回false")] - public async Task BackupAsync_SourceNotExists_ReturnsFalse() - { - var result = await _backup.BackupAsync(Path.Combine(_tempDir, "nonexistent.kext"), Path.Combine(_tempDir, "backup.kext")); - Assert.False(result); - } - - [Fact(DisplayName = "MacOSDriverBackup_BackupAsync_文件复制_返回true")] - public async Task BackupAsync_FileCopy_ReturnsTrue() - { - var sourceFile = Path.Combine(_tempDir, "test.kext"); - await File.WriteAllTextAsync(sourceFile, "kext data"); - var result = await _backup.BackupAsync(sourceFile, Path.Combine(_tempDir, "backups", "driver_backup.kext")); - Assert.True(result); - } - - [Fact(DisplayName = "MacOSDriverBackup_BackupAsync_目录复制_返回true")] - public async Task BackupAsync_DirectoryCopy_ReturnsTrue() - { - var sourceDir = Path.Combine(_tempDir, "MyKext.kext"); - Directory.CreateDirectory(sourceDir); - await File.WriteAllTextAsync(Path.Combine(sourceDir, "Info.plist"), ""); - var result = await _backup.BackupAsync(sourceDir, Path.Combine(_tempDir, "backups", "MyKext.kext")); - Assert.True(result); - } - - [Fact(DisplayName = "MacOSDriverBackup_RestoreAsync_委托给BackupAsync")] - public async Task RestoreAsync_DelegatesToBackup() - { - var sourceFile = Path.Combine(_tempDir, "restore_test.kext"); - await File.WriteAllTextAsync(sourceFile, "data"); - var result = await _backup.RestoreAsync(sourceFile, Path.Combine(_tempDir, "restored.kext")); - Assert.True(result); - } - - [Fact(DisplayName = "MacOSDriverBackup_DeleteBackupAsync_文件存在_返回true")] - public async Task DeleteBackupAsync_FileExists_ReturnsTrue() - { - var file = Path.Combine(_tempDir, "delete_me.kext"); - await File.WriteAllTextAsync(file, "data"); - var result = await _backup.DeleteBackupAsync(file); - Assert.True(result); - } - - [Fact(DisplayName = "MacOSDriverBackup_DeleteBackupAsync_目录存在_递归删除返回true")] - public async Task DeleteBackupAsync_DirectoryExists_ReturnsTrue() - { - var dir = Path.Combine(_tempDir, "delete_dir.kext"); - Directory.CreateDirectory(dir); - var result = await _backup.DeleteBackupAsync(dir); - Assert.True(result); - } -} diff --git a/tests/DrivelutionTest/Models/ModelTests.cs b/tests/DrivelutionTest/Models/ModelTests.cs index 9e788f9e..c2e07d17 100644 --- a/tests/DrivelutionTest/Models/ModelTests.cs +++ b/tests/DrivelutionTest/Models/ModelTests.cs @@ -137,13 +137,13 @@ public void Constructor_CreatesInstanceWithDefaultValues() Assert.Equal(UpdateMode.Full, strategy.Mode); Assert.False(strategy.ForceUpdate); Assert.True(strategy.RequireBackup); - Assert.Equal(3, strategy.RetryCount); - Assert.Equal(5, strategy.RetryIntervalSeconds); + Assert.Equal(0, strategy.RetryCount); // 0 = defer to DrivelutionOptions + Assert.Equal(0, strategy.RetryIntervalSeconds); // 0 = defer to DrivelutionOptions Assert.Equal(0, strategy.Priority); Assert.Equal(RestartMode.Prompt, strategy.RestartMode); Assert.False(strategy.SkipSignatureValidation); Assert.False(strategy.SkipHashValidation); - Assert.Equal(300, strategy.TimeoutSeconds); + Assert.Equal(0, strategy.TimeoutSeconds); // 0 = defer to DrivelutionOptions } /// @@ -321,13 +321,18 @@ public void UpdateStatus_HasExpectedValues() { // Assert Assert.Equal(0, (int)UpdateStatus.NotStarted); - Assert.Equal(1, (int)UpdateStatus.Validating); - Assert.Equal(2, (int)UpdateStatus.BackingUp); - Assert.Equal(3, (int)UpdateStatus.Updating); - Assert.Equal(4, (int)UpdateStatus.Verifying); - Assert.Equal(5, (int)UpdateStatus.Succeeded); - Assert.Equal(6, (int)UpdateStatus.Failed); - Assert.Equal(7, (int)UpdateStatus.RolledBack); + Assert.Equal(1, (int)UpdateStatus.Downloading); + Assert.Equal(2, (int)UpdateStatus.Validating); + Assert.Equal(3, (int)UpdateStatus.BackingUp); + Assert.Equal(4, (int)UpdateStatus.Updating); + Assert.Equal(5, (int)UpdateStatus.Verifying); + Assert.Equal(6, (int)UpdateStatus.Succeeded); + Assert.Equal(7, (int)UpdateStatus.Failed); + Assert.Equal(8, (int)UpdateStatus.RolledBack); + Assert.Equal(9, (int)UpdateStatus.Skipped); + Assert.Equal(10, (int)UpdateStatus.Cancelled); + Assert.Equal(11, (int)UpdateStatus.RestartRequired); + Assert.Equal(12, (int)UpdateStatus.DryRunCompleted); } } diff --git a/tests/DrivelutionTest/Pipeline/AutomaticRollbackTests.cs b/tests/DrivelutionTest/Pipeline/AutomaticRollbackTests.cs new file mode 100644 index 00000000..db0c883d --- /dev/null +++ b/tests/DrivelutionTest/Pipeline/AutomaticRollbackTests.cs @@ -0,0 +1,235 @@ +using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Pipeline; +using Moq; + +namespace DrivelutionTest.Pipeline; + +/// +/// The automatic rollback runs whenever an update fails after its install step began: the step +/// returned Fail, it threw, or it was cut short by the timeout or by a cancellation. +/// +public class AutomaticRollbackTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"drivelution_rollback_{Guid.NewGuid():N}"); + private readonly string _driverFile; + private readonly Mock _validator = new(); + private readonly Mock _backup = new(); + + public AutomaticRollbackTests() + { + Directory.CreateDirectory(_root); + _driverFile = Path.Combine(_root, "driver.package"); + File.WriteAllText(_driverFile, "driver"); + + _validator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + _validator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())) + .ReturnsAsync(true); + _validator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + _backup.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + } + + [Theory] + [InlineData("fail")] // the verify step returns Fail (strict mode) + [InlineData("throw")] // the install step throws, as a failed pnputil or dpkg does + [InlineData("timeout")] // the overall timeout cuts the install short + [InlineData("cancel")] // the caller cancels while the install runs + public async Task UpdateAsync_FailureAfterTheInstallBegan_RollsBackFromTheBackup(string failure) + { + var options = new DrivelutionOptions + { + DefaultBackupPath = Path.Combine(_root, "backups"), + DefaultTimeoutSeconds = failure == "timeout" ? 1 : 60 + }; + var updater = new RecordingUpdater(_validator.Object, _backup.Object, options, failure); + var strategy = new UpdateStrategy { RestartMode = RestartMode.None, FailOnVerificationFailure = failure == "fail" }; + using var cancellation = new CancellationTokenSource(); + + var running = updater.UpdateAsync(CreateDriver(), strategy, cancellationToken: cancellation.Token); + if (failure == "cancel") + { + await updater.InstallEntered.Task; + cancellation.Cancel(); + } + + var result = await running; + + Assert.False(result.Success); + Assert.True(result.RolledBack); + Assert.Equal(result.BackupPath, Assert.Single(updater.RollbackCalls)); + Assert.Contains(result.StepLogs, line => line.EndsWith("Rollback completed")); + + // What broke is still what the result reports. + switch (failure) + { + case "fail": + Assert.Equal(UpdateStatus.RolledBack, result.Status); + Assert.Equal("ERR_PIPELINE", result.Error?.Code); + break; + case "throw": + Assert.Equal(UpdateStatus.Failed, result.Status); + Assert.Equal("ERR_INSTALL", result.Error?.Code); + break; + case "timeout": + Assert.Equal(UpdateStatus.Failed, result.Status); + Assert.Equal(ErrorType.Timeout, result.Error?.Type); + break; + case "cancel": + Assert.Equal(UpdateStatus.Cancelled, result.Status); + Assert.Equal(ErrorType.UserCancelled, result.Error?.Type); + break; + } + } + + [Fact] + public async Task UpdateAsync_FailureWithoutABackup_DoesNotAttemptARollback() + { + // RequireBackup is off: there is nothing to roll back to. + var options = new DrivelutionOptions { DefaultBackupPath = Path.Combine(_root, "backups"), DefaultTimeoutSeconds = 60 }; + var updater = new RecordingUpdater(_validator.Object, _backup.Object, options, "throw"); + + var result = await updater.UpdateAsync( + CreateDriver(), new UpdateStrategy { RestartMode = RestartMode.None, RequireBackup = false }); + + Assert.False(result.Success); + Assert.False(result.RolledBack); + Assert.Empty(updater.RollbackCalls); + } + + [Fact] + public async Task UpdateAsync_FailureBeforeTheInstallBegan_DoesNotAttemptARollback() + { + // The hash check fails: the update never reached its install step, so nothing was changed. + var options = new DrivelutionOptions { DefaultBackupPath = Path.Combine(_root, "backups"), DefaultTimeoutSeconds = 60 }; + _validator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(false); + var updater = new RecordingUpdater(_validator.Object, _backup.Object, options, "throw"); + var driver = CreateDriver(); + driver.Hash = "abc123"; // an expected hash is what makes the integrity check run + + var result = await updater.UpdateAsync( + driver, new UpdateStrategy { RestartMode = RestartMode.None, FailOnVerificationFailure = true }); + + Assert.False(result.Success); + Assert.False(result.RolledBack); + Assert.Empty(updater.RollbackCalls); + } + + [Fact] + public async Task UpdateAsync_DryRun_NeverRollsBack() + { + var options = new DrivelutionOptions { DefaultBackupPath = Path.Combine(_root, "backups"), DefaultTimeoutSeconds = 60 }; + var updater = new RecordingUpdater(_validator.Object, _backup.Object, options, "fail"); + + var result = await updater.UpdateAsync( + CreateDriver(), new UpdateStrategy { RestartMode = RestartMode.None, DryRun = true, FailOnVerificationFailure = true }); + + Assert.True(result.Success); // in a dry run nothing is verified against the system, let alone installed + Assert.False(result.RolledBack); + Assert.Empty(updater.RollbackCalls); + } + + [Fact] + public async Task UpdateAsync_RollbackThatFails_IsReported_AndDoesNotHideTheFailure() + { + var options = new DrivelutionOptions { DefaultBackupPath = Path.Combine(_root, "backups"), DefaultTimeoutSeconds = 60 }; + var updater = new RecordingUpdater(_validator.Object, _backup.Object, options, "throw") { RollbackSucceeds = false }; + + var result = await updater.UpdateAsync(CreateDriver(), new UpdateStrategy { RestartMode = RestartMode.None }); + + Assert.False(result.RolledBack); + Assert.Contains(result.StepLogs, line => line.EndsWith("Rollback failed")); + Assert.Equal("ERR_INSTALL", result.Error?.Code); + } + + [Fact] + public async Task UpdateAsync_RollbackThatThrows_IsReported_AndDoesNotHideTheFailure() + { + var options = new DrivelutionOptions { DefaultBackupPath = Path.Combine(_root, "backups"), DefaultTimeoutSeconds = 60 }; + var updater = new RecordingUpdater(_validator.Object, _backup.Object, options, "throw") { RollbackThrows = true }; + + var result = await updater.UpdateAsync(CreateDriver(), new UpdateStrategy { RestartMode = RestartMode.None }); + + Assert.False(result.Success); + Assert.False(result.RolledBack); + Assert.Contains(result.StepLogs, line => line.EndsWith("Rollback failed")); + Assert.Equal("ERR_INSTALL", result.Error?.Code); + } + + private DriverInfo CreateDriver() => new() + { + Name = "driver", Version = "2.0.0", FilePath = _driverFile, TargetOS = "Windows", Architecture = "x64" + }; + + /// + /// An updater that fails in the way a test asks, and records the rollbacks it is asked to do. + /// + private sealed class RecordingUpdater : BaseDriverUpdater + { + private readonly string _failure; + + public RecordingUpdater(IDriverValidator validator, IDriverBackup backup, DrivelutionOptions options, string failure) + : base(validator, backup, options) + { + _failure = failure; + } + + public List RollbackCalls { get; } = new(); + + public bool RollbackSucceeds { get; init; } = true; + + public bool RollbackThrows { get; init; } + + public TaskCompletionSource InstallEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + protected override async Task InstallCoreAsync(PipelineContext context, CancellationToken cancellationToken) + { + switch (_failure) + { + case "throw": + throw new DriverInstallationException("PnPUtil failed with exit code 259", canRetry: false); + case "timeout": + case "cancel": + // Runs until the overall timeout or the caller's cancellation stops it. + InstallEntered.TrySetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + break; + } + } + + protected override Task VerifyInstallationAsync(PipelineContext context, CancellationToken cancellationToken) + => Task.FromResult(_failure != "fail"); + + public override Task RollbackAsync(string backupPath, CancellationToken cancellationToken = default) + { + RollbackCalls.Add(backupPath); + if (RollbackThrows) + throw new DriverRollbackException("simulated: the rollback itself failed"); + return Task.FromResult(RollbackSucceeds); + } + + public override Task> GetInstalledDriversAsync(CancellationToken cancellationToken = default) + => Task.FromResult(new List()); + } + + public void Dispose() + { + try + { + if (Directory.Exists(_root)) + Directory.Delete(_root, recursive: true); + } + catch + { + // best effort + } + } +} diff --git a/tests/DrivelutionTest/Pipeline/BackupRetentionTests.cs b/tests/DrivelutionTest/Pipeline/BackupRetentionTests.cs new file mode 100644 index 00000000..70033790 --- /dev/null +++ b/tests/DrivelutionTest/Pipeline/BackupRetentionTests.cs @@ -0,0 +1,227 @@ +using GeneralUpdate.Drivelution.Abstractions; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Exceptions; +using GeneralUpdate.Drivelution.Abstractions.Models; +using GeneralUpdate.Drivelution.Core.Pipeline; +using GeneralUpdate.Drivelution.Core.Utilities; +using Moq; + +namespace DrivelutionTest.Pipeline; + +/// +/// Retention deletes old backups — but never one that a running update may still roll back to. +/// +public class BackupRetentionTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"drivelution_retention_{Guid.NewGuid():N}"); + private readonly Mock _validator = new(); + private readonly Mock _backup = new(); + private readonly string _driverFile; + + public BackupRetentionTests() + { + Directory.CreateDirectory(_root); + _driverFile = Path.Combine(_root, "driver.package"); + File.WriteAllText(_driverFile, "driver"); + + _validator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + _validator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())) + .ReturnsAsync(true); + _validator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + _backup.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + } + + #region Backup manifest store + + [Fact] + public void Purge_LeavesAPinnedBackupAlone_UntilItIsReleased() + { + var backups = Path.Combine(_root, "backups"); + var oldest = SaveBackup(backups, "oldest", new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + var middle = SaveBackup(backups, "middle", new DateTime(2026, 1, 2, 0, 0, 0, DateTimeKind.Utc)); + var newest = SaveBackup(backups, "newest", new DateTime(2026, 1, 3, 0, 0, 0, DateTimeKind.Utc)); + + using (BackupManifestStore.Pin(oldest)) + { + // Keep one: the oldest is past its turn, but an update is still using it. + Assert.Equal(1, BackupManifestStore.Purge(backups, keep: 1)); + Assert.True(Directory.Exists(oldest)); + Assert.False(Directory.Exists(middle)); + Assert.True(Directory.Exists(newest)); + } + + Assert.False(BackupManifestStore.IsPinned(oldest)); + Assert.Equal(1, BackupManifestStore.Purge(backups, keep: 1)); + Assert.False(Directory.Exists(oldest)); + Assert.True(Directory.Exists(newest)); + } + + [Fact] + public void Pin_RecognizesOtherSpellingsOfTheDirectory_AndCountsItsHolders() + { + var backup = SaveBackup(Path.Combine(_root, "backups"), "one", DateTime.UtcNow); + + // Relative, with a "." segment and a trailing separator — and on Windows, another case. + var otherSpelling = Path.Combine(Path.GetRelativePath(Environment.CurrentDirectory, backup), ".") + + Path.DirectorySeparatorChar; + if (OperatingSystem.IsWindows()) + otherSpelling = otherSpelling.ToUpperInvariant(); + + var first = BackupManifestStore.Pin(backup); + var second = BackupManifestStore.Pin(otherSpelling); + + Assert.True(BackupManifestStore.IsPinned(backup)); + second.Dispose(); + Assert.True(BackupManifestStore.IsPinned(otherSpelling)); // one holder is left + first.Dispose(); + first.Dispose(); // releasing twice is harmless + Assert.False(BackupManifestStore.IsPinned(backup)); + } + + private static string SaveBackup(string root, string name, DateTime createdAtUtc) + { + var directory = Path.Combine(root, name); + BackupManifestStore.Save(new BackupManifest { DriverName = name, CreatedAtUtc = createdAtUtc }, directory); + return directory; + } + + #endregion + + #region Pipeline + + [Fact] + public async Task UpdateAsync_AnotherUpdateFinishesFirst_KeepsTheBackupOfTheRunningOne() + { + // Two updates share a backup root and keep a single backup. The second one finishes first + // and purges — the first is still installing and its rollback needs its backup. + var backupRoot = Path.Combine(_root, "backups"); + var options = new DrivelutionOptions + { + DefaultBackupPath = backupRoot, BackupsToKeep = 1, AutoCleanupBackups = true, DefaultTimeoutSeconds = 60 + }; + var slow = new BlockingUpdater(_validator.Object, _backup.Object, options, holdInstall: true, failVerification: true); + var fast = new BlockingUpdater(_validator.Object, _backup.Object, options); + var strategy = new UpdateStrategy { RestartMode = RestartMode.None, FailOnVerificationFailure = true }; + + var running = slow.UpdateAsync(CreateDriver("slow"), strategy); + await slow.InstallEntered.Task; // the slow update has made its backup by now + + var finished = await fast.UpdateAsync(CreateDriver("fast"), new UpdateStrategy { RestartMode = RestartMode.None }); + + Assert.True(finished.Success, string.Join(Environment.NewLine, finished.StepLogs)); + Assert.NotNull(finished.BackupPath); + var slowBackup = Directory.GetDirectories(backupRoot).Single(directory => directory != finished.BackupPath); + Assert.True(Directory.Exists(slowBackup)); + + slow.ReleaseInstall.TrySetResult(); // the slow update now fails its verification and rolls back + + var slowResult = await running; + + Assert.True(slowResult.RolledBack); + Assert.Equal(UpdateStatus.RolledBack, slowResult.Status); + + // With nothing using it any more, the next purge takes it. + Assert.Equal(1, await fast.PurgeBackupsAsync(keep: 1)); + Assert.False(Directory.Exists(slowBackup)); + } + + [Fact] + public async Task UpdateAsync_HoldsTheBackupOnlyWhileItRuns() + { + var backupRoot = Path.Combine(_root, "backups"); + var options = new DrivelutionOptions { DefaultBackupPath = backupRoot, DefaultTimeoutSeconds = 60 }; + var updater = new BlockingUpdater(_validator.Object, _backup.Object, options); + + var result = await updater.UpdateAsync(CreateDriver("driver"), new UpdateStrategy { RestartMode = RestartMode.None }); + + Assert.True(result.Success, string.Join(Environment.NewLine, result.StepLogs)); + Assert.True(updater.BackupWasPinnedDuringInstall); + Assert.False(BackupManifestStore.IsPinned(result.BackupPath!)); + } + + [Fact] + public async Task UpdateAsync_RolledBackUpdate_ReleasesItsBackupToo() + { + var backupRoot = Path.Combine(_root, "backups"); + var options = new DrivelutionOptions { DefaultBackupPath = backupRoot, DefaultTimeoutSeconds = 60, AutoCleanupBackups = false }; + var updater = new BlockingUpdater(_validator.Object, _backup.Object, options, holdInstall: true, failVerification: true); + + var running = updater.UpdateAsync(CreateDriver("driver"), + new UpdateStrategy { RestartMode = RestartMode.None, FailOnVerificationFailure = true }); + await updater.InstallEntered.Task; + var backupPath = Directory.GetDirectories(backupRoot).Single(); + Assert.True(BackupManifestStore.IsPinned(backupPath)); + + updater.ReleaseInstall.TrySetResult(); + var result = await running; + + Assert.True(result.RolledBack); + Assert.False(BackupManifestStore.IsPinned(backupPath)); + } + + private DriverInfo CreateDriver(string name) => new() + { + Name = name, Version = "1.0.0", FilePath = _driverFile, TargetOS = "Windows", Architecture = "x64" + }; + + /// + /// An updater whose install step can be held back, to keep an update "running" for as long + /// as a test needs, and whose verification can be made to fail. + /// + private sealed class BlockingUpdater : BaseDriverUpdater + { + private readonly bool _holdInstall; + private readonly bool _failVerification; + + public BlockingUpdater( + IDriverValidator validator, IDriverBackup backup, DrivelutionOptions options, + bool holdInstall = false, bool failVerification = false) + : base(validator, backup, options) + { + _holdInstall = holdInstall; + _failVerification = failVerification; + } + + public TaskCompletionSource InstallEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource ReleaseInstall { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool BackupWasPinnedDuringInstall { get; private set; } + + protected override async Task InstallCoreAsync(PipelineContext context, CancellationToken cancellationToken) + { + BackupWasPinnedDuringInstall = context.Result.BackupPath is { } path && BackupManifestStore.IsPinned(path); + if (!_holdInstall) + return; + + InstallEntered.TrySetResult(); + await ReleaseInstall.Task.WaitAsync(cancellationToken); + } + + protected override Task VerifyInstallationAsync(PipelineContext context, CancellationToken cancellationToken) + => Task.FromResult(!_failVerification); + + public override Task> GetInstalledDriversAsync(CancellationToken cancellationToken = default) + => Task.FromResult(new List()); + } + + #endregion + + public void Dispose() + { + try + { + if (Directory.Exists(_root)) + Directory.Delete(_root, recursive: true); + } + catch + { + // best effort + } + } +} diff --git a/tests/DrivelutionTest/Pipeline/BaseDriverUpdaterTests.cs b/tests/DrivelutionTest/Pipeline/BaseDriverUpdaterTests.cs index 25eb8122..ac188742 100644 --- a/tests/DrivelutionTest/Pipeline/BaseDriverUpdaterTests.cs +++ b/tests/DrivelutionTest/Pipeline/BaseDriverUpdaterTests.cs @@ -24,7 +24,8 @@ public BaseDriverUpdaterTests() // Default: all validations pass _validatorMock.Setup(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); - _validatorMock.Setup(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + _validatorMock.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())) .ReturnsAsync(true); _validatorMock.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(true); @@ -55,7 +56,9 @@ public async Task UpdateAsync_WithProgress_ReportsProgress() var strategy = new UpdateStrategy { RequireBackup = false }; var progressItems = new List(); - var progress = new Progress(p => progressItems.Add(p)); + // Synchronous recorder — Progress posts to the sync context asynchronously and races + // with the assertion below. + var progress = new SyncProgressRecorder(progressItems); await updater.UpdateAsync(driver, strategy, progress); @@ -86,7 +89,7 @@ public async Task UpdateAsync_WithEvents_RaisesEvents() Assert.NotNull(completedResult); } - [Fact(Skip = "Flaky on CI — unrelated to current changes. Runs correctly in local dev.")] + [Fact] public async Task UpdateAsync_WithTimeout_ReportsTimeout() { // Set a very short timeout @@ -208,7 +211,7 @@ public async Task BatchUpdateAsync_WithProgress_ReportsProgress() var drivers = new[] { CreateDriver("drv1", tempFile.Path) }; var strategy = new UpdateStrategy { RequireBackup = false }; var progressItems = new List(); - var progress = new Progress(p => progressItems.Add(p)); + var progress = new SyncProgressRecorder(progressItems); await updater.BatchUpdateAsync(drivers, strategy, BatchMode.Sequential, progress); @@ -223,6 +226,18 @@ public async Task BatchUpdateAsync_WithProgress_ReportsProgress() FilePath = filePath }; + /// + /// Synchronous IProgress implementation for tests (no sync-context races). + /// + private sealed class SyncProgressRecorder : IProgress + { + private readonly List _items; + + public SyncProgressRecorder(List items) => _items = items; + + public void Report(UpdateProgress value) => _items.Add(value); + } + /// /// Minimal concrete subclass for testing BaseDriverUpdater. /// @@ -248,8 +263,11 @@ public TestUpdater( _installAction = installAction; } - protected override Task InstallCoreAsync(DriverInfo driverInfo, UpdateStrategy strategy, CancellationToken cancellationToken) + protected override Task InstallCoreAsync(PipelineContext context, CancellationToken cancellationToken) => _installAction(cancellationToken); + + public override Task> GetInstalledDriversAsync(CancellationToken cancellationToken = default) + => Task.FromResult(new List()); } /// diff --git a/tests/DrivelutionTest/Pipeline/DefaultPipelineStepsTests.cs b/tests/DrivelutionTest/Pipeline/DefaultPipelineStepsTests.cs index e8569272..35cc763c 100644 --- a/tests/DrivelutionTest/Pipeline/DefaultPipelineStepsTests.cs +++ b/tests/DrivelutionTest/Pipeline/DefaultPipelineStepsTests.cs @@ -1,4 +1,5 @@ using GeneralUpdate.Drivelution.Core.Pipeline; +using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Abstractions.Models; using GeneralUpdate.Drivelution.Abstractions; using Moq; @@ -9,13 +10,13 @@ namespace DrivelutionTest.Pipeline; /// DefaultPipelineSteps 测试 /// 分支覆盖点: /// - CreateValidateStep: 文件不存在 -> Fail, Hash验证失败 -> Fail, 签名验证失败 -> Fail, 兼容性失败 -> Fail -/// - CreateValidateStep: 跳过Hash验证(SkipHashValidation=true), 跳过签名(SkipSignatureValidation=true), 空Hash跳过 -/// - CreateValidateStep: TrustedPublishers为空跳过签名验证 +/// - CreateValidateStep: SkipHashValidation/SkipSignatureValidation 在非调试会话中被忽略(仍然验证 + 记录警告) +/// - CreateValidateStep: 空Hash跳过, TrustedPublishers为空且选项中未配置信任时跳过签名验证; 仅选项中配置信任时仍验证 /// - CreateValidateStep: 所有验证通过 -> Ok -/// - CreateBackupStep: RequireBackup=true执行备份, RequireBackup=false跳过 +/// - CreateBackupStep: RequireBackup=true执行备份(写manifest), RequireBackup=false跳过 /// - CreateBackupStep: 备份成功 -> Ok 并设置BackupPath, 备份失败 -> Fail /// - CreateInstallStep: 调用核心安装函数, 成功 -> Ok -/// - CreateVerifyStep: 验证通过 -> Ok, 验证失败不阻塞 -> Ok (仅是警告) +/// - CreateVerifyStep: 验证通过 -> Ok, 验证失败默认非阻塞 -> Ok; FailOnVerificationFailure=true -> Fail /// 触发条件:使用 Mock 的 IDriverValidator 和 IDriverBackup /// 预期结果:管道步骤正确执行和跳过 /// @@ -71,21 +72,26 @@ public async Task CreateValidateStep_HashValidationFails_ReturnsFail() finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } - [Fact(DisplayName = "CreateValidateStep_SkipHashValidation_跳过哈希验证")] - public async Task CreateValidateStep_SkipHashValidation_SkipsHashCheck() + [Fact(DisplayName = "CreateValidateStep_SkipHashValidation_非调试会话仍然验证并警告")] + public async Task CreateValidateStep_SkipHashValidation_OutsideDebugSession_StillValidates() { var tempFile = Path.GetTempFileName(); try { var mockValidator = new Mock(); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); - mockValidator.Setup(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(true); var strategy = new UpdateStrategy { SkipHashValidation = true, RequireBackup = true, BackupPath = "/backups" }; var context = CreateContext(CreateDriver(tempFile), strategy); var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); var result = await step.ExecuteAsync(context, CancellationToken.None); Assert.True(result.Success); - mockValidator.Verify(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + // Test runners run without an attached debugger: the skip switch must be ignored. + mockValidator.Verify(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + Assert.Contains(context.Result.StepLogs, l => l.Contains("WARNING") && l.Contains("SkipHashValidation")); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } @@ -98,7 +104,8 @@ public async Task CreateValidateStep_EmptyHash_SkipsHashCheck() { var mockValidator = new Mock(); mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); - mockValidator.Setup(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(true); var driver = CreateDriver(tempFile); driver.Hash = ""; var context = CreateContext(driver); @@ -110,33 +117,39 @@ public async Task CreateValidateStep_EmptyHash_SkipsHashCheck() finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } - [Fact(DisplayName = "CreateValidateStep_SkipSignatureValidation_跳过签名验证")] - public async Task CreateValidateStep_SkipSignatureValidation_SkipsSignatureCheck() + [Fact(DisplayName = "CreateValidateStep_SkipSignatureValidation_非调试会话仍然验证并警告")] + public async Task CreateValidateStep_SkipSignatureValidation_OutsideDebugSession_StillValidates() { var tempFile = Path.GetTempFileName(); try { var mockValidator = new Mock(); - mockValidator.Setup(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(true); var strategy = new UpdateStrategy { SkipSignatureValidation = true, RequireBackup = true, BackupPath = "/backups" }; var context = CreateContext(CreateDriver(tempFile), strategy); var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); var result = await step.ExecuteAsync(context, CancellationToken.None); Assert.True(result.Success); - mockValidator.Verify(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny()), Times.Never); + mockValidator.Verify(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny()), Times.Once); + Assert.Contains(context.Result.StepLogs, l => l.Contains("WARNING") && l.Contains("SkipSignatureValidation")); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } - [Fact(DisplayName = "CreateValidateStep_TrustedPublishers为空跳过签名验证")] + [Fact(DisplayName = "CreateValidateStep_TrustedPublishers为空且未配置其他信任_跳过签名验证")] public async Task CreateValidateStep_EmptyTrustedPublishers_SkipsSignatureCheck() { var tempFile = Path.GetTempFileName(); try { var mockValidator = new Mock(); - mockValidator.Setup(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); var driver = CreateDriver(tempFile); driver.TrustedPublishers.Clear(); @@ -144,7 +157,48 @@ public async Task CreateValidateStep_EmptyTrustedPublishers_SkipsSignatureCheck( var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); var result = await step.ExecuteAsync(context, CancellationToken.None); Assert.True(result.Success); - mockValidator.Verify(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny()), Times.Never); + mockValidator.Verify(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny()), Times.Never); + } + finally { if (File.Exists(tempFile)) File.Delete(tempFile); } + } + + [Theory(DisplayName = "CreateValidateStep_仅在选项中配置信任_仍按它验证签名")] + [InlineData(true)] + [InlineData(false)] + public async Task CreateValidateStep_TrustConfiguredOnlyInOptions_StillValidatesTheSignature(bool signatureValid) + { + // The options hold signer trust of their own — certificate thumbprints on Windows, GPG + // keys on Linux. A driver that lists no publishers is checked against it: trust that is + // configured but never consulted would accept every package. + if (!OperatingSystem.IsWindows() && !OperatingSystem.IsLinux()) + return; + + var tempFile = Path.GetTempFileName(); + try + { + var mockValidator = new Mock(); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(signatureValid); + mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); + var driver = CreateDriver(tempFile); + driver.TrustedPublishers.Clear(); + var options = new DrivelutionOptions(); + if (OperatingSystem.IsWindows()) + options.TrustedCertificateThumbprints.Add("ABCDEF0123456789ABCDEF0123456789ABCDEF01"); + else + options.TrustedGpgKeys.Add("0123456789ABCDEF0123456789ABCDEF01234567"); + var context = new PipelineContext(driver, CreateStrategy(), new UpdateResult(), options); + var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); + + var result = await step.ExecuteAsync(context, CancellationToken.None); + + Assert.Equal(signatureValid, result.Success); + mockValidator.Verify(v => v.ValidateSignatureAsync( + tempFile, It.IsAny>(), It.IsAny?>(), It.IsAny()), Times.Once); + Assert.Contains(context.Result.StepLogs, l => l.Contains("trust configured in the options")); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } @@ -156,8 +210,10 @@ public async Task CreateValidateStep_SignatureFails_ReturnsFail() try { var mockValidator = new Mock(); - mockValidator.Setup(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); - mockValidator.Setup(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny())).ReturnsAsync(false); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(false); var context = CreateContext(CreateDriver(tempFile)); var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); var result = await step.ExecuteAsync(context, CancellationToken.None); @@ -174,8 +230,10 @@ public async Task CreateValidateStep_CompatibilityFails_ReturnsFail() try { var mockValidator = new Mock(); - mockValidator.Setup(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); - mockValidator.Setup(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(true); mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(false); var context = CreateContext(CreateDriver(tempFile)); var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); @@ -193,8 +251,10 @@ public async Task CreateValidateStep_AllPass_ReturnsOk() try { var mockValidator = new Mock(); - mockValidator.Setup(v => v.ValidateIntegrityAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); - mockValidator.Setup(v => v.ValidateSignatureAsync(It.IsAny(), It.IsAny>(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateIntegrityAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); + mockValidator.Setup(v => v.ValidateSignatureAsync( + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())).ReturnsAsync(true); mockValidator.Setup(v => v.ValidateCompatibilityAsync(It.IsAny(), It.IsAny())).ReturnsAsync(true); var context = CreateContext(CreateDriver(tempFile)); var step = DefaultPipelineSteps.CreateValidateStep(mockValidator.Object); @@ -204,18 +264,29 @@ public async Task CreateValidateStep_AllPass_ReturnsOk() finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } - [Fact(DisplayName = "CreateBackupStep_RequireBackup为true_执行备份")] + [Fact(DisplayName = "CreateBackupStep_RequireBackup为true_执行备份并写manifest")] public async Task CreateBackupStep_RequireBackupTrue_RunsBackup() { - var mockBackup = new Mock(); - mockBackup.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(true); - var context = CreateContext(); - var step = DefaultPipelineSteps.CreateBackupStep(mockBackup.Object); - Assert.True(step.ShouldExecute(context)); - var result = await step.ExecuteAsync(context, CancellationToken.None); - Assert.True(result.Success); - Assert.NotNull(context.Result.BackupPath); - Assert.True(context.Bag.ContainsKey("BackupPath")); + var tempRoot = Path.Combine(Path.GetTempPath(), $"drivelution_backup_{Guid.NewGuid():N}"); + try + { + var mockBackup = new Mock(); + mockBackup.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + var strategy = CreateStrategy(); + strategy.BackupPath = tempRoot; + var context = CreateContext(strategy: strategy); + var step = DefaultPipelineSteps.CreateBackupStep(mockBackup.Object); + Assert.True(step.ShouldExecute(context)); + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.True(result.Success); + Assert.NotNull(context.Result.BackupPath); + Assert.True(context.Bag.ContainsKey("BackupPath")); + // A manifest describing the backup must be written next to it. + Assert.True(File.Exists(Path.Combine(context.Result.BackupPath!, "backup_manifest.json"))); + Assert.Equal(BackupManifest.SourcePackage, context.Bag["BackupSource"]); + } + finally { if (Directory.Exists(tempRoot)) Directory.Delete(tempRoot, recursive: true); } } [Fact(DisplayName = "CreateBackupStep_RequireBackup为false_跳过备份")] @@ -228,16 +299,34 @@ public void CreateBackupStep_RequireBackupFalse_SkipsBackup() Assert.False(step.ShouldExecute(context)); } - [Fact(DisplayName = "CreateBackupStep_备份失败_返回Fail")] - public async Task CreateBackupStep_BackupFails_ReturnsFail() + [Fact(DisplayName = "CreateBackupStep_DryRun_跳过备份")] + public void CreateBackupStep_DryRun_SkipsBackup() { var mockBackup = new Mock(); - mockBackup.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(false); - var context = CreateContext(); + var strategy = new UpdateStrategy { RequireBackup = true, DryRun = true, BackupPath = "/backups" }; + var context = CreateContext(strategy: strategy); var step = DefaultPipelineSteps.CreateBackupStep(mockBackup.Object); - var result = await step.ExecuteAsync(context, CancellationToken.None); - Assert.False(result.Success); - Assert.Equal("Failed to create driver backup", result.ErrorMessage); + Assert.False(step.ShouldExecute(context)); + } + + [Fact(DisplayName = "CreateBackupStep_备份失败_返回Fail")] + public async Task CreateBackupStep_BackupFails_ReturnsFail() + { + var tempRoot = Path.Combine(Path.GetTempPath(), $"drivelution_backup_{Guid.NewGuid():N}"); + try + { + var mockBackup = new Mock(); + mockBackup.Setup(b => b.BackupAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(false); + var strategy = CreateStrategy(); + strategy.BackupPath = tempRoot; + var context = CreateContext(strategy: strategy); + var step = DefaultPipelineSteps.CreateBackupStep(mockBackup.Object); + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.False(result.Success); + Assert.Equal("Failed to create driver backup", result.ErrorMessage); + } + finally { if (Directory.Exists(tempRoot)) Directory.Delete(tempRoot, recursive: true); } } [Fact(DisplayName = "CreateInstallStep_调用InstallCore_返回Ok")] @@ -246,10 +335,10 @@ public async Task CreateInstallStep_CallsInstallCore_ReturnsOk() bool installCalled = false; var driver = CreateDriver(); var context = CreateContext(driver); - var step = DefaultPipelineSteps.CreateInstallStep((d, s, ct) => + var step = DefaultPipelineSteps.CreateInstallStep((ctx, ct) => { installCalled = true; - Assert.Same(driver, d); + Assert.Same(driver, ctx.DriverInfo); return Task.CompletedTask; }); var result = await step.ExecuteAsync(context, CancellationToken.None); @@ -257,24 +346,142 @@ public async Task CreateInstallStep_CallsInstallCore_ReturnsOk() Assert.True(installCalled); } + [Fact(DisplayName = "CreateInstallStep_DryRun_跳过安装")] + public void CreateInstallStep_DryRun_SkipsInstall() + { + var strategy = new UpdateStrategy { DryRun = true }; + var context = CreateContext(strategy: strategy); + var step = DefaultPipelineSteps.CreateInstallStep((_, _) => Task.CompletedTask); + Assert.False(step.ShouldExecute(context)); + } + [Fact(DisplayName = "CreateVerifyStep_验证成功_返回Ok")] public async Task CreateVerifyStep_VerificationSuccess_ReturnsOk() { var driver = CreateDriver(); var context = CreateContext(driver); - var step = DefaultPipelineSteps.CreateVerifyStep((d, ct) => Task.FromResult(true)); + var step = DefaultPipelineSteps.CreateVerifyStep((ctx, ct) => Task.FromResult(true)); var result = await step.ExecuteAsync(context, CancellationToken.None); Assert.True(result.Success); } - [Fact(DisplayName = "CreateVerifyStep_验证失败_仍然返回Ok非阻塞")] + [Fact(DisplayName = "CreateVerifyStep_验证失败_默认仍返回Ok非阻塞")] public async Task CreateVerifyStep_VerificationFails_StillReturnsOk() { var driver = CreateDriver(); var context = CreateContext(driver); - var step = DefaultPipelineSteps.CreateVerifyStep((d, ct) => Task.FromResult(false)); + var step = DefaultPipelineSteps.CreateVerifyStep((ctx, ct) => Task.FromResult(false)); + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.True(result.Success); + Assert.Contains(context.Result.StepLogs, l => l.Contains("WARNING")); + } + + [Fact(DisplayName = "CreateVerifyStep_验证失败且FailOnVerificationFailure_返回Fail")] + public async Task CreateVerifyStep_VerificationFails_StrictMode_ReturnsFail() + { + var driver = CreateDriver(); + var strategy = CreateStrategy(); + strategy.FailOnVerificationFailure = true; + var context = CreateContext(driver, strategy); + var step = DefaultPipelineSteps.CreateVerifyStep((ctx, ct) => Task.FromResult(false)); + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.False(result.Success); + Assert.Contains("verification failed", result.ErrorMessage); + } + + [Fact(DisplayName = "CreatePermissionCheckStep_检查失败且强制终止_返回Fail")] + public async Task CreatePermissionCheckStep_Fails_ForceTerminate_ReturnsFail() + { + var context = CreateContext(); + var step = DefaultPipelineSteps.CreatePermissionCheckStep("CheckPerms", () => "no permission"); + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.False(result.Success); + Assert.Contains("no permission", result.ErrorMessage); + } + + [Fact(DisplayName = "CreatePermissionCheckStep_检查失败但允许继续_返回Ok并警告")] + public async Task CreatePermissionCheckStep_Fails_ContinueAllowed_ReturnsOkWithWarning() + { + var options = new GeneralUpdate.Drivelution.Abstractions.Configuration.DrivelutionOptions + { + ForceTerminateOnPermissionFailure = false + }; + var ctx = new PipelineContext(CreateDriver(), CreateStrategy(), new UpdateResult(), options); + var step = DefaultPipelineSteps.CreatePermissionCheckStep("CheckPerms", () => "no permission"); + var result = await step.ExecuteAsync(ctx, CancellationToken.None); + Assert.True(result.Success); + Assert.Contains(ctx.Result.StepLogs, l => l.Contains("WARNING")); + } + + [Fact(DisplayName = "CreatePermissionCheckStep_检查通过_返回Ok")] + public async Task CreatePermissionCheckStep_Passes_ReturnsOk() + { + var context = CreateContext(); + var step = DefaultPipelineSteps.CreatePermissionCheckStep("CheckPerms", () => null); + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.True(result.Success); + } + + [Fact(DisplayName = "CreateVersionCheckStep_已装版本更新_返回Skip")] + public async Task CreateVersionCheckStep_InstalledNewerOrEqual_Skips() + { + var driver = CreateDriver(); + driver.Version = "1.0.0"; + var context = CreateContext(driver); + context.Strategy.GetType(); // no-op + var strategy = new UpdateStrategy { Mode = UpdateMode.Incremental }; + var ctx = new PipelineContext(driver, strategy, context.Result); + + var step = DefaultPipelineSteps.CreateVersionCheckStep(ct => Task.FromResult(new List + { + new InstalledDriverInfo { Name = "TestDriver", Version = "2.0.0" } + })); + + var result = await step.ExecuteAsync(ctx, CancellationToken.None); + Assert.True(result.Success); + Assert.True(result.Skipped); + Assert.Equal("2.0.0", ctx.Result.PreviousVersion); + } + + [Fact(DisplayName = "CreateVersionCheckStep_新版本更高_继续安装")] + public async Task CreateVersionCheckStep_NewerVersion_Proceeds() + { + var driver = CreateDriver(); + driver.Version = "3.0.0"; + var strategy = new UpdateStrategy { Mode = UpdateMode.Incremental }; + var context = new PipelineContext(driver, strategy, new UpdateResult()); + + var step = DefaultPipelineSteps.CreateVersionCheckStep(ct => Task.FromResult(new List + { + new InstalledDriverInfo { Name = "TestDriver", Version = "2.0.0" } + })); + + var result = await step.ExecuteAsync(context, CancellationToken.None); + Assert.True(result.Success); + Assert.False(result.Skipped); + } + + [Fact(DisplayName = "CreateVersionCheckStep_无匹配已装驱动_继续安装")] + public async Task CreateVersionCheckStep_NoMatch_Proceeds() + { + var driver = CreateDriver(); + driver.Version = "1.0.0"; + var strategy = new UpdateStrategy { Mode = UpdateMode.Incremental }; + var context = new PipelineContext(driver, strategy, new UpdateResult()); + + var step = DefaultPipelineSteps.CreateVersionCheckStep(ct => Task.FromResult(new List())); + var result = await step.ExecuteAsync(context, CancellationToken.None); Assert.True(result.Success); + Assert.False(result.Skipped); + } + + [Fact(DisplayName = "CreateVersionCheckStep_Full模式_不执行")] + public void CreateVersionCheckStep_FullMode_Skips() + { + var context = CreateContext(); + var step = DefaultPipelineSteps.CreateVersionCheckStep(ct => Task.FromResult(new List())); + Assert.False(step.ShouldExecute(context)); } [Fact(DisplayName = "CreateValidateStep_StepName为Validate")] @@ -294,7 +501,7 @@ public void CreateBackupStep_StepName_IsBackup() [Fact(DisplayName = "CreateInstallStep_StepName为Install")] public void CreateInstallStep_StepName_IsInstall() { - var step = DefaultPipelineSteps.CreateInstallStep((_, _, _) => Task.CompletedTask); + var step = DefaultPipelineSteps.CreateInstallStep((_, _) => Task.CompletedTask); Assert.Equal("Install", step.StepName); } diff --git a/tests/DrivelutionTest/Pipeline/RetryPolicyTests.cs b/tests/DrivelutionTest/Pipeline/RetryPolicyTests.cs index 419c6957..a2aa43eb 100644 --- a/tests/DrivelutionTest/Pipeline/RetryPolicyTests.cs +++ b/tests/DrivelutionTest/Pipeline/RetryPolicyTests.cs @@ -1,9 +1,15 @@ using GeneralUpdate.Drivelution.Core.Pipeline; +using GeneralUpdate.Drivelution.Core.Execution; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Models; namespace DrivelutionTest.Pipeline; public class RetryPolicyTests { + private static CommandExecutionException TransientError(int attempt) => + new("cmd", 1, string.Empty, $"Attempt {attempt}"); + [Fact] public void Default_HasExpectedValues() { @@ -26,7 +32,7 @@ public async Task ExecuteAsync_SucceedsOnFirstAttempt_ReturnsResult() { var policy = RetryPolicy.Default; int attempts = 0; - + var result = await policy.ExecuteAsync(async ct => { attempts++; @@ -39,7 +45,7 @@ public async Task ExecuteAsync_SucceedsOnFirstAttempt_ReturnsResult() } [Fact] - public async Task ExecuteAsync_RetriesOnFailure() + public async Task ExecuteAsync_RetriesOnTransientFailure() { var policy = new RetryPolicy(2, TimeSpan.FromMilliseconds(10)); int attempts = 0; @@ -48,7 +54,7 @@ public async Task ExecuteAsync_RetriesOnFailure() { attempts++; if (attempts < 3) - throw new InvalidOperationException($"Attempt {attempts}"); + throw TransientError(attempts); await Task.CompletedTask; return "success"; }); @@ -57,6 +63,46 @@ public async Task ExecuteAsync_RetriesOnFailure() Assert.Equal(3, attempts); } + [Fact] + public async Task ExecuteAsync_DoesNotRetryDeterministicFailure() + { + var policy = new RetryPolicy(3, TimeSpan.FromMilliseconds(10)); + int attempts = 0; + + // Validation failures are deterministic and must not be retried. + await Assert.ThrowsAsync(() => + policy.ExecuteAsync(async ct => + { + attempts++; + await Task.CompletedTask; + throw new InvalidOperationException("deterministic"); + })); + + Assert.Equal(1, attempts); + } + + [Fact] + public async Task ExecuteAsync_CustomPredicate_Wins() + { + var policy = new RetryPolicy( + 2, + TimeSpan.FromMilliseconds(10), + shouldRetry: ex => ex is InvalidOperationException); + int attempts = 0; + + var result = await policy.ExecuteAsync(async ct => + { + attempts++; + if (attempts < 2) + throw new InvalidOperationException("retry-me-per-custom-predicate"); + await Task.CompletedTask; + return "ok"; + }); + + Assert.Equal("ok", result); + Assert.Equal(2, attempts); + } + [Fact] public async Task ExecuteAsync_DoesNotRetryOnCancellation() { @@ -118,7 +164,7 @@ public void FromOptions_Null_ReturnsDefault() [Fact] public void FromOptions_UsesConfiguredValues() { - var options = new GeneralUpdate.Drivelution.Abstractions.Configuration.DrivelutionOptions + var options = new DrivelutionOptions { DefaultRetryCount = 5, DefaultRetryIntervalSeconds = 10, @@ -130,4 +176,62 @@ public void FromOptions_UsesConfiguredValues() Assert.Equal(TimeSpan.FromSeconds(10), policy.Delay); Assert.True(policy.UseExponentialBackoff); } + + [Fact] + public void FromStrategy_StrategyValuesWinOverOptions() + { + var options = new DrivelutionOptions + { + DefaultRetryCount = 5, + DefaultRetryIntervalSeconds = 10 + }; + var strategy = new UpdateStrategy { RetryCount = 1, RetryIntervalSeconds = 2 }; + + var policy = RetryPolicy.FromStrategy(strategy, options); + + Assert.Equal(1, policy.MaxRetries); + Assert.Equal(TimeSpan.FromSeconds(2), policy.Delay); + } + + [Fact] + public void FromStrategy_ZeroStrategyValues_FallBackToOptions() + { + var options = new DrivelutionOptions + { + DefaultRetryCount = 5, + DefaultRetryIntervalSeconds = 10 + }; + var strategy = new UpdateStrategy { RetryCount = 0, RetryIntervalSeconds = 0 }; + + var policy = RetryPolicy.FromStrategy(strategy, options); + + Assert.Equal(5, policy.MaxRetries); + Assert.Equal(TimeSpan.FromSeconds(10), policy.Delay); + } + + [Fact] + public async Task ExecuteAsync_ExponentialBackoff_WithJitter() + { + var options = new DrivelutionOptions + { + DefaultRetryCount = 2, + DefaultRetryIntervalSeconds = 1, + UseExponentialBackoff = true, + UseRetryJitter = true + }; + var policy = RetryPolicy.FromOptions(options); + + int attempts = 0; + var result = await policy.ExecuteAsync(async ct => + { + attempts++; + if (attempts < 3) + throw TransientError(attempts); + await Task.CompletedTask; + return "ok"; + }); + + Assert.Equal("ok", result); + Assert.Equal(3, attempts); + } } diff --git a/tests/DrivelutionTest/Smoke/RealMachineSmokeTests.cs b/tests/DrivelutionTest/Smoke/RealMachineSmokeTests.cs new file mode 100644 index 00000000..3c4b201f --- /dev/null +++ b/tests/DrivelutionTest/Smoke/RealMachineSmokeTests.cs @@ -0,0 +1,148 @@ +using GeneralUpdate.Drivelution; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Models; + +namespace DrivelutionTest.Smoke; + +/// +/// Real-machine smoke tests. They exercise only NON-DESTRUCTIVE flows against the actual +/// operating system: pnputil enumeration (read-only), INF directory scanning (temp files), +/// and a DryRun pipeline (no install, no backup, no system change). +/// Real driver INSTALL/ROLLBACK flows are intentionally NOT covered here — those require an +/// elevated test machine with disposable snapshots; run them manually per the release checklist. +/// +public class RealMachineSmokeTests +{ + [Fact] + public async Task Smoke_GetInstalledDrivers_RealPnputil() + { + if (!OperatingSystem.IsWindows()) + return; + + var updater = GeneralDrivelution.Create(new DrivelutionOptions()); + var drivers = await updater.GetInstalledDriversAsync(); + + // This machine has driver-store packages; the parser must produce usable entries. + Assert.NotEmpty(drivers); + Assert.All(drivers, d => Assert.False(string.IsNullOrEmpty(d.PublishedName))); + Assert.Contains(drivers, d => d.PublishedName.StartsWith("oem", StringComparison.OrdinalIgnoreCase)); + // Version extraction works on the real Win11 combined " " field. + Assert.Contains(drivers, d => !string.IsNullOrEmpty(d.Version) && + d.Version.Split('.').All(p => p.Length > 0 && p.All(char.IsAsciiDigit))); + } + + [Fact] + public async Task Smoke_GetDriversFromDirectory_ParsesMockInf() + { + if (!OperatingSystem.IsWindows()) + return; + + var dir = Path.Combine(Path.GetTempPath(), $"drivelution_smoke_{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + try + { + var inf = Path.Combine(dir, "smoke_driver.inf"); + await File.WriteAllTextAsync(inf, """ + [Version] + Signature="$Windows NT$" + Class=Sample + DriverVer=01/15/2024,1.2.3.4 + + [Strings] + Vendor.Desc="Smoke Test Driver" + + [Sample.Install] + DriverDesc=%Vendor.Desc% + HardwareId=ROOT\SMOKE\0001 + """); + + var updater = GeneralDrivelution.Create(new DrivelutionOptions()); + var drivers = await updater.GetDriversFromDirectoryAsync(dir, "*.inf"); + + var driver = Assert.Single(drivers); + Assert.Equal("smoke_driver", driver.Name); + Assert.Equal("1.2.3.4", driver.Version); + Assert.Equal(new DateTime(2024, 1, 15), driver.ReleaseDate.Date); + // [Strings] indirection is resolved for DriverDesc. + Assert.Equal("Smoke Test Driver", driver.Description); + Assert.Equal("ROOT\\SMOKE\\0001", driver.HardwareId); + // The file's own hash must NOT be presented as an integrity expectation. + Assert.True(string.IsNullOrEmpty(driver.Hash)); + Assert.False(string.IsNullOrEmpty(driver.Metadata["ComputedSHA256"])); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public async Task Smoke_DryRunPipeline_RealMachine_NoSystemChanges() + { + if (!OperatingSystem.IsWindows()) + return; + + var dir = Path.Combine(Path.GetTempPath(), $"drivelution_smoke_{Guid.NewGuid():N}"); + var backupRoot = Path.Combine(Path.GetTempPath(), $"drivelution_smoke_bk_{Guid.NewGuid():N}"); + Directory.CreateDirectory(dir); + Directory.CreateDirectory(backupRoot); + try + { + var inf = Path.Combine(dir, "smoke_dryrun.inf"); + await File.WriteAllTextAsync(inf, """ + [Version] + Signature="$Windows NT$" + Class=Sample + DriverVer=01/15/2024,1.2.3.4 + + [Sample.Install] + DriverDesc="Smoke DryRun Driver" + """); + + var options = new DrivelutionOptions + { + DefaultBackupPath = backupRoot, + // Test runners are not elevated: warn and continue so the pipeline reaches DryRun + // completion instead of stopping at the permission gate. + ForceTerminateOnPermissionFailure = false + }; + var updater = GeneralDrivelution.Create(options); + + var driver = new DriverInfo + { + Name = "smoke_dryrun", + Version = "1.2.3.4", + FilePath = inf, + TargetOS = "Windows", + Architecture = Environment.Is64BitOperatingSystem ? "x64" : "x86" + }; + var strategy = new UpdateStrategy { DryRun = true, RequireBackup = true }; + + var result = await updater.UpdateAsync(driver, strategy); + + Assert.True(result.Success, string.Join(Environment.NewLine, result.StepLogs)); + Assert.Equal(UpdateStatus.DryRunCompleted, result.Status); + Assert.True(result.IsDryRun); + // No backup was taken and nothing was installed. + Assert.Null(result.BackupPath); + Assert.False(Directory.EnumerateDirectories(backupRoot).Any()); + } + finally + { + Directory.Delete(dir, recursive: true); + if (Directory.Exists(backupRoot)) + Directory.Delete(backupRoot, recursive: true); + } + } + + [Fact] + public void Smoke_GetPlatformInfo_ReportsCurrentMachine() + { + var info = GeneralDrivelution.GetPlatformInfo(); + + var expected = OperatingSystem.IsWindows() ? "Windows" : OperatingSystem.IsLinux() ? "Linux" : info.Platform; + Assert.Equal(expected, info.Platform); + Assert.Equal(expected == "Windows" || expected == "Linux", info.IsSupported); + Assert.False(string.IsNullOrEmpty(info.Architecture)); + } +} diff --git a/tests/DrivelutionTest/TestShell.cs b/tests/DrivelutionTest/TestShell.cs new file mode 100644 index 00000000..cc852b8a --- /dev/null +++ b/tests/DrivelutionTest/TestShell.cs @@ -0,0 +1,58 @@ +using System.Globalization; + +namespace DrivelutionTest; + +/// +/// The command interpreter every CI runner has built in, so that tests which need a real process +/// (an exit code, some output, a command that keeps running) behave the same on Windows and on +/// Unix: cmd.exe on Windows, /bin/sh -c elsewhere. +/// +internal static class TestShell +{ + /// + /// The interpreter's file name, for RunAsync(TestShell.FileName, ...). + /// + public static string FileName { get; } = OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/sh"; + + /// + /// Arguments of a command that exits with . + /// + public static string[] Exit(int code) => Run($"exit {code}"); + + /// + /// Arguments of a command that prints — one word, nothing the shell + /// would interpret. + /// + public static string[] Echo(string text) => Run($"echo {text}"); + + /// + /// Arguments of a command that prints the file (relative to the + /// current directory — the command line stays free of quotes, which cmd.exe mangles), then + /// , and exits at once. + /// + public static string[] PrintFileThen(string fileName, string lastLine) => Run(OperatingSystem.IsWindows() + ? $"type {fileName} & echo {lastLine}" + : $"cat {fileName}; echo {lastLine}"); + + /// + /// Arguments of a command that stays quiet for roughly (whole + /// seconds), then prints and exits immediately — the output is the + /// last thing it does. + /// + public static string[] EchoJustBeforeExit(int delaySeconds, string text) => Run(OperatingSystem.IsWindows() + ? $"ping -n {delaySeconds + 1} 127.0.0.1 > nul & echo {text}" + : $"sleep {delaySeconds.ToString(CultureInfo.InvariantCulture)}; echo {text}"); + + /// + /// Arguments of a command that stays alive for about seconds and + /// exits successfully. + /// + public static string[] Sleep(int seconds) => Run(OperatingSystem.IsWindows() + ? $"ping -n {seconds + 1} 127.0.0.1 > nul" + : $"sleep {seconds.ToString(CultureInfo.InvariantCulture)}"); + + /// + /// Arguments that make the interpreter run . + /// + public static string[] Run(string command) => new[] { OperatingSystem.IsWindows() ? "/c" : "-c", command }; +} diff --git a/tests/DrivelutionTest/Tracer/GeneralTracerTests.cs b/tests/DrivelutionTest/Tracer/GeneralTracerTests.cs new file mode 100644 index 00000000..a2cb16f1 --- /dev/null +++ b/tests/DrivelutionTest/Tracer/GeneralTracerTests.cs @@ -0,0 +1,88 @@ +using GeneralUpdate.Drivelution; +using Microsoft.Extensions.Logging; + +namespace DrivelutionTest.Tracer; + +/// +/// The trace state is global: these tests run apart from everything else. +/// +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class GeneralTracerCollection +{ + public const string Name = "GeneralTracer (global trace state)"; +} + +/// +/// The external logger receives every trace message — also while the built-in listeners are +/// turned off, which is what an application that only wants that logger relies on. +/// +[Collection(GeneralTracerCollection.Name)] +public class GeneralTracerTests +{ + private const string Marker = "marker-7f3a9c"; + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ExternalLogger_ReceivesEveryLevel_WhetherOrNotTheBuiltInListenersAreOn(bool builtInOn) + { + var logger = new RecordingLogger(); + var wasEnabled = GeneralTracer.IsTracingEnabled(); + try + { + GeneralTracer.SetExternalLogger(logger); + GeneralTracer.SetTracingEnabled(builtInOn); + + GeneralTracer.Info("info " + Marker); + GeneralTracer.Warn("warn " + Marker); + GeneralTracer.Error("error " + Marker); + + Assert.Equal(builtInOn, GeneralTracer.IsTracingEnabled()); + Assert.Contains(logger.Entries, entry => entry.Level == LogLevel.Information && entry.Message.EndsWith("info " + Marker)); + Assert.Contains(logger.Entries, entry => entry.Level == LogLevel.Warning && entry.Message.EndsWith("warn " + Marker)); + Assert.Contains(logger.Entries, entry => entry.Level == LogLevel.Error && entry.Message.EndsWith("error " + Marker)); + } + finally + { + GeneralTracer.SetTracingEnabled(wasEnabled); + GeneralTracer.SetExternalLogger(null); + } + } + + [Fact] + public void ExternalLogger_ThatThrows_DoesNotBreakTheCaller() + { + try + { + GeneralTracer.SetExternalLogger(new ThrowingLogger()); + + Assert.Null(Record.Exception(() => GeneralTracer.Info("must not throw"))); + } + finally + { + GeneralTracer.SetExternalLogger(null); + } + } + + private sealed class RecordingLogger : ILogger + { + public List<(LogLevel Level, string Message)> Entries { get; } = new(); + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + => Entries.Add((logLevel, formatter(state, exception))); + } + + private sealed class ThrowingLogger : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => false; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + => throw new InvalidOperationException("the logger is unavailable"); + } +} diff --git a/tests/DrivelutionTest/Utilities/SignerTrustTests.cs b/tests/DrivelutionTest/Utilities/SignerTrustTests.cs new file mode 100644 index 00000000..07294136 --- /dev/null +++ b/tests/DrivelutionTest/Utilities/SignerTrustTests.cs @@ -0,0 +1,67 @@ +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using GeneralUpdate.Drivelution.Core.Utilities; + +namespace DrivelutionTest.Utilities; + +/// +/// The signer trust decision behind the Windows signature check: an allowlist accepts what it +/// lists, and only the absence of every allowlist accepts any valid signature. +/// +public class SignerTrustTests +{ + private static readonly string[] NoPublishers = Array.Empty(); + private static readonly string[] NoThumbprints = Array.Empty(); + + [Fact] + public void IsTrusted_NoTrustConfigured_AcceptsAnySigner() + { + Assert.True(SignerTrust.IsTrusted(Certificate("CN=Anyone"), NoPublishers, NoThumbprints)); + } + + [Fact] + public void IsTrusted_ListedThumbprint_AcceptsTheSigner() + { + var certificate = Certificate("CN=Test Driver Publisher"); + + // Thumbprints are compared without regard to case. + Assert.True(SignerTrust.IsTrusted(certificate, NoPublishers, new[] { certificate.Thumbprint.ToLowerInvariant() })); + } + + [Fact] + public void IsTrusted_ThumbprintAllowlistOnly_RejectsAnUnlistedSigner() + { + // The certificate-only configuration: an unlisted certificate used to fall through to + // the "no publishers, accept any signature" clause. + var listed = Certificate("CN=Trusted Vendor"); + var other = Certificate("CN=Someone Else"); + + Assert.False(SignerTrust.IsTrusted(other, NoPublishers, new[] { listed.Thumbprint })); + } + + [Fact] + public void IsTrusted_PublisherAllowlistOnly_AcceptsAMatchingSigner_AndRejectsTheOthers() + { + var certificate = Certificate("CN=Test Driver Publisher, O=Contoso"); + + Assert.True(SignerTrust.IsTrusted(certificate, new[] { "contoso" }, NoThumbprints)); + Assert.False(SignerTrust.IsTrusted(certificate, new[] { "Fabrikam" }, NoThumbprints)); + } + + [Fact] + public void IsTrusted_EitherAllowlistMayMatch() + { + var certificate = Certificate("CN=Test Driver Publisher"); + + Assert.True(SignerTrust.IsTrusted(certificate, new[] { "Fabrikam" }, new[] { certificate.Thumbprint })); + Assert.False(SignerTrust.IsTrusted(certificate, new[] { "Fabrikam" }, new[] { new string('0', 40) })); + } + + private static X509Certificate2 Certificate(string subject) + { + using var key = RSA.Create(2048); + var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + return new X509Certificate2(created.Export(X509ContentType.Pfx)); + } +} diff --git a/tests/DrivelutionTest/Utilities/VersionComparerAndRestartHelperTests.cs b/tests/DrivelutionTest/Utilities/VersionComparerAndRestartHelperTests.cs index ce4a9c84..cf899a61 100644 --- a/tests/DrivelutionTest/Utilities/VersionComparerAndRestartHelperTests.cs +++ b/tests/DrivelutionTest/Utilities/VersionComparerAndRestartHelperTests.cs @@ -351,55 +351,99 @@ public void IsRestartRequired_WithRestartModes_ReturnsTrue(RestartMode mode) } /// - /// Tests that HandleRestartAsync with None mode returns true. + /// Tests that HandleRestartAsync with None mode returns true (nothing to do). /// [Fact] public async Task HandleRestartAsync_WithNoneMode_ReturnsTrue() { // Act - var result = await RestartHelper.HandleRestartAsync(RestartMode.None); + var result = await RestartHelper.HandleRestartAsync(RestartMode.None, restartCallback: null); // Assert Assert.True(result); } /// - /// Tests that HandleRestartAsync with Prompt mode returns false (no user interaction in tests). + /// Tests that HandleRestartAsync Prompt mode without a prompt callback returns false. /// [Fact] - public async Task HandleRestartAsync_WithPromptMode_ReturnsFalse() + public async Task HandleRestartAsync_WithPromptMode_NoCallback_ReturnsFalse() { // Act - var result = await RestartHelper.HandleRestartAsync(RestartMode.Prompt); + var result = await RestartHelper.HandleRestartAsync(RestartMode.Prompt, restartCallback: null); // Assert - Assert.False(result); // Prompt returns false as there's no user interaction + Assert.False(result); // No prompt callback configured } /// - /// Tests that PromptUserForRestart displays message and returns false. + /// Tests that HandleRestartAsync Prompt mode forwards the message to the prompt callback. /// [Fact] - public void PromptUserForRestart_DisplaysMessage_ReturnsFalse() + public async Task HandleRestartAsync_WithPromptMode_CallbackReceivesMessage() { - // Act - var result = RestartHelper.PromptUserForRestart("Test message"); + // Arrange + string? receivedMessage = null; + var result = await RestartHelper.HandleRestartAsync( + RestartMode.Prompt, + restartCallback: null, + promptCallback: message => + { + receivedMessage = message; + return Task.FromResult(true); + }, + message: "Custom restart message"); // Assert - Assert.False(result); + Assert.True(result); + Assert.Equal("Custom restart message", receivedMessage); } /// - /// Tests that PromptUserForRestart with empty message uses default message. + /// Tests that HandleRestartAsync Delayed mode waits for the configured delay then invokes + /// the restart callback with the delay seconds. /// [Fact] - public void PromptUserForRestart_WithEmptyMessage_UsesDefaultMessage() + public async Task HandleRestartAsync_WithDelayedMode_InvokesCallbackAfterDelay() { - // Act - var result = RestartHelper.PromptUserForRestart(""); + // Arrange + int? receivedDelay = null; + var result = await RestartHelper.HandleRestartAsync( + RestartMode.Delayed, + restartCallback: (delaySeconds, ct) => + { + receivedDelay = delaySeconds; + return Task.FromResult(true); + }, + delaySeconds: 1); // Assert - Assert.False(result); + Assert.True(result); + Assert.Equal(1, receivedDelay); + } + + /// + /// Tests that HandleRestartAsync Immediate mode invokes the restart callback with zero delay. + /// + [Fact] + public async Task HandleRestartAsync_WithImmediateMode_InvokesCallback() + { + // Arrange + var called = false; + int? receivedDelay = null; + var result = await RestartHelper.HandleRestartAsync( + RestartMode.Immediate, + restartCallback: (delaySeconds, ct) => + { + called = true; + receivedDelay = delaySeconds; + return Task.FromResult(true); + }); + + // Assert + Assert.True(result); + Assert.True(called); + Assert.Equal(0, receivedDelay); } /// diff --git a/tests/DrivelutionTest/Windows/Implementation/WindowsGeneralDrivelutionTests.cs b/tests/DrivelutionTest/Windows/Implementation/WindowsGeneralDrivelutionTests.cs index 41a0867d..33102786 100644 --- a/tests/DrivelutionTest/Windows/Implementation/WindowsGeneralDrivelutionTests.cs +++ b/tests/DrivelutionTest/Windows/Implementation/WindowsGeneralDrivelutionTests.cs @@ -31,7 +31,7 @@ public WindowsGeneralDrivelutionTests() It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(true); _validatorMock.Setup(v => v.ValidateSignatureAsync( - It.IsAny(), It.IsAny>(), It.IsAny())) + It.IsAny(), It.IsAny>(), It.IsAny?>(), It.IsAny())) .ReturnsAsync(true); _validatorMock.Setup(v => v.ValidateCompatibilityAsync( It.IsAny(), It.IsAny()))