| 1 | using System.Diagnostics; |
| 2 | using System.Text.Json.Nodes; |
| 3 | using System.Text.RegularExpressions; |
| 4 | using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease; |
| 5 | |
| 6 | namespace Cage.GuestClipboard; |
| 7 | |
| 8 | |
| 9 | |
| 10 | internal static class WindowsPhoneBrowser |
| 11 | { |
| 12 | private static readonly SemaphoreSlim Gate = new(1, 1); |
| 13 | private static readonly Dictionary<InputLease, string> Owners = new(); |
| 14 | private static readonly Regex ID = new("^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", RegexOptions.CultureInvariant); |
| 15 | private static Process? process; |
| 16 | private static GuestProcessJob? job; |
| 17 | private static Stream? replies; |
| 18 | private static string current = ""; |
| 19 | internal static bool Installed() => BrowserRpc.BrowserExecutableInstalled() && new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "windows-phone-browser.mjs", "playwright/index.mjs", "modules/browser-phone.mjs", "modules/browser-phone-network.mjs" } |
| 20 | .All(file => File.Exists(Path.Combine(AppContext.BaseDirectory, file))); |
| 21 | |
| 22 | private static JsonObject Error(int status) => new() { ["error"] = "phone_browser_unavailable", ["code"] = "phone_browser_error", ["status"] = status }; |
| 23 | internal static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, InputLease owner) |
| 24 | { |
| 25 | await Gate.WaitAsync(connection); |
| 26 | try |
| 27 | { |
| 28 | var route = request["path"]?.GetValue<string>() ?? ""; |
| 29 | var input = request["input"] as JsonObject ?? new JsonObject(); |
| 30 | var id = input["id"]?.GetValue<string>() ?? ""; |
| 31 | if (!ID.IsMatch(id)) return Error(400); |
| 32 | if (route != "/phone-browser/open" && current != id) return Error(410); |
| 33 | using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35)); |
| 34 | if (route == "/phone-browser/open") |
| 35 | { |
| 36 | if (!Installed()) return Error(501); |
| 37 | var settings = await BrowserRpc.ReadConfiguration(timeout.Token, packetOnly: true); |
| 38 | await Start(settings, timeout.Token); |
| 39 | } |
| 40 | if (process is not { HasExited: false }) return Error(410); |
| 41 | var result = await Control(request, timeout.Token); |
| 42 | if (result["error"] is null && route == "/phone-browser/open") { current = id; Owners[owner] = id; } |
| 43 | if (result["error"] is null && route == "/phone-browser/close") { current = ""; foreach (var key in Owners.Where(p => p.Value == id).Select(p => p.Key).ToArray()) Owners.Remove(key); } |
| 44 | return result; |
| 45 | } |
| 46 | catch (InvalidDataException) { return Error(503); } |
| 47 | catch (Exception error) when (error is OperationCanceledException or EndOfStreamException or IOException) |
| 48 | { Close(); return Error(503); } |
| 49 | finally { Gate.Release(); } |
| 50 | } |
| 51 | internal static async Task Release(InputLease owner) |
| 52 | { |
| 53 | await Gate.WaitAsync(); |
| 54 | try |
| 55 | { |
| 56 | if (!Owners.Remove(owner, out var id) || Owners.Values.Contains(id) || current != id) return; |
| 57 | try |
| 58 | { |
| 59 | using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); |
| 60 | await Control(new JsonObject { ["method"] = "POST", ["path"] = "/phone-browser/close", ["input"] = new JsonObject { ["id"] = id } }, timeout.Token); |
| 61 | current = ""; |
| 62 | } |
| 63 | catch { Close(); } |
| 64 | } |
| 65 | finally { Gate.Release(); } |
| 66 | } |
| 67 | private static async Task Start(JsonObject settings, CancellationToken token) |
| 68 | { |
| 69 | if (process is { HasExited: false }) return; |
| 70 | Close(); |
| 71 | var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "node.exe")) |
| 72 | { |
| 73 | UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = AppContext.BaseDirectory, |
| 74 | RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, |
| 75 | StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8, |
| 76 | }; |
| 77 | start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "windows-phone-browser.mjs")); |
| 78 | process = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable"); |
| 79 | try |
| 80 | { |
| 81 | job = new GuestProcessJob(process); |
| 82 | replies = new ReadAheadStream(process.StandardOutput.BaseStream); |
| 83 | var source = process.StandardError; |
| 84 | _ = Task.Run(async () => { try { var buffer = new char[4096]; while (await source.ReadAsync(buffer) != 0) { } } catch (ObjectDisposedException) { } }); |
| 85 | var result = await Control(new JsonObject { ["operation"] = "configure", ["input"] = settings }, token); |
| 86 | if (result["ok"]?.GetValue<bool>() != true) throw new InvalidDataException("browser_unavailable"); |
| 87 | } |
| 88 | catch { Close(); throw; } |
| 89 | } |
| 90 | private static async Task<JsonObject> Control(JsonObject input, CancellationToken token) |
| 91 | { |
| 92 | await Protocol.Write(process!.StandardInput.BaseStream, input, token); |
| 93 | return await Protocol.Read(replies!, 3 << 20, token) ?? throw new EndOfStreamException(); |
| 94 | } |
| 95 | internal static void Close() |
| 96 | { |
| 97 | var owned = Interlocked.Exchange(ref process, null); current = ""; Owners.Clear(); |
| 98 | try { if (owned is not null) { owned.StandardInput.Close(); if (!owned.WaitForExit(3000)) owned.Kill(true); owned.WaitForExit(2000); } } |
| 99 | catch (InvalidOperationException) { } |
| 100 | finally { job?.Dispose(); job = null; replies?.Dispose(); replies = null; owned?.Dispose(); } |
| 101 | |
| 102 | } |
| 103 | } |