Files
ucvl-zonghengjia-open-source/windows/InstallationIntegration.cs
T

200 lines
12 KiB
C#
Raw Normal View History

using Microsoft.Win32;
using System.Text.Json;
namespace UCVL.VPNPlus;
// Uninstaller, two shortcuts and ten owned registry values participate in the
// SAME durable journal as the program payload. No recursive registry/file removal.
internal static class InstallationIntegration
{
internal record Value(RegistryValueKind Kind, string Data);
internal record Component(int Id, string Sha256, string? PreviousSha256);
internal record Registration(int Id, Value Next, Value? Previous);
internal record Snapshot(bool Isolated, List<Component> Components,
List<Registration> Values, bool[] KeysExisted);
private static readonly string[] Names = ["", "Path", "DisplayName", "DisplayIcon", "DisplayVersion",
"Publisher", "URLInfoAbout", "UninstallString", "NoModify", "NoRepair"];
private static readonly string[] StagedNames = ["Uninstall.exe", "Desktop.lnk", "StartMenu.lnk"];
private static int KeyIndex(int id) => id < 2 ? 0 : 1;
private static RegistryKey Hive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32);
internal static string Key(string target, bool isolated, int index)
{
if (index is < 0 or > 1) throw new IOException("无效安装登记位置。");
if (isolated)
{
target = InstallationTransaction.IsolatedTarget(target);
var id = Path.GetFileName(Path.GetDirectoryName(target))!["ucvl-nsis-acceptance-".Length..];
return $"Software\\UCVL\\InstallerAcceptance\\{id}\\" + (index == 0 ? "app" : "uninstall");
}
return index == 0 ? @"Software\Microsoft\Windows\CurrentVersion\App Paths\VPNPlus.exe"
: @"Software\Microsoft\Windows\CurrentVersion\Uninstall\UCVL.VPNPlus";
}
internal static string Destination(string target, bool isolated, int id)
{
if (isolated) target = InstallationTransaction.IsolatedTarget(target);
var job = Path.GetDirectoryName(target)!;
var path = id switch {
0 => Path.Combine(target, "Uninstall.exe"),
1 => isolated ? Path.Combine(job, "shell", "Desktop.lnk") : Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "优创⁺纵横家.lnk"),
2 => isolated ? Path.Combine(job, "shell", "StartMenu.lnk") : Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Programs), "优创未来", "优创⁺纵横家.lnk"),
_ => throw new IOException("无效安装组件。"),
};
InstallationTransaction.NoLinks(path);
return path;
}
private static string Backup(string backup, int id)
{
if (id is < 0 or > 2) throw new IOException("无效备份组件。");
var path = Path.Combine(backup, "components", StagedNames[id]);
InstallationTransaction.NoLinks(path);
return path;
}
private static Value Encode(object value, RegistryValueKind kind) => new(kind, kind switch {
RegistryValueKind.String or RegistryValueKind.ExpandString => JsonSerializer.Serialize((string)value),
RegistryValueKind.DWord => JsonSerializer.Serialize((int)value),
RegistryValueKind.QWord => JsonSerializer.Serialize((long)value),
RegistryValueKind.MultiString => JsonSerializer.Serialize((string[])value),
RegistryValueKind.Binary or RegistryValueKind.None => JsonSerializer.Serialize((byte[])value),
_ => throw new IOException("不支持的原安装登记类型,未覆盖。"),
});
private static object Decode(Value value) => value.Kind switch {
RegistryValueKind.String or RegistryValueKind.ExpandString => JsonSerializer.Deserialize<string>(value.Data)!,
RegistryValueKind.DWord => JsonSerializer.Deserialize<int>(value.Data),
RegistryValueKind.QWord => JsonSerializer.Deserialize<long>(value.Data),
RegistryValueKind.MultiString => JsonSerializer.Deserialize<string[]>(value.Data)!,
RegistryValueKind.Binary or RegistryValueKind.None => JsonSerializer.Deserialize<byte[]>(value.Data)!,
_ => throw new IOException("无效原登记类型。"),
};
private static Value? Read(RegistryKey hive, string keyName, string name)
{
using var key = hive.OpenSubKey(keyName);
if (key is null || !key.GetValueNames().Contains(name, StringComparer.OrdinalIgnoreCase)) return null;
var value = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames)
?? throw new IOException("无法读取原安装登记。");
return Encode(value, key.GetValueKind(name));
}
internal static Snapshot Prepare(string stage, string target, string backup, bool isolated, string version)
{
stage = InstallationTransaction.Root(stage);
if (isolated) target = InstallationTransaction.IsolatedTarget(target);
var components = new List<Component>();
for (var i = 0; i < 3; i++)
{
var source = Path.Combine(stage, StagedNames[i]);
InstallationTransaction.NoLinks(source);
if (!File.Exists(source) || new FileInfo(source).Length == 0) throw new IOException("缺少已准备的安装组件。");
var destination = Destination(target, isolated, i);
var previous = File.Exists(destination) ? InstallationTransaction.Digest(destination) : null;
if (previous is not null)
{
var saved = Backup(backup, i);
Directory.CreateDirectory(Path.GetDirectoryName(saved)!);
File.Copy(destination, saved);
if (!InstallationTransaction.Matches(saved, previous)) throw new IOException("安装组件备份校验失败。");
}
components.Add(new(i, InstallationTransaction.Digest(source), previous));
}
using var hive = Hive();
var existed = new bool[2];
for (var i = 0; i < 2; i++) { using var key = hive.OpenSubKey(Key(target, isolated, i)); existed[i] = key is not null; }
// Never redirect another registered installation by trusting /D alone.
var registered = Read(hive, Key(target, isolated, 0), "Path");
if (registered is not null && (registered.Kind != RegistryValueKind.String ||
!string.Equals(InstallationTransaction.Root((string)Decode(registered)), target, StringComparison.OrdinalIgnoreCase)))
throw new IOException("安装目录与当前登记不一致,未覆盖其它安装。");
object[] next = [Path.Combine(target, "VPNPlus.exe"), target, "优创⁺纵横家", Path.Combine(target, "VPNPlus.exe"),
version, "优创未来(UCVL)", "https://vpn.toplc.cn/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1];
var values = Names.Select((name, i) => new Registration(i,
Encode(next[i], i < 8 ? RegistryValueKind.String : RegistryValueKind.DWord),
Read(hive, Key(target, isolated, KeyIndex(i)), name))).ToList();
return new(isolated, components, values, existed);
}
private static void Shape(string target, Snapshot snapshot)
{
if (snapshot.Isolated) _ = InstallationTransaction.IsolatedTarget(target);
if (snapshot.Components.Count != 3 || !snapshot.Components.Select(c => c.Id).Order().SequenceEqual(new[] { 0, 1, 2 })
|| snapshot.Values.Count != 10 || !snapshot.Values.Select(v => v.Id).Order().SequenceEqual(Enumerable.Range(0, 10))
|| snapshot.KeysExisted.Length != 2)
throw new IOException("安装组件恢复记录不完整。");
foreach (var c in snapshot.Components)
if (c.Sha256.Length != 64 || c.Sha256.Any(x => !Uri.IsHexDigit(x)) ||
c.PreviousSha256 is not null && (c.PreviousSha256.Length != 64 || c.PreviousSha256.Any(x => !Uri.IsHexDigit(x))))
throw new IOException("组件恢复校验值无效。");
foreach (var r in snapshot.Values) { _ = Decode(r.Next); if (r.Previous is not null) _ = Decode(r.Previous); }
}
internal static void ValidateRecovery(string target, string backup, Snapshot snapshot)
{
Shape(target, snapshot);
foreach (var file in snapshot.Components)
{
var destination = Destination(target, snapshot.Isolated, file.Id);
if (!InstallationTransaction.Matches(destination, file.PreviousSha256) && !InstallationTransaction.Matches(destination, file.Sha256))
throw new IOException("安装组件被其它程序修改,保留备份,不覆盖外部改动。");
if (file.PreviousSha256 is not null && !InstallationTransaction.Matches(Backup(backup, file.Id), file.PreviousSha256))
throw new IOException("安装组件恢复备份损坏。");
}
using var hive = Hive();
foreach (var value in snapshot.Values)
{
var current = Read(hive, Key(target, snapshot.Isolated, KeyIndex(value.Id)), Names[value.Id]);
if (current != value.Previous && current != value.Next) throw new IOException("安装登记被其它程序修改,未覆盖。");
}
}
internal static void Apply(string stage, string target, Snapshot snapshot, Action<int>? afterWrite = null)
{
Shape(target, snapshot);
foreach (var file in snapshot.Components)
{
var destination = Destination(target, snapshot.Isolated, file.Id);
var source = Path.Combine(stage, StagedNames[file.Id]);
InstallationTransaction.NoLinks(source);
if (!InstallationTransaction.Matches(destination, file.PreviousSha256) || !InstallationTransaction.Matches(source, file.Sha256))
throw new IOException("安装组件在准备后发生改变。");
InstallationTransaction.Replace(source, destination);
if (!InstallationTransaction.Matches(destination, file.Sha256)) throw new IOException("组件安装后校验失败。");
afterWrite?.Invoke(file.Id);
}
using var hive = Hive();
foreach (var value in snapshot.Values)
{
var name = Names[value.Id]; var path = Key(target, snapshot.Isolated, KeyIndex(value.Id));
if (Read(hive, path, name) != value.Previous) throw new IOException("登记在备份后发生改变。");
using var key = hive.CreateSubKey(path, true) ?? throw new IOException("无法写入安装登记。");
key.SetValue(name, Decode(value.Next), value.Next.Kind); key.Flush();
if (Read(hive, path, name) != value.Next) throw new IOException("安装登记写入后校验失败。");
afterWrite?.Invoke(3 + value.Id);
}
}
internal static void Recover(string target, string backup, Snapshot snapshot)
{
ValidateRecovery(target, backup, snapshot);
using var hive = Hive();
foreach (var value in snapshot.Values.AsEnumerable().Reverse())
{
var path = Key(target, snapshot.Isolated, KeyIndex(value.Id)); var name = Names[value.Id];
if (Read(hive, path, name) == value.Previous) continue;
using var key = hive.OpenSubKey(path, true) ?? throw new IOException("恢复安装登记失败。");
if (value.Previous is null) key.DeleteValue(name, false);
else key.SetValue(name, Decode(value.Previous), value.Previous.Kind);
key.Flush();
}
foreach (var file in snapshot.Components.AsEnumerable().Reverse())
{
var destination = Destination(target, snapshot.Isolated, file.Id);
if (InstallationTransaction.Matches(destination, file.PreviousSha256)) continue;
if (file.PreviousSha256 is null) File.Delete(destination);
else InstallationTransaction.Replace(Backup(backup, file.Id), destination);
}
for (var i = 0; i < 2; i++)
{
if (snapshot.KeysExisted[i]) continue;
var path = Key(target, snapshot.Isolated, i);
bool empty;
using (var key = hive.OpenSubKey(path)) empty = key is not null && key.ValueCount == 0 && key.SubKeyCount == 0;
if (empty) hive.DeleteSubKey(path, false); // Exact empty owned key; never a tree.
}
}
}