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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
|
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.
#include "precomp.h"
// constants
const DWORD RESTART_RETRIES = 10;
// internal function declarations
static HRESULT InitializeEngineState(
__in BURN_ENGINE_STATE* pEngineState,
__in HANDLE hEngineFile
);
static void UninitializeEngineState(
__in BURN_ENGINE_STATE* pEngineState
);
static HRESULT RunUntrusted(
__in LPCWSTR wzCommandLine,
__in BURN_ENGINE_STATE* pEngineState
);
static HRESULT RunNormal(
__in HINSTANCE hInstance,
__in BURN_ENGINE_STATE* pEngineState
);
static HRESULT RunElevated(
__in HINSTANCE hInstance,
__in LPCWSTR wzCommandLine,
__in BURN_ENGINE_STATE* pEngineState
);
static HRESULT RunEmbedded(
__in HINSTANCE hInstance,
__in BURN_ENGINE_STATE* pEngineState
);
static HRESULT RunRunOnce(
__in const BURN_REGISTRATION* pRegistration,
__in int nCmdShow
);
static HRESULT RunApplication(
__in BURN_ENGINE_STATE* pEngineState,
__out BOOL* pfReloadApp
);
static HRESULT ProcessMessage(
__in BURN_ENGINE_STATE* pEngineState,
__in const MSG* pmsg
);
static HRESULT DAPI RedirectLoggingOverPipe(
__in_z LPCSTR szString,
__in_opt LPVOID pvContext
);
static HRESULT Restart();
// function definitions
extern "C" BOOL EngineInCleanRoom(
__in_z_opt LPCWSTR wzCommandLine
)
{
// Be very careful with the functions you call from here.
// This function will be called before ::SetDefaultDllDirectories()
// has been called so dependencies outside of kernel32.dll are
// very likely to introduce DLL hijacking opportunities.
static DWORD cchCleanRoomSwitch = lstrlenW(BURN_COMMANDLINE_SWITCH_CLEAN_ROOM);
// This check is wholly dependent on the clean room command line switch being
// present at the beginning of the command line. Since Burn is the only thing
// that should be setting this command line option, that is in our control.
BOOL fInCleanRoom = (wzCommandLine &&
(wzCommandLine[0] == L'-' || wzCommandLine[0] == L'/') &&
CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, wzCommandLine + 1, cchCleanRoomSwitch, BURN_COMMANDLINE_SWITCH_CLEAN_ROOM, cchCleanRoomSwitch) &&
wzCommandLine[1 + cchCleanRoomSwitch] == L'='
);
return fInCleanRoom;
}
extern "C" HRESULT EngineRun(
__in HINSTANCE hInstance,
__in HANDLE hEngineFile,
__in_z_opt LPCWSTR wzCommandLine,
__in int nCmdShow,
__out DWORD* pdwExitCode
)
{
HRESULT hr = S_OK;
BOOL fComInitialized = FALSE;
BOOL fLogInitialized = FALSE;
BOOL fCrypInitialized = FALSE;
BOOL fRegInitialized = FALSE;
BOOL fWiuInitialized = FALSE;
BOOL fXmlInitialized = FALSE;
OSVERSIONINFOEXW ovix = { };
LPWSTR sczExePath = NULL;
BOOL fRunNormal = FALSE;
BOOL fRestart = FALSE;
BURN_ENGINE_STATE engineState = { };
engineState.command.cbSize = sizeof(BOOTSTRAPPER_COMMAND);
// Always initialize logging first
LogInitialize(::GetModuleHandleW(NULL));
fLogInitialized = TRUE;
// Ensure that log contains approriate level of information
#ifdef _DEBUG
LogSetLevel(REPORT_DEBUG, FALSE);
#else
LogSetLevel(REPORT_VERBOSE, FALSE); // FALSE means don't write an additional text line to the log saying the level changed
#endif
hr = AppParseCommandLine(wzCommandLine, &engineState.argc, &engineState.argv);
ExitOnFailure(hr, "Failed to parse command line.");
hr = InitializeEngineState(&engineState, hEngineFile);
ExitOnFailure(hr, "Failed to initialize engine state.");
engineState.command.nCmdShow = nCmdShow;
// initialize platform layer
PlatformInitialize();
// initialize COM
hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
ExitOnFailure(hr, "Failed to initialize COM.");
fComInitialized = TRUE;
// Initialize dutil.
hr = CrypInitialize();
ExitOnFailure(hr, "Failed to initialize Cryputil.");
fCrypInitialized = TRUE;
hr = RegInitialize();
ExitOnFailure(hr, "Failed to initialize Regutil.");
fRegInitialized = TRUE;
hr = WiuInitialize();
ExitOnFailure(hr, "Failed to initialize Wiutil.");
fWiuInitialized = TRUE;
hr = XmlInitialize();
ExitOnFailure(hr, "Failed to initialize XML util.");
fXmlInitialized = TRUE;
ovix.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
#pragma warning(suppress: 4996)
if (!::GetVersionExW((LPOSVERSIONINFOW)&ovix))
{
ExitWithLastError(hr, "Failed to get OS info.");
}
PathForCurrentProcess(&sczExePath, NULL); // Ignore failure.
LogId(REPORT_STANDARD, MSG_BURN_INFO, szVerMajorMinorBuild, ovix.dwMajorVersion, ovix.dwMinorVersion, ovix.dwBuildNumber, ovix.wServicePackMajor, sczExePath);
ReleaseNullStr(sczExePath);
// initialize core
hr = CoreInitialize(&engineState);
ExitOnFailure(hr, "Failed to initialize core.");
// Select run mode.
switch (engineState.mode)
{
case BURN_MODE_UNTRUSTED:
hr = RunUntrusted(wzCommandLine, &engineState);
ExitOnFailure(hr, "Failed to run untrusted mode.");
break;
case BURN_MODE_NORMAL:
fRunNormal = TRUE;
hr = RunNormal(hInstance, &engineState);
ExitOnFailure(hr, "Failed to run per-user mode.");
break;
case BURN_MODE_ELEVATED:
hr = RunElevated(hInstance, wzCommandLine, &engineState);
ExitOnFailure(hr, "Failed to run per-machine mode.");
break;
case BURN_MODE_EMBEDDED:
fRunNormal = TRUE;
hr = RunEmbedded(hInstance, &engineState);
ExitOnFailure(hr, "Failed to run embedded mode.");
break;
case BURN_MODE_RUNONCE:
hr = RunRunOnce(&engineState.registration, nCmdShow);
ExitOnFailure(hr, "Failed to run RunOnce mode.");
break;
default:
hr = E_UNEXPECTED;
ExitOnFailure(hr, "Invalid run mode.");
}
// set exit code and remember if we are supposed to restart.
*pdwExitCode = engineState.userExperience.dwExitCode;
fRestart = engineState.fRestart;
LExit:
ReleaseStr(sczExePath);
// If anything went wrong but the log was never open, try to open a "failure" log
// and that will dump anything captured in the log memory buffer to the log.
if (FAILED(hr) && BURN_LOGGING_STATE_CLOSED == engineState.log.state)
{
LoggingOpenFailed();
}
UserExperienceRemove(&engineState.userExperience);
CacheRemoveWorkingFolder(engineState.registration.sczId);
CacheUninitialize();
// If this is a related bundle (but not an update) suppress restart and return the standard restart error code.
if (fRestart && BOOTSTRAPPER_RELATION_NONE != engineState.command.relationType && BOOTSTRAPPER_RELATION_UPDATE != engineState.command.relationType)
{
LogId(REPORT_STANDARD, MSG_RESTART_ABORTED, LoggingRelationTypeToString(engineState.command.relationType));
fRestart = FALSE;
hr = HRESULT_FROM_WIN32(ERROR_SUCCESS_REBOOT_REQUIRED);
}
UninitializeEngineState(&engineState);
if (fXmlInitialized)
{
XmlUninitialize();
}
if (fWiuInitialized)
{
WiuUninitialize();
}
if (fRegInitialized)
{
RegUninitialize();
}
if (fCrypInitialized)
{
CrypUninitialize();
}
if (fComInitialized)
{
::CoUninitialize();
}
if (fRunNormal)
{
LogId(REPORT_STANDARD, MSG_EXITING, FAILED(hr) ? (int)hr : *pdwExitCode, LoggingBoolToString(fRestart));
if (fRestart)
{
LogId(REPORT_STANDARD, MSG_RESTARTING);
}
}
if (fLogInitialized)
{
LogClose(FALSE);
}
if (fRestart)
{
Restart();
}
if (fLogInitialized)
{
LogUninitialize(FALSE);
}
return hr;
}
// internal function definitions
static HRESULT InitializeEngineState(
__in BURN_ENGINE_STATE* pEngineState,
__in HANDLE hEngineFile
)
{
HRESULT hr = S_OK;
LPCWSTR wzParam = NULL;
HANDLE hSectionFile = hEngineFile;
HANDLE hSourceEngineFile = INVALID_HANDLE_VALUE;
pEngineState->automaticUpdates = BURN_AU_PAUSE_ACTION_IFELEVATED;
pEngineState->dwElevatedLoggingTlsId = TLS_OUT_OF_INDEXES;
::InitializeCriticalSection(&pEngineState->csActive);
::InitializeCriticalSection(&pEngineState->userExperience.csEngineActive);
PipeConnectionInitialize(&pEngineState->companionConnection);
PipeConnectionInitialize(&pEngineState->embeddedConnection);
for (int i = 0; i < pEngineState->argc; ++i)
{
if (pEngineState->argv[i][0] == L'-')
{
if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, &pEngineState->argv[i][1], lstrlenW(BURN_COMMANDLINE_SWITCH_FILEHANDLE_ATTACHED), BURN_COMMANDLINE_SWITCH_FILEHANDLE_ATTACHED, lstrlenW(BURN_COMMANDLINE_SWITCH_FILEHANDLE_ATTACHED)))
{
wzParam = &pEngineState->argv[i][2 + lstrlenW(BURN_COMMANDLINE_SWITCH_FILEHANDLE_ATTACHED)];
if (L'=' != wzParam[-1] || L'\0' == wzParam[0])
{
ExitOnRootFailure(hr = E_INVALIDARG, "Missing required parameter for switch: %ls", BURN_COMMANDLINE_SWITCH_FILEHANDLE_ATTACHED);
}
hr = StrStringToUInt32(wzParam, 0, reinterpret_cast<UINT*>(&hSourceEngineFile));
ExitOnFailure(hr, "Failed to parse file handle: '%ls'", (wzParam));
}
if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, &pEngineState->argv[i][1], lstrlenW(BURN_COMMANDLINE_SWITCH_FILEHANDLE_SELF), BURN_COMMANDLINE_SWITCH_FILEHANDLE_SELF, lstrlenW(BURN_COMMANDLINE_SWITCH_FILEHANDLE_SELF)))
{
wzParam = &pEngineState->argv[i][2 + lstrlenW(BURN_COMMANDLINE_SWITCH_FILEHANDLE_SELF)];
if (L'=' != wzParam[-1] || L'\0' == wzParam[0])
{
ExitOnRootFailure(hr = E_INVALIDARG, "Missing required parameter for switch: %ls", BURN_COMMANDLINE_SWITCH_FILEHANDLE_SELF);
}
hr = StrStringToUInt32(wzParam, 0, reinterpret_cast<UINT*>(&hSectionFile));
ExitOnFailure(hr, "Failed to parse file handle: '%ls'", (wzParam));
}
}
}
hr = SectionInitialize(&pEngineState->section, hSectionFile, hSourceEngineFile);
ExitOnFailure(hr, "Failed to initialize engine section.");
LExit:
return hr;
}
static void UninitializeEngineState(
__in BURN_ENGINE_STATE* pEngineState
)
{
if (pEngineState->argv)
{
AppFreeCommandLineArgs(pEngineState->argv);
}
ReleaseStr(pEngineState->sczIgnoreDependencies);
PipeConnectionUninitialize(&pEngineState->embeddedConnection);
PipeConnectionUninitialize(&pEngineState->companionConnection);
ReleaseStr(pEngineState->sczBundleEngineWorkingPath)
ReleaseHandle(pEngineState->hMessageWindowThread);
BurnExtensionUninitialize(&pEngineState->extensions);
::DeleteCriticalSection(&pEngineState->userExperience.csEngineActive);
UserExperienceUninitialize(&pEngineState->userExperience);
ApprovedExesUninitialize(&pEngineState->approvedExes);
UpdateUninitialize(&pEngineState->update);
VariablesUninitialize(&pEngineState->variables);
SearchesUninitialize(&pEngineState->searches);
RegistrationUninitialize(&pEngineState->registration);
PayloadsUninitialize(&pEngineState->payloads);
PackagesUninitialize(&pEngineState->packages);
CatalogUninitialize(&pEngineState->catalogs);
SectionUninitialize(&pEngineState->section);
ContainersUninitialize(&pEngineState->containers);
ReleaseStr(pEngineState->command.wzBootstrapperApplicationDataPath);
ReleaseStr(pEngineState->command.wzBootstrapperWorkingFolder);
ReleaseStr(pEngineState->command.wzLayoutDirectory);
ReleaseStr(pEngineState->command.wzCommandLine);
ReleaseStr(pEngineState->log.sczExtension);
ReleaseStr(pEngineState->log.sczPrefix);
ReleaseStr(pEngineState->log.sczPath);
ReleaseStr(pEngineState->log.sczPathVariable);
if (TLS_OUT_OF_INDEXES != pEngineState->dwElevatedLoggingTlsId)
{
::TlsFree(pEngineState->dwElevatedLoggingTlsId);
}
::DeleteCriticalSection(&pEngineState->csActive);
// clear struct
memset(pEngineState, 0, sizeof(BURN_ENGINE_STATE));
}
static HRESULT RunUntrusted(
__in LPCWSTR wzCommandLine,
__in BURN_ENGINE_STATE* pEngineState
)
{
HRESULT hr = S_OK;
LPWSTR sczCurrentProcessPath = NULL;
LPWSTR wzCleanRoomBundlePath = NULL;
LPWSTR sczCachedCleanRoomBundlePath = NULL;
LPWSTR sczParameters = NULL;
LPWSTR sczFullCommandLine = NULL;
STARTUPINFOW si = { };
PROCESS_INFORMATION pi = { };
HANDLE hFileAttached = NULL;
HANDLE hFileSelf = NULL;
HANDLE hProcess = NULL;
hr = PathForCurrentProcess(&sczCurrentProcessPath, NULL);
ExitOnFailure(hr, "Failed to get path for current process.");
BOOL fRunningFromCache = CacheBundleRunningFromCache();
// If we're running from the package cache, we're in a secure
// folder (DLLs cannot be inserted here for hijacking purposes)
// so just launch the current process's path as the clean room
// process. Technically speaking, we'd be able to skip creating
// a clean room process at all (since we're already running from
// a secure folder) but it makes the code that only wants to run
// in clean room more complicated if we don't launch an explicit
// clean room process.
if (fRunningFromCache)
{
wzCleanRoomBundlePath = sczCurrentProcessPath;
}
else
{
hr = CacheBundleToCleanRoom(&pEngineState->userExperience.payloads, &pEngineState->section, &sczCachedCleanRoomBundlePath);
ExitOnFailure(hr, "Failed to cache to clean room.");
wzCleanRoomBundlePath = sczCachedCleanRoomBundlePath;
}
// The clean room switch must always be at the front of the command line so
// the EngineInCleanRoom function will operate correctly.
hr = StrAllocFormatted(&sczParameters, L"-%ls=\"%ls\"", BURN_COMMANDLINE_SWITCH_CLEAN_ROOM, sczCurrentProcessPath);
ExitOnFailure(hr, "Failed to allocate parameters for unelevated process.");
// Send a file handle for the child Burn process to access the attached container.
hr = CoreAppendFileHandleAttachedToCommandLine(pEngineState->section.hEngineFile, &hFileAttached, &sczParameters);
ExitOnFailure(hr, "Failed to append %ls", BURN_COMMANDLINE_SWITCH_FILEHANDLE_ATTACHED);
// Grab a file handle for the child Burn process.
hr = CoreAppendFileHandleSelfToCommandLine(wzCleanRoomBundlePath, &hFileSelf, &sczParameters, NULL);
ExitOnFailure(hr, "Failed to append %ls", BURN_COMMANDLINE_SWITCH_FILEHANDLE_SELF);
hr = StrAllocFormattedSecure(&sczParameters, L"%ls %ls", sczParameters, wzCommandLine);
ExitOnFailure(hr, "Failed to append original command line.");
#ifdef ENABLE_UNELEVATE
// TODO: Pass file handle to unelevated process if this ever gets reenabled.
if (!pEngineState->fDisableUnelevate)
{
// Try to launch unelevated and if that fails for any reason, we'll launch our process normally (even though that may make it elevated).
hr = ProcExecuteAsInteractiveUser(wzCleanRoomBundlePath, sczParameters, &hProcess);
}
#endif
if (!hProcess)
{
hr = StrAllocFormattedSecure(&sczFullCommandLine, L"\"%ls\" %ls", wzCleanRoomBundlePath, sczParameters);
ExitOnFailure(hr, "Failed to allocate full command-line.");
si.cb = sizeof(si);
si.wShowWindow = static_cast<WORD>(pEngineState->command.nCmdShow);
if (!::CreateProcessW(wzCleanRoomBundlePath, sczFullCommandLine, NULL, NULL, TRUE, 0, 0, NULL, &si, &pi))
{
ExitWithLastError(hr, "Failed to launch clean room process: %ls", sczFullCommandLine);
}
hProcess = pi.hProcess;
pi.hProcess = NULL;
}
hr = ProcWaitForCompletion(hProcess, INFINITE, &pEngineState->userExperience.dwExitCode);
ExitOnFailure(hr, "Failed to wait for clean room process: %ls", wzCleanRoomBundlePath);
LExit:
ReleaseHandle(pi.hThread);
ReleaseFileHandle(hFileSelf);
ReleaseFileHandle(hFileAttached);
ReleaseHandle(hProcess);
StrSecureZeroFreeString(sczFullCommandLine);
StrSecureZeroFreeString(sczParameters);
ReleaseStr(sczCachedCleanRoomBundlePath);
ReleaseStr(sczCurrentProcessPath);
return hr;
}
static HRESULT RunNormal(
__in HINSTANCE hInstance,
__in BURN_ENGINE_STATE* pEngineState
)
{
HRESULT hr = S_OK;
HANDLE hPipesCreatedEvent = NULL;
BOOL fContinueExecution = TRUE;
BOOL fReloadApp = FALSE;
BURN_EXTENSION_ENGINE_CONTEXT extensionEngineContext = { };
// Initialize logging.
hr = LoggingOpen(&pEngineState->log, &pEngineState->variables, pEngineState->command.display, pEngineState->registration.sczDisplayName);
ExitOnFailure(hr, "Failed to open log.");
// Ensure we're on a supported operating system.
hr = ConditionGlobalCheck(&pEngineState->variables, &pEngineState->condition, pEngineState->command.display, pEngineState->registration.sczDisplayName, &pEngineState->userExperience.dwExitCode, &fContinueExecution);
ExitOnFailure(hr, "Failed to check global conditions");
if (!fContinueExecution)
{
LogId(REPORT_STANDARD, MSG_FAILED_CONDITION_CHECK);
// If the block told us to abort, abort!
ExitFunction1(hr = S_OK);
}
if (pEngineState->userExperience.fSplashScreen && BOOTSTRAPPER_DISPLAY_NONE < pEngineState->command.display)
{
SplashScreenCreate(hInstance, NULL, &pEngineState->command.hwndSplashScreen);
}
// Create a top-level window to handle system messages.
hr = UiCreateMessageWindow(hInstance, pEngineState);
ExitOnFailure(hr, "Failed to create the message window.");
// Query registration state.
hr = CoreQueryRegistration(pEngineState);
ExitOnFailure(hr, "Failed to query registration.");
// Set some built-in variables before loading the BA.
hr = PlanSetVariables(pEngineState->command.action, &pEngineState->variables);
ExitOnFailure(hr, "Failed to set action variables.");
hr = RegistrationSetVariables(&pEngineState->registration, &pEngineState->variables);
ExitOnFailure(hr, "Failed to set registration variables.");
// If a layout directory was specified on the command-line, set it as a well-known variable.
if (pEngineState->command.wzLayoutDirectory && *pEngineState->command.wzLayoutDirectory)
{
hr = VariableSetString(&pEngineState->variables, BURN_BUNDLE_LAYOUT_DIRECTORY, pEngineState->command.wzLayoutDirectory, FALSE);
ExitOnFailure(hr, "Failed to set layout directory variable to value provided from command-line.");
}
// Setup the extension engine.
extensionEngineContext.pEngineState = pEngineState;
// Load the extensions.
hr = BurnExtensionLoad(&pEngineState->extensions, &extensionEngineContext);
ExitOnFailure(hr, "Failed to load BundleExtensions.");
do
{
fReloadApp = FALSE;
hr = RunApplication(pEngineState, &fReloadApp);
ExitOnFailure(hr, "Failed while running ");
} while (fReloadApp);
LExit:
BurnExtensionUnload(&pEngineState->extensions);
// If the message window is still around, close it.
UiCloseMessageWindow(pEngineState);
VariablesDump(&pEngineState->variables);
// end per-machine process if running
if (INVALID_HANDLE_VALUE != pEngineState->companionConnection.hPipe)
{
PipeTerminateChildProcess(&pEngineState->companionConnection, pEngineState->userExperience.dwExitCode, FALSE);
}
// If the splash screen is still around, close it.
if (::IsWindow(pEngineState->command.hwndSplashScreen))
{
::PostMessageW(pEngineState->command.hwndSplashScreen, WM_CLOSE, 0, 0);
}
ReleaseHandle(hPipesCreatedEvent);
return hr;
}
static HRESULT RunElevated(
__in HINSTANCE hInstance,
__in LPCWSTR /*wzCommandLine*/,
__in BURN_ENGINE_STATE* pEngineState
)
{
HRESULT hr = S_OK;
HANDLE hLock = NULL;
BOOL fDisabledAutomaticUpdates = FALSE;
// connect to per-user process
hr = PipeChildConnect(&pEngineState->companionConnection, TRUE);
ExitOnFailure(hr, "Failed to connect to unelevated process.");
// Set up the thread local storage to store the correct pipe to communicate logging then
// override logging to write over the pipe.
pEngineState->dwElevatedLoggingTlsId = ::TlsAlloc();
if (TLS_OUT_OF_INDEXES == pEngineState->dwElevatedLoggingTlsId)
{
ExitWithLastError(hr, "Failed to allocate thread local storage for logging.");
}
if (!::TlsSetValue(pEngineState->dwElevatedLoggingTlsId, pEngineState->companionConnection.hPipe))
{
ExitWithLastError(hr, "Failed to set elevated pipe into thread local storage for logging.");
}
LogRedirect(RedirectLoggingOverPipe, pEngineState);
// Create a top-level window to prevent shutting down the elevated process.
hr = UiCreateMessageWindow(hInstance, pEngineState);
ExitOnFailure(hr, "Failed to create the message window.");
SrpInitialize(TRUE);
// Pump messages from parent process.
hr = ElevationChildPumpMessages(pEngineState->dwElevatedLoggingTlsId, pEngineState->companionConnection.hPipe, pEngineState->companionConnection.hCachePipe, &pEngineState->approvedExes, &pEngineState->containers, &pEngineState->packages, &pEngineState->payloads, &pEngineState->variables, &pEngineState->registration, &pEngineState->userExperience, &hLock, &fDisabledAutomaticUpdates, &pEngineState->userExperience.dwExitCode, &pEngineState->fRestart);
LogRedirect(NULL, NULL); // reset logging so the next failure gets written to "log buffer" for the failure log.
ExitOnFailure(hr, "Failed to pump messages from parent process.");
LExit:
LogRedirect(NULL, NULL); // we're done talking to the child so always reset logging now.
// If the message window is still around, close it.
UiCloseMessageWindow(pEngineState);
if (fDisabledAutomaticUpdates)
{
ElevationChildResumeAutomaticUpdates();
}
if (hLock)
{
::ReleaseMutex(hLock);
::CloseHandle(hLock);
}
return hr;
}
static HRESULT RunEmbedded(
__in HINSTANCE hInstance,
__in BURN_ENGINE_STATE* pEngineState
)
{
HRESULT hr = S_OK;
// Disable system restore since the parent bundle may have done it.
pEngineState->fDisableSystemRestore = TRUE;
// Connect to parent process.
hr = PipeChildConnect(&pEngineState->embeddedConnection, FALSE);
ExitOnFailure(hr, "Failed to connect to parent of embedded process.");
// Do not register the bundle to automatically restart if embedded.
if (BOOTSTRAPPER_DISPLAY_EMBEDDED == pEngineState->command.display)
{
pEngineState->registration.fDisableResume = TRUE;
}
// Now run the application like normal.
hr = RunNormal(hInstance, pEngineState);
ExitOnFailure(hr, "Failed to run bootstrapper application embedded.");
LExit:
return hr;
}
static HRESULT RunRunOnce(
__in const BURN_REGISTRATION* pRegistration,
__in int nCmdShow
)
{
HRESULT hr = S_OK;
LPWSTR sczNewCommandLine = NULL;
LPWSTR sczBurnPath = NULL;
HANDLE hProcess = NULL;
hr = RegistrationGetResumeCommandLine(pRegistration, &sczNewCommandLine);
ExitOnFailure(hr, "Unable to get resume command line from the registry");
// and re-launch
hr = PathForCurrentProcess(&sczBurnPath, NULL);
ExitOnFailure(hr, "Failed to get current process path.");
hr = ProcExec(sczBurnPath, 0 < sczNewCommandLine ? sczNewCommandLine : L"", nCmdShow, &hProcess);
ExitOnFailure(hr, "Failed to re-launch bundle process after RunOnce: %ls", sczBurnPath);
LExit:
ReleaseHandle(hProcess);
ReleaseStr(sczNewCommandLine);
ReleaseStr(sczBurnPath);
return hr;
}
static HRESULT RunApplication(
__in BURN_ENGINE_STATE* pEngineState,
__out BOOL* pfReloadApp
)
{
HRESULT hr = S_OK;
BOOTSTRAPPER_ENGINE_CONTEXT engineContext = { };
BOOL fStartupCalled = FALSE;
BOOL fRet = FALSE;
MSG msg = { };
BOOTSTRAPPER_SHUTDOWN_ACTION shutdownAction = BOOTSTRAPPER_SHUTDOWN_ACTION_NONE;
::PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
// Setup the bootstrapper engine.
engineContext.dwThreadId = ::GetCurrentThreadId();
engineContext.pEngineState = pEngineState;
// Load the bootstrapper application.
hr = UserExperienceLoad(&pEngineState->userExperience, &engineContext, &pEngineState->command);
ExitOnFailure(hr, "Failed to load BA.");
fStartupCalled = TRUE;
hr = UserExperienceOnStartup(&pEngineState->userExperience);
ExitOnFailure(hr, "Failed to start bootstrapper application.");
// Enter the message pump.
while (0 != (fRet = ::GetMessageW(&msg, NULL, 0, 0)))
{
if (-1 == fRet)
{
hr = E_UNEXPECTED;
ExitOnRootFailure(hr, "Unexpected return value from message pump.");
}
else
{
ProcessMessage(pEngineState, &msg);
}
}
// Get exit code.
pEngineState->userExperience.dwExitCode = (DWORD)msg.wParam;
LExit:
if (fStartupCalled)
{
UserExperienceOnShutdown(&pEngineState->userExperience, &shutdownAction);
if (BOOTSTRAPPER_SHUTDOWN_ACTION_RESTART == shutdownAction)
{
LogId(REPORT_STANDARD, MSG_BA_REQUESTED_RESTART, LoggingBoolToString(pEngineState->fRestart));
pEngineState->fRestart = TRUE;
}
else if (BOOTSTRAPPER_SHUTDOWN_ACTION_RELOAD_BOOTSTRAPPER == shutdownAction)
{
LogId(REPORT_STANDARD, MSG_BA_REQUESTED_RELOAD);
*pfReloadApp = TRUE;
}
}
// Unload BA.
UserExperienceUnload(&pEngineState->userExperience);
return hr;
}
static HRESULT ProcessMessage(
__in BURN_ENGINE_STATE* pEngineState,
__in const MSG* pmsg
)
{
HRESULT hr = S_OK;
switch (pmsg->message)
{
case WM_BURN_DETECT:
hr = CoreDetect(pEngineState, reinterpret_cast<HWND>(pmsg->lParam));
break;
case WM_BURN_PLAN:
hr = CorePlan(pEngineState, static_cast<BOOTSTRAPPER_ACTION>(pmsg->lParam));
break;
case WM_BURN_ELEVATE:
hr = CoreElevate(pEngineState, reinterpret_cast<HWND>(pmsg->lParam));
break;
case WM_BURN_APPLY:
hr = CoreApply(pEngineState, reinterpret_cast<HWND>(pmsg->lParam));
break;
case WM_BURN_LAUNCH_APPROVED_EXE:
hr = CoreLaunchApprovedExe(pEngineState, reinterpret_cast<BURN_LAUNCH_APPROVED_EXE*>(pmsg->lParam));
break;
case WM_BURN_QUIT:
hr = CoreQuit(pEngineState, static_cast<int>(pmsg->wParam));
break;
}
return hr;
}
static HRESULT DAPI RedirectLoggingOverPipe(
__in_z LPCSTR szString,
__in_opt LPVOID pvContext
)
{
static BOOL s_fCurrentlyLoggingToPipe = FALSE;
HRESULT hr = S_OK;
BURN_ENGINE_STATE* pEngineState = static_cast<BURN_ENGINE_STATE*>(pvContext);
BOOL fStartedLogging = FALSE;
HANDLE hPipe = INVALID_HANDLE_VALUE;
BYTE* pbData = NULL;
SIZE_T cbData = 0;
DWORD dwResult = 0;
// Prevent this function from being called recursively.
if (s_fCurrentlyLoggingToPipe)
{
ExitFunction();
}
s_fCurrentlyLoggingToPipe = TRUE;
fStartedLogging = TRUE;
// Make sure the current thread set the pipe in TLS.
hPipe = ::TlsGetValue(pEngineState->dwElevatedLoggingTlsId);
if (!hPipe || INVALID_HANDLE_VALUE == hPipe)
{
hr = HRESULT_FROM_WIN32(ERROR_PIPE_NOT_CONNECTED);
ExitFunction();
}
// Do not log or use ExitOnFailure() macro here because they will be discarded
// by the recursive block at the top of this function.
hr = BuffWriteStringAnsi(&pbData, &cbData, szString);
if (SUCCEEDED(hr))
{
hr = PipeSendMessage(hPipe, static_cast<DWORD>(BURN_PIPE_MESSAGE_TYPE_LOG), pbData, cbData, NULL, NULL, &dwResult);
if (SUCCEEDED(hr))
{
hr = (HRESULT)dwResult;
}
}
LExit:
ReleaseBuffer(pbData);
// We started logging so remember to say we are no longer logging.
if (fStartedLogging)
{
s_fCurrentlyLoggingToPipe = FALSE;
}
return hr;
}
static HRESULT Restart()
{
HRESULT hr = S_OK;
HANDLE hProcessToken = NULL;
TOKEN_PRIVILEGES priv = { };
DWORD dwRetries = 0;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hProcessToken))
{
ExitWithLastError(hr, "Failed to get process token.");
}
priv.PrivilegeCount = 1;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!::LookupPrivilegeValueW(NULL, L"SeShutdownPrivilege", &priv.Privileges[0].Luid))
{
ExitWithLastError(hr, "Failed to get shutdown privilege LUID.");
}
if (!::AdjustTokenPrivileges(hProcessToken, FALSE, &priv, sizeof(TOKEN_PRIVILEGES), NULL, 0))
{
ExitWithLastError(hr, "Failed to adjust token to add shutdown privileges.");
}
do
{
hr = S_OK;
// Wait a second to let the companion process (assuming we did an elevated install) to get to the
// point where it too is thinking about restarting the computer. Only one will schedule the restart
// but both will have their log files closed and otherwise be ready to exit.
//
// On retry, we'll also wait a second to let the OS try to get to a place where the restart can
// be initiated.
::Sleep(1000);
if (!vpfnInitiateSystemShutdownExW(NULL, NULL, 0, FALSE, TRUE, SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION | SHTDN_REASON_FLAG_PLANNED))
{
hr = HRESULT_FROM_WIN32(::GetLastError());
}
} while (dwRetries++ < RESTART_RETRIES && (HRESULT_FROM_WIN32(ERROR_MACHINE_LOCKED) == hr || HRESULT_FROM_WIN32(ERROR_NOT_READY) == hr));
ExitOnRootFailure(hr, "Failed to schedule restart.");
LExit:
ReleaseHandle(hProcessToken);
return hr;
}
|