Repository navigation
Expand file tree
/
Copy pathwindows_controller.cs
More file actions
324 lines (293 loc) · 11.9 KB
/
Copy pathwindows_controller.cs
File metadata and controls
324 lines (293 loc) · 11.9 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Text;
namespace WebCodexPersistentShell
{
public sealed class UserHost : PSHost
{
private readonly PSHost inner;
private readonly Guid instanceId = Guid.NewGuid();
public UserHost(PSHost inner)
{
if (inner == null)
{
throw new ArgumentNullException("inner");
}
this.inner = inner;
}
public override Guid InstanceId
{
get { return instanceId; }
}
public override string Name
{
get { return "WebCodexPersistentShellUserHost"; }
}
public override Version Version
{
get { return inner.Version; }
}
public override PSHostUserInterface UI
{
get { return inner.UI; }
}
public override CultureInfo CurrentCulture
{
get { return inner.CurrentCulture; }
}
public override CultureInfo CurrentUICulture
{
get { return inner.CurrentUICulture; }
}
public override void SetShouldExit(int requestedExitCode)
{
// `exit N` is shell termination, not command completion. Terminate
// the owned PowerShell process immediately so controller code can
// never publish a completion frame for an exited user shell.
Environment.Exit(requestedExitCode);
}
public override void EnterNestedPrompt()
{
inner.EnterNestedPrompt();
}
public override void ExitNestedPrompt()
{
inner.ExitNestedPrompt();
}
public override void NotifyBeginApplication()
{
inner.NotifyBeginApplication();
}
public override void NotifyEndApplication()
{
inner.NotifyEndApplication();
}
}
public static class Controller
{
private const string StdoutMagic = "WCPSO1";
private const string StderrMagic = "WCPSE1";
private const string ControlMagic = "WCPS1";
private const string StatusTag = "WebCodexPersistentShellCommandStatus";
private const string StatusProbe = "([int][bool]$?).ToString([Globalization.CultureInfo]::InvariantCulture) + ':' + ([int]$LASTEXITCODE).ToString([Globalization.CultureInfo]::InvariantCulture)";
private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(false);
private static readonly Encoding Ascii = Encoding.ASCII;
public static void Run(PSHost outerHost)
{
Stream stdin = Console.OpenStandardInput();
Stream stdout = Console.OpenStandardOutput();
Stream stderr = Console.OpenStandardError();
StreamReader reader = new StreamReader(stdin, Utf8NoBom, false, 4096, true);
UserHost userHost = new UserHost(outerHost);
Runspace userRunspace = RunspaceFactory.CreateRunspace(userHost);
userRunspace.Open();
try
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(new char[] { '\t' });
if (parts.Length != 3 || !ValidToken(parts[0]))
{
Environment.Exit(125);
return;
}
// Framing authority is deliberately confined to these stack locals.
// Neither the token nor the publication target is stored in a
// PowerShell variable, Runspace SessionState, host field, or static field.
string token = parts[0];
string source;
string controlPath;
try
{
source = Utf8NoBom.GetString(Convert.FromBase64String(parts[1]));
controlPath = Utf8NoBom.GetString(Convert.FromBase64String(parts[2]));
}
catch (Exception)
{
Environment.Exit(125);
return;
}
if (String.IsNullOrEmpty(controlPath))
{
Environment.Exit(125);
return;
}
int status = InvokeUserCommand(userRunspace, source, stderr);
// These writes are reachable only after InvokeUserCommand returned.
// User PowerShell can write marker-like bytes, but it cannot learn
// the active token/control target through shell-language state.
WriteSync(stdout, StdoutMagic, token);
WriteSync(stderr, StderrMagic, token);
string cwd;
try
{
cwd = userRunspace.SessionStateProxy.Path.CurrentLocation.ProviderPath;
}
catch (Exception)
{
Environment.Exit(125);
return;
}
if (String.IsNullOrEmpty(cwd))
{
Environment.Exit(125);
return;
}
string controlText = ControlMagic + '\0' + token + '\0' + status.ToString(CultureInfo.InvariantCulture) + '\0' + cwd + '\0';
string temporaryControlPath = controlPath + ".tmp";
try
{
File.WriteAllBytes(temporaryControlPath, Utf8NoBom.GetBytes(controlText));
File.Move(temporaryControlPath, controlPath);
}
catch (Exception)
{
try { File.Delete(temporaryControlPath); } catch (Exception) { }
Environment.Exit(125);
return;
}
}
}
finally
{
try { userRunspace.Close(); } catch (Exception) { }
userRunspace.Dispose();
reader.Dispose();
}
}
private static int InvokeUserCommand(Runspace userRunspace, string source, Stream stderr)
{
int status = 0;
Collection<PSObject> results = null;
using (PowerShell shell = PowerShell.Create())
{
shell.Runspace = userRunspace;
try
{
// Match the prior Windows transport's per-command native-status reset.
userRunspace.SessionStateProxy.SetVariable("LASTEXITCODE", 0);
// Keep user source, user output rendering, and trusted status capture as
// separate command components in one invocation. A top-level `return`
// can end only the user script component; it cannot skip StatusProbe.
// Out-Default consumes user success output before the final component,
// so Invoke() returns only the controller-owned status value.
shell.AddScript(source, false);
// Pin the built-in renderer by module-qualified cmdlet identity. The
// persistent user Runspace may contain a user-defined Out-Default
// function or alias; resolving that name dynamically would let user
// state run between source and the trusted status probe.
shell.AddCommand("Microsoft.PowerShell.Core\\Out-Default");
shell.AddScript(StatusProbe, false);
results = shell.Invoke();
}
catch (Exception error)
{
status = 1;
if (shell.Streams.Error.Count == 0)
{
WriteErrorLine(stderr, error.ToString());
}
}
foreach (ErrorRecord errorRecord in shell.Streams.Error)
{
WriteErrorLine(stderr, errorRecord.ToString());
}
if (status == 0)
{
int capturedStatus;
if (TryReadCommandStatus(results, shell, out capturedStatus))
{
status = capturedStatus;
}
else
{
// Trusted status is mandatory. Never infer success from an
// otherwise clean invocation when the host-owned result is absent.
status = 1;
}
}
}
return status;
}
private static bool TryReadCommandStatus(Collection<PSObject> results, PowerShell shell, out int status)
{
status = 1;
if (results == null || results.Count != 1 || results[0] == null)
{
return false;
}
string[] parts = results[0].ToString().Split(new char[] { ':' });
int nativeExitCode;
if (parts.Length != 2
|| (parts[0] != "0" && parts[0] != "1")
|| !Int32.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out nativeExitCode))
{
return false;
}
bool ok = parts[0] == "1";
bool statusStreamTampered = HasUserStatusRecord(shell);
if (statusStreamTampered && shell.HadErrors)
{
// The legacy public Information tag is no longer an authority channel.
// If user code writes it while this invocation also has real failure
// evidence, fail closed instead of allowing that write to turn the
// final `$?` back to success. A clean successful command remains clean,
// so a forged failure record cannot manufacture an exit code either.
status = nativeExitCode != 0 ? nativeExitCode : 1;
}
else
{
status = ok ? 0 : (nativeExitCode != 0 ? nativeExitCode : 1);
}
return true;
}
private static bool HasUserStatusRecord(PowerShell shell)
{
foreach (InformationRecord record in shell.Streams.Information)
{
foreach (string tag in record.Tags)
{
if (String.Equals(tag, StatusTag, StringComparison.Ordinal))
{
return true;
}
}
}
return false;
}
private static void WriteSync(Stream stream, string magic, string token)
{
byte[] bytes = Ascii.GetBytes(magic + '\0' + token + '\0');
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
private static void WriteErrorLine(Stream stderr, string text)
{
byte[] bytes = Utf8NoBom.GetBytes((text ?? String.Empty) + Environment.NewLine);
stderr.Write(bytes, 0, bytes.Length);
stderr.Flush();
}
private static bool ValidToken(string token)
{
if (token == null || token.Length != 32)
{
return false;
}
for (int index = 0; index < token.Length; index++)
{
char value = token[index];
if (!((value >= '0' && value <= '9') || (value >= 'a' && value <= 'f')))
{
return false;
}
}
return true;
}
}
}