chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using OpenTap.Diagnostic;
 
namespace OpenTap
{
    /// <summary>
    /// This is an abstraction for running child processes with support for elevation.
    /// It executes a test step (which can have child test steps) in a new process
    /// It supports subscribing to log events from the child process, and forwarding the logs directly.
    /// </summary>
    class SubProcessHost
    {
        public bool ForwardLogs { get; set; } 
        public string LogHeader { get; set; } = "";
        public bool Unlocked { get; set; } = false;
        public HashSet<string> MutedSources { get; } = new HashSet<string>();
 
        public static bool IsAdmin()
        {
            if (OperatingSystem.Current == OperatingSystem.Windows)
            {
                using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
                {
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    return principal.IsInRole(WindowsBuiltInRole.Administrator);
                }
            }
            else // assume UNIX
            {
                // id -u should print '0' if running as sudo or the current user is root
                var pInfo = new ProcessStartInfo()
                {
                    FileName = "id",
                    Arguments = "-u",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                };
 
                using (var p = Process.Start(pInfo))
                {
                    if (p == null) return false;
                    var output = p.StandardOutput.ReadToEnd().Trim();
                    if (int.TryParse(output, out var id) && id == 0)
                        return true;
                    return false;
                }
            }
        }
 
        private static readonly TraceSource log = Log.CreateSource(nameof(SubProcessHost));
        internal Process LastProcessHandle;
 
        private static readonly object StdoutLock = new object();
        private static bool stdoutSuspended;
        private static TextWriter originalOut;
        private static StringWriter tmpOut;
 
        private static void SuspendStdout()
        {
            lock (StdoutLock)
            {
                if (stdoutSuspended) return;
                originalOut = Console.Out;
                tmpOut = new StringWriter();
                Console.SetOut(tmpOut);
                originalOut.Flush();
                stdoutSuspended = true;
            }
        }
 
        private static void ResumeStdout()
        {
            lock (StdoutLock)
            {
                if (stdoutSuspended == false) return;
                // Restore stdout after the server has connected
                Console.SetOut(originalOut);
                var lines = tmpOut.ToString()
                    .Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries);
 
                foreach (var line in lines)
                {
                    Console.WriteLine(line);
                }
 
                stdoutSuspended = false;
                tmpOut.Dispose();
                tmpOut = null;
            }
        }
 
        public Verdict Run(ITestStep step, bool elevate, CancellationToken token)
        {
            var plan = new TestPlan();
            plan.ChildTestSteps.Add(step);
            try
            {
                return Run(plan, elevate, token);
            }
            catch (Win32Exception ex)
            {
                // This happens when the UAC dialog is cancelled. It should be treated as an OperationCanceledException.
                if (ex.Message.Contains("The operation was canceled by the user"))
                    throw new OperationCanceledException(ex.Message);
                throw;
            }
        }
 
        public Verdict Run(TestPlan step, bool elevate, CancellationToken token)
        {
            var dotnet = ExecutorClient.Dotnet;
            var tapDll = Path.Combine(ExecutorClient.ExeDir, "tap.dll");
            var handle = Guid.NewGuid().ToString();
            var pInfo = new ProcessStartInfo(dotnet)
            {
                Arguments = $"\"{tapDll}\" {nameof(ProcessCliAction)} --PipeHandle \"{handle}\"",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
            };
 
            if (elevate)
            {
                if (OperatingSystem.Current == OperatingSystem.Linux)
                {
                    // -E preserves environment variables
                    pInfo.Arguments = $"-E \"{pInfo.FileName}\" {pInfo.Arguments}";
                    pInfo.FileName = "sudo";
                    if (SudoHelper.IsSudoAuthenticated() == false)
                        if (SudoHelper.Authenticate() == false)
                            throw new Exception($"User failed to authenticate as sudo.");
                }
                else
                {
                    pInfo.Verb = "runas";
                    pInfo.UseShellExecute = true;
                    pInfo.RedirectStandardOutput = false;
                    pInfo.RedirectStandardError = false;
                }
            }
 
            SuspendStdout();
 
            using var p = Process.Start(pInfo);
            LastProcessHandle = p ?? throw new Exception($"Failed to spawn process.");
 
            // Ensure the process is cleaned up
            TapThread.Current.AbortToken.Register(() =>
            {
                if (p.HasExited) return;
 
                try
                {
                    // process.Kill may throw if it has already exited.
                    p.Kill();
                }
                catch (Exception ex)
                {
                    log.Warning("Caught exception when killing process. {0}", ex.Message);
                }
            });
 
            try
            {
                var server = new NamedPipeServerStream(handle, PipeDirection.InOut, 1);
                try
                {
                    server.WaitForConnectionAsync(token).Wait(token);
                }
                catch (OperationCanceledException)
                {
                    throw new OperationCanceledException($"Process cancelled by the user.");
                }
                // Resume stdout after the server has connected as we now know the application has launched
                ResumeStdout();
 
                server.WriteMessage(step);
 
 
                while (server.IsConnected && p.HasExited == false)
                {
                    if (token.IsCancellationRequested)
                        throw new OperationCanceledException($"Process cancelled by the user.");
 
                    if (server.TryReadMessage<Event[]>(out var events) && ForwardLogs)
                    {
                        if (string.IsNullOrWhiteSpace(LogHeader) == false)
                        {
                            for(int i = 0; i < events.Length; i++)
                                events[i].Message = LogHeader + ": " + events[i].Message;
                        }
 
                        var _evt = events;
                        if (MutedSources.Any())
                        {
                            _evt = events.Where(e => !MutedSources.Contains(e.Source)).ToArray();
                        }
                        _evt.ForEach(((ILogContext2)Log.Context).AddEvent);
                    }
                }
 
                var processExitTask = Task.Run(() => p.WaitForExit(), token);
                var tokenCancelledTask = Task.Run(() => token.WaitHandle.WaitOne(), token);
 
                Task.WaitAny(processExitTask, tokenCancelledTask);
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException($"Process cancelled by the user.");
                }
 
                return (Verdict) p.ExitCode;
            }
            finally
            {
                ResumeStdout();
                if (p.HasExited == false)
                {
                    p.Kill();
                }
            }
        }
    }
}