-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathUserSettings.cpp
More file actions
293 lines (249 loc) · 8.89 KB
/
UserSettings.cpp
File metadata and controls
293 lines (249 loc) · 8.89 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
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
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
UserSettings.cpp
Abstract:
Implementation of UserSettings — YAML loading and validation.
--*/
#include "UserSettings.h"
#include "filesystem.hpp"
#include "string.hpp"
#include "wslutil.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <format>
#include <fstream>
#include <set>
using namespace wsl::windows::common::string;
namespace wsl::windows::wslc::settings {
// Default settings file template — written on first run.
// All entries are commented out; the values shown are the built-in defaults.
// TODO: localization for comments needed?
static constexpr std::string_view s_DefaultSettingsTemplate =
"# wslc user settings\n"
"# https://aka.ms/wslc-settings\n"
"\n"
"session:\n"
" # Number of virtual CPUs allocated to the session (default: 4)\n"
" # cpuCount: 4\n"
"\n"
" # Memory limit for the session in megabytes (default: 2GB)\n"
" # memorySize: 2GB\n"
"\n"
" # Maximum disk image size in megabytes (default: 100GB)\n"
" # maxStorageSize: 100GB\n"
"\n"
" # Default path for session storage. By default, storage is per-session under:\n"
" # %LocalAppData%\\wslc\\sessions\\wslc-cli (standard sessions)\n"
" # %LocalAppData%\\wslc\\sessions\\wslc-cli-admin (elevated sessions)\n"
" # defaultStoragePath: \"\"\n";
// Validate individual setting specializations
namespace details {
std::optional<uint32_t> ParseSettingsMemoryValue(const std::string& value)
{
auto parsed = wsl::shared::string::ParseMemorySize(value.c_str());
auto converted = parsed.has_value() ? *parsed / _1MB : 0; // To Mb, and anything less than 1Mb is considered invalid.
return converted > 0 ? std::optional{static_cast<uint32_t>(converted)} : std::nullopt;
}
#define WSLC_VALIDATE_SETTING(_setting_) \
std::optional<SettingMapping<Setting::_setting_>::value_t> SettingMapping<Setting::_setting_>::Validate( \
const SettingMapping<Setting::_setting_>::yaml_t& value)
WSLC_VALIDATE_SETTING(SessionCpuCount)
{
return value > 0 ? std::optional{value} : std::nullopt;
}
WSLC_VALIDATE_SETTING(SessionMemoryMb)
{
return ParseSettingsMemoryValue(value);
}
WSLC_VALIDATE_SETTING(SessionStorageSizeMb)
{
return ParseSettingsMemoryValue(value);
}
// yaml_t = std::string (UTF-8 from yaml-cpp), value_t = std::wstring
WSLC_VALIDATE_SETTING(SessionStoragePath)
{
return MultiByteToWide(value);
}
WSLC_VALIDATE_SETTING(SessionNetworkingMode)
{
if (value == "none")
{
return WSLCNetworkingModeNone;
}
if (value == "nat")
{
return WSLCNetworkingModeNAT;
}
if (value == "virtioproxy")
{
return WSLCNetworkingModeVirtioProxy;
}
return std::nullopt;
}
WSLC_VALIDATE_SETTING(SessionHostFileShareMode)
{
if (value == "plan9")
{
return HostFileShareMode::Plan9;
}
if (value == "virtiofs")
{
return HostFileShareMode::VirtioFs;
}
return std::nullopt;
}
WSLC_VALIDATE_SETTING(SessionDnsTunneling)
{
return value;
}
#undef WSLC_VALIDATE_SETTING
} // namespace details
// Helpers
namespace {
// Traverses a dot-separated path (e.g. "session.cpuCount") through a YAML node tree.
// Returns nullopt if any segment is invalid or missing.
std::optional<YAML::Node> NavigateYamlPath(const YAML::Node& root, std::string_view path)
{
YAML::Node current = root;
auto subPaths = wsl::shared::string::Split(std::string{path}, '.');
for (auto const& subPath : subPaths)
{
if (current.IsDefined() && current.IsMap())
{
// Use the const operator[] to avoid yaml-cpp's AssignNode/set_ref side-effect,
// which mutates the shared detail::node and corrupts subsequent lookups.
// Then use reset() to rebind 'current' without triggering set_ref.
auto child = static_cast<const YAML::Node&>(current)[subPath];
if (!child.IsDefined())
{
return std::nullopt;
}
current.reset(child);
}
else
{
return std::nullopt;
}
}
return current;
}
// Validates and stores a single setting from the YAML document.
template <Setting S>
void ValidateSetting(const YAML::Node& root, SettingsMap& map, std::vector<Warning>& warnings)
{
constexpr auto path = details::SettingMapping<S>::YamlPath;
auto node = NavigateYamlPath(root, path);
if (!node || !node->IsDefined() || node->IsNull())
{
// Key absent — silently use the built-in default.
return;
}
try
{
auto rawValue = node->as<typename details::SettingMapping<S>::yaml_t>();
auto validated = details::SettingMapping<S>::Validate(rawValue);
if (validated.has_value())
{
map.Add<S>(std::move(validated.value()));
}
else
{
const auto widePath = MultiByteToWide(path);
warnings.push_back({std::format(L"Warning: Invalid value for setting '{}'. Using default.", widePath), widePath});
}
}
catch (...)
{
const auto widePath = MultiByteToWide(path);
warnings.push_back({std::format(L"Warning: Invalid type for setting '{}'. Using default.", widePath), widePath});
}
}
// Validates all settings via a fold over the Setting enum index sequence.
template <size_t... S>
void ValidateAll(const YAML::Node& root, SettingsMap& map, std::vector<Warning>& warnings, std::index_sequence<S...>)
{
(ValidateSetting<static_cast<Setting>(S)>(root, map, warnings), ...);
}
// Attempts to parse a YAML document from the given file path.
// Returns an empty optional and pushes a warning if the file exists but fails to parse.
std::optional<YAML::Node> TryLoadYaml(const std::filesystem::path& path, std::vector<Warning>& warnings)
{
std::ifstream stream(path);
if (!stream.is_open())
{
auto err = errno;
// If the file exists but cannot be opened (permissions, sharing violation, etc.),
// emit a warning so the user understands why settings were ignored.
if (err != ENOENT)
{
warnings.push_back(
{std::format(L"Warning: Failed to open '{}', errno: {}. Using default settings.", path.filename().wstring(), err), {}});
}
return std::nullopt;
}
try
{
return YAML::Load(stream);
}
catch (const std::exception& e)
{
warnings.push_back(
{std::format(L"Warning: '{}' could not be parsed: {}.", path.filename().wstring(), MultiByteToWide(e.what())), {}});
return std::nullopt;
}
}
const std::filesystem::path& SettingsDir()
{
static const std::filesystem::path dir = wsl::windows::common::filesystem::GetLocalAppDataPath(nullptr) / L"wslc";
return dir;
}
} // namespace
UserSettings const& UserSettings::Instance()
{
static UserSettings instance;
return instance;
}
UserSettings::UserSettings() : UserSettings(SettingsDir())
{
}
UserSettings::UserSettings(const std::filesystem::path& settingsDir)
{
m_settingsPath = settingsDir / L"settings.yaml";
auto root = TryLoadYaml(m_settingsPath, m_warnings);
if (root.has_value())
{
m_type = UserSettingsType::Standard;
}
if (root.has_value())
{
constexpr auto settingCount = static_cast<size_t>(Setting::Max);
ValidateAll(root.value(), m_settings, m_warnings, std::make_index_sequence<settingCount>());
// TODO: Iterate through all nodes and warn about unknown keys?
}
// Emit any settings load warnings.
for (const auto& warning : m_warnings)
{
wsl::windows::common::wslutil::PrintMessage(warning.Message, stderr);
}
}
void UserSettings::Reset() const
{
std::filesystem::create_directories(m_settingsPath.parent_path());
std::ofstream file(m_settingsPath);
THROW_HR_IF_MSG(E_UNEXPECTED, !file.is_open(), "Failed to create settings file");
file << s_DefaultSettingsTemplate;
}
void UserSettings::PrepareToShellExecuteFile() const
{
if (m_type == UserSettingsType::Default && !std::filesystem::exists(m_settingsPath))
{
// First run — create the directory and write the commented-out defaults template.
Reset();
}
}
std::filesystem::path UserSettings::SettingsFilePath() const
{
return m_settingsPath;
}
} // namespace wsl::windows::wslc::settings