| 1 | using System.Runtime.CompilerServices; |
| 2 | using System.Collections.Concurrent; |
| 3 | using System.Security.AccessControl; |
| 4 | using System.Security.Principal; |
| 5 | using System.Text.Json.Nodes; |
| 6 | |
| 7 | namespace Cage.GuestClipboard; |
| 8 | |
| 9 | |
| 10 | |
| 11 | internal static class AttachmentsRpc |
| 12 | { |
| 13 | private static readonly SemaphoreSlim Slots = new(12, 12); |
| 14 | private sealed record Batch(string Directory, string Target, string Kind, double X, double Y) |
| 15 | { |
| 16 | internal readonly List<string> Paths = []; |
| 17 | internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow; |
| 18 | internal readonly long Epoch = ClipboardAgent.Current?.SessionEpoch ?? 0; |
| 19 | internal bool Receiving; |
| 20 | internal Action? AssertChooser; |
| 21 | } |
| 22 | private static readonly ConcurrentDictionary<string, Batch> Batches = new(); |
| 23 | internal const long FileLimit = 2L << 30; |
| 24 | [ModuleInitializer] internal static void Register() => GuestOperations.Register("attachments", Run); |
| 25 | internal static bool NameValid(string name) => name.Length is > 0 and <= 255 && name is not "." and not ".." && |
| 26 | !name.EndsWith(' ') && !name.EndsWith('.') && name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && |
| 27 | !new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }.Contains(name.Split('.')[0], StringComparer.OrdinalIgnoreCase); |
| 28 | internal static string NewDirectory() |
| 29 | { |
| 30 | var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 31 | using var identity = WindowsIdentity.GetCurrent(); |
| 32 | var parent = Path.Combine(home, "Cage", "Attachments"); |
| 33 | var directory = Path.Combine(parent, Guid.NewGuid().ToString("N")); |
| 34 | foreach (var path in new[] { Path.Combine(home, "Cage"), parent, directory }) |
| 35 | { |
| 36 | Directory.CreateDirectory(path); |
| 37 | var info = new DirectoryInfo(path); |
| 38 | if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != identity.User?.Value) |
| 39 | throw new InvalidDataException("attachment_directory_invalid"); |
| 40 | } |
| 41 | return directory; |
| 42 | } |
| 43 | internal static JsonObject StartBatch(string target, string kind, double x, double y) |
| 44 | { |
| 45 | foreach(var pair in Batches.Where(pair=>DateTimeOffset.UtcNow-pair.Value.Created>TimeSpan.FromMinutes(30))) CancelBatch(pair.Key); |
| 46 | if(Batches.Count>=12 || kind is not ("paste" or "drop" or "image") || kind=="drop" && (!double.IsFinite(x) || !double.IsFinite(y) || x<0 || x>1 || y<0 || y>1))throw new InvalidDataException("attachment_request_invalid"); |
| 47 | var id=Guid.NewGuid().ToString("D"); var batch=new Batch(NewDirectory(),target,kind,x,y); |
| 48 | if(!Batches.TryAdd(id,batch))throw new InvalidDataException("attachment_request_invalid"); |
| 49 | return new JsonObject { ["ok"]=true,["id"]=id }; |
| 50 | } |
| 51 | |
| 52 | |
| 53 | internal static JsonObject StartChooserBatch(string target,Action assertChooser) |
| 54 | { |
| 55 | assertChooser(); |
| 56 | foreach(var pair in Batches.Where(pair=>DateTimeOffset.UtcNow-pair.Value.Created>TimeSpan.FromMinutes(30)))CancelBatch(pair.Key); |
| 57 | if(Batches.Count>=12)throw new InvalidDataException("attachment_request_limit"); |
| 58 | var id=Guid.NewGuid().ToString("D");var batch=new Batch(NewDirectory(),target,"chooser",0,0){AssertChooser=assertChooser}; |
| 59 | if(!Batches.TryAdd(id,batch))throw new InvalidDataException("attachment_request_invalid"); |
| 60 | try{assertChooser();return new JsonObject{["ok"]=true,["id"]=id};}catch{CancelBatch(id);throw;} |
| 61 | } |
| 62 | internal static void CancelBatch(string id) |
| 63 | { |
| 64 | if(!Batches.TryRemove(id,out var batch))return; |
| 65 | lock(batch) { if(!batch.Receiving) try { Directory.Delete(batch.Directory,true); } catch { } } |
| 66 | } |
| 67 | internal static async Task FinishBatch(string id, Func<string,string,string[],double,double,Task> deliver) |
| 68 | { |
| 69 | if(!Batches.TryGetValue(id,out var batch))throw new InvalidDataException("attachment_request_invalid"); |
| 70 | string[] paths; |
| 71 | lock(batch) { if(batch.Receiving || batch.Paths.Count==0 || batch.Epoch!=ClipboardAgent.Current?.SessionEpoch)throw new InvalidDataException("attachment_incomplete");batch.AssertChooser?.Invoke(); batch.Receiving=true;paths=batch.Paths.ToArray(); } |
| 72 | try |
| 73 | { |
| 74 | await deliver(batch.Target,batch.Kind,paths,batch.X,batch.Y); |
| 75 | Batches.TryRemove(id,out _); |
| 76 | if(batch.Kind=="image")Directory.Delete(batch.Directory,true); |
| 77 | } |
| 78 | finally { lock(batch)batch.Receiving=false; } |
| 79 | } |
| 80 | private static async Task Run(Stream stream, CancellationToken token, Func<bool> available) |
| 81 | { |
| 82 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 83 | if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("attachment_limit"); |
| 84 | string? directory = null; bool completed = false, ownsReceiving=false; Batch? batch=null; |
| 85 | try |
| 86 | { |
| 87 | var request = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException(); |
| 88 | var name = request["name"]?.GetValue<string>() ?? ""; |
| 89 | if (request["action"]?.GetValue<string>() != "save" || !NameValid(name)) throw new InvalidDataException("attachment_request_invalid"); |
| 90 | var id=request["id"]?.GetValue<string>(); |
| 91 | if(id!=null) |
| 92 | { |
| 93 | if(!Batches.TryGetValue(id,out batch))throw new InvalidDataException("attachment_request_invalid"); |
| 94 | lock(batch) { if(batch.Receiving || batch.Paths.Count>=100)throw new InvalidDataException("attachment_limit");batch.AssertChooser?.Invoke();batch.Receiving=true;ownsReceiving=true; } |
| 95 | directory=batch.Directory; |
| 96 | } |
| 97 | else directory = NewDirectory(); |
| 98 | var fileDirectory=directory; |
| 99 | if(batch?.Kind=="chooser") |
| 100 | { |
| 101 | |
| 102 | |
| 103 | |
| 104 | fileDirectory=Path.Combine(directory,Guid.NewGuid().ToString("N")); |
| 105 | Directory.CreateDirectory(fileDirectory); |
| 106 | using var identity=WindowsIdentity.GetCurrent();var info=new DirectoryInfo(fileDirectory); |
| 107 | if(info.Attributes.HasFlag(FileAttributes.ReparsePoint)||info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value!=identity.User?.Value) |
| 108 | throw new InvalidDataException("attachment_directory_invalid"); |
| 109 | batch.AssertChooser?.Invoke(); |
| 110 | } |
| 111 | var path = Path.Combine(fileDirectory, name); |
| 112 | await using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 << 10, FileOptions.Asynchronous)) |
| 113 | { |
| 114 | using var bounded = new LimitedWriteStream(file, FileLimit); |
| 115 | await Protocol.ReceiveFrames(stream, bounded, token); |
| 116 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 117 | await file.FlushAsync(token); file.Flush(true); |
| 118 | batch?.AssertChooser?.Invoke(); |
| 119 | } |
| 120 | if(batch!=null) |
| 121 | { |
| 122 | if(!Batches.TryGetValue(id!,out var current) || !ReferenceEquals(batch,current))throw new InvalidDataException("attachment_cancelled"); |
| 123 | lock(batch)batch.Paths.Add(path); |
| 124 | } |
| 125 | await Protocol.Write(stream, new JsonObject { ["ok"] = true, ["scope"] = "attachments", ["path"] = path }, token); |
| 126 | completed = true; |
| 127 | } |
| 128 | finally |
| 129 | { |
| 130 | |
| 131 | |
| 132 | if(ownsReceiving && batch!=null)lock(batch)batch.Receiving=false; |
| 133 | var cancelled=ownsReceiving && batch!=null && !Batches.Values.Any(current=>ReferenceEquals(current,batch)); |
| 134 | if ((!completed || cancelled) && directory != null) |
| 135 | { |
| 136 | foreach(var pair in Batches.Where(pair=>ReferenceEquals(pair.Value,batch)))Batches.TryRemove(pair.Key,out _); |
| 137 | try { Directory.Delete(directory, true); } catch { } |
| 138 | } |
| 139 | Slots.Release(); |
| 140 | } |
| 141 | } |
| 142 | internal sealed class LimitedWriteStream(Stream inner, long limit) : Stream |
| 143 | { |
| 144 | private long written; |
| 145 | public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; |
| 146 | public override long Length => written; public override long Position { get => written; set => throw new NotSupportedException(); } |
| 147 | public override void Flush() => inner.Flush(); |
| 148 | public override Task FlushAsync(CancellationToken token) => inner.FlushAsync(token); |
| 149 | public override void Write(byte[] buffer, int offset, int count) { Check(count); inner.Write(buffer, offset, count); } |
| 150 | public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default) { Check(buffer.Length); await inner.WriteAsync(buffer, token); } |
| 151 | private void Check(int count) { if (count < 0 || written > limit - count) throw new InvalidDataException("attachment_size_limit"); written += count; } |
| 152 | public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); |
| 153 | public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); |
| 154 | public override void SetLength(long value) => throw new NotSupportedException(); |
| 155 | } |
| 156 | } |