From f196a1c7b67759ca5071d8d76a77f286f6e74cbd Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:38:15 +0000 Subject: [PATCH 001/202] Add unit test project and CI build --- .github/CONTRIBUTING.md | 2 + .github/scripts/create_secret_stub.ps1 | 19 +++++++ .github/workflows/ci.yml | 54 ++++++++++++++++++++ CDPI.sln | 23 +++++++++ CDPIUI.Tests/CDPIUI.Tests.csproj | 27 ++++++++++ CDPIUI.Tests/Core/ConfigCommandLineTests.cs | 23 +++++++++ CDPIUI.Tests/Core/VersionHelperTests.cs | 22 ++++++++ CDPIUI.Tests/Shared/PipePayloadCodecTests.cs | 16 ++++++ 8 files changed, 186 insertions(+) create mode 100644 .github/scripts/create_secret_stub.ps1 create mode 100644 .github/workflows/ci.yml create mode 100644 CDPIUI.Tests/CDPIUI.Tests.csproj create mode 100644 CDPIUI.Tests/Core/ConfigCommandLineTests.cs create mode 100644 CDPIUI.Tests/Core/VersionHelperTests.cs create mode 100644 CDPIUI.Tests/Shared/PipePayloadCodecTests.cs diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 24a3d25f..7363121a 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -17,6 +17,8 @@ Recommended Visual Studio version – 2022. Here is few steps after NuGet restore you must to do: - Create `Secret.cs` in `/CDPIUI.Shared/Secrets/`. Create static class Secret. [Ref](https://github.com/Storik4pro/cdpiui/blob/dev/CDPIUI.Shared/Secrets/SecretExample.cs) + For a local build without Store access run `pwsh .github/scripts/create_secret_stub.ps1`: it creates a `public static class Secret` with empty values (the file is ignored by git). +- Run unit tests with `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj`. - Project using CommunityToolkit.Labs. Connect it from Azure, to restore experimental packages. [Ref](https://marketplace.visualstudio.com/items?itemName=ISWIX-LLC.IsWiX) > Project uses IsWix for MSI-installer building. [Ref](https://marketplace.visualstudio.com/items?itemName=ISWIX-LLC.IsWiX) diff --git a/.github/scripts/create_secret_stub.ps1 b/.github/scripts/create_secret_stub.ps1 new file mode 100644 index 00000000..298efc53 --- /dev/null +++ b/.github/scripts/create_secret_stub.ps1 @@ -0,0 +1,19 @@ +$path = Join-Path $PSScriptRoot '../../CDPIUI.Shared/Secrets/Secret.cs' +if (Test-Path $path) { return } + +@' +using System.Collections.Generic; + +namespace CDPIUI.Shared.Secrets +{ + public static class Secret + { + public static string GitHubToken = ""; + public static string GitLabToken = ""; + public const string ProxyURL = ""; + public const string ProxyKey = ""; + public static string AuthGuid = ""; + public static readonly List TrustedCertificates = []; + } +} +'@ | Set-Content -Path $path -Encoding utf8 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..779a5e7c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + push: + branches: [ main, dev, 'fix/**' ] + pull_request: + +permissions: + contents: read + +jobs: + libraries: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Create build secrets stub + shell: pwsh + run: ./.github/scripts/create_secret_stub.ps1 + + - name: Build + run: | + dotnet build CDPIUI.Shared/CDPIUI.Shared.csproj -c Release + dotnet build CDPIUI.Core/CDPIUI.Core.csproj -c Release -p:Platform=x64 + dotnet build CDPIUI.AddOns/CDPIUI.AddOns.csproj -c Release + dotnet build CDPIUI.TrayIcon/CDPIUI.TrayIcon.csproj -c Release -p:Platform=x64 + + - name: Test + run: dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release + + gui: + runs-on: windows-latest + # The WinUI project needs the CommunityToolkit Labs feed and the Windows App SDK + # tooling; keep it informative until the build is reproducible on hosted runners. + continue-on-error: true + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - uses: microsoft/setup-msbuild@v2 + + - name: Create build secrets stub + shell: pwsh + run: ./.github/scripts/create_secret_stub.ps1 + + - name: Build GUI + run: msbuild CDPIUI/CDPIUI.csproj /restore /p:Configuration=Release /p:Platform=x64 /m diff --git a/CDPI.sln b/CDPI.sln index 4a456105..799ca991 100644 --- a/CDPI.sln +++ b/CDPI.sln @@ -24,6 +24,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CDPIUI.Core", "CDPIUI.Core\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CDPIUI.AddOns", "CDPIUI.AddOns\CDPIUI.AddOns.csproj", "{B7D509E3-DB69-4DAF-A06D-608932C34316}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CDPIUI.Tests", "CDPIUI.Tests\CDPIUI.Tests.csproj", "{8E9C98F3-0483-4381-99FF-78E21C156F2C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM64 = Debug|ARM64 @@ -271,6 +273,27 @@ Global {B7D509E3-DB69-4DAF-A06D-608932C34316}.SingleFileRelease|x64.Build.0 = Release|Any CPU {B7D509E3-DB69-4DAF-A06D-608932C34316}.SingleFileRelease|x86.ActiveCfg = Release|Any CPU {B7D509E3-DB69-4DAF-A06D-608932C34316}.SingleFileRelease|x86.Build.0 = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Debug|ARM64.Build.0 = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Debug|x64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Debug|x64.Build.0 = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Debug|x86.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Debug|x86.Build.0 = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.MsiRelease|ARM64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.MsiRelease|x64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.MsiRelease|x86.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Release|ARM64.ActiveCfg = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Release|ARM64.Build.0 = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Release|x64.ActiveCfg = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Release|x64.Build.0 = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Release|x86.ActiveCfg = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.Release|x86.Build.0 = Release|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.RemoteDebug|ARM64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.RemoteDebug|x64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.RemoteDebug|x86.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.SingleFileRelease|ARM64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.SingleFileRelease|x64.ActiveCfg = Debug|Any CPU + {8E9C98F3-0483-4381-99FF-78E21C156F2C}.SingleFileRelease|x86.ActiveCfg = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj new file mode 100644 index 00000000..61c1765a --- /dev/null +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + + diff --git a/CDPIUI.Tests/Core/ConfigCommandLineTests.cs b/CDPIUI.Tests/Core/ConfigCommandLineTests.cs new file mode 100644 index 00000000..30d8a750 --- /dev/null +++ b/CDPIUI.Tests/Core/ConfigCommandLineTests.cs @@ -0,0 +1,23 @@ +using CDPIUI.Core.ComponentServices.Helpers.Configuration; + +namespace CDPIUI.Tests.Core; + +public class ConfigCommandLineTests +{ + [Fact] + public void TokenizeKeepsQuotedPathTogether() + { + var tokens = ConfigCommandLine.Tokenize("--wf-tcp=80 --hostlist=\"C:\\My Lists\\a.txt\" --new"); + + Assert.Equal(3, tokens.Count); + Assert.Equal("--wf-tcp=80", tokens[0]); + Assert.Equal("--new", tokens[2]); + } + + [Fact] + public void TokenizeEmptyReturnsEmpty() + { + Assert.Empty(ConfigCommandLine.Tokenize(null)); + Assert.Empty(ConfigCommandLine.Tokenize(" ")); + } +} diff --git a/CDPIUI.Tests/Core/VersionHelperTests.cs b/CDPIUI.Tests/Core/VersionHelperTests.cs new file mode 100644 index 00000000..b2b72e10 --- /dev/null +++ b/CDPIUI.Tests/Core/VersionHelperTests.cs @@ -0,0 +1,22 @@ +using CDPIUI.Core.Store; + +namespace CDPIUI.Tests.Core; + +public class VersionHelperTests +{ + [Theory] + [InlineData("1.0.0", "1.0.1")] + [InlineData("1.9.0", "1.10.0")] + [InlineData("v1.2.0", "v1.3.0")] + [InlineData("1.0.0.1", "1.0.0.2")] + public void OlderVersionPrecedesNewer(string oldVersion, string newVersion) + { + Assert.True(VersionHelper.CompareVersionStrings(oldVersion, newVersion) < 0); + } + + [Fact] + public void EqualVersionsCompareAsZero() + { + Assert.Equal(0, VersionHelper.CompareVersionStrings("1.2.3", "1.2.3")); + } +} diff --git a/CDPIUI.Tests/Shared/PipePayloadCodecTests.cs b/CDPIUI.Tests/Shared/PipePayloadCodecTests.cs new file mode 100644 index 00000000..6440313e --- /dev/null +++ b/CDPIUI.Tests/Shared/PipePayloadCodecTests.cs @@ -0,0 +1,16 @@ +using CDPIUI.Shared.Pipe; + +namespace CDPIUI.Tests.Shared; + +public class PipePayloadCodecTests +{ + [Theory] + [InlineData("")] + [InlineData("plain")] + [InlineData("C:\\Tom & Jerry\\list #1+2.txt")] + [InlineData("Юникод ✓")] + public void StringRoundTrip(string value) + { + Assert.Equal(value, PipePayloadCodec.DecodeString(PipePayloadCodec.Encode(value))); + } +} From c29d7b61768faad0953a5800ecc57936c11b5ffe Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:42:35 +0000 Subject: [PATCH 002/202] Fix GoodCheck success ratio calculation Integer division made every strategy below 100% count as failed. --- CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs b/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs index c61ae438..d4cfc264 100644 --- a/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs +++ b/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs @@ -391,7 +391,7 @@ private void AddOutput(string output) StrategyResultAdded?.Invoke(Tuple.Create(currentInt, allInt)); - if (allInt != 0 && currentInt / allInt * 100 >= 65) + if (allInt != 0 && currentInt * 100 / allInt >= 65) { CorrectCount++; CorrectCountChanged?.Invoke(CorrectCount); From cf9626192de62341b02e7fd8ee471fc666558311 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:42:35 +0000 Subject: [PATCH 003/202] Keep NoDPI --quiet flag separated from other arguments --- CDPIUI.Core/ComponentServices/ProcessService.cs | 13 +++++++++++-- CDPIUI.Tests/Core/ProcessServiceTests.cs | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 CDPIUI.Tests/Core/ProcessServiceTests.cs diff --git a/CDPIUI.Core/ComponentServices/ProcessService.cs b/CDPIUI.Core/ComponentServices/ProcessService.cs index 7ce630bd..1228e117 100644 --- a/CDPIUI.Core/ComponentServices/ProcessService.cs +++ b/CDPIUI.Core/ComponentServices/ProcessService.cs @@ -84,7 +84,7 @@ public async Task StartProcess() string args = SetupProxy(componentHelper.GetStartupParams(), Id); var component = HardcodedItemIds.ComponentIds.GetKeyByValue(Id); - if (component == Components.NoDPI) args = args.Replace("--quiet", "") + "--quiet"; + if (component == Components.NoDPI) args = AppendQuietFlag(args); Logger.Instance.CreateDebugLog(nameof(ProcessService), $"Args is {args}"); @@ -120,7 +120,7 @@ public async Task StartProcess(string args, string? _reserved = null) // TODO: r args = SetupProxy(args, Id); var component = HardcodedItemIds.ComponentIds.GetKeyByValue(Id); - if (component == Components.NoDPI) args = args.Replace("--quiet", "") + "--quiet"; + if (component == Components.NoDPI) args = AppendQuietFlag(args); Logger.Instance.CreateDebugLog(nameof(ProcessService), $"Args is {args}"); @@ -326,6 +326,15 @@ public void SetOutput(string output) OutputReset?.Invoke(); } + public static string AppendQuietFlag(string args) + { + string withoutQuiet = QuietFlagRegex().Replace(args, string.Empty).Trim(); + return withoutQuiet.Length == 0 ? "--quiet" : $"{withoutQuiet} --quiet"; + } + + [GeneratedRegex(@"(? Date: Thu, 22 Oct 2026 22:42:35 +0000 Subject: [PATCH 004/202] Report running third-party DPI processes in basic diagnostics --- CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs b/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs index 9bdd0575..588e4ff8 100644 --- a/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs +++ b/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs @@ -234,7 +234,7 @@ public async Task> RunBasicDiagnostic() { RunBasicDialogStates.CheckVPNs, isRunningVPN }, { RunBasicDialogStates.CheckDNS, isUsedDNS }, { RunBasicDialogStates.CheckWinDivert, isWinDivertRunning }, - { RunBasicDialogStates.CheckAnotherComponents, isAnotherServiceComponentRunned }, + { RunBasicDialogStates.CheckAnotherComponents, isAnotherComponentRunned }, { RunBasicDialogStates.CheckAnotherComponentsServices, isAnotherServiceComponentRunned }, }; From 8ad35819f264482c3942efc686f54687bb1283f3 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:42:35 +0000 Subject: [PATCH 005/202] Preserve quotes in imported batch variable values --- CDPIUI.AddOns/CDPIUI.AddOns.csproj | 4 ++++ .../ConfigImport/ConfigImportService.cs | 10 ++++++++-- CDPIUI.Core/CDPIUI.Core.csproj | 4 ++++ .../AddOns/ConfigImportServiceTests.cs | 18 ++++++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 CDPIUI.Tests/AddOns/ConfigImportServiceTests.cs diff --git a/CDPIUI.AddOns/CDPIUI.AddOns.csproj b/CDPIUI.AddOns/CDPIUI.AddOns.csproj index 6bf46f6f..859e1b01 100644 --- a/CDPIUI.AddOns/CDPIUI.AddOns.csproj +++ b/CDPIUI.AddOns/CDPIUI.AddOns.csproj @@ -27,4 +27,8 @@ + + + + diff --git a/CDPIUI.AddOns/ConfigImport/ConfigImportService.cs b/CDPIUI.AddOns/ConfigImport/ConfigImportService.cs index 2372ece6..b2fc636a 100644 --- a/CDPIUI.AddOns/ConfigImport/ConfigImportService.cs +++ b/CDPIUI.AddOns/ConfigImport/ConfigImportService.cs @@ -874,11 +874,17 @@ private static bool HasContinuationCaret(string line) return count % 2 == 1; } - private static bool TryParseSet(string line, out string name, out string value) + internal static bool TryParseSet(string line, out string name, out string value) { Match match = SetRegex().Match(line); name = match.Success ? match.Groups["name"].Value.Trim() : string.Empty; - value = match.Success ? match.Groups["value"].Value.Trim().TrimEnd('"') : string.Empty; + value = match.Success ? match.Groups["value"].Value.Trim() : string.Empty; + if (match.Success && match.Groups["quoted"].Success) + { + int closingQuote = value.LastIndexOf('"'); + if (closingQuote >= 0) + value = value[..closingQuote].TrimEnd(); + } return match.Success && name.Length > 0; } diff --git a/CDPIUI.Core/CDPIUI.Core.csproj b/CDPIUI.Core/CDPIUI.Core.csproj index 89011d2f..426b154c 100644 --- a/CDPIUI.Core/CDPIUI.Core.csproj +++ b/CDPIUI.Core/CDPIUI.Core.csproj @@ -55,4 +55,8 @@ none + + + + diff --git a/CDPIUI.Tests/AddOns/ConfigImportServiceTests.cs b/CDPIUI.Tests/AddOns/ConfigImportServiceTests.cs new file mode 100644 index 00000000..b3190b85 --- /dev/null +++ b/CDPIUI.Tests/AddOns/ConfigImportServiceTests.cs @@ -0,0 +1,18 @@ +using CDPIUI.AddOns.ConfigImport; + +namespace CDPIUI.Tests.AddOns; + +public class ConfigImportServiceTests +{ + [Theory] + [InlineData("set LIST=--hostlist=\"%~dp0lists\\list.txt\"", "LIST", "--hostlist=\"%~dp0lists\\list.txt\"")] + [InlineData("set \"BIN=%~dp0bin\\\"", "BIN", "%~dp0bin\\")] + [InlineData("set \"ARGS=--hostlist=\"a b.txt\"\"", "ARGS", "--hostlist=\"a b.txt\"")] + [InlineData("@SET PORT=443", "PORT", "443")] + public void TryParseSetKeepsQuotesInsideValue(string line, string expectedName, string expectedValue) + { + Assert.True(ConfigImportService.TryParseSet(line, out string name, out string value)); + Assert.Equal(expectedName, name); + Assert.Equal(expectedValue, value); + } +} From 0864c1f5a8627bf1f50bf061cca1837c9d58b5f0 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:42:35 +0000 Subject: [PATCH 006/202] Merge localization files without duplicate key errors on pack export --- .../Helpers/Configuration/ConfigPackMakeHelper.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs index 9f8cac80..66bd22e8 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs @@ -252,7 +252,8 @@ private static async Task> CopyLocFile Path.Combine(item.Item2, locFile.Value)); if (oldLocalizationDict == null || newLocalizationDict == null) continue; - oldLocalizationDict.AddRange(newLocalizationDict); + foreach (var (key, value) in newLocalizationDict) + oldLocalizationDict.TryAdd(key, value); string jsonString = JSONConvertor.SerializeObject(oldLocalizationDict); File.WriteAllText(targetDir, jsonString); From 76ddd0c118bb8f7cf3ac39c984af3c173313e1ca Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:42:35 +0000 Subject: [PATCH 007/202] Handle store items without dependencies --- CDPIUI.Core/Store/StoreHelper.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CDPIUI.Core/Store/StoreHelper.cs b/CDPIUI.Core/Store/StoreHelper.cs index 3544b9f0..773267c8 100644 --- a/CDPIUI.Core/Store/StoreHelper.cs +++ b/CDPIUI.Core/Store/StoreHelper.cs @@ -669,11 +669,11 @@ await LScriptCore.RunScript(item.before_install_actions), } } - private static void AddDependencies(List dependencies, string id) + private static void AddDependencies(List? dependencies, string id) { - foreach (var dependency in dependencies) + foreach (var dependency in dependencies ?? []) { - if (!DatabaseHelper.Instance.IsItemInstalled(dependency[0])) + if (dependency.Length < 2 || !DatabaseHelper.Instance.IsItemInstalled(dependency[0])) continue; DatabaseStoreItem dependencyItem = DatabaseHelper.Instance.GetItemById(dependency[0]); From 9786dde16d4f66b6314a811eabd32b090ee3bc7f Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:43:59 +0000 Subject: [PATCH 008/202] Store installed version and link for online store items Update checks compared against an empty version and never reported updates. --- CDPIUI.Core/Store/OnlineItemsInstallationService.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CDPIUI.Core/Store/OnlineItemsInstallationService.cs b/CDPIUI.Core/Store/OnlineItemsInstallationService.cs index 0c6c484f..ad86c57a 100644 --- a/CDPIUI.Core/Store/OnlineItemsInstallationService.cs +++ b/CDPIUI.Core/Store/OnlineItemsInstallationService.cs @@ -164,6 +164,10 @@ RepoItemModel item if (!result) return OperationResultModel .FailureResult(DownloadWorker.LastError); + + downloadUrl = downloadLinkModel.link ?? downloadUrl; + if (!string.IsNullOrEmpty(downloadLinkModel.version)) + tag = downloadLinkModel.version; } if (restartFlag) From a9d092e4b78cae5b3ab46afe58b643b67786f654 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:43:59 +0000 Subject: [PATCH 009/202] Keep HTTP status code in download error result --- CDPIUI.Core/Store/Network/DownloadWorker.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CDPIUI.Core/Store/Network/DownloadWorker.cs b/CDPIUI.Core/Store/Network/DownloadWorker.cs index 2a5022bf..b4545b8c 100644 --- a/CDPIUI.Core/Store/Network/DownloadWorker.cs +++ b/CDPIUI.Core/Store/Network/DownloadWorker.cs @@ -88,8 +88,10 @@ await requestWorker.DownloadFileAsync(url, tempDestination, ReportDownloadProgre } catch (HttpRequestException ex) when (ex.StatusCode.HasValue) { + string errorCode = $"ERR_DOWNLOAD_{PrettyErrorCode.UNEXPECTED_STATUS_CODE}_{(int)ex.StatusCode.Value}"; StageChanged?.Invoke(Tuple.Create(OperationId, "ErrorHappens")); - ErrorHappens?.Invoke(Tuple.Create(OperationId, $"ERR_DOWNLOAD_{PrettyErrorCode.UNEXPECTED_STATUS_CODE}_{(int)ex.StatusCode.Value}", "Server Error")); + ErrorHappens?.Invoke(Tuple.Create(OperationId, errorCode, "Server Error")); + LastError = ErrorModel.OnlyErrorCode(errorCode); return false; } From ffc88e1b8eb915254193df6c78c3419742b2c685 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:43:59 +0000 Subject: [PATCH 010/202] Treat .MSI extension case-insensitively and handle restart-initiated exit code --- CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs index f6dd8e59..99d4ff67 100644 --- a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs +++ b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs @@ -165,7 +165,7 @@ private async Task ProcessMsi(string operationId, string filePath) lock (_lock) { - if (Path.GetExtension(filePath) == ".msi") + if (string.Equals(Path.GetExtension(filePath), ".msi", StringComparison.OrdinalIgnoreCase)) _currentProcess = RunHelper.Run("msiexec.exe", $"/i \"{filePath}\" /passive /norestart"); else _currentProcess = RunHelper.Run(filePath, $"/install /passive /norestart"); @@ -181,7 +181,7 @@ private async Task ProcessMsi(string operationId, string filePath) await _currentProcess.WaitForExitAsync().ConfigureAwait(false); int exitCode = _currentProcess.ExitCode; - if (exitCode == 3010) + if (exitCode == 3010 || exitCode == 1641) { _ = PipeHelper.SendMsiInstallationPacket(MSIInstallationMessageIds.SetOperationStatus, operationId, MsiState.CompleteRestartRequest); } From ac5735f2cecf30459331259a76c4dc24b39b1cd2 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:43:59 +0000 Subject: [PATCH 011/202] Restore tray component controls after GoodCheck finishes --- CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs | 1 - CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs | 6 +++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs b/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs index 29791856..b6cc7437 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs @@ -191,7 +191,6 @@ private static async Task HandleGoodCheckMessage(GoodCheckMessageModel model) return; await GoodCheckProcessHelper.Instance.StartAsync(executable, arguments, taskId); - TasksHelper.Instance.ApplyStatusToAllTasks(false); return; } diff --git a/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs b/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs index 3473cd94..52963179 100644 --- a/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs +++ b/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs @@ -50,7 +50,7 @@ public async Task StartAsync(string executable, string args, string operat _cancellationTokenSource = new(); _cancellationToken = _cancellationTokenSource.Token; await PipeHelper.SendGoodCheckPacket(Shared.Pipe.Models.GoodCheckMessageIds.Runned, operationId); - TasksHelper.Instance.ApplyStatusToAllTasks(true); + TasksHelper.Instance.ApplyStatusToAllTasks(false); var startInfo = new ProcessStartInfo @@ -72,6 +72,7 @@ public async Task StartAsync(string executable, string args, string operat if (!Process.Start()) { HandleProcessException("ERR_UNABLE_START_PROCESS", operationId); + TasksHelper.Instance.ApplyStatusToAllTasks(true); return false; } } @@ -79,13 +80,16 @@ public async Task StartAsync(string executable, string args, string operat { Logger.Instance.CreateErrorLog(nameof(GoodCheckProcessHelper), $"ERR_UNABLE_START_PROCESS details => {ex.Message}"); HandleProcessException("ERR_UNABLE_START_PROCESS", operationId); + TasksHelper.Instance.ApplyStatusToAllTasks(true); return false; } if (!AssignProcessToJobObject(Job, Process.Handle)) { + TryKillProcess(Process); HandleProcessException("ERR_WIN32_EXCEPTION", operationId); Logger.Instance.CreateErrorLog(nameof(GoodCheckProcessHelper), $"ERR_WIN32_EXCEPTION details => {Marshal.GetLastWin32Error()}"); + TasksHelper.Instance.ApplyStatusToAllTasks(true); return false; } From d20683088c29417d409efa0276193cf9599ca206 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:45:54 +0000 Subject: [PATCH 012/202] Validate archive entry paths before extraction Entries that resolve outside of the target directory now fail extraction. A missing root folder argument no longer throws. --- .../Repository/RepositoryLoaderService.cs | 3 +- CDPIUI.Core/System/ArchivePaths.cs | 33 ++++++++++++ CDPIUI.Core/System/ZipService.cs | 4 +- CDPIUI.Tests/Core/ArchivePathsTests.cs | 51 +++++++++++++++++++ 4 files changed, 88 insertions(+), 3 deletions(-) create mode 100644 CDPIUI.Core/System/ArchivePaths.cs create mode 100644 CDPIUI.Tests/Core/ArchivePathsTests.cs diff --git a/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs b/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs index 865a1c44..054e9414 100644 --- a/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs +++ b/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs @@ -10,6 +10,7 @@ using CDPIUI.Shared.Secrets; using System.Diagnostics; using System.IO.Compression; +using CDPIUI.Core.System; namespace CDPIUI.Core.Store.Repository { @@ -121,7 +122,7 @@ await requestWorker.DownloadFileAsync(zipUrl, tempZipPath, string[] subParts = parts.Skip(1).ToArray(); string relativePath = Path.Combine(subParts); - string destinationPath = Path.Combine(targetFolder, relativePath); + string destinationPath = ArchivePaths.GetDestinationOrThrow(targetFolder, relativePath); string destDir = Path.GetDirectoryName(destinationPath); if (!string.IsNullOrEmpty(destDir)) diff --git a/CDPIUI.Core/System/ArchivePaths.cs b/CDPIUI.Core/System/ArchivePaths.cs new file mode 100644 index 00000000..9e0014cc --- /dev/null +++ b/CDPIUI.Core/System/ArchivePaths.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; + +namespace CDPIUI.Core.System +{ + public static class ArchivePaths + { + public static bool TryGetDestination(string root, string relativePath, out string destination) + { + destination = string.Empty; + if (string.IsNullOrEmpty(relativePath) || Path.IsPathRooted(relativePath) || relativePath.Contains(':')) + return false; + + string fullRoot = Path.GetFullPath(root); + if (!fullRoot.EndsWith(Path.DirectorySeparatorChar)) + fullRoot += Path.DirectorySeparatorChar; + + string fullPath = Path.GetFullPath(Path.Combine(fullRoot, relativePath)); + if (!fullPath.StartsWith(fullRoot, StringComparison.OrdinalIgnoreCase)) + return false; + + destination = fullPath; + return true; + } + + public static string GetDestinationOrThrow(string root, string relativePath) + { + if (!TryGetDestination(root, relativePath, out string destination)) + throw new InvalidDataException($"Archive entry \"{relativePath}\" points outside of the target directory."); + return destination; + } + } +} diff --git a/CDPIUI.Core/System/ZipService.cs b/CDPIUI.Core/System/ZipService.cs index 4b970fb7..ce3f2f41 100644 --- a/CDPIUI.Core/System/ZipService.cs +++ b/CDPIUI.Core/System/ZipService.cs @@ -30,7 +30,7 @@ public static async Task ExtractZip( int totalFiles = entries.Count; int extractedFiles = 0; - if (zipFolderToUnpack == "/") + if (zipFolderToUnpack == null || zipFolderToUnpack == "/") zipFolderToUnpack = string.Empty; else if (zipFolderToUnpack.EndsWith("/")) zipFolderToUnpack = zipFolderToUnpack.TrimEnd('/'); @@ -85,7 +85,7 @@ public static async Task ExtractZip( if (filesToSkip.Any(skip => relativePath.Contains(skip))) continue; - var destinationPath = Path.Combine(extractTo, relativePath); + var destinationPath = ArchivePaths.GetDestinationOrThrow(extractTo, relativePath); var destinationDir = Path.GetDirectoryName(destinationPath); if (!Directory.Exists(destinationDir) && !string.IsNullOrEmpty(destinationDir)) Directory.CreateDirectory(destinationDir); diff --git a/CDPIUI.Tests/Core/ArchivePathsTests.cs b/CDPIUI.Tests/Core/ArchivePathsTests.cs new file mode 100644 index 00000000..b983a381 --- /dev/null +++ b/CDPIUI.Tests/Core/ArchivePathsTests.cs @@ -0,0 +1,51 @@ +using CDPIUI.Core.System; + +namespace CDPIUI.Tests.Core; + +public class ArchivePathsTests +{ + private static readonly string Root = Path.Combine(Path.GetTempPath(), "cdpiui-archive-root"); + + [Theory] + [InlineData("file.txt")] + [InlineData("lists/hosts.txt")] + [InlineData("a/./b/c.bin")] + [InlineData("a/../b.txt")] + public void AcceptsPathsInsideRoot(string relative) + { + Assert.True(ArchivePaths.TryGetDestination(Root, relative, out string destination)); + Assert.StartsWith(Path.GetFullPath(Root), destination); + } + + [Theory] + [InlineData("../evil.txt")] + [InlineData("a/../../evil.txt")] + [InlineData("/etc/evil")] + [InlineData("C:/evil.txt")] + [InlineData("C:evil.txt")] + [InlineData("")] + public void RejectsPathsOutsideRoot(string relative) + { + Assert.False(ArchivePaths.TryGetDestination(Root, relative, out _)); + } + + [Fact] + public void RejectsSiblingDirectoryWithSamePrefix() + { + Assert.False(ArchivePaths.TryGetDestination(Root, "../cdpiui-archive-root2/x.txt", out _)); + } + + [Fact] + public void RootWithTrailingSeparatorBehavesTheSame() + { + Assert.True(ArchivePaths.TryGetDestination(Root + Path.DirectorySeparatorChar, "x.txt", out string a)); + Assert.True(ArchivePaths.TryGetDestination(Root, "x.txt", out string b)); + Assert.Equal(a, b); + } + + [Fact] + public void GetDestinationOrThrowThrowsInvalidData() + { + Assert.Throws(() => ArchivePaths.GetDestinationOrThrow(Root, "../x")); + } +} From 8bf30e79c0280c7593b260f6eac34d276dcf4f41 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:45:54 +0000 Subject: [PATCH 013/202] Validate update package entry paths before applying --- Update/InstallHelper.cs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Update/InstallHelper.cs b/Update/InstallHelper.cs index 1b3f44f4..66275829 100644 --- a/Update/InstallHelper.cs +++ b/Update/InstallHelper.cs @@ -209,6 +209,17 @@ private async Task ExtractZipAsync() return false; } + foreach (var entry in relevantEntries) + { + var relativePath = entry.FullName.Replace('\\', '/').Substring(UiRootPrefix.Length); + if (!string.IsNullOrEmpty(relativePath) && !TryGetDestination(relativePath, out _)) + { + Log($"Archive entry '{entry.FullName}' points outside of the target folder. Update aborted."); + ProgressChanged?.Invoke(1.0); + return false; + } + } + foreach (var entry in relevantEntries) { var entryName = entry.FullName.Replace('\\', '/'); @@ -216,7 +227,8 @@ private async Task ExtractZipAsync() if (string.IsNullOrEmpty(relativePath)) continue; - string destPath = Path.Combine(_targetFolder, relativePath); + string destPath; + TryGetDestination(relativePath, out destPath); string destDir = Path.GetDirectoryName(destPath); var fileName = Path.GetFileName(relativePath); @@ -383,6 +395,24 @@ private bool LaunchApplication(bool error = false) } } + private bool TryGetDestination(string relativePath, out string destination) + { + destination = null; + if (Path.IsPathRooted(relativePath) || relativePath.IndexOf(':') >= 0) + return false; + + string fullRoot = Path.GetFullPath(_targetFolder); + if (!fullRoot.EndsWith(Path.DirectorySeparatorChar.ToString())) + fullRoot += Path.DirectorySeparatorChar; + + string fullPath = Path.GetFullPath(Path.Combine(fullRoot, relativePath)); + if (!fullPath.StartsWith(fullRoot, StringComparison.OrdinalIgnoreCase)) + return false; + + destination = fullPath; + return true; + } + private void Log(string text) { try From 04da03cd4909778a8ef15c2ded27bfcc2ea4a433 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:46:53 +0000 Subject: [PATCH 014/202] Escape pipe message values Characters such as + & # % were altered by query string parsing, which corrupted component arguments and file paths. --- .../Pipe/Models/PipeMessageModels.cs | 5 ++- CDPIUI.Tests/Shared/PipeMessageModelTests.cs | 41 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 CDPIUI.Tests/Shared/PipeMessageModelTests.cs diff --git a/CDPIUI.Shared/Pipe/Models/PipeMessageModels.cs b/CDPIUI.Shared/Pipe/Models/PipeMessageModels.cs index a9879d1b..600d3b44 100644 --- a/CDPIUI.Shared/Pipe/Models/PipeMessageModels.cs +++ b/CDPIUI.Shared/Pipe/Models/PipeMessageModels.cs @@ -24,7 +24,10 @@ public override string ToString() foreach (var name in MessageData.AllKeys) { - @params += $"{name}={MessageData[name]}&"; + if (name == null) + continue; + + @params += $"{Uri.EscapeDataString(name)}={Uri.EscapeDataString(MessageData[name] ?? string.Empty)}&"; } return $"{SharedConstants.Schema}://{Target}/{MessageType}?{@params}"; diff --git a/CDPIUI.Tests/Shared/PipeMessageModelTests.cs b/CDPIUI.Tests/Shared/PipeMessageModelTests.cs new file mode 100644 index 00000000..bf931ed1 --- /dev/null +++ b/CDPIUI.Tests/Shared/PipeMessageModelTests.cs @@ -0,0 +1,41 @@ +using System.Collections.Specialized; +using CDPIUI.Shared.Pipe.Models; + +namespace CDPIUI.Tests.Shared; + +public class PipeMessageModelTests +{ + [Theory] + [InlineData("--dpi-desync-repeats=6 --dpi-desync-fooling=badseq --dup=+1:3-64")] + [InlineData("C:\\Tom & Jerry\\list #1.txt")] + [InlineData("100% = a+b")] + [InlineData("Список сайтов.txt")] + [InlineData("")] + public void ValuesSurviveRoundTrip(string value) + { + var model = new CONPTYMessageModel + { + MessageType = CONPTYMessageIds.StartProcessId, + MessageData = new NameValueCollection + { + { "componentId", "CSZTBN012" }, + { "args", value }, + }, + }; + + var parsed = PipeModelConvertor.ConvertBack(model.ToString()) as CONPTYMessageModel; + + Assert.NotNull(parsed); + Assert.Equal(CONPTYMessageIds.StartProcessId, parsed!.MessageType); + Assert.Equal("CSZTBN012", parsed.MessageData?["componentId"]); + Assert.Equal(value, parsed.MessageData?["args"]); + } + + [Fact] + public void MessageWithoutDataHasNoQuery() + { + var model = new CONPTYMessageModel { MessageType = CONPTYMessageIds.StartProcessId }; + + Assert.DoesNotContain("?", model.ToString()); + } +} From 67abc7f96e8b990dce132049c330f10b79847012 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:48:14 +0000 Subject: [PATCH 015/202] Prevent duplicate tasks for the same component Lookup and insertion now happen under one lock, and bulk operations enumerate a snapshot of the task list. --- .../ComponentsTask/TasksManageService.cs | 175 ++++++------------ .../Shared/TasksManageServiceTests.cs | 78 ++++++++ 2 files changed, 135 insertions(+), 118 deletions(-) create mode 100644 CDPIUI.Tests/Shared/TasksManageServiceTests.cs diff --git a/CDPIUI.Shared/ComponentsTask/TasksManageService.cs b/CDPIUI.Shared/ComponentsTask/TasksManageService.cs index 15a80627..35912791 100644 --- a/CDPIUI.Shared/ComponentsTask/TasksManageService.cs +++ b/CDPIUI.Shared/ComponentsTask/TasksManageService.cs @@ -67,32 +67,38 @@ public TasksManageService() { } return null; } - /// - /// Add new task to task list - /// - /// Task Id - public async void AddNewTask(string id) + private async Task<(TaskModel Task, bool Created)> GetOrAddTask(string id, bool? isSetupComplete = null) { - var t = await GetTaskFromId(id); - if (t != null) return; - await _taskOperationLock.WaitAsync(); - - var processManager = new T() { Id = id }; - processManager.ProcessStateChanged += HandleProcessStateUpdate; - processManager.ShowErrorMessageWindow += HandleShowErrorMessageWindow; - try { - Tasks.Add(new() { Id = id, ProcessManager = processManager }); + var existTask = Tasks.FirstOrDefault(t => t.Id == id); + if (existTask != null) + return (existTask, false); + + T processManager = new() { Id = id }; + processManager.ProcessStateChanged += HandleProcessStateUpdate; + processManager.ShowErrorMessageWindow += HandleShowErrorMessageWindow; + + var task = new TaskModel { Id = id, ProcessManager = processManager, IsSetupComplete = isSetupComplete }; + Tasks.Add(task); + return (task, true); } - catch { } finally { _taskOperationLock.Release(); } + } - TaskListUpdated?.Invoke(); + /// + /// Add new task to task list + /// + /// Task Id + public async void AddNewTask(string id) + { + var (_, created) = await GetOrAddTask(id); + if (created) + TaskListUpdated?.Invoke(); } /// @@ -101,31 +107,13 @@ public async void AddNewTask(string id) /// Task Id public async Task CreateAndRunNewTask(string id) { - var t = await GetTaskFromId(id); - if (t != null) - { - await StopTask(id); - await t.ProcessManager.StartProcess(); - } + var (task, created) = await GetOrAddTask(id); + if (created) + TaskListUpdated?.Invoke(); else - { - T processManager = new() { Id = id }; - processManager.ProcessStateChanged += HandleProcessStateUpdate; - processManager.ShowErrorMessageWindow += HandleShowErrorMessageWindow; - await processManager.StartProcess(); + await task.ProcessManager.StopProcess(); - await _taskOperationLock.WaitAsync(); - try - { - Tasks.Add(new() { Id = id, ProcessManager = processManager }); - } - catch { } - finally - { - _taskOperationLock.Release(); - } - TaskListUpdated?.Invoke(); - } + await task.ProcessManager.StartProcess(); } /// /// Add new task to task list, run associated with custom executable @@ -135,32 +123,13 @@ public async Task CreateAndRunNewTask(string id) /// Command-line flags public virtual async Task CreateAndRunNewTask(string id, string executable, string args) { - var t = await GetTaskFromId(id); - if (t != null) - { - await StopTask(id); - await t.ProcessManager.StartProcess(executable, args); - } + var (task, created) = await GetOrAddTask(id); + if (created) + TaskListUpdated?.Invoke(); else - { - await _taskOperationLock.WaitAsync(); - - T processManager = new() { Id = id }; - processManager.ProcessStateChanged += HandleProcessStateUpdate; - processManager.ShowErrorMessageWindow += HandleShowErrorMessageWindow; - await processManager.StartProcess(executable, args); + await task.ProcessManager.StopProcess(); - try - { - Tasks.Add(new() { Id = id, ProcessManager = processManager }); - } - catch { } - finally - { - _taskOperationLock.Release(); - } - TaskListUpdated?.Invoke(); - } + await task.ProcessManager.StartProcess(executable, args); } /// @@ -170,32 +139,13 @@ public virtual async Task CreateAndRunNewTask(string id, string executable, stri /// Command-line flags public async Task CreateAndRunNewTask(string id, string args) { - var t = await GetTaskFromId(id); - if (t != null) - { - await StopTask(id); - await t.ProcessManager.StartProcess(args, null); - } + var (task, created) = await GetOrAddTask(id); + if (created) + TaskListUpdated?.Invoke(); else - { - await _taskOperationLock.WaitAsync(); - - T processManager = new() { Id = id }; - processManager.ProcessStateChanged += HandleProcessStateUpdate; - processManager.ShowErrorMessageWindow += HandleShowErrorMessageWindow; - await processManager.StartProcess(args, null); + await task.ProcessManager.StopProcess(); - try - { - Tasks.Add(new() { Id = id, ProcessManager = processManager }); - } - catch { } - finally - { - _taskOperationLock.Release(); - } - TaskListUpdated?.Invoke(); - } + await task.ProcessManager.StartProcess(args, null); } /// @@ -205,31 +155,11 @@ public async Task CreateAndRunNewTask(string id, string args) /// Is task with Id ready to run public async void SetTaskStatus(string id, bool isSetupComplete) { - var targetTask = await GetTaskFromId(id); - if (targetTask != null) - { - targetTask.IsSetupComplete = isSetupComplete; - } - else - { - await _taskOperationLock.WaitAsync(); - - T processManager = new() { Id = id }; - processManager.ProcessStateChanged += HandleProcessStateUpdate; - processManager.ShowErrorMessageWindow += HandleShowErrorMessageWindow; - - try - { - Tasks.Add(new() { Id = id, ProcessManager = processManager, IsSetupComplete = isSetupComplete }); - } - catch { } - finally - { - _taskOperationLock.Release(); - } - + var (targetTask, created) = await GetOrAddTask(id, isSetupComplete); + if (created) TaskListUpdated?.Invoke(); - } + else + targetTask.IsSetupComplete = isSetupComplete; TaskSetupStateUpdated?.Invoke(Tuple.Create(id, isSetupComplete)); } @@ -240,13 +170,11 @@ public async void SetTaskStatus(string id, bool isSetupComplete) /// Target status public async void ApplyStatusToAllTasks(bool status) { - foreach (var task in Tasks) + foreach (var task in await GetTasksSnapshot()) { task.IsSetupComplete = status; TaskSetupStateUpdated?.Invoke(Tuple.Create(task.Id, status)); } - - await Task.CompletedTask; } /// @@ -309,15 +237,26 @@ public async Task RestartTask(string id) /// public async Task StopAllTasks() { - await _taskOperationLock.WaitAsync(); - try + foreach (var task in await GetTasksSnapshot()) { - foreach (var task in Tasks) + try { await task.ProcessManager.StopProcess(); } + catch { } + } + } + + /// + /// Get a copy of the tasks list that is safe to enumerate while tasks are added or removed + /// + public async Task>> GetTasksSnapshot() + { + await _taskOperationLock.WaitAsync(); + try + { + return [.. Tasks]; } - catch { } finally { _taskOperationLock.Release(); diff --git a/CDPIUI.Tests/Shared/TasksManageServiceTests.cs b/CDPIUI.Tests/Shared/TasksManageServiceTests.cs new file mode 100644 index 00000000..62fc9c97 --- /dev/null +++ b/CDPIUI.Tests/Shared/TasksManageServiceTests.cs @@ -0,0 +1,78 @@ +using CDPIUI.Shared.ComponentsTask; +using CDPIUI.Shared.PrettyErrorConvertionService; + +namespace CDPIUI.Tests.Shared; + +public class TasksManageServiceTests +{ + private sealed class FakeProcess : IProcessService + { + public string Id { get; set; } = string.Empty; + public string ProcessName => Id; + public bool IsProcessRunning { get; private set; } + public bool IsErrorHappens => false; + public ErrorModel? LastError => null; + public int StartCount { get; private set; } + +#pragma warning disable CS0067 + public event Action>? ProcessStateChanged; + public event Action? ErrorHappens; + public event Action? OutputReceived; + public event Action? ProcessNameChanged; + public event Action? ShowErrorMessageWindow; +#pragma warning restore CS0067 + + public async Task StartProcess() + { + StartCount++; + await Task.Delay(5); + IsProcessRunning = true; + } + + public Task StartProcess(string stringParameter1, string? stringParameter2) => StartProcess(); + + public Task StopProcess(bool boolParameter = true) + { + IsProcessRunning = false; + return Task.CompletedTask; + } + + public Task RestartProcess() => StartProcess(); + } + + [Fact] + public async Task ConcurrentCreationKeepsSingleTaskPerId() + { + var service = new TasksManageService(); + + await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => service.CreateAndRunNewTask("component"))); + + var tasks = await service.GetTasksSnapshot(); + Assert.Single(tasks); + Assert.True(tasks[0].ProcessManager.IsProcessRunning); + } + + [Fact] + public async Task StopAllTasksStopsEveryTask() + { + var service = new TasksManageService(); + await service.CreateAndRunNewTask("a"); + await service.CreateAndRunNewTask("b"); + + await service.StopAllTasks(); + + Assert.All(await service.GetTasksSnapshot(), task => Assert.False(task.ProcessManager.IsProcessRunning)); + } + + [Fact] + public async Task ExistingTaskIsReusedOnRestart() + { + var service = new TasksManageService(); + await service.CreateAndRunNewTask("a"); + await service.CreateAndRunNewTask("a"); + + var tasks = await service.GetTasksSnapshot(); + Assert.Single(tasks); + Assert.Equal(2, tasks[0].ProcessManager.StartCount); + } +} From b5cbbf593eb5f5ce2c41f155249a5b9f04fafe3f Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:48:56 +0000 Subject: [PATCH 016/202] Rebuild tray component list in a single UI pass Overlapping updates could interleave clear and add operations and show duplicate rows. --- CDPIUI.TrayIcon/Forms/TrayMenuForm.cs | 53 ++++++++++++++++----------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/CDPIUI.TrayIcon/Forms/TrayMenuForm.cs b/CDPIUI.TrayIcon/Forms/TrayMenuForm.cs index 05bfc6f7..80d5a1eb 100644 --- a/CDPIUI.TrayIcon/Forms/TrayMenuForm.cs +++ b/CDPIUI.TrayIcon/Forms/TrayMenuForm.cs @@ -1,4 +1,5 @@ -using CDPIUI.Shared.Pipe.Models; +using CDPIUI.Shared.ComponentsTask; +using CDPIUI.Shared.Pipe.Models; using CDPIUI.TrayIcon.Controls; using CDPIUI.TrayIcon.Helper; using CDPIUI.TrayIcon.Helper.Basic; @@ -85,7 +86,7 @@ private void DisconnectHandlers() private void DisconnectComponentPanelChildrensHandlers() { - foreach (Control control in ComponentPanel.Controls) + foreach (Control control in ComponentPanel.Controls.Cast().ToList()) { if (control is ComponentUserControl componentUserControl) { @@ -134,18 +135,29 @@ private void HandleEventHappens() private void HandleTasksListUpdate() { + if (IsDisposed || !IsHandleCreated) + return; + + List> tasks; + try + { + tasks = TasksHelper.Instance.Tasks.ToList().DistinctBy(task => task.Id).ToList(); + } + catch (InvalidOperationException) + { + return; + } + this.Invoke(() => { + ComponentPanel.SuspendLayout(); DisconnectComponentPanelChildrensHandlers(); ComponentPanel.Controls.Clear(); - }); - int targetWidth = ComponentPanel.Width; - int offset = 0; + int targetWidth = ComponentPanel.Width; + int offset = 0; - if (TasksHelper.Instance.Tasks.Count == 0) - { - this.Invoke(() => + if (tasks.Count == 0) { var storeButton = new ModernButtonUserControl() { @@ -158,14 +170,10 @@ private void HandleTasksListUpdate() storeButton.Clicked += HandleButtonClick; ComponentPanel.Controls.Add(storeButton); storeButton.Invalidate(); - }); - - } - else - { - foreach (var task in TasksHelper.Instance.Tasks) + } + else { - this.Invoke(() => + foreach (var task in tasks) { var control = new ComponentUserControl() { @@ -180,18 +188,15 @@ private void HandleTasksListUpdate() Top = offset }; - - control.EventHappens += HandleEventHappens; ComponentPanel.Controls.Add(control); control.Invalidate(); offset += control.Height + control.Margin.Top + control.Margin.Bottom; - }); + } } - } - this.Invoke(() => - { + + ComponentPanel.ResumeLayout(); CheckWindowHeight(); ComponentPanel.Invalidate(); }); @@ -199,6 +204,9 @@ private void HandleTasksListUpdate() private async void HandleTaskStateUpdate(Tuple taskStateUpdate) { + if (IsDisposed || !IsHandleCreated) + return; + this.Invoke(() => { Control[] controls = ComponentPanel.Controls.Find(taskStateUpdate.Item1, false); @@ -220,6 +228,9 @@ private async void HandleTaskStateUpdate(Tuple taskStateUpdate) private async void HandleTaskSetupStateUpdate(Tuple taskStateUpdate) { + if (IsDisposed || !IsHandleCreated) + return; + this.Invoke(() => { Control[] controls = ComponentPanel.Controls.Find(taskStateUpdate.Item1, false); From d71de5854dfda126167a974908a0de66d928ba79 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:51:23 +0000 Subject: [PATCH 017/202] Make settings persistence culture-independent and retry busy writes A sharing violation while the other process read Settings.xml disabled saving for the rest of the session. Numbers and dates are now written in invariant format and values written in the current culture by older versions are still read. Missing keys in nested groups use template defaults. --- CDPIUI.Shared/Basic/XMLSettingsService.cs | 186 +++++++++++------- .../Shared/XmlSettingsServiceTests.cs | 59 ++++++ 2 files changed, 176 insertions(+), 69 deletions(-) create mode 100644 CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs diff --git a/CDPIUI.Shared/Basic/XMLSettingsService.cs b/CDPIUI.Shared/Basic/XMLSettingsService.cs index 52117d1e..1ba79f95 100644 --- a/CDPIUI.Shared/Basic/XMLSettingsService.cs +++ b/CDPIUI.Shared/Basic/XMLSettingsService.cs @@ -2,8 +2,10 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; +using System.Threading; using System.Xml.Linq; using System.Xml; @@ -98,6 +100,9 @@ private static XDocument LoadDocument(string path) return document; } + private const int SaveAttempts = 5; + private const int SaveRetryDelayMs = 50; + private void SaveSettings(bool keepBackup = true) { if (_persistenceUnavailable) return; @@ -106,16 +111,33 @@ private void SaveSettings(bool keepBackup = true) { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(SettingsFilePath))!); _xDocument!.Save(temporaryPath); - if (File.Exists(SettingsFilePath)) - File.Replace(temporaryPath, SettingsFilePath, keepBackup ? SettingsFilePath + ".bak" : null); - else - File.Move(temporaryPath, SettingsFilePath); + + for (int attempt = 1; ; attempt++) + { + try + { + if (File.Exists(SettingsFilePath)) + File.Replace(temporaryPath, SettingsFilePath, keepBackup ? SettingsFilePath + ".bak" : null); + else + File.Move(temporaryPath, SettingsFilePath); + break; + } + catch (IOException) when (attempt < SaveAttempts) + { + // The other process (GUI or tray) may be reading the file at this moment. + Thread.Sleep(SaveRetryDelayMs * attempt); + } + } } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + catch (UnauthorizedAccessException ex) { _persistenceUnavailable = true; Debug.WriteLine(ex); } + catch (IOException ex) + { + Debug.WriteLine(ex); + } finally { try { File.Delete(temporaryPath); } @@ -231,7 +253,7 @@ private void SaveSettings(bool keepBackup = true) if (settingElement == null) { if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); - var defaultValue = GetDefaultValue(); + var defaultValue = GetDefaultValueForKey(groupPath, key); SetValue(groupPath, key, defaultValue); Debug.WriteLine($"Setting '{key}' in group path '{string.Join("/", groupPath)}' not found."); return defaultValue; @@ -310,10 +332,10 @@ public void SetValue(string group, string key, T value) type = "int"; valueString = value.ToString(); } - else if (value is double) + else if (value is double d) { type = "double"; - valueString = value.ToString(); + valueString = FormatDouble(d); } else if (value is bool) { @@ -325,10 +347,10 @@ public void SetValue(string group, string key, T value) type = "string"; valueString = value as string; } - else if (value is DateTime) + else if (value is DateTime dateTime) { type = nameof(DateTime); - valueString = value.ToString(); + valueString = FormatDateTime(dateTime); } else if (typeof(T) == typeof(List)) { @@ -339,38 +361,41 @@ public void SetValue(string group, string key, T value) } else { - type = nameof(T); - valueString = value.ToString(); + type = typeof(T).Name; + valueString = value?.ToString() ?? string.Empty; } - var groupElement = _xDocument.Root - .Elements("Group") - .FirstOrDefault(g => g.Attribute("Name")?.Value == group); - - if (groupElement == null) + lock (_reloadLock) { - groupElement = new XElement("Group", new XAttribute("Name", group)); - _xDocument.Root.Add(groupElement); - } + var groupElement = _xDocument.Root + .Elements("Group") + .FirstOrDefault(g => g.Attribute("Name")?.Value == group); - var settingElement = groupElement - .Elements("Setting") - .FirstOrDefault(s => s.Attribute("Key")?.Value == key); + if (groupElement == null) + { + groupElement = new XElement("Group", new XAttribute("Name", group)); + _xDocument.Root.Add(groupElement); + } - if (settingElement != null) - { - settingElement.SetAttributeValue("Value", valueString); - settingElement.SetAttributeValue("Type", type); - } - else - { - groupElement.Add(new XElement("Setting", - new XAttribute("Key", key), - new XAttribute("Type", type), - new XAttribute("Value", valueString))); - } + var settingElement = groupElement + .Elements("Setting") + .FirstOrDefault(s => s.Attribute("Key")?.Value == key); + + if (settingElement != null) + { + settingElement.SetAttributeValue("Value", valueString); + settingElement.SetAttributeValue("Type", type); + } + else + { + groupElement.Add(new XElement("Setting", + new XAttribute("Key", key), + new XAttribute("Type", type), + new XAttribute("Value", valueString))); + } - SaveSettings(); + SaveSettings(); + } PropertyChanged?.Invoke(group); } @@ -394,7 +419,7 @@ public void SetValue(IEnumerable groupPath, string key, T value) break; case double d: type = "double"; - valueString = d.ToString(); + valueString = FormatDouble(d); break; case bool b: type = "bool"; @@ -408,64 +433,87 @@ public void SetValue(IEnumerable groupPath, string key, T value) type = nameof(List); valueString = string.Join(";", lst); break; + case DateTime dateTime: + type = nameof(DateTime); + valueString = FormatDateTime(dateTime); + break; default: - type = nameof(T); - valueString = value.ToString(); + type = typeof(T).Name; + valueString = value?.ToString() ?? string.Empty; break; } - XElement current = _xDocument.Root; - foreach (var grp in groupPath) + lock (_reloadLock) { - var next = current - .Elements("Group") - .FirstOrDefault(g => (string)g.Attribute("Name") == grp); - - if (next == null) + XElement current = _xDocument.Root; + foreach (var grp in groupPath) { - next = new XElement("Group", new XAttribute("Name", grp)); - current.Add(next); + var next = current + .Elements("Group") + .FirstOrDefault(g => (string)g.Attribute("Name") == grp); + + if (next == null) + { + next = new XElement("Group", new XAttribute("Name", grp)); + current.Add(next); + } + + current = next; } - current = next; - } + var setting = current + .Elements("Setting") + .FirstOrDefault(s => (string)s.Attribute("Key") == key); - var setting = current - .Elements("Setting") - .FirstOrDefault(s => (string)s.Attribute("Key") == key); + if (setting != null) + { + setting.SetAttributeValue("Type", type); + setting.SetAttributeValue("Value", valueString); + } + else + { + current.Add(new XElement("Setting", + new XAttribute("Key", key), + new XAttribute("Type", type), + new XAttribute("Value", valueString))); + } - if (setting != null) - { - setting.SetAttributeValue("Type", type); - setting.SetAttributeValue("Value", valueString); + SaveSettings(); } - else - { - current.Add(new XElement("Setting", - new XAttribute("Key", key), - new XAttribute("Type", type), - new XAttribute("Value", valueString))); - } - - SaveSettings(); EnumPropertyChanged?.Invoke(groupPath); } private static T? GetValueFromString(string? value, string? type) { if (typeof(T) == typeof(int) && type == "int" && int.TryParse(value, out var iv)) return (T)(object)iv; - if (typeof(T) == typeof(double) && type == "double" && double.TryParse(value, out var dv)) return (T)(object)dv; + if (typeof(T) == typeof(double) && type == "double" && TryParseDouble(value, out var dv)) return (T)(object)dv; if (typeof(T) == typeof(bool) && type == "bool" && bool.TryParse(value, out var bv)) return (T)(object)bv; if (typeof(T) == typeof(string) && type == "string") return (T)(object)value; if (typeof(T) == typeof(List) && type == nameof(List)) return string.IsNullOrEmpty(value) ? (T)(object)new List() : (T)(object)value.Split(';').ToList(); - if (typeof(T) == typeof(DateTime) && type == nameof(DateTime)) - return (T)(object)DateTime.Parse((string)value); + if (typeof(T) == typeof(DateTime) && type == nameof(DateTime) && TryParseDateTime(value, out var dtv)) + return (T)(object)dtv; throw new Exception(); } + public static string FormatDouble(double value) => + value.ToString("R", CultureInfo.InvariantCulture); + + public static string FormatDateTime(DateTime value) => + value.ToString("o", CultureInfo.InvariantCulture); + + // Values written by older versions used the current culture, so it is tried after the invariant form. + public static bool TryParseDouble(string? value, out double result) => + double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result) + || double.TryParse(value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out result); + + public static bool TryParseDateTime(string? value, out DateTime result) => + DateTime.TryParseExact(value, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out result) + || DateTime.TryParse(value, CultureInfo.CurrentCulture, DateTimeStyles.None, out result) + || DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out result); + protected virtual T? GetDefaultValueForKey(string group, string key) { return GetDefaultValue(); diff --git a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs new file mode 100644 index 00000000..43f723fc --- /dev/null +++ b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs @@ -0,0 +1,59 @@ +using System.Globalization; +using CDPIUI.Shared.Basic; + +namespace CDPIUI.Tests.Shared; + +public class XmlSettingsServiceTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "cdpiui-settings-" + Guid.NewGuid().ToString("N")); + private readonly CultureInfo _culture = CultureInfo.CurrentCulture; + + private string SettingsPath => Path.Combine(_directory, "Settings.xml"); + + public void Dispose() + { + CultureInfo.CurrentCulture = _culture; + if (Directory.Exists(_directory)) + Directory.Delete(_directory, true); + } + + [Fact] + public void DoubleRoundTripsAcrossCultures() + { + CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); + new XMLSettingsService(SettingsPath).SetValue("PSEUDOCONSOLE", "fontSize", 12.5); + + CultureInfo.CurrentCulture = new CultureInfo("en-US"); + Assert.Equal(12.5, new XMLSettingsService(SettingsPath).GetValue("PSEUDOCONSOLE", "fontSize")); + } + + [Fact] + public void DateTimeRoundTripsAcrossCultures() + { + var value = new DateTime(2026, 5, 10, 13, 45, 0, DateTimeKind.Utc); + + CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); + new XMLSettingsService(SettingsPath).SetValue("STORE", "lastSyncTime", value); + + CultureInfo.CurrentCulture = new CultureInfo("en-US"); + Assert.Equal(value, new XMLSettingsService(SettingsPath).GetValue("STORE", "lastSyncTime")); + } + + [Fact] + public void ReadsDoubleWrittenInCurrentCultureByOlderVersions() + { + CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); + Assert.True(XMLSettingsService.TryParseDouble("12,5", out double value)); + Assert.Equal(12.5, value); + } + + [Fact] + public void DateTimeWithGroupPathIsReadable() + { + var value = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc); + var settings = new XMLSettingsService(SettingsPath); + settings.SetValue(["ADDONS", "ASGKOI001"], "lastRun", value); + + Assert.Equal(value, new XMLSettingsService(SettingsPath).GetValue(["ADDONS", "ASGKOI001"], "lastRun")); + } +} From a6ababa0f5d66258f176704280beb807fa12dd42 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:52:24 +0000 Subject: [PATCH 018/202] Do not throw from tray error handlers Prefixed error code strings were parsed as enum names, which threw inside catch blocks and lost the original error. --- CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs | 4 ++-- CDPIUI.TrayIcon/Helper/Basic/ErrorHelper.cs | 6 ++++++ CDPIUI.TrayIcon/Helper/ProcessManager.cs | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs index e00a696d..86702e3c 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs @@ -340,7 +340,7 @@ public async void RunProcess(string exePath, string args, string workingDirector } catch (Exception ex) { - ShowErrorMessage(ErrorHelper.Convertor.GetPrettyErrorCode(nameof(ConPTYHelper), ex).ToEnum(), _object: "console"); + ShowErrorMessage(ErrorHelper.Convertor.GetLoggedErrorCode(nameof(ConPTYHelper), ex), _object: "console"); SendStopMessage("Unexpected error happens while trying to stop process"); processState = false; @@ -492,7 +492,7 @@ public async void RunProcessWithConPTY(string exePath, string args, string worki catch (Exception ex) { if (ex.Message != "External component has thrown an exception.") - ShowErrorMessage(ErrorHelper.Convertor.GetPrettyErrorCode(nameof(ConPTYHelper), ex).ToEnum(), _object: "console"); + ShowErrorMessage(ErrorHelper.Convertor.GetLoggedErrorCode(nameof(ConPTYHelper), ex), _object: "console"); } finally diff --git a/CDPIUI.TrayIcon/Helper/Basic/ErrorHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/ErrorHelper.cs index bd088462..14277719 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/ErrorHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/ErrorHelper.cs @@ -38,5 +38,11 @@ public override string GetPrettyErrorCode(string preffix, Exception ex, ILogger? { return base.GetPrettyErrorCode(preffix, ex, Logger.Instance); } + + public PrettyErrorCode GetLoggedErrorCode(string preffix, Exception ex) + { + GetPrettyErrorCode(preffix, ex); + return MapExceptionToCode(ex, out _); + } } } diff --git a/CDPIUI.TrayIcon/Helper/ProcessManager.cs b/CDPIUI.TrayIcon/Helper/ProcessManager.cs index 43525b63..5bc9673b 100644 --- a/CDPIUI.TrayIcon/Helper/ProcessManager.cs +++ b/CDPIUI.TrayIcon/Helper/ProcessManager.cs @@ -289,7 +289,7 @@ private void StartSystemProxy(string ip, string port) } catch (Exception ex) { - ShowErrorMessage(Tuple.Create(ErrorHelper.Convertor.GetPrettyErrorCode(nameof(ConPTYHelper), ex).ToEnum(), nameof(RegeditHelper))); + ShowErrorMessage(Tuple.Create(ErrorHelper.Convertor.GetLoggedErrorCode(nameof(RegeditHelper), ex), nameof(RegeditHelper))); Logger.Instance.CreateErrorLog(nameof(ProcessManager), $"{ex.Message}"); } } @@ -302,7 +302,7 @@ private void StopSystemProxy() } catch (Exception ex) { - ShowErrorMessage(Tuple.Create(ErrorHelper.Convertor.GetPrettyErrorCode(nameof(RegeditHelper), ex).ToEnum(), nameof(RegeditHelper))); + ShowErrorMessage(Tuple.Create(ErrorHelper.Convertor.GetLoggedErrorCode(nameof(RegeditHelper), ex), nameof(RegeditHelper))); Logger.Instance.CreateErrorLog(nameof(ProcessManager), $"{ex.Message}"); } } From fd625e082ac3e8034a08e68a942060231245dc65 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:53:09 +0000 Subject: [PATCH 019/202] Restore proxy configuration when a component is restarted --- CDPIUI.TrayIcon/Helper/ProcessManager.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/ProcessManager.cs b/CDPIUI.TrayIcon/Helper/ProcessManager.cs index 5bc9673b..842bb232 100644 --- a/CDPIUI.TrayIcon/Helper/ProcessManager.cs +++ b/CDPIUI.TrayIcon/Helper/ProcessManager.cs @@ -87,6 +87,7 @@ public async void StartProxy(string _proxyType, string ip, string port) _ip = ip; _port = port; proxyType = _proxyType; + useProxy = !string.IsNullOrEmpty(proxyType); Debug.WriteLine($"Proxy setup for {proxyType}, {ip}, {port}"); if (!string.IsNullOrEmpty(proxyType)) { @@ -113,11 +114,11 @@ public async Task StopProxy() public async Task StartProcess() { - if (useProxy) - StartProxy(proxyType, _ip, _port); - if (Executable != null && Args != null && !IsProcessInfoChanged) { + if (useProxy) + StartProxy(proxyType, _ip, _port); + await StartProcess(Executable, Args); } else From 40c4bade9ccedc89638dc90e46f17f74d0ca91c0 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:54:56 +0000 Subject: [PATCH 020/202] Restore the previous system proxy settings when the component stops Stopping a component only disabled the proxy and left the server value, which also replaced a proxy the user had configured before. --- CDPIUI.TrayIcon/Helper/Basic/RegeditHelper.cs | 53 +++++++++++++++---- CDPIUI.TrayIcon/Helper/ProcessManager.cs | 19 ++++++- 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/Basic/RegeditHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/RegeditHelper.cs index d4dec91b..85364513 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/RegeditHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/RegeditHelper.cs @@ -41,6 +41,49 @@ public static Dictionary ReadProxySettings() return result; } + public sealed record ProxySnapshot(int? ProxyEnable, string? ProxyServer, string? ProxyOverride); + + public static ProxySnapshot ReadProxySnapshot() + { + using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsKeyPath, writable: false); + return new ProxySnapshot( + key?.GetValue("ProxyEnable") as int?, + key?.GetValue("ProxyServer") as string, + key?.GetValue("ProxyOverride") as string); + } + + public static void RestoreProxySnapshot(ProxySnapshot snapshot) + { + using (var key = Registry.CurrentUser.CreateSubKey(InternetSettingsKeyPath)) + { + if (key == null) + throw new InvalidOperationException("ERR_REGISTRY_WRITE"); + + SetOrDelete(key, "ProxyServer", snapshot.ProxyServer); + SetOrDelete(key, "ProxyOverride", snapshot.ProxyOverride); + key.SetValue("ProxyEnable", snapshot.ProxyEnable ?? 0, RegistryValueKind.DWord); + } + + NotifySettingsChanged(); + } + + private static void SetOrDelete(RegistryKey key, string name, string? value) + { + if (value == null) + key.DeleteValue(name, throwOnMissingValue: false); + else + key.SetValue(name, value, RegistryValueKind.String); + } + + private static void NotifySettingsChanged() + { + if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0)) + throw new Win32Exception(Marshal.GetLastWin32Error(), "ERR_WININET_CALL"); + + if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0)) + throw new Win32Exception(Marshal.GetLastWin32Error(), "ERR_WININET_CALL"); + } + public static void SaveProxySettings(string proxyServer, string proxyOverride, int proxyEnable) { if (proxyEnable != 0 && proxyEnable != 1) @@ -60,15 +103,7 @@ public static void SaveProxySettings(string proxyServer, string proxyOverride, i key.SetValue("ProxyEnable", proxyEnable, RegistryValueKind.DWord); } - if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0)) - { - throw new Win32Exception(Marshal.GetLastWin32Error(), "ERR_WININET_CALL"); - } - - if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0)) - { - throw new Win32Exception(Marshal.GetLastWin32Error(), "ERR_WININET_CALL"); - } + NotifySettingsChanged(); } } } diff --git a/CDPIUI.TrayIcon/Helper/ProcessManager.cs b/CDPIUI.TrayIcon/Helper/ProcessManager.cs index 842bb232..a333b636 100644 --- a/CDPIUI.TrayIcon/Helper/ProcessManager.cs +++ b/CDPIUI.TrayIcon/Helper/ProcessManager.cs @@ -265,6 +265,10 @@ public void SendState() } } + // The system proxy is global, so the user's previous settings are kept once for all components. + private static readonly object SystemProxyLock = new(); + private static RegeditHelper.ProxySnapshot? _systemProxyBackup; + private void StartSystemProxy(string ip, string port) { string proxyServer = string.Empty; @@ -286,7 +290,11 @@ private void StartSystemProxy(string ip, string port) } try { - RegeditHelper.SaveProxySettings(proxyServer, string.Empty, 1); + lock (SystemProxyLock) + { + _systemProxyBackup ??= RegeditHelper.ReadProxySnapshot(); + RegeditHelper.SaveProxySettings(proxyServer, string.Empty, 1); + } } catch (Exception ex) { @@ -299,7 +307,14 @@ private void StopSystemProxy() { try { - RegeditHelper.SaveProxySettings(string.Empty, string.Empty, 0); + lock (SystemProxyLock) + { + if (_systemProxyBackup != null) + RegeditHelper.RestoreProxySnapshot(_systemProxyBackup); + else + RegeditHelper.SaveProxySettings(string.Empty, string.Empty, 0); + _systemProxyBackup = null; + } } catch (Exception ex) { From 6815d95ee507779e213aa9520b324084994e5758 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:54:56 +0000 Subject: [PATCH 021/202] Stop components when the tray exits or the session ends Also tolerate a malformed tray icon id in settings and keep the resume handler from crashing the tray. --- CDPIUI.TrayIcon/Forms/EmptyForm.cs | 36 ++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/CDPIUI.TrayIcon/Forms/EmptyForm.cs b/CDPIUI.TrayIcon/Forms/EmptyForm.cs index 4f341d3a..4be8dd42 100644 --- a/CDPIUI.TrayIcon/Forms/EmptyForm.cs +++ b/CDPIUI.TrayIcon/Forms/EmptyForm.cs @@ -43,7 +43,7 @@ public EmptyForm() private static Guid GetGuid() { string savedGUID = SettingsManager.Instance.GetValue("TRAY", "iconGUID"); - if (savedGUID == "NaN") + if (savedGUID == "NaN" || !Guid.TryParse(savedGUID, out Guid parsedGuid)) { Guid guid = Guid.NewGuid(); SettingsManager.Instance.SetValue("TRAY", "iconGUID", guid.ToString()); @@ -51,22 +51,42 @@ private static Guid GetGuid() } else { - return new(savedGUID); + return parsedGuid; } } private void Application_ApplicationExit(object? sender, EventArgs e) { Application.ApplicationExit -= Application_ApplicationExit; + StopComponentsBeforeExit(); this.Close(); this.Dispose(); } + private void OnSessionEnding(object? sender, SessionEndingEventArgs e) + { + StopComponentsBeforeExit(); + } + + private static void StopComponentsBeforeExit() + { + try + { + // Runs off the UI thread so continuations inside StopAllTasks cannot wait for the blocked message loop. + Task.Run(() => TasksHelper.Instance.StopAllTasks()).Wait(TimeSpan.FromSeconds(5)); + } + catch (Exception ex) + { + Logger.Instance.CreateErrorLog(nameof(EmptyForm), $"Cannot stop components before exit: {ex.Message}"); + } + } + private void ConnectHandlers() { TasksHelper.Instance.TaskStateUpdated += HandleTaskStateUpdate; TasksHelper.Instance.TaskListUpdated += HandleTasksListUpdate; SystemEvents.PowerModeChanged += OnPowerChange; + SystemEvents.SessionEnding += OnSessionEnding; } private void DisconnectHandlers() @@ -74,6 +94,7 @@ private void DisconnectHandlers() TasksHelper.Instance.TaskStateUpdated -= HandleTaskStateUpdate; TasksHelper.Instance.TaskListUpdated -= HandleTasksListUpdate; SystemEvents.PowerModeChanged -= OnPowerChange; + SystemEvents.SessionEnding -= OnSessionEnding; } private async void OnPowerChange(object s, PowerModeChangedEventArgs e) @@ -81,12 +102,19 @@ private async void OnPowerChange(object s, PowerModeChangedEventArgs e) switch (e.Mode) { case PowerModes.Resume: - foreach (var task in TasksHelper.Instance.Tasks) + foreach (var task in await TasksHelper.Instance.GetTasksSnapshot()) { - if (task.ProcessManager.IsProcessRunning) + if (!task.ProcessManager.IsProcessRunning) + continue; + + try { await TasksHelper.Instance.RestartTask(task.Id); } + catch (Exception ex) + { + Logger.Instance.CreateErrorLog(nameof(EmptyForm), $"Cannot restart {task.Id} after resume: {ex.Message}"); + } } break; case PowerModes.Suspend: From 0a45b6d35b1a1b1ce727c4ea2603bc09613853e6 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:56:13 +0000 Subject: [PATCH 022/202] Wait for a running tray process before starting a new one A slow tray start made the UI launch a second tray instance and close itself without showing anything. --- .../Communication/PipeClientService.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/CDPIUI.Core/Communication/PipeClientService.cs b/CDPIUI.Core/Communication/PipeClientService.cs index 5890ee95..1835317e 100644 --- a/CDPIUI.Core/Communication/PipeClientService.cs +++ b/CDPIUI.Core/Communication/PipeClientService.cs @@ -71,6 +71,18 @@ public async void Start() } catch { } + if (!PipeStream.IsConnected && IsTrayProcessRunning()) + { + try + { + await ((NamedPipeClientStream)PipeStream).ConnectAsync(TrayStartupWaitMs); + } + catch (Exception ex) when (ex is TimeoutException or IOException) + { + Logger?.CreateErrorLog(nameof(PipeClientService), $"Tray process is running but did not accept the connection: {ex.Message}"); + } + } + if (!PipeStream.IsConnected) { try @@ -119,6 +131,24 @@ public async void Start() } + private const int TrayStartupWaitMs = 15000; + + private static bool IsTrayProcessRunning() + { + try + { + var processes = Process.GetProcessesByName("CDPIUI_TrayIcon"); + bool running = processes.Length > 0; + foreach (var process in processes) + process.Dispose(); + return running; + } + catch (Exception) + { + return false; + } + } + protected override async Task SendConnectionPacket() { await SendMessageAsync(ServiceMessageModel.RequestAuth(Shared.Secrets.Secret.AuthGuid).ToString()); From d6c85cfcdfd926261d48af1b92c984b0fb225993 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:56:51 +0000 Subject: [PATCH 023/202] Ignore broken pipe errors while disposing the pipe --- CDPIUI.Shared/Pipe/PipeServiceBase.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CDPIUI.Shared/Pipe/PipeServiceBase.cs b/CDPIUI.Shared/Pipe/PipeServiceBase.cs index 3ce1413d..707e6fa5 100644 --- a/CDPIUI.Shared/Pipe/PipeServiceBase.cs +++ b/CDPIUI.Shared/Pipe/PipeServiceBase.cs @@ -148,7 +148,12 @@ private async Task SendStringMessageToPipe(string message) public virtual void Dispose() { Disconnected?.Invoke(); - PipeStream?.WaitForPipeDrain(); + try + { + if (PipeStream?.IsConnected == true) + PipeStream.WaitForPipeDrain(); + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException or InvalidOperationException) { } PipeStream?.Dispose(); StreamString = null; From 74586cfc54d976590c843d2f3b7edcf4f92e5fa3 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:57:26 +0000 Subject: [PATCH 024/202] Rebuild converted Zapret2 command lines after an application update The cache key did not include the converter version, so fixes in the converter never reached existing installations. --- .../Configuration/Converters/Zapret2LegacyConfigService.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/Converters/Zapret2LegacyConfigService.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/Converters/Zapret2LegacyConfigService.cs index a8f5749f..bded4d35 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/Converters/Zapret2LegacyConfigService.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/Converters/Zapret2LegacyConfigService.cs @@ -19,6 +19,7 @@ public static class Zapret2LegacyConfigService public const bool DefaultHashValidationValue = true; private const string CacheFormatVersion = "1"; + private static readonly Lazy ConverterVersion = new(() => global::CDPIUI.Core.ApplicationInfo.Version); private static readonly object SyncRoot = new(); public static string CacheRoot => @@ -295,6 +296,7 @@ private static string ComputeInputHash( { using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); AppendString(hash, CacheFormatVersion); + AppendString(hash, ConverterVersion.Value); AppendString(hash, config.packId ?? string.Empty); AppendString(hash, config.file_name ?? string.Empty); AppendString(hash, expandedLegacyStartupString); From 08119cba07515aaca8328f411aa2b0cb12d7359c Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:59:24 +0000 Subject: [PATCH 025/202] Fix system proxy page crash when no proxy is configured An empty or per-protocol ProxyServer value threw while the page was created. Defaults are used when the value cannot be parsed. --- .../WindowsNativeProxySettingsService.cs | 32 +++++++++++++++++++ CDPIUI.Tests/Core/ProxySettingsTests.cs | 29 +++++++++++++++++ .../SetupProxy/SetupProxyForSystem.xaml.cs | 17 ++++++---- 3 files changed, 71 insertions(+), 7 deletions(-) create mode 100644 CDPIUI.Tests/Core/ProxySettingsTests.cs diff --git a/CDPIUI.Core/Proxy/WindowsNativeProxySettingsService.cs b/CDPIUI.Core/Proxy/WindowsNativeProxySettingsService.cs index 8d4a12b0..f5cc7363 100644 --- a/CDPIUI.Core/Proxy/WindowsNativeProxySettingsService.cs +++ b/CDPIUI.Core/Proxy/WindowsNativeProxySettingsService.cs @@ -45,6 +45,38 @@ public static Dictionary ReadProxySettings() return result; } + public static bool TryParseProxyServer(string? proxyServer, out string host, out string port) + { + host = string.Empty; + port = string.Empty; + if (string.IsNullOrWhiteSpace(proxyServer)) + return false; + + string entry = proxyServer.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .FirstOrDefault() ?? string.Empty; + int schemeSeparator = entry.IndexOf('='); + if (schemeSeparator >= 0) + entry = entry[(schemeSeparator + 1)..]; + + int portSeparator = entry.LastIndexOf(':'); + if (entry.StartsWith('[')) + { + int closingBracket = entry.IndexOf(']'); + if (closingBracket < 0 || portSeparator < closingBracket) + return false; + host = entry[1..closingBracket]; + } + else + { + if (portSeparator <= 0 || entry.IndexOf(':') != portSeparator) + return false; + host = entry[..portSeparator]; + } + + port = entry[(portSeparator + 1)..]; + return host.Length > 0 && port.Length > 0; + } + public static bool IsProxyEnabled() { try diff --git a/CDPIUI.Tests/Core/ProxySettingsTests.cs b/CDPIUI.Tests/Core/ProxySettingsTests.cs new file mode 100644 index 00000000..2acd58f6 --- /dev/null +++ b/CDPIUI.Tests/Core/ProxySettingsTests.cs @@ -0,0 +1,29 @@ +using CDPIUI.Core.Proxy; + +namespace CDPIUI.Tests.Core; + +public class ProxySettingsTests +{ + [Theory] + [InlineData("socks=127.0.0.1:1080", "127.0.0.1", "1080")] + [InlineData("127.0.0.1:8080", "127.0.0.1", "8080")] + [InlineData("socks=[::1]:1080", "::1", "1080")] + [InlineData("http=proxy.local:3128;https=proxy.local:3129", "proxy.local", "3128")] + public void ParsesKnownFormats(string value, string host, string port) + { + Assert.True(WindowsNativeProxySettingsService.TryParseProxyServer(value, out string parsedHost, out string parsedPort)); + Assert.Equal(host, parsedHost); + Assert.Equal(port, parsedPort); + } + + [Theory] + [InlineData("")] + [InlineData(null)] + [InlineData("proxy.local")] + [InlineData("[::1]")] + [InlineData("::1")] + public void RejectsValuesWithoutPort(string? value) + { + Assert.False(WindowsNativeProxySettingsService.TryParseProxyServer(value, out _, out _)); + } +} diff --git a/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs b/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs index 812f7c68..59359e4b 100644 --- a/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs +++ b/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs @@ -66,13 +66,16 @@ private void SetSettings() { Dictionary currentSettings = WindowsNativeProxySettingsService.ReadProxySettings(); - IPValue.Text = (currentSettings["ProxyServer"].Split("]:").Length >= 2 ? - currentSettings["ProxyServer"].Split("]:")[0] : - currentSettings["ProxyServer"].Split(":")[0]) - .Replace("[", "").Replace("]", "").Replace("socks=", ""); - PortValue.Text = currentSettings["ProxyServer"].Split("]:").Length >= 2 ? - currentSettings["ProxyServer"].Split("]:")[1] : - currentSettings["ProxyServer"].Split(":")[1]; + if (WindowsNativeProxySettingsService.TryParseProxyServer(currentSettings["ProxyServer"], out string host, out string port)) + { + IPValue.Text = host; + PortValue.Text = port; + } + else + { + IPValue.Text = "127.0.0.1"; + PortValue.Text = "1080"; + } BypassLocalCheckBox.IsChecked = currentSettings["ProxyOverride"].Contains(""); From 4056575530e197017a34536eadfcfdecd3bfc67f Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:00:13 +0000 Subject: [PATCH 026/202] Keep the preset editor open until unsaved changes are confirmed The close was cancelled only after an await, so the window closed and the unsaved preset was lost. --- CDPIUI/Windows/ConfigMakerWindow.xaml.cs | 36 ++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/CDPIUI/Windows/ConfigMakerWindow.xaml.cs b/CDPIUI/Windows/ConfigMakerWindow.xaml.cs index 1e39207a..59846901 100644 --- a/CDPIUI/Windows/ConfigMakerWindow.xaml.cs +++ b/CDPIUI/Windows/ConfigMakerWindow.xaml.cs @@ -117,12 +117,35 @@ private async void RootGrid_Loaded(object sender, RoutedEventArgs e) + private bool closeConfirmed; + private bool isExitDialogOpened; + private async void ConfigMakerWindow_Closed(object sender, WindowEventArgs args) { - if (!await IsExitAvailable()) + if (!closeConfirmed && HasUnsavedChanges()) { + // Handled must be set before the first await, otherwise the window is already closing. args.Handled = true; - return; + if (isExitDialogOpened) + return; + + isExitDialogOpened = true; + bool confirmed; + try + { + confirmed = await ShowAskExitDialog(); + } + finally + { + isExitDialogOpened = false; + } + + if (!confirmed) + return; + + closeConfirmed = true; + Close(); + return; } Closed -= ConfigMakerWindow_Closed; @@ -241,11 +264,14 @@ private async void OpenWelcomeDialog_Click(object sender, RoutedEventArgs e) } } + private bool HasUnsavedChanges() => + !string.IsNullOrEmpty(ConfigMaker.CommandText) || + ConfigMaker.HasVariables || + ConfigMaker.HasPresetFiles; + private async Task IsExitAvailable() { - if (!string.IsNullOrEmpty(ConfigMaker.CommandText) || - ConfigMaker.HasVariables || - ConfigMaker.HasPresetFiles) + if (HasUnsavedChanges()) { var result = await ShowAskExitDialog(); From 9acd4fcee50f4461f78e4ca8613fd783e55503d7 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:01:11 +0000 Subject: [PATCH 027/202] Do not crash on store items without version bounds --- CDPIUI.Core/Store/VersionComparier.cs | 14 ++++++++++++++ CDPIUI.Tests/Core/VersionHelperTests.cs | 12 ++++++++++++ CDPIUI/Views/Store/ItemViewPage.xaml.cs | 12 +----------- CDPIUI/Windows/WelcomeWindow.xaml.cs | 12 +----------- 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/CDPIUI.Core/Store/VersionComparier.cs b/CDPIUI.Core/Store/VersionComparier.cs index b3fc6fcd..3bdfb539 100644 --- a/CDPIUI.Core/Store/VersionComparier.cs +++ b/CDPIUI.Core/Store/VersionComparier.cs @@ -52,6 +52,20 @@ public static int CompareVersionStrings(string? oldVersion, string? newVersion) return 0; } + public static bool IsVersionInRange(string? version, string? minVersion, string? maxVersion) + { + if (!Version.TryParse(version, out Version? current) || !Version.TryParse(minVersion, out Version? min)) + return false; + + if (current < min) + return false; + + if (string.IsNullOrEmpty(maxVersion) || maxVersion == "NaN") + return true; + + return Version.TryParse(maxVersion, out Version? max) && current <= max; + } + /// /// Is version string are correct /// diff --git a/CDPIUI.Tests/Core/VersionHelperTests.cs b/CDPIUI.Tests/Core/VersionHelperTests.cs index b2b72e10..173ba41a 100644 --- a/CDPIUI.Tests/Core/VersionHelperTests.cs +++ b/CDPIUI.Tests/Core/VersionHelperTests.cs @@ -19,4 +19,16 @@ public void EqualVersionsCompareAsZero() { Assert.Equal(0, VersionHelper.CompareVersionStrings("1.2.3", "1.2.3")); } + + [Theory] + [InlineData("1.0.4.0", "1.0.0", "NaN", true)] + [InlineData("1.0.4.0", "1.0.0", null, true)] + [InlineData("1.0.4.0", "1.0.0", "1.0.3", false)] + [InlineData("1.0.4.0", "2.0", "NaN", false)] + [InlineData("1.0.4.0", null, "NaN", false)] + [InlineData("1.0.4.0", "1.0.0", "garbage", false)] + public void IsVersionInRangeHandlesMissingBounds(string version, string? min, string? max, bool expected) + { + Assert.Equal(expected, VersionHelper.IsVersionInRange(version, min, max)); + } } diff --git a/CDPIUI/Views/Store/ItemViewPage.xaml.cs b/CDPIUI/Views/Store/ItemViewPage.xaml.cs index 6c286697..cae83a80 100644 --- a/CDPIUI/Views/Store/ItemViewPage.xaml.cs +++ b/CDPIUI/Views/Store/ItemViewPage.xaml.cs @@ -239,17 +239,7 @@ private void CheckCurrentStatus() private bool IsItemSupported() { - Version curVer = new Version(ApplicationInfo.Version); - Version minV = new Version(item.target_minversion); - - if (curVer < minV) return false; - - if (item.target_maxversion != "NaN") - { - Version maxV = new Version(item.target_maxversion); - if (curVer > maxV) return false; - } - return true; + return VersionHelper.IsVersionInRange(ApplicationInfo.Version, item.target_minversion, item.target_maxversion); } private void ShowErrorDialog() diff --git a/CDPIUI/Windows/WelcomeWindow.xaml.cs b/CDPIUI/Windows/WelcomeWindow.xaml.cs index 58722de0..431dc47a 100644 --- a/CDPIUI/Windows/WelcomeWindow.xaml.cs +++ b/CDPIUI/Windows/WelcomeWindow.xaml.cs @@ -462,17 +462,7 @@ private bool IsItemSupported(RepoItemModel item) { Logger.Instance.CreateDebugLog(nameof(WelcomeWindow), $"Checking is item supported for {item.store_id} ({item.short_name})"); - Version curVer = new Version(ApplicationInfo.Version); - Version minV = new Version(item.target_minversion); - - if (curVer < minV) return false; - - if (item.target_maxversion != "NaN") - { - Version maxV = new Version(item.target_maxversion); - if (curVer > maxV) return false; - } - return true; + return VersionHelper.IsVersionInRange(ApplicationInfo.Version, item.target_minversion, item.target_maxversion); } From 8aa911ba9a38aaee34ee7455a24884dc01bc5798 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:01:11 +0000 Subject: [PATCH 028/202] Install every selected kit in the welcome wizard The loop stopped at the first kit whose items were already installed. --- CDPIUI/Windows/WelcomeWindow.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI/Windows/WelcomeWindow.xaml.cs b/CDPIUI/Windows/WelcomeWindow.xaml.cs index 431dc47a..c5ac81d9 100644 --- a/CDPIUI/Windows/WelcomeWindow.xaml.cs +++ b/CDPIUI/Windows/WelcomeWindow.xaml.cs @@ -214,7 +214,7 @@ private async void DownloadItems() .Where(item => !DatabaseHelper.Instance.IsItemInstalled(item.store_id)) .ToList(); if (itemsToInstall.Count == 0) - return; + continue; List licenses = itemsToInstall .SelectMany(item => item.license ?? []) From 6dd1d5a47e1d0b59f5c97c77eda245a9c0fad03b Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:03 +0000 Subject: [PATCH 029/202] Stop after a failed preset save The success dialog was shown and the component pointed at a preset that was never written. --- CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs | 1 + CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs | 3 +++ 2 files changed, 4 insertions(+) diff --git a/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs b/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs index 17b4e3cf..0835af97 100644 --- a/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs @@ -840,6 +840,7 @@ private async void SaveConfigButton_Click(object sender, RoutedEventArgs e) string.Format(localizer.GetLocalizedString("CannotSaveConfigMessage"), errorCode), localizer.GetLocalizedString("SomethingWentWrong") ); + return; } ComponentHelper componentHelper = diff --git a/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs b/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs index eb439c4d..f277ed9b 100644 --- a/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs +++ b/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs @@ -433,7 +433,10 @@ private async void CreatePlConfig() string errorCode = await ConfigurationService.SaveConfigItem(fileName, SharedConstants.LocalUserItemsId, item); if (!string.IsNullOrEmpty(errorCode)) + { ShowErrorDialog(string.Format(localizer.GetLocalizedString("SaveConfigException"), errorCode), localizer.GetLocalizedString("SomethingWentWrong")); + return; + } SettingsManager.Instance.SetValue(["CONFIGS", ComponentId], "configFile", fileName); SettingsManager.Instance.SetValue(["CONFIGS", ComponentId], "configId", SharedConstants.LocalUserItemsId); From 10dae1f820b12d9ed8e9445f5c48a4dde753a284 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:03 +0000 Subject: [PATCH 030/202] Fix default filters in file dialogs --- .../CreateConfigHelper/ConfigMakerUserControl.xaml.cs | 2 +- .../CreateConfigHelper/FileConfigInspectUserControl.xaml.cs | 5 +++-- CDPIUI/Helper/AddOns/ConfigImport/ConfigImportHelper.cs | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs index bb09b583..b2456a2f 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs @@ -2934,7 +2934,7 @@ public async Task SaveTextAsync() DefaultExt = ".cdpiconfig", Filter = (!HasVariables ? localizer.GetLocalizedString("ConfigMakerTextFileFilter") + "|" : "") + localizer.GetLocalizedString("ConfigMakerCCFileFilter"), }; - dialog.FilterIndex = dialog.Filter.Count(); + dialog.FilterIndex = dialog.Filter.Split('|').Length / 2; if (dialog.ShowDialog() != true) { return; diff --git a/CDPIUI/Controls/CreateConfigHelper/FileConfigInspectUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/FileConfigInspectUserControl.xaml.cs index 85510d0a..41412f6b 100644 --- a/CDPIUI/Controls/CreateConfigHelper/FileConfigInspectUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/FileConfigInspectUserControl.xaml.cs @@ -146,8 +146,9 @@ private void SelectNewFile_Click(object sender, RoutedEventArgs e) openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); openFileDialog.FilterIndex = 0; - openFileDialog.Filter = Path.GetExtension(FilePath) == ".txt" ? "TXT files (*.txt)|*.txt" : - Path.GetExtension(FilePath) == ".txt" ? "BIN files (*.bin)|*.bin" : "All files (*.*)|*.*"; + string extension = Path.GetExtension(FilePath); + openFileDialog.Filter = string.Equals(extension, ".txt", StringComparison.OrdinalIgnoreCase) ? "TXT files (*.txt)|*.txt" : + string.Equals(extension, ".bin", StringComparison.OrdinalIgnoreCase) ? "BIN files (*.bin)|*.bin" : "All files (*.*)|*.*"; openFileDialog.RestoreDirectory = false; if (openFileDialog.ShowDialog() == DialogResult.OK) diff --git a/CDPIUI/Helper/AddOns/ConfigImport/ConfigImportHelper.cs b/CDPIUI/Helper/AddOns/ConfigImport/ConfigImportHelper.cs index b3d9f099..d45c22aa 100644 --- a/CDPIUI/Helper/AddOns/ConfigImport/ConfigImportHelper.cs +++ b/CDPIUI/Helper/AddOns/ConfigImport/ConfigImportHelper.cs @@ -58,7 +58,7 @@ public static OperationResultModel OpenFileSelectionDialog(bool multis $"{localizer.GetLocalizedString("AllSupported")}|*.txt;*.bat;*.cmd;*.json" + ";*" + ConfigShareService.Extension; openFileDialog.RestoreDirectory = true; - openFileDialog.FilterIndex = openFileDialog.Filter.Count(); + openFileDialog.FilterIndex = openFileDialog.Filter.Split('|').Length / 2; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { From 2d33ed129c4fece030d10d1a9a4ae8f4f62ada14 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:03 +0000 Subject: [PATCH 031/202] Show the selected Mica Smoke editor background in the menu --- CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs b/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs index 8078f224..387d0c30 100644 --- a/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs +++ b/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs @@ -447,7 +447,7 @@ private void SetEditorBackgroundSettings() MicaAltMenuItem.IsChecked = true; break; case "MicaSmoke": - MicaBackgroundMenuItem.IsChecked = true; + MicaSmokeMenuItem.IsChecked = true; break; default: DefaultBackgroundMenuItem.IsChecked = true; From d531db4ab66414812513fe70119b8b556bde18cd Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:03 +0000 Subject: [PATCH 032/202] Fix dependency property registrations NoContentToDisplay registered its Text property for another control, and the selector bar item never raised its enabled change callback. --- CDPIUI/Controls/Navigation/AnimatedSelectorBar.xaml.cs | 5 ++++- .../Controls/Universal/NoContentToDisplayUserControl.xaml.cs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CDPIUI/Controls/Navigation/AnimatedSelectorBar.xaml.cs b/CDPIUI/Controls/Navigation/AnimatedSelectorBar.xaml.cs index a3d13ba6..a78878be 100644 --- a/CDPIUI/Controls/Navigation/AnimatedSelectorBar.xaml.cs +++ b/CDPIUI/Controls/Navigation/AnimatedSelectorBar.xaml.cs @@ -297,7 +297,10 @@ public bool IsEnabled nameof(IsEnabled), typeof(bool), typeof(AnimatedSelectorBarItem), - new PropertyMetadata(true, EnabledChanged)); + new PropertyMetadata(true, OnIsEnabledChanged)); + + private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => + EnabledChanged?.Invoke(d, e); public string Header { diff --git a/CDPIUI/Controls/Universal/NoContentToDisplayUserControl.xaml.cs b/CDPIUI/Controls/Universal/NoContentToDisplayUserControl.xaml.cs index 4f69708c..f31cc965 100644 --- a/CDPIUI/Controls/Universal/NoContentToDisplayUserControl.xaml.cs +++ b/CDPIUI/Controls/Universal/NoContentToDisplayUserControl.xaml.cs @@ -36,6 +36,6 @@ public string Text public static readonly DependencyProperty TextProperty = DependencyProperty.Register( - nameof(Text), typeof(string), typeof(SitelistButton), new PropertyMetadata(localizer.GetLocalizedString("NoContentToDisplay")) + nameof(Text), typeof(string), typeof(NoContentToDisplayUserControl), new PropertyMetadata(localizer.GetLocalizedString("NoContentToDisplay")) ); } From 9867919c87c22572faa2751cecbd0ead3d33c1ff Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:03 +0000 Subject: [PATCH 033/202] Count temporary files in the storage usage view --- .../Store/Settings/MemoryDiskUsageViewUserControl.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI/Controls/Store/Settings/MemoryDiskUsageViewUserControl.xaml.cs b/CDPIUI/Controls/Store/Settings/MemoryDiskUsageViewUserControl.xaml.cs index 10d06425..65835ee0 100644 --- a/CDPIUI/Controls/Store/Settings/MemoryDiskUsageViewUserControl.xaml.cs +++ b/CDPIUI/Controls/Store/Settings/MemoryDiskUsageViewUserControl.xaml.cs @@ -244,7 +244,7 @@ private async Task CreateTilesForCategories(string directory, long totalSize) } } } - else if (relpath.StartsWith("TempFiles/")) + else if (relpath.StartsWith("TempFiles")) { CreateTileForMemoryUsageCategory(size, totalSize, MemoryUsageCategories.Temp); } From 0b200f5cac7d729cc95ddaaf15d61ebd10428628 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:03 +0000 Subject: [PATCH 034/202] Save the new value of the monospace-only font option --- CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs b/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs index 329118c1..37bb7e82 100644 --- a/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs +++ b/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs @@ -69,8 +69,8 @@ public bool OnlyMonospace if (Equals(onlyMonospace, value)) return; - SettingsManager.Instance.SetValue("PSEUDOCONSOLE", "showOnlyMonospaceFontsInView", onlyMonospace); onlyMonospace = value; + SettingsManager.Instance.SetValue("PSEUDOCONSOLE", "showOnlyMonospaceFontsInView", onlyMonospace); LoadFonts(); Notify(nameof(OnlyMonospace)); } From 907ef2a96e0b3bc351a1362f31e933834b8ad816 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:03:54 +0000 Subject: [PATCH 035/202] Do not save window geometry while the window is minimized Closing a minimized window stored its tiny minimized size and off-screen position, so it reopened as a small window. --- .../WindowHelper/WindowsPositionHelper.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CDPIUI/Helper/WindowHelper/WindowsPositionHelper.cs b/CDPIUI/Helper/WindowHelper/WindowsPositionHelper.cs index c709d398..1273464e 100644 --- a/CDPIUI/Helper/WindowHelper/WindowsPositionHelper.cs +++ b/CDPIUI/Helper/WindowHelper/WindowsPositionHelper.cs @@ -151,6 +151,10 @@ public static void SetWindowOwner(Window window, Window ownerWindow) SetWindowLongPtr(windowHandle, GWLP_HWNDPARENT, ownerHandle); } + private const int MinRestoredWindowSize = 200; + // Windows reports this position for minimized windows. + private const int MinimizedWindowCoordinate = -30000; + public static void SetCustomWindowSizeAndPositionFromSettings(Window window) { WindowResizeOptions resizeOptions = GetWindowResizeOptionsFromWindow(window); @@ -163,6 +167,17 @@ public static void SetCustomWindowSizeAndPositionFromSettings(Window window) bool isMaximized = SettingsManager.Instance.GetValue(["WINDOWS", window.GetType().Name], "isMaximized"); + if (width < MinRestoredWindowSize || height < MinRestoredWindowSize) + { + width = 0; + height = 0; + } + if (x <= MinimizedWindowCoordinate || y <= MinimizedWindowCoordinate) + { + x = 0; + y = 0; + } + RECT desiredRect = new RECT { left = x, top = y, right = x + width, bottom = y + height }; RECT workArea; if (!TryGetMonitorWorkArea(desiredRect, out workArea)) @@ -213,6 +228,8 @@ public static void SaveWindowSizeAndPostionsettings(Window window) AppWindow appWindow = AppWindow.GetFromWindowId(windowId); var presenter = appWindow.Presenter as OverlappedPresenter; + if (presenter == null || presenter.State == OverlappedPresenterState.Minimized) + return; int width = appWindow.Size.Width; int height = appWindow.Size.Height; From d6549e984b538d5125c52480e27ebc82e77453a9 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:05:55 +0000 Subject: [PATCH 036/202] Report MSI fatal error 1603 as a failed installation --- CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs index 99d4ff67..65d100d0 100644 --- a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs +++ b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs @@ -185,7 +185,7 @@ private async Task ProcessMsi(string operationId, string filePath) { _ = PipeHelper.SendMsiInstallationPacket(MSIInstallationMessageIds.SetOperationStatus, operationId, MsiState.CompleteRestartRequest); } - else if (exitCode == 0 || exitCode == 1603 || exitCode == 1638) + else if (exitCode == 0 || exitCode == 1638) { _ = PipeHelper.SendMsiInstallationPacket(MSIInstallationMessageIds.SetOperationStatus, operationId, MsiState.Complete); } From fd0b1ea023c52580f20db26c644e00707bd1ab73 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:07:04 +0000 Subject: [PATCH 037/202] Synchronize settings reads with writes --- CDPIUI.Shared/Basic/XMLSettingsService.cs | 188 ++++++++++-------- .../Shared/XmlSettingsServiceTests.cs | 17 ++ 2 files changed, 117 insertions(+), 88 deletions(-) diff --git a/CDPIUI.Shared/Basic/XMLSettingsService.cs b/CDPIUI.Shared/Basic/XMLSettingsService.cs index 1ba79f95..61f9f673 100644 --- a/CDPIUI.Shared/Basic/XMLSettingsService.cs +++ b/CDPIUI.Shared/Basic/XMLSettingsService.cs @@ -156,20 +156,23 @@ private void SaveSettings(bool keepBackup = true) /// Value if key exsits, otherwise default public T? GetValueOrDefault(string group, string key, XElement? xElement = null, T? defaultValue = default) { - if (xElement == null) xElement = _xDocument.Root; - var settingElement = xElement - .Elements("Group") - .FirstOrDefault(g => g.Attribute("Name")?.Value == group)? - .Elements("Setting") - .FirstOrDefault(s => s.Attribute("Key")?.Value == key); - - if (settingElement == null) + lock (_reloadLock) { - SetValue(group, key, defaultValue); - Debug.WriteLine($"Setting '{key}' in group '{group}' not found."); - return defaultValue; + if (xElement == null) xElement = _xDocument.Root; + var settingElement = xElement + .Elements("Group") + .FirstOrDefault(g => g.Attribute("Name")?.Value == group)? + .Elements("Setting") + .FirstOrDefault(s => s.Attribute("Key")?.Value == key); + + if (settingElement == null) + { + SetValue(group, key, defaultValue); + Debug.WriteLine($"Setting '{key}' in group '{group}' not found."); + return defaultValue; + } + else return GetValue(group, key, xElement); } - else return GetValue(group, key, xElement); } /// /// Get value or hardcoded defailt. Sets default value to settings file. @@ -185,33 +188,36 @@ private void SaveSettings(bool keepBackup = true) /// public T? GetValue(string group, string key, XElement? xElement = null, bool raiseExceptionIfNotExits = false) { - xElement ??= _xDocument.Root; - var settingElement = xElement - .Elements("Group") - .FirstOrDefault(g => g.Attribute("Name")?.Value == group)? - .Elements("Setting") - .FirstOrDefault(s => s.Attribute("Key")?.Value == key); - - if (settingElement == null) + lock (_reloadLock) { - if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); + xElement ??= _xDocument.Root; + var settingElement = xElement + .Elements("Group") + .FirstOrDefault(g => g.Attribute("Name")?.Value == group)? + .Elements("Setting") + .FirstOrDefault(s => s.Attribute("Key")?.Value == key); - var defaultValue = GetDefaultValueForKey(group, key); + if (settingElement == null) + { + if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); - SetValue(group, key, defaultValue); - Debug.WriteLine($"Setting '{key}' in group '{group}' not found."); - return defaultValue; - } - string value = settingElement.Attribute("Value")?.Value; - string type = settingElement.Attribute("Type")?.Value; + var defaultValue = GetDefaultValueForKey(group, key); - try - { - return GetValueFromString(value, type); - } - catch - { - throw new SettingTypeNotSupported($"Type mismatch or unsupported type for setting '{key}' in group '{group}'."); + SetValue(group, key, defaultValue); + Debug.WriteLine($"Setting '{key}' in group '{group}' not found."); + return defaultValue; + } + string value = settingElement.Attribute("Value")?.Value; + string type = settingElement.Attribute("Type")?.Value; + + try + { + return GetValueFromString(value, type); + } + catch + { + throw new SettingTypeNotSupported($"Type mismatch or unsupported type for setting '{key}' in group '{group}'."); + } } } /// @@ -228,47 +234,50 @@ private void SaveSettings(bool keepBackup = true) /// public T? GetValue(IEnumerable groupPath, string key, XElement? xElement = null, bool raiseExceptionIfNotExits = false) { - if (xElement == null) xElement = _xDocument.Root; - XElement current = xElement; - - foreach (var grp in groupPath) + lock (_reloadLock) { - current = current - .Elements("Group") - .FirstOrDefault(g => (string)g.Attribute("Name") == grp); - if (current == null) + if (xElement == null) xElement = _xDocument.Root; + XElement current = xElement; + + foreach (var grp in groupPath) + { + current = current + .Elements("Group") + .FirstOrDefault(g => (string)g.Attribute("Name") == grp); + if (current == null) + { + if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); + var defaultValue = GetDefaultValueForKey(groupPath, key); + SetValue(groupPath, key, defaultValue); + Debug.WriteLine($"Group path '{string.Join("/", groupPath)}' not found."); + return defaultValue; + } + } + + var settingElement = current + .Elements("Setting") + .FirstOrDefault(s => (string)s.Attribute("Key") == key); + + if (settingElement == null) { if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); var defaultValue = GetDefaultValueForKey(groupPath, key); SetValue(groupPath, key, defaultValue); - Debug.WriteLine($"Group path '{string.Join("/", groupPath)}' not found."); + Debug.WriteLine($"Setting '{key}' in group path '{string.Join("/", groupPath)}' not found."); return defaultValue; } - } - - var settingElement = current - .Elements("Setting") - .FirstOrDefault(s => (string)s.Attribute("Key") == key); - if (settingElement == null) - { - if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); - var defaultValue = GetDefaultValueForKey(groupPath, key); - SetValue(groupPath, key, defaultValue); - Debug.WriteLine($"Setting '{key}' in group path '{string.Join("/", groupPath)}' not found."); - return defaultValue; - } - - string value = (string)settingElement.Attribute("Value"); - string type = (string)settingElement.Attribute("Type"); + string value = (string)settingElement.Attribute("Value"); + string type = (string)settingElement.Attribute("Type"); - try - { - return GetValueFromString(value, type); - } - catch - { - throw new SettingTypeNotSupported($"Type mismatch or unsupported type for setting '{key}' in group path '{string.Join("/", groupPath)}'."); + try + { + return GetValueFromString(value, type); + } + catch + { + throw new SettingTypeNotSupported($"Type mismatch or unsupported type for setting '{key}' in group path '{string.Join("/", groupPath)}'."); + } } } @@ -283,35 +292,38 @@ private void SaveSettings(bool keepBackup = true) /// public Dictionary GetKeyPair(IEnumerable groupPath, XElement? xElement = null, bool raiseExceptionIfNotExits = false) { - if (xElement == null) xElement = _xDocument.Root; - XElement current = xElement; + lock (_reloadLock) + { + if (xElement == null) xElement = _xDocument.Root; + XElement current = xElement; - Dictionary dict = []; + Dictionary dict = []; - foreach (var grp in groupPath) - { - current = current - .Elements("Group") - .FirstOrDefault(g => (string)g.Attribute("Name") == grp); - if (current == null) + foreach (var grp in groupPath) { - if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); - var defaultValue = GetDefaultValueForKey(groupPath, "$$~"); - SetValue(groupPath, "$$~", defaultValue); - Debug.WriteLine($"Group path '{string.Join("/", groupPath)}' not found."); - return dict; + current = current + .Elements("Group") + .FirstOrDefault(g => (string)g.Attribute("Name") == grp); + if (current == null) + { + if (raiseExceptionIfNotExits) throw new SettingNotFoundException("Value not exist"); + var defaultValue = GetDefaultValueForKey(groupPath, "$$~"); + SetValue(groupPath, "$$~", defaultValue); + Debug.WriteLine($"Group path '{string.Join("/", groupPath)}' not found."); + return dict; + } } - } - if (current != null) - { - foreach (var setting in current.Elements("Setting")) + if (current != null) { - var result = GetValueFromString((string)setting.Attribute("Value"), (string)setting.Attribute("Type")); - dict.Add((string)setting.Attribute("Key"), result); + foreach (var setting in current.Elements("Setting")) + { + var result = GetValueFromString((string)setting.Attribute("Value"), (string)setting.Attribute("Type")); + dict.Add((string)setting.Attribute("Key"), result); + } } + return dict; } - return dict; } diff --git a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs index 43f723fc..e558cbf6 100644 --- a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs +++ b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs @@ -56,4 +56,21 @@ public void DateTimeWithGroupPathIsReadable() Assert.Equal(value, new XMLSettingsService(SettingsPath).GetValue(["ADDONS", "ASGKOI001"], "lastRun")); } + + [Fact] + public async Task ConcurrentReadsAndWritesDoNotThrow() + { + var settings = new XMLSettingsService(SettingsPath); + + await Task.WhenAll(Enumerable.Range(0, 8).Select(worker => Task.Run(() => + { + for (int i = 0; i < 50; i++) + { + settings.SetValue("GROUP" + worker, "key" + i, i); + settings.GetValue("GROUP" + ((worker + 1) % 8), "key" + i); + } + }))); + + Assert.Equal(49, new XMLSettingsService(SettingsPath).GetValue("GROUP3", "key49")); + } } From fe36066aea24b252dd9c38f1b716c37be3bd5463 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:09:06 +0000 Subject: [PATCH 038/202] Restrict the tray pipe to the application UI The pipe is now accessible only to the tray user, the desktop user and LocalSystem, network clients are denied, and both ends verify the executable of the process on the other side. The UI connects with identification-level impersonation and the authentication value is no longer written to debug output. --- .../Communication/PipeClientService.cs | 10 ++- CDPIUI.Shared/Pipe/PipePeerVerifier.cs | 68 ++++++++++++++++ .../Helper/Basic/ConnectionHelper.cs | 20 ++--- .../Helper/Basic/PipeAccessPolicy.cs | 78 +++++++++++++++++++ 4 files changed, 162 insertions(+), 14 deletions(-) create mode 100644 CDPIUI.Shared/Pipe/PipePeerVerifier.cs create mode 100644 CDPIUI.TrayIcon/Helper/Basic/PipeAccessPolicy.cs diff --git a/CDPIUI.Core/Communication/PipeClientService.cs b/CDPIUI.Core/Communication/PipeClientService.cs index 1835317e..56c33a76 100644 --- a/CDPIUI.Core/Communication/PipeClientService.cs +++ b/CDPIUI.Core/Communication/PipeClientService.cs @@ -53,7 +53,7 @@ public void Init() { PipeStream = new NamedPipeClientStream(".", SharedConstants.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous, - TokenImpersonationLevel.Impersonation); + TokenImpersonationLevel.Identification); } public async void Start() @@ -108,6 +108,14 @@ public async void Start() return; } + if (!PipePeerVerifier.IsServerExpected((NamedPipeClientStream)PipeStream, Path.Combine(Data.Directories.CurrentDirectory, "CDPIUI_TrayIcon.exe"))) + { + Logger?.CreateErrorLog(nameof(PipeClientService), "Pipe server is not the application tray process. Connection closed."); + Dispose(); + Process.GetCurrentProcess().Kill(); + return; + } + CancellationTokenSource.Dispose(); CancellationTokenSource = null; CreateCancellationToken(); diff --git a/CDPIUI.Shared/Pipe/PipePeerVerifier.cs b/CDPIUI.Shared/Pipe/PipePeerVerifier.cs new file mode 100644 index 00000000..8142d49c --- /dev/null +++ b/CDPIUI.Shared/Pipe/PipePeerVerifier.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Text; + +namespace CDPIUI.Shared.Pipe +{ + public static class PipePeerVerifier + { + private const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; + + public static bool IsClientExpected(NamedPipeServerStream pipe, string expectedImagePath) => + GetNamedPipeClientProcessId(pipe.SafePipeHandle, out uint processId) && + IsProcessImage(processId, expectedImagePath); + + public static bool IsServerExpected(NamedPipeClientStream pipe, string expectedImagePath) => + GetNamedPipeServerProcessId(pipe.SafePipeHandle, out uint processId) && + IsProcessImage(processId, expectedImagePath); + + public static bool IsProcessImage(uint processId, string expectedImagePath) + { + string? imagePath = GetProcessImagePath(processId); + if (imagePath == null) + return false; + +#if DEBUG + // Debug builds of the UI and the tray are produced in different output folders. + return string.Equals(Path.GetFileName(imagePath), Path.GetFileName(expectedImagePath), StringComparison.OrdinalIgnoreCase); +#else + return string.Equals(Path.GetFullPath(imagePath), Path.GetFullPath(expectedImagePath), StringComparison.OrdinalIgnoreCase); +#endif + } + + public static string? GetProcessImagePath(uint processId) + { + IntPtr process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId); + if (process == IntPtr.Zero) + return null; + + try + { + var buffer = new StringBuilder(32768); + int size = buffer.Capacity; + return QueryFullProcessImageName(process, 0, buffer, ref size) ? buffer.ToString(0, size) : null; + } + finally + { + CloseHandle(process); + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetNamedPipeClientProcessId(SafeHandle pipe, out uint clientProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetNamedPipeServerProcessId(SafeHandle pipe, out uint serverProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, uint processId); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder exeName, ref int size); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle(IntPtr handle); + } +} diff --git a/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs index 4a4d2050..7c6d8664 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs @@ -56,17 +56,7 @@ private async Task ListenLoopAsync() IsAuthorized = false; try { - var ps = new PipeSecurity(); - - var currentUserSid = WindowsIdentity.GetCurrent().User; - if (currentUserSid == null) - { - continue; - } - ps.AddAccessRule(new PipeAccessRule(currentUserSid, PipeAccessRights.FullControl, AccessControlType.Allow)); - - var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); - ps.AddAccessRule(new PipeAccessRule(everyone, PipeAccessRights.ReadWrite, AccessControlType.Allow)); + var ps = PipeAccessPolicy.CreatePipeSecurity(); PipeStream = NamedPipeServerStreamAcl.Create( SharedConstants.PipeName, @@ -89,10 +79,15 @@ private async Task ListenLoopAsync() try { - Console.WriteLine("WAIT"); await ((NamedPipeServerStream)PipeStream).WaitForConnectionAsync(CancellationToken ?? default); int threadId = Thread.CurrentThread.ManagedThreadId; + if (!PipePeerVerifier.IsClientExpected((NamedPipeServerStream)PipeStream, PipeAccessPolicy.ExpectedClientPath)) + { + Logger?.CreateWarningLog(nameof(PipeServer), "Rejected a pipe client that is not the application UI."); + continue; + } + Logger?.CreateDebugLog(nameof(PipeServer), $"Client connected on thread[{threadId}]."); await HandleConnectionAsync(); } @@ -131,7 +126,6 @@ protected override async Task RunMessageActions(IPipeMessage message) { if (messageModel.MessageType == ServiceMessageIds.RequestAuth) { - Debug.WriteLine(messageModel.MessageData["GUID"]); if (messageModel.MessageData != null && messageModel.MessageData["GUID"] == Secret.AuthGuid) { IsAuthorized = true; diff --git a/CDPIUI.TrayIcon/Helper/Basic/PipeAccessPolicy.cs b/CDPIUI.TrayIcon/Helper/Basic/PipeAccessPolicy.cs new file mode 100644 index 00000000..26bd8a09 --- /dev/null +++ b/CDPIUI.TrayIcon/Helper/Basic/PipeAccessPolicy.cs @@ -0,0 +1,78 @@ +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; + +namespace CDPIUI.TrayIcon.Helper.Basic +{ + public static class PipeAccessPolicy + { + private const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; + private const uint TOKEN_QUERY = 0x0008; + + public static string ExpectedClientPath => Path.Combine(Utils.GetDataDirectory(), "CDPIUI.exe"); + + public static PipeSecurity CreatePipeSecurity() + { + var security = new PipeSecurity(); + var trayUser = WindowsIdentity.GetCurrent().User + ?? throw new InvalidOperationException("Cannot determine the tray process user."); + + security.SetOwner(trayUser); + security.AddAccessRule(new PipeAccessRule(trayUser, PipeAccessRights.FullControl, AccessControlType.Allow)); + security.AddAccessRule(new PipeAccessRule( + new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); + + // With over-the-shoulder elevation the tray runs as an administrator account while the UI runs as the desktop user. + var desktopUser = GetDesktopUserSid(); + if (desktopUser != null && desktopUser != trayUser) + security.AddAccessRule(new PipeAccessRule(desktopUser, PipeAccessRights.ReadWrite, AccessControlType.Allow)); + + security.AddAccessRule(new PipeAccessRule( + new SecurityIdentifier(WellKnownSidType.NetworkSid, null), PipeAccessRights.FullControl, AccessControlType.Deny)); + + return security; + } + + public static SecurityIdentifier? GetDesktopUserSid() + { + IntPtr shellWindow = GetShellWindow(); + if (shellWindow == IntPtr.Zero || GetWindowThreadProcessId(shellWindow, out uint shellProcessId) == 0) + return null; + + IntPtr process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, shellProcessId); + if (process == IntPtr.Zero) + return null; + + IntPtr token = IntPtr.Zero; + try + { + if (!OpenProcessToken(process, TOKEN_QUERY, out token)) + return null; + + using var identity = new WindowsIdentity(token); + return identity.User; + } + finally + { + if (token != IntPtr.Zero) CloseHandle(token); + CloseHandle(process); + } + } + + [DllImport("user32.dll")] + private static extern IntPtr GetShellWindow(); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, uint processId); + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle(IntPtr handle); + } +} From a87b90a943a15fa95ce79e91789b1711d454671b Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:06:58 +0000 Subject: [PATCH 039/202] Restore nuget.org as a package source for the GUI project The project nuget.config clears all sources and adds only the CommunityToolkit Labs feed, so restore on a clean machine cannot find any nuget.org package. --- CDPIUI/nuget.config | 1 + 1 file changed, 1 insertion(+) diff --git a/CDPIUI/nuget.config b/CDPIUI/nuget.config index c7ee09d3..2f395739 100644 --- a/CDPIUI/nuget.config +++ b/CDPIUI/nuget.config @@ -2,6 +2,7 @@ + \ No newline at end of file From d13acdf48ebd5c430b572dbb045d5aa13caa0b9d Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:35:43 +0000 Subject: [PATCH 040/202] Preserve hosts file encoding and write it atomically The helper rewrote the hosts file as UTF-8 without BOM, appended lines one by one, and glued the first added line to the last line when the file did not end with a newline. On a CRLF checkout of the embedded list every line kept a trailing CR, so the duplicate check never matched and each line got an extra CR. The file is now read with its BOM or detected encoding and line endings, the new content is built in memory and swapped in through a temporary file with File.Replace, so the ACL is kept and the file is never half written. Errors are returned as the exit code instead of crashing with an unhandled exception, and a missing backup is reported as file not found. --- EditHostFile/Program.cs | 174 +++++++++++++++++++++++++++++++++------- 1 file changed, 147 insertions(+), 27 deletions(-) diff --git a/EditHostFile/Program.cs b/EditHostFile/Program.cs index 9e5ae477..bdabc80e 100644 --- a/EditHostFile/Program.cs +++ b/EditHostFile/Program.cs @@ -2,22 +2,22 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; namespace EditHostFile { internal class Program { + private const int E_INVALIDARG = unchecked((int)0x80070057); + private static void Log(string message) { Console.WriteLine($"[CDPI UI/EditHostFileHelper] {message}"); } - static void Main(string[] args) + static int Main(string[] args) { Log("Getting ready..."); string pathpart = "hosts"; @@ -28,65 +28,185 @@ static void Main(string[] args) } string hostfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), pathpart); - if (args.Contains("/remove")) + try { - RemoveAddedLines(hostfile); + if (args.Contains("/remove")) + { + RemoveAddedLines(hostfile); + } + else if (args.Contains("/add")) + { + AddNewLines(hostfile); + } + else if (args.Contains("/recover")) + { + RestoreBackup(hostfile); + } + else + { + Log("Unknown command"); + return E_INVALIDARG; + } } - else if (args.Contains("/add")) + catch (Exception ex) { - AddNewLines(hostfile); + Log($"Work failed: {ex}"); + return ex.HResult != 0 ? ex.HResult : 1; } - else if (args.Contains("/recover")) + Log("Work finished. Goodbye~"); + return 0; + } + + private sealed class HostsText + { + public string Text; + public Encoding Encoding; + public string NewLine; + } + + private static HostsText Read(string path) + { + byte[] bytes = File.ReadAllBytes(path); + Encoding encoding; + int offset = 0; + + if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) { - RestoreBackup(hostfile); + encoding = new UTF8Encoding(true); + offset = 3; } - Log("Work finished. Goodbye~"); + else if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) + { + encoding = new UnicodeEncoding(false, true); + offset = 2; + } + else if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) + { + encoding = new UnicodeEncoding(true, true); + offset = 2; + } + else + { + // No BOM: keep UTF-8 if the content is valid UTF-8, otherwise it is in the ANSI code page. + encoding = new UTF8Encoding(false, true); + try + { + encoding.GetString(bytes); + encoding = new UTF8Encoding(false); + } + catch (DecoderFallbackException) + { + encoding = Encoding.Default; + } + } + + string text = encoding.GetString(bytes, offset, bytes.Length - offset); + string newLine = text.Contains("\r\n") ? "\r\n" : text.Contains("\n") ? "\n" : "\r\n"; + return new HostsText { Text = text, Encoding = encoding, NewLine = newLine }; } - private static void CreateBackup(string path) + private static void Write(string path, HostsText content) + { + byte[] preamble = content.Encoding.GetPreamble(); + byte[] body = content.Encoding.GetBytes(content.Text); + + // Write next to the target and swap it in, so the hosts file is never left half written. + string temp = $"{path}.cdpiui.tmp"; + using (var stream = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None)) + { + stream.Write(preamble, 0, preamble.Length); + stream.Write(body, 0, body.Length); + stream.Flush(true); + } + + try + { + if (File.Exists(path)) + { + File.Replace(temp, path, null); + } + else + { + File.Move(temp, path); + } + } + finally + { + if (File.Exists(temp)) File.Delete(temp); + } + } + + private static void CreateBackup(string path, HostsText content) { Log($"Creating backup for \"{path}\" in \"{path}.bak\""); - File.Copy(path, $"{path}.bak", true); + Write($"{path}.bak", content); } private static void RestoreBackup(string path) { Log($"Restoring backup for \"{path}\" in \"{path}.bak\""); - File.Copy($"{path}.bak", path, true); - File.Delete($"{path}.bak"); + string backup = $"{path}.bak"; + if (!File.Exists(backup)) throw new FileNotFoundException("Backup not found", backup); + + Write(path, Read(backup)); + File.Delete(backup); + } + + private static string RemoveBlock(string text) + { + return Regex.Replace(text, @"(# \[CDOM-B\](?:.*?)# \[CDOM-E\](?:.*?))(?:\n|$)", "", RegexOptions.Singleline); } private static void RemoveAddedLines(string path) { Log($"Removing added lines in \"{path}\""); - string textContent = File.ReadAllText(path); - textContent = Regex.Replace(textContent, @"(# \[CDOM-B\](?:.*?)# \[CDOM-E\](?:.*?))(?:\n|$)", "", RegexOptions.Singleline); + HostsText content = Read(path); + string text = RemoveBlock(content.Text); + if (text == content.Text) return; + + content.Text = text; + Write(path, content); + } - File.WriteAllText(path, textContent); + private static List SplitLines(string text) + { + return text.Split('\n').Select(line => line.TrimEnd('\r')).ToList(); } private static void AddNewLines(string path) { Log($"Adding new lines in \"{path}\""); Assembly assembly = Assembly.GetExecutingAssembly(); - var stream = assembly.GetManifestResourceStream("EditHostFile.Data.hosts"); - StreamReader reader = new StreamReader(stream); - string text = reader.ReadToEnd(); + string resource; + using (var stream = assembly.GetManifestResourceStream("EditHostFile.Data.hosts")) + using (var reader = new StreamReader(stream)) + { + resource = reader.ReadToEnd(); + } - RemoveAddedLines(path); - CreateBackup(path); + HostsText content = Read(path); + string text = RemoveBlock(content.Text); + content.Text = text; + CreateBackup(path, content); - string[] lines = File.ReadAllLines(path); - foreach (string line in text.Split('\n')) + List lines = SplitLines(text); + var builder = new StringBuilder(text); + if (text.Length > 0 && !text.EndsWith("\n")) { - if (!lines.Contains(line)) + builder.Append(content.NewLine); + } + foreach (string line in SplitLines(resource)) + { + if (line.Length == 0 || !lines.Contains(line)) { - File.AppendAllLines(path, new String[] { line }); + builder.Append(line).Append(content.NewLine); } } - Log($"Adding new lines in \"{path}\". Status: COMPLETE"); + content.Text = builder.ToString(); + Write(path, content); + Log($"Adding new lines in \"{path}\". Status: COMPLETE"); } } } From 0578bb64acc992a580d771a7de7c536dbbc10082 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:37:30 +0000 Subject: [PATCH 041/202] Stage updates and roll back replaced files on failure The updater extracted the archive straight over the installed files, so a failure in the middle left a mix of old and new files. The downgrade then copied the .old folder over the installation, but nothing fills that folder for this updater: it only ever holds the GDPIUI-Rollback.exe installer, so the downgrade either failed or copied that installer into the application folder. The archive is now extracted into .update-staging first; nothing is changed if any entry fails. The staged files are then moved into place one by one, each replaced file is moved to .update-backup, and on any error the applied files are removed and the backups are moved back before the previous version is launched with --after-failed-update. The backup is kept only if the rollback itself fails. --- Update/InstallHelper.cs | 310 +++++++++++++++++++--------------------- 1 file changed, 149 insertions(+), 161 deletions(-) diff --git a/Update/InstallHelper.cs b/Update/InstallHelper.cs index 66275829..7ccfaa25 100644 --- a/Update/InstallHelper.cs +++ b/Update/InstallHelper.cs @@ -89,18 +89,26 @@ public void StartInstall() CloseProcessIfRunning("CDPIUI_TrayIcon"); InstallationStateChanged?.Invoke(InstallState.Unpack); - bool extractedOk = await ExtractZipAsync(); + List stagedFiles = await StageAsync(); - if (FinishStatus == InstallError.None && extractedOk) + bool applied = false; + if (FinishStatus == InstallError.None && stagedFiles != null) + { + InstallationStateChanged?.Invoke(InstallState.Copy); + applied = ApplyStaged(stagedFiles); + } + + if (applied) { InstallationStateChanged?.Invoke(InstallState.Finalize); + Cleanup(); FinishStatus = InstallError.OK; bool launched = LaunchApplication(false); if (launched) { InstallationStateChanged?.Invoke(InstallState.Completed); ProgressChanged?.Invoke(1.0); - Log("Extraction completed successfully and application launched."); + Log("Update applied successfully and application launched."); } else { @@ -110,25 +118,14 @@ public void StartInstall() } else { - Log("An error occurred during extraction. Attempting downgrade."); - InstallationStateChanged?.Invoke(InstallState.Copy); - bool downgraded = DowngradeProgram(); - - if (downgraded) + Log("Update was not applied. The previous version is kept."); + Cleanup(); + FinishStatus = InstallError.OK; + bool launched = LaunchApplication(true); + if (launched) { - Log("Successfully downgraded to previous version."); - FinishStatus = InstallError.OK; - bool launched = LaunchApplication(true); - if (launched) - { - InstallationStateChanged?.Invoke(InstallState.Completed); - ProgressChanged?.Invoke(1.0); - Application.Exit(); - } - else - { - InstallationStateChanged?.Invoke(InstallState.Error); - } + InstallationStateChanged?.Invoke(InstallState.Completed); + ProgressChanged?.Invoke(1.0); } else { @@ -148,6 +145,9 @@ public void StartInstall() }); } + private string StagingFolder => Path.Combine(_targetFolder, ".update-staging"); + private string BackupFolder => Path.Combine(_targetFolder, ".update-backup"); + private void CloseProcessIfRunning(string processNameWithoutExt) { try @@ -170,66 +170,58 @@ private void CloseProcessIfRunning(string processNameWithoutExt) } } - private async Task ExtractZipAsync() + /// + /// Extracts the update into the staging folder without touching the installed files. + /// + /// Relative paths of the staged files, or null if the update cannot be applied + private async Task> StageAsync() { try { if (string.IsNullOrWhiteSpace(_archiveFilePath) || !File.Exists(_archiveFilePath)) { FinishStatus = InstallError.FileNotFound; - // ErrorOccurred?.Invoke(FinishStatus, "Zip archive not found."); - return false; + return null; } if (!Directory.Exists(_targetFolder)) Directory.CreateDirectory(_targetFolder); + DeleteDirectory(StagingFolder); + DeleteDirectory(BackupFolder); + Directory.CreateDirectory(StagingFolder); + using (var zip = ZipFile.OpenRead(_archiveFilePath)) { - var relevantEntries = zip.Entries + var fileEntries = zip.Entries .Where(e => { var name = e.FullName.Replace('\\', '/'); - return name.StartsWith(UiRootPrefix, StringComparison.OrdinalIgnoreCase); + return name.StartsWith(UiRootPrefix, StringComparison.OrdinalIgnoreCase) && !name.EndsWith("/"); }) .ToList(); - var fileEntries = relevantEntries - .Where(e => !e.FullName.EndsWith("/")) - .ToList(); - int totalFiles = fileEntries.Count; - int extractedFiles = 0; - if (totalFiles == 0) { Log($"No files found to extract in archive under '{UiRootPrefix}'."); - - ProgressChanged?.Invoke(1.0); - return false; + FinishStatus = InstallError.ExtractingFile; + return null; } - foreach (var entry in relevantEntries) + var staged = new List(); + foreach (var entry in fileEntries) { var relativePath = entry.FullName.Replace('\\', '/').Substring(UiRootPrefix.Length); - if (!string.IsNullOrEmpty(relativePath) && !TryGetDestination(relativePath, out _)) + string destPath; + string stagedPath; + if (!TryGetDestination(_targetFolder, relativePath, out destPath) || + !TryGetDestination(StagingFolder, relativePath, out stagedPath)) { Log($"Archive entry '{entry.FullName}' points outside of the target folder. Update aborted."); - ProgressChanged?.Invoke(1.0); - return false; + FinishStatus = InstallError.ExtractingFile; + return null; } - } - - foreach (var entry in relevantEntries) - { - var entryName = entry.FullName.Replace('\\', '/'); - var relativePath = entryName.Substring(UiRootPrefix.Length); - if (string.IsNullOrEmpty(relativePath)) - continue; - - string destPath; - TryGetDestination(relativePath, out destPath); - string destDir = Path.GetDirectoryName(destPath); var fileName = Path.GetFileName(relativePath); if (_skipFiles.Contains(fileName, StringComparer.OrdinalIgnoreCase) && File.Exists(destPath)) @@ -238,122 +230,135 @@ private async Task ExtractZipAsync() continue; } - if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir)) - Directory.CreateDirectory(destDir); - - if (entry.FullName.EndsWith("/")) - { - if (!Directory.Exists(destPath)) - Directory.CreateDirectory(destPath); - } - else + CurrentFileChanged?.Invoke($"Extracting {relativePath}"); + Directory.CreateDirectory(Path.GetDirectoryName(stagedPath)); + using (var stream = entry.Open()) + using (var outFile = new FileStream(stagedPath, FileMode.Create, FileAccess.Write, FileShare.None)) { - try - { - CurrentFileChanged?.Invoke($"Extracting {relativePath}"); - using (var stream = entry.Open()) - using (var outFile = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.None)) - { - await stream.CopyToAsync(outFile); - } - } - catch (UnauthorizedAccessException uaEx) - { - Log($"Permission denied when extracting {relativePath}: {uaEx.Message}"); - FinishStatus = InstallError.PermissionDenied; - // ErrorOccurred?.Invoke(FinishStatus, $"Permission denied when extracting {relativePath}"); - return false; - } - catch (IOException ioEx) - { - Log($"IO error when extracting {relativePath}: {ioEx.Message}"); - FinishStatus = InstallError.ExtractingFile; - // ErrorOccurred?.Invoke(FinishStatus, $"IO error when extracting {relativePath}: {ioEx.Message}"); - return false; - } - catch (Exception ex) - { - Log($"Error extracting {relativePath}: {ex}"); - FinishStatus = InstallError.ExtractingFile; - // ErrorOccurred?.Invoke(FinishStatus, $"Error extracting {relativePath}: {ex.Message}"); - return false; - } - - extractedFiles++; - double progress = (double)extractedFiles / Math.Max(1, totalFiles); - ProgressChanged?.Invoke(progress); + await stream.CopyToAsync(outFile); } - } - ProgressChanged?.Invoke(1.0); - } - return true; + staged.Add(relativePath); + ProgressChanged?.Invoke((double)staged.Count / totalFiles); + } + + return staged; + } + } + catch (UnauthorizedAccessException uaEx) + { + Log($"Permission denied while extracting the update: {uaEx.Message}"); + FinishStatus = InstallError.PermissionDenied; + return null; } catch (Exception ex) { Log($"Extraction failed: {ex}"); - FinishStatus = InstallError.UnexpectedError; - // ErrorOccurred?.Invoke(FinishStatus, ex.Message); - return false; + FinishStatus = InstallError.ExtractingFile; + return null; } } - private bool DowngradeProgram() + /// + /// Moves the staged files into place. Replaced files are kept in the backup folder + /// and moved back if any file cannot be applied. + /// + private bool ApplyStaged(List stagedFiles) { + // Relative path and whether an installed file was moved to the backup folder. + var applied = new List>(); try { - string oldDirectory = Path.Combine(_targetFolder, ".old"); - if (!Directory.Exists(oldDirectory)) + for (int i = 0; i < stagedFiles.Count; i++) { - FinishStatus = InstallError.NoOldVersion; - ErrorOccurred?.Invoke(FinishStatus, "No old version found to downgrade to."); - return false; + string relativePath = stagedFiles[i]; + string destPath, stagedPath, backupPath; + TryGetDestination(_targetFolder, relativePath, out destPath); + TryGetDestination(StagingFolder, relativePath, out stagedPath); + TryGetDestination(BackupFolder, relativePath, out backupPath); + + CurrentFileChanged?.Invoke($"Copying {relativePath}"); + Directory.CreateDirectory(Path.GetDirectoryName(destPath)); + + bool backedUp = false; + if (File.Exists(destPath)) + { + Directory.CreateDirectory(Path.GetDirectoryName(backupPath)); + File.Move(destPath, backupPath); + backedUp = true; + } + applied.Add(new KeyValuePair(relativePath, backedUp)); + + File.Move(stagedPath, destPath); + ProgressChanged?.Invoke((double)(i + 1) / stagedFiles.Count); } - var allFiles = Directory.GetFiles(oldDirectory, "*", SearchOption.AllDirectories); - int total = allFiles.Length; - int idx = 0; + return true; + } + catch (Exception ex) + { + Log($"Failed to apply the update: {ex}"); + FinishStatus = ex is UnauthorizedAccessException ? InstallError.PermissionDenied : InstallError.ExtractingFile; - foreach (var src in allFiles) + InstallationStateChanged?.Invoke(InstallState.Copy); + if (!Rollback(applied)) { - var relative = GetRelativePath(oldDirectory, src); - var dest = Path.Combine(_targetFolder, relative); - var destDir = Path.GetDirectoryName(dest); - if (!Directory.Exists(destDir)) - Directory.CreateDirectory(destDir); + FinishStatus = InstallError.NoOldVersion; + ErrorOccurred?.Invoke(FinishStatus, ex.Message); + } + return false; + } + } - try - { - File.Copy(src, dest, true); - idx++; - ProgressChanged?.Invoke((double)idx / Math.Max(1, total)); - CurrentFileChanged?.Invoke($"Downgraded {relative}"); - } - catch (UnauthorizedAccessException uaEx) - { - Log($"Permission denied while downgrading {relative}: {uaEx.Message}"); - FinishStatus = InstallError.PermissionDenied; - ErrorOccurred?.Invoke(FinishStatus, $"Permission denied while downgrading {relative}"); - return false; - } - catch (Exception ex) + private bool Rollback(List> applied) + { + bool restored = true; + for (int i = applied.Count - 1; i >= 0; i--) + { + string relativePath = applied[i].Key; + string destPath, backupPath; + TryGetDestination(_targetFolder, relativePath, out destPath); + TryGetDestination(BackupFolder, relativePath, out backupPath); + try + { + if (File.Exists(destPath)) + File.Delete(destPath); + + if (applied[i].Value) { - Log($"Error while downgrading {relative}: {ex}"); - FinishStatus = InstallError.UnexpectedError; - ErrorOccurred?.Invoke(FinishStatus, $"Error while downgrading {relative}: {ex.Message}"); - return false; + File.Move(backupPath, destPath); } + CurrentFileChanged?.Invoke($"Restored {relativePath}"); + } + catch (Exception ex) + { + Log($"Failed to restore {relativePath}: {ex}"); + restored = false; } + } - ProgressChanged?.Invoke(1.0); - return true; + Log(restored ? "Previous version restored." : "Previous version was restored only partially."); + return restored; + } + + private void Cleanup() + { + // Keep the backup if a rollback did not finish, so the files can still be recovered by hand. + if (FinishStatus != InstallError.NoOldVersion) + DeleteDirectory(BackupFolder); + DeleteDirectory(StagingFolder); + } + + private void DeleteDirectory(string path) + { + try + { + if (Directory.Exists(path)) + Directory.Delete(path, true); } catch (Exception ex) { - Log($"Downgrade failed: {ex}"); - FinishStatus = InstallError.UnexpectedError; - ErrorOccurred?.Invoke(FinishStatus, ex.Message); - return false; + Log($"Failed to delete {path}: {ex.Message}"); } } @@ -395,13 +400,13 @@ private bool LaunchApplication(bool error = false) } } - private bool TryGetDestination(string relativePath, out string destination) + private static bool TryGetDestination(string root, string relativePath, out string destination) { destination = null; - if (Path.IsPathRooted(relativePath) || relativePath.IndexOf(':') >= 0) + if (string.IsNullOrEmpty(relativePath) || Path.IsPathRooted(relativePath) || relativePath.IndexOf(':') >= 0) return false; - string fullRoot = Path.GetFullPath(_targetFolder); + string fullRoot = Path.GetFullPath(root); if (!fullRoot.EndsWith(Path.DirectorySeparatorChar.ToString())) fullRoot += Path.DirectorySeparatorChar; @@ -425,22 +430,5 @@ private void Log(string text) // pass } } - private string GetRelativePath(string basePath, string fullPath) - { - if (string.IsNullOrEmpty(basePath)) throw new ArgumentNullException(nameof(basePath)); - if (string.IsNullOrEmpty(fullPath)) throw new ArgumentNullException(nameof(fullPath)); - - Uri baseUri = new Uri(basePath.EndsWith(Path.DirectorySeparatorChar.ToString()) ? basePath : basePath + Path.DirectorySeparatorChar); - Uri fullUri = new Uri(fullPath); - - if (baseUri.IsBaseOf(fullUri)) - { - return Uri.UnescapeDataString(baseUri.MakeRelativeUri(fullUri).ToString()); - } - else - { - throw new InvalidOperationException("The fullPath is not a subpath of basePath."); - } - } } } \ No newline at end of file From 4e2b0b5259c114791d1ccf216699b5900dfb5f5b Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:37:46 +0000 Subject: [PATCH 042/202] Build Update and EditHostFile in CI Both are .NET Framework projects that the existing jobs never compiled. --- .github/workflows/ci.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 779a5e7c..519e2f83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,3 +52,17 @@ jobs: - name: Build GUI run: msbuild CDPIUI/CDPIUI.csproj /restore /p:Configuration=Release /p:Platform=x64 /m + + tools: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: microsoft/setup-msbuild@v2 + + - name: Build Update and EditHostFile + shell: pwsh + run: | + msbuild Update/Update.csproj /restore /p:RestorePackagesConfig=true "/p:SolutionDir=$pwd\" /p:Configuration=Release /m + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + msbuild EditHostFile/EditHostFile.csproj /p:Configuration=Release /m From e0e707128ec74b681a891de08cd8721e2a607955 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:38:51 +0000 Subject: [PATCH 043/202] Handle unhandled exceptions in the GUI Exceptions thrown from async void event handlers closed the whole application without writing anything to the log. They are now logged and shown in the standard error dialog, and unobserved task exceptions and fatal domain exceptions are logged too. --- CDPIUI/App.xaml.cs | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/CDPIUI/App.xaml.cs b/CDPIUI/App.xaml.cs index 6b2e69f2..354ddebb 100644 --- a/CDPIUI/App.xaml.cs +++ b/CDPIUI/App.xaml.cs @@ -78,10 +78,12 @@ private sealed class ModalSession public Windows.Foundation.TypedEventHandler ClosedHandler; } private readonly SemaphoreSlim migrationWindowActivationLock = new(1, 1); + private int isUnhandledErrorShown; public App() { this.InitializeComponent(); + RegisterUnhandledExceptionHandlers(); PipeClientService.Instance.MessageReceived += (m) => CommandsHandler.HandleCommand(m); CoreErrorsLookupService.Instance.Init(); @@ -95,6 +97,55 @@ public App() GetReadyFeatures(); } + private void RegisterUnhandledExceptionHandlers() + { + UnhandledException += App_UnhandledException; + AppDomain.CurrentDomain.UnhandledException += (_, e) => + Logger.Instance.CreateErrorLog(nameof(App), $"Fatal unhandled exception: {e.ExceptionObject}"); + TaskScheduler.UnobservedTaskException += (_, e) => + { + Logger.Instance.CreateErrorLog(nameof(App), $"Unobserved task exception: {e.Exception}"); + e.SetObserved(); + }; + } + + private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) + { + Logger.Instance.CreateErrorLog(nameof(App), $"Unhandled exception: {e.Exception?.ToString() ?? e.Message}"); + + // Exceptions from async void event handlers end up here. Keep the application + // running and show the error instead of closing every window without a trace. + e.Handled = true; + ShowUnhandledError(e.Exception); + } + + private async void ShowUnhandledError(Exception exception) + { + if (Interlocked.Exchange(ref isUnhandledErrorShown, 1) != 0) + return; + + try + { + XamlRoot xamlRoot = OpenWindows.LastOrDefault(w => w.Content?.XamlRoot != null)?.Content.XamlRoot; + if (xamlRoot == null) + return; + + string code = exception != null + ? ErrorsHelper.Convertor.GetPrettyErrorCode("APP", exception) + : "APP_UNKNOWN"; + await new Controls.Dialogs.Universal.ErrorContentDialog().ShowErrorDialogAsync( + Localizer.Get().GetLocalizedString("SomethingWentWrong"), code, xamlRoot); + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(App), $"Cannot show unhandled exception: {ex.Message}"); + } + finally + { + Interlocked.Exchange(ref isUnhandledErrorShown, 0); + } + } + private void StoreStateChanged(bool isWorking) { try From 2c1ba58c6e2462a05513782cb04b0c26b29366cb Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:40:20 +0000 Subject: [PATCH 044/202] Save two Windows-1252 source files as UTF-8 GoodCheckWorkPage.xaml.cs and ChangeSiteListContentDialog.xaml.cs were in Windows-1252, so their em and en dashes were compiled as replacement characters and shown as such in the UI. --- .../ComponentSettings/ChangeSiteListContentDialog.xaml.cs | 4 ++-- CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CDPIUI/Controls/Dialogs/ComponentSettings/ChangeSiteListContentDialog.xaml.cs b/CDPIUI/Controls/Dialogs/ComponentSettings/ChangeSiteListContentDialog.xaml.cs index 4554847b..130153bd 100644 --- a/CDPIUI/Controls/Dialogs/ComponentSettings/ChangeSiteListContentDialog.xaml.cs +++ b/CDPIUI/Controls/Dialogs/ComponentSettings/ChangeSiteListContentDialog.xaml.cs @@ -1,4 +1,4 @@ -using CDPIUI.Core; +using CDPIUI.Core; using CDPIUI.Core.Basic; using CDPIUI.Core.Store.Database; using CDPIUI.Helper.Parsers; @@ -105,7 +105,7 @@ private void Init() SiteListModels.Add(new() { Title = Path.GetFileName(file), - Developer = $"{item.ShortName} – {item.Developer}", + Developer = $"{item.ShortName} – {item.Developer}", FileName = file, Size = UnitsParser.FormatSize(FileSystemService.GetFileSize(file, Logger.Instance)) }); diff --git a/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs b/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs index bc63fc93..e01ee711 100644 --- a/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs @@ -1,4 +1,4 @@ -using CDPIUI.Core; +using CDPIUI.Core; using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; @@ -242,7 +242,7 @@ private void CalcSpeed(int current, int all) allSecondsRemaining = etaSecondsCurrent + remainingOpsCount * perOpEstimate; } - string speedText = _speedElementsPerSec > 0 ? $"{_speedElementsPerSec:F3} e/s" : "—"; + string speedText = _speedElementsPerSec > 0 ? $"{_speedElementsPerSec:F3} e/s" : "—"; string etaCurrentText = double.IsInfinity(etaSecondsCurrent) ? localizer.GetLocalizedString("Calculating") : UnitsParser.ConvertMinutesToPrettyText((etaSecondsCurrent / 60.0)); string allTimeText = double.IsInfinity(allSecondsRemaining) ? localizer.GetLocalizedString("Calculating") : UnitsParser.ConvertMinutesToPrettyText((allSecondsRemaining / 60.0)); From 63450ce438e83a342373216669b647f7bae11072 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:41:08 +0000 Subject: [PATCH 045/202] Unsubscribe GoodCheck pages from the process service GoodCheckWorkPage subscribed lambdas to the singleton service on every creation and never removed them, so pages from earlier runs kept updating closed windows and calling Kill when a later run completed. The handlers are now methods that are removed when the page is unloaded or replaced by a new page. CreateViaGoodCheck added another ErrorHappens logger on every start, so each error was logged once per earlier run. --- .../CreateViaGoodCheckPage.xaml.cs | 11 ++- .../GoodCheckWorkPage.xaml.cs | 93 ++++++++++++------- 2 files changed, 69 insertions(+), 35 deletions(-) diff --git a/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs b/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs index 424a6d5b..a9ef4d48 100644 --- a/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs @@ -429,15 +429,18 @@ GoodCheckSitelistButton button in listModels ); - GoodCheckProcessService.Instance.ErrorHappens += (e) => - { - Logger.Instance.CreateErrorLog(nameof(CreateViaGoodCheck), $"{e}"); - }; + GoodCheckProcessService.Instance.ErrorHappens -= LogGoodCheckError; + GoodCheckProcessService.Instance.ErrorHappens += LogGoodCheckError; GoodCheckProcessService.Instance.Start(); } + private static void LogGoodCheckError(string error) + { + Logger.Instance.CreateErrorLog(nameof(CreateViaGoodCheck), error); + } + private void GoBackButton_Click(object sender, RoutedEventArgs e) { switch (_currentState) diff --git a/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs b/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs index e01ee711..e8b9ebfc 100644 --- a/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs @@ -52,6 +52,9 @@ public sealed partial class GoodCheckWorkPage : TemplatePage private ILocalizer localizer = Localizer.Get(); + // The service is a singleton, so only the page that is currently shown may stay subscribed. + private static GoodCheckWorkPage _connectedPage; + public GoodCheckWorkPage() { InitializeComponent(); @@ -59,7 +62,6 @@ public GoodCheckWorkPage() _uiDispatcher = DispatcherQueue.GetForCurrentThread(); TemplateWindow.ToggleLoadingState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Indeterminate); - GoodCheckProcessService.Instance.AllComplete += AllCompletedActions; SiteListProgressText.Text = GoodCheckProcessService.Instance.CurrentSiteList; GoodStrategyCount.Text = GoodCheckProcessService.Instance.CorrectCount.ToString(); @@ -67,6 +69,8 @@ public GoodCheckWorkPage() ConnectHandlers(); + Loaded += (_, _) => ConnectHandlers(); + Unloaded += (_, _) => DisconnectHandlers(); } private void AllCompletedActions(string filepath) @@ -90,42 +94,69 @@ private void AllCompletedActions(string filepath) private void ConnectHandlers() { - GoodCheckProcessService.Instance.CurrentSiteListChanged += (name) => - { - CurrentSiteListText(name); + if (_connectedPage == this) + return; + _connectedPage?.DisconnectHandlers(); + _connectedPage = this; + + var service = GoodCheckProcessService.Instance; + service.AllComplete += AllCompletedActions; + service.CurrentSiteListChanged += OnCurrentSiteListChanged; + service.ProgressChanged += OnProgressChanged; + service.CorrectCountChanged += OnCorrectCountChanged; + service.IncorrectCountChanged += OnIncorrectCountChanged; + } - _lastProgressTime = DateTime.MinValue; - _lastProgressCount = 0; - _speedElementsPerSec = 0.0; - _initialEstimatedSecondsPerOperation = 0.0; + private void DisconnectHandlers() + { + var service = GoodCheckProcessService.Instance; + service.AllComplete -= AllCompletedActions; + service.CurrentSiteListChanged -= OnCurrentSiteListChanged; + service.ProgressChanged -= OnProgressChanged; + service.CorrectCountChanged -= OnCorrectCountChanged; + service.IncorrectCountChanged -= OnIncorrectCountChanged; + + if (_connectedPage == this) + _connectedPage = null; + } - }; - GoodCheckProcessService.Instance.ProgressChanged += (tuple) => - { - int.TryParse(tuple.Item1, out int current); - int.TryParse(tuple.Item2, out int all); - string strategy = tuple.Item3; + private void OnCurrentSiteListChanged(string name) + { + CurrentSiteListText(name); - if (all == 0) - { - SetSiteListProgressText($"ERR%"); - return; - } + _lastProgressTime = DateTime.MinValue; + _lastProgressCount = 0; + _speedElementsPerSec = 0.0; + _initialEstimatedSecondsPerOperation = 0.0; + } - double percent = (double)current / (double)all * 100.0; - CalcSpeed(current, all); + private void OnProgressChanged(Tuple tuple) + { + int.TryParse(tuple.Item1, out int current); + int.TryParse(tuple.Item2, out int all); + string strategy = tuple.Item3; - TemplateWindow.ToggleLoadingState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Normal, current, all); - SetSiteListProgressText($"{percent:F0}% [{current}/{all}]"); - }; - GoodCheckProcessService.Instance.CorrectCountChanged += (count) => + if (all == 0) { - SetCorrectCountText(count.ToString()); - }; - GoodCheckProcessService.Instance.IncorrectCountChanged += (count) => - { - SetIncorrectCountText(count.ToString()); - }; + SetSiteListProgressText($"ERR%"); + return; + } + + double percent = (double)current / (double)all * 100.0; + CalcSpeed(current, all); + + TemplateWindow.ToggleLoadingState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Normal, current, all); + SetSiteListProgressText($"{percent:F0}% [{current}/{all}]"); + } + + private void OnCorrectCountChanged(int count) + { + SetCorrectCountText(count.ToString()); + } + + private void OnIncorrectCountChanged(int count) + { + SetIncorrectCountText(count.ToString()); } From 1ca25c9576509b4e940e21d6cc6c8f3613ef3b1e Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:41:33 +0000 Subject: [PATCH 046/202] Stop preset tests when they are cancelled or the window closes Cancelling a preset test left the component running with the preset that was being tested, and closing the test window did not cancel the test at all, so it kept restarting the component with other presets in the background and then updated the closed window. The component is now stopped on cancellation, closing the window cancels the test, and the window is no longer updated after it is closed. --- CDPIUI/Helper/AddOns/PresetTestHelper.cs | 2 ++ CDPIUI/Windows/ConfigTestWindow.xaml.cs | 27 +++++++++++++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/CDPIUI/Helper/AddOns/PresetTestHelper.cs b/CDPIUI/Helper/AddOns/PresetTestHelper.cs index a79a6fbd..ac8295ae 100644 --- a/CDPIUI/Helper/AddOns/PresetTestHelper.cs +++ b/CDPIUI/Helper/AddOns/PresetTestHelper.cs @@ -431,6 +431,8 @@ public async Task RunAsync( { wasCancelled = true; CancelAllCurls(); + // Do not leave the component running with the preset that was being tested. + try { await processManager.StopProcess(false); } catch { } } finally { diff --git a/CDPIUI/Windows/ConfigTestWindow.xaml.cs b/CDPIUI/Windows/ConfigTestWindow.xaml.cs index f2ba798f..ab66c4da 100644 --- a/CDPIUI/Windows/ConfigTestWindow.xaml.cs +++ b/CDPIUI/Windows/ConfigTestWindow.xaml.cs @@ -32,6 +32,7 @@ public sealed partial class ConfigTestWindow : TemplateWindow private CancellationTokenSource _testCts; private bool _isTesting = false; + private bool _isClosed = false; private string componentIdToTest = string.Empty; public string ComponentIdToTest @@ -75,6 +76,13 @@ public ConfigTestWindow() ComponentComboBox.ItemsSource = Models; ResultsListView.ItemsSource = _resultItems; LoadComponents(); + + // Closing the window must not leave a test switching presets in the background. + Closed += (_, _) => + { + _isClosed = true; + CancelTest(); + }; } private void LoadComponents() @@ -190,7 +198,8 @@ private async void StartTestButton_Click(object sender, RoutedEventArgs e) if (runResult.WasCancelled) AppendLine(new TestLogSegment(localizer.GetLocalizedString("PT_Cancelled"), TestLogColor.Yellow)); - ShowResults(runResult, _lastTestType); + if (!_isClosed) + ShowResults(runResult, _lastTestType); } catch (Exception ex) { @@ -200,8 +209,11 @@ private async void StartTestButton_Click(object sender, RoutedEventArgs e) } finally { - SetTestingUi(false); - HideProgress(); + if (!_isClosed) + { + SetTestingUi(false); + HideProgress(); + } _activeHelper = null; _testCts?.Dispose(); _testCts = null; @@ -209,6 +221,11 @@ private async void StartTestButton_Click(object sender, RoutedEventArgs e) } private void StopTestButton_Click(object sender, RoutedEventArgs e) + { + CancelTest(); + } + + private void CancelTest() { try { @@ -311,7 +328,7 @@ private void ClearResults() private void UpdateProgress(PresetTestProgress p) { - if (p == null) return; + if (p == null || _isClosed) return; ProgressPanel.Visibility = Visibility.Visible; TestProgressBar.Value = p.Percent; @@ -379,7 +396,7 @@ private void ClearOutput() private void AppendLine(List segments) { - if (segments == null) return; + if (segments == null || _isClosed) return; foreach (TestLogSegment segment in segments) { OutputParagraph.Inlines.Add(new Run From 3fe6ee583bf995ec62ecac042982cf0876339372 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:46:08 +0000 Subject: [PATCH 047/202] Clean up running components, drivers and autorun on uninstall Uninstalling the MSI package left the tray and the components running with their WinDivert driver loaded, the system proxy pointing to a stopped component, the WinDivert service registered with a path to deleted files, and the CDPIUI_Autostart task that runs a missing executable at every logon. The package now runs CDPIUI_TrayIcon.exe --uninstall-cleanup as SYSTEM before removing files on a full uninstall (not on upgrades). It signals a global event that every running tray listens to; the tray then exits as from its menu, which stops the components and restores the proxy settings. After the trays exit, the cleanup ends the processes still running from the installation or a CDPIUI user data directory, stops and deletes WinDivert services whose driver is in those directories, and deletes the autorun task. Drivers and processes of other software are not touched. --- .../Filesystem/ApplicationPathMatcher.cs | 41 +++++ .../Shared/ApplicationPathMatcherTests.cs | 39 +++++ .../Helper/Settings/AutoStartManager.cs | 2 +- CDPIUI.TrayIcon/Helper/UninstallHelper.cs | 160 ++++++++++++++++++ CDPIUI.TrayIcon/Program.cs | 7 + NewSetup/NewSetupFiles.wxs | 2 +- NewSetup/Product.wxs | 4 + 7 files changed, 253 insertions(+), 2 deletions(-) create mode 100644 CDPIUI.Shared/Basic/Filesystem/ApplicationPathMatcher.cs create mode 100644 CDPIUI.Tests/Shared/ApplicationPathMatcherTests.cs create mode 100644 CDPIUI.TrayIcon/Helper/UninstallHelper.cs diff --git a/CDPIUI.Shared/Basic/Filesystem/ApplicationPathMatcher.cs b/CDPIUI.Shared/Basic/Filesystem/ApplicationPathMatcher.cs new file mode 100644 index 00000000..ee8f8e24 --- /dev/null +++ b/CDPIUI.Shared/Basic/Filesystem/ApplicationPathMatcher.cs @@ -0,0 +1,41 @@ +using System; + +namespace CDPIUI.Shared.Basic.Filesystem +{ + /// + /// Decides which processes and drivers belong to the application when it is uninstalled. + /// + public static class ApplicationPathMatcher + { + // Data directory of MSI builds for every user profile. + private const string UserDataSegment = @"\AppData\Local\CDPIUI\"; + + /// + /// Converts a process path or a service ImagePath to a plain Windows path + /// + public static string Normalize(string path) + { + string result = path.Trim().Trim('"').Replace('/', '\\'); + if (result.StartsWith(@"\??\", StringComparison.Ordinal)) + result = result.Substring(4); + return result; + } + + /// + /// Checks whether a file is inside the installation directory or a user data directory of the application + /// + /// Process path or service ImagePath + /// Installation directory + public static bool BelongsToApplication(string? path, string installDirectory) + { + if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(installDirectory)) + return false; + + string normalized = Normalize(path!); + string root = Normalize(installDirectory).TrimEnd('\\') + "\\"; + + return normalized.StartsWith(root, StringComparison.OrdinalIgnoreCase) || + normalized.IndexOf(UserDataSegment, StringComparison.OrdinalIgnoreCase) >= 0; + } + } +} diff --git a/CDPIUI.Tests/Shared/ApplicationPathMatcherTests.cs b/CDPIUI.Tests/Shared/ApplicationPathMatcherTests.cs new file mode 100644 index 00000000..67dae374 --- /dev/null +++ b/CDPIUI.Tests/Shared/ApplicationPathMatcherTests.cs @@ -0,0 +1,39 @@ +using CDPIUI.Shared.Basic.Filesystem; + +namespace CDPIUI.Tests.Shared; + +public class ApplicationPathMatcherTests +{ + private const string InstallDirectory = @"C:\Program Files\Storik4\CDPI UI"; + + [Theory] + [InlineData(@"C:\Program Files\Storik4\CDPI UI\CDPIUI_TrayIcon.exe")] + [InlineData(@"c:\program files\storik4\cdpi ui\Store\Items\CSZTBN012\bin\winws.exe")] + [InlineData(@"\??\C:\Users\user\AppData\Local\CDPIUI\Store\Items\CSZTBN012\bin\WinDivert64.sys")] + [InlineData("\"C:\\Users\\user\\AppData\\Local\\CDPIUI\\Store\\Items\\CSGIVS036\\x86_64\\goodbyedpi.exe\"")] + [InlineData(@"C:/Users/user/AppData/Local/CDPIUI/Store/Items/CSBIHA024/ciadpi.exe")] + public void ApplicationFilesMatch(string path) + { + Assert.True(ApplicationPathMatcher.BelongsToApplication(path, InstallDirectory)); + } + + [Theory] + [InlineData(@"C:\Program Files\Storik4\CDPI UI Other\winws.exe")] + [InlineData(@"C:\zapret\bin\winws.exe")] + [InlineData(@"\??\C:\zapret\bin\WinDivert64.sys")] + [InlineData(@"C:\Users\user\AppData\Local\CDPIUI2\winws.exe")] + [InlineData(@"\SystemRoot\System32\drivers\WinDivert.sys")] + [InlineData("")] + [InlineData(null)] + public void OtherFilesDoNotMatch(string? path) + { + Assert.False(ApplicationPathMatcher.BelongsToApplication(path, InstallDirectory)); + } + + [Fact] + public void InstallDirectoryWithTrailingSeparatorMatches() + { + Assert.True(ApplicationPathMatcher.BelongsToApplication( + @"C:\Program Files\Storik4\CDPI UI\CDPIUI.exe", InstallDirectory + "\\")); + } +} diff --git a/CDPIUI.TrayIcon/Helper/Settings/AutoStartManager.cs b/CDPIUI.TrayIcon/Helper/Settings/AutoStartManager.cs index c3293c5e..415cd0d0 100644 --- a/CDPIUI.TrayIcon/Helper/Settings/AutoStartManager.cs +++ b/CDPIUI.TrayIcon/Helper/Settings/AutoStartManager.cs @@ -11,7 +11,7 @@ namespace CDPIUI.TrayIcon.Helper { public static class AutoStartManager { - private const string TaskName = "CDPIUI_Autostart"; + internal const string TaskName = "CDPIUI_Autostart"; public static bool AddToAutorun() { diff --git a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs new file mode 100644 index 00000000..6c91856c --- /dev/null +++ b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs @@ -0,0 +1,160 @@ +using CDPIUI.Shared.Basic.Filesystem; +using CDPIUI.TrayIcon.Helper.Basic; +using Microsoft.Win32; +using Microsoft.Win32.TaskScheduler; +using System.Diagnostics; + +namespace CDPIUI.TrayIcon.Helper +{ + /// + /// Shuts the application down before the MSI package removes its files + /// + public static class UninstallHelper + { + public const string CleanupArgument = "--uninstall-cleanup"; + + // Set by the uninstaller; every running tray then exits as if Exit was chosen in its menu, + // which stops the components and restores the system proxy settings. + private const string ShutdownEventName = @"Global\CDPIUI_TrayShutdown"; + private static readonly TimeSpan TrayExitTimeout = TimeSpan.FromSeconds(20); + + private static EventWaitHandle? _shutdownEvent; + private static RegisteredWaitHandle? _shutdownWait; + + public static void ListenForShutdown(Control invoker, System.Action exit) + { + try + { + _shutdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, ShutdownEventName); + _shutdownWait = ThreadPool.RegisterWaitForSingleObject(_shutdownEvent, (_, _) => + { + try { invoker.BeginInvoke(exit); } catch { } + }, null, Timeout.Infinite, executeOnlyOnce: true); + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(UninstallHelper), $"Cannot listen for uninstall: {ex.Message}"); + } + } + + /// + /// Runs from the uninstaller as SYSTEM. Does not touch settings or logs, because they would be + /// created in the system profile. + /// + public static void Cleanup() + { + string installDirectory = AppContext.BaseDirectory; + int selfId = Environment.ProcessId; + + EventWaitHandle? shutdownEvent = null; + try + { + if (EventWaitHandle.TryOpenExisting(ShutdownEventName, out shutdownEvent)) + { + shutdownEvent.Set(); + WaitForTrayExit(selfId); + } + + KillApplicationProcesses(installDirectory, selfId); + RemoveDrivers(installDirectory); + RemoveAutorunTask(); + } + finally + { + try { shutdownEvent?.Reset(); } catch { } + shutdownEvent?.Dispose(); + } + } + + private static void WaitForTrayExit(int selfId) + { + var stopwatch = Stopwatch.StartNew(); + string trayName = Path.GetFileNameWithoutExtension(Environment.ProcessPath) ?? "CDPIUI_TrayIcon"; + while (stopwatch.Elapsed < TrayExitTimeout) + { + Process[] trays = Process.GetProcessesByName(trayName); + bool running = trays.Any(p => p.Id != selfId); + foreach (var p in trays) p.Dispose(); + if (!running) return; + + Thread.Sleep(250); + } + } + + private static void KillApplicationProcesses(string installDirectory, int selfId) + { + foreach (Process process in Process.GetProcesses()) + { + using (process) + { + if (process.Id == selfId) + continue; + + string? path; + try { path = process.MainModule?.FileName; } + catch { continue; } + + if (!ApplicationPathMatcher.BelongsToApplication(path, installDirectory)) + continue; + + try + { + process.Kill(); + process.WaitForExit(5000); + } + catch { } + } + } + } + + private static void RemoveDrivers(string installDirectory) + { + using RegistryKey? services = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services"); + if (services == null) + return; + + foreach (string name in services.GetSubKeyNames()) + { + if (!name.StartsWith("WinDivert", StringComparison.OrdinalIgnoreCase)) + continue; + + string? imagePath; + using (RegistryKey? service = services.OpenSubKey(name)) + { + imagePath = service?.GetValue("ImagePath") as string; + } + + // A driver installed by other software stays. + if (!ApplicationPathMatcher.BelongsToApplication(imagePath, installDirectory)) + continue; + + RunServiceControl($"stop \"{name}\""); + RunServiceControl($"delete \"{name}\""); + } + } + + private static void RunServiceControl(string arguments) + { + try + { + using var process = Process.Start(new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "sc.exe"), arguments) + { + UseShellExecute = false, + CreateNoWindow = true, + }); + process?.WaitForExit(15000); + } + catch { } + } + + private static void RemoveAutorunTask() + { + try + { + using var taskService = new TaskService(); + taskService.RootFolder.DeleteTask(AutoStartManager.TaskName, false); + } + catch { } + } + } +} diff --git a/CDPIUI.TrayIcon/Program.cs b/CDPIUI.TrayIcon/Program.cs index ddd5189c..b9383485 100644 --- a/CDPIUI.TrayIcon/Program.cs +++ b/CDPIUI.TrayIcon/Program.cs @@ -19,6 +19,12 @@ class Programm [STAThread] static void Main(string[] args) { + if (args.Contains(UninstallHelper.CleanupArgument)) + { + UninstallHelper.Cleanup(); + return; + } + AppDomain.CurrentDomain.UnhandledException += (_, e) => Logger.Instance.CreateDebugLog("Startup", $"Unhandled exception; terminating={e.IsTerminating}: {e.ExceptionObject}"); @@ -106,6 +112,7 @@ public TrayApplicationContext(bool runStartupActions = false) _trayForm = new EmptyForm(); _trayForm.AddIcon(notify: true); + UninstallHelper.ListenForShutdown(_trayForm, Application.Exit); try { ConditionalLaunchEngine.Instance.Start(_trayForm); diff --git a/NewSetup/NewSetupFiles.wxs b/NewSetup/NewSetupFiles.wxs index 195eed3f..3ecc3f18 100644 --- a/NewSetup/NewSetupFiles.wxs +++ b/NewSetup/NewSetupFiles.wxs @@ -162,7 +162,7 @@ - + diff --git a/NewSetup/Product.wxs b/NewSetup/Product.wxs index e46fde06..707fde59 100644 --- a/NewSetup/Product.wxs +++ b/NewSetup/Product.wxs @@ -34,8 +34,12 @@ + + + \ No newline at end of file From 9f67545fc662bca5ad3c1d5aa4b3f1c5479e8239 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:46:29 +0000 Subject: [PATCH 048/202] Build Update without strong naming in CI Its key file is not in the repository. --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 519e2f83..b82703bb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,6 +63,7 @@ jobs: - name: Build Update and EditHostFile shell: pwsh run: | - msbuild Update/Update.csproj /restore /p:RestorePackagesConfig=true "/p:SolutionDir=$pwd\" /p:Configuration=Release /m + # The strong name key is not in the repository. + msbuild Update/Update.csproj /restore /p:RestorePackagesConfig=true "/p:SolutionDir=$pwd\" /p:Configuration=Release /p:SignAssembly=false /m if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } msbuild EditHostFile/EditHostFile.csproj /p:Configuration=Release /m From 91d699e228de0ef95c4a28848d54afefd5a9122b Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:47:41 +0000 Subject: [PATCH 049/202] Show preset arguments before importing Neither the import wizard nor the shared preset dialog showed what a preset starts the component with, although testing or adding it runs those arguments. Both now show the startup string as written in the preset, without expanding variables or running its scripts. --- CDPIUI/Strings/en-us/Resources.resw | 3 +++ CDPIUI/Strings/ru/Resources.resw | 3 +++ CDPIUI/ViewModels/ConfigImportPresetViewModel.cs | 9 +++++++++ CDPIUI/Views/ConfigImportUtil/MainPage.xaml | 16 ++++++++++++++++ .../Messages/ConfigShareImportDialog.xaml | 13 +++++++++++++ .../Messages/ConfigShareImportDialog.xaml.cs | 9 +++++++++ 6 files changed, 53 insertions(+) diff --git a/CDPIUI/Strings/en-us/Resources.resw b/CDPIUI/Strings/en-us/Resources.resw index 6395c4fd..dd635861 100644 --- a/CDPIUI/Strings/en-us/Resources.resw +++ b/CDPIUI/Strings/en-us/Resources.resw @@ -6169,4 +6169,7 @@ By enabling this setting, you acknowledge that you have read this information. Connect Telegram to proxy + + Arguments + \ No newline at end of file diff --git a/CDPIUI/Strings/ru/Resources.resw b/CDPIUI/Strings/ru/Resources.resw index 5cfb9372..aaa9887d 100644 --- a/CDPIUI/Strings/ru/Resources.resw +++ b/CDPIUI/Strings/ru/Resources.resw @@ -6172,4 +6172,7 @@ https://discord.com/app Подключить Telegram к прокси + + Аргументы + \ No newline at end of file diff --git a/CDPIUI/ViewModels/ConfigImportPresetViewModel.cs b/CDPIUI/ViewModels/ConfigImportPresetViewModel.cs index 51fa8323..19125703 100644 --- a/CDPIUI/ViewModels/ConfigImportPresetViewModel.cs +++ b/CDPIUI/ViewModels/ConfigImportPresetViewModel.cs @@ -50,6 +50,15 @@ public ConfigImportPresetViewModel( public string FileName => Path.GetFileName(Result.SourcePath); + // Shown as written in the preset, without expanding variables or running scripts, + // so the user sees what the component will be started with before testing or saving it. + public string Arguments => Result.Config?.startup_string ?? string.Empty; + + public string ArgumentsHeader => localizer.GetLocalizedString("ConfigImportArguments"); + + public Visibility ArgumentsVisibility => + string.IsNullOrWhiteSpace(Arguments) ? Visibility.Collapsed : Visibility.Visible; + public IReadOnlyCollection MissingFileResolutions => missingFileResolutions.Values; diff --git a/CDPIUI/Views/ConfigImportUtil/MainPage.xaml b/CDPIUI/Views/ConfigImportUtil/MainPage.xaml index b7fa14f0..9f3517df 100644 --- a/CDPIUI/Views/ConfigImportUtil/MainPage.xaml +++ b/CDPIUI/Views/ConfigImportUtil/MainPage.xaml @@ -245,6 +245,22 @@ Grid.Column="2"/> + + + + + + + + + + + + + + + + + + diff --git a/CDPIUI/Windows/Messages/ConfigShareImportDialog.xaml.cs b/CDPIUI/Windows/Messages/ConfigShareImportDialog.xaml.cs index 54b02788..9ba8e794 100644 --- a/CDPIUI/Windows/Messages/ConfigShareImportDialog.xaml.cs +++ b/CDPIUI/Windows/Messages/ConfigShareImportDialog.xaml.cs @@ -89,6 +89,15 @@ public async Task SetFileAsync(string path) DeveloperName.Text = string.Format(localizer.GetLocalizedString("StoreSmallDeveloperText"), package.Manifest.Developer); + // The raw startup string, so the user can check what the preset runs before adding it. + string arguments = package.Config?.startup_string; + if (!string.IsNullOrWhiteSpace(arguments)) + { + ArgumentsHeader.Text = localizer.GetLocalizedString("ConfigImportArguments"); + PresetArguments.Text = arguments; + ArgumentsPanel.Visibility = Visibility.Visible; + } + KitName.Text = string.Format(localizer.GetLocalizedString("ConfigShareKitBy"), package.Manifest.Developer); var packs = service.GetDestinationPacks().ToList(); foreach (var pack in packs) From ebe554b214e8d44eb85c7640573431f0e5546fc4 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:51:09 +0000 Subject: [PATCH 050/202] Restrict paths the tray accepts from the UI The elevated tray ran any executable, MSI package or update archive path it received over the pipe, and granted Everyone full control over any directory it was asked to fix. With the default per-machine installation that let any local account replace the component executables that the tray then starts elevated. The tray now accepts these paths only inside the installation directory or the CDPIUI data directory of its user, and only if no directory below that root, or the file itself, is a symbolic link or junction. Access fixes are limited to the store directories and grant Modify to the tray user instead of full control to Everyone. A rejected path is logged and reported to the UI as a failed operation. Access fixes also no longer report failure after a success. --- .../Basic/Filesystem/TrustedPathValidator.cs | 71 ++++++++++++++++ .../Shared/TrustedPathValidatorTests.cs | 81 +++++++++++++++++++ .../Helper/Basic/CommandsHandler.cs | 4 + CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs | 3 + .../Helper/GoodCheckProcessHelper.cs | 6 ++ CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs | 3 + CDPIUI.TrayIcon/Helper/TrustedPaths.cs | 36 +++++++++ CDPIUI.TrayIcon/Helper/Utils.cs | 23 +++++- 8 files changed, 224 insertions(+), 3 deletions(-) create mode 100644 CDPIUI.Shared/Basic/Filesystem/TrustedPathValidator.cs create mode 100644 CDPIUI.Tests/Shared/TrustedPathValidatorTests.cs create mode 100644 CDPIUI.TrayIcon/Helper/TrustedPaths.cs diff --git a/CDPIUI.Shared/Basic/Filesystem/TrustedPathValidator.cs b/CDPIUI.Shared/Basic/Filesystem/TrustedPathValidator.cs new file mode 100644 index 00000000..a77d7e1a --- /dev/null +++ b/CDPIUI.Shared/Basic/Filesystem/TrustedPathValidator.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace CDPIUI.Shared.Basic.Filesystem +{ + /// + /// Checks paths that an elevated process receives from a less trusted one + /// + public static class TrustedPathValidator + { + /// + /// Checks that a path is inside one of the roots and that no directory between the root + /// and the path, and not the path itself, is a symbolic link or a junction + /// + /// Path to check + /// Allowed root directories + public static bool IsInside(string? path, IEnumerable roots) + { + if (string.IsNullOrWhiteSpace(path)) + return false; + + string fullPath; + try { fullPath = Path.GetFullPath(path); } + catch { return false; } + + foreach (string? root in roots) + { + if (string.IsNullOrWhiteSpace(root)) + continue; + + string fullRoot; + try { fullRoot = WithSeparator(Path.GetFullPath(root)); } + catch { continue; } + + if (!fullPath.StartsWith(fullRoot, StringComparison.OrdinalIgnoreCase)) + continue; + + return !HasLinkBelowRoot(fullRoot, fullPath); + } + + return false; + } + + private static bool HasLinkBelowRoot(string fullRoot, string fullPath) + { + string current = fullRoot.TrimEnd(Path.DirectorySeparatorChar); + string[] parts = fullPath.Substring(fullRoot.Length) + .Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); + + foreach (string part in parts) + { + current = Path.Combine(current, part); + FileAttributes attributes; + try { attributes = File.GetAttributes(current); } + catch (FileNotFoundException) { return false; } + catch (DirectoryNotFoundException) { return false; } + catch { return true; } + + if ((attributes & FileAttributes.ReparsePoint) != 0) + return true; + } + return false; + } + + private static string WithSeparator(string path) => + path.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) + ? path + : path + Path.DirectorySeparatorChar; + } +} diff --git a/CDPIUI.Tests/Shared/TrustedPathValidatorTests.cs b/CDPIUI.Tests/Shared/TrustedPathValidatorTests.cs new file mode 100644 index 00000000..ca7538d8 --- /dev/null +++ b/CDPIUI.Tests/Shared/TrustedPathValidatorTests.cs @@ -0,0 +1,81 @@ +using CDPIUI.Shared.Basic.Filesystem; + +namespace CDPIUI.Tests.Shared; + +public sealed class TrustedPathValidatorTests : IDisposable +{ + private readonly string root = Path.Combine(Path.GetTempPath(), "cdpiui-trusted-" + Guid.NewGuid().ToString("N")); + private readonly string outside = Path.Combine(Path.GetTempPath(), "cdpiui-outside-" + Guid.NewGuid().ToString("N")); + + public TrustedPathValidatorTests() + { + Directory.CreateDirectory(Path.Combine(root, "Store", "Items", "CSZTBN012")); + File.WriteAllText(Path.Combine(root, "Store", "Items", "CSZTBN012", "winws.exe"), ""); + Directory.CreateDirectory(outside); + File.WriteAllText(Path.Combine(outside, "tool.exe"), ""); + } + + public void Dispose() + { + Directory.Delete(root, true); + Directory.Delete(outside, true); + } + + [Fact] + public void FileInsideRootIsAllowed() + { + Assert.True(TrustedPathValidator.IsInside(Path.Combine(root, "Store", "Items", "CSZTBN012", "winws.exe"), [root])); + } + + [Fact] + public void MissingFileInsideRootIsAllowed() + { + Assert.True(TrustedPathValidator.IsInside(Path.Combine(root, "Store", "Items", "new", "patch.msi"), [root])); + } + + [Fact] + public void FileOutsideRootsIsRejected() + { + Assert.False(TrustedPathValidator.IsInside(Path.Combine(outside, "tool.exe"), [root, null, ""])); + } + + [Fact] + public void ParentTraversalIsRejected() + { + string path = Path.Combine(root, "Store", "..", "..", Path.GetFileName(outside), "tool.exe"); + Assert.False(TrustedPathValidator.IsInside(path, [root])); + } + + [Fact] + public void SiblingWithSamePrefixIsRejected() + { + Assert.False(TrustedPathValidator.IsInside(root + "-other" + Path.DirectorySeparatorChar + "tool.exe", [root])); + } + + [Fact] + public void LinkedDirectoryInsideRootIsRejected() + { + string link = Path.Combine(root, "Store", "link"); + Directory.CreateSymbolicLink(link, outside); + + Assert.False(TrustedPathValidator.IsInside(Path.Combine(link, "tool.exe"), [root])); + } + + [Fact] + public void LinkedFileInsideRootIsRejected() + { + string link = Path.Combine(root, "Store", "tool.exe"); + File.CreateSymbolicLink(link, Path.Combine(outside, "tool.exe")); + + Assert.False(TrustedPathValidator.IsInside(link, [root])); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void EmptyPathIsRejected(string? path) + { + Assert.False(TrustedPathValidator.IsInside(path, [root])); + } +} diff --git a/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs b/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs index b6cc7437..54c9db15 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/CommandsHandler.cs @@ -139,6 +139,10 @@ private static async Task CaptureHelpOutputAsync(CONPTYMessageModel model) "The component executable was not found.", executablePath); } + if (!TrustedPaths.IsAllowed(executablePath, "help output capture")) + { + throw new UnauthorizedAccessException("The executable is outside the application directories."); + } ConPTYCaptureResult result = await ConPTYHelper.CaptureProcessOutputAsync( executablePath, diff --git a/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs index 86702e3c..bf1c2390 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/ConPTYHelper.cs @@ -363,6 +363,9 @@ public async void RunProcessWithConPTY(string exePath, string args, string worki try { + if (!TrustedPaths.IsAllowed(exePath, "process start")) + throw new UnauthorizedAccessException("The executable is outside the application directories."); + CreatePipe(out hInputRead, out hInputWrite, false); CreatePipe(out hOutputRead, out hOutputWrite, false); diff --git a/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs b/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs index 52963179..7bd8d7ed 100644 --- a/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs +++ b/CDPIUI.TrayIcon/Helper/GoodCheckProcessHelper.cs @@ -45,6 +45,12 @@ public GoodCheckProcessHelper() public async Task StartAsync(string executable, string args, string operationId) { + if (!TrustedPaths.IsAllowed(executable, "GoodCheck start")) + { + HandleProcessException("ERR_UNABLE_START_PROCESS", operationId); + return false; + } + await TasksHelper.Instance.StopAllTasks(); _cancellationTokenSource = new(); diff --git a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs index 65d100d0..f13bd812 100644 --- a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs +++ b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs @@ -160,6 +160,9 @@ private async Task ProcessMsi(string operationId, string filePath) { try { + if (!TrustedPaths.IsAllowed(filePath, "package installation")) + throw new UnauthorizedAccessException("The package is outside the application directories."); + _ = PipeHelper .SendMsiInstallationPacket(MSIInstallationMessageIds.SetOperationStatus, operationId, MsiState.Installing); diff --git a/CDPIUI.TrayIcon/Helper/TrustedPaths.cs b/CDPIUI.TrayIcon/Helper/TrustedPaths.cs new file mode 100644 index 00000000..fe9cb459 --- /dev/null +++ b/CDPIUI.TrayIcon/Helper/TrustedPaths.cs @@ -0,0 +1,36 @@ +using CDPIUI.Shared.Basic.Filesystem; +using CDPIUI.TrayIcon.Helper.Basic; + +namespace CDPIUI.TrayIcon.Helper +{ + /// + /// Limits the files that the UI may ask the elevated tray to run, install or change access to + /// + public static class TrustedPaths + { + // The installation directory and the data directory of MSI builds for the tray user. + private static IEnumerable Roots => + [ + Utils.GetDataDirectory(), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CDPIUI"), + ]; + + public static bool IsAllowed(string? path, string operation) + { + if (TrustedPathValidator.IsInside(path, Roots)) + return true; + + Logger.Instance.CreateWarningLog(nameof(TrustedPaths), $"Rejected {operation} for \"{path}\": the path is outside the application directories"); + return false; + } + + public static bool IsInStore(string? path, string operation) + { + if (TrustedPathValidator.IsInside(path, Roots.Select(root => Path.Combine(root, "Store")))) + return true; + + Logger.Instance.CreateWarningLog(nameof(TrustedPaths), $"Rejected {operation} for \"{path}\": the path is outside the store directory"); + return false; + } + } +} diff --git a/CDPIUI.TrayIcon/Helper/Utils.cs b/CDPIUI.TrayIcon/Helper/Utils.cs index d7f51575..e8d2c1b3 100644 --- a/CDPIUI.TrayIcon/Helper/Utils.cs +++ b/CDPIUI.TrayIcon/Helper/Utils.cs @@ -56,6 +56,12 @@ public static string GetSettingsFile() public static void StartUpdate(string targetFile) { + if (!TrustedPaths.IsAllowed(targetFile, "application update")) + { + NotifyHelper.ShowMessage("CDPI UI", LocaleHelper.GetLocaleString("UpdateFailure"), "UPDATE:OPEN_LOG"); + return; + } + if (Path.GetExtension(targetFile).ToLower() == ".msi") { RunHelper.Run("msiexec.exe", $"/i \"{targetFile}\" /qn+"); @@ -88,6 +94,12 @@ public static float GetScalingFactorForMainDisplay() public static async void GrantAccess(string file, bool conptySignal) { + if (!TrustedPaths.IsInStore(file, "access change")) + { + if (conptySignal) await PipeHelper.SendGrantAcessPacket(false); + return; + } + try { bool exists = System.IO.Directory.Exists(file); @@ -97,17 +109,22 @@ public static async void GrantAccess(string file, bool conptySignal) } DirectoryInfo dInfo = new DirectoryInfo(file); DirectorySecurity dSecurity = dInfo.GetAccessControl(); + // Only the user the tray runs for gets write access: these directories hold + // the executables that the tray starts elevated. + SecurityIdentifier user = WindowsIdentity.GetCurrent().User + ?? throw new InvalidOperationException("Cannot get the current user."); dSecurity.AddAccessRule( new FileSystemAccessRule( - new SecurityIdentifier(WellKnownSidType.WorldSid, null), - FileSystemRights.FullControl, + user, + FileSystemRights.Modify, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, - PropagationFlags.NoPropagateInherit, + PropagationFlags.None, AccessControlType.Allow ) ); dInfo.SetAccessControl(dSecurity); if (conptySignal) await PipeHelper.SendGrantAcessPacket(true); + return; } catch (Exception ex) { From 952edaad04f31be0dbfab170a8fc9cb787416455 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:51:46 +0000 Subject: [PATCH 051/202] Accept the desktop user's data directory in the tray path check When the tray is elevated with another account, the UI and its components use the data directory of the desktop user, not of the tray user. --- CDPIUI.TrayIcon/Helper/TrustedPaths.cs | 30 +++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/TrustedPaths.cs b/CDPIUI.TrayIcon/Helper/TrustedPaths.cs index fe9cb459..19d46c14 100644 --- a/CDPIUI.TrayIcon/Helper/TrustedPaths.cs +++ b/CDPIUI.TrayIcon/Helper/TrustedPaths.cs @@ -1,5 +1,6 @@ using CDPIUI.Shared.Basic.Filesystem; using CDPIUI.TrayIcon.Helper.Basic; +using Microsoft.Win32; namespace CDPIUI.TrayIcon.Helper { @@ -8,13 +9,36 @@ namespace CDPIUI.TrayIcon.Helper /// public static class TrustedPaths { - // The installation directory and the data directory of MSI builds for the tray user. - private static IEnumerable Roots => + // The installation directory and the data directory of MSI builds for the tray user and, + // when the tray was elevated with another account, for the desktop user that runs the UI. + private static IEnumerable Roots => [ Utils.GetDataDirectory(), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CDPIUI"), + GetDesktopUserDataDirectory(), ]; + private static string? GetDesktopUserDataDirectory() + { + try + { + var sid = PipeAccessPolicy.GetDesktopUserSid(); + if (sid == null) + return null; + + using RegistryKey? profile = Registry.LocalMachine.OpenSubKey( + $@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid.Value}"); + if (profile?.GetValue("ProfileImagePath") is not string profilePath) + return null; + + return Path.Combine(Environment.ExpandEnvironmentVariables(profilePath), "AppData", "Local", "CDPIUI"); + } + catch + { + return null; + } + } + public static bool IsAllowed(string? path, string operation) { if (TrustedPathValidator.IsInside(path, Roots)) @@ -26,7 +50,7 @@ public static bool IsAllowed(string? path, string operation) public static bool IsInStore(string? path, string operation) { - if (TrustedPathValidator.IsInside(path, Roots.Select(root => Path.Combine(root, "Store")))) + if (TrustedPathValidator.IsInside(path, Roots.Select(root => root == null ? null : Path.Combine(root, "Store")))) return true; Logger.Instance.CreateWarningLog(nameof(TrustedPaths), $"Rejected {operation} for \"{path}\": the path is outside the store directory"); From 63e7a09fba2b571daef4ef837b03345bc052f179 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:29:27 +0000 Subject: [PATCH 052/202] Keep later hosts file changes when recovering /recover copied the backup taken before /add over the hosts file, which dropped every change made since then by VPN clients, Docker or the user, and failed when there was no backup. It now removes only the block added by the application and deletes the backup. Comment lines of the added block are no longer skipped as duplicates. --- EditHostFile/Program.cs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/EditHostFile/Program.cs b/EditHostFile/Program.cs index bdabc80e..66c52617 100644 --- a/EditHostFile/Program.cs +++ b/EditHostFile/Program.cs @@ -144,12 +144,14 @@ private static void CreateBackup(string path, HostsText content) private static void RestoreBackup(string path) { - Log($"Restoring backup for \"{path}\" in \"{path}.bak\""); - string backup = $"{path}.bak"; - if (!File.Exists(backup)) throw new FileNotFoundException("Backup not found", backup); + // The backup is the file as it was before /add without the added block. Copying it back + // would also drop every change made to the hosts file since then (VPN clients, Docker, + // manual edits), so only the added block is removed and the backup is discarded. + Log($"Restoring \"{path}\" to its state without added lines"); + RemoveAddedLines(path); - Write(path, Read(backup)); - File.Delete(backup); + string backup = $"{path}.bak"; + if (File.Exists(backup)) File.Delete(backup); } private static string RemoveBlock(string text) @@ -197,7 +199,8 @@ private static void AddNewLines(string path) } foreach (string line in SplitLines(resource)) { - if (line.Length == 0 || !lines.Contains(line)) + // Blank lines and comments keep the block readable and are always added. + if (line.Length == 0 || line.StartsWith("#") || !lines.Contains(line)) { builder.Append(line).Append(content.NewLine); } From 5d31bdd45661c1ea9f7ee5b3f984430ae05cffe8 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:30:06 +0000 Subject: [PATCH 053/202] Remove the hosts block and runtime files on uninstall, link the MSI version The uninstall cleanup now also removes the block the application added to the hosts file, so its domains are no longer redirected after the program is gone, and deletes the logs, update staging and backup folders and update.log from the installation directory, which the package does not own and therefore left behind. The package version is bound to the file version of CDPIUI.exe instead of a separate default that drifted from the application version, and same-version upgrades are allowed because Windows Installer ignores the fourth version field. The application is launched after installation only on a fresh install, not on repair. The undocumented InstallPrivileges and AdminImage properties had no effect and are removed. --- CDPIUI.TrayIcon/Helper/UninstallHelper.cs | 43 +++++++++++++++++++++++ NewSetup/NewSetupFiles.wxs | 2 +- NewSetup/Product.wxs | 11 +++--- 3 files changed, 49 insertions(+), 7 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs index 6c91856c..b6820926 100644 --- a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs +++ b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs @@ -58,6 +58,8 @@ public static void Cleanup() KillApplicationProcesses(installDirectory, selfId); RemoveDrivers(installDirectory); RemoveAutorunTask(); + RemoveHostsBlock(installDirectory); + RemoveRuntimeFiles(installDirectory); } finally { @@ -147,6 +149,47 @@ private static void RunServiceControl(string arguments) catch { } } + private static void RemoveHostsBlock(string installDirectory) + { + string editor = Path.Combine(installDirectory, "EditHostFile.exe"); + if (!File.Exists(editor)) + return; + + try + { + using var process = Process.Start(new ProcessStartInfo(editor, "/remove") + { + UseShellExecute = false, + CreateNoWindow = true, + }); + process?.WaitForExit(15000); + } + catch { } + } + + // Files the application creates next to the installed ones; the package does not know them, + // so the installation directory would otherwise stay behind. + private static readonly string[] RuntimeDirectories = ["Logs", ".update-staging", ".update-backup", ".old"]; + private static readonly string[] RuntimeFiles = ["update.log"]; + + private static void RemoveRuntimeFiles(string installDirectory) + { + foreach (string name in RuntimeDirectories) + { + try + { + string path = Path.Combine(installDirectory, name); + if (Directory.Exists(path)) Directory.Delete(path, true); + } + catch { } + } + foreach (string name in RuntimeFiles) + { + try { File.Delete(Path.Combine(installDirectory, name)); } + catch { } + } + } + private static void RemoveAutorunTask() { try diff --git a/NewSetup/NewSetupFiles.wxs b/NewSetup/NewSetupFiles.wxs index 3ecc3f18..4b14ba89 100644 --- a/NewSetup/NewSetupFiles.wxs +++ b/NewSetup/NewSetupFiles.wxs @@ -177,7 +177,7 @@ - + diff --git a/NewSetup/Product.wxs b/NewSetup/Product.wxs index 707fde59..5183abe3 100644 --- a/NewSetup/Product.wxs +++ b/NewSetup/Product.wxs @@ -8,11 +8,12 @@ The Product@Id attribute (ProductCode Property) will be a random GUID for each build. This is to support "Major Upgrades" where each install is a seamless uninstall/reinstall. --> - + - - + + @@ -21,8 +22,6 @@ - - @@ -38,7 +37,7 @@ application processes and removes the WinDivert driver and the autorun task created by the application. --> - + From 779e10efc61e2811df301db3d43f0817b2ea859a Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:31:30 +0000 Subject: [PATCH 054/202] Close the tray gracefully before updating and remove dropped files Update.exe killed the tray, so a component that had set the system proxy left it pointing to a stopped server, and it started extracting without checking that the killed processes were gone. It now signals the tray to exit as from its menu, which stops the components and restores the proxy, kills what is left, and aborts the update while any application process still runs. Files from the previous update that are not in the new package are now removed through the same backup as replaced files, so a rollback restores them. The list of updated files is kept in .update-manifest and deleted on uninstall. A quoted destination that ends with a backslash no longer breaks argument parsing, and starting Update.exe without arguments shows what it is for instead of exiting silently. --- CDPIUI.TrayIcon/Helper/UninstallHelper.cs | 2 +- Update/InstallHelper.cs | 115 +++++++++++++++++++++- Update/Program.cs | 10 +- 3 files changed, 120 insertions(+), 7 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs index b6820926..7454cbda 100644 --- a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs +++ b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs @@ -170,7 +170,7 @@ private static void RemoveHostsBlock(string installDirectory) // Files the application creates next to the installed ones; the package does not know them, // so the installation directory would otherwise stay behind. private static readonly string[] RuntimeDirectories = ["Logs", ".update-staging", ".update-backup", ".old"]; - private static readonly string[] RuntimeFiles = ["update.log"]; + private static readonly string[] RuntimeFiles = ["update.log", ".update-manifest"]; private static void RemoveRuntimeFiles(string installDirectory) { diff --git a/Update/InstallHelper.cs b/Update/InstallHelper.cs index 7ccfaa25..55a05618 100644 --- a/Update/InstallHelper.cs +++ b/Update/InstallHelper.cs @@ -5,6 +5,7 @@ using System.IO.Compression; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; @@ -84,12 +85,11 @@ public void StartInstall() { InstallationStateChanged?.Invoke(InstallState.Prepare); Log("Starting extraction process"); - CloseProcessIfRunning("goodbyeDPI"); - CloseProcessIfRunning("CDPIUI"); - CloseProcessIfRunning("CDPIUI_TrayIcon"); + if (!StopApplication()) + FinishStatus = InstallError.PermissionDenied; InstallationStateChanged?.Invoke(InstallState.Unpack); - List stagedFiles = await StageAsync(); + List stagedFiles = FinishStatus == InstallError.None ? await StageAsync() : null; bool applied = false; if (FinishStatus == InstallError.None && stagedFiles != null) @@ -101,6 +101,7 @@ public void StartInstall() if (applied) { InstallationStateChanged?.Invoke(InstallState.Finalize); + WriteManifest(stagedFiles); Cleanup(); FinishStatus = InstallError.OK; bool launched = LaunchApplication(false); @@ -147,6 +148,74 @@ public void StartInstall() private string StagingFolder => Path.Combine(_targetFolder, ".update-staging"); private string BackupFolder => Path.Combine(_targetFolder, ".update-backup"); + // Files written by the last update, so files dropped from a newer version can be removed. + private string ManifestPath => Path.Combine(_targetFolder, ".update-manifest"); + + private static readonly string[] ApplicationProcesses = { "goodbyeDPI", "CDPIUI", "CDPIUI_TrayIcon" }; + private const string TrayShutdownEventName = @"Global\CDPIUI_TrayShutdown"; + + /// + /// Closes the application and checks that no process that holds its files is left + /// + private bool StopApplication() + { + EventWaitHandle shutdownEvent = null; + try + { + // Let the tray exit as from its menu first: it then stops the components and + // restores the system proxy settings, which a killed tray leaves behind. + bool opened; + try { opened = EventWaitHandle.TryOpenExisting(TrayShutdownEventName, out shutdownEvent); } + catch (Exception ex) + { + Log($"Cannot ask the tray to exit: {ex.Message}"); + opened = false; + } + if (opened) + { + shutdownEvent.Set(); + WaitForExit("CDPIUI_TrayIcon", TimeSpan.FromSeconds(20)); + } + + foreach (string name in ApplicationProcesses) + CloseProcessIfRunning(name); + + foreach (string name in ApplicationProcesses) + { + if (!WaitForExit(name, TimeSpan.FromSeconds(10))) + { + Log($"{name}.exe is still running. Update aborted."); + return false; + } + } + return true; + } + catch (Exception ex) + { + Log($"Cannot close the application: {ex}"); + return false; + } + finally + { + try { shutdownEvent?.Reset(); } catch { } + shutdownEvent?.Dispose(); + } + } + + private static bool WaitForExit(string processName, TimeSpan timeout) + { + var stopwatch = Stopwatch.StartNew(); + while (true) + { + Process[] processes = Process.GetProcessesByName(processName); + bool running = processes.Length > 0; + foreach (var process in processes) process.Dispose(); + + if (!running) return true; + if (stopwatch.Elapsed > timeout) return false; + Thread.Sleep(250); + } + } private void CloseProcessIfRunning(string processNameWithoutExt) { @@ -293,6 +362,20 @@ private bool ApplyStaged(List stagedFiles) ProgressChanged?.Invoke((double)(i + 1) / stagedFiles.Count); } + foreach (string relativePath in GetRemovedFiles(stagedFiles)) + { + string destPath, backupPath; + if (!TryGetDestination(_targetFolder, relativePath, out destPath) || + !TryGetDestination(BackupFolder, relativePath, out backupPath) || + !File.Exists(destPath)) + continue; + + CurrentFileChanged?.Invoke($"Removing {relativePath}"); + Directory.CreateDirectory(Path.GetDirectoryName(backupPath)); + File.Move(destPath, backupPath); + applied.Add(new KeyValuePair(relativePath, true)); + } + return true; } catch (Exception ex) @@ -310,6 +393,30 @@ private bool ApplyStaged(List stagedFiles) } } + private IEnumerable GetRemovedFiles(List stagedFiles) + { + if (!File.Exists(ManifestPath)) + return Enumerable.Empty(); + + var current = new HashSet(stagedFiles, StringComparer.OrdinalIgnoreCase); + return File.ReadAllLines(ManifestPath) + .Where(line => !string.IsNullOrWhiteSpace(line) && !current.Contains(line)) + .Where(line => !_skipFiles.Contains(Path.GetFileName(line), StringComparer.OrdinalIgnoreCase)) + .ToList(); + } + + private void WriteManifest(List stagedFiles) + { + try + { + File.WriteAllLines(ManifestPath, stagedFiles); + } + catch (Exception ex) + { + Log($"Cannot write the update manifest: {ex.Message}"); + } + } + private bool Rollback(List> applied) { bool restored = true; diff --git a/Update/Program.cs b/Update/Program.cs index d032ea8e..9003479c 100644 --- a/Update/Program.cs +++ b/Update/Program.cs @@ -16,13 +16,14 @@ static void Main(string[] args) string destinationPath = null; for (int i = 0; i < args.Length; i++) { + // A quoted path that ends with a backslash ("C:\") reaches us with a trailing quote. if (args[i] == "--directory-to-zip" && i + 1 < args.Length) { - extractFileName = args[++i]; + extractFileName = args[++i].Trim('"'); } else if (args[i] == "--destination-directory" && i + 1 < args.Length) { - destinationPath = args[++i]; + destinationPath = args[++i].Trim('"'); } } if (!string.IsNullOrEmpty(extractFileName) && !string.IsNullOrEmpty(destinationPath)) @@ -34,6 +35,11 @@ static void Main(string[] args) Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainWindow()); } + else + { + MessageBox.Show("Update.exe is started by CDPI UI to install an application update.", + "CDPI UI Update", MessageBoxButtons.OK, MessageBoxIcon.Information); + } } } } From 7edc97c2226764420c7d43a5a42bb028ee54ed5b Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:33:10 +0000 Subject: [PATCH 055/202] Map Win32, socket and HTTP errors to their codes The Win32Exception check looked at the outer exception instead of the one being inspected, Win32 codes such as 5, 2 and 32 were looked up as HRESULTs and gave UNKNOWN, the HTTP status code was never filled in, network failures from HttpClient always gave UNKNOWN, a timeout inside a cancellation was missed, and GetErrorModel never set HResult. Win32 codes are now also looked up in their HRESULT form and back, socket errors inside an HttpRequestException map to the network codes, the status code is taken from HttpRequestException and reported as UNEXPECTED_STATUS_CODE, and the error model carries the HRESULT. --- .../ErrorConvertor.cs | 73 ++++++++++++++++-- CDPIUI.Tests/Shared/ErrorConvertorTests.cs | 76 +++++++++++++++++++ 2 files changed, 142 insertions(+), 7 deletions(-) create mode 100644 CDPIUI.Tests/Shared/ErrorConvertorTests.cs diff --git a/CDPIUI.Shared/PrettyErrorConvertionService/ErrorConvertor.cs b/CDPIUI.Shared/PrettyErrorConvertionService/ErrorConvertor.cs index 45c37f38..589f52eb 100644 --- a/CDPIUI.Shared/PrettyErrorConvertionService/ErrorConvertor.cs +++ b/CDPIUI.Shared/PrettyErrorConvertionService/ErrorConvertor.cs @@ -76,8 +76,19 @@ public virtual PrettyErrorCode MapExceptionToCode(Exception ex, out uint? rawHRe case UnknownException: return PrettyErrorCode.UNKNOWN; + case TimeoutException: + return PrettyErrorCode.TIMEOUT; + case SocketException socketException: + { + PrettyErrorCode socketCode = MapSocketError(socketException.SocketErrorCode); + if (socketCode != PrettyErrorCode.UNKNOWN) return socketCode; + break; + } } - if (current is IOException) + + statusCode ??= GetHttpStatusCode(current); + // A network IOException wraps the socket error, which says more. + if (current is IOException && current.InnerException is not SocketException) { var hrGeneric = unchecked((uint)current.HResult); @@ -92,7 +103,7 @@ public virtual PrettyErrorCode MapExceptionToCode(Exception ex, out uint? rawHRe return PrettyErrorCode.EXTRACT_INVALID_ARCHIVE; int _hr = current.HResult; - if (ex is Win32Exception w32ex) + if (current is Win32Exception w32ex) { _hr = w32ex.NativeErrorCode; } @@ -106,17 +117,65 @@ public virtual PrettyErrorCode MapExceptionToCode(Exception ex, out uint? rawHRe if (code != PrettyErrorCode.UNKNOWN) return code; } } - if (ex is UriFormatException) - return PrettyErrorCode.INVALID_URI; - if (ex is TimeoutException) - return PrettyErrorCode.TIMEOUT; + if (statusCode != null) + return PrettyErrorCode.UNEXPECTED_STATUS_CODE; + if (ex is HttpRequestException) + return PrettyErrorCode.HTTP_REQUEST_EXCEPTION; return PrettyErrorCode.UNKNOWN; } + private static PrettyErrorCode MapSocketError(SocketError error) + { + switch (error) + { + case SocketError.HostNotFound: + case SocketError.NoData: + case SocketError.TryAgain: + return PrettyErrorCode.HOST_NAME_NOT_RESOLVED; + case SocketError.ConnectionRefused: + case SocketError.NetworkUnreachable: + case SocketError.HostUnreachable: + case SocketError.NetworkDown: + return PrettyErrorCode.CANNOT_CONNECT; + case SocketError.ConnectionReset: + return PrettyErrorCode.CONNECTION_RESET; + case SocketError.ConnectionAborted: + return PrettyErrorCode.CONNECTION_ABORTED; + case SocketError.TimedOut: + return PrettyErrorCode.TIMEOUT; + default: + return PrettyErrorCode.UNKNOWN; + } + } + + // HttpRequestException.StatusCode exists only on .NET 5 and later. + private static int? GetHttpStatusCode(Exception exception) + { + if (exception is not HttpRequestException) + return null; + object? value = exception.GetType().GetProperty("StatusCode")?.GetValue(exception); + return value == null ? null : Convert.ToInt32(value); + } + private static PrettyErrorCode ConvertHresultToCode(int HResult, out uint? rawHResult) { uint hr = unchecked((uint)HResult); rawHResult = hr; + + // Win32 error codes arrive both as such (Win32Exception.NativeErrorCode) and wrapped + // into an HRESULT; the table below knows some codes in only one of these forms. + PrettyErrorCode code = ConvertExactHresultToCode(hr); + if (code != PrettyErrorCode.UNKNOWN || hr == 0) + return code; + if (hr < 0x10000) + return ConvertExactHresultToCode(0x80070000u | hr); + if ((hr & 0xFFFF0000u) == 0x80070000u) + return ConvertExactHresultToCode(hr & 0xFFFFu); + return code; + } + + private static PrettyErrorCode ConvertExactHresultToCode(uint hr) + { switch (hr) { case 0: @@ -234,7 +293,7 @@ public virtual ErrorModel GetErrorModel(string @object, Exception ex, ILogger? l logger?.CreateErrorLog(nameof(ErrorConvertor), $"{code} - {ex}"); - string hrHex = null; + string? hrHex = hr != null ? $"0x{hr.Value:X8}" : null; ErrorModel errorModel = new() { diff --git a/CDPIUI.Tests/Shared/ErrorConvertorTests.cs b/CDPIUI.Tests/Shared/ErrorConvertorTests.cs new file mode 100644 index 00000000..e759482b --- /dev/null +++ b/CDPIUI.Tests/Shared/ErrorConvertorTests.cs @@ -0,0 +1,76 @@ +using System.ComponentModel; +using System.Net; +using System.Net.Sockets; +using CDPIUI.Shared.PrettyErrorConvertionService; + +namespace CDPIUI.Tests.Shared; + +public class ErrorConvertorTests +{ + private readonly ErrorConvertor convertor = new(); + + [Theory] + [InlineData(5, PrettyErrorCode.ACCESS_DENIED)] + [InlineData(2, PrettyErrorCode.IO_FILE_NOT_FOUND)] + [InlineData(32, PrettyErrorCode.IO_FILE_USED_FOR_ANOTHER_PROCESS)] + [InlineData(1223, PrettyErrorCode.OPERATION_CANCELLED_BY_USER)] + public void Win32ErrorsAreMapped(int error, PrettyErrorCode expected) + { + Assert.Equal(expected, convertor.MapExceptionToCode(new Win32Exception(error), out _)); + } + + [Fact] + public void Win32ErrorInsideAnotherExceptionIsMapped() + { + var exception = new InvalidOperationException("Start failed", new Win32Exception(5)); + Assert.Equal(PrettyErrorCode.ACCESS_DENIED, convertor.MapExceptionToCode(exception, out _)); + } + + [Theory] + [InlineData(SocketError.HostNotFound, PrettyErrorCode.HOST_NAME_NOT_RESOLVED)] + [InlineData(SocketError.ConnectionRefused, PrettyErrorCode.CANNOT_CONNECT)] + [InlineData(SocketError.ConnectionReset, PrettyErrorCode.CONNECTION_RESET)] + [InlineData(SocketError.TimedOut, PrettyErrorCode.TIMEOUT)] + public void NetworkErrorsAreMapped(SocketError error, PrettyErrorCode expected) + { + var exception = new HttpRequestException("Request failed", + new IOException("Transport failed", new SocketException((int)error))); + Assert.Equal(expected, convertor.MapExceptionToCode(exception, out _)); + } + + [Fact] + public void HttpStatusCodeIsKept() + { + var exception = new HttpRequestException("Not found", null, HttpStatusCode.NotFound); + + PrettyErrorCode code = convertor.MapExceptionToCode(exception, out _, out int? statusCode); + + Assert.Equal(PrettyErrorCode.UNEXPECTED_STATUS_CODE, code); + Assert.Equal(404, statusCode); + Assert.StartsWith("TEST_UNEXPECTED_STATUS_CODE_404", convertor.GetPrettyErrorCode("TEST", exception, null)); + } + + [Fact] + public void TimeoutInsideCancellationIsMapped() + { + var exception = new TaskCanceledException("Timed out", new TimeoutException()); + Assert.Equal(PrettyErrorCode.TIMEOUT, convertor.MapExceptionToCode(exception, out _)); + } + + [Fact] + public void ErrorModelKeepsHresult() + { + var exception = new IOException("Disk full", unchecked((int)0x80070070)); + + ErrorModel model = convertor.GetErrorModel("test", exception, null); + + Assert.Equal(nameof(PrettyErrorCode.IO_DISK_FULL), model.ErrorCode); + Assert.Equal("0x80070070", model.HResult); + } + + [Fact] + public void SuccessCodeIsUnchanged() + { + Assert.Equal("HOSTEDIT_SUCCESS (0x00000000)", convertor.GetPrettyErrorCode("HOSTEDIT", 0, null)); + } +} From 376ed7f6843a00db160e5740f039fccccedf8f3c Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:34:20 +0000 Subject: [PATCH 056/202] Save conditional tasks atomically and skip duplicate task ids Task files were truncated and rewritten in place, so a crash during a save left a broken file, load errors were swallowed without a trace, and a copied task file made the same task run twice and register its hotkey twice. Tasks are now written to a temporary file and swapped in, the second file with an identifier already loaded is skipped, and the tray logs every skipped file. --- .../ConditionalTaskModels.cs | 49 ++++++++++++---- .../Shared/ConditionalTaskFileServiceTests.cs | 58 +++++++++++++++++++ .../ConditionalLaunchEngine.cs | 5 +- 3 files changed, 101 insertions(+), 11 deletions(-) create mode 100644 CDPIUI.Tests/Shared/ConditionalTaskFileServiceTests.cs diff --git a/CDPIUI.Shared/ConditionalLaunch/ConditionalTaskModels.cs b/CDPIUI.Shared/ConditionalLaunch/ConditionalTaskModels.cs index 83f294f9..f54bd9de 100644 --- a/CDPIUI.Shared/ConditionalLaunch/ConditionalTaskModels.cs +++ b/CDPIUI.Shared/ConditionalLaunch/ConditionalTaskModels.cs @@ -181,21 +181,29 @@ public static string GetTasksDirectoryFromSettingsFile(string settingsFilePath) return Path.Combine(dataDirectory, DirectoryName); } - public static IReadOnlyList LoadDirectory(string directoryPath) + /// Receives the path and the error of every file that is skipped + public static IReadOnlyList LoadDirectory(string directoryPath, Action? onError = null) { Directory.CreateDirectory(directoryPath); var tasks = new List(); - foreach (var filePath in Directory.EnumerateFiles(directoryPath, $"*{FileExtension}")) + var ids = new HashSet(StringComparer.OrdinalIgnoreCase); + // Sorted, so the same copy of a duplicated task wins on every load. + foreach (var filePath in Directory.EnumerateFiles(directoryPath, $"*{FileExtension}") + .OrderBy(path => path, StringComparer.OrdinalIgnoreCase)) { try { - tasks.Add(Load(filePath)); + ConditionalTask task = Load(filePath); + // A copied task file would otherwise run the same task twice. + if (!ids.Add(task.Id)) + throw new InvalidDataException($"Another task file already has the identifier {task.Id}."); + tasks.Add(task); } - catch + catch (Exception ex) { - // Invalid task files are ignored by the runtime. The editor - // reports import/load errors to the user separately. + // Invalid task files are skipped. The editor reports import errors to the user separately. + onError?.Invoke(filePath, ex); } } @@ -234,13 +242,35 @@ public static string Save(ConditionalTask task, string directoryPath, string? fi if (!filePath.StartsWith(targetDirectory, StringComparison.OrdinalIgnoreCase)) filePath = Path.Combine(directoryPath, $"{task.Id}{FileExtension}"); - using (var stream = File.Create(filePath)) - Serializer.Serialize(stream, task); + WriteTask(task, filePath); task.FilePath = filePath; return filePath; } + // Writes next to the target and swaps the file in, so a crash never leaves a truncated task. + private static void WriteTask(ConditionalTask task, string filePath) + { + string tempPath = filePath + ".tmp"; + try + { + using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + Serializer.Serialize(stream, task); + stream.Flush(true); + } + + if (File.Exists(filePath)) + File.Replace(tempPath, filePath, null); + else + File.Move(tempPath, filePath); + } + finally + { + if (File.Exists(tempPath)) File.Delete(tempPath); + } + } + public static void Export(ConditionalTask task, string filePath) { Validate(task); @@ -248,8 +278,7 @@ public static void Export(ConditionalTask task, string filePath) if (!string.Equals(Path.GetExtension(filePath), FileExtension, StringComparison.OrdinalIgnoreCase)) filePath += FileExtension; - using var stream = File.Create(filePath); - Serializer.Serialize(stream, task); + WriteTask(task, Path.GetFullPath(filePath)); } public static void Validate(ConditionalTask task) diff --git a/CDPIUI.Tests/Shared/ConditionalTaskFileServiceTests.cs b/CDPIUI.Tests/Shared/ConditionalTaskFileServiceTests.cs new file mode 100644 index 00000000..28241838 --- /dev/null +++ b/CDPIUI.Tests/Shared/ConditionalTaskFileServiceTests.cs @@ -0,0 +1,58 @@ +using CDPIUI.Shared.ConditionalLaunch; + +namespace CDPIUI.Tests.Shared; + +public sealed class ConditionalTaskFileServiceTests : IDisposable +{ + private readonly string directory = Path.Combine(Path.GetTempPath(), "cdpiui-tasks-" + Guid.NewGuid().ToString("N")); + + public void Dispose() => Directory.Delete(directory, true); + + private static ConditionalTask CreateTask(string name) => new() + { + Name = name, + Triggers = [new ConditionalTrigger()], + Actions = [new ConditionalAction()], + }; + + [Fact] + public void SavedTaskLoadsBackWithoutTemporaryFiles() + { + ConditionalTask task = CreateTask("First"); + string path = ConditionalTaskFileService.Save(task, directory); + task.Name = "Renamed"; + ConditionalTaskFileService.Save(task, directory); + + ConditionalTask loaded = ConditionalTaskFileService.Load(path); + + Assert.Equal("Renamed", loaded.Name); + Assert.Single(Directory.GetFiles(directory)); + } + + [Fact] + public void CopiedTaskFileIsSkippedAndReported() + { + ConditionalTask task = CreateTask("Task"); + string path = ConditionalTaskFileService.Save(task, directory); + File.Copy(path, Path.Combine(directory, "copy" + ConditionalTaskFileService.FileExtension)); + var errors = new List(); + + IReadOnlyList tasks = ConditionalTaskFileService.LoadDirectory(directory, (file, _) => errors.Add(file)); + + Assert.Single(tasks); + Assert.Single(errors); + } + + [Fact] + public void BrokenTaskFileIsReported() + { + Directory.CreateDirectory(directory); + File.WriteAllText(Path.Combine(directory, "broken" + ConditionalTaskFileService.FileExtension), "(); + + IReadOnlyList tasks = ConditionalTaskFileService.LoadDirectory(directory, (file, _) => errors.Add(file)); + + Assert.Empty(tasks); + Assert.Single(errors); + } +} diff --git a/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs b/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs index f761cedd..91db3da3 100644 --- a/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs +++ b/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs @@ -97,7 +97,10 @@ public void Reload(string? tasksDirectory = null) IReadOnlyList loadedTasks; try { - loadedTasks = ConditionalTaskFileService.LoadDirectory(directory); + loadedTasks = ConditionalTaskFileService.LoadDirectory(directory, (path, error) => + Logger.Instance.CreateWarningLog( + nameof(ConditionalLaunchEngine), + $"Skipped conditional task file \"{path}\": {error.Message}")); } catch (Exception ex) { From dc085c5941a87d7b33fd31d7ac4e6d3449d89c7b Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:34:47 +0000 Subject: [PATCH 057/202] Make temporary names unique and do not copy a file onto itself Temporary names had a one-second resolution, so two downloads or extractions started within the same second shared a name, and the default extension produced a double dot. CopyFileAsync truncated the source when the destination was the same file. --- CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs b/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs index 76403f0b..01aa07ff 100644 --- a/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs +++ b/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs @@ -94,7 +94,7 @@ public static string GetNewTempFileName() /// /// Get unique temp file/folder name. Format /// - /// secondsSinceEpoch_suffix(.extention) + /// secondsSinceEpoch_suffix_random(.extention) /// /// /// Suffix of file @@ -104,9 +104,11 @@ public static string GetNewTempFileName(string suffix, string? extention = null) { TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); int secondsSinceEpoch = (int)t.TotalSeconds; + // Seconds alone repeat when two names are requested within the same second. + string unique = Guid.NewGuid().ToString("N").Substring(0, 8); - if (string.IsNullOrEmpty(extention)) return $"{secondsSinceEpoch}_{suffix}"; - return $"{secondsSinceEpoch}_{suffix}.{extention}"; + if (string.IsNullOrEmpty(extention)) return $"{secondsSinceEpoch}_{suffix}_{unique}"; + return $"{secondsSinceEpoch}_{suffix}_{unique}.{extention!.TrimStart('.')}"; } /// @@ -116,6 +118,10 @@ public static string GetNewTempFileName(string suffix, string? extention = null) /// Copy destination public static async Task CopyFileAsync(string sourcePath, string destinationPath) { + // Creating the destination first would truncate the source when both are the same file. + if (string.Equals(Path.GetFullPath(sourcePath), Path.GetFullPath(destinationPath), StringComparison.OrdinalIgnoreCase)) + return; + using Stream source = File.OpenRead(sourcePath); using Stream destination = File.Create(destinationPath); await source.CopyToAsync(destination); From 5bafb69bef4bd7f0e73cd1f80e7f2862cf9741bf Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:35:14 +0000 Subject: [PATCH 058/202] Read the desktop user's settings in a tray elevated with another account The tray looked for Settings.xml next to its executable and then in its own profile, so when UAC elevation used another administrator account it read a different settings file than the UI wrote. The desktop user's data directory is now checked before the tray profile. --- CDPIUI.TrayIcon/Helper/TrustedPaths.cs | 2 +- CDPIUI.TrayIcon/Helper/Utils.cs | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CDPIUI.TrayIcon/Helper/TrustedPaths.cs b/CDPIUI.TrayIcon/Helper/TrustedPaths.cs index 19d46c14..2803910f 100644 --- a/CDPIUI.TrayIcon/Helper/TrustedPaths.cs +++ b/CDPIUI.TrayIcon/Helper/TrustedPaths.cs @@ -18,7 +18,7 @@ public static class TrustedPaths GetDesktopUserDataDirectory(), ]; - private static string? GetDesktopUserDataDirectory() + public static string? GetDesktopUserDataDirectory() { try { diff --git a/CDPIUI.TrayIcon/Helper/Utils.cs b/CDPIUI.TrayIcon/Helper/Utils.cs index e8d2c1b3..e72077c5 100644 --- a/CDPIUI.TrayIcon/Helper/Utils.cs +++ b/CDPIUI.TrayIcon/Helper/Utils.cs @@ -41,6 +41,16 @@ public static string GetSettingsFile() } else { + // The UI keeps its settings in the profile of the desktop user, which differs from + // the tray profile when the tray was elevated with another administrator account. + string? desktopUserFolder = TrustedPaths.GetDesktopUserDataDirectory(); + if (desktopUserFolder != null) + { + string desktopUserFile = Path.Combine(desktopUserFolder, "Settings", "Settings.xml"); + if (File.Exists(desktopUserFile)) + return desktopUserFile; + } + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var targetFolder = Path.Combine(localAppData, "CDPIUI"); string localAppDataFile = Path.Combine(targetFolder, "Settings", "Settings.xml"); From 7521f302631106df5a08ba72e08a7447fa680e2e Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:40:12 +0000 Subject: [PATCH 059/202] Verify the catalog signature instead of only reading its certificate CertificateCheck took the certificate out of catalog.cat with X509Certificate.CreateFromSignedFile and compared its thumbprint, which does not check the signature at all: a catalog with any content, signed by any key and carrying the trusted certificate, passed. The PowerShell command also put paths into single quotes without escaping, and its output was read only after the process exited, without a timeout. CatalogVerifier now decodes the catalog as CMS, requires every signer certificate to be pinned and checks every signature. The pinned certificates are self-signed, so the chain is not built and WinVerifyTrust would reject them. Test-FileCatalog gets the paths through environment variables, its output is read while it runs, and it is killed after two minutes. Tests use the catalog of the published 1.0.3.2 patch, a tampered copy of it and a catalog signed by another key with the trusted certificate embedded. --- CDPIUI.Core/Security/CertificateCheck.cs | 66 +++------- CDPIUI.Shared/CDPIUI.Shared.csproj | 1 + CDPIUI.Shared/Security/CatalogVerifier.cs | 127 ++++++++++++++++++++ CDPIUI.Tests/CDPIUI.Tests.csproj | 4 + CDPIUI.Tests/Shared/CatalogVerifierTests.cs | 87 ++++++++++++++ CDPIUI.Tests/TestData/release-catalog.cat | Bin 0 -> 54459 bytes 6 files changed, 234 insertions(+), 51 deletions(-) create mode 100644 CDPIUI.Shared/Security/CatalogVerifier.cs create mode 100644 CDPIUI.Tests/Shared/CatalogVerifierTests.cs create mode 100644 CDPIUI.Tests/TestData/release-catalog.cat diff --git a/CDPIUI.Core/Security/CertificateCheck.cs b/CDPIUI.Core/Security/CertificateCheck.cs index 4fab1c44..2f511de6 100644 --- a/CDPIUI.Core/Security/CertificateCheck.cs +++ b/CDPIUI.Core/Security/CertificateCheck.cs @@ -1,8 +1,5 @@ -using CDPIUI.Shared.Exceptions.Catalog; -using CDPIUI.Shared.Secrets; -using System.Diagnostics; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; +using CDPIUI.Shared.Secrets; +using CDPIUI.Shared.Security; namespace CDPIUI.Core.Security { @@ -19,57 +16,24 @@ public class CertificateCheck { public static async Task CheckCatalog(string catalogFile, string compareDirectory) { - CatalogCheckResult catalogCheckResult; - bool result = false; try { - result = await OpenAndCompareCatalogFile(catalogFile, compareDirectory); - if (result) catalogCheckResult = CatalogCheckResult.Success; - else catalogCheckResult = CatalogCheckResult.FailureNotValid; - } - catch (Exception ex) - { - if (ex is CertificateNotTrusted) catalogCheckResult = CatalogCheckResult.FailureNotTrustedSignature; - else if (ex is CryptographicException) catalogCheckResult = CatalogCheckResult.FailureNoSignature; - else catalogCheckResult = CatalogCheckResult.FailureUnknown; - } - - await Task.CompletedTask; - return catalogCheckResult; - } + CatalogVerification verification = await CatalogVerifier.VerifyAsync( + catalogFile, compareDirectory, Secret.TrustedCertificates); - private static async Task OpenAndCompareCatalogFile(string catalogFile, string compareDirectory) - { - X509Certificate catalogFileSign = X509Certificate.CreateFromSignedFile(catalogFile); - if (!Secret.TrustedCertificates.Contains(catalogFileSign.GetCertHashString())) + return verification switch + { + CatalogVerification.Success => CatalogCheckResult.Success, + CatalogVerification.NoSignature => CatalogCheckResult.FailureNoSignature, + CatalogVerification.NotTrustedSignature => CatalogCheckResult.FailureNotTrustedSignature, + CatalogVerification.FilesDoNotMatch => CatalogCheckResult.FailureNotValid, + _ => CatalogCheckResult.FailureUnknown, + }; + } + catch { - throw new CertificateNotTrusted("Certificate not trusted"); + return CatalogCheckResult.FailureUnknown; } - - ProcessStartInfo startInfo = new ProcessStartInfo(); - - startInfo.FileName = @"powershell.exe"; - startInfo.Arguments = - $"Test-FileCatalog " + - $"-CatalogFilePath \'{catalogFile}\' " + - $"-Path \'{compareDirectory}\' " + - $"-FilesToSkip catalog.cat"; - startInfo.RedirectStandardOutput = true; - startInfo.RedirectStandardError = true; - startInfo.UseShellExecute = false; - startInfo.CreateNoWindow = true; - - Process process = new Process(); - - process.StartInfo = startInfo; - process.Start(); - await process.WaitForExitAsync(); - - string output = process.StandardOutput.ReadToEnd().ReplaceLineEndings(""); - if (string.Equals("Valid", output, StringComparison.OrdinalIgnoreCase)) - return true; - else - return false; } } } diff --git a/CDPIUI.Shared/CDPIUI.Shared.csproj b/CDPIUI.Shared/CDPIUI.Shared.csproj index fefa1059..f16dfaf5 100644 --- a/CDPIUI.Shared/CDPIUI.Shared.csproj +++ b/CDPIUI.Shared/CDPIUI.Shared.csproj @@ -16,6 +16,7 @@ + diff --git a/CDPIUI.Shared/Security/CatalogVerifier.cs b/CDPIUI.Shared/Security/CatalogVerifier.cs new file mode 100644 index 00000000..448cee96 --- /dev/null +++ b/CDPIUI.Shared/Security/CatalogVerifier.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Threading.Tasks; + +namespace CDPIUI.Shared.Security +{ + public enum CatalogVerification + { + Success, + NoSignature, + NotTrustedSignature, + FilesDoNotMatch, + Failure + } + + /// + /// Verifies signed file catalogs (catalog.cat) of packages and application updates + /// + public static class CatalogVerifier + { + private static readonly TimeSpan FileCheckTimeout = TimeSpan.FromMinutes(2); + + /// + /// Checks the catalog signature and that the files of the directory match the catalog + /// + /// Catalog file + /// Directory the catalog describes + /// SHA-1 thumbprints of the certificates allowed to sign catalogs + public static async Task VerifyAsync(string catalogFile, string directory, IEnumerable trustedThumbprints) + { + if (!File.Exists(catalogFile)) + return CatalogVerification.NoSignature; + + CatalogVerification signature = VerifySignature(File.ReadAllBytes(catalogFile), trustedThumbprints); + if (signature != CatalogVerification.Success) + return signature; + + return await VerifyFilesAsync(catalogFile, directory) ? CatalogVerification.Success : CatalogVerification.FilesDoNotMatch; + } + + /// + /// Checks that the catalog is signed and that every signature is valid and made by a trusted certificate. + /// The certificates are pinned and self-signed, so the chain is not built. + /// + public static CatalogVerification VerifySignature(byte[] catalog, IEnumerable trustedThumbprints) + { + var trusted = new HashSet( + trustedThumbprints.Select(NormalizeThumbprint), StringComparer.OrdinalIgnoreCase); + + var cms = new SignedCms(); + try + { + cms.Decode(catalog); + } + catch (CryptographicException) + { + return CatalogVerification.NoSignature; + } + + if (cms.SignerInfos.Count == 0) + return CatalogVerification.NoSignature; + + foreach (SignerInfo signer in cms.SignerInfos) + { + // Only the signer certificate is compared: a certificate merely embedded in the + // catalog proves nothing about who signed it. + if (signer.Certificate == null || !trusted.Contains(signer.Certificate.Thumbprint)) + return CatalogVerification.NotTrustedSignature; + + try + { + signer.CheckSignature(verifySignatureOnly: true); + } + catch (CryptographicException) + { + return CatalogVerification.NotTrustedSignature; + } + } + + return CatalogVerification.Success; + } + + private static string NormalizeThumbprint(string thumbprint) => + new string(thumbprint.Where(Uri.IsHexDigit).ToArray()); + + private static async Task VerifyFilesAsync(string catalogFile, string directory) + { + var startInfo = new ProcessStartInfo("powershell.exe") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + // Paths go through the environment, so quotes in them cannot change the command. + startInfo.ArgumentList.Add("-NoProfile"); + startInfo.ArgumentList.Add("-NonInteractive"); + startInfo.ArgumentList.Add("-Command"); + startInfo.ArgumentList.Add( + "(Test-FileCatalog -CatalogFilePath $env:CDPIUI_CATALOG -Path $env:CDPIUI_CATALOG_DIRECTORY -FilesToSkip catalog.cat).ToString()"); + startInfo.Environment["CDPIUI_CATALOG"] = Path.GetFullPath(catalogFile); + startInfo.Environment["CDPIUI_CATALOG_DIRECTORY"] = Path.GetFullPath(directory); + + using var process = Process.Start(startInfo); + if (process == null) + return false; + + Task output = process.StandardOutput.ReadToEndAsync(); + Task errors = process.StandardError.ReadToEndAsync(); + Task exited = Task.Run(() => process.WaitForExit()); + + if (await Task.WhenAny(exited, Task.Delay(FileCheckTimeout)) != exited) + { + try { process.Kill(); } catch { } + return false; + } + + await Task.WhenAll(output, errors); + return string.Equals(output.Result.Trim(), "Valid", StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/CDPIUI.Tests/CDPIUI.Tests.csproj b/CDPIUI.Tests/CDPIUI.Tests.csproj index 61c1765a..ebaee70d 100644 --- a/CDPIUI.Tests/CDPIUI.Tests.csproj +++ b/CDPIUI.Tests/CDPIUI.Tests.csproj @@ -8,6 +8,10 @@ true + + + + diff --git a/CDPIUI.Tests/Shared/CatalogVerifierTests.cs b/CDPIUI.Tests/Shared/CatalogVerifierTests.cs new file mode 100644 index 00000000..34638c00 --- /dev/null +++ b/CDPIUI.Tests/Shared/CatalogVerifierTests.cs @@ -0,0 +1,87 @@ +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using CDPIUI.Shared.Security; + +namespace CDPIUI.Tests.Shared; + +public class CatalogVerifierTests +{ + // Signer of the catalogs in the published application patches (CN=Storik4). + private const string ReleaseThumbprint = "03AB9EBCE1C2A66BE3974FD17AB90E0ECCDB2909"; + + private static byte[] ReleaseCatalog() => + File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "TestData", "release-catalog.cat")); + + [Fact] + public void ReleaseCatalogSignedByTrustedCertificatePasses() + { + Assert.Equal(CatalogVerification.Success, CatalogVerifier.VerifySignature(ReleaseCatalog(), [ReleaseThumbprint])); + } + + [Fact] + public void ThumbprintFormattingIsIgnored() + { + Assert.Equal(CatalogVerification.Success, + CatalogVerifier.VerifySignature(ReleaseCatalog(), ["03 ab 9e bc e1 c2 a6 6b e3 97 4f d1 7a b9 0e 0e cc db 29 09"])); + } + + [Fact] + public void ReleaseCatalogWithUnknownThumbprintFails() + { + Assert.Equal(CatalogVerification.NotTrustedSignature, + CatalogVerifier.VerifySignature(ReleaseCatalog(), ["0000000000000000000000000000000000000000"])); + } + + [Fact] + public void ModifiedCatalogContentFails() + { + var cms = new SignedCms(); + cms.Decode(ReleaseCatalog()); + byte[] content = (byte[])cms.ContentInfo.Content.Clone(); + + // Change one byte of the signed content and keep the original signature and certificate. + byte[] catalog = ReleaseCatalog(); + int index = IndexOf(catalog, content); + Assert.True(index > 0); + catalog[index + content.Length / 2] ^= 0xFF; + + Assert.Equal(CatalogVerification.NotTrustedSignature, CatalogVerifier.VerifySignature(catalog, [ReleaseThumbprint])); + } + + [Fact] + public void CatalogSignedByAnotherKeyWithEmbeddedTrustedCertificateFails() + { + var release = new SignedCms(); + release.Decode(ReleaseCatalog()); + X509Certificate2 trusted = release.Certificates[0]; + + using RSA key = RSA.Create(2048); + var request = new CertificateRequest("CN=Storik4", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using X509Certificate2 attacker = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + + var forged = new SignedCms(release.ContentInfo, false); + forged.ComputeSignature(new CmsSigner(attacker)); + forged.Certificates.Add(trusted); + + Assert.Equal(CatalogVerification.NotTrustedSignature, + CatalogVerifier.VerifySignature(forged.Encode(), [ReleaseThumbprint])); + } + + [Fact] + public void UnsignedDataFails() + { + Assert.Equal(CatalogVerification.NoSignature, CatalogVerifier.VerifySignature([1, 2, 3], [ReleaseThumbprint])); + } + + private static int IndexOf(byte[] haystack, byte[] needle) + { + for (int i = 0; i <= haystack.Length - needle.Length; i++) + { + int j = 0; + while (j < needle.Length && haystack[i + j] == needle[j]) j++; + if (j == needle.Length) return i; + } + return -1; + } +} diff --git a/CDPIUI.Tests/TestData/release-catalog.cat b/CDPIUI.Tests/TestData/release-catalog.cat new file mode 100644 index 0000000000000000000000000000000000000000..0823d2c0cb83accfc38dac2f9932f42df605dd41 GIT binary patch literal 54459 zcmdsg2|QHY|No4J>{=#EC4&}4+_6Sls8H5I6rrryvnS$Cmb7Tm!c&r@RhCwX78O}a z;-Ot-X+gA0+yC5|XSl;mw;A{Oe!su}t5-eN=kqz|e9mWif0hH$>MsZgO-nFI_##Fe z&UcVje+;74ALb(xsS=QwfRIaq3DJERiI2!nfM|CW1ca0Yh$JFSN0@k!c6T)Rk_03w zApFl4MTtbx2!*M|#ry*N^Ha1Z2+aDDO_CB**M@YdI_i)nRfD=55=Z^`Fy#MQQw_nd zNE8COMe=#Pgy@<{&mB4zr&K1!&y`f4*YHD7!>?FAUUL@}z7CD(|6RUeR6ZI3vhDi{ zACW{gh8CcHhL0$7h%c4^Q3ospn-*l>_rDe8BT^SZCKE;wj0mdU`G66jJ5&{7aO9-~$Uu(co0N}u# z&Q%EbuOIk2!dWQzsX+SokgvKC?7)J8z;{-Izn*|sKkzk#(@Mapj==?ZxcSM|Iok|p zt%*A9ZQzqhg$vkl3h!rO72XQLn>aEXIFQ-pfQ3Lhvmpd^u)_%3j7_x$A0fN$3YN1P zFzpYPLnRmxR)LR0!PkEOv;B+7B9TdUDL2mOO}Oqi{KmzQcyZmM&QCR|@Fq5k31eA{ z7v#ZlC1(9ASwOHDuQN_W&(@ ztH2FF$H>KL2iunkZ7Hs44E7GZ!^2mBea@HYd}=E&dp-_oQJ1xS>U1g~L2&6>}f z>Ph$KOuk9uHx_r2+$dS{le97T+VY#dRQUNo7I-!+ShS!aXck+#2J{6x>_}Ju_7&M< z6L12E#0K|SC+1Hf-$e`$Q<)c%$Rl@ZkF5T=fi!vXu?7{BSH4kGES6B=3^t30H?bT* z6cowv09;swm!XcC7s`=f4uk~}Sj1?00s%oj4K7*BUw8COqdSs^&*++I5ZNm4E z$fJeYFWOi-&3ST6^Lom;jZw-W5wEH1*)ZhI!jL1hoFhYX2dXVJOLk!IeCa-fANa@y z9DDzF`wp2#oJXRJcIeo$`n1vap8YopH0qu~RSRu;UsUsBIIe#S7)}g#et|aF7(^$90$Ypt48a61@L2#jJ%(%Zr@q2_ zu#30XF9{2O_+7`M+g(uGe(UALZKMAX91V{H=xc8A2-8{}W6!u!}P z6i#3{)(9w!EV^81MnY?m8 z)r$?+HY`jVLGw8>J#FAV27x_v?Atw6u*Zma(RYqU97m!^nfw2>tnPkn=>F!i%rV5& z>GR}IB`Tfi*t@j7#b{e@78U-?h9TZA9TqL%d9y6^zpTE2=PkV~^Oj@Q+2ZrHJwD3? z4rtFwd85b1^9Gim3;T$8b$;MaC=hXmwL{cm0J!-+^v_j6V1wLyMC?_8sX<}~#GeZS zR|NSt810=zkjOID+Bvg=p6UyCYpoTeJ+h>HxR^_IVRLF`EW0}!(&s2f3iE*XZw2Tx zctHH5KssG-@Grs-@QdKjB#K;8!94NZD_rZQ^N%zs6gXMZnjd_+W@hEe3axu?ZOwsH zxRwncyh#rhEy#mqdG^p!j?2^UzuJR?9|Pc`xB>GS0Ib$Za3~Au+wRxzlK7Iy6sefQ zj*Ypytar}b`R19dz40^2BUGD#O9f&vmxU*F2;#_-BoZ+C{d3SL_Y-a)Q7B$Xd!oZj z?|xg>l?UH_WBF>_l>09a6fFM5SF=|otE!ECWXpv!%Fqgk0SW@EMl=NC#~}I`95ipo zg~c;OBhDaE|y4T&|x`)8@#GpmHTtCSzlg)nc;S(_WqXup(&rU8D zF$g}wa$N9U2;Rlj51k3aA$XBwZHHMaa_QrUkp1XTyBiQ%RofCoA}?RP`_8SW)f6p5J? zNg=w@((~0ududk$q&sK!Mr3@>I5*Diqe`lF6BYg&x1+|Q1^p-8TbM>7D?YwSu5Q1` z-)XSpagnG%VY=?puT*a~>s`tsf+mm=M*&n}4Fu5PH#5vaJOAAz%0#wtM6pDrTyfbNA0UAQzT}E`h8#E>xTILXCl%4ghxv z5k&-R^8t#h53-~Y1)2z$+#M;n6fr!MU`Tc_-!a+Kl;sit10k{oV-w@Ms>8Id>pqh?9!mbf%d^Tvr6$ zXMmIFpI{sda>@Jc1#rHnHBgT{cbaGxwnB6I4Dt1s9AYHH**M=o7P)Y~ncN^y6asrQ zVJAdXm|F9X!6_PXB#ELt*lOEchACysveB>?nmP-84w*6L=b$97frzrV@SN8@rQsHtO_vH7q zAjdwlIPwH_2P!fpgLQwfWJ03|QPdAcqYV%p6FP@fBf9jHxar3*-0P3oNTMP`h z1$|&%}?ZOo(sU zY!kfg*rTwh;z^;Y>dy~YNyrS(z( zp1?2NibZQEN}l0aGt#V#!V?67G6RB-0M4$!%sCP`154XUWS!XNP@|E@&q3pFwj1+5 z%$7C#Nux%v5fV3+!(0m4a6C#q)(D<8Dd-5YUr6+hBnX#+TZ&XPpl&FQC`_X0yf|iS zymjoeueFIYEGHB^6=^)b!ll2*}S$aD%+Sf00rYFM1G-$|S*WNt79X z`FlTn)*7;K=hm)oFY~-J9*n9mlKbjJ`c^-EZ>fAJ6|NY_AyA@Rpk15`I$Y@vBU13v zSF|xS)rz$idI`{sd*8nagm2k>ahk@Xs|u3O8gE{`g(v>X(0S-M8Es2hi^(|s6iUPC zgClyeKpzaYv!d4M-(%bW27cj5S3@W~f^H#nT}MqB_p-ER=bYgynv$fQ zD>`SLRoZd4)3Px~`H*LKEuIzvi`Gyq#E>u#7?k?y7Kqh&TFTyCcSUERXY>sPeX_A) zw`-ALag3W-oP|#ho~3?Rw74nt8>r+M$#Epx>P9c}LEHqE6gkMQ>K07j95CGwZrfh8 zjQ{WbQtpA>6@#;@K$UTkT^$HCF%u?8CE7o}A&sa?qUeo`N*$-Y*DGb)z=m~#@vpzgWW+%u_D{mo>z;g&UC zaw0Qz8}j(C2*?{xxvZ!V66dy0i-*#1@`C(NcQ_?J4I)9 z&6c$9iV-LAgmf9;r~z;pkz#Bl!8f>;*$y}Yh`MC{)Lwo-Sa(~amnkKc; zVm7&nRrpm*4u-r~gCh~j=Ay9a@!V}0PBfiQx<7e-kF_{ zji(jHqQ#9BW{m~WU=dOs?oZb#h%?`h(Ex=vSLB}3Gjsd&mc>zWo8ml|xQ$*9Y8eNW z_yKMHKa*Rf5j9B^L)EHP4u|2hCO+mNc3}~TvkO~wj=Jxum6Uo@6K`PK4NSN=ZWjxS z7z7_;^|@0Zcsoa*JFNd|u}fg0eP{GF8|-sy(i5`&z|BHpNKU`kXDHx$64|iacL@|k zJQouES5B!?RklUJwg*)B5}Td+zf-dVs&nV*H{OV-Uu-P9+axEas`Q4Sj80y?d9cBC z1gDt8=kvaZ{bkdSwwi!|c#vx~@q66seUTP=W!2q`~~tsbS;Z{U8)`n7e!v zdHnQ2TCjfD?_uda*IkbhDUYfo`#*5udoj&52$`O7jqt2VG`@mRHiB>}8Z7aBZdbNV#mG!kXexUt3p zkNFQ>A=Moo842f_AfU`ov?OtFJ18^YAy?~Q|Ysc|s_%aWg zS=hr}wH51LS%bTRlrb@rM&{raAvN&*ccqj>UQ`kzwkBYkZ{5@d@zjpD740eEBr1HI z&Hnt4X1zciyP2lg{nsu@^~x~^;%1uaJZ&0rZ_!Ze*jbaEeV_GJA z<-*{A7ZpuU1ZR3VwV5BiJ3j-@_zjB|KJgn`$DkB0{17bm%lPQAHx35;I8(5rG1jN( z(q9I{*2Y+c#lKm)`nyt>EEPV-=H~EJFvSQ~1{F;4X1%fahF}2ZSn5=H1szh7-~4yT zmLtQz-`#h4q4!Y19L^?i|N&3J;psMwviUB_AhsBI7?QLHB>t zRk&%uixC%3t-CcW%t=|?GcdNMY8B|z!Y?U|MT@tjFhf-PHxP-Tki4n~_{%6oTT1^3 z=`%*45k{25tnThNM?eOxt3*{SLR1P0o?m@mchGB^LBO(Nd}R>LW*|M%hyZMPfNpJs zRrGz2Bav-FrEV`DS7-*>hUXj-+U2HoT`r31%SP;QnOM@#8cOuwpCpQ{yoy@3$t)ma zR5i|ZrH0(vw>$0kKG=V8_eOb*1*b=Esi?c41pH0>y1%f9@!b8zxWugfCMS?0_>aUuyyJ9LjMz4(JZ`d|+e9SoIfQ9k- zX?81xK}{!q!vnBrapRNqBTa*ox0u5N=z+^BjZho4;wRH@Eh2X7eY_&r-0U-zpbo`qgX z4X^#K)-Ju!2E0IF+*AM-F$g}uq66SBO3`0VUaWs$c>|%En>Ac1DyiK%qVuf&g@dMA4wFCPnQy8 zrhOPGq;*&C?5|?|>yyqrDaxFp{_SOL;HpdOK~sDU8-95+x>&RzF4_nN`W=j%A9A&j zP?&LzY`}jR8^Th`iQsgeQ?7gN_LTJM+ON9GsDkqIjpQiuP%#qrEMcZ0k@-)aRMW+6 z=Ng7lTk5QgMB6`qmbYsg>ij28g2D!xgMlD;1|&-m%K1FBrmVhxGAGt&T%`0P{V%s; zcVu0Z8NGnd1y4c1qQ#9Ma9XA#5CczugoM-a5GG2+GRT%j1f}pk+rB>xbCB!RJiRP^ zMP704>XSd;rz`EAT&A+^ZmXwDB(OR7mBM2Y+mm%@5vcKCUWof0$$Il;~zZD1R!buR(}T!+F$~v&zWOEeA6~wGGqLsJ-!Fu%X>b> zyA6g}A&wqmh?G)B(!mF$Qy3l2fLW#iA-DIPHtLMfQyfmwTbp_0eSFROA0HczE&F0P^OZc2I8#CYanaBj;#PKrrx#s8VC#^W)m3%h66wgsfShTnq zmBgx+(UIZr^BDc5o~KFV;5;9D%_r1o>qg57lEo8kBJK8wQsFc<5;~O185{v8q#!?p z;4p07(b5sd}vN;tz_OL!^=^GD#-p=Y2)8 z^a>}AX#AnKaHz%2Ll=U(U_TvQM*k`w6;~)+eK%{5(e{kC$pTdP0y`n#v8I&~yt4*u zXd{T;-NCRuw>7O`T1RAc#gS19Y;`{DtVo436Q@YnyOzF={=VNdF|_!FO6e#(r*&Y_ z!e?4Xe;k6srTt0db^c1jbL|>LXtp6i9}X)&qsV5IQkM=qJK!D|vP3|dkUGZ*NZJ{U zLkR?!8pA6=bxI*~D5I$bizLMDwt0jE4PM+V{1J8<5ELz-DlyX*F>`E^BZPx!cOYXnV zj)dPY8C3MdzRn1~-ds*h74_Zqr9IE_`+|eBge0A1B)2XeH;H- z8wX~(#A%2>u2c~^|KgWzzI5%)$j^&DX%2O!%RnWGZfj%eD%Lm*Af$1Jt2Cz{+@2gO z`#s~^l!i@Pd?h#idk87pu~o=BH1QPk(6Q1EcE3KRyiVJ_MsADA>^tnI_43+X%Zp=( z#x&7x&R~qXAK3)?ssyR4%N}RS5^qKvY;bzxoHtuD?$NfiYWEAzQb=t{X4@-BgnPwSu-x zcf@D0Z{HezRjRpuxzlJ`U##4z`}Q!N4X#+Uc#HuV+8p0Go1jE2Y5S3O$J__^_2Mq= zi4RYo65|?^f^&%&+OgN?pZxK6y0Z&J>4KEF>7h@(a-uDH^CLw;Qvn>j!{ z>l-Xu-1N_JcK#8R6-g+00&I09*j03~8NkA~7Wn;CNhp3}{rIfbx{JcQw%hHH7>tF3 zHFAN4b7rRB;pxl7B99Oz8|Am8OeisIT)X-9^)+{1KYgSjU%lhy9p(5N#AQnPop@pk zShVoR7WzXiP~5le{_bn(`ARF@4ULixtADi`_HhO5=@_S4a;N=F=cbhh@htAcqJ__y z_80f{EtFmuu|s&R(@p>7v!=d)ZKk--|4^hOxL9w3VWaNxQk%bQpNZmH7=cBM=fVhf z3ikI-C$EJO01w$AqPQgMuZGEW2fb-ZH>GqfWwQu_@emM)ay1%_(@S!HQiJ`BMA?yl zv0hIr%^+ivU-ax*7U7}`toiKgE_|D!vN9>B!5Bo!>NM;?~a^6a8eZ&Z&~MGTooN1JM$=z zRX*JOOe|s$yoY7;;6#wz;kbR?Or6S{walr^0~r^>>3dj}Z_MZHfQ3v^9U6@*qf3BgMCu#SPsgBhqTr>H zT}iH=$4}2R(B0WkZj-mw{hXgTn2L_yW0_397%8><{oKob-|!T>?GaV~7Q^gnj#xAE=&rhc=eeI@fOhO&8Cmo*Rdet5DM+y1 z%u{9QJ&&dUyN6%PJQgvYTjtr}#8^HWtCGTOnFsGAq-n3Qp83!zZ`0>C{+>@8Tjg7d zod&;?00e=HwqMq6bHq9$#s}R52fV@qvMqDw-LOmW8zDD2enaSYzxW$}5B3T{h{lCi z*zYtj99%TSfmsC(gBp(v?~J`gQ^(4a{jQbNIxIh)bMM#B@X$ITT9C~gE7Wp?phOrM-Je9fhAy&bp48C_6+niVW$vzGLse%-cNuJ_p_ zkHGP8As5W{Z>CSj{JhU>^5zU<@y&3Cv$~HjoGdXnrRJl6!3LY!>;gsA=!G{d%n$EX zj?w3*+T-dBV-e%o8OFk+hwKc~dq58_n7%>(#A4sCYqNwr&$%qW7cl2?QNI2Aiw{hK zZXZ+30DFaB4=5I~|56XA1{la51n?!~#XzLCkn!9!yVnEz#1{q*#t~DoyjzyzZ|=M( zvN$K+EdI59l-Kh$XOB#DI8ky{%+4532Lp>1Hx7mkSRnG4Ju+1s0oRaMq0klF$Skpe zUr`0+j(*@b2%vxp3}rlWKKp2F8NbSf9r|7- zM?D(yf4DkR+dg?N*Bwz8o~w1Ck`0;*lo_v$CjU7+Wfxe^Mb*eto6|Jf8n5d#cbPU! zQkwIg8pS4%=c03Nh{q3J13G3U;AeYa;zV`(+ZM8q?v64E_y30PYd{<(`@)+@*B%IQaARv0yi&6aR6yp0vWLDxc4ieIf^s=6asRp(=6dahRiGm4H*4Ek_)%;B-ScYK3ty+3(^cm}^oBUrR} zYuICW_~^rA`1jmS8UZyPc~fIw&OBkeues!m^6rY6Gjh`|PZ(;A2WOdE1?G#m16U^z zSVmOlh2DOa|Kw18#+Ie$R%QJ4?fkAj?mZs^}%^D%$F=A@d zy%p~sed-)>9nYy!ShVn&D#hvLCQy=by41gRzc%c$Q?x1l+0&Faqps_LH^=cV73YNc zB6$iX{Q0Lt7J*GYL!2q!H1^nue5EW|uhPd`sBsZ(L$#@__Xll2{Z6G4deEk9qS%FG}^Ep2f zyL0U>WV!g}`W=krTM>QJlYL@_*NMaI9JfEOG~gvhNG6dlguO2w_2KBFUW<&Dg=$vQ zo{G&~Kn-K#t*m0nnAku|IOa=ca27TuKscSCO_%{ZcI01_(nj2;3rD^Zru?XMduQrs zX5>|!Gt)``)L{1sfIwWhPwZe@?Af06cZg{v+}<7w-#Xz^(4 z(160gTgm!9*`MTTz|+lzk=tZPJvq`@7X2bRtg~0CI>Q%C2`^)Fd^|th%nLG#*VE15 zEw+o=xtm`kT<^Aj-d;3c+A{0Afe>}5Z?UnDb6Ep!PEFL{ZQn~~8=jAt^ku^v?~@b7 zYuB|bT{}#$V0H31l~dxE-<}Z%&ye8vwl5YfZr=7~)mmszm}6K&zj(#fD#XP?+Gd8c zoi{mtvKZ+)Vs-0+pjDUoYf8()JS`5?-h5%K%?*1((75W$Y2V9}{{F!}?&D&@BzqZUV(u)}-n;?1SSx_wrzFZ{ z(>rUkuU=jdXjq*+zkH&_yZ7BAua4Ti_FUjoC9Mf$zMT4Zdgz5DWshD`)Z?Hs~IC{@I!0 z-MXm=wiNL^foI^xI42x?eCajh*BYk9x5}(tlwY(~FoUo4uj`w<73;Ij#Xd|_nHrw< z&H&FEax7Xr){yfez!-hRbSru7^K5eZ=ywg%0vnz`*#9ZnGd_w!)<1drzM_(NGUN{i zt#%BQT7ZG`rn|9d@n|K{?kPJchBe`hQI)fvL@piq{Z;Hfh0O{In|+gI9v&_Kp}vXg zF>n`v!C1m#Fy=#s91VsN`tCY|cXN@7(N;*}=q|Ndtpe^v1+zZ7c4jYD|eA;|3A;)k`LofB08pQJyBY!H-Fl8;=k4 zK75wu6s~2ye*TwMU8g!y?wG&M7(EI;H{MyL9t^H$*Qd|L`HZKATPVyhh-nr1bA zG_MqU+lpsjJQgi(`r-!$W9W*X-@Gdcg9pzlM>#;w3e-%kyz=s6%t~=P);TjIAndW61_D?@Or;>yJbw8P8V!w6Pe+$Jo&K==Ttx zC4D+o5WQ2u9n5R%!xwx>5m`;tr@KyLeOVjtxGE#|mXM)%M zWQ%pnCOM$tgT=8*Q*S#^r)lbY?@*dAhJSn1n| z`EPVG3AyF5zpFIB&8M5VI_6c+{rPscficH#6eJccZYBW!PAM^yavXXR=)Q5SX_2o_ zVyUK;_m|;nbq~ch^(NJC`Xf=J@r+PplMtcKZxj zmk#8H)u8>^tUplk((p0wqwfKeyQd{Yr+?zRS~#Wb{C4)pC$AMR?EI@gPZ_d$TIkC*kE)v!SL9f4A$lAcke4yNF$7L3ojgllQL@ zVpBdYD?B>VCi><4k;nZzG6nvy!TEx@VbjM=Zl64EyVzU4?i#!0 zrEynWZoSISx;N&+^A(_2RgjHW%3H94MGX319~lB_9Uh&uiVVp=Re0`2^StQW4Oy=f zkIeq}Y8{xz_WS-6FfZ)UuhxTFQsx%k<3Al%2#V=#GowWY7k!=*cqZ@0&&C{QJm-aB z(c-4*;CELDd*m>Pq@KvS>MN!>R%BPE$CFWk4z*6rI<{b4WVdwrG#oyF5x#G=KGv&gz=*7j9{d%6CZi0 z@%fvm?yF@@ek1&=ayOgp4d|6$>ebX#(`-7*PGq6=Ek8VK>ab{WQ&aalb-}c@td_Qr zL~h=2+F#~zl(G8Ub?Hl9k=IGR%9f>e3nDMYmU)V@*CTV{5rREO5(WEPWWnq5j3`dD?+Hzg7;lx+%0ZGY$Kg>`Gc$k)VE{?G>M_YehF z@`nI?ty7ii3LMq6gvvfVJA1IT!Ft#9@LvaKnN*eNUnuTLEx;4t!=l9vz{jc{5v{>! zqjaQK`y;L1?B96=CaNud+;}ICiYN9zqvbA@DH=HR?)S#mM4{PXnqdTpWAn5HjX0S^ zdFgw|V(k_4Q!?fU_B~W0=*fqFbq}9;siMJ>Punsyr?$Nk^!GZo0Z?$_UM%+M|?Uu$TaEGpaKQB`D|28N99 zV1Cx++gS4k=7{r6x7{T^kjC zJ#Y=c^BtP6iba!~_w5k7?+5;b0`-qPQm__yUjg8cFPOrCe69+zxd_0H00OH2Oj`+~ z+kd1JDu|v2?0?`C3<~cE*ngyHqRNV-&~b5NRHi8HTwD#Zb?g$5Fpq=6*3)2I8@-vTQ ze@rd0Gl;AGNc!e)ME+8L<@OANa_>%{du7=ygE!raMGWG(=$GAzV<}&}ihjX#z_+0( zlx3qV_{X;k3tqC+xiBX7c*jBOm%DdBsYhh9&#h%sp$G2xToz|s9fCMI%NS} z+M#I)EUqCWANaOKA}QeBQex=Hq==ATX3rNjI&Lp1on|$xht%O+s&)_0d>|Gr-t&R| zHihvhC-eO+GoZSH=}K%hefk!tQ=k_|b*0u`Yw6h%*rR`c$tie4mi{4mv#2@;Z9$bhRFnoA#gz!)w3Ui87DHKZ4Pe&@Pz`5-ZzOCo<#nss4?w8NxD$3-n;Y_&|9X}3T) z`0va>Lx8-2&lqyuNBYSi?XLo-WQ>wxH|bMj5hrmrEVmzsOF`7JpjynK@)@VM|h9fm{kCz#hCXipHok|>|* z76+ZIT{Z8HY{1*I)y3&yLXrHEWfl&n^TUsnoqHffg&*POXkpQU{_`(K2a(91hj&h~ z)Y=(wGhTR~$;*+uE-Fjkr!Hr+XfFCOf`DcoILt7RuDO9JhXG3VIm}t$zQ&}L(w{P% z@4d`>pPX7o94bmS&^R!1-XG|LzTTes>-NQ3 zJ>OmFH~n(X@odSP73+)e?dxTjPhKCA;sLIW0;?(@=WdwpK2p6-%2d91ZdAhF))J~4 z8{x-)iYyGO$a)^C9jPD&&&bl*6Qgu)jcwlIsbGrjCN}iLSfUay$b(~4Vm1)hVK!}{0)GF2kE zPR+r|{~Rdg!Ebx8Xz{o`e;$=_m&*W=`Y$!on3E2AA0sMZ0goJHb2C3HnP z#jjmsc2{GAZ>49s!Q%3+uXFuAg!mZjyI&p;> zpyN%m>&PPQFU2}XHEy`P^!TIbWin@^3YJz2ZOKbHKjFF6t*c3MB{ub54PUxr$7q$~ zlIy>kF}3rpkK!fr}IN?&C9B)Mc|!Jbl+Z*VlZ*hy)^f zhrsrO9U>B3WD~9H#!J5bzFmH#r;OljeeyT;K)%jA!Klqrrky{<$In-mNHsm)yp=F{ zxbe=*B@U(6dWQRkyuPU=R(q0KIe&A?@v#e(3|qwgw%M3(m&@I_(@t^C>m7BQ`5go7 zyt8dw6zV?m-%4woAHVhM&IMyJ9-FrQaw}2)N`cLrEo+_@pO`pDa7$Wv_T_WOo!11W)P9t)&r7ZS z`TmN@)X%e~oGc&PaiVQ%qW^@#Wmn-_t|_nb3$>=L$hG+-;dD^=ROsir?O%UgBM--*< zK?F#;Ptb*iQAGrVlm&<+B27n_2&wgdheTB%QJgAuD;6zz;TB6hUw7-%3H8dOGslxE z{Cq|^oSZ%OqB|LVXn-0C1TVq`rr9#lXipM~iy@&+gfAVz$AWkKF-^B6lRVQEx|$EbrakQha92s=G^$-;FkS z;=DbpE^yP%2KSTs^G)Zy$qrC!h3bz}VlSU)SxhSU>&vYc2a~cRXU@III&?|!$g(jj z{L?q{8)u4HAD=^hXk&gNMW(#g+;4QYZ{tnF$@?Cu&x`-HMkmT9W6b#rrI+U!j9mDR zR=eC|?1s1yk6izm#wRS!ML}5~eSVx==>AEm!l~3YM$W@=!n>I??Mb8sCF$)3qr|mD fiHA+^6^?YDZr Date: Fri, 23 Oct 2026 16:43:15 +0000 Subject: [PATCH 060/202] Check update and installer packages in the tray before running them The elevated tray installed any MSI or ran any EXE with /install that the UI pointed to, and started Update.exe on a patch in the user's data directory, where it could be swapped after the UI had checked it. The tray now copies every package into .staging under the installation directory and works only with that copy: - store installers must have a valid Authenticode signature (the store ships the signed Windows Packet Filter MSI and vc_redist); - update packages must carry a catalog signed by a pinned certificate for every layer, checked again with CatalogVerifier; - application MSIs are only staged, because the published Setup.msi is not signed. The update package itself was broken: the merged CDPIUI folder was moved out before the archive was created, so patch.cdpipatch held only requirements.json, and merging several patches into one folder would have left files that no catalog covers. Each patch is now packed as its own layer (layers/0/, layers/1/, ...) with its catalog, and Update.exe applies the layers in order; a published patch with a single CDPIUI folder still works. The temporary patch folder is now deleted recursively. --- .../Application/ApplicationUpdateService.cs | 28 ++- CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs | 15 +- CDPIUI.TrayIcon/Helper/PackageStaging.cs | 171 ++++++++++++++++++ CDPIUI.TrayIcon/Helper/UninstallHelper.cs | 2 +- CDPIUI.TrayIcon/Helper/Utils.cs | 28 ++- CDPIUI.TrayIcon/Program.cs | 2 + Update/InstallHelper.cs | 50 +++-- 7 files changed, 266 insertions(+), 30 deletions(-) create mode 100644 CDPIUI.TrayIcon/Helper/PackageStaging.cs diff --git a/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs b/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs index 1a7b5f4a..ff462922 100644 --- a/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs +++ b/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs @@ -23,7 +23,6 @@ public async Task> GetPatchReadyToInstall( string appItemDirectory = Path.Combine(Directories.StoreItemsDirectory, SharedConstants.ApplicationStoreId); string patchesDirectory = Path.Combine(appItemDirectory, "Patches"); - string finalDirectory = Path.Combine(appItemDirectory, "CDPIUI"); string patchDirectory = Path.Combine( patchesDirectory, @@ -61,7 +60,6 @@ public async Task> GetPatchReadyToInstall( FinalizePatch( downloadedPatches, patchDirectory, - finalDirectory, appItemDirectory); return OperationResultModel.SuccessResult(); @@ -74,7 +72,7 @@ public async Task> GetPatchReadyToInstall( { try { - Directory.Delete(patchesDirectory); + Directory.Delete(patchesDirectory, recursive: true); } catch { } } @@ -192,18 +190,28 @@ private static async Task ValidateCatalog(string dir) throw new CatalogInvalid(); } - private void FinalizePatch(List patches, string patchDirectory, string finalDirectory, string appItemDirectory) + /// + /// Packs the required patches, oldest first, and the main patch as separate layers + /// (layers/0/, layers/1/, ...). Each layer keeps its own signed catalog, so the elevated + /// tray can check every signature again before Update.exe applies the layers in order. + /// + private void FinalizePatch(List patches, string patchDirectory, string appItemDirectory) { - foreach (string dir in patches) - { - Directory.Move(dir, finalDirectory); - } - Directory.Move(Path.Combine(patchDirectory, "CDPIUI"), finalDirectory); + var layers = new List(patches) { Path.Combine(patchDirectory, "CDPIUI") }; string finalPatchFile = Path.Combine(appItemDirectory, "patch.cdpipatch"); if (File.Exists(finalPatchFile)) File.Delete(finalPatchFile); - ZipFile.CreateFromDirectory(patchDirectory, finalPatchFile); + + using ZipArchive archive = ZipFile.Open(finalPatchFile, ZipArchiveMode.Create); + for (int i = 0; i < layers.Count; i++) + { + foreach (string file in Directory.EnumerateFiles(layers[i], "*", SearchOption.AllDirectories)) + { + string relativePath = Path.GetRelativePath(layers[i], file).Replace('\\', '/'); + archive.CreateEntryFromFile(file, $"layers/{i}/{relativePath}"); + } + } } private static ErrorModel HandleException(Exception ex) diff --git a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs index f13bd812..03b7210f 100644 --- a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs +++ b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs @@ -158,20 +158,27 @@ private void TryStartNext() private async Task ProcessMsi(string operationId, string filePath) { + string? stagedPath = null; try { if (!TrustedPaths.IsAllowed(filePath, "package installation")) throw new UnauthorizedAccessException("The package is outside the application directories."); + // Installers from the store (driver and runtime packages) are signed by their vendors. + // The copy is checked and run, so the user's copy cannot be swapped after the check. + stagedPath = PackageStaging.Stage(filePath); + if (!PackageStaging.HasValidSignature(stagedPath)) + throw new UnauthorizedAccessException("The package does not have a valid signature."); + _ = PipeHelper .SendMsiInstallationPacket(MSIInstallationMessageIds.SetOperationStatus, operationId, MsiState.Installing); lock (_lock) { - if (string.Equals(Path.GetExtension(filePath), ".msi", StringComparison.OrdinalIgnoreCase)) - _currentProcess = RunHelper.Run("msiexec.exe", $"/i \"{filePath}\" /passive /norestart"); + if (string.Equals(Path.GetExtension(stagedPath), ".msi", StringComparison.OrdinalIgnoreCase)) + _currentProcess = RunHelper.Run("msiexec.exe", $"/i \"{stagedPath}\" /passive /norestart"); else - _currentProcess = RunHelper.Run(filePath, $"/install /passive /norestart"); + _currentProcess = RunHelper.Run(stagedPath, $"/install /passive /norestart"); } if (_currentProcess == null) @@ -223,6 +230,8 @@ private async Task ProcessMsi(string operationId, string filePath) _currentProcess = null; _currentOperationId = null; } + if (stagedPath != null) + PackageStaging.Release(stagedPath); TryStartNext(); } diff --git a/CDPIUI.TrayIcon/Helper/PackageStaging.cs b/CDPIUI.TrayIcon/Helper/PackageStaging.cs new file mode 100644 index 00000000..38aba091 --- /dev/null +++ b/CDPIUI.TrayIcon/Helper/PackageStaging.cs @@ -0,0 +1,171 @@ +using CDPIUI.Shared.Secrets; +using CDPIUI.Shared.Security; +using CDPIUI.TrayIcon.Helper.Basic; +using System.IO.Compression; +using System.Runtime.InteropServices; + +namespace CDPIUI.TrayIcon.Helper +{ + /// + /// Copies packages that the tray installs elevated out of the user's data directory and checks + /// them there, so the file cannot be replaced between the check and the installation + /// + public static class PackageStaging + { + // Under the installation directory, which only administrators can change in a per-machine installation. + private static string Root => Path.Combine(Utils.GetDataDirectory(), ".staging"); + + public static string Stage(string sourcePath) + { + string directory = Path.Combine(Root, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + string stagedPath = Path.Combine(directory, Path.GetFileName(sourcePath)); + File.Copy(sourcePath, stagedPath); + return stagedPath; + } + + public static void Release(string stagedPath) + { + try + { + string? directory = Path.GetDirectoryName(stagedPath); + if (directory != null && Directory.Exists(directory)) + Directory.Delete(directory, true); + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(PackageStaging), $"Cannot delete {stagedPath}: {ex.Message}"); + } + } + + /// + /// Removes packages left from earlier runs, for example by an installer that was started without waiting. + /// + public static void CleanUp() + { + try + { + if (Directory.Exists(Root)) + Directory.Delete(Root, true); + } + catch { } + } + + /// + /// Checks the signed catalog of every layer of an application update package + /// + public static async Task VerifyUpdatePackageAsync(string stagedPackage) + { + string verifyDirectory = Path.Combine(Path.GetDirectoryName(stagedPackage)!, "verify"); + try + { + using (ZipArchive archive = ZipFile.OpenRead(stagedPackage)) + { + archive.ExtractToDirectory(verifyDirectory); + } + + string layersDirectory = Path.Combine(verifyDirectory, "layers"); + List layers = Directory.Exists(layersDirectory) + ? Directory.GetDirectories(layersDirectory).ToList() + : [Path.Combine(verifyDirectory, "CDPIUI")]; + + if (layers.Count == 0 || !layers.All(Directory.Exists)) + return false; + + foreach (string layer in layers) + { + CatalogVerification result = await CatalogVerifier.VerifyAsync( + Path.Combine(layer, "catalog.cat"), layer, Secret.TrustedCertificates); + if (result != CatalogVerification.Success) + { + Logger.Instance.CreateWarningLog(nameof(PackageStaging), $"Update layer {Path.GetFileName(layer)} failed verification: {result}"); + return false; + } + } + return true; + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(PackageStaging), $"Cannot verify the update package: {ex.Message}"); + return false; + } + finally + { + try { if (Directory.Exists(verifyDirectory)) Directory.Delete(verifyDirectory, true); } catch { } + } + } + + /// + /// Checks that the file has a valid Authenticode signature that chains to a trusted root + /// + public static bool HasValidSignature(string path) + { + var fileInfo = new WINTRUST_FILE_INFO + { + cbStruct = (uint)Marshal.SizeOf(), + pcwszFilePath = path, + }; + IntPtr fileInfoPointer = Marshal.AllocHGlobal(Marshal.SizeOf()); + try + { + Marshal.StructureToPtr(fileInfo, fileInfoPointer, false); + var data = new WINTRUST_DATA + { + cbStruct = (uint)Marshal.SizeOf(), + dwUIChoice = WTD_UI_NONE, + fdwRevocationChecks = WTD_REVOKE_NONE, + dwUnionChoice = WTD_CHOICE_FILE, + pFile = fileInfoPointer, + dwStateAction = WTD_STATEACTION_IGNORE, + }; + + Guid action = WINTRUST_ACTION_GENERIC_VERIFY_V2; + int result = WinVerifyTrust(IntPtr.Zero, ref action, ref data); + if (result != 0) + Logger.Instance.CreateWarningLog(nameof(PackageStaging), $"Signature check of {path} failed: 0x{result:X8}"); + return result == 0; + } + finally + { + Marshal.DestroyStructure(fileInfoPointer); + Marshal.FreeHGlobal(fileInfoPointer); + } + } + + private static readonly Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 = new("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); + private const uint WTD_UI_NONE = 2; + private const uint WTD_REVOKE_NONE = 0; + private const uint WTD_CHOICE_FILE = 1; + private const uint WTD_STATEACTION_IGNORE = 0; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct WINTRUST_FILE_INFO + { + public uint cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] public string pcwszFilePath; + public IntPtr hFile; + public IntPtr pgKnownSubject; + } + + [StructLayout(LayoutKind.Sequential)] + private struct WINTRUST_DATA + { + public uint cbStruct; + public IntPtr pPolicyCallbackData; + public IntPtr pSIPClientData; + public uint dwUIChoice; + public uint fdwRevocationChecks; + public uint dwUnionChoice; + public IntPtr pFile; + public uint dwStateAction; + public IntPtr hWVTStateData; + public IntPtr pwszURLReference; + public uint dwProvFlags; + public uint dwUIContext; + public IntPtr pSignatureSettings; + } + + [DllImport("wintrust.dll", ExactSpelling = true, SetLastError = false, CharSet = CharSet.Unicode)] + private static extern int WinVerifyTrust(IntPtr hwnd, ref Guid pgActionID, ref WINTRUST_DATA pWVTData); + } +} diff --git a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs index 7454cbda..e482904a 100644 --- a/CDPIUI.TrayIcon/Helper/UninstallHelper.cs +++ b/CDPIUI.TrayIcon/Helper/UninstallHelper.cs @@ -169,7 +169,7 @@ private static void RemoveHostsBlock(string installDirectory) // Files the application creates next to the installed ones; the package does not know them, // so the installation directory would otherwise stay behind. - private static readonly string[] RuntimeDirectories = ["Logs", ".update-staging", ".update-backup", ".old"]; + private static readonly string[] RuntimeDirectories = ["Logs", ".update-staging", ".update-backup", ".old", ".staging"]; private static readonly string[] RuntimeFiles = ["update.log", ".update-manifest"]; private static void RemoveRuntimeFiles(string installDirectory) diff --git a/CDPIUI.TrayIcon/Helper/Utils.cs b/CDPIUI.TrayIcon/Helper/Utils.cs index e72077c5..62de7cb9 100644 --- a/CDPIUI.TrayIcon/Helper/Utils.cs +++ b/CDPIUI.TrayIcon/Helper/Utils.cs @@ -64,7 +64,7 @@ public static string GetSettingsFile() } } - public static void StartUpdate(string targetFile) + public static async void StartUpdate(string targetFile) { if (!TrustedPaths.IsAllowed(targetFile, "application update")) { @@ -72,16 +72,36 @@ public static void StartUpdate(string targetFile) return; } - if (Path.GetExtension(targetFile).ToLower() == ".msi") + // The installer runs from a copy the user cannot change, checked where possible. + string stagedFile; + try + { + stagedFile = PackageStaging.Stage(targetFile); + } + catch (Exception ex) { - RunHelper.Run("msiexec.exe", $"/i \"{targetFile}\" /qn+"); + Logger.Instance.CreateErrorLog(nameof(Utils), $"Cannot copy the update package: {ex.Message}"); + NotifyHelper.ShowMessage("CDPI UI", LocaleHelper.GetLocaleString("UpdateFailure"), "UPDATE:OPEN_LOG"); + return; + } + + if (Path.GetExtension(stagedFile).ToLower() == ".msi") + { + // Published Setup.msi files are not Authenticode-signed, so there is no signature to check yet. + RunHelper.Run("msiexec.exe", $"/i \"{stagedFile}\" /qn+"); _ = PipeHelper.SendApplicationPacket(ApplicationMessageIds.CloseApplicationUI); NotifyHelper.Instance.Dispose(); Application.Exit(); } else { - RunHelper.Run(Path.Combine(GetDataDirectory(), "Update.exe"), $"--directory-to-zip \"{targetFile}\" --destination-directory \"{GetDataDirectory()}\""); + if (!await PackageStaging.VerifyUpdatePackageAsync(stagedFile)) + { + PackageStaging.Release(stagedFile); + NotifyHelper.ShowMessage("CDPI UI", LocaleHelper.GetLocaleString("UpdateFailure"), "UPDATE:OPEN_LOG"); + return; + } + RunHelper.Run(Path.Combine(GetDataDirectory(), "Update.exe"), $"--directory-to-zip \"{stagedFile}\" --destination-directory \"{GetDataDirectory()}\""); } } diff --git a/CDPIUI.TrayIcon/Program.cs b/CDPIUI.TrayIcon/Program.cs index b9383485..97d90889 100644 --- a/CDPIUI.TrayIcon/Program.cs +++ b/CDPIUI.TrayIcon/Program.cs @@ -40,6 +40,8 @@ static void Main(string[] args) ToastNotificationManagerCompat.History.Clear(); + PackageStaging.CleanUp(); + PipeServer.Instance.Init(); PipeServer.Instance.Start(); diff --git a/Update/InstallHelper.cs b/Update/InstallHelper.cs index 55a05618..a57cd62e 100644 --- a/Update/InstallHelper.cs +++ b/Update/InstallHelper.cs @@ -56,7 +56,8 @@ public static InstallHelper Instance private string _targetFolder; private string _targetExecutable; private readonly List _skipFiles = new List { "Update.exe", "catalog.cat" }; - private const string UiRootPrefix = "CDPIUI/"; + private const string UiRootPrefix = "CDPIUI/"; + private const string LayersPrefix = "layers/"; public Action InstallationStateChanged; public Action ProgressChanged; @@ -262,26 +263,30 @@ private async Task> StageAsync() using (var zip = ZipFile.OpenRead(_archiveFilePath)) { - var fileEntries = zip.Entries - .Where(e => - { - var name = e.FullName.Replace('\\', '/'); - return name.StartsWith(UiRootPrefix, StringComparison.OrdinalIgnoreCase) && !name.EndsWith("/"); - }) + // Entries with the path relative to the installation, layer by layer: a later + // layer overwrites the files of an earlier one. + var fileEntries = GetLayerPrefixes(zip) + .SelectMany(prefix => zip.Entries + .Select(e => new { Entry = e, Name = e.FullName.Replace('\\', '/') }) + .Where(e => e.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && !e.Name.EndsWith("/")) + .Select(e => new { e.Entry, RelativePath = e.Name.Substring(prefix.Length) })) .ToList(); int totalFiles = fileEntries.Count; if (totalFiles == 0) { - Log($"No files found to extract in archive under '{UiRootPrefix}'."); + Log("No files found to extract in the update archive."); FinishStatus = InstallError.ExtractingFile; return null; } var staged = new List(); - foreach (var entry in fileEntries) + var stagedSet = new HashSet(StringComparer.OrdinalIgnoreCase); + int extracted = 0; + foreach (var item in fileEntries) { - var relativePath = entry.FullName.Replace('\\', '/').Substring(UiRootPrefix.Length); + var entry = item.Entry; + var relativePath = item.RelativePath; string destPath; string stagedPath; if (!TryGetDestination(_targetFolder, relativePath, out destPath) || @@ -307,8 +312,9 @@ private async Task> StageAsync() await stream.CopyToAsync(outFile); } - staged.Add(relativePath); - ProgressChanged?.Invoke((double)staged.Count / totalFiles); + if (stagedSet.Add(relativePath)) + staged.Add(relativePath); + ProgressChanged?.Invoke((double)++extracted / totalFiles); } return staged; @@ -328,6 +334,26 @@ private async Task> StageAsync() } } + /// + /// Prefixes of the archive folders to apply, in order: layers/0/, layers/1/, ... in packages + /// made by the application, or CDPIUI/ in a single published patch. + /// + private static List GetLayerPrefixes(ZipArchive zip) + { + var layers = zip.Entries + .Select(e => e.FullName.Replace('\\', '/')) + .Where(name => name.StartsWith(LayersPrefix, StringComparison.OrdinalIgnoreCase)) + .Select(name => name.Substring(LayersPrefix.Length).Split('/')[0]) + .Distinct() + .Select(index => { int number; return int.TryParse(index, out number) ? number : -1; }) + .Where(number => number >= 0) + .OrderBy(number => number) + .Select(number => $"{LayersPrefix}{number}/") + .ToList(); + + return layers.Count > 0 ? layers : new List { UiRootPrefix }; + } + /// /// Moves the staged files into place. Replaced files are kept in the backup folder /// and moved back if any file cannot be applied. From 4b77021ab89d01af3ed317e55efe9fd4598c6e0d Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:44:29 +0000 Subject: [PATCH 061/202] Do not let the elevated tray run user-chosen programs Opening a log from a tray notification went through ShellExecute in the elevated tray, and the handler of a file type is taken from HKCU, so any program the user registered for .log ran with administrator rights. The file is now opened by explorer.exe started with the desktop user's token, or by notepad.exe from System32 if that is not possible. The tray also started sc, msiexec.exe and powershell.exe by bare name, which .NET first looks up in the application directory; they now run from System32. The output and error streams of service commands are read concurrently. --- CDPIUI.Shared/Security/CatalogVerifier.cs | 4 +++- CDPIUI.TrayIcon/Helper/Basic/NotifyHelper.cs | 17 ++++++++++++----- CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs | 2 +- CDPIUI.TrayIcon/Helper/ProcessManager.cs | 11 +++++++---- CDPIUI.TrayIcon/Helper/Utils.cs | 2 +- 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/CDPIUI.Shared/Security/CatalogVerifier.cs b/CDPIUI.Shared/Security/CatalogVerifier.cs index 448cee96..59ce8de8 100644 --- a/CDPIUI.Shared/Security/CatalogVerifier.cs +++ b/CDPIUI.Shared/Security/CatalogVerifier.cs @@ -90,7 +90,9 @@ private static string NormalizeThumbprint(string thumbprint) => private static async Task VerifyFilesAsync(string catalogFile, string directory) { - var startInfo = new ProcessStartInfo("powershell.exe") + // A full path: the elevated tray would otherwise also look in its own, possibly writable, directory. + string powershell = Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"); + var startInfo = new ProcessStartInfo(powershell) { RedirectStandardOutput = true, RedirectStandardError = true, diff --git a/CDPIUI.TrayIcon/Helper/Basic/NotifyHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/NotifyHelper.cs index be2ef74b..48139001 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/NotifyHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/NotifyHelper.cs @@ -129,12 +129,19 @@ public static void OpenFileInDefaultApp(string filePath) { try { - var psi = new ProcessStartInfo + // The tray is elevated, and the handler of a file type comes from HKCU: opening the file + // through the shell here would run a program the user chose with administrator rights. + string fullPath = Path.GetFullPath(filePath); + string explorer = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"); + if (RunHelper.RunAsDesktopUser(explorer, $"\"{fullPath}\"")) + return; + + Process.Start(new ProcessStartInfo { - FileName = Path.GetFullPath(filePath), - UseShellExecute = true - }; - Process.Start(psi); + FileName = Path.Combine(Environment.SystemDirectory, "notepad.exe"), + Arguments = $"\"{fullPath}\"", + UseShellExecute = false, + }); } catch (Exception ex) { diff --git a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs index 03b7210f..8bd05345 100644 --- a/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs +++ b/CDPIUI.TrayIcon/Helper/MsiInstallerHelper.cs @@ -176,7 +176,7 @@ private async Task ProcessMsi(string operationId, string filePath) lock (_lock) { if (string.Equals(Path.GetExtension(stagedPath), ".msi", StringComparison.OrdinalIgnoreCase)) - _currentProcess = RunHelper.Run("msiexec.exe", $"/i \"{stagedPath}\" /passive /norestart"); + _currentProcess = RunHelper.Run(Path.Combine(Environment.SystemDirectory, "msiexec.exe"), $"/i \"{stagedPath}\" /passive /norestart"); else _currentProcess = RunHelper.Run(stagedPath, $"/install /passive /norestart"); } diff --git a/CDPIUI.TrayIcon/Helper/ProcessManager.cs b/CDPIUI.TrayIcon/Helper/ProcessManager.cs index a333b636..fd324715 100644 --- a/CDPIUI.TrayIcon/Helper/ProcessManager.cs +++ b/CDPIUI.TrayIcon/Helper/ProcessManager.cs @@ -180,7 +180,7 @@ public static async Task StopService() string error = "NaN"; try { - await ExecuteCommand("sc", "stop WinDivert"); + await ExecuteCommand(Path.Combine(Environment.SystemDirectory, "sc.exe"), "stop WinDivert"); } catch (Exception ex) { @@ -188,7 +188,7 @@ public static async Task StopService() } try { - await ExecuteCommand("sc", "delete WinDivert"); + await ExecuteCommand(Path.Combine(Environment.SystemDirectory, "sc.exe"), "delete WinDivert"); } catch (Exception ex) { @@ -221,9 +221,12 @@ private static async Task ExecuteCommand(string fileName, string arguments) process.StartInfo.CreateNoWindow = true; process.Start(); - string output = process.StandardOutput.ReadToEnd(); - string error = process.StandardError.ReadToEnd(); + // Both streams are read at once, so a full error pipe cannot block the process. + Task outputTask = process.StandardOutput.ReadToEndAsync(); + Task errorTask = process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); + string output = await outputTask; + string error = await errorTask; if (process.ExitCode != 0) { diff --git a/CDPIUI.TrayIcon/Helper/Utils.cs b/CDPIUI.TrayIcon/Helper/Utils.cs index 62de7cb9..dcb3a071 100644 --- a/CDPIUI.TrayIcon/Helper/Utils.cs +++ b/CDPIUI.TrayIcon/Helper/Utils.cs @@ -88,7 +88,7 @@ public static async void StartUpdate(string targetFile) if (Path.GetExtension(stagedFile).ToLower() == ".msi") { // Published Setup.msi files are not Authenticode-signed, so there is no signature to check yet. - RunHelper.Run("msiexec.exe", $"/i \"{stagedFile}\" /qn+"); + RunHelper.Run(Path.Combine(Environment.SystemDirectory, "msiexec.exe"), $"/i \"{stagedFile}\" /qn+"); _ = PipeHelper.SendApplicationPacket(ApplicationMessageIds.CloseApplicationUI); NotifyHelper.Instance.Dispose(); Application.Exit(); From a90a1c1a52a8cbf92e9a64b5d83de0a71db49d49 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:45:05 +0000 Subject: [PATCH 062/202] Keep tray task directory and settings parsing inside safe limits The UI could make the elevated tray create and watch any directory as the conditional tasks directory; it now has to be in the application directories. Settings files are read by the elevated tray from a location the user can change, so DTD processing is now prohibited when they are parsed. --- CDPIUI.Shared/Basic/XMLSettingsService.cs | 7 ++++++- .../ConditionalLaunch/ConditionalLaunchEngine.cs | 5 ++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CDPIUI.Shared/Basic/XMLSettingsService.cs b/CDPIUI.Shared/Basic/XMLSettingsService.cs index 61f9f673..b360deaa 100644 --- a/CDPIUI.Shared/Basic/XMLSettingsService.cs +++ b/CDPIUI.Shared/Basic/XMLSettingsService.cs @@ -94,7 +94,12 @@ private static bool IsReadFailure(Exception exception) => private static XDocument LoadDocument(string path) { - var document = XDocument.Load(path); + // Settings are read by the elevated tray from a file the user can change: no DTD processing, + // so internal entities cannot blow up the memory of the elevated process. + var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; + XDocument document; + using (var reader = XmlReader.Create(path, readerSettings)) + document = XDocument.Load(reader); if (document.Root?.Name != "Settings") throw new XmlException("The settings document must have a Settings root element."); return document; diff --git a/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs b/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs index 91db3da3..d1b71f7b 100644 --- a/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs +++ b/CDPIUI.TrayIcon/ConditionalLaunch/ConditionalLaunchEngine.cs @@ -86,7 +86,10 @@ public void Reload(string? tasksDirectory = null) string? directory; lock (_sync) { - if (!string.IsNullOrWhiteSpace(tasksDirectory)) + // The directory comes from the UI; the elevated tray only creates and watches one in the + // application directories. + if (!string.IsNullOrWhiteSpace(tasksDirectory) && + TrustedPaths.IsAllowed(tasksDirectory, "conditional tasks directory")) ConfigureTasksDirectory(tasksDirectory); directory = _tasksDirectory; } From 0acfe15b75a6adc0b18fe030ea6fe5e1ea014e56 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:45:14 +0000 Subject: [PATCH 063/202] Fall back to the template log level instead of debug logging Release builds wrote debug logs whenever the logLevel setting was missing or invalid, while the settings template sets WARN. --- CDPIUI.Core/Basic/Logger.cs | 2 +- CDPIUI.TrayIcon/Helper/Basic/Logger.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CDPIUI.Core/Basic/Logger.cs b/CDPIUI.Core/Basic/Logger.cs index 221ff255..f84aa745 100644 --- a/CDPIUI.Core/Basic/Logger.cs +++ b/CDPIUI.Core/Basic/Logger.cs @@ -30,7 +30,7 @@ private static LogSelevirity GetSelevirity() #if DEBUG return LogSelevirity.DEBG; #else - return SettingsManager.Instance.GetValue("DEBUG", "logLevel").ToEnum(LogSelevirity.DEBG); + return SettingsManager.Instance.GetValue("DEBUG", "logLevel").ToEnum(LogSelevirity.WARN); #endif } } diff --git a/CDPIUI.TrayIcon/Helper/Basic/Logger.cs b/CDPIUI.TrayIcon/Helper/Basic/Logger.cs index 16107bce..b9c8ab77 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/Logger.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/Logger.cs @@ -36,7 +36,7 @@ private static LogSelevirity GetSelevirity() #if DEBUG return LogSelevirity.DEBG; #else - return SettingsManager.Instance.GetValue("DEBUG", "logLevel").ToEnum(LogSelevirity.DEBG); + return SettingsManager.Instance.GetValue("DEBUG", "logLevel").ToEnum(LogSelevirity.WARN); #endif } } From b922dde0565a5074bc55412a1423d6d7527b5777 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:45:44 +0000 Subject: [PATCH 064/202] Retry pipe creation instead of exiting when another process holds the name The tray recreates its pipe after every client and killed itself whenever creating it failed, so any local process that grabbed the name in between took the tray down for good. It now exits only when another tray instance is running and otherwise retries; clients already check that the server is the tray. --- .../Helper/Basic/ConnectionHelper.cs | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs b/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs index 7c6d8664..e994b249 100644 --- a/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs +++ b/CDPIUI.TrayIcon/Helper/Basic/ConnectionHelper.cs @@ -70,11 +70,21 @@ private async Task ListenLoopAsync() } catch (Exception ex) { - Logger?.CreateDebugLog(nameof(PipeServer), - $"Terminating PID={Environment.ProcessId}: pipe creation failed. " + - $"Another tray instance may already own the pipe. Exception: {ex}"); - Process.GetCurrentProcess().Kill(); - return; + if (IsAnotherTrayRunning()) + { + Logger?.CreateDebugLog(nameof(PipeServer), + $"Terminating PID={Environment.ProcessId}: pipe creation failed and another tray instance is running. " + + $"Exception: {ex}"); + Process.GetCurrentProcess().Kill(); + return; + } + + // Another process took the name while the pipe was being recreated. Clients check + // that the server is this tray, so waiting for the name to be released is enough. + Logger?.CreateWarningLog(nameof(PipeServer), $"Cannot create the pipe, retrying: {ex.Message}"); + try { await Task.Delay(TimeSpan.FromSeconds(2), CancellationToken ?? default); } + catch (OperationCanceledException) { break; } + continue; } try @@ -120,6 +130,20 @@ private async Task ListenLoopAsync() } } + private static bool IsAnotherTrayRunning() + { + using var current = Process.GetCurrentProcess(); + Process[] trays = Process.GetProcessesByName(current.ProcessName); + try + { + return trays.Any(process => process.Id != current.Id); + } + finally + { + foreach (var process in trays) process.Dispose(); + } + } + protected override async Task RunMessageActions(IPipeMessage message) { if (message is ServiceMessageModel messageModel) From af00a8768b3ffe4ab8468424f6846ff7958f7183 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:45:58 +0000 Subject: [PATCH 065/202] Give a custom installation directory the rights of Program Files The installer lets the user choose any directory, and a directory such as C:\CDPI UI inherits write access for authenticated users from the drive root. Every user could then replace files that the tray runs elevated. The installation directory now gets a protected ACL: full control for SYSTEM and Administrators, read and execute for Users. --- NewSetup/Product.wxs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/NewSetup/Product.wxs b/NewSetup/Product.wxs index 5183abe3..f4ed6f53 100644 --- a/NewSetup/Product.wxs +++ b/NewSetup/Product.wxs @@ -31,7 +31,16 @@ + + + + + + + From bd0f6472d257db35bad8760979f3b67d43e48417 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:48:03 +0000 Subject: [PATCH 066/202] Keep unsigned packs from bringing programs and install actions Only the import preview dropped ExecutableFile of an unsigned pack; the actual installation read init.json again and kept the executable name and the before and after install actions, so an unsigned pack could name the program the tray starts elevated and run install scripts. The queue now records whether the pack catalog was verified, and an unsigned pack is installed without an executable and without actions. Unsigned packs also no longer bring libraries, drivers, installers or scripts, not only .exe files, and the skip list matches by extension instead of by substring. install_msi only accepts packages inside the item's own folder, and DOWNLOAD= actions only accept HTTPS URLs and a plain file name, so they cannot write outside the item folder. The update patch import compared the extension without its dot. --- CDPIUI.Core/LScript/LScriptMsiHandler.cs | 19 ++++++++++++++++--- .../Store/LocalItemsInstallerHelper.cs | 17 ++++++++++++----- .../Store/OnlineItemsInstallationService.cs | 7 +++++++ .../Store/Queue/IQueueManagerService.cs | 2 +- CDPIUI.Core/Store/Queue/QueueItemModel.cs | 4 +++- .../Store/Queue/QueueManagerService.cs | 4 ++-- CDPIUI.Core/Store/StoreHelper.cs | 12 +++++++----- CDPIUI.Core/System/ZipService.cs | 5 ++++- 8 files changed, 52 insertions(+), 18 deletions(-) diff --git a/CDPIUI.Core/LScript/LScriptMsiHandler.cs b/CDPIUI.Core/LScript/LScriptMsiHandler.cs index b54af4c1..80e813d1 100644 --- a/CDPIUI.Core/LScript/LScriptMsiHandler.cs +++ b/CDPIUI.Core/LScript/LScriptMsiHandler.cs @@ -11,9 +11,15 @@ public class LScriptMsiHandler() public static async void InstallMsi( string[] scriptArgs, Dictionary? extraArgs, CancellationToken cancellationToken) { - string path = Path.Combine( - extraArgs?.GetValueOrDefault("CurrentDirectory", string.Empty) ?? string.Empty, - scriptArgs[0]); + string itemDirectory = extraArgs?.GetValueOrDefault("CurrentDirectory", string.Empty) ?? string.Empty; + string path = Path.Combine(itemDirectory, scriptArgs[0]); + + // A script may only install packages that its own item brought. + string checkedPath = path.EndsWith("$ALL") ? path.Substring(0, path.Length - "$ALL".Length) : path; + if (string.IsNullOrEmpty(itemDirectory) || !IsInsideDirectory(checkedPath, itemDirectory)) + { + throw new MsiInstallException("The package is outside the item directory"); + } if (bool.TryParse(scriptArgs[1], out bool removeAfterAction)) { Debug.WriteLine(path); @@ -42,6 +48,13 @@ public static async void InstallMsi( } } + private static bool IsInsideDirectory(string path, string directory) + { + string root = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + string fullPath = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + return fullPath.StartsWith(root, StringComparison.OrdinalIgnoreCase); + } + private static async Task> InstallAllMsiFromPath(string directory, bool removeAfterAction, CancellationToken cancellationToken) { bool requestRestart = false; diff --git a/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs b/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs index c7bc8c16..2fd57464 100644 --- a/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs +++ b/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs @@ -48,6 +48,13 @@ public static LocalItemsInstallerHelper Instance } } + // Files an unsigned pack may not bring: programs, libraries, drivers, installers and scripts. + private static readonly List UnsignedPackSkippedFiles = + [ + "*.exe", "*.dll", "*.sys", "*.msi", "*.com", "*.scr", "*.cpl", "*.bat", "*.cmd", + "*.ps1", "*.vbs", "*.vbe", "*.js", "*.jse", "*.wsf", "*.hta", "*.lnk", "*.url", + ]; + private LocalItemsInstallerHelper() { string localAppData = CDPIUI.Core.Data.Directories.DataDirectory; @@ -60,7 +67,7 @@ private LocalItemsInstallerHelper() string tempDestination = Path.Combine(TempDirectory, tempFolderName); bool isCatalogCheckRequired = Path.GetExtension(itemPackFile) == ".cdpisignedpack" ? true : false; - List filesToSkip = isCatalogCheckRequired ? [] : [".exe"]; + List filesToSkip = isCatalogCheckRequired ? [] : UnsignedPackSkippedFiles; try { @@ -113,7 +120,7 @@ public async Task BeginLocalItemInstalling(string itemPackFile, Action? string tempDestination = Path.Combine(TempDirectory, tempFolderName); bool isCatalogCheckRequired = Path.GetExtension(itemPackFile) == ".cdpisignedpack" ? true : false; - List filesToSkip = isCatalogCheckRequired ? [] : [".exe"]; + List filesToSkip = isCatalogCheckRequired ? [] : UnsignedPackSkippedFiles; try { @@ -129,7 +136,7 @@ public async Task BeginLocalItemInstalling(string itemPackFile, Action? LocalItemInitModel localItemInitModel = JSONConvertor.LoadJson(initFilePath); if (cancellationToken.IsCancellationRequested) return; - StoreHelper.Instance.AddItemToQueue(localItemInitModel.StoreId!, packFile: tempDestination); + StoreHelper.Instance.AddItemToQueue(localItemInitModel.StoreId!, packFile: tempDestination, isSignedPack: isCatalogCheckRequired); return; } catch (Exception ex) @@ -146,8 +153,8 @@ public async void ImportApplicationUpdatePatchFromFile(string path) string tempFolderName = FileSystemService.GetNewTempFileName("ap"); string tempDestination = Path.Combine(TempDirectory, tempFolderName); - bool isCatalogCheckRequired = Path.GetExtension(path) == "cdpisignedpack" ? true : false; - List filesToSkip = isCatalogCheckRequired ? [] : [".exe"]; + bool isCatalogCheckRequired = Path.GetExtension(path) == ".cdpisignedpack" ? true : false; + List filesToSkip = isCatalogCheckRequired ? [] : UnsignedPackSkippedFiles; try { diff --git a/CDPIUI.Core/Store/OnlineItemsInstallationService.cs b/CDPIUI.Core/Store/OnlineItemsInstallationService.cs index ad86c57a..d61ec28d 100644 --- a/CDPIUI.Core/Store/OnlineItemsInstallationService.cs +++ b/CDPIUI.Core/Store/OnlineItemsInstallationService.cs @@ -64,6 +64,13 @@ public async Task LaunchBeforeInstallActions(string? actions, string destD string url = _p[0]; string filename = _p[1]; + // Both come from item metadata: download only over HTTPS and only into the item folder. + if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) || uri.Scheme != Uri.UriSchemeHttps) + throw new InvalidDataException($"Only HTTPS downloads are allowed: {url}"); + if (string.IsNullOrWhiteSpace(filename) || filename != Path.GetFileName(filename) || + filename == "." || filename == ".." || filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) + throw new InvalidDataException($"Invalid download file name: {filename}"); + if (DownloadWorker == null) { throw new NullReferenceException(nameof(DownloadWorker)); diff --git a/CDPIUI.Core/Store/Queue/IQueueManagerService.cs b/CDPIUI.Core/Store/Queue/IQueueManagerService.cs index e210126d..75faf31f 100644 --- a/CDPIUI.Core/Store/Queue/IQueueManagerService.cs +++ b/CDPIUI.Core/Store/Queue/IQueueManagerService.cs @@ -15,7 +15,7 @@ internal interface IQueueManagerService /// Item version (null if latest) /// Clean files after instaliing (if msi-like) /// Pack file (null if online download - void AddItemToQueue(string itemId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFile = null); + void AddItemToQueue(string itemId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFile = null, bool isSignedPack = false); /// /// Cancel operation for item id diff --git a/CDPIUI.Core/Store/Queue/QueueItemModel.cs b/CDPIUI.Core/Store/Queue/QueueItemModel.cs index cc6168db..9144a5e9 100644 --- a/CDPIUI.Core/Store/Queue/QueueItemModel.cs +++ b/CDPIUI.Core/Store/Queue/QueueItemModel.cs @@ -1,12 +1,14 @@ namespace CDPIUI.Core.Store.Queue { - public class QueueItemModel(string itemId, string operationId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFilePath = null) + public class QueueItemModel(string itemId, string operationId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFilePath = null, bool isSignedPack = false) { public string OperationId { get; } = operationId; public string ItemId { get; } = itemId; public string Version { get; } = version ?? string.Empty; public bool CleanDirectoryBeforeInstalling { get; } = cleanDirectoryBeforeInstalling; public string? PackFilePath { get; } = packFilePath ?? string.Empty; + // A local pack whose catalog signature was verified; only such packs may bring executables and install actions. + public bool IsSignedPack { get; } = isSignedPack; public string Status { get; set; } = "WAIT"; public string DownloadStage { get; set; } = string.Empty; public double DownloadProgress { get; set; } diff --git a/CDPIUI.Core/Store/Queue/QueueManagerService.cs b/CDPIUI.Core/Store/Queue/QueueManagerService.cs index ae90a0ca..fddb4b95 100644 --- a/CDPIUI.Core/Store/Queue/QueueManagerService.cs +++ b/CDPIUI.Core/Store/Queue/QueueManagerService.cs @@ -11,13 +11,13 @@ internal class QueueManagerService : IQueueManagerService public QueueItemModel? CurrentDownloadingItem { get; set; } - public void AddItemToQueue(string itemId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFile = null) // PUBLIC + public void AddItemToQueue(string itemId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFile = null, bool isSignedPack = false) // PUBLIC { RemoveItemFromDownloadFailureList(itemId); if (GetOperationIdFromItemId(itemId) != null) return; var opId = Guid.NewGuid().ToString(); - var qi = new QueueItemModel(itemId, opId, version, cleanDirectoryBeforeInstalling, packFilePath: packFile); + var qi = new QueueItemModel(itemId, opId, version, cleanDirectoryBeforeInstalling, packFilePath: packFile, isSignedPack: isSignedPack); lock (_queueLock) { diff --git a/CDPIUI.Core/Store/StoreHelper.cs b/CDPIUI.Core/Store/StoreHelper.cs index 773267c8..a8a27c39 100644 --- a/CDPIUI.Core/Store/StoreHelper.cs +++ b/CDPIUI.Core/Store/StoreHelper.cs @@ -185,8 +185,8 @@ private void AddItemToDownloadFailureList(string itemId, string operationId, str #endregion #region Queue - public void AddItemToQueue(string itemId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFile = null) => - QueueManagerService.AddItemToQueue(itemId, version, cleanDirectoryBeforeInstalling, packFile); + public void AddItemToQueue(string itemId, string? version = null, bool cleanDirectoryBeforeInstalling = false, string? packFile = null, bool isSignedPack = false) => + QueueManagerService.AddItemToQueue(itemId, version, cleanDirectoryBeforeInstalling, packFile, isSignedPack); public bool RemoveItemFromQueue(string itemId) => QueueManagerService.RemoveItemFromQueue(itemId); @@ -530,15 +530,17 @@ private async Task>> D type = localItemInitModel.Type ?? "configlist", name = localItemInitModel.Name ?? localItemInitModel.ShortName ?? qi.ItemId, short_name = localItemInitModel.ShortName ?? qi.ItemId, - target_executable_file = localItemInitModel.ExecutableFile, + // An unsigned pack is only a set of presets and lists: it cannot name the executable + // the tray starts elevated, and it cannot run install actions. + target_executable_file = qi.IsSignedPack ? localItemInitModel.ExecutableFile : null, filetype = "localPack", version_control = "local", icon = localItemInitModel.Icon, developer = localItemInitModel.Developer, background = localItemInitModel.Color, dependencies = localItemInitModel.Requirements, - before_install_actions = localItemInitModel.BeforeInstallActions, - after_install_actions = localItemInitModel.AfterInstallActions, + before_install_actions = qi.IsSignedPack ? localItemInitModel.BeforeInstallActions : null, + after_install_actions = qi.IsSignedPack ? localItemInitModel.AfterInstallActions : null, }; tag = localItemInitModel.Version; downloadUrl = null; diff --git a/CDPIUI.Core/System/ZipService.cs b/CDPIUI.Core/System/ZipService.cs index ce3f2f41..0a78c434 100644 --- a/CDPIUI.Core/System/ZipService.cs +++ b/CDPIUI.Core/System/ZipService.cs @@ -82,7 +82,10 @@ public static async Task ExtractZip( if (string.IsNullOrEmpty(relativePath)) continue; - if (filesToSkip.Any(skip => relativePath.Contains(skip))) + // "*.ext" skips by extension; any other value skips paths that contain it. + if (filesToSkip.Any(skip => skip.StartsWith("*.") + ? relativePath.EndsWith(skip.Substring(1), StringComparison.OrdinalIgnoreCase) + : relativePath.Contains(skip))) continue; var destinationPath = ArchivePaths.GetDestinationOrThrow(extractTo, relativePath); From b385a4f92cea58f348f29878ad439b19e22b0b39 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:49:24 +0000 Subject: [PATCH 067/202] Validate store item ids and accept only HTTPS store downloads Store item ids from metadata and local packs became folder names that are deleted recursively without any check, and RemoveItem deleted whatever directory the item database named. Ids must now be short alphanumeric names, local packs with other ids are rejected, and only a folder inside the store items directory is deleted. Store and update downloads also accepted plain HTTP, the release version from item metadata was put into the API path unescaped, so "../" could reach another endpoint with the store token, and the store archive was downloaded to a fixed name in the shared temp folder. --- .../Store/LocalItemsInstallerHelper.cs | 10 +++++++ CDPIUI.Core/Store/Network/APIWorker.cs | 5 ++++ CDPIUI.Core/Store/Network/RequestWorker.cs | 7 +++-- .../Repository/RepositoryLoaderService.cs | 5 ++-- CDPIUI.Core/Store/StoreHelper.cs | 7 ++++- CDPIUI.Core/Store/StoreItemIds.cs | 28 +++++++++++++++++++ 6 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 CDPIUI.Core/Store/StoreItemIds.cs diff --git a/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs b/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs index 2fd57464..e6cfe9cc 100644 --- a/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs +++ b/CDPIUI.Core/Store/LocalItemsInstallerHelper.cs @@ -100,6 +100,10 @@ private LocalItemsInstallerHelper() { throw new AccessViolationException("StoreId is protected by security policy"); } + if (!StoreItemIds.IsValid(localItemInitModel.StoreId)) + { + throw new InvalidDataException("StoreId is not a valid identifier"); + } Directory.Delete(tempDestination, recursive: true); @@ -134,6 +138,12 @@ public async Task BeginLocalItemInstalling(string itemPackFile, Action? return; } LocalItemInitModel localItemInitModel = JSONConvertor.LoadJson(initFilePath); + if (!StoreItemIds.IsValid(localItemInitModel.StoreId) || + localItemInitModel.StoreId == SharedConstants.ApplicationStoreId || + localItemInitModel.StoreId == SharedConstants.LocalUserItemsId) + { + throw new InvalidDataException("StoreId is not allowed for a local pack"); + } if (cancellationToken.IsCancellationRequested) return; StoreHelper.Instance.AddItemToQueue(localItemInitModel.StoreId!, packFile: tempDestination, isSignedPack: isCatalogCheckRequired); diff --git a/CDPIUI.Core/Store/Network/APIWorker.cs b/CDPIUI.Core/Store/Network/APIWorker.cs index 17f5e51e..35421331 100644 --- a/CDPIUI.Core/Store/Network/APIWorker.cs +++ b/CDPIUI.Core/Store/Network/APIWorker.cs @@ -210,6 +210,11 @@ private async Task GetGithubResponse( private static string GetApiUrlForVersion(string owner, string repo, string? version, SupportedVersionControls versionControl) { string url = string.Empty; + // The version comes from item metadata; escaped, "../" cannot move the request to another API endpoint. + if (!string.IsNullOrEmpty(version)) + version = Uri.EscapeDataString(version); + owner = Uri.EscapeDataString(owner); + repo = Uri.EscapeDataString(repo); if (versionControl == SupportedVersionControls.GitHub) { url = string.IsNullOrEmpty(version) diff --git a/CDPIUI.Core/Store/Network/RequestWorker.cs b/CDPIUI.Core/Store/Network/RequestWorker.cs index 4454d02b..efa31351 100644 --- a/CDPIUI.Core/Store/Network/RequestWorker.cs +++ b/CDPIUI.Core/Store/Network/RequestWorker.cs @@ -100,9 +100,10 @@ public async Task DownloadFileAsync( private static HttpRequestMessage CreateRequest( string url, string? token, string authenticationScheme, bool useStoreUserAgent, bool proxyEnable) { - if (!Uri.TryCreate(url, UriKind.Absolute, out var sourceUri) || - (sourceUri.Scheme != Uri.UriSchemeHttp && sourceUri.Scheme != Uri.UriSchemeHttps)) - throw new ArgumentException("The source URL must be an absolute HTTP or HTTPS URL.", nameof(url)); + // Downloads carry components and installers without signatures of their own, so plain HTTP + // would let anyone on the way replace them. + if (!Uri.TryCreate(url, UriKind.Absolute, out var sourceUri) || sourceUri.Scheme != Uri.UriSchemeHttps) + throw new ArgumentException("The source URL must be an absolute HTTPS URL.", nameof(url)); var request = new HttpRequestMessage(HttpMethod.Get, proxyEnable ? CreateProxyUri(url) : sourceUri); try diff --git a/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs b/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs index 054e9414..d24f0f15 100644 --- a/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs +++ b/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs @@ -59,7 +59,7 @@ public static async Task TryLoadDatabaseForVersionControl(SupportedVersion { string zipUrl = GetStoreUrl(versionControl); - string tempZipPath = Path.Combine(Path.GetTempPath(), "store_repo.tmp"); + string tempZipPath = Path.Combine(Path.GetTempPath(), $"cdpiui_store_{Guid.NewGuid():N}.tmp"); using var requestWorker = new RequestWorker(); await requestWorker.DownloadFileAsync(zipUrl, tempZipPath, token: versionControl == SupportedVersionControls.GitHub ? GitHubApiToken : GitLabApiToken, @@ -97,7 +97,8 @@ public async Task LoadAllStoreDatabase(bool forseSync, SupportedVersionCon string zipUrl = GetStoreUrl(usedVersionControl); Debug.WriteLine(zipUrl); - string tempZipPath = Path.Combine(Path.GetTempPath(), "store_repo.tmp"); + // A fixed name in the shared temp folder could be prepared by another process. + string tempZipPath = Path.Combine(Path.GetTempPath(), $"cdpiui_store_{Guid.NewGuid():N}.tmp"); using var requestWorker = new RequestWorker(); await requestWorker.DownloadFileAsync(zipUrl, tempZipPath, token: usedVersionControl == SupportedVersionControls.GitHub ? GitHubApiToken : GitLabApiToken, diff --git a/CDPIUI.Core/Store/StoreHelper.cs b/CDPIUI.Core/Store/StoreHelper.cs index a8a27c39..7400d3bf 100644 --- a/CDPIUI.Core/Store/StoreHelper.cs +++ b/CDPIUI.Core/Store/StoreHelper.cs @@ -276,7 +276,8 @@ public void RemoveItem(string itemId) try { - if (Path.Exists(item.Directory)) + // The directory comes from the item database; never delete anything outside the item folders. + if (Path.Exists(item.Directory) && StoreItemIds.IsItemFolder(item.Directory)) { Directory.Delete(item.Directory, recursive: true); } @@ -392,6 +393,10 @@ private async Task> InstallItemWorker(QueueIte NowProcessItemActions?.Invoke(id); + if (!StoreItemIds.IsValid(id)) + return OperationResultModel + .FailureResult(ErrorModel.OnlyErrorCode(HandleException(new InvalidDataException($"Invalid store item id: {id}")))); + List> requiredItems = []; if (DatabaseHelper.Instance.IsItemInstalled(id)) { diff --git a/CDPIUI.Core/Store/StoreItemIds.cs b/CDPIUI.Core/Store/StoreItemIds.cs new file mode 100644 index 00000000..530ad843 --- /dev/null +++ b/CDPIUI.Core/Store/StoreItemIds.cs @@ -0,0 +1,28 @@ +using System.Text.RegularExpressions; + +namespace CDPIUI.Core.Store +{ + /// + /// Store item identifiers come from item metadata and local packs; they become folder names + /// that are created, replaced and deleted recursively + /// + public static class StoreItemIds + { + private static readonly Regex ValidId = new(@"^[A-Za-z0-9_-]{1,64}$", RegexOptions.CultureInvariant); + + public static bool IsValid(string? id) => id != null && ValidId.IsMatch(id); + + /// + /// Checks that a directory is a single item folder inside the store items directory + /// + public static bool IsItemFolder(string? directory) + { + if (string.IsNullOrWhiteSpace(directory)) + return false; + + string root = Path.GetFullPath(CDPIUI.Core.Data.Directories.StoreItemsDirectory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + string fullPath = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar); + return fullPath.StartsWith(root, StringComparison.OrdinalIgnoreCase) && fullPath.Length > root.Length; + } + } +} From 4668ee1df9b1d3d882fde8d0276ae366061ca0da Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:50:04 +0000 Subject: [PATCH 068/202] Check signed archives before their files reach the destination Signed packs and store archives were extracted straight into the item folder and their catalog was checked afterwards, so the files of a rejected archive stayed in place, and files already in the folder took part in the check. A signed archive is now extracted into a folder of its own, checked there and moved into place only when its catalog is valid. --- CDPIUI.Core/System/ZipService.cs | 81 +++++++++++++++++++++++++------- 1 file changed, 64 insertions(+), 17 deletions(-) diff --git a/CDPIUI.Core/System/ZipService.cs b/CDPIUI.Core/System/ZipService.cs index 0a78c434..94acbcc5 100644 --- a/CDPIUI.Core/System/ZipService.cs +++ b/CDPIUI.Core/System/ZipService.cs @@ -18,6 +18,54 @@ public static async Task ExtractZip( IEnumerable? filesToSkip = null, bool isCatalogCheckRequired = false ) + { + if (!isCatalogCheckRequired) + { + await ExtractEntries(zipFilePath, zipFolderToUnpack, extractTo, filesToSkip, mergeTextFiles: true); + return; + } + + // A signed archive is checked in a folder of its own and moved into place only when its + // catalog is valid, so files of a rejected archive never reach the destination. + string verifyDirectory = extractTo.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + ".verify-" + Guid.NewGuid().ToString("N"); + try + { + await ExtractEntries(zipFilePath, zipFolderToUnpack, verifyDirectory, filesToSkip, mergeTextFiles: false); + await VerifyCatalog(verifyDirectory); + MoveContents(verifyDirectory, extractTo); + } + finally + { + try + { + if (Directory.Exists(verifyDirectory)) + Directory.Delete(verifyDirectory, recursive: true); + } + catch { } + } + } + + private static void MoveContents(string sourceDirectory, string destinationDirectory) + { + Directory.CreateDirectory(destinationDirectory); + foreach (string file in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories)) + { + string destination = Path.Combine(destinationDirectory, Path.GetRelativePath(sourceDirectory, file)); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Move(file, destination, overwrite: true); + } + foreach (string directory in Directory.EnumerateDirectories(sourceDirectory, "*", SearchOption.AllDirectories)) + Directory.CreateDirectory(Path.Combine(destinationDirectory, Path.GetRelativePath(sourceDirectory, directory))); + } + + private static async Task ExtractEntries( + string zipFilePath, + string? zipFolderToUnpack, + string extractTo, + IEnumerable? filesToSkip, + bool mergeTextFiles + ) { filesToSkip = filesToSkip ?? Enumerable.Empty(); @@ -93,7 +141,7 @@ public static async Task ExtractZip( if (!Directory.Exists(destinationDir) && !string.IsNullOrEmpty(destinationDir)) Directory.CreateDirectory(destinationDir); - if (!isCatalogCheckRequired) + if (mergeTextFiles) { if (relativePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) && File.Exists(destinationPath)) @@ -139,24 +187,23 @@ public static async Task ExtractZip( extractedFiles++; } } + } - if (isCatalogCheckRequired) + private static async Task VerifyCatalog(string directory) + { + CatalogCheckResult catalogCheckResult = await CertificateCheck.CheckCatalog(Path.Combine(directory, "catalog.cat"), directory); + switch (catalogCheckResult) { - CatalogCheckResult catalogCheckResult = await CertificateCheck.CheckCatalog(Path.Combine(extractTo, "catalog.cat"), extractTo); - switch (catalogCheckResult) - { - case CatalogCheckResult.Success: - return; - case CatalogCheckResult.FailureNoSignature: - throw new CatalogNoSignature("Catalog file isn't signed"); - case CatalogCheckResult.FailureNotTrustedSignature: - throw new CatalogNoSignature("Signature not trusted"); - case CatalogCheckResult.FailureNotValid: - throw new CatalogInvalid(); - case CatalogCheckResult.FailureUnknown: - throw new CatalogInvalid("Unknown"); - - } + case CatalogCheckResult.Success: + return; + case CatalogCheckResult.FailureNoSignature: + throw new CatalogNoSignature("Catalog file isn't signed"); + case CatalogCheckResult.FailureNotTrustedSignature: + throw new CatalogNoSignature("Signature not trusted"); + case CatalogCheckResult.FailureNotValid: + throw new CatalogInvalid(); + default: + throw new CatalogInvalid("Unknown"); } } } From 9f42050124ff1ec314f0d4b154901da67e09eccf Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:51:24 +0000 Subject: [PATCH 069/202] Merge settings changes with the file instead of overwriting it The UI and the tray keep their own copy of the shared Settings.xml in memory and saved the whole copy on every change, so a change made by one process was lost as soon as the other one saved anything from its older copy. Every change is now made under a lock file shared by both processes: the file is read again, only the changed setting is applied and the file is saved. A lock file is used because a named mutex created by the elevated tray could not be opened by the UI. --- CDPIUI.Shared/Basic/XMLSettingsService.cs | 164 ++++++++++-------- .../Shared/XmlSettingsServiceTests.cs | 19 +- 2 files changed, 113 insertions(+), 70 deletions(-) diff --git a/CDPIUI.Shared/Basic/XMLSettingsService.cs b/CDPIUI.Shared/Basic/XMLSettingsService.cs index b360deaa..3de689a6 100644 --- a/CDPIUI.Shared/Basic/XMLSettingsService.cs +++ b/CDPIUI.Shared/Basic/XMLSettingsService.cs @@ -1,4 +1,4 @@ -using CDPIUI.Shared.Exceptions.Settings; +using CDPIUI.Shared.Exceptions.Settings; using System; using System.Collections.Generic; using System.Diagnostics; @@ -105,6 +105,98 @@ private static XDocument LoadDocument(string path) return document; } + private static void ApplySetting(XElement root, IEnumerable groupPath, string key, string type, string valueString) + { + XElement current = root; + foreach (var grp in groupPath) + { + var next = current + .Elements("Group") + .FirstOrDefault(g => (string?)g.Attribute("Name") == grp); + + if (next == null) + { + next = new XElement("Group", new XAttribute("Name", grp)); + current.Add(next); + } + + current = next; + } + + var setting = current + .Elements("Setting") + .FirstOrDefault(s => (string?)s.Attribute("Key") == key); + + if (setting != null) + { + setting.SetAttributeValue("Type", type); + setting.SetAttributeValue("Value", valueString); + } + else + { + current.Add(new XElement("Setting", + new XAttribute("Key", key), + new XAttribute("Type", type), + new XAttribute("Value", valueString))); + } + } + + /// + /// The UI and the tray share the settings file. Each change is applied to the file as it is on disk + /// now, so a process with an older copy in memory does not overwrite what the other one saved. + /// + private void SaveChange(IEnumerable groupPath, string key, string type, string valueString) + { + lock (_reloadLock) + { + using (AcquireFileLock()) + { + if (!_persistenceUnavailable && File.Exists(SettingsFilePath)) + { + try + { + _xDocument = LoadDocument(SettingsFilePath); + } + catch (Exception ex) when (IsReadFailure(ex)) + { + // Keep the copy in memory; saving it replaces the unreadable file. + } + } + + ApplySetting(_xDocument!.Root!, groupPath, key, type, valueString); + SaveSettings(); + } + } + } + + private const int LockAttempts = 40; + private const int LockRetryDelayMs = 50; + + // A lock file works for both processes, while a named mutex of the elevated tray would not be + // accessible to the UI. + private IDisposable? AcquireFileLock() + { + string lockPath = SettingsFilePath + ".lock"; + for (int attempt = 1; attempt <= LockAttempts; attempt++) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(SettingsFilePath))!); + return new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, + 1, FileOptions.DeleteOnClose); + } + catch (IOException) + { + Thread.Sleep(LockRetryDelayMs); + } + catch (UnauthorizedAccessException) + { + return null; + } + } + return null; + } + private const int SaveAttempts = 5; private const int SaveRetryDelayMs = 50; @@ -382,37 +474,7 @@ public void SetValue(string group, string key, T value) valueString = value?.ToString() ?? string.Empty; } - lock (_reloadLock) - { - var groupElement = _xDocument.Root - .Elements("Group") - .FirstOrDefault(g => g.Attribute("Name")?.Value == group); - - if (groupElement == null) - { - groupElement = new XElement("Group", new XAttribute("Name", group)); - _xDocument.Root.Add(groupElement); - } - - var settingElement = groupElement - .Elements("Setting") - .FirstOrDefault(s => s.Attribute("Key")?.Value == key); - - if (settingElement != null) - { - settingElement.SetAttributeValue("Value", valueString); - settingElement.SetAttributeValue("Type", type); - } - else - { - groupElement.Add(new XElement("Setting", - new XAttribute("Key", key), - new XAttribute("Type", type), - new XAttribute("Value", valueString))); - } - - SaveSettings(); - } + SaveChange([group], key, type, valueString); PropertyChanged?.Invoke(group); } @@ -460,43 +522,7 @@ public void SetValue(IEnumerable groupPath, string key, T value) break; } - lock (_reloadLock) - { - XElement current = _xDocument.Root; - foreach (var grp in groupPath) - { - var next = current - .Elements("Group") - .FirstOrDefault(g => (string)g.Attribute("Name") == grp); - - if (next == null) - { - next = new XElement("Group", new XAttribute("Name", grp)); - current.Add(next); - } - - current = next; - } - - var setting = current - .Elements("Setting") - .FirstOrDefault(s => (string)s.Attribute("Key") == key); - - if (setting != null) - { - setting.SetAttributeValue("Type", type); - setting.SetAttributeValue("Value", valueString); - } - else - { - current.Add(new XElement("Setting", - new XAttribute("Key", key), - new XAttribute("Type", type), - new XAttribute("Value", valueString))); - } - - SaveSettings(); - } + SaveChange(groupPath, key, type, valueString); EnumPropertyChanged?.Invoke(groupPath); } diff --git a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs index e558cbf6..19221a2b 100644 --- a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs +++ b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using CDPIUI.Shared.Basic; namespace CDPIUI.Tests.Shared; @@ -73,4 +73,21 @@ await Task.WhenAll(Enumerable.Range(0, 8).Select(worker => Task.Run(() => Assert.Equal(49, new XMLSettingsService(SettingsPath).GetValue("GROUP3", "key49")); } + + [Fact] + public void ProcessWithOlderCopyDoesNotOverwriteOtherChanges() + { + var ui = new XMLSettingsService(SettingsPath); + var tray = new XMLSettingsService(SettingsPath); + + ui.SetValue("APPEARANCE", "Theme", "Dark"); + tray.SetValue("TRAY", "iconGUID", "guid"); + ui.SetValue(["CONFIGS", "CSZTBN012"], "configFile", "preset.json"); + + var reloaded = new XMLSettingsService(SettingsPath); + Assert.Equal("Dark", reloaded.GetValue("APPEARANCE", "Theme")); + Assert.Equal("guid", reloaded.GetValue("TRAY", "iconGUID")); + Assert.Equal("preset.json", reloaded.GetValue(["CONFIGS", "CSZTBN012"], "configFile")); + Assert.False(File.Exists(SettingsPath + ".lock")); + } } From 30a477e10a331c0c5a77608497adfbaae0afa06f Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:51:46 +0000 Subject: [PATCH 070/202] Await MSI installs from item scripts and harden script parsing install_msi was an async void method that threw on failure, so a failed MSI installation crashed the application while the item was reported as installed before the installer finished. It is now awaited and fails the item installation. A trailing ';' in a script list threw IndexOutOfRange, a '$' in script arguments was treated as a regex substitution, and script errors were swallowed without a log entry. --- CDPIUI.Core/LScript/LScriptCore.cs | 14 ++++++++------ CDPIUI.Core/LScript/LScriptMsiHandler.cs | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CDPIUI.Core/LScript/LScriptCore.cs b/CDPIUI.Core/LScript/LScriptCore.cs index e4de9a1c..8f30a94a 100644 --- a/CDPIUI.Core/LScript/LScriptCore.cs +++ b/CDPIUI.Core/LScript/LScriptCore.cs @@ -44,7 +44,7 @@ public static string GetScriptArgs(string scriptString, string scriptArgs = null } if (scriptArgs != null) - scriptData = Regex.Replace(scriptData, @"{.*?}", scriptArgs); + scriptData = Regex.Replace(scriptData, @"{.*?}", _ => scriptArgs); } return scriptData; } @@ -111,7 +111,7 @@ public virtual string ExecuteScriptWork( } catch (Exception ex) { - // pass + Logger.Instance.CreateWarningLog(nameof(LScriptCore), $"Script {scriptString} failed: {ex.Message}"); } return executeResult; @@ -148,7 +148,7 @@ public static string ExecuteScriptUnsafe( if (!string.IsNullOrEmpty(scriptArgs)) { - scriptData = Regex.Replace(scriptData, @"{.*?}", scriptArgs); + scriptData = Regex.Replace(scriptData, @"{.*?}", _ => scriptArgs); } string replacement = m.Value; @@ -334,6 +334,9 @@ public static string LocalCondition(string condition, Dictionary? } string[] parts = scriptData.Split(", ", StringSplitOptions.RemoveEmptyEntries); + // An empty script, for example after a trailing ';'. + if (parts.Length == 0) + continue; string scriptName = parts[0]; string[] scriptArgs = parts.Skip(1).ToArray(); @@ -350,15 +353,14 @@ public static string LocalCondition(string condition, Dictionary? case "install_msi": if (scriptArgs.Length < 2) break; - LScriptMsiHandler.InstallMsi(scriptArgs, extraArgs, cancellationToken ?? default); + // Awaited, so a failed installation fails the item installation instead of the process. + await LScriptMsiHandler.InstallMsi(scriptArgs, extraArgs, cancellationToken ?? default); break; default: Logger.Instance.CreateWarningLog(nameof(LScriptCore), $"Unknown script command: {scriptName}"); break; } } - await Task.CompletedTask; - return result; } diff --git a/CDPIUI.Core/LScript/LScriptMsiHandler.cs b/CDPIUI.Core/LScript/LScriptMsiHandler.cs index 80e813d1..a896542d 100644 --- a/CDPIUI.Core/LScript/LScriptMsiHandler.cs +++ b/CDPIUI.Core/LScript/LScriptMsiHandler.cs @@ -8,7 +8,7 @@ namespace CDPIUI.Core.LScript { public class LScriptMsiHandler() { - public static async void InstallMsi( + public static async Task InstallMsi( string[] scriptArgs, Dictionary? extraArgs, CancellationToken cancellationToken) { string itemDirectory = extraArgs?.GetValueOrDefault("CurrentDirectory", string.Empty) ?? string.Empty; From c271d65d34e5786de25e4d66b7f44452c8032aeb Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:52:35 +0000 Subject: [PATCH 071/202] Send long pipe messages whole and keep the auth GUID out of logs The pipe frame had a two-byte length, so a message longer than 65535 bytes was cut in the middle of a character. Such messages now send 0xFFFF followed by a four-byte length, up to 16 MB; shorter messages keep the old header, so both sides stay compatible with an older peer for every message that used to work. Every received message, including the authentication request with the GUID, was logged at Info level, and every sent one at Debug level. Both are now logged at Debug level with the GUID masked. --- CDPIUI.Shared/Pipe/PipeServiceBase.cs | 9 +++++-- CDPIUI.Shared/Pipe/StreamString.cs | 25 +++++++++++++++--- CDPIUI.Tests/Shared/StreamStringTests.cs | 32 ++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 CDPIUI.Tests/Shared/StreamStringTests.cs diff --git a/CDPIUI.Shared/Pipe/PipeServiceBase.cs b/CDPIUI.Shared/Pipe/PipeServiceBase.cs index 707e6fa5..e60bd6ac 100644 --- a/CDPIUI.Shared/Pipe/PipeServiceBase.cs +++ b/CDPIUI.Shared/Pipe/PipeServiceBase.cs @@ -69,11 +69,16 @@ public async Task HandleConnectionAsync() continue; } - Logger?.CreateInfoLog(nameof(PipeServiceBase), $"Received message: {message}"); + Logger?.CreateDebugLog(nameof(PipeServiceBase), $"Received message: {RedactSecrets(message)}"); } Logger?.CreateInfoLog(nameof(PipeServiceBase), $"{CancellationToken?.IsCancellationRequested}, {PipeStream.IsConnected.ToString()}"); } + // The authentication GUID must not end up in log files. + private static string RedactSecrets(string message) => + System.Text.RegularExpressions.Regex.Replace(message, "(GUID=)[^&]*", "$1***", + System.Text.RegularExpressions.RegexOptions.IgnoreCase); + public async void SendMessage(string message) { await SendMessageAsync(message); @@ -116,7 +121,7 @@ protected virtual async Task RunMessageActions(IPipeMessage model) private async Task SendStringMessageToPipe(string message) { - Logger?.CreateDebugLog(nameof(PipeServiceBase), $"Message \"{message}\" added to send queue"); + Logger?.CreateDebugLog(nameof(PipeServiceBase), $"Message \"{RedactSecrets(message)}\" added to send queue"); if (PipeStream == null || !PipeStream.IsConnected || StreamString == null) { diff --git a/CDPIUI.Shared/Pipe/StreamString.cs b/CDPIUI.Shared/Pipe/StreamString.cs index fc5c685e..30e63717 100644 --- a/CDPIUI.Shared/Pipe/StreamString.cs +++ b/CDPIUI.Shared/Pipe/StreamString.cs @@ -13,12 +13,25 @@ public class StreamString(Stream ioStream) ioStream ?? throw new ArgumentNullException(nameof(ioStream)); private readonly Encoding streamEncoding = Encoding.Unicode; + // Messages shorter than 0xFFFF bytes keep the original two-byte length. Longer ones, which were + // cut off in the middle of a character before, send 0xFFFF followed by a four-byte length. + private const int ExtendedLengthMarker = ushort.MaxValue; + private const int MaxMessageLength = 16 * 1024 * 1024; + public async Task ReadStringAsync(CancellationToken token = default) { byte[] lenBuffer = new byte[2]; await ReadExactlyAsync(lenBuffer, token).ConfigureAwait(false); int len = lenBuffer[0] * 256 + lenBuffer[1]; + if (len == ExtendedLengthMarker) + { + byte[] extendedBuffer = new byte[4]; + await ReadExactlyAsync(extendedBuffer, token).ConfigureAwait(false); + len = (extendedBuffer[0] << 24) | (extendedBuffer[1] << 16) | (extendedBuffer[2] << 8) | extendedBuffer[3]; + if (len < 0 || len > MaxMessageLength) + throw new InvalidDataException("The pipe message is too long."); + } byte[] inBuffer = new byte[len]; await ReadExactlyAsync(inBuffer, token).ConfigureAwait(false); @@ -46,15 +59,19 @@ private async Task ReadExactlyAsync(byte[] buffer, CancellationToken token) public async Task WriteStringAsync(string outString, CancellationToken token = default) { byte[] outBuffer = streamEncoding.GetBytes(outString ?? string.Empty); - int len = Math.Min(outBuffer.Length, ushort.MaxValue); + int len = outBuffer.Length; + if (len > MaxMessageLength) + throw new InvalidDataException("The pipe message is too long."); - byte[] header = new byte[2] { (byte)(len / 256), (byte)(len & 255) }; + byte[] header = len < ExtendedLengthMarker + ? new byte[] { (byte)(len / 256), (byte)(len & 255) } + : new byte[] { 0xFF, 0xFF, (byte)(len >> 24), (byte)(len >> 16), (byte)(len >> 8), (byte)len }; - await ioStream.WriteAsync(header, 0, 2, token).ConfigureAwait(false); + await ioStream.WriteAsync(header, 0, header.Length, token).ConfigureAwait(false); await ioStream.WriteAsync(outBuffer, 0, len, token).ConfigureAwait(false); await ioStream.FlushAsync(token).ConfigureAwait(false); - return len + 2; + return len + header.Length; } } } diff --git a/CDPIUI.Tests/Shared/StreamStringTests.cs b/CDPIUI.Tests/Shared/StreamStringTests.cs new file mode 100644 index 00000000..1cc5ebfd --- /dev/null +++ b/CDPIUI.Tests/Shared/StreamStringTests.cs @@ -0,0 +1,32 @@ +using CDPIUI.Shared.Pipe; + +namespace CDPIUI.Tests.Shared; + +public class StreamStringTests +{ + [Theory] + [InlineData(0)] + [InlineData(10)] + [InlineData(32767)] + [InlineData(32768)] + [InlineData(200_000)] + public async Task MessagesOfAnyLengthRoundTrip(int length) + { + string message = string.Concat(Enumerable.Range(0, length).Select(i => (char)('а' + i % 32))); + using var stream = new MemoryStream(); + + await new StreamString(stream).WriteStringAsync(message); + stream.Position = 0; + + Assert.Equal(message, await new StreamString(stream).ReadStringAsync()); + } + + [Fact] + public async Task ShortMessageKeepsTwoByteHeader() + { + using var stream = new MemoryStream(); + await new StreamString(stream).WriteStringAsync("ab"); + + Assert.Equal(new byte[] { 0, 4, (byte)'a', 0, (byte)'b', 0 }, stream.ToArray()); + } +} From 574ad00f64f0a44cb6e1824e28b26bc372064e61 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:53:24 +0000 Subject: [PATCH 072/202] Do not block the UI thread on task lookups and fix SendTaskData CoreCommandsHandler waited six times for GetTaskFromId with .Result in the UI synchronization context, and the component settings page did the same with IsTaskRunned; they now await. SendTaskData dereferenced the task when it was not found, and SendTasksData enumerated the live task list without its lock. --- .../Communication/CoreCommandsHandler.cs | 24 +++++-------------- .../ComponentTasksManager.cs | 5 ++-- .../DefaultComponentSettingsPage.xaml.cs | 9 ++++++- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/CDPIUI.Core/Communication/CoreCommandsHandler.cs b/CDPIUI.Core/Communication/CoreCommandsHandler.cs index 44937764..a3489ff1 100644 --- a/CDPIUI.Core/Communication/CoreCommandsHandler.cs +++ b/CDPIUI.Core/Communication/CoreCommandsHandler.cs @@ -102,9 +102,7 @@ private static async Task HandleCONPTYMessage(CONPTYMessageModel model) var id = model.MessageData?["componentId"]; if (id == null) return; - ComponentTasksManager.Instance - .GetTaskFromId(id) - .Result? + (await ComponentTasksManager.Instance.GetTaskFromId(id))? .ProcessManager? .ClearOutput(); @@ -116,9 +114,7 @@ private static async Task HandleCONPTYMessage(CONPTYMessageModel model) var id = model.MessageData?["componentId"]; if (id == null) return; - ComponentTasksManager.Instance - .GetTaskFromId(id) - .Result? + (await ComponentTasksManager.Instance.GetTaskFromId(id))? .ProcessManager? .MarkAsStarted(); @@ -133,9 +129,7 @@ private static async Task HandleCONPTYMessage(CONPTYMessageModel model) var title = model.MessageData?["errorMessage"]; var text = model.MessageData?["errorObject"]; - var pm = ComponentTasksManager.Instance - .GetTaskFromId(id) - .Result? + var pm = (await ComponentTasksManager.Instance.GetTaskFromId(id))? .ProcessManager; if (title != null && text != null) @@ -159,9 +153,7 @@ private static async Task HandleCONPTYMessage(CONPTYMessageModel model) if (id == null || processName == null) return; - ComponentTasksManager.Instance - .GetTaskFromId(id) - .Result? + (await ComponentTasksManager.Instance.GetTaskFromId(id))? .ProcessManager? .ChangeProcName(processName); @@ -176,9 +168,7 @@ private static async Task HandleCONPTYMessage(CONPTYMessageModel model) if (id == null || output == null) return; - ComponentTasksManager.Instance - .GetTaskFromId(id) - .Result? + (await ComponentTasksManager.Instance.GetTaskFromId(id))? .ProcessManager? .AddOutput(output); @@ -193,9 +183,7 @@ private static async Task HandleCONPTYMessage(CONPTYMessageModel model) if (id == null || output == null) return; - var pm = ComponentTasksManager.Instance - .GetTaskFromId(id) - .Result? + var pm = (await ComponentTasksManager.Instance.GetTaskFromId(id))? .ProcessManager; pm?.SetOutput(output); diff --git a/CDPIUI.Core/ComponentServices/ComponentTasksManager.cs b/CDPIUI.Core/ComponentServices/ComponentTasksManager.cs index aa5c7fa9..db65d5c1 100644 --- a/CDPIUI.Core/ComponentServices/ComponentTasksManager.cs +++ b/CDPIUI.Core/ComponentServices/ComponentTasksManager.cs @@ -84,15 +84,16 @@ await PipeHelper.SendSettingsPacket( } else { + // The task can be missing here, so the requested id is reported. await PipeHelper.SendSettingsPacket( Shared.Pipe.Models.SettingsMessageIds.ComponentNotInstalled, - new() { { "componentId", task.Id } }); + new() { { "componentId", id } }); } } public async void SendTasksData() { - foreach (var task in Tasks) + foreach (var task in await GetTasksSnapshot()) { await SendTaskData(task.Id); } diff --git a/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs b/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs index 5a70a52c..e497d58c 100644 --- a/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs +++ b/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs @@ -309,6 +309,13 @@ private void InitSettingsTiles(ConfigSelectorItem sel) }); } + // Waiting for the task list on the UI thread with .Result could deadlock. + private async Task RestartComponentIfRunning() + { + if (await ComponentTasksManager.Instance.IsTaskRunned(ComponentId)) + await ComponentTasksManager.Instance.RestartTask(ComponentId); + } + private void HandleSettingTileElementClick(ActionIds actionId, List arguments, SettingTileContentDefinition contentDefinition) { switch (actionId) @@ -353,7 +360,7 @@ private void HandleSettingTileElementClick(ActionIds actionId, List argu ShowAnim = false; var item = ConfigChooseCombobox.SelectedItem as ConfigSelectorItem; Task.Run(() => InitSettingsTiles(item)); - if (ComponentTasksManager.Instance.IsTaskRunned(ComponentId).Result) _ = ComponentTasksManager.Instance.RestartTask(ComponentId); + _ = RestartComponentIfRunning(); break; case ActionIds.FullButtonElementClicked: ButtonClick(contentDefinition); From e013113273801ee5233466b4c3eecd4e9be91d54 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:54:16 +0000 Subject: [PATCH 073/202] Keep list settings items that contain the separator List settings joined items with ';', so a site list file name containing ';' became two broken entries. A ';' or '%' inside an item is now stored as %3B or %25; lists written by older versions contain neither sequence and read the same. --- CDPIUI.Shared/Basic/XMLSettingsService.cs | 18 +++++++++++++++--- .../Shared/XmlSettingsServiceTests.cs | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/CDPIUI.Shared/Basic/XMLSettingsService.cs b/CDPIUI.Shared/Basic/XMLSettingsService.cs index 3de689a6..ec977df8 100644 --- a/CDPIUI.Shared/Basic/XMLSettingsService.cs +++ b/CDPIUI.Shared/Basic/XMLSettingsService.cs @@ -105,6 +105,18 @@ private static XDocument LoadDocument(string path) return document; } + // Items are separated by ';'. A ';' or '%' inside an item is stored as %3B or %25, so file + // names with ';' survive; values written before contain neither sequence and read the same. + private static string JoinList(IEnumerable items) => + string.Join(";", items.Select(item => (item ?? string.Empty).Replace("%", "%25").Replace(";", "%3B"))); + + private static List SplitList(string value) => + value.Split(';') + .Select(item => System.Text.RegularExpressions.Regex.Replace(item, "%(3B|25)", match => + string.Equals(match.Groups[1].Value, "3B", StringComparison.OrdinalIgnoreCase) ? ";" : "%", + System.Text.RegularExpressions.RegexOptions.IgnoreCase)) + .ToList(); + private static void ApplySetting(XElement root, IEnumerable groupPath, string key, string type, string valueString) { XElement current = root; @@ -464,7 +476,7 @@ public void SetValue(string group, string key, T value) else if (typeof(T) == typeof(List)) { type = nameof(List); - valueString = string.Join(";", (List)(object)value); + valueString = JoinList((List)(object)value); Debug.WriteLine(valueString); } @@ -510,7 +522,7 @@ public void SetValue(IEnumerable groupPath, string key, T value) break; case List lst: type = nameof(List); - valueString = string.Join(";", lst); + valueString = JoinList(lst); break; case DateTime dateTime: type = nameof(DateTime); @@ -533,7 +545,7 @@ public void SetValue(IEnumerable groupPath, string key, T value) if (typeof(T) == typeof(bool) && type == "bool" && bool.TryParse(value, out var bv)) return (T)(object)bv; if (typeof(T) == typeof(string) && type == "string") return (T)(object)value; - if (typeof(T) == typeof(List) && type == nameof(List)) return string.IsNullOrEmpty(value) ? (T)(object)new List() : (T)(object)value.Split(';').ToList(); + if (typeof(T) == typeof(List) && type == nameof(List)) return string.IsNullOrEmpty(value) ? (T)(object)new List() : (T)(object)SplitList(value); if (typeof(T) == typeof(DateTime) && type == nameof(DateTime) && TryParseDateTime(value, out var dtv)) return (T)(object)dtv; diff --git a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs index 19221a2b..440d3046 100644 --- a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs +++ b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs @@ -90,4 +90,23 @@ public void ProcessWithOlderCopyDoesNotOverwriteOtherChanges() Assert.Equal("preset.json", reloaded.GetValue(["CONFIGS", "CSZTBN012"], "configFile")); Assert.False(File.Exists(SettingsPath + ".lock")); } + + [Fact] + public void ListItemsWithSeparatorsRoundTrip() + { + List items = [@"C:\Lists\a;b.txt", "100%.txt", "%3B literal", ""]; + new XMLSettingsService(SettingsPath).SetValue>("USERCHOISES", "siteLists", items); + + Assert.Equal(items, new XMLSettingsService(SettingsPath).GetValue>("USERCHOISES", "siteLists")); + } + + [Fact] + public void ListsWrittenByOlderVersionsAreRead() + { + Directory.CreateDirectory(_directory); + File.WriteAllText(SettingsPath, + ""); + + Assert.Equal([@"C:\x\100%\a.txt", "b.txt"], new XMLSettingsService(SettingsPath).GetValue>("USERCHOISES", "siteLists")); + } } From e9f51e84d005675dd4ab52c82fb18e8676d1d480 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:54:43 +0000 Subject: [PATCH 074/202] Save presets atomically without breaking the cached name SaveConfigItem replaced the cached item name with the raw name key before saving, so the UI showed $LOADDYNAMIC(...) afterwards, and wrote null when the preset had no separate raw name. The raw name is now used only for the written file. Presets are written through a temporary file, so a crash cannot leave a truncated preset. --- .../Configuration/ConfigurationService.cs | 17 ++++++++++--- .../Basic/Filesystem/FileSystemService.cs | 24 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs index d21b2d0f..11788a90 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs @@ -281,13 +281,24 @@ public static async Task SaveConfigItem(string filename, string packId, string folder = GetItemFolderFromPackId(packId); string fileName = Path.Combine(folder, filename); - item.name = item.not_converted_name; + // The file keeps the name as written by its author ($LOADDYNAMIC... keys), while the cached + // item keeps showing the localized name. + string? displayName = item.name; + string jsonString; + try + { + item.name = item.not_converted_name ?? item.name; + jsonString = JSONConvertor.SerializeObject(item); + } + finally + { + item.name = displayName; + } - string jsonString = JSONConvertor.SerializeObject(item); Logger.Instance.CreateDebugLog(nameof(ConfigurationService), jsonString); try { - File.WriteAllText(fileName, jsonString); + CDPIUI.Shared.Basic.Filesystem.FileSystemService.WriteAllTextAtomic(fileName, jsonString); } catch (Exception ex) { diff --git a/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs b/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs index 01aa07ff..0c74c50d 100644 --- a/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs +++ b/CDPIUI.Shared/Basic/Filesystem/FileSystemService.cs @@ -111,6 +111,30 @@ public static string GetNewTempFileName(string suffix, string? extention = null) return $"{secondsSinceEpoch}_{suffix}_{unique}.{extention!.TrimStart('.')}"; } + /// + /// Writes text to a temporary file next to the target and swaps it in, so readers never + /// see a half-written file and a crash keeps the previous content + /// + /// Target file + /// Text to write + public static void WriteAllTextAtomic(string path, string contents) + { + string fullPath = Path.GetFullPath(path); + string tempPath = fullPath + ".tmp-" + Guid.NewGuid().ToString("N"); + try + { + File.WriteAllText(tempPath, contents); + if (File.Exists(fullPath)) + File.Replace(tempPath, fullPath, null); + else + File.Move(tempPath, fullPath); + } + finally + { + if (File.Exists(tempPath)) File.Delete(tempPath); + } + } + /// /// Copy file to folder asynchronically /// From 12ba653a7b01c19aae19e32a11c7675e3109919f Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:55:44 +0000 Subject: [PATCH 075/202] Read batch files in their code page and match commands in any case The older .bat import read files only as UTF-8, which broke Cyrillic text in OEM 866 and ANSI 1251 files, and matched set, rem and start only in lower case. The import wizard fell back to 1251 for every non-UTF-8 file, although cmd batch files are often saved in 866. Both now use BatchFileEncoding, which honours a BOM, keeps valid UTF-8 and otherwise chooses between 866 and 1251 by where the Cyrillic bytes fall, and commands are matched in any case. --- .../ConfigImport/ZapretConfigImportService.cs | 32 ++---------- .../Configuration/ConfigurationService.cs | 8 +-- CDPIUI.Core/System/BatchFileEncoding.cs | 49 +++++++++++++++++++ CDPIUI.Tests/Core/BatchFileEncodingTests.cs | 28 +++++++++++ 4 files changed, 84 insertions(+), 33 deletions(-) create mode 100644 CDPIUI.Core/System/BatchFileEncoding.cs create mode 100644 CDPIUI.Tests/Core/BatchFileEncodingTests.cs diff --git a/CDPIUI.AddOns/ConfigImport/ZapretConfigImportService.cs b/CDPIUI.AddOns/ConfigImport/ZapretConfigImportService.cs index 83e0cc05..bd77ea95 100644 --- a/CDPIUI.AddOns/ConfigImport/ZapretConfigImportService.cs +++ b/CDPIUI.AddOns/ConfigImport/ZapretConfigImportService.cs @@ -1,4 +1,4 @@ -using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; using CDPIUI.Core.Store.Data; using CDPIUI.Core.Store.Database; using System.Security.Cryptography; @@ -1414,34 +1414,8 @@ private static void MergeVariables( } } - private static string[] ReadAllLines(string filePath) - { - byte[] bytes = File.ReadAllBytes(filePath); - Encoding encoding = DetectEncoding(bytes); - string text = encoding.GetString(bytes).TrimStart('\uFEFF'); - return text.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n'); - } - - private static Encoding DetectEncoding(byte[] bytes) - { - if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) - return new UTF8Encoding(encoderShouldEmitUTF8Identifier: true); - if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) - return Encoding.Unicode; - if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) - return Encoding.BigEndianUnicode; - - try - { - _ = new UTF8Encoding(false, true).GetString(bytes); - return new UTF8Encoding(false); - } - catch (DecoderFallbackException) - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - return Encoding.GetEncoding(1251); - } - } + private static string[] ReadAllLines(string filePath) => + CDPIUI.Core.System.BatchFileEncoding.ReadAllLines(filePath); private static string NormalizeWhitespace(string input) { diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs index 11788a90..b888b957 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs @@ -836,7 +836,7 @@ public static string GetItemFolderFromPackId(string packId) private static Tuple ConvertConfigFromBAT(string filepath) { // TODO: recursevily call other .BAT files via GOTO check - string[] lines = File.ReadAllLines(filepath, Encoding.UTF8); + string[] lines = CDPIUI.Core.System.BatchFileEncoding.ReadAllLines(filepath); Dictionary vars = []; List availableVarValues = []; @@ -852,7 +852,7 @@ private static Tuple ConvertConfigFromBAT(string filepath) if (string.IsNullOrEmpty(line)) continue; - if (line.StartsWith("set")) + if (line.StartsWith("set", StringComparison.OrdinalIgnoreCase)) { string[] setLine = line[3..].Split("="); if (setLine.Length >= 2) @@ -900,7 +900,7 @@ private static Tuple ConvertConfigFromBAT(string filepath) comment = line[2..^2].Trim(); continue; } - if (line.StartsWith("rem") && line.Contains("set")) + if (line.StartsWith("rem", StringComparison.OrdinalIgnoreCase) && line.Contains("set", StringComparison.OrdinalIgnoreCase)) { string _l = line[3..]; var rx = new Regex(@"\s+set\b", RegexOptions.None); @@ -947,7 +947,7 @@ private static Tuple ConvertConfigFromBAT(string filepath) } continue; } - if (line.StartsWith("start")) + if (line.StartsWith("start", StringComparison.OrdinalIgnoreCase)) { if (line.Contains("winws.exe")) { diff --git a/CDPIUI.Core/System/BatchFileEncoding.cs b/CDPIUI.Core/System/BatchFileEncoding.cs new file mode 100644 index 00000000..8866ecf9 --- /dev/null +++ b/CDPIUI.Core/System/BatchFileEncoding.cs @@ -0,0 +1,49 @@ +using System.Text; + +namespace CDPIUI.Core.System +{ + /// + /// Reads batch files that can be saved as UTF-8, UTF-16 or in a Cyrillic code page + /// + public static class BatchFileEncoding + { + public static string ReadAllText(string path) => Decode(File.ReadAllBytes(path)); + + public static string[] ReadAllLines(string path) => + ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n'); + + public static string Decode(byte[] bytes) => Detect(bytes).GetString(bytes).TrimStart('\uFEFF'); + + public static Encoding Detect(byte[] bytes) + { + if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) + return new UTF8Encoding(encoderShouldEmitUTF8Identifier: true); + if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) + return Encoding.Unicode; + if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) + return Encoding.BigEndianUnicode; + + try + { + _ = new UTF8Encoding(false, true).GetString(bytes); + return new UTF8Encoding(false); + } + catch (DecoderFallbackException) + { + } + + // Without a BOM a Cyrillic file is either OEM 866 (what cmd uses) or ANSI 1251 (Notepad). + // Lowercase letters fall into 0xA0-0xAF and 0xE0-0xEF in 866 and into 0xE0-0xFF in 1251, + // and 0x80-0xBF holds the 866 letters that 1251 uses only for rare symbols. + int oemScore = 0, ansiScore = 0; + foreach (byte value in bytes) + { + if (value >= 0x80 && value <= 0xAF) oemScore++; + else if (value >= 0xC0) ansiScore++; + } + + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + return Encoding.GetEncoding(oemScore > ansiScore ? 866 : 1251); + } + } +} diff --git a/CDPIUI.Tests/Core/BatchFileEncodingTests.cs b/CDPIUI.Tests/Core/BatchFileEncodingTests.cs new file mode 100644 index 00000000..c78cbab9 --- /dev/null +++ b/CDPIUI.Tests/Core/BatchFileEncodingTests.cs @@ -0,0 +1,28 @@ +using System.Text; +using CDPIUI.Core.System; + +namespace CDPIUI.Tests.Core; + +public class BatchFileEncodingTests +{ + private const string Text = "rem Обход блокировок YouTube и Discord\r\nset BIN=%~dp0bin\\"; + + static BatchFileEncodingTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + [Theory] + [InlineData(866)] + [InlineData(1251)] + [InlineData(65001)] + public void CyrillicBatchFilesAreDecoded(int codePage) + { + byte[] bytes = Encoding.GetEncoding(codePage).GetBytes(Text); + Assert.Equal(Text, BatchFileEncoding.Decode(bytes)); + } + + [Fact] + public void Utf8BomIsRemoved() + { + byte[] bytes = [.. new UTF8Encoding(true).GetPreamble(), .. Encoding.UTF8.GetBytes(Text)]; + Assert.Equal(Text, BatchFileEncoding.Decode(bytes)); + } +} From 241b0eefd136002ed33e5b6534e5e678033a1e11 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:56:20 +0000 Subject: [PATCH 076/202] Merge domain lists by whole lines When a pack updated a domain list, a new line was skipped if it appeared anywhere in the existing file as a substring, so t.co was dropped because the list had reddit.com, and every check scanned the whole file. Lines are now compared as a set, and the first added line no longer joins the last line of a file without a trailing newline. --- CDPIUI.Core/System/ZipService.cs | 41 ++++++++++++++++++++-------- CDPIUI.Tests/Core/ZipServiceTests.cs | 28 +++++++++++++++++++ 2 files changed, 57 insertions(+), 12 deletions(-) create mode 100644 CDPIUI.Tests/Core/ZipServiceTests.cs diff --git a/CDPIUI.Core/System/ZipService.cs b/CDPIUI.Core/System/ZipService.cs index 94acbcc5..0317da2b 100644 --- a/CDPIUI.Core/System/ZipService.cs +++ b/CDPIUI.Core/System/ZipService.cs @@ -152,23 +152,40 @@ bool mergeTextFiles destinationPath = $"{destinationPath}.bak"; } // End of piece of shit - string destLines = File.ReadAllText(destinationPath); - string tmpFile = Path.Combine(destinationDir!, $"__TEMPFILE.txt"); - entry.ExtractToFile(tmpFile, overwrite: true); - - var stream = File.AppendText(destinationPath); + // Whole lines are compared: as a substring, "t.co" was dropped because + // the list already had "reddit.com". + var destLines = new HashSet( + File.ReadLines(destinationPath).Select(line => line.Trim()), StringComparer.Ordinal); + bool endsWithNewLine; + using (var existing = File.OpenRead(destinationPath)) + { + endsWithNewLine = existing.Length == 0; + if (!endsWithNewLine) + { + existing.Seek(-1, SeekOrigin.End); + endsWithNewLine = existing.ReadByte() == '\n'; + } + } - using (stream) + var newLines = new List(); + using (var reader = new StreamReader(entry.Open())) { - foreach (var line in File.ReadLines(tmpFile)) + string? line; + while ((line = await reader.ReadLineAsync()) != null) { - if (!destLines.Contains(line)) - { - await stream.WriteLineAsync(line); - } + if (line.Trim().Length > 0 && destLines.Add(line.Trim())) + newLines.Add(line); } } - File.Delete(tmpFile); + + if (newLines.Count > 0) + { + using var stream = File.AppendText(destinationPath); + if (!endsWithNewLine) + await stream.WriteLineAsync(); + foreach (string line in newLines) + await stream.WriteLineAsync(line); + } continue; } diff --git a/CDPIUI.Tests/Core/ZipServiceTests.cs b/CDPIUI.Tests/Core/ZipServiceTests.cs new file mode 100644 index 00000000..dcf0693b --- /dev/null +++ b/CDPIUI.Tests/Core/ZipServiceTests.cs @@ -0,0 +1,28 @@ +using System.IO.Compression; +using CDPIUI.Core.System; + +namespace CDPIUI.Tests.Core; + +public sealed class ZipServiceTests : IDisposable +{ + private readonly string directory = Path.Combine(Path.GetTempPath(), "cdpiui-zip-" + Guid.NewGuid().ToString("N")); + + public void Dispose() => Directory.Delete(directory, true); + + [Fact] + public async Task DomainListsAreMergedByWholeLines() + { + string target = Path.Combine(directory, "item"); + Directory.CreateDirectory(target); + File.WriteAllText(Path.Combine(target, "list.txt"), "reddit.com"); + + string archivePath = Path.Combine(directory, "pack.zip"); + using (var archive = ZipFile.Open(archivePath, ZipArchiveMode.Create)) + using (var writer = new StreamWriter(archive.CreateEntry("list.txt").Open())) + writer.Write("t.co\nreddit.com\nyoutube.com\n"); + + await ZipService.ExtractZip(archivePath, "/", target); + + Assert.Equal(["reddit.com", "t.co", "youtube.com"], File.ReadAllLines(Path.Combine(target, "list.txt"))); + } +} From be3e6cac05319f972bbf4f25eafcb1b94677a328 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:56:43 +0000 Subject: [PATCH 077/202] Compare release tags with the version helper The update check parsed the release tag with new Version(...), which throws on tags such as v1.2 or 1.3-preview, and the patch chain did the same with the version taken from each patch URL. Both now use VersionHelper.CompareVersionStrings, which handles the v prefix, semantic versions and four-part versions. --- CDPIUI.Core/Features/ApplicationUpdate.cs | 6 ++---- CDPIUI.Core/Store/Application/ApplicationUpdateService.cs | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/CDPIUI.Core/Features/ApplicationUpdate.cs b/CDPIUI.Core/Features/ApplicationUpdate.cs index 52cdd48f..936071fa 100644 --- a/CDPIUI.Core/Features/ApplicationUpdate.cs +++ b/CDPIUI.Core/Features/ApplicationUpdate.cs @@ -109,10 +109,8 @@ public async Task CheckForUpdates(bool notify = false) return false; } - Version serverVersion = new(_data.Result.ReleaseTag!); - Version currentVersion = new(ApplicationInfo.Version); - - if (serverVersion > currentVersion) + // Release tags such as v1.2 or 1.3-preview do not parse as System.Version. + if (Store.VersionHelper.CompareVersionStrings(ApplicationInfo.Version, _data.Result.ReleaseTag) < 0) { ServerVersion = _data.Result.ReleaseTag!; IsUpdateAvailable = true; diff --git a/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs b/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs index ff462922..f8bf121a 100644 --- a/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs +++ b/CDPIUI.Core/Store/Application/ApplicationUpdateService.cs @@ -141,8 +141,7 @@ private async Task>> DownloadRequiredPatches( { string[] reversedParts = parts.Reverse().ToArray(); Logger.Instance.CreateInfoLog(nameof(ApplicationUpdateService), $"Version {reversedParts[1]}"); - Version patchVer = new(reversedParts[1]); - if (currentVersion >= patchVer) + if (VersionHelper.CompareVersionStrings(currentVersion.ToString(), reversedParts[1]) >= 0) continue; } else From 363c4e8d8f03b136f6e88f8e366965312eb47b90 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:57:31 +0000 Subject: [PATCH 078/202] Keep whole arguments when removing proxy address arguments ReplaseIp split the command line at every space and every '=', so --x=a=b became --x=a and a quoted path with spaces was cut apart. Arguments are now split only at whitespace outside double quotes and kept whole. --- CDPIUI.Core/Proxy/ProxyHelper.cs | 63 +++++++++++++++++---------- CDPIUI.Tests/Core/ProxyHelperTests.cs | 16 +++++++ 2 files changed, 57 insertions(+), 22 deletions(-) create mode 100644 CDPIUI.Tests/Core/ProxyHelperTests.cs diff --git a/CDPIUI.Core/Proxy/ProxyHelper.cs b/CDPIUI.Core/Proxy/ProxyHelper.cs index f388a983..0cff1aef 100644 --- a/CDPIUI.Core/Proxy/ProxyHelper.cs +++ b/CDPIUI.Core/Proxy/ProxyHelper.cs @@ -15,40 +15,59 @@ public static class ProxyHelper { public static List Tokens = new() { "-p", "--port", "-i", "--ip", "-addr", "--host" }; + /// + /// Removes the address and port arguments, which the application sets itself + /// public static string ReplaseIp(string args) { - string[] splittedArgs = args.Split(' '); + List tokens = SplitArguments(args); string finalArgs = string.Empty; - for (int i = 0; i < splittedArgs.Length; i++) + for (int i = 0; i < tokens.Count; i++) { - var spA = splittedArgs[i].Split("="); - string token = spA[0]; - string value = spA.Length > 1 ? spA[1] + " " : string.Empty; - if (Tokens.Contains(token)) + string token = tokens[i]; + int separator = token.IndexOf('='); + string name = separator >= 0 ? token[..separator] : token; + if (Tokens.Contains(name)) { - if (splittedArgs[i].Contains('=')) - { - continue; - } - else - { + // "--port 8080" takes the next token as its value, "--port=8080" does not. + if (separator < 0) i++; - continue; - } - } - if (!string.IsNullOrEmpty(value)) - { - finalArgs += $"{token}={value}"; - } - else - { - finalArgs += $"{token} "; + continue; } + // The token is kept whole: "--x=a=b" and quoted paths with spaces stay intact. + finalArgs += $"{token} "; } return finalArgs; } + // Whitespace separates arguments except inside double quotes, as on the command line. + private static List SplitArguments(string args) + { + var tokens = new List(); + var current = new global::System.Text.StringBuilder(); + bool quoted = false; + foreach (char c in args ?? string.Empty) + { + if (c == '"') + quoted = !quoted; + + if (char.IsWhiteSpace(c) && !quoted) + { + if (current.Length > 0) + { + tokens.Add(current.ToString()); + current.Clear(); + } + continue; + } + current.Append(c); + } + if (current.Length > 0) + tokens.Add(current.ToString()); + return tokens; + } + public static List ProxyLikeComponents = [ HardcodedItemIds.ComponentIds[Components.ByeDPI], HardcodedItemIds.ComponentIds[Components.NoDPI], diff --git a/CDPIUI.Tests/Core/ProxyHelperTests.cs b/CDPIUI.Tests/Core/ProxyHelperTests.cs new file mode 100644 index 00000000..1c8bbf3d --- /dev/null +++ b/CDPIUI.Tests/Core/ProxyHelperTests.cs @@ -0,0 +1,16 @@ +using CDPIUI.Core.Proxy; + +namespace CDPIUI.Tests.Core; + +public class ProxyHelperTests +{ + [Theory] + [InlineData("--port 1080 --mode=split", "--mode=split ")] + [InlineData("--ip=127.0.0.1 --port=1080 --auto=a=b", "--auto=a=b ")] + [InlineData("-addr 0.0.0.0 -f \"C:\\Program Files\\list.txt\"", "-f \"C:\\Program Files\\list.txt\" ")] + [InlineData(" --disorder 1 --host example.com ", "--disorder 1 ")] + public void AddressAndPortArgumentsAreRemoved(string args, string expected) + { + Assert.Equal(expected, ProxyHelper.ReplaseIp(args)); + } +} From 312979bcf43f3aa6d4902de7848e57f5f2009515 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:58:05 +0000 Subject: [PATCH 079/202] Do not treat apostrophes as quotes in preset command lines ConfigCommandLine.Tokenize grouped text between apostrophes like a quoted argument, so a file name or Lua argument with an apostrophe swallowed the arguments that followed it. Only double quotes group, as on the Windows command line. --- .../Helpers/Configuration/ConfigCommandLine.cs | 4 +++- CDPIUI.Tests/Core/ConfigCommandLineTests.cs | 9 ++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigCommandLine.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigCommandLine.cs index 8818383d..2d05e21b 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigCommandLine.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigCommandLine.cs @@ -23,7 +23,9 @@ public static IReadOnlyList Tokenize(string? commandLine) int backslashes = 0; foreach (char character in commandLine ?? string.Empty) { - if ((character is '"' or '\'') && + // Only double quotes group on the Windows command line; an apostrophe inside a value + // (a Lua argument, a file name) must not join the following arguments. + if (character == '"' && (quote == '\0' || quote == character) && backslashes % 2 == 0) { quote = quote == character ? '\0' : character; diff --git a/CDPIUI.Tests/Core/ConfigCommandLineTests.cs b/CDPIUI.Tests/Core/ConfigCommandLineTests.cs index 30d8a750..f331f99e 100644 --- a/CDPIUI.Tests/Core/ConfigCommandLineTests.cs +++ b/CDPIUI.Tests/Core/ConfigCommandLineTests.cs @@ -1,4 +1,4 @@ -using CDPIUI.Core.ComponentServices.Helpers.Configuration; +using CDPIUI.Core.ComponentServices.Helpers.Configuration; namespace CDPIUI.Tests.Core; @@ -20,4 +20,11 @@ public void TokenizeEmptyReturnsEmpty() Assert.Empty(ConfigCommandLine.Tokenize(null)); Assert.Empty(ConfigCommandLine.Tokenize(" ")); } + + [Fact] + public void ApostropheDoesNotGroupArguments() + { + Assert.Equal(["--hostlist=O'Brien.txt", "--wf-tcp=443"], + CDPIUI.Core.ComponentServices.Helpers.Configuration.ConfigCommandLine.Tokenize("--hostlist=O'Brien.txt --wf-tcp=443")); + } } From a4800c7a7e29ff618ee2f518cf3935f277d52445 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:58:34 +0000 Subject: [PATCH 080/202] Share HTTP clients between store requests Every API call and store sync created a RequestWorker with its own HttpClient and disposed it afterwards, which opens a new connection pool each time and leaves sockets in TIME_WAIT. Workers created without a client now use one shared client for direct and one for proxied connections. --- CDPIUI.Core/Store/Network/RequestWorker.cs | 23 +++++++++------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/CDPIUI.Core/Store/Network/RequestWorker.cs b/CDPIUI.Core/Store/Network/RequestWorker.cs index efa31351..1c396f26 100644 --- a/CDPIUI.Core/Store/Network/RequestWorker.cs +++ b/CDPIUI.Core/Store/Network/RequestWorker.cs @@ -12,14 +12,17 @@ internal sealed class RequestWorker : IDisposable { private readonly Lazy directClient; private readonly Lazy proxyClient; - private readonly bool ownsClient; private int disposed; + // A client per request leaves a connection pool and sockets behind every time; the workers + // created for single requests share these instead. + private static readonly Lazy SharedDirectClient = new(() => new HttpClient(CreateHandler(proxyEnable: false))); + private static readonly Lazy SharedProxyClient = new(() => new HttpClient(CreateHandler(proxyEnable: true))); + public RequestWorker(HttpClient? client = null) { - directClient = new(() => client ?? new HttpClient(CreateHandler(proxyEnable: false))); - proxyClient = new(() => client ?? new HttpClient(CreateHandler(proxyEnable: true))); - ownsClient = client == null; + directClient = client != null ? new(() => client) : SharedDirectClient; + proxyClient = client != null ? new(() => client) : SharedProxyClient; } private static HttpClientHandler CreateHandler(bool proxyEnable) @@ -143,15 +146,7 @@ private static Uri CreateProxyUri(string url) return builder.Uri; } - public void Dispose() - { - if (Interlocked.Exchange(ref disposed, 1) == 0 && ownsClient) - { - if (directClient.IsValueCreated) - directClient.Value.Dispose(); - if (proxyClient.IsValueCreated) - proxyClient.Value.Dispose(); - } - } + // The clients are shared or owned by the caller, so only this worker is marked as disposed. + public void Dispose() => Interlocked.Exchange(ref disposed, 1); } } From 0475a072bfea63fcf943ae0f14e87acabebf0861 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:59:12 +0000 Subject: [PATCH 081/202] Rotate log files and never fall back to the working directory Log files grew without limit, and a write failed whenever the UI and the tray appended to the same file at once. A log over 5 MB is now moved to *.old.log, and files are opened for appending with shared write access. When the data directory cannot be determined, files went to the current working directory; they now go to %LocalAppData%\CDPIUI. --- CDPIUI.Core/Data/Directories.cs | 6 ++++-- CDPIUI.Shared/Logger/LoggerBase.cs | 17 ++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/CDPIUI.Core/Data/Directories.cs b/CDPIUI.Core/Data/Directories.cs index 677730f5..36d7f86d 100644 --- a/CDPIUI.Core/Data/Directories.cs +++ b/CDPIUI.Core/Data/Directories.cs @@ -96,9 +96,11 @@ private string TryGetDataDirectory() } else { - DataDirectoryProperty = string.Empty; + // An empty path made every file go to the current working directory. + DataDirectoryProperty = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CDPIUI"); CoreEvents.Instance.InvokeCriticalCoreExceptionHappens(result.Error ?? new UnknownException()); - return string.Empty; + return DataDirectoryProperty; } } diff --git a/CDPIUI.Shared/Logger/LoggerBase.cs b/CDPIUI.Shared/Logger/LoggerBase.cs index 298455bb..19c50846 100644 --- a/CDPIUI.Shared/Logger/LoggerBase.cs +++ b/CDPIUI.Shared/Logger/LoggerBase.cs @@ -31,6 +31,9 @@ public class LoggerBase(string? actualPath, LogSelevirity logLevel) public readonly LogSelevirity? LogLevel = logLevel; private static readonly object _logLock = new object(); + // A log grows without limit otherwise; the previous file is kept as *.old.log. + private const long MaxLogFileSize = 5 * 1024 * 1024; + private void LogWrite(string fileName, string logMessage) { if (string.IsNullOrEmpty(ActualPath)) return; @@ -40,12 +43,20 @@ private void LogWrite(string fileName, string logMessage) string logFilePath = Path.Combine(logFileDir, $"{fileName}{LoggerResources.LogsFileExtention}"); if (!Directory.Exists(logFileDir)) Directory.CreateDirectory(logFileDir); - if (!File.Exists(logFilePath)) + + var info = new FileInfo(logFilePath); + if (info.Exists && info.Length > MaxLogFileSize) { - File.WriteAllText(logFilePath, LoggerResources.LoggerReadyMessage + $" {LogLevel} " + Environment.NewLine); + File.Copy(logFilePath, Path.ChangeExtension(logFilePath, ".old" + LoggerResources.LogsFileExtention), true); + File.WriteAllText(logFilePath, string.Empty); + info.Refresh(); } - using StreamWriter w = File.AppendText(logFilePath); + // Shared write access: the UI and the tray may log to the same file at the same time. + using var stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + using var w = new StreamWriter(stream); + if (!info.Exists || info.Length == 0) + w.WriteLine(LoggerResources.LoggerReadyMessage + $" {LogLevel} "); WriteMessageToTextWriter(logMessage, w); } catch { } From 587cc1d71d859a25e1a35b642072952edf682c90 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:00:18 +0000 Subject: [PATCH 082/202] Queue content dialogs per window WinUI allows one open ContentDialog per window, and ShowAsync throws when another one is already shown, which happened whenever an error or a background event raised a dialog over an open one. All content dialogs now go through ShowQueuedAsync, which waits until the dialogs opened before it in the same window are closed. MessageDialog calls are unchanged. --- .../ComponentHelpfulLinksUserControl.xaml.cs | 2 +- .../ComponentSettings/ConfigSelector.xaml.cs | 2 +- .../ComponentSettingUserControl.xaml.cs | 2 +- .../ConfigMakerUserControl.xaml.cs | 18 +++++----- .../CreateConfigDesignerUserControl.xaml.cs | 4 +-- ...GoodCheckReportStrategyUserControl.xaml.cs | 2 +- .../VariableUserControl.xaml.cs | 2 +- .../Dialogs/Universal/ErrorContentDialog.cs | 2 +- .../MainPage/ComponentTileUserControl.xaml.cs | 2 +- .../SmallComponentTileUserControl.xaml.cs | 2 +- .../Store/StoreDownloadItemButton.xaml.cs | 2 +- .../AddOns/ConfigShare/ConfigShareUI.cs | 4 +-- CDPIUI/Helper/AddOns/HostsFileEditHelper.cs | 2 +- CDPIUI/Helper/Basic/ContentDialogQueue.cs | 36 +++++++++++++++++++ .../UserExperience/ConsoleFontHelper.cs | 2 +- CDPIUI/Helper/ViewModels/WidgetHelper.cs | 2 +- CDPIUI/Views/BlockCheck2/MainPage.xaml.cs | 2 +- .../BlockCheck2/PresetReviewPage.xaml.cs | 8 ++--- .../BlockCheck2/ReportHistoryPage.xaml.cs | 2 +- CDPIUI/Views/BlockCheck2/ResultPage.xaml.cs | 4 +-- .../CreateNewConfigPage.xaml.cs | 4 +-- .../EditConfigKitPage.xaml.cs | 2 +- .../Views/CreateConfigHelper/MainPage.xaml.cs | 4 +-- .../CreateViaGoodCheckPage.xaml.cs | 2 +- .../DefaultComponentSettingsPage.xaml.cs | 8 ++--- .../Components/TgWsProxyComponentPage.xaml.cs | 8 ++--- CDPIUI/Views/ModernMainPage.xaml.cs | 2 +- CDPIUI/Views/SettingsPage.xaml.cs | 2 +- .../Views/SetupProxy/ManualSetupPage.xaml.cs | 2 +- .../SetupProxy/ProxiFyreSetupPage.xaml.cs | 4 +-- .../SetupProxy/SetupProxyForSystem.xaml.cs | 2 +- CDPIUI/Views/Store/ItemViewPage.xaml.cs | 10 +++--- CDPIUI/Views/Store/ReadyKitViewPage.xaml.cs | 6 ++-- ...ryViewConditionalLaunchDetailsPage.xaml.cs | 2 +- CDPIUI/Views/Store/SettingsPage.xaml.cs | 2 +- .../Windows/BlockCheck2ResultWindow.xaml.cs | 2 +- .../Windows/ConditionalLaunchWindow.xaml.cs | 2 +- .../ConditionalTaskEditorWindow.xaml.cs | 4 +-- CDPIUI/Windows/ConfigMakerWindow.xaml.cs | 8 ++--- .../Windows/CreateConfigHelperWindow.xaml.cs | 10 +++--- CDPIUI/Windows/CreateConfigUtilWindow.xaml.cs | 2 +- .../Messages/StoreSmallDownloadDialog.xaml.cs | 2 +- CDPIUI/Windows/StoreWindow.xaml.cs | 2 +- CDPIUI/Windows/WelcomeWindow.xaml.cs | 4 +-- 44 files changed, 117 insertions(+), 81 deletions(-) create mode 100644 CDPIUI/Helper/Basic/ContentDialogQueue.cs diff --git a/CDPIUI/Controls/ComponentSettings/ComponentHelpfulLinksUserControl.xaml.cs b/CDPIUI/Controls/ComponentSettings/ComponentHelpfulLinksUserControl.xaml.cs index c3f209fe..2648eabd 100644 --- a/CDPIUI/Controls/ComponentSettings/ComponentHelpfulLinksUserControl.xaml.cs +++ b/CDPIUI/Controls/ComponentSettings/ComponentHelpfulLinksUserControl.xaml.cs @@ -75,7 +75,7 @@ private async void SettingsCard_Click(object sender, RoutedEventArgs e) { XamlRoot = this.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); break; case HelpfulLinkType.SetupProxy: CommandsHandler.HandleCommand($"cdpiui://Tools/Proxy"); diff --git a/CDPIUI/Controls/ComponentSettings/ConfigSelector.xaml.cs b/CDPIUI/Controls/ComponentSettings/ConfigSelector.xaml.cs index fa2c3fb2..81be84c6 100644 --- a/CDPIUI/Controls/ComponentSettings/ConfigSelector.xaml.cs +++ b/CDPIUI/Controls/ComponentSettings/ConfigSelector.xaml.cs @@ -60,7 +60,7 @@ private async void ShareButton_Click(object sender, RoutedEventArgs e) XamlRoot = XamlRoot, Title = Helper.AddOns.ConfigShare.ConfigShareUI.Text("ConfigShareError"), Message = Helper.AddOns.ConfigShare.ConfigShareUI.ErrorText(exception) }; - await error.ShowAsync(); + await error.ShowQueuedAsync(); } finally { ShareButton.IsEnabled = true; } } diff --git a/CDPIUI/Controls/CreateConfigHelper/ComponentSettingUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/ComponentSettingUserControl.xaml.cs index 2ef56654..990a7acf 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ComponentSettingUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/ComponentSettingUserControl.xaml.cs @@ -371,7 +371,7 @@ private async void ViewSelectedFileButton_Click(object sender, RoutedEventArgs e XamlRoot = this.XamlRoot, FilePath = TextValue.Replace("\"", ""), }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.IsSuccess) SettingsManager.Instance.SetValue("FILEOPENACTIONS", "isDialogShown", true); } diff --git a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs index b2456a2f..4af59e64 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/ConfigMakerUserControl.xaml.cs @@ -1038,7 +1038,7 @@ private async void ReplacePresetFileItem_Click(object sender, RoutedEventArgs e) CloseButtonText = localizer.GetLocalizedString("Cancel"), DefaultButton = ContentDialogButton.Primary, }; - ContentDialogResult result = await dialog.ShowAsync(); + ContentDialogResult result = await dialog.ShowQueuedAsync(); if (result == ContentDialogResult.Primary) { ConfigImportAutoCorrector autoCorrector = new(); @@ -1393,7 +1393,7 @@ private async void OpenPresetFileItem_Click(object sender, RoutedEventArgs e) XamlRoot = XamlRoot, FilePath = path, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.IsSuccess) { SettingsManager.Instance.SetValue("FILEOPENACTIONS", "isDialogShown", true); @@ -1548,7 +1548,7 @@ private async void RemovePresetFileItem_Click(object sender, RoutedEventArgs e) CloseButtonText = localizer.GetLocalizedString("Cancel"), DefaultButton = ContentDialogButton.Close, }; - if (await confirmation.ShowAsync() != ContentDialogResult.Primary) + if (await confirmation.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } @@ -2082,7 +2082,7 @@ public async Task SaveToApplicationAsync() OverwriteEnable = !string.IsNullOrWhiteSpace(presetDocument.PackId) && !string.IsNullOrWhiteSpace(presetDocument.FileName), }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { return ConfigMakerPresetSaveResult.Failed("CANCELED"); } @@ -2136,7 +2136,7 @@ private async void CreateVariableButton_Click(object sender, RoutedEventArgs e) { XamlRoot = XamlRoot, }; - if (await dialog.ShowAsync() == ContentDialogResult.Primary && + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary && dialog.ResultVariable != null) { presetDocument.Variables.Add(dialog.ResultVariable); @@ -2162,7 +2162,7 @@ private async Task EditVariableAsync(ConfigMakerVariableDefinition variable) { XamlRoot = XamlRoot, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary || + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary || dialog.ResultVariable == null) { return; @@ -2203,7 +2203,7 @@ private async void RemoveVariableButton_Click(object sender, RoutedEventArgs e) CloseButtonText = localizer.GetLocalizedString("Cancel"), DefaultButton = ContentDialogButton.Close, }; - if (await confirmation.ShowAsync() != ContentDialogResult.Primary) + if (await confirmation.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } @@ -2906,7 +2906,7 @@ public async Task NewDocumentAsync() CloseButtonText = localizer.GetLocalizedString("Cancel"), DefaultButton = ContentDialogButton.Close, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } @@ -3029,7 +3029,7 @@ public async Task StartTestAsync() CloseButtonText = localizer.GetLocalizedString("Cancel"), DefaultButton = ContentDialogButton.Close, }; - if (await confirmation.ShowAsync() != ContentDialogResult.Primary) + if (await confirmation.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } diff --git a/CDPIUI/Controls/CreateConfigHelper/CreateConfigDesignerUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/CreateConfigDesignerUserControl.xaml.cs index ca5fe2f0..ed29411d 100644 --- a/CDPIUI/Controls/CreateConfigHelper/CreateConfigDesignerUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/CreateConfigDesignerUserControl.xaml.cs @@ -168,7 +168,7 @@ private void ViewFullArgs() Args = [this.Args ?? string.Empty] }; - _ = dialog.ShowAsync(); + _ = dialog.ShowQueuedAsync(); } private async void EditByeDPIMode() @@ -177,7 +177,7 @@ private async void EditByeDPIMode() { XamlRoot = this.XamlRoot, }; - var result = await dialog.ShowAsync(); + var result = await dialog.ShowQueuedAsync(); if (result == ContentDialogResult.Primary) { Modes = dialog.Result; diff --git a/CDPIUI/Controls/CreateConfigHelper/GoodCheckReportStrategyUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/GoodCheckReportStrategyUserControl.xaml.cs index e98c9cea..72ddf2cf 100644 --- a/CDPIUI/Controls/CreateConfigHelper/GoodCheckReportStrategyUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/GoodCheckReportStrategyUserControl.xaml.cs @@ -212,7 +212,7 @@ private void ViewFullArgs() Args = [this.Args ?? string.Empty] }; - _ = dialog.ShowAsync(); + _ = dialog.ShowQueuedAsync(); } private void SetVisible(bool isVisible) diff --git a/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml.cs b/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml.cs index eeacab4e..cf6fa1e5 100644 --- a/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml.cs +++ b/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml.cs @@ -125,7 +125,7 @@ private async void EditButton_Click(object sender, RoutedEventArgs e) { XamlRoot = this.XamlRoot, }; - var result = await dialog.ShowAsync(); + var result = await dialog.ShowQueuedAsync(); if (result == ContentDialogResult.Primary) { VarValue = dialog.VarValue; diff --git a/CDPIUI/Controls/Dialogs/Universal/ErrorContentDialog.cs b/CDPIUI/Controls/Dialogs/Universal/ErrorContentDialog.cs index 783a7be8..33c4db02 100644 --- a/CDPIUI/Controls/Dialogs/Universal/ErrorContentDialog.cs +++ b/CDPIUI/Controls/Dialogs/Universal/ErrorContentDialog.cs @@ -123,7 +123,7 @@ public async Task ShowErrorDialogAsync(string content, string errorDetails, Xaml dialog.Content = scrollView; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } private void ViewMoreHandler(object sender, RoutedEventArgs e) diff --git a/CDPIUI/Controls/MainPage/ComponentTileUserControl.xaml.cs b/CDPIUI/Controls/MainPage/ComponentTileUserControl.xaml.cs index aa149f01..6093db8c 100644 --- a/CDPIUI/Controls/MainPage/ComponentTileUserControl.xaml.cs +++ b/CDPIUI/Controls/MainPage/ComponentTileUserControl.xaml.cs @@ -617,7 +617,7 @@ private async void AvailableFeaturesButton_Click(object sender, RoutedEventArgs { XamlRoot = this.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); break; } } diff --git a/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml.cs b/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml.cs index c9f57406..db0800a5 100644 --- a/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml.cs +++ b/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml.cs @@ -367,6 +367,6 @@ private async void ProxyButton_Click(object sender, RoutedEventArgs e) { XamlRoot = this.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } } diff --git a/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs b/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs index 562cdd77..cc9636cc 100644 --- a/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs +++ b/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs @@ -507,7 +507,7 @@ private async void ViewMoreButton_Click(object sender, RoutedEventArgs e) Text = Description }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } private void UpdateButton_Click(object sender, RoutedEventArgs e) diff --git a/CDPIUI/Helper/AddOns/ConfigShare/ConfigShareUI.cs b/CDPIUI/Helper/AddOns/ConfigShare/ConfigShareUI.cs index b6989aa6..4dc50a7a 100644 --- a/CDPIUI/Helper/AddOns/ConfigShare/ConfigShareUI.cs +++ b/CDPIUI/Helper/AddOns/ConfigShare/ConfigShareUI.cs @@ -30,7 +30,7 @@ internal static async Task ShowExportAsync(XamlRoot root, ConfigSelectorItem sel { await Task.Run(ConfigShareService.CleanupPreviousSystemShares); var dialog = new ConfigShareExportContentDialog(selected) { XamlRoot = root }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } internal static async Task OfferComponentInstallAsync(XamlRoot root, ConfigItem config) @@ -48,7 +48,7 @@ internal static async Task OfferComponentInstallAsync(XamlRoot root, ConfigItem PrimaryButtonText = Text("ConfigShareInstallComponent"), CloseButtonText = Text("ConfigShareLater") }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) return; + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) return; if (ConfigShareService.GetMissingComponentId(config) == null) return; Logger.Instance.CreateInfoLog(nameof(ConfigShareUI), $"Opening required component installer: {componentId}"); var app = (App)Application.Current; diff --git a/CDPIUI/Helper/AddOns/HostsFileEditHelper.cs b/CDPIUI/Helper/AddOns/HostsFileEditHelper.cs index e482630e..74cfdeef 100644 --- a/CDPIUI/Helper/AddOns/HostsFileEditHelper.cs +++ b/CDPIUI/Helper/AddOns/HostsFileEditHelper.cs @@ -35,7 +35,7 @@ private static async void ShowEditAskDialog(string file, XamlRoot xamlRoot) UseUAC = true, UseNotepadAsDefault = true, }; - await editSitelistAskApplicationContentDialog.ShowAsync(); + await editSitelistAskApplicationContentDialog.ShowQueuedAsync(); if (editSitelistAskApplicationContentDialog.IsSuccess) SettingsManager.Instance.SetValue("FILEOPENACTIONS", "isDialogShown", true); } diff --git a/CDPIUI/Helper/Basic/ContentDialogQueue.cs b/CDPIUI/Helper/Basic/ContentDialogQueue.cs new file mode 100644 index 00000000..d02f710e --- /dev/null +++ b/CDPIUI/Helper/Basic/ContentDialogQueue.cs @@ -0,0 +1,36 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; + +namespace CDPIUI; + +/// +/// Only one can be open in a window: ShowAsync throws while another one +/// is shown, which happened when a background event raised a dialog over an open one +/// +public static class ContentDialogQueue +{ + private static readonly ConditionalWeakTable Gates = new(); + + /// + /// Shows the dialog once the dialogs opened before it in the same window are closed + /// + public static async Task ShowQueuedAsync(this ContentDialog dialog) + { + if (dialog.XamlRoot == null) + return await dialog.ShowAsync(); + + SemaphoreSlim gate = Gates.GetValue(dialog.XamlRoot, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(); + try + { + return await dialog.ShowAsync(); + } + finally + { + gate.Release(); + } + } +} diff --git a/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs b/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs index 37bb7e82..4b16ad54 100644 --- a/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs +++ b/CDPIUI/Helper/UserExperience/ConsoleFontHelper.cs @@ -105,7 +105,7 @@ public async void ShowFontSettingsDialogForXamlRoot(XamlRoot xamlRoot) { FontSettingsContentDialog dialog = new() { XamlRoot = xamlRoot }; - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) { FontFamily = dialog.FontName; FontSize = dialog.FontSize; diff --git a/CDPIUI/Helper/ViewModels/WidgetHelper.cs b/CDPIUI/Helper/ViewModels/WidgetHelper.cs index f9656f6c..4582b3f3 100644 --- a/CDPIUI/Helper/ViewModels/WidgetHelper.cs +++ b/CDPIUI/Helper/ViewModels/WidgetHelper.cs @@ -168,7 +168,7 @@ public static async void RunActions(WidgetType actionType, object actionObject, dialog.XamlRoot = xamlRoot; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); break; case WidgetType.LaunchUrl: diff --git a/CDPIUI/Views/BlockCheck2/MainPage.xaml.cs b/CDPIUI/Views/BlockCheck2/MainPage.xaml.cs index c1a22edb..a7f1c778 100644 --- a/CDPIUI/Views/BlockCheck2/MainPage.xaml.cs +++ b/CDPIUI/Views/BlockCheck2/MainPage.xaml.cs @@ -299,7 +299,7 @@ private async System.Threading.Tasks.Task EditCustomSiteListAsync( XamlRoot = XamlRoot, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } diff --git a/CDPIUI/Views/BlockCheck2/PresetReviewPage.xaml.cs b/CDPIUI/Views/BlockCheck2/PresetReviewPage.xaml.cs index c01c596b..b3ed509b 100644 --- a/CDPIUI/Views/BlockCheck2/PresetReviewPage.xaml.cs +++ b/CDPIUI/Views/BlockCheck2/PresetReviewPage.xaml.cs @@ -114,7 +114,7 @@ private async void AllowEditingCheckBox_Click(object sender, RoutedEventArgs e) CloseButtonText = Text("BlockCheck2CancelDialogButtonText"), DefaultButton = ContentDialogButton.Close, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { updatingEditingToggle = true; AllowEditingCheckBox.IsChecked = false; @@ -143,7 +143,7 @@ public async Task NavigateBackToBuilderAsync() CloseButtonText = Text("BlockCheck2CancelDialogButtonText"), DefaultButton = ContentDialogButton.Close, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } @@ -196,7 +196,7 @@ public async Task SaveToApplicationAsync() }; nameTextBox.TextChanged += (_, _) => dialog.IsPrimaryButtonEnabled = !string.IsNullOrWhiteSpace(nameTextBox.Text); - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } @@ -266,7 +266,7 @@ private async void ShowDialog() XamlRoot = this.XamlRoot }; BlockCheck2ResultWindow window = ((App)Application.Current).GetCurrentWindowFromType(); - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) window?.Close(); else { diff --git a/CDPIUI/Views/BlockCheck2/ReportHistoryPage.xaml.cs b/CDPIUI/Views/BlockCheck2/ReportHistoryPage.xaml.cs index 4b96beff..8016394a 100644 --- a/CDPIUI/Views/BlockCheck2/ReportHistoryPage.xaml.cs +++ b/CDPIUI/Views/BlockCheck2/ReportHistoryPage.xaml.cs @@ -211,7 +211,7 @@ private async void DeleteButton_Click(object sender, RoutedEventArgs e) CloseButtonText = Text("BlockCheck2CancelDialogButtonText"), DefaultButton = ContentDialogButton.Close, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } diff --git a/CDPIUI/Views/BlockCheck2/ResultPage.xaml.cs b/CDPIUI/Views/BlockCheck2/ResultPage.xaml.cs index e7e95fb0..a33e253a 100644 --- a/CDPIUI/Views/BlockCheck2/ResultPage.xaml.cs +++ b/CDPIUI/Views/BlockCheck2/ResultPage.xaml.cs @@ -480,7 +480,7 @@ public async Task StartTestAsync() CloseButtonText = localizer.GetLocalizedString("Cancel"), DefaultButton = ContentDialogButton.Close, }; - if (await confirmation.ShowAsync() != ContentDialogResult.Primary) + if (await confirmation.ShowQueuedAsync() != ContentDialogResult.Primary) { return; } @@ -578,7 +578,7 @@ private async void AddForListButton_Click(object sender, RoutedEventArgs e) CloseButtonText = Text("BlockCheck2CancelDialogButtonText"), DefaultButton = ContentDialogButton.Primary, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary || selector.SelectedItem is not string path) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary || selector.SelectedItem is not string path) { return; } diff --git a/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs b/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs index 0835af97..b2909c18 100644 --- a/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigHelper/CreateNewConfigPage.xaml.cs @@ -483,7 +483,7 @@ private async void AskAutoFillFiles(ConfigItem configItem, string dir, AskAutoFi { XamlRoot = this.XamlRoot }; - var result = await dialog.ShowAsync(); + var result = await dialog.ShowQueuedAsync(); if (dialog.Result == CreateConfigResult.Selected) { ConfigItem = ConfigurationService.ReplaceFilesPath(ConfigItem, dialog.Files); @@ -789,7 +789,7 @@ private async void ShowDialog() XamlRoot = this.XamlRoot }; CreateConfigHelperWindow.Instanse.IsOperationExitAskAvailable = false; - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) CreateConfigHelperWindow.Instanse.Close(); else { diff --git a/CDPIUI/Views/CreateConfigHelper/EditConfigKitPage.xaml.cs b/CDPIUI/Views/CreateConfigHelper/EditConfigKitPage.xaml.cs index c065d1f5..26cfb5fd 100644 --- a/CDPIUI/Views/CreateConfigHelper/EditConfigKitPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigHelper/EditConfigKitPage.xaml.cs @@ -295,7 +295,7 @@ private async void SaveAsButton_Click(object sender, RoutedEventArgs e) DisplayName = DatabaseHelper.Instance.GetItemById(KitId)?.ShortName + $" ({localizer.GetLocalizedString("Edited")})" ?? string.Empty, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); var result = dialog.Result; diff --git a/CDPIUI/Views/CreateConfigHelper/MainPage.xaml.cs b/CDPIUI/Views/CreateConfigHelper/MainPage.xaml.cs index 52fdb41b..c2891e72 100644 --- a/CDPIUI/Views/CreateConfigHelper/MainPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigHelper/MainPage.xaml.cs @@ -62,7 +62,7 @@ private async void EditConfigButton_Click(object sender, RoutedEventArgs e) { XamlRoot = this.Content.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.SelectedConfigResult == SelectResult.Selected) { ConfigItem configItem = dialog.SelectedConfigItem; @@ -82,7 +82,7 @@ private async void GoodCheckRecentReportButton_Click(object sender, RoutedEventA { XamlRoot = this.Content.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.SelectedResult == SelectResult.Selected) { string directory = dialog.SelectedReport; diff --git a/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs b/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs index a9ef4d48..9f9b8b47 100644 --- a/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml.cs @@ -868,7 +868,7 @@ private async void ShowErrorDialod(string message = null) PrimaryButtonText = "OK", XamlRoot = this.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); CreateConfigUtilWindow window = await ((App)Application.Current).SafeCreateNewWindow(); window.Close(); } diff --git a/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs b/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs index e497d58c..722a4cb3 100644 --- a/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs +++ b/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs @@ -327,7 +327,7 @@ private void HandleSettingTileElementClick(ActionIds actionId, List argu Args = contentDefinition.PrettyViewParams, XamlRoot = this.XamlRoot, }; - _ = dialog.ShowAsync(); + _ = dialog.ShowQueuedAsync(); break; case ActionIds.OpenFolderClicked: ShellHelper.LookupFileInDirectory(contentDefinition.EditFilePath); @@ -393,7 +393,7 @@ private async void ShowEditCommaVariableDialog(SettingTileContentDefinition cont { XamlRoot = XamlRoot, }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary || + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary || string.Equals(dialog.VarValue, variable.value, StringComparison.Ordinal)) { return; @@ -449,7 +449,7 @@ private async void ShowChangeListDialog(string file, string packId, string fileN FileName = fileName, IsIpSet = isIPSet, }; - await changeListContentDialog.ShowAsync(); + await changeListContentDialog.ShowQueuedAsync(); if (changeListContentDialog.IsDialogFinishedSuccessfully) { @@ -489,7 +489,7 @@ private async void ShowEditAskDialog(string file) XamlRoot = this.XamlRoot, FilePath = file }; - await editSitelistAskApplicationContentDialog.ShowAsync(); + await editSitelistAskApplicationContentDialog.ShowQueuedAsync(); if (editSitelistAskApplicationContentDialog.IsSuccess) SettingsManager.Instance.SetValue("FILEOPENACTIONS", "isDialogShown", true); } diff --git a/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs b/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs index f277ed9b..dd21e66f 100644 --- a/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs +++ b/CDPIUI/Views/Main/Components/TgWsProxyComponentPage.xaml.cs @@ -276,7 +276,7 @@ private async void EditElement(string guid) Title = localizer.GetLocalizedString("EditDataCenter") }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.Result) { @@ -333,7 +333,7 @@ private async void AddButton_Click(object sender, RoutedEventArgs e) Title = localizer.GetLocalizedString("AddDataCenter") }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.Result) { TelegramDataCenterModels.Add(new() @@ -453,7 +453,7 @@ private async void CreateConfig() XamlRoot = this.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.Result == CreateNewConfigForComponentContentDialog.ConfigCreationVariants.FromTemplate) { @@ -581,7 +581,7 @@ private async void LinkedSettingClicked(object param) { XamlRoot = this.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); break; } } diff --git a/CDPIUI/Views/ModernMainPage.xaml.cs b/CDPIUI/Views/ModernMainPage.xaml.cs index 66fbee01..29aebb6f 100644 --- a/CDPIUI/Views/ModernMainPage.xaml.cs +++ b/CDPIUI/Views/ModernMainPage.xaml.cs @@ -174,7 +174,7 @@ private async void QHyperlinkButton_Click(object sender, RoutedEventArgs e) { XamlRoot = this.XamlRoot, }; - await q.ShowAsync(); + await q.ShowQueuedAsync(); } private void RootGrid_SizeChanged(object sender, SizeChangedEventArgs e) diff --git a/CDPIUI/Views/SettingsPage.xaml.cs b/CDPIUI/Views/SettingsPage.xaml.cs index d9cdab44..5feeba7d 100644 --- a/CDPIUI/Views/SettingsPage.xaml.cs +++ b/CDPIUI/Views/SettingsPage.xaml.cs @@ -180,7 +180,7 @@ private async void OpenComponentSiteListToEditCard_Click(object sender, RoutedEv { XamlRoot = this.XamlRoot }; - await editSitelistAskApplicationContentDialog.ShowAsync(); + await editSitelistAskApplicationContentDialog.ShowQueuedAsync(); UpdateTextFileOpenSettings(); } diff --git a/CDPIUI/Views/SetupProxy/ManualSetupPage.xaml.cs b/CDPIUI/Views/SetupProxy/ManualSetupPage.xaml.cs index 453858f7..fffac084 100644 --- a/CDPIUI/Views/SetupProxy/ManualSetupPage.xaml.cs +++ b/CDPIUI/Views/SetupProxy/ManualSetupPage.xaml.cs @@ -119,7 +119,7 @@ private bool SaveSettings() CloseButtonText = "OK", Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style, XamlRoot = this.XamlRoot - }.ShowAsync(); + }.ShowQueuedAsync(); } return false; } diff --git a/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs b/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs index 05924411..12dfdfa1 100644 --- a/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs +++ b/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs @@ -380,7 +380,7 @@ private async void ApplicationBlackListCard_Click(object sender, RoutedEventArgs SelectAppContentDialog dialog = new SelectAppContentDialog(BlackList); dialog.XamlRoot = this.XamlRoot; dialog.Title = string.Format(localizer.GetLocalizedString("EditApplicationListDialogTitle"), localizer.GetLocalizedString("ApplicationBlackList")); - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); BlackList = dialog._applications.ToList(); SetDescription(); @@ -391,7 +391,7 @@ private async void ApplicationWhiteListCard_Click(object sender, RoutedEventArgs SelectAppContentDialog dialog = new SelectAppContentDialog(WhiteList); dialog.XamlRoot = this.XamlRoot; dialog.Title = string.Format(localizer.GetLocalizedString("EditApplicationListDialogTitle"), localizer.GetLocalizedString("ApplicationWhiteList")); - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); WhiteList = dialog._applications.ToList(); SetDescription(); diff --git a/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs b/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs index 59359e4b..d4ee5dfb 100644 --- a/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs +++ b/CDPIUI/Views/SetupProxy/SetupProxyForSystem.xaml.cs @@ -129,7 +129,7 @@ private bool SaveSettings() CloseButtonText = "OK", Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style, XamlRoot = this.XamlRoot - }.ShowAsync(); + }.ShowQueuedAsync(); } return false; } diff --git a/CDPIUI/Views/Store/ItemViewPage.xaml.cs b/CDPIUI/Views/Store/ItemViewPage.xaml.cs index cae83a80..e32e4417 100644 --- a/CDPIUI/Views/Store/ItemViewPage.xaml.cs +++ b/CDPIUI/Views/Store/ItemViewPage.xaml.cs @@ -253,7 +253,7 @@ private void ShowErrorDialog() Content = string.Format(localizer.GetLocalizedString("ElementNotExistMessage"), _storeId, "ERR_STORE_ITEM_NOT_FOUND"), PrimaryButtonText = "OK" }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (Frame.CanGoBack) Frame.GoBack(); else @@ -534,7 +534,7 @@ private async void ItemWarningButton_Click(object sender, RoutedEventArgs e) PrimaryButtonText = "OK", XamlRoot = this.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } private async void ItemActionButton_Click(object sender, RoutedEventArgs e) @@ -567,7 +567,7 @@ private async void ErrorHelpButton_Click(object sender, RoutedEventArgs e) { XamlRoot = XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } private void DeleteButton_Click(object sender, RoutedEventArgs e) @@ -598,7 +598,7 @@ private async void ReinstallButton_Click(object sender, RoutedEventArgs e) CloseButtonText = localizer.GetLocalizedString("No"), Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style }; - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) { StoreHelper.Instance.RemoveItem(_storeId); InstallingItemActions(); @@ -615,7 +615,7 @@ private async Task AskLicense() Licenses = item.license, XamlRoot = this.XamlRoot }; - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) { return true; } diff --git a/CDPIUI/Views/Store/ReadyKitViewPage.xaml.cs b/CDPIUI/Views/Store/ReadyKitViewPage.xaml.cs index b6c0172c..4b43a826 100644 --- a/CDPIUI/Views/Store/ReadyKitViewPage.xaml.cs +++ b/CDPIUI/Views/Store/ReadyKitViewPage.xaml.cs @@ -237,7 +237,7 @@ private async void InstallButton_Click(object sender, RoutedEventArgs e) Licenses = licenses, XamlRoot = XamlRoot }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) return; } @@ -553,7 +553,7 @@ private async void ErrorHelpButton_Click(object sender, RoutedEventArgs e) { XamlRoot = XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); } private void LaunchKitUnsupportedHelp_Click(object sender, RoutedEventArgs e) @@ -621,7 +621,7 @@ private void ShowLoadErrorDialog() Content = $"{_loadErrorMessage} {_loadErrorCode}", PrimaryButtonText = "OK" }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (Frame.CanGoBack) Frame.GoBack(); diff --git a/CDPIUI/Views/Store/Settings/Memory/MemoryViewConditionalLaunchDetailsPage.xaml.cs b/CDPIUI/Views/Store/Settings/Memory/MemoryViewConditionalLaunchDetailsPage.xaml.cs index 2db03710..8068b3e2 100644 --- a/CDPIUI/Views/Store/Settings/Memory/MemoryViewConditionalLaunchDetailsPage.xaml.cs +++ b/CDPIUI/Views/Store/Settings/Memory/MemoryViewConditionalLaunchDetailsPage.xaml.cs @@ -101,7 +101,7 @@ private async void DeleteAllTasksButton_Click(object sender, RoutedEventArgs e) XamlRoot = XamlRoot }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) return; try diff --git a/CDPIUI/Views/Store/SettingsPage.xaml.cs b/CDPIUI/Views/Store/SettingsPage.xaml.cs index 21800295..bae29390 100644 --- a/CDPIUI/Views/Store/SettingsPage.xaml.cs +++ b/CDPIUI/Views/Store/SettingsPage.xaml.cs @@ -145,7 +145,7 @@ private async void ManualItemInstallation_Click(object sender, RoutedEventArgs e XamlRoot = this.XamlRoot }; - var result = await dialog.ShowAsync(); + var result = await dialog.ShowQueuedAsync(); if (result == ContentDialogResult.Secondary) { diff --git a/CDPIUI/Windows/BlockCheck2ResultWindow.xaml.cs b/CDPIUI/Windows/BlockCheck2ResultWindow.xaml.cs index 7a75274c..f854ad59 100644 --- a/CDPIUI/Windows/BlockCheck2ResultWindow.xaml.cs +++ b/CDPIUI/Windows/BlockCheck2ResultWindow.xaml.cs @@ -156,7 +156,7 @@ private async System.Threading.Tasks.Task ShowModeChoiceAsync() : ContentDialogButton.Secondary, IsPrimaryButtonEnabled = viewModel.CanUseConfig, }; - ContentDialogResult result = await dialog.ShowAsync(); + ContentDialogResult result = await dialog.ShowQueuedAsync(); if (result == ContentDialogResult.Primary) { OpenPresetReview(); diff --git a/CDPIUI/Windows/ConditionalLaunchWindow.xaml.cs b/CDPIUI/Windows/ConditionalLaunchWindow.xaml.cs index ebab2eef..095efdd1 100644 --- a/CDPIUI/Windows/ConditionalLaunchWindow.xaml.cs +++ b/CDPIUI/Windows/ConditionalLaunchWindow.xaml.cs @@ -432,7 +432,7 @@ private async void DeleteButton_Click(object sender, RoutedEventArgs e) XamlRoot = Content.XamlRoot }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) return; try diff --git a/CDPIUI/Windows/ConditionalTaskEditorWindow.xaml.cs b/CDPIUI/Windows/ConditionalTaskEditorWindow.xaml.cs index 7d3d50d2..7035778c 100644 --- a/CDPIUI/Windows/ConditionalTaskEditorWindow.xaml.cs +++ b/CDPIUI/Windows/ConditionalTaskEditorWindow.xaml.cs @@ -175,7 +175,7 @@ private async System.Threading.Tasks.Task EditSelectedTriggerAsync() { XamlRoot = Content.XamlRoot }; - return await dialog.ShowAsync() == ContentDialogResult.Primary + return await dialog.ShowQueuedAsync() == ContentDialogResult.Primary ? dialog.ResultTrigger : null; } @@ -265,7 +265,7 @@ private async System.Threading.Tasks.Task EditSelectedActionAsync() { XamlRoot = Content.XamlRoot }; - return await dialog.ShowAsync() == ContentDialogResult.Primary + return await dialog.ShowQueuedAsync() == ContentDialogResult.Primary ? dialog.ResultAction : null; } diff --git a/CDPIUI/Windows/ConfigMakerWindow.xaml.cs b/CDPIUI/Windows/ConfigMakerWindow.xaml.cs index 59846901..3334ee64 100644 --- a/CDPIUI/Windows/ConfigMakerWindow.xaml.cs +++ b/CDPIUI/Windows/ConfigMakerWindow.xaml.cs @@ -107,7 +107,7 @@ private async void RootGrid_Loaded(object sender, RoutedEventArgs e) Content = localizer.GetLocalizedString("ConfigMakerNoComponentsDialogMessage"), CloseButtonText = localizer.GetLocalizedString("Cancel"), }; - await unavailableDialog.ShowAsync(); + await unavailableDialog.ShowQueuedAsync(); Close(); return; } @@ -244,7 +244,7 @@ private async void EditConfigMenuItem_Click(object sender, RoutedEventArgs e) { XamlRoot = this.Content.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.SelectedConfigResult == SelectResult.Selected) { @@ -292,7 +292,7 @@ private async Task ShowAskExitDialog() XamlRoot = this.Content.XamlRoot, Style = (Style)Application.Current.Resources["DefaultContentDialogStyle"] }; - var result = await exitDialog.ShowAsync(); + var result = await exitDialog.ShowQueuedAsync(); if (result == ContentDialogResult.Primary) { return true; @@ -307,7 +307,7 @@ private async Task ShowWelcomeDialog() XamlRoot = this.Content.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (!string.IsNullOrEmpty(dialog.ResultSelectedComponentId)) { diff --git a/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs b/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs index 387d0c30..7f883607 100644 --- a/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs +++ b/CDPIUI/Windows/CreateConfigHelperWindow.xaml.cs @@ -117,7 +117,7 @@ private async void AskForExit(NavigatingCancelEventArgs e) XamlRoot = this.Content.XamlRoot, Style = (Style)Application.Current.Resources["DefaultContentDialogStyle"] }; - var result = await exitDialog.ShowAsync(); + var result = await exitDialog.ShowQueuedAsync(); if (result == ContentDialogResult.Primary) { ContentFrame.DispatcherQueue.TryEnqueue(() => @@ -218,7 +218,7 @@ public void OpenConfigEditPage(bool skp = false, ConfigItem configItem = null) { XamlRoot = this.Content.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.SelectedConfigResult == SelectResult.Selected) { configItem = dialog.SelectedConfigItem; @@ -270,7 +270,7 @@ private async void ImportConfigFromFileButton_Click(object sender, RoutedEventAr { if (!SettingsManager.Instance.GetValue("AD", "ImportConfigFromFile")) { ImportConfigFromFileDialog dialog = new ImportConfigFromFileDialog() { XamlRoot = this.Content.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); SettingsManager.Instance.SetValue("AD", "ImportConfigFromFile", true); } @@ -354,7 +354,7 @@ private async void RecentGoodCheckSelectionButton_Click(object sender, RoutedEve { XamlRoot = this.Content.XamlRoot }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (dialog.SelectedResult == SelectResult.Selected) { string directory = dialog.SelectedReport; @@ -510,7 +510,7 @@ private async void EditConfigKitButton_Click(object sender, RoutedEventArgs e) XamlRoot = this.Content.XamlRoot, }; - await dialog.ShowAsync(); + await dialog.ShowQueuedAsync(); if (!string.IsNullOrEmpty(dialog.Result)) { diff --git a/CDPIUI/Windows/CreateConfigUtilWindow.xaml.cs b/CDPIUI/Windows/CreateConfigUtilWindow.xaml.cs index fa609167..59c80377 100644 --- a/CDPIUI/Windows/CreateConfigUtilWindow.xaml.cs +++ b/CDPIUI/Windows/CreateConfigUtilWindow.xaml.cs @@ -107,7 +107,7 @@ private async void AskForExit() CloseButtonText = localizer.GetLocalizedString("No"), XamlRoot = this.Content.XamlRoot }; - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) { StopActiveSelection(); this.Close(); diff --git a/CDPIUI/Windows/Messages/StoreSmallDownloadDialog.xaml.cs b/CDPIUI/Windows/Messages/StoreSmallDownloadDialog.xaml.cs index 4bf9a32a..7df34de2 100644 --- a/CDPIUI/Windows/Messages/StoreSmallDownloadDialog.xaml.cs +++ b/CDPIUI/Windows/Messages/StoreSmallDownloadDialog.xaml.cs @@ -198,7 +198,7 @@ private async Task AskLicense() Licenses = item.license, XamlRoot = this.Content.XamlRoot }; - if (await dialog.ShowAsync() == ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) { return true; } diff --git a/CDPIUI/Windows/StoreWindow.xaml.cs b/CDPIUI/Windows/StoreWindow.xaml.cs index 5ea76f74..b42b60d3 100644 --- a/CDPIUI/Windows/StoreWindow.xaml.cs +++ b/CDPIUI/Windows/StoreWindow.xaml.cs @@ -90,7 +90,7 @@ private void Instance_ItemInstallingErrorHappens(Tuple obj) CloseButtonText = "OK", XamlRoot = this.Content.XamlRoot, }; - _ = dialog.ShowAsync(); + _ = dialog.ShowQueuedAsync(); */ } diff --git a/CDPIUI/Windows/WelcomeWindow.xaml.cs b/CDPIUI/Windows/WelcomeWindow.xaml.cs index c5ac81d9..25a27600 100644 --- a/CDPIUI/Windows/WelcomeWindow.xaml.cs +++ b/CDPIUI/Windows/WelcomeWindow.xaml.cs @@ -229,7 +229,7 @@ private async void DownloadItems() Licenses = licenses, XamlRoot = this.Content.XamlRoot }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) return; } @@ -437,7 +437,7 @@ await FailMigrationAsync( Licenses = licenses, XamlRoot = Content.XamlRoot }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) + if (await dialog.ShowQueuedAsync() != ContentDialogResult.Primary) { migrationFlowStarted = false; RetryMigrationButton.Visibility = Visibility.Visible; From 798bb3ba0f82cf4a7980c922f0ba71da83a56150 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:00:52 +0000 Subject: [PATCH 083/202] Restore the component after a preset test The preset test stopped the component when it finished, so a component that had been running with the user's preset stayed stopped, and the test window stopped it again after an error. RunAsync now stops the tested preset on every exit path and starts the component again with the user's preset if it was running before the test. --- CDPIUI/Helper/AddOns/PresetTestHelper.cs | 13 +++++++++++-- CDPIUI/Windows/ConfigTestWindow.xaml.cs | 2 +- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/CDPIUI/Helper/AddOns/PresetTestHelper.cs b/CDPIUI/Helper/AddOns/PresetTestHelper.cs index ac8295ae..68963ec7 100644 --- a/CDPIUI/Helper/AddOns/PresetTestHelper.cs +++ b/CDPIUI/Helper/AddOns/PresetTestHelper.cs @@ -364,6 +364,9 @@ public async Task RunAsync( Line(log, new TestLogSegment(new string('=', 60), TestLogColor.Gray)); Tagged(log, "PT_Warn", TestLogColor.Yellow, S("PT_MayTakeTime")); + // The test restarts the component with every preset; afterwards it runs again with the + // user's own preset if it was running before the test. + bool wasRunning = processManager.IsProcessRunning; try { int index = 0; @@ -431,8 +434,6 @@ public async Task RunAsync( { wasCancelled = true; CancelAllCurls(); - // Do not leave the component running with the preset that was being tested. - try { await processManager.StopProcess(false); } catch { } } finally { @@ -441,6 +442,14 @@ public async Task RunAsync( { try { File.Delete(payloadFile); } catch { } } + // Whatever ended the test, the component must not keep running with a tested preset. + try + { + await processManager.StopProcess(false); + if (wasRunning) + await processManager.StartProcess(); + } + catch { } } return BuildRunResult(results, testType, wasCancelled); diff --git a/CDPIUI/Windows/ConfigTestWindow.xaml.cs b/CDPIUI/Windows/ConfigTestWindow.xaml.cs index ab66c4da..216906df 100644 --- a/CDPIUI/Windows/ConfigTestWindow.xaml.cs +++ b/CDPIUI/Windows/ConfigTestWindow.xaml.cs @@ -203,9 +203,9 @@ private async void StartTestButton_Click(object sender, RoutedEventArgs e) } catch (Exception ex) { + // RunAsync has already stopped the tested preset and restored the component. AppendLine(new TestLogSegment($"[{localizer.GetLocalizedString("PT_Warn")}] ", TestLogColor.Yellow), new TestLogSegment(ex.Message, TestLogColor.Red)); - try { await processManager.StopProcess(false); } catch { } } finally { From cd397f2e70ea79bf3f0d98bf0cd97b6046efbba8 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:01:14 +0000 Subject: [PATCH 084/202] Make GoodCheck service notifications events GoodCheckProcessService exposed its notifications as public Action fields, so any subscriber could replace or invoke the handlers of all others. They are now events; every subscriber already used += and -=. --- .../GoodCheck/GoodCheckProcessService.cs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs b/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs index d4cfc264..f6ae6851 100644 --- a/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs +++ b/CDPIUI.AddOns/GoodCheck/GoodCheckProcessService.cs @@ -43,18 +43,18 @@ public enum GoodCheckOperationType } public class GoodCheckProcessService { - public Action AllComplete; - public Action ErrorHappens; - public Action ProcessCompleted; - public Action CurrentSiteListChanged; - public Action> ProgressChanged; - public Action> StrategyResultAdded; - public Action CorrectCountChanged; - public Action IncorrectCountChanged; - - public Action> OperationOutputAdded; - public Action> OperationTypeChanged; - public Action OperationsListChanged; + public event Action? AllComplete; + public event Action? ErrorHappens; + public event Action? ProcessCompleted; + public event Action? CurrentSiteListChanged; + public event Action>? ProgressChanged; + public event Action>? StrategyResultAdded; + public event Action? CorrectCountChanged; + public event Action? IncorrectCountChanged; + + public event Action>? OperationOutputAdded; + public event Action>? OperationTypeChanged; + public event Action? OperationsListChanged; public int CorrectCount { get; private set; } public int IncorrectCount { get; private set; } From fafed28c29a223be27f59c11ea178d9a582918f7 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:02:01 +0000 Subject: [PATCH 085/202] Fix the timestamps check and run troubleshooting tools without blocking The timestamps check passed '| findstr ...' to netsh as arguments, because there is no shell to build a pipe, so it always reported the wrong state; netsh output is also localized. The state is now read with Get-NetTCPSetting, which returns Enabled or Disabled in any language. netsh and PowerShell are started from System32 without a console window, their output is read concurrently, and they are awaited with a timeout instead of blocking the calling thread. --- .../Troubleshooting/TroubleshootingService.cs | 82 ++++++++++++------- 1 file changed, 54 insertions(+), 28 deletions(-) diff --git a/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs b/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs index 588e4ff8..67b054bd 100644 --- a/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs +++ b/CDPIUI.AddOns/Troubleshooting/TroubleshootingService.cs @@ -186,7 +186,7 @@ public async Task> RunBasicDiagnostic() bool isNetshExistInPATH = ExistsOnPath("netsh.exe"); CurrentStateChanged?.Invoke(RunBasicDialogStates.CheckTimestamps); - bool isTimestampsChecked = CheckTimestamps(); + bool isTimestampsChecked = await CheckTimestamps(); CurrentStateChanged?.Invoke(RunBasicDialogStates.CheckAdGuard); bool isAdGuardRunning = IsProcessRunning("adguardvpnsvc") || IsProcessRunning("adguardvpn") || IsProcessRunning("adguardsvc"); @@ -209,7 +209,7 @@ public async Task> RunBasicDiagnostic() bool isRunningVPN = IsServiceExist("vpn"); CurrentStateChanged?.Invoke(RunBasicDialogStates.CheckDNS); - bool isUsedDNS = GetDnsAdress(); + bool isUsedDNS = await GetDnsAdress(); CurrentStateChanged?.Invoke(RunBasicDialogStates.CheckWinDivert); bool isWinDivertRunning = IsServiceRunning("windivert"); @@ -272,7 +272,7 @@ public async Task TryToFixBasicError(RunBasicDialogStates state) switch (state) { case RunBasicDialogStates.CheckTimestamps: - fixResultModel.IsFixed = EnableTimestamps(); + fixResultModel.IsFixed = await EnableTimestamps(); fixResultModel.ErrorCode = fixResultModel.IsFixed ? string.Empty : "ERR_WIN32_UNKNOWN"; break; case RunBasicDialogStates.CheckWinDivert: @@ -386,17 +386,48 @@ private static bool ExistsOnPath(string fileName) return null; } - private bool EnableTimestamps() + private static readonly string PowerShellPath = + Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"); + + /// + /// Runs a system tool without a console window and without blocking the calling thread + /// + private static async Task<(int ExitCode, string Output)> RunToolAsync(string fileName, params string[] arguments) { + var startInfo = new ProcessStartInfo(fileName) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (string argument in arguments) + startInfo.ArgumentList.Add(argument); + + using var process = Process.Start(startInfo) ?? throw new InvalidOperationException($"Cannot start {fileName}"); + Task output = process.StandardOutput.ReadToEndAsync(); + Task errors = process.StandardError.ReadToEndAsync(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); try { - Process p = new Process(); - ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface tcp set global timestamps=enabled"); - p.StartInfo = psi; - p.Start(); - p.WaitForExit(); - // Debug.WriteLine(p.StandardOutput); - return p.ExitCode == 0; + await process.WaitForExitAsync(timeout.Token); + } + catch (OperationCanceledException) + { + try { process.Kill(); } catch { } + throw new System.TimeoutException($"{fileName} did not finish in time"); + } + await errors; + return (process.ExitCode, await output); + } + + private async Task EnableTimestamps() + { + try + { + var result = await RunToolAsync(Path.Combine(Environment.SystemDirectory, "netsh.exe"), + "interface", "tcp", "set", "global", "timestamps=enabled"); + return result.ExitCode == 0; } catch (Exception ex) { @@ -405,17 +436,16 @@ private bool EnableTimestamps() } } - private bool CheckTimestamps() + private async Task CheckTimestamps() { try { - Process p = new Process(); - ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface tcp show global | findstr /i \"timestamps\" | findstr /i \"enabled\""); - p.StartInfo = psi; - p.Start(); - p.WaitForExit(); - // Debug.WriteLine(p.StandardOutput); - return p.ExitCode == 0; + // netsh prints localized text and cannot pipe into findstr without a shell; + // Get-NetTCPSetting returns the state as Enabled or Disabled in any language. + var result = await RunToolAsync(PowerShellPath, "-NoProfile", "-NonInteractive", "-Command", + "(Get-NetTCPSetting -SettingName Internet).Timestamps"); + return result.ExitCode == 0 && + string.Equals(result.Output.Trim(), "Enabled", StringComparison.OrdinalIgnoreCase); } catch (Exception ex) { @@ -436,18 +466,14 @@ private static bool IsProcessRunning(string procName) return false; } - private static bool GetDnsAdress() + private static async Task GetDnsAdress() { try { - Process p = new Process(); - ProcessStartInfo psi = new ProcessStartInfo("powershell", "Get-ChildItem -Recurse -Path 'HKLM:System\\CurrentControlSet\\Services\\Dnscache\\InterfaceSpecificParameters\\' | Get-ItemProperty | Where-Object { $_.DohFlags -gt 0 } | Measure-Object | Select-Object -ExpandProperty Count"); - p.StartInfo = psi; - p.StartInfo.RedirectStandardOutput = true; - p.Start(); - p.WaitForExit(); - - return int.TryParse(p.StandardOutput.ReadToEnd(), out int result) && result != 0; + var result = await RunToolAsync(PowerShellPath, "-NoProfile", "-NonInteractive", "-Command", + "Get-ChildItem -Recurse -Path 'HKLM:System\\CurrentControlSet\\Services\\Dnscache\\InterfaceSpecificParameters\\' | Get-ItemProperty | Where-Object { $_.DohFlags -gt 0 } | Measure-Object | Select-Object -ExpandProperty Count"); + + return int.TryParse(result.Output.Trim(), out int count) && count != 0; } catch (Exception ex) { From d6d0cbeb45817639205ae1278928b6cd2dea147a Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:02:48 +0000 Subject: [PATCH 086/202] Unsubscribe pages from store and update events when they unload DownloadsPage removed two of its six store handlers, AboutPage, the troubleshooting work page, MainPage and ModernMainPage removed none, and the store download button kept its installation error handler. Pages that were closed kept updating, and every new instance added another handler. The pages now connect their handlers when loaded and disconnect them when unloaded, and the button removes all of its handlers. --- .../Store/StoreDownloadItemButton.xaml.cs | 1 + CDPIUI/Views/AboutPage.xaml.cs | 27 +++++++++++-- CDPIUI/Views/MainPage.xaml.cs | 22 +++++++++- CDPIUI/Views/ModernMainPage.xaml.cs | 24 ++++++++++- CDPIUI/Views/Store/DownloadsPage.xaml.cs | 40 ++++++++++++++----- CDPIUI/Views/Troubleshooting/WorkPage.xaml.cs | 19 +++++++++ 6 files changed, 118 insertions(+), 15 deletions(-) diff --git a/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs b/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs index cc9636cc..ccaac9e4 100644 --- a/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs +++ b/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs @@ -329,6 +329,7 @@ private void RemoveHandlers() StoreHelper.Instance.ItemTimeRemainingChanged -= StoreHelper_ItemTimeRemainingChanged; StoreHelper.Instance.ItemDownloadSpeedChanged -= StoreHelper_ItemDownloadSpeedChanged; StoreHelper.Instance.ItemActionsStopped -= StoreHelper_ItemActionsStopped; + StoreHelper.Instance.ItemInstallingErrorHappens -= StoreHelper_ItemInstallingErrorHappens; } private void StoreHelper_ItemInstallingErrorHappens(Tuple obj) diff --git a/CDPIUI/Views/AboutPage.xaml.cs b/CDPIUI/Views/AboutPage.xaml.cs index a44dad91..a4773704 100644 --- a/CDPIUI/Views/AboutPage.xaml.cs +++ b/CDPIUI/Views/AboutPage.xaml.cs @@ -100,9 +100,9 @@ public AboutPage() SetServerVersion(ApplicationUpdate.Instance.ServerVersion); } - ApplicationUpdate.Instance.ErrorHappens += ApplicationUpdateHelper_ErrorHappens; - ApplicationUpdate.Instance.CheckForUpdatesCompleted += ApplicationUpdateHelper_CheckForUpdatesCompleted; - ApplicationUpdate.Instance.CheckForUpdatesStarted += ApplicationUpdateHelper_CheckForUpdatesStarted; + ConnectEvents(); + Loaded += (_, _) => ConnectEvents(); + Unloaded += (_, _) => DisconnectEvents(); RepoRun.Text = UrlOpenHelper.MainRepoUrl; @@ -110,6 +110,27 @@ public AboutPage() RequirementsListView.ItemsSource = RequrementsList; } + // The services are singletons: a page that is not shown must not keep receiving their events. + private bool eventsConnected; + + private void ConnectEvents() + { + if (eventsConnected) return; + eventsConnected = true; + ApplicationUpdate.Instance.ErrorHappens += ApplicationUpdateHelper_ErrorHappens; + ApplicationUpdate.Instance.CheckForUpdatesCompleted += ApplicationUpdateHelper_CheckForUpdatesCompleted; + ApplicationUpdate.Instance.CheckForUpdatesStarted += ApplicationUpdateHelper_CheckForUpdatesStarted; + } + + private void DisconnectEvents() + { + if (!eventsConnected) return; + eventsConnected = false; + ApplicationUpdate.Instance.ErrorHappens -= ApplicationUpdateHelper_ErrorHappens; + ApplicationUpdate.Instance.CheckForUpdatesCompleted -= ApplicationUpdateHelper_CheckForUpdatesCompleted; + ApplicationUpdate.Instance.CheckForUpdatesStarted -= ApplicationUpdateHelper_CheckForUpdatesStarted; + } + protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); diff --git a/CDPIUI/Views/MainPage.xaml.cs b/CDPIUI/Views/MainPage.xaml.cs index 71ae92a6..1ef69a0d 100644 --- a/CDPIUI/Views/MainPage.xaml.cs +++ b/CDPIUI/Views/MainPage.xaml.cs @@ -43,10 +43,30 @@ public MainPage() LoadComponents(); ShowComponentSettingsClickCommand = new RelayCommand(p => ShowComponentSettings(p)); + ConnectEvents(); + Loaded += (_, _) => ConnectEvents(); + Unloaded += (_, _) => DisconnectEvents(); + + IsBackwardAnimationToPageAvailable = true; + } + + // The services are singletons: a page that is not shown must not keep receiving their events. + private bool eventsConnected; + + private void ConnectEvents() + { + if (eventsConnected) return; + eventsConnected = true; StoreHelper.Instance.ItemActionsStopped += Instance_ItemActionsStopped; StoreHelper.Instance.ItemRemoved += Instance_ItemRemoved; + } - IsBackwardAnimationToPageAvailable = true; + private void DisconnectEvents() + { + if (!eventsConnected) return; + eventsConnected = false; + StoreHelper.Instance.ItemActionsStopped -= Instance_ItemActionsStopped; + StoreHelper.Instance.ItemRemoved -= Instance_ItemRemoved; } private void Instance_ItemRemoved(string obj) diff --git a/CDPIUI/Views/ModernMainPage.xaml.cs b/CDPIUI/Views/ModernMainPage.xaml.cs index 29aebb6f..616ea06b 100644 --- a/CDPIUI/Views/ModernMainPage.xaml.cs +++ b/CDPIUI/Views/ModernMainPage.xaml.cs @@ -69,8 +69,9 @@ public ModernMainPage() InitializeComponent(); this.DataContext = this; - StoreHelper.Instance.ItemActionsStopped += Instance_ItemActionsStopped; - StoreHelper.Instance.ItemRemoved += Instance_ItemRemoved; + ConnectEvents(); + Loaded += (_, _) => ConnectEvents(); + Unloaded += (_, _) => DisconnectEvents(); this.Loaded += ModernMainPage_Loaded; @@ -86,6 +87,25 @@ public ModernMainPage() } } + // The services are singletons: a page that is not shown must not keep receiving their events. + private bool eventsConnected; + + private void ConnectEvents() + { + if (eventsConnected) return; + eventsConnected = true; + StoreHelper.Instance.ItemActionsStopped += Instance_ItemActionsStopped; + StoreHelper.Instance.ItemRemoved += Instance_ItemRemoved; + } + + private void DisconnectEvents() + { + if (!eventsConnected) return; + eventsConnected = false; + StoreHelper.Instance.ItemActionsStopped -= Instance_ItemActionsStopped; + StoreHelper.Instance.ItemRemoved -= Instance_ItemRemoved; + } + private void Instance_ItemRemoved(string obj) { CreateTiles(); diff --git a/CDPIUI/Views/Store/DownloadsPage.xaml.cs b/CDPIUI/Views/Store/DownloadsPage.xaml.cs index 2f460175..0fa61552 100644 --- a/CDPIUI/Views/Store/DownloadsPage.xaml.cs +++ b/CDPIUI/Views/Store/DownloadsPage.xaml.cs @@ -1,4 +1,4 @@ -using CDPIUI.Core.Store; +using CDPIUI.Core.Store; using CDPIUI.Core.Store.Queue; using CDPIUI.Core.Store.Repository.Localization; using CDPIUI.Helper.LScript; @@ -64,13 +64,10 @@ public DownloadsPage() UpdateCurrentDownloadsList(); UpdateCurrentDownloadItem(); - StoreHelper.Instance.QueueUpdated += UpdateCurrentDownloadsList; - StoreHelper.Instance.ErrorListUpdated += UpdateCurrentDownloadsList; - StoreHelper.Instance.NowProcessItemActions += StoreHelper_NowProcessItemActions; - StoreHelper.Instance.ItemActionsStopped += StoreHelper_ItemActionsStopped; + ConnectEvents(); + Loaded += (_, _) => ConnectEvents(); + Unloaded += (_, _) => DisconnectEvents(); - StoreHelper.Instance.UpdateCheckStarted += StoreHelper_UpdateCheckStarted; - StoreHelper.Instance.UpdateCheckStopped += StoreHelper_UpdateCheckStopped; ActionCommand = new RelayCommand(p => RemoveItem((DownloadItemModel)p)); UpdateCommand = new RelayCommand(p => UpdateElement((DownloadItemModel)p)); @@ -79,6 +76,33 @@ public DownloadsPage() ToggleUpdateMode(StoreHelper.Instance.IsNowUpdatesChecked); } + // The services are singletons: a page that is not shown must not keep receiving their events. + private bool eventsConnected; + + private void ConnectEvents() + { + if (eventsConnected) return; + eventsConnected = true; + StoreHelper.Instance.QueueUpdated += UpdateCurrentDownloadsList; + StoreHelper.Instance.ErrorListUpdated += UpdateCurrentDownloadsList; + StoreHelper.Instance.NowProcessItemActions += StoreHelper_NowProcessItemActions; + StoreHelper.Instance.ItemActionsStopped += StoreHelper_ItemActionsStopped; + StoreHelper.Instance.UpdateCheckStarted += StoreHelper_UpdateCheckStarted; + StoreHelper.Instance.UpdateCheckStopped += StoreHelper_UpdateCheckStopped; + } + + private void DisconnectEvents() + { + if (!eventsConnected) return; + eventsConnected = false; + StoreHelper.Instance.QueueUpdated -= UpdateCurrentDownloadsList; + StoreHelper.Instance.ErrorListUpdated -= UpdateCurrentDownloadsList; + StoreHelper.Instance.NowProcessItemActions -= StoreHelper_NowProcessItemActions; + StoreHelper.Instance.ItemActionsStopped -= StoreHelper_ItemActionsStopped; + StoreHelper.Instance.UpdateCheckStarted -= StoreHelper_UpdateCheckStarted; + StoreHelper.Instance.UpdateCheckStopped -= StoreHelper_UpdateCheckStopped; + } + protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); @@ -98,8 +122,6 @@ protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); - StoreHelper.Instance.QueueUpdated -= UpdateCurrentDownloadsList; - StoreHelper.Instance.ErrorListUpdated -= UpdateCurrentDownloadsList; } private void AuditSubHeaderVisible() diff --git a/CDPIUI/Views/Troubleshooting/WorkPage.xaml.cs b/CDPIUI/Views/Troubleshooting/WorkPage.xaml.cs index e9d03d09..b562ea5a 100644 --- a/CDPIUI/Views/Troubleshooting/WorkPage.xaml.cs +++ b/CDPIUI/Views/Troubleshooting/WorkPage.xaml.cs @@ -70,9 +70,28 @@ public WorkPage() DiagnosticResultListView.ItemsSource = DisplayDiagnosticResultsCollection; FixResultListView.ItemsSource = FixResults; + ConnectEvents(); + Loaded += (_, _) => ConnectEvents(); + Unloaded += (_, _) => DisconnectEvents(); + } + + // The services are singletons: a page that is not shown must not keep receiving their events. + private bool eventsConnected; + + private void ConnectEvents() + { + if (eventsConnected) return; + eventsConnected = true; TroubleshootingService.Instance.CurrentStateChanged += TroubleshootingHelper_BasicDialogStateChanged; } + private void DisconnectEvents() + { + if (!eventsConnected) return; + eventsConnected = false; + TroubleshootingService.Instance.CurrentStateChanged -= TroubleshootingHelper_BasicDialogStateChanged; + } + protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); From fbb6b3aadc8d891c2a0a149053f721edb8b20245 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:03:08 +0000 Subject: [PATCH 087/202] Fix two missing resource keys The remaining time used /UIHelper/TwoHour, but the resource is TwoHours, and the remove confirmation in the preset editor used a Remove key that did not exist, so both showed empty text. --- CDPIUI/Helper/Parsers/UnitsParser.cs | 2 +- CDPIUI/Strings/en-us/Resources.resw | 3 +++ CDPIUI/Strings/ru/Resources.resw | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CDPIUI/Helper/Parsers/UnitsParser.cs b/CDPIUI/Helper/Parsers/UnitsParser.cs index 2a13de81..8765ba0f 100644 --- a/CDPIUI/Helper/Parsers/UnitsParser.cs +++ b/CDPIUI/Helper/Parsers/UnitsParser.cs @@ -57,7 +57,7 @@ public static string ConvertMinutesToPrettyText(double min) if (hours < 1.5) return localizer.GetLocalizedString("/UIHelper/Hour"); else if (hours >= 1.5 && hours <= 2.5) - return localizer.GetLocalizedString("/UIHelper/TwoHour"); + return localizer.GetLocalizedString("/UIHelper/TwoHours"); else return localizer.GetLocalizedString("/UIHelper/MoreThanThreeHours"); } diff --git a/CDPIUI/Strings/en-us/Resources.resw b/CDPIUI/Strings/en-us/Resources.resw index dd635861..fc74ad40 100644 --- a/CDPIUI/Strings/en-us/Resources.resw +++ b/CDPIUI/Strings/en-us/Resources.resw @@ -6172,4 +6172,7 @@ By enabling this setting, you acknowledge that you have read this information. Arguments + + Remove + \ No newline at end of file diff --git a/CDPIUI/Strings/ru/Resources.resw b/CDPIUI/Strings/ru/Resources.resw index aaa9887d..f572b8f2 100644 --- a/CDPIUI/Strings/ru/Resources.resw +++ b/CDPIUI/Strings/ru/Resources.resw @@ -6175,4 +6175,7 @@ https://discord.com/app Аргументы + + Удалить + \ No newline at end of file From 1170436eb793ce9f858e51517d04687691ec691f Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:03:39 +0000 Subject: [PATCH 088/202] Use existing resource keys for two loading texts The GoodCheck progress page looked up Preparing in Resources, but the string is in Troubleshooting, and the utility buttons used WorkingOnItTextBlock, which exists only as a XAML property key; both showed empty text. --- CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs | 2 +- CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs b/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs index 028323ba..92b50461 100644 --- a/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs +++ b/CDPIUI/Controls/Universal/UtilityButtonControls.xaml.cs @@ -514,7 +514,7 @@ public string LoadingStateText public static readonly DependencyProperty LoadingStateTextProperty = DependencyProperty.Register( - nameof(LoadingStateText), typeof(string), typeof(UtilityButtonControls), new PropertyMetadata(localizer.GetLocalizedString("WorkingOnItTextBlock")) + nameof(LoadingStateText), typeof(string), typeof(UtilityButtonControls), new PropertyMetadata(localizer.GetLocalizedString("WorkingOnIt")) ); diff --git a/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs b/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs index e8b9ebfc..3da154cc 100644 --- a/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs +++ b/CDPIUI/Views/CreateConfigUtil/GoodCheckWorkPage.xaml.cs @@ -168,9 +168,9 @@ private void CurrentSiteListText(string text) return; } SiteListProgressText.Text = text; - SetSiteListProgressText(localizer.GetLocalizedString("Preparing")); - SetCorrectCountText(localizer.GetLocalizedString("Preparing")); - SetIncorrectCountText(localizer.GetLocalizedString("Preparing")); + SetSiteListProgressText(localizer.GetLocalizedString("/Troubleshooting/Preparing")); + SetCorrectCountText(localizer.GetLocalizedString("/Troubleshooting/Preparing")); + SetIncorrectCountText(localizer.GetLocalizedString("/Troubleshooting/Preparing")); } private void SetSiteListProgressText(string text) { From 1c7817ca4c1920cb566e9085320e880c6aad8405 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:04:18 +0000 Subject: [PATCH 089/202] Localize the critical error window and the GoodCheck DoH header The DoH resolvers header in GoodCheck settings was a Russian literal shown in every language, and the critical error window was English only. Both now use resource strings; the critical error window keeps its English text as a fallback in case the localizer itself failed, and its icon-only report button has an accessible name. --- .../en-us/GoodCheckAdditionalSettings.resw | 3 ++ CDPIUI/Strings/en-us/Resources.resw | 36 +++++++++++++++++++ .../ru/GoodCheckAdditionalSettings.resw | 3 ++ CDPIUI/Strings/ru/Resources.resw | 36 +++++++++++++++++++ .../CreateViaGoodCheckPage.xaml | 2 +- .../Service/CriticalErrorHandlerWindow.xaml | 23 ++++++------ .../CriticalErrorHandlerWindow.xaml.cs | 6 +++- 7 files changed, 96 insertions(+), 13 deletions(-) diff --git a/CDPIUI/Strings/en-us/GoodCheckAdditionalSettings.resw b/CDPIUI/Strings/en-us/GoodCheckAdditionalSettings.resw index ce248d6d..ab1dacd7 100644 --- a/CDPIUI/Strings/en-us/GoodCheckAdditionalSettings.resw +++ b/CDPIUI/Strings/en-us/GoodCheckAdditionalSettings.resw @@ -186,4 +186,7 @@ Requests + + DoH resolvers + \ No newline at end of file diff --git a/CDPIUI/Strings/en-us/Resources.resw b/CDPIUI/Strings/en-us/Resources.resw index fc74ad40..07b6b779 100644 --- a/CDPIUI/Strings/en-us/Resources.resw +++ b/CDPIUI/Strings/en-us/Resources.resw @@ -6175,4 +6175,40 @@ By enabling this setting, you acknowledge that you have read this information. Remove + + Something went wrong + + + Where: + + + Why: + + + Error code: + + + Additional information: + + + If this error persists, please contact app support and report the issue. + + + View log folder + + + Report problem + + + Report problem + + + Copy + + + Copied + + + Critical error + \ No newline at end of file diff --git a/CDPIUI/Strings/ru/GoodCheckAdditionalSettings.resw b/CDPIUI/Strings/ru/GoodCheckAdditionalSettings.resw index 47216bcc..6a1b8516 100644 --- a/CDPIUI/Strings/ru/GoodCheckAdditionalSettings.resw +++ b/CDPIUI/Strings/ru/GoodCheckAdditionalSettings.resw @@ -186,4 +186,7 @@ Запросы + + DoH резолверы + \ No newline at end of file diff --git a/CDPIUI/Strings/ru/Resources.resw b/CDPIUI/Strings/ru/Resources.resw index f572b8f2..528e59ee 100644 --- a/CDPIUI/Strings/ru/Resources.resw +++ b/CDPIUI/Strings/ru/Resources.resw @@ -6178,4 +6178,40 @@ https://discord.com/app Удалить + + Что-то пошло не так + + + Где: + + + Почему: + + + Код ошибки: + + + Дополнительные сведения: + + + Если ошибка повторяется, сообщите о ней в поддержку приложения. + + + Открыть папку журналов + + + Сообщить о проблеме + + + Сообщить о проблеме + + + Копировать + + + Скопировано + + + Критическая ошибка + \ No newline at end of file diff --git a/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml b/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml index d5e8c8fc..07afa7af 100644 --- a/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml +++ b/CDPIUI/Views/CreateConfigUtil/CreateViaGoodCheckPage.xaml @@ -265,7 +265,7 @@ - + diff --git a/CDPIUI/Windows/Service/CriticalErrorHandlerWindow.xaml b/CDPIUI/Windows/Service/CriticalErrorHandlerWindow.xaml index ae8f5e61..a8c042b7 100644 --- a/CDPIUI/Windows/Service/CriticalErrorHandlerWindow.xaml +++ b/CDPIUI/Windows/Service/CriticalErrorHandlerWindow.xaml @@ -11,7 +11,8 @@ Title="Error Handler" xmlns:animatedvisuals="using:Microsoft.UI.Xaml.Controls.AnimatedVisuals" xmlns:template="using:CDPIUI.Default" - xmlns:wc="using:CDPIUI.Controls.WindowControls"> + xmlns:wc="using:CDPIUI.Controls.WindowControls" + xmlns:l="using:WinUI3Localizer"> @@ -38,26 +39,26 @@ - + - + - + - + - + - - + + @@ -65,7 +66,7 @@ - diff --git a/CDPIUI/Controls/ComponentSettings/SettingTile.xaml b/CDPIUI/Controls/ComponentSettings/SettingTile.xaml index 09f13613..9fe114d9 100644 --- a/CDPIUI/Controls/ComponentSettings/SettingTile.xaml +++ b/CDPIUI/Controls/ComponentSettings/SettingTile.xaml @@ -40,11 +40,11 @@ - - diff --git a/CDPIUI/Controls/CreateConfigHelper/ConditionUserControl.xaml b/CDPIUI/Controls/CreateConfigHelper/ConditionUserControl.xaml index 6c9006ca..a629a7b0 100644 --- a/CDPIUI/Controls/CreateConfigHelper/ConditionUserControl.xaml +++ b/CDPIUI/Controls/CreateConfigHelper/ConditionUserControl.xaml @@ -42,7 +42,7 @@ - - - - @@ -271,7 +271,7 @@ - - - - - diff --git a/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml b/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml index 86a3925b..e2103c50 100644 --- a/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml +++ b/CDPIUI/Controls/CreateConfigHelper/VariableUserControl.xaml @@ -48,7 +48,7 @@ - @@ -84,7 +84,7 @@ - @@ -115,7 +115,7 @@ diff --git a/CDPIUI/Controls/Dialogs/ProxySetupUtil/SelectAppContentDialog.xaml b/CDPIUI/Controls/Dialogs/ProxySetupUtil/SelectAppContentDialog.xaml index cc32896f..a5e6a45d 100644 --- a/CDPIUI/Controls/Dialogs/ProxySetupUtil/SelectAppContentDialog.xaml +++ b/CDPIUI/Controls/Dialogs/ProxySetupUtil/SelectAppContentDialog.xaml @@ -70,7 +70,7 @@ - @@ -89,7 +89,7 @@ - diff --git a/CDPIUI/Controls/GoodCheck/GoodCheckSitelistStrategyChooserControl.xaml b/CDPIUI/Controls/GoodCheck/GoodCheckSitelistStrategyChooserControl.xaml index 02d0327f..ad46c732 100644 --- a/CDPIUI/Controls/GoodCheck/GoodCheckSitelistStrategyChooserControl.xaml +++ b/CDPIUI/Controls/GoodCheck/GoodCheckSitelistStrategyChooserControl.xaml @@ -24,7 +24,7 @@ - - - diff --git a/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml b/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml index b183f3b9..86bad726 100644 --- a/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml +++ b/CDPIUI/Controls/MainPage/SmallComponentTileUserControl.xaml @@ -143,7 +143,7 @@ - diff --git a/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml b/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml index 74732e96..4cc1d522 100644 --- a/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml +++ b/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml @@ -94,7 +94,7 @@ - - - - - - - - - - - - - - @@ -273,7 +273,7 @@ - /// Task Id public async void AddNewTask(string id) + { + await AddNewTaskAsync(id); + } + + /// + /// Add new task to task list + /// + /// Task Id + public async Task AddNewTaskAsync(string id) { var (_, created) = await GetOrAddTask(id); if (created) diff --git a/CDPIUI/Windows/Default/TemplateWindow.cs b/CDPIUI/Windows/Default/TemplateWindow.cs index ecad6a03..a84ffb47 100644 --- a/CDPIUI/Windows/Default/TemplateWindow.cs +++ b/CDPIUI/Windows/Default/TemplateWindow.cs @@ -408,8 +408,15 @@ struct RECT { public int left, top, right, bottom; } private void ApplyDarkThemeToSystemMenu() { - SetPreferredAppMode(2); - FlushMenuThemes(); + // Undocumented uxtheme exports: #135 is SetPreferredAppMode since Windows 10 1903 and + // AllowDarkModeForApp(BOOL) on 1809, where 2 also means "allow". Older systems lack them. + try + { + SetPreferredAppMode(2); + FlushMenuThemes(); + } + catch (EntryPointNotFoundException) { } + catch (DllNotFoundException) { } } [DllImport("uxtheme.dll", EntryPoint = "#135", SetLastError = true, CharSet = CharSet.Unicode)] diff --git a/CDPIUI/Windows/MainWindow.xaml.cs b/CDPIUI/Windows/MainWindow.xaml.cs index a1066d4b..7fea1cc7 100644 --- a/CDPIUI/Windows/MainWindow.xaml.cs +++ b/CDPIUI/Windows/MainWindow.xaml.cs @@ -345,8 +345,15 @@ private struct MINMAXINFO private void ApplyDarkThemeToSystemMenu() { - SetPreferredAppMode(2); - FlushMenuThemes(); + // Undocumented uxtheme exports: #135 is SetPreferredAppMode since Windows 10 1903 and + // AllowDarkModeForApp(BOOL) on 1809, where 2 also means "allow". Older systems lack them. + try + { + SetPreferredAppMode(2); + FlushMenuThemes(); + } + catch (EntryPointNotFoundException) { } + catch (DllNotFoundException) { } } [DllImport("uxtheme.dll", EntryPoint = "#135", SetLastError = true, CharSet = CharSet.Unicode)] From e901e713dc548a54d470150551d3600996bb63bb Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:21:24 +0000 Subject: [PATCH 101/202] Create windows only after the localizer is ready and fall back to a known language The localizer was built in an async void method started from the App constructor, and windows created before it finished showed no text; a language value without a matching Strings folder had the same effect (issue #8). SafeCreateNewWindow now waits for the localizer, failures are logged, and an unknown language falls back to the system language. --- CDPIUI/App.xaml.cs | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/CDPIUI/App.xaml.cs b/CDPIUI/App.xaml.cs index 354ddebb..a5cbddf7 100644 --- a/CDPIUI/App.xaml.cs +++ b/CDPIUI/App.xaml.cs @@ -492,12 +492,27 @@ private async Task ShowSettingsRecoveryWarningAsync() } - public async void GetReadyFeatures() + // Windows read their strings from the localizer, so they are created only after it is built. + private Task _localizerReady = Task.CompletedTask; + + public void GetReadyFeatures() { - DatabaseInitializationService.QuickRestore(); - await InitializeLocalizer(); - ApplicationInfo.Instance.SetLocalization(Localizer.Get().GetCurrentLanguage()); - FileAssociationService.EnsureRegistered(); + _localizerReady = GetReadyFeaturesAsync(); + } + + private async Task GetReadyFeaturesAsync() + { + try + { + DatabaseInitializationService.QuickRestore(); + await InitializeLocalizer(); + ApplicationInfo.Instance.SetLocalization(Localizer.Get().GetCurrentLanguage()); + FileAssociationService.EnsureRegistered(); + } + catch (Exception ex) + { + Logger.Instance.CreateErrorLog(nameof(App), $"Cannot prepare the application: {ex}"); + } } public bool CheckWindow() where TWindow : Window @@ -664,6 +679,8 @@ public async Task SafeCreateNewWindow(Type windowType, bool activate = t public async Task SafeCreateNewWindow(bool activate = true) where TWindow : Window, new() { + await _localizerReady; + var findWindows = OpenWindows.OfType().ToList(); int findWindowCount = findWindows.Count; @@ -999,7 +1016,10 @@ private async Task InitializeLocalizer() string lang = SettingsManager.Instance.GetValue("SYSTEM", "language"); var culture = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName; - if (lang == "NaN") + // An unknown or damaged value would leave every text empty (issue #8). + if (string.IsNullOrWhiteSpace(lang) || lang == "NaN" || + lang.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || + !Directory.Exists(Path.Combine(stringsFolderPath, lang))) { lang = culture switch { From 72c8cbaeea58cf4e608b8422272c7537a5d0dad0 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:22:56 +0000 Subject: [PATCH 102/202] Survive damaged pack, ProxiFyre and settings files A damaged init.json of one preset pack failed the preset list of every component, a damaged init.json of a local pack threw out of GetReadyLocalItem, and a damaged or empty app-config.json of ProxiFyre crashed its setup page. These files are now read with a fallback and the error is logged. GetValue threw SettingTypeNotSupported when a stored value had another type, for example after a manual edit, and no caller handled it. It now returns the default value (issue #61). --- .../Configuration/ConfigurationService.cs | 27 ++++++++++++++++-- CDPIUI.Core/Store/StoreHelper.cs | 14 +++++++++- CDPIUI.Shared/Basic/XMLSettingsService.cs | 10 ++++--- .../Shared/XmlSettingsServiceTests.cs | 10 +++++++ .../SetupProxy/ProxiFyreSetupPage.xaml.cs | 28 +++++++++++++------ 5 files changed, 73 insertions(+), 16 deletions(-) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs index b888b957..895a73a3 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigurationService.cs @@ -47,7 +47,19 @@ private List InitConfigDirectory(DatabaseStoreItem item) if (!File.Exists(initFile)) return configItems; - ConfigInitItem configInitItem = JSONConvertor.LoadJson(initFile); + // A damaged pack must not hide the presets of the other packs (issue #61). + ConfigInitItem? configInitItem; + try + { + configInitItem = JSONConvertor.LoadJson(initFile); + } + catch (Exception ex) + { + Logger.Instance.CreateErrorLog(nameof(ConfigurationService), $"Cannot read \"{initFile}\": {ex.Message}"); + return configItems; + } + if (configInitItem == null) + return configItems; string[] jsonFiles = Directory.GetFiles(directory, "*.json"); @@ -318,8 +330,17 @@ public static string GetDefaultLocalePath(string packId) if (!File.Exists(initFile)) return string.Empty; - ConfigInitItem configInitItem = JSONConvertor.LoadJson(initFile); - string _preFilepath = configInitItem.localized_strings_directory?.GetValueOrDefault("EN", null) ?? string.Empty; + ConfigInitItem? configInitItem; + try + { + configInitItem = JSONConvertor.LoadJson(initFile); + } + catch (Exception ex) + { + Logger.Instance.CreateErrorLog(nameof(ConfigurationService), $"Cannot read \"{initFile}\": {ex.Message}"); + return string.Empty; + } + string _preFilepath = configInitItem?.localized_strings_directory?.GetValueOrDefault("EN", null) ?? string.Empty; return string.IsNullOrEmpty(_preFilepath) ? string.Empty : Path.Combine(folder, _preFilepath); } diff --git a/CDPIUI.Core/Store/StoreHelper.cs b/CDPIUI.Core/Store/StoreHelper.cs index 7400d3bf..5754c6aa 100644 --- a/CDPIUI.Core/Store/StoreHelper.cs +++ b/CDPIUI.Core/Store/StoreHelper.cs @@ -527,7 +527,19 @@ private async Task>> D return OperationResultModel> .FailureResult(HandleException(PrettyErrorCode.PACK_NOT_SUPPORTED_TYPE)); - LocalItemInitModel localItemInitModel = JSONConvertor.LoadJson(initFilePath); + LocalItemInitModel? localItemInitModel; + try + { + localItemInitModel = JSONConvertor.LoadJson(initFilePath); + } + catch (Exception ex) + { + Logger.Instance.CreateErrorLog(nameof(StoreHelper), $"Cannot read \"{initFilePath}\": {ex.Message}"); + localItemInitModel = null; + } + if (localItemInitModel == null) + return OperationResultModel> + .FailureResult(HandleException(PrettyErrorCode.PACK_NOT_SUPPORTED_TYPE)); item = new() { diff --git a/CDPIUI.Shared/Basic/XMLSettingsService.cs b/CDPIUI.Shared/Basic/XMLSettingsService.cs index ec977df8..5a9aa5fe 100644 --- a/CDPIUI.Shared/Basic/XMLSettingsService.cs +++ b/CDPIUI.Shared/Basic/XMLSettingsService.cs @@ -293,7 +293,6 @@ private void SaveSettings(bool keepBackup = true) /// Custom if settings must be loaded from another file /// Throw if not found in file /// Value if key exsits, otherwise default - /// /// public T? GetValue(string group, string key, XElement? xElement = null, bool raiseExceptionIfNotExits = false) { @@ -325,7 +324,10 @@ private void SaveSettings(bool keepBackup = true) } catch { - throw new SettingTypeNotSupported($"Type mismatch or unsupported type for setting '{key}' in group '{group}'."); + // A value of another type, for example after a manual edit, must not crash + // the caller: hardly any of them expects an exception here (issue #61). + Debug.WriteLine($"Type mismatch or unsupported type for setting '{key}' in group '{group}'."); + return GetDefaultValueForKey(group, key); } } } @@ -339,7 +341,6 @@ private void SaveSettings(bool keepBackup = true) /// Custom if settings must be loaded from another file /// Throw if not found in file /// Value if key exsits, otherwise default - /// /// public T? GetValue(IEnumerable groupPath, string key, XElement? xElement = null, bool raiseExceptionIfNotExits = false) { @@ -385,7 +386,8 @@ private void SaveSettings(bool keepBackup = true) } catch { - throw new SettingTypeNotSupported($"Type mismatch or unsupported type for setting '{key}' in group path '{string.Join("/", groupPath)}'."); + Debug.WriteLine($"Type mismatch or unsupported type for setting '{key}' in group path '{string.Join("/", groupPath)}'."); + return GetDefaultValueForKey(groupPath, key); } } } diff --git a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs index 440d3046..566422ab 100644 --- a/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs +++ b/CDPIUI.Tests/Shared/XmlSettingsServiceTests.cs @@ -47,6 +47,16 @@ public void ReadsDoubleWrittenInCurrentCultureByOlderVersions() Assert.Equal(12.5, value); } + [Fact] + public void ValueOfAnotherTypeReturnsDefault() + { + new XMLSettingsService(SettingsPath).SetValue("SYSTEM", "someNumber", "not a number"); + + var settings = new XMLSettingsService(SettingsPath); + Assert.Equal(0, settings.GetValue("SYSTEM", "someNumber")); + Assert.Equal(0, settings.GetValue(["SYSTEM"], "someNumber")); + } + [Fact] public void DateTimeWithGroupPathIsReadable() { diff --git a/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs b/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs index 2eccfb97..450f1492 100644 --- a/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs +++ b/CDPIUI/Views/SetupProxy/ProxiFyreSetupPage.xaml.cs @@ -182,14 +182,11 @@ private void GetSettings() string readyToCompareIpAddr = GetProxyIpString( SettingsManager.Instance.GetValue("PROXY", "IPAddress"), SettingsManager.Instance.GetValue("PROXY", "port")); - ProxiFyreSettings settings = JSONConvertor.LoadJson(settingsFile); - ProxiFyreProxyGroup proxyGroup = settings.proxies.FirstOrDefault(x => x.socks5ProxyEndpoint == readyToCompareIpAddr); - if (proxyGroup is null && settings.proxies.Count > 0) - { - proxyGroup = settings.proxies.First(); - } + ProxiFyreSettings? settings = TryLoadSettings(settingsFile); + ProxiFyreProxyGroup? proxyGroup = settings?.proxies?.FirstOrDefault(x => x.socks5ProxyEndpoint == readyToCompareIpAddr) + ?? settings?.proxies?.FirstOrDefault(); - foreach (string app in proxyGroup.appNames) + foreach (string app in proxyGroup?.appNames ?? []) { WhiteList.Add(new() { @@ -227,6 +224,19 @@ private void GetSettings() SetDescription(); } + private static ProxiFyreSettings? TryLoadSettings(string settingsFile) + { + try + { + return JSONConvertor.LoadJson(settingsFile); + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(ProxiFyreSetupPage), $"Cannot read \"{settingsFile}\": {ex.Message}"); + return null; + } + } + private bool SaveSettings() { string dir = Path.Combine(Directories.StoreItemsDirectory, AddOnId); @@ -243,8 +253,10 @@ private bool SaveSettings() } else { - settings = JSONConvertor.LoadJson(settingsFile); + // A damaged app-config.json is replaced instead of failing the setup. + settings = TryLoadSettings(settingsFile) ?? new(); } + settings.proxies ??= []; string readyToCompareIpAddr = GetProxyIpString(IPValue.Text, PortValue.Text); From 20b360bd27eb92a0f0394e1ffc672d52f36384a5 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:23:45 +0000 Subject: [PATCH 103/202] Install the PKCS library with the MSI and keep the file list in sync The new installer file check found that System.Security.Cryptography.Pkcs.dll, needed by the catalog check, was published but not installed by the MSI, and that four listed libraries are no longer part of the build. The GUI also published Windows App SDK .mui files for some 90 languages; it is limited to English and Russian, the languages the application has and the MSI installs. --- CDPIUI/CDPIUI.csproj | 2 ++ NewSetup/NewSetupFiles.wxs | 15 +++------------ 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/CDPIUI/CDPIUI.csproj b/CDPIUI/CDPIUI.csproj index 10b6dac9..fe39c3dc 100644 --- a/CDPIUI/CDPIUI.csproj +++ b/CDPIUI/CDPIUI.csproj @@ -19,6 +19,8 @@ true en-US;ru-RU + + en-US;ru-RU embedded CDPIUI $(DefineConstants);DISABLE_XAML_GENERATED_MAIN diff --git a/NewSetup/NewSetupFiles.wxs b/NewSetup/NewSetupFiles.wxs index ea1bf305..a7c74e5e 100644 --- a/NewSetup/NewSetupFiles.wxs +++ b/NewSetup/NewSetupFiles.wxs @@ -227,9 +227,6 @@ - - - @@ -239,12 +236,6 @@ - - - - - - @@ -489,9 +480,6 @@ - - - @@ -927,6 +915,9 @@ + + + From 1cd5e23c823896d63c56a23fda9a0c80bde9d8c8 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:24:50 +0000 Subject: [PATCH 104/202] Stop a component before its files are replaced or deleted Updating or removing a running component failed with files in use, and the error was swallowed (issue #37). The installer now stops a running component and the driver service before it writes the new files and starts the component again afterwards; removal stops it first, retries the delete a few times and logs a failure. Reinstall waits until the old files are gone before queueing the installation. --- CDPIUI.Core/Store/StoreHelper.cs | 75 ++++++++++++++++--- .../Store/StoreLibraryItemButton.xaml.cs | 5 +- CDPIUI/Views/Store/ItemViewPage.xaml.cs | 3 +- 3 files changed, 68 insertions(+), 15 deletions(-) diff --git a/CDPIUI.Core/Store/StoreHelper.cs b/CDPIUI.Core/Store/StoreHelper.cs index 5754c6aa..e58e0cb0 100644 --- a/CDPIUI.Core/Store/StoreHelper.cs +++ b/CDPIUI.Core/Store/StoreHelper.cs @@ -265,8 +265,11 @@ private async Task ProcessAsync(QueueItemModel qi) public void RemoveItem(string itemId) { - _ = ProcessService.StopService(); - _ = ComponentTasksManager.Instance.StopTask(itemId); + _ = RemoveItemAsync(itemId); + } + + public async Task RemoveItemAsync(string itemId) + { var item = DatabaseHelper.Instance.GetItemById(itemId); if (item == null || @@ -274,21 +277,59 @@ public void RemoveItem(string itemId) item.Id == SharedConstants.LocalUserItemsId) return; - try + // The component has to exit before its files can be deleted (issue #37). + await StopComponentForFileChanges(item); + + // The directory comes from the item database; never delete anything outside the item folders. + if (Path.Exists(item.Directory) && StoreItemIds.IsItemFolder(item.Directory)) { - // The directory comes from the item database; never delete anything outside the item folders. - if (Path.Exists(item.Directory) && StoreItemIds.IsItemFolder(item.Directory)) + for (int attempt = 1; ; attempt++) { - Directory.Delete(item.Directory, recursive: true); + try + { + Directory.Delete(item.Directory, recursive: true); + break; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + if (attempt == 5) + { + Logger.Instance.CreateErrorLog(nameof(StoreHelper), $"Cannot delete \"{item.Directory}\": {ex.Message}"); + break; + } + await Task.Delay(500 * attempt); + } } - } - catch { } DatabaseHelper.Instance.DeleteItemById(itemId); ItemRemoved?.Invoke(itemId); } + /// + /// Stops the component before its files are replaced or deleted, together with the + /// driver service it may hold open. Returns whether the component was running. + /// + private static async Task StopComponentForFileChanges(DatabaseStoreItem item) + { + if (item.Type != "component") + return false; + + bool wasRunning = false; + try + { + var task = await ComponentTasksManager.Instance.GetTaskFromId(item.Id!); + wasRunning = task?.ProcessManager?.IsProcessRunning ?? false; + await ComponentTasksManager.Instance.StopTask(item.Id!); + await ProcessService.StopService(); + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(StoreHelper), $"Cannot stop {item.Id}: {ex.Message}"); + } + return wasRunning; + } + public async Task CheckUpdates() { if (IsNowUpdatesChecked) return; @@ -379,9 +420,12 @@ private async Task InstallItem(QueueItemModel qi) try { - RemoveItem(qi.ItemId); + await RemoveItemAsync(qi.ItemId); + } + catch (Exception ex) + { + Logger.Instance.CreateWarningLog(nameof(StoreHelper), $"Cannot clean up {qi.ItemId} after a failed installation: {ex.Message}"); } - catch { } } } @@ -398,9 +442,13 @@ private async Task> InstallItemWorker(QueueIte .FailureResult(ErrorModel.OnlyErrorCode(HandleException(new InvalidDataException($"Invalid store item id: {id}")))); List> requiredItems = []; + bool restartAfterUpdate = false; if (DatabaseHelper.Instance.IsItemInstalled(id)) { - requiredItems = DatabaseHelper.Instance.GetItemById(id).RequiredItemIds; + DatabaseStoreItem installedItem = DatabaseHelper.Instance.GetItemById(id); + requiredItems = installedItem.RequiredItemIds; + // Running executables cannot be overwritten (issue #37). + restartAfterUpdate = await StopComponentForFileChanges(installedItem); } string itemFolder = Path.Combine(Directories.StoreItemsDirectory, qi.ItemId); @@ -458,7 +506,10 @@ private async Task> InstallItemWorker(QueueIte return gettingPatchReadyResult; } - return await AddItemToDatabase(tag, downloadUrl, itemFolder, item, requiredItems); + var addResult = await AddItemToDatabase(tag, downloadUrl, itemFolder, item, requiredItems); + if (restartAfterUpdate) + await ComponentTasksManager.Instance.CreateAndRunNewTask(id); + return addResult; } private async Task>> DownloadItemOnline(string itemId, QueueItemModel qi) diff --git a/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml.cs b/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml.cs index 6ba7b2fa..b12dfbe6 100644 --- a/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml.cs +++ b/CDPIUI/Controls/Store/StoreLibraryItemButton.xaml.cs @@ -167,12 +167,13 @@ private async void ActionButton_Click(object sender, RoutedEventArgs e) } } - private void ReinstallButton_Click(object sender, RoutedEventArgs e) + private async void ReinstallButton_Click(object sender, RoutedEventArgs e) { - StoreHelper.Instance.RemoveItem(StoreId); DeleteButton.IsEnabled = false; ReinstallButton.IsEnabled = false; ProgressBar.Visibility = Visibility.Visible; + // The old files must be gone before the new ones are written. + await StoreHelper.Instance.RemoveItemAsync(StoreId); StoreHelper.Instance.AddItemToQueue(StoreId, string.Empty); } diff --git a/CDPIUI/Views/Store/ItemViewPage.xaml.cs b/CDPIUI/Views/Store/ItemViewPage.xaml.cs index e32e4417..2bb77e26 100644 --- a/CDPIUI/Views/Store/ItemViewPage.xaml.cs +++ b/CDPIUI/Views/Store/ItemViewPage.xaml.cs @@ -600,7 +600,8 @@ private async void ReinstallButton_Click(object sender, RoutedEventArgs e) }; if (await dialog.ShowQueuedAsync() == ContentDialogResult.Primary) { - StoreHelper.Instance.RemoveItem(_storeId); + // The old files must be gone before the new ones are written. + await StoreHelper.Instance.RemoveItemAsync(_storeId); InstallingItemActions(); } } From f31bb22c97b675610771fd5f7e88a9078b60b0b8 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:25:13 +0000 Subject: [PATCH 105/202] Stop writing the unknown apply_config command into preset packs The preset pack builder set after_install_actions to $RUNSCRIPT(apply_config, ...), a command LScript does not have, so every installation of such a pack logged "Unknown script command" (issue #10). New packs get no action, and the command in existing packs is accepted as a no-op. --- .../Helpers/Configuration/ConfigPackMakeHelper.cs | 3 ++- CDPIUI.Core/LScript/LScriptCore.cs | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs index 66bd22e8..fbd4991c 100644 --- a/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs +++ b/CDPIUI.Core/ComponentServices/Helpers/Configuration/ConfigPackMakeHelper.cs @@ -188,7 +188,8 @@ private static ConfigPackInitModel FillInitModel( modelTemplate.Name ??= modelTemplate.ShortName; modelTemplate.BeforeInstallActions ??= string.Empty; - modelTemplate.AfterInstallActions ??= $"$RUNSCRIPT(apply_config, {modelTemplate.StoreId})"; + // Nothing to run: the preset lists are reloaded after every installation. + modelTemplate.AfterInstallActions ??= string.Empty; modelTemplate.Type = "configlist"; diff --git a/CDPIUI.Core/LScript/LScriptCore.cs b/CDPIUI.Core/LScript/LScriptCore.cs index 69af9738..98796a7f 100644 --- a/CDPIUI.Core/LScript/LScriptCore.cs +++ b/CDPIUI.Core/LScript/LScriptCore.cs @@ -345,6 +345,10 @@ public static string LocalCondition(string condition, Dictionary? case "finish_component_setup": await FinishComponentSetup(scriptArgs); break; + case "apply_config": + // Written by older preset pack builders. The preset lists are reloaded + // after every installation, so there is nothing left to do. + break; case "download_easy_designer_annotation_file": if (scriptArgs.Length < 1) break; From 1b0fbe17feac4bcb44df074818563b696f50b2fa Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:25:44 +0000 Subject: [PATCH 106/202] Wait for the network before restarting components after resume Components were restarted as soon as Windows reported resume, usually before the network adapters were back, so they bound to no interface and the connection stayed broken (issue #7). The tray now waits up to 30 seconds for a network first. --- CDPIUI.TrayIcon/Forms/EmptyForm.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CDPIUI.TrayIcon/Forms/EmptyForm.cs b/CDPIUI.TrayIcon/Forms/EmptyForm.cs index 4be8dd42..20f296a3 100644 --- a/CDPIUI.TrayIcon/Forms/EmptyForm.cs +++ b/CDPIUI.TrayIcon/Forms/EmptyForm.cs @@ -102,6 +102,9 @@ private async void OnPowerChange(object s, PowerModeChangedEventArgs e) switch (e.Mode) { case PowerModes.Resume: + // Network adapters come back some seconds after resume; components started + // before that bind to no interface and the connection stays broken (issue #7). + await WaitForNetworkAsync(TimeSpan.FromSeconds(30)); foreach (var task in await TasksHelper.Instance.GetTasksSnapshot()) { if (!task.ProcessManager.IsProcessRunning) @@ -122,6 +125,21 @@ private async void OnPowerChange(object s, PowerModeChangedEventArgs e) } } + private static async Task WaitForNetworkAsync(TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + try + { + if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) + return; + } + catch (System.Net.NetworkInformation.NetworkInformationException) { return; } + await Task.Delay(1000); + } + } + private string GetCurrentIcon() { int rt = 0; From e5f4fa688f620e51e55cc7cd677adac2d6aae32e Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:26:18 +0000 Subject: [PATCH 107/202] Keep the Store cache until a new one is extracted and fall back to GitLab The Store cache was deleted before the new archive was extracted, so a damaged download left the Store empty, and a blocked GitHub failed the sync although the GitLab mirror has the same content (issue #26). The archive is now extracted into a separate folder that replaces the cache only when complete, temporary files are removed on failure, and a failed GitHub download is retried from GitLab. --- .../Repository/RepositoryLoaderService.cs | 109 ++++++++++++------ 1 file changed, 71 insertions(+), 38 deletions(-) diff --git a/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs b/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs index d24f0f15..c711b1d0 100644 --- a/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs +++ b/CDPIUI.Core/Store/Repository/RepositoryLoaderService.cs @@ -94,46 +94,16 @@ public async Task LoadAllStoreDatabase(bool forseSync, SupportedVersionCon if ((forseSync && t.TotalDays >= 1) || !Path.Exists(targetFolder)) { - string zipUrl = GetStoreUrl(usedVersionControl); - - Debug.WriteLine(zipUrl); - // A fixed name in the shared temp folder could be prepared by another process. - string tempZipPath = Path.Combine(Path.GetTempPath(), $"cdpiui_store_{Guid.NewGuid():N}.tmp"); - using var requestWorker = new RequestWorker(); - await requestWorker.DownloadFileAsync(zipUrl, tempZipPath, - token: usedVersionControl == SupportedVersionControls.GitHub ? GitHubApiToken : GitLabApiToken, - useStoreUserAgent: true, - completionOption: HttpCompletionOption.ResponseContentRead); - - if (Directory.Exists(targetFolder)) - Directory.Delete(targetFolder, recursive: true); - Directory.CreateDirectory(targetFolder); - - using (var archive = ZipFile.OpenRead(tempZipPath)) + try { - foreach (var entry in archive.Entries) - { - if (string.IsNullOrEmpty(entry.Name) && entry.FullName.EndsWith("/")) - continue; - - var parts = entry.FullName.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length <= 1) - continue; - - string[] subParts = parts.Skip(1).ToArray(); - string relativePath = Path.Combine(subParts); - - string destinationPath = ArchivePaths.GetDestinationOrThrow(targetFolder, relativePath); - - string destDir = Path.GetDirectoryName(destinationPath); - if (!string.IsNullOrEmpty(destDir)) - Directory.CreateDirectory(destDir); - - entry.ExtractToFile(destinationPath, overwrite: true); - } + await DownloadAndExtractStore(usedVersionControl, targetFolder); + } + catch (Exception ex) when (usedVersionControl == SupportedVersionControls.GitHub) + { + // GitHub is blocked for some users: the GitLab mirror has the same content (issue #26). + Logger.Instance.CreateWarningLog(nameof(RepositoryLoaderService), $"GitHub is not available, using GitLab: {ex.Message}"); + await DownloadAndExtractStore(SupportedVersionControls.GitLab, targetFolder); } - - File.Delete(tempZipPath); SettingsManager.Instance.SetValue("STORE", "lastSyncTime", DateTime.UtcNow); } @@ -155,6 +125,69 @@ await requestWorker.DownloadFileAsync(zipUrl, tempZipPath, return false; } + /// + /// Downloads the Store repository and replaces the cache only after the archive was + /// extracted completely, so a failed download or a damaged archive keeps the old cache. + /// + private async Task DownloadAndExtractStore(SupportedVersionControls versionControl, string targetFolder) + { + string zipUrl = GetStoreUrl(versionControl); + Debug.WriteLine(zipUrl); + + // A fixed name in the shared temp folder could be prepared by another process. + string tempZipPath = Path.Combine(Path.GetTempPath(), $"cdpiui_store_{Guid.NewGuid():N}.tmp"); + string newFolder = $"{targetFolder.TrimEnd(Path.DirectorySeparatorChar)}.new-{Guid.NewGuid():N}"; + try + { + using (var requestWorker = new RequestWorker()) + { + await requestWorker.DownloadFileAsync(zipUrl, tempZipPath, + token: versionControl == SupportedVersionControls.GitHub ? GitHubApiToken : GitLabApiToken, + useStoreUserAgent: true, + completionOption: HttpCompletionOption.ResponseContentRead); + } + + Directory.CreateDirectory(newFolder); + using (var archive = ZipFile.OpenRead(tempZipPath)) + { + foreach (var entry in archive.Entries) + { + if (string.IsNullOrEmpty(entry.Name) && entry.FullName.EndsWith("/")) + continue; + + var parts = entry.FullName.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length <= 1) + continue; + + string[] subParts = parts.Skip(1).ToArray(); + string relativePath = Path.Combine(subParts); + + string destinationPath = ArchivePaths.GetDestinationOrThrow(newFolder, relativePath); + + string? destDir = Path.GetDirectoryName(destinationPath); + if (!string.IsNullOrEmpty(destDir)) + Directory.CreateDirectory(destDir); + + entry.ExtractToFile(destinationPath, overwrite: true); + } + } + + if (Directory.Exists(targetFolder)) + Directory.Delete(targetFolder, recursive: true); + Directory.Move(newFolder, targetFolder); + } + finally + { + try { File.Delete(tempZipPath); } catch (IOException) { } + try + { + if (Directory.Exists(newFolder)) + Directory.Delete(newFolder, recursive: true); + } + catch (IOException) { } + } + } + public RepoItemModel? GetItemInfoFromStoreId(string? storeId) { if (storeId == SharedConstants.LocalUserItemsId) From ab56f0b8c09beae0e260be7a4c462b1eac396346 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:27:21 +0000 Subject: [PATCH 108/202] Accept only public routes in cdpiui:// links from outside the application A cdpiui:// link whose host matched no route was parsed as an internal pipe message, so any web page could mark a running GoodCheck as dead, forge tray responses or open windows by type name; window names were looked up in every loaded assembly and instantiated before the type was checked. Links from activations and help pages now map only to the public routes, and window names resolve only to window types of the application. --- .github/workflows/ci.yml | 4 ++++ CDPIUI/Commands/CommandUriMapper.cs | 10 ++++++++-- CDPIUI/Commands/CommandsHandler.cs | 9 ++++++++- CDPIUI/Helper/WindowHelper/WindowOpenHelper.cs | 13 +++++++------ CDPIUI/Windows/OfflineHelpWindow.xaml.cs | 3 ++- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b71b4e1e..d098753a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,10 @@ on: permissions: contents: read +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: libraries: runs-on: windows-latest diff --git a/CDPIUI/Commands/CommandUriMapper.cs b/CDPIUI/Commands/CommandUriMapper.cs index a09e17ea..650bdaf0 100644 --- a/CDPIUI/Commands/CommandUriMapper.cs +++ b/CDPIUI/Commands/CommandUriMapper.cs @@ -256,7 +256,13 @@ internal static class CommandUriMapper }) ]; - public static IPipeMessage? ConvertBack(string commandUri) + /// + /// Converts a cdpiui:// link to a command. Links from outside the application (browser, + /// other programs, help pages) may only use ; the internal pipe message + /// form is accepted only with , for links built by the + /// application itself. Otherwise any web page could forge tray responses (audit 9.1). + /// + public static IPipeMessage? ConvertBack(string commandUri, bool allowPipeMessages = false) { if (!Uri.TryCreate(commandUri, UriKind.Absolute, out var uri) || !uri.Scheme.Equals(SharedConstants.Schema, StringComparison.OrdinalIgnoreCase)) @@ -273,7 +279,7 @@ internal static class CommandUriMapper return route.CreateCommand(parameters); } - if (routesForHost.Any()) + if (routesForHost.Any() || !allowPipeMessages) return null; try diff --git a/CDPIUI/Commands/CommandsHandler.cs b/CDPIUI/Commands/CommandsHandler.cs index 90dcb173..bdfa0ddc 100644 --- a/CDPIUI/Commands/CommandsHandler.cs +++ b/CDPIUI/Commands/CommandsHandler.cs @@ -46,9 +46,12 @@ private void ExecuteCommand(object parameter) #endregion + /// + /// Handles a link built by the application itself; it may be an internal pipe message. + /// public static bool HandleCommand(string commandUri) { - var message = CommandUriMapper.ConvertBack(commandUri); + var message = CommandUriMapper.ConvertBack(commandUri, allowPipeMessages: true); return message != null && HandleCommand(message); } @@ -61,6 +64,10 @@ public static bool HandleCommand(IPipeMessage message) return true; } + /// + /// Handles a link that comes from outside the application, such as a cdpiui:// activation: + /// only the public routes are accepted. + /// public static async Task HandleCommandAsync(string commandUri) { var message = CommandUriMapper.ConvertBack(commandUri); diff --git a/CDPIUI/Helper/WindowHelper/WindowOpenHelper.cs b/CDPIUI/Helper/WindowHelper/WindowOpenHelper.cs index 8574160c..9cb1f428 100644 --- a/CDPIUI/Helper/WindowHelper/WindowOpenHelper.cs +++ b/CDPIUI/Helper/WindowHelper/WindowOpenHelper.cs @@ -86,12 +86,13 @@ public static async Task OpenAsync(NameValueCollection parameters) private static Type GetWindowType(string windowName) { - var fullName = $"CDPIUI.{windowName}"; - - return AppDomain.CurrentDomain.GetAssemblies() - .Select(a => a.GetType(fullName, false)) - .FirstOrDefault(t => t != null) - ?? null; + // Only windows of this application: the name can come from a cdpiui:// link, and any + // other type found by name would be instantiated before the cast. + var type = typeof(App).Assembly.GetType($"CDPIUI.{windowName}", false); + return type != null && typeof(Window).IsAssignableFrom(type) && !type.IsAbstract && + type.GetConstructor(Type.EmptyTypes) != null + ? type + : null; } private static Type GetPageType(string windowName, string pageName) diff --git a/CDPIUI/Windows/OfflineHelpWindow.xaml.cs b/CDPIUI/Windows/OfflineHelpWindow.xaml.cs index f24b4909..8a55eeb5 100644 --- a/CDPIUI/Windows/OfflineHelpWindow.xaml.cs +++ b/CDPIUI/Windows/OfflineHelpWindow.xaml.cs @@ -228,7 +228,8 @@ private void MarkdownTextBlock_OnLinkClicked(object sender, LinkClickedEventArgs if (url.StartsWith("cdpiui://", StringComparison.OrdinalIgnoreCase)) { - Commands.CommandsHandler.HandleCommand(url); + // Help pages are documents: their links get the same routes as links from a browser. + _ = Commands.CommandsHandler.HandleCommandAsync(url); } return; } From 5dc48d38ed687038d6ce3b001aa1e39af5b12cb7 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:27:51 +0000 Subject: [PATCH 109/202] Do not leave a second instance hanging when the activation redirect fails The second instance waited without a timeout for the activation redirect, and an exception in RedirectActivationToAsync, for example while the main instance was exiting, skipped SetEvent, so every double click on a pack or cdpiui:// link could leave an invisible process. The event is now always set, the wait is bounded, and an instance whose redirect failed tries to become the main instance. --- CDPIUI/Program.cs | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/CDPIUI/Program.cs b/CDPIUI/Program.cs index 81da8b8b..d34e8316 100644 --- a/CDPIUI/Program.cs +++ b/CDPIUI/Program.cs @@ -70,8 +70,22 @@ private static bool DecideRedirection() } else { - isRedirect = true; - RedirectActivationTo(args, keyInstance); + isRedirect = RedirectActivationTo(args, keyInstance); + if (!isRedirect) + { + // The main instance did not take the activation, usually because it is + // exiting: try to become the main instance instead of leaving silently. + keyInstance = AppInstance.FindOrRegisterForKey("CDPI_GUIApp"); + if (keyInstance.IsCurrent) + { + InitialActivationArguments = args; + keyInstance.Activated += OnActivated; + } + else + { + isRedirect = true; + } + } } return isRedirect; @@ -171,23 +185,38 @@ private static extern uint CoWaitForMultipleObjects( // Do the redirection on another thread, and use a non-blocking // wait method to wait for the redirection to complete. - public static void RedirectActivationTo(AppActivationArguments args, + // Returns false when the main instance did not accept the activation in time. + public static bool RedirectActivationTo(AppActivationArguments args, AppInstance keyInstance) { redirectEventHandle = CreateEvent(IntPtr.Zero, true, false, null); AllowSetForegroundWindow(keyInstance.ProcessId); + bool redirected = false; Task.Run(() => { - keyInstance.RedirectActivationToAsync(args).AsTask().Wait(); - SetEvent(redirectEventHandle); + try + { + keyInstance.RedirectActivationToAsync(args).AsTask().Wait(); + redirected = true; + } + catch (Exception) + { + // The main instance exited or crashed meanwhile. + } + finally + { + // Without the event the wait below never ends and the process stays without a window. + SetEvent(redirectEventHandle); + } }); uint CWMO_DEFAULT = 0; - uint INFINITE = 0xFFFFFFFF; + uint RedirectTimeoutMs = 30000; _ = CoWaitForMultipleObjects( - CWMO_DEFAULT, INFINITE, 1, + CWMO_DEFAULT, RedirectTimeoutMs, 1, [redirectEventHandle], out uint handleIndex); + return Volatile.Read(ref redirected); } } } From 1fb1abf274cb152ebf29750f268a4e5164657f87 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:29:19 +0000 Subject: [PATCH 110/202] Keep activation arguments when the GUI has to start the tray first When the GUI found no tray, it started the tray elevated and exited, and the tray started the GUI again with --show-ui only: the opened file, cdpiui:// link or --direct: command was lost. The arguments now travel to the tray encoded in --gui-args: and come back as a properly quoted command line. A redirected launch also handles --direct: now, and its arguments are split with CommandLineToArgvW instead of a regex that broke on mixed quoted and plain arguments. --- .../Communication/PipeClientService.cs | 6 ++ .../CommandLine/GuiActivationArguments.cs | 93 +++++++++++++++++++ .../Shared/GuiActivationArgumentsTests.cs | 38 ++++++++ CDPIUI.TrayIcon/Program.cs | 9 +- CDPIUI/App.xaml.cs | 45 ++++++++- 5 files changed, 185 insertions(+), 6 deletions(-) create mode 100644 CDPIUI.Shared/Basic/CommandLine/GuiActivationArguments.cs create mode 100644 CDPIUI.Tests/Shared/GuiActivationArgumentsTests.cs diff --git a/CDPIUI.Core/Communication/PipeClientService.cs b/CDPIUI.Core/Communication/PipeClientService.cs index 56c33a76..8ed084ca 100644 --- a/CDPIUI.Core/Communication/PipeClientService.cs +++ b/CDPIUI.Core/Communication/PipeClientService.cs @@ -93,6 +93,12 @@ public async void Start() { startupString = $"--show-ui {migrationRequest!.RawArgument}"; } + else if (Shared.Basic.CommandLine.GuiActivationArguments.Encode( + Environment.GetCommandLineArgs().Skip(1)) is string guiArgs) + { + // The tray starts the GUI again with these, so the opened file or link is not lost. + startupString = $"--show-ui {guiArgs}"; + } var psi = new ProcessStartInfo(Path.Combine(Data.Directories.CurrentDirectory, "CDPIUI_TrayIcon.exe"), startupString) { UseShellExecute = true, diff --git a/CDPIUI.Shared/Basic/CommandLine/GuiActivationArguments.cs b/CDPIUI.Shared/Basic/CommandLine/GuiActivationArguments.cs new file mode 100644 index 00000000..f0ca39c3 --- /dev/null +++ b/CDPIUI.Shared/Basic/CommandLine/GuiActivationArguments.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CDPIUI.Shared.Basic.CommandLine +{ + /// + /// Carries the command-line arguments of a GUI start through the tray. When the GUI finds no + /// tray, it starts the tray and exits; the tray then starts the GUI again. Without these + /// arguments the opened file, cdpiui:// link or --direct: command was lost. + /// + public static class GuiActivationArguments + { + public const string Prefix = "--gui-args:"; + + // Arguments longer than this are dropped rather than passed half. + private const int MaxEncodedLength = 16 * 1024; + + public static string? Encode(IEnumerable arguments) + { + var list = arguments.Where(a => !string.IsNullOrEmpty(a)).ToList(); + if (list.Count == 0) + return null; + + string encoded = Prefix + string.Join(".", list.Select(a => Convert.ToBase64String(Encoding.UTF8.GetBytes(a)))); + return encoded.Length <= MaxEncodedLength ? encoded : null; + } + + public static bool TryDecode(IEnumerable arguments, out string[] decoded) + { + decoded = Array.Empty(); + string? value = arguments.FirstOrDefault(a => a.StartsWith(Prefix, StringComparison.Ordinal)); + if (value == null || value.Length > MaxEncodedLength) + return false; + + try + { + decoded = value.Substring(Prefix.Length) + .Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) + .Select(part => Encoding.UTF8.GetString(Convert.FromBase64String(part))) + .ToArray(); + return decoded.Length > 0; + } + catch (FormatException) + { + decoded = Array.Empty(); + return false; + } + } + + /// + /// Builds a command line that CommandLineToArgvW and the .NET runtime split back into + /// exactly . + /// + public static string JoinCommandLine(IEnumerable arguments) + { + return string.Join(" ", arguments.Select(Quote)); + } + + private static string Quote(string argument) + { + if (argument.Length > 0 && argument.IndexOfAny(new[] { ' ', '\t', '\n', '\v', '"' }) < 0) + return argument; + + var builder = new StringBuilder("\""); + int backslashes = 0; + foreach (char c in argument) + { + if (c == '\\') + { + backslashes++; + continue; + } + if (c == '"') + { + // Backslashes before a quote are escaped, and so is the quote. + builder.Append('\\', backslashes * 2 + 1); + } + else + { + builder.Append('\\', backslashes); + } + backslashes = 0; + builder.Append(c); + } + // Backslashes before the closing quote are escaped too. + builder.Append('\\', backslashes * 2); + builder.Append('"'); + return builder.ToString(); + } + } +} diff --git a/CDPIUI.Tests/Shared/GuiActivationArgumentsTests.cs b/CDPIUI.Tests/Shared/GuiActivationArgumentsTests.cs new file mode 100644 index 00000000..632560bf --- /dev/null +++ b/CDPIUI.Tests/Shared/GuiActivationArgumentsTests.cs @@ -0,0 +1,38 @@ +using CDPIUI.Shared.Basic.CommandLine; + +namespace CDPIUI.Tests.Shared; + +public class GuiActivationArgumentsTests +{ + [Fact] + public void ArgumentsSurviveEncoding() + { + string[] args = ["C:\\Users\\Иван\\Мои пресеты\\a b.cdpiconfig", "--direct:cdpiui://x?y=1&z=2", "\"quoted\""]; + + string? encoded = GuiActivationArguments.Encode(args); + + Assert.NotNull(encoded); + Assert.DoesNotContain(" ", encoded); + Assert.True(GuiActivationArguments.TryDecode(["--show-ui", encoded!], out var decoded)); + Assert.Equal(args, decoded); + } + + [Fact] + public void MissingOrDamagedValueIsIgnored() + { + Assert.False(GuiActivationArguments.TryDecode(["--show-ui"], out _)); + Assert.False(GuiActivationArguments.TryDecode(["--gui-args:%%%"], out _)); + Assert.Null(GuiActivationArguments.Encode([])); + } + + [Theory] + [InlineData("simple", "simple")] + [InlineData("with space", "\"with space\"")] + [InlineData("C:\\dir with space\\", "\"C:\\dir with space\\\\\"")] + [InlineData("say \"hi\"", "\"say \\\"hi\\\"\"")] + [InlineData("", "\"\"")] + public void ArgumentsAreQuotedForCommandLineToArgv(string argument, string expected) + { + Assert.Equal(expected, GuiActivationArguments.JoinCommandLine([argument])); + } +} diff --git a/CDPIUI.TrayIcon/Program.cs b/CDPIUI.TrayIcon/Program.cs index 97d90889..ed5e1a3a 100644 --- a/CDPIUI.TrayIcon/Program.cs +++ b/CDPIUI.TrayIcon/Program.cs @@ -1,4 +1,5 @@ -using CDPIUI.TrayIcon.Helper.Basic; +using CDPIUI.Shared.Basic.CommandLine; +using CDPIUI.TrayIcon.Helper.Basic; using CDPIUI.TrayIcon.Forms; using CDPIUI.TrayIcon.Helper; using Microsoft.Toolkit.Uwp.Notifications; @@ -56,9 +57,13 @@ static void Main(string[] args) if (args.Contains("--show-ui") || args.Contains("--after-patching") || args.Contains("--after-failed-update") || migrationRequest != null) { + // Arguments of a GUI start that had to start the tray first. + string guiCommandLine = GuiActivationArguments.TryDecode(args, out var guiArgs) + ? GuiActivationArguments.JoinCommandLine(guiArgs) + : migrationRequest?.RawArgument ?? string.Empty; RunHelper.RunAsDesktopUser( Path.Combine(Utils.GetDataDirectory(), "CDPIUI.exe"), - migrationRequest?.RawArgument ?? string.Empty); + guiCommandLine); } string updateFilePath = Path.Combine(Utils.GetDataDirectory(), "Update.exe"); diff --git a/CDPIUI/App.xaml.cs b/CDPIUI/App.xaml.cs index a5cbddf7..3ef8ab3d 100644 --- a/CDPIUI/App.xaml.cs +++ b/CDPIUI/App.xaml.cs @@ -376,11 +376,20 @@ public async void PrefferRequestedActions(AppActivationArguments appActivationAr appActivationArguments.Data is ILaunchActivatedEventArgs fileActivatedEventArgs) { result = await TryHandleMigrationActivationAsync(fileActivatedEventArgs.Arguments); + string[] args = SplitCommandLine(fileActivatedEventArgs.Arguments); if (!result) { - string[] args = GetFilesFromStringRegex().Split(fileActivatedEventArgs.Arguments); - result = await ProcessFiles(args); + // The same --direct: commands as in a first start (audit 9.4). + string directArgs = args.FirstOrDefault(x => x.StartsWith("--direct:")); + if (directArgs != null) + { + string value = directArgs["--direct:".Length..]; + result = await CoreCommandsHandler.HandleCommandAsync(PipeModelConvertor.ConvertBack(value)) + || CommandsHandler.HandleCommand(value); + } } + if (!result) + result = await ProcessFiles(args); } } catch (Exception ex) @@ -1064,7 +1073,35 @@ private async Task InitializeLocalizer() private const uint SWP_SHOWWINDOW = 0x0040; private const int GWLP_HWNDPARENT = -8; - [GeneratedRegex(@"""(.*?)\""")] - private static partial Regex GetFilesFromStringRegex(); + /// + /// Splits a command line the way the runtime splits the arguments of Main. File paths + /// with spaces and quoted arguments mixed with plain ones were split wrongly by a regex. + /// + private static string[] SplitCommandLine(string commandLine) + { + if (string.IsNullOrWhiteSpace(commandLine)) + return []; + + IntPtr argv = CommandLineToArgvW(commandLine, out int argc); + if (argv == IntPtr.Zero) + return []; + try + { + var result = new string[argc]; + for (int i = 0; i < argc; i++) + result[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(argv, i * IntPtr.Size)) ?? string.Empty; + return result; + } + finally + { + LocalFree(argv); + } + } + + [DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern IntPtr CommandLineToArgvW(string lpCmdLine, out int pNumArgs); + + [DllImport("kernel32.dll")] + private static extern IntPtr LocalFree(IntPtr hMem); } } From 1f325e65bbed670432fc0e2402dd17438e2da547 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:29:53 +0000 Subject: [PATCH 111/202] Let only the latest settings tile build fill the component page Changing the preset, the component state and the page load each started InitSettingsTiles with Task.Run, and the builds interleaved as Clear, Clear, Add, Add, so tiles appeared twice. Each build now has a generation number and only the latest one clears and fills the list. --- .../DefaultComponentSettingsPage.xaml.cs | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs b/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs index 722a4cb3..bee7d2db 100644 --- a/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs +++ b/CDPIUI/Views/Main/Components/DefaultComponentSettingsPage.xaml.cs @@ -23,6 +23,7 @@ using Microsoft.UI.Xaml.Hosting; using Microsoft.UI.Xaml.Navigation; using System; +using System.Threading; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -75,12 +76,25 @@ protected override void OnNavigatedTo(NavigationEventArgs e) } + // Several builds can run at once (Task.Run from different events); only the latest + // one may fill the list, otherwise the tiles appeared twice (audit 9.5). + private int _tilesGeneration; + + private void AddTileIfCurrent(int generation, UIElement tile) + { + if (generation == Volatile.Read(ref _tilesGeneration)) + _tiles.Add(tile); + } + private void InitSettingsTiles(ConfigSelectorItem sel) { bool _flag; + int generation = Interlocked.Increment(ref _tilesGeneration); DispatcherQueue.TryEnqueue(() => { + if (generation != Volatile.Read(ref _tilesGeneration)) + return; _tiles.Clear(); HelpfulLinksControl.Visibility = Visibility.Collapsed; SetupAsProxyHelpfulLink.IsVisible = ProxyHelper.ProxyLikeComponents.Contains(ComponentId); @@ -131,7 +145,7 @@ private void InitSettingsTiles(ConfigSelectorItem sel) } DispatcherQueue.TryEnqueue(() => { - _tiles.Add(CreateSettingTile(variablesItem, HandleSettingTileElementClick)); + AddTileIfCurrent(generation, CreateSettingTile(variablesItem, HandleSettingTileElementClick)); }); } @@ -180,7 +194,7 @@ private void InitSettingsTiles(ConfigSelectorItem sel) _flag = true; } - DispatcherQueue.TryEnqueue(() => { _tiles.Add(CreateSettingTile(sitelistTile, HandleSettingTileElementClick)); }); + DispatcherQueue.TryEnqueue(() => { AddTileIfCurrent(generation, CreateSettingTile(sitelistTile, HandleSettingTileElementClick)); }); } List excludeList = componentHelper.GetConfigHelper().GetExcludedSiteListItems(sel.FileName, sel.PackId, ignoreNull: true); if (excludeList.Count > 0) @@ -227,7 +241,7 @@ private void InitSettingsTiles(ConfigSelectorItem sel) _flag = true; } - DispatcherQueue.TryEnqueue(() => { _tiles.Add(CreateSettingTile(sitelistTile, HandleSettingTileElementClick)); }); + DispatcherQueue.TryEnqueue(() => { AddTileIfCurrent(generation, CreateSettingTile(sitelistTile, HandleSettingTileElementClick)); }); } if (commaVariables.Count > 0) @@ -262,7 +276,7 @@ private void InitSettingsTiles(ConfigSelectorItem sel) DispatcherQueue.TryEnqueue(() => { - _tiles.Add(CreateSettingTile(commaVariablesWidget, HandleSettingTileElementClick)); + AddTileIfCurrent(generation, CreateSettingTile(commaVariablesWidget, HandleSettingTileElementClick)); }); } @@ -304,7 +318,7 @@ private void InitSettingsTiles(ConfigSelectorItem sel) // TODO: add dynamic help DispatcherQueue.TryEnqueue(() => { - _tiles.Add(CreateSettingTile(helpTile, HandleSettingTileElementClick)); + AddTileIfCurrent(generation, CreateSettingTile(helpTile, HandleSettingTileElementClick)); HelpfulLinksControl.Visibility = Visibility.Visible; }); } From 955a916b6d00ff40a63f4d8023824cd8e6675ee7 Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:30:06 +0000 Subject: [PATCH 112/202] Update the accent preview on the UI thread UISettings.ColorValuesChanged comes on a background thread, and the handler created a brush there, which threw COMException and crashed the application when the Windows accent color changed while the personalization page was open. --- CDPIUI/Views/Settings/PersonalizePage.xaml.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CDPIUI/Views/Settings/PersonalizePage.xaml.cs b/CDPIUI/Views/Settings/PersonalizePage.xaml.cs index 43043ca2..acb544cf 100644 --- a/CDPIUI/Views/Settings/PersonalizePage.xaml.cs +++ b/CDPIUI/Views/Settings/PersonalizePage.xaml.cs @@ -161,9 +161,9 @@ private void HandleAccentChanged(UISettings sender, object args) { var accentColor = sender.GetColorValue(UIColorType.Accent); - var backgroundColor = sender.GetColorValue(UIColorType.Background); - - SystemColorBorder.Background = new SolidColorBrush(accentColor); + // UISettings raises the event on a background thread; a brush made there throws + // COMException (audit 9.6). + DispatcherQueue.TryEnqueue(() => SystemColorBorder.Background = new SolidColorBrush(accentColor)); } private void CheckFontSettings() From ec240b086ed435cd33373d4e0cdc3939f89050dd Mon Sep 17 00:00:00 2001 From: lumenpearson <139921639+lumenpearson@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:30:40 +0000 Subject: [PATCH 113/202] Rank failed handshakes as failures in the preset test and fix remaining time curl on Windows reports a TLS handshake reset by DPI as exit code 35 with a schannel message, which the preset test counted as an unsupported check without penalty, so a preset that failed ranked above one that timed out. A failed DNS lookup was shown as a certificate error, and a preset without a single successful check was still marked as recommended. The remaining time showed only the minutes component, so 1 h 20 min read as 20 min, here and in the Store download button. --- .../Store/StoreDownloadItemButton.xaml.cs | 2 +- CDPIUI/Helper/AddOns/PresetTestHelper.cs | 16 +++++++++++----- CDPIUI/Windows/ConfigTestWindow.xaml.cs | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs b/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs index ccaac9e4..8312028d 100644 --- a/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs +++ b/CDPIUI/Controls/Store/StoreDownloadItemButton.xaml.cs @@ -412,7 +412,7 @@ private void StoreHelper_ItemTimeRemainingChanged(Tuple obj) if (StoreHelper.Instance.GetItemIdFromOperationId(operationId) != StoreId) return; - TimeTextBlock.Text = UnitsParser.ConvertMinutesToPrettyText(time.Minutes); + TimeTextBlock.Text = UnitsParser.ConvertMinutesToPrettyText(time.TotalMinutes); } private void PreferItemDownloadingStateActions(string state) diff --git a/CDPIUI/Helper/AddOns/PresetTestHelper.cs b/CDPIUI/Helper/AddOns/PresetTestHelper.cs index 68963ec7..2bad6efb 100644 --- a/CDPIUI/Helper/AddOns/PresetTestHelper.cs +++ b/CDPIUI/Helper/AddOns/PresetTestHelper.cs @@ -128,11 +128,15 @@ public class PresetTestHelper private readonly object _curlLock = new(); private readonly List _activeCurls = new(); + // A failed DNS lookup is an ordinary error, not a certificate problem. private static readonly Regex CertRegex = new( - "Could not resolve host|certificate|SSL certificate problem|self[- ]?signed|certificate verify failed|unable to get local issuer certificate", + "certificate|SSL certificate problem|self[- ]?signed|certificate verify failed|unable to get local issuer certificate", RegexOptions.IgnoreCase | RegexOptions.Compiled); + // curl on Windows uses schannel, and a TLS handshake reset by DPI ends with exit code 35 + // and "schannel: failed to receive handshake": that is a failure of the preset, not an + // unsupported curl feature, so neither "schannel" nor code 35 alone means unsupported. private static readonly Regex UnsupportedRegex = new( - "does not support|not supported|unsupported protocol|unsupported option|unsupported feature|Unrecognized option|Unknown option|schannel", + "does not support|not supported|unsupported protocol|unsupported option|unsupported feature|Unrecognized option|Unknown option", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex DpiMetricsRegex = new( @"^(?\d{3})\s+(?\d+)\s+(?\d+)\s+(?