-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathPreIndexedPackageSourceFactory.cpp
More file actions
739 lines (608 loc) · 32.5 KB
/
PreIndexedPackageSourceFactory.cpp
File metadata and controls
739 lines (608 loc) · 32.5 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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "Microsoft/PreIndexedPackageSourceFactory.h"
#include "Microsoft/SQLiteIndex.h"
#include "Microsoft/SQLiteIndexSource.h"
#include "SourceUpdateChecks.h"
#include <AppInstallerDateTime.h>
#include <AppInstallerDeployment.h>
#include <AppInstallerDownloader.h>
#include <AppInstallerMsixInfo.h>
#include <winget/ManagedFile.h>
#include <winget/ExperimentalFeature.h>
using namespace std::string_literals;
using namespace std::string_view_literals;
namespace AppInstaller::Repository::Microsoft
{
namespace
{
// To use an unsigned source, set AICLI_ALLOW_UNSIGNED_SOURCE and use a debug build.
// Ex: set CL=/DAICLI_ALLOW_UNSIGNED_SOURCE
#if ! defined( AICLI_DISABLE_TEST_HOOKS ) && defined( AICLI_ALLOW_UNSIGNED_SOURCE )
static bool s_AllowUnsignedSource = true;
#else
static bool s_AllowUnsignedSource = false;
#endif
static constexpr std::string_view s_PreIndexedPackageSourceFactory_PackageFileName = "source.msix"sv;
static constexpr std::string_view s_PreIndexedPackageSourceFactory_V2_PackageFileName = "source2.msix"sv;
static constexpr std::string_view s_PreIndexedPackageSourceFactory_PackageVersionHeader = "x-ms-meta-sourceversion"sv;
static constexpr std::string_view s_PreIndexedPackageSourceFactory_IndexFileName = "index.db"sv;
// TODO: This being hard coded to force using the Public directory name is not ideal.
static constexpr std::string_view s_PreIndexedPackageSourceFactory_IndexFilePath = "Public\\index.db"sv;
// Construct the package location from the given details.
// Currently expects that the arg is an https uri pointing to the root of the data.
std::string GetPackageLocation(const std::string& basePath, std::string_view fileName)
{
std::string result = basePath;
if (result.back() != '/')
{
result += '/';
}
result += fileName;
return result;
}
// Gets the set of package locations that should be tried, in order.
std::vector<std::string> GetPackageLocations(const SourceDetails& details)
{
THROW_HR_IF(E_INVALIDARG, details.Arg.empty());
std::vector<std::string> result;
result.emplace_back(GetPackageLocation(details.Arg, s_PreIndexedPackageSourceFactory_V2_PackageFileName));
result.emplace_back(GetPackageLocation(details.Arg, s_PreIndexedPackageSourceFactory_PackageFileName));
if (!details.AlternateArg.empty())
{
result.emplace_back(GetPackageLocation(details.AlternateArg, s_PreIndexedPackageSourceFactory_V2_PackageFileName));
result.emplace_back(GetPackageLocation(details.AlternateArg, s_PreIndexedPackageSourceFactory_PackageFileName));
}
return result;
}
// Abstracts the fallback for package location when the MsixInfo is needed.
struct PreIndexedPackageInfo
{
template <typename LocationCheck>
PreIndexedPackageInfo(const SourceDetails& details, LocationCheck&& locationCheck)
{
std::vector<std::string> potentialLocations = GetPackageLocations(details);
for (const auto& location : potentialLocations)
{
locationCheck(location);
}
std::exception_ptr primaryException;
for (const auto& location : potentialLocations)
{
try
{
m_msixInfo = std::make_unique<Msix::MsixInfo>(location);
m_packageLocation = location;
return;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION_MSG("PreIndexedPackageInfo failed on location: %hs", location.c_str());
if (!primaryException)
{
primaryException = std::current_exception();
}
}
}
std::rethrow_exception(primaryException);
}
const std::string& PackageLocation() const { return m_packageLocation; }
Msix::MsixInfo& MsixInfo() { return *m_msixInfo; }
private:
std::string m_packageLocation;
std::unique_ptr<Msix::MsixInfo> m_msixInfo;
};
// Abstracts the fallback for package location when an update is being done.
struct PreIndexedPackageUpdateCheck
{
PreIndexedPackageUpdateCheck(const SourceDetails& details)
{
std::vector<std::string> potentialLocations = GetPackageLocations(details);
std::exception_ptr primaryException;
for (const auto& location : potentialLocations)
{
try
{
m_availableVersion = GetAvailableVersionFrom(location);
m_packageLocation = location;
return;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION_MSG("PreIndexedPackageUpdateCheck failed on location: %hs", location.c_str());
if (!primaryException)
{
primaryException = std::current_exception();
}
}
}
std::rethrow_exception(primaryException);
}
const std::string& PackageLocation() const { return m_packageLocation; }
const Msix::PackageVersion& AvailableVersion() const { return m_availableVersion; }
private:
std::string m_packageLocation;
Msix::PackageVersion m_availableVersion;
Msix::PackageVersion GetAvailableVersionFrom(const std::string& packageLocation)
{
if (Utility::IsUrlRemote(packageLocation))
{
std::map<std::string, std::string> headers = Utility::GetHeaders(packageLocation);
auto itr = headers.find(std::string{ s_PreIndexedPackageSourceFactory_PackageVersionHeader });
if (itr != headers.end())
{
AICLI_LOG(Repo, Verbose, << "Header indicates version is: " << itr->second);
return { itr->second };
}
// We did not find the header we were looking for, log the ones we did find
AICLI_LOG(Repo, Verbose, << "Did not find " << s_PreIndexedPackageSourceFactory_PackageVersionHeader << " in:\n" << [&]()
{
std::ostringstream headerLog;
for (const auto& header : headers)
{
headerLog << " " << header.first << " : " << header.second << '\n';
}
return std::move(headerLog).str();
}());
}
AICLI_LOG(Repo, Verbose, << "Reading package data to determine version");
Msix::MsixInfo info{ packageLocation };
auto manifest = info.GetAppPackageManifests();
THROW_HR_IF(APPINSTALLER_CLI_ERROR_PACKAGE_IS_BUNDLE, manifest.size() > 1);
THROW_HR_IF(E_UNEXPECTED, manifest.size() == 0);
return manifest[0].GetIdentity().GetVersion();
}
};
// Gets the package family name from the details.
std::string GetPackageFamilyNameFromDetails(const SourceDetails& details)
{
THROW_HR_IF(E_UNEXPECTED, details.Data.empty());
return details.Data;
}
// Creates a name for the cross process reader-writer lock given the details.
std::string CreateNameForCPL(const SourceDetails& details)
{
// The only relevant data is the package family name
return "PreIndexedSourceCPL_"s + GetPackageFamilyNameFromDetails(details);
}
// The base class for a package that comes from a preindexed packaged source.
struct PreIndexedFactoryBase : public ISourceFactory
{
std::string_view TypeName() const override final
{
return PreIndexedPackageSourceFactory::Type();
}
std::shared_ptr<ISourceReference> Create(const SourceDetails& details) override final
{
// With more than one source implementation, we will probably need to probe first
THROW_HR_IF(E_INVALIDARG, !details.Type.empty() && details.Type != PreIndexedPackageSourceFactory::Type());
return CreateInternal(details);
}
virtual std::shared_ptr<ISourceReference> CreateInternal(const SourceDetails& details) = 0;
bool Add(SourceDetails& details, IProgressCallback& progress) override final
{
if (details.Type.empty())
{
// With more than one source implementation, we will probably need to probe first
details.Type = PreIndexedPackageSourceFactory::Type();
AICLI_LOG(Repo, Info, << "Initializing source type: " << details.Name << " => " << details.Type);
}
else
{
THROW_HR_IF(E_INVALIDARG, details.Type != PreIndexedPackageSourceFactory::Type());
}
PreIndexedPackageInfo packageInfo(details, [](const std::string& packageLocation)
{
THROW_HR_IF(APPINSTALLER_CLI_ERROR_SOURCE_NOT_SECURE, Utility::IsUrlRemote(packageLocation) && !Utility::IsUrlSecure(packageLocation));
});
AICLI_LOG(Repo, Info, << "Initializing source from: " << details.Name << " => " << packageInfo.PackageLocation());
THROW_HR_IF(APPINSTALLER_CLI_ERROR_PACKAGE_IS_BUNDLE, packageInfo.MsixInfo().GetIsBundle());
auto fullName = packageInfo.MsixInfo().GetPackageFullName();
AICLI_LOG(Repo, Info, << "Found package full name: " << details.Name << " => " << fullName);
details.Data = Msix::GetPackageFamilyNameFromFullName(fullName);
details.Identifier = Msix::GetPackageFamilyNameFromFullName(fullName);
auto lock = LockExclusive(details, progress);
if (!lock)
{
return false;
}
return UpdateInternal(packageInfo.PackageLocation(), details, progress);
}
bool Update(const SourceDetails& details, IProgressCallback& progress) override final
{
return UpdateBase(details, false, progress);
}
bool BackgroundUpdate(const SourceDetails& details, IProgressCallback& progress) override final
{
return UpdateBase(details, true, progress);
}
// Retrieves the currently cached version of the package.
virtual std::optional<Msix::PackageVersion> GetCurrentVersion(const SourceDetails& details) = 0;
virtual bool UpdateInternal(const std::string& packageLocation, const SourceDetails& details, IProgressCallback& progress) = 0;
bool Remove(const SourceDetails& details, IProgressCallback& progress) override final
{
THROW_HR_IF(E_INVALIDARG, details.Type != PreIndexedPackageSourceFactory::Type());
auto lock = LockExclusive(details, progress);
if (!lock)
{
return false;
}
return RemoveInternal(details, progress);
}
virtual bool RemoveInternal(const SourceDetails& details, IProgressCallback&) = 0;
private:
Synchronization::CrossProcessLock LockExclusive(const SourceDetails& details, IProgressCallback& progress, bool isBackground = false)
{
Synchronization::CrossProcessLock result(CreateNameForCPL(details));
if (isBackground)
{
// If this is a background update, don't wait on the lock.
result.TryAcquireNoWait();
}
else
{
result.Acquire(progress);
}
return result;
}
bool UpdateBase(const SourceDetails& details, bool isBackground, IProgressCallback& progress)
{
THROW_HR_IF(E_INVALIDARG, details.Type != PreIndexedPackageSourceFactory::Type());
std::optional<Msix::PackageVersion> currentVersion = GetCurrentVersion(details);
PreIndexedPackageUpdateCheck updateCheck(details);
if (currentVersion)
{
if (currentVersion.value() >= updateCheck.AvailableVersion())
{
AICLI_LOG(Repo, Verbose, << "Remote source data (" << updateCheck.AvailableVersion().ToString() <<
") was not newer than existing (" << currentVersion.value().ToString() << "), no update needed");
return true;
}
else
{
AICLI_LOG(Repo, Verbose, << "Remote source data (" << updateCheck.AvailableVersion().ToString() <<
") was newer than existing (" << currentVersion.value().ToString() << "), updating");
}
}
if (progress.IsCancelledBy(CancelReason::Any))
{
AICLI_LOG(Repo, Info, << "Cancelling update upon request");
return false;
}
auto lock = LockExclusive(details, progress, isBackground);
if (!lock)
{
return false;
}
return UpdateInternal(updateCheck.PackageLocation(), details, progress);
}
};
// *Should only be called when under a CrossProcessReaderWriteLock*
std::optional<Deployment::Extension> GetExtensionFromDetails(const SourceDetails& details)
{
Deployment::ExtensionCatalog catalog(Deployment::SourceExtensionName);
return catalog.FindByPackageFamilyAndId(GetPackageFamilyNameFromDetails(details), Deployment::IndexDBId);
}
std::optional<Msix::PackageVersion> PackagedContextGetCurrentVersion(const SourceDetails& details)
{
auto extension = GetExtensionFromDetails(details);
if (extension)
{
auto version = extension->GetPackageVersion();
return Msix::PackageVersion{ version.Major, version.Minor, version.Build, version.Revision };
}
else
{
return std::nullopt;
}
}
// Constructs the location that we will write files to.
std::filesystem::path GetStatePathFromDetails(const SourceDetails& details)
{
std::filesystem::path result = Runtime::GetPathTo(Runtime::PathName::LocalState);
result /= PreIndexedPackageSourceFactory::Type();
result /= GetPackageFamilyNameFromDetails(details);
return result;
}
std::optional<Msix::PackageVersion> DesktopContextGetCurrentVersion(const SourceDetails& details)
{
std::filesystem::path packageState = GetStatePathFromDetails(details);
std::filesystem::path packagePath = packageState / s_PreIndexedPackageSourceFactory_PackageFileName;
if (std::filesystem::exists(packagePath))
{
// If we already have a trusted index package, use it to determine if we need to update or not.
Msix::WriteLockedMsixFile indexPackage{ packagePath };
if (indexPackage.ValidateTrustInfo(WI_IsFlagSet(details.TrustLevel, SourceTrustLevel::StoreOrigin)))
{
Msix::MsixInfo msixInfo{ packagePath };
auto manifest = msixInfo.GetAppPackageManifests();
if (manifest.size() == 1)
{
return manifest[0].GetIdentity().GetVersion();
}
}
}
return std::nullopt;
}
bool CheckForUpdateBeforeOpen(const SourceDetails& details, std::optional<Msix::PackageVersion> currentVersion, const std::optional<TimeSpan>& requestedUpdateInterval)
{
// If we can't find a good package, then we have to update to operate
if (!currentVersion)
{
AICLI_LOG(Repo, Verbose, << "Source `" << details.Name << "` has no data");
return true;
}
using namespace std::chrono_literals;
using clock = std::chrono::system_clock;
// Attempt to convert the package version to a time_point
clock::time_point versionTime = Utility::GetTimePointFromVersion(currentVersion.value());
// Since we expect that the version time indicates creation time, don't let it be far in the future.
auto now = clock::now();
if (versionTime > now && versionTime - now > 24h)
{
versionTime = clock::time_point::min();
}
// Use the later of the version and last update times
clock::time_point timeToCheck = (versionTime > details.LastUpdateTime ? versionTime : details.LastUpdateTime);
return IsAfterUpdateCheckTime(details.Name, timeToCheck, requestedUpdateInterval);
}
struct PackagedContextSourceReference : public ISourceReference
{
PackagedContextSourceReference(const SourceDetails& details) : m_details(details)
{
if (!m_details.Data.empty())
{
m_details.Identifier = GetPackageFamilyNameFromDetails(details);
}
}
std::string GetIdentifier() override { return m_details.Identifier; }
SourceDetails& GetDetails() override { return m_details; };
bool ShouldUpdateBeforeOpen(const std::optional<TimeSpan>& requestedUpdateInterval) override
{
return CheckForUpdateBeforeOpen(m_details, PackagedContextGetCurrentVersion(m_details), requestedUpdateInterval);
}
std::shared_ptr<ISource> Open(IProgressCallback& progress) override
{
Synchronization::CrossProcessLock lock(CreateNameForCPL(m_details));
if (!lock.Acquire(progress))
{
return {};
}
auto extension = GetExtensionFromDetails(m_details);
if (!extension)
{
AICLI_LOG(Repo, Info, << "Package not found " << m_details.Data);
THROW_HR(APPINSTALLER_CLI_ERROR_SOURCE_DATA_MISSING);
}
THROW_HR_IF(HRESULT_FROM_WIN32(ERROR_NEEDS_REMEDIATION), !extension->VerifyContentIntegrity(progress));
// To work around an issue with accessing the public folder, we are temporarily
// constructing the location ourself. This was already the case for the non-packaged
// runtime, and we can fix both in the future. The only problem with this is that
// the directory in the extension *must* be Public, rather than one set by the creator.
std::filesystem::path indexLocation = extension->GetPackagePath();
indexLocation /= s_PreIndexedPackageSourceFactory_IndexFilePath;
SQLiteIndex index = SQLiteIndex::Open(indexLocation.u8string(), SQLiteIndex::OpenDisposition::Immutable);
// We didn't use to store the source identifier, so we compute it here in case it's
// missing from the details.
m_details.Identifier = GetPackageFamilyNameFromDetails(m_details);
return std::make_shared<SQLiteIndexSource>(m_details, std::move(index), false, true);
}
private:
SourceDetails m_details;
};
// Source factory for running within a packaged context
struct PackagedContextFactory : public PreIndexedFactoryBase
{
std::shared_ptr<ISourceReference> CreateInternal(const SourceDetails& details) override
{
return std::make_shared<PackagedContextSourceReference>(details);
}
std::optional<Msix::PackageVersion> GetCurrentVersion(const SourceDetails& details) override
{
return PackagedContextGetCurrentVersion(details);
}
bool UpdateInternal(const std::string& packageLocation, const SourceDetails& details, IProgressCallback& progress) override
{
// Due to complications with deployment, download the file and deploy from
// a local source while we investigate further.
bool download = Utility::IsUrlRemote(packageLocation);
std::filesystem::path localFile;
if (download)
{
localFile = Runtime::GetPathTo(Runtime::PathName::Temp);
localFile /= GetPackageFamilyNameFromDetails(details) + ".msix";
Utility::Download(packageLocation, localFile, Utility::DownloadType::Index, progress);
}
else
{
localFile = Utility::ConvertToUTF16(packageLocation);
}
// Verify the local file
Msix::WriteLockedMsixFile fileLock{ localFile };
Msix::MsixInfo localMsixInfo{ localFile };
// The package should not be a bundle
THROW_HR_IF(APPINSTALLER_CLI_ERROR_PACKAGE_IS_BUNDLE, localMsixInfo.GetIsBundle());
// Ensure that family name has not changed
THROW_HR_IF(APPINSTALLER_CLI_ERROR_SOURCE_DATA_INTEGRITY_FAILURE,
GetPackageFamilyNameFromDetails(details) != Msix::GetPackageFamilyNameFromFullName(localMsixInfo.GetPackageFullName()));
if (!fileLock.ValidateTrustInfo(WI_IsFlagSet(details.TrustLevel, SourceTrustLevel::StoreOrigin)))
{
AICLI_LOG(Repo, Error, << "Source update failed. Source package failed trust validation.");
THROW_HR(APPINSTALLER_CLI_ERROR_SOURCE_DATA_INTEGRITY_FAILURE);
}
winrt::Windows::Foundation::Uri uri = winrt::Windows::Foundation::Uri(localFile.c_str());
Deployment::AddPackage(
uri,
Deployment::Options{ WI_IsFlagSet(details.TrustLevel, SourceTrustLevel::Trusted) },
progress);
if (download)
{
try
{
// If successful, delete the file
std::filesystem::remove(localFile);
}
CATCH_LOG();
}
return true;
}
bool RemoveInternal(const SourceDetails& details, IProgressCallback& callback) override
{
auto fullName = Msix::GetPackageFullNameFromFamilyName(GetPackageFamilyNameFromDetails(details));
if (!fullName)
{
AICLI_LOG(Repo, Info, << "No full name found for family name: " << GetPackageFamilyNameFromDetails(details));
}
else
{
AICLI_LOG(Repo, Info, << "Removing package: " << *fullName);
Deployment::RemovePackage(*fullName, winrt::Windows::Management::Deployment::RemovalOptions::None, callback);
}
return true;
}
};
struct DesktopContextSourceReference : public ISourceReference
{
DesktopContextSourceReference(const SourceDetails& details) : m_details(details)
{
if (!m_details.Data.empty())
{
m_details.Identifier = GetPackageFamilyNameFromDetails(details);
}
}
std::string GetIdentifier() override { return m_details.Identifier; }
SourceDetails& GetDetails() override { return m_details; };
bool ShouldUpdateBeforeOpen(const std::optional<TimeSpan>& requestedUpdateInterval) override
{
return CheckForUpdateBeforeOpen(m_details, DesktopContextGetCurrentVersion(m_details), requestedUpdateInterval);
}
std::shared_ptr<ISource> Open(IProgressCallback& progress) override
{
Synchronization::CrossProcessLock lock(CreateNameForCPL(m_details));
if (!lock.Acquire(progress))
{
return {};
}
std::filesystem::path packageLocation = GetStatePathFromDetails(m_details);
packageLocation /= s_PreIndexedPackageSourceFactory_PackageFileName;
if (!std::filesystem::exists(packageLocation))
{
AICLI_LOG(Repo, Info, << "Data not found at " << packageLocation);
THROW_HR(APPINSTALLER_CLI_ERROR_SOURCE_DATA_MISSING);
}
// Put a write exclusive lock on the index package.
Msix::WriteLockedMsixFile indexPackage{ packageLocation };
// Validate index package trust info.
THROW_HR_IF(APPINSTALLER_CLI_ERROR_SOURCE_DATA_INTEGRITY_FAILURE, !s_AllowUnsignedSource && !indexPackage.ValidateTrustInfo(WI_IsFlagSet(m_details.TrustLevel, SourceTrustLevel::StoreOrigin)));
// Create a temp lock exclusive index file.
auto tempIndexFilePath = Runtime::GetNewTempFilePath();
auto tempIndexFile = Utility::ManagedFile::CreateWriteLockedFile(tempIndexFilePath, GENERIC_WRITE, true);
// Populate temp index file.
Msix::MsixInfo packageInfo(packageLocation);
packageInfo.WriteToFileHandle(s_PreIndexedPackageSourceFactory_IndexFilePath, tempIndexFile.GetFileHandle(), progress);
if (progress.IsCancelledBy(CancelReason::Any))
{
AICLI_LOG(Repo, Info, << "Cancelling open upon request");
return {};
}
SQLiteIndex index = SQLiteIndex::Open(tempIndexFile.GetFilePath().u8string(), SQLiteIndex::OpenDisposition::Immutable, std::move(tempIndexFile));
// We didn't use to store the source identifier, so we compute it here in case it's
// missing from the details.
m_details.Identifier = GetPackageFamilyNameFromDetails(m_details);
return std::make_shared<SQLiteIndexSource>(m_details, std::move(index), false, true);
}
private:
SourceDetails m_details;
};
// Source factory for running outside of a package.
struct DesktopContextFactory : public PreIndexedFactoryBase
{
std::shared_ptr<ISourceReference> CreateInternal(const SourceDetails& details) override
{
return std::make_shared<DesktopContextSourceReference>(details);
}
std::optional<Msix::PackageVersion> GetCurrentVersion(const SourceDetails& details) override
{
return DesktopContextGetCurrentVersion(details);
}
bool UpdateInternal(const std::string& packageLocation, const SourceDetails& details, IProgressCallback& progress) override
{
// We will extract the manifest and index files directly to this location
std::filesystem::path packageState = GetStatePathFromDetails(details);
std::filesystem::create_directories(packageState);
std::filesystem::path packagePath = packageState / s_PreIndexedPackageSourceFactory_PackageFileName;
std::filesystem::path tempPackagePath = packagePath.u8string() + ".dnld.msix";
auto removeTempFileOnExit = wil::scope_exit([&]()
{
try
{
std::filesystem::remove(tempPackagePath);
}
catch (...)
{
AICLI_LOG(Repo, Info, << "Failed to remove temp index file at: " << tempPackagePath);
}
});
if (Utility::IsUrlRemote(packageLocation))
{
AppInstaller::Utility::Download(packageLocation, tempPackagePath, AppInstaller::Utility::DownloadType::Index, progress);
}
else
{
std::filesystem::copy(packageLocation, tempPackagePath);
progress.OnProgress(100, 100, ProgressType::Percent);
}
if (progress.IsCancelledBy(CancelReason::Any))
{
AICLI_LOG(Repo, Info, << "Cancelling update upon request");
return false;
}
{
// Extra scope to release the file lock right after trust validation.
Msix::WriteLockedMsixFile tempIndexPackage{ tempPackagePath };
Msix::MsixInfo tempMsixInfo{ tempPackagePath };
// The package should not be a bundle
THROW_HR_IF(APPINSTALLER_CLI_ERROR_PACKAGE_IS_BUNDLE, tempMsixInfo.GetIsBundle());
// Ensure that family name has not changed
THROW_HR_IF(APPINSTALLER_CLI_ERROR_SOURCE_DATA_INTEGRITY_FAILURE,
GetPackageFamilyNameFromDetails(details) != Msix::GetPackageFamilyNameFromFullName(tempMsixInfo.GetPackageFullName()));
if (!s_AllowUnsignedSource && !tempIndexPackage.ValidateTrustInfo(WI_IsFlagSet(details.TrustLevel, SourceTrustLevel::StoreOrigin)))
{
AICLI_LOG(Repo, Error, << "Source update failed. Source package failed trust validation.");
THROW_HR(APPINSTALLER_CLI_ERROR_SOURCE_DATA_INTEGRITY_FAILURE);
}
}
std::filesystem::rename(tempPackagePath, packagePath);
AICLI_LOG(Repo, Info, << "Source update success.");
removeTempFileOnExit.release();
return true;
}
bool RemoveInternal(const SourceDetails& details, IProgressCallback&) override
{
std::filesystem::path packageState = GetStatePathFromDetails(details);
if (!std::filesystem::exists(packageState))
{
AICLI_LOG(Repo, Info, << "No state found for source: " << packageState.u8string());
}
else
{
AICLI_LOG(Repo, Info, << "Removing state found for source: " << packageState.u8string());
std::filesystem::remove_all(packageState);
}
return true;
}
};
}
std::unique_ptr<ISourceFactory> PreIndexedPackageSourceFactory::Create()
{
if (!s_AllowUnsignedSource && Runtime::IsRunningInPackagedContext())
{
return std::make_unique<PackagedContextFactory>();
}
else
{
return std::make_unique<DesktopContextFactory>();
}
}
}