| 1 | using System.Buffers.Binary; |
| 2 | using System.Security.Cryptography; |
| 3 | using System.Runtime.InteropServices; |
| 4 | using System.Text.Json.Nodes; |
| 5 | |
| 6 | namespace Cage.GuestClipboard; |
| 7 | |
| 8 | internal static class SelfTest |
| 9 | { |
| 10 | static void Assert(bool value) { if (!value) throw new Exception("self_test_failed"); } |
| 11 | static void Reject(Action action) { try { action(); } catch { return; } throw new Exception("self_test_failed"); } |
| 12 | internal static void Run() |
| 13 | { |
| 14 | ReceiptPublication(); |
| 15 | var driver = Path.Combine(AppContext.BaseDirectory, "wintun.dll"); |
| 16 | if (File.Exists(driver)) |
| 17 | { |
| 18 | var library = NativeLibrary.Load(driver); |
| 19 | try |
| 20 | { |
| 21 | foreach (var symbol in new[] { "WintunCreateAdapter", "WintunCloseAdapter", "WintunGetAdapterLUID", "WintunStartSession", "WintunEndSession", "WintunReceivePacket", "WintunReleaseReceivePacket", "WintunAllocateSendPacket", "WintunSendPacket" }) |
| 22 | Assert(NativeLibrary.GetExport(library, symbol) != IntPtr.Zero); |
| 23 | } |
| 24 | finally { NativeLibrary.Free(library); } |
| 25 | } |
| 26 | var vm = Guid.NewGuid(); var endpoint = new HyperVEndPoint(vm, Protocol.Service); |
| 27 | Assert(WindowsSystemSettings.BrowserLanguage(new JsonObject { ["locale"]="zh_CN.UTF-8",["browser_language"]="en-GB" })=="en-GB"); |
| 28 | Reject(()=>WindowsSystemSettings.BrowserLanguage(new JsonObject { ["browser_language"]="en-US';exit" })); |
| 29 | Reject(()=>WindowsSystemSettings.BrowserLanguage(new JsonObject { ["locale"]="en_US.UTF-8" })); |
| 30 | Assert(NativeSafetyRpc.ObservedTimezone("China Standard Time","Asia/Hong_Kong")=="Asia/Hong_Kong"); |
| 31 | Assert(NativeSafetyRpc.ObservedTimezone("China Standard Time","America/New_York")!="America/New_York"); |
| 32 | var publicHello = Protocol.PublicHello(new JsonObject { ["version"] = 1, ["os"] = "windows", ["available"] = true }); |
| 33 | Assert(publicHello["hello"]?["os"]?.GetValue<string>() == "windows" && !publicHello.ContainsKey("version")); |
| 34 | using var native = HyperVEndPoint.Socket(); |
| 35 | var roundtrip = (HyperVEndPoint)endpoint.Create(endpoint.Serialize()); Assert(roundtrip.VM == vm && roundtrip.Service == Protocol.Service && endpoint.Serialize().Size == 36); |
| 36 | var secret = RandomNumberGenerator.GetBytes(32); var sid = "S-1-5-21-1-2-3-1001"; |
| 37 | var proof = Protocol.Proof(secret, "server", "nonce", vm, sid, "session", "", null); |
| 38 | Assert(Protocol.EqualProof(proof, proof)); Assert(!Protocol.EqualProof(proof, "invalid")); |
| 39 | Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "", null))); |
| 40 | Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "server", "nonce", Guid.NewGuid(), sid, "session", "", null))); |
| 41 | Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "server", "nonce", vm, sid + "2", "session", "", null))); |
| 42 | var selection = new JsonArray(@"C:\test\中文😀.txt"); |
| 43 | var first = Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "export", selection); |
| 44 | Assert(!Protocol.EqualProof(first, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "import", selection))); |
| 45 | Assert(!Protocol.EqualProof(first, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "export", new JsonArray(@"C:\other.txt")))); |
| 46 | Reject(() => Protocol.Paths(new JsonArray())); Reject(() => Protocol.Paths(new JsonArray("relative.txt"))); |
| 47 | Assert(Protocol.Paths(selection).Length == 1); |
| 48 | var image = new byte[33]; new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }.CopyTo(image, 0); "IHDR"u8.CopyTo(image.AsSpan(12)); |
| 49 | BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(16, 4), 8000); BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(20, 4), 5000); Protocol.Png(image); |
| 50 | BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(20, 4), 5001); Reject(() => Protocol.Png(image)); |
| 51 | var data = RandomNumberGenerator.GetBytes(200_000); using var encoded = new MemoryStream(); |
| 52 | Protocol.SendFrames(new MemoryStream(data), encoded, default).GetAwaiter().GetResult(); |
| 53 | encoded.Position = 0; using var decoded = new MemoryStream(); Protocol.ReceiveFrames(encoded, decoded, default).GetAwaiter().GetResult(); Assert(data.SequenceEqual(decoded.ToArray())); |
| 54 | Reject(() => Protocol.ReceiveFrames(new MemoryStream(encoded.ToArray()[..^1]), Stream.Null, default).GetAwaiter().GetResult()); |
| 55 | Assert(AttachmentsRpc.NameValid("中文 O'Brien.txt")); |
| 56 | foreach (var name in new[] { "../outside.txt", "CON.txt", "file.txt:stream", "trailing.", "C:\\private.txt", "bad\nname" }) Assert(!AttachmentsRpc.NameValid(name)); |
| 57 | using (var limited = new AttachmentsRpc.LimitedWriteStream(Stream.Null, 3)) |
| 58 | { limited.Write([1, 2, 3], 0, 3); Reject(() => limited.Write([4], 0, 1)); } |
| 59 | using var json = new ReadAheadStream(new MemoryStream("{\"text\":\"中文😀\\nsecond\"}\n{\"ack\":2}\n"u8.ToArray())); |
| 60 | Assert(Protocol.Read(json, 1024, default).GetAwaiter().GetResult()!["text"]!.GetValue<string>() == "中文😀\nsecond"); |
| 61 | Assert(Protocol.Read(json, 1024, default).GetAwaiter().GetResult()!["ack"]!.GetValue<int>() == 2); |
| 62 | using var blank=new Bitmap(240,240); |
| 63 | using(var paint=Graphics.FromImage(blank)){paint.Clear(Color.White);paint.FillRectangle(Brushes.Black,210,0,25,16);} |
| 64 | Assert(!ClaudeGraphicsCapture.HasContent(blank)); |
| 65 | using(var paint=Graphics.FromImage(blank)){paint.FillRectangle(Brushes.Black,70,110,100,30);} |
| 66 | Assert(ClaudeGraphicsCapture.HasContent(blank)); |
| 67 | var browserFrame = new JsonObject { ["jpeg"] = "page-pixels", ["target"] = "native-window", ["sequence"] = "cdp-first", ["width"] = 800, ["height"] = 600 }; |
| 68 | var published = BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), null); |
| 69 | var sequence = published["sequence"]!.GetValue<string>(); |
| 70 | Assert(published["target"]!.GetValue<string>() == "native-window"); |
| 71 | browserFrame["sequence"] = "cdp-next"; |
| 72 | Assert(BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), sequence)["unchanged"]?.GetValue<bool>() == true); |
| 73 | browserFrame["overlays"] = new JsonArray(new JsonObject { ["png"] = "native-menu-pixels", ["x"] = 20, ["y"] = 30, ["width"] = 50, ["height"] = 60 }); |
| 74 | var menu = BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), sequence); |
| 75 | Assert(menu["unchanged"] is null && menu["sequence"]!.GetValue<string>() != sequence); |
| 76 | var withoutMenu = (JsonObject)browserFrame.DeepClone(); withoutMenu.Remove("overlays"); |
| 77 | Assert(BrowserWindowCapture.FrameReply(withoutMenu, menu["sequence"]!.GetValue<string>())["unchanged"] is null); |
| 78 | browserFrame["target"] = "resized-native-window"; |
| 79 | Assert(BrowserWindowCapture.FrameReply(browserFrame, menu["sequence"]!.GetValue<string>())["unchanged"] is null); |
| 80 | CryptographicOperations.ZeroMemory(secret); |
| 81 | } |
| 82 | |
| 83 | private static void ReceiptPublication() |
| 84 | { |
| 85 | var directory=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); |
| 86 | Directory.CreateDirectory(directory); |
| 87 | var destination=Path.Combine(directory,"receipt.json");var stage=Path.Combine(directory,"receipt.stage"); |
| 88 | try |
| 89 | { |
| 90 | File.WriteAllText(destination,"old-complete"); |
| 91 | using(var snapshot=new FileStream(destination,FileMode.Open,FileAccess.Read,FileShare.Read|FileShare.Delete)) |
| 92 | { |
| 93 | NetworkRuntime.PublishReceipt(stage,destination,"new-complete",default).GetAwaiter().GetResult(); |
| 94 | using var reader=new StreamReader(snapshot); |
| 95 | Assert(reader.ReadToEnd()=="old-complete" && File.ReadAllText(destination)=="new-complete"); |
| 96 | } |
| 97 | using(var blocker=File.OpenRead(destination)) |
| 98 | { |
| 99 | var release=Task.Run(async()=>{await Task.Delay(100);blocker.Dispose();}); |
| 100 | try { NetworkRuntime.PublishReceipt(stage,destination,"after-short-reader",default).GetAwaiter().GetResult(); } |
| 101 | finally { release.GetAwaiter().GetResult(); } |
| 102 | } |
| 103 | Assert(File.ReadAllText(destination)=="after-short-reader"); |
| 104 | using(var blocker=File.OpenRead(destination)) |
| 105 | Reject(()=>NetworkRuntime.PublishReceipt(stage,destination,"must-not-publish",default).GetAwaiter().GetResult()); |
| 106 | Assert(File.ReadAllText(destination)=="after-short-reader"); |
| 107 | } |
| 108 | finally { Directory.Delete(directory,true); } |
| 109 | } |
| 110 | } |