-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathMsiExecArguments.cpp
More file actions
570 lines (505 loc) · 21.8 KB
/
MsiExecArguments.cpp
File metadata and controls
570 lines (505 loc) · 21.8 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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "Public/winget/MsiExecArguments.h"
#include "Public/AppInstallerErrors.h"
#include "Public/AppInstallerLogging.h"
#include "Public/AppInstallerStrings.h"
namespace AppInstaller::Msi
{
using namespace std::string_view_literals;
namespace
{
const char MsiExecQuietOption = 'q';
const char MsiExecLogOption = 'l';
// Description of how a long option is replaced by a short option.
struct TokenReplacement
{
TokenReplacement(std::string_view longOption, std::string_view shortOption) : LongOption(longOption), ShortOption({ shortOption }) {}
TokenReplacement(std::string_view longOption, std::vector<std::string_view>&& shortOption) : LongOption(longOption), ShortOption(std::move(shortOption)) {}
std::string_view LongOption;
std::vector<std::string_view> ShortOption;
};
// Determines whether an argument token is a switch/option.
bool IsSwitch(std::string_view token)
{
THROW_HR_IF(APPINSTALLER_CLI_ERROR_INTERNAL_ERROR, token.empty());
return token[0] == '-' || token[0] == '/';
}
// Parses the log mode and log file for the Log (/l) option.
// The option has a modifier specifying the log mode (what is logged)
// and a value specifying the log file.
// E.g. /l* log.txt, /lw warnings.txt
void ParseLogOption(std::string_view logModeString, std::string_view logFile, MsiParsedArguments& parsedArgs)
{
if (Utility::IsEmptyOrWhitespace(logFile))
{
AICLI_LOG(Core, Error, << "MSI log file path cannot be empty");
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
INSTALLLOGMODE logMode = {};
INSTALLLOGATTRIBUTES logAttributes = {};
// Note: These flags are mostly consecutive bits in the order given, except where indicated.
// Skipped flags are not mapped to a command line option.
std::map<char, INSTALLLOGMODE> ValidLogModes
{
{ 'm', INSTALLLOGMODE_FATALEXIT },
{ 'e', INSTALLLOGMODE_ERROR },
{ 'w', INSTALLLOGMODE_WARNING },
{ 'u', INSTALLLOGMODE_USER },
{ 'i', INSTALLLOGMODE_INFO },
// FILESINUSE
// RESOLVESOURCE
{ 'o', INSTALLLOGMODE_OUTOFDISKSPACE },
{ 'a', INSTALLLOGMODE_ACTIONSTART },
{ 'r', INSTALLLOGMODE_ACTIONDATA },
{ 'p', INSTALLLOGMODE_PROPERTYDUMP },
{ 'c', INSTALLLOGMODE_COMMONDATA },
{ 'v', INSTALLLOGMODE_VERBOSE },
{ 'x', INSTALLLOGMODE_EXTRADEBUG },
// LOGONLYONERROR
// LOGPERFORMANCE
};
std::map<char, INSTALLLOGATTRIBUTES> ValidLogAttributes
{
{ '+', INSTALLLOGATTRIBUTES_APPEND },
{ '!', INSTALLLOGATTRIBUTES_FLUSHEACHLINE },
};
bool isLogModeSet = false;
for (char c : logModeString)
{
// Log-all option
if (c == '*')
{
logMode |= AllLogMode;
isLogModeSet = true;
continue;
}
auto modeItr = ValidLogModes.find(c);
if (modeItr != ValidLogModes.end())
{
logMode |= modeItr->second;
isLogModeSet = true;
continue;
}
auto attributeItr = ValidLogAttributes.find(c);
if (attributeItr != ValidLogAttributes.end())
{
logAttributes |= attributeItr->second;
continue;
}
AICLI_LOG(Core, Error, << "Unknown msiexec log modifier: " << c);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
if (!isLogModeSet)
{
logMode = DefaultLogMode;
}
parsedArgs.LogMode = logMode;
parsedArgs.LogAttributes = logAttributes;
parsedArgs.LogFile = Utility::ConvertToUTF16(logFile);
}
// Parses the modifier for the UI Level option (/q)
// The modifier starts with a base (b, f, n, r), followed by extra flags (+, -, !).
// E.g. /qn, /qb-!
void ParseQuietOption(std::string_view modifier, MsiParsedArguments& parsedArgs)
{
if (modifier.empty())
{
// /q is treated as equivalent to /qn
modifier = "n"sv;
}
// Lower values in INSTALLUILEVEL work like a base enum (e.g. None=2, Basic=3)
// with higher values being modifying flags (e.g. HideCancel=0x20, ProgressOnly=0x40).
// Some steps depend on the base enum, so we keep it separate for easier checking.
INSTALLUILEVEL uiLevelBase = {};
INSTALLUILEVEL uiLevelModifiers = {};
// Parse the base level
switch (std::tolower(modifier[0]))
{
case 'f':
uiLevelBase = INSTALLUILEVEL_FULL;
break;
case 'r':
uiLevelBase = INSTALLUILEVEL_REDUCED;
break;
case 'b':
uiLevelBase = INSTALLUILEVEL_BASIC;
break;
case '+':
uiLevelBase = INSTALLUILEVEL_NONE;
uiLevelModifiers = INSTALLUILEVEL_ENDDIALOG;
break;
case 'n':
uiLevelBase = INSTALLUILEVEL_NONE;
break;
default:
AICLI_LOG(Core, Error, << "Invalid modifier for msiexec /q argument: " << modifier);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
};
// Parse the modifiers
for (size_t i = 1; i < modifier.size(); ++i)
{
const char c = modifier[i];
if (c == '+')
{
WI_SetFlag(uiLevelModifiers, INSTALLUILEVEL_ENDDIALOG);
}
else if (c == '-')
{
if (uiLevelBase == INSTALLUILEVEL_BASIC)
{
WI_SetFlag(uiLevelModifiers, INSTALLUILEVEL_PROGRESSONLY);
}
else
{
AICLI_LOG(Core, Error, << "msiexec UI option Progress Only (-) is only valid with UI level Basic (b)");
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
}
else if (c == '!')
{
if (uiLevelBase == INSTALLUILEVEL_BASIC)
{
WI_SetFlag(uiLevelModifiers, INSTALLUILEVEL_HIDECANCEL);
}
else
{
AICLI_LOG(Core, Error, << "msiexec UI option Hide Cancel (!) is only valid with UI level Basic (b)");
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
}
}
// Only deviation from msiexec:
// When using UI Level None, allow showing the UAC prompt.
WI_SetFlagIf(uiLevelModifiers, INSTALLUILEVEL_UACONLY, uiLevelBase == INSTALLUILEVEL_NONE);
parsedArgs.UILevel = uiLevelBase | uiLevelModifiers;
}
bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t';
}
// Gets the next token found in the arguments string, starting the search on the given position.
// If there are no more tokens, return empty.
// After finding the token, updates `start` to point to the next place we need to start the next token search.
std::string_view GetNextToken(std::string_view arguments, size_t& start)
{
// Eat leading whitespace
while (start < arguments.size() && IsWhiteSpace(arguments[start]))
{
++start;
}
if (start >= arguments.size())
{
// We reached the end
return {};
}
size_t pos = start;
bool seekingSpaceSeparator = ('"' != arguments[pos]);
bool withinQuotes = false;
// Start looking from the next character
++pos;
// Advance until we hit the end or the next separator
while (pos < arguments.size())
{
bool isSpace = IsWhiteSpace(arguments[pos]);
bool isQuote = ('"' == arguments[pos]);
if (isSpace || isQuote)
{
// We've encountered one of the two separators we're interested in
if (seekingSpaceSeparator)
{
if (isQuote)
{
// We will ignore space characters enclosed between double quotes
withinQuotes = !withinQuotes;
}
else
{
// This is a space character. If it is between quotes we ignore it;
// otherwise it is a separator.
if (!withinQuotes)
{
break;
}
}
}
else
{
if (isQuote)
{
// we've got what we needed, it is OK to stop
break;
}
}
}
++pos;
}
if (!seekingSpaceSeparator)
{
// We were looking for a terminating " character.
if (pos < arguments.size())
{
// We move past the " character (it is OK for the end of the line
// to act as the matching " character in some cases)
++pos;
}
}
auto result = arguments.substr(start, pos - start);
start = pos;
return result;
}
// Split the arguments string into tokens. Tokens are delimited by whitespace
// unless quoted. Each token represents an option (like /q), an argument
// for an option, or a property.
std::list<std::string> TokenizeMsiArguments(std::string_view arguments)
{
size_t start = 0;
std::list<std::string> result;
auto token = GetNextToken(arguments, start);
while (!token.empty())
{
result.emplace_back(token);
token = GetNextToken(arguments, start);
}
return result;
}
// Parses a token that represents an argument to an option.
// If the value is unquoted, returns it as is.
// If the value is quoted, removes the quotes and replaces escaped characters.
std::string ParseValue(std::string_view valueToken)
{
if (valueToken.empty() || valueToken[0] != '"')
{
// Nothing to do for empty or unquoted tokens
return std::string{ valueToken };
}
// Copy the string ignoring the quotes and replacing escaped characters.
// In quoted tokens, the back quote represents double quotes (` means ")
// and can be escaped with back slash (\` means `).
// Note that we accept quoted values with a missing closing quote (the end
// of string signals the end).
std::string result;
for (size_t i = 1; i < valueToken.size(); ++i)
{
if (valueToken[i] == '"')
{
// The tokenizer can leave several pairs of quotes in the token
// but they are not accepted in this case. We only accept the final
// closing quotes.
if (i + 1 == valueToken.size())
{
break;
}
else
{
AICLI_LOG(Core, Error, << "Invalid msiexec argument: " << valueToken);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
}
if (i + 1 < valueToken.size() && valueToken[i] == '\\' && valueToken[i + 1] == '`')
{
result += '`';
++i;
}
else if (valueToken[i] == '`')
{
result += '"';
}
else
{
result += valueToken[i];
}
}
return result;
}
// Validates that a token represents a property.
// This checks that the property has the form PropertyName=Value,
// with the value optionally quoted.
bool IsValidPropertyToken(std::string_view token)
{
THROW_HR_IF(APPINSTALLER_CLI_ERROR_INTERNAL_ERROR, token.empty());
if (token[0] != '%' && !IsCharAlphaNumericA(token[0]))
{
AICLI_LOG(Core, Error, << "Bad property for msiexec: " << token);
return false;
}
// Find the = separator at the end of the property name
size_t pos = 0;
while (pos < token.size() && !IsWhiteSpace(token[pos]) && token[pos] != '=')
{
++pos;
}
if (pos == token.size() || token[pos] != '=')
{
AICLI_LOG(Core, Error, << "Expected property for call to msiexec, but couldn't find separator: " << token);
return false;
}
// Validate the property value.
// It should be completely enclosed in quotes, or not contain white space.
// If quoted, there can be pairs of consecutive quotes that work as escape sequences.
// We accept empty property values.
++pos;
if (pos == token.size())
{
// Empty value
return true;
}
// If quoted, we will only inspect the values between the quotes.
bool quoted = false;
size_t end = token.size();
if (token[pos] == '"')
{
++pos;
if (pos >= end || token.back() != '"')
{
AICLI_LOG(Core, Error, << "Badly quoted msiexec property: " << token);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
--end;
quoted = true;
}
while (pos < end)
{
if (quoted)
{
// For quoted values, any internal quote must be followed by another one.
if (token[pos] == '"')
{
if (pos + 1 < end && token[pos + 1] == '"')
{
// Skip the two quotes
++pos;
}
else
{
AICLI_LOG(Core, Error, << "Unexpected quotes in msiexec property arg: " << token);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
}
}
else
{
// For unquoted values, we only check that there is no whitespace
if (IsWhiteSpace(token[pos]))
{
AICLI_LOG(Core, Error, << "Unexpected space in msiexec property arg: " << token);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
}
++pos;
}
return true;
}
// Replaces long options in the arguments (e.g. /quiet), by their short equivalents
// (e.g. /qn). The replacement is done in-place.
void ReplaceLongOptions(std::list<std::string>& tokens)
{
// We don't handle all possible options because we don't need to.
// Options not handled:
// /update
// /uninstall
// /package
// /help
const std::vector<TokenReplacement> Replacements
{
{ "quiet"sv, "/qn"sv },
{ "passive"sv, { "/qb!-"sv, "REBOOTPROMPT=S"sv } },
{ "norestart"sv, "REBOOT=ReallySuppress"sv },
{ "forcerestart"sv, "REBOOT=Force"sv },
{ "promptrestart"sv, "REBOOTPROMPT=\"\""sv },
{ "log"sv, "/l*"sv },
};
auto itr = tokens.begin();
while (itr != tokens.end())
{
if (!IsSwitch(*itr))
{
// We only need to replace switches.
++itr;
continue;
}
// Find if there is a replacement for this option.
// We ignore the leading / or - when comparing.
auto option = std::string_view(*itr).substr(1);
auto replacementItr = std::find_if(Replacements.begin(), Replacements.end(), [&](const TokenReplacement& replacement) { return Utility::CaseInsensitiveEquals(replacement.LongOption, option); });
if (replacementItr == Replacements.end())
{
// There is no replacement for this switch;
++itr;
continue;
}
// Add all the replacements tokens needed before this one, then delete the existing token.
tokens.insert(itr, replacementItr->ShortOption.begin(), replacementItr->ShortOption.end());
// Delete the current token an move to the next one.
// We don't need to do anything more to the newly added tokens.
itr = tokens.erase(itr);
}
}
// Consumes the next argument token in the list. If the token is an option
// that takes an argument, also consumes it. After consuming the token(s),
// removes it from the list and updates the parsed arguments accordingly.
void ConsumeNextToken(std::list<std::string>& tokens, MsiParsedArguments& parsedArgs)
{
THROW_HR_IF(APPINSTALLER_CLI_ERROR_INTERNAL_ERROR, tokens.empty());
auto token = std::move(tokens.front());
tokens.pop_front();
if (!IsSwitch(token))
{
// Token is a property, i.e. NAME=value. Add it to the parsed args.
THROW_HR_IF(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT, !IsValidPropertyToken(token));
parsedArgs.Properties += L" " + Utility::ConvertToUTF16(token);
return;
}
// Token is an option.
if (token.size() <= 1)
{
AICLI_LOG(Core, Error, << "Invalid command line argument for msiexec: " << token);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
char option = token[1];
auto optionModifier = ParseValue(std::string_view(token).substr(2));
// Options are case-insensitive
switch (std::tolower(option))
{
case MsiExecQuietOption:
{
ParseQuietOption(optionModifier, parsedArgs);
break;
}
case MsiExecLogOption:
{
if (tokens.empty())
{
// Log option must be followed by an option argument
AICLI_LOG(Core, Error, << "msiexec option " << token << " must be followed by a value");
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
const auto optionValue = ParseValue(tokens.front());
tokens.pop_front();
ParseLogOption(optionModifier, optionValue, parsedArgs);
break;
}
default:
{
AICLI_LOG(Core, Error, << "Invalid option for msiexec: " << token);
THROW_HR(APPINSTALLER_CLI_ERROR_INVALID_MSIEXEC_ARGUMENT);
}
}
}
}
MsiParsedArguments ParseMSIArguments(std::string_view arguments)
{
// Split the arguments into tokens, which we will process one by one.
auto argumentTokens = TokenizeMsiArguments(arguments);
// Replace long options so we can work only with short ones.
ReplaceLongOptions(argumentTokens);
// Process the arguments.
MsiParsedArguments result;
while (!argumentTokens.empty())
{
ConsumeNextToken(argumentTokens, result);
}
return result;
}
}