| 1 | using System.Diagnostics; |
| 2 | using System.Runtime.CompilerServices; |
| 3 | using System.Security.AccessControl; |
| 4 | using System.Security.Cryptography; |
| 5 | using System.Security.Principal; |
| 6 | using System.Text.Json.Nodes; |
| 7 | |
| 8 | namespace Cage.GuestClipboard; |
| 9 | |
| 10 | internal static class GuestVersions |
| 11 | { |
| 12 | [ModuleInitializer] |
| 13 | internal static void Register() => GuestOperations.Register("versions", Read); |
| 14 | |
| 15 | private static async Task Read(Stream stream, CancellationToken token, Func<bool> available) |
| 16 | { |
| 17 | var result = Snapshot(); |
| 18 | var tools = new JsonObject(); |
| 19 | tools["node"] = await Version(Path.Combine(AppContext.BaseDirectory, "node.exe"), token); |
| 20 | tools["code_server"] = await Version(Path.Combine(AppContext.BaseDirectory, "vscode-cli", "code.exe"), token); |
| 21 | var chrome = new[] { |
| 22 | Path.Combine(AppContext.BaseDirectory, "chrome", "chrome.exe"), |
| 23 | Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Google", "Chrome", "Application", "chrome.exe"), |
| 24 | Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft", "Edge", "Application", "msedge.exe") |
| 25 | }.FirstOrDefault(File.Exists); |
| 26 | tools["chromium"] = chrome is null ? "" : FileVersionInfo.GetVersionInfo(chrome).ProductVersion ?? ""; |
| 27 | try |
| 28 | { |
| 29 | var receipt = Path.Combine(AppContext.BaseDirectory, "cli-tools.json"); |
| 30 | Pairing.PrivateFile(receipt); |
| 31 | var cli = JsonNode.Parse(File.ReadAllBytes(receipt)) as JsonObject; |
| 32 | foreach (var name in new[] { "python", "claude", "git_bash" }) |
| 33 | { |
| 34 | var filename = cli?[name]?.GetValue<string>(); |
| 35 | var expected = cli?[name + "_sha256"]?.GetValue<string>(); |
| 36 | if (filename is null || expected is null || !Path.IsPathRooted(filename)) continue; |
| 37 | using (var file = File.OpenRead(filename)) |
| 38 | if (!Convert.ToHexString(SHA256.HashData(file)).Equals(expected, StringComparison.OrdinalIgnoreCase)) continue; |
| 39 | if (name == "git_bash") |
| 40 | tools["git"] = await Version(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(filename))!, "cmd", "git.exe"), token); |
| 41 | else tools[name] = await Version(filename, token); |
| 42 | } |
| 43 | } |
| 44 | catch (IOException) { } |
| 45 | catch (UnauthorizedAccessException) { } |
| 46 | catch (System.Text.Json.JsonException) { } |
| 47 | result["tools"] = tools; |
| 48 | await Protocol.Write(stream, result, token); |
| 49 | } |
| 50 | |
| 51 | internal static JsonObject Snapshot() |
| 52 | { |
| 53 | var result = new JsonObject { ["manifest"] = null, ["installed"] = false, ["missing"] = new JsonArray() }; |
| 54 | try |
| 55 | { |
| 56 | var path = Path.Combine(AppContext.BaseDirectory, "native-components.json"); |
| 57 | CheckReceipt(path); |
| 58 | var manifest = JsonNode.Parse(File.ReadAllText(path)) as JsonObject; |
| 59 | if (manifest?["protocol"]?.GetValue<int>() != 1 || manifest["system"]?.GetValue<string>() != "windows-11" || manifest["files"] is not JsonArray files || files.Count > 10000) |
| 60 | throw new InvalidDataException("component_manifest_invalid"); |
| 61 | var missing = new JsonArray(); |
| 62 | foreach (var entry in files.OfType<JsonObject>()) |
| 63 | { |
| 64 | var target = entry["target"]?.GetValue<string>() ?? ""; |
| 65 | if (target.Length == 0) continue; |
| 66 | var filename = Target(target); |
| 67 | try |
| 68 | { |
| 69 | using var file = File.OpenRead(filename); |
| 70 | var hash = Convert.ToHexString(SHA256.HashData(file)); |
| 71 | if (!hash.Equals(entry["installed_sha256"]?.GetValue<string>(), StringComparison.OrdinalIgnoreCase) && missing.Count < 20) missing.Add(target); |
| 72 | } |
| 73 | catch (IOException) { if (missing.Count < 20) missing.Add(target); } |
| 74 | } |
| 75 | result["manifest"] = new JsonObject { |
| 76 | ["protocol"] = 1, ["revision"] = missing.Count == 0 ? manifest["revision"]?.DeepClone() : "", |
| 77 | ["app_version"] = manifest["app_version"]?.DeepClone() |
| 78 | }; |
| 79 | result["installed"] = missing.Count == 0; |
| 80 | result["missing"] = missing; |
| 81 | } |
| 82 | catch (Exception error) when (error is IOException or UnauthorizedAccessException or System.Text.Json.JsonException or InvalidOperationException) |
| 83 | { |
| 84 | result["error"] = "客机尚无可核验的组件记录,请同步环境组件。"; |
| 85 | } |
| 86 | return result; |
| 87 | } |
| 88 | |
| 89 | private static void CheckReceipt(string path) |
| 90 | { |
| 91 | var file = new FileInfo(path); |
| 92 | if (!file.Exists || file.Length is < 1 or > 4 << 20 || file.Attributes.HasFlag(FileAttributes.ReparsePoint)) |
| 93 | throw new InvalidDataException("component_manifest_invalid"); |
| 94 | for (var parent = file.Directory; parent is not null; parent = parent.Parent) |
| 95 | if (parent.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("component_manifest_invalid"); |
| 96 | var acl = file.GetAccessControl(); |
| 97 | var administrators = new HashSet<string> { "S-1-5-18", "S-1-5-32-544" }; |
| 98 | var owner = acl.GetOwner(typeof(SecurityIdentifier))?.Value; |
| 99 | if (!acl.AreAccessRulesProtected || owner is null || !administrators.Contains(owner)) |
| 100 | throw new InvalidDataException("component_permissions_invalid"); |
| 101 | var read = FileSystemRights.ReadAndExecute | FileSystemRights.Synchronize; |
| 102 | foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier))) |
| 103 | { |
| 104 | if (rule.AccessControlType != AccessControlType.Allow || administrators.Contains(rule.IdentityReference.Value)) continue; |
| 105 | if (rule.IdentityReference.Value != GuestContext.SID || (rule.FileSystemRights & ~read) != 0) |
| 106 | throw new InvalidDataException("component_permissions_invalid"); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | private static string Target(string target) |
| 111 | { |
| 112 | var parts = target.Split('/'); |
| 113 | if (parts.Length < 2 || parts.Any(part => part.Length == 0 || part is "." or ".." || part.Contains('\\') || part.Contains(':'))) |
| 114 | throw new InvalidDataException("component_target_invalid"); |
| 115 | var root = parts[0] switch { |
| 116 | "bridge" => AppContext.BaseDirectory, |
| 117 | "network" => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cage Guest Network", GuestContext.VM.ToString("D")), |
| 118 | _ => throw new InvalidDataException("component_target_invalid") |
| 119 | }; |
| 120 | return Path.Combine([root, .. parts.Skip(1)]); |
| 121 | } |
| 122 | |
| 123 | private static async Task<string> Version(string executable, CancellationToken parent) |
| 124 | { |
| 125 | if (!File.Exists(executable)) return ""; |
| 126 | using var timeout = CancellationTokenSource.CreateLinkedTokenSource(parent); |
| 127 | timeout.CancelAfter(TimeSpan.FromSeconds(3)); |
| 128 | var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; |
| 129 | start.ArgumentList.Add("--version"); |
| 130 | start.Environment["DISABLE_AUTOUPDATER"] = "1"; |
| 131 | Process? launched; |
| 132 | try { launched = Process.Start(start); } |
| 133 | catch (Exception error) when (error is System.ComponentModel.Win32Exception or IOException) { return ""; } |
| 134 | using var process = launched; |
| 135 | if (process is null) return ""; |
| 136 | process.StandardInput.Close(); |
| 137 | using var cancel = timeout.Token.Register(() => { |
| 138 | try { process.Kill(true); } |
| 139 | catch (Exception error) when (error is InvalidOperationException or System.ComponentModel.Win32Exception) { } |
| 140 | }); |
| 141 | try |
| 142 | { |
| 143 | var errors = process.StandardError.BaseStream.CopyToAsync(Stream.Null, timeout.Token); |
| 144 | var output = new char[512]; |
| 145 | var count = await process.StandardOutput.ReadAsync(output, timeout.Token); |
| 146 | await process.StandardOutput.BaseStream.CopyToAsync(Stream.Null, timeout.Token); |
| 147 | await process.WaitForExitAsync(timeout.Token); |
| 148 | await errors; |
| 149 | var line = new string(output, 0, count).Split('\n')[0].Trim(); |
| 150 | return process.ExitCode == 0 ? line[..Math.Min(line.Length, 200)] : ""; |
| 151 | } |
| 152 | catch (OperationCanceledException) { return ""; } |
| 153 | } |
| 154 | } |