| 1 | using System.Diagnostics; |
| 2 | using System.Collections.Concurrent; |
| 3 | using System.IO; |
| 4 | using System.Runtime.InteropServices; |
| 5 | using System.Security.Cryptography; |
| 6 | using System.Text; |
| 7 | |
| 8 | namespace Cage.GuestClipboard; |
| 9 | |
| 10 | |
| 11 | |
| 12 | internal static class WindowsFileDialogNative |
| 13 | { |
| 14 | internal sealed record Owner(int PID,long Started,int Session,IntPtr Window,string Executable,Func<Process,bool> Authorized) |
| 15 | { |
| 16 | internal void Assert() |
| 17 | { |
| 18 | using var process=Process.GetProcessById(PID); |
| 19 | if(process.HasExited||process.StartTime.ToUniversalTime().Ticks!=Started||process.SessionId!=Session|| |
| 20 | !string.Equals(process.MainModule?.FileName,Executable,StringComparison.OrdinalIgnoreCase)||!Authorized(process)|| |
| 21 | !IsWindowVisible(Window)||GetWindowThreadProcessId(Window,out var pid)==0||pid!=PID) |
| 22 | throw new InvalidDataException("file_dialog_owner_changed"); |
| 23 | } |
| 24 | } |
| 25 | private static readonly string Property="Cage.FileDialog."+Guid.NewGuid().ToString("N"); |
| 26 | private static readonly ConcurrentDictionary<IntPtr,Observer> Observers=new(); |
| 27 | [UnmanagedFunctionPointer(CallingConvention.Winapi)] |
| 28 | [return: MarshalAs(UnmanagedType.Bool)] |
| 29 | private delegate bool WindowCallback(IntPtr window, IntPtr parameter); |
| 30 | [DllImport("user32.dll")] |
| 31 | [return: MarshalAs(UnmanagedType.Bool)] |
| 32 | private static extern bool EnumWindows(WindowCallback callback,IntPtr parameter); |
| 33 | [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window); |
| 34 | [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid); |
| 35 | [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr window,uint kind); |
| 36 | [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); |
| 37 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern int GetClassNameW(IntPtr window,StringBuilder value,int length); |
| 38 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] private static extern bool SetPropW(IntPtr window,string name,IntPtr value); |
| 39 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr GetPropW(IntPtr window,string name); |
| 40 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr RemovePropW(IntPtr window,string name); |
| 41 | [DllImport("user32.dll")] internal static extern int GetDlgCtrlID(IntPtr window); |
| 42 | [DllImport("user32.dll")] internal static extern bool IsChild(IntPtr parent,IntPtr child); |
| 43 | [DllImport("user32.dll")] private static extern IntPtr GetDlgItem(IntPtr dialog,int id); |
| 44 | [DllImport("user32.dll")] private static extern bool IsWindowEnabled(IntPtr window); |
| 45 | [DllImport("user32.dll",ExactSpelling=true)] private static extern bool PostMessageW(IntPtr window,uint message,IntPtr parameter,IntPtr data); |
| 46 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,string data,uint flags,uint timeout,out IntPtr result); |
| 47 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,StringBuilder data,uint flags,uint timeout,out IntPtr result); |
| 48 | [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,IntPtr data,uint flags,uint timeout,out IntPtr result); |
| 49 | private delegate void EventCallback(IntPtr hook,uint kind,IntPtr window,int objectID,int childID,uint thread,uint time); |
| 50 | [DllImport("user32.dll")] private static extern IntPtr SetWinEventHook(uint first,uint last,IntPtr module,EventCallback callback,uint process,uint thread,uint flags); |
| 51 | [DllImport("user32.dll")] private static extern bool UnhookWinEvent(IntPtr hook); |
| 52 | |
| 53 | |
| 54 | internal sealed class Observer : IDisposable |
| 55 | { |
| 56 | private IntPtr hook; |
| 57 | private readonly EventCallback callback; |
| 58 | private readonly int thread=Environment.CurrentManagedThreadId; |
| 59 | internal Observer(Owner owner,Action<IntPtr> destroyed) |
| 60 | { |
| 61 | owner.Assert(); |
| 62 | callback=(_,kind,window,objectID,childID,_,_)=>{if(kind==0x8001&&objectID==0&&childID==0)destroyed(window);}; |
| 63 | hook=SetWinEventHook(0x8001,0x8001,IntPtr.Zero,callback,(uint)owner.PID,0,0); |
| 64 | if(hook==IntPtr.Zero)throw new InvalidDataException("file_dialog_observer_unavailable"); |
| 65 | Observers[hook]=this; |
| 66 | } |
| 67 | public void Dispose() |
| 68 | { |
| 69 | if(hook==IntPtr.Zero)return; |
| 70 | if(Environment.CurrentManagedThreadId!=thread||!UnhookWinEvent(hook))throw new InvalidDataException("file_dialog_observer_cleanup_failed"); |
| 71 | Observers.TryRemove(hook,out _);hook=IntPtr.Zero;GC.KeepAlive(callback); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | internal static bool Owned(Owner owner,IntPtr dialog) |
| 76 | { |
| 77 | if(!IsWindowVisible(dialog)||GetWindowThreadProcessId(dialog,out var pid)==0||pid!=owner.PID)return false; |
| 78 | var name=new StringBuilder(128);GetClassNameW(dialog,name,name.Capacity);if(name.ToString()!="#32770")return false; |
| 79 | var seen=new HashSet<IntPtr>();var parent=GetWindow(dialog,4); |
| 80 | while(parent!=IntPtr.Zero&&seen.Add(parent)&&seen.Count<=8){if(parent==owner.Window)return true;parent=GetWindow(parent,4);} |
| 81 | return false; |
| 82 | } |
| 83 | internal static IntPtr[] Candidates(Owner owner) |
| 84 | { |
| 85 | owner.Assert();var result=new List<IntPtr>(); |
| 86 | EnumWindows((window,_)=>{if(Owned(owner,window))result.Add(window);return true;},IntPtr.Zero); |
| 87 | owner.Assert();return result.ToArray(); |
| 88 | } |
| 89 | internal static IntPtr Stamp(Owner owner,IntPtr dialog) |
| 90 | { |
| 91 | owner.Assert();if(!Owned(owner,dialog))throw new InvalidDataException("file_dialog_owner_changed"); |
| 92 | var bytes=RandomNumberGenerator.GetBytes(8); |
| 93 | var stamp=new IntPtr((long)(BitConverter.ToUInt64(bytes)&0x7fffffffffffffffUL));if(stamp==IntPtr.Zero)stamp=new IntPtr(1); |
| 94 | if(!SetPropW(dialog,Property,stamp))throw new InvalidDataException("file_dialog_binding_unavailable"); |
| 95 | try{owner.Assert();if(!Owned(owner,dialog)||GetPropW(dialog,Property)!=stamp)throw new InvalidDataException("file_dialog_owner_changed");return stamp;} |
| 96 | catch{Remove(dialog,stamp);throw;} |
| 97 | } |
| 98 | internal static bool Alive(Owner owner,IntPtr dialog,IntPtr stamp) |
| 99 | { |
| 100 | try{owner.Assert();return Owned(owner,dialog)&&GetPropW(dialog,Property)==stamp;} |
| 101 | catch{return false;} |
| 102 | } |
| 103 | internal static void Assert(Owner owner,IntPtr dialog,IntPtr stamp,bool foreground) |
| 104 | { |
| 105 | if(!Alive(owner,dialog,stamp)||foreground&&GetForegroundWindow()!=dialog)throw new InvalidDataException("file_dialog_changed"); |
| 106 | } |
| 107 | internal static void Remove(IntPtr dialog,IntPtr stamp) |
| 108 | {if(GetPropW(dialog,Property)==stamp)RemovePropW(dialog,Property);} |
| 109 | |
| 110 | internal static void Accept(Owner owner,IntPtr dialog,IntPtr stamp) |
| 111 | { |
| 112 | Assert(owner,dialog,stamp,true); |
| 113 | var button=GetDlgItem(dialog,1); |
| 114 | var name=new StringBuilder(128);GetClassNameW(button,name,name.Capacity); |
| 115 | if(button==IntPtr.Zero||!IsChild(dialog,button)||!IsWindowEnabled(button)||name.ToString()!="Button"|| |
| 116 | GetWindowThreadProcessId(button,out var pid)==0||pid!=owner.PID|| |
| 117 | !PostMessageW(button,0x00F5,IntPtr.Zero,IntPtr.Zero))throw new InvalidDataException("file_dialog_selection_invalid"); |
| 118 | } |
| 119 | |
| 120 | internal static void SetFilename(Owner owner,IntPtr dialog,IntPtr stamp,IntPtr field,string text) |
| 121 | { |
| 122 | Assert(owner,dialog,stamp,true); |
| 123 | var name=new StringBuilder(128);GetClassNameW(field,name,name.Capacity); |
| 124 | if(text.Length>1<<20||field==IntPtr.Zero||!IsChild(dialog,field)||name.ToString()!="Edit"|| |
| 125 | GetWindowThreadProcessId(field,out var pid)==0||pid!=owner.PID) |
| 126 | throw new InvalidDataException("file_dialog_selection_invalid"); |
| 127 | |
| 128 | |
| 129 | if(SendMessageTimeoutW(field,0x000C,IntPtr.Zero,text,0x22,2000,out var written)==IntPtr.Zero||written==IntPtr.Zero) |
| 130 | throw new InvalidDataException("file_dialog_input_failed"); |
| 131 | Assert(owner,dialog,stamp,true); |
| 132 | if(SendMessageTimeoutW(field,0x000E,IntPtr.Zero,IntPtr.Zero,0x22,2000,out var textLength)==IntPtr.Zero||textLength.ToInt64()!=text.Length) |
| 133 | throw new InvalidDataException("file_dialog_selection_invalid"); |
| 134 | var actual=new StringBuilder(text.Length+1); |
| 135 | if(SendMessageTimeoutW(field,0x000D,new IntPtr(actual.Capacity),actual,0x22,2000,out var length)==IntPtr.Zero|| |
| 136 | length.ToInt64()!=text.Length||actual.ToString()!=text) |
| 137 | throw new InvalidDataException("file_dialog_selection_invalid"); |
| 138 | Assert(owner,dialog,stamp,true); |
| 139 | } |
| 140 | } |