-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathMSStore.cpp
More file actions
437 lines (376 loc) · 17.4 KB
/
MSStore.cpp
File metadata and controls
437 lines (376 loc) · 17.4 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include <winget/MSStore.h>
#include <winget/ManifestCommon.h>
#include <winget/Runtime.h>
#include <AppInstallerFileLogger.h>
#include <AppInstallerErrors.h>
#include <winrt/Windows.ApplicationModel.h>
namespace AppInstaller::MSStore
{
using namespace std::string_view_literals;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Windows::ApplicationModel::Store::Preview::InstallControl;
namespace
{
// The type of entitlement we were able to acquire/ensure.
enum class EntitlementType
{
None,
User,
Device,
};
EntitlementType EnsureFreeEntitlement(const std::wstring& productId, Manifest::ScopeEnum scope)
{
AppInstallManager installManager;
AICLI_LOG(Core, Info, << "Getting entitlement for ProductId: " << Utility::ConvertToUTF8(productId));
// Verifying/Acquiring product ownership
GetEntitlementResult entitlementResult{ nullptr };
EntitlementType result = EntitlementType::None;
if (scope == Manifest::ScopeEnum::Machine)
{
AICLI_LOG(Core, Info, << "Get device entitlement (machine scope install).");
result = EntitlementType::Device;
try
{
entitlementResult = installManager.GetFreeDeviceEntitlementAsync(productId, winrt::hstring(), winrt::hstring()).get();
}
CATCH_LOG();
}
else
{
AICLI_LOG(Core, Info, << "Get user entitlement.");
result = EntitlementType::User;
try
{
entitlementResult = installManager.GetFreeUserEntitlementAsync(productId, winrt::hstring(), winrt::hstring()).get();
}
CATCH_LOG();
if (!entitlementResult || entitlementResult.Status() == GetEntitlementStatus::NoStoreAccount)
{
AICLI_LOG(Core, Info, << "Get device entitlement (no store account).");
result = EntitlementType::Device;
try
{
entitlementResult = installManager.GetFreeDeviceEntitlementAsync(productId, winrt::hstring(), winrt::hstring()).get();
}
CATCH_LOG();
}
}
if (entitlementResult && entitlementResult.Status() == GetEntitlementStatus::Succeeded)
{
AICLI_LOG(Core, Info, << "Get entitlement succeeded.");
}
else if (entitlementResult)
{
result = EntitlementType::None;
if (entitlementResult.Status() == GetEntitlementStatus::NetworkError)
{
AICLI_LOG(Core, Error, << "Get entitlement failed. Network error.");
}
else if (entitlementResult.Status() == GetEntitlementStatus::ServerError)
{
AICLI_LOG(Core, Error, << "Get entitlement failed. Server error.");
}
else
{
AICLI_LOG(Core, Error, << "Get entitlement failed. Unknown status: " << static_cast<int32_t>(entitlementResult.Status()));
}
}
else
{
result = EntitlementType::None;
AICLI_LOG(Core, Error, << "Get entitlement failed. Exception.");
}
return result;
}
enum class CheckExistingItemResult
{
None,
Restart,
Cancel,
};
CheckExistingItemResult CheckRestartOrCancelForPossibleExistingOperation(const IVectorView<AppInstallItem>& installItems)
{
CheckExistingItemResult result = CheckExistingItemResult::None;
for (auto const& installItem : installItems)
{
const auto& status = installItem.GetCurrentStatus();
switch (status.InstallState())
{
case AppInstallState::Canceled:
case AppInstallState::Error:
// For these states, always do a cancel;
result = CheckExistingItemResult::Cancel;
return result;
case AppInstallState::Paused:
case AppInstallState::PausedLowBattery:
case AppInstallState::PausedWiFiRecommended:
case AppInstallState::PausedWiFiRequired:
case AppInstallState::ReadyToDownload:
// For these states, set result to restart and continue the loop to see if future items need cancel.
result = CheckExistingItemResult::Restart;
break;
}
}
return result;
}
bool DoesInstallItemsContainProduct(const IVectorView<AppInstallItem>& installItems, std::wstring_view productId)
{
for (auto const& installItem : installItems)
{
if (Utility::CaseInsensitiveEquals(installItem.ProductId(), productId))
{
return true;
}
}
return false;
}
// Returns true if Restart or Cancel happened. False otherwise.
HRESULT RestartOrCancelExistingOperationIfNecessary(const IVectorView<AppInstallItem>& installItems, AppInstallManager& installManager, std::wstring_view productId)
{
auto existingItemResult = CheckRestartOrCancelForPossibleExistingOperation(installItems);
if (existingItemResult == CheckExistingItemResult::Cancel || existingItemResult == CheckExistingItemResult::Restart)
{
if (existingItemResult == CheckExistingItemResult::Cancel)
{
installManager.Cancel(productId);
// Wait for at most 10 seconds for install item to be removed from queue.
for (int i = 0; i < 50; ++i)
{
Sleep(200);
if (!DoesInstallItemsContainProduct(installManager.AppInstallItems(), productId))
{
return S_OK;
}
}
RETURN_HR(HRESULT_FROM_WIN32(ERROR_TIMEOUT));
}
else
{
installManager.Restart(productId);
return S_OK;
}
}
return S_FALSE;
}
// Used to detect a signal that a package update is being requested so that we can early out
// on an attempt to update ourself. This is only needed for elevated processes because the
// standard shutdown signals are not sent to elevated processes in the same manner.
struct PackageUpdateMonitor
{
PackageUpdateMonitor()
{
if (Runtime::IsRunningAsAdmin() && Runtime::IsRunningInPackagedContext())
{
m_catalog = winrt::Windows::ApplicationModel::PackageCatalog::OpenForCurrentPackage();
m_updatingEvent = m_catalog.PackageUpdating(
winrt::auto_revoke, [this](winrt::Windows::ApplicationModel::PackageCatalog, winrt::Windows::ApplicationModel::PackageUpdatingEventArgs args)
{
// Deployment always sends a value of 0 before doing any work and a value of 100 when completely done.
constexpr double minProgress = 0;
auto progress = args.Progress();
if (progress > minProgress)
{
m_isUpdating = true;
}
});
}
}
bool IsUpdating() const
{
return m_isUpdating;
}
private:
winrt::Windows::ApplicationModel::PackageCatalog m_catalog = nullptr;
decltype(winrt::Windows::ApplicationModel::PackageCatalog{ nullptr }.PackageUpdating(winrt::auto_revoke, nullptr)) m_updatingEvent;
std::atomic_bool m_isUpdating = false;
};
HRESULT WaitForOperation(const std::wstring& productId, bool isSilentMode, IVectorView<AppInstallItem>& installItems, IProgressCallback& progress, const PackageUpdateMonitor& monitor)
{
auto cancelIfOperationFailed = wil::scope_exit(
[&]()
{
try
{
AppInstallManager installManager;
installManager.Cancel(productId);
}
CATCH_LOG();
});
for (auto const& installItem : installItems)
{
AICLI_LOG(Core, Info, <<
"Started MSStore package execution. ProductId: " << Utility::ConvertToUTF8(installItem.ProductId()) <<
" PackageFamilyName: " << Utility::ConvertToUTF8(installItem.PackageFamilyName()));
if (isSilentMode)
{
installItem.InstallInProgressToastNotificationMode(AppInstallationToastNotificationMode::NoToast);
installItem.CompletedInstallToastNotificationMode(AppInstallationToastNotificationMode::NoToast);
}
}
HRESULT errorCode = S_OK;
// We are aggregating all AppInstallItem progresses into one.
// Averaging every progress for now until we have a better way to find overall progress.
uint64_t overallProgressMax = 100 * static_cast<uint64_t>(installItems.Size());
uint64_t currentProgress = 0;
while (currentProgress < overallProgressMax)
{
currentProgress = 0;
for (auto const& installItem : installItems)
{
const auto& status = installItem.GetCurrentStatus();
currentProgress += static_cast<uint64_t>(status.PercentComplete());
errorCode = status.ErrorCode();
if (!SUCCEEDED(errorCode))
{
return errorCode;
}
}
// It may take a while for Store client to pick up the install request.
// So we show indefinite progress here to avoid a progress bar stuck at 0.
if (currentProgress > 0)
{
progress.OnProgress(currentProgress, overallProgressMax, ProgressType::Percent);
}
if (progress.IsCancelledBy(CancelReason::User))
{
for (auto const& installItem : installItems)
{
installItem.Cancel();
}
}
// If app shutdown then we have 30s to keep installing, keep going and hope for the best.
else if (progress.IsCancelledBy(CancelReason::AppShutdown) || monitor.IsUpdating())
{
for (auto const& installItem : installItems)
{
// Insert spiderman meme.
if (installItem.ProductId() == std::wstring{ s_AppInstallerProductId })
{
AICLI_LOG(Core, Info, << "Asked to shutdown while installing AppInstaller.");
progress.OnProgress(overallProgressMax, overallProgressMax, ProgressType::Percent);
cancelIfOperationFailed.release();
return S_OK;
}
}
}
Sleep(100);
}
if (SUCCEEDED(errorCode))
{
cancelIfOperationFailed.release();
}
return errorCode;
}
}
HRESULT MSStoreOperation::StartAndWaitForOperation(IProgressCallback& progress)
{
// Best effort verifying/acquiring product ownership.
std::ignore = EnsureFreeEntitlement(m_productId, m_scope);
if (m_type == MSStoreOperationType::Update)
{
return UpdatePackage(progress);
}
else
{
return InstallPackage(progress);
}
}
HRESULT MSStoreOperation::InstallPackage(IProgressCallback& progress)
{
PackageUpdateMonitor monitor;
AppInstallManager installManager;
AppInstallOptions installOptions;
installOptions.AllowForcedAppRestart(m_force);
if (m_isSilentMode)
{
installOptions.InstallInProgressToastNotificationMode(AppInstallationToastNotificationMode::NoToast);
installOptions.CompletedInstallToastNotificationMode(AppInstallationToastNotificationMode::NoToast);
}
if (m_type == MSStoreOperationType::Repair)
{
// Attempt to repair the installation of an app that is already installed.
installOptions.Repair(true);
}
if (m_scope == Manifest::ScopeEnum::Machine)
{
// TODO: There was a bug in InstallService where admin user is incorrectly identified as not admin,
// causing false access denied on many OS versions.
// Remove this check when the OS bug is fixed and back ported.
if (!Runtime::IsRunningAsSystem())
{
AICLI_LOG(Core, Error, << "Device wide install for msstore type is not supported under admin context.");
return APPINSTALLER_CLI_ERROR_INSTALL_SYSTEM_NOT_SUPPORTED;
}
installOptions.InstallForAllUsers(true);
}
IVectorView<AppInstallItem> installItems = installManager.StartProductInstallAsync(
m_productId, // ProductId
winrt::hstring(), // FlightId
L"WinGetCli", // ClientId
winrt::hstring(),
installOptions).get();
// Check if we need to restart or cancel existing items.
auto restartOrCancelResult = RestartOrCancelExistingOperationIfNecessary(installItems, installManager, m_productId);
RETURN_IF_FAILED(restartOrCancelResult);
// If restart or cancel happened, try again.
if (restartOrCancelResult == S_OK)
{
// Try again
installItems = installManager.StartProductInstallAsync(
m_productId, // ProductId
winrt::hstring(), // FlightId
L"WinGetCli", // ClientId
winrt::hstring(),
installOptions).get();
}
return WaitForOperation(m_productId, m_isSilentMode, installItems, progress, monitor);
}
HRESULT MSStoreOperation::UpdatePackage(IProgressCallback& progress)
{
PackageUpdateMonitor monitor;
AppInstallManager installManager;
AppUpdateOptions updateOptions;
updateOptions.AllowForcedAppRestart(m_force);
// SearchForUpdateAsync will automatically trigger update if found.
AppInstallItem installItem = installManager.SearchForUpdatesAsync(
m_productId, // ProductId
winrt::hstring(), // SkuId
winrt::hstring(),
winrt::hstring(), // ClientId
updateOptions
).get();
if (!installItem)
{
return APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE;
}
std::vector<AppInstallItem> installItemVector{ installItem };
IVectorView<AppInstallItem> installItems = winrt::single_threaded_vector(std::move(installItemVector)).GetView();
// Check if we need to restart or cancel existing items.
auto restartOrCancelResult = RestartOrCancelExistingOperationIfNecessary(installItems, installManager, m_productId);
RETURN_IF_FAILED(restartOrCancelResult);
// If restart or cancel happened, try again.
if (restartOrCancelResult == S_OK)
{
// Try again
installItem = installManager.SearchForUpdatesAsync(
m_productId, // ProductId
winrt::hstring(), // SkuId
winrt::hstring(),
winrt::hstring(), // ClientId
updateOptions
).get();
if (!installItem)
{
return APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE;
}
installItemVector.clear();
installItemVector.emplace_back(installItem);
installItems = winrt::single_threaded_vector(std::move(installItemVector)).GetView();
}
return WaitForOperation(m_productId, m_isSilentMode, installItems, progress, monitor);
}
}