| 1 | using System.Collections.Concurrent; |
| 2 | using System.Diagnostics; |
| 3 | using System.Runtime.CompilerServices; |
| 4 | using System.Security.Principal; |
| 5 | using System.Text.Json.Nodes; |
| 6 | using System.Text.RegularExpressions; |
| 7 | using Microsoft.Win32; |
| 8 | |
| 9 | namespace Cage.GuestClipboard; |
| 10 | |
| 11 | internal static class ProjectRpc |
| 12 | { |
| 13 | private static readonly ConcurrentDictionary<string, Mount> Mounts = new(StringComparer.Ordinal); |
| 14 | private static readonly SemaphoreSlim Slots = new(32, 32); |
| 15 | internal static event Action<string, string>? Revoked; |
| 16 | private static readonly Regex ID = new("^[a-f0-9]{16}$", RegexOptions.CultureInvariant); |
| 17 | private static readonly Regex Grant = new("^[a-f0-9]{64}$", RegexOptions.CultureInvariant); |
| 18 | private static readonly Regex Probe = new("^\\.cage-mount-probe-[A-Za-z0-9_-]{1,100}$", RegexOptions.CultureInvariant); |
| 19 | [ModuleInitializer] |
| 20 | internal static void Register() { if (ToolsPresent()) GuestOperations.Register("project-mount", Run); } |
| 21 | internal static bool ToolsPresent() |
| 22 | { |
| 23 | try |
| 24 | { |
| 25 | using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); |
| 26 | using var key = registry.OpenSubKey(@"SOFTWARE\WinFsp"); |
| 27 | var install = key?.GetValue("InstallDir") as string; |
| 28 | return install is not null && File.Exists(Path.Combine(install, "bin", "winfsp-x64.dll")) && |
| 29 | File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "SSHFS-Win", "bin", "sshfs-win.exe")); |
| 30 | } |
| 31 | catch { return false; } |
| 32 | } |
| 33 | internal static string Resolve(string id, string grant) |
| 34 | { |
| 35 | if (!ID.IsMatch(id) || !Grant.IsMatch(grant) || !Mounts.TryGetValue(id, out var mount) || |
| 36 | mount.Grant != grant || !mount.Ready || mount.Child.HasExited || mount.Lifetime.IsCancellationRequested) |
| 37 | throw new InvalidDataException("project_grant_unavailable"); |
| 38 | return mount.Path; |
| 39 | } |
| 40 | internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) |
| 41 | { |
| 42 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 43 | var value = await Protocol.Read(stream, 16384, token) ?? throw new EndOfStreamException(); |
| 44 | var id = value["id"]?.GetValue<string>() ?? ""; |
| 45 | var grant = value["grant"]?.GetValue<string>() ?? ""; |
| 46 | if (!ID.IsMatch(id) || !Grant.IsMatch(grant)) throw new InvalidDataException("project_grant_invalid"); |
| 47 | switch (value["action"]?.GetValue<string>()) |
| 48 | { |
| 49 | case "mount": await Start(stream, id, grant, token, available); break; |
| 50 | case "probe": |
| 51 | if (!Mounts.TryGetValue(id, out var mount) || mount.Grant != grant || mount.Child.HasExited) |
| 52 | throw new InvalidDataException("project_grant_unavailable"); |
| 53 | var name = value["probe_name"]?.GetValue<string>() ?? ""; |
| 54 | if (!Probe.IsMatch(name)) throw new InvalidDataException("project_probe_invalid"); |
| 55 | try |
| 56 | { |
| 57 | using var file = File.OpenRead(Path.Combine(mount.Path, name)); |
| 58 | if (file.Length is < 1 or > 4096) throw new InvalidDataException("project_probe_invalid"); |
| 59 | using var reader = new StreamReader(file, Protocol.Utf8); |
| 60 | var proof = await reader.ReadToEndAsync(token); |
| 61 | if (!available() || mount.Lifetime.IsCancellationRequested || mount.Child.HasExited) throw new InvalidDataException("requires_gui_login"); |
| 62 | mount.Ready = true; |
| 63 | await Protocol.Write(stream, new() { ["mounted"] = true, ["id"] = id, ["path"] = mount.Path, ["proof"] = proof }, token); |
| 64 | } |
| 65 | catch (IOException) { await Protocol.Write(stream, new() { ["mounted"] = false }, token); } |
| 66 | break; |
| 67 | case "unmount": |
| 68 | if (!Mounts.TryGetValue(id, out var selected) || selected.Grant != grant) throw new InvalidDataException("project_grant_unavailable"); |
| 69 | Revoke(id, selected); |
| 70 | selected.Lifetime.Cancel(); |
| 71 | await selected.Done.Task.WaitAsync(token); |
| 72 | await Protocol.Write(stream, new() { ["unmounted"] = true }, token); break; |
| 73 | default: throw new InvalidDataException("project_operation_invalid"); |
| 74 | } |
| 75 | } |
| 76 | private static async Task Start(Stream stream, string id, string grant, CancellationToken token, Func<bool> available) |
| 77 | { |
| 78 | if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("project_limit"); |
| 79 | try { await StartCore(stream, id, grant, token, available); } finally { Slots.Release(); } |
| 80 | } |
| 81 | private static async Task StartCore(Stream stream, string id, string grant, CancellationToken token, Func<bool> available) |
| 82 | { |
| 83 | if (Mounts.TryGetValue(id, out var previous)) |
| 84 | { |
| 85 | if (previous.Grant == grant) throw new InvalidDataException("project_mount_busy"); |
| 86 | Revoke(id, previous); previous.Lifetime.Cancel(); |
| 87 | await previous.Done.Task.WaitAsync(token); |
| 88 | } |
| 89 | var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 90 | using var identity = WindowsIdentity.GetCurrent(); |
| 91 | var parent = Path.Combine(home, "Cage", "Projects"); |
| 92 | foreach (var directory in new[] { Path.Combine(home, "Cage"), parent }) |
| 93 | { |
| 94 | Directory.CreateDirectory(directory); |
| 95 | var info = new DirectoryInfo(directory); |
| 96 | if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != identity.User?.Value) |
| 97 | throw new InvalidDataException("project_mount_parent_invalid"); |
| 98 | } |
| 99 | var path = Path.Combine(parent, id); |
| 100 | |
| 101 | if (Path.Exists(path)) throw new InvalidDataException("project_mount_path_exists"); |
| 102 | var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "SSHFS-Win", "bin", "sshfs-win.exe"); |
| 103 | if (!File.Exists(executable)) throw new InvalidDataException("project_tools_missing"); |
| 104 | var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; |
| 105 | foreach (var arg in new[] { "cmd", ":/", CygwinPath(path), "-f", "-o", "slave,uid=-1,gid=-1,cache=no,nodev,nosuid" }) start.ArgumentList.Add(arg); |
| 106 | using var child = new Process { StartInfo = start }; |
| 107 | using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(token); |
| 108 | var mount = new Mount(grant, path, child, lifetime); |
| 109 | if (!Mounts.TryAdd(id, mount)) throw new InvalidDataException("project_mount_busy"); |
| 110 | Task? input = null, output = null, stderr = null, exited = null; |
| 111 | try |
| 112 | { |
| 113 | if (!available() || !child.Start()) throw new InvalidDataException("requires_gui_login"); |
| 114 | using var stop = lifetime.Token.Register(() => { try { child.Kill(true); } catch { } }); |
| 115 | await Protocol.Write(stream, new() { ["started"] = true, ["id"] = id, ["path"] = path }, lifetime.Token); |
| 116 | input = stream.CopyToAsync(child.StandardInput.BaseStream, lifetime.Token); |
| 117 | output = child.StandardOutput.BaseStream.CopyToAsync(stream, lifetime.Token); |
| 118 | stderr = child.StandardError.BaseStream.CopyToAsync(Stream.Null, lifetime.Token); |
| 119 | exited = child.WaitForExitAsync(lifetime.Token); |
| 120 | await Task.WhenAny(input, output, exited); |
| 121 | } |
| 122 | finally |
| 123 | { |
| 124 | Revoke(id, mount); |
| 125 | lifetime.Cancel(); |
| 126 | try { child.StandardInput.Close(); } catch { } |
| 127 | try { if (!child.HasExited) child.Kill(true); await child.WaitForExitAsync(); } catch { } |
| 128 | foreach (var task in new[] { input, output, stderr, exited }) if (task is not null) try { await task; } catch { } |
| 129 | mount.Done.TrySetResult(); |
| 130 | } |
| 131 | } |
| 132 | private static void Revoke(string id, Mount mount) |
| 133 | { |
| 134 | mount.Ready = false; |
| 135 | if (!((ICollection<KeyValuePair<string, Mount>>)Mounts).Remove(new(id, mount))) return; |
| 136 | if (Revoked is { } handlers) |
| 137 | foreach (Action<string, string> handler in handlers.GetInvocationList()) |
| 138 | try { handler(id, mount.Grant); } catch { } |
| 139 | } |
| 140 | private static string CygwinPath(string path) |
| 141 | { |
| 142 | if (path.Length < 4 || !char.IsAsciiLetter(path[0]) || path[1] != ':' || path[2] != '\\') throw new InvalidDataException("project_mount_path_invalid"); |
| 143 | return "/cygdrive/" + char.ToLowerInvariant(path[0]) + path[2..].Replace('\\', '/'); |
| 144 | } |
| 145 | private sealed class Mount(string grant, string path, Process child, CancellationTokenSource lifetime) |
| 146 | { |
| 147 | internal string Grant { get; } = grant; |
| 148 | internal string Path { get; } = path; |
| 149 | internal Process Child { get; } = child; |
| 150 | internal CancellationTokenSource Lifetime { get; } = lifetime; |
| 151 | internal readonly TaskCompletionSource Done = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 152 | internal volatile bool Ready; |
| 153 | } |
| 154 | } |