using System.Collections.Concurrent; using System.ComponentModel; using System.Diagnostics; using System.IO.Pipes; using System.Text; using System.Text.Json.Nodes; using XFEWorkflow.Abstractions; using XFEWorkflow.Infrastructure.Communication; namespace XFEWorkflow.Infrastructure.Execution; /// Runs a shell in an owned helper, including UAC elevation, without using temporary output files. public sealed class CommandProcessHost(string runnerPath) : IAsyncDisposable { private readonly ConcurrentDictionary> owners = []; public async Task ExecuteAsync(string owner, JsonObject input, CancellationToken ct) { if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("命令行节点需要 Windows"); var name = "XFEWorkflow-Command-" + Guid.NewGuid().ToString("N"); var elevated = input.Boolean("administrator"); await using var pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); var session = new Session(pipe); var sessions = owners.GetOrAdd(owner, _ => []); sessions[name] = session; using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, session.Stop.Token); try { var start = new ProcessStartInfo(runnerPath) { UseShellExecute = elevated, CreateNoWindow = !elevated, WindowStyle = ProcessWindowStyle.Hidden }; start.ArgumentList.Add("--command-host"); start.ArgumentList.Add(name); if (elevated) start.Verb = "runas"; // UAC can outlive cancellation. The helper has a bounded connect timeout and cannot run a command without this pipe. var launch = Task.Run(() => Process.Start(start) ?? throw new IOException("无法启动命令执行进程")); try { session.Process = await launch.WaitAsync(linked.Token); } catch (OperationCanceledException) { _ = launch.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion) t.Result.Dispose(); }, TaskScheduler.Default); throw; } catch (Win32Exception ex) when (ex.NativeErrorCode == 1223) { throw new OperationCanceledException("已取消管理员启动,命令未执行", ex); } using var deadline = CancellationTokenSource.CreateLinkedTokenSource(linked.Token); deadline.CancelAfter(TimeSpan.FromSeconds(20)); await pipe.WaitForConnectionAsync(deadline.Token); session.Peer = new RpcPeer(pipe); session.Peer.Start(); return await session.Peer.RequestAsync("run", input, linked.Token) ?? throw new IOException("命令执行未返回结果"); } finally { await session.DisposeAsync(); sessions.TryRemove(name, out _); } } public async Task ReleaseAsync(string owner) { if (owners.TryRemove(owner, out var sessions)) foreach (var session in sessions.Values) { try { await session.Stop.CancelAsync(); } catch (ObjectDisposedException) { } } } public async ValueTask DisposeAsync() { foreach (var owner in owners.Keys) await ReleaseAsync(owner); } private sealed class Session(NamedPipeServerStream pipe) : IAsyncDisposable { public CancellationTokenSource Stop { get; } = new(); public Process? Process { get; set; } public RpcPeer? Peer { get; set; } public async ValueTask DisposeAsync() { if (Peer is not null) { try { await Peer.RequestAsync("cancel").WaitAsync(TimeSpan.FromSeconds(1)); } catch (Exception) { } await Peer.DisposeAsync(); } else await pipe.DisposeAsync(); if (Process is { } process) { try { await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); } catch (TimeoutException) { try { process.Kill(true); } catch (Win32Exception) { /* Elevated helper cancels its own child after pipe closure. */ } } finally { process.Dispose(); } } Stop.Dispose(); } } } public static class CommandProcessWorker { public static async Task RunAsync(string pipeName) { if (!pipeName.StartsWith("XFEWorkflow-Command-", StringComparison.Ordinal)) return 2; using var lifetime = new CancellationTokenSource(); await using var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); try { await pipe.ConnectAsync(5000, lifetime.Token); } catch (Exception) { return 3; } await using var peer = new RpcPeer(pipe); var started = 0; Task? command = null; peer.RequestReceived = async (method, value, ct) => { if (method == "cancel") { await lifetime.CancelAsync(); return new JsonObject { ["cancelled"] = true }; } if (method != "run" || Interlocked.Exchange(ref started, 1) != 0) throw new InvalidOperationException("命令执行进程只接受一次任务"); command = ExecuteAsync(value?.AsObject() ?? [], lifetime.Token); return await command; }; peer.Start(); await peer.Completion; await lifetime.CancelAsync(); if (command is not null) { try { await command; } catch (Exception) { } } return 0; } public static async Task ExecuteAsync(JsonObject input, CancellationToken ct) { if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("命令行节点需要 Windows"); var shell = input.String("shell"); if (shell is not ("powershell" or "cmd")) throw new ArgumentException("请选择 PowerShell 或 CMD"); var script = input.String("script"); if (string.IsNullOrWhiteSpace(script) || script.Length > 256 * 1024) throw new ArgumentException("命令不能为空且不能超过 256 Ki 字符"); var directory = input.String("workingDirectory"); if (directory.Length == 0) directory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); directory = Path.GetFullPath(directory); if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("工作目录不存在:" + directory); var executable = shell == "cmd" ? Path.Combine(Environment.SystemDirectory, "cmd.exe") : Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"); var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, WorkingDirectory = directory, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 }; if (input["environment"] is JsonObject environment) foreach (var pair in environment) start.Environment[pair.Key] = pair.Value.Text(); string? scriptFile = null; try { if (shell == "powershell") { start.ArgumentList.Add("-NoLogo"); start.ArgumentList.Add("-NoProfile"); start.ArgumentList.Add("-NonInteractive"); start.ArgumentList.Add("-EncodedCommand"); start.ArgumentList.Add(Convert.ToBase64String(Encoding.Unicode.GetBytes("[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); $OutputEncoding = [Console]::OutputEncoding;\n" + script))); } else { var temporary = Path.Combine(Path.GetTempPath(), "XFEWorkflow-Commands", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(temporary); scriptFile = Path.Combine(temporary, "command.cmd"); await File.WriteAllTextAsync(scriptFile, "@echo off\r\nchcp 65001 >nul\r\n" + script.ReplaceLineEndings("\r\n"), new UTF8Encoding(false), ct); start.ArgumentList.Add("/D"); start.ArgumentList.Add("/C"); start.ArgumentList.Add(scriptFile); } using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); var seconds = input.Integer("timeoutSeconds", 300); if (seconds is < 1 or > 86400) throw new ArgumentException("命令超时必须为 1 到 86400 秒"); timeout.CancelAfter(TimeSpan.FromSeconds(seconds)); using var process = Process.Start(start) ?? throw new IOException("无法启动命令行"); var stdout = ReadAsync(process.StandardOutput); var stderr = ReadAsync(process.StandardError); try { await process.WaitForExitAsync(timeout.Token); } catch (OperationCanceledException) { if (!process.HasExited) process.Kill(true); await process.WaitForExitAsync(); await Task.WhenAll(stdout, stderr); if (ct.IsCancellationRequested) throw; throw new TimeoutException("命令执行超时,已终止进程及其子进程"); } var streams = await Task.WhenAll(stdout, stderr); var result = new JsonObject { ["stdout"] = streams[0].Text, ["stderr"] = streams[1].Text, ["exitCode"] = process.ExitCode, ["succeeded"] = process.ExitCode == 0, ["truncated"] = streams.Any(x => x.Truncated), ["processId"] = process.Id, ["administrator"] = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) }; if (input.Boolean("failOnNonZero") && process.ExitCode != 0) throw new InvalidOperationException($"命令退出码 {process.ExitCode}:{streams[1].Text}"); return result; } finally { if (scriptFile is not null) { File.Delete(scriptFile); try { Directory.Delete(Path.GetDirectoryName(scriptFile)!); } catch (IOException) { } } } } private static async Task<(string Text, bool Truncated)> ReadAsync(StreamReader reader) { const int limit = 256 * 1024; var text = new StringBuilder(); var buffer = new char[8192]; var truncated = false; while (await reader.ReadAsync(buffer) is var read && read > 0) { var keep = Math.Min(read, limit - text.Length); text.Append(buffer, 0, keep); truncated |= keep < read; } return (text.ToString(), truncated); } }