forked from microsoft/WSL-DistroLauncher
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathDistributionInfo.cpp
More file actions
91 lines (81 loc) · 3 KB
/
DistributionInfo.cpp
File metadata and controls
91 lines (81 loc) · 3 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
//
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the terms described in the LICENSE file in the root of this project.
//
#include "stdafx.h"
bool DistributionInfo::CreateUser(std::wstring_view userName)
{
// Create the user account.
DWORD exitCode;
std::wstring commandLine = L"/usr/sbin/adduser --quiet --comment '' ";
commandLine += userName;
auto hr = g_wslApi.WslLaunchInteractive(commandLine.c_str(), true, &exitCode);
if (FAILED(hr) || exitCode != 0)
{
return false;
}
// Add the user account to any relevant groups.
commandLine = L"/usr/sbin/usermod -aG adm,cdrom,sudo,dip,plugdev,video,irc,render ";
commandLine += userName;
hr = g_wslApi.WslLaunchInteractive(commandLine.c_str(), true, &exitCode);
if (FAILED(hr) || exitCode != 0)
{
// Delete the user if the group add command failed.
commandLine = L"/usr/sbin/deluser ";
commandLine += userName;
g_wslApi.WslLaunchInteractive(commandLine.c_str(), true, &exitCode);
return false;
}
return true;
}
ULONG DistributionInfo::QueryUid(std::wstring_view userName)
{
// Create a pipe to read the output of the launched process.
HANDLE readPipe;
HANDLE writePipe;
SECURITY_ATTRIBUTES sa{sizeof sa, nullptr, true};
auto uid = UID_INVALID;
if (CreatePipe(&readPipe, &writePipe, &sa, 0))
{
// Query the UID of the supplied username.
std::wstring command = L"/usr/bin/id -u ";
command += userName;
HANDLE child;
// ReSharper disable once CppTooWideScope
// ReSharper disable once CppTooWideScopeInitStatement
auto hr = g_wslApi.WslLaunch(command.c_str(), true, GetStdHandle(STD_INPUT_HANDLE), writePipe,
GetStdHandle(STD_ERROR_HANDLE), &child);
if (SUCCEEDED(hr))
{
// Wait for the child to exit and ensure process exited successfully.
WaitForSingleObject(child, INFINITE);
DWORD exitCode;
if (GetExitCodeProcess(child, &exitCode) == false || exitCode != 0)
{
hr = E_INVALIDARG;
}
CloseHandle(child);
if (SUCCEEDED(hr))
{
// ReSharper disable once CppTooWideScope
char buffer[64]{};
DWORD bytesRead;
// Read the output of the command from the pipe and convert to a UID.
if (ReadFile(readPipe, buffer, sizeof buffer - 1, &bytesRead, nullptr))
{
buffer[bytesRead] = ANSI_NULL;
try
{
uid = std::stoul(buffer, nullptr, 10);
}
catch (...)
{
}
}
}
}
CloseHandle(readPipe);
CloseHandle(writePipe);
}
return uid;
}