aboutsummaryrefslogtreecommitdiff
path: root/src/burn/engine/detect.cpp
blob: 08f6b57c5452b4fb953adc0a14d0334691707e7b (plain)
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
// 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"

typedef struct _DETECT_AUTHENTICATION_REQUIRED_DATA
{
    BURN_USER_EXPERIENCE* pUX;
    LPCWSTR wzPackageOrContainerId;
} DETECT_AUTHENTICATION_REQUIRED_DATA;

// internal function definitions
static HRESULT WINAPI AuthenticationRequired(
    __in LPVOID pData,
    __in HINTERNET hUrl,
    __in long lHttpCode,
    __out BOOL* pfRetrySend,
    __out BOOL* pfRetry
    );

static HRESULT DetectAtomFeedUpdate(
    __in_z LPCWSTR wzBundleCode,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_UPDATE* pUpdate
    );

static HRESULT DownloadUpdateFeed(
    __in_z LPCWSTR wzBundleCode,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_UPDATE* pUpdate,
    __deref_inout_z LPWSTR* psczTempFile
    );

// function definitions

extern "C" void DetectReset(
    __in BURN_REGISTRATION* pRegistration,
    __in BURN_PACKAGES* pPackages
    )
{
    RelatedBundlesUninitialize(&pRegistration->relatedBundles);
    ReleaseNullStr(pRegistration->sczDetectedProviderKeyBundleCode);
    pRegistration->fDetectedForeignProviderKeyBundleCode = FALSE;
    pRegistration->fSelfRegisteredAsDependent = FALSE;
    pRegistration->fParentRegisteredAsDependent = FALSE;
    pRegistration->fForwardCompatibleBundleExists = FALSE;
    pRegistration->fEligibleForCleanup = FALSE;

    if (pRegistration->rgDependents)
    {
        ReleaseDependencyArray(pRegistration->rgDependents, pRegistration->cDependents);
    }
    pRegistration->rgDependents = NULL;
    pRegistration->cDependents = 0;

    for (DWORD iPackage = 0; iPackage < pPackages->cPackages; ++iPackage)
    {
        BURN_PACKAGE* pPackage = pPackages->rgPackages + iPackage;

        pPackage->currentState = BOOTSTRAPPER_PACKAGE_STATE_UNKNOWN;
        pPackage->cacheRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_UNKNOWN;
        pPackage->installRegistrationState = BURN_PACKAGE_REGISTRATION_STATE_UNKNOWN;

        pPackage->fCached = FALSE;

        if (BURN_PACKAGE_TYPE_MSI == pPackage->type)
        {
            pPackage->Msi.operation = BOOTSTRAPPER_RELATED_OPERATION_NONE;

            for (DWORD iFeature = 0; iFeature < pPackage->Msi.cFeatures; ++iFeature)
            {
                BURN_MSIFEATURE* pFeature = pPackage->Msi.rgFeatures + iFeature;

                pFeature->currentState = BOOTSTRAPPER_FEATURE_STATE_UNKNOWN;
            }

            for (DWORD iSlipstreamMsp = 0; iSlipstreamMsp < pPackage->Msi.cSlipstreamMspPackages; ++iSlipstreamMsp)
            {
                BURN_SLIPSTREAM_MSP* pSlipstreamMsp = pPackage->Msi.rgSlipstreamMsps + iSlipstreamMsp;

                pSlipstreamMsp->dwMsiChainedPatchIndex = BURN_PACKAGE_INVALID_PATCH_INDEX;
            }

            ReleaseNullMem(pPackage->Msi.rgChainedPatches);
            pPackage->Msi.cChainedPatches = 0;
        }
        else if (BURN_PACKAGE_TYPE_MSP == pPackage->type)
        {
            ReleaseNullMem(pPackage->Msp.rgTargetProducts);
            pPackage->Msp.cTargetProductCodes = 0;
        }

        for (DWORD iProvider = 0; iProvider < pPackage->cDependencyProviders; ++iProvider)
        {
            BURN_DEPENDENCY_PROVIDER* pProvider = pPackage->rgDependencyProviders + iProvider;

            pProvider->fExists = FALSE;
            pProvider->fBundleRegisteredAsDependent = FALSE;

            if (pProvider->rgDependents)
            {
                ReleaseDependencyArray(pProvider->rgDependents, pProvider->cDependents);
            }
            pProvider->rgDependents = NULL;
            pProvider->cDependents = 0;
        }

        PackageUninitializeCompatible(&pPackage->compatiblePackage);
    }

    for (DWORD iPatchInfo = 0; iPatchInfo < pPackages->cPatchInfo; ++iPatchInfo)
    {
        MSIPATCHSEQUENCEINFOW* pPatchInfo = pPackages->rgPatchInfo + iPatchInfo;
        pPatchInfo->dwOrder = 0;
        pPatchInfo->uStatus = 0;
    }
}

extern "C" HRESULT DetectForwardCompatibleBundles(
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_REGISTRATION* pRegistration
    )
{
    HRESULT hr = S_OK;
    int nCompareResult = 0;

    if (pRegistration->fDetectedForeignProviderKeyBundleCode)
    {
        for (DWORD iRelatedBundle = 0; iRelatedBundle < pRegistration->relatedBundles.cRelatedBundles; ++iRelatedBundle)
        {
            BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgRelatedBundles + iRelatedBundle;

            if (BOOTSTRAPPER_RELATION_UPGRADE == pRelatedBundle->detectRelationType &&
                CSTR_EQUAL == ::CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, pRegistration->sczDetectedProviderKeyBundleCode, -1, pRelatedBundle->package.sczId, -1))
            {
                hr = VerCompareParsedVersions(pRegistration->pVersion, pRelatedBundle->pVersion, &nCompareResult);
                ExitOnFailure(hr, "Failed to compare bundle version '%ls' to related bundle version '%ls'", pRegistration->pVersion->sczVersion, pRelatedBundle->pVersion->sczVersion);

                if (nCompareResult <= 0)
                {
                    if (pRelatedBundle->fPlannable)
                    {
                        pRelatedBundle->fForwardCompatible = TRUE;
                        pRegistration->fForwardCompatibleBundleExists = TRUE;
                    }

                    hr = BACallbackOnDetectForwardCompatibleBundle(pUX, pRelatedBundle->package.sczId, pRelatedBundle->detectRelationType, pRelatedBundle->sczTag, pRelatedBundle->package.fPerMachine, pRelatedBundle->pVersion, !pRelatedBundle->package.fCached);
                    ExitOnRootFailure(hr, "BA aborted detect forward compatible bundle.");

                    LogId(REPORT_STANDARD, MSG_DETECTED_FORWARD_COMPATIBLE_BUNDLE, pRelatedBundle->package.sczId, LoggingRelationTypeToString(pRelatedBundle->detectRelationType), LoggingPerMachineToString(pRelatedBundle->package.fPerMachine), pRelatedBundle->pVersion->sczVersion, LoggingBoolToString(pRelatedBundle->package.fCached));
                }
            }
        }
    }

LExit:
    return hr;
}

extern "C" HRESULT DetectReportRelatedBundles(
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_REGISTRATION* pRegistration,
    __in BOOTSTRAPPER_RELATION_TYPE relationType,
    __out BOOL* pfEligibleForCleanup
    )
{
    HRESULT hr = S_OK;
    BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE planRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_NONE;
    BOOTSTRAPPER_REQUEST_STATE uninstallRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;
    *pfEligibleForCleanup = BOOTSTRAPPER_REGISTRATION_TYPE_NONE != pRegistration->detectedRegistrationType || pRegistration->fCached;

    for (DWORD iRelatedBundle = 0; iRelatedBundle < pRegistration->relatedBundles.cRelatedBundles; ++iRelatedBundle)
    {
        const BURN_RELATED_BUNDLE* pRelatedBundle = pRegistration->relatedBundles.rgRelatedBundles + iRelatedBundle;

        LogId(REPORT_STANDARD, MSG_DETECTED_RELATED_BUNDLE, pRelatedBundle->package.sczId, LoggingRelationTypeToString(pRelatedBundle->detectRelationType), LoggingPerMachineToString(pRelatedBundle->package.fPerMachine), pRelatedBundle->pVersion->sczVersion, LoggingBoolToString(pRelatedBundle->package.fCached));

        hr = BACallbackOnDetectRelatedBundle(pUX, pRelatedBundle->package.sczId, pRelatedBundle->detectRelationType, pRelatedBundle->sczTag, pRelatedBundle->package.fPerMachine, pRelatedBundle->pVersion, !pRelatedBundle->package.fCached);
        ExitOnRootFailure(hr, "BA aborted detect related bundle.");

        // For now, if any related bundles will be executed during uninstall by default then never automatically clean up the bundle.
        if (*pfEligibleForCleanup && pRelatedBundle->fPlannable)
        {
            planRelationType = BOOTSTRAPPER_RELATED_BUNDLE_PLAN_TYPE_NONE;
            uninstallRequestState = BOOTSTRAPPER_REQUEST_STATE_NONE;

            hr = PlanDefaultRelatedBundlePlanType(pRelatedBundle->detectRelationType, pRegistration->pVersion, pRelatedBundle->pVersion, &planRelationType);
            ExitOnFailure(hr, "Failed to get the default plan type for related bundle for calculating fEligibleForCleanup");

            hr = PlanDefaultRelatedBundleRequestState(relationType, planRelationType, BOOTSTRAPPER_ACTION_UNINSTALL, &uninstallRequestState);
            ExitOnFailure(hr, "Failed to get the default request state for related bundle for calculating fEligibleForCleanup");

            if (BOOTSTRAPPER_REQUEST_STATE_NONE != uninstallRequestState)
            {
                *pfEligibleForCleanup = FALSE;
            }
        }
    }

LExit:
    return hr;
}

extern "C" HRESULT DetectUpdate(
    __in_z LPCWSTR wzBundleCode,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_UPDATE* pUpdate
    )
{
    HRESULT hr = S_OK;
    BOOL fBeginCalled = FALSE;
    BOOL fSkip = TRUE;
    BOOL fIgnoreError = FALSE;
    LPWSTR sczOriginalSource = NULL;

    // If no update source was specified, skip update detection.
    if (!pUpdate->sczUpdateSource || !*pUpdate->sczUpdateSource)
    {
        ExitFunction();
    }

    fBeginCalled = TRUE;

    hr = StrAllocString(&sczOriginalSource, pUpdate->sczUpdateSource, 0);
    ExitOnFailure(hr, "Failed to duplicate update feed source.");

    hr = BACallbackOnDetectUpdateBegin(pUX, sczOriginalSource, &fSkip);
    ExitOnRootFailure(hr, "BA aborted detect update begin.");

    if (!fSkip)
    {
        hr = DetectAtomFeedUpdate(wzBundleCode, pUX, pUpdate);
        ExitOnFailure(hr, "Failed to detect atom feed update.");
    }

LExit:
    ReleaseStr(sczOriginalSource);

    if (fBeginCalled)
    {
        BACallbackOnDetectUpdateComplete(pUX, hr, &fIgnoreError);
        if (fIgnoreError)
        {
            hr = S_OK;
        }
    }

    return hr;
}

static HRESULT WINAPI AuthenticationRequired(
    __in LPVOID pData,
    __in HINTERNET hUrl,
    __in long lHttpCode,
    __out BOOL* pfRetrySend,
    __out BOOL* pfRetry
    )
{
    Assert(401 == lHttpCode || 407 == lHttpCode);

    HRESULT hr = S_OK;
    DWORD er = ERROR_SUCCESS;
    BOOTSTRAPPER_ERROR_TYPE errorType = (401 == lHttpCode) ? BOOTSTRAPPER_ERROR_TYPE_HTTP_AUTH_SERVER : BOOTSTRAPPER_ERROR_TYPE_HTTP_AUTH_PROXY;
    LPWSTR sczError = NULL;
    DETECT_AUTHENTICATION_REQUIRED_DATA* pAuthenticationData = reinterpret_cast<DETECT_AUTHENTICATION_REQUIRED_DATA*>(pData);
    int nResult = IDNOACTION;

    *pfRetrySend = FALSE;
    *pfRetry = FALSE;

    hr = StrAllocFromError(&sczError, HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED), NULL);
    ExitOnFailure(hr, "Failed to allocation error string.");

    BACallbackOnError(pAuthenticationData->pUX, errorType, pAuthenticationData->wzPackageOrContainerId, ERROR_ACCESS_DENIED, sczError, MB_RETRYCANCEL, 0, NULL, &nResult); // ignore return value.
    nResult = BootstrapperApplicationCheckExecuteResult(pAuthenticationData->pUX, FALSE, BURN_MB_RETRYTRYAGAIN, nResult);
    if (IDTRYAGAIN == nResult && pAuthenticationData->pUX->hwndDetect)
    {
        er = ::InternetErrorDlg(pAuthenticationData->pUX->hwndDetect, hUrl, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, NULL);
        if (ERROR_SUCCESS == er || ERROR_CANCELLED == er)
        {
            hr = HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT);
        }
        else if (ERROR_INTERNET_FORCE_RETRY == er)
        {
            *pfRetrySend = TRUE;
            hr = S_OK;
        }
        else
        {
            hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
        }
    }
    else if (IDRETRY == nResult)
    {
        *pfRetry = TRUE;
        hr = S_OK;
    }
    else
    {
        hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
    }

LExit:
    ReleaseStr(sczError);

    return hr;
}

static HRESULT DownloadUpdateFeed(
    __in_z LPCWSTR wzBundleCode,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_UPDATE* pUpdate,
    __deref_inout_z LPWSTR* psczTempFile
    )
{
    HRESULT hr = S_OK;
    DOWNLOAD_SOURCE downloadSource = { };
    DOWNLOAD_CACHE_CALLBACK cacheCallback = { };
    DOWNLOAD_AUTHENTICATION_CALLBACK authenticationCallback = { };
    DETECT_AUTHENTICATION_REQUIRED_DATA authenticationData = { };
    LPWSTR sczUpdateId = NULL;
    LPWSTR sczError = NULL;
    DWORD64 qwDownloadSize = 0;

    // Always do our work in the working folder, even if cached.
    hr = PathCreateTimeBasedTempFile(NULL, L"UpdateFeed", NULL, L"xml", psczTempFile, NULL);
    ExitOnFailure(hr, "Failed to create UpdateFeed based on current system time.");

    // Do we need a means of the BA to pass in a user name and password? If so, we should copy it to downloadSource here
    hr = StrAllocString(&downloadSource.sczUrl, pUpdate->sczUpdateSource, 0);
    ExitOnFailure(hr, "Failed to copy update url.");

    cacheCallback.pfnProgress = NULL; //UpdateProgressRoutine;
    cacheCallback.pfnCancel = NULL; // TODO: set this
    cacheCallback.pv = NULL; //pProgress;

    authenticationData.pUX = pUX;
    authenticationData.wzPackageOrContainerId = wzBundleCode;

    authenticationCallback.pv =  static_cast<LPVOID>(&authenticationData);
    authenticationCallback.pfnAuthenticate = &AuthenticationRequired;

    hr = DownloadUrl(&downloadSource, qwDownloadSize, *psczTempFile, &cacheCallback, &authenticationCallback);
    ExitOnFailure(hr, "Failed attempt to download update feed from URL: '%ls' to: '%ls'", downloadSource.sczUrl, *psczTempFile);

LExit:
    if (FAILED(hr))
    {
        if (*psczTempFile)
        {
            FileEnsureDelete(*psczTempFile);
        }

        ReleaseNullStr(*psczTempFile);
    }

    ReleaseStr(downloadSource.sczUrl);
    ReleaseStr(downloadSource.sczUser);
    ReleaseStr(downloadSource.sczPassword);
    ReleaseStr(downloadSource.sczAuthorizationHeader);
    ReleaseStr(sczUpdateId);
    ReleaseStr(sczError);
    return hr;
}


static HRESULT DetectAtomFeedUpdate(
    __in_z LPCWSTR wzBundleCode,
    __in BURN_USER_EXPERIENCE* pUX,
    __in BURN_UPDATE* pUpdate
    )
{
    Assert(pUpdate && pUpdate->sczUpdateSource && *pUpdate->sczUpdateSource);
#ifdef DEBUG
    LogStringLine(REPORT_STANDARD, "DetectAtomFeedUpdate() - update location: %ls", pUpdate->sczUpdateSource);
#endif


    HRESULT hr = S_OK;
    LPWSTR sczUpdateFeedTempFile = NULL;
    ATOM_FEED* pAtomFeed = NULL;
    APPLICATION_UPDATE_CHAIN* pApupChain = NULL;
    BOOL fStopProcessingUpdates = FALSE;
    LPWSTR sczHash = NULL;

    hr = AtomInitialize();
    ExitOnFailure(hr, "Failed to initialize Atom.");

    hr = DownloadUpdateFeed(wzBundleCode, pUX, pUpdate, &sczUpdateFeedTempFile);
    ExitOnFailure(hr, "Failed to download update feed.");

    hr = AtomParseFromFile(sczUpdateFeedTempFile, &pAtomFeed);
    ExitOnFailure(hr, "Failed to parse update atom feed: %ls.", sczUpdateFeedTempFile);

    hr = ApupAllocChainFromAtom(pAtomFeed, &pApupChain);
    ExitOnFailure(hr, "Failed to allocate update chain from atom feed.");

    if (0 < pApupChain->cEntries)
    {
        for (DWORD i = 0; i < pApupChain->cEntries; ++i)
        {
            APPLICATION_UPDATE_ENTRY* pAppUpdateEntry = &pApupChain->rgEntries[i];
            APPLICATION_UPDATE_ENCLOSURE* pEnclosure = pAppUpdateEntry->rgEnclosures;
            LPCWSTR wzHash = L"";
            BOOTSTRAPPER_UPDATE_HASH_TYPE hashType = BOOTSTRAPPER_UPDATE_HASH_TYPE_NONE;

            if (pEnclosure && pEnclosure->rgbDigest && APUP_HASH_ALGORITHM_SHA512 == pEnclosure->digestAlgorithm)
            {
                hr = StrAllocHexEncode(pEnclosure->rgbDigest, pEnclosure->cbDigest, &sczHash);
                ExitOnFailure(hr, "Failed to encode hash as string.");

                wzHash = sczHash;
                hashType = BOOTSTRAPPER_UPDATE_HASH_TYPE_SHA512;
            }

            hr = BACallbackOnDetectUpdate(pUX,
                pEnclosure ? pEnclosure->wzUrl : NULL,
                pEnclosure ? pEnclosure->dw64Size : 0,
                wzHash,
                hashType,
                pAppUpdateEntry->pVersion,
                pAppUpdateEntry->wzTitle,
                pAppUpdateEntry->wzSummary,
                pAppUpdateEntry->wzContentType,
                pAppUpdateEntry->wzContent,
                &fStopProcessingUpdates);
            ExitOnRootFailure(hr, "BA aborted detect update.");

            if (fStopProcessingUpdates)
            {
                break;
            }
        }
    }

LExit:
    if (sczUpdateFeedTempFile && *sczUpdateFeedTempFile)
    {
        FileEnsureDelete(sczUpdateFeedTempFile);
    }

    ApupFreeChain(pApupChain);
    AtomFreeFeed(pAtomFeed);
    ReleaseStr(sczUpdateFeedTempFile);
    ReleaseStr(sczHash);
    AtomUninitialize();

    return hr;
}