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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
|
// 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"
static const LPCWSTR BUNDLE_CLEAN_ROOM_WORKING_FOLDER_NAME = L".cr";
static const LPCWSTR BUNDLE_WORKING_FOLDER_NAME = L".be";
static const LPCWSTR UNVERIFIED_CACHE_FOLDER_NAME = L".unverified";
static const LPCWSTR PACKAGE_CACHE_FOLDER_NAME = L"Package Cache";
static const DWORD FILE_OPERATION_RETRY_COUNT = 3;
static const DWORD FILE_OPERATION_RETRY_WAIT = 2000;
static BOOL vfInitializedCache = FALSE;
static BOOL vfRunningFromCache = FALSE;
static LPWSTR vsczSourceProcessPath = NULL;
static LPWSTR vsczWorkingFolder = NULL;
static LPWSTR vsczDefaultUserPackageCache = NULL;
static LPWSTR vsczDefaultMachinePackageCache = NULL;
static LPWSTR vsczCurrentMachinePackageCache = NULL;
static HRESULT CalculateWorkingFolder(
__in_z LPCWSTR wzBundleId,
__deref_out_z LPWSTR* psczWorkingFolder
);
static HRESULT GetLastUsedSourceFolder(
__in BURN_VARIABLES* pVariables,
__out_z LPWSTR* psczLastSource
);
static HRESULT CreateCompletedPath(
__in BOOL fPerMachine,
__in LPCWSTR wzCacheId,
__out LPWSTR* psczCacheDirectory
);
static HRESULT CreateUnverifiedPath(
__in BOOL fPerMachine,
__in_z LPCWSTR wzPayloadId,
__out_z LPWSTR* psczUnverifiedPayloadPath
);
static HRESULT GetRootPath(
__in BOOL fPerMachine,
__in BOOL fAllowRedirect,
__deref_out_z LPWSTR* psczRootPath
);
static HRESULT VerifyThenTransferContainer(
__in BURN_CONTAINER* pContainer,
__in_z LPCWSTR wzCachedPath,
__in_z LPCWSTR wzUnverifiedContainerPath,
__in BOOL fMove
);
static HRESULT VerifyThenTransferPayload(
__in BURN_PAYLOAD* pPayload,
__in_z LPCWSTR wzCachedPath,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in BOOL fMove
);
static HRESULT TransferWorkingPathToUnverifiedPath(
__in_z LPCWSTR wzWorkingPath,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in BOOL fMove
);
static HRESULT VerifyFileAgainstPayload(
__in BURN_PAYLOAD* pPayload,
__in_z LPCWSTR wzVerifyPath
);
static HRESULT ResetPathPermissions(
__in BOOL fPerMachine,
__in_z LPCWSTR wzPath
);
static HRESULT SecurePath(
__in LPCWSTR wzPath
);
static HRESULT CopyEngineToWorkingFolder(
__in_z LPCWSTR wzSourcePath,
__in_z LPCWSTR wzWorkingFolderName,
__in_z LPCWSTR wzExecutableName,
__in BURN_PAYLOADS* pUxPayloads,
__in BURN_SECTION* pSection,
__deref_out_z_opt LPWSTR* psczEngineWorkingPath
);
static HRESULT CopyEngineWithSignatureFixup(
__in HANDLE hEngineFile,
__in_z LPCWSTR wzEnginePath,
__in_z LPCWSTR wzTargetPath,
__in BURN_SECTION* pSection
);
static HRESULT RemoveBundleOrPackage(
__in BOOL fBundle,
__in BOOL fPerMachine,
__in_z LPCWSTR wzBundleOrPackageId,
__in_z LPCWSTR wzCacheId
);
static HRESULT VerifyHash(
__in BYTE* pbHash,
__in DWORD cbHash,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in HANDLE hFile
);
extern "C" HRESULT CacheInitialize(
__in BURN_REGISTRATION* pRegistration,
__in BURN_VARIABLES* pVariables,
__in_z_opt LPCWSTR wzSourceProcessPath
)
{
HRESULT hr = S_OK;
LPWSTR sczCurrentPath = NULL;
LPWSTR sczCompletedFolder = NULL;
LPWSTR sczCompletedPath = NULL;
LPWSTR sczOriginalSource = NULL;
LPWSTR sczOriginalSourceFolder = NULL;
int nCompare = 0;
if (!vfInitializedCache)
{
hr = PathForCurrentProcess(&sczCurrentPath, NULL);
ExitOnFailure(hr, "Failed to get current process path.");
// Determine if we are running from the package cache or not.
hr = CacheGetCompletedPath(pRegistration->fPerMachine, pRegistration->sczId, &sczCompletedFolder);
ExitOnFailure(hr, "Failed to get completed path for bundle.");
hr = PathConcat(sczCompletedFolder, pRegistration->sczExecutableName, &sczCompletedPath);
ExitOnFailure(hr, "Failed to combine working path with engine file name.");
hr = PathCompare(sczCurrentPath, sczCompletedPath, &nCompare);
ExitOnFailure(hr, "Failed to compare current path for bundle: %ls", sczCurrentPath);
vfRunningFromCache = (CSTR_EQUAL == nCompare);
// If a source process path was not provided (e.g. we are not being
// run in a clean room) then use the current process path as the
// source process path.
if (!wzSourceProcessPath)
{
wzSourceProcessPath = sczCurrentPath;
}
hr = StrAllocString(&vsczSourceProcessPath, wzSourceProcessPath, 0);
ExitOnFailure(hr, "Failed to initialize cache source path.");
// If we're not running from the cache, ensure the original source is set.
if (!vfRunningFromCache)
{
// If the original source has not been set already then set it where the bundle is
// running from right now. This value will be persisted and we'll use it when launched
// from the clean room or package cache since none of our packages will be relative to
// those locations.
hr = VariableGetString(pVariables, BURN_BUNDLE_ORIGINAL_SOURCE, &sczOriginalSource);
if (E_NOTFOUND == hr)
{
hr = VariableSetString(pVariables, BURN_BUNDLE_ORIGINAL_SOURCE, wzSourceProcessPath, FALSE, FALSE);
ExitOnFailure(hr, "Failed to set original source variable.");
hr = StrAllocString(&sczOriginalSource, wzSourceProcessPath, 0);
ExitOnFailure(hr, "Failed to copy current path to original source.");
}
hr = VariableGetString(pVariables, BURN_BUNDLE_ORIGINAL_SOURCE_FOLDER, &sczOriginalSourceFolder);
if (E_NOTFOUND == hr)
{
hr = PathGetDirectory(sczOriginalSource, &sczOriginalSourceFolder);
ExitOnFailure(hr, "Failed to get directory from original source path.");
hr = VariableSetString(pVariables, BURN_BUNDLE_ORIGINAL_SOURCE_FOLDER, sczOriginalSourceFolder, FALSE, FALSE);
ExitOnFailure(hr, "Failed to set original source directory variable.");
}
}
vfInitializedCache = TRUE;
}
LExit:
ReleaseStr(sczCurrentPath);
ReleaseStr(sczCompletedFolder);
ReleaseStr(sczCompletedPath);
ReleaseStr(sczOriginalSource);
ReleaseStr(sczOriginalSourceFolder);
return hr;
}
extern "C" HRESULT CacheEnsureWorkingFolder(
__in_z_opt LPCWSTR wzBundleId,
__deref_out_z_opt LPWSTR* psczWorkingFolder
)
{
HRESULT hr = S_OK;
LPWSTR sczWorkingFolder = NULL;
hr = CalculateWorkingFolder(wzBundleId, &sczWorkingFolder);
ExitOnFailure(hr, "Failed to calculate working folder to ensure it exists.");
hr = DirEnsureExists(sczWorkingFolder, NULL);
ExitOnFailure(hr, "Failed create working folder.");
// Best effort to ensure our working folder is not encrypted.
::DecryptFileW(sczWorkingFolder, 0);
if (psczWorkingFolder)
{
hr = StrAllocString(psczWorkingFolder, sczWorkingFolder, 0);
ExitOnFailure(hr, "Failed to copy working folder.");
}
LExit:
ReleaseStr(sczWorkingFolder);
return hr;
}
extern "C" HRESULT CacheCalculateBundleWorkingPath(
__in_z LPCWSTR wzBundleId,
__in LPCWSTR wzExecutableName,
__deref_out_z LPWSTR* psczWorkingPath
)
{
Assert(vfInitializedCache);
HRESULT hr = S_OK;
LPWSTR sczWorkingFolder = NULL;
// If the bundle is running out of the package cache then we use that as the
// working folder since we feel safe in the package cache.
if (vfRunningFromCache)
{
hr = PathForCurrentProcess(psczWorkingPath, NULL);
ExitOnFailure(hr, "Failed to get current process path.");
}
else // Otherwise, use the real working folder.
{
hr = CalculateWorkingFolder(wzBundleId, &sczWorkingFolder);
ExitOnFailure(hr, "Failed to get working folder for bundle.");
hr = StrAllocFormatted(psczWorkingPath, L"%ls%ls\\%ls", sczWorkingFolder, BUNDLE_WORKING_FOLDER_NAME, wzExecutableName);
ExitOnFailure(hr, "Failed to calculate the bundle working path.");
}
LExit:
ReleaseStr(sczWorkingFolder);
return hr;
}
extern "C" HRESULT CacheCalculateBundleLayoutWorkingPath(
__in_z LPCWSTR wzBundleId,
__deref_out_z LPWSTR* psczWorkingPath
)
{
HRESULT hr = S_OK;
LPWSTR sczWorkingFolder = NULL;
hr = CalculateWorkingFolder(wzBundleId, psczWorkingPath);
ExitOnFailure(hr, "Failed to get working folder for bundle layout.");
hr = StrAllocConcat(psczWorkingPath, wzBundleId, 0);
ExitOnFailure(hr, "Failed to append bundle id for bundle layout working path.");
LExit:
ReleaseStr(sczWorkingFolder);
return hr;
}
extern "C" HRESULT CacheCalculatePayloadWorkingPath(
__in_z LPCWSTR wzBundleId,
__in BURN_PAYLOAD* pPayload,
__deref_out_z LPWSTR* psczWorkingPath
)
{
HRESULT hr = S_OK;
hr = CalculateWorkingFolder(wzBundleId, psczWorkingPath);
ExitOnFailure(hr, "Failed to get working folder for payload.");
hr = StrAllocConcat(psczWorkingPath, pPayload->sczKey, 0);
ExitOnFailure(hr, "Failed to append SHA1 hash as payload unverified path.");
LExit:
return hr;
}
extern "C" HRESULT CacheCalculateContainerWorkingPath(
__in_z LPCWSTR wzBundleId,
__in BURN_CONTAINER* pContainer,
__deref_out_z LPWSTR* psczWorkingPath
)
{
HRESULT hr = S_OK;
hr = CalculateWorkingFolder(wzBundleId, psczWorkingPath);
ExitOnFailure(hr, "Failed to get working folder for container.");
hr = StrAllocConcat(psczWorkingPath, pContainer->sczHash, 0);
ExitOnFailure(hr, "Failed to append SHA1 hash as container unverified path.");
LExit:
return hr;
}
extern "C" HRESULT CacheGetRootCompletedPath(
__in BOOL fPerMachine,
__in BOOL fForceInitialize,
__deref_out_z LPWSTR* psczRootCompletedPath
)
{
HRESULT hr = S_OK;
if (fForceInitialize)
{
hr = CreateCompletedPath(fPerMachine, L"", psczRootCompletedPath);
}
else
{
hr = GetRootPath(fPerMachine, TRUE, psczRootCompletedPath);
}
return hr;
}
extern "C" HRESULT CacheGetCompletedPath(
__in BOOL fPerMachine,
__in_z LPCWSTR wzCacheId,
__deref_out_z LPWSTR* psczCompletedPath
)
{
HRESULT hr = S_OK;
BOOL fRedirected = FALSE;
LPWSTR sczRootPath = NULL;
LPWSTR sczCurrentCompletedPath = NULL;
LPWSTR sczDefaultCompletedPath = NULL;
hr = GetRootPath(fPerMachine, TRUE, &sczRootPath);
ExitOnFailure(hr, "Failed to get %hs package cache root directory.", fPerMachine ? "per-machine" : "per-user");
// GetRootPath returns S_FALSE if the package cache is redirected elsewhere.
fRedirected = S_FALSE == hr;
hr = PathConcat(sczRootPath, wzCacheId, &sczCurrentCompletedPath);
ExitOnFailure(hr, "Failed to construct cache path.");
hr = PathBackslashTerminate(&sczCurrentCompletedPath);
ExitOnFailure(hr, "Failed to ensure cache path was backslash terminated.");
// Return the old package cache directory if the new directory does not exist but the old directory does.
// If neither package cache directory exists return the (possibly) redirected package cache directory.
if (fRedirected && !DirExists(sczCurrentCompletedPath, NULL))
{
hr = GetRootPath(fPerMachine, FALSE, &sczRootPath);
ExitOnFailure(hr, "Failed to get old %hs package cache root directory.", fPerMachine ? "per-machine" : "per-user");
hr = PathConcat(sczRootPath, wzCacheId, &sczDefaultCompletedPath);
ExitOnFailure(hr, "Failed to construct cache path.");
hr = PathBackslashTerminate(&sczDefaultCompletedPath);
ExitOnFailure(hr, "Failed to ensure cache path was backslash terminated.");
if (DirExists(sczDefaultCompletedPath, NULL))
{
*psczCompletedPath = sczDefaultCompletedPath;
sczDefaultCompletedPath = NULL;
ExitFunction();
}
}
*psczCompletedPath = sczCurrentCompletedPath;
sczCurrentCompletedPath = NULL;
LExit:
ReleaseNullStr(sczDefaultCompletedPath);
ReleaseNullStr(sczCurrentCompletedPath);
ReleaseNullStr(sczRootPath);
return hr;
}
extern "C" HRESULT CacheGetResumePath(
__in_z LPCWSTR wzPayloadWorkingPath,
__deref_out_z LPWSTR* psczResumePath
)
{
HRESULT hr = S_OK;
hr = StrAllocFormatted(psczResumePath, L"%ls.R", wzPayloadWorkingPath);
ExitOnFailure(hr, "Failed to create resume path.");
LExit:
return hr;
}
extern "C" HRESULT CacheFindLocalSource(
__in_z LPCWSTR wzSourcePath,
__in BURN_VARIABLES* pVariables,
__out BOOL* pfFound,
__out_z LPWSTR* psczSourceFullPath
)
{
HRESULT hr = S_OK;
LPWSTR sczSourceProcessFolder = NULL;
LPWSTR sczCurrentPath = NULL;
LPWSTR sczLastSourcePath = NULL;
LPWSTR sczLastSourceFolder = NULL;
LPWSTR sczLayoutPath = NULL;
LPWSTR sczLayoutFolder = NULL;
LPCWSTR rgwzSearchPaths[3] = { };
DWORD cSearchPaths = 0;
// If the source path provided is a full path, obviously that is where we should be looking.
if (PathIsAbsolute(wzSourcePath))
{
rgwzSearchPaths[0] = wzSourcePath;
cSearchPaths = 1;
}
else
{
// If we're not running from cache or we couldn't get the last source, use
// the source path location first. In the case where we are in the bundle's
// package cache and couldn't find a last used source we unfortunately will
// be picking the package cache path which isn't likely to have what we are
// looking for.
hr = GetLastUsedSourceFolder(pVariables, &sczLastSourceFolder);
if (!vfRunningFromCache || FAILED(hr))
{
hr = PathGetDirectory(vsczSourceProcessPath, &sczSourceProcessFolder);
ExitOnFailure(hr, "Failed to get current process directory.");
hr = PathConcat(sczSourceProcessFolder, wzSourcePath, &sczCurrentPath);
ExitOnFailure(hr, "Failed to combine last source with source.");
rgwzSearchPaths[0] = sczCurrentPath;
cSearchPaths = 1;
}
// If we have a last used source and it does not duplicate the existing search path,
// add the last used source to the search path second.
if (sczLastSourceFolder && *sczLastSourceFolder)
{
hr = PathConcat(sczLastSourceFolder, wzSourcePath, &sczLastSourcePath);
ExitOnFailure(hr, "Failed to combine last source with source.");
if (0 == cSearchPaths || CSTR_EQUAL != ::CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, rgwzSearchPaths[0], -1, sczLastSourcePath, -1))
{
rgwzSearchPaths[cSearchPaths] = sczLastSourcePath;
++cSearchPaths;
}
}
// Also consider the layout directory if set on the command line or by the BA.
hr = VariableGetString(pVariables, BURN_BUNDLE_LAYOUT_DIRECTORY, &sczLayoutFolder);
if (E_NOTFOUND != hr)
{
ExitOnFailure(hr, "Failed to get bundle layout directory property.");
hr = PathConcat(sczLayoutFolder, wzSourcePath, &sczLayoutPath);
ExitOnFailure(hr, "Failed to combine layout source with source.");
rgwzSearchPaths[cSearchPaths] = sczLayoutPath;
++cSearchPaths;
}
}
*pfFound = FALSE; // assume we won't find the file locally.
for (DWORD i = 0; i < cSearchPaths; ++i)
{
// If the file exists locally, copy its path.
if (FileExistsEx(rgwzSearchPaths[i], NULL))
{
hr = StrAllocString(psczSourceFullPath, rgwzSearchPaths[i], 0);
ExitOnFailure(hr, "Failed to copy source path.");
*pfFound = TRUE;
break;
}
}
// If nothing was found, return the first thing in our search path as the
// best path where we thought we should have found the file.
if (!*pfFound)
{
hr = StrAllocString(psczSourceFullPath, rgwzSearchPaths[0], 0);
ExitOnFailure(hr, "Failed to copy source path.");
}
LExit:
ReleaseStr(sczCurrentPath);
ReleaseStr(sczSourceProcessFolder);
ReleaseStr(sczLastSourceFolder);
ReleaseStr(sczLastSourcePath);
ReleaseStr(sczLayoutFolder);
ReleaseStr(sczLayoutPath);
return hr;
}
extern "C" HRESULT CacheSetLastUsedSource(
__in BURN_VARIABLES* pVariables,
__in_z LPCWSTR wzSourcePath,
__in_z LPCWSTR wzRelativePath
)
{
HRESULT hr = S_OK;
size_t cchSourcePath = 0;
size_t cchRelativePath = 0;
size_t iSourceRelativePath = 0;
LPWSTR sczSourceFolder = NULL;
LPWSTR sczLastSourceFolder = NULL;
int nCompare = 0;
hr = ::StringCchLengthW(wzSourcePath, STRSAFE_MAX_CCH, &cchSourcePath);
ExitOnFailure(hr, "Failed to determine length of source path.");
hr = ::StringCchLengthW(wzRelativePath, STRSAFE_MAX_CCH, &cchRelativePath);
ExitOnFailure(hr, "Failed to determine length of relative path.");
// If the source path is smaller than the relative path (plus space for "X:\") then we know they
// are not relative to each other.
if (cchSourcePath < cchRelativePath + 3)
{
ExitFunction();
}
// If the source path ends with the relative path then this source could be a new path.
iSourceRelativePath = cchSourcePath - cchRelativePath;
if (CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, wzSourcePath + iSourceRelativePath, -1, wzRelativePath, -1))
{
hr = StrAllocString(&sczSourceFolder, wzSourcePath, iSourceRelativePath);
ExitOnFailure(hr, "Failed to trim source folder.");
hr = VariableGetString(pVariables, BURN_BUNDLE_LAST_USED_SOURCE, &sczLastSourceFolder);
if (SUCCEEDED(hr))
{
nCompare = ::CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, sczSourceFolder, -1, sczLastSourceFolder, -1);
}
else if (E_NOTFOUND == hr)
{
nCompare = CSTR_GREATER_THAN;
hr = S_OK;
}
if (CSTR_EQUAL != nCompare)
{
hr = VariableSetString(pVariables, BURN_BUNDLE_LAST_USED_SOURCE, sczSourceFolder, FALSE, FALSE);
ExitOnFailure(hr, "Failed to set last source.");
}
}
LExit:
ReleaseStr(sczLastSourceFolder);
ReleaseStr(sczSourceFolder);
return hr;
}
extern "C" HRESULT CacheSendProgressCallback(
__in DOWNLOAD_CACHE_CALLBACK* pCallback,
__in DWORD64 dw64Progress,
__in DWORD64 dw64Total,
__in HANDLE hDestinationFile
)
{
static LARGE_INTEGER LARGE_INTEGER_ZERO = { };
HRESULT hr = S_OK;
DWORD dwResult = PROGRESS_CONTINUE;
LARGE_INTEGER liTotalSize = { };
LARGE_INTEGER liTotalTransferred = { };
if (pCallback->pfnProgress)
{
liTotalSize.QuadPart = dw64Total;
liTotalTransferred.QuadPart = dw64Progress;
dwResult = (*pCallback->pfnProgress)(liTotalSize, liTotalTransferred, LARGE_INTEGER_ZERO, LARGE_INTEGER_ZERO, 1, CALLBACK_CHUNK_FINISHED, INVALID_HANDLE_VALUE, hDestinationFile, pCallback->pv);
switch (dwResult)
{
case PROGRESS_CONTINUE:
hr = S_OK;
break;
case PROGRESS_CANCEL: __fallthrough; // TODO: should cancel and stop be treated differently?
case PROGRESS_STOP:
hr = HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT);
ExitOnRootFailure(hr, "UX aborted on download progress.");
case PROGRESS_QUIET: // Not actually an error, just an indication to the caller to stop requesting progress.
pCallback->pfnProgress = NULL;
hr = S_OK;
break;
default:
hr = E_UNEXPECTED;
ExitOnRootFailure(hr, "Invalid return code from progress routine.");
}
}
LExit:
return hr;
}
extern "C" void CacheSendErrorCallback(
__in DOWNLOAD_CACHE_CALLBACK* pCallback,
__in HRESULT hrError,
__in_z_opt LPCWSTR wzError,
__out_opt BOOL* pfRetry
)
{
if (pfRetry)
{
*pfRetry = FALSE;
}
if (pCallback->pfnCancel)
{
int nResult = (*pCallback->pfnCancel)(hrError, wzError, pfRetry != NULL, pCallback->pv);
if (pfRetry && IDRETRY == nResult)
{
*pfRetry = TRUE;
}
}
}
extern "C" BOOL CacheBundleRunningFromCache()
{
return vfRunningFromCache;
}
extern "C" HRESULT CacheBundleToCleanRoom(
__in BURN_PAYLOADS* pUxPayloads,
__in BURN_SECTION* pSection,
__deref_out_z_opt LPWSTR* psczCleanRoomBundlePath
)
{
HRESULT hr = S_OK;
LPWSTR sczSourcePath = NULL;
LPWSTR wzExecutableName = NULL;
hr = PathForCurrentProcess(&sczSourcePath, NULL);
ExitOnFailure(hr, "Failed to get current path for process to cache to clean room.");
wzExecutableName = PathFile(sczSourcePath);
hr = CopyEngineToWorkingFolder(sczSourcePath, BUNDLE_CLEAN_ROOM_WORKING_FOLDER_NAME, wzExecutableName, pUxPayloads, pSection, psczCleanRoomBundlePath);
ExitOnFailure(hr, "Failed to cache bundle to clean room.");
LExit:
ReleaseStr(sczSourcePath);
return hr;
}
extern "C" HRESULT CacheBundleToWorkingDirectory(
__in_z LPCWSTR /*wzBundleId*/,
__in_z LPCWSTR wzExecutableName,
__in BURN_PAYLOADS* pUxPayloads,
__in BURN_SECTION* pSection,
__deref_out_z_opt LPWSTR* psczEngineWorkingPath
)
{
Assert(vfInitializedCache);
HRESULT hr = S_OK;
LPWSTR sczSourcePath = NULL;
// Initialize the source.
hr = PathForCurrentProcess(&sczSourcePath, NULL);
ExitOnFailure(hr, "Failed to get current process path.");
// If the bundle is running out of the package cache then we don't need to copy it to
// the working folder since we feel safe in the package cache and will run from there.
if (vfRunningFromCache)
{
hr = StrAllocString(psczEngineWorkingPath, sczSourcePath, 0);
ExitOnFailure(hr, "Failed to use current process path as target path.");
}
else // otherwise, carry on putting the bundle in the working folder.
{
hr = CopyEngineToWorkingFolder(sczSourcePath, BUNDLE_WORKING_FOLDER_NAME, wzExecutableName, pUxPayloads, pSection, psczEngineWorkingPath);
ExitOnFailure(hr, "Failed to copy engine to working folder.");
}
LExit:
ReleaseStr(sczSourcePath);
return hr;
}
extern "C" HRESULT CacheLayoutBundle(
__in_z LPCWSTR wzExecutableName,
__in_z LPCWSTR wzLayoutDirectory,
__in_z LPCWSTR wzSourceBundlePath
)
{
HRESULT hr = S_OK;
LPWSTR sczTargetPath = NULL;
hr = PathConcat(wzLayoutDirectory, wzExecutableName, &sczTargetPath);
ExitOnFailure(hr, "Failed to combine completed path with engine file name for layout.");
LogStringLine(REPORT_STANDARD, "Layout bundle from: '%ls' to: '%ls'", wzSourceBundlePath, sczTargetPath);
hr = FileEnsureMoveWithRetry(wzSourceBundlePath, sczTargetPath, TRUE, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to layout bundle from: '%ls' to '%ls'", wzSourceBundlePath, sczTargetPath);
LExit:
ReleaseStr(sczTargetPath);
return hr;
}
extern "C" HRESULT CacheCompleteBundle(
__in BOOL fPerMachine,
__in_z LPCWSTR wzExecutableName,
__in_z LPCWSTR wzBundleId,
__in BURN_PAYLOADS* pUxPayloads,
__in_z LPCWSTR wzSourceBundlePath
#ifdef DEBUG
, __in_z LPCWSTR wzExecutablePath
#endif
)
{
HRESULT hr = S_OK;
int nCompare = 0;
LPWSTR sczTargetDirectory = NULL;
LPWSTR sczTargetPath = NULL;
LPWSTR sczSourceDirectory = NULL;
LPWSTR sczPayloadSourcePath = NULL;
hr = CreateCompletedPath(fPerMachine, wzBundleId, &sczTargetDirectory);
ExitOnFailure(hr, "Failed to create completed cache path for bundle.");
hr = PathConcat(sczTargetDirectory, wzExecutableName, &sczTargetPath);
ExitOnFailure(hr, "Failed to combine completed path with engine file name.");
Assert(CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, wzExecutablePath, -1, sczTargetPath, -1));
// If the bundle is running out of the package cache then we don't need to copy it there
// (and don't want to since it'll be in use) so bail.
hr = PathCompare(wzSourceBundlePath, sczTargetPath, &nCompare);
ExitOnFailure(hr, "Failed to compare completed cache path for bundle: %ls", wzSourceBundlePath);
if (CSTR_EQUAL == nCompare)
{
ExitFunction();
}
// Otherwise, carry on putting the bundle in the cache.
LogStringLine(REPORT_STANDARD, "Caching bundle from: '%ls' to: '%ls'", wzSourceBundlePath, sczTargetPath);
FileRemoveFromPendingRename(sczTargetPath); // best effort to ensure bundle is not deleted from cache post restart.
hr = FileEnsureCopyWithRetry(wzSourceBundlePath, sczTargetPath, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to cache bundle from: '%ls' to '%ls'", wzSourceBundlePath, sczTargetPath);
// Reset the path permissions in the cache.
hr = ResetPathPermissions(fPerMachine, sczTargetPath);
ExitOnFailure(hr, "Failed to reset permissions on cached bundle: '%ls'", sczTargetPath);
hr = PathGetDirectory(wzSourceBundlePath, &sczSourceDirectory);
ExitOnFailure(hr, "Failed to get directory from engine working path: %ls", wzSourceBundlePath);
// Cache external UX payloads to completed path.
for (DWORD i = 0; i < pUxPayloads->cPayloads; ++i)
{
BURN_PAYLOAD* pPayload = &pUxPayloads->rgPayloads[i];
if (BURN_PAYLOAD_PACKAGING_EXTERNAL == pPayload->packaging)
{
hr = PathConcat(sczSourceDirectory, pPayload->sczSourcePath, &sczPayloadSourcePath);
ExitOnFailure(hr, "Failed to build payload source path.");
hr = CacheCompletePayload(fPerMachine, pPayload, wzBundleId, sczPayloadSourcePath, FALSE);
ExitOnFailure(hr, "Failed to complete the cache of payload: %ls", pPayload->sczKey);
}
}
LExit:
ReleaseStr(sczPayloadSourcePath);
ReleaseStr(sczSourceDirectory);
ReleaseStr(sczTargetPath);
ReleaseStr(sczTargetDirectory);
return hr;
}
extern "C" HRESULT CacheLayoutContainer(
__in BURN_CONTAINER* pContainer,
__in_z_opt LPCWSTR wzLayoutDirectory,
__in_z LPCWSTR wzUnverifiedContainerPath,
__in BOOL fMove
)
{
HRESULT hr = S_OK;
LPWSTR sczCachedPath = NULL;
hr = PathConcat(wzLayoutDirectory, pContainer->sczFilePath, &sczCachedPath);
ExitOnFailure(hr, "Failed to concat complete cached path.");
hr = VerifyThenTransferContainer(pContainer, sczCachedPath, wzUnverifiedContainerPath, fMove);
ExitOnFailure(hr, "Failed to layout container from cached path: %ls", sczCachedPath);
LExit:
ReleaseStr(sczCachedPath);
return hr;
}
extern "C" HRESULT CacheLayoutPayload(
__in BURN_PAYLOAD* pPayload,
__in_z_opt LPCWSTR wzLayoutDirectory,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in BOOL fMove
)
{
HRESULT hr = S_OK;
LPWSTR sczCachedPath = NULL;
hr = PathConcat(wzLayoutDirectory, pPayload->sczFilePath, &sczCachedPath);
ExitOnFailure(hr, "Failed to concat complete cached path.");
hr = VerifyThenTransferPayload(pPayload, sczCachedPath, wzUnverifiedPayloadPath, fMove);
ExitOnFailure(hr, "Failed to layout payload from cached payload: %ls", sczCachedPath);
LExit:
ReleaseStr(sczCachedPath);
return hr;
}
extern "C" HRESULT CacheCompletePayload(
__in BOOL fPerMachine,
__in BURN_PAYLOAD* pPayload,
__in_z_opt LPCWSTR wzCacheId,
__in_z LPCWSTR wzWorkingPayloadPath,
__in BOOL fMove
)
{
HRESULT hr = S_OK;
LPWSTR sczCachedDirectory = NULL;
LPWSTR sczCachedPath = NULL;
LPWSTR sczUnverifiedPayloadPath = NULL;
hr = CreateCompletedPath(fPerMachine, wzCacheId, &sczCachedDirectory);
ExitOnFailure(hr, "Failed to get cached path for package with cache id: %ls", wzCacheId);
hr = PathConcat(sczCachedDirectory, pPayload->sczFilePath, &sczCachedPath);
ExitOnFailure(hr, "Failed to concat complete cached path.");
// If the cached file matches what we expected, we're good.
hr = VerifyFileAgainstPayload(pPayload, sczCachedPath);
if (SUCCEEDED(hr))
{
::DecryptFileW(sczCachedPath, 0); // Let's try to make sure it's not encrypted.
LogId(REPORT_STANDARD, MSG_VERIFIED_EXISTING_PAYLOAD, pPayload->sczKey, sczCachedPath);
ExitFunction();
}
else if (E_PATHNOTFOUND != hr && E_FILENOTFOUND != hr)
{
LogErrorId(hr, MSG_FAILED_VERIFY_PAYLOAD, pPayload->sczKey, sczCachedPath, NULL);
FileEnsureDelete(sczCachedPath); // if the file existed but did not verify correctly, make it go away.
}
hr = CreateUnverifiedPath(fPerMachine, pPayload->sczKey, &sczUnverifiedPayloadPath);
ExitOnFailure(hr, "Failed to create unverified path.");
// If the working path exists, let's get it into the unverified path so we can reset the ACLs and verify the file.
if (FileExistsEx(wzWorkingPayloadPath, NULL))
{
hr = TransferWorkingPathToUnverifiedPath(wzWorkingPayloadPath, sczUnverifiedPayloadPath, fMove);
ExitOnFailure(hr, "Failed to transfer working path to unverified path for payload: %ls.", pPayload->sczKey);
}
else if (!FileExistsEx(sczUnverifiedPayloadPath, NULL)) // if the working path and unverified path do not exist, nothing we can do.
{
hr = E_FILENOTFOUND;
ExitOnFailure(hr, "Failed to find payload: %ls in working path: %ls and unverified path: %ls", pPayload->sczKey, wzWorkingPayloadPath, sczUnverifiedPayloadPath);
}
hr = ResetPathPermissions(fPerMachine, sczUnverifiedPayloadPath);
ExitOnFailure(hr, "Failed to reset permissions on unverified cached payload: %ls", pPayload->sczKey);
hr = VerifyFileAgainstPayload(pPayload, sczUnverifiedPayloadPath);
if (FAILED(hr))
{
LogErrorId(hr, MSG_FAILED_VERIFY_PAYLOAD, pPayload->sczKey, sczUnverifiedPayloadPath, NULL);
FileEnsureDelete(sczUnverifiedPayloadPath); // if the file did not verify correctly, make it go away.
ExitFunction();
}
LogId(REPORT_STANDARD, MSG_VERIFIED_ACQUIRED_PAYLOAD, pPayload->sczKey, sczUnverifiedPayloadPath, fMove ? "moving" : "copying", sczCachedPath);
hr = FileEnsureMoveWithRetry(sczUnverifiedPayloadPath, sczCachedPath, TRUE, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to move verified file to complete payload path: %ls", sczCachedPath);
::DecryptFileW(sczCachedPath, 0); // Let's try to make sure it's not encrypted.
LExit:
ReleaseStr(sczUnverifiedPayloadPath);
ReleaseStr(sczCachedPath);
ReleaseStr(sczCachedDirectory);
return hr;
}
extern "C" HRESULT CacheRemoveWorkingFolder(
__in_z_opt LPCWSTR wzBundleId
)
{
HRESULT hr = S_OK;
LPWSTR sczWorkingFolder = NULL;
if (vfInitializedCache)
{
hr = CalculateWorkingFolder(wzBundleId, &sczWorkingFolder);
ExitOnFailure(hr, "Failed to calculate the working folder to remove it.");
// Try to clean out everything in the working folder.
hr = DirEnsureDeleteEx(sczWorkingFolder, DIR_DELETE_FILES | DIR_DELETE_RECURSE | DIR_DELETE_SCHEDULE);
TraceError(hr, "Could not delete bundle engine working folder.");
}
LExit:
ReleaseStr(sczWorkingFolder);
return hr;
}
extern "C" HRESULT CacheRemoveBundle(
__in BOOL fPerMachine,
__in_z LPCWSTR wzBundleId
)
{
HRESULT hr = S_OK;
hr = RemoveBundleOrPackage(TRUE, fPerMachine, wzBundleId, wzBundleId);
ExitOnFailure(hr, "Failed to remove bundle id: %ls.", wzBundleId);
LExit:
return hr;
}
extern "C" HRESULT CacheRemovePackage(
__in BOOL fPerMachine,
__in_z LPCWSTR wzPackageId,
__in_z LPCWSTR wzCacheId
)
{
HRESULT hr = S_OK;
hr = RemoveBundleOrPackage(FALSE, fPerMachine, wzPackageId, wzCacheId);
ExitOnFailure(hr, "Failed to remove package id: %ls.", wzPackageId);
LExit:
return hr;
}
extern "C" void CacheCleanup(
__in BOOL fPerMachine,
__in_z LPCWSTR wzBundleId
)
{
HRESULT hr = S_OK;
LPWSTR sczFolder = NULL;
LPWSTR sczFiles = NULL;
LPWSTR sczDelete = NULL;
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATAW wfd = { };
DWORD cFileName = 0;
hr = CacheGetCompletedPath(fPerMachine, UNVERIFIED_CACHE_FOLDER_NAME, &sczFolder);
if (SUCCEEDED(hr))
{
hr = DirEnsureDeleteEx(sczFolder, DIR_DELETE_FILES | DIR_DELETE_RECURSE | DIR_DELETE_SCHEDULE);
}
if (!fPerMachine)
{
hr = CalculateWorkingFolder(wzBundleId, &sczFolder);
if (SUCCEEDED(hr))
{
hr = PathConcat(sczFolder, L"*.*", &sczFiles);
if (SUCCEEDED(hr))
{
hFind = ::FindFirstFileW(sczFiles, &wfd);
if (INVALID_HANDLE_VALUE != hFind)
{
do
{
// Skip directories.
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
continue;
}
// For extra safety and to silence OACR.
wfd.cFileName[MAX_PATH - 1] = L'\0';
// Skip resume files (they end with ".R").
cFileName = lstrlenW(wfd.cFileName);
if (2 < cFileName && L'.' == wfd.cFileName[cFileName - 2] && (L'R' == wfd.cFileName[cFileName - 1] || L'r' == wfd.cFileName[cFileName - 1]))
{
continue;
}
hr = PathConcat(sczFolder, wfd.cFileName, &sczDelete);
if (SUCCEEDED(hr))
{
hr = FileEnsureDelete(sczDelete);
}
} while (::FindNextFileW(hFind, &wfd));
}
}
}
}
if (INVALID_HANDLE_VALUE != hFind)
{
::FindClose(hFind);
}
ReleaseStr(sczDelete);
ReleaseStr(sczFiles);
ReleaseStr(sczFolder);
}
extern "C" void CacheUninitialize()
{
ReleaseNullStr(vsczCurrentMachinePackageCache);
ReleaseNullStr(vsczDefaultMachinePackageCache);
ReleaseNullStr(vsczDefaultUserPackageCache);
ReleaseNullStr(vsczWorkingFolder);
ReleaseNullStr(vsczSourceProcessPath);
vfRunningFromCache = FALSE;
vfInitializedCache = FALSE;
}
// Internal functions.
static HRESULT CalculateWorkingFolder(
__in_z_opt LPCWSTR /*wzBundleId*/,
__deref_out_z LPWSTR* psczWorkingFolder
)
{
HRESULT hr = S_OK;
RPC_STATUS rs = RPC_S_OK;
BOOL fElevated = FALSE;
WCHAR wzTempPath[MAX_PATH] = { };
UUID guid = {};
WCHAR wzGuid[39];
if (!vsczWorkingFolder)
{
ProcElevated(::GetCurrentProcess(), &fElevated);
if (fElevated)
{
if (!::GetWindowsDirectoryW(wzTempPath, countof(wzTempPath)))
{
ExitWithLastError(hr, "Failed to get windows path for working folder.");
}
hr = PathFixedBackslashTerminate(wzTempPath, countof(wzTempPath));
ExitOnFailure(hr, "Failed to ensure windows path for working folder ended in backslash.");
hr = ::StringCchCatW(wzTempPath, countof(wzTempPath), L"Temp\\");
ExitOnFailure(hr, "Failed to concat Temp directory on windows path for working folder.");
}
else if (0 == ::GetTempPathW(countof(wzTempPath), wzTempPath))
{
ExitWithLastError(hr, "Failed to get temp path for working folder.");
}
rs = ::UuidCreate(&guid);
hr = HRESULT_FROM_RPC(rs);
ExitOnFailure(hr, "Failed to create working folder guid.");
if (!::StringFromGUID2(guid, wzGuid, countof(wzGuid)))
{
hr = E_OUTOFMEMORY;
ExitOnRootFailure(hr, "Failed to convert working folder guid into string.");
}
hr = StrAllocFormatted(&vsczWorkingFolder, L"%ls%ls\\", wzTempPath, wzGuid);
ExitOnFailure(hr, "Failed to append bundle id on to temp path for working folder.");
}
hr = StrAllocString(psczWorkingFolder, vsczWorkingFolder, 0);
ExitOnFailure(hr, "Failed to copy working folder path.");
LExit:
return hr;
}
static HRESULT GetRootPath(
__in BOOL fPerMachine,
__in BOOL fAllowRedirect,
__deref_out_z LPWSTR* psczRootPath
)
{
HRESULT hr = S_OK;
LPWSTR sczAppData = NULL;
int nCompare = 0;
// Cache paths are initialized once so they cannot be changed while the engine is caching payloads.
if (fPerMachine)
{
// Always construct the default machine package cache path so we can determine if we're redirected.
if (!vsczDefaultMachinePackageCache)
{
hr = PathGetKnownFolder(CSIDL_COMMON_APPDATA, &sczAppData);
ExitOnFailure(hr, "Failed to find local %hs appdata directory.", "per-machine");
hr = PathConcat(sczAppData, PACKAGE_CACHE_FOLDER_NAME, &vsczDefaultMachinePackageCache);
ExitOnFailure(hr, "Failed to construct %hs package cache directory name.", "per-machine");
hr = PathBackslashTerminate(&vsczDefaultMachinePackageCache);
ExitOnFailure(hr, "Failed to backslash terminate default %hs package cache directory name.", "per-machine");
}
if (!vsczCurrentMachinePackageCache)
{
hr = PolcReadString(POLICY_BURN_REGISTRY_PATH, L"PackageCache", NULL, &vsczCurrentMachinePackageCache);
ExitOnFailure(hr, "Failed to read PackageCache policy directory.");
if (vsczCurrentMachinePackageCache)
{
hr = PathBackslashTerminate(&vsczCurrentMachinePackageCache);
ExitOnFailure(hr, "Failed to backslash terminate redirected per-machine package cache directory name.");
}
else
{
hr = StrAllocString(&vsczCurrentMachinePackageCache, vsczDefaultMachinePackageCache, 0);
ExitOnFailure(hr, "Failed to copy default package cache directory to current package cache directory.");
}
}
hr = StrAllocString(psczRootPath, fAllowRedirect ? vsczCurrentMachinePackageCache : vsczDefaultMachinePackageCache, 0);
ExitOnFailure(hr, "Failed to copy %hs package cache root directory.", "per-machine");
hr = PathCompare(vsczDefaultMachinePackageCache, *psczRootPath, &nCompare);
ExitOnFailure(hr, "Failed to compare default and current package cache directories.");
// Return S_FALSE if the current location is not the default location (redirected).
hr = CSTR_EQUAL == nCompare ? S_OK : S_FALSE;
}
else
{
if (!vsczDefaultUserPackageCache)
{
hr = PathGetKnownFolder(CSIDL_LOCAL_APPDATA, &sczAppData);
ExitOnFailure(hr, "Failed to find local %hs appdata directory.", "per-user");
hr = PathConcat(sczAppData, PACKAGE_CACHE_FOLDER_NAME, &vsczDefaultUserPackageCache);
ExitOnFailure(hr, "Failed to construct %hs package cache directory name.", "per-user");
hr = PathBackslashTerminate(&vsczDefaultUserPackageCache);
ExitOnFailure(hr, "Failed to backslash terminate default %hs package cache directory name.", "per-user");
}
hr = StrAllocString(psczRootPath, vsczDefaultUserPackageCache, 0);
ExitOnFailure(hr, "Failed to copy %hs package cache root directory.", "per-user");
}
LExit:
ReleaseStr(sczAppData);
return hr;
}
static HRESULT GetLastUsedSourceFolder(
__in BURN_VARIABLES* pVariables,
__out_z LPWSTR* psczLastSource
)
{
HRESULT hr = S_OK;
LPWSTR sczOriginalSource = NULL;
hr = VariableGetString(pVariables, BURN_BUNDLE_LAST_USED_SOURCE, psczLastSource);
if (E_NOTFOUND == hr)
{
// Try the original source folder.
hr = VariableGetString(pVariables, BURN_BUNDLE_ORIGINAL_SOURCE, &sczOriginalSource);
if (SUCCEEDED(hr))
{
hr = PathGetDirectory(sczOriginalSource, psczLastSource);
}
}
return hr;
}
static HRESULT CreateCompletedPath(
__in BOOL fPerMachine,
__in LPCWSTR wzId,
__out LPWSTR* psczCacheDirectory
)
{
static BOOL fPerMachineCacheRootVerified = FALSE;
HRESULT hr = S_OK;
LPWSTR sczCacheDirectory = NULL;
// If we are doing a permachine install but have not yet verified that the root cache folder
// was created with the correct ACLs yet, do that now.
if (fPerMachine && !fPerMachineCacheRootVerified)
{
hr = GetRootPath(fPerMachine, TRUE, &sczCacheDirectory);
ExitOnFailure(hr, "Failed to get cache directory.");
hr = DirEnsureExists(sczCacheDirectory, NULL);
ExitOnFailure(hr, "Failed to create cache directory: %ls", sczCacheDirectory);
hr = SecurePath(sczCacheDirectory);
ExitOnFailure(hr, "Failed to secure cache directory: %ls", sczCacheDirectory);
fPerMachineCacheRootVerified = TRUE;
}
// Get the cache completed path, ensure it exists, and reset any permissions people
// might have tried to set on the directory so we inherit the (correct!) security
// permissions from the parent directory.
hr = CacheGetCompletedPath(fPerMachine, wzId, &sczCacheDirectory);
ExitOnFailure(hr, "Failed to get cache directory.");
hr = DirEnsureExists(sczCacheDirectory, NULL);
ExitOnFailure(hr, "Failed to create cache directory: %ls", sczCacheDirectory);
ResetPathPermissions(fPerMachine, sczCacheDirectory);
*psczCacheDirectory = sczCacheDirectory;
sczCacheDirectory = NULL;
LExit:
ReleaseStr(sczCacheDirectory);
return hr;
}
static HRESULT CreateUnverifiedPath(
__in BOOL fPerMachine,
__in_z LPCWSTR wzPayloadId,
__out_z LPWSTR* psczUnverifiedPayloadPath
)
{
static BOOL fUnverifiedCacheFolderCreated = FALSE;
HRESULT hr = S_OK;
LPWSTR sczUnverifiedCacheFolder = NULL;
hr = CacheGetCompletedPath(fPerMachine, UNVERIFIED_CACHE_FOLDER_NAME, &sczUnverifiedCacheFolder);
ExitOnFailure(hr, "Failed to get cache directory.");
if (!fUnverifiedCacheFolderCreated)
{
hr = DirEnsureExists(sczUnverifiedCacheFolder, NULL);
ExitOnFailure(hr, "Failed to create unverified cache directory: %ls", sczUnverifiedCacheFolder);
ResetPathPermissions(fPerMachine, sczUnverifiedCacheFolder);
}
hr = PathConcat(sczUnverifiedCacheFolder, wzPayloadId, psczUnverifiedPayloadPath);
ExitOnFailure(hr, "Failed to concat payload id to unverified folder path.");
LExit:
ReleaseStr(sczUnverifiedCacheFolder);
return hr;
}
static HRESULT VerifyThenTransferContainer(
__in BURN_CONTAINER* pContainer,
__in_z LPCWSTR wzCachedPath,
__in_z LPCWSTR wzUnverifiedContainerPath,
__in BOOL fMove
)
{
HRESULT hr = S_OK;
HANDLE hFile = INVALID_HANDLE_VALUE;
// Get the container on disk actual hash.
hFile = ::CreateFileW(wzUnverifiedContainerPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
ExitWithLastError(hr, "Failed to open container in working path: %ls", wzUnverifiedContainerPath);
}
// Container should have a hash we can use to verify with.
if (pContainer->pbHash)
{
hr = VerifyHash(pContainer->pbHash, pContainer->cbHash, wzUnverifiedContainerPath, hFile);
ExitOnFailure(hr, "Failed to verify container hash: %ls", wzCachedPath);
}
LogStringLine(REPORT_STANDARD, "%ls container from working path '%ls' to path '%ls'", fMove ? L"Moving" : L"Copying", wzUnverifiedContainerPath, wzCachedPath);
if (fMove)
{
hr = FileEnsureMoveWithRetry(wzUnverifiedContainerPath, wzCachedPath, TRUE, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to move %ls to %ls", wzUnverifiedContainerPath, wzCachedPath);
}
else
{
hr = FileEnsureCopyWithRetry(wzUnverifiedContainerPath, wzCachedPath, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to copy %ls to %ls", wzUnverifiedContainerPath, wzCachedPath);
}
LExit:
ReleaseFileHandle(hFile);
return hr;
}
static HRESULT VerifyThenTransferPayload(
__in BURN_PAYLOAD* pPayload,
__in_z LPCWSTR wzCachedPath,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in BOOL fMove
)
{
HRESULT hr = S_OK;
HANDLE hFile = INVALID_HANDLE_VALUE;
// Get the payload on disk actual hash.
hFile = ::CreateFileW(wzUnverifiedPayloadPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
ExitWithLastError(hr, "Failed to open payload in working path: %ls", wzUnverifiedPayloadPath);
}
if (pPayload->pbHash) // the payload should have a hash we can use to verify it.
{
hr = VerifyHash(pPayload->pbHash, pPayload->cbHash, wzUnverifiedPayloadPath, hFile);
ExitOnFailure(hr, "Failed to verify payload hash: %ls", wzCachedPath);
}
LogStringLine(REPORT_STANDARD, "%ls payload from working path '%ls' to path '%ls'", fMove ? L"Moving" : L"Copying", wzUnverifiedPayloadPath, wzCachedPath);
if (fMove)
{
hr = FileEnsureMoveWithRetry(wzUnverifiedPayloadPath, wzCachedPath, TRUE, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to move %ls to %ls", wzUnverifiedPayloadPath, wzCachedPath);
}
else
{
hr = FileEnsureCopyWithRetry(wzUnverifiedPayloadPath, wzCachedPath, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to copy %ls to %ls", wzUnverifiedPayloadPath, wzCachedPath);
}
LExit:
ReleaseFileHandle(hFile);
return hr;
}
static HRESULT TransferWorkingPathToUnverifiedPath(
__in_z LPCWSTR wzWorkingPath,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in BOOL fMove
)
{
HRESULT hr = S_OK;
if (fMove)
{
hr = FileEnsureMoveWithRetry(wzWorkingPath, wzUnverifiedPayloadPath, TRUE, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to move %ls to %ls", wzWorkingPath, wzUnverifiedPayloadPath);
}
else
{
hr = FileEnsureCopyWithRetry(wzWorkingPath, wzUnverifiedPayloadPath, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to copy %ls to %ls", wzWorkingPath, wzUnverifiedPayloadPath);
}
LExit:
return hr;
}
static HRESULT VerifyFileAgainstPayload(
__in BURN_PAYLOAD* pPayload,
__in_z LPCWSTR wzVerifyPath
)
{
HRESULT hr = S_OK;
HANDLE hFile = INVALID_HANDLE_VALUE;
// Get the payload on disk actual hash.
hFile = ::CreateFileW(wzVerifyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
hr = HRESULT_FROM_WIN32(::GetLastError());
if (E_PATHNOTFOUND == hr || E_FILENOTFOUND == hr)
{
ExitFunction(); // do not log error when the file was not found.
}
ExitOnRootFailure(hr, "Failed to open payload at path: %ls", wzVerifyPath);
}
if (pPayload->pbHash) // the payload should have a hash we can use to verify it.
{
hr = VerifyHash(pPayload->pbHash, pPayload->cbHash, wzVerifyPath, hFile);
ExitOnFailure(hr, "Failed to verify hash of payload: %ls", pPayload->sczKey);
}
LExit:
ReleaseFileHandle(hFile);
return hr;
}
static HRESULT AllocateSid(
__in WELL_KNOWN_SID_TYPE type,
__out PSID* ppSid
)
{
HRESULT hr = S_OK;
PSID pAllocSid = NULL;
DWORD cbSid = SECURITY_MAX_SID_SIZE;
pAllocSid = static_cast<PSID>(MemAlloc(cbSid, TRUE));
ExitOnNull(pAllocSid, hr, E_OUTOFMEMORY, "Failed to allocate memory for well known SID.");
if (!::CreateWellKnownSid(type, NULL, pAllocSid, &cbSid))
{
ExitWithLastError(hr, "Failed to create well known SID.");
}
*ppSid = pAllocSid;
pAllocSid = NULL;
LExit:
ReleaseMem(pAllocSid);
return hr;
}
static HRESULT ResetPathPermissions(
__in BOOL fPerMachine,
__in_z LPCWSTR wzPath
)
{
HRESULT hr = S_OK;
DWORD er = ERROR_SUCCESS;
DWORD dwSetSecurity = DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION;
ACL acl = { };
PSID pSid = NULL;
if (fPerMachine)
{
hr = AllocateSid(WinBuiltinAdministratorsSid, &pSid);
ExitOnFailure(hr, "Failed to allocate administrator SID.");
// Create an empty (not NULL!) ACL to reset the permissions on the file to purely inherit from parent.
if (!::InitializeAcl(&acl, sizeof(acl), ACL_REVISION))
{
ExitWithLastError(hr, "Failed to initialize ACL.");
}
dwSetSecurity |= OWNER_SECURITY_INFORMATION;
}
hr = AclSetSecurityWithRetry(wzPath, SE_FILE_OBJECT, dwSetSecurity, pSid, NULL, &acl, NULL, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnWin32Error(er, hr, "Failed to reset the ACL on cached file: %ls", wzPath);
::SetFileAttributesW(wzPath, FILE_ATTRIBUTE_NORMAL); // Let's try to reset any possible read-only/system bits.
LExit:
ReleaseMem(pSid);
return hr;
}
static HRESULT GrantAccessAndAllocateSid(
__in WELL_KNOWN_SID_TYPE type,
__in DWORD dwGrantAccess,
__in EXPLICIT_ACCESS* pAccess
)
{
HRESULT hr = S_OK;
hr = AllocateSid(type, reinterpret_cast<PSID*>(&pAccess->Trustee.ptstrName));
ExitOnFailure(hr, "Failed to allocate SID to grate access.");
pAccess->grfAccessMode = GRANT_ACCESS;
pAccess->grfAccessPermissions = dwGrantAccess;
pAccess->grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
pAccess->Trustee.TrusteeForm = TRUSTEE_IS_SID;
pAccess->Trustee.TrusteeType = TRUSTEE_IS_GROUP;
LExit:
return hr;
}
static HRESULT SecurePath(
__in LPCWSTR wzPath
)
{
HRESULT hr = S_OK;
DWORD er = ERROR_SUCCESS;
EXPLICIT_ACCESSW access[4] = { };
PACL pAcl = NULL;
// Administrators must be the first one in the array so we can reuse the allocated SID below.
hr = GrantAccessAndAllocateSid(WinBuiltinAdministratorsSid, FILE_ALL_ACCESS, &access[0]);
ExitOnFailure(hr, "Failed to allocate access for Administrators group to path: %ls", wzPath);
hr = GrantAccessAndAllocateSid(WinLocalSystemSid, FILE_ALL_ACCESS, &access[1]);
ExitOnFailure(hr, "Failed to allocate access for SYSTEM group to path: %ls", wzPath);
hr = GrantAccessAndAllocateSid(WinWorldSid, GENERIC_READ | GENERIC_EXECUTE, &access[2]);
ExitOnFailure(hr, "Failed to allocate access for Everyone group to path: %ls", wzPath);
hr = GrantAccessAndAllocateSid(WinBuiltinUsersSid, GENERIC_READ | GENERIC_EXECUTE, &access[3]);
ExitOnFailure(hr, "Failed to allocate access for Users group to path: %ls", wzPath);
er = ::SetEntriesInAclW(countof(access), access, NULL, &pAcl);
ExitOnWin32Error(er, hr, "Failed to create ACL to secure cache path: %ls", wzPath);
// Set the ACL and ensure the Administrators group ends up the owner
hr = AclSetSecurityWithRetry(wzPath, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
reinterpret_cast<PSID>(access[0].Trustee.ptstrName), NULL, pAcl, NULL, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to secure cache path: %ls", wzPath);
LExit:
if (pAcl)
{
::LocalFree(pAcl);
}
for (DWORD i = 0; i < countof(access); ++i)
{
ReleaseMem(access[i].Trustee.ptstrName);
}
return hr;
}
static HRESULT CopyEngineToWorkingFolder(
__in_z LPCWSTR wzSourcePath,
__in_z LPCWSTR wzWorkingFolderName,
__in_z LPCWSTR wzExecutableName,
__in BURN_PAYLOADS* pUxPayloads,
__in BURN_SECTION* pSection,
__deref_out_z_opt LPWSTR* psczEngineWorkingPath
)
{
HRESULT hr = S_OK;
LPWSTR sczWorkingFolder = NULL;
LPWSTR sczTargetDirectory = NULL;
LPWSTR sczTargetPath = NULL;
LPWSTR sczSourceDirectory = NULL;
LPWSTR sczPayloadSourcePath = NULL;
LPWSTR sczPayloadTargetPath = NULL;
hr = CacheEnsureWorkingFolder(NULL, &sczWorkingFolder);
ExitOnFailure(hr, "Failed to create working path to copy engine.");
hr = PathConcat(sczWorkingFolder, wzWorkingFolderName, &sczTargetDirectory);
ExitOnFailure(hr, "Failed to calculate the bundle working folder target name.");
hr = DirEnsureExists(sczTargetDirectory, NULL);
ExitOnFailure(hr, "Failed create bundle working folder.");
hr = PathConcat(sczTargetDirectory, wzExecutableName, &sczTargetPath);
ExitOnFailure(hr, "Failed to combine working path with engine file name.");
// Copy the engine without any attached containers to the working path.
hr = CopyEngineWithSignatureFixup(pSection->hEngineFile, wzSourcePath, sczTargetPath, pSection);
ExitOnFailure(hr, "Failed to copy engine: '%ls' to working path: %ls", wzSourcePath, sczTargetPath);
// Copy external UX payloads to working path.
for (DWORD i = 0; i < pUxPayloads->cPayloads; ++i)
{
BURN_PAYLOAD* pPayload = &pUxPayloads->rgPayloads[i];
if (BURN_PAYLOAD_PACKAGING_EXTERNAL == pPayload->packaging)
{
if (!sczSourceDirectory)
{
hr = PathGetDirectory(wzSourcePath, &sczSourceDirectory);
ExitOnFailure(hr, "Failed to get directory from engine path: %ls", wzSourcePath);
}
hr = PathConcat(sczSourceDirectory, pPayload->sczSourcePath, &sczPayloadSourcePath);
ExitOnFailure(hr, "Failed to build payload source path for working copy.");
hr = PathConcat(sczTargetDirectory, pPayload->sczFilePath, &sczPayloadTargetPath);
ExitOnFailure(hr, "Failed to build payload target path for working copy.");
hr = FileEnsureCopyWithRetry(sczPayloadSourcePath, sczPayloadTargetPath, TRUE, FILE_OPERATION_RETRY_COUNT, FILE_OPERATION_RETRY_WAIT);
ExitOnFailure(hr, "Failed to copy UX payload from: '%ls' to: '%ls'", sczPayloadSourcePath, sczPayloadTargetPath);
}
}
if (psczEngineWorkingPath)
{
hr = StrAllocString(psczEngineWorkingPath, sczTargetPath, 0);
ExitOnFailure(hr, "Failed to copy target path for engine working path.");
}
LExit:
ReleaseStr(sczPayloadTargetPath);
ReleaseStr(sczPayloadSourcePath);
ReleaseStr(sczSourceDirectory);
ReleaseStr(sczTargetPath);
ReleaseStr(sczTargetDirectory);
ReleaseStr(sczWorkingFolder);
return hr;
}
static HRESULT CopyEngineWithSignatureFixup(
__in HANDLE hEngineFile,
__in_z LPCWSTR wzEnginePath,
__in_z LPCWSTR wzTargetPath,
__in BURN_SECTION* pSection
)
{
HRESULT hr = S_OK;
HANDLE hTarget = INVALID_HANDLE_VALUE;
LARGE_INTEGER li = { };
DWORD dwZeroOriginals[3] = { };
hTarget = ::CreateFileW(wzTargetPath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (INVALID_HANDLE_VALUE == hTarget)
{
ExitWithLastError(hr, "Failed to create engine file at path: %ls", wzTargetPath);
}
hr = FileSetPointer(hEngineFile, 0, NULL, FILE_BEGIN);
ExitOnFailure(hr, "Failed to seek to beginning of engine file: %ls", wzEnginePath);
hr = FileCopyUsingHandles(hEngineFile, hTarget, pSection->cbEngineSize, NULL);
ExitOnFailure(hr, "Failed to copy engine from: %ls to: %ls", wzEnginePath, wzTargetPath);
// If the original executable was signed, let's put back the checksum and signature.
if (pSection->dwOriginalSignatureOffset)
{
// Fix up the checksum.
li.QuadPart = pSection->dwChecksumOffset;
if (!::SetFilePointerEx(hTarget, li, NULL, FILE_BEGIN))
{
ExitWithLastError(hr, "Failed to seek to checksum in exe header.");
}
hr = FileWriteHandle(hTarget, reinterpret_cast<LPBYTE>(&pSection->dwOriginalChecksum), sizeof(pSection->dwOriginalChecksum));
ExitOnFailure(hr, "Failed to update signature offset.");
// Fix up the signature information.
li.QuadPart = pSection->dwCertificateTableOffset;
if (!::SetFilePointerEx(hTarget, li, NULL, FILE_BEGIN))
{
ExitWithLastError(hr, "Failed to seek to signature table in exe header.");
}
hr = FileWriteHandle(hTarget, reinterpret_cast<LPBYTE>(&pSection->dwOriginalSignatureOffset), sizeof(pSection->dwOriginalSignatureOffset));
ExitOnFailure(hr, "Failed to update signature offset.");
hr = FileWriteHandle(hTarget, reinterpret_cast<LPBYTE>(&pSection->dwOriginalSignatureSize), sizeof(pSection->dwOriginalSignatureSize));
ExitOnFailure(hr, "Failed to update signature offset.");
// Zero out the original information since that is how it was when the file was originally signed.
li.QuadPart = pSection->dwOriginalChecksumAndSignatureOffset;
if (!::SetFilePointerEx(hTarget, li, NULL, FILE_BEGIN))
{
ExitWithLastError(hr, "Failed to seek to original data in exe burn section header.");
}
hr = FileWriteHandle(hTarget, reinterpret_cast<LPBYTE>(&dwZeroOriginals), sizeof(dwZeroOriginals));
ExitOnFailure(hr, "Failed to zero out original data offset.");
}
LExit:
ReleaseFileHandle(hTarget);
return hr;
}
static HRESULT RemoveBundleOrPackage(
__in BOOL fBundle,
__in BOOL fPerMachine,
__in_z LPCWSTR wzBundleOrPackageId,
__in_z LPCWSTR wzCacheId
)
{
HRESULT hr = S_OK;
LPWSTR sczRootCacheDirectory = NULL;
LPWSTR sczDirectory = NULL;
hr = CacheGetCompletedPath(fPerMachine, wzCacheId, &sczDirectory);
ExitOnFailure(hr, "Failed to calculate cache path.");
LogId(REPORT_STANDARD, fBundle ? MSG_UNCACHE_BUNDLE : MSG_UNCACHE_PACKAGE, wzBundleOrPackageId, sczDirectory);
// Try really hard to remove the cache directory.
hr = E_FAIL;
for (DWORD iRetry = 0; FAILED(hr) && iRetry < FILE_OPERATION_RETRY_COUNT; ++iRetry)
{
if (0 < iRetry)
{
::Sleep(FILE_OPERATION_RETRY_WAIT);
}
hr = DirEnsureDeleteEx(sczDirectory, DIR_DELETE_FILES | DIR_DELETE_RECURSE | DIR_DELETE_SCHEDULE);
if (E_PATHNOTFOUND == hr)
{
break;
}
}
if (FAILED(hr))
{
LogId(REPORT_STANDARD, fBundle ? MSG_UNABLE_UNCACHE_BUNDLE : MSG_UNABLE_UNCACHE_PACKAGE, wzBundleOrPackageId, sczDirectory, hr);
hr = S_OK;
}
else
{
// Try to remove root package cache in the off chance it is now empty.
hr = GetRootPath(fPerMachine, TRUE, &sczRootCacheDirectory);
ExitOnFailure(hr, "Failed to get %hs package cache root directory.", fPerMachine ? "per-machine" : "per-user");
DirEnsureDeleteEx(sczRootCacheDirectory, DIR_DELETE_SCHEDULE);
// GetRootPath returns S_FALSE if the package cache is redirected elsewhere.
if (S_FALSE == hr)
{
hr = GetRootPath(fPerMachine, FALSE, &sczRootCacheDirectory);
ExitOnFailure(hr, "Failed to get old %hs package cache root directory.", fPerMachine ? "per-machine" : "per-user");
DirEnsureDeleteEx(sczRootCacheDirectory, DIR_DELETE_SCHEDULE);
}
}
LExit:
ReleaseStr(sczDirectory);
ReleaseStr(sczRootCacheDirectory);
return hr;
}
static HRESULT VerifyHash(
__in BYTE* pbHash,
__in DWORD cbHash,
__in_z LPCWSTR wzUnverifiedPayloadPath,
__in HANDLE hFile
)
{
UNREFERENCED_PARAMETER(wzUnverifiedPayloadPath);
HRESULT hr = S_OK;
BYTE rgbActualHash[SHA1_HASH_LEN] = { };
DWORD64 qwHashedBytes;
LPWSTR pszExpected = NULL;
LPWSTR pszActual = NULL;
// TODO: create a cryp hash file that sends progress.
hr = CrypHashFileHandle(hFile, PROV_RSA_FULL, CALG_SHA1, rgbActualHash, sizeof(rgbActualHash), &qwHashedBytes);
ExitOnFailure(hr, "Failed to calculate hash for path: %ls", wzUnverifiedPayloadPath);
// Compare hashes.
if (cbHash != sizeof(rgbActualHash) || 0 != memcmp(pbHash, rgbActualHash, SHA1_HASH_LEN))
{
hr = CRYPT_E_HASH_VALUE;
// Best effort to log the expected and actual hash value strings.
if (SUCCEEDED(StrAllocHexEncode(pbHash, cbHash, &pszExpected)) &&
SUCCEEDED(StrAllocHexEncode(rgbActualHash, SHA1_HASH_LEN, &pszActual)))
{
ExitOnFailure(hr, "Hash mismatch for path: %ls, expected: %ls, actual: %ls", wzUnverifiedPayloadPath, pszExpected, pszActual);
}
else
{
ExitOnFailure(hr, "Hash mismatch for path: %ls", wzUnverifiedPayloadPath);
}
}
LExit:
ReleaseStr(pszActual);
ReleaseStr(pszExpected);
return hr;
}
|