action.c 237 KB
Newer Older
1 2 3
/*
 * Implementation of the Microsoft Installer (msi.dll)
 *
4
 * Copyright 2004,2005 Aric Stewart for CodeWeavers
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * 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
 */

#include <stdarg.h>

23 24
#define COBJMACROS

25 26 27 28
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "winreg.h"
29
#include "winsvc.h"
30
#include "odbcinst.h"
31
#include "wine/debug.h"
32
#include "msidefs.h"
33 34 35
#include "msipriv.h"
#include "winuser.h"
#include "shlobj.h"
36 37 38
#include "objbase.h"
#include "mscoree.h"
#include "shlwapi.h"
39
#include "imagehlp.h"
40
#include "wine/unicode.h"
41
#include "winver.h"
42

43 44
#define REG_PROGRESS_VALUE 13200
#define COMPONENT_PROGRESS_VALUE 24000
45 46 47

WINE_DEFAULT_DEBUG_CHANNEL(msi);

48
static const WCHAR szCreateFolders[] =
49
    {'C','r','e','a','t','e','F','o','l','d','e','r','s',0};
50
static const WCHAR szCostFinalize[] =
51
    {'C','o','s','t','F','i','n','a','l','i','z','e',0};
52
static const WCHAR szWriteRegistryValues[] =
53
    {'W','r','i','t','e','R','e','g','i','s','t','r','y','V','a','l','u','e','s',0};
54
static const WCHAR szFileCost[] = 
55
    {'F','i','l','e','C','o','s','t',0};
56
static const WCHAR szInstallInitialize[] = 
57
    {'I','n','s','t','a','l','l','I','n','i','t','i','a','l','i','z','e',0};
58
static const WCHAR szInstallValidate[] = 
59
    {'I','n','s','t','a','l','l','V','a','l','i','d','a','t','e',0};
60
static const WCHAR szLaunchConditions[] = 
61
    {'L','a','u','n','c','h','C','o','n','d','i','t','i','o','n','s',0};
62
static const WCHAR szProcessComponents[] = 
63
    {'P','r','o','c','e','s','s','C','o','m','p','o','n','e','n','t','s',0};
64
static const WCHAR szRegisterTypeLibraries[] = 
65
    {'R','e','g','i','s','t','e','r','T','y','p','e','L','i','b','r','a','r','i','e','s',0};
66
static const WCHAR szCreateShortcuts[] = 
67
    {'C','r','e','a','t','e','S','h','o','r','t','c','u','t','s',0};
68
static const WCHAR szPublishProduct[] = 
69
    {'P','u','b','l','i','s','h','P','r','o','d','u','c','t',0};
70
static const WCHAR szWriteIniValues[] = 
71
    {'W','r','i','t','e','I','n','i','V','a','l','u','e','s',0};
72
static const WCHAR szSelfRegModules[] = 
73
    {'S','e','l','f','R','e','g','M','o','d','u','l','e','s',0};
74
static const WCHAR szPublishFeatures[] = 
75
    {'P','u','b','l','i','s','h','F','e','a','t','u','r','e','s',0};
76
static const WCHAR szRegisterProduct[] = 
77
    {'R','e','g','i','s','t','e','r','P','r','o','d','u','c','t',0};
78
static const WCHAR szInstallExecute[] = 
79
    {'I','n','s','t','a','l','l','E','x','e','c','u','t','e',0};
80
static const WCHAR szInstallExecuteAgain[] = 
81
    {'I','n','s','t','a','l','l','E','x','e','c','u','t','e','A','g','a','i','n',0};
82
static const WCHAR szInstallFinalize[] = 
83
    {'I','n','s','t','a','l','l','F','i','n','a','l','i','z','e',0};
84
static const WCHAR szForceReboot[] = 
85
    {'F','o','r','c','e','R','e','b','o','o','t',0};
86
static const WCHAR szResolveSource[] =
87
    {'R','e','s','o','l','v','e','S','o','u','r','c','e',0};
88
static const WCHAR szAllocateRegistrySpace[] = 
89
    {'A','l','l','o','c','a','t','e','R','e','g','i','s','t','r','y','S','p','a','c','e',0};
90
static const WCHAR szBindImage[] = 
91
    {'B','i','n','d','I','m','a','g','e',0};
92
static const WCHAR szDeleteServices[] = 
93
    {'D','e','l','e','t','e','S','e','r','v','i','c','e','s',0};
94
static const WCHAR szDisableRollback[] = 
95
    {'D','i','s','a','b','l','e','R','o','l','l','b','a','c','k',0};
96
static const WCHAR szExecuteAction[] = 
97
    {'E','x','e','c','u','t','e','A','c','t','i','o','n',0};
98
static const WCHAR szInstallAdminPackage[] = 
99
    {'I','n','s','t','a','l','l','A','d','m','i','n','P','a','c','k','a','g','e',0};
100
static const WCHAR szInstallSFPCatalogFile[] = 
101
    {'I','n','s','t','a','l','l','S','F','P','C','a','t','a','l','o','g','F','i','l','e',0};
102
static const WCHAR szIsolateComponents[] = 
103
    {'I','s','o','l','a','t','e','C','o','m','p','o','n','e','n','t','s',0};
104 105
static const WCHAR szMigrateFeatureStates[] =
    {'M','i','g','r','a','t','e','F','e','a','t','u','r','e','S','t','a','t','e','s',0};
106
static const WCHAR szMsiUnpublishAssemblies[] = 
107
    {'M','s','i','U','n','p','u','b','l','i','s','h','A','s','s','e','m','b','l','i','e','s',0};
108
static const WCHAR szInstallODBC[] = 
109
    {'I','n','s','t','a','l','l','O','D','B','C',0};
110
static const WCHAR szInstallServices[] = 
111
    {'I','n','s','t','a','l','l','S','e','r','v','i','c','e','s',0};
112
static const WCHAR szPublishComponents[] = 
113
    {'P','u','b','l','i','s','h','C','o','m','p','o','n','e','n','t','s',0};
114
static const WCHAR szRegisterComPlus[] =
115
    {'R','e','g','i','s','t','e','r','C','o','m','P','l','u','s',0};
116
static const WCHAR szRegisterUser[] =
117
    {'R','e','g','i','s','t','e','r','U','s','e','r',0};
118
static const WCHAR szRemoveEnvironmentStrings[] =
119 120 121
    {'R','e','m','o','v','e','E','n','v','i','r','o','n','m','e','n','t','S','t','r','i','n','g','s',0};
static const WCHAR szRemoveExistingProducts[] =
    {'R','e','m','o','v','e','E','x','i','s','t','i','n','g','P','r','o','d','u','c','t','s',0};
122
static const WCHAR szRemoveFolders[] =
123
    {'R','e','m','o','v','e','F','o','l','d','e','r','s',0};
124
static const WCHAR szRemoveIniValues[] =
125
    {'R','e','m','o','v','e','I','n','i','V','a','l','u','e','s',0};
126
static const WCHAR szRemoveODBC[] =
127
    {'R','e','m','o','v','e','O','D','B','C',0};
128
static const WCHAR szRemoveRegistryValues[] =
129
    {'R','e','m','o','v','e','R','e','g','i','s','t','r','y','V','a','l','u','e','s',0};
130
static const WCHAR szRemoveShortcuts[] =
131
    {'R','e','m','o','v','e','S','h','o','r','t','c','u','t','s',0};
132
static const WCHAR szRMCCPSearch[] =
133
    {'R','M','C','C','P','S','e','a','r','c','h',0};
134
static const WCHAR szScheduleReboot[] =
135
    {'S','c','h','e','d','u','l','e','R','e','b','o','o','t',0};
136
static const WCHAR szSelfUnregModules[] =
137
    {'S','e','l','f','U','n','r','e','g','M','o','d','u','l','e','s',0};
138
static const WCHAR szSetODBCFolders[] =
139
    {'S','e','t','O','D','B','C','F','o','l','d','e','r','s',0};
140
static const WCHAR szStartServices[] =
141
    {'S','t','a','r','t','S','e','r','v','i','c','e','s',0};
142
static const WCHAR szStopServices[] =
143
    {'S','t','o','p','S','e','r','v','i','c','e','s',0};
144
static const WCHAR szUnpublishComponents[] =
145
    {'U','n','p','u','b','l','i','s','h', 'C','o','m','p','o','n','e','n','t','s',0};
146
static const WCHAR szUnpublishFeatures[] =
147
    {'U','n','p','u','b','l','i','s','h','F','e','a','t','u','r','e','s',0};
148
static const WCHAR szUnregisterComPlus[] =
149
    {'U','n','r','e','g','i','s','t','e','r','C','o','m','P','l','u','s',0};
150
static const WCHAR szUnregisterTypeLibraries[] =
151
    {'U','n','r','e','g','i','s','t','e','r','T','y','p','e','L','i','b','r','a','r','i','e','s',0};
152
static const WCHAR szValidateProductID[] =
153
    {'V','a','l','i','d','a','t','e','P','r','o','d','u','c','t','I','D',0};
154
static const WCHAR szWriteEnvironmentStrings[] =
155
    {'W','r','i','t','e','E','n','v','i','r','o','n','m','e','n','t','S','t','r','i','n','g','s',0};
156

157
static void ui_actionstart(MSIPACKAGE *package, LPCWSTR action)
158 159
{
    static const WCHAR Query_t[] = 
160
        {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
Aric Stewart's avatar
Aric Stewart committed
161 162 163
         '`','A','c','t','i','o', 'n','T','e','x','t','`',' ',
         'W','H','E','R','E', ' ','`','A','c','t','i','o','n','`',' ','=', 
         ' ','\'','%','s','\'',0};
164
    MSIRECORD * row;
165

166 167
    row = MSI_QueryGetRecord( package->db, Query_t, action );
    if (!row)
168
        return;
169 170
    MSI_ProcessMessage(package, INSTALLMESSAGE_ACTIONSTART, row);
    msiobj_release(&row->hdr);
171 172
}

173
static void ui_actioninfo(MSIPACKAGE *package, LPCWSTR action, BOOL start, 
174 175
                          UINT rc)
{
176
    MSIRECORD * row;
177
    static const WCHAR template_s[]=
178 179
        {'A','c','t','i','o','n',' ','s','t','a','r','t',' ','%','s',':',' ',
         '%','s', '.',0};
180
    static const WCHAR template_e[]=
181 182 183
        {'A','c','t','i','o','n',' ','e','n','d','e','d',' ','%','s',':',' ',
         '%','s', '.',' ','R','e','t','u','r','n',' ','v','a','l','u','e',' ',
         '%','i','.',0};
184
    static const WCHAR format[] = 
185
        {'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0};
186 187 188 189 190 191 192 193 194
    WCHAR message[1024];
    WCHAR timet[0x100];

    GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, format, timet, 0x100);
    if (start)
        sprintfW(message,template_s,timet,action);
    else
        sprintfW(message,template_e,timet,action,rc);
    
195 196
    row = MSI_CreateRecord(1);
    MSI_RecordSetStringW(row,1,message);
197
 
198 199
    MSI_ProcessMessage(package, INSTALLMESSAGE_INFO, row);
    msiobj_release(&row->hdr);
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
enum parse_state
{
    state_whitespace,
    state_token,
    state_quote
};

static int parse_prop( const WCHAR *str, WCHAR *value, int *quotes )
{
    enum parse_state state = state_quote;
    const WCHAR *p;
    WCHAR *out = value;
    int ignore, in_quotes = 0, count = 0, len = 0;

    for (p = str; *p; p++)
    {
        ignore = 0;
        switch (state)
        {
        case state_whitespace:
            switch (*p)
            {
            case ' ':
                in_quotes = 1;
                ignore = 1;
227
                len++;
228 229 230
                break;
            case '"':
                state = state_quote;
231
                if (in_quotes && p[1] != '\"') count--;
232 233 234 235
                else count++;
                break;
            default:
                state = state_token;
236
                in_quotes = 1;
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                len++;
                break;
            }
            break;

        case state_token:
            switch (*p)
            {
            case '"':
                state = state_quote;
                if (in_quotes) count--;
                else count++;
                break;
            case ' ':
                state = state_whitespace;
                if (!count) goto done;
                in_quotes = 1;
254
                len++;
255 256 257 258 259 260 261 262 263 264 265 266 267
                break;
            default:
                if (!count) in_quotes = 0;
                else in_quotes = 1;
                len++;
                break;
            }
            break;

        case state_quote:
            switch (*p)
            {
            case '"':
268
                if (in_quotes && p[1] != '\"') count--;
269 270 271 272
                else count++;
                break;
            case ' ':
                state = state_whitespace;
273
                if (!count || (count > 1 && !len)) goto done;
274
                in_quotes = 1;
275
                len++;
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
                break;
            default:
                state = state_token;
                if (!count) in_quotes = 0;
                else in_quotes = 1;
                len++;
                break;
            }
            break;

        default: break;
        }
        if (!ignore) *out++ = *p;
    }

done:
    if (!len) *value = 0;
    else *out = 0;

    *quotes = count;
    return p - str;
}

static void remove_quotes( WCHAR *str )
{
    WCHAR *p = str;
    int len = strlenW( str );

    while ((p = strchrW( p, '"' )))
    {
        memmove( p, p + 1, (len - (p - str)) * sizeof(WCHAR) );
        p++;
    }
}

311 312
UINT msi_parse_command_line( MSIPACKAGE *package, LPCWSTR szCommandLine,
                             BOOL preserve_case )
313
{
314
    LPCWSTR ptr, ptr2;
315
    int num_quotes;
316
    DWORD len;
317 318
    WCHAR *prop, *val;
    UINT r;
319 320 321 322 323 324 325

    if (!szCommandLine)
        return ERROR_SUCCESS;

    ptr = szCommandLine;
    while (*ptr)
    {
326 327
        while (*ptr == ' ') ptr++;
        if (!*ptr) break;
328

329 330
        ptr2 = strchrW( ptr, '=' );
        if (!ptr2) return ERROR_INVALID_COMMAND_LINE;
331
 
332 333
        len = ptr2 - ptr;
        if (!len) return ERROR_INVALID_COMMAND_LINE;
334

335 336 337 338
        prop = msi_alloc( (len + 1) * sizeof(WCHAR) );
        memcpy( prop, ptr, len * sizeof(WCHAR) );
        prop[len] = 0;
        if (!preserve_case) struprW( prop );
339

340
        ptr2++;
341 342
        while (*ptr2 == ' ') ptr2++;

343
        num_quotes = 0;
344
        val = msi_alloc( (strlenW( ptr2 ) + 1) * sizeof(WCHAR) );
345 346
        len = parse_prop( ptr2, val, &num_quotes );
        if (num_quotes % 2)
347
        {
348 349 350 351
            WARN("unbalanced quotes\n");
            msi_free( val );
            msi_free( prop );
            return ERROR_INVALID_COMMAND_LINE;
352
        }
353 354
        remove_quotes( val );
        TRACE("Found commandline property %s = %s\n", debugstr_w(prop), debugstr_w(val));
355

356
        r = msi_set_property( package->db, prop, val, -1 );
357
        if (r == ERROR_SUCCESS && !strcmpW( prop, szSourceDir ))
358
            msi_reset_folders( package, TRUE );
359

360 361
        msi_free( val );
        msi_free( prop );
362

363
        ptr = ptr2 + len;
364 365 366 367 368
    }

    return ERROR_SUCCESS;
}

369
WCHAR **msi_split_string( const WCHAR *str, WCHAR sep )
370
{
371
    LPCWSTR pc;
372 373 374 375 376 377 378
    LPWSTR p, *ret = NULL;
    UINT count = 0;

    if (!str)
        return ret;

    /* count the number of substrings */
379
    for ( pc = str, count = 0; pc; count++ )
380
    {
381 382 383
        pc = strchrW( pc, sep );
        if (pc)
            pc++;
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    }

    /* allocate space for an array of substring pointers and the substrings */
    ret = msi_alloc( (count+1) * sizeof (LPWSTR) +
                     (lstrlenW(str)+1) * sizeof(WCHAR) );
    if (!ret)
        return ret;

    /* copy the string and set the pointers */
    p = (LPWSTR) &ret[count+1];
    lstrcpyW( p, str );
    for( count = 0; (ret[count] = p); count++ )
    {
        p = strchrW( p, sep );
        if (p)
            *p++ = 0;
    }

    return ret;
}

405
static BOOL ui_sequence_exists( MSIPACKAGE *package )
406
{
407 408 409 410 411
    static const WCHAR query [] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','I','n','s','t','a','l','l','U','I','S','e','q','u','e','n','c','e','`',' ',
        'W','H','E','R','E',' ','`','S','e','q','u','e','n','c','e','`',' ','>',' ','0',' ',
        'O','R','D','E','R',' ','B','Y',' ','`','S','e','q','u','e','n','c','e','`',0};
412 413 414
    MSIQUERY *view;
    UINT rc;

415
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
416 417 418 419 420 421 422 423
    if (rc == ERROR_SUCCESS)
    {
        msiobj_release(&view->hdr);
        return TRUE;
    }
    return FALSE;
}

424
UINT msi_set_sourcedir_props(MSIPACKAGE *package, BOOL replace)
425 426
{
    LPWSTR source, check;
427

428 429 430
    if (msi_get_property_int( package->db, szInstalled, 0 ))
    {
        HKEY hkey;
431

432 433 434 435 436
        MSIREG_OpenInstallProps( package->ProductCode, package->Context, NULL, &hkey, FALSE );
        source = msi_reg_get_val_str( hkey, INSTALLPROPERTY_INSTALLSOURCEW );
        RegCloseKey( hkey );
    }
    else
437
    {
438 439 440 441 442 443 444 445
        LPWSTR p, db;
        DWORD len;

        db = msi_dup_property( package->db, szOriginalDatabase );
        if (!db)
            return ERROR_OUTOFMEMORY;

        p = strrchrW( db, '\\' );
446 447
        if (!p)
        {
448 449 450 451 452 453
            p = strrchrW( db, '/' );
            if (!p)
            {
                msi_free(db);
                return ERROR_SUCCESS;
            }
454
        }
455

456 457 458 459 460
        len = p - db + 2;
        source = msi_alloc( len * sizeof(WCHAR) );
        lstrcpynW( source, db, len );
        msi_free( db );
    }
461

462
    check = msi_dup_property( package->db, szSourceDir );
463
    if (!check || replace)
464
    {
465
        UINT r = msi_set_property( package->db, szSourceDir, source, -1 );
466 467 468
        if (r == ERROR_SUCCESS)
            msi_reset_folders( package, TRUE );
    }
469 470
    msi_free( check );

471
    check = msi_dup_property( package->db, szSOURCEDIR );
472
    if (!check || replace)
473
        msi_set_property( package->db, szSOURCEDIR, source, -1 );
474 475 476 477 478 479 480

    msi_free( check );
    msi_free( source );

    return ERROR_SUCCESS;
}

481 482
static BOOL needs_ui_sequence(MSIPACKAGE *package)
{
483
    return (package->ui_level & INSTALLUILEVEL_MASK) >= INSTALLUILEVEL_REDUCED;
484 485
}

486
UINT msi_set_context(MSIPACKAGE *package)
487
{
488 489 490 491 492 493 494 495 496
    UINT r = msi_locate_product( package->ProductCode, &package->Context );
    if (r != ERROR_SUCCESS)
    {
        int num = msi_get_property_int( package->db, szAllUsers, 0 );
        if (num == 1 || num == 2)
            package->Context = MSIINSTALLCONTEXT_MACHINE;
        else
            package->Context = MSIINSTALLCONTEXT_USERUNMANAGED;
    }
497 498 499
    return ERROR_SUCCESS;
}

500 501 502 503
static UINT ITERATE_Actions(MSIRECORD *row, LPVOID param)
{
    UINT rc;
    LPCWSTR cond, action;
504
    MSIPACKAGE *package = param;
505 506 507 508 509

    action = MSI_RecordGetString(row,1);
    if (!action)
    {
        ERR("Error is retrieving action name\n");
510
        return ERROR_FUNCTION_FAILED;
511 512 513 514
    }

    /* check conditions */
    cond = MSI_RecordGetString(row,2);
515 516

    /* this is a hack to skip errors in the condition code */
517
    if (MSI_EvaluateConditionW(package, cond) == MSICONDITION_FALSE)
518
    {
519 520
        TRACE("Skipping action: %s (condition is false)\n", debugstr_w(action));
        return ERROR_SUCCESS;
521 522
    }

523
    if (needs_ui_sequence(package))
524
        rc = ACTION_PerformUIAction(package, action, SCRIPT_NONE);
525
    else
526
        rc = ACTION_PerformAction(package, action, SCRIPT_NONE);
527

528 529
    msi_dialog_check_messages( NULL );

530 531
    if (package->CurrentInstallState != ERROR_SUCCESS)
        rc = package->CurrentInstallState;
532

533 534 535 536
    if (rc == ERROR_FUNCTION_NOT_CALLED)
        rc = ERROR_SUCCESS;

    if (rc != ERROR_SUCCESS)
537
        ERR("Execution halted, action %s returned %i\n", debugstr_w(action), rc);
538

539 540 541 542 543 544
    if (package->need_reboot_now)
    {
        TRACE("action %s asked for immediate reboot, suspending installation\n",
              debugstr_w(action));
        rc = ACTION_ForceReboot( package );
    }
545 546 547
    return rc;
}

548
UINT MSI_Sequence( MSIPACKAGE *package, LPCWSTR table )
549
{
550 551 552
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','`','%','s','`',
         ' ','W','H','E','R','E',' ','`','S','e','q','u','e','n','c','e','`',' ',
553 554
         '>',' ','0',' ','O','R','D','E','R',' ','B','Y',' ',
         '`','S','e','q','u','e','n','c','e','`',0};
555 556
    MSIQUERY *view;
    UINT r;
557

558
    TRACE("%p %s\n", package, debugstr_w(table));
559

560
    r = MSI_OpenQuery( package->db, &view, query, table );
561 562
    if (r == ERROR_SUCCESS)
    {
563
        r = MSI_IterateRecords( view, NULL, ITERATE_Actions, package );
564 565 566 567 568
        msiobj_release(&view->hdr);
    }
    return r;
}

569
static UINT ACTION_ProcessExecSequence(MSIPACKAGE *package, BOOL UIran)
570
{
571 572 573 574 575 576 577 578 579 580 581 582 583
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
        '`','I','n','s','t','a','l','l','E','x','e','c','u','t','e',
        'S','e','q','u','e','n','c','e','`',' ', 'W','H','E','R','E',' ',
        '`','S','e','q','u','e','n','c','e','`',' ', '>',' ','%','i',' ',
        'O','R','D','E','R',' ', 'B','Y',' ','`','S','e','q','u','e','n','c','e','`',0};
    static const WCHAR query_validate[] = {
        'S','E','L','E','C','T',' ','`','S','e','q','u','e','n','c','e','`',
        ' ', 'F','R','O','M',' ','`','I','n','s','t','a','l','l',
        'E','x','e','c','u','t','e','S','e','q','u','e','n','c','e','`',' ',
        'W','H','E','R','E',' ','`','A','c','t','i','o','n','`',' ','=',
        ' ','\'', 'I','n','s','t','a','l','l','V','a','l','i','d','a','t','e','\'',0};
    MSIQUERY *view;
584
    INT seq = 0;
585
    UINT rc;
586

587
    if (package->script->ExecuteSequenceRun)
588 589 590 591 592
    {
        TRACE("Execute Sequence already Run\n");
        return ERROR_SUCCESS;
    }

593
    package->script->ExecuteSequenceRun = TRUE;
594

595
    /* get the sequence number */
596 597
    if (UIran)
    {
598 599
        MSIRECORD *row = MSI_QueryGetRecord(package->db, query_validate);
        if (!row) return ERROR_FUNCTION_FAILED;
600 601
        seq = MSI_RecordGetInteger(row,1);
        msiobj_release(&row->hdr);
602
    }
603
    rc = MSI_OpenQuery(package->db, &view, query, seq);
604 605
    if (rc == ERROR_SUCCESS)
    {
606
        TRACE("Running the actions\n");
607

608
        msi_set_property( package->db, szSourceDir, NULL, -1 );
609
        rc = MSI_IterateRecords(view, NULL, ITERATE_Actions, package);
610
        msiobj_release(&view->hdr);
611 612 613 614
    }
    return rc;
}

615
static UINT ACTION_ProcessUISequence(MSIPACKAGE *package)
616
{
617 618 619 620 621 622
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','I','n','s','t','a','l','l','U','I','S','e','q','u','e','n','c','e','`',' ',
        'W','H','E','R','E',' ','`','S','e','q','u','e','n','c','e','`',' ','>',' ','0',' ',
        'O','R','D','E','R',' ','B','Y',' ','`','S','e','q','u','e','n','c','e','`',0};
    MSIQUERY *view;
623
    UINT rc;
624

625
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
626 627
    if (rc == ERROR_SUCCESS)
    {
628
        TRACE("Running the actions\n"); 
629
        rc = MSI_IterateRecords(view, NULL, ITERATE_Actions, package);
630
        msiobj_release(&view->hdr);
631 632 633 634
    }
    return rc;
}

635 636 637
/********************************************************
 * ACTION helper functions and functions that perform the actions
 *******************************************************/
638
static BOOL ACTION_HandleCustomAction( MSIPACKAGE* package, LPCWSTR action,
639
                                       UINT* rc, UINT script, BOOL force )
640 641 642 643
{
    BOOL ret=FALSE;
    UINT arc;

644
    arc = ACTION_CustomAction(package, action, script, force);
645 646 647 648 649 650 651 652

    if (arc != ERROR_CALL_NOT_IMPLEMENTED)
    {
        *rc = arc;
        ret = TRUE;
    }
    return ret;
}
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
MSICOMPONENT *msi_get_loaded_component( MSIPACKAGE *package, const WCHAR *Component )
{
    MSICOMPONENT *comp;

    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
        if (!strcmpW( Component, comp->Component )) return comp;
    }
    return NULL;
}

MSIFEATURE *msi_get_loaded_feature(MSIPACKAGE* package, const WCHAR *Feature )
{
    MSIFEATURE *feature;

    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
    {
        if (!strcmpW( Feature, feature->Feature )) return feature;
    }
    return NULL;
}

MSIFILE *msi_get_loaded_file( MSIPACKAGE *package, const WCHAR *key )
{
    MSIFILE *file;

    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
    {
        if (!strcmpW( key, file->File )) return file;
    }
    return NULL;
}

MSIFOLDER *msi_get_loaded_folder( MSIPACKAGE *package, const WCHAR *dir )
{
    MSIFOLDER *folder;

    LIST_FOR_EACH_ENTRY( folder, &package->folders, MSIFOLDER, entry )
    {
        if (!strcmpW( dir, folder->Directory )) return folder;
    }
    return NULL;
}

698
/*
699 700
 * Recursively create all directories in the path.
 * shamelessly stolen from setupapi/queue.c
701
 */
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
BOOL msi_create_full_path( const WCHAR *path )
{
    BOOL ret = TRUE;
    WCHAR *new_path;
    int len;

    new_path = msi_alloc( (strlenW( path ) + 1) * sizeof(WCHAR) );
    strcpyW( new_path, path );

    while ((len = strlenW( new_path )) && new_path[len - 1] == '\\')
    new_path[len - 1] = 0;

    while (!CreateDirectoryW( new_path, NULL ))
    {
        WCHAR *slash;
        DWORD last_error = GetLastError();
        if (last_error == ERROR_ALREADY_EXISTS) break;
        if (last_error != ERROR_PATH_NOT_FOUND)
        {
            ret = FALSE;
            break;
        }
        if (!(slash = strrchrW( new_path, '\\' )))
        {
            ret = FALSE;
            break;
        }
        len = slash - new_path;
        new_path[len] = 0;
        if (!msi_create_full_path( new_path ))
        {
            ret = FALSE;
            break;
        }
        new_path[len] = '\\';
    }
    msi_free( new_path );
    return ret;
}

void msi_ui_progress( MSIPACKAGE *package, int a, int b, int c, int d )
{
    MSIRECORD *row;

    row = MSI_CreateRecord( 4 );
    MSI_RecordSetInteger( row, 1, a );
    MSI_RecordSetInteger( row, 2, b );
    MSI_RecordSetInteger( row, 3, c );
    MSI_RecordSetInteger( row, 4, d );
    MSI_ProcessMessage( package, INSTALLMESSAGE_PROGRESS, row );
    msiobj_release( &row->hdr );

    msi_dialog_check_messages( NULL );
}

void msi_ui_actiondata( MSIPACKAGE *package, const WCHAR *action, MSIRECORD *record )
{
    static const WCHAR query[] =
        {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
         '`','A','c','t','i','o', 'n','T','e','x','t','`',' ',
         'W','H','E','R','E',' ', '`','A','c','t','i','o','n','`',' ','=',' ','\'','%','s','\'',0};
    WCHAR message[1024];
    MSIRECORD *row = 0;
    DWORD size;

    if (!package->LastAction || strcmpW( package->LastAction, action ))
    {
        if (!(row = MSI_QueryGetRecord( package->db, query, action ))) return;

        if (MSI_RecordIsNull( row, 3 ))
        {
            msiobj_release( &row->hdr );
            return;
        }
        /* update the cached action format */
        msi_free( package->ActionFormat );
        package->ActionFormat = msi_dup_record_field( row, 3 );
        msi_free( package->LastAction );
        package->LastAction = strdupW( action );
        msiobj_release( &row->hdr );
    }
    size = 1024;
    MSI_RecordSetStringW( record, 0, package->ActionFormat );
    MSI_FormatRecordW( package, record, message, &size );
    row = MSI_CreateRecord( 1 );
    MSI_RecordSetStringW( row, 1, message );
    MSI_ProcessMessage( package, INSTALLMESSAGE_ACTIONDATA, row );
    msiobj_release( &row->hdr );
}
791

792 793 794 795 796 797 798 799
INSTALLSTATE msi_get_component_action( MSIPACKAGE *package, MSICOMPONENT *comp )
{
    if (!comp->Enabled)
    {
        TRACE("component is disabled: %s\n", debugstr_w(comp->Component));
        return INSTALLSTATE_UNKNOWN;
    }
    if (package->need_rollback) return comp->Installed;
800 801 802
    if (comp->num_clients > 0 && comp->ActionRequest == INSTALLSTATE_ABSENT)
    {
        TRACE("%s has %u clients left\n", debugstr_w(comp->Component), comp->num_clients);
803
        return INSTALLSTATE_UNKNOWN;
804
    }
805 806 807
    return comp->ActionRequest;
}

808 809 810 811 812 813
INSTALLSTATE msi_get_feature_action( MSIPACKAGE *package, MSIFEATURE *feature )
{
    if (package->need_rollback) return feature->Installed;
    return feature->ActionRequest;
}

814 815
static UINT ITERATE_CreateFolders(MSIRECORD *row, LPVOID param)
{
816
    MSIPACKAGE *package = param;
817
    LPCWSTR dir, component, full_path;
818 819
    MSIRECORD *uirow;
    MSIFOLDER *folder;
820 821 822
    MSICOMPONENT *comp;

    component = MSI_RecordGetString(row, 2);
823 824 825
    if (!component)
        return ERROR_SUCCESS;

826
    comp = msi_get_loaded_component(package, component);
827 828 829
    if (!comp)
        return ERROR_SUCCESS;

830 831
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
832
    {
833
        TRACE("component not scheduled for installation: %s\n", debugstr_w(component));
834 835
        return ERROR_SUCCESS;
    }
836 837 838 839

    dir = MSI_RecordGetString(row,1);
    if (!dir)
    {
840
        ERR("Unable to get folder id\n");
841 842 843
        return ERROR_SUCCESS;
    }

844 845
    uirow = MSI_CreateRecord(1);
    MSI_RecordSetStringW(uirow, 1, dir);
846
    msi_ui_actiondata(package, szCreateFolders, uirow);
847 848
    msiobj_release(&uirow->hdr);

849
    full_path = msi_get_target_folder( package, dir );
850 851
    if (!full_path)
    {
852
        ERR("Unable to retrieve folder %s\n", debugstr_w(dir));
853 854
        return ERROR_SUCCESS;
    }
855
    TRACE("folder is %s\n", debugstr_w(full_path));
856

857
    folder = msi_get_loaded_folder( package, dir );
858
    if (folder->State == FOLDER_STATE_UNINITIALIZED) msi_create_full_path( full_path );
859
    folder->State = FOLDER_STATE_CREATED;
860 861 862
    return ERROR_SUCCESS;
}

863
static UINT ACTION_CreateFolders(MSIPACKAGE *package)
864
{
865 866 867
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','C','r','e','a','t','e','F','o','l','d','e','r','`',0};
868
    MSIQUERY *view;
869
    UINT rc;
870

871
    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
872
    if (rc != ERROR_SUCCESS)
873
        return ERROR_SUCCESS;
874

875
    rc = MSI_IterateRecords(view, NULL, ITERATE_CreateFolders, package);
876
    msiobj_release(&view->hdr);
877 878 879
    return rc;
}

880 881 882 883 884 885 886 887 888 889 890 891 892 893
static void remove_persistent_folder( MSIFOLDER *folder )
{
    FolderList *fl;

    LIST_FOR_EACH_ENTRY( fl, &folder->children, FolderList, entry )
    {
        remove_persistent_folder( fl->folder );
    }
    if (folder->persistent && folder->State != FOLDER_STATE_REMOVED)
    {
        if (RemoveDirectoryW( folder->ResolvedTarget )) folder->State = FOLDER_STATE_REMOVED;
    }
}

894 895 896
static UINT ITERATE_RemoveFolders( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
897
    LPCWSTR dir, component, full_path;
898 899
    MSIRECORD *uirow;
    MSIFOLDER *folder;
900 901 902
    MSICOMPONENT *comp;

    component = MSI_RecordGetString(row, 2);
903 904 905
    if (!component)
        return ERROR_SUCCESS;

906
    comp = msi_get_loaded_component(package, component);
907 908 909
    if (!comp)
        return ERROR_SUCCESS;

910 911
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
912
    {
913
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
914 915
        return ERROR_SUCCESS;
    }
916 917 918 919 920 921 922 923

    dir = MSI_RecordGetString( row, 1 );
    if (!dir)
    {
        ERR("Unable to get folder id\n");
        return ERROR_SUCCESS;
    }

924
    full_path = msi_get_target_folder( package, dir );
925 926
    if (!full_path)
    {
927
        ERR("Unable to resolve folder %s\n", debugstr_w(dir));
928 929 930 931 932
        return ERROR_SUCCESS;
    }
    TRACE("folder is %s\n", debugstr_w(full_path));

    uirow = MSI_CreateRecord( 1 );
933
    MSI_RecordSetStringW( uirow, 1, dir );
934
    msi_ui_actiondata( package, szRemoveFolders, uirow );
935 936
    msiobj_release( &uirow->hdr );

937
    folder = msi_get_loaded_folder( package, dir );
938
    remove_persistent_folder( folder );
939 940 941 942 943
    return ERROR_SUCCESS;
}

static UINT ACTION_RemoveFolders( MSIPACKAGE *package )
{
944 945 946
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','C','r','e','a','t','e','F','o','l','d','e','r','`',0};
947 948 949 950 951 952 953 954 955 956 957 958
    MSIQUERY *view;
    UINT rc;

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

959
static UINT load_component( MSIRECORD *row, LPVOID param )
960
{
961
    MSIPACKAGE *package = param;
962
    MSICOMPONENT *comp;
963

964
    comp = msi_alloc_zero( sizeof(MSICOMPONENT) );
965
    if (!comp)
966 967 968
        return ERROR_FUNCTION_FAILED;

    list_add_tail( &package->components, &comp->entry );
969

970
    /* fill in the data */
971
    comp->Component = msi_dup_record_field( row, 1 );
972

973
    TRACE("Loading Component %s\n", debugstr_w(comp->Component));
974

975 976
    comp->ComponentId = msi_dup_record_field( row, 2 );
    comp->Directory = msi_dup_record_field( row, 3 );
977
    comp->Attributes = MSI_RecordGetInteger(row,4);
978 979
    comp->Condition = msi_dup_record_field( row, 5 );
    comp->KeyPath = msi_dup_record_field( row, 6 );
980

981
    comp->Installed = INSTALLSTATE_UNKNOWN;
982 983
    comp->Action = INSTALLSTATE_UNKNOWN;
    comp->ActionRequest = INSTALLSTATE_UNKNOWN;
984

985
    comp->assembly = msi_load_assembly( package, comp );
986 987 988
    return ERROR_SUCCESS;
}

989
UINT msi_load_all_components( MSIPACKAGE *package )
990 991
{
    static const WCHAR query[] = {
992 993
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','C','o','m','p','o','n','e','n','t','`',0};
994 995 996 997 998
    MSIQUERY *view;
    UINT r;

    if (!list_empty(&package->components))
        return ERROR_SUCCESS;
999

1000 1001 1002 1003
    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r != ERROR_SUCCESS)
        return r;

1004 1005 1006 1007 1008 1009 1010
    if (!msi_init_assembly_caches( package ))
    {
        ERR("can't initialize assembly caches\n");
        msiobj_release( &view->hdr );
        return ERROR_FUNCTION_FAILED;
    }

1011 1012 1013
    r = MSI_IterateRecords(view, NULL, load_component, package);
    msiobj_release(&view->hdr);
    return r;
1014 1015
}

1016 1017
typedef struct {
    MSIPACKAGE *package;
1018
    MSIFEATURE *feature;
1019 1020
} _ilfs;

1021
static UINT add_feature_component( MSIFEATURE *feature, MSICOMPONENT *comp )
1022 1023 1024
{
    ComponentList *cl;

1025
    cl = msi_alloc( sizeof (*cl) );
1026 1027
    if ( !cl )
        return ERROR_NOT_ENOUGH_MEMORY;
1028
    cl->component = comp;
1029
    list_add_tail( &feature->Components, &cl->entry );
1030 1031 1032 1033

    return ERROR_SUCCESS;
}

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
static UINT add_feature_child( MSIFEATURE *parent, MSIFEATURE *child )
{
    FeatureList *fl;

    fl = msi_alloc( sizeof(*fl) );
    if ( !fl )
        return ERROR_NOT_ENOUGH_MEMORY;
    fl->feature = child;
    list_add_tail( &parent->Children, &fl->entry );

    return ERROR_SUCCESS;
}

1047
static UINT iterate_load_featurecomponents(MSIRECORD *row, LPVOID param)
1048
{
1049
    _ilfs* ilfs = param;
1050
    LPCWSTR component;
1051
    MSICOMPONENT *comp;
1052 1053 1054 1055

    component = MSI_RecordGetString(row,1);

    /* check to see if the component is already loaded */
1056
    comp = msi_get_loaded_component( ilfs->package, component );
1057
    if (!comp)
1058
    {
1059 1060
        WARN("ignoring unknown component %s\n", debugstr_w(component));
        return ERROR_SUCCESS;
1061
    }
1062 1063
    add_feature_component( ilfs->feature, comp );
    comp->Enabled = TRUE;
1064 1065 1066 1067 1068 1069

    return ERROR_SUCCESS;
}

static UINT load_feature(MSIRECORD * row, LPVOID param)
{
1070 1071
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','`','C','o','m','p','o','n','e','n','t','_','`',
Aric Stewart's avatar
Aric Stewart committed
1072
         ' ','F','R','O','M',' ','`','F','e','a','t','u','r','e',
1073
         'C','o','m','p','o','n','e','n','t','s','`',' ','W','H','E','R','E',' ',
Aric Stewart's avatar
Aric Stewart committed
1074
         '`','F','e', 'a','t','u','r','e','_','`',' ','=','\'','%','s','\'',0};
1075 1076 1077
    MSIPACKAGE *package = param;
    MSIFEATURE *feature;
    MSIQUERY *view;
1078
    _ilfs ilfs;
1079
    UINT rc;
1080

1081 1082
    /* fill in the data */

1083
    feature = msi_alloc_zero( sizeof (MSIFEATURE) );
1084 1085
    if (!feature)
        return ERROR_NOT_ENOUGH_MEMORY;
1086

1087
    list_init( &feature->Children );
1088
    list_init( &feature->Components );
1089
    
1090
    feature->Feature = msi_dup_record_field( row, 1 );
1091

1092
    TRACE("Loading feature %s\n",debugstr_w(feature->Feature));
1093

1094 1095 1096
    feature->Feature_Parent = msi_dup_record_field( row, 2 );
    feature->Title = msi_dup_record_field( row, 3 );
    feature->Description = msi_dup_record_field( row, 4 );
1097

1098
    if (!MSI_RecordIsNull(row,5))
1099
        feature->Display = MSI_RecordGetInteger(row,5);
1100
  
1101
    feature->Level= MSI_RecordGetInteger(row,6);
1102
    feature->Directory = msi_dup_record_field( row, 7 );
1103
    feature->Attributes = MSI_RecordGetInteger(row,8);
1104

1105
    feature->Installed = INSTALLSTATE_UNKNOWN;
1106 1107
    feature->Action = INSTALLSTATE_UNKNOWN;
    feature->ActionRequest = INSTALLSTATE_UNKNOWN;
1108

1109
    list_add_tail( &package->features, &feature->entry );
1110 1111 1112

    /* load feature components */

1113
    rc = MSI_OpenQuery( package->db, &view, query, feature->Feature );
1114
    if (rc != ERROR_SUCCESS)
1115
        return ERROR_SUCCESS;
1116

1117 1118 1119
    ilfs.package = package;
    ilfs.feature = feature;

1120
    rc = MSI_IterateRecords(view, NULL, iterate_load_featurecomponents , &ilfs);
1121
    msiobj_release(&view->hdr);
1122
    return rc;
1123 1124
}

1125 1126
static UINT find_feature_children(MSIRECORD * row, LPVOID param)
{
1127
    MSIPACKAGE *package = param;
1128 1129
    MSIFEATURE *parent, *child;

1130
    child = msi_get_loaded_feature( package, MSI_RecordGetString( row, 1 ) );
1131 1132 1133 1134 1135 1136
    if (!child)
        return ERROR_FUNCTION_FAILED;

    if (!child->Feature_Parent)
        return ERROR_SUCCESS;

1137
    parent = msi_get_loaded_feature( package, child->Feature_Parent );
1138 1139 1140 1141 1142 1143 1144
    if (!parent)
        return ERROR_FUNCTION_FAILED;

    add_feature_child( parent, child );
    return ERROR_SUCCESS;
}

1145
UINT msi_load_all_features( MSIPACKAGE *package )
1146 1147
{
    static const WCHAR query[] = {
1148 1149 1150
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','F','e','a','t','u','r','e','`',' ','O','R','D','E','R',' ','B','Y',' ',
        '`','D','i','s','p','l','a','y','`',0};
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    MSIQUERY *view;
    UINT r;

    if (!list_empty(&package->features))
        return ERROR_SUCCESS;
 
    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r != ERROR_SUCCESS)
        return r;

    r = MSI_IterateRecords( view, NULL, load_feature, package );
1162
    if (r != ERROR_SUCCESS)
1163 1164
    {
        msiobj_release( &view->hdr );
1165
        return r;
1166
    }
1167
    r = MSI_IterateRecords( view, NULL, find_feature_children, package );
1168 1169 1170 1171
    msiobj_release( &view->hdr );
    return r;
}

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
static LPWSTR folder_split_path(LPWSTR p, WCHAR ch)
{
    if (!p)
        return p;
    p = strchrW(p, ch);
    if (!p)
        return p;
    *p = 0;
    return p+1;
}

1183 1184 1185 1186 1187 1188 1189
static UINT load_file_hash(MSIPACKAGE *package, MSIFILE *file)
{
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
        '`','M','s','i','F','i','l','e','H','a','s','h','`',' ',
        'W','H','E','R','E',' ','`','F','i','l','e','_','`',' ','=',' ','\'','%','s','\'',0};
    MSIQUERY *view = NULL;
1190
    MSIRECORD *row = NULL;
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
    UINT r;

    TRACE("%s\n", debugstr_w(file->File));

    r = MSI_OpenQuery(package->db, &view, query, file->File);
    if (r != ERROR_SUCCESS)
        goto done;

    r = MSI_ViewExecute(view, NULL);
    if (r != ERROR_SUCCESS)
        goto done;

    r = MSI_ViewFetch(view, &row);
    if (r != ERROR_SUCCESS)
        goto done;

    file->hash.dwFileHashInfoSize = sizeof(MSIFILEHASHINFO);
    file->hash.dwData[0] = MSI_RecordGetInteger(row, 3);
    file->hash.dwData[1] = MSI_RecordGetInteger(row, 4);
    file->hash.dwData[2] = MSI_RecordGetInteger(row, 5);
    file->hash.dwData[3] = MSI_RecordGetInteger(row, 6);

done:
    if (view) msiobj_release(&view->hdr);
1215
    if (row) msiobj_release(&row->hdr);
1216 1217 1218
    return r;
}

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
static UINT load_file_disk_id( MSIPACKAGE *package, MSIFILE *file )
{
    MSIRECORD *row;
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','`','D','i','s','k','I','d','`',' ', 'F','R','O','M',' ',
        '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
        '`','L','a','s','t','S','e','q','u','e','n','c','e','`',' ','>','=',' ','%','i',0};

    row = MSI_QueryGetRecord( package->db, query, file->Sequence );
    if (!row)
    {
        WARN("query failed\n");
        return ERROR_FUNCTION_FAILED;
    }

    file->disk_id = MSI_RecordGetInteger( row, 1 );
    msiobj_release( &row->hdr );
    return ERROR_SUCCESS;
}

1239
static UINT load_file(MSIRECORD *row, LPVOID param)
1240
{
1241
    MSIPACKAGE* package = param;
1242
    LPCWSTR component;
1243
    MSIFILE *file;
1244 1245 1246

    /* fill in the data */

1247
    file = msi_alloc_zero( sizeof (MSIFILE) );
1248 1249
    if (!file)
        return ERROR_NOT_ENOUGH_MEMORY;
1250
 
1251
    file->File = msi_dup_record_field( row, 1 );
1252

1253
    component = MSI_RecordGetString( row, 2 );
1254
    file->Component = msi_get_loaded_component( package, component );
1255

1256
    if (!file->Component)
1257 1258 1259 1260 1261 1262
    {
        WARN("Component not found: %s\n", debugstr_w(component));
        msi_free(file->File);
        msi_free(file);
        return ERROR_SUCCESS;
    }
1263

1264
    file->FileName = msi_dup_record_field( row, 3 );
1265
    msi_reduce_to_long_filename( file->FileName );
1266

1267
    file->ShortName = msi_dup_record_field( row, 3 );
1268
    file->LongName = strdupW( folder_split_path(file->ShortName, '|'));
1269
    
1270
    file->FileSize = MSI_RecordGetInteger( row, 4 );
1271 1272
    file->Version = msi_dup_record_field( row, 5 );
    file->Language = msi_dup_record_field( row, 6 );
1273 1274 1275
    file->Attributes = MSI_RecordGetInteger( row, 7 );
    file->Sequence = MSI_RecordGetInteger( row, 8 );

1276
    file->state = msifs_invalid;
1277

1278 1279 1280
    /* if the compressed bits are not set in the file attributes,
     * then read the information from the package word count property
     */
1281 1282 1283 1284 1285 1286
    if (package->WordCount & msidbSumInfoSourceTypeAdminImage)
    {
        file->IsCompressed = FALSE;
    }
    else if (file->Attributes &
             (msidbFileAttributesCompressed | msidbFileAttributesPatchAdded))
1287 1288 1289 1290 1291 1292 1293 1294 1295
    {
        file->IsCompressed = TRUE;
    }
    else if (file->Attributes & msidbFileAttributesNoncompressed)
    {
        file->IsCompressed = FALSE;
    }
    else
    {
1296
        file->IsCompressed = package->WordCount & msidbSumInfoSourceTypeCompressed;
1297 1298
    }

1299
    load_file_hash(package, file);
1300
    load_file_disk_id(package, file);
1301

1302
    TRACE("File Loaded (%s)\n",debugstr_w(file->File));  
1303

1304
    list_add_tail( &package->files, &file->entry );
1305 1306 1307 1308
 
    return ERROR_SUCCESS;
}

1309
static UINT load_all_files(MSIPACKAGE *package)
1310
{
1311 1312 1313 1314 1315
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
        '`','F','i','l','e','`',' ', 'O','R','D','E','R',' ','B','Y',' ',
        '`','S','e','q','u','e','n','c','e','`', 0};
    MSIQUERY *view;
1316 1317
    UINT rc;

1318 1319 1320
    if (!list_empty(&package->files))
        return ERROR_SUCCESS;

1321
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
1322
    if (rc != ERROR_SUCCESS)
1323
        return ERROR_SUCCESS;
1324

1325
    rc = MSI_IterateRecords(view, NULL, load_file, package);
1326
    msiobj_release(&view->hdr);
1327
    return rc;
1328 1329
}

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
static UINT load_media( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    UINT disk_id = MSI_RecordGetInteger( row, 1 );
    const WCHAR *cabinet = MSI_RecordGetString( row, 4 );

    /* FIXME: load external cabinets and directory sources too */
    if (!cabinet || cabinet[0] != '#') return ERROR_SUCCESS;
    msi_add_cabinet_stream( package, disk_id, package->db->storage, cabinet );
    return ERROR_SUCCESS;
}

static UINT load_all_media( MSIPACKAGE *package )
{
1344 1345 1346 1347
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','`',
        'M','e','d','i','a','`',' ','O','R','D','E','R',' ','B','Y',' ',
        '`','D','i','s','k','I','d','`',0};
1348 1349 1350 1351
    MSIQUERY *view;
    UINT r;

    r = MSI_DatabaseOpenViewW( package->db, query, &view );
1352 1353
    if (r != ERROR_SUCCESS)
        return ERROR_SUCCESS;
1354

1355
    r = MSI_IterateRecords( view, NULL, load_media, package );
1356
    msiobj_release( &view->hdr );
1357
    return r;
1358 1359
}

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
static UINT load_patch(MSIRECORD *row, LPVOID param)
{
    MSIPACKAGE *package = param;
    MSIFILEPATCH *patch;
    LPWSTR file_key;

    patch = msi_alloc_zero( sizeof (MSIFILEPATCH) );
    if (!patch)
        return ERROR_NOT_ENOUGH_MEMORY;

    file_key = msi_dup_record_field( row, 1 );
1371
    patch->File = msi_get_loaded_file( package, file_key );
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    msi_free(file_key);

    if( !patch->File )
    {
        ERR("Failed to find target for patch in File table\n");
        msi_free(patch);
        return ERROR_FUNCTION_FAILED;
    }

    patch->Sequence = MSI_RecordGetInteger( row, 2 );

    /* FIXME: The database should be properly transformed */
    patch->Sequence += MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;

    patch->PatchSize = MSI_RecordGetInteger( row, 3 );
    patch->Attributes = MSI_RecordGetInteger( row, 4 );
    patch->IsApplied = FALSE;

    /* FIXME:
     * Header field - for patch validation.
     * _StreamRef   - External key into MsiPatchHeaders (instead of the header field)
     */

    TRACE("Patch Loaded (%s)\n", debugstr_w(patch->File->File));

    list_add_tail( &package->filepatches, &patch->entry );

    return ERROR_SUCCESS;
}

static UINT load_all_patches(MSIPACKAGE *package)
{
1404 1405 1406 1407
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','P','a','t','c','h','`',' ','O','R','D','E','R',' ','B','Y',' ',
        '`','S','e','q','u','e','n','c','e','`',0};
1408 1409 1410 1411 1412 1413
    MSIQUERY *view;
    UINT rc;

    if (!list_empty(&package->filepatches))
        return ERROR_SUCCESS;

1414
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
1415 1416 1417 1418 1419
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords(view, NULL, load_patch, package);
    msiobj_release(&view->hdr);
1420
    return rc;
1421 1422
}

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
static UINT load_folder_persistence( MSIPACKAGE *package, MSIFOLDER *folder )
{
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','C','r','e','a','t','e','F','o','l','d','e','r','`',' ','W','H','E','R','E',' ',
        '`','D','i','r','e','c','t','o','r','y','_','`',' ','=','\'','%','s','\'',0};
    MSIQUERY *view;

    folder->persistent = FALSE;
    if (!MSI_OpenQuery( package->db, &view, query, folder->Directory ))
    {
        if (!MSI_ViewExecute( view, NULL ))
        {
            MSIRECORD *rec;
            if (!MSI_ViewFetch( view, &rec ))
            {
                TRACE("directory %s is persistent\n", debugstr_w(folder->Directory));
                folder->persistent = TRUE;
                msiobj_release( &rec->hdr );
            }
        }
        msiobj_release( &view->hdr );
    }
    return ERROR_SUCCESS;
}

1449 1450 1451 1452 1453 1454 1455
static UINT load_folder( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    static WCHAR szEmpty[] = { 0 };
    LPWSTR p, tgt_short, tgt_long, src_short, src_long;
    MSIFOLDER *folder;

1456 1457
    if (!(folder = msi_alloc_zero( sizeof(*folder) ))) return ERROR_NOT_ENOUGH_MEMORY;
    list_init( &folder->children );
1458
    folder->Directory = msi_dup_record_field( row, 1 );
1459 1460
    folder->Parent = msi_dup_record_field( row, 2 );
    p = msi_dup_record_field(row, 3);
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

    TRACE("%s\n", debugstr_w(folder->Directory));

    /* split src and target dir */
    tgt_short = p;
    src_short = folder_split_path( p, ':' );

    /* split the long and short paths */
    tgt_long = folder_split_path( tgt_short, '|' );
    src_long = folder_split_path( src_short, '|' );

    /* check for no-op dirs */
1473
    if (tgt_short && !strcmpW( szDot, tgt_short ))
1474
        tgt_short = szEmpty;
1475
    if (src_short && !strcmpW( szDot, src_short ))
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
        src_short = szEmpty;

    if (!tgt_long)
        tgt_long = tgt_short;

    if (!src_short) {
        src_short = tgt_short;
        src_long = tgt_long;
    }

    if (!src_long)
        src_long = src_short;

    /* FIXME: use the target short path too */
    folder->TargetDefault = strdupW(tgt_long);
    folder->SourceShortPath = strdupW(src_short);
    folder->SourceLongPath = strdupW(src_long);
    msi_free(p);

    TRACE("TargetDefault = %s\n",debugstr_w( folder->TargetDefault ));
    TRACE("SourceLong = %s\n", debugstr_w( folder->SourceLongPath ));
    TRACE("SourceShort = %s\n", debugstr_w( folder->SourceShortPath ));

1499 1500
    load_folder_persistence( package, folder );

1501
    list_add_tail( &package->folders, &folder->entry );
1502 1503
    return ERROR_SUCCESS;
}
1504

1505 1506 1507
static UINT add_folder_child( MSIFOLDER *parent, MSIFOLDER *child )
{
    FolderList *fl;
1508

1509 1510 1511
    if (!(fl = msi_alloc( sizeof(*fl) ))) return ERROR_NOT_ENOUGH_MEMORY;
    fl->folder = child;
    list_add_tail( &parent->children, &fl->entry );
1512 1513 1514
    return ERROR_SUCCESS;
}

1515 1516 1517 1518 1519
static UINT find_folder_children( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    MSIFOLDER *parent, *child;

1520
    if (!(child = msi_get_loaded_folder( package, MSI_RecordGetString( row, 1 ) )))
1521 1522 1523 1524
        return ERROR_FUNCTION_FAILED;

    if (!child->Parent) return ERROR_SUCCESS;

1525
    if (!(parent = msi_get_loaded_folder( package, child->Parent )))
1526 1527 1528 1529 1530
        return ERROR_FUNCTION_FAILED;

    return add_folder_child( parent, child );
}

1531 1532 1533
static UINT load_all_folders( MSIPACKAGE *package )
{
    static const WCHAR query[] = {
1534 1535
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','D','i','r','e','c','t','o','r','y','`',0};
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    MSIQUERY *view;
    UINT r;

    if (!list_empty(&package->folders))
        return ERROR_SUCCESS;

    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r != ERROR_SUCCESS)
        return r;

1546 1547 1548 1549 1550 1551 1552 1553
    r = MSI_IterateRecords( view, NULL, load_folder, package );
    if (r != ERROR_SUCCESS)
    {
        msiobj_release( &view->hdr );
        return r;
    }
    r = MSI_IterateRecords( view, NULL, find_folder_children, package );
    msiobj_release( &view->hdr );
1554 1555
    return r;
}
1556 1557 1558

static UINT ACTION_CostInitialize(MSIPACKAGE *package)
{
1559 1560
    msi_set_property( package->db, szCostingComplete, szZero, -1 );
    msi_set_property( package->db, szRootDrive, szCRoot, -1 );
1561

James Hawkins's avatar
James Hawkins committed
1562
    load_all_folders( package );
1563 1564
    msi_load_all_components( package );
    msi_load_all_features( package );
1565
    load_all_files( package );
1566
    load_all_patches( package );
1567
    load_all_media( package );
1568 1569 1570 1571

    return ERROR_SUCCESS;
}

1572
static UINT execute_script_action( MSIPACKAGE *package, UINT script, UINT index )
1573
{
1574 1575 1576 1577 1578 1579 1580 1581 1582
    const WCHAR *action = package->script->Actions[script][index];
    ui_actionstart( package, action );
    TRACE("executing %s\n", debugstr_w(action));
    return ACTION_PerformAction( package, action, script );
}

static UINT execute_script( MSIPACKAGE *package, UINT script )
{
    UINT i, rc = ERROR_SUCCESS;
1583

1584
    TRACE("executing script %u\n", script);
1585

1586 1587 1588 1589 1590
    if (!package->script)
    {
        ERR("no script!\n");
        return ERROR_FUNCTION_FAILED;
    }
1591
    if (script == SCRIPT_ROLLBACK)
1592
    {
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
        for (i = package->script->ActionCount[script]; i > 0; i--)
        {
            rc = execute_script_action( package, script, i - 1 );
            if (rc != ERROR_SUCCESS) break;
        }
    }
    else
    {
        for (i = 0; i < package->script->ActionCount[script]; i++)
        {
            rc = execute_script_action( package, script, i );
            if (rc != ERROR_SUCCESS) break;
        }
1606
    }
1607
    msi_free_action_script(package, script);
1608 1609 1610
    return rc;
}

1611 1612 1613 1614 1615
static UINT ACTION_FileCost(MSIPACKAGE *package)
{
    return ERROR_SUCCESS;
}

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
static void get_client_counts( MSIPACKAGE *package )
{
    MSICOMPONENT *comp;
    HKEY hkey;

    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
        if (!comp->ComponentId) continue;

        if (MSIREG_OpenUserDataComponentKey( comp->ComponentId, szLocalSid, &hkey, FALSE ) &&
            MSIREG_OpenUserDataComponentKey( comp->ComponentId, NULL, &hkey, FALSE ))
        {
            comp->num_clients = 0;
            continue;
        }
        RegQueryInfoKeyW( hkey, NULL, NULL, NULL, NULL, NULL, NULL, (DWORD *)&comp->num_clients,
                          NULL, NULL, NULL, NULL );
        RegCloseKey( hkey );
    }
}

1637
static void ACTION_GetComponentInstallStates(MSIPACKAGE *package)
1638
{
1639
    MSICOMPONENT *comp;
1640
    UINT r;
1641

1642 1643
    LIST_FOR_EACH_ENTRY(comp, &package->components, MSICOMPONENT, entry)
    {
1644
        if (!comp->ComponentId) continue;
1645

1646 1647 1648
        r = MsiQueryComponentStateW( package->ProductCode, NULL,
                                     MSIINSTALLCONTEXT_USERMANAGED, comp->ComponentId,
                                     &comp->Installed );
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
        if (r == ERROR_SUCCESS) continue;

        r = MsiQueryComponentStateW( package->ProductCode, NULL,
                                     MSIINSTALLCONTEXT_USERUNMANAGED, comp->ComponentId,
                                     &comp->Installed );
        if (r == ERROR_SUCCESS) continue;

        r = MsiQueryComponentStateW( package->ProductCode, NULL,
                                     MSIINSTALLCONTEXT_MACHINE, comp->ComponentId,
                                     &comp->Installed );
        if (r == ERROR_SUCCESS) continue;

        comp->Installed = INSTALLSTATE_ABSENT;
1662
    }
1663 1664
}

1665
static void ACTION_GetFeatureInstallStates(MSIPACKAGE *package)
1666 1667
{
    MSIFEATURE *feature;
1668

1669
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
1670
    {
1671 1672 1673
        INSTALLSTATE state = MsiQueryFeatureStateW( package->ProductCode, feature->Feature );

        if (state == INSTALLSTATE_UNKNOWN || state == INSTALLSTATE_INVALIDARG)
1674 1675
            feature->Installed = INSTALLSTATE_ABSENT;
        else
1676
            feature->Installed = state;
1677 1678 1679
    }
}

1680 1681 1682 1683 1684
static inline BOOL is_feature_selected( MSIFEATURE *feature, INT level )
{
    return (feature->Level > 0 && feature->Level <= level);
}

1685 1686
static BOOL process_state_property(MSIPACKAGE* package, int level,
                                   LPCWSTR property, INSTALLSTATE state)
1687
{
1688
    LPWSTR override;
1689
    MSIFEATURE *feature;
1690

1691
    override = msi_dup_property( package->db, property );
1692 1693
    if (!override)
        return FALSE;
1694

1695
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
1696
    {
1697
        if (strcmpW( property, szRemove ) && !is_feature_selected( feature, level ))
1698 1699
            continue;

1700
        if (!strcmpW(property, szReinstall)) state = feature->Installed;
1701

1702
        if (!strcmpiW( override, szAll ))
1703 1704 1705 1706 1707 1708 1709
        {
            if (feature->Installed != state)
            {
                feature->Action = state;
                feature->ActionRequest = state;
            }
        }
1710 1711 1712 1713
        else
        {
            LPWSTR ptr = override;
            LPWSTR ptr2 = strchrW(override,',');
1714

1715 1716
            while (ptr)
            {
1717 1718 1719 1720
                int len = ptr2 - ptr;

                if ((ptr2 && strlenW(feature->Feature) == len && !strncmpW(ptr, feature->Feature, len))
                    || (!ptr2 && !strcmpW(ptr, feature->Feature)))
1721
                {
1722 1723 1724 1725 1726
                    if (feature->Installed != state)
                    {
                        feature->Action = state;
                        feature->ActionRequest = state;
                    }
1727
                    break;
1728
                }
1729 1730 1731 1732 1733 1734 1735
                if (ptr2)
                {
                    ptr=ptr2+1;
                    ptr2 = strchrW(ptr,',');
                }
                else
                    break;
1736
            }
1737
        }
1738
    }
1739
    msi_free(override);
1740
    return TRUE;
1741 1742
}

1743
static BOOL process_overrides( MSIPACKAGE *package, int level )
1744
{
1745 1746
    static const WCHAR szAddLocal[] =
        {'A','D','D','L','O','C','A','L',0};
1747 1748
    static const WCHAR szAddSource[] =
        {'A','D','D','S','O','U','R','C','E',0};
1749 1750
    static const WCHAR szAdvertise[] =
        {'A','D','V','E','R','T','I','S','E',0};
1751
    BOOL ret = FALSE;
1752

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    /* all these activation/deactivation things happen in order and things
     * later on the list override things earlier on the list.
     *
     *  0  INSTALLLEVEL processing
     *  1  ADDLOCAL
     *  2  REMOVE
     *  3  ADDSOURCE
     *  4  ADDDEFAULT
     *  5  REINSTALL
     *  6  ADVERTISE
     *  7  COMPADDLOCAL
     *  8  COMPADDSOURCE
     *  9  FILEADDLOCAL
     * 10  FILEADDSOURCE
     * 11  FILEADDDEFAULT
     */
    ret |= process_state_property( package, level, szAddLocal, INSTALLSTATE_LOCAL );
    ret |= process_state_property( package, level, szRemove, INSTALLSTATE_ABSENT );
    ret |= process_state_property( package, level, szAddSource, INSTALLSTATE_SOURCE );
    ret |= process_state_property( package, level, szReinstall, INSTALLSTATE_UNKNOWN );
    ret |= process_state_property( package, level, szAdvertise, INSTALLSTATE_ADVERTISED );
1774

1775
    if (ret && !package->full_reinstall)
1776
        msi_set_property( package->db, szPreselected, szOne, -1 );
1777 1778 1779 1780 1781 1782 1783 1784 1785

    return ret;
}

UINT MSI_SetFeatureStates(MSIPACKAGE *package)
{
    int level;
    MSICOMPONENT* component;
    MSIFEATURE *feature;
1786 1787 1788

    TRACE("Checking Install Level\n");

1789
    level = msi_get_property_int(package->db, szInstallLevel, 1);
1790

1791
    if (!msi_get_property_int( package->db, szPreselected, 0 ))
1792
    {
1793
        LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
1794
        {
1795
            if (!is_feature_selected( feature, level )) continue;
1796

1797
            if (feature->ActionRequest == INSTALLSTATE_UNKNOWN)
1798
            {
1799
                if (feature->Attributes & msidbFeatureAttributesFavorSource)
1800 1801 1802 1803
                {
                    feature->Action = INSTALLSTATE_SOURCE;
                    feature->ActionRequest = INSTALLSTATE_SOURCE;
                }
1804
                else if (feature->Attributes & msidbFeatureAttributesFavorAdvertise)
1805 1806 1807 1808
                {
                    feature->Action = INSTALLSTATE_ADVERTISED;
                    feature->ActionRequest = INSTALLSTATE_ADVERTISED;
                }
1809
                else
1810 1811 1812 1813
                {
                    feature->Action = INSTALLSTATE_LOCAL;
                    feature->ActionRequest = INSTALLSTATE_LOCAL;
                }
1814
            }
1815
        }
1816
        /* disable child features of unselected parent or follow parent */
1817 1818 1819 1820 1821
        LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
        {
            FeatureList *fl;

            LIST_FOR_EACH_ENTRY( fl, &feature->Children, FeatureList, entry )
1822
            {
1823 1824 1825 1826 1827 1828 1829
                if (!is_feature_selected( feature, level ))
                {
                    fl->feature->Action = INSTALLSTATE_UNKNOWN;
                    fl->feature->ActionRequest = INSTALLSTATE_UNKNOWN;
                }
                else if (fl->feature->Attributes & msidbFeatureAttributesFollowParent)
                {
1830 1831 1832
                    TRACE("feature %s (level %d request %d) follows parent %s (level %d request %d)\n",
                          debugstr_w(fl->feature->Feature), fl->feature->Level, fl->feature->ActionRequest,
                          debugstr_w(feature->Feature), feature->Level, feature->ActionRequest);
1833 1834 1835
                    fl->feature->Action = feature->Action;
                    fl->feature->ActionRequest = feature->ActionRequest;
                }
1836
            }
1837
        }
1838
    }
1839
    else /* preselected */
1840 1841 1842
    {
        LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
        {
1843
            if (!is_feature_selected( feature, level )) continue;
1844

1845
            if (feature->ActionRequest == INSTALLSTATE_UNKNOWN)
1846
            {
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
                if (feature->Installed == INSTALLSTATE_ABSENT)
                {
                    feature->Action = INSTALLSTATE_UNKNOWN;
                    feature->ActionRequest = INSTALLSTATE_UNKNOWN;
                }
                else
                {
                    feature->Action = feature->Installed;
                    feature->ActionRequest = feature->Installed;
                }
1857 1858
            }
        }
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
        LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
        {
            FeatureList *fl;

            LIST_FOR_EACH_ENTRY( fl, &feature->Children, FeatureList, entry )
            {
                if (fl->feature->Attributes & msidbFeatureAttributesFollowParent &&
                    (!(feature->Attributes & msidbFeatureAttributesFavorAdvertise)))
                {
                    TRACE("feature %s (level %d request %d) follows parent %s (level %d request %d)\n",
                          debugstr_w(fl->feature->Feature), fl->feature->Level, fl->feature->ActionRequest,
                          debugstr_w(feature->Feature), feature->Level, feature->ActionRequest);
                    fl->feature->Action = feature->Action;
                    fl->feature->ActionRequest = feature->ActionRequest;
                }
            }
        }
1876
    }
1877

1878
    /* now we want to set component state based based on feature state */
1879
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
1880
    {
1881 1882
        ComponentList *cl;

1883
        TRACE("examining feature %s (level %d installed %d request %d action %d)\n",
1884 1885
              debugstr_w(feature->Feature), feature->Level, feature->Installed,
              feature->ActionRequest, feature->Action);
1886

1887
        if (!is_feature_selected( feature, level )) continue;
1888 1889 1890 1891

        /* features with components that have compressed files are made local */
        LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
        {
1892
            if (cl->component->ForceLocalState &&
1893
                feature->ActionRequest == INSTALLSTATE_SOURCE)
1894
            {
1895 1896
                feature->Action = INSTALLSTATE_LOCAL;
                feature->ActionRequest = INSTALLSTATE_LOCAL;
1897 1898 1899
                break;
            }
        }
1900

1901
        LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
1902
        {
1903
            component = cl->component;
1904

1905
            switch (feature->ActionRequest)
1906
            {
1907 1908 1909
            case INSTALLSTATE_ABSENT:
                component->anyAbsent = 1;
                break;
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
            case INSTALLSTATE_ADVERTISED:
                component->hasAdvertiseFeature = 1;
                break;
            case INSTALLSTATE_SOURCE:
                component->hasSourceFeature = 1;
                break;
            case INSTALLSTATE_LOCAL:
                component->hasLocalFeature = 1;
                break;
            case INSTALLSTATE_DEFAULT:
                if (feature->Attributes & msidbFeatureAttributesFavorAdvertise)
                    component->hasAdvertiseFeature = 1;
                else if (feature->Attributes & msidbFeatureAttributesFavorSource)
                    component->hasSourceFeature = 1;
1924
                else
1925 1926 1927 1928
                    component->hasLocalFeature = 1;
                break;
            default:
                break;
1929
            }
1930 1931
        }
    }
1932

1933 1934 1935 1936 1937 1938 1939 1940
    LIST_FOR_EACH_ENTRY( component, &package->components, MSICOMPONENT, entry )
    {
        /* check if it's local or source */
        if (!(component->Attributes & msidbComponentAttributesOptional) &&
             (component->hasLocalFeature || component->hasSourceFeature))
        {
            if ((component->Attributes & msidbComponentAttributesSourceOnly) &&
                 !component->ForceLocalState)
1941 1942 1943 1944
            {
                component->Action = INSTALLSTATE_SOURCE;
                component->ActionRequest = INSTALLSTATE_SOURCE;
            }
1945
            else
1946 1947 1948 1949
            {
                component->Action = INSTALLSTATE_LOCAL;
                component->ActionRequest = INSTALLSTATE_LOCAL;
            }
1950 1951
            continue;
        }
1952

1953 1954 1955
        /* if any feature is local, the component must be local too */
        if (component->hasLocalFeature)
        {
1956 1957
            component->Action = INSTALLSTATE_LOCAL;
            component->ActionRequest = INSTALLSTATE_LOCAL;
1958 1959 1960 1961
            continue;
        }
        if (component->hasSourceFeature)
        {
1962 1963
            component->Action = INSTALLSTATE_SOURCE;
            component->ActionRequest = INSTALLSTATE_SOURCE;
1964
            continue;
1965
        }
1966 1967
        if (component->hasAdvertiseFeature)
        {
1968 1969
            component->Action = INSTALLSTATE_ADVERTISED;
            component->ActionRequest = INSTALLSTATE_ADVERTISED;
1970 1971 1972
            continue;
        }
        TRACE("nobody wants component %s\n", debugstr_w(component->Component));
1973
        if (component->anyAbsent && component->ComponentId)
1974 1975 1976 1977
        {
            component->Action = INSTALLSTATE_ABSENT;
            component->ActionRequest = INSTALLSTATE_ABSENT;
        }
1978
    }
1979

1980
    LIST_FOR_EACH_ENTRY( component, &package->components, MSICOMPONENT, entry )
1981
    {
1982
        if (component->ActionRequest == INSTALLSTATE_DEFAULT)
1983 1984
        {
            TRACE("%s was default, setting to local\n", debugstr_w(component->Component));
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
            component->Action = INSTALLSTATE_LOCAL;
            component->ActionRequest = INSTALLSTATE_LOCAL;
        }

        if (component->ActionRequest == INSTALLSTATE_SOURCE &&
            component->Installed == INSTALLSTATE_SOURCE &&
            component->hasSourceFeature)
        {
            component->Action = INSTALLSTATE_UNKNOWN;
            component->ActionRequest = INSTALLSTATE_UNKNOWN;
1995 1996
        }

1997
        TRACE("component %s (installed %d request %d action %d)\n",
1998
              debugstr_w(component->Component), component->Installed, component->ActionRequest, component->Action);
1999 2000 2001 2002 2003

        if (component->Action == INSTALLSTATE_LOCAL || component->Action == INSTALLSTATE_SOURCE)
            component->num_clients++;
        else if (component->Action == INSTALLSTATE_ABSENT)
            component->num_clients--;
2004 2005
    }

2006 2007 2008
    return ERROR_SUCCESS;
}

2009 2010
static UINT ITERATE_CostFinalizeConditions(MSIRECORD *row, LPVOID param)
{
2011
    MSIPACKAGE *package = param;
2012 2013
    LPCWSTR name;
    MSIFEATURE *feature;
2014

2015
    name = MSI_RecordGetString( row, 1 );
2016

2017
    feature = msi_get_loaded_feature( package, name );
2018 2019
    if (!feature)
        ERR("FAILED to find loaded feature %s\n",debugstr_w(name));
2020 2021 2022 2023 2024
    else
    {
        LPCWSTR Condition;
        Condition = MSI_RecordGetString(row,3);

2025
        if (MSI_EvaluateConditionW(package,Condition) == MSICONDITION_TRUE)
2026 2027
        {
            int level = MSI_RecordGetInteger(row,2);
2028
            TRACE("Resetting feature %s to level %i\n", debugstr_w(name), level);
2029
            feature->Level = level;
2030 2031 2032 2033 2034
        }
    }
    return ERROR_SUCCESS;
}

2035
VS_FIXEDFILEINFO *msi_get_disk_file_version( LPCWSTR filename )
2036
{
2037
    static const WCHAR name[] = {'\\',0};
2038
    VS_FIXEDFILEINFO *ptr, *ret;
2039
    LPVOID version;
2040
    DWORD versize, handle;
2041 2042 2043 2044 2045 2046 2047
    UINT sz;

    versize = GetFileVersionInfoSizeW( filename, &handle );
    if (!versize)
        return NULL;

    version = msi_alloc( versize );
2048 2049 2050
    if (!version)
        return NULL;

2051 2052
    GetFileVersionInfoW( filename, 0, versize, version );

2053
    if (!VerQueryValueW( version, name, (LPVOID *)&ptr, &sz ))
2054 2055 2056 2057
    {
        msi_free( version );
        return NULL;
    }
2058

2059 2060 2061
    ret = msi_alloc( sz );
    memcpy( ret, ptr, sz );

2062
    msi_free( version );
2063 2064
    return ret;
}
2065

2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
int msi_compare_file_versions( VS_FIXEDFILEINFO *fi, const WCHAR *version )
{
    DWORD ms, ls;

    msi_parse_version_string( version, &ms, &ls );

    if (fi->dwFileVersionMS > ms) return 1;
    else if (fi->dwFileVersionMS < ms) return -1;
    else if (fi->dwFileVersionLS > ls) return 1;
    else if (fi->dwFileVersionLS < ls) return -1;
    return 0;
2077 2078
}

2079
int msi_compare_font_versions( const WCHAR *ver1, const WCHAR *ver2 )
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
{
    DWORD ms1, ms2;

    msi_parse_version_string( ver1, &ms1, NULL );
    msi_parse_version_string( ver2, &ms2, NULL );

    if (ms1 > ms2) return 1;
    else if (ms1 < ms2) return -1;
    return 0;
}

2091
DWORD msi_get_disk_file_size( LPCWSTR filename )
2092 2093 2094 2095 2096 2097 2098 2099 2100
{
    HANDLE file;
    DWORD size;

    file = CreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
    if (file == INVALID_HANDLE_VALUE)
        return INVALID_FILE_SIZE;

    size = GetFileSize( file, NULL );
2101
    TRACE("size is %u\n", size);
2102 2103 2104 2105
    CloseHandle( file );
    return size;
}

2106
BOOL msi_file_hash_matches( MSIFILE *file )
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
{
    UINT r;
    MSIFILEHASHINFO hash;

    hash.dwFileHashInfoSize = sizeof(MSIFILEHASHINFO);
    r = MsiGetFileHashW( file->TargetPath, 0, &hash );
    if (r != ERROR_SUCCESS)
        return FALSE;

    return !memcmp( &hash, &file->hash, sizeof(MSIFILEHASHINFO) );
}

2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
static WCHAR *get_temp_dir( void )
{
    static UINT id;
    WCHAR tmp[MAX_PATH], dir[MAX_PATH];

    GetTempPathW( MAX_PATH, tmp );
    for (;;)
    {
        if (!GetTempFileNameW( tmp, szMsi, ++id, dir )) return NULL;
        if (CreateDirectoryW( dir, NULL )) break;
    }
    return strdupW( dir );
}

2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
/*
 *  msi_build_directory_name()
 *
 *  This function is to save messing round with directory names
 *  It handles adding backslashes between path segments,
 *  and can add \ at the end of the directory name if told to.
 *
 *  It takes a variable number of arguments.
 *  It always allocates a new string for the result, so make sure
 *  to free the return value when finished with it.
 *
 *  The first arg is the number of path segments that follow.
 *  The arguments following count are a list of path segments.
 *  A path segment may be NULL.
 *
 *  Path segments will be added with a \ separating them.
 *  A \ will not be added after the last segment, however if the
 *  last segment is NULL, then the last character will be a \
 */
WCHAR *msi_build_directory_name( DWORD count, ... )
{
    DWORD sz = 1, i;
    WCHAR *dir;
    va_list va;

    va_start( va, count );
    for (i = 0; i < count; i++)
    {
        const WCHAR *str = va_arg( va, const WCHAR * );
        if (str) sz += strlenW( str ) + 1;
    }
    va_end( va );

    dir = msi_alloc( sz * sizeof(WCHAR) );
    dir[0] = 0;

    va_start( va, count );
    for (i = 0; i < count; i++)
    {
        const WCHAR *str = va_arg( va, const WCHAR * );
        if (!str) continue;
        strcatW( dir, str );
2175
        if ( i + 1 != count && dir[0] && dir[strlenW( dir ) - 1] != '\\') strcatW( dir, szBackSlash );
2176 2177 2178 2179 2180
    }
    va_end( va );
    return dir;
}

2181 2182 2183 2184 2185 2186 2187
static void set_target_path( MSIPACKAGE *package, MSIFILE *file )
{
    MSIASSEMBLY *assembly = file->Component->assembly;

    TRACE("file %s is named %s\n", debugstr_w(file->File), debugstr_w(file->FileName));

    msi_free( file->TargetPath );
2188
    if (assembly && !assembly->application)
2189 2190
    {
        if (!assembly->tempdir) assembly->tempdir = get_temp_dir();
2191 2192
        file->TargetPath = msi_build_directory_name( 2, assembly->tempdir, file->FileName );
        msi_track_tempfile( package, file->TargetPath );
2193 2194 2195
    }
    else
    {
2196
        const WCHAR *dir = msi_get_target_folder( package, file->Component->Directory );
2197
        file->TargetPath = msi_build_directory_name( 2, dir, file->FileName );
2198 2199 2200 2201 2202
    }

    TRACE("resolves to %s\n", debugstr_w(file->TargetPath));
}

2203
static UINT calculate_file_cost( MSIPACKAGE *package )
2204
{
2205
    VS_FIXEDFILEINFO *file_version;
2206
    WCHAR *font_version;
2207
    MSIFILE *file;
2208

2209
    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
2210
    {
2211
        MSICOMPONENT *comp = file->Component;
2212
        DWORD file_size;
2213

2214
        if (!comp->Enabled) continue;
2215

2216 2217 2218
        if (file->IsCompressed)
            comp->ForceLocalState = TRUE;

2219
        set_target_path( package, file );
2220

2221 2222
        if ((comp->assembly && !comp->assembly->installed) ||
            GetFileAttributesW(file->TargetPath) == INVALID_FILE_ATTRIBUTES)
2223 2224 2225 2226
        {
            comp->Cost += file->FileSize;
            continue;
        }
2227 2228
        file_size = msi_get_disk_file_size( file->TargetPath );

2229
        if (file->Version)
2230
        {
2231
            if ((file_version = msi_get_disk_file_version( file->TargetPath )))
2232
            {
2233 2234
                if (msi_compare_file_versions( file_version, file->Version ) < 0)
                {
2235
                    comp->Cost += file->FileSize - file_size;
2236 2237 2238
                }
                msi_free( file_version );
                continue;
2239
            }
2240
            else if ((font_version = msi_font_version_from_file( file->TargetPath )))
2241
            {
2242 2243
                if (msi_compare_font_versions( font_version, file->Version ) < 0)
                {
2244
                    comp->Cost += file->FileSize - file_size;
2245 2246 2247
                }
                msi_free( font_version );
                continue;
2248
            }
2249
        }
2250
        if (file_size != file->FileSize)
2251
        {
2252 2253
            comp->Cost += file->FileSize - file_size;
        }
2254
    }
2255 2256 2257
    return ERROR_SUCCESS;
}

2258
WCHAR *msi_normalize_path( const WCHAR *in )
2259
{
2260 2261 2262
    const WCHAR *p = in;
    WCHAR *q, *ret;
    int n, len = strlenW( in ) + 2;
2263

2264 2265 2266
    if (!(q = ret = msi_alloc( len * sizeof(WCHAR) ))) return NULL;

    len = 0;
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
    while (1)
    {
        /* copy until the end of the string or a space */
        while (*p != ' ' && (*q = *p))
        {
            p++, len++;
            /* reduce many backslashes to one */
            if (*p != '\\' || *q != '\\')
                q++;
        }

        /* quit at the end of the string */
        if (!*p)
            break;

        /* count the number of spaces */
        n = 0;
        while (p[n] == ' ')
            n++;

        /* if it's leading or trailing space, skip it */
        if ( len == 0 || p[-1] == '\\' || p[n] == '\\' )
            p += n;
        else  /* copy n spaces */
            while (n && (*q++ = *p++)) n--;
    }
2293 2294
    while (q - ret > 0 && q[-1] == ' ') q--;
    if (q - ret > 0 && q[-1] != '\\')
2295
    {
2296 2297
        q[0] = '\\';
        q[1] = 0;
2298
    }
2299
    return ret;
2300 2301
}

2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
static WCHAR *get_install_location( MSIPACKAGE *package )
{
    HKEY hkey;
    WCHAR *path;

    if (!package->ProductCode) return NULL;
    if (MSIREG_OpenInstallProps( package->ProductCode, package->Context, NULL, &hkey, FALSE ))
        return NULL;
    path = msi_reg_get_val_str( hkey, szInstallLocation );
    RegCloseKey( hkey );
    return path;
}

2315 2316 2317 2318
void msi_resolve_target_folder( MSIPACKAGE *package, const WCHAR *name, BOOL load_prop )
{
    FolderList *fl;
    MSIFOLDER *folder, *parent, *child;
2319
    WCHAR *path, *normalized_path;
2320 2321 2322

    TRACE("resolving %s\n", debugstr_w(name));

2323
    if (!(folder = msi_get_loaded_folder( package, name ))) return;
2324

2325
    if (!strcmpW( folder->Directory, szTargetDir )) /* special resolving for target root dir */
2326
    {
2327 2328
        if (!(path = get_install_location( package )) &&
            (!load_prop || !(path = msi_dup_property( package->db, szTargetDir ))))
2329
        {
2330
            path = msi_dup_property( package->db, szRootDrive );
2331 2332 2333 2334
        }
    }
    else if (!load_prop || !(path = msi_dup_property( package->db, folder->Directory )))
    {
2335 2336 2337 2338 2339 2340 2341
        if (folder->Parent && strcmpW( folder->Directory, folder->Parent ))
        {
            parent = msi_get_loaded_folder( package, folder->Parent );
            path = msi_build_directory_name( 3, parent->ResolvedTarget, folder->TargetDefault, NULL );
        }
        else
            path = msi_build_directory_name( 2, folder->TargetDefault, NULL );
2342
    }
2343 2344 2345
    normalized_path = msi_normalize_path( path );
    msi_free( path );
    if (folder->ResolvedTarget && !strcmpiW( normalized_path, folder->ResolvedTarget ))
2346 2347
    {
        TRACE("%s already resolved to %s\n", debugstr_w(name), debugstr_w(folder->ResolvedTarget));
2348
        msi_free( normalized_path );
2349 2350
        return;
    }
2351
    msi_set_property( package->db, folder->Directory, normalized_path, -1 );
2352
    msi_free( folder->ResolvedTarget );
2353
    folder->ResolvedTarget = normalized_path;
2354 2355 2356 2357 2358 2359 2360 2361 2362

    LIST_FOR_EACH_ENTRY( fl, &folder->children, FolderList, entry )
    {
        child = fl->folder;
        msi_resolve_target_folder( package, child->Directory, load_prop );
    }
    TRACE("%s resolves to %s\n", debugstr_w(name), debugstr_w(folder->ResolvedTarget));
}

2363 2364
static UINT ACTION_CostFinalize(MSIPACKAGE *package)
{
2365 2366 2367 2368 2369
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','C','o','n','d','i','t','i','o','n','`',0};
    static const WCHAR szOutOfDiskSpace[] = {
        'O','u','t','O','f','D','i','s','k','S','p','a','c','e',0};
2370
    MSICOMPONENT *comp;
2371
    MSIQUERY *view;
2372
    LPWSTR level;
2373
    UINT rc;
2374

2375
    TRACE("Building directory properties\n");
2376
    msi_resolve_target_folder( package, szTargetDir, TRUE );
2377

2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
    TRACE("Evaluating component conditions\n");
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
        if (MSI_EvaluateConditionW( package, comp->Condition ) == MSICONDITION_FALSE)
        {
            TRACE("Disabling component %s\n", debugstr_w(comp->Component));
            comp->Enabled = FALSE;
        }
        else
            comp->Enabled = TRUE;
    }
2389
    get_client_counts( package );
2390

2391 2392
    /* read components states from the registry */
    ACTION_GetComponentInstallStates(package);
2393
    ACTION_GetFeatureInstallStates(package);
2394

2395
    if (!process_overrides( package, msi_get_property_int( package->db, szInstallLevel, 1 ) ))
2396
    {
2397
        TRACE("Evaluating feature conditions\n");
2398

2399
        rc = MSI_DatabaseOpenViewW( package->db, query, &view );
2400
        if (rc == ERROR_SUCCESS)
2401
        {
2402 2403
            rc = MSI_IterateRecords( view, NULL, ITERATE_CostFinalizeConditions, package );
            msiobj_release( &view->hdr );
2404 2405
            if (rc != ERROR_SUCCESS)
                return rc;
2406
        }
2407
    }
2408

2409 2410
    TRACE("Calculating file cost\n");
    calculate_file_cost( package );
2411

2412
    msi_set_property( package->db, szCostingComplete, szOne, -1 );
2413
    /* set default run level if not set */
2414
    level = msi_dup_property( package->db, szInstallLevel );
2415
    if (!level)
2416
        msi_set_property( package->db, szInstallLevel, szOne, -1 );
2417
    msi_free(level);
2418

2419
    /* FIXME: check volume disk space */
2420
    msi_set_property( package->db, szOutOfDiskSpace, szZero, -1 );
2421

2422
    return MSI_SetFeatureStates(package);
2423 2424
}

2425
static BYTE *parse_value( MSIPACKAGE *package, const WCHAR *value, DWORD *type, DWORD *size )
2426
{
2427
    BYTE *data = NULL;
2428

2429 2430
    if (!value)
    {
2431
        *size = sizeof(WCHAR);
2432
        *type = REG_SZ;
2433
        if ((data = msi_alloc( *size ))) *(WCHAR *)data = 0;
2434 2435
        return data;
    }
2436
    if (value[0]=='#' && value[1]!='#' && value[1]!='%')
2437
    {
2438 2439 2440 2441
        if (value[1]=='x')
        {
            LPWSTR ptr;
            CHAR byte[5];
2442
            LPWSTR deformated = NULL;
2443 2444
            int count;

2445
            deformat_string(package, &value[2], &deformated);
2446 2447

            /* binary value type */
2448 2449 2450 2451 2452 2453 2454
            ptr = deformated;
            *type = REG_BINARY;
            if (strlenW(ptr)%2)
                *size = (strlenW(ptr)/2)+1;
            else
                *size = strlenW(ptr)/2;

2455
            data = msi_alloc(*size);
2456

2457 2458 2459 2460
            byte[0] = '0'; 
            byte[1] = 'x'; 
            byte[4] = 0; 
            count = 0;
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
            /* if uneven pad with a zero in front */
            if (strlenW(ptr)%2)
            {
                byte[2]= '0';
                byte[3]= *ptr;
                ptr++;
                data[count] = (BYTE)strtol(byte,NULL,0);
                count ++;
                TRACE("Uneven byte count\n");
            }
2471 2472 2473 2474 2475 2476 2477 2478 2479
            while (*ptr)
            {
                byte[2]= *ptr;
                ptr++;
                byte[3]= *ptr;
                ptr++;
                data[count] = (BYTE)strtol(byte,NULL,0);
                count ++;
            }
2480
            msi_free(deformated);
2481

2482
            TRACE("Data %i bytes(%i)\n",*size,count);
2483 2484 2485 2486
        }
        else
        {
            LPWSTR deformated;
2487 2488
            LPWSTR p;
            DWORD d = 0;
2489
            deformat_string(package, &value[1], &deformated);
2490 2491 2492

            *type=REG_DWORD; 
            *size = sizeof(DWORD);
2493
            data = msi_alloc(*size);
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
            p = deformated;
            if (*p == '-')
                p++;
            while (*p)
            {
                if ( (*p < '0') || (*p > '9') )
                    break;
                d *= 10;
                d += (*p - '0');
                p++;
            }
            if (deformated[0] == '-')
                d = -d;
            *(LPDWORD)data = d;
2508
            TRACE("DWORD %i\n",*(LPDWORD)data);
2509

2510
            msi_free(deformated);
2511
        }
2512 2513 2514
    }
    else
    {
2515 2516
        const WCHAR *ptr = value;
        DWORD len;
2517

2518 2519
        *type = REG_SZ;
        if (value[0] == '#')
2520
        {
2521 2522
            ptr++;
            if (value[1] == '%')
2523
            {
2524 2525
                ptr++;
                *type = REG_EXPAND_SZ;
2526
            }
2527
        }
2528 2529 2530
        len = deformat_string( package, ptr, (WCHAR **)&data );
        if (len > strlenW( (const WCHAR *)data )) *type = REG_MULTI_SZ;
        *size = (len + 1) * sizeof(WCHAR);
2531 2532 2533 2534
    }
    return data;
}

2535 2536 2537 2538 2539 2540 2541
static const WCHAR *get_root_key( MSIPACKAGE *package, INT root, HKEY *root_key )
{
    const WCHAR *ret;

    switch (root)
    {
    case -1:
2542
        if (msi_get_property_int( package->db, szAllUsers, 0 ))
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
        {
            *root_key = HKEY_LOCAL_MACHINE;
            ret = szHLM;
        }
        else
        {
            *root_key = HKEY_CURRENT_USER;
            ret = szHCU;
        }
        break;
    case 0:
        *root_key = HKEY_CLASSES_ROOT;
        ret = szHCR;
        break;
    case 1:
        *root_key = HKEY_CURRENT_USER;
        ret = szHCU;
        break;
    case 2:
        *root_key = HKEY_LOCAL_MACHINE;
        ret = szHLM;
        break;
    case 3:
        *root_key = HKEY_USERS;
        ret = szHU;
        break;
    default:
        ERR("Unknown root %i\n", root);
        return NULL;
    }

    return ret;
}

2577
static WCHAR *get_keypath( MSICOMPONENT *comp, HKEY root, const WCHAR *path )
2578 2579 2580 2581
{
    static const WCHAR prefixW[] = {'S','O','F','T','W','A','R','E','\\'};
    static const UINT len = sizeof(prefixW) / sizeof(prefixW[0]);

2582 2583
    if ((is_64bit || is_wow64) &&
        !(comp->Attributes & msidbComponentAttributes64bit) &&
2584 2585 2586 2587 2588
        root == HKEY_LOCAL_MACHINE && !strncmpiW( path, prefixW, len ))
    {
        UINT size;
        WCHAR *path_32node;

2589 2590
        size = (strlenW( path ) + strlenW( szWow6432Node ) + 2) * sizeof(WCHAR);
        if (!(path_32node = msi_alloc( size ))) return NULL;
2591 2592

        memcpy( path_32node, path, len * sizeof(WCHAR) );
2593
        strcpyW( path_32node + len, szWow6432Node );
2594 2595 2596 2597 2598 2599 2600
        strcatW( path_32node, szBackSlash );
        strcatW( path_32node, path + len );
        return path_32node;
    }
    return strdupW( path );
}

2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
static HKEY open_key( HKEY root, const WCHAR *path, BOOL create )
{
    REGSAM access = KEY_ALL_ACCESS;
    WCHAR *subkey, *p, *q;
    HKEY hkey, ret = NULL;
    LONG res;

    if (is_wow64) access |= KEY_WOW64_64KEY;

    if (!(subkey = strdupW( path ))) return NULL;
    p = subkey;
    if ((q = strchrW( p, '\\' ))) *q = 0;
    if (create)
        res = RegCreateKeyExW( root, subkey, 0, NULL, 0, access, NULL, &hkey, NULL );
    else
        res = RegOpenKeyExW( root, subkey, 0, access, &hkey );
    if (res)
    {
        TRACE("failed to open key %s (%d)\n", debugstr_w(subkey), res);
        msi_free( subkey );
        return NULL;
    }
    if (q && q[1])
    {
        ret = open_key( hkey, q + 1, create );
        RegCloseKey( hkey );
    }
    else ret = hkey;
    msi_free( subkey );
    return ret;
}

2633
static BOOL is_special_entry( const WCHAR *name )
2634
{
2635
     return (name && (name[0] == '*' || name[0] == '+') && !name[1]);
2636 2637
}

2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
static WCHAR **split_multi_string_values( const WCHAR *str, DWORD len, DWORD *count )
{
    const WCHAR *p = str;
    WCHAR **ret;
    int i = 0;

    *count = 0;
    if (!str) return NULL;
    while ((p - str) < len)
    {
        p += strlenW( p ) + 1;
        (*count)++;
    }
    if (!(ret = msi_alloc( *count * sizeof(WCHAR *) ))) return NULL;
    p = str;
    while ((p - str) < len)
    {
        if (!(ret[i] = strdupW( p )))
        {
            for (; i >= 0; i--) msi_free( ret[i] );
            msi_free( ret );
            return NULL;
        }
        p += strlenW( p ) + 1;
        i++;
    }
    return ret;
}

static WCHAR *flatten_multi_string_values( WCHAR **left, DWORD left_count,
                                           WCHAR **right, DWORD right_count, DWORD *size )
{
    WCHAR *ret, *p;
    unsigned int i;

    *size = sizeof(WCHAR);
    for (i = 0; i < left_count; i++) *size += (strlenW( left[i] ) + 1) * sizeof(WCHAR);
    for (i = 0; i < right_count; i++) *size += (strlenW( right[i] ) + 1) * sizeof(WCHAR);

    if (!(ret = p = msi_alloc( *size ))) return NULL;

    for (i = 0; i < left_count; i++)
    {
        strcpyW( p, left[i] );
        p += strlenW( p ) + 1;
    }
    for (i = 0; i < right_count; i++)
    {
        strcpyW( p, right[i] );
        p += strlenW( p ) + 1;
    }
    *p = 0;
    return ret;
}

static DWORD remove_duplicate_values( WCHAR **old, DWORD old_count,
                                      WCHAR **new, DWORD new_count )
{
    DWORD ret = old_count;
    unsigned int i, j, k;

    for (i = 0; i < new_count; i++)
    {
        for (j = 0; j < old_count; j++)
        {
            if (old[j] && !strcmpW( new[i], old[j] ))
            {
                msi_free( old[j] );
                for (k = j; k < old_count - 1; k++) { old[k] = old[k + 1]; }
                old[k] = NULL;
                ret--;
            }
        }
    }
    return ret;
}

enum join_op
{
    JOIN_OP_APPEND,
    JOIN_OP_PREPEND,
    JOIN_OP_REPLACE
};

static WCHAR *join_multi_string_values( enum join_op op, WCHAR **old, DWORD old_count,
                                        WCHAR **new, DWORD new_count, DWORD *size )
{
    switch (op)
    {
    case JOIN_OP_APPEND:
        old_count = remove_duplicate_values( old, old_count, new, new_count );
        return flatten_multi_string_values( old, old_count, new, new_count, size );

    case JOIN_OP_PREPEND:
        old_count = remove_duplicate_values( old, old_count, new, new_count );
        return flatten_multi_string_values( new, new_count, old, old_count, size );

    case JOIN_OP_REPLACE:
        return flatten_multi_string_values( new, new_count, NULL, 0, size );

    default:
        ERR("unhandled join op %u\n", op);
        return NULL;
    }
}

static BYTE *build_multi_string_value( BYTE *old_value, DWORD old_size,
                                       BYTE *new_value, DWORD new_size, DWORD *size )
{
    DWORD i, old_len = 0, new_len = 0, old_count = 0, new_count = 0;
    const WCHAR *new_ptr = NULL, *old_ptr = NULL;
    enum join_op op = JOIN_OP_REPLACE;
    WCHAR **old = NULL, **new = NULL;
    BYTE *ret;

    if (new_size / sizeof(WCHAR) - 1 > 1)
    {
        new_ptr = (const WCHAR *)new_value;
        new_len = new_size / sizeof(WCHAR) - 1;

        if (!new_ptr[0] && new_ptr[new_len - 1])
        {
            op = JOIN_OP_APPEND;
            new_len--;
            new_ptr++;
        }
        else if (new_ptr[0] && !new_ptr[new_len - 1])
        {
            op = JOIN_OP_PREPEND;
            new_len--;
        }
        else if (new_len > 2 && !new_ptr[0] && !new_ptr[new_len - 1])
        {
            op = JOIN_OP_REPLACE;
            new_len -= 2;
            new_ptr++;
        }
        new = split_multi_string_values( new_ptr, new_len, &new_count );
    }
    if (old_size / sizeof(WCHAR) - 1 > 1)
    {
        old_ptr = (const WCHAR *)old_value;
        old_len = old_size / sizeof(WCHAR) - 1;
        old = split_multi_string_values( old_ptr, old_len, &old_count );
    }
    ret = (BYTE *)join_multi_string_values( op, old, old_count, new, new_count, size );
    for (i = 0; i < old_count; i++) msi_free( old[i] );
    for (i = 0; i < new_count; i++) msi_free( new[i] );
    msi_free( old );
    msi_free( new );
    return ret;
}

static BYTE *reg_get_value( HKEY hkey, const WCHAR *name, DWORD *type, DWORD *size )
{
    BYTE *ret;
    if (RegQueryValueExW( hkey, name, NULL, NULL, NULL, size )) return NULL;
    if (!(ret = msi_alloc( *size ))) return NULL;
    RegQueryValueExW( hkey, name, NULL, type, ret, size );
    return ret;
}

2800
static UINT ITERATE_WriteRegistryValues(MSIRECORD *row, LPVOID param)
2801
{
2802
    MSIPACKAGE *package = param;
2803
    BYTE *new_value, *old_value = NULL;
2804
    HKEY  root_key, hkey;
2805
    DWORD type, old_type, new_size, old_size = 0;
2806
    LPWSTR deformated, uikey, keypath;
2807
    const WCHAR *szRoot, *component, *name, *key, *str;
2808
    MSICOMPONENT *comp;
2809 2810 2811
    MSIRECORD * uirow;
    INT   root;
    BOOL check_first = FALSE;
2812
    int len;
2813

2814
    msi_ui_progress( package, 2, REG_PROGRESS_VALUE, 0, 0 );
2815

2816
    component = MSI_RecordGetString(row, 6);
2817
    comp = msi_get_loaded_component(package,component);
2818 2819
    if (!comp)
        return ERROR_SUCCESS;
2820

2821 2822
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
2823
    {
2824
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
2825 2826
        return ERROR_SUCCESS;
    }
2827

2828 2829 2830 2831 2832 2833
    name = MSI_RecordGetString(row, 4);
    if( MSI_RecordIsNull(row,5) && name )
    {
        /* null values can have special meanings */
        if (name[0]=='-' && name[1] == 0)
                return ERROR_SUCCESS;
2834 2835
        if ((name[0] == '+' || name[0] == '*') && !name[1])
            check_first = TRUE;
2836
    }
2837

2838 2839 2840
    root = MSI_RecordGetInteger(row,2);
    key = MSI_RecordGetString(row, 3);

2841 2842
    szRoot = get_root_key( package, root, &root_key );
    if (!szRoot)
2843
        return ERROR_SUCCESS;
2844

2845
    deformat_string(package, key , &deformated);
2846
    uikey = msi_alloc( (strlenW(deformated) + strlenW(szRoot) + 1) * sizeof(WCHAR) );
2847 2848
    strcpyW(uikey,szRoot);
    strcatW(uikey,deformated);
2849

2850
    keypath = get_keypath( comp, root_key, deformated );
2851
    msi_free( deformated );
2852
    if (!(hkey = open_key( root_key, keypath, TRUE )))
2853
    {
2854
        ERR("Could not create key %s\n", debugstr_w(keypath));
2855
        msi_free(uikey);
2856
        msi_free(keypath);
2857
        return ERROR_FUNCTION_FAILED;
2858
    }
2859 2860 2861 2862 2863 2864 2865 2866
    str = msi_record_get_string( row, 5, &len );
    if (str && len > strlenW( str ))
    {
        type = REG_MULTI_SZ;
        new_size = (len + 1) * sizeof(WCHAR);
        new_value = (BYTE *)msi_strdupW( str, len );
    }
    else new_value = parse_value( package, str, &type, &new_size );
2867
    deformat_string(package, name, &deformated);
2868 2869

    if (!is_special_entry( name ))
2870
    {
2871 2872 2873 2874
        old_value = reg_get_value( hkey, deformated, &old_type, &old_size );
        if (type == REG_MULTI_SZ)
        {
            BYTE *new;
2875
            if (old_value && old_type != REG_MULTI_SZ)
2876 2877 2878 2879 2880 2881 2882 2883 2884
            {
                msi_free( old_value );
                old_value = NULL;
                old_size = 0;
            }
            new = build_multi_string_value( old_value, old_size, new_value, new_size, &new_size );
            msi_free( new_value );
            new_value = new;
        }
2885
        if (!check_first)
Aric Stewart's avatar
Aric Stewart committed
2886
        {
2887 2888
            TRACE("setting value %s of %s type %u\n", debugstr_w(deformated), debugstr_w(uikey), type);
            RegSetValueExW( hkey, deformated, 0, type, new_value, new_size );
Aric Stewart's avatar
Aric Stewart committed
2889
        }
2890
        else if (!old_value)
Aric Stewart's avatar
Aric Stewart committed
2891
        {
2892
            if (deformated || new_size)
2893
            {
2894 2895
                TRACE("setting value %s of %s type %u\n", debugstr_w(deformated), debugstr_w(uikey), type);
                RegSetValueExW( hkey, deformated, 0, type, new_value, new_size );
2896
            }
Aric Stewart's avatar
Aric Stewart committed
2897
        }
2898
        else TRACE("not overwriting existing value %s of %s\n", debugstr_w(deformated), debugstr_w(uikey));
2899 2900
    }
    RegCloseKey(hkey);
2901

2902 2903 2904
    uirow = MSI_CreateRecord(3);
    MSI_RecordSetStringW(uirow,2,deformated);
    MSI_RecordSetStringW(uirow,1,uikey);
2905
    if (type == REG_SZ || type == REG_EXPAND_SZ)
2906
        MSI_RecordSetStringW(uirow, 3, (LPWSTR)new_value);
2907
    msi_ui_actiondata( package, szWriteRegistryValues, uirow );
2908
    msiobj_release( &uirow->hdr );
2909

2910 2911
    msi_free(new_value);
    msi_free(old_value);
2912 2913
    msi_free(deformated);
    msi_free(uikey);
2914
    msi_free(keypath);
2915 2916 2917 2918 2919 2920

    return ERROR_SUCCESS;
}

static UINT ACTION_WriteRegistryValues(MSIPACKAGE *package)
{
2921 2922 2923 2924
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','R','e','g','i','s','t','r','y','`',0};
    MSIQUERY *view;
2925 2926
    UINT rc;

2927
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
2928 2929 2930 2931
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords(view, NULL, ITERATE_WriteRegistryValues, package);
2932
    msiobj_release(&view->hdr);
2933 2934 2935
    return rc;
}

2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
static void delete_key( HKEY root, const WCHAR *path )
{
    REGSAM access = 0;
    WCHAR *subkey, *p;
    HKEY hkey;
    LONG res;

    if (is_wow64) access |= KEY_WOW64_64KEY;

    if (!(subkey = strdupW( path ))) return;
    for (;;)
    {
        if ((p = strrchrW( subkey, '\\' ))) *p = 0;
        hkey = open_key( root, subkey, FALSE );
        if (!hkey) break;
        if (p && p[1])
            res = RegDeleteKeyExW( hkey, p + 1, access, 0 );
        else
            res = RegDeleteKeyExW( root, subkey, access, 0 );
        if (res)
        {
            TRACE("failed to delete key %s (%d)\n", debugstr_w(subkey), res);
            break;
        }
        if (p && p[1]) RegCloseKey( hkey );
        else break;
    }
    msi_free( subkey );
}

static void delete_value( HKEY root, const WCHAR *path, const WCHAR *value )
2967 2968 2969 2970 2971
{
    LONG res;
    HKEY hkey;
    DWORD num_subkeys, num_values;

2972
    if ((hkey = open_key( root, path, FALSE )))
2973 2974
    {
        if ((res = RegDeleteValueW( hkey, value )))
2975
            TRACE("failed to delete value %s (%d)\n", debugstr_w(value), res);
2976

2977 2978 2979 2980 2981
        res = RegQueryInfoKeyW( hkey, NULL, NULL, NULL, &num_subkeys, NULL, NULL, &num_values,
                                NULL, NULL, NULL, NULL );
        RegCloseKey( hkey );
        if (!res && !num_subkeys && !num_values)
        {
2982 2983
            TRACE("removing empty key %s\n", debugstr_w(path));
            delete_key( root, path );
2984 2985 2986 2987
        }
    }
}

2988
static void delete_tree( HKEY root, const WCHAR *path )
2989
{
2990
    LONG res;
2991
    HKEY hkey;
2992 2993

    if (!(hkey = open_key( root, path, FALSE ))) return;
2994
    res = RegDeleteTreeW( hkey, NULL );
2995 2996
    if (res) TRACE("failed to delete subtree of %s (%d)\n", debugstr_w(path), res);
    delete_key( root, path );
2997
    RegCloseKey( hkey );
2998
}
2999 3000 3001 3002 3003

static UINT ITERATE_RemoveRegistryValuesOnUninstall( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR component, name, key_str, root_key_str;
3004
    LPWSTR deformated_key, deformated_name, ui_key_str, keypath;
3005 3006 3007 3008 3009 3010 3011
    MSICOMPONENT *comp;
    MSIRECORD *uirow;
    BOOL delete_key = FALSE;
    HKEY hkey_root;
    UINT size;
    INT root;

3012
    msi_ui_progress( package, 2, REG_PROGRESS_VALUE, 0, 0 );
3013 3014

    component = MSI_RecordGetString( row, 6 );
3015
    comp = msi_get_loaded_component( package, component );
3016 3017 3018
    if (!comp)
        return ERROR_SUCCESS;

3019 3020
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
3021
    {
3022
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
3023 3024 3025 3026 3027 3028 3029 3030
        return ERROR_SUCCESS;
    }

    name = MSI_RecordGetString( row, 4 );
    if (MSI_RecordIsNull( row, 5 ) && name )
    {
        if (name[0] == '+' && !name[1])
            return ERROR_SUCCESS;
3031
        if ((name[0] == '-' || name[0] == '*') && !name[1])
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052
        {
            delete_key = TRUE;
            name = NULL;
        }
    }

    root = MSI_RecordGetInteger( row, 2 );
    key_str = MSI_RecordGetString( row, 3 );

    root_key_str = get_root_key( package, root, &hkey_root );
    if (!root_key_str)
        return ERROR_SUCCESS;

    deformat_string( package, key_str, &deformated_key );
    size = strlenW( deformated_key ) + strlenW( root_key_str ) + 1;
    ui_key_str = msi_alloc( size * sizeof(WCHAR) );
    strcpyW( ui_key_str, root_key_str );
    strcatW( ui_key_str, deformated_key );

    deformat_string( package, name, &deformated_name );

3053
    keypath = get_keypath( comp, hkey_root, deformated_key );
3054
    msi_free( deformated_key );
3055 3056
    if (delete_key) delete_tree( hkey_root, keypath );
    else delete_value( hkey_root, keypath, deformated_name );
3057
    msi_free( keypath );
3058 3059 3060 3061

    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, ui_key_str );
    MSI_RecordSetStringW( uirow, 2, deformated_name );
3062
    msi_ui_actiondata( package, szRemoveRegistryValues, uirow );
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
    msiobj_release( &uirow->hdr );

    msi_free( ui_key_str );
    msi_free( deformated_name );
    return ERROR_SUCCESS;
}

static UINT ITERATE_RemoveRegistryValuesOnInstall( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR component, name, key_str, root_key_str;
3074
    LPWSTR deformated_key, deformated_name, ui_key_str, keypath;
3075 3076 3077 3078 3079 3080 3081 3082
    MSICOMPONENT *comp;
    MSIRECORD *uirow;
    BOOL delete_key = FALSE;
    HKEY hkey_root;
    UINT size;
    INT root;

    component = MSI_RecordGetString( row, 5 );
3083
    comp = msi_get_loaded_component( package, component );
3084 3085 3086
    if (!comp)
        return ERROR_SUCCESS;

3087 3088
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
3089
    {
3090
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
        return ERROR_SUCCESS;
    }

    if ((name = MSI_RecordGetString( row, 4 )))
    {
        if (name[0] == '-' && !name[1])
        {
            delete_key = TRUE;
            name = NULL;
        }
    }

    root = MSI_RecordGetInteger( row, 2 );
    key_str = MSI_RecordGetString( row, 3 );

    root_key_str = get_root_key( package, root, &hkey_root );
    if (!root_key_str)
        return ERROR_SUCCESS;

    deformat_string( package, key_str, &deformated_key );
    size = strlenW( deformated_key ) + strlenW( root_key_str ) + 1;
    ui_key_str = msi_alloc( size * sizeof(WCHAR) );
    strcpyW( ui_key_str, root_key_str );
    strcatW( ui_key_str, deformated_key );

    deformat_string( package, name, &deformated_name );

3118
    keypath = get_keypath( comp, hkey_root, deformated_key );
3119
    msi_free( deformated_key );
3120 3121
    if (delete_key) delete_tree( hkey_root, keypath );
    else delete_value( hkey_root, keypath, deformated_name );
3122
    msi_free( keypath );
3123 3124 3125 3126

    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, ui_key_str );
    MSI_RecordSetStringW( uirow, 2, deformated_name );
3127
    msi_ui_actiondata( package, szRemoveRegistryValues, uirow );
3128 3129 3130 3131 3132 3133 3134 3135 3136
    msiobj_release( &uirow->hdr );

    msi_free( ui_key_str );
    msi_free( deformated_name );
    return ERROR_SUCCESS;
}

static UINT ACTION_RemoveRegistryValues( MSIPACKAGE *package )
{
3137 3138 3139 3140 3141 3142
    static const WCHAR registry_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','R','e','g','i','s','t','r','y','`',0};
    static const WCHAR remove_registry_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','R','e','m','o','v','e','R','e','g','i','s','t','r','y','`',0};
3143
    MSIQUERY *view;
3144
    UINT rc;
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164

    rc = MSI_DatabaseOpenViewW( package->db, registry_query, &view );
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveRegistryValuesOnUninstall, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
    rc = MSI_DatabaseOpenViewW( package->db, remove_registry_query, &view );
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveRegistryValuesOnInstall, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
    return ERROR_SUCCESS;
}

3165
static UINT ACTION_InstallInitialize(MSIPACKAGE *package)
3166
{
3167 3168
    package->script->CurrentlyScripting = TRUE;

3169 3170 3171
    return ERROR_SUCCESS;
}

3172

3173
static UINT ACTION_InstallValidate(MSIPACKAGE *package)
3174
{
3175 3176 3177
    static const WCHAR query[]= {
        'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
        '`','R','e','g','i','s','t','r','y','`',0};
3178
    MSICOMPONENT *comp;
3179
    DWORD total = 0, count = 0;
3180
    MSIQUERY *view;
3181
    MSIFEATURE *feature;
3182
    MSIFILE *file;
3183
    UINT rc;
3184

3185
    TRACE("InstallValidate\n");
3186

3187
    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
3188
    if (rc == ERROR_SUCCESS)
3189
    {
3190
        rc = MSI_IterateRecords( view, &count, NULL, package );
3191
        msiobj_release( &view->hdr );
3192 3193
        if (rc != ERROR_SUCCESS)
            return rc;
3194
        total += count * REG_PROGRESS_VALUE;
3195
    }
3196 3197
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
        total += COMPONENT_PROGRESS_VALUE;
3198

3199 3200
    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
        total += file->FileSize;
3201

3202
    msi_ui_progress( package, 0, total, 0, 0 );
3203

3204
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
3205
    {
3206 3207 3208
        TRACE("Feature: %s Installed %d Request %d Action %d\n",
              debugstr_w(feature->Feature), feature->Installed,
              feature->ActionRequest, feature->Action);
3209
    }
3210 3211 3212
    return ERROR_SUCCESS;
}

3213 3214
static UINT ITERATE_LaunchConditions(MSIRECORD *row, LPVOID param)
{
3215
    MSIPACKAGE* package = param;
3216 3217
    LPCWSTR cond = NULL; 
    LPCWSTR message = NULL;
3218 3219
    UINT r;

3220 3221 3222 3223 3224
    static const WCHAR title[]=
        {'I','n','s','t','a','l','l',' ','F','a', 'i','l','e','d',0};

    cond = MSI_RecordGetString(row,1);

3225 3226
    r = MSI_EvaluateConditionW(package,cond);
    if (r == MSICONDITION_FALSE)
3227
    {
3228
        if ((package->ui_level & INSTALLUILEVEL_MASK) != INSTALLUILEVEL_NONE)
3229 3230 3231 3232 3233 3234 3235 3236 3237
        {
            LPWSTR deformated;
            message = MSI_RecordGetString(row,2);
            deformat_string(package,message,&deformated);
            MessageBoxW(NULL,deformated,title,MB_OK);
            msi_free(deformated);
        }

        return ERROR_INSTALL_FAILURE;
3238 3239 3240 3241 3242
    }

    return ERROR_SUCCESS;
}

3243
static UINT ACTION_LaunchConditions(MSIPACKAGE *package)
3244
{
3245 3246 3247 3248
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','L','a','u','n','c','h','C','o','n','d','i','t','i','o','n','`',0};
    MSIQUERY *view;
3249 3250 3251 3252
    UINT rc;

    TRACE("Checking launch conditions\n");

3253
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
3254
    if (rc != ERROR_SUCCESS)
3255
        return ERROR_SUCCESS;
3256

3257
    rc = MSI_IterateRecords(view, NULL, ITERATE_LaunchConditions, package);
3258
    msiobj_release(&view->hdr);
3259 3260
    return rc;
}
3261

3262
static LPWSTR resolve_keypath( MSIPACKAGE* package, MSICOMPONENT *cmp )
3263 3264
{

3265
    if (!cmp->KeyPath)
3266
        return strdupW( msi_get_target_folder( package, cmp->Directory ) );
3267

3268
    if (cmp->Attributes & msidbComponentAttributesRegistryKeyPath)
3269
    {
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
        static const WCHAR query[] = {
            'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
            '`','R','e','g','i','s','t','r','y','`',' ','W','H','E','R','E',' ',
            '`','R','e','g','i','s','t','r','y','`',' ','=',' ' ,'\'','%','s','\'',0};
        static const WCHAR fmt[] = {'%','0','2','i',':','\\','%','s','\\',0};
        static const WCHAR fmt2[]= {'%','0','2','i',':','\\','%','s','\\','%','s',0};
        MSIRECORD *row;
        UINT root, len;
        LPWSTR deformated, buffer, deformated_name;
        LPCWSTR key, name;

        row = MSI_QueryGetRecord(package->db, query, cmp->KeyPath);
3282
        if (!row)
3283 3284 3285
            return NULL;

        root = MSI_RecordGetInteger(row,2);
3286 3287
        key = MSI_RecordGetString(row, 3);
        name = MSI_RecordGetString(row, 4);
3288 3289 3290
        deformat_string(package, key , &deformated);
        deformat_string(package, name, &deformated_name);

3291
        len = strlenW(deformated) + 6;
3292 3293 3294
        if (deformated_name)
            len+=strlenW(deformated_name);

3295
        buffer = msi_alloc( len *sizeof(WCHAR));
3296 3297 3298 3299 3300 3301

        if (deformated_name)
            sprintfW(buffer,fmt2,root,deformated,deformated_name);
        else
            sprintfW(buffer,fmt,root,deformated);

3302 3303
        msi_free(deformated);
        msi_free(deformated_name);
3304 3305 3306 3307
        msiobj_release(&row->hdr);

        return buffer;
    }
3308
    else if (cmp->Attributes & msidbComponentAttributesODBCDataSource)
3309 3310
    {
        FIXME("UNIMPLEMENTED keypath as ODBC Source\n");
3311
        return NULL;
3312 3313 3314
    }
    else
    {
3315
        MSIFILE *file = msi_get_loaded_file( package, cmp->KeyPath );
3316

3317 3318
        if (file)
            return strdupW( file->TargetPath );
3319
    }
3320
    return NULL;
3321 3322
}

3323
static HKEY openSharedDLLsKey(void)
3324 3325
{
    HKEY hkey=0;
3326 3327 3328 3329 3330 3331
    static const WCHAR path[] =
        {'S','o','f','t','w','a','r','e','\\',
         'M','i','c','r','o','s','o','f','t','\\',
         'W','i','n','d','o','w','s','\\',
         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
         'S','h','a','r','e','d','D','L','L','s',0};
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358

    RegCreateKeyW(HKEY_LOCAL_MACHINE,path,&hkey);
    return hkey;
}

static UINT ACTION_GetSharedDLLsCount(LPCWSTR dll)
{
    HKEY hkey;
    DWORD count=0;
    DWORD type;
    DWORD sz = sizeof(count);
    DWORD rc;
    
    hkey = openSharedDLLsKey();
    rc = RegQueryValueExW(hkey, dll, NULL, &type, (LPBYTE)&count, &sz);
    if (rc != ERROR_SUCCESS)
        count = 0;
    RegCloseKey(hkey);
    return count;
}

static UINT ACTION_WriteSharedDLLsCount(LPCWSTR path, UINT count)
{
    HKEY hkey;

    hkey = openSharedDLLsKey();
    if (count > 0)
3359
        msi_reg_set_val_dword( hkey, path, count );
3360 3361 3362 3363 3364 3365
    else
        RegDeleteValueW(hkey,path);
    RegCloseKey(hkey);
    return count;
}

3366
static void ACTION_RefCountComponent( MSIPACKAGE* package, MSICOMPONENT *comp )
3367
{
3368
    MSIFEATURE *feature;
3369 3370 3371 3372
    INT count = 0;
    BOOL write = FALSE;

    /* only refcount DLLs */
3373
    if (comp->KeyPath == NULL || 
3374
        comp->assembly ||
3375 3376
        comp->Attributes & msidbComponentAttributesRegistryKeyPath || 
        comp->Attributes & msidbComponentAttributesODBCDataSource)
3377 3378 3379
        write = FALSE;
    else
    {
3380
        count = ACTION_GetSharedDLLsCount( comp->FullKeypath);
3381 3382
        write = (count > 0);

3383
        if (comp->Attributes & msidbComponentAttributesSharedDllRefCount)
3384 3385 3386 3387
            write = TRUE;
    }

    /* increment counts */
3388
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
3389
    {
3390
        ComponentList *cl;
3391

3392
        if (msi_get_feature_action( package, feature ) != INSTALLSTATE_LOCAL)
3393 3394
            continue;

3395
        LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
3396
        {
3397
            if ( cl->component == comp )
3398 3399 3400
                count++;
        }
    }
3401

3402
    /* decrement counts */
3403
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
3404
    {
3405 3406
        ComponentList *cl;

3407
        if (msi_get_feature_action( package, feature ) != INSTALLSTATE_ABSENT)
3408 3409
            continue;

3410
        LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
3411
        {
3412
            if ( cl->component == comp )
3413 3414 3415 3416 3417 3418
                count--;
        }
    }

    /* ref count all the files in the component */
    if (write)
3419 3420 3421 3422
    {
        MSIFILE *file;

        LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
3423
        {
3424 3425
            if (file->Component == comp)
                ACTION_WriteSharedDLLsCount( file->TargetPath, count );
3426
        }
3427
    }
3428
    
Austin English's avatar
Austin English committed
3429
    /* add a count for permanent */
3430
    if (comp->Attributes & msidbComponentAttributesPermanent)
3431 3432
        count ++;
    
3433
    comp->RefCount = count;
3434 3435

    if (write)
3436
        ACTION_WriteSharedDLLsCount( comp->FullKeypath, comp->RefCount );
3437 3438
}

3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456
static WCHAR *build_full_keypath( MSIPACKAGE *package, MSICOMPONENT *comp )
{
    if (comp->assembly)
    {
        const WCHAR prefixW[] = {'<','\\',0};
        DWORD len = strlenW( prefixW ) + strlenW( comp->assembly->display_name );
        WCHAR *keypath = msi_alloc( (len + 1) * sizeof(WCHAR) );

        if (keypath)
        {
            strcpyW( keypath, prefixW );
            strcatW( keypath, comp->assembly->display_name );
        }
        return keypath;
    }
    return resolve_keypath( package, comp );
}

3457
static UINT ACTION_ProcessComponents(MSIPACKAGE *package)
3458
{
3459
    WCHAR squished_pc[GUID_SIZE], squished_cc[GUID_SIZE];
3460
    UINT rc;
3461
    MSICOMPONENT *comp;
3462
    HKEY hkey;
3463

3464 3465
    TRACE("\n");

3466
    squash_guid(package->ProductCode,squished_pc);
3467 3468
    msi_set_sourcedir_props(package, FALSE);

3469
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
3470
    {
3471 3472
        MSIRECORD *uirow;
        INSTALLSTATE action;
3473

3474
        msi_ui_progress( package, 2, COMPONENT_PROGRESS_VALUE, 0, 0 );
3475 3476
        if (!comp->ComponentId)
            continue;
3477

3478 3479 3480
        squash_guid( comp->ComponentId, squished_cc );
        msi_free( comp->FullKeypath );
        comp->FullKeypath = build_full_keypath( package, comp );
3481

3482
        ACTION_RefCountComponent( package, comp );
3483

3484 3485 3486
        if (package->need_rollback) action = comp->Installed;
        else action = comp->ActionRequest;

3487
        TRACE("Component %s (%s) Keypath=%s RefCount=%u Clients=%u Action=%u\n",
3488
                            debugstr_w(comp->Component), debugstr_w(squished_cc),
3489
                            debugstr_w(comp->FullKeypath), comp->RefCount, comp->num_clients, action);
3490 3491

        if (action == INSTALLSTATE_LOCAL || action == INSTALLSTATE_SOURCE)
3492
        {
3493
            if (package->Context == MSIINSTALLCONTEXT_MACHINE)
3494
                rc = MSIREG_OpenUserDataComponentKey(comp->ComponentId, szLocalSid, &hkey, TRUE);
3495
            else
3496
                rc = MSIREG_OpenUserDataComponentKey(comp->ComponentId, NULL, &hkey, TRUE);
3497

3498 3499
            if (rc != ERROR_SUCCESS)
                continue;
3500

3501
            if (comp->Attributes & msidbComponentAttributesPermanent)
3502
            {
3503 3504 3505 3506
                static const WCHAR szPermKey[] =
                    { '0','0','0','0','0','0','0','0','0','0','0','0',
                      '0','0','0','0','0','0','0','0','0','0','0','0',
                      '0','0','0','0','0','0','0','0',0 };
3507

3508
                msi_reg_set_val_str(hkey, szPermKey, comp->FullKeypath);
3509
            }
3510
            if (action == INSTALLSTATE_LOCAL)
3511 3512 3513 3514 3515 3516 3517 3518
                msi_reg_set_val_str(hkey, squished_pc, comp->FullKeypath);
            else
            {
                MSIFILE *file;
                MSIRECORD *row;
                LPWSTR ptr, ptr2;
                WCHAR source[MAX_PATH];
                WCHAR base[MAX_PATH];
3519
                LPWSTR sourcepath;
3520 3521 3522 3523 3524 3525 3526 3527 3528

                static const WCHAR fmt[] = {'%','0','2','d','\\',0};
                static const WCHAR query[] = {
                    'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
                    '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
                    '`','L','a','s','t','S','e','q','u','e','n','c','e','`',' ',
                    '>','=',' ','%','i',' ','O','R','D','E','R',' ','B','Y',' ',
                    '`','D','i','s','k','I','d','`',0};

3529
                if (!comp->KeyPath || !(file = msi_get_loaded_file(package, comp->KeyPath)))
3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
                    continue;

                row = MSI_QueryGetRecord(package->db, query, file->Sequence);
                sprintfW(source, fmt, MSI_RecordGetInteger(row, 1));
                ptr2 = strrchrW(source, '\\') + 1;
                msiobj_release(&row->hdr);

                lstrcpyW(base, package->PackagePath);
                ptr = strrchrW(base, '\\');
                *(ptr + 1) = '\0';

3541
                sourcepath = msi_resolve_file_source(package, file);
3542
                ptr = sourcepath + lstrlenW(base);
3543
                lstrcpyW(ptr2, ptr);
3544
                msi_free(sourcepath);
3545 3546 3547

                msi_reg_set_val_str(hkey, squished_pc, source);
            }
3548
            RegCloseKey(hkey);
3549
        }
3550
        else if (action == INSTALLSTATE_ABSENT)
3551
        {
3552 3553 3554 3555 3556 3557 3558
            if (comp->num_clients <= 0)
            {
                if (package->Context == MSIINSTALLCONTEXT_MACHINE)
                    MSIREG_DeleteUserDataComponentKey( comp->ComponentId, szLocalSid );
                else
                    MSIREG_DeleteUserDataComponentKey( comp->ComponentId, NULL );
            }
3559
        }
3560 3561 3562 3563 3564 3565

        /* UI stuff */
        uirow = MSI_CreateRecord(3);
        MSI_RecordSetStringW(uirow,1,package->ProductCode);
        MSI_RecordSetStringW(uirow,2,comp->ComponentId);
        MSI_RecordSetStringW(uirow,3,comp->FullKeypath);
3566
        msi_ui_actiondata( package, szProcessComponents, uirow );
3567 3568
        msiobj_release( &uirow->hdr );
    }
3569
    return ERROR_SUCCESS;
3570 3571
}

3572 3573 3574 3575 3576 3577 3578 3579
typedef struct {
    CLSID       clsid;
    LPWSTR      source;

    LPWSTR      path;
    ITypeLib    *ptLib;
} typelib_struct;

3580
static BOOL CALLBACK Typelib_EnumResNameProc( HMODULE hModule, LPCWSTR lpszType, 
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
                                       LPWSTR lpszName, LONG_PTR lParam)
{
    TLIBATTR *attr;
    typelib_struct *tl_struct = (typelib_struct*) lParam;
    static const WCHAR fmt[] = {'%','s','\\','%','i',0};
    int sz; 
    HRESULT res;

    if (!IS_INTRESOURCE(lpszName))
    {
        ERR("Not Int Resource Name %s\n",debugstr_w(lpszName));
        return TRUE;
    }

    sz = strlenW(tl_struct->source)+4;
    sz *= sizeof(WCHAR);

3598
    if ((INT_PTR)lpszName == 1)
3599 3600 3601
        tl_struct->path = strdupW(tl_struct->source);
    else
    {
3602
        tl_struct->path = msi_alloc(sz);
3603 3604
        sprintfW(tl_struct->path,fmt,tl_struct->source, lpszName);
    }
3605 3606 3607

    TRACE("trying %s\n", debugstr_w(tl_struct->path));
    res = LoadTypeLib(tl_struct->path,&tl_struct->ptLib);
3608
    if (FAILED(res))
3609
    {
3610
        msi_free(tl_struct->path);
3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
        tl_struct->path = NULL;

        return TRUE;
    }

    ITypeLib_GetLibAttr(tl_struct->ptLib, &attr);
    if (IsEqualGUID(&(tl_struct->clsid),&(attr->guid)))
    {
        ITypeLib_ReleaseTLibAttr(tl_struct->ptLib, attr);
        return FALSE;
    }

3623
    msi_free(tl_struct->path);
3624 3625 3626 3627 3628 3629 3630 3631
    tl_struct->path = NULL;

    ITypeLib_ReleaseTLibAttr(tl_struct->ptLib, attr);
    ITypeLib_Release(tl_struct->ptLib);

    return TRUE;
}

3632
static UINT ITERATE_RegisterTypeLibraries(MSIRECORD *row, LPVOID param)
3633
{
3634
    MSIPACKAGE* package = param;
3635
    LPCWSTR component;
3636
    MSICOMPONENT *comp;
3637
    MSIFILE *file;
3638
    typelib_struct tl_struct;
3639
    ITypeLib *tlib;
3640
    HMODULE module;
3641 3642
    HRESULT hr;

3643
    component = MSI_RecordGetString(row,3);
3644
    comp = msi_get_loaded_component(package,component);
3645
    if (!comp)
3646
        return ERROR_SUCCESS;
3647

3648 3649
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
3650
    {
3651
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
3652 3653
        return ERROR_SUCCESS;
    }
3654

3655
    if (!comp->KeyPath || !(file = msi_get_loaded_file( package, comp->KeyPath )))
3656 3657
    {
        TRACE("component has no key path\n");
3658
        return ERROR_SUCCESS;
3659
    }
3660
    msi_ui_actiondata( package, szRegisterTypeLibraries, row );
3661

3662
    module = LoadLibraryExW( file->TargetPath, NULL, LOAD_LIBRARY_AS_DATAFILE );
3663
    if (module)
3664
    {
3665 3666
        LPCWSTR guid;
        guid = MSI_RecordGetString(row,1);
3667
        CLSIDFromString( guid, &tl_struct.clsid);
3668
        tl_struct.source = strdupW( file->TargetPath );
3669
        tl_struct.path = NULL;
3670

3671 3672
        EnumResourceNamesW(module, szTYPELIB, Typelib_EnumResNameProc,
                        (LONG_PTR)&tl_struct);
3673

3674
        if (tl_struct.path)
3675
        {
3676
            LPCWSTR helpid, help_path = NULL;
3677
            HRESULT res;
3678

3679
            helpid = MSI_RecordGetString(row,6);
3680

3681 3682
            if (helpid) help_path = msi_get_target_folder( package, helpid );
            res = RegisterTypeLib( tl_struct.ptLib, tl_struct.path, (OLECHAR *)help_path );
3683

3684
            if (FAILED(res))
3685
                ERR("Failed to register type library %s\n", debugstr_w(tl_struct.path));
3686 3687 3688 3689
            else
                TRACE("Registered %s\n", debugstr_w(tl_struct.path));

            ITypeLib_Release(tl_struct.ptLib);
3690
            msi_free(tl_struct.path);
3691
        }
3692
        else ERR("Failed to load type library %s\n", debugstr_w(tl_struct.source));
3693 3694

        FreeLibrary(module);
3695
        msi_free(tl_struct.source);
3696
    }
3697
    else
3698 3699 3700 3701 3702
    {
        hr = LoadTypeLibEx(file->TargetPath, REGKIND_REGISTER, &tlib);
        if (FAILED(hr))
        {
            ERR("Failed to load type library: %08x\n", hr);
3703
            return ERROR_INSTALL_FAILURE;
3704 3705 3706 3707
        }

        ITypeLib_Release(tlib);
    }
3708 3709 3710 3711 3712 3713

    return ERROR_SUCCESS;
}

static UINT ACTION_RegisterTypeLibraries(MSIPACKAGE *package)
{
3714 3715 3716 3717
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','T','y','p','e','L','i','b','`',0};
    MSIQUERY *view;
3718 3719
    UINT rc;

3720
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
3721 3722 3723 3724
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords(view, NULL, ITERATE_RegisterTypeLibraries, package);
3725
    msiobj_release(&view->hdr);
3726 3727 3728
    return rc;
}

3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
static UINT ITERATE_UnregisterTypeLibraries( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR component, guid;
    MSICOMPONENT *comp;
    GUID libid;
    UINT version;
    LCID language;
    SYSKIND syskind;
    HRESULT hr;

    component = MSI_RecordGetString( row, 3 );
3741
    comp = msi_get_loaded_component( package, component );
3742 3743 3744
    if (!comp)
        return ERROR_SUCCESS;

3745 3746
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
3747
    {
3748
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
3749 3750
        return ERROR_SUCCESS;
    }
3751
    msi_ui_actiondata( package, szUnregisterTypeLibraries, row );
3752

3753
    guid = MSI_RecordGetString( row, 1 );
3754
    CLSIDFromString( guid, &libid );
3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
    version = MSI_RecordGetInteger( row, 4 );
    language = MSI_RecordGetInteger( row, 2 );

#ifdef _WIN64
    syskind = SYS_WIN64;
#else
    syskind = SYS_WIN32;
#endif

    hr = UnRegisterTypeLib( &libid, (version >> 8) & 0xffff, version & 0xff, language, syskind );
    if (FAILED(hr))
    {
        WARN("Failed to unregister typelib: %08x\n", hr);
    }

    return ERROR_SUCCESS;
}

static UINT ACTION_UnregisterTypeLibraries( MSIPACKAGE *package )
{
3775 3776 3777
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','T','y','p','e','L','i','b','`',0};
3778
    MSIQUERY *view;
3779
    UINT rc;
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

3790 3791 3792
static WCHAR *get_link_file( MSIPACKAGE *package, MSIRECORD *row )
{
    static const WCHAR szlnk[] = {'.','l','n','k',0};
3793 3794
    LPCWSTR directory, extension, link_folder;
    LPWSTR link_file, filename;
3795 3796

    directory = MSI_RecordGetString( row, 2 );
3797
    link_folder = msi_get_target_folder( package, directory );
3798 3799
    if (!link_folder)
    {
3800 3801
        ERR("unable to resolve folder %s\n", debugstr_w(directory));
        return NULL;
3802
    }
3803
    /* may be needed because of a bug somewhere else */
3804
    msi_create_full_path( link_folder );
3805 3806

    filename = msi_dup_record_field( row, 3 );
3807
    msi_reduce_to_long_filename( filename );
3808 3809 3810 3811 3812 3813 3814 3815

    extension = strchrW( filename, '.' );
    if (!extension || strcmpiW( extension, szlnk ))
    {
        int len = strlenW( filename );
        filename = msi_realloc( filename, len * sizeof(WCHAR) + sizeof(szlnk) );
        memcpy( filename + len, szlnk, sizeof(szlnk) );
    }
3816
    link_file = msi_build_directory_name( 2, link_folder, filename );
3817 3818 3819 3820 3821
    msi_free( filename );

    return link_file;
}

3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
WCHAR *msi_build_icon_path( MSIPACKAGE *package, const WCHAR *icon_name )
{
    static const WCHAR szMicrosoft[] = {'M','i','c','r','o','s','o','f','t','\\',0};
    static const WCHAR szInstaller[] = {'I','n','s','t','a','l','l','e','r','\\',0};
    WCHAR *folder, *dest, *path;

    if (package->Context == MSIINSTALLCONTEXT_MACHINE)
        folder = msi_dup_property( package->db, szWindowsFolder );
    else
    {
        WCHAR *appdata = msi_dup_property( package->db, szAppDataFolder );
        folder = msi_build_directory_name( 2, appdata, szMicrosoft );
        msi_free( appdata );
    }
    dest = msi_build_directory_name( 3, folder, szInstaller, package->ProductCode );
    msi_create_full_path( dest );
    path = msi_build_directory_name( 2, dest, icon_name );
    msi_free( folder );
    msi_free( dest );
    return path;
}

3844
static UINT ITERATE_CreateShortcuts(MSIRECORD *row, LPVOID param)
3845
{
3846
    MSIPACKAGE *package = param;
3847 3848
    LPWSTR link_file, deformated, path;
    LPCWSTR component, target;
3849
    MSICOMPONENT *comp;
3850 3851
    IShellLinkW *sl = NULL;
    IPersistFile *pf = NULL;
3852 3853
    HRESULT res;

3854
    component = MSI_RecordGetString(row, 4);
3855
    comp = msi_get_loaded_component(package, component);
3856
    if (!comp)
3857
        return ERROR_SUCCESS;
3858

3859 3860
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
3861
    {
3862
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
3863 3864
        return ERROR_SUCCESS;
    }
3865
    msi_ui_actiondata( package, szCreateShortcuts, row );
3866

3867 3868
    res = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                    &IID_IShellLinkW, (LPVOID *) &sl );
3869

3870
    if (FAILED( res ))
3871
    {
3872 3873
        ERR("CLSID_ShellLink not available\n");
        goto err;
3874
    }
3875

3876
    res = IShellLinkW_QueryInterface( sl, &IID_IPersistFile,(LPVOID*) &pf );
3877
    if (FAILED( res ))
3878
    {
3879 3880
        ERR("QueryInterface(IID_IPersistFile) failed\n");
        goto err;
3881
    }
3882

3883 3884
    target = MSI_RecordGetString(row, 5);
    if (strchrW(target, '['))
3885
    {
3886
        deformat_string( package, target, &path );
3887 3888 3889
        TRACE("target path is %s\n", debugstr_w(path));
        IShellLinkW_SetPath( sl, path );
        msi_free( path );
3890 3891 3892 3893
    }
    else
    {
        FIXME("poorly handled shortcut format, advertised shortcut\n");
3894
        IShellLinkW_SetPath(sl,comp->FullKeypath);
3895
    }
3896

3897 3898
    if (!MSI_RecordIsNull(row,6))
    {
3899 3900
        LPCWSTR arguments = MSI_RecordGetString(row, 6);
        deformat_string(package, arguments, &deformated);
3901
        IShellLinkW_SetArguments(sl,deformated);
3902
        msi_free(deformated);
3903
    }
3904

3905 3906
    if (!MSI_RecordIsNull(row,7))
    {
3907 3908
        LPCWSTR description = MSI_RecordGetString(row, 7);
        IShellLinkW_SetDescription(sl, description);
3909
    }
3910

3911 3912
    if (!MSI_RecordIsNull(row,8))
        IShellLinkW_SetHotkey(sl,MSI_RecordGetInteger(row,8));
3913

3914 3915 3916
    if (!MSI_RecordIsNull(row,9))
    {
        INT index; 
3917
        LPCWSTR icon = MSI_RecordGetString(row, 9);
3918

3919
        path = msi_build_icon_path(package, icon);
3920
        index = MSI_RecordGetInteger(row,10);
3921

3922 3923 3924 3925
        /* no value means 0 */
        if (index == MSI_NULL_INTEGER)
            index = 0;

3926 3927
        IShellLinkW_SetIconLocation(sl, path, index);
        msi_free(path);
3928
    }
3929

3930 3931
    if (!MSI_RecordIsNull(row,11))
        IShellLinkW_SetShowCmd(sl,MSI_RecordGetInteger(row,11));
3932

3933 3934
    if (!MSI_RecordIsNull(row,12))
    {
3935 3936 3937
        LPCWSTR full_path, wkdir = MSI_RecordGetString( row, 12 );
        full_path = msi_get_target_folder( package, wkdir );
        if (full_path) IShellLinkW_SetWorkingDirectory( sl, full_path );
3938
    }
3939
    link_file = get_link_file(package, row);
3940

3941 3942 3943
    TRACE("Writing shortcut to %s\n", debugstr_w(link_file));
    IPersistFile_Save(pf, link_file, FALSE);
    msi_free(link_file);
3944

3945 3946 3947 3948 3949
err:
    if (pf)
        IPersistFile_Release( pf );
    if (sl)
        IShellLinkW_Release( sl );
3950

3951 3952
    return ERROR_SUCCESS;
}
3953

3954 3955
static UINT ACTION_CreateShortcuts(MSIPACKAGE *package)
{
3956 3957 3958 3959
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','S','h','o','r','t','c','u','t','`',0};
    MSIQUERY *view;
3960
    HRESULT res;
3961
    UINT rc;
3962

3963
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
3964 3965 3966 3967
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    res = CoInitialize( NULL );
3968

3969 3970
    rc = MSI_IterateRecords(view, NULL, ITERATE_CreateShortcuts, package);
    msiobj_release(&view->hdr);
3971

3972
    if (SUCCEEDED(res)) CoUninitialize();
3973 3974 3975
    return rc;
}

3976 3977 3978 3979 3980 3981 3982 3983
static UINT ITERATE_RemoveShortcuts( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPWSTR link_file;
    LPCWSTR component;
    MSICOMPONENT *comp;

    component = MSI_RecordGetString( row, 4 );
3984
    comp = msi_get_loaded_component( package, component );
3985 3986 3987
    if (!comp)
        return ERROR_SUCCESS;

3988 3989
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
3990
    {
3991
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
3992 3993
        return ERROR_SUCCESS;
    }
3994
    msi_ui_actiondata( package, szRemoveShortcuts, row );
3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009

    link_file = get_link_file( package, row );

    TRACE("Removing shortcut file %s\n", debugstr_w( link_file ));
    if (!DeleteFileW( link_file ))
    {
        WARN("Failed to remove shortcut file %u\n", GetLastError());
    }
    msi_free( link_file );

    return ERROR_SUCCESS;
}

static UINT ACTION_RemoveShortcuts( MSIPACKAGE *package )
{
4010 4011 4012
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','S','h','o','r','t','c','u','t','`',0};
4013
    MSIQUERY *view;
4014
    UINT rc;
4015 4016 4017 4018 4019 4020 4021 4022 4023 4024

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

4025
static UINT ITERATE_PublishIcon(MSIRECORD *row, LPVOID param)
4026
{
4027
    MSIPACKAGE* package = param;
4028
    HANDLE the_file;
4029 4030
    LPWSTR FilePath;
    LPCWSTR FileName;
4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041
    CHAR buffer[1024];
    DWORD sz;
    UINT rc;

    FileName = MSI_RecordGetString(row,1);
    if (!FileName)
    {
        ERR("Unable to get FileName\n");
        return ERROR_SUCCESS;
    }

4042
    FilePath = msi_build_icon_path(package, FileName);
4043 4044 4045 4046 4047 4048 4049 4050 4051

    TRACE("Creating icon file at %s\n",debugstr_w(FilePath));

    the_file = CreateFileW(FilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL, NULL);

    if (the_file == INVALID_HANDLE_VALUE)
    {
        ERR("Unable to create file %s\n",debugstr_w(FilePath));
4052
        msi_free(FilePath);
4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
        return ERROR_SUCCESS;
    }

    do 
    {
        DWORD write;
        sz = 1024;
        rc = MSI_RecordReadStream(row,2,buffer,&sz);
        if (rc != ERROR_SUCCESS)
        {
            ERR("Failed to get stream\n");
            CloseHandle(the_file);  
            DeleteFileW(FilePath);
            break;
        }
        WriteFile(the_file,buffer,sz,&write,NULL);
    } while (sz == 1024);

4071
    msi_free(FilePath);
4072
    CloseHandle(the_file);
4073

4074 4075
    return ERROR_SUCCESS;
}
4076

4077 4078 4079
static UINT msi_publish_icons(MSIPACKAGE *package)
{
    static const WCHAR query[]= {
4080 4081 4082 4083
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','I','c','o','n','`',0};
    MSIQUERY *view;
    UINT r;
4084 4085 4086 4087

    r = MSI_DatabaseOpenViewW(package->db, query, &view);
    if (r == ERROR_SUCCESS)
    {
4088
        r = MSI_IterateRecords(view, NULL, ITERATE_PublishIcon, package);
4089
        msiobj_release(&view->hdr);
4090 4091
        if (r != ERROR_SUCCESS)
            return r;
4092 4093 4094 4095
    }
    return ERROR_SUCCESS;
}

4096
static UINT msi_publish_sourcelist(MSIPACKAGE *package, HKEY hkey)
4097 4098
{
    UINT r;
4099
    HKEY source;
4100 4101 4102 4103
    LPWSTR buffer;
    MSIMEDIADISK *disk;
    MSISOURCELISTINFO *info;

4104 4105 4106 4107 4108
    r = RegCreateKeyW(hkey, szSourceList, &source);
    if (r != ERROR_SUCCESS)
        return r;

    RegCloseKey(source);
4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130

    buffer = strrchrW(package->PackagePath, '\\') + 1;
    r = MsiSourceListSetInfoW(package->ProductCode, NULL,
                              package->Context, MSICODE_PRODUCT,
                              INSTALLPROPERTY_PACKAGENAMEW, buffer);
    if (r != ERROR_SUCCESS)
        return r;

    r = MsiSourceListSetInfoW(package->ProductCode, NULL,
                              package->Context, MSICODE_PRODUCT,
                              INSTALLPROPERTY_MEDIAPACKAGEPATHW, szEmpty);
    if (r != ERROR_SUCCESS)
        return r;

    r = MsiSourceListSetInfoW(package->ProductCode, NULL,
                              package->Context, MSICODE_PRODUCT,
                              INSTALLPROPERTY_DISKPROMPTW, szEmpty);
    if (r != ERROR_SUCCESS)
        return r;

    LIST_FOR_EACH_ENTRY(info, &package->sourcelist_info, MSISOURCELISTINFO, entry)
    {
4131
        if (!strcmpW( info->property, INSTALLPROPERTY_LASTUSEDSOURCEW ))
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149
            msi_set_last_used_source(package->ProductCode, NULL, info->context,
                                     info->options, info->value);
        else
            MsiSourceListSetInfoW(package->ProductCode, NULL,
                                  info->context, info->options,
                                  info->property, info->value);
    }

    LIST_FOR_EACH_ENTRY(disk, &package->sourcelist_media, MSIMEDIADISK, entry)
    {
        MsiSourceListAddMediaDiskW(package->ProductCode, NULL,
                                   disk->context, disk->options,
                                   disk->disk_id, disk->volume_label, disk->disk_prompt);
    }

    return ERROR_SUCCESS;
}

4150 4151 4152 4153
static UINT msi_publish_product_properties(MSIPACKAGE *package, HKEY hkey)
{
    MSIHANDLE hdb, suminfo;
    WCHAR guids[MAX_PATH];
4154
    WCHAR packcode[SQUISH_GUID_SIZE];
4155 4156 4157 4158 4159 4160 4161 4162
    LPWSTR buffer;
    LPWSTR ptr;
    DWORD langid;
    DWORD size;
    UINT r;

    static const WCHAR szARPProductIcon[] =
        {'A','R','P','P','R','O','D','U','C','T','I','C','O','N',0};
4163 4164 4165 4166 4167 4168 4169
    static const WCHAR szAssignment[] =
        {'A','s','s','i','g','n','m','e','n','t',0};
    static const WCHAR szAdvertiseFlags[] =
        {'A','d','v','e','r','t','i','s','e','F','l','a','g','s',0};
    static const WCHAR szClients[] =
        {'C','l','i','e','n','t','s',0};
    static const WCHAR szColon[] = {':',0};
4170

4171
    buffer = msi_dup_property(package->db, INSTALLPROPERTY_PRODUCTNAMEW);
4172 4173 4174
    msi_reg_set_val_str(hkey, INSTALLPROPERTY_PRODUCTNAMEW, buffer);
    msi_free(buffer);

4175
    langid = msi_get_property_int(package->db, szProductLanguage, 0);
4176 4177 4178 4179 4180
    msi_reg_set_val_dword(hkey, INSTALLPROPERTY_LANGUAGEW, langid);

    /* FIXME */
    msi_reg_set_val_dword(hkey, INSTALLPROPERTY_AUTHORIZED_LUA_APPW, 0);

4181
    buffer = msi_dup_property(package->db, szARPProductIcon);
4182 4183
    if (buffer)
    {
4184
        LPWSTR path = msi_build_icon_path(package, buffer);
4185 4186 4187 4188 4189
        msi_reg_set_val_str(hkey, INSTALLPROPERTY_PRODUCTICONW, path);
        msi_free(path);
        msi_free(buffer);
    }

4190
    buffer = msi_dup_property(package->db, szProductVersion);
4191 4192 4193 4194 4195 4196 4197
    if (buffer)
    {
        DWORD verdword = msi_version_str_to_dword(buffer);
        msi_reg_set_val_dword(hkey, INSTALLPROPERTY_VERSIONW, verdword);
        msi_free(buffer);
    }

4198 4199 4200 4201 4202
    msi_reg_set_val_dword(hkey, szAssignment, 0);
    msi_reg_set_val_dword(hkey, szAdvertiseFlags, 0x184);
    msi_reg_set_val_dword(hkey, INSTALLPROPERTY_INSTANCETYPEW, 0);
    msi_reg_set_val_str(hkey, szClients, szColon);

4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219
    hdb = alloc_msihandle(&package->db->hdr);
    if (!hdb)
        return ERROR_NOT_ENOUGH_MEMORY;

    r = MsiGetSummaryInformationW(hdb, NULL, 0, &suminfo);
    MsiCloseHandle(hdb);
    if (r != ERROR_SUCCESS)
        goto done;

    size = MAX_PATH;
    r = MsiSummaryInfoGetPropertyW(suminfo, PID_REVNUMBER, NULL, NULL,
                                   NULL, guids, &size);
    if (r != ERROR_SUCCESS)
        goto done;

    ptr = strchrW(guids, ';');
    if (ptr) *ptr = 0;
4220 4221
    squash_guid(guids, packcode);
    msi_reg_set_val_str(hkey, INSTALLPROPERTY_PACKAGECODEW, packcode);
4222 4223 4224 4225 4226 4227

done:
    MsiCloseHandle(suminfo);
    return ERROR_SUCCESS;
}

4228 4229 4230 4231 4232 4233 4234
static UINT msi_publish_upgrade_code(MSIPACKAGE *package)
{
    UINT r;
    HKEY hkey;
    LPWSTR upgrade;
    WCHAR squashed_pc[SQUISH_GUID_SIZE];

4235
    upgrade = msi_dup_property(package->db, szUpgradeCode);
4236 4237 4238
    if (!upgrade)
        return ERROR_SUCCESS;

4239 4240 4241 4242
    if (package->Context == MSIINSTALLCONTEXT_MACHINE)
        r = MSIREG_OpenClassesUpgradeCodesKey(upgrade, &hkey, TRUE);
    else
        r = MSIREG_OpenUserUpgradeCodesKey(upgrade, &hkey, TRUE);
4243

4244 4245 4246 4247 4248 4249
    if (r != ERROR_SUCCESS)
    {
        WARN("failed to open upgrade code key\n");
        msi_free(upgrade);
        return ERROR_SUCCESS;
    }
4250 4251 4252 4253
    squash_guid(package->ProductCode, squashed_pc);
    msi_reg_set_val_str(hkey, squashed_pc, NULL);
    RegCloseKey(hkey);
    msi_free(upgrade);
4254
    return ERROR_SUCCESS;
4255 4256
}

4257 4258 4259 4260 4261 4262
static BOOL msi_check_publish(MSIPACKAGE *package)
{
    MSIFEATURE *feature;

    LIST_FOR_EACH_ENTRY(feature, &package->features, MSIFEATURE, entry)
    {
4263 4264
        feature->Action = msi_get_feature_action( package, feature );
        if (feature->Action == INSTALLSTATE_LOCAL)
4265 4266 4267 4268 4269 4270
            return TRUE;
    }

    return FALSE;
}

4271 4272 4273 4274 4275 4276
static BOOL msi_check_unpublish(MSIPACKAGE *package)
{
    MSIFEATURE *feature;

    LIST_FOR_EACH_ENTRY(feature, &package->features, MSIFEATURE, entry)
    {
4277 4278
        feature->Action = msi_get_feature_action( package, feature );
        if (feature->Action != INSTALLSTATE_ABSENT)
4279 4280 4281 4282 4283 4284
            return FALSE;
    }

    return TRUE;
}

4285
static UINT msi_publish_patches( MSIPACKAGE *package )
4286
{
4287
    static const WCHAR szAllPatches[] = {'A','l','l','P','a','t','c','h','e','s',0};
4288
    WCHAR patch_squashed[GUID_SIZE];
4289
    HKEY patches_key = NULL, product_patches_key = NULL, product_key;
4290
    LONG res;
4291
    MSIPATCHINFO *patch;
4292
    UINT r;
4293 4294
    WCHAR *p, *all_patches = NULL;
    DWORD len = 0;
4295

4296
    r = MSIREG_OpenProductKey( package->ProductCode, NULL, package->Context, &product_key, TRUE );
4297
    if (r != ERROR_SUCCESS)
4298 4299
        return ERROR_FUNCTION_FAILED;

4300 4301 4302 4303 4304 4305 4306
    res = RegCreateKeyExW( product_key, szPatches, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &patches_key, NULL );
    if (res != ERROR_SUCCESS)
    {
        r = ERROR_FUNCTION_FAILED;
        goto done;
    }

4307 4308 4309 4310
    r = MSIREG_OpenUserDataProductPatchesKey( package->ProductCode, package->Context, &product_patches_key, TRUE );
    if (r != ERROR_SUCCESS)
        goto done;

4311 4312 4313 4314 4315
    LIST_FOR_EACH_ENTRY( patch, &package->patches, MSIPATCHINFO, entry )
    {
        squash_guid( patch->patchcode, patch_squashed );
        len += strlenW( patch_squashed ) + 1;
    }
4316

4317 4318
    p = all_patches = msi_alloc( (len + 1) * sizeof(WCHAR) );
    if (!all_patches)
4319 4320
        goto done;

4321 4322
    LIST_FOR_EACH_ENTRY( patch, &package->patches, MSIPATCHINFO, entry )
    {
4323 4324
        HKEY patch_key;

4325 4326 4327
        squash_guid( patch->patchcode, p );
        p += strlenW( p ) + 1;

4328
        res = RegSetValueExW( patches_key, patch_squashed, 0, REG_SZ,
4329 4330 4331 4332
                              (const BYTE *)patch->transforms,
                              (strlenW(patch->transforms) + 1) * sizeof(WCHAR) );
        if (res != ERROR_SUCCESS)
            goto done;
4333 4334 4335 4336 4337

        r = MSIREG_OpenUserDataPatchKey( patch->patchcode, package->Context, &patch_key, TRUE );
        if (r != ERROR_SUCCESS)
            goto done;

4338 4339
        res = RegSetValueExW( patch_key, szLocalPackage, 0, REG_SZ, (const BYTE *)patch->localfile,
                              (strlenW( patch->localfile ) + 1) * sizeof(WCHAR) );
4340 4341 4342 4343
        RegCloseKey( patch_key );
        if (res != ERROR_SUCCESS)
            goto done;

4344 4345 4346 4347 4348 4349
        if (patch->filename && !CopyFileW( patch->filename, patch->localfile, FALSE ))
        {
            res = GetLastError();
            ERR("Unable to copy patch package %d\n", res);
            goto done;
        }
4350
        res = RegCreateKeyExW( product_patches_key, patch_squashed, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &patch_key, NULL );
4351 4352 4353 4354
        if (res != ERROR_SUCCESS)
            goto done;

        res = RegSetValueExW( patch_key, szState, 0, REG_DWORD, (const BYTE *)&patch->state, sizeof(patch->state) );
4355 4356 4357
        RegCloseKey( patch_key );
        if (res != ERROR_SUCCESS)
            goto done;
4358 4359 4360
    }

    all_patches[len] = 0;
4361
    res = RegSetValueExW( patches_key, szPatches, 0, REG_MULTI_SZ,
4362
                          (const BYTE *)all_patches, (len + 1) * sizeof(WCHAR) );
4363 4364 4365 4366 4367 4368 4369
    if (res != ERROR_SUCCESS)
        goto done;

    res = RegSetValueExW( product_patches_key, szAllPatches, 0, REG_MULTI_SZ,
                          (const BYTE *)all_patches, (len + 1) * sizeof(WCHAR) );
    if (res != ERROR_SUCCESS)
        r = ERROR_FUNCTION_FAILED;
4370 4371

done:
4372 4373
    RegCloseKey( product_patches_key );
    RegCloseKey( patches_key );
4374
    RegCloseKey( product_key );
4375
    msi_free( all_patches );
4376 4377 4378
    return r;
}

4379
static UINT ACTION_PublishProduct(MSIPACKAGE *package)
4380 4381
{
    UINT rc;
4382 4383
    HKEY hukey = NULL, hudkey = NULL;
    MSIRECORD *uirow;
4384

4385 4386 4387 4388 4389 4390 4391
    if (!list_empty(&package->patches))
    {
        rc = msi_publish_patches(package);
        if (rc != ERROR_SUCCESS)
            goto end;
    }

4392 4393 4394 4395
    /* FIXME: also need to publish if the product is in advertise mode */
    if (!msi_check_publish(package))
        return ERROR_SUCCESS;

4396
    rc = MSIREG_OpenProductKey(package->ProductCode, NULL, package->Context,
4397 4398 4399 4400
                               &hukey, TRUE);
    if (rc != ERROR_SUCCESS)
        goto end;

4401 4402 4403 4404
    rc = MSIREG_OpenUserDataProductKey(package->ProductCode, package->Context,
                                       NULL, &hudkey, TRUE);
    if (rc != ERROR_SUCCESS)
        goto end;
4405

4406 4407 4408
    rc = msi_publish_upgrade_code(package);
    if (rc != ERROR_SUCCESS)
        goto end;
4409 4410 4411

    rc = msi_publish_product_properties(package, hukey);
    if (rc != ERROR_SUCCESS)
4412
        goto end;
Aric Stewart's avatar
Aric Stewart committed
4413

4414
    rc = msi_publish_sourcelist(package, hukey);
4415 4416
    if (rc != ERROR_SUCCESS)
        goto end;
4417

4418
    rc = msi_publish_icons(package);
4419

4420
end:
4421 4422
    uirow = MSI_CreateRecord( 1 );
    MSI_RecordSetStringW( uirow, 1, package->ProductCode );
4423
    msi_ui_actiondata( package, szPublishProduct, uirow );
4424 4425
    msiobj_release( &uirow->hdr );

4426
    RegCloseKey(hukey);
4427
    RegCloseKey(hudkey);
4428 4429 4430
    return rc;
}

4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444
static WCHAR *get_ini_file_name( MSIPACKAGE *package, MSIRECORD *row )
{
    WCHAR *filename, *ptr, *folder, *ret;
    const WCHAR *dirprop;

    filename = msi_dup_record_field( row, 2 );
    if (filename && (ptr = strchrW( filename, '|' )))
        ptr++;
    else
        ptr = filename;

    dirprop = MSI_RecordGetString( row, 3 );
    if (dirprop)
    {
4445 4446
        folder = strdupW( msi_get_target_folder( package, dirprop ) );
        if (!folder) folder = msi_dup_property( package->db, dirprop );
4447 4448
    }
    else
4449
        folder = msi_dup_property( package->db, szWindowsFolder );
4450 4451 4452 4453 4454 4455 4456 4457

    if (!folder)
    {
        ERR("Unable to resolve folder %s\n", debugstr_w(dirprop));
        msi_free( filename );
        return NULL;
    }

4458
    ret = msi_build_directory_name( 2, folder, ptr );
4459 4460 4461 4462 4463 4464

    msi_free( filename );
    msi_free( folder );
    return ret;
}

4465
static UINT ITERATE_WriteIniValues(MSIRECORD *row, LPVOID param)
4466
{
4467
    MSIPACKAGE *package = param;
4468 4469
    LPCWSTR component, section, key, value, identifier;
    LPWSTR deformated_section, deformated_key, deformated_value, fullname;
4470
    MSIRECORD * uirow;
4471 4472
    INT action;
    MSICOMPONENT *comp;
4473

4474
    component = MSI_RecordGetString(row, 8);
4475
    comp = msi_get_loaded_component(package,component);
4476 4477
    if (!comp)
        return ERROR_SUCCESS;
4478

4479 4480
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
4481
    {
4482
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
4483 4484
        return ERROR_SUCCESS;
    }
4485

4486 4487 4488 4489 4490
    identifier = MSI_RecordGetString(row,1); 
    section = MSI_RecordGetString(row,4);
    key = MSI_RecordGetString(row,5);
    value = MSI_RecordGetString(row,6);
    action = MSI_RecordGetInteger(row,7);
4491

4492 4493 4494
    deformat_string(package,section,&deformated_section);
    deformat_string(package,key,&deformated_key);
    deformat_string(package,value,&deformated_value);
4495

4496
    fullname = get_ini_file_name(package, row);
4497

4498 4499 4500
    if (action == 0)
    {
        TRACE("Adding value %s to section %s in %s\n",
4501 4502
                debugstr_w(deformated_key), debugstr_w(deformated_section),
                debugstr_w(fullname));
4503 4504 4505 4506 4507 4508 4509 4510 4511
        WritePrivateProfileStringW(deformated_section, deformated_key,
                                   deformated_value, fullname);
    }
    else if (action == 1)
    {
        WCHAR returned[10];
        GetPrivateProfileStringW(deformated_section, deformated_key, NULL,
                                 returned, 10, fullname);
        if (returned[0] == 0)
4512
        {
4513
            TRACE("Adding value %s to section %s in %s\n",
4514 4515 4516
                    debugstr_w(deformated_key), debugstr_w(deformated_section),
                    debugstr_w(fullname));

4517
            WritePrivateProfileStringW(deformated_section, deformated_key,
4518 4519
                                       deformated_value, fullname);
        }
4520 4521 4522 4523 4524 4525 4526 4527 4528
    }
    else if (action == 3)
        FIXME("Append to existing section not yet implemented\n");

    uirow = MSI_CreateRecord(4);
    MSI_RecordSetStringW(uirow,1,identifier);
    MSI_RecordSetStringW(uirow,2,deformated_section);
    MSI_RecordSetStringW(uirow,3,deformated_key);
    MSI_RecordSetStringW(uirow,4,deformated_value);
4529
    msi_ui_actiondata( package, szWriteIniValues, uirow );
4530
    msiobj_release( &uirow->hdr );
4531

4532 4533 4534 4535
    msi_free(fullname);
    msi_free(deformated_key);
    msi_free(deformated_value);
    msi_free(deformated_section);
4536 4537 4538 4539 4540
    return ERROR_SUCCESS;
}

static UINT ACTION_WriteIniValues(MSIPACKAGE *package)
{
4541 4542 4543 4544
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','I','n','i','F','i','l','e','`',0};
    MSIQUERY *view;
4545 4546
    UINT rc;

4547
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
4548 4549 4550 4551
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords(view, NULL, ITERATE_WriteIniValues, package);
4552 4553 4554 4555
    msiobj_release(&view->hdr);
    return rc;
}

4556 4557 4558 4559 4560 4561 4562 4563 4564 4565
static UINT ITERATE_RemoveIniValuesOnUninstall( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR component, section, key, value, identifier;
    LPWSTR deformated_section, deformated_key, deformated_value, filename;
    MSICOMPONENT *comp;
    MSIRECORD *uirow;
    INT action;

    component = MSI_RecordGetString( row, 8 );
4566
    comp = msi_get_loaded_component( package, component );
4567 4568 4569
    if (!comp)
        return ERROR_SUCCESS;

4570 4571
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
4572
    {
4573
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
        return ERROR_SUCCESS;
    }

    identifier = MSI_RecordGetString( row, 1 );
    section = MSI_RecordGetString( row, 4 );
    key = MSI_RecordGetString( row, 5 );
    value = MSI_RecordGetString( row, 6 );
    action = MSI_RecordGetInteger( row, 7 );

    deformat_string( package, section, &deformated_section );
    deformat_string( package, key, &deformated_key );
    deformat_string( package, value, &deformated_value );

    if (action == msidbIniFileActionAddLine || action == msidbIniFileActionCreateLine)
    {
        filename = get_ini_file_name( package, row );

        TRACE("Removing key %s from section %s in %s\n",
               debugstr_w(deformated_key), debugstr_w(deformated_section), debugstr_w(filename));

        if (!WritePrivateProfileStringW( deformated_section, deformated_key, NULL, filename ))
        {
            WARN("Unable to remove key %u\n", GetLastError());
        }
        msi_free( filename );
    }
    else
        FIXME("Unsupported action %d\n", action);


    uirow = MSI_CreateRecord( 4 );
    MSI_RecordSetStringW( uirow, 1, identifier );
    MSI_RecordSetStringW( uirow, 2, deformated_section );
    MSI_RecordSetStringW( uirow, 3, deformated_key );
    MSI_RecordSetStringW( uirow, 4, deformated_value );
4609
    msi_ui_actiondata( package, szRemoveIniValues, uirow );
4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627
    msiobj_release( &uirow->hdr );

    msi_free( deformated_key );
    msi_free( deformated_value );
    msi_free( deformated_section );
    return ERROR_SUCCESS;
}

static UINT ITERATE_RemoveIniValuesOnInstall( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR component, section, key, value, identifier;
    LPWSTR deformated_section, deformated_key, deformated_value, filename;
    MSICOMPONENT *comp;
    MSIRECORD *uirow;
    INT action;

    component = MSI_RecordGetString( row, 8 );
4628
    comp = msi_get_loaded_component( package, component );
4629 4630 4631
    if (!comp)
        return ERROR_SUCCESS;

4632 4633
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
4634
    {
4635
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669
        return ERROR_SUCCESS;
    }

    identifier = MSI_RecordGetString( row, 1 );
    section = MSI_RecordGetString( row, 4 );
    key = MSI_RecordGetString( row, 5 );
    value = MSI_RecordGetString( row, 6 );
    action = MSI_RecordGetInteger( row, 7 );

    deformat_string( package, section, &deformated_section );
    deformat_string( package, key, &deformated_key );
    deformat_string( package, value, &deformated_value );

    if (action == msidbIniFileActionRemoveLine)
    {
        filename = get_ini_file_name( package, row );

        TRACE("Removing key %s from section %s in %s\n",
               debugstr_w(deformated_key), debugstr_w(deformated_section), debugstr_w(filename));

        if (!WritePrivateProfileStringW( deformated_section, deformated_key, NULL, filename ))
        {
            WARN("Unable to remove key %u\n", GetLastError());
        }
        msi_free( filename );
    }
    else
        FIXME("Unsupported action %d\n", action);

    uirow = MSI_CreateRecord( 4 );
    MSI_RecordSetStringW( uirow, 1, identifier );
    MSI_RecordSetStringW( uirow, 2, deformated_section );
    MSI_RecordSetStringW( uirow, 3, deformated_key );
    MSI_RecordSetStringW( uirow, 4, deformated_value );
4670
    msi_ui_actiondata( package, szRemoveIniValues, uirow );
4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
    msiobj_release( &uirow->hdr );

    msi_free( deformated_key );
    msi_free( deformated_value );
    msi_free( deformated_section );
    return ERROR_SUCCESS;
}

static UINT ACTION_RemoveIniValues( MSIPACKAGE *package )
{
4681 4682 4683 4684 4685 4686
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','I','n','i','F','i','l','e','`',0};
    static const WCHAR remove_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','R','e','m','o','v','e','I','n','i','F','i','l','e','`',0};
4687
    MSIQUERY *view;
4688
    UINT rc;
4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveIniValuesOnUninstall, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
    rc = MSI_DatabaseOpenViewW( package->db, remove_query, &view );
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveIniValuesOnInstall, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
    return ERROR_SUCCESS;
}

4709 4710
static void register_dll( const WCHAR *dll, BOOL unregister )
{
4711 4712 4713 4714 4715 4716 4717
    static const WCHAR regW[] =
        {'r','e','g','s','v','r','3','2','.','e','x','e',' ','\"','%','s','\"',0};
    static const WCHAR unregW[] =
        {'r','e','g','s','v','r','3','2','.','e','x','e',' ','/','u',' ','\"','%','s','\"',0};
    PROCESS_INFORMATION pi;
    STARTUPINFOW si;
    WCHAR *cmd;
4718

4719
    if (!(cmd = msi_alloc( strlenW(dll) * sizeof(WCHAR) + sizeof(unregW) ))) return;
4720

4721 4722 4723 4724 4725 4726 4727 4728 4729
    if (unregister) sprintfW( cmd, unregW, dll );
    else sprintfW( cmd, regW, dll );

    memset( &si, 0, sizeof(STARTUPINFOW) );
    if (CreateProcessW( NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
    {
        CloseHandle( pi.hThread );
        msi_dialog_check_messages( pi.hProcess );
        CloseHandle( pi.hProcess );
4730
    }
4731
    msi_free( cmd );
4732 4733
}

4734
static UINT ITERATE_SelfRegModules(MSIRECORD *row, LPVOID param)
4735
{
4736
    MSIPACKAGE *package = param;
4737
    LPCWSTR filename;
4738
    MSIFILE *file;
4739
    MSIRECORD *uirow;
Aric Stewart's avatar
Aric Stewart committed
4740

4741
    filename = MSI_RecordGetString( row, 1 );
4742
    file = msi_get_loaded_file( package, filename );
4743
    if (!file)
4744
    {
4745 4746 4747 4748 4749 4750 4751
        WARN("unable to find file %s\n", debugstr_w(filename));
        return ERROR_SUCCESS;
    }
    file->Component->Action = msi_get_component_action( package, file->Component );
    if (file->Component->Action != INSTALLSTATE_LOCAL)
    {
        TRACE("component not scheduled for installation %s\n", debugstr_w(file->Component->Component));
4752
        return ERROR_SUCCESS;
4753 4754
    }

4755 4756
    TRACE("Registering %s\n", debugstr_w( file->TargetPath ));
    register_dll( file->TargetPath, FALSE );
4757

4758
    uirow = MSI_CreateRecord( 2 );
4759
    MSI_RecordSetStringW( uirow, 1, file->File );
4760
    MSI_RecordSetStringW( uirow, 2, file->Component->Directory );
4761
    msi_ui_actiondata( package, szSelfRegModules, uirow );
4762 4763
    msiobj_release( &uirow->hdr );

4764 4765
    return ERROR_SUCCESS;
}
4766

4767 4768
static UINT ACTION_SelfRegModules(MSIPACKAGE *package)
{
4769 4770 4771 4772
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','S','e','l','f','R','e','g','`',0};
    MSIQUERY *view;
4773
    UINT rc;
4774

4775
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
4776 4777 4778
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

4779
    rc = MSI_IterateRecords(view, NULL, ITERATE_SelfRegModules, package);
4780
    msiobj_release(&view->hdr);
4781
    return rc;
4782 4783
}

4784 4785 4786 4787 4788 4789 4790 4791
static UINT ITERATE_SelfUnregModules( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR filename;
    MSIFILE *file;
    MSIRECORD *uirow;

    filename = MSI_RecordGetString( row, 1 );
4792
    file = msi_get_loaded_file( package, filename );
4793 4794
    if (!file)
    {
4795 4796 4797 4798 4799 4800 4801
        WARN("unable to find file %s\n", debugstr_w(filename));
        return ERROR_SUCCESS;
    }
    file->Component->Action = msi_get_component_action( package, file->Component );
    if (file->Component->Action != INSTALLSTATE_ABSENT)
    {
        TRACE("component not scheduled for removal %s\n", debugstr_w(file->Component->Component));
4802 4803 4804
        return ERROR_SUCCESS;
    }

4805 4806
    TRACE("Unregistering %s\n", debugstr_w( file->TargetPath ));
    register_dll( file->TargetPath, TRUE );
4807 4808

    uirow = MSI_CreateRecord( 2 );
4809
    MSI_RecordSetStringW( uirow, 1, file->File );
4810
    MSI_RecordSetStringW( uirow, 2, file->Component->Directory );
4811
    msi_ui_actiondata( package, szSelfUnregModules, uirow );
4812 4813 4814 4815 4816 4817 4818
    msiobj_release( &uirow->hdr );

    return ERROR_SUCCESS;
}

static UINT ACTION_SelfUnregModules( MSIPACKAGE *package )
{
4819 4820 4821
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','S','e','l','f','R','e','g','`',0};
4822
    MSIQUERY *view;
4823
    UINT rc;
4824 4825 4826 4827 4828

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

4829
    rc = MSI_IterateRecords( view, NULL, ITERATE_SelfUnregModules, package );
4830
    msiobj_release( &view->hdr );
4831
    return rc;
4832 4833
}

4834 4835
static UINT ACTION_PublishFeatures(MSIPACKAGE *package)
{
4836
    MSIFEATURE *feature;
4837
    UINT rc;
4838
    HKEY hkey = NULL, userdata = NULL;
4839 4840 4841 4842

    if (!msi_check_publish(package))
        return ERROR_SUCCESS;

4843
    rc = MSIREG_OpenFeaturesKey(package->ProductCode, NULL, package->Context,
4844 4845 4846 4847
                                &hkey, TRUE);
    if (rc != ERROR_SUCCESS)
        goto end;

4848
    rc = MSIREG_OpenUserDataFeaturesKey(package->ProductCode, NULL, package->Context,
4849 4850 4851
                                        &userdata, TRUE);
    if (rc != ERROR_SUCCESS)
        goto end;
4852

4853
    /* here the guids are base 85 encoded */
4854
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
4855
    {
4856
        ComponentList *cl;
4857 4858 4859
        LPWSTR data = NULL;
        GUID clsid;
        INT size;
4860
        BOOL absent = FALSE;
4861
        MSIRECORD *uirow;
4862

4863 4864 4865
        if (feature->Action != INSTALLSTATE_LOCAL &&
            feature->Action != INSTALLSTATE_SOURCE &&
            feature->Action != INSTALLSTATE_ADVERTISED) absent = TRUE;
4866

4867
        size = 1;
4868
        LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
4869 4870 4871
        {
            size += 21;
        }
4872
        if (feature->Feature_Parent)
4873
            size += strlenW( feature->Feature_Parent )+2;
4874

4875
        data = msi_alloc(size * sizeof(WCHAR));
4876 4877

        data[0] = 0;
4878
        LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
4879
        {
4880
            MSICOMPONENT* component = cl->component;
4881
            WCHAR buf[21];
4882

4883
            buf[0] = 0;
4884
            if (component->ComponentId)
4885
            {
4886 4887
                TRACE("From %s\n",debugstr_w(component->ComponentId));
                CLSIDFromString(component->ComponentId, &clsid);
4888 4889 4890 4891
                encode_base85_guid(&clsid,buf);
                TRACE("to %s\n",debugstr_w(buf));
                strcatW(data,buf);
            }
4892
        }
4893

4894
        if (feature->Feature_Parent)
4895 4896 4897
        {
            static const WCHAR sep[] = {'\2',0};
            strcatW(data,sep);
4898
            strcatW(data,feature->Feature_Parent);
4899 4900
        }

4901
        msi_reg_set_val_str( userdata, feature->Feature, data );
4902
        msi_free(data);
4903

4904 4905 4906
        size = 0;
        if (feature->Feature_Parent)
            size = strlenW(feature->Feature_Parent)*sizeof(WCHAR);
4907 4908
        if (!absent)
        {
4909
            size += sizeof(WCHAR);
4910
            RegSetValueExW(hkey,feature->Feature,0,REG_SZ,
4911
                           (const BYTE*)(feature->Feature_Parent ? feature->Feature_Parent : szEmpty),size);
4912 4913 4914
        }
        else
        {
4915
            size += 2*sizeof(WCHAR);
4916
            data = msi_alloc(size);
4917
            data[0] = 0x6;
4918 4919 4920
            data[1] = 0;
            if (feature->Feature_Parent)
                strcpyW( &data[1], feature->Feature_Parent );
4921
            RegSetValueExW(hkey,feature->Feature,0,REG_SZ,
4922
                       (LPBYTE)data,size);
4923
            msi_free(data);
4924
        }
4925 4926 4927 4928

        /* the UI chunk */
        uirow = MSI_CreateRecord( 1 );
        MSI_RecordSetStringW( uirow, 1, feature->Feature );
4929
        msi_ui_actiondata( package, szPublishFeatures, uirow );
4930
        msiobj_release( &uirow->hdr );
4931
        /* FIXME: call msi_ui_progress? */
4932 4933 4934
    }

end:
4935 4936
    RegCloseKey(hkey);
    RegCloseKey(userdata);
4937 4938 4939
    return rc;
}

4940 4941 4942 4943
static UINT msi_unpublish_feature(MSIPACKAGE *package, MSIFEATURE *feature)
{
    UINT r;
    HKEY hkey;
4944
    MSIRECORD *uirow;
4945 4946 4947

    TRACE("unpublishing feature %s\n", debugstr_w(feature->Feature));

4948
    r = MSIREG_OpenFeaturesKey(package->ProductCode, NULL, package->Context,
4949
                               &hkey, FALSE);
4950 4951 4952 4953 4954 4955
    if (r == ERROR_SUCCESS)
    {
        RegDeleteValueW(hkey, feature->Feature);
        RegCloseKey(hkey);
    }

4956
    r = MSIREG_OpenUserDataFeaturesKey(package->ProductCode, NULL, package->Context,
4957
                                       &hkey, FALSE);
4958 4959 4960 4961 4962 4963
    if (r == ERROR_SUCCESS)
    {
        RegDeleteValueW(hkey, feature->Feature);
        RegCloseKey(hkey);
    }

4964 4965
    uirow = MSI_CreateRecord( 1 );
    MSI_RecordSetStringW( uirow, 1, feature->Feature );
4966
    msi_ui_actiondata( package, szUnpublishFeatures, uirow );
4967 4968
    msiobj_release( &uirow->hdr );

4969 4970 4971 4972 4973 4974 4975
    return ERROR_SUCCESS;
}

static UINT ACTION_UnpublishFeatures(MSIPACKAGE *package)
{
    MSIFEATURE *feature;

4976
    if (!msi_check_unpublish(package))
4977 4978 4979 4980 4981 4982 4983 4984 4985 4986
        return ERROR_SUCCESS;

    LIST_FOR_EACH_ENTRY(feature, &package->features, MSIFEATURE, entry)
    {
        msi_unpublish_feature(package, feature);
    }

    return ERROR_SUCCESS;
}

4987
static UINT msi_publish_install_properties(MSIPACKAGE *package, HKEY hkey)
4988
{
4989 4990
    SYSTEMTIME systime;
    DWORD size, langid;
4991 4992
    WCHAR date[9], *val, *buffer;
    const WCHAR *prop, *key;
4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005

    static const WCHAR date_fmt[] = {'%','i','%','0','2','i','%','0','2','i',0};
    static const WCHAR modpath_fmt[] =
        {'M','s','i','E','x','e','c','.','e','x','e',' ',
         '/','I','[','P','r','o','d','u','c','t','C','o','d','e',']',0};
    static const WCHAR szModifyPath[] =
        {'M','o','d','i','f','y','P','a','t','h',0};
    static const WCHAR szUninstallString[] =
        {'U','n','i','n','s','t','a','l','l','S','t','r','i','n','g',0};
    static const WCHAR szEstimatedSize[] =
        {'E','s','t','i','m','a','t','e','d','S','i','z','e',0};
    static const WCHAR szDisplayVersion[] =
        {'D','i','s','p','l','a','y','V','e','r','s','i','o','n',0};
5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053
    static const WCHAR szInstallSource[] =
        {'I','n','s','t','a','l','l','S','o','u','r','c','e',0};
    static const WCHAR szARPAUTHORIZEDCDFPREFIX[] =
        {'A','R','P','A','U','T','H','O','R','I','Z','E','D','C','D','F','P','R','E','F','I','X',0};
    static const WCHAR szAuthorizedCDFPrefix[] =
        {'A','u','t','h','o','r','i','z','e','d','C','D','F','P','r','e','f','i','x',0};
    static const WCHAR szARPCONTACT[] =
        {'A','R','P','C','O','N','T','A','C','T',0};
    static const WCHAR szContact[] =
        {'C','o','n','t','a','c','t',0};
    static const WCHAR szARPCOMMENTS[] =
        {'A','R','P','C','O','M','M','E','N','T','S',0};
    static const WCHAR szComments[] =
        {'C','o','m','m','e','n','t','s',0};
    static const WCHAR szProductName[] =
        {'P','r','o','d','u','c','t','N','a','m','e',0};
    static const WCHAR szDisplayName[] =
        {'D','i','s','p','l','a','y','N','a','m','e',0};
    static const WCHAR szARPHELPLINK[] =
        {'A','R','P','H','E','L','P','L','I','N','K',0};
    static const WCHAR szHelpLink[] =
        {'H','e','l','p','L','i','n','k',0};
    static const WCHAR szARPHELPTELEPHONE[] =
        {'A','R','P','H','E','L','P','T','E','L','E','P','H','O','N','E',0};
    static const WCHAR szHelpTelephone[] =
        {'H','e','l','p','T','e','l','e','p','h','o','n','e',0};
    static const WCHAR szARPINSTALLLOCATION[] =
        {'A','R','P','I','N','S','T','A','L','L','L','O','C','A','T','I','O','N',0};
    static const WCHAR szManufacturer[] =
        {'M','a','n','u','f','a','c','t','u','r','e','r',0};
    static const WCHAR szPublisher[] =
        {'P','u','b','l','i','s','h','e','r',0};
    static const WCHAR szARPREADME[] =
        {'A','R','P','R','E','A','D','M','E',0};
    static const WCHAR szReadme[] =
        {'R','e','a','d','M','e',0};
    static const WCHAR szARPSIZE[] =
        {'A','R','P','S','I','Z','E',0};
    static const WCHAR szSize[] =
        {'S','i','z','e',0};
    static const WCHAR szARPURLINFOABOUT[] =
        {'A','R','P','U','R','L','I','N','F','O','A','B','O','U','T',0};
    static const WCHAR szURLInfoAbout[] =
        {'U','R','L','I','n','f','o','A','b','o','u','t',0};
    static const WCHAR szARPURLUPDATEINFO[] =
        {'A','R','P','U','R','L','U','P','D','A','T','E','I','N','F','O',0};
    static const WCHAR szURLUpdateInfo[] =
        {'U','R','L','U','p','d','a','t','e','I','n','f','o',0};
5054 5055 5056 5057
    static const WCHAR szARPSYSTEMCOMPONENT[] =
        {'A','R','P','S','Y','S','T','E','M','C','O','M','P','O','N','E','N','T',0};
    static const WCHAR szSystemComponent[] =
        {'S','y','s','t','e','m','C','o','m','p','o','n','e','n','t',0};
5058 5059 5060 5061 5062 5063 5064 5065 5066

    static const WCHAR *propval[] = {
        szARPAUTHORIZEDCDFPREFIX, szAuthorizedCDFPrefix,
        szARPCONTACT,             szContact,
        szARPCOMMENTS,            szComments,
        szProductName,            szDisplayName,
        szARPHELPLINK,            szHelpLink,
        szARPHELPTELEPHONE,       szHelpTelephone,
        szARPINSTALLLOCATION,     szInstallLocation,
5067
        szSourceDir,              szInstallSource,
5068 5069 5070 5071 5072 5073
        szManufacturer,           szPublisher,
        szARPREADME,              szReadme,
        szARPSIZE,                szSize,
        szARPURLINFOABOUT,        szURLInfoAbout,
        szARPURLUPDATEINFO,       szURLUpdateInfo,
        NULL
5074
    };
5075
    const WCHAR **p = propval;
5076

5077
    while (*p)
5078
    {
5079 5080
        prop = *p++;
        key = *p++;
5081
        val = msi_dup_property(package->db, prop);
5082
        msi_reg_set_val_str(hkey, key, val);
5083 5084
        msi_free(val);
    }
5085 5086

    msi_reg_set_val_dword(hkey, szWindowsInstaller, 1);
5087 5088 5089 5090
    if (msi_get_property_int( package->db, szARPSYSTEMCOMPONENT, 0 ))
    {
        msi_reg_set_val_dword( hkey, szSystemComponent, 1 );
    }
5091
    size = deformat_string(package, modpath_fmt, &buffer) * sizeof(WCHAR);
5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
    RegSetValueExW(hkey, szModifyPath, 0, REG_EXPAND_SZ, (LPBYTE)buffer, size);
    RegSetValueExW(hkey, szUninstallString, 0, REG_EXPAND_SZ, (LPBYTE)buffer, size);
    msi_free(buffer);

    /* FIXME: Write real Estimated Size when we have it */
    msi_reg_set_val_dword(hkey, szEstimatedSize, 0);

    GetLocalTime(&systime);
    sprintfW(date, date_fmt, systime.wYear, systime.wMonth, systime.wDay);
    msi_reg_set_val_str(hkey, INSTALLPROPERTY_INSTALLDATEW, date);

5103
    langid = msi_get_property_int(package->db, szProductLanguage, 0);
5104 5105
    msi_reg_set_val_dword(hkey, INSTALLPROPERTY_LANGUAGEW, langid);

5106
    buffer = msi_dup_property(package->db, szProductVersion);
5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117
    msi_reg_set_val_str(hkey, szDisplayVersion, buffer);
    if (buffer)
    {
        DWORD verdword = msi_version_str_to_dword(buffer);

        msi_reg_set_val_dword(hkey, INSTALLPROPERTY_VERSIONW, verdword);
        msi_reg_set_val_dword(hkey, INSTALLPROPERTY_VERSIONMAJORW, verdword >> 24);
        msi_reg_set_val_dword(hkey, INSTALLPROPERTY_VERSIONMINORW, (verdword >> 16) & 0xFF);
        msi_free(buffer);
    }

5118 5119 5120
    return ERROR_SUCCESS;
}

Aric Stewart's avatar
Aric Stewart committed
5121 5122
static UINT ACTION_RegisterProduct(MSIPACKAGE *package)
{
5123
    WCHAR squashed_pc[SQUISH_GUID_SIZE];
5124
    MSIRECORD *uirow;
5125
    LPWSTR upgrade_code;
5126
    HKEY hkey, props, upgrade_key;
5127
    UINT rc;
5128

5129 5130 5131
    /* FIXME: also need to publish if the product is in advertise mode */
    if (!msi_check_publish(package))
        return ERROR_SUCCESS;
Aric Stewart's avatar
Aric Stewart committed
5132

5133
    rc = MSIREG_OpenUninstallKey(package->ProductCode, package->platform, &hkey, TRUE);
Aric Stewart's avatar
Aric Stewart committed
5134
    if (rc != ERROR_SUCCESS)
5135
        return rc;
Aric Stewart's avatar
Aric Stewart committed
5136

5137
    rc = MSIREG_OpenInstallProps(package->ProductCode, package->Context, NULL, &props, TRUE);
5138 5139
    if (rc != ERROR_SUCCESS)
        goto done;
5140

5141 5142 5143
    rc = msi_publish_install_properties(package, hkey);
    if (rc != ERROR_SUCCESS)
        goto done;
5144

5145 5146 5147
    rc = msi_publish_install_properties(package, props);
    if (rc != ERROR_SUCCESS)
        goto done;
5148

5149
    upgrade_code = msi_dup_property(package->db, szUpgradeCode);
5150 5151
    if (upgrade_code)
    {
5152 5153 5154 5155 5156 5157 5158 5159
        rc = MSIREG_OpenUpgradeCodesKey( upgrade_code, &upgrade_key, TRUE );
        if (rc == ERROR_SUCCESS)
        {
            squash_guid( package->ProductCode, squashed_pc );
            msi_reg_set_val_str( upgrade_key, squashed_pc, NULL );
            RegCloseKey( upgrade_key );
        }
        msi_free( upgrade_code );
5160
    }
5161 5162
    msi_reg_set_val_str( props, INSTALLPROPERTY_LOCALPACKAGEW, package->localfile );
    package->delete_on_close = FALSE;
5163

5164
done:
5165 5166
    uirow = MSI_CreateRecord( 1 );
    MSI_RecordSetStringW( uirow, 1, package->ProductCode );
5167
    msi_ui_actiondata( package, szRegisterProduct, uirow );
5168
    msiobj_release( &uirow->hdr );
Aric Stewart's avatar
Aric Stewart committed
5169

5170
    RegCloseKey(hkey);
Aric Stewart's avatar
Aric Stewart committed
5171 5172 5173 5174 5175
    return ERROR_SUCCESS;
}

static UINT ACTION_InstallExecute(MSIPACKAGE *package)
{
5176
    return execute_script(package, SCRIPT_INSTALL);
Aric Stewart's avatar
Aric Stewart committed
5177 5178
}

5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217
static UINT ITERATE_UnpublishIcon( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    const WCHAR *icon = MSI_RecordGetString( row, 1 );
    WCHAR *p, *icon_path;

    if (!icon) return ERROR_SUCCESS;
    if ((icon_path = msi_build_icon_path( package, icon )))
    {
        TRACE("removing icon file %s\n", debugstr_w(icon_path));
        DeleteFileW( icon_path );
        if ((p = strrchrW( icon_path, '\\' )))
        {
            *p = 0;
            RemoveDirectoryW( icon_path );
        }
        msi_free( icon_path );
    }
    return ERROR_SUCCESS;
}

static UINT msi_unpublish_icons( MSIPACKAGE *package )
{
    static const WCHAR query[]= {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','`','I','c','o','n','`',0};
    MSIQUERY *view;
    UINT r;

    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r == ERROR_SUCCESS)
    {
        r = MSI_IterateRecords( view, NULL, ITERATE_UnpublishIcon, package );
        msiobj_release( &view->hdr );
        if (r != ERROR_SUCCESS)
            return r;
    }
    return ERROR_SUCCESS;
}

5218
static UINT msi_unpublish_product( MSIPACKAGE *package, const WCHAR *remove )
5219
{
5220
    static const WCHAR szUpgradeCode[] = {'U','p','g','r','a','d','e','C','o','d','e',0};
5221
    WCHAR *upgrade, **features;
5222 5223
    BOOL full_uninstall = TRUE;
    MSIFEATURE *feature;
5224
    MSIPATCHINFO *patch;
5225
    UINT i;
5226

5227
    LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
5228
    {
5229
        if (feature->Action == INSTALLSTATE_LOCAL) full_uninstall = FALSE;
5230
    }
5231 5232
    features = msi_split_string( remove, ',' );
    for (i = 0; features && features[i]; i++)
5233
    {
5234
        if (!strcmpW( features[i], szAll )) full_uninstall = TRUE;
5235
    }
5236
    msi_free(features);
5237 5238

    if (!full_uninstall)
5239
        return ERROR_SUCCESS;
5240 5241 5242

    MSIREG_DeleteProductKey(package->ProductCode);
    MSIREG_DeleteUserDataProductKey(package->ProductCode);
5243
    MSIREG_DeleteUninstallKey(package->ProductCode, package->platform);
5244

5245 5246 5247 5248
    MSIREG_DeleteLocalClassesProductKey(package->ProductCode);
    MSIREG_DeleteLocalClassesFeaturesKey(package->ProductCode);
    MSIREG_DeleteUserProductKey(package->ProductCode);
    MSIREG_DeleteUserFeaturesKey(package->ProductCode);
5249

5250
    upgrade = msi_dup_property(package->db, szUpgradeCode);
5251 5252 5253
    if (upgrade)
    {
        MSIREG_DeleteUserUpgradeCodesKey(upgrade);
5254
        MSIREG_DeleteClassesUpgradeCodesKey(upgrade);
5255 5256 5257
        msi_free(upgrade);
    }

5258 5259 5260
    LIST_FOR_EACH_ENTRY(patch, &package->patches, MSIPATCHINFO, entry)
    {
        MSIREG_DeleteUserDataPatchKey(patch->patchcode, package->Context);
5261 5262 5263 5264 5265
        if (!strcmpW( package->ProductCode, patch->products ))
        {
            TRACE("removing local patch package %s\n", debugstr_w(patch->localfile));
            patch->delete_on_close = TRUE;
        }
5266
        /* FIXME: remove local patch package if this is the last product */
5267
    }
5268
    TRACE("removing local package %s\n", debugstr_w(package->localfile));
5269
    package->delete_on_close = TRUE;
5270 5271

    msi_unpublish_icons( package );
5272 5273 5274
    return ERROR_SUCCESS;
}

Aric Stewart's avatar
Aric Stewart committed
5275 5276
static UINT ACTION_InstallFinalize(MSIPACKAGE *package)
{
5277
    UINT rc;
5278
    WCHAR *remove;
5279

5280
    /* turn off scheduling */
5281 5282
    package->script->CurrentlyScripting= FALSE;

5283
    /* first do the same as an InstallExecute */
5284 5285 5286
    rc = ACTION_InstallExecute(package);
    if (rc != ERROR_SUCCESS)
        return rc;
5287

5288 5289
    /* then handle commit actions */
    rc = execute_script(package, SCRIPT_COMMIT);
5290 5291 5292 5293
    if (rc != ERROR_SUCCESS)
        return rc;

    remove = msi_dup_property(package->db, szRemove);
5294
    rc = msi_unpublish_product(package, remove);
5295
    msi_free(remove);
5296
    return rc;
Aric Stewart's avatar
Aric Stewart committed
5297 5298
}

5299
UINT ACTION_ForceReboot(MSIPACKAGE *package)
Aric Stewart's avatar
Aric Stewart committed
5300 5301 5302 5303 5304 5305
{
    static const WCHAR RunOnce[] = {
    'S','o','f','t','w','a','r','e','\\',
    'M','i','c','r','o','s','o','f','t','\\',
    'W','i','n','d','o','w','s','\\',
    'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
5306
    'R','u','n','O','n','c','e',0};
Aric Stewart's avatar
Aric Stewart committed
5307 5308 5309 5310 5311 5312
    static const WCHAR InstallRunOnce[] = {
    'S','o','f','t','w','a','r','e','\\',
    'M','i','c','r','o','s','o','f','t','\\',
    'W','i','n','d','o','w','s','\\',
    'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
    'I','n','s','t','a','l','l','e','r','\\',
5313
    'R','u','n','O','n','c','e','E','n','t','r','i','e','s',0};
Aric Stewart's avatar
Aric Stewart committed
5314 5315

    static const WCHAR msiexec_fmt[] = {
5316
    '%','s',
Aric Stewart's avatar
Aric Stewart committed
5317 5318 5319 5320 5321 5322
    '\\','M','s','i','E','x','e','c','.','e','x','e',' ','/','@',' ',
    '\"','%','s','\"',0};
    static const WCHAR install_fmt[] = {
    '/','I',' ','\"','%','s','\"',' ',
    'A','F','T','E','R','R','E','B','O','O','T','=','1',' ',
    'R','U','N','O','N','C','E','E','N','T','R','Y','=','\"','%','s','\"',0};
5323
    WCHAR buffer[256], sysdir[MAX_PATH];
5324
    HKEY hkey;
5325
    WCHAR squished_pc[100];
Aric Stewart's avatar
Aric Stewart committed
5326

5327
    squash_guid(package->ProductCode,squished_pc);
Aric Stewart's avatar
Aric Stewart committed
5328

5329
    GetSystemDirectoryW(sysdir, sizeof(sysdir)/sizeof(sysdir[0]));
Aric Stewart's avatar
Aric Stewart committed
5330
    RegCreateKeyW(HKEY_LOCAL_MACHINE,RunOnce,&hkey);
5331 5332
    snprintfW(buffer,sizeof(buffer)/sizeof(buffer[0]),msiexec_fmt,sysdir,
     squished_pc);
Aric Stewart's avatar
Aric Stewart committed
5333

5334
    msi_reg_set_val_str( hkey, squished_pc, buffer );
Aric Stewart's avatar
Aric Stewart committed
5335 5336 5337 5338 5339
    RegCloseKey(hkey);

    TRACE("Reboot command %s\n",debugstr_w(buffer));

    RegCreateKeyW(HKEY_LOCAL_MACHINE,InstallRunOnce,&hkey);
5340
    sprintfW(buffer,install_fmt,package->ProductCode,squished_pc);
5341

5342
    msi_reg_set_val_str( hkey, squished_pc, buffer );
Aric Stewart's avatar
Aric Stewart committed
5343 5344
    RegCloseKey(hkey);

5345
    return ERROR_INSTALL_SUSPEND;
Aric Stewart's avatar
Aric Stewart committed
5346 5347
}

5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384
WCHAR *msi_build_error_string( MSIPACKAGE *package, UINT error, DWORD count, ... )
{
    static const WCHAR query[] =
        {'S','E','L','E','C','T',' ','`','M','e','s','s','a','g','e','`',' ',
         'F','R','O','M',' ','`','E','r','r','o','r','`',' ','W','H','E','R','E',' ',
         '`','E','r','r','o','r','`',' ','=',' ','%','i',0};
    MSIRECORD *rec, *row;
    DWORD i, size = 0;
    va_list va;
    const WCHAR *str;
    WCHAR *data;

    if (!(row = MSI_QueryGetRecord( package->db, query, error ))) return 0;

    rec = MSI_CreateRecord( count + 2 );
    str = MSI_RecordGetString( row, 1 );
    MSI_RecordSetStringW( rec, 0, str );
    msiobj_release( &row->hdr );
    MSI_RecordSetInteger( rec, 1, error );

    va_start( va, count );
    for (i = 0; i < count; i++)
    {
        str = va_arg( va, const WCHAR *);
        MSI_RecordSetStringW( rec, i + 2, str );
    }
    va_end( va );

    MSI_FormatRecordW( package, rec, NULL, &size );
    size++;
    data = msi_alloc( size * sizeof(WCHAR) );
    if (size > 1) MSI_FormatRecordW( package, rec, data, &size );
    else data[0] = 0;
    msiobj_release( &rec->hdr );
    return data;
}

5385
static UINT ACTION_ResolveSource(MSIPACKAGE* package)
5386
{
5387
    DWORD attrib;
5388
    UINT rc;
Mike McCormack's avatar
Mike McCormack committed
5389

5390
    /*
Mike McCormack's avatar
Mike McCormack committed
5391 5392
     * We are currently doing what should be done here in the top level Install
     * however for Administrative and uninstalls this step will be needed
5393
     */
5394 5395 5396
    if (!package->PackagePath)
        return ERROR_SUCCESS;

5397
    msi_set_sourcedir_props(package, TRUE);
5398

5399
    attrib = GetFileAttributesW(package->db->path);
5400 5401
    if (attrib == INVALID_FILE_ATTRIBUTES)
    {
5402
        LPWSTR prompt, msg;
5403 5404 5405
        DWORD size = 0;

        rc = MsiSourceListGetInfoW(package->ProductCode, NULL, 
5406
                package->Context, MSICODE_PRODUCT,
5407 5408 5409
                INSTALLPROPERTY_DISKPROMPTW,NULL,&size);
        if (rc == ERROR_MORE_DATA)
        {
5410
            prompt = msi_alloc(size * sizeof(WCHAR));
5411
            MsiSourceListGetInfoW(package->ProductCode, NULL, 
5412
                    package->Context, MSICODE_PRODUCT,
5413 5414 5415
                    INSTALLPROPERTY_DISKPROMPTW,prompt,&size);
        }
        else
5416
            prompt = strdupW(package->db->path);
5417

5418
        msg = msi_build_error_string(package, 1302, 1, prompt);
5419
        msi_free(prompt);
5420 5421
        while(attrib == INVALID_FILE_ATTRIBUTES)
        {
5422
            rc = MessageBoxW(NULL, msg, NULL, MB_OKCANCEL);
5423 5424
            if (rc == IDCANCEL)
            {
5425
                msi_free(msg);
5426
                return ERROR_INSTALL_USEREXIT;
5427
            }
5428
            attrib = GetFileAttributesW(package->db->path);
5429
        }
5430
        msi_free(msg);
5431 5432 5433 5434 5435 5436
        rc = ERROR_SUCCESS;
    }
    else
        return ERROR_SUCCESS;

    return rc;
5437 5438
}

5439 5440
static UINT ACTION_RegisterUser(MSIPACKAGE *package)
{
5441 5442 5443 5444
    HKEY hkey = 0;
    LPWSTR buffer, productid = NULL;
    UINT i, rc = ERROR_SUCCESS;
    MSIRECORD *uirow;
5445 5446 5447

    static const WCHAR szPropKeys[][80] = 
    {
5448 5449 5450 5451
        {'P','r','o','d','u','c','t','I','D',0},
        {'U','S','E','R','N','A','M','E',0},
        {'C','O','M','P','A','N','Y','N','A','M','E',0},
        {0},
5452 5453 5454 5455
    };

    static const WCHAR szRegKeys[][80] = 
    {
5456 5457 5458 5459
        {'P','r','o','d','u','c','t','I','D',0},
        {'R','e','g','O','w','n','e','r',0},
        {'R','e','g','C','o','m','p','a','n','y',0},
        {0},
5460 5461
    };

5462 5463 5464
    if (msi_check_unpublish(package))
    {
        MSIREG_DeleteUserDataProductKey(package->ProductCode);
5465
        goto end;
5466 5467
    }

5468
    productid = msi_dup_property( package->db, INSTALLPROPERTY_PRODUCTIDW );
5469
    if (!productid)
5470
        goto end;
5471

5472 5473
    rc = MSIREG_OpenInstallProps(package->ProductCode, package->Context,
                                 NULL, &hkey, TRUE);
5474 5475 5476
    if (rc != ERROR_SUCCESS)
        goto end;

5477
    for( i = 0; szPropKeys[i][0]; i++ )
5478
    {
5479
        buffer = msi_dup_property( package->db, szPropKeys[i] );
5480
        msi_reg_set_val_str( hkey, szRegKeys[i], buffer );
5481
        msi_free( buffer );
5482 5483 5484
    }

end:
5485 5486
    uirow = MSI_CreateRecord( 1 );
    MSI_RecordSetStringW( uirow, 1, productid );
5487
    msi_ui_actiondata( package, szRegisterUser, uirow );
5488 5489
    msiobj_release( &uirow->hdr );

5490
    msi_free(productid);
5491
    RegCloseKey(hkey);
5492
    return rc;
5493 5494
}

5495 5496 5497 5498

static UINT ACTION_ExecuteAction(MSIPACKAGE *package)
{
    UINT rc;
5499

5500
    package->script->InWhatSequence |= SEQUENCE_EXEC;
5501
    rc = ACTION_ProcessExecSequence(package,FALSE);
5502 5503 5504
    return rc;
}

5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532
WCHAR *msi_create_component_advertise_string( MSIPACKAGE *package, MSICOMPONENT *component, const WCHAR *feature )
{
    static const WCHAR fmt[] = {'%','s','%','s','%','c','%','s',0};
    WCHAR productid_85[21], component_85[21], *ret;
    GUID clsid;
    DWORD sz;

    /* > is used if there is a component GUID and < if not.  */

    productid_85[0] = 0;
    component_85[0] = 0;
    CLSIDFromString( package->ProductCode, &clsid );

    encode_base85_guid( &clsid, productid_85 );
    if (component)
    {
        CLSIDFromString( component->ComponentId, &clsid );
        encode_base85_guid( &clsid, component_85 );
    }

    TRACE("product=%s feature=%s component=%s\n", debugstr_w(productid_85), debugstr_w(feature),
          debugstr_w(component_85));

    sz = 20 + strlenW( feature ) + 20 + 3;
    ret = msi_alloc_zero( sz * sizeof(WCHAR) );
    if (ret) sprintfW( ret, fmt, productid_85, feature, component ? '>' : '<', component_85 );
    return ret;
}
5533

5534 5535
static UINT ITERATE_PublishComponent(MSIRECORD *rec, LPVOID param)
{
5536
    MSIPACKAGE *package = param;
5537
    LPCWSTR compgroupid, component, feature, qualifier, text;
5538
    LPWSTR advertise = NULL, output = NULL, existing = NULL, p, q;
5539
    HKEY hkey = NULL;
5540
    UINT rc;
5541
    MSICOMPONENT *comp;
5542 5543
    MSIFEATURE *feat;
    DWORD sz;
5544
    MSIRECORD *uirow;
5545
    int len;
5546

5547
    feature = MSI_RecordGetString(rec, 5);
5548
    feat = msi_get_loaded_feature(package, feature);
5549
    if (!feat)
5550
        return ERROR_SUCCESS;
5551

5552 5553 5554 5555
    feat->Action = msi_get_feature_action( package, feat );
    if (feat->Action != INSTALLSTATE_LOCAL &&
        feat->Action != INSTALLSTATE_SOURCE &&
        feat->Action != INSTALLSTATE_ADVERTISED)
5556
    {
5557
        TRACE("feature not scheduled for installation %s\n", debugstr_w(feature));
5558 5559
        return ERROR_SUCCESS;
    }
5560

5561
    component = MSI_RecordGetString(rec, 3);
5562
    comp = msi_get_loaded_component(package, component);
5563 5564 5565
    if (!comp)
        return ERROR_SUCCESS;

5566
    compgroupid = MSI_RecordGetString(rec,1);
5567
    qualifier = MSI_RecordGetString(rec,2);
5568 5569 5570 5571 5572

    rc = MSIREG_OpenUserComponentsKey(compgroupid, &hkey, TRUE);
    if (rc != ERROR_SUCCESS)
        goto end;

5573
    advertise = msi_create_component_advertise_string( package, comp, feature );
5574
    text = MSI_RecordGetString( rec, 4 );
5575
    if (text)
5576 5577 5578 5579 5580 5581 5582 5583
    {
        p = msi_alloc( (strlenW( advertise ) + strlenW( text ) + 1) * sizeof(WCHAR) );
        strcpyW( p, advertise );
        strcatW( p, text );
        msi_free( advertise );
        advertise = p;
    }
    existing = msi_reg_get_val_str( hkey, qualifier );
5584

5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613
    sz = strlenW( advertise ) + 1;
    if (existing)
    {
        for (p = existing; *p; p += len)
        {
            len = strlenW( p ) + 1;
            if (strcmpW( advertise, p )) sz += len;
        }
    }
    if (!(output = msi_alloc( (sz + 1) * sizeof(WCHAR) )))
    {
        rc = ERROR_OUTOFMEMORY;
        goto end;
    }
    q = output;
    if (existing)
    {
        for (p = existing; *p; p += len)
        {
            len = strlenW( p ) + 1;
            if (strcmpW( advertise, p ))
            {
                memcpy( q, p, len * sizeof(WCHAR) );
                q += len;
            }
        }
    }
    strcpyW( q, advertise );
    q[strlenW( q ) + 1] = 0;
5614

5615
    msi_reg_set_val_multi_str( hkey, qualifier, output );
5616 5617 5618
    
end:
    RegCloseKey(hkey);
5619 5620 5621
    msi_free( output );
    msi_free( advertise );
    msi_free( existing );
5622 5623 5624 5625 5626

    /* the UI chunk */
    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, compgroupid );
    MSI_RecordSetStringW( uirow, 2, qualifier);
5627
    msi_ui_actiondata( package, szPublishComponents, uirow );
5628 5629 5630
    msiobj_release( &uirow->hdr );
    /* FIXME: call ui_progress? */

5631 5632 5633 5634 5635 5636 5637 5638 5639
    return rc;
}

/*
 * At present I am ignorning the advertised components part of this and only
 * focusing on the qualified component sets
 */
static UINT ACTION_PublishComponents(MSIPACKAGE *package)
{
5640 5641 5642 5643
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','P','u','b','l','i','s','h','C','o','m','p','o','n','e','n','t','`',0};
    MSIQUERY *view;
5644 5645
    UINT rc;
    
5646
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
5647 5648 5649 5650 5651 5652 5653
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords(view, NULL, ITERATE_PublishComponent, package);
    msiobj_release(&view->hdr);
    return rc;
}
5654

5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671
static UINT ITERATE_UnpublishComponent( MSIRECORD *rec, LPVOID param )
{
    static const WCHAR szInstallerComponents[] = {
        'S','o','f','t','w','a','r','e','\\',
        'M','i','c','r','o','s','o','f','t','\\',
        'I','n','s','t','a','l','l','e','r','\\',
        'C','o','m','p','o','n','e','n','t','s','\\',0};

    MSIPACKAGE *package = param;
    LPCWSTR compgroupid, component, feature, qualifier;
    MSICOMPONENT *comp;
    MSIFEATURE *feat;
    MSIRECORD *uirow;
    WCHAR squashed[GUID_SIZE], keypath[MAX_PATH];
    LONG res;

    feature = MSI_RecordGetString( rec, 5 );
5672
    feat = msi_get_loaded_feature( package, feature );
5673 5674 5675
    if (!feat)
        return ERROR_SUCCESS;

5676 5677
    feat->Action = msi_get_feature_action( package, feat );
    if (feat->Action != INSTALLSTATE_ABSENT)
5678
    {
5679
        TRACE("feature not scheduled for removal %s\n", debugstr_w(feature));
5680 5681 5682 5683
        return ERROR_SUCCESS;
    }

    component = MSI_RecordGetString( rec, 3 );
5684
    comp = msi_get_loaded_component( package, component );
5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703
    if (!comp)
        return ERROR_SUCCESS;

    compgroupid = MSI_RecordGetString( rec, 1 );
    qualifier = MSI_RecordGetString( rec, 2 );

    squash_guid( compgroupid, squashed );
    strcpyW( keypath, szInstallerComponents );
    strcatW( keypath, squashed );

    res = RegDeleteKeyW( HKEY_CURRENT_USER, keypath );
    if (res != ERROR_SUCCESS)
    {
        WARN("Unable to delete component key %d\n", res);
    }

    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, compgroupid );
    MSI_RecordSetStringW( uirow, 2, qualifier );
5704
    msi_ui_actiondata( package, szUnpublishComponents, uirow );
5705 5706 5707 5708 5709 5710 5711
    msiobj_release( &uirow->hdr );

    return ERROR_SUCCESS;
}

static UINT ACTION_UnpublishComponents( MSIPACKAGE *package )
{
5712 5713 5714
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','P','u','b','l','i','s','h','C','o','m','p','o','n','e','n','t','`',0};
5715
    MSIQUERY *view;
5716
    UINT rc;
5717 5718 5719 5720 5721 5722 5723 5724 5725 5726

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

5727 5728
static UINT ITERATE_InstallService(MSIRECORD *rec, LPVOID param)
{
5729 5730 5731 5732
    static const WCHAR query[] =
        {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
         '`','C','o','m','p','o','n','e','n','t','`',' ','W','H','E','R','E',' ',
         '`','C','o','m','p','o','n','e','n','t','`',' ','=','\'','%','s','\'',0};
5733
    MSIPACKAGE *package = param;
5734
    MSICOMPONENT *component;
5735 5736
    MSIRECORD *row;
    MSIFILE *file;
5737
    SC_HANDLE hscm = NULL, service = NULL;
5738 5739
    LPCWSTR comp, key;
    LPWSTR name = NULL, disp = NULL, load_order = NULL, serv_name = NULL;
5740 5741
    LPWSTR depends = NULL, pass = NULL, args = NULL, image_path = NULL;
    DWORD serv_type, start_type, err_control;
5742
    SERVICE_DESCRIPTIONW sd = {NULL};
5743
    UINT ret = ERROR_SUCCESS;
5744

5745
    comp = MSI_RecordGetString( rec, 12 );
5746
    component = msi_get_loaded_component( package, comp );
5747 5748 5749 5750 5751
    if (!component)
    {
        WARN("service component not found\n");
        goto done;
    }
5752 5753
    component->Action = msi_get_component_action( package, component );
    if (component->Action != INSTALLSTATE_LOCAL)
5754
    {
5755
        TRACE("component not scheduled for installation %s\n", debugstr_w(comp));
5756 5757
        goto done;
    }
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768
    hscm = OpenSCManagerW(NULL, SERVICES_ACTIVE_DATABASEW, GENERIC_WRITE);
    if (!hscm)
    {
        ERR("Failed to open the SC Manager!\n");
        goto done;
    }

    start_type = MSI_RecordGetInteger(rec, 5);
    if (start_type == SERVICE_BOOT_START || start_type == SERVICE_SYSTEM_START)
        goto done;

5769 5770
    deformat_string(package, MSI_RecordGetString(rec, 2), &name);
    deformat_string(package, MSI_RecordGetString(rec, 3), &disp);
5771 5772
    serv_type = MSI_RecordGetInteger(rec, 4);
    err_control = MSI_RecordGetInteger(rec, 6);
5773
    deformat_string(package, MSI_RecordGetString(rec, 7), &load_order);
5774
    deformat_string(package, MSI_RecordGetString(rec, 8), &depends);
5775 5776
    deformat_string(package, MSI_RecordGetString(rec, 9), &serv_name);
    deformat_string(package, MSI_RecordGetString(rec, 10), &pass);
5777
    deformat_string(package, MSI_RecordGetString(rec, 11), &args);
5778
    deformat_string(package, MSI_RecordGetString(rec, 13), &sd.lpDescription);
5779 5780 5781 5782 5783

    /* fetch the service path */
    row = MSI_QueryGetRecord(package->db, query, comp);
    if (!row)
    {
5784
        ERR("Query failed\n");
5785 5786 5787
        goto done;
    }
    key = MSI_RecordGetString(row, 6);
5788
    file = msi_get_loaded_file(package, key);
5789
    msiobj_release(&row->hdr);
5790 5791 5792 5793 5794 5795
    if (!file)
    {
        ERR("Failed to load the service file\n");
        goto done;
    }

5796 5797 5798 5799 5800
    if (!args || !args[0]) image_path = file->TargetPath;
    else
    {
        int len = strlenW(file->TargetPath) + strlenW(args) + 2;
        if (!(image_path = msi_alloc(len * sizeof(WCHAR))))
5801 5802 5803 5804
        {
            ret = ERROR_OUTOFMEMORY;
            goto done;
        }
5805 5806 5807 5808 5809

        strcpyW(image_path, file->TargetPath);
        strcatW(image_path, szSpace);
        strcatW(image_path, args);
    }
5810
    service = CreateServiceW(hscm, name, disp, GENERIC_ALL, serv_type,
5811 5812 5813
                             start_type, err_control, image_path, load_order,
                             NULL, depends, serv_name, pass);

5814 5815 5816 5817 5818
    if (!service)
    {
        if (GetLastError() != ERROR_SERVICE_EXISTS)
            ERR("Failed to create service %s: %d\n", debugstr_w(name), GetLastError());
    }
5819 5820 5821 5822 5823
    else if (sd.lpDescription)
    {
        if (!ChangeServiceConfig2W(service, SERVICE_CONFIG_DESCRIPTION, &sd))
            WARN("failed to set service description %u\n", GetLastError());
    }
5824

5825
    if (image_path != file->TargetPath) msi_free(image_path);
5826 5827 5828
done:
    CloseServiceHandle(service);
    CloseServiceHandle(hscm);
5829 5830
    msi_free(name);
    msi_free(disp);
5831
    msi_free(sd.lpDescription);
5832 5833 5834
    msi_free(load_order);
    msi_free(serv_name);
    msi_free(pass);
5835
    msi_free(depends);
5836
    msi_free(args);
5837

5838
    return ret;
5839 5840 5841 5842
}

static UINT ACTION_InstallServices( MSIPACKAGE *package )
{
5843 5844 5845 5846
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        'S','e','r','v','i','c','e','I','n','s','t','a','l','l',0};
    MSIQUERY *view;
5847 5848
    UINT rc;
    
5849
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
5850 5851 5852 5853 5854 5855 5856 5857
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

5858
/* converts arg1[~]arg2[~]arg3 to a list of ptrs to the strings */
5859
static LPCWSTR *msi_service_args_to_vector(LPWSTR args, DWORD *numargs)
5860
{
5861
    LPCWSTR *vector, *temp_vector;
5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886
    LPWSTR p, q;
    DWORD sep_len;

    static const WCHAR separator[] = {'[','~',']',0};

    *numargs = 0;
    sep_len = sizeof(separator) / sizeof(WCHAR) - 1;

    if (!args)
        return NULL;

    vector = msi_alloc(sizeof(LPWSTR));
    if (!vector)
        return NULL;

    p = args;
    do
    {
        (*numargs)++;
        vector[*numargs - 1] = p;

        if ((q = strstrW(p, separator)))
        {
            *q = '\0';

5887 5888 5889 5890
            temp_vector = msi_realloc(vector, (*numargs + 1) * sizeof(LPWSTR));
            if (!temp_vector)
            {
                msi_free(vector);
5891
                return NULL;
5892 5893
            }
            vector = temp_vector;
5894 5895 5896 5897 5898 5899 5900 5901 5902 5903

            p = q + sep_len;
        }
    } while (q);

    return vector;
}

static UINT ITERATE_StartService(MSIRECORD *rec, LPVOID param)
{
5904
    MSIPACKAGE *package = param;
5905
    MSICOMPONENT *comp;
5906
    MSIRECORD *uirow;
5907
    SC_HANDLE scm = NULL, service = NULL;
5908
    LPCWSTR component, *vector = NULL;
5909
    LPWSTR name, args, display_name = NULL;
5910
    DWORD event, numargs, len, wait, dummy;
5911
    UINT r = ERROR_FUNCTION_FAILED;
5912 5913
    SERVICE_STATUS_PROCESS status;
    ULONGLONG start_time;
5914

5915
    component = MSI_RecordGetString(rec, 6);
5916
    comp = msi_get_loaded_component(package, component);
5917 5918 5919
    if (!comp)
        return ERROR_SUCCESS;

5920 5921
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
5922
    {
5923
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
5924
        return ERROR_SUCCESS;
5925
    }
5926

5927 5928
    deformat_string(package, MSI_RecordGetString(rec, 2), &name);
    deformat_string(package, MSI_RecordGetString(rec, 4), &args);
5929
    event = MSI_RecordGetInteger(rec, 3);
5930
    wait = MSI_RecordGetInteger(rec, 5);
5931 5932

    if (!(event & msidbServiceControlEventStart))
5933 5934 5935 5936
    {
        r = ERROR_SUCCESS;
        goto done;
    }
5937 5938 5939 5940 5941 5942 5943 5944

    scm = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
    if (!scm)
    {
        ERR("Failed to open the service control manager\n");
        goto done;
    }

5945 5946 5947 5948 5949 5950 5951 5952
    len = 0;
    if (!GetServiceDisplayNameW( scm, name, NULL, &len ) &&
        GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        if ((display_name = msi_alloc( ++len * sizeof(WCHAR ))))
            GetServiceDisplayNameW( scm, name, display_name, &len );
    }

5953
    service = OpenServiceW(scm, name, SERVICE_START|SERVICE_QUERY_STATUS);
5954 5955
    if (!service)
    {
5956
        ERR("Failed to open service %s (%u)\n", debugstr_w(name), GetLastError());
5957 5958 5959
        goto done;
    }

5960
    vector = msi_service_args_to_vector(args, &numargs);
5961

5962 5963
    if (!StartServiceW(service, numargs, vector) &&
        GetLastError() != ERROR_SERVICE_ALREADY_RUNNING)
5964
    {
5965
        ERR("Failed to start service %s (%u)\n", debugstr_w(name), GetLastError());
5966 5967 5968 5969
        goto done;
    }

    r = ERROR_SUCCESS;
5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996
    if (wait)
    {
        /* wait for at most 30 seconds for the service to be up and running */
        if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
            (BYTE *)&status, sizeof(SERVICE_STATUS_PROCESS), &dummy))
        {
            TRACE("failed to query service status (%u)\n", GetLastError());
            goto done;
        }
        start_time = GetTickCount64();
        while (status.dwCurrentState == SERVICE_START_PENDING)
        {
            if (GetTickCount64() - start_time > 30000) break;
            Sleep(1000);
            if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
                (BYTE *)&status, sizeof(SERVICE_STATUS_PROCESS), &dummy))
            {
                TRACE("failed to query service status (%u)\n", GetLastError());
                goto done;
            }
        }
        if (status.dwCurrentState != SERVICE_RUNNING)
        {
            WARN("service failed to start %u\n", status.dwCurrentState);
            r = ERROR_FUNCTION_FAILED;
        }
    }
5997 5998

done:
5999 6000 6001
    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, display_name );
    MSI_RecordSetStringW( uirow, 2, name );
6002
    msi_ui_actiondata( package, szStartServices, uirow );
6003 6004
    msiobj_release( &uirow->hdr );

6005 6006 6007
    CloseServiceHandle(service);
    CloseServiceHandle(scm);

6008
    msi_free(name);
6009 6010
    msi_free(args);
    msi_free(vector);
6011
    msi_free(display_name);
6012 6013 6014 6015 6016 6017 6018
    return r;
}

static UINT ACTION_StartServices( MSIPACKAGE *package )
{
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6019 6020 6021
        'S','e','r','v','i','c','e','C','o','n','t','r','o','l',0};
    MSIQUERY *view;
    UINT rc;
6022 6023 6024 6025 6026 6027 6028 6029 6030 6031

    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

6032 6033 6034 6035 6036 6037
static BOOL stop_service_dependents(SC_HANDLE scm, SC_HANDLE service)
{
    DWORD i, needed, count;
    ENUM_SERVICE_STATUSW *dependencies;
    SERVICE_STATUS ss;
    SC_HANDLE depserv;
6038
    BOOL stopped, ret = FALSE;
6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052

    if (EnumDependentServicesW(service, SERVICE_ACTIVE, NULL,
                               0, &needed, &count))
        return TRUE;

    if (GetLastError() != ERROR_MORE_DATA)
        return FALSE;

    dependencies = msi_alloc(needed);
    if (!dependencies)
        return FALSE;

    if (!EnumDependentServicesW(service, SERVICE_ACTIVE, dependencies,
                                needed, &needed, &count))
6053
        goto done;
6054 6055 6056 6057 6058 6059

    for (i = 0; i < count; i++)
    {
        depserv = OpenServiceW(scm, dependencies[i].lpServiceName,
                               SERVICE_STOP | SERVICE_QUERY_STATUS);
        if (!depserv)
6060
            goto done;
6061

6062 6063 6064 6065
        stopped = ControlService(depserv, SERVICE_CONTROL_STOP, &ss);
        CloseServiceHandle(depserv);
        if (!stopped)
            goto done;
6066 6067
    }

6068
    ret = TRUE;
6069

6070
done:
6071
    msi_free(dependencies);
6072
    return ret;
6073 6074
}

6075
static UINT stop_service( LPCWSTR name )
6076
{
6077
    SC_HANDLE scm = NULL, service = NULL;
6078 6079
    SERVICE_STATUS status;
    SERVICE_STATUS_PROCESS ssp;
6080
    DWORD needed;
6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094

    scm = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (!scm)
    {
        WARN("Failed to open the SCM: %d\n", GetLastError());
        goto done;
    }

    service = OpenServiceW(scm, name,
                           SERVICE_STOP |
                           SERVICE_QUERY_STATUS |
                           SERVICE_ENUMERATE_DEPENDENTS);
    if (!service)
    {
6095
        WARN("Failed to open service (%s): %d\n", debugstr_w(name), GetLastError());
6096 6097 6098 6099 6100 6101
        goto done;
    }

    if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp,
                              sizeof(SERVICE_STATUS_PROCESS), &needed))
    {
6102
        WARN("Failed to query service status (%s): %d\n", debugstr_w(name), GetLastError());
6103 6104 6105 6106 6107 6108 6109 6110
        goto done;
    }

    if (ssp.dwCurrentState == SERVICE_STOPPED)
        goto done;

    stop_service_dependents(scm, service);

James Hawkins's avatar
James Hawkins committed
6111
    if (!ControlService(service, SERVICE_CONTROL_STOP, &status))
6112 6113 6114 6115 6116
        WARN("Failed to stop service (%s): %d\n", debugstr_w(name), GetLastError());

done:
    CloseServiceHandle(service);
    CloseServiceHandle(scm);
6117 6118 6119 6120 6121 6122 6123 6124

    return ERROR_SUCCESS;
}

static UINT ITERATE_StopService( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
    MSICOMPONENT *comp;
6125
    MSIRECORD *uirow;
6126
    LPCWSTR component;
6127 6128 6129
    LPWSTR name = NULL, display_name = NULL;
    DWORD event, len;
    SC_HANDLE scm;
6130 6131 6132 6133 6134

    event = MSI_RecordGetInteger( rec, 3 );
    if (!(event & msidbServiceControlEventStop))
        return ERROR_SUCCESS;

6135
    component = MSI_RecordGetString( rec, 6 );
6136
    comp = msi_get_loaded_component( package, component );
6137
    if (!comp)
6138 6139
        return ERROR_SUCCESS;

6140 6141
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
6142
    {
6143
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
6144 6145 6146
        return ERROR_SUCCESS;
    }

6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162
    scm = OpenSCManagerW( NULL, NULL, SC_MANAGER_CONNECT );
    if (!scm)
    {
        ERR("Failed to open the service control manager\n");
        goto done;
    }

    len = 0;
    if (!GetServiceDisplayNameW( scm, name, NULL, &len ) &&
        GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        if ((display_name = msi_alloc( ++len * sizeof(WCHAR ))))
            GetServiceDisplayNameW( scm, name, display_name, &len );
    }
    CloseServiceHandle( scm );

6163 6164
    deformat_string( package, MSI_RecordGetString( rec, 2 ), &name );
    stop_service( name );
6165

6166 6167 6168 6169
done:
    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, display_name );
    MSI_RecordSetStringW( uirow, 2, name );
6170
    msi_ui_actiondata( package, szStopServices, uirow );
6171 6172 6173 6174
    msiobj_release( &uirow->hdr );

    msi_free( name );
    msi_free( display_name );
6175 6176 6177 6178 6179 6180 6181
    return ERROR_SUCCESS;
}

static UINT ACTION_StopServices( MSIPACKAGE *package )
{
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6182 6183 6184
        'S','e','r','v','i','c','e','C','o','n','t','r','o','l',0};
    MSIQUERY *view;
    UINT rc;
6185 6186 6187 6188 6189 6190 6191 6192 6193 6194

    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

6195 6196 6197 6198
static UINT ITERATE_DeleteService( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
    MSICOMPONENT *comp;
6199 6200 6201
    MSIRECORD *uirow;
    LPWSTR name = NULL, display_name = NULL;
    DWORD event, len;
6202 6203
    SC_HANDLE scm = NULL, service = NULL;

6204
    comp = msi_get_loaded_component( package, MSI_RecordGetString(rec, 6) );
6205 6206 6207
    if (!comp)
        return ERROR_SUCCESS;

6208 6209 6210
    event = MSI_RecordGetInteger( rec, 3 );
    deformat_string( package, MSI_RecordGetString(rec, 2), &name );

6211
    comp->Action = msi_get_component_action( package, comp );
6212 6213
    if (!(comp->Action == INSTALLSTATE_LOCAL && (event & msidbServiceControlEventDelete)) &&
        !(comp->Action == INSTALLSTATE_ABSENT && (event & msidbServiceControlEventUninstallDelete)))
6214
    {
6215 6216
        TRACE("service %s not scheduled for removal\n", debugstr_w(name));
        msi_free( name );
6217
        return ERROR_SUCCESS;
6218
    }
6219 6220 6221 6222 6223 6224 6225 6226 6227
    stop_service( name );

    scm = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS );
    if (!scm)
    {
        WARN("Failed to open the SCM: %d\n", GetLastError());
        goto done;
    }

6228 6229 6230 6231 6232 6233 6234 6235
    len = 0;
    if (!GetServiceDisplayNameW( scm, name, NULL, &len ) &&
        GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        if ((display_name = msi_alloc( ++len * sizeof(WCHAR ))))
            GetServiceDisplayNameW( scm, name, display_name, &len );
    }

6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246
    service = OpenServiceW( scm, name, DELETE );
    if (!service)
    {
        WARN("Failed to open service (%s): %u\n", debugstr_w(name), GetLastError());
        goto done;
    }

    if (!DeleteService( service ))
        WARN("Failed to delete service (%s): %u\n", debugstr_w(name), GetLastError());

done:
6247 6248 6249
    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, display_name );
    MSI_RecordSetStringW( uirow, 2, name );
6250
    msi_ui_actiondata( package, szDeleteServices, uirow );
6251 6252
    msiobj_release( &uirow->hdr );

6253 6254 6255
    CloseServiceHandle( service );
    CloseServiceHandle( scm );
    msi_free( name );
6256
    msi_free( display_name );
6257 6258 6259 6260 6261 6262 6263 6264

    return ERROR_SUCCESS;
}

static UINT ACTION_DeleteServices( MSIPACKAGE *package )
{
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6265 6266 6267
        'S','e','r','v','i','c','e','C','o','n','t','r','o','l',0};
    MSIQUERY *view;
    UINT rc;
6268 6269 6270 6271 6272 6273 6274 6275 6276 6277

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

6278 6279
static UINT ITERATE_InstallODBCDriver( MSIRECORD *rec, LPVOID param )
{
6280
    MSIPACKAGE *package = param;
6281 6282
    LPWSTR driver, driver_path, ptr;
    WCHAR outpath[MAX_PATH];
6283
    MSIFILE *driver_file = NULL, *setup_file = NULL;
6284
    MSICOMPONENT *comp;
6285
    MSIRECORD *uirow;
6286
    LPCWSTR desc, file_key, component;
6287 6288 6289 6290 6291 6292 6293 6294 6295 6296
    DWORD len, usage;
    UINT r = ERROR_SUCCESS;

    static const WCHAR driver_fmt[] = {
        'D','r','i','v','e','r','=','%','s',0};
    static const WCHAR setup_fmt[] = {
        'S','e','t','u','p','=','%','s',0};
    static const WCHAR usage_fmt[] = {
        'F','i','l','e','U','s','a','g','e','=','1',0};

6297
    component = MSI_RecordGetString( rec, 2 );
6298
    comp = msi_get_loaded_component( package, component );
6299 6300 6301
    if (!comp)
        return ERROR_SUCCESS;

6302 6303
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
6304
    {
6305
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
6306 6307
        return ERROR_SUCCESS;
    }
6308 6309
    desc = MSI_RecordGetString(rec, 3);

6310
    file_key = MSI_RecordGetString( rec, 4 );
6311
    if (file_key) driver_file = msi_get_loaded_file( package, file_key );
6312 6313

    file_key = MSI_RecordGetString( rec, 5 );
6314
    if (file_key) setup_file = msi_get_loaded_file( package, file_key );
6315

6316
    if (!driver_file)
6317 6318 6319 6320 6321
    {
        ERR("ODBC Driver entry not found!\n");
        return ERROR_FUNCTION_FAILED;
    }

6322 6323 6324
    len = lstrlenW(desc) + lstrlenW(driver_fmt) + lstrlenW(driver_file->FileName);
    if (setup_file)
        len += lstrlenW(setup_fmt) + lstrlenW(setup_file->FileName);
6325
    len += lstrlenW(usage_fmt) + 2; /* \0\0 */
6326

6327 6328 6329 6330 6331 6332 6333 6334
    driver = msi_alloc(len * sizeof(WCHAR));
    if (!driver)
        return ERROR_OUTOFMEMORY;

    ptr = driver;
    lstrcpyW(ptr, desc);
    ptr += lstrlenW(ptr) + 1;

6335 6336
    len = sprintfW(ptr, driver_fmt, driver_file->FileName);
    ptr += len + 1;
6337

6338 6339
    if (setup_file)
    {
6340 6341
        len = sprintfW(ptr, setup_fmt, setup_file->FileName);
        ptr += len + 1;
6342
    }
6343 6344 6345 6346 6347

    lstrcpyW(ptr, usage_fmt);
    ptr += lstrlenW(ptr) + 1;
    *ptr = '\0';

6348 6349 6350 6351 6352
    if (!driver_file->TargetPath)
    {
        const WCHAR *dir = msi_get_target_folder( package, driver_file->Component->Directory );
        driver_file->TargetPath = msi_build_directory_name( 2, dir, driver_file->FileName );
    }
6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363
    driver_path = strdupW(driver_file->TargetPath);
    ptr = strrchrW(driver_path, '\\');
    if (ptr) *ptr = '\0';

    if (!SQLInstallDriverExW(driver, driver_path, outpath, MAX_PATH,
                             NULL, ODBC_INSTALL_COMPLETE, &usage))
    {
        ERR("Failed to install SQL driver!\n");
        r = ERROR_FUNCTION_FAILED;
    }

6364 6365 6366
    uirow = MSI_CreateRecord( 5 );
    MSI_RecordSetStringW( uirow, 1, desc );
    MSI_RecordSetStringW( uirow, 2, MSI_RecordGetString(rec, 2) );
6367
    MSI_RecordSetStringW( uirow, 3, driver_file->Component->Directory );
6368
    msi_ui_actiondata( package, szInstallODBC, uirow );
6369 6370
    msiobj_release( &uirow->hdr );

6371 6372 6373 6374 6375 6376
    msi_free(driver);
    msi_free(driver_path);

    return r;
}

6377 6378
static UINT ITERATE_InstallODBCTranslator( MSIRECORD *rec, LPVOID param )
{
6379
    MSIPACKAGE *package = param;
6380 6381
    LPWSTR translator, translator_path, ptr;
    WCHAR outpath[MAX_PATH];
6382
    MSIFILE *translator_file = NULL, *setup_file = NULL;
6383
    MSICOMPONENT *comp;
6384
    MSIRECORD *uirow;
6385
    LPCWSTR desc, file_key, component;
6386 6387 6388 6389 6390 6391 6392 6393
    DWORD len, usage;
    UINT r = ERROR_SUCCESS;

    static const WCHAR translator_fmt[] = {
        'T','r','a','n','s','l','a','t','o','r','=','%','s',0};
    static const WCHAR setup_fmt[] = {
        'S','e','t','u','p','=','%','s',0};

6394
    component = MSI_RecordGetString( rec, 2 );
6395
    comp = msi_get_loaded_component( package, component );
6396 6397 6398
    if (!comp)
        return ERROR_SUCCESS;

6399 6400
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
6401
    {
6402
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
6403 6404
        return ERROR_SUCCESS;
    }
6405 6406
    desc = MSI_RecordGetString(rec, 3);

6407
    file_key = MSI_RecordGetString( rec, 4 );
6408
    if (file_key) translator_file = msi_get_loaded_file( package, file_key );
6409 6410

    file_key = MSI_RecordGetString( rec, 5 );
6411
    if (file_key) setup_file = msi_get_loaded_file( package, file_key );
6412

6413
    if (!translator_file)
6414 6415 6416 6417 6418
    {
        ERR("ODBC Translator entry not found!\n");
        return ERROR_FUNCTION_FAILED;
    }

6419
    len = lstrlenW(desc) + lstrlenW(translator_fmt) + lstrlenW(translator_file->FileName) + 2; /* \0\0 */
6420 6421 6422
    if (setup_file)
        len += lstrlenW(setup_fmt) + lstrlenW(setup_file->FileName);

6423 6424 6425 6426 6427 6428 6429 6430
    translator = msi_alloc(len * sizeof(WCHAR));
    if (!translator)
        return ERROR_OUTOFMEMORY;

    ptr = translator;
    lstrcpyW(ptr, desc);
    ptr += lstrlenW(ptr) + 1;

6431 6432
    len = sprintfW(ptr, translator_fmt, translator_file->FileName);
    ptr += len + 1;
6433

6434 6435
    if (setup_file)
    {
6436 6437
        len = sprintfW(ptr, setup_fmt, setup_file->FileName);
        ptr += len + 1;
6438
    }
6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451
    *ptr = '\0';

    translator_path = strdupW(translator_file->TargetPath);
    ptr = strrchrW(translator_path, '\\');
    if (ptr) *ptr = '\0';

    if (!SQLInstallTranslatorExW(translator, translator_path, outpath, MAX_PATH,
                                 NULL, ODBC_INSTALL_COMPLETE, &usage))
    {
        ERR("Failed to install SQL translator!\n");
        r = ERROR_FUNCTION_FAILED;
    }

6452 6453 6454
    uirow = MSI_CreateRecord( 5 );
    MSI_RecordSetStringW( uirow, 1, desc );
    MSI_RecordSetStringW( uirow, 2, MSI_RecordGetString(rec, 2) );
6455
    MSI_RecordSetStringW( uirow, 3, translator_file->Component->Directory );
6456
    msi_ui_actiondata( package, szInstallODBC, uirow );
6457 6458
    msiobj_release( &uirow->hdr );

6459 6460 6461 6462 6463 6464
    msi_free(translator);
    msi_free(translator_path);

    return r;
}

6465 6466
static UINT ITERATE_InstallODBCDataSource( MSIRECORD *rec, LPVOID param )
{
6467
    MSIPACKAGE *package = param;
6468
    MSICOMPONENT *comp;
6469
    LPWSTR attrs;
6470
    LPCWSTR desc, driver, component;
6471 6472 6473 6474
    WORD request = ODBC_ADD_SYS_DSN;
    INT registration;
    DWORD len;
    UINT r = ERROR_SUCCESS;
6475
    MSIRECORD *uirow;
6476 6477 6478 6479

    static const WCHAR attrs_fmt[] = {
        'D','S','N','=','%','s',0 };

6480
    component = MSI_RecordGetString( rec, 2 );
6481
    comp = msi_get_loaded_component( package, component );
6482 6483 6484
    if (!comp)
        return ERROR_SUCCESS;

6485 6486
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
6487
    {
6488
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
6489 6490 6491
        return ERROR_SUCCESS;
    }

6492 6493 6494 6495 6496 6497 6498
    desc = MSI_RecordGetString(rec, 3);
    driver = MSI_RecordGetString(rec, 4);
    registration = MSI_RecordGetInteger(rec, 5);

    if (registration == msidbODBCDataSourceRegistrationPerMachine) request = ODBC_ADD_SYS_DSN;
    else if (registration == msidbODBCDataSourceRegistrationPerUser) request = ODBC_ADD_DSN;

6499
    len = lstrlenW(attrs_fmt) + lstrlenW(desc) + 2; /* \0\0 */
6500 6501 6502 6503
    attrs = msi_alloc(len * sizeof(WCHAR));
    if (!attrs)
        return ERROR_OUTOFMEMORY;

6504 6505
    len = sprintfW(attrs, attrs_fmt, desc);
    attrs[len + 1] = 0;
6506 6507 6508 6509 6510 6511 6512

    if (!SQLConfigDataSourceW(NULL, request, driver, attrs))
    {
        ERR("Failed to install SQL data source!\n");
        r = ERROR_FUNCTION_FAILED;
    }

6513 6514 6515 6516
    uirow = MSI_CreateRecord( 5 );
    MSI_RecordSetStringW( uirow, 1, desc );
    MSI_RecordSetStringW( uirow, 2, MSI_RecordGetString(rec, 2) );
    MSI_RecordSetInteger( uirow, 3, request );
6517
    msi_ui_actiondata( package, szInstallODBC, uirow );
6518 6519
    msiobj_release( &uirow->hdr );

6520 6521 6522 6523 6524
    msi_free(attrs);

    return r;
}

6525 6526
static UINT ACTION_InstallODBC( MSIPACKAGE *package )
{
6527
    static const WCHAR driver_query[] = {
6528
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6529
        'O','D','B','C','D','r','i','v','e','r',0};
6530 6531
    static const WCHAR translator_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6532
        'O','D','B','C','T','r','a','n','s','l','a','t','o','r',0};
6533 6534
    static const WCHAR source_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6535 6536 6537
        'O','D','B','C','D','a','t','a','S','o','u','r','c','e',0};
    MSIQUERY *view;
    UINT rc;
6538

6539
    rc = MSI_DatabaseOpenViewW(package->db, driver_query, &view);
6540 6541 6542 6543 6544 6545 6546
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords(view, NULL, ITERATE_InstallODBCDriver, package);
        msiobj_release(&view->hdr);
        if (rc != ERROR_SUCCESS)
            return rc;
    }
6547
    rc = MSI_DatabaseOpenViewW(package->db, translator_query, &view);
6548 6549 6550 6551 6552 6553 6554
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords(view, NULL, ITERATE_InstallODBCTranslator, package);
        msiobj_release(&view->hdr);
        if (rc != ERROR_SUCCESS)
            return rc;
    }
6555
    rc = MSI_DatabaseOpenViewW(package->db, source_query, &view);
6556 6557 6558 6559 6560 6561 6562 6563
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords(view, NULL, ITERATE_InstallODBCDataSource, package);
        msiobj_release(&view->hdr);
        if (rc != ERROR_SUCCESS)
            return rc;
    }
    return ERROR_SUCCESS;
6564 6565
}

6566 6567
static UINT ITERATE_RemoveODBCDriver( MSIRECORD *rec, LPVOID param )
{
6568
    MSIPACKAGE *package = param;
6569
    MSICOMPONENT *comp;
6570
    MSIRECORD *uirow;
6571
    DWORD usage;
6572 6573 6574
    LPCWSTR desc, component;

    component = MSI_RecordGetString( rec, 2 );
6575
    comp = msi_get_loaded_component( package, component );
6576 6577 6578
    if (!comp)
        return ERROR_SUCCESS;

6579 6580
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
6581
    {
6582
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
6583 6584
        return ERROR_SUCCESS;
    }
6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595

    desc = MSI_RecordGetString( rec, 3 );
    if (!SQLRemoveDriverW( desc, FALSE, &usage ))
    {
        WARN("Failed to remove ODBC driver\n");
    }
    else if (!usage)
    {
        FIXME("Usage count reached 0\n");
    }

6596 6597 6598
    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, desc );
    MSI_RecordSetStringW( uirow, 2, MSI_RecordGetString(rec, 2) );
6599
    msi_ui_actiondata( package, szRemoveODBC, uirow );
6600 6601
    msiobj_release( &uirow->hdr );

6602 6603 6604 6605 6606
    return ERROR_SUCCESS;
}

static UINT ITERATE_RemoveODBCTranslator( MSIRECORD *rec, LPVOID param )
{
6607
    MSIPACKAGE *package = param;
6608
    MSICOMPONENT *comp;
6609
    MSIRECORD *uirow;
6610
    DWORD usage;
6611 6612 6613
    LPCWSTR desc, component;

    component = MSI_RecordGetString( rec, 2 );
6614
    comp = msi_get_loaded_component( package, component );
6615 6616 6617
    if (!comp)
        return ERROR_SUCCESS;

6618 6619
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
6620
    {
6621
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
6622 6623
        return ERROR_SUCCESS;
    }
6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634

    desc = MSI_RecordGetString( rec, 3 );
    if (!SQLRemoveTranslatorW( desc, &usage ))
    {
        WARN("Failed to remove ODBC translator\n");
    }
    else if (!usage)
    {
        FIXME("Usage count reached 0\n");
    }

6635 6636 6637
    uirow = MSI_CreateRecord( 2 );
    MSI_RecordSetStringW( uirow, 1, desc );
    MSI_RecordSetStringW( uirow, 2, MSI_RecordGetString(rec, 2) );
6638
    msi_ui_actiondata( package, szRemoveODBC, uirow );
6639 6640
    msiobj_release( &uirow->hdr );

6641 6642 6643 6644 6645
    return ERROR_SUCCESS;
}

static UINT ITERATE_RemoveODBCDataSource( MSIRECORD *rec, LPVOID param )
{
6646
    MSIPACKAGE *package = param;
6647
    MSICOMPONENT *comp;
6648
    MSIRECORD *uirow;
6649
    LPWSTR attrs;
6650
    LPCWSTR desc, driver, component;
6651 6652 6653 6654 6655 6656 6657
    WORD request = ODBC_REMOVE_SYS_DSN;
    INT registration;
    DWORD len;

    static const WCHAR attrs_fmt[] = {
        'D','S','N','=','%','s',0 };

6658
    component = MSI_RecordGetString( rec, 2 );
6659
    comp = msi_get_loaded_component( package, component );
6660 6661 6662
    if (!comp)
        return ERROR_SUCCESS;

6663 6664
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
6665
    {
6666
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
6667 6668 6669
        return ERROR_SUCCESS;
    }

6670 6671 6672 6673 6674 6675 6676
    desc = MSI_RecordGetString( rec, 3 );
    driver = MSI_RecordGetString( rec, 4 );
    registration = MSI_RecordGetInteger( rec, 5 );

    if (registration == msidbODBCDataSourceRegistrationPerMachine) request = ODBC_REMOVE_SYS_DSN;
    else if (registration == msidbODBCDataSourceRegistrationPerUser) request = ODBC_REMOVE_DSN;

6677
    len = strlenW( attrs_fmt ) + strlenW( desc ) + 2; /* \0\0 */
6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692
    attrs = msi_alloc( len * sizeof(WCHAR) );
    if (!attrs)
        return ERROR_OUTOFMEMORY;

    FIXME("Use ODBCSourceAttribute table\n");

    len = sprintfW( attrs, attrs_fmt, desc );
    attrs[len + 1] = 0;

    if (!SQLConfigDataSourceW( NULL, request, driver, attrs ))
    {
        WARN("Failed to remove ODBC data source\n");
    }
    msi_free( attrs );

6693 6694 6695 6696
    uirow = MSI_CreateRecord( 3 );
    MSI_RecordSetStringW( uirow, 1, desc );
    MSI_RecordSetStringW( uirow, 2, MSI_RecordGetString(rec, 2) );
    MSI_RecordSetInteger( uirow, 3, request );
6697
    msi_ui_actiondata( package, szRemoveODBC, uirow );
6698 6699
    msiobj_release( &uirow->hdr );

6700 6701 6702 6703 6704 6705 6706
    return ERROR_SUCCESS;
}

static UINT ACTION_RemoveODBC( MSIPACKAGE *package )
{
    static const WCHAR driver_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6707
        'O','D','B','C','D','r','i','v','e','r',0};
6708 6709
    static const WCHAR translator_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6710
        'O','D','B','C','T','r','a','n','s','l','a','t','o','r',0};
6711 6712
    static const WCHAR source_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
6713 6714 6715
        'O','D','B','C','D','a','t','a','S','o','u','r','c','e',0};
    MSIQUERY *view;
    UINT rc;
6716 6717

    rc = MSI_DatabaseOpenViewW( package->db, driver_query, &view );
6718 6719 6720 6721 6722 6723 6724
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveODBCDriver, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
6725
    rc = MSI_DatabaseOpenViewW( package->db, translator_query, &view );
6726 6727 6728 6729 6730 6731 6732
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveODBCTranslator, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
6733
    rc = MSI_DatabaseOpenViewW( package->db, source_query, &view );
6734 6735 6736 6737 6738 6739 6740 6741
    if (rc == ERROR_SUCCESS)
    {
        rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveODBCDataSource, package );
        msiobj_release( &view->hdr );
        if (rc != ERROR_SUCCESS)
            return rc;
    }
    return ERROR_SUCCESS;
6742 6743
}

6744 6745 6746
#define ENV_ACT_SETALWAYS   0x1
#define ENV_ACT_SETABSENT   0x2
#define ENV_ACT_REMOVE      0x4
6747
#define ENV_ACT_REMOVEMATCH 0x8
6748 6749 6750 6751

#define ENV_MOD_MACHINE     0x20000000
#define ENV_MOD_APPEND      0x40000000
#define ENV_MOD_PREFIX      0x80000000
6752 6753 6754 6755
#define ENV_MOD_MASK        0xC0000000

#define check_flag_combo(x, y) ((x) & ~(y)) == (y)

6756
static UINT env_parse_flags( LPCWSTR *name, LPCWSTR *value, DWORD *flags )
6757 6758 6759 6760
{
    LPCWSTR cptr = *name;

    static const WCHAR prefix[] = {'[','~',']',0};
6761
    static const int prefix_len = 3;
6762 6763

    *flags = 0;
6764
    while (*cptr)
6765
    {
6766
        if (*cptr == '=')
6767
            *flags |= ENV_ACT_SETALWAYS;
6768
        else if (*cptr == '+')
6769
            *flags |= ENV_ACT_SETABSENT;
6770
        else if (*cptr == '-')
6771
            *flags |= ENV_ACT_REMOVE;
6772
        else if (*cptr == '!')
6773
            *flags |= ENV_ACT_REMOVEMATCH;
6774
        else if (*cptr == '*')
6775
            *flags |= ENV_MOD_MACHINE;
6776
        else
6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788
            break;

        cptr++;
        (*name)++;
    }

    if (!*cptr)
    {
        ERR("Missing environment variable\n");
        return ERROR_FUNCTION_FAILED;
    }

6789
    if (*value)
6790
    {
6791 6792
        LPCWSTR ptr = *value;
        if (!strncmpW(ptr, prefix, prefix_len))
6793
        {
6794 6795 6796 6797 6798 6799 6800 6801 6802
            if (ptr[prefix_len] == szSemiColon[0])
            {
                *flags |= ENV_MOD_APPEND;
                *value += lstrlenW(prefix);
            }
            else
            {
                *value = NULL;
            }
6803 6804 6805 6806
        }
        else if (lstrlenW(*value) >= prefix_len)
        {
            ptr += lstrlenW(ptr) - prefix_len;
6807
            if (!strcmpW( ptr, prefix ))
6808
            {
6809 6810 6811 6812 6813 6814 6815 6816 6817
                if ((ptr-1) > *value && *(ptr-1) == szSemiColon[0])
                {
                    *flags |= ENV_MOD_PREFIX;
                    /* the "[~]" will be removed by deformat_string */;
                }
                else
                {
                    *value = NULL;
                }
6818
            }
6819 6820 6821
        }
    }

6822
    if (check_flag_combo(*flags, ENV_ACT_SETALWAYS | ENV_ACT_SETABSENT) ||
6823 6824 6825 6826 6827 6828 6829 6830
        check_flag_combo(*flags, ENV_ACT_REMOVEMATCH | ENV_ACT_SETABSENT) ||
        check_flag_combo(*flags, ENV_ACT_REMOVEMATCH | ENV_ACT_SETALWAYS) ||
        check_flag_combo(*flags, ENV_ACT_SETABSENT | ENV_MOD_MASK))
    {
        ERR("Invalid flags: %08x\n", *flags);
        return ERROR_FUNCTION_FAILED;
    }

6831 6832 6833
    if (!*flags)
        *flags = ENV_ACT_SETALWAYS | ENV_ACT_REMOVE;

6834 6835
    return ERROR_SUCCESS;
}
6836

6837
static UINT open_env_key( DWORD flags, HKEY *key )
6838
{
6839 6840 6841
    static const WCHAR user_env[] =
        {'E','n','v','i','r','o','n','m','e','n','t',0};
    static const WCHAR machine_env[] =
6842 6843 6844 6845 6846
        {'S','y','s','t','e','m','\\',
         'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
         'C','o','n','t','r','o','l','\\',
         'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
         'E','n','v','i','r','o','n','m','e','n','t',0};
6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878
    const WCHAR *env;
    HKEY root;
    LONG res;

    if (flags & ENV_MOD_MACHINE)
    {
        env = machine_env;
        root = HKEY_LOCAL_MACHINE;
    }
    else
    {
        env = user_env;
        root = HKEY_CURRENT_USER;
    }

    res = RegOpenKeyExW( root, env, 0, KEY_ALL_ACCESS, key );
    if (res != ERROR_SUCCESS)
    {
        WARN("Failed to open key %s (%d)\n", debugstr_w(env), res);
        return ERROR_FUNCTION_FAILED;
    }

    return ERROR_SUCCESS;
}

static UINT ITERATE_WriteEnvironmentString( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR name, value, component;
    LPWSTR data = NULL, newval = NULL, deformatted = NULL, ptr;
    DWORD flags, type, size;
    UINT res;
6879
    HKEY env = NULL;
6880 6881 6882
    MSICOMPONENT *comp;
    MSIRECORD *uirow;
    int action = 0;
6883

6884
    component = MSI_RecordGetString(rec, 4);
6885
    comp = msi_get_loaded_component(package, component);
6886 6887 6888
    if (!comp)
        return ERROR_SUCCESS;

6889 6890
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
6891
    {
6892
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
6893 6894
        return ERROR_SUCCESS;
    }
6895 6896 6897
    name = MSI_RecordGetString(rec, 2);
    value = MSI_RecordGetString(rec, 3);

6898 6899
    TRACE("name %s value %s\n", debugstr_w(name), debugstr_w(value));

6900
    res = env_parse_flags(&name, &value, &flags);
6901
    if (res != ERROR_SUCCESS || !value)
6902
       goto done;
6903

6904
    if (value && !deformat_string(package, value, &deformatted))
6905 6906 6907 6908 6909
    {
        res = ERROR_OUTOFMEMORY;
        goto done;
    }

6910
    value = deformatted;
6911

6912
    res = open_env_key( flags, &env );
6913
    if (res != ERROR_SUCCESS)
6914
        goto done;
6915

6916 6917
    if (flags & ENV_MOD_MACHINE)
        action |= 0x20000000;
6918 6919

    size = 0;
6920
    type = REG_SZ;
6921 6922
    res = RegQueryValueExW(env, name, NULL, &type, NULL, &size);
    if ((res != ERROR_SUCCESS && res != ERROR_FILE_NOT_FOUND) ||
6923
        (res == ERROR_SUCCESS && type != REG_SZ && type != REG_EXPAND_SZ))
6924
        goto done;
6925

6926 6927
    if ((res == ERROR_FILE_NOT_FOUND || !(flags & ENV_MOD_MASK)))
    {
6928 6929
        action = 0x2;

6930 6931 6932 6933 6934 6935 6936
        /* Nothing to do. */
        if (!value)
        {
            res = ERROR_SUCCESS;
            goto done;
        }

6937 6938 6939
        /* If we are appending but the string was empty, strip ; */
        if ((flags & ENV_MOD_APPEND) && (value[0] == szSemiColon[0])) value++;

6940 6941 6942 6943 6944 6945 6946 6947 6948
        size = (lstrlenW(value) + 1) * sizeof(WCHAR);
        newval = strdupW(value);
        if (!newval)
        {
            res = ERROR_OUTOFMEMORY;
            goto done;
        }
    }
    else
6949
    {
6950 6951
        action = 0x1;

6952 6953
        /* Contrary to MSDN, +-variable to [~];path works */
        if (flags & ENV_ACT_SETABSENT && !(flags & ENV_MOD_MASK))
6954 6955 6956 6957 6958
        {
            res = ERROR_SUCCESS;
            goto done;
        }

6959 6960
        data = msi_alloc(size);
        if (!data)
6961
        {
6962 6963
            RegCloseKey(env);
            return ERROR_OUTOFMEMORY;
6964 6965
        }

6966 6967 6968 6969
        res = RegQueryValueExW(env, name, NULL, &type, (LPVOID)data, &size);
        if (res != ERROR_SUCCESS)
            goto done;

6970
        if (flags & ENV_ACT_REMOVEMATCH && (!value || !strcmpW( data, value )))
6971
        {
6972 6973 6974 6975
            action = 0x4;
            res = RegDeleteValueW(env, name);
            if (res != ERROR_SUCCESS)
                WARN("Failed to remove value %s (%d)\n", debugstr_w(name), res);
6976
            goto done;
6977 6978
        }

6979 6980 6981 6982 6983 6984 6985
        size = (lstrlenW(data) + 1) * sizeof(WCHAR);
        if (flags & ENV_MOD_MASK)
        {
            DWORD mod_size;
            int multiplier = 0;
            if (flags & ENV_MOD_APPEND) multiplier++;
            if (flags & ENV_MOD_PREFIX) multiplier++;
6986
            mod_size = lstrlenW(value) * multiplier;
6987 6988 6989 6990
            size += mod_size * sizeof(WCHAR);
        }

        newval = msi_alloc(size);
6991 6992 6993 6994
        ptr = newval;
        if (!newval)
        {
            res = ERROR_OUTOFMEMORY;
6995
            goto done;
6996
        }
6997

6998
        if (flags & ENV_MOD_PREFIX)
6999
        {
7000
            lstrcpyW(newval, value);
7001
            ptr = newval + lstrlenW(value);
7002
            action |= 0x80000000;
7003
        }
7004

7005
        lstrcpyW(ptr, data);
7006

7007
        if (flags & ENV_MOD_APPEND)
7008
        {
7009
            lstrcatW(newval, value);
7010
            action |= 0x40000000;
7011 7012
        }
    }
7013 7014
    TRACE("setting %s to %s\n", debugstr_w(name), debugstr_w(newval));
    res = RegSetValueExW(env, name, 0, type, (LPVOID)newval, size);
7015 7016 7017 7018
    if (res)
    {
        WARN("Failed to set %s to %s (%d)\n",  debugstr_w(name), debugstr_w(newval), res);
    }
7019 7020

done:
7021 7022 7023 7024
    uirow = MSI_CreateRecord( 3 );
    MSI_RecordSetStringW( uirow, 1, name );
    MSI_RecordSetStringW( uirow, 2, newval );
    MSI_RecordSetInteger( uirow, 3, action );
7025
    msi_ui_actiondata( package, szWriteEnvironmentStrings, uirow );
7026 7027
    msiobj_release( &uirow->hdr );

7028
    if (env) RegCloseKey(env);
7029 7030 7031
    msi_free(deformatted);
    msi_free(data);
    msi_free(newval);
7032 7033 7034 7035 7036
    return res;
}

static UINT ACTION_WriteEnvironmentStrings( MSIPACKAGE *package )
{
7037 7038 7039 7040
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','E','n','v','i','r','o','n','m','e','n','t','`',0};
    MSIQUERY *view;
7041
    UINT rc;
7042 7043

    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
7044 7045 7046 7047 7048 7049 7050 7051
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065
static UINT ITERATE_RemoveEnvironmentString( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPCWSTR name, value, component;
    LPWSTR deformatted = NULL;
    DWORD flags;
    HKEY env;
    MSICOMPONENT *comp;
    MSIRECORD *uirow;
    int action = 0;
    LONG res;
    UINT r;

    component = MSI_RecordGetString( rec, 4 );
7066
    comp = msi_get_loaded_component( package, component );
7067 7068 7069
    if (!comp)
        return ERROR_SUCCESS;

7070 7071
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
7072
    {
7073
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119
        return ERROR_SUCCESS;
    }
    name = MSI_RecordGetString( rec, 2 );
    value = MSI_RecordGetString( rec, 3 );

    TRACE("name %s value %s\n", debugstr_w(name), debugstr_w(value));

    r = env_parse_flags( &name, &value, &flags );
    if (r != ERROR_SUCCESS)
       return r;

    if (!(flags & ENV_ACT_REMOVE))
    {
        TRACE("Environment variable %s not marked for removal\n", debugstr_w(name));
        return ERROR_SUCCESS;
    }

    if (value && !deformat_string( package, value, &deformatted ))
        return ERROR_OUTOFMEMORY;

    value = deformatted;

    r = open_env_key( flags, &env );
    if (r != ERROR_SUCCESS)
    {
        r = ERROR_SUCCESS;
        goto done;
    }

    if (flags & ENV_MOD_MACHINE)
        action |= 0x20000000;

    TRACE("Removing %s\n", debugstr_w(name));

    res = RegDeleteValueW( env, name );
    if (res != ERROR_SUCCESS)
    {
        WARN("Failed to delete value %s (%d)\n", debugstr_w(name), res);
        r = ERROR_SUCCESS;
    }

done:
    uirow = MSI_CreateRecord( 3 );
    MSI_RecordSetStringW( uirow, 1, name );
    MSI_RecordSetStringW( uirow, 2, value );
    MSI_RecordSetInteger( uirow, 3, action );
7120
    msi_ui_actiondata( package, szRemoveEnvironmentStrings, uirow );
7121 7122 7123 7124 7125 7126 7127 7128 7129
    msiobj_release( &uirow->hdr );

    if (env) RegCloseKey( env );
    msi_free( deformatted );
    return r;
}

static UINT ACTION_RemoveEnvironmentStrings( MSIPACKAGE *package )
{
7130 7131 7132
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','E','n','v','i','r','o','n','m','e','n','t','`',0};
7133
    MSIQUERY *view;
7134
    UINT rc;
7135 7136 7137 7138 7139 7140 7141 7142 7143 7144

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

7145
UINT msi_validate_product_id( MSIPACKAGE *package )
7146 7147 7148 7149
{
    LPWSTR key, template, id;
    UINT r = ERROR_SUCCESS;

7150
    id = msi_dup_property( package->db, szProductID );
7151 7152 7153 7154 7155
    if (id)
    {
        msi_free( id );
        return ERROR_SUCCESS;
    }
7156 7157
    template = msi_dup_property( package->db, szPIDTemplate );
    key = msi_dup_property( package->db, szPIDKEY );
7158 7159 7160
    if (key && template)
    {
        FIXME( "partial stub: template %s key %s\n", debugstr_w(template), debugstr_w(key) );
7161
        r = msi_set_property( package->db, szProductID, key, -1 );
7162 7163 7164 7165 7166 7167
    }
    msi_free( template );
    msi_free( key );
    return r;
}

7168 7169 7170 7171 7172
static UINT ACTION_ValidateProductID( MSIPACKAGE *package )
{
    return msi_validate_product_id( package );
}

7173 7174 7175
static UINT ACTION_ScheduleReboot( MSIPACKAGE *package )
{
    TRACE("\n");
7176
    package->need_reboot_at_end = 1;
7177 7178 7179
    return ERROR_SUCCESS;
}

7180 7181
static UINT ACTION_AllocateRegistrySpace( MSIPACKAGE *package )
{
Hans Leidekker's avatar
Hans Leidekker committed
7182 7183
    static const WCHAR szAvailableFreeReg[] =
        {'A','V','A','I','L','A','B','L','E','F','R','E','E','R','E','G',0};
7184
    MSIRECORD *uirow;
7185
    int space = msi_get_property_int( package->db, szAvailableFreeReg, 0 );
7186 7187 7188 7189 7190

    TRACE("%p %d kilobytes\n", package, space);

    uirow = MSI_CreateRecord( 1 );
    MSI_RecordSetInteger( uirow, 1, space );
7191
    msi_ui_actiondata( package, szAllocateRegistrySpace, uirow );
7192
    msiobj_release( &uirow->hdr );
Hans Leidekker's avatar
Hans Leidekker committed
7193

7194 7195 7196 7197 7198
    return ERROR_SUCCESS;
}

static UINT ACTION_DisableRollback( MSIPACKAGE *package )
{
7199 7200
    TRACE("%p\n", package);

7201
    msi_set_property( package->db, szRollbackDisabled, szOne, -1 );
7202 7203 7204 7205 7206 7207 7208 7209 7210
    return ERROR_SUCCESS;
}

static UINT ACTION_InstallAdminPackage( MSIPACKAGE *package )
{
    FIXME("%p\n", package);
    return ERROR_SUCCESS;
}

7211 7212 7213 7214
static UINT ACTION_SetODBCFolders( MSIPACKAGE *package )
{
    static const WCHAR driver_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
7215
        'O','D','B','C','D','r','i','v','e','r',0};
7216 7217
    static const WCHAR translator_query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
7218 7219 7220
        'O','D','B','C','T','r','a','n','s','l','a','t','o','r',0};
    MSIQUERY *view;
    UINT r, count;
7221 7222 7223 7224 7225 7226 7227

    r = MSI_DatabaseOpenViewW( package->db, driver_query, &view );
    if (r == ERROR_SUCCESS)
    {
        count = 0;
        r = MSI_IterateRecords( view, &count, NULL, package );
        msiobj_release( &view->hdr );
7228 7229
        if (r != ERROR_SUCCESS)
            return r;
7230 7231 7232 7233 7234 7235 7236 7237
        if (count) FIXME("ignored %u rows in ODBCDriver table\n", count);
    }
    r = MSI_DatabaseOpenViewW( package->db, translator_query, &view );
    if (r == ERROR_SUCCESS)
    {
        count = 0;
        r = MSI_IterateRecords( view, &count, NULL, package );
        msiobj_release( &view->hdr );
7238 7239
        if (r != ERROR_SUCCESS)
            return r;
7240 7241 7242 7243 7244
        if (count) FIXME("ignored %u rows in ODBCTranslator table\n", count);
    }
    return ERROR_SUCCESS;
}

7245 7246
static UINT ITERATE_RemoveExistingProducts( MSIRECORD *rec, LPVOID param )
{
7247 7248
    static const WCHAR fmtW[] =
        {'m','s','i','e','x','e','c',' ','/','i',' ','%','s',' ','R','E','M','O','V','E','=','%','s',0};
7249
    MSIPACKAGE *package = param;
7250
    const WCHAR *property = MSI_RecordGetString( rec, 7 );
7251
    int attrs = MSI_RecordGetInteger( rec, 5 );
7252 7253 7254 7255 7256
    UINT len = sizeof(fmtW)/sizeof(fmtW[0]);
    WCHAR *product, *features, *cmd;
    STARTUPINFOW si;
    PROCESS_INFORMATION info;
    BOOL ret;
7257

7258
    if (attrs & msidbUpgradeAttributesOnlyDetect) return ERROR_SUCCESS;
7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269
    if (!(product = msi_dup_property( package->db, property ))) return ERROR_SUCCESS;

    deformat_string( package, MSI_RecordGetString( rec, 6 ), &features );

    len += strlenW( product );
    if (features)
        len += strlenW( features );
    else
        len += sizeof(szAll) / sizeof(szAll[0]);

    if (!(cmd = msi_alloc( len * sizeof(WCHAR) )))
7270
    {
7271 7272 7273
        msi_free( product );
        msi_free( features );
        return ERROR_OUTOFMEMORY;
7274
    }
7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286
    sprintfW( cmd, fmtW, product, features ? features : szAll );
    msi_free( product );
    msi_free( features );

    memset( &si, 0, sizeof(STARTUPINFOW) );
    ret = CreateProcessW( NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &info );
    msi_free( cmd );
    if (!ret) return GetLastError();
    CloseHandle( info.hThread );

    WaitForSingleObject( info.hProcess, INFINITE );
    CloseHandle( info.hProcess );
7287 7288 7289 7290 7291
    return ERROR_SUCCESS;
}

static UINT ACTION_RemoveExistingProducts( MSIPACKAGE *package )
{
7292
    static const WCHAR query[] = {
7293
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','U','p','g','r','a','d','e',0};
7294
    MSIQUERY *view;
7295
    UINT r;
7296 7297 7298 7299 7300 7301

    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r == ERROR_SUCCESS)
    {
        r = MSI_IterateRecords( view, NULL, ITERATE_RemoveExistingProducts, package );
        msiobj_release( &view->hdr );
7302 7303
        if (r != ERROR_SUCCESS)
            return r;
7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344
    }
    return ERROR_SUCCESS;
}

static UINT ITERATE_MigrateFeatureStates( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
    int attributes = MSI_RecordGetInteger( rec, 5 );

    if (attributes & msidbUpgradeAttributesMigrateFeatures)
    {
        const WCHAR *upgrade_code = MSI_RecordGetString( rec, 1 );
        const WCHAR *version_min = MSI_RecordGetString( rec, 2 );
        const WCHAR *version_max = MSI_RecordGetString( rec, 3 );
        const WCHAR *language = MSI_RecordGetString( rec, 4 );
        HKEY hkey;
        UINT r;

        if (package->Context == MSIINSTALLCONTEXT_MACHINE)
        {
            r = MSIREG_OpenClassesUpgradeCodesKey( upgrade_code, &hkey, FALSE );
            if (r != ERROR_SUCCESS)
                return ERROR_SUCCESS;
        }
        else
        {
            r = MSIREG_OpenUserUpgradeCodesKey( upgrade_code, &hkey, FALSE );
            if (r != ERROR_SUCCESS)
                return ERROR_SUCCESS;
        }
        RegCloseKey( hkey );

        FIXME("migrate feature states from %s version min %s version max %s language %s\n",
              debugstr_w(upgrade_code), debugstr_w(version_min),
              debugstr_w(version_max), debugstr_w(language));
    }
    return ERROR_SUCCESS;
}

static UINT ACTION_MigrateFeatureStates( MSIPACKAGE *package )
{
7345 7346 7347
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        'U','p','g','r','a','d','e',0};
7348
    MSIQUERY *view;
7349
    UINT r;
7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365

    if (msi_get_property_int( package->db, szInstalled, 0 ))
    {
        TRACE("product is installed, skipping action\n");
        return ERROR_SUCCESS;
    }
    if (msi_get_property_int( package->db, szPreselected, 0 ))
    {
        TRACE("Preselected property is set, not migrating feature states\n");
        return ERROR_SUCCESS;
    }
    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r == ERROR_SUCCESS)
    {
        r = MSI_IterateRecords( view, NULL, ITERATE_MigrateFeatureStates, package );
        msiobj_release( &view->hdr );
7366 7367
        if (r != ERROR_SUCCESS)
            return r;
7368 7369 7370 7371
    }
    return ERROR_SUCCESS;
}

7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417
static void bind_image( const char *filename, const char *path )
{
    if (!BindImageEx( 0, filename, path, NULL, NULL ))
    {
        WARN("failed to bind image %u\n", GetLastError());
    }
}

static UINT ITERATE_BindImage( MSIRECORD *rec, LPVOID param )
{
    UINT i;
    MSIFILE *file;
    MSIPACKAGE *package = param;
    const WCHAR *key = MSI_RecordGetString( rec, 1 );
    const WCHAR *paths = MSI_RecordGetString( rec, 2 );
    char *filenameA, *pathA;
    WCHAR *pathW, **path_list;

    if (!(file = msi_get_loaded_file( package, key )))
    {
        WARN("file %s not found\n", debugstr_w(key));
        return ERROR_SUCCESS;
    }
    if (!(filenameA = strdupWtoA( file->TargetPath ))) return ERROR_SUCCESS;
    path_list = msi_split_string( paths, ';' );
    if (!path_list) bind_image( filenameA, NULL );
    else
    {
        for (i = 0; path_list[i] && path_list[i][0]; i++)
        {
            deformat_string( package, path_list[i], &pathW );
            if ((pathA = strdupWtoA( pathW )))
            {
                bind_image( filenameA, pathA );
                msi_free( pathA );
            }
            msi_free( pathW );
        }
    }
    msi_free( path_list );
    msi_free( filenameA );
    return ERROR_SUCCESS;
}

static UINT ACTION_BindImage( MSIPACKAGE *package )
{
7418 7419 7420
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        'B','i','n','d','I','m','a','g','e',0};
7421
    MSIQUERY *view;
7422
    UINT r;
7423 7424 7425 7426 7427 7428

    r = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (r == ERROR_SUCCESS)
    {
        r = MSI_IterateRecords( view, NULL, ITERATE_BindImage, package );
        msiobj_release( &view->hdr );
7429 7430
        if (r != ERROR_SUCCESS)
            return r;
7431 7432 7433 7434
    }
    return ERROR_SUCCESS;
}

7435
static UINT msi_unimplemented_action_stub( MSIPACKAGE *package, LPCSTR action, LPCWSTR table )
7436
{
7437
    static const WCHAR query[] = {
7438 7439
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','`','%','s','`',0};
    MSIQUERY *view;
7440
    DWORD count = 0;
7441
    UINT r;
7442
    
7443 7444
    r = MSI_OpenQuery( package->db, &view, query, table );
    if (r == ERROR_SUCCESS)
7445
    {
7446
        r = MSI_IterateRecords(view, &count, NULL, package);
7447
        msiobj_release(&view->hdr);
7448 7449
        if (r != ERROR_SUCCESS)
            return r;
7450
    }
7451
    if (count) FIXME("%s: ignored %u rows from %s\n", action, count, debugstr_w(table));
7452 7453
    return ERROR_SUCCESS;
}
7454

7455
static UINT ACTION_IsolateComponents( MSIPACKAGE *package )
7456
{
7457
    static const WCHAR table[] = {
7458
        'I','s','o','l','a','t','e','d','C','o','m','p','o','n','e','n','t',0 };
7459 7460
    return msi_unimplemented_action_stub( package, "IsolateComponents", table );
}
7461

7462 7463 7464 7465 7466 7467
static UINT ACTION_RMCCPSearch( MSIPACKAGE *package )
{
    static const WCHAR table[] = { 'C','C','P','S','e','a','r','c','h',0 };
    return msi_unimplemented_action_stub( package, "RMCCPSearch", table );
}

7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479
static UINT ACTION_RegisterComPlus( MSIPACKAGE *package )
{
    static const WCHAR table[] = { 'C','o','m','p','l','u','s',0 };
    return msi_unimplemented_action_stub( package, "RegisterComPlus", table );
}

static UINT ACTION_UnregisterComPlus( MSIPACKAGE *package )
{
    static const WCHAR table[] = { 'C','o','m','p','l','u','s',0 };
    return msi_unimplemented_action_stub( package, "UnregisterComPlus", table );
}

7480 7481 7482 7483 7484 7485
static UINT ACTION_InstallSFPCatalogFile( MSIPACKAGE *package )
{
    static const WCHAR table[] = { 'S','F','P','C','a','t','a','l','o','g',0 };
    return msi_unimplemented_action_stub( package, "InstallSFPCatalogFile", table );
}

7486 7487 7488 7489
static const struct
{
    const WCHAR *action;
    UINT (*handler)(MSIPACKAGE *);
7490
    const WCHAR *action_rollback;
7491 7492 7493
}
StandardActions[] =
{
7494 7495 7496 7497 7498 7499 7500 7501
    { szAllocateRegistrySpace, ACTION_AllocateRegistrySpace, NULL },
    { szAppSearch, ACTION_AppSearch, NULL },
    { szBindImage, ACTION_BindImage, NULL },
    { szCCPSearch, ACTION_CCPSearch, NULL },
    { szCostFinalize, ACTION_CostFinalize, NULL },
    { szCostInitialize, ACTION_CostInitialize, NULL },
    { szCreateFolders, ACTION_CreateFolders, szRemoveFolders },
    { szCreateShortcuts, ACTION_CreateShortcuts, szRemoveShortcuts },
7502
    { szDeleteServices, ACTION_DeleteServices, szInstallServices },
7503 7504 7505 7506 7507 7508 7509 7510 7511
    { szDisableRollback, ACTION_DisableRollback, NULL },
    { szDuplicateFiles, ACTION_DuplicateFiles, szRemoveDuplicateFiles },
    { szExecuteAction, ACTION_ExecuteAction, NULL },
    { szFileCost, ACTION_FileCost, NULL },
    { szFindRelatedProducts, ACTION_FindRelatedProducts, NULL },
    { szForceReboot, ACTION_ForceReboot, NULL },
    { szInstallAdminPackage, ACTION_InstallAdminPackage, NULL },
    { szInstallExecute, ACTION_InstallExecute, NULL },
    { szInstallExecuteAgain, ACTION_InstallExecute, NULL },
7512
    { szInstallFiles, ACTION_InstallFiles, szRemoveFiles },
7513 7514
    { szInstallFinalize, ACTION_InstallFinalize, NULL },
    { szInstallInitialize, ACTION_InstallInitialize, NULL },
7515 7516
    { szInstallODBC, ACTION_InstallODBC, szRemoveODBC },
    { szInstallServices, ACTION_InstallServices, szDeleteServices },
7517 7518 7519 7520 7521 7522 7523
    { szInstallSFPCatalogFile, ACTION_InstallSFPCatalogFile, NULL },
    { szInstallValidate, ACTION_InstallValidate, NULL },
    { szIsolateComponents, ACTION_IsolateComponents, NULL },
    { szLaunchConditions, ACTION_LaunchConditions, NULL },
    { szMigrateFeatureStates, ACTION_MigrateFeatureStates, NULL },
    { szMoveFiles, ACTION_MoveFiles, NULL },
    { szMsiPublishAssemblies, ACTION_MsiPublishAssemblies, szMsiUnpublishAssemblies },
7524
    { szMsiUnpublishAssemblies, ACTION_MsiUnpublishAssemblies, szMsiPublishAssemblies },
7525
    { szPatchFiles, ACTION_PatchFiles, NULL },
7526
    { szProcessComponents, ACTION_ProcessComponents, szProcessComponents },
7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538
    { szPublishComponents, ACTION_PublishComponents, szUnpublishComponents },
    { szPublishFeatures, ACTION_PublishFeatures, szUnpublishFeatures },
    { szPublishProduct, ACTION_PublishProduct, NULL },
    { szRegisterClassInfo, ACTION_RegisterClassInfo, szUnregisterClassInfo },
    { szRegisterComPlus, ACTION_RegisterComPlus, szUnregisterComPlus },
    { szRegisterExtensionInfo, ACTION_RegisterExtensionInfo, szUnregisterExtensionInfo },
    { szRegisterFonts, ACTION_RegisterFonts, szUnregisterFonts },
    { szRegisterMIMEInfo, ACTION_RegisterMIMEInfo, szUnregisterMIMEInfo },
    { szRegisterProduct, ACTION_RegisterProduct, NULL },
    { szRegisterProgIdInfo, ACTION_RegisterProgIdInfo, szUnregisterProgIdInfo },
    { szRegisterTypeLibraries, ACTION_RegisterTypeLibraries, szUnregisterTypeLibraries },
    { szRegisterUser, ACTION_RegisterUser, NULL },
7539 7540
    { szRemoveDuplicateFiles, ACTION_RemoveDuplicateFiles, szDuplicateFiles },
    { szRemoveEnvironmentStrings, ACTION_RemoveEnvironmentStrings, szWriteEnvironmentStrings },
7541
    { szRemoveExistingProducts, ACTION_RemoveExistingProducts, NULL },
7542 7543 7544 7545 7546 7547
    { szRemoveFiles, ACTION_RemoveFiles, szInstallFiles },
    { szRemoveFolders, ACTION_RemoveFolders, szCreateFolders },
    { szRemoveIniValues, ACTION_RemoveIniValues, szWriteIniValues },
    { szRemoveODBC, ACTION_RemoveODBC, szInstallODBC },
    { szRemoveRegistryValues, ACTION_RemoveRegistryValues, szWriteRegistryValues },
    { szRemoveShortcuts, ACTION_RemoveShortcuts, szCreateShortcuts },
7548 7549 7550 7551
    { szResolveSource, ACTION_ResolveSource, NULL },
    { szRMCCPSearch, ACTION_RMCCPSearch, NULL },
    { szScheduleReboot, ACTION_ScheduleReboot, NULL },
    { szSelfRegModules, ACTION_SelfRegModules, szSelfUnregModules },
7552
    { szSelfUnregModules, ACTION_SelfUnregModules, szSelfRegModules },
7553 7554
    { szSetODBCFolders, ACTION_SetODBCFolders, NULL },
    { szStartServices, ACTION_StartServices, szStopServices },
7555 7556 7557 7558 7559 7560 7561 7562 7563 7564
    { szStopServices, ACTION_StopServices, szStartServices },
    { szUnpublishComponents, ACTION_UnpublishComponents, szPublishComponents },
    { szUnpublishFeatures, ACTION_UnpublishFeatures, szPublishFeatures },
    { szUnregisterClassInfo, ACTION_UnregisterClassInfo, szRegisterClassInfo },
    { szUnregisterComPlus, ACTION_UnregisterComPlus, szRegisterComPlus },
    { szUnregisterExtensionInfo, ACTION_UnregisterExtensionInfo, szRegisterExtensionInfo },
    { szUnregisterFonts, ACTION_UnregisterFonts, szRegisterFonts },
    { szUnregisterMIMEInfo, ACTION_UnregisterMIMEInfo, szRegisterMIMEInfo },
    { szUnregisterProgIdInfo, ACTION_UnregisterProgIdInfo, szRegisterProgIdInfo },
    { szUnregisterTypeLibraries, ACTION_UnregisterTypeLibraries, szRegisterTypeLibraries },
7565 7566 7567 7568 7569
    { szValidateProductID, ACTION_ValidateProductID, NULL },
    { szWriteEnvironmentStrings, ACTION_WriteEnvironmentStrings, szRemoveEnvironmentStrings },
    { szWriteIniValues, ACTION_WriteIniValues, szRemoveIniValues },
    { szWriteRegistryValues, ACTION_WriteRegistryValues, szRemoveRegistryValues },
    { NULL, NULL, NULL }
7570
};
7571

7572
static BOOL ACTION_HandleStandardAction( MSIPACKAGE *package, LPCWSTR action, UINT *rc )
7573 7574
{
    BOOL ret = FALSE;
7575
    UINT i;
7576 7577 7578 7579

    i = 0;
    while (StandardActions[i].action != NULL)
    {
7580
        if (!strcmpW( StandardActions[i].action, action ))
7581
        {
7582 7583
            ui_actionstart( package, action );
            if (StandardActions[i].handler)
7584
            {
7585 7586 7587
                ui_actioninfo( package, action, TRUE, 0 );
                *rc = StandardActions[i].handler( package );
                ui_actioninfo( package, action, FALSE, *rc );
7588

7589
                if (StandardActions[i].action_rollback && !package->need_rollback)
7590 7591
                {
                    TRACE("scheduling rollback action\n");
7592
                    msi_schedule_action( package, SCRIPT_ROLLBACK, StandardActions[i].action_rollback );
7593
                }
7594 7595 7596
            }
            else
            {
7597 7598
                FIXME("unhandled standard action %s\n", debugstr_w(action));
                *rc = ERROR_SUCCESS;
7599 7600 7601 7602 7603 7604 7605 7606
            }
            ret = TRUE;
            break;
        }
        i++;
    }
    return ret;
}
7607

7608
UINT ACTION_PerformAction(MSIPACKAGE *package, const WCHAR *action, UINT script)
7609 7610 7611 7612 7613 7614
{
    UINT rc = ERROR_SUCCESS;
    BOOL handled;

    TRACE("Performing action (%s)\n", debugstr_w(action));

7615
    handled = ACTION_HandleStandardAction(package, action, &rc);
7616 7617

    if (!handled)
7618
        handled = ACTION_HandleCustomAction(package, action, &rc, script, TRUE);
7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635

    if (!handled)
    {
        WARN("unhandled msi action %s\n", debugstr_w(action));
        rc = ERROR_FUNCTION_NOT_CALLED;
    }

    return rc;
}

UINT ACTION_PerformUIAction(MSIPACKAGE *package, const WCHAR *action, UINT script)
{
    UINT rc = ERROR_SUCCESS;
    BOOL handled = FALSE;

    TRACE("Performing action (%s)\n", debugstr_w(action));

7636
    package->action_progress_increment = 0;
7637
    handled = ACTION_HandleStandardAction(package, action, &rc);
7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653

    if (!handled)
        handled = ACTION_HandleCustomAction(package, action, &rc, script, FALSE);

    if( !handled && ACTION_DialogBox(package, action) == ERROR_SUCCESS )
        handled = TRUE;

    if (!handled)
    {
        WARN("unhandled msi action %s\n", debugstr_w(action));
        rc = ERROR_FUNCTION_NOT_CALLED;
    }

    return rc;
}

7654
static UINT ACTION_PerformActionSequence(MSIPACKAGE *package, UINT seq)
7655 7656
{
    UINT rc = ERROR_SUCCESS;
7657
    MSIRECORD *row;
7658

7659
    static const WCHAR query[] =
7660 7661 7662 7663
        {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
         '`','I','n','s','t','a','l','l','E','x','e','c','u','t','e',
         'S','e','q','u','e','n','c','e','`',' ', 'W','H','E','R','E',' ',
         '`','S','e','q','u','e','n','c','e','`',' ', '=',' ','%','i',0};
7664
    static const WCHAR ui_query[] =
7665 7666 7667 7668 7669
        {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
     '`','I','n','s','t','a','l','l','U','I','S','e','q','u','e','n','c','e',
     '`', ' ', 'W','H','E','R','E',' ','`','S','e','q','u','e','n','c','e','`',
	 ' ', '=',' ','%','i',0};

7670
    if (needs_ui_sequence(package))
7671
        row = MSI_QueryGetRecord(package->db, ui_query, seq);
7672
    else
7673
        row = MSI_QueryGetRecord(package->db, query, seq);
7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685

    if (row)
    {
        LPCWSTR action, cond;

        TRACE("Running the actions\n");

        /* check conditions */
        cond = MSI_RecordGetString(row, 2);

        /* this is a hack to skip errors in the condition code */
        if (MSI_EvaluateConditionW(package, cond) == MSICONDITION_FALSE)
7686 7687 7688 7689
        {
            msiobj_release(&row->hdr);
            return ERROR_SUCCESS;
        }
7690 7691 7692 7693 7694

        action = MSI_RecordGetString(row, 1);
        if (!action)
        {
            ERR("failed to fetch action\n");
7695 7696
            msiobj_release(&row->hdr);
            return ERROR_FUNCTION_FAILED;
7697 7698
        }

7699
        if (needs_ui_sequence(package))
7700
            rc = ACTION_PerformUIAction(package, action, SCRIPT_NONE);
7701
        else
7702
            rc = ACTION_PerformAction(package, action, SCRIPT_NONE);
7703

7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716
        msiobj_release(&row->hdr);
    }

    return rc;
}

/****************************************************
 * TOP level entry points
 *****************************************************/

UINT MSI_InstallPackage( MSIPACKAGE *package, LPCWSTR szPackagePath,
                         LPCWSTR szCommandLine )
{
7717
    static const WCHAR szDisableRollback[] = {'D','I','S','A','B','L','E','R','O','L','L','B','A','C','K',0};
7718 7719
    static const WCHAR szAction[] = {'A','C','T','I','O','N',0};
    static const WCHAR szInstall[] = {'I','N','S','T','A','L','L',0};
7720
    WCHAR *reinstall, *remove, *patch;
7721 7722
    BOOL ui_exists;
    UINT rc;
7723

7724
    msi_set_property( package->db, szAction, szInstall, -1 );
7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763

    package->script->InWhatSequence = SEQUENCE_INSTALL;

    if (szPackagePath)
    {
        LPWSTR p, dir;
        LPCWSTR file;

        dir = strdupW(szPackagePath);
        p = strrchrW(dir, '\\');
        if (p)
        {
            *(++p) = 0;
            file = szPackagePath + (p - dir);
        }
        else
        {
            msi_free(dir);
            dir = msi_alloc(MAX_PATH * sizeof(WCHAR));
            GetCurrentDirectoryW(MAX_PATH, dir);
            lstrcatW(dir, szBackSlash);
            file = szPackagePath;
        }

        msi_free( package->PackagePath );
        package->PackagePath = msi_alloc((lstrlenW(dir) + lstrlenW(file) + 1) * sizeof(WCHAR));
        if (!package->PackagePath)
        {
            msi_free(dir);
            return ERROR_OUTOFMEMORY;
        }

        lstrcpyW(package->PackagePath, dir);
        lstrcatW(package->PackagePath, file);
        msi_free(dir);

        msi_set_sourcedir_props(package, FALSE);
    }

7764 7765 7766
    rc = msi_parse_command_line( package, szCommandLine, FALSE );
    if (rc != ERROR_SUCCESS)
        return rc;
7767 7768 7769 7770

    msi_apply_transforms( package );
    msi_apply_patches( package );

7771
    patch = msi_dup_property( package->db, szPatch );
7772 7773
    remove = msi_dup_property( package->db, szRemove );
    reinstall = msi_dup_property( package->db, szReinstall );
7774
    if (msi_get_property_int( package->db, szInstalled, 0 ) && !remove && !reinstall && !patch)
7775
    {
7776
        TRACE("setting REINSTALL property to ALL\n");
7777
        msi_set_property( package->db, szReinstall, szAll, -1 );
7778
        package->full_reinstall = 1;
7779 7780 7781 7782
    }

    /* properties may have been added by a transform */
    msi_clone_properties( package );
7783
    msi_set_original_database_property( package->db, szPackagePath );
7784 7785

    msi_parse_command_line( package, szCommandLine, FALSE );
7786
    msi_adjust_privilege_properties( package );
7787 7788
    msi_set_context( package );

7789 7790 7791
    if (msi_get_property_int( package->db, szDisableRollback, 0 ))
    {
        TRACE("disabling rollback\n");
7792
        msi_set_property( package->db, szRollbackDisabled, szOne, -1 );
7793 7794
    }

7795
    if (needs_ui_sequence( package))
7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812
    {
        package->script->InWhatSequence |= SEQUENCE_UI;
        rc = ACTION_ProcessUISequence(package);
        ui_exists = ui_sequence_exists(package);
        if (rc == ERROR_SUCCESS || !ui_exists)
        {
            package->script->InWhatSequence |= SEQUENCE_EXEC;
            rc = ACTION_ProcessExecSequence(package, ui_exists);
        }
    }
    else
        rc = ACTION_ProcessExecSequence(package, FALSE);

    package->script->CurrentlyScripting = FALSE;

    /* process the ending type action */
    if (rc == ERROR_SUCCESS)
7813
        ACTION_PerformActionSequence(package, -1);
7814
    else if (rc == ERROR_INSTALL_USEREXIT)
7815
        ACTION_PerformActionSequence(package, -2);
7816
    else if (rc == ERROR_INSTALL_SUSPEND)
7817
        ACTION_PerformActionSequence(package, -4);
7818
    else  /* failed */
7819
    {
7820
        ACTION_PerformActionSequence(package, -3);
7821 7822 7823 7824
        if (!msi_get_property_int( package->db, szRollbackDisabled, 0 ))
        {
            package->need_rollback = TRUE;
        }
7825
    }
7826 7827 7828 7829

    /* finish up running custom actions */
    ACTION_FinishCustomActions(package);

7830
    if (package->need_rollback && !reinstall)
7831 7832
    {
        WARN("installation failed, running rollback script\n");
7833
        execute_script( package, SCRIPT_ROLLBACK );
7834
    }
7835
    msi_free( reinstall );
7836
    msi_free( remove );
7837
    msi_free( patch );
7838

7839
    if (rc == ERROR_SUCCESS && package->need_reboot_at_end)
7840 7841 7842 7843
        return ERROR_SUCCESS_REBOOT_REQUIRED;

    return rc;
}