@mrrlin-dev/mcp 0.4.227 → 0.4.230

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1208 @@
1
+ // Mrrlin drain service for Windows (openspec change f54-trusted-attempt-drain, design §2.5).
2
+ //
3
+ // Compiled at install with the .NET Framework's own csc.exe (C# 5), so it uses nothing newer than C# 5 and
4
+ // references only System, System.Core and System.ServiceProcess:
5
+ // csc.exe /nologo /target:exe /r:System.ServiceProcess.dll /out:MrrlinDrain.exe MrrlinDrain.cs
6
+ //
7
+ // It runs as the virtual account NT SERVICE\MrrlinDrain. Per bridge connection on \\.\pipe\mrrlin-drain it
8
+ // speaks the same framed protocol as the Linux daemon (apps/mcp/src/drain-service/protocol.ts):
9
+ // frame = u32 BE length · u8 kind (1 control JSON, 2 data bytes) · body
10
+ // `start` impersonates the pipe client, checks that it is the configured provider account and not elevated,
11
+ // launches the attempt worker with CreateProcessWithTokenW(CREATE_SUSPENDED), assigns it to a fresh Job
12
+ // (KILL_ON_JOB_CLOSE, no breakaway) and resumes it. Data frames carry the worker's stdin/stdout.
13
+ //
14
+ // Drain (stop, bridge EOF or the deadline received in `start`): TerminateJobObject until ActiveProcesses is
15
+ // 0 and every held process handle is signaled. `drained` additionally requires that the service held a handle
16
+ // for EVERY process the Job ever contained (held == TotalProcesses); a process it never managed to open makes
17
+ // the verdict unknown(windows_unaccounted_process). Past the drain deadline: unknown(windows_drain_timeout).
18
+ // Statements are signed (ECDSA P-256 over SHA-256, IEEE-P1363, base64url) over
19
+ // "mrrlin:drain-statement:v1\n" + canonical JSON, spooled atomically before the IPC answer, and journaled so a
20
+ // restarted service reports unknown(service_restart) for every supervision it had open.
21
+ using System;
22
+ using System.Collections.Generic;
23
+ using System.ComponentModel;
24
+ using System.IO;
25
+ using System.Runtime.InteropServices;
26
+ using System.Security.AccessControl;
27
+ using System.Security.Cryptography;
28
+ using System.Security.Principal;
29
+ using System.ServiceProcess;
30
+ using System.Text;
31
+ using System.Threading;
32
+ using Microsoft.Win32.SafeHandles;
33
+
34
+ namespace Mrrlin.Drain
35
+ {
36
+ // ------------------------------------------------------------------------------------------------
37
+ // Minimal JSON: a parser for control messages and config, and a canonical writer (keys sorted).
38
+ // ------------------------------------------------------------------------------------------------
39
+ public static class Json
40
+ {
41
+ const int MaxDepth = 32;
42
+
43
+ public static object Parse(string text)
44
+ {
45
+ int i = 0;
46
+ object value = ParseValue(text, ref i, 0);
47
+ SkipWs(text, ref i);
48
+ if (i != text.Length) throw new FormatException("json: trailing data");
49
+ return value;
50
+ }
51
+
52
+ static void SkipWs(string s, ref int i)
53
+ {
54
+ while (i < s.Length && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++;
55
+ }
56
+
57
+ static object ParseValue(string s, ref int i, int depth)
58
+ {
59
+ if (depth > MaxDepth) throw new FormatException("json: nested too deeply");
60
+ SkipWs(s, ref i);
61
+ if (i >= s.Length) throw new FormatException("json: unexpected end");
62
+ char c = s[i];
63
+ if (c == '{')
64
+ {
65
+ var obj = new SortedDictionary<string, object>(StringComparer.Ordinal);
66
+ i++;
67
+ SkipWs(s, ref i);
68
+ if (i < s.Length && s[i] == '}') { i++; return obj; }
69
+ while (true)
70
+ {
71
+ SkipWs(s, ref i);
72
+ string key = ParseString(s, ref i);
73
+ SkipWs(s, ref i);
74
+ if (i >= s.Length || s[i] != ':') throw new FormatException("json: expected ':'");
75
+ i++;
76
+ obj[key] = ParseValue(s, ref i, depth + 1);
77
+ SkipWs(s, ref i);
78
+ if (i < s.Length && s[i] == ',') { i++; continue; }
79
+ if (i < s.Length && s[i] == '}') { i++; return obj; }
80
+ throw new FormatException("json: expected ',' or '}'");
81
+ }
82
+ }
83
+ if (c == '[')
84
+ {
85
+ var list = new List<object>();
86
+ i++;
87
+ SkipWs(s, ref i);
88
+ if (i < s.Length && s[i] == ']') { i++; return list; }
89
+ while (true)
90
+ {
91
+ list.Add(ParseValue(s, ref i, depth + 1));
92
+ SkipWs(s, ref i);
93
+ if (i < s.Length && s[i] == ',') { i++; continue; }
94
+ if (i < s.Length && s[i] == ']') { i++; return list; }
95
+ throw new FormatException("json: expected ',' or ']'");
96
+ }
97
+ }
98
+ if (c == '"') return ParseString(s, ref i);
99
+ if (s.Length - i >= 4 && string.CompareOrdinal(s, i, "true", 0, 4) == 0) { i += 4; return true; }
100
+ if (s.Length - i >= 5 && string.CompareOrdinal(s, i, "false", 0, 5) == 0) { i += 5; return false; }
101
+ if (s.Length - i >= 4 && string.CompareOrdinal(s, i, "null", 0, 4) == 0) { i += 4; return null; }
102
+ int start = i;
103
+ if (i < s.Length && s[i] == '-') i++;
104
+ while (i < s.Length && ((s[i] >= '0' && s[i] <= '9') || s[i] == '.' || s[i] == 'e' || s[i] == 'E' || s[i] == '+' || s[i] == '-')) i++;
105
+ if (start == i) throw new FormatException("json: unexpected character");
106
+ return double.Parse(s.Substring(start, i - start), System.Globalization.CultureInfo.InvariantCulture);
107
+ }
108
+
109
+ static string ParseString(string s, ref int i)
110
+ {
111
+ if (i >= s.Length || s[i] != '"') throw new FormatException("json: expected string");
112
+ i++;
113
+ var sb = new StringBuilder();
114
+ while (i < s.Length)
115
+ {
116
+ char c = s[i++];
117
+ if (c == '"') return sb.ToString();
118
+ if (c != '\\') { sb.Append(c); continue; }
119
+ if (i >= s.Length) break;
120
+ char e = s[i++];
121
+ switch (e)
122
+ {
123
+ case '"': sb.Append('"'); break;
124
+ case '\\': sb.Append('\\'); break;
125
+ case '/': sb.Append('/'); break;
126
+ case 'b': sb.Append('\b'); break;
127
+ case 'f': sb.Append('\f'); break;
128
+ case 'n': sb.Append('\n'); break;
129
+ case 'r': sb.Append('\r'); break;
130
+ case 't': sb.Append('\t'); break;
131
+ case 'u':
132
+ if (i + 4 > s.Length) throw new FormatException("json: bad escape");
133
+ sb.Append((char)Convert.ToInt32(s.Substring(i, 4), 16));
134
+ i += 4;
135
+ break;
136
+ default: throw new FormatException("json: bad escape");
137
+ }
138
+ }
139
+ throw new FormatException("json: unterminated string");
140
+ }
141
+
142
+ // Canonical writer: object keys sorted ordinally at every depth, like packages/schemas canonicalJson.
143
+ public static string Write(object value)
144
+ {
145
+ var sb = new StringBuilder();
146
+ WriteValue(sb, value);
147
+ return sb.ToString();
148
+ }
149
+
150
+ static void WriteValue(StringBuilder sb, object value)
151
+ {
152
+ if (value == null) { sb.Append("null"); return; }
153
+ if (value is string) { WriteString(sb, (string)value); return; }
154
+ if (value is bool) { sb.Append((bool)value ? "true" : "false"); return; }
155
+ if (value is int || value is long)
156
+ {
157
+ sb.Append(Convert.ToInt64(value).ToString(System.Globalization.CultureInfo.InvariantCulture));
158
+ return;
159
+ }
160
+ if (value is double)
161
+ {
162
+ double d = (double)value;
163
+ if (d == Math.Floor(d) && Math.Abs(d) < 9007199254740992.0)
164
+ sb.Append(((long)d).ToString(System.Globalization.CultureInfo.InvariantCulture));
165
+ else sb.Append(d.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
166
+ return;
167
+ }
168
+ var dict = value as IDictionary<string, object>;
169
+ if (dict != null)
170
+ {
171
+ var keys = new List<string>(dict.Keys);
172
+ keys.Sort(StringComparer.Ordinal);
173
+ sb.Append('{');
174
+ for (int k = 0; k < keys.Count; k++)
175
+ {
176
+ if (k > 0) sb.Append(',');
177
+ WriteString(sb, keys[k]);
178
+ sb.Append(':');
179
+ WriteValue(sb, dict[keys[k]]);
180
+ }
181
+ sb.Append('}');
182
+ return;
183
+ }
184
+ var list = value as IList<object>;
185
+ if (list != null)
186
+ {
187
+ sb.Append('[');
188
+ for (int k = 0; k < list.Count; k++)
189
+ {
190
+ if (k > 0) sb.Append(',');
191
+ WriteValue(sb, list[k]);
192
+ }
193
+ sb.Append(']');
194
+ return;
195
+ }
196
+ throw new ArgumentException("json: unsupported value");
197
+ }
198
+
199
+ // JSON.stringify escaping for the characters it escapes.
200
+ static void WriteString(StringBuilder sb, string s)
201
+ {
202
+ sb.Append('"');
203
+ foreach (char c in s)
204
+ {
205
+ switch (c)
206
+ {
207
+ case '"': sb.Append("\\\""); break;
208
+ case '\\': sb.Append("\\\\"); break;
209
+ case '\b': sb.Append("\\b"); break;
210
+ case '\f': sb.Append("\\f"); break;
211
+ case '\n': sb.Append("\\n"); break;
212
+ case '\r': sb.Append("\\r"); break;
213
+ case '\t': sb.Append("\\t"); break;
214
+ default:
215
+ if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4"));
216
+ else sb.Append(c);
217
+ break;
218
+ }
219
+ }
220
+ sb.Append('"');
221
+ }
222
+
223
+ public static IDictionary<string, object> Obj(params object[] pairs)
224
+ {
225
+ var d = new SortedDictionary<string, object>(StringComparer.Ordinal);
226
+ for (int k = 0; k + 1 < pairs.Length; k += 2) d[(string)pairs[k]] = pairs[k + 1];
227
+ return d;
228
+ }
229
+ }
230
+
231
+ // ------------------------------------------------------------------------------------------------
232
+ // Win32
233
+ // ------------------------------------------------------------------------------------------------
234
+ static class Native
235
+ {
236
+ public const uint PIPE_ACCESS_DUPLEX = 0x00000003;
237
+ public const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000, FILE_FLAG_OVERLAPPED = 0x40000000;
238
+ public const uint PIPE_TYPE_BYTE = 0, PIPE_READMODE_BYTE = 0, PIPE_WAIT = 0, PIPE_REJECT_REMOTE_CLIENTS = 0x8;
239
+ public const uint PIPE_UNLIMITED_INSTANCES = 255;
240
+ public const int ERROR_PIPE_CONNECTED = 535;
241
+ public const uint TOKEN_QUERY = 0x0008, TOKEN_DUPLICATE = 0x0002, TOKEN_ASSIGN_PRIMARY = 0x0001,
242
+ TOKEN_ADJUST_DEFAULT = 0x0080, TOKEN_ADJUST_SESSIONID = 0x0100, TOKEN_IMPERSONATE = 0x0004;
243
+ public const uint MAXIMUM_ALLOWED = 0x02000000;
244
+ public const int SecurityImpersonation = 2, TokenPrimary = 1;
245
+ public const int TokenUser = 1, TokenElevation = 20;
246
+ public const uint CREATE_SUSPENDED = 0x4, CREATE_UNICODE_ENVIRONMENT = 0x400, CREATE_NO_WINDOW = 0x08000000;
247
+ public const uint LOGON_WITH_PROFILE = 1;
248
+ public const int STARTF_USESTDHANDLES = 0x100;
249
+ public const int JobObjectBasicAccountingInformation = 1, JobObjectBasicProcessIdList = 3,
250
+ JobObjectAssociateCompletionPortInformation = 7, JobObjectExtendedLimitInformation = 9;
251
+ public const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000;
252
+ public const uint JOB_OBJECT_MSG_NEW_PROCESS = 6;
253
+ public const uint SYNCHRONIZE = 0x00100000, PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
254
+ public const uint WAIT_OBJECT_0 = 0, WAIT_TIMEOUT = 0x102;
255
+ public const uint MOVEFILE_REPLACE_EXISTING = 1, MOVEFILE_WRITE_THROUGH = 8;
256
+ public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
257
+
258
+ [StructLayout(LayoutKind.Sequential)]
259
+ public struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
260
+
261
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
262
+ public struct STARTUPINFO
263
+ {
264
+ public int cb; public string lpReserved; public string lpDesktop; public string lpTitle;
265
+ public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
266
+ public short wShowWindow, cbReserved2; public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
267
+ }
268
+
269
+ [StructLayout(LayoutKind.Sequential)]
270
+ public struct PROCESS_INFORMATION { public IntPtr hProcess, hThread; public int dwProcessId, dwThreadId; }
271
+
272
+ [StructLayout(LayoutKind.Sequential)]
273
+ public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
274
+ {
275
+ public long PerProcessUserTimeLimit, PerJobUserTimeLimit; public uint LimitFlags;
276
+ public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize; public uint ActiveProcessLimit;
277
+ public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
278
+ }
279
+
280
+ [StructLayout(LayoutKind.Sequential)]
281
+ public struct IO_COUNTERS { public ulong a, b, c, d, e, f; }
282
+
283
+ [StructLayout(LayoutKind.Sequential)]
284
+ public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
285
+ {
286
+ public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo;
287
+ public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
288
+ }
289
+
290
+ [StructLayout(LayoutKind.Sequential)]
291
+ public struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT { public IntPtr CompletionKey, CompletionPort; }
292
+
293
+ [StructLayout(LayoutKind.Sequential)]
294
+ public struct JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
295
+ {
296
+ public long TotalUserTime, TotalKernelTime, ThisPeriodTotalUserTime, ThisPeriodTotalKernelTime;
297
+ public uint TotalPageFaultCount, TotalProcesses, ActiveProcesses, TotalTerminatedProcesses;
298
+ }
299
+
300
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
301
+ public static extern SafePipeHandle CreateNamedPipe(string name, uint openMode, uint pipeMode, uint maxInstances,
302
+ uint outBuffer, uint inBuffer, uint defaultTimeout, ref SECURITY_ATTRIBUTES sa);
303
+ [DllImport("kernel32.dll", SetLastError = true)]
304
+ public static extern bool ConnectNamedPipe(SafePipeHandle pipe, IntPtr overlapped);
305
+ [DllImport("kernel32.dll", SetLastError = true)]
306
+ public static extern bool DisconnectNamedPipe(SafePipeHandle pipe);
307
+ [DllImport("advapi32.dll", SetLastError = true)]
308
+ public static extern bool ImpersonateNamedPipeClient(SafePipeHandle pipe);
309
+ [DllImport("advapi32.dll", SetLastError = true)]
310
+ public static extern bool RevertToSelf();
311
+ [DllImport("kernel32.dll")]
312
+ public static extern IntPtr GetCurrentThread();
313
+ [DllImport("advapi32.dll", SetLastError = true)]
314
+ public static extern bool OpenThreadToken(IntPtr thread, uint access, bool openAsSelf, out IntPtr token);
315
+ [DllImport("advapi32.dll", SetLastError = true)]
316
+ public static extern bool DuplicateTokenEx(IntPtr existing, uint access, IntPtr sa, int level, int type, out IntPtr newToken);
317
+ [DllImport("advapi32.dll", SetLastError = true)]
318
+ public static extern bool GetTokenInformation(IntPtr token, int cls, IntPtr info, int length, out int returned);
319
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
320
+ public static extern bool ConvertSidToStringSid(IntPtr sid, out IntPtr str);
321
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
322
+ public static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string sddl, int revision,
323
+ out IntPtr sd, IntPtr size);
324
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
325
+ public static extern bool CreateProcessWithTokenW(IntPtr token, uint logonFlags, string app, StringBuilder cmd,
326
+ uint flags, IntPtr env, string cwd, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
327
+ [DllImport("userenv.dll", SetLastError = true)]
328
+ public static extern bool CreateEnvironmentBlock(out IntPtr env, IntPtr token, bool inherit);
329
+ [DllImport("userenv.dll", SetLastError = true)]
330
+ public static extern bool DestroyEnvironmentBlock(IntPtr env);
331
+ [DllImport("kernel32.dll", SetLastError = true)]
332
+ public static extern bool CreatePipe(out IntPtr read, out IntPtr write, ref SECURITY_ATTRIBUTES sa, int size);
333
+ [DllImport("kernel32.dll", SetLastError = true)]
334
+ public static extern bool SetHandleInformation(IntPtr h, uint mask, uint flags);
335
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
336
+ public static extern IntPtr CreateFile(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa,
337
+ uint disposition, uint flags, IntPtr template);
338
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
339
+ public static extern IntPtr CreateJobObject(IntPtr sa, string name);
340
+ [DllImport("kernel32.dll", SetLastError = true)]
341
+ public static extern bool SetInformationJobObject(IntPtr job, int cls, IntPtr info, int length);
342
+ [DllImport("kernel32.dll", SetLastError = true)]
343
+ public static extern bool QueryInformationJobObject(IntPtr job, int cls, IntPtr info, int length, out int returned);
344
+ [DllImport("kernel32.dll", SetLastError = true)]
345
+ public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
346
+ [DllImport("kernel32.dll", SetLastError = true)]
347
+ public static extern bool TerminateJobObject(IntPtr job, uint exitCode);
348
+ [DllImport("kernel32.dll", SetLastError = true)]
349
+ public static extern bool IsProcessInJob(IntPtr process, IntPtr job, out bool result);
350
+ [DllImport("kernel32.dll", SetLastError = true)]
351
+ public static extern IntPtr CreateIoCompletionPort(IntPtr file, IntPtr existing, UIntPtr key, uint threads);
352
+ [DllImport("kernel32.dll", SetLastError = true)]
353
+ public static extern bool GetQueuedCompletionStatus(IntPtr port, out uint bytes, out UIntPtr key, out IntPtr overlapped, uint ms);
354
+ [DllImport("kernel32.dll", SetLastError = true)]
355
+ public static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
356
+ [DllImport("kernel32.dll", SetLastError = true)]
357
+ public static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
358
+ [DllImport("kernel32.dll", SetLastError = true)]
359
+ public static extern uint WaitForSingleObject(IntPtr h, uint ms);
360
+ [DllImport("kernel32.dll", SetLastError = true)]
361
+ public static extern uint ResumeThread(IntPtr thread);
362
+ [DllImport("kernel32.dll", SetLastError = true)]
363
+ public static extern bool TerminateProcess(IntPtr process, uint code);
364
+ [DllImport("kernel32.dll", SetLastError = true)]
365
+ public static extern bool CloseHandle(IntPtr h);
366
+ [DllImport("kernel32.dll")]
367
+ public static extern IntPtr LocalFree(IntPtr h);
368
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
369
+ public static extern bool MoveFileEx(string from, string to, uint flags);
370
+ [DllImport("kernel32.dll")]
371
+ public static extern IntPtr GetCurrentProcess();
372
+ [DllImport("advapi32.dll", SetLastError = true)]
373
+ public static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
374
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
375
+ public static extern bool LookupPrivilegeValue(string system, string name, out long luid);
376
+ public const int TokenPrivileges = 3;
377
+ public const uint SE_PRIVILEGE_ENABLED_BY_DEFAULT = 1, SE_PRIVILEGE_ENABLED = 2;
378
+
379
+ public static Win32Exception Last(string what)
380
+ {
381
+ int code = Marshal.GetLastWin32Error();
382
+ return new Win32Exception(code, what + " failed (" + code + ")");
383
+ }
384
+ }
385
+
386
+ // ------------------------------------------------------------------------------------------------
387
+ // Configuration (written by `mrrlin-mcp drain-service install` on Windows)
388
+ // ------------------------------------------------------------------------------------------------
389
+ public sealed class Config
390
+ {
391
+ public string Version, ProviderSid, ServiceSid, PipeName, JournalDir, SpoolDir, KeyPath;
392
+ public string WorkerExe; public string[] WorkerArgs;
393
+ public int DrainDeadlineMs = 60000;
394
+
395
+ public static Config Load(string path)
396
+ {
397
+ var o = (IDictionary<string, object>)Json.Parse(File.ReadAllText(path, Encoding.UTF8));
398
+ var c = new Config();
399
+ c.Version = (string)o["version"];
400
+ c.ProviderSid = (string)o["providerSid"];
401
+ c.ServiceSid = (string)o["serviceSid"];
402
+ c.PipeName = (string)o["pipeName"];
403
+ c.JournalDir = (string)o["journalDir"];
404
+ c.SpoolDir = (string)o["spoolDir"];
405
+ c.KeyPath = (string)o["keyPath"];
406
+ var command = (IList<object>)o["workerCommand"];
407
+ if (command.Count < 1) throw new FormatException("workerCommand is empty");
408
+ c.WorkerExe = (string)command[0];
409
+ c.WorkerArgs = new string[command.Count - 1];
410
+ for (int k = 1; k < command.Count; k++) c.WorkerArgs[k - 1] = (string)command[k];
411
+ object deadline;
412
+ if (o.TryGetValue("drainDeadlineMs", out deadline) && deadline != null) c.DrainDeadlineMs = Convert.ToInt32(deadline);
413
+ if (c.DrainDeadlineMs < 1000 || c.DrainDeadlineMs > 600000) throw new FormatException("drainDeadlineMs must be 1000..600000");
414
+ if (!c.PipeName.StartsWith(@"\\.\pipe\", StringComparison.Ordinal)) throw new FormatException("pipeName must be a local pipe");
415
+ // The two identities every access decision rests on: a real user account and this service's own SID.
416
+ if (!System.Text.RegularExpressions.Regex.IsMatch(c.ProviderSid, @"^S-1-5-21(-\d{1,10}){4}$"))
417
+ throw new FormatException("providerSid must be a user SID");
418
+ if (!System.Text.RegularExpressions.Regex.IsMatch(c.ServiceSid, @"^S-1-5-80(-\d{1,10}){5}$"))
419
+ throw new FormatException("serviceSid must be a service SID");
420
+ return c;
421
+ }
422
+ }
423
+
424
+ // ------------------------------------------------------------------------------------------------
425
+ // Signing, journal and spool (same file formats as apps/mcp/src/drain-service/journal.ts)
426
+ // ------------------------------------------------------------------------------------------------
427
+ public sealed class Statements
428
+ {
429
+ public const string Domain = "mrrlin:drain-statement:v1";
430
+ readonly ECDsaCng key;
431
+ readonly string journalDir, spoolDir;
432
+
433
+ public Statements(string keyPath, string journalDir, string spoolDir, string serviceSid)
434
+ {
435
+ // The key is a BCRYPT ECCPRIVATE blob written at install into a file only the service can read.
436
+ var security = File.GetAccessControl(keyPath);
437
+ foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
438
+ {
439
+ if (rule.AccessControlType != AccessControlType.Allow) continue;
440
+ string sid = rule.IdentityReference.Value;
441
+ if (sid != "S-1-5-32-544" && sid != "S-1-5-18" && sid != serviceSid)
442
+ throw new InvalidOperationException("drain_key_exposed: " + sid + " may read the signing key");
443
+ }
444
+ var blob = File.ReadAllBytes(keyPath);
445
+ key = new ECDsaCng(CngKey.Import(blob, CngKeyBlobFormat.EccPrivateBlob));
446
+ key.HashAlgorithm = CngAlgorithm.Sha256;
447
+ this.journalDir = journalDir;
448
+ this.spoolDir = spoolDir;
449
+ Directory.CreateDirectory(journalDir);
450
+ Directory.CreateDirectory(spoolDir);
451
+ }
452
+
453
+ public static string Base64Url(byte[] bytes)
454
+ {
455
+ return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
456
+ }
457
+
458
+ public IDictionary<string, object> Sign(Entry e, string kind, string reason)
459
+ {
460
+ var facts = reason == null ? Json.Obj() : Json.Obj("reason", reason);
461
+ var statement = Json.Obj("v", 1, "kind", kind, "supervisionId", e.SupervisionId, "projectSlug", e.ProjectSlug,
462
+ "runId", e.RunId, "leaseId", e.LeaseId, "nonce", e.Nonce, "instance", e.Instance, "seq", e.NextSeq, "facts", facts);
463
+ var bytes = Encoding.UTF8.GetBytes(Domain + "\n" + Json.Write(statement));
464
+ // ECDsaCng.SignData returns r‖s (IEEE P1363), 64 bytes for P-256.
465
+ var signature = key.SignData(bytes);
466
+ return Json.Obj("statement", statement, "signature", Base64Url(signature));
467
+ }
468
+
469
+ static void WriteAtomic(string dir, string name, string content)
470
+ {
471
+ string temp = Path.Combine(dir, "." + name + "." + Guid.NewGuid().ToString("N") + ".tmp");
472
+ using (var fs = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
473
+ {
474
+ var bytes = new UTF8Encoding(false).GetBytes(content);
475
+ fs.Write(bytes, 0, bytes.Length);
476
+ fs.Flush(true);
477
+ }
478
+ if (!Native.MoveFileEx(temp, Path.Combine(dir, name), Native.MOVEFILE_REPLACE_EXISTING | Native.MOVEFILE_WRITE_THROUGH))
479
+ throw Native.Last("MoveFileEx");
480
+ }
481
+
482
+ public void Record(Entry e) { WriteAtomic(journalDir, e.SupervisionId + ".json", Json.Write(e.ToJson())); }
483
+
484
+ public void Forget(string supervisionId)
485
+ {
486
+ try { File.Delete(Path.Combine(journalDir, supervisionId + ".json")); } catch (IOException) { }
487
+ }
488
+
489
+ public string Spool(IDictionary<string, object> signed)
490
+ {
491
+ var st = (IDictionary<string, object>)signed["statement"];
492
+ string name = (string)st["supervisionId"] + "." + Convert.ToInt64(st["seq"]).ToString("D6") + ".json";
493
+ WriteAtomic(spoolDir, name, Json.Write(signed));
494
+ return name;
495
+ }
496
+
497
+ public List<Entry> Entries()
498
+ {
499
+ var list = new List<Entry>();
500
+ foreach (var path in Directory.GetFiles(journalDir, "*.json"))
501
+ {
502
+ try { list.Add(Entry.FromJson((IDictionary<string, object>)Json.Parse(File.ReadAllText(path, Encoding.UTF8)))); }
503
+ catch (Exception) { /* left for the operator; the others still recover */ }
504
+ }
505
+ return list;
506
+ }
507
+ }
508
+
509
+ public sealed class Entry
510
+ {
511
+ public string SupervisionId, ProjectSlug, RunId, LeaseId, Nonce, Instance;
512
+ public long NextSeq;
513
+
514
+ public IDictionary<string, object> ToJson()
515
+ {
516
+ return Json.Obj("supervisionId", SupervisionId, "projectSlug", ProjectSlug, "runId", RunId, "leaseId", LeaseId,
517
+ "nonce", Nonce, "instance", Instance, "nextSeq", NextSeq);
518
+ }
519
+
520
+ public static Entry FromJson(IDictionary<string, object> o)
521
+ {
522
+ var e = new Entry();
523
+ e.SupervisionId = (string)o["supervisionId"]; e.ProjectSlug = (string)o["projectSlug"]; e.RunId = (string)o["runId"];
524
+ e.LeaseId = (string)o["leaseId"]; e.Nonce = (string)o["nonce"]; e.Instance = (string)o["instance"];
525
+ e.NextSeq = Convert.ToInt64(o["nextSeq"]);
526
+ return e;
527
+ }
528
+ }
529
+
530
+ // ------------------------------------------------------------------------------------------------
531
+ // Framed IPC over the pipe
532
+ // ------------------------------------------------------------------------------------------------
533
+ public sealed class Frames
534
+ {
535
+ public const int MaxFrame = 2 * 1024 * 1024;
536
+ readonly Stream stream;
537
+ readonly object writeLock = new object();
538
+
539
+ public Frames(Stream stream) { this.stream = stream; }
540
+
541
+ static bool ReadExactly(Stream s, byte[] buf, int count)
542
+ {
543
+ int off = 0;
544
+ while (off < count)
545
+ {
546
+ int n = s.Read(buf, off, count - off);
547
+ if (n <= 0) return false;
548
+ off += n;
549
+ }
550
+ return true;
551
+ }
552
+
553
+ /// <summary>Returns false at EOF. kind 1 = control (JSON), 2 = data.</summary>
554
+ public bool Read(out int kind, out byte[] body)
555
+ {
556
+ kind = 0; body = null;
557
+ var head = new byte[5];
558
+ if (!ReadExactly(stream, head, 4)) return false;
559
+ int length = (head[0] << 24) | (head[1] << 16) | (head[2] << 8) | head[3];
560
+ if (length < 1 || length > MaxFrame) throw new InvalidDataException("drain_ipc_invalid_length");
561
+ var rest = new byte[length];
562
+ if (!ReadExactly(stream, rest, length)) return false;
563
+ kind = rest[0];
564
+ body = new byte[length - 1];
565
+ Buffer.BlockCopy(rest, 1, body, 0, length - 1);
566
+ if (kind != 1 && kind != 2) throw new InvalidDataException("drain_ipc_unknown_kind");
567
+ return true;
568
+ }
569
+
570
+ public void Write(int kind, byte[] body, int count)
571
+ {
572
+ int length = count + 1;
573
+ var head = new byte[] { (byte)(length >> 24), (byte)(length >> 16), (byte)(length >> 8), (byte)length, (byte)kind };
574
+ lock (writeLock)
575
+ {
576
+ stream.Write(head, 0, 5);
577
+ if (count > 0) stream.Write(body, 0, count);
578
+ stream.Flush();
579
+ }
580
+ }
581
+
582
+ public void Control(IDictionary<string, object> message)
583
+ {
584
+ var bytes = Encoding.UTF8.GetBytes(Json.Write(message));
585
+ Write(1, bytes, bytes.Length);
586
+ }
587
+ }
588
+
589
+ // ------------------------------------------------------------------------------------------------
590
+ // One supervised Job
591
+ // ------------------------------------------------------------------------------------------------
592
+ public sealed class Supervision
593
+ {
594
+ readonly IntPtr job, port;
595
+ readonly Dictionary<string, IntPtr> held = new Dictionary<string, IntPtr>(); // "pid:creation" → handle
596
+ readonly object gate = new object();
597
+ public readonly Entry Entry;
598
+ public IntPtr WorkerStdin, WorkerStdout;
599
+
600
+ public Supervision(Entry entry)
601
+ {
602
+ Entry = entry;
603
+ // Null security attributes: the Job handle is not inheritable, so only this service ever holds it.
604
+ job = Native.CreateJobObject(IntPtr.Zero, null);
605
+ if (job == IntPtr.Zero) throw Native.Last("CreateJobObject");
606
+ try
607
+ {
608
+ var limits = new Native.JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
609
+ // KILL_ON_JOB_CLOSE and nothing else: no BREAKAWAY_OK, no SILENT_BREAKAWAY_OK, no process limit.
610
+ limits.BasicLimitInformation.LimitFlags = Native.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
611
+ SetJob(Native.JobObjectExtendedLimitInformation, limits);
612
+ port = Native.CreateIoCompletionPort(Native.INVALID_HANDLE_VALUE, IntPtr.Zero, UIntPtr.Zero, 1);
613
+ if (port == IntPtr.Zero) throw Native.Last("CreateIoCompletionPort");
614
+ var assoc = new Native.JOBOBJECT_ASSOCIATE_COMPLETION_PORT();
615
+ assoc.CompletionKey = new IntPtr(1);
616
+ assoc.CompletionPort = port;
617
+ SetJob(Native.JobObjectAssociateCompletionPortInformation, assoc);
618
+ }
619
+ catch
620
+ {
621
+ if (port != IntPtr.Zero) Native.CloseHandle(port);
622
+ Native.CloseHandle(job);
623
+ throw;
624
+ }
625
+ }
626
+
627
+ void SetJob<T>(int cls, T value) where T : struct
628
+ {
629
+ int size = Marshal.SizeOf(typeof(T));
630
+ IntPtr p = Marshal.AllocHGlobal(size);
631
+ try
632
+ {
633
+ Marshal.StructureToPtr(value, p, false);
634
+ if (!Native.SetInformationJobObject(job, cls, p, size)) throw Native.Last("SetInformationJobObject");
635
+ }
636
+ finally { Marshal.FreeHGlobal(p); }
637
+ }
638
+
639
+ /// <summary>Launch the worker as the pipe client (already impersonated by the caller's token).</summary>
640
+ public void Launch(IntPtr primaryToken, Config config)
641
+ {
642
+ var sa = new Native.SECURITY_ATTRIBUTES();
643
+ sa.nLength = Marshal.SizeOf(typeof(Native.SECURITY_ATTRIBUTES));
644
+ sa.bInheritHandle = true;
645
+ IntPtr inRead, inWrite, outRead, outWrite;
646
+ if (!Native.CreatePipe(out inRead, out inWrite, ref sa, 0)) throw Native.Last("CreatePipe");
647
+ if (!Native.CreatePipe(out outRead, out outWrite, ref sa, 0)) throw Native.Last("CreatePipe");
648
+ // The service's ends never reach the child.
649
+ Native.SetHandleInformation(inWrite, 1, 0);
650
+ Native.SetHandleInformation(outRead, 1, 0);
651
+ IntPtr nul = Native.CreateFile("NUL", 0x40000000, 3, ref sa, 3, 0, IntPtr.Zero);
652
+
653
+ var si = new Native.STARTUPINFO();
654
+ si.cb = Marshal.SizeOf(typeof(Native.STARTUPINFO));
655
+ si.dwFlags = Native.STARTF_USESTDHANDLES;
656
+ si.hStdInput = inRead;
657
+ si.hStdOutput = outWrite;
658
+ si.hStdError = nul;
659
+ var cmd = new StringBuilder(Quote(config.WorkerExe));
660
+ foreach (var arg in config.WorkerArgs) cmd.Append(' ').Append(Quote(arg));
661
+
662
+ IntPtr env;
663
+ if (!Native.CreateEnvironmentBlock(out env, primaryToken, false)) throw Native.Last("CreateEnvironmentBlock");
664
+ Native.PROCESS_INFORMATION pi;
665
+ try
666
+ {
667
+ if (!Native.CreateProcessWithTokenW(primaryToken, Native.LOGON_WITH_PROFILE, config.WorkerExe, cmd,
668
+ Native.CREATE_SUSPENDED | Native.CREATE_UNICODE_ENVIRONMENT | Native.CREATE_NO_WINDOW, env, null, ref si, out pi))
669
+ throw Native.Last("CreateProcessWithTokenW");
670
+ }
671
+ finally
672
+ {
673
+ Native.DestroyEnvironmentBlock(env);
674
+ Native.CloseHandle(inRead);
675
+ Native.CloseHandle(outWrite);
676
+ if (nul != Native.INVALID_HANDLE_VALUE) Native.CloseHandle(nul);
677
+ }
678
+ if (!Native.AssignProcessToJobObject(job, pi.hProcess))
679
+ {
680
+ var error = Native.Last("AssignProcessToJobObject");
681
+ Native.TerminateProcess(pi.hProcess, 1);
682
+ Native.CloseHandle(pi.hThread);
683
+ Native.CloseHandle(pi.hProcess);
684
+ throw error;
685
+ }
686
+ Hold(pi.hProcess, pi.dwProcessId);
687
+ Native.ResumeThread(pi.hThread);
688
+ Native.CloseHandle(pi.hThread);
689
+ WorkerStdin = inWrite;
690
+ WorkerStdout = outRead;
691
+ }
692
+
693
+ static string Quote(string arg)
694
+ {
695
+ if (arg.Length > 0 && arg.IndexOfAny(new[] { ' ', '\t', '"' }) < 0) return arg;
696
+ var sb = new StringBuilder("\"");
697
+ int backslashes = 0;
698
+ foreach (char c in arg)
699
+ {
700
+ if (c == '\\') { backslashes++; continue; }
701
+ if (c == '"') { sb.Append('\\', backslashes * 2 + 1); sb.Append('"'); backslashes = 0; continue; }
702
+ sb.Append('\\', backslashes); backslashes = 0; sb.Append(c);
703
+ }
704
+ sb.Append('\\', backslashes * 2).Append('"');
705
+ return sb.ToString();
706
+ }
707
+
708
+ void Hold(IntPtr handle, int pid)
709
+ {
710
+ long creation, exit, kernel, user;
711
+ if (!Native.GetProcessTimes(handle, out creation, out exit, out kernel, out user)) { Native.CloseHandle(handle); return; }
712
+ string key = pid + ":" + creation;
713
+ lock (gate)
714
+ {
715
+ if (held.ContainsKey(key)) { Native.CloseHandle(handle); return; }
716
+ held[key] = handle;
717
+ }
718
+ }
719
+
720
+ /// <summary>Open, verify membership and hold a process of this Job. Never closes a held handle.</summary>
721
+ void Observe(int pid)
722
+ {
723
+ IntPtr h = Native.OpenProcess(Native.SYNCHRONIZE | Native.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
724
+ if (h == IntPtr.Zero) return; // exited (or never ours): it stays unaccounted, which fails the count
725
+ bool inJob;
726
+ if (!Native.IsProcessInJob(h, job, out inJob) || !inJob) { Native.CloseHandle(h); return; }
727
+ Hold(h, pid);
728
+ }
729
+
730
+ /// <summary>Drain the completion port and poll the PID list; both sources feed the held set.</summary>
731
+ public void Collect(uint waitMs)
732
+ {
733
+ uint bytes; UIntPtr key; IntPtr overlapped;
734
+ while (Native.GetQueuedCompletionStatus(port, out bytes, out key, out overlapped, waitMs))
735
+ {
736
+ waitMs = 0;
737
+ if (bytes == Native.JOB_OBJECT_MSG_NEW_PROCESS) Observe(overlapped.ToInt32());
738
+ }
739
+ const int capacity = 4096;
740
+ int size = 8 + IntPtr.Size * capacity;
741
+ IntPtr buf = Marshal.AllocHGlobal(size);
742
+ try
743
+ {
744
+ int returned;
745
+ if (Native.QueryInformationJobObject(job, Native.JobObjectBasicProcessIdList, buf, size, out returned))
746
+ {
747
+ int count = Marshal.ReadInt32(buf, 4);
748
+ for (int k = 0; k < count && k < capacity; k++) Observe(Marshal.ReadIntPtr(buf, 8 + k * IntPtr.Size).ToInt32());
749
+ }
750
+ }
751
+ finally { Marshal.FreeHGlobal(buf); }
752
+ }
753
+
754
+ Native.JOBOBJECT_BASIC_ACCOUNTING_INFORMATION Accounting()
755
+ {
756
+ int size = Marshal.SizeOf(typeof(Native.JOBOBJECT_BASIC_ACCOUNTING_INFORMATION));
757
+ IntPtr buf = Marshal.AllocHGlobal(size);
758
+ try
759
+ {
760
+ int returned;
761
+ if (!Native.QueryInformationJobObject(job, Native.JobObjectBasicAccountingInformation, buf, size, out returned))
762
+ throw Native.Last("QueryInformationJobObject");
763
+ return (Native.JOBOBJECT_BASIC_ACCOUNTING_INFORMATION)Marshal.PtrToStructure(buf, typeof(Native.JOBOBJECT_BASIC_ACCOUNTING_INFORMATION));
764
+ }
765
+ finally { Marshal.FreeHGlobal(buf); }
766
+ }
767
+
768
+ /// <summary>Kill the Job and decide: null = drained, otherwise the unknown reason.</summary>
769
+ public string Drain(int deadlineMs)
770
+ {
771
+ var started = DateTime.UtcNow;
772
+ int backoff = 10;
773
+ while (true)
774
+ {
775
+ Native.TerminateJobObject(job, 1);
776
+ Collect(0);
777
+ var acct = Accounting();
778
+ if (acct.ActiveProcesses == 0 && AllHeldSignaled())
779
+ {
780
+ // One last collection pass, then the signal check again over everything now held.
781
+ Collect(0);
782
+ acct = Accounting();
783
+ if (acct.ActiveProcesses == 0 && AllHeldSignaled())
784
+ {
785
+ int count;
786
+ lock (gate) count = held.Count;
787
+ // Every process the Job ever contained must have been held and seen signaled.
788
+ return count == (int)acct.TotalProcesses ? null : "windows_unaccounted_process";
789
+ }
790
+ }
791
+ if ((DateTime.UtcNow - started).TotalMilliseconds > deadlineMs) return "windows_drain_timeout";
792
+ Thread.Sleep(backoff);
793
+ backoff = Math.Min(250, backoff * 2);
794
+ }
795
+ }
796
+
797
+ bool AllHeldSignaled()
798
+ {
799
+ lock (gate)
800
+ {
801
+ foreach (var h in held.Values)
802
+ if (Native.WaitForSingleObject(h, 0) != Native.WAIT_OBJECT_0) return false;
803
+ return true;
804
+ }
805
+ }
806
+
807
+ /// <summary>After the verdict is signed: release every handle (the Job's close kills anything left).</summary>
808
+ public void Close()
809
+ {
810
+ lock (gate)
811
+ {
812
+ foreach (var h in held.Values) Native.CloseHandle(h);
813
+ held.Clear();
814
+ }
815
+ if (WorkerStdin != IntPtr.Zero) Native.CloseHandle(WorkerStdin);
816
+ if (WorkerStdout != IntPtr.Zero) Native.CloseHandle(WorkerStdout);
817
+ Native.CloseHandle(port);
818
+ Native.CloseHandle(job);
819
+ }
820
+ }
821
+
822
+ // ------------------------------------------------------------------------------------------------
823
+ // The service
824
+ // ------------------------------------------------------------------------------------------------
825
+ public sealed class DrainService : ServiceBase
826
+ {
827
+ public const int Protocol = 1;
828
+ readonly Config config;
829
+ readonly Statements statements;
830
+ readonly string instance = "svc-" + Guid.NewGuid().ToString("N").Substring(0, 8);
831
+ readonly Dictionary<string, Supervision> active = new Dictionary<string, Supervision>();
832
+ readonly object gate = new object();
833
+ Thread listener;
834
+ volatile bool stopping;
835
+
836
+ public DrainService(Config config)
837
+ {
838
+ ServiceName = "MrrlinDrain";
839
+ this.config = config;
840
+ statements = new Statements(config.KeyPath, config.JournalDir, config.SpoolDir, config.ServiceSid);
841
+ }
842
+
843
+ public int RecoverJournal()
844
+ {
845
+ int count = 0;
846
+ foreach (var entry in statements.Entries())
847
+ {
848
+ var signed = statements.Sign(entry, "unknown", "service_restart");
849
+ statements.Spool(signed);
850
+ statements.Forget(entry.SupervisionId);
851
+ count++;
852
+ }
853
+ return count;
854
+ }
855
+
856
+ protected override void OnStart(string[] args)
857
+ {
858
+ RecoverJournal();
859
+ var first = CreateInstance(true); // refuses to start if anyone else owns the pipe name
860
+ listener = new Thread(delegate() { Listen(first); });
861
+ listener.IsBackground = true;
862
+ listener.Start();
863
+ }
864
+
865
+ protected override void OnStop() { stopping = true; }
866
+
867
+ public void RunConsole()
868
+ {
869
+ OnStart(new string[0]);
870
+ Console.WriteLine("mrrlin drain service listening on " + config.PipeName);
871
+ listener.Join();
872
+ }
873
+
874
+ SafePipeHandle CreateInstance(bool first)
875
+ {
876
+ // Only the service and the provider account may open the pipe; remote clients are rejected.
877
+ string sddl = "D:P(A;;GA;;;" + config.ServiceSid + ")(A;;GRGW;;;" + config.ProviderSid + ")";
878
+ IntPtr sd;
879
+ if (!Native.ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, out sd, IntPtr.Zero))
880
+ throw Native.Last("ConvertStringSecurityDescriptorToSecurityDescriptor");
881
+ try
882
+ {
883
+ var sa = new Native.SECURITY_ATTRIBUTES();
884
+ sa.nLength = Marshal.SizeOf(typeof(Native.SECURITY_ATTRIBUTES));
885
+ sa.lpSecurityDescriptor = sd;
886
+ // Overlapped: the connection thread reads while the output pump writes. On a synchronous handle Windows
887
+ // serialises I/O per file object, so a pending read would block every write — a deadlock with a bridge
888
+ // that is itself waiting for the worker's output.
889
+ uint mode = Native.PIPE_ACCESS_DUPLEX | Native.FILE_FLAG_OVERLAPPED | (first ? Native.FILE_FLAG_FIRST_PIPE_INSTANCE : 0);
890
+ var pipe = Native.CreateNamedPipe(config.PipeName, mode,
891
+ Native.PIPE_TYPE_BYTE | Native.PIPE_READMODE_BYTE | Native.PIPE_WAIT | Native.PIPE_REJECT_REMOTE_CLIENTS,
892
+ Native.PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, ref sa);
893
+ if (pipe.IsInvalid) throw Native.Last(first ? "CreateNamedPipe (pipe name already taken?)" : "CreateNamedPipe");
894
+ return pipe;
895
+ }
896
+ finally { Native.LocalFree(sd); }
897
+ }
898
+
899
+ void Listen(SafePipeHandle next)
900
+ {
901
+ while (!stopping)
902
+ {
903
+ var pipe = next;
904
+ // isAsync: the stream drives the overlapped handle (connect, and concurrent read and write).
905
+ var stream = new System.IO.Pipes.NamedPipeServerStream(System.IO.Pipes.PipeDirection.InOut, true, false, pipe);
906
+ try { stream.WaitForConnection(); }
907
+ catch (IOException)
908
+ {
909
+ stream.Dispose();
910
+ next = CreateInstance(false);
911
+ continue;
912
+ }
913
+ next = CreateInstance(false);
914
+ var worker = new Thread(delegate() { Connection(stream, pipe); });
915
+ worker.IsBackground = true;
916
+ worker.Start();
917
+ }
918
+ }
919
+
920
+ static string Str(IDictionary<string, object> m, string key)
921
+ {
922
+ object v;
923
+ return m.TryGetValue(key, out v) ? v as string : null;
924
+ }
925
+
926
+ static readonly System.Text.RegularExpressions.Regex Uuid =
927
+ new System.Text.RegularExpressions.Regex("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$");
928
+ static readonly System.Text.RegularExpressions.Regex Ident =
929
+ new System.Text.RegularExpressions.Regex("^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$");
930
+ static readonly System.Text.RegularExpressions.Regex NonceRe =
931
+ new System.Text.RegularExpressions.Regex("^[A-Za-z0-9_-]{16,128}$");
932
+
933
+ void Connection(System.IO.Pipes.NamedPipeServerStream stream, SafePipeHandle handle)
934
+ {
935
+ using (stream)
936
+ {
937
+ var frames = new Frames(stream);
938
+ Supervision supervision = null;
939
+ Timer deadline = null;
940
+ bool greeted = false;
941
+ object stopGate = new object();
942
+ IDictionary<string, object> terminal = null;
943
+ // Drains the Job once; every caller gets the same signed answer.
944
+ Func<IDictionary<string, object>> stop = delegate()
945
+ {
946
+ lock (stopGate)
947
+ {
948
+ if (terminal != null || supervision == null) return terminal;
949
+ if (deadline != null) deadline.Dispose();
950
+ string reason;
951
+ try { reason = supervision.Drain(config.DrainDeadlineMs); }
952
+ catch (Exception) { reason = "windows_drain_error"; }
953
+ var signed = Terminal(supervision.Entry, reason == null ? "drained" : "unknown", reason);
954
+ supervision.Close();
955
+ lock (gate) active.Remove(supervision.Entry.SupervisionId);
956
+ terminal = Json.Obj("type", reason == null ? "drained" : "unknown", "signed", signed);
957
+ return terminal;
958
+ }
959
+ };
960
+ try
961
+ {
962
+ int kind; byte[] body;
963
+ while (frames.Read(out kind, out body))
964
+ {
965
+ if (kind == 2)
966
+ {
967
+ if (supervision != null && body.Length > 0) WriteAll(supervision.WorkerStdin, body);
968
+ continue;
969
+ }
970
+ var message = Json.Parse(Encoding.UTF8.GetString(body)) as IDictionary<string, object>;
971
+ string type = message == null ? null : Str(message, "type");
972
+ if (type == null) throw new InvalidDataException("drain_ipc_invalid_control");
973
+ if (!greeted)
974
+ {
975
+ object protocol;
976
+ if (type != "hello" || !message.TryGetValue("protocol", out protocol) || Convert.ToInt32(protocol) != Protocol)
977
+ {
978
+ frames.Control(Json.Obj("type", "refused", "reason", "protocol_mismatch"));
979
+ return;
980
+ }
981
+ greeted = true;
982
+ frames.Control(Json.Obj("type", "hello", "protocol", Protocol, "version", config.Version, "instance", instance));
983
+ continue;
984
+ }
985
+ if (type == "status")
986
+ {
987
+ int count;
988
+ lock (gate) count = active.Count;
989
+ frames.Control(Json.Obj("type", "status", "healthy", true, "supervisions", count, "version", config.Version,
990
+ "impersonatePrivilege", HasImpersonatePrivilege()));
991
+ }
992
+ else if (type == "start")
993
+ {
994
+ if (supervision != null) { frames.Control(Json.Obj("type", "refused", "reason", "already_started")); continue; }
995
+ // Before the worker exists a failure is a refusal; once it was launched every failure goes
996
+ // through the normal drain below (the finally's stop()), so a launched Job is never orphaned.
997
+ try { supervision = Start(message, handle, frames); }
998
+ catch (Exception error)
999
+ {
1000
+ frames.Control(Json.Obj("type", "refused", "reason", error is ArgumentException ? error.Message : "start_failed"));
1001
+ continue;
1002
+ }
1003
+ {
1004
+ var signed = Sign(supervision.Entry, "started", null);
1005
+ frames.Control(Json.Obj("type", "started", "signed", signed));
1006
+ object ms;
1007
+ message.TryGetValue("leaseRemainingMs", out ms);
1008
+ deadline = new Timer(delegate(object state)
1009
+ {
1010
+ // A throw here would kill the service process; the spool and journal decide instead.
1011
+ try
1012
+ {
1013
+ var t = stop();
1014
+ if (t != null) frames.Control(t);
1015
+ }
1016
+ catch (Exception) { }
1017
+ }, null, Math.Max(1, Convert.ToInt32(ms)), Timeout.Infinite);
1018
+ }
1019
+ }
1020
+ else if (type == "stop")
1021
+ {
1022
+ var t = stop();
1023
+ if (t != null) frames.Control(t);
1024
+ }
1025
+ }
1026
+ }
1027
+ catch (Exception) { /* EOF, a broken pipe or a malformed frame: treated as bridge loss below */ }
1028
+ finally
1029
+ {
1030
+ // Bridge loss is a stop: the Job is drained and the statement waits in the spool.
1031
+ stop();
1032
+ }
1033
+ }
1034
+ }
1035
+
1036
+ static void WriteAll(IntPtr handle, byte[] data)
1037
+ {
1038
+ using (var fs = new FileStream(new SafeFileHandle(handle, false), FileAccess.Write, 1))
1039
+ {
1040
+ fs.Write(data, 0, data.Length);
1041
+ fs.Flush();
1042
+ }
1043
+ }
1044
+
1045
+ Supervision Start(IDictionary<string, object> m, SafePipeHandle pipe, Frames frames)
1046
+ {
1047
+ var e = new Entry();
1048
+ e.SupervisionId = Str(m, "supervisionId"); e.ProjectSlug = Str(m, "projectSlug"); e.RunId = Str(m, "runId");
1049
+ e.LeaseId = Str(m, "leaseId"); e.Nonce = Str(m, "nonce"); e.Instance = instance; e.NextSeq = 0;
1050
+ if (e.SupervisionId == null || !Uuid.IsMatch(e.SupervisionId)) throw new ArgumentException("start.supervisionId");
1051
+ if (e.ProjectSlug == null || !Ident.IsMatch(e.ProjectSlug)) throw new ArgumentException("start.projectSlug");
1052
+ if (e.RunId == null || !Ident.IsMatch(e.RunId)) throw new ArgumentException("start.runId");
1053
+ if (e.LeaseId == null || !Ident.IsMatch(e.LeaseId)) throw new ArgumentException("start.leaseId");
1054
+ if (e.Nonce == null || !NonceRe.IsMatch(e.Nonce)) throw new ArgumentException("start.nonce");
1055
+ object ms;
1056
+ if (!m.TryGetValue("leaseRemainingMs", out ms) || !(ms is double) || (double)ms <= 0 || (double)ms > 86400000 ||
1057
+ (double)ms != Math.Floor((double)ms)) throw new ArgumentException("start.leaseRemainingMs");
1058
+ lock (gate) if (active.ContainsKey(e.SupervisionId)) throw new ArgumentException("already_supervised");
1059
+
1060
+ IntPtr primary = ClientPrimaryToken(pipe);
1061
+ Supervision s = null;
1062
+ try
1063
+ {
1064
+ // Journal first: a crash after this line reports unknown(service_restart).
1065
+ statements.Record(e);
1066
+ s = new Supervision(e);
1067
+ s.Launch(primary, config);
1068
+ }
1069
+ catch
1070
+ {
1071
+ if (s != null) { s.Drain(config.DrainDeadlineMs); s.Close(); }
1072
+ statements.Forget(e.SupervisionId);
1073
+ throw;
1074
+ }
1075
+ finally { Native.CloseHandle(primary); }
1076
+ lock (gate) active[e.SupervisionId] = s;
1077
+ var supervision = s;
1078
+ var pump = new Thread(delegate() { Pump(supervision, frames); });
1079
+ pump.IsBackground = true;
1080
+ pump.Start();
1081
+ return s;
1082
+ }
1083
+
1084
+ /// <summary>Impersonate the pipe client, check it is the provider account and not elevated, return a primary token.</summary>
1085
+ IntPtr ClientPrimaryToken(SafePipeHandle pipe)
1086
+ {
1087
+ if (!Native.ImpersonateNamedPipeClient(pipe)) throw Native.Last("ImpersonateNamedPipeClient");
1088
+ IntPtr impersonation;
1089
+ try
1090
+ {
1091
+ if (!Native.OpenThreadToken(Native.GetCurrentThread(),
1092
+ Native.TOKEN_QUERY | Native.TOKEN_DUPLICATE | Native.TOKEN_ASSIGN_PRIMARY | Native.TOKEN_IMPERSONATE, true, out impersonation))
1093
+ throw Native.Last("OpenThreadToken");
1094
+ }
1095
+ finally { Native.RevertToSelf(); }
1096
+ try
1097
+ {
1098
+ if (TokenUserSid(impersonation) != config.ProviderSid) throw new ArgumentException("provider_mismatch");
1099
+ if (TokenElevated(impersonation)) throw new ArgumentException("provider_elevated");
1100
+ IntPtr primary;
1101
+ if (!Native.DuplicateTokenEx(impersonation, Native.MAXIMUM_ALLOWED, IntPtr.Zero, Native.SecurityImpersonation,
1102
+ Native.TokenPrimary, out primary)) throw Native.Last("DuplicateTokenEx");
1103
+ return primary;
1104
+ }
1105
+ finally { Native.CloseHandle(impersonation); }
1106
+ }
1107
+
1108
+ static string TokenUserSid(IntPtr token)
1109
+ {
1110
+ int size;
1111
+ Native.GetTokenInformation(token, Native.TokenUser, IntPtr.Zero, 0, out size);
1112
+ IntPtr buf = Marshal.AllocHGlobal(size);
1113
+ try
1114
+ {
1115
+ if (!Native.GetTokenInformation(token, Native.TokenUser, buf, size, out size)) throw Native.Last("GetTokenInformation");
1116
+ IntPtr str;
1117
+ if (!Native.ConvertSidToStringSid(Marshal.ReadIntPtr(buf), out str)) throw Native.Last("ConvertSidToStringSid");
1118
+ try { return Marshal.PtrToStringUni(str); } finally { Native.LocalFree(str); }
1119
+ }
1120
+ finally { Marshal.FreeHGlobal(buf); }
1121
+ }
1122
+
1123
+ /// <summary>Whether this service's own token holds SeImpersonatePrivilege (CreateProcessWithTokenW needs it).</summary>
1124
+ public static bool HasImpersonatePrivilege()
1125
+ {
1126
+ IntPtr token;
1127
+ if (!Native.OpenProcessToken(Native.GetCurrentProcess(), Native.TOKEN_QUERY, out token)) return false;
1128
+ try
1129
+ {
1130
+ long wanted;
1131
+ if (!Native.LookupPrivilegeValue(null, "SeImpersonatePrivilege", out wanted)) return false;
1132
+ int size;
1133
+ Native.GetTokenInformation(token, Native.TokenPrivileges, IntPtr.Zero, 0, out size);
1134
+ IntPtr buf = Marshal.AllocHGlobal(size);
1135
+ try
1136
+ {
1137
+ if (!Native.GetTokenInformation(token, Native.TokenPrivileges, buf, size, out size)) return false;
1138
+ int count = Marshal.ReadInt32(buf);
1139
+ for (int k = 0; k < count; k++)
1140
+ {
1141
+ int offset = 4 + k * 12; // LUID_AND_ATTRIBUTES: 8-byte LUID + 4-byte attributes
1142
+ long luid = Marshal.ReadInt64(buf, offset);
1143
+ uint attributes = (uint)Marshal.ReadInt32(buf, offset + 8);
1144
+ if (luid == wanted)
1145
+ return (attributes & (Native.SE_PRIVILEGE_ENABLED | Native.SE_PRIVILEGE_ENABLED_BY_DEFAULT)) != 0;
1146
+ }
1147
+ return false;
1148
+ }
1149
+ finally { Marshal.FreeHGlobal(buf); }
1150
+ }
1151
+ finally { Native.CloseHandle(token); }
1152
+ }
1153
+
1154
+ static bool TokenElevated(IntPtr token)
1155
+ {
1156
+ IntPtr buf = Marshal.AllocHGlobal(4);
1157
+ try
1158
+ {
1159
+ int size;
1160
+ if (!Native.GetTokenInformation(token, Native.TokenElevation, buf, 4, out size)) return true; // unknown → refuse
1161
+ return Marshal.ReadInt32(buf) != 0;
1162
+ }
1163
+ finally { Marshal.FreeHGlobal(buf); }
1164
+ }
1165
+
1166
+ /// <summary>Worker stdout → data frames, until the worker's stdout closes.</summary>
1167
+ static void Pump(Supervision s, Frames frames)
1168
+ {
1169
+ try
1170
+ {
1171
+ using (var fs = new FileStream(new SafeFileHandle(s.WorkerStdout, false), FileAccess.Read, 65536))
1172
+ {
1173
+ var buf = new byte[65536];
1174
+ int n;
1175
+ while ((n = fs.Read(buf, 0, buf.Length)) > 0) frames.Write(2, buf, n);
1176
+ }
1177
+ }
1178
+ catch (Exception) { /* the bridge or the worker went away; the stop path decides */ }
1179
+ }
1180
+
1181
+ IDictionary<string, object> Sign(Entry e, string kind, string reason)
1182
+ {
1183
+ var signed = statements.Sign(e, kind, reason);
1184
+ statements.Spool(signed); // spooled before anyone hears the answer
1185
+ e.NextSeq += 1;
1186
+ statements.Record(e);
1187
+ return signed;
1188
+ }
1189
+
1190
+ IDictionary<string, object> Terminal(Entry e, string kind, string reason)
1191
+ {
1192
+ var signed = Sign(e, kind, reason);
1193
+ statements.Forget(e.SupervisionId);
1194
+ return signed;
1195
+ }
1196
+
1197
+ public static int Main(string[] args)
1198
+ {
1199
+ string configPath = args.Length > 1 && args[0] == "--config" ? args[1]
1200
+ : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Mrrlin Drain", "config.json");
1201
+ var config = Config.Load(configPath);
1202
+ var service = new DrainService(config);
1203
+ if (Array.IndexOf(args, "--console") >= 0) { service.RunConsole(); return 0; }
1204
+ ServiceBase.Run(service);
1205
+ return 0;
1206
+ }
1207
+ }
1208
+ }