Debian Codegraph @

lib/ansible/module_utils/csharp/Ansible.Process.cs

raw
1 using Microsoft.Win32.SafeHandles;
2 using System;
3 using System.Collections;
4 using System.IO;
5 using System.Linq;
6 using System.Runtime.InteropServices;
7 using System.Text;
8 using System.Threading;
9
10 namespace Ansible.Process
11 {
12 internal class NativeHelpers
13 {
14 [StructLayout(LayoutKind.Sequential)]
15 public class SECURITY_ATTRIBUTES
16 {
17 public UInt32 nLength;
18 public IntPtr lpSecurityDescriptor;
19 public bool bInheritHandle = false;
20 public SECURITY_ATTRIBUTES()
21 {
22 nLength = (UInt32)Marshal.SizeOf(this);
23 }
24 }
25
26 [StructLayout(LayoutKind.Sequential)]
27 public class STARTUPINFO
28 {
29 public UInt32 cb;
30 public IntPtr lpReserved;
31 [MarshalAs(UnmanagedType.LPWStr)] public string lpDesktop;
32 [MarshalAs(UnmanagedType.LPWStr)] public string lpTitle;
33 public UInt32 dwX;
34 public UInt32 dwY;
35 public UInt32 dwXSize;
36 public UInt32 dwYSize;
37 public UInt32 dwXCountChars;
38 public UInt32 dwYCountChars;
39 public UInt32 dwFillAttribute;
40 public StartupInfoFlags dwFlags;
41 public UInt16 wShowWindow;
42 public UInt16 cbReserved2;
43 public IntPtr lpReserved2;
44 public SafeFileHandle hStdInput;
45 public SafeFileHandle hStdOutput;
46 public SafeFileHandle hStdError;
47 public STARTUPINFO()
48 {
49 cb = (UInt32)Marshal.SizeOf(this);
50 }
51 }
52
53 [StructLayout(LayoutKind.Sequential)]
54 public class STARTUPINFOEX
55 {
56 public STARTUPINFO startupInfo;
57 public IntPtr lpAttributeList;
58 public STARTUPINFOEX()
59 {
60 startupInfo = new STARTUPINFO();
61 startupInfo.cb = (UInt32)Marshal.SizeOf(this);
62 }
63 }
64
65 [StructLayout(LayoutKind.Sequential)]
66 public struct PROCESS_INFORMATION
67 {
68 public IntPtr hProcess;
69 public IntPtr hThread;
70 public int dwProcessId;
71 public int dwThreadId;
72 }
73
74 [Flags]
75 public enum ProcessCreationFlags : uint
76 {
77 CREATE_NEW_CONSOLE = 0x00000010,
78 CREATE_UNICODE_ENVIRONMENT = 0x00000400,
79 EXTENDED_STARTUPINFO_PRESENT = 0x00080000
80 }
81
82 [Flags]
83 public enum StartupInfoFlags : uint
84 {
85 USESTDHANDLES = 0x00000100
86 }
87
88 [Flags]
89 public enum HandleFlags : uint
90 {
91 None = 0,
92 INHERIT = 1
93 }
94 }
95
96 internal class NativeMethods
97 {
98 [DllImport("kernel32.dll", SetLastError = true)]
99 public static extern bool AllocConsole();
100
101 [DllImport("shell32.dll", SetLastError = true)]
102 public static extern SafeMemoryBuffer CommandLineToArgvW(
103 [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
104 out int pNumArgs);
105
106 [DllImport("kernel32.dll", SetLastError = true)]
107 public static extern bool CreatePipe(
108 out SafeFileHandle hReadPipe,
109 out SafeFileHandle hWritePipe,
110 NativeHelpers.SECURITY_ATTRIBUTES lpPipeAttributes,
111 UInt32 nSize);
112
113 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
114 public static extern bool CreateProcessW(
115 [MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName,
116 StringBuilder lpCommandLine,
117 IntPtr lpProcessAttributes,
118 IntPtr lpThreadAttributes,
119 bool bInheritHandles,
120 NativeHelpers.ProcessCreationFlags dwCreationFlags,
121 SafeMemoryBuffer lpEnvironment,
122 [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory,
123 NativeHelpers.STARTUPINFOEX lpStartupInfo,
124 out NativeHelpers.PROCESS_INFORMATION lpProcessInformation);
125
126 [DllImport("kernel32.dll", SetLastError = true)]
127 public static extern bool FreeConsole();
128
129 [DllImport("kernel32.dll", SetLastError = true)]
130 public static extern IntPtr GetConsoleWindow();
131
132 [DllImport("kernel32.dll", SetLastError = true)]
133 public static extern bool GetExitCodeProcess(
134 SafeWaitHandle hProcess,
135 out UInt32 lpExitCode);
136
137 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
138 public static extern uint SearchPathW(
139 [MarshalAs(UnmanagedType.LPWStr)] string lpPath,
140 [MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
141 [MarshalAs(UnmanagedType.LPWStr)] string lpExtension,
142 UInt32 nBufferLength,
143 [MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpBuffer,
144 out IntPtr lpFilePart);
145
146 [DllImport("kernel32.dll", SetLastError = true)]
147 public static extern bool SetConsoleCP(
148 UInt32 wCodePageID);
149
150 [DllImport("kernel32.dll", SetLastError = true)]
151 public static extern bool SetConsoleOutputCP(
152 UInt32 wCodePageID);
153
154 [DllImport("kernel32.dll", SetLastError = true)]
155 public static extern bool SetHandleInformation(
156 SafeFileHandle hObject,
157 NativeHelpers.HandleFlags dwMask,
158 NativeHelpers.HandleFlags dwFlags);
159
160 [DllImport("kernel32.dll")]
161 public static extern UInt32 WaitForSingleObject(
162 SafeWaitHandle hHandle,
163 UInt32 dwMilliseconds);
164 }
165
166 internal class SafeMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid
167 {
168 public SafeMemoryBuffer() : base(true) { }
169 public SafeMemoryBuffer(int cb) : base(true)
170 {
171 base.SetHandle(Marshal.AllocHGlobal(cb));
172 }
173 public SafeMemoryBuffer(IntPtr handle) : base(true)
174 {
175 base.SetHandle(handle);
176 }
177
178 protected override bool ReleaseHandle()
179 {
180 Marshal.FreeHGlobal(handle);
181 return true;
182 }
183 }
184
185 public class Win32Exception : System.ComponentModel.Win32Exception
186 {
187 private string _msg;
188
189 public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { }
190 public Win32Exception(int errorCode, string message) : base(errorCode)
191 {
192 _msg = String.Format("{0} ({1}, Win32ErrorCode {2})", message, base.Message, errorCode);
193 }
194
195 public override string Message { get { return _msg; } }
196 public static explicit operator Win32Exception(string message) { return new Win32Exception(message); }
197 }
198
199 public class Result
200 {
201 public string StandardOut { get; internal set; }
202 public string StandardError { get; internal set; }
203 public uint ExitCode { get; internal set; }
204 }
205
206 public class ProcessUtil
207 {
208 /// <summary>
209 /// Parses a command line string into an argv array according to the Windows rules
210 /// </summary>
211 /// <param name="lpCommandLine">The command line to parse</param>
212 /// <returns>An array of arguments interpreted by Windows</returns>
213 public static string[] ParseCommandLine(string lpCommandLine)
214 {
215 int numArgs;
216 using (SafeMemoryBuffer buf = NativeMethods.CommandLineToArgvW(lpCommandLine, out numArgs))
217 {
218 if (buf.IsInvalid)
219 throw new Win32Exception("Error parsing command line");
220 IntPtr[] strptrs = new IntPtr[numArgs];
221 Marshal.Copy(buf.DangerousGetHandle(), strptrs, 0, numArgs);
222 return strptrs.Select(s => Marshal.PtrToStringUni(s)).ToArray();
223 }
224 }
225
226 /// <summary>
227 /// Searches the path for the executable specified. Will throw a Win32Exception if the file is not found.
228 /// </summary>
229 /// <param name="lpFileName">The executable to search for</param>
230 /// <returns>The full path of the executable to search for</returns>
231 public static string SearchPath(string lpFileName)
232 {
233 StringBuilder sbOut = new StringBuilder(0);
234 IntPtr filePartOut = IntPtr.Zero;
235 UInt32 res = NativeMethods.SearchPathW(null, lpFileName, null, (UInt32)sbOut.Capacity, sbOut, out filePartOut);
236 if (res == 0)
237 {
238 int lastErr = Marshal.GetLastWin32Error();
239 if (lastErr == 2) // ERROR_FILE_NOT_FOUND
240 throw new FileNotFoundException(String.Format("Could not find file '{0}'.", lpFileName));
241 else
242 throw new Win32Exception(String.Format("SearchPathW({0}) failed to get buffer length", lpFileName));
243 }
244
245 sbOut.EnsureCapacity((int)res);
246 if (NativeMethods.SearchPathW(null, lpFileName, null, (UInt32)sbOut.Capacity, sbOut, out filePartOut) == 0)
247 throw new Win32Exception(String.Format("SearchPathW({0}) failed", lpFileName));
248
249 return sbOut.ToString();
250 }
251
252 public static Result CreateProcess(string command)
253 {
254 return CreateProcess(null, command, null, null, String.Empty);
255 }
256
257 public static Result CreateProcess(string lpApplicationName, string lpCommandLine, string lpCurrentDirectory,
258 IDictionary environment)
259 {
260 return CreateProcess(lpApplicationName, lpCommandLine, lpCurrentDirectory, environment, String.Empty);
261 }
262
263 public static Result CreateProcess(string lpApplicationName, string lpCommandLine, string lpCurrentDirectory,
264 IDictionary environment, string stdin)
265 {
266 return CreateProcess(lpApplicationName, lpCommandLine, lpCurrentDirectory, environment, stdin, null);
267 }
268
269 public static Result CreateProcess(string lpApplicationName, string lpCommandLine, string lpCurrentDirectory,
270 IDictionary environment, byte[] stdin)
271 {
272 return CreateProcess(lpApplicationName, lpCommandLine, lpCurrentDirectory, environment, stdin, null);
273 }
274
275 public static Result CreateProcess(string lpApplicationName, string lpCommandLine, string lpCurrentDirectory,
276 IDictionary environment, string stdin, string outputEncoding)
277 {
278 byte[] stdinBytes;
279 if (String.IsNullOrEmpty(stdin))
280 stdinBytes = new byte[0];
281 else
282 {
283 if (!stdin.EndsWith(Environment.NewLine))
284 stdin += Environment.NewLine;
285 stdinBytes = new UTF8Encoding(false).GetBytes(stdin);
286 }
287 return CreateProcess(lpApplicationName, lpCommandLine, lpCurrentDirectory, environment, stdinBytes, outputEncoding);
288 }
289
290 /// <summary>
291 /// Creates a process based on the CreateProcess API call.
292 /// </summary>
293 /// <param name="lpApplicationName">The name of the executable or batch file to execute</param>
294 /// <param name="lpCommandLine">The command line to execute, typically this includes lpApplication as the first argument</param>
295 /// <param name="lpCurrentDirectory">The full path to the current directory for the process, null will have the same cwd as the calling process</param>
296 /// <param name="environment">A dictionary of key/value pairs to define the new process environment</param>
297 /// <param name="stdin">A byte array to send over the stdin pipe</param>
298 /// <param name="outputEncoding">The character encoding for decoding stdout/stderr output of the process.</param>
299 /// <returns>Result object that contains the command output and return code</returns>
300 public static Result CreateProcess(string lpApplicationName, string lpCommandLine, string lpCurrentDirectory,
301 IDictionary environment, byte[] stdin, string outputEncoding)
302 {
303 NativeHelpers.ProcessCreationFlags creationFlags = NativeHelpers.ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT |
304 NativeHelpers.ProcessCreationFlags.EXTENDED_STARTUPINFO_PRESENT;
305 NativeHelpers.PROCESS_INFORMATION pi = new NativeHelpers.PROCESS_INFORMATION();
306 NativeHelpers.STARTUPINFOEX si = new NativeHelpers.STARTUPINFOEX();
307 si.startupInfo.dwFlags = NativeHelpers.StartupInfoFlags.USESTDHANDLES;
308
309 SafeFileHandle stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinRead, stdinWrite;
310 CreateStdioPipes(si, out stdoutRead, out stdoutWrite, out stderrRead, out stderrWrite, out stdinRead,
311 out stdinWrite);
312 FileStream stdinStream = new FileStream(stdinWrite, FileAccess.Write);
313
314 // $null from PowerShell ends up as an empty string, we need to convert back as an empty string doesn't
315 // make sense for these parameters
316 if (lpApplicationName == "")
317 lpApplicationName = null;
318
319 if (lpCurrentDirectory == "")
320 lpCurrentDirectory = null;
321
322 using (SafeMemoryBuffer lpEnvironment = CreateEnvironmentPointer(environment))
323 {
324 // Create console with utf-8 CP if no existing console is present
325 bool isConsole = false;
326 if (NativeMethods.GetConsoleWindow() == IntPtr.Zero)
327 {
328 isConsole = NativeMethods.AllocConsole();
329
330 // Set console input/output codepage to UTF-8
331 NativeMethods.SetConsoleCP(65001);
332 NativeMethods.SetConsoleOutputCP(65001);
333 }
334
335 try
336 {
337 StringBuilder commandLine = new StringBuilder(lpCommandLine);
338 if (!NativeMethods.CreateProcessW(lpApplicationName, commandLine, IntPtr.Zero, IntPtr.Zero,
339 true, creationFlags, lpEnvironment, lpCurrentDirectory, si, out pi))
340 {
341 throw new Win32Exception("CreateProcessW() failed");
342 }
343 }
344 finally
345 {
346 if (isConsole)
347 NativeMethods.FreeConsole();
348 }
349 }
350
351 return WaitProcess(stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinStream, stdin, pi.hProcess,
352 outputEncoding);
353 }
354
355 internal static void CreateStdioPipes(NativeHelpers.STARTUPINFOEX si, out SafeFileHandle stdoutRead,
356 out SafeFileHandle stdoutWrite, out SafeFileHandle stderrRead, out SafeFileHandle stderrWrite,
357 out SafeFileHandle stdinRead, out SafeFileHandle stdinWrite)
358 {
359 NativeHelpers.SECURITY_ATTRIBUTES pipesec = new NativeHelpers.SECURITY_ATTRIBUTES();
360 pipesec.bInheritHandle = true;
361
362 if (!NativeMethods.CreatePipe(out stdoutRead, out stdoutWrite, pipesec, 0))
363 throw new Win32Exception("STDOUT pipe setup failed");
364 if (!NativeMethods.SetHandleInformation(stdoutRead, NativeHelpers.HandleFlags.INHERIT, 0))
365 throw new Win32Exception("STDOUT pipe handle setup failed");
366
367 if (!NativeMethods.CreatePipe(out stderrRead, out stderrWrite, pipesec, 0))
368 throw new Win32Exception("STDERR pipe setup failed");
369 if (!NativeMethods.SetHandleInformation(stderrRead, NativeHelpers.HandleFlags.INHERIT, 0))
370 throw new Win32Exception("STDERR pipe handle setup failed");
371
372 if (!NativeMethods.CreatePipe(out stdinRead, out stdinWrite, pipesec, 0))
373 throw new Win32Exception("STDIN pipe setup failed");
374 if (!NativeMethods.SetHandleInformation(stdinWrite, NativeHelpers.HandleFlags.INHERIT, 0))
375 throw new Win32Exception("STDIN pipe handle setup failed");
376
377 si.startupInfo.hStdOutput = stdoutWrite;
378 si.startupInfo.hStdError = stderrWrite;
379 si.startupInfo.hStdInput = stdinRead;
380 }
381
382 internal static SafeMemoryBuffer CreateEnvironmentPointer(IDictionary environment)
383 {
384 IntPtr lpEnvironment = IntPtr.Zero;
385 if (environment != null && environment.Count > 0)
386 {
387 StringBuilder environmentString = new StringBuilder();
388 foreach (DictionaryEntry kv in environment)
389 environmentString.AppendFormat("{0}={1}\0", kv.Key, kv.Value);
390 environmentString.Append('\0');
391
392 lpEnvironment = Marshal.StringToHGlobalUni(environmentString.ToString());
393 }
394 return new SafeMemoryBuffer(lpEnvironment);
395 }
396
397 internal static Result WaitProcess(SafeFileHandle stdoutRead, SafeFileHandle stdoutWrite, SafeFileHandle stderrRead,
398 SafeFileHandle stderrWrite, FileStream stdinStream, byte[] stdin, IntPtr hProcess, string outputEncoding = null)
399 {
400 // Default to using UTF-8 as the output encoding, this should be a logical default for most scenarios.
401 outputEncoding = String.IsNullOrEmpty(outputEncoding) ? "utf-8" : outputEncoding;
402 Encoding encodingInstance = Encoding.GetEncoding(outputEncoding);
403
404 FileStream stdoutFS = new FileStream(stdoutRead, FileAccess.Read, 4096);
405 StreamReader stdout = new StreamReader(stdoutFS, encodingInstance, true, 4096);
406 stdoutWrite.Close();
407
408 FileStream stderrFS = new FileStream(stderrRead, FileAccess.Read, 4096);
409 StreamReader stderr = new StreamReader(stderrFS, encodingInstance, true, 4096);
410 stderrWrite.Close();
411
412 stdinStream.Write(stdin, 0, stdin.Length);
413 stdinStream.Close();
414
415 string stdoutStr, stderrStr = null;
416 GetProcessOutput(stdout, stderr, out stdoutStr, out stderrStr);
417 UInt32 rc = GetProcessExitCode(hProcess);
418
419 return new Result
420 {
421 StandardOut = stdoutStr,
422 StandardError = stderrStr,
423 ExitCode = rc
424 };
425 }
426
427 internal static void GetProcessOutput(StreamReader stdoutStream, StreamReader stderrStream, out string stdout, out string stderr)
428 {
429 var sowait = new EventWaitHandle(false, EventResetMode.ManualReset);
430 var sewait = new EventWaitHandle(false, EventResetMode.ManualReset);
431 string so = null, se = null;
432 ThreadPool.QueueUserWorkItem((s) =>
433 {
434 so = stdoutStream.ReadToEnd();
435 sowait.Set();
436 });
437 ThreadPool.QueueUserWorkItem((s) =>
438 {
439 se = stderrStream.ReadToEnd();
440 sewait.Set();
441 });
442 foreach (var wh in new WaitHandle[] { sowait, sewait })
443 wh.WaitOne();
444 stdout = so;
445 stderr = se;
446 }
447
448 internal static UInt32 GetProcessExitCode(IntPtr processHandle)
449 {
450 SafeWaitHandle hProcess = new SafeWaitHandle(processHandle, true);
451 NativeMethods.WaitForSingleObject(hProcess, 0xFFFFFFFF);
452
453 UInt32 exitCode;
454 if (!NativeMethods.GetExitCodeProcess(hProcess, out exitCode))
455 throw new Win32Exception("GetExitCodeProcess() failed");
456 return exitCode;
457 }
458 }
459 }