/
Wsl.cs
445 lines (362 loc) · 18.3 KB
/
Wsl.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Wslhub.Sdk
{
/// <summary>
/// Provides functionality to help you call WSL from .NET applications.
/// </summary>
public static class Wsl
{
/// <summary>
/// Call CoInitializeSecurity so that you can call the WSL API.
/// </summary>
public static void InitializeSecurityModel()
{
var result = NativeMethods.CoInitializeSecurity(
IntPtr.Zero,
(-1),
IntPtr.Zero,
IntPtr.Zero,
NativeMethods.RpcAuthnLevel.Default,
NativeMethods.RpcImpLevel.Impersonate,
IntPtr.Zero,
NativeMethods.EoAuthnCap.StaticCloaking,
IntPtr.Zero);
if (result != 0)
throw new COMException("Cannot complete CoInitializeSecurity.", result);
}
/// <summary>
/// Checks if a 64-bit process is running on a 64-bit system.
/// </summary>
/// <returns>Returns True or False depending on whether or not.</returns>
private static bool InternalCheckIsWow64()
{
var osvi = new NativeMethods.OSVERSIONINFOEXW();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
if (NativeMethods.GetVersionExW(ref osvi))
{
if ((osvi.dwMajorVersion == 5 && osvi.dwMinorVersion >= 1) ||
osvi.dwMajorVersion >= 6)
{
if (NativeMethods.IsWow64Process(NativeMethods.GetCurrentProcess(), out bool retVal))
return retVal;
}
}
return false;
}
/// <summary>
/// Checks if the environment you are running in now supports WSL.
/// </summary>
public static void AssertWslSupported()
{
var commonErrorMessage = "Windows Subsystems for Linux requires 64-bit system and latest version of Windows 10 or higher than Windows Server 1709.";
var is64BitProcess = (IntPtr.Size == 8);
var is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();
if (!is64BitOperatingSystem || !is64BitProcess)
throw new PlatformNotSupportedException(commonErrorMessage);
var osvi = new NativeMethods.OSVERSIONINFOEXW();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
if (!NativeMethods.GetVersionExW(ref osvi))
throw new PlatformNotSupportedException(commonErrorMessage);
if (osvi.dwPlatformId != 2)
throw new PlatformNotSupportedException(commonErrorMessage);
if (osvi.dwMajorVersion < 10 ||
osvi.dwMinorVersion < 0 ||
osvi.dwBuildNumber < 16299)
throw new PlatformNotSupportedException(commonErrorMessage);
var systemDirectory = Path.Combine(
Environment.GetEnvironmentVariable("WINDIR"),
"system32");
if (!File.Exists(Path.Combine(systemDirectory, "wslapi.dll")))
throw new NotSupportedException("This system does not have WSL enabled.");
if (!File.Exists(Path.Combine(systemDirectory, "wsl.exe")))
throw new NotSupportedException("This system does not have wsl.exe CLI.");
}
/// <summary>
/// Reads WSL-related information from a registry key and returns it as a model object.
/// </summary>
/// <param name="lxssKey">Registry key from which to read information.</param>
/// <param name="keyName">The GUID name under the LXSS registry key.</param>
/// <param name="parsedDefaultGuid">Default distribution's GUID key as recorded in the LXSS registry key.</param>
/// <returns>Returns the WSL distribution information obtained through registry information.</returns>
private static DistroRegistryInfo ReadFromRegistryKey(RegistryKey lxssKey, string keyName, Guid? parsedDefaultGuid)
{
if (!Guid.TryParse(keyName, out Guid parsedGuid))
return null;
using (var distroKey = lxssKey.OpenSubKey(keyName))
{
var distroName = distroKey.GetValue("DistributionName", default(string)) as string;
if (string.IsNullOrWhiteSpace(distroName))
return null;
var basePath = distroKey.GetValue("BasePath", default(string)) as string;
var normalizedPath = Path.GetFullPath(basePath);
var kernelCommandLine = (distroKey.GetValue("KernelCommandLine", default(string)) as string ?? string.Empty);
var result = new DistroRegistryInfo()
{
DistroId = parsedGuid,
DistroName = distroName,
BasePath = normalizedPath,
};
result.KernelCommandLine.AddRange(kernelCommandLine.Split(
new char[] { ' ', '\t', },
StringSplitOptions.RemoveEmptyEntries));
if (parsedDefaultGuid.HasValue && parsedDefaultGuid == parsedGuid)
{
result.IsDefault = true;
return result;
}
}
return null;
}
/// <summary>
/// Returns information about the default WSL distribution from the registry.
/// </summary>
/// <returns>
/// Returns default WSL distribution information obtained through registry information.
/// Returns null if no WSL distro is installed or no distro is set as the default.
/// </returns>
public static DistroRegistryInfo GetDefaultDistro()
{
var currentUser = Registry.CurrentUser;
var lxssPath = Path.Combine("SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Lxss");
using (var lxssKey = currentUser.OpenSubKey(lxssPath, false))
{
var defaultGuid = Guid.TryParse(
lxssKey.GetValue("DefaultDistribution", default(string)) as string,
out Guid parsedDefaultGuid) ? parsedDefaultGuid : default(Guid?);
foreach (var keyName in lxssKey.GetSubKeyNames())
{
var info = ReadFromRegistryKey(lxssKey, keyName, defaultGuid);
if (info == null)
continue;
if (info.IsDefault)
return info;
}
}
return null;
}
/// <summary>
/// Returns information about WSL distributions obtained from the registry without calling the WSL API.
/// </summary>
/// <returns>Returns a list of information about the searched WSL distributions.</returns>
public static IEnumerable<DistroRegistryInfo> GetDistroListFromRegistry()
{
var currentUser = Registry.CurrentUser;
var lxssPath = Path.Combine("SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Lxss");
using (var lxssKey = currentUser.OpenSubKey(lxssPath, false))
{
var defaultGuid = Guid.TryParse(
lxssKey.GetValue("DefaultDistribution", default(string)) as string,
out Guid parsedDefaultGuid) ? parsedDefaultGuid : default(Guid?);
foreach (var keyName in lxssKey.GetSubKeyNames())
{
var info = ReadFromRegistryKey(lxssKey, keyName, defaultGuid);
if (info == null)
continue;
if (info.IsDefault)
yield return info;
}
}
}
/// <summary>
/// Get details of WSL distributions reported as installed on the system by calling the WSL API.
/// </summary>
/// <returns>Returns the list of WSL distributions inquired for detailed information with the WSL API.</returns>
public unsafe static IEnumerable<DistroInfo> GetDistroQueryResult()
{
AssertWslSupported();
var results = new List<DistroInfo>();
foreach (var eachItem in GetDistroListFromRegistry())
{
var distro = new DistroInfo()
{
DistroId = eachItem.DistroId,
DistroName = eachItem.DistroName,
BasePath = eachItem.BasePath,
};
distro.KernelCommandLine.AddRange(eachItem.KernelCommandLine);
results.Add(distro);
distro.IsRegistered = NativeMethods.WslIsDistributionRegistered(eachItem.DistroName);
if (!distro.IsRegistered)
continue;
var hr = NativeMethods.WslGetDistributionConfiguration(
eachItem.DistroName,
out int distroVersion,
out int defaultUserId,
out DistroFlags flags,
out IntPtr environmentVariables,
out int environmentVariableCount);
if (hr != 0)
continue;
distro.WslVersion = distroVersion;
distro.DefaultUid = defaultUserId;
distro.DistroFlags = flags;
var lpEnvironmentVariables = (byte***)environmentVariables.ToPointer();
for (int i = 0; i < environmentVariableCount; i++)
{
byte** lpArray = lpEnvironmentVariables[i];
var content = Marshal.PtrToStringAnsi(new IntPtr(lpArray));
distro.DefaultEnvironmentVariables.Add(content);
Marshal.FreeCoTaskMem(new IntPtr(lpArray));
}
Marshal.FreeCoTaskMem(new IntPtr(lpEnvironmentVariables));
}
return results;
}
/// <summary>
/// Execute the specified command through the default shell of a specific WSL distribution, and get the result as a System.IO.Stream object.
/// </summary>
/// <param name="distroName">The name of the WSL distribution on which to run the command.</param>
/// <param name="commandLine">The command you want to run.</param>
/// <param name="outputStream">The System.IO.Stream object to receive the results. It must be writable.</param>
/// <param name="bufferLength">Specifies the size of the buffer array to use when copying from anonymous pipes to the underlying stream. You do not need to specify a value.</param>
/// <returns>Returns the sum of the number of bytes received.</returns>
public static unsafe long RunWslCommand(string distroName, string commandLine, Stream outputStream, int bufferLength = 65536)
{
var isRegistered = NativeMethods.WslIsDistributionRegistered(distroName);
if (!isRegistered)
throw new Exception($"{distroName} is not registered distro.");
var stdin = NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE);
var stderr = NativeMethods.GetStdHandle(NativeMethods.STD_ERROR_HANDLE);
var attributes = new NativeMethods.SECURITY_ATTRIBUTES
{
lpSecurityDescriptor = IntPtr.Zero,
bInheritHandle = true,
};
attributes.nLength = Marshal.SizeOf(attributes);
if (!NativeMethods.CreatePipe(out IntPtr readPipe, out IntPtr writePipe, ref attributes, 0))
throw new Exception("Cannot create pipe for I/O.");
try
{
var hr = NativeMethods.WslLaunch(distroName, commandLine, false, stdin, writePipe, stderr, out IntPtr child);
if (hr < 0)
throw new COMException("Cannot launch WSL process", hr);
NativeMethods.WaitForSingleObject(child, NativeMethods.INFINITE);
if (!NativeMethods.GetExitCodeProcess(child, out int exitCode))
{
var lastError = Marshal.GetLastWin32Error();
NativeMethods.CloseHandle(child);
throw new Win32Exception(lastError, "Cannot query exit code of the process.");
}
if (exitCode != 0)
{
NativeMethods.CloseHandle(child);
throw new Exception($"Process exit code is non-zero: {exitCode}");
}
NativeMethods.CloseHandle(child);
bufferLength = Math.Min(bufferLength, 1024);
var bufferPointer = Marshal.AllocHGlobal(bufferLength);
var pBufferPointer = (byte*)bufferPointer.ToPointer();
var buffer = new byte[bufferLength];
var length = 0L;
var read = 0;
while (true)
{
if (!NativeMethods.ReadFile(readPipe, bufferPointer, bufferLength, out read, IntPtr.Zero))
{
var lastError = Marshal.GetLastWin32Error();
Marshal.FreeHGlobal(bufferPointer);
if (lastError != 0)
throw new Win32Exception(lastError, "Cannot read data from pipe.");
break;
}
fixed (byte* pBuffer = buffer)
{
Buffer.MemoryCopy(pBufferPointer, pBuffer, read, read);
length += read;
}
outputStream.Write(buffer, 0, read);
if (read < bufferLength)
{
Marshal.FreeHGlobal(bufferPointer);
break;
}
}
return length;
}
finally
{
NativeMethods.CloseHandle(readPipe);
NativeMethods.CloseHandle(writePipe);
}
}
/// <summary>
/// Execute the specified command through the default shell of a specific WSL distribution, and get the result as a string.
/// </summary>
/// <remarks>
/// When receiving data from WSL, it is encoded as UTF-8 data without the byte order mark.
/// </remarks>
/// <param name="distroName">The name of the WSL distribution on which to run the command.</param>
/// <param name="commandLine">The command you want to run.</param>
/// <param name="bufferLength">Specifies the size of the buffer array to use when copying from anonymous pipes to the underlying stream. You do not need to specify a value.</param>
/// <returns>Returns the collected output string.</returns>
public static unsafe string RunWslCommand(string distroName, string commandLine, int bufferLength = 65536)
{
var isRegistered = NativeMethods.WslIsDistributionRegistered(distroName);
if (!isRegistered)
throw new Exception($"{distroName} is not registered distro.");
var stdin = NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE);
var stderr = NativeMethods.GetStdHandle(NativeMethods.STD_ERROR_HANDLE);
var attributes = new NativeMethods.SECURITY_ATTRIBUTES
{
lpSecurityDescriptor = IntPtr.Zero,
bInheritHandle = true,
};
attributes.nLength = Marshal.SizeOf(attributes);
if (!NativeMethods.CreatePipe(out IntPtr readPipe, out IntPtr writePipe, ref attributes, 0))
throw new Exception("Cannot create pipe for I/O.");
try
{
var hr = NativeMethods.WslLaunch(distroName, commandLine, false, stdin, writePipe, stderr, out IntPtr child);
if (hr < 0)
throw new COMException("Cannot launch WSL process", hr);
NativeMethods.WaitForSingleObject(child, NativeMethods.INFINITE);
if (!NativeMethods.GetExitCodeProcess(child, out int exitCode))
{
var lastError = Marshal.GetLastWin32Error();
NativeMethods.CloseHandle(child);
throw new Win32Exception(lastError, "Cannot query exit code of the process.");
}
if (exitCode != 0)
{
NativeMethods.CloseHandle(child);
throw new Exception($"Process exit code is non-zero: {exitCode}");
}
NativeMethods.CloseHandle(child);
bufferLength = Math.Min(bufferLength, 1024);
var bufferPointer = Marshal.AllocHGlobal(bufferLength);
var outputContents = new StringBuilder();
var encoding = new UTF8Encoding(false);
var read = 0;
while (true)
{
if (!NativeMethods.ReadFile(readPipe, bufferPointer, bufferLength, out read, IntPtr.Zero))
{
var lastError = Marshal.GetLastWin32Error();
Marshal.FreeHGlobal(bufferPointer);
if (lastError != 0)
throw new Win32Exception(lastError, "Cannot read data from pipe.");
break;
}
outputContents.Append(encoding.GetString((byte *)bufferPointer.ToPointer(), read));
if (read < bufferLength)
{
Marshal.FreeHGlobal(bufferPointer);
break;
}
}
return outputContents.ToString();
}
finally
{
NativeMethods.CloseHandle(readPipe);
NativeMethods.CloseHandle(writePipe);
}
}
}
}