| 1 | using System.Collections.Concurrent; |
| 2 | using System.Diagnostics; |
| 3 | using System.Security.Cryptography; |
| 4 | using System.Text.Json.Nodes; |
| 5 | using System.Text.RegularExpressions; |
| 6 | |
| 7 | namespace Cage.GuestClipboard; |
| 8 | |
| 9 | |
| 10 | |
| 11 | internal static class WindowsEditorServer |
| 12 | { |
| 13 | private static readonly ConcurrentDictionary<string, Editor> Editors = new(StringComparer.Ordinal); |
| 14 | private static readonly Regex Commit = new("^[a-f0-9]{40}$", RegexOptions.CultureInvariant); |
| 15 | private static readonly Regex Listening = new(@"Web UI available at (http://127\.0\.0\.1:[1-9][0-9]*)", RegexOptions.CultureInvariant); |
| 16 | internal sealed record Connection(string ID, string Project, string Grant, string Folder, string URL, bool? TrustDefault = null); |
| 17 | |
| 18 | internal static bool Installed() |
| 19 | { |
| 20 | try |
| 21 | { |
| 22 | var root = AppContext.BaseDirectory; |
| 23 | return File.Exists(Path.Combine(root, "vscode-cli", "code.exe")) && |
| 24 | File.Exists(Path.Combine(root, "vscode-server", "bin", "code-server.cmd")) && |
| 25 | Commit.IsMatch((JsonNode.Parse(File.ReadAllText(Path.Combine(root, "editor-runtime.json"))) as JsonObject)?["commit"]?.GetValue<string>() ?? ""); |
| 26 | } |
| 27 | catch { return false; } |
| 28 | } |
| 29 | |
| 30 | internal static async Task<Connection> Open(string project, string grant, bool restart, CancellationToken token) |
| 31 | { |
| 32 | var folder = ProjectRpc.Resolve(project, grant); |
| 33 | if (!Installed()) throw new InvalidDataException("editor_components_missing"); |
| 34 | var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cage", "Editors"); |
| 35 | var trustDefault = WindowsEditorPreferences.TrustDefault(home); |
| 36 | if (Editors.TryGetValue(project, out var existing)) |
| 37 | { |
| 38 | if (existing.Grant == grant && !existing.Process.HasExited && existing.Folder == folder && !restart) return existing.Connection with { TrustDefault = trustDefault }; |
| 39 | if (Editors.TryRemove(project, out var old)) old.Dispose(); |
| 40 | } |
| 41 | var root = AppContext.BaseDirectory; |
| 42 | var commit = (JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(root, "editor-runtime.json"), token)) as JsonObject)?["commit"]?.GetValue<string>() ?? ""; |
| 43 | if (!Commit.IsMatch(commit)) throw new InvalidDataException("editor_components_missing"); |
| 44 | var runtime = Path.Combine(home, "runtime"); |
| 45 | var cached = Path.Combine(runtime, "serve-web", commit); |
| 46 | if (!Directory.Exists(cached)) |
| 47 | { |
| 48 | var stage = cached + "." + Guid.NewGuid().ToString("N"); |
| 49 | try { CopyPackage(Path.Combine(root, "vscode-server"), stage, token); Directory.Move(stage, cached); } |
| 50 | finally { if (Directory.Exists(stage)) Directory.Delete(stage, true); } |
| 51 | } |
| 52 | if (!File.Exists(Path.Combine(cached, "bin", "code-server.cmd"))) throw new InvalidDataException("editor_components_missing"); |
| 53 | var profile = Path.Combine(home, "profiles", project); |
| 54 | Directory.CreateDirectory(profile); |
| 55 | var tokenFile = Path.Combine(profile, "connection-token"); |
| 56 | var portFile = Path.Combine(profile, "port"); |
| 57 | ushort port = 0; |
| 58 | if (File.Exists(portFile) && new FileInfo(portFile).Length <= 16) ushort.TryParse(await File.ReadAllTextAsync(portFile, token), out port); |
| 59 | var secret = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); |
| 60 | await File.WriteAllTextAsync(tokenFile, secret, Protocol.Utf8, token); |
| 61 | var start = new ProcessStartInfo(Path.Combine(root, "vscode-cli", "code.exe")) |
| 62 | { |
| 63 | UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, |
| 64 | RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = folder, |
| 65 | }; |
| 66 | foreach (var arg in new[] { "serve-web", "--host", "127.0.0.1", "--port", port.ToString(System.Globalization.CultureInfo.InvariantCulture), "--connection-token-file", tokenFile, |
| 67 | "--default-folder", folder, "--server-data-dir", Path.Combine(home, "server"), "--cli-data-dir", runtime, |
| 68 | "--commit-id", commit, "--disable-telemetry", "--accept-server-license-terms" }) start.ArgumentList.Add(arg); |
| 69 | |
| 70 | |
| 71 | var process = Process.Start(start) ?? throw new InvalidDataException("editor_start_failed"); |
| 72 | var editor = new Editor(project, grant, folder, process); |
| 73 | try |
| 74 | { |
| 75 | editor.Job = new GuestProcessJob(process); |
| 76 | var address = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 77 | editor.Output = Drain(process.StandardOutput, address); |
| 78 | editor.Errors = Drain(process.StandardError, address); |
| 79 | using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(20)); |
| 80 | var url = await address.Task.WaitAsync(timeout.Token); |
| 81 | var endpoint = new Uri(url); |
| 82 | await File.WriteAllTextAsync(portFile, endpoint.Port.ToString(System.Globalization.CultureInfo.InvariantCulture), Protocol.Utf8, token); |
| 83 | editor.Connection = new Connection(Guid.NewGuid().ToString("N"), project, grant, folder, "http://" + project + ".cage-editor.localhost:" + endpoint.Port + "/?tkn=" + Uri.EscapeDataString(secret), trustDefault); |
| 84 | if (ProjectRpc.Resolve(project, grant) != folder || process.HasExited) throw new InvalidDataException("project_grant_unavailable"); |
| 85 | if (!Editors.TryAdd(project, editor)) throw new InvalidDataException("editor_start_busy"); |
| 86 | return editor.Connection; |
| 87 | } |
| 88 | catch { editor.Dispose(); throw; } |
| 89 | } |
| 90 | |
| 91 | private static async Task Drain(StreamReader reader, TaskCompletionSource<string> listening) |
| 92 | { |
| 93 | try |
| 94 | { |
| 95 | |
| 96 | |
| 97 | var buffer = new char[4096]; var recent = ""; int count; |
| 98 | while ((count = await reader.ReadAsync(buffer)) != 0) |
| 99 | { |
| 100 | recent = (recent + new string(buffer, 0, count)); |
| 101 | if (recent.Length > 8192) recent = recent[^8192..]; |
| 102 | var match = Listening.Match(recent); |
| 103 | if (match.Success) listening.TrySetResult(match.Groups[1].Value); |
| 104 | } |
| 105 | listening.TrySetException(new InvalidDataException("editor_start_failed")); |
| 106 | } |
| 107 | catch { listening.TrySetException(new InvalidDataException("editor_start_failed")); } |
| 108 | } |
| 109 | |
| 110 | private static void CopyPackage(string source, string target, CancellationToken token) |
| 111 | { |
| 112 | var directory = new DirectoryInfo(source); |
| 113 | if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("editor_package_invalid"); |
| 114 | Directory.CreateDirectory(target); |
| 115 | foreach (var file in directory.EnumerateFiles()) |
| 116 | { |
| 117 | token.ThrowIfCancellationRequested(); |
| 118 | if (file.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("editor_package_invalid"); |
| 119 | file.CopyTo(Path.Combine(target, file.Name), false); |
| 120 | } |
| 121 | foreach (var child in directory.EnumerateDirectories()) CopyPackage(child.FullName, Path.Combine(target, child.Name), token); |
| 122 | } |
| 123 | |
| 124 | internal static void Revoke(string project, string grant) |
| 125 | { |
| 126 | if (Editors.TryGetValue(project, out var editor) && editor.Grant == grant && |
| 127 | ((ICollection<KeyValuePair<string, Editor>>)Editors).Remove(new(project, editor))) editor.Dispose(); |
| 128 | } |
| 129 | internal static void Close() { foreach (var entry in Editors) if (Editors.TryRemove(entry.Key, out var editor)) editor.Dispose(); } |
| 130 | |
| 131 | private sealed class Editor(string project, string grant, string folder, Process process) : IDisposable |
| 132 | { |
| 133 | internal string Grant { get; } = grant; |
| 134 | internal string Folder { get; } = folder; |
| 135 | internal Process Process { get; } = process; |
| 136 | internal Connection Connection { get; set; } = new("", project, grant, folder, ""); |
| 137 | internal Task? Output, Errors; |
| 138 | internal GuestProcessJob? Job; |
| 139 | public void Dispose() |
| 140 | { |
| 141 | try { Process.StandardInput.Close(); if (!Process.HasExited) Process.Kill(true); Process.WaitForExit(2000); } catch (InvalidOperationException) { } |
| 142 | Job?.Dispose();Process.Dispose(); |
| 143 | |
| 144 | } |
| 145 | } |
| 146 | } |