/
SilentProcessRunner.cs
238 lines (209 loc) · 8.79 KB
/
SilentProcessRunner.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Calamari.Util;
namespace Calamari.Integration.Processes
{
public static class SilentProcessRunner
{
// ReSharper disable once InconsistentNaming
private const int CP_OEMCP = 1;
private static readonly Encoding oemEncoding;
static SilentProcessRunner()
{
try
{
CPINFOEX info;
if (GetCPInfoEx(CP_OEMCP, 0, out info))
{
oemEncoding = Encoding.GetEncoding(info.CodePage);
}
else
{
oemEncoding = Encoding.GetEncoding(850);
}
}
catch (Exception)
{
Trace.WriteLine("Couldn't get default OEM encoding");
oemEncoding = Encoding.UTF8;
}
}
public static SilentProcessRunnerResult ExecuteCommand(
string executable,
string arguments,
string workingDirectory,
Action<string> output,
Action<string> error)
{
return ExecuteCommand(executable, arguments, workingDirectory, null, null, null, output, error);
}
public static SilentProcessRunnerResult ExecuteCommand(
string executable,
string arguments,
string workingDirectory,
Dictionary<string, string> environmentVars,
Action<string> output,
Action<string> error)
{
return ExecuteCommand(executable, arguments, workingDirectory, environmentVars, null, null, output, error);
}
public static SilentProcessRunnerResult ExecuteCommand(
string executable,
string arguments,
string workingDirectory,
Dictionary<string, string> environmentVars,
string userName,
SecureString password,
Action<string> output,
Action<string> error)
{
try
{
using (var process = new Process())
{
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.StandardOutputEncoding = oemEncoding;
process.StartInfo.StandardErrorEncoding = oemEncoding;
if (environmentVars != null)
{
foreach (string environmentVar in environmentVars.Keys)
{
process.StartInfo.EnvironmentVariables[environmentVar] = environmentVars[environmentVar];
}
}
RunProcessWithCredentials(process.StartInfo, userName, password);
using (var outputWaitHandle = new AutoResetEvent(false))
using (var errorWaitHandle = new AutoResetEvent(false))
{
var errorData = new StringBuilder();
process.OutputDataReceived += (sender, e) =>
{
try
{
if (e.Data == null)
outputWaitHandle.Set();
else
output(e.Data);
}
catch (Exception ex)
{
try
{
error($"Error occured handling message: {ex.PrettyPrint()}");
}
catch
{
// Ignore
}
}
};
process.ErrorDataReceived += (sender, e) =>
{
try
{
if (e.Data == null)
errorWaitHandle.Set();
else
{
errorData.AppendLine(e.Data);
error(e.Data);
}
}
catch (Exception ex)
{
try
{
error($"Error occured handling message: {ex.PrettyPrint()}");
}
catch
{
// Ignore
}
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
outputWaitHandle.WaitOne();
errorWaitHandle.WaitOne();
return new SilentProcessRunnerResult(process.ExitCode, errorData.ToString());
}
}
}
catch (Exception ex)
{
throw new Exception($"Error when attempting to execute {executable}: {ex.Message}", ex);
}
}
static void RunProcessWithCredentials(ProcessStartInfo processStartInfo, string userName, SecureString password)
{
if (string.IsNullOrEmpty(userName) || password == null)
{
return;
}
var parts = userName.Split(new[] { '\\' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
var domainPart = parts[0];
var userNamePart = parts[1];
processStartInfo.Domain = domainPart;
processStartInfo.UserName = userNamePart;
WindowStationAndDesktopAccess.GrantAccessToWindowStationAndDesktop(userNamePart, domainPart);
}
else
{
processStartInfo.UserName = userName;
WindowStationAndDesktopAccess.GrantAccessToWindowStationAndDesktop(userName);
}
processStartInfo.Password = password;
// Environment variables (such as {env:TentacleHome}) are usually inherited from the parent process.
// When running as a different user they are not inherited, so manually add them to the process.
AddTentacleEnvironmentVariablesToProcess(processStartInfo);
}
static void AddTentacleEnvironmentVariablesToProcess(ProcessStartInfo processStartInfo)
{
foreach (DictionaryEntry environmentVariable in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process))
{
var key = environmentVariable.Key.ToString();
if (!key.StartsWith("Tentacle"))
{
continue;
}
processStartInfo.EnvironmentVariables[key] = environmentVariable.Value.ToString();
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetCPInfoEx([MarshalAs(UnmanagedType.U4)] int CodePage, [MarshalAs(UnmanagedType.U4)] int dwFlags, out CPINFOEX lpCPInfoEx);
private const int MAX_DEFAULTCHAR = 2;
private const int MAX_LEADBYTES = 12;
private const int MAX_PATH = 260;
[StructLayout(LayoutKind.Sequential)]
private struct CPINFOEX
{
[MarshalAs(UnmanagedType.U4)]
public int MaxCharSize;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_DEFAULTCHAR)]
public byte[] DefaultChar;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_LEADBYTES)]
public byte[] LeadBytes;
public char UnicodeDefaultChar;
[MarshalAs(UnmanagedType.U4)]
public int CodePage;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string CodePageName;
}
}
}