appsearch.c 34.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Implementation of the AppSearch action of the Microsoft Installer (msi.dll)
 *
 * Copyright 2005 Juan Lang
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21 22 23 24 25
 */
#include <stdarg.h>

#define COBJMACROS

#include "windef.h"
#include "winbase.h"
26
#include "winreg.h"
27 28
#include "msi.h"
#include "msiquery.h"
29
#include "msidefs.h"
30
#include "winver.h"
31
#include "shlwapi.h"
32 33 34 35 36 37 38 39
#include "wine/unicode.h"
#include "wine/debug.h"
#include "msipriv.h"

WINE_DEFAULT_DEBUG_CHANNEL(msi);

typedef struct tagMSISIGNATURE
{
40
    LPCWSTR  Name;     /* NOT owned by this structure */
41 42 43 44 45 46 47 48 49 50 51 52
    LPWSTR   File;
    DWORD    MinVersionMS;
    DWORD    MinVersionLS;
    DWORD    MaxVersionMS;
    DWORD    MaxVersionLS;
    DWORD    MinSize;
    DWORD    MaxSize;
    FILETIME MinTime;
    FILETIME MaxTime;
    LPWSTR   Languages;
}MSISIGNATURE;

53
void msi_parse_version_string(LPCWSTR verStr, PDWORD ms, PDWORD ls)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
{
    const WCHAR *ptr;
    int x1 = 0, x2 = 0, x3 = 0, x4 = 0;

    x1 = atoiW(verStr);
    ptr = strchrW(verStr, '.');
    if (ptr)
    {
        x2 = atoiW(ptr + 1);
        ptr = strchrW(ptr + 1, '.');
    }
    if (ptr)
    {
        x3 = atoiW(ptr + 1);
        ptr = strchrW(ptr + 1, '.');
    }
    if (ptr)
        x4 = atoiW(ptr + 1);
    /* FIXME: byte-order dependent? */
    *ms = x1 << 16 | x2;
74
    if (ls) *ls = x3 << 16 | x4;
75 76
}

77
/* Fills in sig with the values from the Signature table, where name is the
78 79 80 81 82 83
 * signature to find.  Upon return, sig->File will be NULL if the record is not
 * found, and not NULL if it is found.
 * Warning: clears all fields in sig!
 * Returns ERROR_SUCCESS upon success (where not finding the record counts as
 * success), something else on error.
 */
84
static UINT ACTION_AppSearchGetSignature(MSIPACKAGE *package, MSISIGNATURE *sig, LPCWSTR name)
85
{
86 87 88 89 90 91
    static const WCHAR query[] = {
        's','e','l','e','c','t',' ','*',' ',
        'f','r','o','m',' ',
        'S','i','g','n','a','t','u','r','e',' ',
        'w','h','e','r','e',' ','S','i','g','n','a','t','u','r','e',' ','=',' ',
        '\'','%','s','\'',0};
92
    LPWSTR minVersion, maxVersion, p;
93 94 95 96
    MSIRECORD *row;
    DWORD time;

    TRACE("package %p, sig %p\n", package, sig);
97 98

    memset(sig, 0, sizeof(*sig));
99
    sig->Name = name;
100 101
    row = MSI_QueryGetRecord( package->db, query, name );
    if (!row)
102
    {
103 104 105
        TRACE("failed to query signature for %s\n", debugstr_w(name));
        return ERROR_SUCCESS;
    }
106

107 108
    /* get properties */
    sig->File = msi_dup_record_field(row,2);
109 110 111 112 113 114
    if ((p = strchrW(sig->File, '|')))
    {
        p++;
        memmove(sig->File, p, (strlenW(p) + 1) * sizeof(WCHAR));
    }

115 116 117
    minVersion = msi_dup_record_field(row,3);
    if (minVersion)
    {
118
        msi_parse_version_string( minVersion, &sig->MinVersionMS, &sig->MinVersionLS );
119
        msi_free( minVersion );
120
    }
121 122
    maxVersion = msi_dup_record_field(row,4);
    if (maxVersion)
123
    {
124
        msi_parse_version_string( maxVersion, &sig->MaxVersionMS, &sig->MaxVersionLS );
125
        msi_free( maxVersion );
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
    sig->MinSize = MSI_RecordGetInteger(row,5);
    if (sig->MinSize == MSI_NULL_INTEGER)
        sig->MinSize = 0;
    sig->MaxSize = MSI_RecordGetInteger(row,6);
    if (sig->MaxSize == MSI_NULL_INTEGER)
        sig->MaxSize = 0;
    sig->Languages = msi_dup_record_field(row,9);
    time = MSI_RecordGetInteger(row,7);
    if (time != MSI_NULL_INTEGER)
        DosDateTimeToFileTime(HIWORD(time), LOWORD(time), &sig->MinTime);
    time = MSI_RecordGetInteger(row,8);
    if (time != MSI_NULL_INTEGER)
        DosDateTimeToFileTime(HIWORD(time), LOWORD(time), &sig->MaxTime);

    TRACE("Found file name %s for Signature_ %s;\n",
          debugstr_w(sig->File), debugstr_w(name));
    TRACE("MinVersion is %d.%d.%d.%d\n", HIWORD(sig->MinVersionMS),
          LOWORD(sig->MinVersionMS), HIWORD(sig->MinVersionLS),
          LOWORD(sig->MinVersionLS));
    TRACE("MaxVersion is %d.%d.%d.%d\n", HIWORD(sig->MaxVersionMS),
          LOWORD(sig->MaxVersionMS), HIWORD(sig->MaxVersionLS),
          LOWORD(sig->MaxVersionLS));
    TRACE("MinSize is %d, MaxSize is %d;\n", sig->MinSize, sig->MaxSize);
    TRACE("Languages is %s\n", debugstr_w(sig->Languages));

    msiobj_release( &row->hdr );
153

154
    return ERROR_SUCCESS;
155 156
}

157 158 159 160 161 162 163
/* Frees any memory allocated in sig */
static void ACTION_FreeSignature(MSISIGNATURE *sig)
{
    msi_free(sig->File);
    msi_free(sig->Languages);
}

164 165 166 167 168 169 170
static LPWSTR app_search_file(LPWSTR path, MSISIGNATURE *sig)
{
    VS_FIXEDFILEINFO *info;
    DWORD attr, handle, size;
    LPWSTR val = NULL;
    LPBYTE buffer;

171 172 173 174 175 176 177 178 179 180 181 182 183
    if (!sig->File)
    {
        PathRemoveFileSpecW(path);
        PathAddBackslashW(path);

        attr = GetFileAttributesW(path);
        if (attr != INVALID_FILE_ATTRIBUTES &&
            (attr & FILE_ATTRIBUTE_DIRECTORY))
            return strdupW(path);

        return NULL;
    }

184
    attr = GetFileAttributesW(path);
185 186
    if (attr == INVALID_FILE_ATTRIBUTES ||
        (attr & FILE_ATTRIBUTE_DIRECTORY))
187 188 189 190 191 192 193 194 195 196 197 198 199
        return NULL;

    size = GetFileVersionInfoSizeW(path, &handle);
    if (!size)
        return strdupW(path);

    buffer = msi_alloc(size);
    if (!buffer)
        return NULL;

    if (!GetFileVersionInfoW(path, 0, size, buffer))
        goto done;

200
    if (!VerQueryValueW(buffer, szBackSlash, (LPVOID)&info, &size) || !info)
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
        goto done;

    if (sig->MinVersionLS || sig->MinVersionMS)
    {
        if (info->dwFileVersionMS < sig->MinVersionMS)
            goto done;

        if (info->dwFileVersionMS == sig->MinVersionMS &&
            info->dwFileVersionLS < sig->MinVersionLS)
            goto done;
    }

    if (sig->MaxVersionLS || sig->MaxVersionMS)
    {
        if (info->dwFileVersionMS > sig->MaxVersionMS)
            goto done;

        if (info->dwFileVersionMS == sig->MaxVersionMS &&
            info->dwFileVersionLS > sig->MaxVersionLS)
            goto done;
    }

    val = strdupW(path);

done:
    msi_free(buffer);
    return val;
}

230
static UINT ACTION_AppSearchComponents(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
231
{
232
    static const WCHAR query[] =  {
233 234 235 236 237 238 239 240 241
        'S','E','L','E','C','T',' ','*',' ',
        'F','R','O','M',' ',
        '`','C','o','m','p','L','o','c','a','t','o','r','`',' ',
        'W','H','E','R','E',' ','`','S','i','g','n','a','t','u','r','e','_','`',' ','=',' ',
        '\'','%','s','\'',0};
    static const WCHAR sigquery[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','S','i','g','n','a','t','u','r','e','`',' ',
        'W','H','E','R','E',' ','`','S','i','g','n','a','t','u','r','e','`',' ','=',' ',
242
        '\'','%','s','\'',0};
243 244 245 246 247 248 249 250 251 252

    MSIRECORD *row, *rec;
    LPCWSTR signature, guid;
    BOOL sigpresent = TRUE;
    BOOL isdir;
    UINT type;
    WCHAR path[MAX_PATH];
    DWORD size = MAX_PATH;
    LPWSTR ptr;
    DWORD attr;
253 254 255

    TRACE("%s\n", debugstr_w(sig->Name));

256
    *appValue = NULL;
257

258
    row = MSI_QueryGetRecord(package->db, query, sig->Name);
259
    if (!row)
260
    {
261 262
        TRACE("failed to query CompLocator for %s\n", debugstr_w(sig->Name));
        return ERROR_SUCCESS;
263 264
    }

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    signature = MSI_RecordGetString(row, 1);
    guid = MSI_RecordGetString(row, 2);
    type = MSI_RecordGetInteger(row, 3);

    rec = MSI_QueryGetRecord(package->db, sigquery, signature);
    if (!rec)
        sigpresent = FALSE;

    *path = '\0';
    MsiLocateComponentW(guid, path, &size);
    if (!*path)
        goto done;

    attr = GetFileAttributesW(path);
    if (attr == INVALID_FILE_ATTRIBUTES)
        goto done;

    isdir = (attr & FILE_ATTRIBUTE_DIRECTORY);

    if (type != msidbLocatorTypeDirectory && sigpresent && !isdir)
    {
286
        *appValue = app_search_file(path, sig);
287 288 289 290 291 292 293 294 295 296 297 298 299
    }
    else if (!sigpresent && (type != msidbLocatorTypeDirectory || isdir))
    {
        if (type == msidbLocatorTypeFileName)
        {
            ptr = strrchrW(path, '\\');
            *(ptr + 1) = '\0';
        }
        else
            PathAddBackslashW(path);

        *appValue = strdupW(path);
    }
300 301 302 303 304 305
    else if (sigpresent)
    {
        PathAddBackslashW(path);
        lstrcatW(path, MSI_RecordGetString(rec, 2));

        attr = GetFileAttributesW(path);
306 307
        if (attr != INVALID_FILE_ATTRIBUTES &&
            !(attr & FILE_ATTRIBUTE_DIRECTORY))
308 309
            *appValue = strdupW(path);
    }
310

311 312 313
done:
    if (rec) msiobj_release(&rec->hdr);
    msiobj_release(&row->hdr);
314
    return ERROR_SUCCESS;
315 316
}

317 318 319 320
static void ACTION_ConvertRegValue(DWORD regType, const BYTE *value, DWORD sz,
 LPWSTR *appValue)
{
    static const WCHAR dwordFmt[] = { '#','%','d','\0' };
321 322 323
    static const WCHAR binPre[] = { '#','x','\0' };
    static const WCHAR binFmt[] = { '%','0','2','X','\0' };
    LPWSTR ptr;
324 325 326 327 328
    DWORD i;

    switch (regType)
    {
        case REG_SZ:
329
            if (*(LPCWSTR)value == '#')
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
            {
                /* escape leading pound with another */
                *appValue = msi_alloc(sz + sizeof(WCHAR));
                (*appValue)[0] = '#';
                strcpyW(*appValue + 1, (LPCWSTR)value);
            }
            else
            {
                *appValue = msi_alloc(sz);
                strcpyW(*appValue, (LPCWSTR)value);
            }
            break;
        case REG_DWORD:
            /* 7 chars for digits, 1 for NULL, 1 for #, and 1 for sign
             * char if needed
             */
            *appValue = msi_alloc(10 * sizeof(WCHAR));
            sprintfW(*appValue, dwordFmt, *(const DWORD *)value);
            break;
        case REG_EXPAND_SZ:
350 351 352
            sz = ExpandEnvironmentStringsW((LPCWSTR)value, NULL, 0);
            *appValue = msi_alloc(sz * sizeof(WCHAR));
            ExpandEnvironmentStringsW((LPCWSTR)value, *appValue, sz);
353 354
            break;
        case REG_BINARY:
355 356 357 358 359 360
            /* #x<nibbles>\0 */
            *appValue = msi_alloc((sz * 2 + 3) * sizeof(WCHAR));
            lstrcpyW(*appValue, binPre);
            ptr = *appValue + lstrlenW(binPre);
            for (i = 0; i < sz; i++, ptr += 2)
                sprintfW(ptr, binFmt, value[i]);
361 362
            break;
        default:
363
            WARN("unimplemented for values of type %d\n", regType);
364 365 366 367
            *appValue = NULL;
    }
}

368 369 370
static UINT ACTION_SearchDirectory(MSIPACKAGE *package, MSISIGNATURE *sig,
 LPCWSTR path, int depth, LPWSTR *appValue);

371
static UINT ACTION_AppSearchReg(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
372
{
373
    static const WCHAR query[] =  {
374 375
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        'R','e','g','L','o','c','a','t','o','r',' ','W','H','E','R','E',' ',
376
        'S','i','g','n','a','t','u','r','e','_',' ','=',' ', '\'','%','s','\'',0};
377 378
    const WCHAR *keyPath, *valueName;
    WCHAR *deformatted = NULL, *ptr = NULL, *end;
379 380 381 382 383
    int root, type;
    HKEY rootKey, key = NULL;
    DWORD sz = 0, regType;
    LPBYTE value = NULL;
    MSIRECORD *row;
384 385
    UINT rc;

386 387
    TRACE("%s\n", debugstr_w(sig->Name));

388
    *appValue = NULL;
389 390 391

    row = MSI_QueryGetRecord( package->db, query, sig->Name );
    if (!row)
392
    {
393 394 395
        TRACE("failed to query RegLocator for %s\n", debugstr_w(sig->Name));
        return ERROR_SUCCESS;
    }
396

397 398 399 400
    root = MSI_RecordGetInteger(row, 2);
    keyPath = MSI_RecordGetString(row, 3);
    valueName = MSI_RecordGetString(row, 4);
    type = MSI_RecordGetInteger(row, 5);
401

402 403
    deformat_string(package, keyPath, &deformatted);

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    switch (root)
    {
    case msidbRegistryRootClassesRoot:
        rootKey = HKEY_CLASSES_ROOT;
        break;
    case msidbRegistryRootCurrentUser:
        rootKey = HKEY_CURRENT_USER;
        break;
    case msidbRegistryRootLocalMachine:
        rootKey = HKEY_LOCAL_MACHINE;
        break;
    case msidbRegistryRootUsers:
        rootKey = HKEY_USERS;
        break;
    default:
        WARN("Unknown root key %d\n", root);
        goto end;
421
    }
422

423
    rc = RegOpenKeyW(rootKey, deformatted, &key);
424
    if (rc)
425
    {
426 427
        TRACE("RegOpenKeyW returned %d\n", rc);
        goto end;
428 429
    }

430 431 432 433
    msi_free(deformatted);
    deformat_string(package, valueName, &deformatted);

    rc = RegQueryValueExW(key, deformatted, NULL, NULL, NULL, &sz);
434 435 436 437 438 439 440 441 442
    if (rc)
    {
        TRACE("RegQueryValueExW returned %d\n", rc);
        goto end;
    }
    /* FIXME: sanity-check sz before allocating (is there an upper-limit
     * on the value of a property?)
     */
    value = msi_alloc( sz );
443
    rc = RegQueryValueExW(key, deformatted, NULL, &regType, value, &sz);
444 445 446 447 448 449 450 451 452 453
    if (rc)
    {
        TRACE("RegQueryValueExW returned %d\n", rc);
        goto end;
    }

    /* bail out if the registry key is empty */
    if (sz == 0)
        goto end;

454 455 456 457 458 459 460 461 462 463 464 465 466
    /* expand if needed */
    if (regType == REG_EXPAND_SZ)
    {
        sz = ExpandEnvironmentStringsW((LPCWSTR)value, NULL, 0);
        if (sz)
        {
            LPWSTR buf = msi_alloc(sz * sizeof(WCHAR));
            ExpandEnvironmentStringsW((LPCWSTR)value, buf, sz);
            msi_free(value);
            value = (LPBYTE)buf;
        }
    }

467 468
    if ((regType == REG_SZ || regType == REG_EXPAND_SZ) &&
        (ptr = strchrW((LPWSTR)value, '"')) && (end = strchrW(++ptr, '"')))
469 470 471 472
        *end = '\0';
    else
        ptr = (LPWSTR)value;

473 474 475
    switch (type & 0x0f)
    {
    case msidbLocatorTypeDirectory:
476
        ACTION_SearchDirectory(package, sig, ptr, 0, appValue);
477 478
        break;
    case msidbLocatorTypeFileName:
479
        *appValue = app_search_file(ptr, sig);
480 481 482 483 484
        break;
    case msidbLocatorTypeRawValue:
        ACTION_ConvertRegValue(regType, value, sz, appValue);
        break;
    default:
485
        FIXME("unimplemented for type %d (key path %s, value %s)\n",
486 487 488 489 490
              type, debugstr_w(keyPath), debugstr_w(valueName));
    }
end:
    msi_free( value );
    RegCloseKey( key );
491
    msi_free( deformatted );
492 493 494

    msiobj_release(&row->hdr);
    return ERROR_SUCCESS;
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
static LPWSTR get_ini_field(LPWSTR buf, int field)
{
    LPWSTR beg, end;
    int i = 1;

    if (field == 0)
        return strdupW(buf);

    beg = buf;
    while ((end = strchrW(beg, ',')) && i < field)
    {
        beg = end + 1;
        while (*beg && *beg == ' ')
            beg++;

        i++;
    }

    end = strchrW(beg, ',');
    if (!end)
        end = beg + lstrlenW(beg);

    *end = '\0';
    return strdupW(beg);
}

523
static UINT ACTION_AppSearchIni(MSIPACKAGE *package, LPWSTR *appValue,
524 525
 MSISIGNATURE *sig)
{
526 527 528 529 530 531 532 533 534 535
    static const WCHAR query[] =  {
        's','e','l','e','c','t',' ','*',' ',
        'f','r','o','m',' ',
        'I','n','i','L','o','c','a','t','o','r',' ',
        'w','h','e','r','e',' ',
        'S','i','g','n','a','t','u','r','e','_',' ','=',' ','\'','%','s','\'',0};
    MSIRECORD *row;
    LPWSTR fileName, section, key;
    int field, type;
    WCHAR buf[MAX_PATH];
536

537
    TRACE("%s\n", debugstr_w(sig->Name));
538

539
    *appValue = NULL;
540

541 542 543 544 545
    row = MSI_QueryGetRecord( package->db, query, sig->Name );
    if (!row)
    {
        TRACE("failed to query IniLocator for %s\n", debugstr_w(sig->Name));
        return ERROR_SUCCESS;
546
    }
547 548 549 550 551 552 553 554 555 556 557 558 559

    fileName = msi_dup_record_field(row, 2);
    section = msi_dup_record_field(row, 3);
    key = msi_dup_record_field(row, 4);
    field = MSI_RecordGetInteger(row, 5);
    type = MSI_RecordGetInteger(row, 6);
    if (field == MSI_NULL_INTEGER)
        field = 0;
    if (type == MSI_NULL_INTEGER)
        type = 0;

    GetPrivateProfileStringW(section, key, NULL, buf, MAX_PATH, fileName);
    if (buf[0])
560
    {
561 562 563
        switch (type & 0x0f)
        {
        case msidbLocatorTypeDirectory:
564
            ACTION_SearchDirectory(package, sig, buf, 0, appValue);
565 566
            break;
        case msidbLocatorTypeFileName:
567
            *appValue = app_search_file(buf, sig);
568 569
            break;
        case msidbLocatorTypeRawValue:
570
            *appValue = get_ini_field(buf, field);
571 572
            break;
        }
573 574
    }

575 576 577 578 579
    msi_free(fileName);
    msi_free(section);
    msi_free(key);

    msiobj_release(&row->hdr);
580

581
    return ERROR_SUCCESS;
582 583 584 585 586 587 588 589 590 591 592 593 594 595
}

/* Expands the value in src into a path without property names and only
 * containing long path names into dst.  Replaces at most len characters of dst,
 * and always NULL-terminates dst if dst is not NULL and len >= 1.
 * May modify src.
 * Assumes src and dst are non-overlapping.
 * FIXME: return code probably needed:
 * - what does AppSearch return if the table values are invalid?
 * - what if dst is too small?
 */
static void ACTION_ExpandAnyPath(MSIPACKAGE *package, WCHAR *src, WCHAR *dst,
 size_t len)
{
596
    WCHAR *ptr, *deformatted;
597 598

    if (!src || !dst || !len)
599 600
    {
        if (dst) *dst = '\0';
601
        return;
602
    }
603

604 605 606
    dst[0] = '\0';

    /* Ignore the short portion of the path */
607 608 609 610 611
    if ((ptr = strchrW(src, '|')))
        ptr++;
    else
        ptr = src;

612
    deformat_string(package, ptr, &deformatted);
613
    if (!deformatted || strlenW(deformatted) > len - 1)
614 615 616
    {
        msi_free(deformatted);
        return;
617
    }
618 619 620 621

    lstrcpyW(dst, deformatted);
    dst[lstrlenW(deformatted)] = '\0';
    msi_free(deformatted);
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
static LANGID *parse_languages( const WCHAR *languages, DWORD *num_ids )
{
    UINT i, count = 1;
    WCHAR *str = strdupW( languages ), *p, *q;
    LANGID *ret;

    if (!str) return NULL;
    for (p = q = str; (q = strchrW( q, ',' )); q++) count++;

    if (!(ret = msi_alloc( count * sizeof(LANGID) )))
    {
        msi_free( str );
        return NULL;
    }
    i = 0;
    while (*p)
    {
        q = strchrW( p, ',' );
        if (q) *q = 0;
        ret[i] = atoiW( p );
        if (!q) break;
        p = q + 1;
        i++;
    }
    msi_free( str );
    *num_ids = count;
    return ret;
}

static BOOL match_languages( const void *version, const WCHAR *languages )
{
    struct lang
    {
        USHORT id;
        USHORT codepage;
    } *lang;
    DWORD len, num_ids, i, j;
    BOOL found = FALSE;
    LANGID *ids;

    if (!languages || !languages[0]) return TRUE;
    if (!VerQueryValueW( version, szLangResource, (void **)&lang, &len )) return FALSE;
    if (!(ids = parse_languages( languages, &num_ids ))) return FALSE;

    for (i = 0; i < num_ids; i++)
    {
        found = FALSE;
        for (j = 0; j < len / sizeof(struct lang); j++)
        {
            if (!ids[i] || ids[i] == lang[j].id) found = TRUE;
        }
        if (!found) goto done;
    }

done:
    msi_free( ids );
    return found;
}

683 684 685
/* Sets *matches to whether the file (whose path is filePath) matches the
 * versions set in sig.
 * Return ERROR_SUCCESS in case of success (whether or not the file matches),
686
 * something else if an install-halting error occurs.
687
 */
688
static UINT ACTION_FileVersionMatches(const MSISIGNATURE *sig, LPCWSTR filePath,
689 690
 BOOL *matches)
{
691 692 693 694
    UINT len;
    void *version;
    VS_FIXEDFILEINFO *info = NULL;
    DWORD zero, size = GetFileVersionInfoSizeW( filePath, &zero );
695 696 697

    *matches = FALSE;

698 699
    if (!size) return ERROR_SUCCESS;
    if (!(version = msi_alloc( size ))) return ERROR_OUTOFMEMORY;
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    if (GetFileVersionInfoW( filePath, 0, size, version ))
        VerQueryValueW( version, szBackSlash, (void **)&info, &len );

    if (info)
    {
        TRACE("comparing file version %d.%d.%d.%d:\n",
              HIWORD(info->dwFileVersionMS),
              LOWORD(info->dwFileVersionMS),
              HIWORD(info->dwFileVersionLS),
              LOWORD(info->dwFileVersionLS));
        if (info->dwFileVersionMS < sig->MinVersionMS
            || (info->dwFileVersionMS == sig->MinVersionMS &&
                info->dwFileVersionLS < sig->MinVersionLS))
        {
            TRACE("less than minimum version %d.%d.%d.%d\n",
                   HIWORD(sig->MinVersionMS),
                   LOWORD(sig->MinVersionMS),
                   HIWORD(sig->MinVersionLS),
                   LOWORD(sig->MinVersionLS));
720
        }
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
        else if ((sig->MaxVersionMS || sig->MaxVersionLS) &&
                 (info->dwFileVersionMS > sig->MaxVersionMS ||
                  (info->dwFileVersionMS == sig->MaxVersionMS &&
                   info->dwFileVersionLS > sig->MaxVersionLS)))
        {
            TRACE("greater than maximum version %d.%d.%d.%d\n",
                   HIWORD(sig->MaxVersionMS),
                   LOWORD(sig->MaxVersionMS),
                   HIWORD(sig->MaxVersionLS),
                   LOWORD(sig->MaxVersionLS));
        }
        else if (!match_languages( version, sig->Languages ))
        {
            TRACE("languages %s not supported\n", debugstr_w( sig->Languages ));
        }
        else *matches = TRUE;
737
    }
738 739
    msi_free( version );
    return ERROR_SUCCESS;
740 741 742 743 744 745
}

/* Sets *matches to whether the file in findData matches that in sig.
 * fullFilePath is assumed to be the full path of the file specified in
 * findData, which may be necessary to compare the version.
 * Return ERROR_SUCCESS in case of success (whether or not the file matches),
746
 * something else if an install-halting error occurs.
747
 */
748 749
static UINT ACTION_FileMatchesSig(const MSISIGNATURE *sig,
 const WIN32_FIND_DATAW *findData, LPCWSTR fullFilePath, BOOL *matches)
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
{
    UINT rc = ERROR_SUCCESS;

    *matches = TRUE;
    /* assumes the caller has already ensured the filenames match, so check
     * the other fields..
     */
    if (sig->MinTime.dwLowDateTime || sig->MinTime.dwHighDateTime)
    {
        if (findData->ftCreationTime.dwHighDateTime <
         sig->MinTime.dwHighDateTime ||
         (findData->ftCreationTime.dwHighDateTime == sig->MinTime.dwHighDateTime
         && findData->ftCreationTime.dwLowDateTime <
         sig->MinTime.dwLowDateTime))
            *matches = FALSE;
    }
    if (*matches && (sig->MaxTime.dwLowDateTime || sig->MaxTime.dwHighDateTime))
    {
        if (findData->ftCreationTime.dwHighDateTime >
         sig->MaxTime.dwHighDateTime ||
         (findData->ftCreationTime.dwHighDateTime == sig->MaxTime.dwHighDateTime
         && findData->ftCreationTime.dwLowDateTime >
         sig->MaxTime.dwLowDateTime))
            *matches = FALSE;
    }
    if (*matches && sig->MinSize && findData->nFileSizeLow < sig->MinSize)
        *matches = FALSE;
    if (*matches && sig->MaxSize && findData->nFileSizeLow > sig->MaxSize)
        *matches = FALSE;
    if (*matches && (sig->MinVersionMS || sig->MinVersionLS ||
     sig->MaxVersionMS || sig->MaxVersionLS))
781
        rc = ACTION_FileVersionMatches(sig, fullFilePath, matches);
782 783 784 785 786 787 788 789
    return rc;
}

/* Recursively searches the directory dir for files that match the signature
 * sig, up to (depth + 1) levels deep.  That is, if depth is 0, it searches dir
 * (and only dir).  If depth is 1, searches dir and its immediate
 * subdirectories.
 * Assumes sig->File is not NULL.
790 791
 * Returns ERROR_SUCCESS on success (which may include non-critical errors),
 * something else on failures which should halt the install.
792
 */
793
static UINT ACTION_RecurseSearchDirectory(MSIPACKAGE *package, LPWSTR *appValue,
794 795
 MSISIGNATURE *sig, LPCWSTR dir, int depth)
{
796 797
    HANDLE hFind;
    WIN32_FIND_DATAW findData;
798 799
    UINT rc = ERROR_SUCCESS;
    size_t dirLen = lstrlenW(dir), fileLen = lstrlenW(sig->File);
800
    WCHAR subpath[MAX_PATH];
801
    WCHAR *buf;
802
    DWORD len;
803

804 805
    static const WCHAR starDotStarW[] = { '*','.','*',0 };

806
    TRACE("Searching directory %s for file %s, depth %d\n", debugstr_w(dir),
807
          debugstr_w(sig->File), depth);
808 809

    if (depth < 0)
810
        return ERROR_SUCCESS;
811

812
    *appValue = NULL;
813 814
    /* We need the buffer in both paths below, so go ahead and allocate it
     * here.  Add two because we might need to add a backslash if the dir name
815
     * isn't backslash-terminated.
816
     */
817 818
    len = dirLen + max(fileLen, strlenW(starDotStarW)) + 2;
    buf = msi_alloc(len * sizeof(WCHAR));
819 820 821 822 823 824 825 826 827
    if (!buf)
        return ERROR_OUTOFMEMORY;

    lstrcpyW(buf, dir);
    PathAddBackslashW(buf);
    lstrcatW(buf, sig->File);

    hFind = FindFirstFileW(buf, &findData);
    if (hFind != INVALID_HANDLE_VALUE)
828
    {
829
        if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
830
        {
831
            BOOL matches;
832

833 834 835 836 837 838 839
            rc = ACTION_FileMatchesSig(sig, &findData, buf, &matches);
            if (rc == ERROR_SUCCESS && matches)
            {
                TRACE("found file, returning %s\n", debugstr_w(buf));
                *appValue = buf;
            }
        }
840 841 842
        FindClose(hFind);
    }

843
    if (rc == ERROR_SUCCESS && !*appValue)
844 845 846 847 848
    {
        lstrcpyW(buf, dir);
        PathAddBackslashW(buf);
        lstrcatW(buf, starDotStarW);

849 850 851
        hFind = FindFirstFileW(buf, &findData);
        if (hFind != INVALID_HANDLE_VALUE)
        {
852
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
853 854
                strcmpW( findData.cFileName, szDot ) &&
                strcmpW( findData.cFileName, szDotDot ))
855 856 857
            {
                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
858
                rc = ACTION_RecurseSearchDirectory(package, appValue, sig,
859 860
                                                   subpath, depth - 1);
            }
861

862 863
            while (rc == ERROR_SUCCESS && !*appValue &&
                   FindNextFileW(hFind, &findData) != 0)
864
            {
865 866
                if (!strcmpW( findData.cFileName, szDot ) ||
                    !strcmpW( findData.cFileName, szDotDot ))
867 868 869 870
                    continue;

                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
871
                if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
872
                    rc = ACTION_RecurseSearchDirectory(package, appValue,
873
                                                       sig, subpath, depth - 1);
874
            }
875 876

            FindClose(hFind);
877 878
        }
    }
879

880
    if (*appValue != buf)
881
        msi_free(buf);
882

883 884 885
    return rc;
}

886 887
static UINT ACTION_CheckDirectory(MSIPACKAGE *package, LPCWSTR dir,
 LPWSTR *appValue)
888
{
889
    DWORD attr = GetFileAttributesW(dir);
890

891
    if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY))
892
    {
893 894
        TRACE("directory exists, returning %s\n", debugstr_w(dir));
        *appValue = strdupW(dir);
895
    }
896 897

    return ERROR_SUCCESS;
898 899
}

900 901 902 903 904
static BOOL ACTION_IsFullPath(LPCWSTR path)
{
    WCHAR first = toupperW(path[0]);
    BOOL ret;

905
    if (first >= 'A' && first <= 'Z' && path[1] == ':')
906 907 908 909 910 911 912 913 914
        ret = TRUE;
    else if (path[0] == '\\' && path[1] == '\\')
        ret = TRUE;
    else
        ret = FALSE;
    return ret;
}

static UINT ACTION_SearchDirectory(MSIPACKAGE *package, MSISIGNATURE *sig,
915
 LPCWSTR path, int depth, LPWSTR *appValue)
916 917
{
    UINT rc;
918
    DWORD attr;
919
    LPWSTR val = NULL;
920

921 922
    TRACE("%p, %p, %s, %d, %p\n", package, sig, debugstr_w(path), depth,
     appValue);
923

924
    if (ACTION_IsFullPath(path))
925 926
    {
        if (sig->File)
927
            rc = ACTION_RecurseSearchDirectory(package, &val, sig, path, depth);
928 929 930 931 932
        else
        {
            /* Recursively searching a directory makes no sense when the
             * directory to search is the thing you're trying to find.
             */
933
            rc = ACTION_CheckDirectory(package, path, &val);
934 935 936 937 938 939 940 941 942
        }
    }
    else
    {
        WCHAR pathWithDrive[MAX_PATH] = { 'C',':','\\',0 };
        DWORD drives = GetLogicalDrives();
        int i;

        rc = ERROR_SUCCESS;
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
        for (i = 0; rc == ERROR_SUCCESS && !val && i < 26; i++)
        {
            if (!(drives & (1 << i)))
                continue;

            pathWithDrive[0] = 'A' + i;
            if (GetDriveTypeW(pathWithDrive) != DRIVE_FIXED)
                continue;

            lstrcpynW(pathWithDrive + 3, path,
                      sizeof(pathWithDrive) / sizeof(pathWithDrive[0]) - 3);

            if (sig->File)
                rc = ACTION_RecurseSearchDirectory(package, &val, sig,
                                                   pathWithDrive, depth);
            else
                rc = ACTION_CheckDirectory(package, pathWithDrive, &val);
        }
961
    }
962

963
    attr = GetFileAttributesW(val);
964 965
    if (attr != INVALID_FILE_ATTRIBUTES &&
        (attr & FILE_ATTRIBUTE_DIRECTORY) &&
966
        val && val[lstrlenW(val) - 1] != '\\')
967 968 969 970 971 972 973 974 975 976
    {
        val = msi_realloc(val, (lstrlenW(val) + 2) * sizeof(WCHAR));
        if (!val)
            rc = ERROR_OUTOFMEMORY;
        else
            PathAddBackslashW(val);
    }

    *appValue = val;

977
    TRACE("returning %d\n", rc);
978 979 980
    return rc;
}

981 982 983
static UINT ACTION_AppSearchSigName(MSIPACKAGE *package, LPCWSTR sigName,
 MSISIGNATURE *sig, LPWSTR *appValue);

984
static UINT ACTION_AppSearchDr(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig)
985
{
986 987 988 989 990 991
    static const WCHAR query[] =  {
        's','e','l','e','c','t',' ','*',' ',
        'f','r','o','m',' ',
        'D','r','L','o','c','a','t','o','r',' ',
        'w','h','e','r','e',' ',
        'S','i','g','n','a','t','u','r','e','_',' ','=',' ', '\'','%','s','\'',0};
992 993
    LPWSTR parent = NULL;
    LPCWSTR parentName;
994
    WCHAR path[MAX_PATH];
995 996 997
    WCHAR expanded[MAX_PATH];
    MSIRECORD *row;
    int depth;
998
    DWORD sz, attr;
999 1000
    UINT rc;

1001
    TRACE("%s\n", debugstr_w(sig->Name));
1002

1003
    *appValue = NULL;
1004

1005 1006 1007 1008 1009 1010
    row = MSI_QueryGetRecord( package->db, query, sig->Name );
    if (!row)
    {
        TRACE("failed to query DrLocator for %s\n", debugstr_w(sig->Name));
        return ERROR_SUCCESS;
    }
1011

1012
    /* check whether parent is set */
1013
    parentName = MSI_RecordGetString(row, 2);
1014 1015 1016
    if (parentName)
    {
        MSISIGNATURE parentSig;
1017

1018
        ACTION_AppSearchSigName(package, parentName, &parentSig, &parent);
1019
        ACTION_FreeSignature(&parentSig);
1020
        if (!parent)
Hans Leidekker's avatar
Hans Leidekker committed
1021 1022
        {
            msiobj_release(&row->hdr);
1023
            return ERROR_SUCCESS;
Hans Leidekker's avatar
Hans Leidekker committed
1024
        }
1025
    }
1026 1027 1028 1029

    sz = MAX_PATH;
    MSI_RecordGetStringW(row, 3, path, &sz);

1030 1031
    if (MSI_RecordIsNull(row,4))
        depth = 0;
1032
    else
1033
        depth = MSI_RecordGetInteger(row,4);
1034

1035 1036 1037 1038
    if (sz)
        ACTION_ExpandAnyPath(package, path, expanded, MAX_PATH);
    else
        strcpyW(expanded, path);
1039

1040
    if (parent)
1041
    {
1042 1043 1044
        attr = GetFileAttributesW(parent);
        if (attr != INVALID_FILE_ATTRIBUTES &&
            !(attr & FILE_ATTRIBUTE_DIRECTORY))
1045 1046 1047 1048 1049
        {
            PathRemoveFileSpecW(parent);
            PathAddBackslashW(parent);
        }

1050 1051
        strcpyW(path, parent);
        strcatW(path, expanded);
1052
    }
1053
    else if (sz)
1054 1055 1056
        strcpyW(path, expanded);

    PathAddBackslashW(path);
1057 1058 1059 1060 1061

    rc = ACTION_SearchDirectory(package, sig, path, depth, appValue);

    msi_free(parent);
    msiobj_release(&row->hdr);
1062 1063 1064 1065 1066

    TRACE("returning %d\n", rc);
    return rc;
}

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
static UINT ACTION_AppSearchSigName(MSIPACKAGE *package, LPCWSTR sigName,
 MSISIGNATURE *sig, LPWSTR *appValue)
{
    UINT rc;

    *appValue = NULL;
    rc = ACTION_AppSearchGetSignature(package, sig, sigName);
    if (rc == ERROR_SUCCESS)
    {
        rc = ACTION_AppSearchComponents(package, appValue, sig);
        if (rc == ERROR_SUCCESS && !*appValue)
        {
            rc = ACTION_AppSearchReg(package, appValue, sig);
            if (rc == ERROR_SUCCESS && !*appValue)
            {
                rc = ACTION_AppSearchIni(package, appValue, sig);
                if (rc == ERROR_SUCCESS && !*appValue)
                    rc = ACTION_AppSearchDr(package, appValue, sig);
            }
        }
    }
    return rc;
}

1091
static UINT iterate_appsearch(MSIRECORD *row, LPVOID param)
1092
{
1093
    MSIPACKAGE *package = param;
1094 1095
    LPCWSTR propName, sigName;
    LPWSTR value = NULL;
1096
    MSISIGNATURE sig;
1097
    MSIRECORD *uirow;
1098
    UINT r;
1099

1100
    /* get property and signature */
1101 1102
    propName = MSI_RecordGetString(row, 1);
    sigName = MSI_RecordGetString(row, 2);
1103

1104
    TRACE("%s %s\n", debugstr_w(propName), debugstr_w(sigName));
1105

1106 1107 1108
    r = ACTION_AppSearchSigName(package, sigName, &sig, &value);
    if (value)
    {
1109
        r = msi_set_property( package->db, propName, value, -1 );
1110
        if (r == ERROR_SUCCESS && !strcmpW( propName, szSourceDir ))
1111 1112
            msi_reset_folders( package, TRUE );

1113 1114 1115
        msi_free(value);
    }
    ACTION_FreeSignature(&sig);
1116 1117 1118 1119

    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, propName );
    MSI_RecordSetStringW( uirow, 2, sigName );
1120
    msi_ui_actiondata( package, szAppSearch, uirow );
1121
    msiobj_release( &uirow->hdr );
1122

1123 1124
    return r;
}
1125

1126 1127 1128
UINT ACTION_AppSearch(MSIPACKAGE *package)
{
    static const WCHAR query[] =  {
1129
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1130
        'A','p','p','S','e','a','r','c','h',0};
1131
    MSIQUERY *view;
1132
    UINT r;
1133

1134
    if (msi_action_is_unique(package, szAppSearch))
1135 1136 1137 1138 1139
    {
        TRACE("Skipping AppSearch action: already done in UI sequence\n");
        return ERROR_SUCCESS;
    }
    else
1140
        msi_register_unique_action(package, szAppSearch);
1141

1142 1143 1144
    r = MSI_OpenQuery( package->db, &view, query );
    if (r != ERROR_SUCCESS)
        return ERROR_SUCCESS;
1145

1146 1147 1148
    r = MSI_IterateRecords( view, NULL, iterate_appsearch, package );
    msiobj_release( &view->hdr );
    return r;
1149
}
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

static UINT ITERATE_CCPSearch(MSIRECORD *row, LPVOID param)
{
    MSIPACKAGE *package = param;
    LPCWSTR signature;
    LPWSTR value = NULL;
    MSISIGNATURE sig;
    UINT r = ERROR_SUCCESS;

    static const WCHAR success[] = {'C','C','P','_','S','u','c','c','e','s','s',0};

    signature = MSI_RecordGetString(row, 1);

    TRACE("%s\n", debugstr_w(signature));

    ACTION_AppSearchSigName(package, signature, &sig, &value);
    if (value)
    {
        TRACE("Found signature %s\n", debugstr_w(signature));
1169
        msi_set_property( package->db, success, szOne, -1 );
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        msi_free(value);
        r = ERROR_NO_MORE_ITEMS;
    }

    ACTION_FreeSignature(&sig);

    return r;
}

UINT ACTION_CCPSearch(MSIPACKAGE *package)
{
    static const WCHAR query[] =  {
1182
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1183
        'C','C','P','S','e','a','r','c','h',0};
1184
    MSIQUERY *view;
1185 1186
    UINT r;

1187
    if (msi_action_is_unique(package, szCCPSearch))
1188 1189 1190 1191 1192
    {
        TRACE("Skipping AppSearch action: already done in UI sequence\n");
        return ERROR_SUCCESS;
    }
    else
1193
        msi_register_unique_action(package, szCCPSearch);
1194

1195 1196 1197 1198 1199 1200 1201 1202
    r = MSI_OpenQuery(package->db, &view, query);
    if (r != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    r = MSI_IterateRecords(view, NULL, ITERATE_CCPSearch, package);
    msiobj_release(&view->hdr);
    return r;
}