1using System;
2using System.Text;
3using System.Diagnostics;
4using System.Threading;
5using System.Runtime.InteropServices;
6public class ComputerProcess {
7 [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
8 [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenJobObject(uint access,bool inherit,string name);
9 [DllImport("kernel32.dll",SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
10 [DllImport("kernel32.dll")] static extern bool TerminateJobObject(IntPtr job, uint code);
11 [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
12 [StructLayout(LayoutKind.Sequential)] struct SECURITY {public int length;public IntPtr descriptor;public int inherit;}
13 [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;}
14 [StructLayout(LayoutKind.Sequential)] struct CREATED {public IntPtr process,thread;public uint pid,tid;}
15 [DllImport("kernel32.dll",SetLastError=true)] static extern bool CreatePipe(out IntPtr read,out IntPtr write,ref SECURITY attributes,uint size);
16 [DllImport("kernel32.dll",SetLastError=true)] static extern bool SetHandleInformation(IntPtr handle,uint mask,uint flags);
17 [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);
18 [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);
19 [DllImport("kernel32.dll",SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
20 [DllImport("kernel32.dll")] static extern bool TerminateProcess(IntPtr process,uint code);
21 [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr handle,uint milliseconds);
22 [DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process,out uint code);
23 [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; }
24 [StructLayout(LayoutKind.Sequential)] struct COUNTERS { public ulong readOps,writeOps,otherOps,readBytes,writeBytes,otherBytes; }
25 [StructLayout(LayoutKind.Sequential)] struct LIMIT { public BASICLIMIT basic; public COUNTERS io; public UIntPtr processMemory,jobMemory,peakProcess,peakJob; }
26 [DllImport("kernel32.dll")] static extern bool SetInformationJobObject(IntPtr job,int type,ref LIMIT info,uint size);
27 [StructLayout(LayoutKind.Sequential)] struct ACCOUNTING {public long user,kernel,periodUser,periodKernel;public uint faults,total,active,terminated;}
28 [DllImport("kernel32.dll",SetLastError=true)] static extern bool QueryInformationJobObject(IntPtr job,int type,out ACCOUNTING info,uint size,IntPtr returned);
29 static string JobName(string request) {return "Global\\SnowglobeComputer-"+System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(request));}
30 static bool WaitForEmpty(IntPtr job,int timeout) {
31 var clock=Stopwatch.StartNew();
32 do {
33 ACCOUNTING count;
34 if(!QueryInformationJobObject(job,1,out count,(uint)Marshal.SizeOf(typeof(ACCOUNTING)),IntPtr.Zero))throw new System.ComponentModel.Win32Exception();
35 if(count.active==0)return true;
36 Thread.Sleep(10);
37 } while(timeout<0 || clock.ElapsedMilliseconds<timeout);
38 return false;
39 }
40 public static void Stop(string request) {
41 IntPtr job=OpenJobObject(12,false,JobName(request));
42 if(job==IntPtr.Zero) {if(Marshal.GetLastWin32Error()==2)return;throw new System.ComponentModel.Win32Exception();}
43 try {if(!TerminateJobObject(job,124) || !WaitForEmpty(job,10000))throw new Exception("Process cleanup failed");}
44 finally {CloseHandle(job);}
45 }
46 class Drain {
47 public byte[] bytes=new byte[65536]; public int length; public bool truncated;
48 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;}}
49 public string Text(){return Encoding.UTF8.GetString(bytes,0,length);}
50 }
51 public static object Run(string executable, string arguments, string directory, int timeout, string request, Action<object> started=null) {
52 var stdout=new Drain();var stderr=new Drain();
53 Thread outThread=null,errThread=null;
54 IntPtr output=IntPtr.Zero,outputWrite=IntPtr.Zero,error=IntPtr.Zero,errorWrite=IntPtr.Zero,input=IntPtr.Zero;
55 var created=new CREATED();
56 System.IO.FileStream outputStream=null,errorStream=null;
57 IntPtr job=CreateJobObject(IntPtr.Zero,JobName(request));
58 if(job==IntPtr.Zero)throw new Exception("Cannot create process job");
59 try {
60 var limit=new LIMIT();limit.basic.flags=8192;
61 if(!SetInformationJobObject(job,9,ref limit,(uint)Marshal.SizeOf(typeof(LIMIT))))throw new Exception("Cannot configure process job");
62 var security=new SECURITY {length=Marshal.SizeOf(typeof(SECURITY)),inherit=1};
63 if(!CreatePipe(out output,out outputWrite,ref security,0) || !SetHandleInformation(output,1,0) ||
64 !CreatePipe(out error,out errorWrite,ref security,0) || !SetHandleInformation(error,1,0))throw new System.ComponentModel.Win32Exception();
65 input=CreateFile("NUL",0x80000000,3,ref security,3,0,IntPtr.Zero);
66 if(input==new IntPtr(-1))throw new System.ComponentModel.Win32Exception();
67 var startup=new STARTUP {size=Marshal.SizeOf(typeof(STARTUP)),flags=256,input=input,output=outputWrite,error=errorWrite};
68 // No script instruction may run before the process belongs to its cleanup job.
69 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();
70 if(!AssignProcessToJobObject(job,created.process))throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(),"Cannot isolate process job");
71 CloseHandle(outputWrite);outputWrite=IntPtr.Zero;CloseHandle(errorWrite);errorWrite=IntPtr.Zero;CloseHandle(input);input=IntPtr.Zero;
72 outputStream=new System.IO.FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(output,true),System.IO.FileAccess.Read);output=IntPtr.Zero;
73 errorStream=new System.IO.FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(error,true),System.IO.FileAccess.Read);error=IntPtr.Zero;
74 outThread=new Thread(()=>stdout.Read(outputStream));outThread.IsBackground=true;outThread.Start();
75 errThread=new Thread(()=>stderr.Read(errorStream));errThread.IsBackground=true;errThread.Start();
76 object handle=null;
77 if(started!=null)using(var owner=Process.GetCurrentProcess())handle=new {pid=(int)created.pid,id=owner.Id+":"+owner.StartTime.ToUniversalTime().Ticks};
78 if(!System.IO.File.Exists(request))throw new Exception("Process cleanup failed");
79 if(ResumeThread(created.thread)==UInt32.MaxValue)throw new System.ComponentModel.Win32Exception();
80 if(started!=null) {
81 started(handle);
82 CloseHandle(created.process);created.process=IntPtr.Zero;CloseHandle(created.thread);created.thread=IntPtr.Zero;
83 WaitForEmpty(job,-1);
84 return handle;
85 }
86 var clock=Stopwatch.StartNew();
87 uint waited=WaitForSingleObject(created.process,(uint)timeout);
88 if(waited!=0 && waited!=258)throw new System.ComponentModel.Win32Exception();
89 bool timedOut=waited==258;
90 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;}
91 if(timedOut)TerminateJobObject(job,124);
92 if(WaitForSingleObject(created.process,5000)!=0)throw new Exception("Process cleanup failed");
93 outThread.Join(5000);errThread.Join(5000);
94 uint code;if(!GetExitCodeProcess(created.process,out code))throw new System.ComponentModel.Win32Exception();
95 return new {exit=unchecked((int)code),stdout=stdout.Text(),stderr=stderr.Text(),timed_out=timedOut,stdout_truncated=stdout.truncated,stderr_truncated=stderr.truncated};
96 } finally {
97 TerminateJobObject(job,124);
98 if(created.process!=IntPtr.Zero)TerminateProcess(created.process,124);
99 foreach(var handle in new[]{created.process,created.thread,output,outputWrite,error,errorWrite,input})if(handle!=IntPtr.Zero && handle!=new IntPtr(-1))CloseHandle(handle);
100 WaitForEmpty(job,-1);CloseHandle(job);
101 if(outputStream!=null)outputStream.Dispose();if(errorStream!=null)errorStream.Dispose();
102 }
103
104 }
105 [StructLayout(LayoutKind.Sequential)] struct KEYBDINPUT {public ushort vk,scan;public uint flags,time;public UIntPtr extra;}
106 [StructLayout(LayoutKind.Explicit)] struct INPUTUNION {[FieldOffset(0)]public KEYBDINPUT keyboard;[FieldOffset(0)]public MOUSEINPUT mouse;}
107 [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT {public int x,y;public uint data,flags,time;public UIntPtr extra;}
108 [StructLayout(LayoutKind.Sequential)] struct INPUT {public uint type;public INPUTUNION data;}
109 [DllImport("user32.dll",SetLastError=true)] static extern uint SendInput(uint count, INPUT[] inputs,int size);
110 public static void Type(string text) {
111 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");}
112 }
113}
114
115public static class ComputerWorker {
116 static System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = 4194304 };
117 static string requestPath,responsePath;
118 static System.Collections.Generic.Dictionary<string,object> Map(object value) { return (System.Collections.Generic.Dictionary<string,object>)value; }
119 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; }
120 static string Text(System.Collections.Generic.Dictionary<string,object> value, string key, string fallback = "") { return Convert.ToString(Get(value,key,fallback)); }
121 static int Number(System.Collections.Generic.Dictionary<string,object> value, string key, int fallback = 0) { return Convert.ToInt32(Get(value,key,fallback)); }
122 [DllImport("user32.dll")] static extern bool SetProcessDPIAware();
123 [STAThread] public static void Main(string[] args) {
124 if(args.Length != 2) return;
125 requestPath=args[0];responsePath=args[1]; object result;
126 try { SetProcessDPIAware(); result=Run(Map(json.DeserializeObject(System.IO.File.ReadAllText(requestPath)))); }
127 catch(Exception error) { result=new { error=error.Message }; }
128 Reply(result);
129 }
130 static void Reply(object result) {System.IO.File.WriteAllText(responsePath,json.Serialize(result),new UTF8Encoding(false));}
131 static object Target(System.Windows.Automation.AutomationElement node) {
132 var current=node.Current;
133 using(var process=Process.GetProcessById(current.ProcessId)) {
134 return new {pid=current.ProcessId,started=process.StartTime.ToUniversalTime().Ticks.ToString(),id=String.Join(".",node.GetRuntimeId()),role=current.ControlType.ProgrammaticName,name=current.Name};
135 }
136 }
137 static System.Windows.Automation.AutomationElement Find(System.Collections.Generic.Dictionary<string,object> target) {
138 using(var process=Process.GetProcessById(Number(target,"pid"))) {
139 if(process.StartTime.ToUniversalTime().Ticks.ToString()!=Text(target,"started")) throw new Exception("The application changed. Read a fresh UI tree.");
140 }
141 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")));
142 var queue=new System.Collections.Generic.Queue<System.Windows.Automation.AutomationElement>();
143 foreach(System.Windows.Automation.AutomationElement root in roots)queue.Enqueue(root);
144 var walker=System.Windows.Automation.TreeWalker.ControlViewWalker;var clock=Stopwatch.StartNew();int count=0;
145 while(queue.Count>0 && count++<5000 && clock.ElapsedMilliseconds<8000) {
146 var node=queue.Dequeue();var current=node.Current;
147 if(String.Join(".",node.GetRuntimeId())==Text(target,"id") && current.Name==Text(target,"name") && current.ControlType.ProgrammaticName==Text(target,"role"))return node;
148 for(var child=walker.GetFirstChild(node);child!=null && queue.Count<5000;child=walker.GetNextSibling(child))queue.Enqueue(child);
149 }
150 throw new Exception("The UI element changed. Read a fresh tree.");
151 }
152 static object Ui(System.Collections.Generic.Dictionary<string,object> request) {
153 var nodes=new System.Collections.Generic.List<object>();
154 var queue=new System.Collections.Generic.Queue<Tuple<System.Windows.Automation.AutomationElement,int>>();
155 queue.Enqueue(Tuple.Create(System.Windows.Automation.AutomationElement.RootElement,0));
156 var walker=System.Windows.Automation.TreeWalker.ControlViewWalker;var clock=Stopwatch.StartNew();
157 while(queue.Count>0 && nodes.Count<1500 && clock.ElapsedMilliseconds<8000) {
158 var entry=queue.Dequeue();var node=entry.Item1;int depth=entry.Item2;
159 try {
160 var current=node.Current;
161 if(depth==1 && Number(request,"pid")>0 && current.ProcessId!=Number(request,"pid"))continue;
162 if(depth>0) {
163 var actions=new System.Collections.Generic.List<string>();actions.Add("focus");object pattern;string value=null;
164 if(node.TryGetCurrentPattern(System.Windows.Automation.InvokePattern.Pattern,out pattern))actions.Add("press");
165 if(node.TryGetCurrentPattern(System.Windows.Automation.TogglePattern.Pattern,out pattern))actions.Add("toggle");
166 if(node.TryGetCurrentPattern(System.Windows.Automation.SelectionItemPattern.Pattern,out pattern))actions.Add("select");
167 if(node.TryGetCurrentPattern(System.Windows.Automation.ExpandCollapsePattern.Pattern,out pattern)){actions.Add("expand");actions.Add("collapse");}
168 if(node.TryGetCurrentPattern(System.Windows.Automation.ValuePattern.Pattern,out pattern)) {
169 var properties=((System.Windows.Automation.ValuePattern)pattern).Current;
170 value=properties.Value;if(value.Length>1024)value=value.Substring(0,1024);
171 if(!properties.IsReadOnly)actions.Add("set_value");
172 } else if(node.TryGetCurrentPattern(System.Windows.Automation.TextPattern.Pattern,out pattern)) {
173 value=((System.Windows.Automation.TextPattern)pattern).DocumentRange.GetText(1024);
174 }
175 var r=current.BoundingRectangle;
176 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});
177 }
178 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));
179 } catch(System.Windows.Automation.ElementNotAvailableException) {} catch(ArgumentException) {} catch(InvalidOperationException) {}
180 }
181 return new {nodes=nodes,truncated=queue.Count>0};
182 }
183 static object UiAction(System.Collections.Generic.Dictionary<string,object> request) {
184 var node=Find(Map(Get(request,"target")));
185 switch(Text(request,"operation")) {
186 case "focus": node.SetFocus();break;
187 case "press": ((System.Windows.Automation.InvokePattern)node.GetCurrentPattern(System.Windows.Automation.InvokePattern.Pattern)).Invoke();break;
188 case "toggle": ((System.Windows.Automation.TogglePattern)node.GetCurrentPattern(System.Windows.Automation.TogglePattern.Pattern)).Toggle();break;
189 case "select": ((System.Windows.Automation.SelectionItemPattern)node.GetCurrentPattern(System.Windows.Automation.SelectionItemPattern.Pattern)).Select();break;
190 case "expand": ((System.Windows.Automation.ExpandCollapsePattern)node.GetCurrentPattern(System.Windows.Automation.ExpandCollapsePattern.Pattern)).Expand();break;
191 case "collapse": ((System.Windows.Automation.ExpandCollapsePattern)node.GetCurrentPattern(System.Windows.Automation.ExpandCollapsePattern.Pattern)).Collapse();break;
192 case "set_value": ((System.Windows.Automation.ValuePattern)node.GetCurrentPattern(System.Windows.Automation.ValuePattern.Pattern)).SetValue(Text(request,"value"));break;
193 default: throw new Exception("Choose an action reported by computer_ui.");
194 }
195 return new {completed=true};
196 }
197 static object Run(System.Collections.Generic.Dictionary<string,object> request) {
198 string action=Text(request,"action");string root=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
199 if(action=="status") {
200 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");
201 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};
202 }
203 if(action=="input") {
204 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};
205 }
206 if(action=="ui")return Ui(request);
207 if(action=="ui_action")return UiAction(request);
208 if(action=="exec" || action=="spawn") {
209 string runtime=Text(request,"runtime","default"),directory=System.IO.Path.GetDirectoryName(requestPath),file,exe,arguments,script=Text(request,"script");
210 if(runtime=="default")runtime="powershell";
211 switch(runtime) {
212 // PowerShell 3 caches pipeline encoding before the script runs.
213 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;
214 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;
215 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;
216 default:throw new Exception("Choose a runtime reported by computer_status.");
217 }
218 System.IO.File.WriteAllText(file,script,new UTF8Encoding(runtime!="cmd"));
219 string home=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
220 if(action=="exec")return ComputerProcess.Run(exe,arguments,home,Number(request,"timeout_ms"),requestPath);
221 return ComputerProcess.Run(exe,arguments,home,0,requestPath,Reply);
222 }
223 if(action=="process") {
224 string[] parts=Text(request,"id").Split(':');Process process;
225 try {process=Process.GetProcessById(Int32.Parse(parts[0]));}catch(ArgumentException){return new {running=false};}
226 using(process) {
227 if(parts.Length!=2 || process.StartTime.ToUniversalTime().Ticks.ToString()!=parts[1])return new {running=false};
228 if(Text(request,"operation")=="stop") {
229 var info=new ProcessStartInfo("taskkill.exe","/PID "+process.Id+" /T /F") {UseShellExecute=false,CreateNoWindow=true};
230 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};
231 }
232 return new {running=true,pid=process.Id};
233 }
234 }
235 if(action=="file") {
236 string path=Text(request,"path");
237 if(!System.Text.RegularExpressions.Regex.IsMatch(path,@"^[A-Za-z]:[\\/]") || path.IndexOf('\0')>=0)throw new Exception("Use an absolute guest file path.");
238 switch(Text(request,"operation")) {
239 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")};
240 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};
241 case "mkdir": System.IO.Directory.CreateDirectory(path);return new {path=path};
242 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};
243 case "remove": System.IO.File.Delete(path);return new {removed=true};
244 default: throw new Exception("Choose a supported file operation.");
245 }
246 }
247 throw new Exception("Choose a supported computer operation.");
248 }
249}