| 1 | using System; |
| 2 | using System.Text; |
| 3 | using System.Diagnostics; |
| 4 | using System.Threading; |
| 5 | using System.Runtime.InteropServices; |
| 6 | using System.Management; |
| 7 | public class ComputerProcess { |
| 8 | [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr attributes, string name); |
| 9 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenJobObject(uint access,bool inherit,string name); |
| 10 | [DllImport("kernel32.dll",SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); |
| 11 | [DllImport("kernel32.dll")] static extern bool TerminateJobObject(IntPtr job, uint code); |
| 12 | [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle); |
| 13 | [StructLayout(LayoutKind.Sequential)] struct SECURITY {public int length;public IntPtr descriptor;public int inherit;} |
| 14 | [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] struct STARTUP {public int size;public string reserved,desktop,title;public int x,y,width,height,columns,rows,fill,flags;public short show,reservedSize;public IntPtr reservedPointer,input,output,error;} |
| 15 | [StructLayout(LayoutKind.Sequential)] struct CREATED {public IntPtr process,thread;public uint pid,tid;} |
| 16 | [DllImport("kernel32.dll",SetLastError=true)] static extern bool CreatePipe(out IntPtr read,out IntPtr write,ref SECURITY attributes,uint size); |
| 17 | [DllImport("kernel32.dll",SetLastError=true)] static extern bool SetHandleInformation(IntPtr handle,uint mask,uint flags); |
| 18 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr CreateFile(string path,uint access,uint share,ref SECURITY attributes,uint mode,uint flags,IntPtr template); |
| 19 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool CreateProcess(string application,StringBuilder command,IntPtr processAttributes,IntPtr threadAttributes,bool inherit,uint flags,IntPtr environment,string directory,ref STARTUP startup,out CREATED created); |
| 20 | [DllImport("kernel32.dll",SetLastError=true)] static extern uint ResumeThread(IntPtr thread); |
| 21 | [DllImport("kernel32.dll",SetLastError=true)] internal static extern bool TerminateProcess(IntPtr process,uint code); |
| 22 | [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr handle,uint milliseconds); |
| 23 | [DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process,out uint code); |
| 24 | [StructLayout(LayoutKind.Sequential)] struct BASICLIMIT { public long perProcess,perJob; public uint flags; public UIntPtr minWorking,maxWorking; public uint active; public UIntPtr affinity; public uint priority,scheduling; } |
| 25 | [StructLayout(LayoutKind.Sequential)] struct COUNTERS { public ulong readOps,writeOps,otherOps,readBytes,writeBytes,otherBytes; } |
| 26 | [StructLayout(LayoutKind.Sequential)] struct LIMIT { public BASICLIMIT basic; public COUNTERS io; public UIntPtr processMemory,jobMemory,peakProcess,peakJob; } |
| 27 | [DllImport("kernel32.dll")] static extern bool SetInformationJobObject(IntPtr job,int type,ref LIMIT info,uint size); |
| 28 | [StructLayout(LayoutKind.Sequential)] struct ACCOUNTING {public long user,kernel,periodUser,periodKernel;public uint faults,total,active,terminated;} |
| 29 | [DllImport("kernel32.dll",SetLastError=true)] static extern bool QueryInformationJobObject(IntPtr job,int type,out ACCOUNTING info,uint size,IntPtr returned); |
| 30 | static string JobName(string request) {return "Global\\SnowglobeComputer-"+System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(request));} |
| 31 | static bool WaitForEmpty(IntPtr job,int timeout) { |
| 32 | var clock=Stopwatch.StartNew(); |
| 33 | do { |
| 34 | ACCOUNTING count; |
| 35 | if(!QueryInformationJobObject(job,1,out count,(uint)Marshal.SizeOf(typeof(ACCOUNTING)),IntPtr.Zero))throw new System.ComponentModel.Win32Exception(); |
| 36 | if(count.active==0)return true; |
| 37 | Thread.Sleep(10); |
| 38 | } while(timeout<0 || clock.ElapsedMilliseconds<timeout); |
| 39 | return false; |
| 40 | } |
| 41 | public static void Stop(string request) { |
| 42 | IntPtr job=OpenJobObject(12,false,JobName(request)); |
| 43 | if(job==IntPtr.Zero) {if(Marshal.GetLastWin32Error()==2)return;throw new System.ComponentModel.Win32Exception();} |
| 44 | try {if(!TerminateJobObject(job,124) || !WaitForEmpty(job,10000))throw new Exception("Process cleanup failed");} |
| 45 | finally {CloseHandle(job);} |
| 46 | } |
| 47 | class Drain { |
| 48 | public byte[] bytes=new byte[65536]; public int length; public bool truncated; |
| 49 | public void Read(System.IO.Stream stream){try{var buffer=new byte[4096];int count;while((count=stream.Read(buffer,0,buffer.Length))>0){int take=Math.Min(count,bytes.Length-length);Array.Copy(buffer,0,bytes,length,take);length+=take;if(take<count)truncated=true;}}catch(System.IO.IOException){truncated=true;}catch(ObjectDisposedException){truncated=true;}} |
| 50 | public string Text(){return Encoding.UTF8.GetString(bytes,0,length);} |
| 51 | } |
| 52 | public static object Run(string executable, string arguments, string directory, int timeout, string request, Action<object> started=null) { |
| 53 | var stdout=new Drain();var stderr=new Drain(); |
| 54 | Thread outThread=null,errThread=null; |
| 55 | IntPtr output=IntPtr.Zero,outputWrite=IntPtr.Zero,error=IntPtr.Zero,errorWrite=IntPtr.Zero,input=IntPtr.Zero; |
| 56 | var created=new CREATED(); |
| 57 | System.IO.FileStream outputStream=null,errorStream=null; |
| 58 | IntPtr job=CreateJobObject(IntPtr.Zero,JobName(request)); |
| 59 | if(job==IntPtr.Zero)throw new Exception("Cannot create process job"); |
| 60 | try { |
| 61 | var limit=new LIMIT();limit.basic.flags=8192; |
| 62 | if(!SetInformationJobObject(job,9,ref limit,(uint)Marshal.SizeOf(typeof(LIMIT))))throw new Exception("Cannot configure process job"); |
| 63 | var security=new SECURITY {length=Marshal.SizeOf(typeof(SECURITY)),inherit=1}; |
| 64 | if(!CreatePipe(out output,out outputWrite,ref security,0) || !SetHandleInformation(output,1,0) || |
| 65 | !CreatePipe(out error,out errorWrite,ref security,0) || !SetHandleInformation(error,1,0))throw new System.ComponentModel.Win32Exception(); |
| 66 | input=CreateFile("NUL",0x80000000,3,ref security,3,0,IntPtr.Zero); |
| 67 | if(input==new IntPtr(-1))throw new System.ComponentModel.Win32Exception(); |
| 68 | var startup=new STARTUP {size=Marshal.SizeOf(typeof(STARTUP)),flags=256,input=input,output=outputWrite,error=errorWrite}; |
| 69 | // No script instruction may run before the process belongs to its cleanup job. |
| 70 | if(!CreateProcess(null,new StringBuilder("\""+executable+"\" "+arguments),IntPtr.Zero,IntPtr.Zero,true,0x08000004,IntPtr.Zero,directory,ref startup,out created))throw new System.ComponentModel.Win32Exception(); |
| 71 | if(!AssignProcessToJobObject(job,created.process))throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(),"Cannot isolate process job"); |
| 72 | CloseHandle(outputWrite);outputWrite=IntPtr.Zero;CloseHandle(errorWrite);errorWrite=IntPtr.Zero;CloseHandle(input);input=IntPtr.Zero; |
| 73 | outputStream=new System.IO.FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(output,true),System.IO.FileAccess.Read);output=IntPtr.Zero; |
| 74 | errorStream=new System.IO.FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(error,true),System.IO.FileAccess.Read);error=IntPtr.Zero; |
| 75 | outThread=new Thread(()=>stdout.Read(outputStream));outThread.IsBackground=true;outThread.Start(); |
| 76 | errThread=new Thread(()=>stderr.Read(errorStream));errThread.IsBackground=true;errThread.Start(); |
| 77 | object handle=null; |
| 78 | if(started!=null)using(var owner=Process.GetCurrentProcess())handle=new {pid=(int)created.pid,id=owner.Id+":"+owner.StartTime.ToUniversalTime().Ticks}; |
| 79 | if(!System.IO.File.Exists(request))throw new Exception("Process cleanup failed"); |
| 80 | if(ResumeThread(created.thread)==UInt32.MaxValue)throw new System.ComponentModel.Win32Exception(); |
| 81 | if(started!=null) { |
| 82 | started(handle); |
| 83 | CloseHandle(created.process);created.process=IntPtr.Zero;CloseHandle(created.thread);created.thread=IntPtr.Zero; |
| 84 | WaitForEmpty(job,-1); |
| 85 | return handle; |
| 86 | } |
| 87 | var clock=Stopwatch.StartNew(); |
| 88 | uint waited=WaitForSingleObject(created.process,(uint)timeout); |
| 89 | if(waited!=0 && waited!=258)throw new System.ComponentModel.Win32Exception(); |
| 90 | bool timedOut=waited==258; |
| 91 | if(!timedOut){int remaining=Math.Max(0,timeout-(int)clock.ElapsedMilliseconds);timedOut=!outThread.Join(remaining);remaining=Math.Max(0,timeout-(int)clock.ElapsedMilliseconds);timedOut=!errThread.Join(remaining)||timedOut;} |
| 92 | if(timedOut)TerminateJobObject(job,124); |
| 93 | if(WaitForSingleObject(created.process,5000)!=0)throw new Exception("Process cleanup failed"); |
| 94 | outThread.Join(5000);errThread.Join(5000); |
| 95 | uint code;if(!GetExitCodeProcess(created.process,out code))throw new System.ComponentModel.Win32Exception(); |
| 96 | return new {exit=unchecked((int)code),stdout=stdout.Text(),stderr=stderr.Text(),timed_out=timedOut,stdout_truncated=stdout.truncated,stderr_truncated=stderr.truncated}; |
| 97 | } finally { |
| 98 | TerminateJobObject(job,124); |
| 99 | if(created.process!=IntPtr.Zero)TerminateProcess(created.process,124); |
| 100 | foreach(var handle in new[]{created.process,created.thread,output,outputWrite,error,errorWrite,input})if(handle!=IntPtr.Zero && handle!=new IntPtr(-1))CloseHandle(handle); |
| 101 | WaitForEmpty(job,-1);CloseHandle(job); |
| 102 | if(outputStream!=null)outputStream.Dispose();if(errorStream!=null)errorStream.Dispose(); |
| 103 | } |
| 104 | |
| 105 | } |
| 106 | [StructLayout(LayoutKind.Sequential)] struct KEYBDINPUT {public ushort vk,scan;public uint flags,time;public UIntPtr extra;} |
| 107 | [StructLayout(LayoutKind.Explicit)] struct INPUTUNION {[FieldOffset(0)]public KEYBDINPUT keyboard;[FieldOffset(0)]public MOUSEINPUT mouse;} |
| 108 | [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT {public int x,y;public uint data,flags,time;public UIntPtr extra;} |
| 109 | [StructLayout(LayoutKind.Sequential)] struct INPUT {public uint type;public INPUTUNION data;} |
| 110 | [DllImport("user32.dll",SetLastError=true)] static extern uint SendInput(uint count, INPUT[] inputs,int size); |
| 111 | public static void Type(string text) { |
| 112 | foreach(char unit in text){var inputs=new INPUT[2];for(int i=0;i<2;i++){inputs[i].type=1;inputs[i].data.keyboard.scan=unit;inputs[i].data.keyboard.flags=(uint)(4+i*2);}if(SendInput(2,inputs,Marshal.SizeOf(typeof(INPUT)))!=2)throw new Exception("Desktop refused text input");} |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | public static class ComputerWorker { |
| 117 | static System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = 4194304 }; |
| 118 | static string requestPath,responsePath; |
| 119 | static System.Collections.Generic.Dictionary<string,object> Map(object value) { return (System.Collections.Generic.Dictionary<string,object>)value; } |
| 120 | static object Get(System.Collections.Generic.Dictionary<string,object> value, string key, object fallback = null) { object found; return value.TryGetValue(key,out found) ? found : fallback; } |
| 121 | static string Text(System.Collections.Generic.Dictionary<string,object> value, string key, string fallback = "") { return Convert.ToString(Get(value,key,fallback)); } |
| 122 | static int Number(System.Collections.Generic.Dictionary<string,object> value, string key, int fallback = 0) { return Convert.ToInt32(Get(value,key,fallback)); } |
| 123 | [DllImport("user32.dll")] static extern bool SetProcessDPIAware(); |
| 124 | [DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int informationClass,out int elevation,int length,out int returned); |
| 125 | [STAThread] public static int Main(string[] args) { |
| 126 | if(args.Length==2 && (args[0]=="--prepare" || args[0]=="--cleanup" || args[0]=="--release" || args[0]=="--install")) { |
| 127 | try { |
| 128 | if(args[0]=="--prepare")System.IO.Directory.CreateDirectory(args[1]); |
| 129 | else if(args[0]=="--install") { |
| 130 | System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(args[1])); |
| 131 | string temporary=args[1]+"."+Guid.NewGuid().ToString("N")+".new"; |
| 132 | try { |
| 133 | System.IO.File.Copy(System.Reflection.Assembly.GetExecutingAssembly().Location,temporary,true); |
| 134 | if(!System.IO.File.Exists(args[1]))System.IO.File.Move(temporary,args[1]); |
| 135 | } finally {System.IO.File.Delete(temporary);} |
| 136 | } |
| 137 | else Cleanup(args[1],args[0]=="--release"); |
| 138 | return 0; |
| 139 | } |
| 140 | catch { return 1; } |
| 141 | } |
| 142 | if(args.Length==3 && args[0]=="--launch") { |
| 143 | requestPath=args[1];responsePath=args[2]; |
| 144 | try { Launch(); } |
| 145 | catch(Exception error) { Reply(new {error=error.Message}); } |
| 146 | return 0; |
| 147 | } |
| 148 | if(args.Length != 2) return 1; |
| 149 | requestPath=args[0];responsePath=args[1]; object result; |
| 150 | try { SetProcessDPIAware(); result=Run(Map(json.DeserializeObject(System.IO.File.ReadAllText(requestPath)))); } |
| 151 | catch(Exception error) { result=new { error=error.Message }; } |
| 152 | Reply(result); |
| 153 | return 0; |
| 154 | } |
| 155 | static void Reply(object result) {System.IO.File.WriteAllText(responsePath,json.Serialize(result),new UTF8Encoding(false));} |
| 156 | static void Launch() { |
| 157 | var request=Map(json.DeserializeObject(System.IO.File.ReadAllText(requestPath))); |
| 158 | string user=null; |
| 159 | using(var query=new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")) |
| 160 | using(var rows=query.Get()) |
| 161 | foreach(ManagementObject row in rows) |
| 162 | using(row) { user=row["UserName"] as string; } |
| 163 | if(String.IsNullOrEmpty(user))throw new Exception("Sign in to the VM desktop before running commands."); |
| 164 | dynamic service=Activator.CreateInstance(Type.GetTypeFromProgID("Schedule.Service")); |
| 165 | service.Connect(null,null,null,null); |
| 166 | dynamic task=service.NewTask(0); |
| 167 | task.Principal.UserId=user; |
| 168 | task.Principal.LogonType=3; |
| 169 | task.Principal.RunLevel=1; |
| 170 | task.Settings.ExecutionTimeLimit=Text(request,"action")=="spawn" ? "PT0S" : "PT210S"; |
| 171 | task.Settings.Priority=4; |
| 172 | task.Settings.DisallowStartIfOnBatteries=false; |
| 173 | task.Settings.StopIfGoingOnBatteries=false; |
| 174 | dynamic action=task.Actions.Create(0); |
| 175 | action.Path=System.Reflection.Assembly.GetExecutingAssembly().Location; |
| 176 | action.Arguments="\""+requestPath+"\" \""+responsePath+"\""; |
| 177 | string name="SnowglobeComputer-"+System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(requestPath)); |
| 178 | dynamic registered=service.GetFolder("\\").RegisterTaskDefinition(name,task,6,user,null,3,null); |
| 179 | registered.Run(null); |
| 180 | } |
| 181 | static void Cleanup(string directory,bool keepSpawn) { |
| 182 | string request=System.IO.Path.Combine(directory,"request.json"); |
| 183 | if(!keepSpawn) { |
| 184 | if(System.IO.File.Exists(request))System.IO.File.Delete(request); |
| 185 | ComputerProcess.Stop(request); |
| 186 | using(var query=new ManagementObjectSearcher("SELECT ProcessId,CommandLine FROM Win32_Process")) |
| 187 | using(var rows=query.Get()) |
| 188 | foreach(ManagementObject row in rows) |
| 189 | using(row) { |
| 190 | if((row["CommandLine"] as string ?? "").IndexOf(request,StringComparison.OrdinalIgnoreCase)<0)continue; |
| 191 | try { |
| 192 | using(var process=Process.GetProcessById(Convert.ToInt32(row["ProcessId"]))) { |
| 193 | IntPtr handle=process.Handle; |
| 194 | row.Get(); |
| 195 | if(process.HasExited || (row["CommandLine"] as string ?? "").IndexOf(request,StringComparison.OrdinalIgnoreCase)<0)continue; |
| 196 | if(!ComputerProcess.TerminateProcess(handle,124) && !process.HasExited)throw new System.ComponentModel.Win32Exception(); |
| 197 | if(!process.WaitForExit(10000))throw new Exception("The command worker could not stop."); |
| 198 | } |
| 199 | } catch(ArgumentException) {} catch(ManagementException error) { |
| 200 | if(error.ErrorCode!=ManagementStatus.NotFound)throw; |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | dynamic service=Activator.CreateInstance(Type.GetTypeFromProgID("Schedule.Service")); |
| 205 | service.Connect(null,null,null,null); |
| 206 | dynamic folder=service.GetFolder("\\"); |
| 207 | try { folder.DeleteTask("SnowglobeComputer-"+System.IO.Path.GetFileName(directory),0); } |
| 208 | catch(Exception error) { if(error.HResult!=unchecked((int)0x80070002))throw; } |
| 209 | if(!keepSpawn && System.IO.Directory.Exists(directory))System.IO.Directory.Delete(directory,true); |
| 210 | } |
| 211 | static object Target(System.Windows.Automation.AutomationElement node) { |
| 212 | var current=node.Current; |
| 213 | using(var process=Process.GetProcessById(current.ProcessId)) { |
| 214 | return new {pid=current.ProcessId,started=process.StartTime.ToUniversalTime().Ticks.ToString(),id=String.Join(".",node.GetRuntimeId()),role=current.ControlType.ProgrammaticName,name=current.Name}; |
| 215 | } |
| 216 | } |
| 217 | static System.Windows.Automation.AutomationElement Find(System.Collections.Generic.Dictionary<string,object> target) { |
| 218 | using(var process=Process.GetProcessById(Number(target,"pid"))) { |
| 219 | if(process.StartTime.ToUniversalTime().Ticks.ToString()!=Text(target,"started")) throw new Exception("The application changed. Read a fresh UI tree."); |
| 220 | } |
| 221 | var roots=System.Windows.Automation.AutomationElement.RootElement.FindAll(System.Windows.Automation.TreeScope.Children,new System.Windows.Automation.PropertyCondition(System.Windows.Automation.AutomationElement.ProcessIdProperty,Number(target,"pid"))); |
| 222 | var queue=new System.Collections.Generic.Queue<System.Windows.Automation.AutomationElement>(); |
| 223 | foreach(System.Windows.Automation.AutomationElement root in roots)queue.Enqueue(root); |
| 224 | var walker=System.Windows.Automation.TreeWalker.ControlViewWalker;var clock=Stopwatch.StartNew();int count=0; |
| 225 | while(queue.Count>0 && count++<5000 && clock.ElapsedMilliseconds<8000) { |
| 226 | var node=queue.Dequeue();var current=node.Current; |
| 227 | if(String.Join(".",node.GetRuntimeId())==Text(target,"id") && current.Name==Text(target,"name") && current.ControlType.ProgrammaticName==Text(target,"role"))return node; |
| 228 | for(var child=walker.GetFirstChild(node);child!=null && queue.Count<5000;child=walker.GetNextSibling(child))queue.Enqueue(child); |
| 229 | } |
| 230 | throw new Exception("The UI element changed. Read a fresh tree."); |
| 231 | } |
| 232 | static object Ui(System.Collections.Generic.Dictionary<string,object> request) { |
| 233 | var nodes=new System.Collections.Generic.List<object>(); |
| 234 | var queue=new System.Collections.Generic.Queue<Tuple<System.Windows.Automation.AutomationElement,int>>(); |
| 235 | queue.Enqueue(Tuple.Create(System.Windows.Automation.AutomationElement.RootElement,0)); |
| 236 | var walker=System.Windows.Automation.TreeWalker.ControlViewWalker;var clock=Stopwatch.StartNew(); |
| 237 | while(queue.Count>0 && nodes.Count<1500 && clock.ElapsedMilliseconds<8000) { |
| 238 | var entry=queue.Dequeue();var node=entry.Item1;int depth=entry.Item2; |
| 239 | try { |
| 240 | var current=node.Current; |
| 241 | if(depth==1 && Number(request,"pid")>0 && current.ProcessId!=Number(request,"pid"))continue; |
| 242 | if(depth>0) { |
| 243 | var actions=new System.Collections.Generic.List<string>();if(current.IsEnabled && current.IsKeyboardFocusable)actions.Add("focus");object pattern;string value=null; |
| 244 | if(node.TryGetCurrentPattern(System.Windows.Automation.InvokePattern.Pattern,out pattern))actions.Add("press"); |
| 245 | if(node.TryGetCurrentPattern(System.Windows.Automation.TogglePattern.Pattern,out pattern))actions.Add("toggle"); |
| 246 | if(node.TryGetCurrentPattern(System.Windows.Automation.SelectionItemPattern.Pattern,out pattern))actions.Add("select"); |
| 247 | if(node.TryGetCurrentPattern(System.Windows.Automation.ExpandCollapsePattern.Pattern,out pattern)){actions.Add("expand");actions.Add("collapse");} |
| 248 | if(node.TryGetCurrentPattern(System.Windows.Automation.ValuePattern.Pattern,out pattern)) { |
| 249 | var properties=((System.Windows.Automation.ValuePattern)pattern).Current; |
| 250 | value=properties.Value;if(value.Length>1024)value=value.Substring(0,1024); |
| 251 | if(!properties.IsReadOnly)actions.Add("set_value"); |
| 252 | } else if(node.TryGetCurrentPattern(System.Windows.Automation.TextPattern.Pattern,out pattern)) { |
| 253 | value=((System.Windows.Automation.TextPattern)pattern).DocumentRange.GetText(1024); |
| 254 | } |
| 255 | var r=current.BoundingRectangle; |
| 256 | nodes.Add(new {target=Target(node),role=current.ControlType.ProgrammaticName,name=current.Name,value=value,enabled=current.IsEnabled,focused=current.HasKeyboardFocus,bounds=new[]{r.X,r.Y,r.Width,r.Height},actions=actions}); |
| 257 | } |
| 258 | if(depth<20) for(var child=walker.GetFirstChild(node);child!=null && queue.Count<3000;child=walker.GetNextSibling(child))queue.Enqueue(Tuple.Create(child,depth+1)); |
| 259 | } catch(System.Windows.Automation.ElementNotAvailableException) {} catch(ArgumentException) {} catch(InvalidOperationException) {} |
| 260 | } |
| 261 | return new {nodes=nodes,truncated=queue.Count>0}; |
| 262 | } |
| 263 | static object UiAction(System.Collections.Generic.Dictionary<string,object> request) { |
| 264 | var node=Find(Map(Get(request,"target"))); |
| 265 | switch(Text(request,"operation")) { |
| 266 | case "focus": node.SetFocus();break; |
| 267 | case "press": ((System.Windows.Automation.InvokePattern)node.GetCurrentPattern(System.Windows.Automation.InvokePattern.Pattern)).Invoke();break; |
| 268 | case "toggle": ((System.Windows.Automation.TogglePattern)node.GetCurrentPattern(System.Windows.Automation.TogglePattern.Pattern)).Toggle();break; |
| 269 | case "select": ((System.Windows.Automation.SelectionItemPattern)node.GetCurrentPattern(System.Windows.Automation.SelectionItemPattern.Pattern)).Select();break; |
| 270 | case "expand": ((System.Windows.Automation.ExpandCollapsePattern)node.GetCurrentPattern(System.Windows.Automation.ExpandCollapsePattern.Pattern)).Expand();break; |
| 271 | case "collapse": ((System.Windows.Automation.ExpandCollapsePattern)node.GetCurrentPattern(System.Windows.Automation.ExpandCollapsePattern.Pattern)).Collapse();break; |
| 272 | case "set_value": ((System.Windows.Automation.ValuePattern)node.GetCurrentPattern(System.Windows.Automation.ValuePattern.Pattern)).SetValue(Text(request,"value"));break; |
| 273 | default: throw new Exception("Choose an action reported by computer_ui."); |
| 274 | } |
| 275 | return new {completed=true}; |
| 276 | } |
| 277 | static object Run(System.Collections.Generic.Dictionary<string,object> request) { |
| 278 | string action=Text(request,"action");string root=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); |
| 279 | if(action=="status") { |
| 280 | var runtimes=new System.Collections.Generic.List<string>(new[]{"powershell","cmd"});if(System.IO.File.Exists(System.IO.Path.Combine(root,"AutoHotkey.exe")))runtimes.Add("ahk"); |
| 281 | using(var identity=System.Security.Principal.WindowsIdentity.GetCurrent()) |
| 282 | using(var process=Process.GetCurrentProcess()) { |
| 283 | int elevation,returned; |
| 284 | if(!GetTokenInformation(identity.Token,20,out elevation,4,out returned))throw new System.ComponentModel.Win32Exception(); |
| 285 | return new {platform="windows",hostname=Environment.MachineName,runtimes=runtimes,capabilities=new[]{"shot","input","ui","ui_action","exec","spawn","process","file"},coordinate_units="screenshot_pixels",max_timeout_ms=180000, |
| 286 | execution_context=new {user=identity.Name,elevated=elevation!=0,session=process.SessionId}}; |
| 287 | } |
| 288 | } |
| 289 | if(action=="input") { |
| 290 | var actions=(object[])Get(request,"actions");foreach(var value in actions) {var item=Map(value);if(Text(item,"type")!="text")throw new Exception("Use the VM console for pointer and key actions.");ComputerProcess.Type(Text(item,"text"));}return new {completed=actions.Length}; |
| 291 | } |
| 292 | if(action=="ui")return Ui(request); |
| 293 | if(action=="ui_action")return UiAction(request); |
| 294 | if(action=="exec" || action=="spawn") { |
| 295 | string runtime=Text(request,"runtime","default"),directory=System.IO.Path.GetDirectoryName(requestPath),file,exe,arguments,script=Text(request,"script"); |
| 296 | if(runtime=="default")runtime="powershell"; |
| 297 | switch(runtime) { |
| 298 | // PowerShell 3 caches pipeline encoding before the script runs. |
| 299 | case "powershell": file=System.IO.Path.Combine(directory,"script.ps1");exe="cmd.exe";arguments="/d /s /c \"chcp 65001 >nul & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \""+file+"\"\"";break; |
| 300 | case "cmd": file=System.IO.Path.Combine(directory,"script.cmd");exe="cmd.exe";arguments="/d /s /c \"\""+file+"\"\"";script="@chcp 65001 >nul\r\n"+script;break; |
| 301 | case "ahk": file=System.IO.Path.Combine(directory,"script.ahk");exe=System.IO.Path.Combine(root,"AutoHotkey.exe");arguments="/ErrorStdOut \""+file+"\"";script="#Requires AutoHotkey v2.0\n#SingleInstance Off\n#NoTrayIcon\nFileEncoding 'UTF-8-RAW'\nSendMode 'Input'\nCoordMode 'Mouse', 'Screen'\nCoordMode 'Pixel', 'Screen'\nCoordMode 'ToolTip', 'Screen'\nSetTitleMatchMode 2\nDetectHiddenWindows true\n"+script;break; |
| 302 | default:throw new Exception("Choose a runtime reported by computer_status."); |
| 303 | } |
| 304 | System.IO.File.WriteAllText(file,script,new UTF8Encoding(runtime!="cmd")); |
| 305 | string home=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 306 | if(action=="exec")return ComputerProcess.Run(exe,arguments,home,Number(request,"timeout_ms"),requestPath); |
| 307 | return ComputerProcess.Run(exe,arguments,home,0,requestPath,Reply); |
| 308 | } |
| 309 | if(action=="process") { |
| 310 | string[] parts=Text(request,"id").Split(':');Process process; |
| 311 | try {process=Process.GetProcessById(Int32.Parse(parts[0]));}catch(ArgumentException){return new {running=false};} |
| 312 | using(process) { |
| 313 | if(parts.Length!=2 || process.StartTime.ToUniversalTime().Ticks.ToString()!=parts[1])return new {running=false}; |
| 314 | if(Text(request,"operation")=="stop") { |
| 315 | var info=new ProcessStartInfo("taskkill.exe","/PID "+process.Id+" /T /F") {UseShellExecute=false,CreateNoWindow=true}; |
| 316 | using(var stop=Process.Start(info)){if(!stop.WaitForExit(10000) || stop.ExitCode!=0)throw new Exception("The process could not stop. Check its status.");}return new {stopping=true}; |
| 317 | } |
| 318 | return new {running=true,pid=process.Id}; |
| 319 | } |
| 320 | } |
| 321 | if(action=="file") { |
| 322 | string path=Text(request,"path"); |
| 323 | if(!System.Text.RegularExpressions.Regex.IsMatch(path,@"^[A-Za-z]:[\\/]") || path.IndexOf('\0')>=0)throw new Exception("Use an absolute guest file path."); |
| 324 | switch(Text(request,"operation")) { |
| 325 | case "stat": if(System.IO.Directory.Exists(path))return new {path=path,size=0,directory=true};var f=new System.IO.FileInfo(path);return new {path=f.FullName,size=f.Length,directory=false,modified=f.LastWriteTimeUtc.ToString("o")}; |
| 326 | case "list": var entries=new System.Collections.Generic.List<object>();foreach(string child in System.IO.Directory.EnumerateFileSystemEntries(path)) {if(entries.Count==1000)return new {entries=entries,truncated=true};entries.Add(new {name=System.IO.Path.GetFileName(child),directory=System.IO.Directory.Exists(child)});}return new {entries=entries,truncated=false}; |
| 327 | case "mkdir": System.IO.Directory.CreateDirectory(path);return new {path=path}; |
| 328 | case "commit": string destination=Text(request,"destination");if(Convert.ToBoolean(Get(request,"overwrite",false)) && System.IO.File.Exists(destination))System.IO.File.Replace(path,destination,null);else System.IO.File.Move(path,destination);return new {path=destination}; |
| 329 | case "remove": System.IO.File.Delete(path);return new {removed=true}; |
| 330 | default: throw new Exception("Choose a supported file operation."); |
| 331 | } |
| 332 | } |
| 333 | throw new Exception("Choose a supported computer operation."); |
| 334 | } |
| 335 | } |