| 1 | using System.Net.Sockets; |
| 2 | using System.ComponentModel; |
| 3 | using System.Security.Cryptography; |
| 4 | using System.Runtime.InteropServices; |
| 5 | using System.Text.Json; |
| 6 | using System.Text.Json.Nodes; |
| 7 | |
| 8 | namespace Cage.GuestClipboard; |
| 9 | |
| 10 | internal static class GuestOperations |
| 11 | { |
| 12 | internal static readonly HashSet<string> Names = ["stream", "status", "import", "export", "terminal", "cli", "browser", "desktop", "attachments", "audio", "resources", "diagnostics", "versions", "safety", "project-mount", "network-stream", "network-settings"]; |
| 13 | static readonly Dictionary<string, Func<Stream, CancellationToken, Func<bool>, Task>> handlers = new(StringComparer.Ordinal); |
| 14 | internal static void Register(string name, Func<Stream, CancellationToken, Func<bool>, Task> handler) |
| 15 | { |
| 16 | if (!Names.Contains(name) || name is "stream" or "status" or "import" or "export" || !handlers.TryAdd(name, handler)) |
| 17 | throw new InvalidOperationException("guest_operation_registration_invalid"); |
| 18 | } |
| 19 | internal static string[] Capabilities() => ["clipboard", .. handlers.Keys.Order()]; |
| 20 | internal static Task Run(string name, Stream stream, CancellationToken token) => handlers.TryGetValue(name, out var handler) |
| 21 | ? handler(stream, token, SessionGuard.Available) : throw new InvalidOperationException("guest_operation_unavailable"); |
| 22 | } |
| 23 | |
| 24 | internal static class Program |
| 25 | { |
| 26 | [DllImport("kernel32.dll")] static extern bool FreeConsole(); |
| 27 | [STAThread] |
| 28 | static int Main(string[] args) |
| 29 | { |
| 30 | try |
| 31 | { |
| 32 | if (args is ["self-test"]) { SelfTest.Run(); Console.WriteLine("Windows guest protocol tests passed."); return 0; } |
| 33 | if (args.Length > 1 && args[0] == "--relay-profile") { Relay.Run(args).GetAwaiter().GetResult(); return 0; } |
| 34 | if (args is ["pair", "--vm-id", var pairVM, "--sid", var pairSID, "--token-file", var source, "--output", var destination]) |
| 35 | { Pairing.Protect(source, destination, Guid.Parse(pairVM), pairSID); return 0; } |
| 36 | if (args is ["serve-network", "--vm-id", var networkVM, "--sid", var networkSID, "--token-file", var networkKey]) |
| 37 | { |
| 38 | using var networkLifetime = new CancellationTokenSource(); |
| 39 | Console.CancelKeyPress += (_, e) => { e.Cancel = true; networkLifetime.Cancel(); }; |
| 40 | NetworkRuntime.Run(Guid.Parse(networkVM), networkSID, networkKey, networkLifetime.Token).GetAwaiter().GetResult(); return 0; |
| 41 | } |
| 42 | if (args is not ["serve", "--vm-id", var vmText, "--sid", var sid, "--token-file", var tokenFile]) throw new InvalidDataException("command_invalid"); |
| 43 | var vm = Guid.Parse(vmText); SessionGuard.Target(vm, sid); GuestContext.VM = vm; GuestContext.SID = sid; |
| 44 | FreeConsole(); |
| 45 | var secret = Pairing.Load(tokenFile, vm, sid, false); |
| 46 | Application.SetHighDpiMode(HighDpiMode.SystemAware); |
| 47 | using var lifetime = new CancellationTokenSource(); |
| 48 | using var agent = new ClipboardAgent(Path.Combine(AppContext.BaseDirectory, "cage-guest-files.exe")); |
| 49 | using var listener = HyperVEndPoint.Socket(); |
| 50 | listener.Bind(new HyperVEndPoint(Protocol.Parent, Protocol.Service)); listener.Listen(64); |
| 51 | GuestDiagnostics.Record("lifecycle", "started"); |
| 52 | Application.ApplicationExit += (_, _) => { lifetime.Cancel(); listener.Dispose(); CryptographicOperations.ZeroMemory(secret); }; |
| 53 | _ = Accept(listener, agent, vm, sid, secret, lifetime.Token); |
| 54 | Application.Run(); return 0; |
| 55 | } |
| 56 | catch (Exception ex) |
| 57 | { |
| 58 | if (args.Length > 0 && args[0] is "serve" or "serve-network") GuestDiagnostics.Failure("startup", ex); |
| 59 | var reason = ex switch |
| 60 | { |
| 61 | SocketException socketError => "socket_" + socketError.NativeErrorCode, |
| 62 | Win32Exception nativeError => "win32_" + nativeError.NativeErrorCode, |
| 63 | _ => ex.GetType().Name |
| 64 | }; |
| 65 | Console.Error.WriteLine("Windows guest channel unavailable (" + Relay.Phase + ":" + reason + "); check the bound VM, GUI login, pairing and deployed tools."); return 1; |
| 66 | } |
| 67 | } |
| 68 | static async Task Accept(Socket listener, ClipboardAgent agent, Guid vm, string sid, byte[] secret, CancellationToken token) |
| 69 | { |
| 70 | using var slots = new SemaphoreSlim(64); |
| 71 | try |
| 72 | { |
| 73 | while (!token.IsCancellationRequested) |
| 74 | { |
| 75 | await slots.WaitAsync(token); |
| 76 | var socket = await Task.Run(listener.Accept, CancellationToken.None).WaitAsync(token); |
| 77 | _ = Task.Run(async () => { try { await Connection(socket, agent, vm, sid, secret, token); } finally { socket.Dispose(); slots.Release(); } }, CancellationToken.None); |
| 78 | } |
| 79 | } |
| 80 | catch (OperationCanceledException) { } |
| 81 | catch (ObjectDisposedException) { } |
| 82 | catch { Application.Exit(); } |
| 83 | } |
| 84 | static JsonObject Status(ClipboardAgent agent, Guid vm, string sid) |
| 85 | { |
| 86 | var status = agent.Hello(); status["vm_id"] = vm.ToString("D"); status["gui_user_sid"] = sid; |
| 87 | status["reason"] = SessionGuard.Available() ? "" : "requires_gui_login"; |
| 88 | status["capabilities"] = JsonSerializer.SerializeToNode(GuestOperations.Capabilities()); |
| 89 | status["setup_account_disabled"] = SetupAccount.Disabled(); |
| 90 | var browser=BrowserRpc.Status();status["browser"]=browser; |
| 91 | status["components"]=WindowsComponentStatus.Snapshot(browser);return status; |
| 92 | } |
| 93 | static async Task Connection(Socket socket, ClipboardAgent agent, Guid vm, string sid, byte[] secret, CancellationToken lifetime) |
| 94 | { |
| 95 | using var network = new NetworkStream(socket, false); |
| 96 | using var stream = new ReadAheadStream(network); |
| 97 | using var handshake = CancellationTokenSource.CreateLinkedTokenSource(lifetime); handshake.CancelAfter(TimeSpan.FromSeconds(10)); |
| 98 | var authenticated = false; var operation = ""; |
| 99 | try |
| 100 | { |
| 101 | var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); |
| 102 | await Protocol.Write(stream, new() { ["nonce"] = nonce, ["vm_id"] = vm.ToString("D"), ["sid"] = sid, ["session"] = agent.Session, |
| 103 | ["proof"] = Protocol.Proof(secret, "server", nonce, vm, sid, agent.Session, "", null) }, handshake.Token); |
| 104 | var request = await Protocol.Read(stream, Protocol.PathLimit + 4096, handshake.Token) ?? throw new EndOfStreamException(); |
| 105 | operation = request["operation"]?.GetValue<string>() ?? ""; |
| 106 | if (!GuestOperations.Names.Contains(operation) || request["vm_id"]?.GetValue<string>() != vm.ToString("D") || request["sid"]?.GetValue<string>() != sid || |
| 107 | !Protocol.EqualProof(Protocol.Proof(secret, "client", nonce, vm, sid, agent.Session, operation, request["paths"]), request["proof"]?.GetValue<string>())) |
| 108 | throw new InvalidDataException("pairing_invalid"); |
| 109 | authenticated = true; |
| 110 | if (operation == "status") { await Protocol.Write(stream, Status(agent, vm, sid), lifetime); return; } |
| 111 | await Protocol.Write(stream, agent.Hello(), lifetime); |
| 112 | if (operation == "diagnostics") { await GuestOperations.Run(operation, stream, lifetime); return; } |
| 113 | if (operation == "stream") { await ClipboardStream(stream, agent, lifetime); return; } |
| 114 | SessionGuard.Assert(); |
| 115 | using var activity = CancellationTokenSource.CreateLinkedTokenSource(lifetime); |
| 116 | var guard = Task.Run(async () => { try { while (true) { await Task.Delay(100, activity.Token); if (!SessionGuard.Available()) { activity.Cancel(); return; } } } catch (OperationCanceledException) { } }); |
| 117 | try |
| 118 | { |
| 119 | if (operation == "import") await agent.Import(stream, activity.Token); |
| 120 | else if (operation == "export") await agent.Export(stream, request["paths"], activity.Token); |
| 121 | else await GuestOperations.Run(operation, stream, activity.Token); |
| 122 | } |
| 123 | finally { activity.Cancel(); await guard; } |
| 124 | } |
| 125 | catch (Exception error) |
| 126 | { |
| 127 | if (authenticated && operation != "diagnostics") GuestDiagnostics.Failure(operation, error); |
| 128 | |
| 129 | |
| 130 | if (authenticated && operation != "export") |
| 131 | try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)); await Protocol.Write(stream, new() { ["error"] = SessionGuard.Available() ? "guest_operation_failed" : "requires_gui_login" }, timeout.Token); } catch { } |
| 132 | } |
| 133 | } |
| 134 | static async Task ClipboardStream(Stream stream, ClipboardAgent agent, CancellationToken lifetime) |
| 135 | { |
| 136 | using var channel = CancellationTokenSource.CreateLinkedTokenSource(lifetime); |
| 137 | var events = await agent.Subscribe(); |
| 138 | var writer = Task.Run(async () => |
| 139 | { |
| 140 | try { await foreach (var message in events.ReadAllAsync(channel.Token)) await Protocol.Write(stream, message, channel.Token); } |
| 141 | finally { channel.Cancel(); } |
| 142 | }); |
| 143 | try |
| 144 | { |
| 145 | while (await Protocol.Read(stream, Protocol.WireLimit, channel.Token) is { } request) |
| 146 | try { await agent.Apply(request); } |
| 147 | catch { await agent.GUI(() => { agent.ReportError(); return true; }); } |
| 148 | } |
| 149 | finally { channel.Cancel(); await agent.Unsubscribe(); try { await writer; } catch (OperationCanceledException) { } } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | internal static class GuestContext |
| 154 | { |
| 155 | internal static Guid VM { get; set; } |
| 156 | internal static string SID { get; set; } = ""; |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | internal sealed class ReadAheadStream(Stream inner) : Stream |
| 162 | { |
| 163 | readonly byte[] buffer = new byte[64 << 10]; int position, count; |
| 164 | internal async Task<byte[]?> Line(int limit, CancellationToken token) |
| 165 | { |
| 166 | using var line = new MemoryStream(); |
| 167 | while (true) |
| 168 | { |
| 169 | if (position == count) |
| 170 | { |
| 171 | count = await inner.ReadAsync(buffer, token); position = 0; |
| 172 | if (count == 0) { if (line.Length == 0) return null; throw new EndOfStreamException(); } |
| 173 | } |
| 174 | var newline = buffer.AsSpan(position, count - position).IndexOf((byte)10); |
| 175 | var n = newline < 0 ? count - position : newline; |
| 176 | if (line.Length + n > limit) throw new InvalidDataException("message_limit"); |
| 177 | line.Write(buffer, position, n); position += n; |
| 178 | if (newline >= 0) { position++; return line.ToArray(); } |
| 179 | } |
| 180 | } |
| 181 | public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; |
| 182 | public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } |
| 183 | public override async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken token = default) |
| 184 | { |
| 185 | if (destination.Length == 0) return 0; |
| 186 | if (position == count) { count = await inner.ReadAsync(buffer, token); position = 0; if (count == 0) return 0; } |
| 187 | var n = Math.Min(destination.Length, count - position); buffer.AsMemory(position, n).CopyTo(destination); position += n; return n; |
| 188 | } |
| 189 | public override int Read(byte[] bytes, int offset, int size) => ReadAsync(bytes.AsMemory(offset, size)).AsTask().GetAwaiter().GetResult(); |
| 190 | public override ValueTask WriteAsync(ReadOnlyMemory<byte> bytes, CancellationToken token = default) => inner.WriteAsync(bytes, token); |
| 191 | public override void Write(byte[] bytes, int offset, int size) => inner.Write(bytes, offset, size); |
| 192 | public override void Flush() => inner.Flush(); public override Task FlushAsync(CancellationToken token) => inner.FlushAsync(token); |
| 193 | public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long length) => throw new NotSupportedException(); |
| 194 | } |