shlexec.c 68.2 KB
Newer Older
1 2 3
/*
 * 				Shell Library Functions
 *
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * Copyright 1998 Marcus Meissner
 * Copyright 2002 Eric Pouech
 *
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21 22
 */

#include "config.h"
23
#include "wine/port.h"
24 25 26

#include <stdlib.h>
#include <string.h>
27
#include <stdarg.h>
28
#include <stdio.h>
29 30 31
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
32 33 34
#include <ctype.h>
#include <assert.h>

35 36
#define COBJMACROS

37
#include "windef.h"
38
#include "winbase.h"
39 40
#include "winerror.h"
#include "winreg.h"
41
#include "winuser.h"
42 43 44 45
#include "shlwapi.h"
#include "ddeml.h"

#include "shell32_main.h"
46
#include "pidl.h"
47
#include "shresdef.h"
48

49
#include "wine/debug.h"
50

51
WINE_DEFAULT_DEBUG_CHANNEL(exec);
52

53 54
static const WCHAR wszOpen[] = {'o','p','e','n',0};
static const WCHAR wszExe[] = {'.','e','x','e',0};
55
static const WCHAR wszILPtr[] = {':','%','p',0};
56
static const WCHAR wszShell[] = {'\\','s','h','e','l','l','\\',0};
57 58
static const WCHAR wszFolder[] = {'F','o','l','d','e','r',0};
static const WCHAR wszEmpty[] = {0};
59

60 61
#define SEE_MASK_CLASSALL (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY)

62 63 64
typedef UINT_PTR (*SHELL_ExecuteW32)(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
			    const SHELLEXECUTEINFOW *sei, LPSHELLEXECUTEINFOW sei_out);

65 66 67 68
static inline BOOL isSpace(WCHAR c)
{
    return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v';
}
69

70
/***********************************************************************
71 72
 *	SHELL_ArgifyW [Internal]
 *
73
 * this function is supposed to expand the escape sequences found in the registry
74
 * some diving reported that the following were used:
75
 * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
76 77 78 79
 *	%1 file
 *	%2 printer
 *	%3 driver
 *	%4 port
Francois Gouget's avatar
Francois Gouget committed
80
 * %I address of a global item ID (explorer switch /idlist)
81 82 83
 * %L seems to be %1 as long filename followed by the 8+3 variation
 * %S ???
 * %* all following parameters (see batfile)
84
 *
85
 */
86
static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args, DWORD* out_len)
87
{
88 89
    WCHAR   xlpFile[1024];
    BOOL    done = FALSE;
90
    BOOL    found_p1 = FALSE;
91 92
    PWSTR   res = out;
    PCWSTR  cmd;
93
    DWORD   used = 0;
94

95 96 97
    TRACE("%p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
          debugstr_w(lpFile), pidl, args);

98 99 100 101 102 103 104
    while (*fmt)
    {
        if (*fmt == '%')
        {
            switch (*++fmt)
            {
            case '\0':
105
            case '%':
106 107 108
                used++;
                if (used < len)
                    *res++ = '%';
109
                break;
110 111 112 113 114 115 116 117 118 119

            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
120
            case '*':
121 122 123 124
                if (args)
                {
                    if (*fmt == '*')
                    {
125 126 127
                        used++;
                        if (used < len)
                            *res++ = '"';
128
                        while(*args)
129 130 131 132 133 134 135 136 137 138
                        {
                            used++;
                            if (used < len)
                                *res++ = *args++;
                            else
                                args++;
                        }
                        used++;
                        if (used < len)
                            *res++ = '"';
139 140 141
                    }
                    else
                    {
142
                        while(*args && !isSpace(*args))
143 144 145 146 147 148 149
                        {
                            used++;
                            if (used < len)
                                *res++ = *args++;
                            else
                                args++;
                        }
150

151
                        while(isSpace(*args))
152 153 154 155 156 157
                            ++args;
                    }
                    break;
                }
                /* else fall through */
            case '1':
158
                if (!done || (*fmt == '1'))
159
                {
160
                    /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
161
                    if (SearchPathW(NULL, lpFile, wszExe, ARRAY_SIZE(xlpFile), xlpFile, NULL))
162 163 164 165
                        cmd = xlpFile;
                    else
                        cmd = lpFile;

166 167
                    used += strlenW(cmd);
                    if (used < len)
168
                    {
169 170
                        strcpyW(res, cmd);
                        res += strlenW(cmd);
171
                    }
172
                }
173
                found_p1 = TRUE;
174
                break;
175

176
            /*
177
             * IE uses this a lot for activating things such as windows media
178 179 180
             * player. This is not verified to be fully correct but it appears
             * to work just fine.
             */
181
            case 'l':
182
            case 'L':
183
		if (lpFile) {
184 185 186 187 188 189
		    used += strlenW(lpFile);
		    if (used < len)
		    {
			strcpyW(res, lpFile);
			res += strlenW(lpFile);
		    }
190
		}
191
		found_p1 = TRUE;
192 193 194 195 196
                break;

            case 'i':
            case 'I':
		if (pidl) {
197
		    INT chars = 0;
198
		    /* %p should not exceed 8, maybe 16 when looking forward to 64bit.
199 200 201
		     * allowing a buffer of 100 should more than exceed all needs */
		    WCHAR buf[100];
		    LPVOID  pv;
202 203
		    HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
		    pv = SHLockShared(hmem, 0);
204
		    chars = sprintfW(buf, wszILPtr, pv);
205
		    if (chars >= ARRAY_SIZE(buf))
206
			ERR("pidl format buffer too small!\n");
207 208 209 210 211 212
		    used += chars;
		    if (used < len)
		    {
			strcpyW(res,buf);
			res += chars;
		    }
213 214
		    SHUnlockShared(pv);
		}
215
                found_p1 = TRUE;
216 217
                break;

218 219
	    default:
                /*
220
                 * Check if this is an env-variable here...
221 222 223 224 225 226 227 228 229 230 231 232 233 234
                 */

                /* Make sure that we have at least one more %.*/
                if (strchrW(fmt, '%'))
                {
                    WCHAR   tmpBuffer[1024];
                    PWSTR   tmpB = tmpBuffer;
                    WCHAR   tmpEnvBuff[MAX_PATH];
                    DWORD   envRet;

                    while (*fmt != '%')
                        *tmpB++ = *fmt++;
                    *tmpB++ = 0;

235
                    TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
236 237 238

                    envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
                    if (envRet == 0 || envRet > MAX_PATH)
239 240 241 242 243 244 245 246
                    {
                        used += strlenW(tmpBuffer);
                        if (used < len)
                        {
                            strcpyW( res, tmpBuffer );
                            res += strlenW(tmpBuffer);
                        }
                    }
247
                    else
248 249 250 251 252 253 254 255
                    {
                        used += strlenW(tmpEnvBuff);
                        if (used < len)
                        {
                            strcpyW( res, tmpEnvBuff );
                            res += strlenW(tmpEnvBuff);
                        }
                    }
256 257 258
                }
                done = TRUE;
                break;
259
            }
260 261 262 263 264
            /* Don't skip past terminator (catch a single '%' at the end) */
            if (*fmt != '\0')
            {
                fmt++;
            }
265 266
        }
        else
267 268 269 270 271 272 273
        {
            used ++;
            if (used < len) 
                *res++ = *fmt++;
            else
                fmt++;
        }
274
    }
275

276 277 278 279 280 281
    used ++;
    if (res - out < len)
        *res = '\0';
    else
        out[len-1] = '\0';

282 283 284
    TRACE("used %i of %i space\n",used,len);
    if (out_len)
        *out_len = used;
285

286
    return found_p1;
Duane Clark's avatar
Duane Clark committed
287 288
}

289
static HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
{
    STRRET strret;
    IShellFolder* desktop;

    HRESULT hr = SHGetDesktopFolder(&desktop);

    if (SUCCEEDED(hr)) {
	hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);

	if (SUCCEEDED(hr))
	    StrRetToStrNW(pszPath, uOutSize, &strret, pidl);

	IShellFolder_Release(desktop);
    }

    return hr;
}

Duane Clark's avatar
Duane Clark committed
308
/*************************************************************************
309
 *	SHELL_ExecuteW [Internal]
Duane Clark's avatar
Duane Clark committed
310 311
 *
 */
Kevin Koltzau's avatar
Kevin Koltzau committed
312
static UINT_PTR SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
313
			    const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
Duane Clark's avatar
Duane Clark committed
314
{
315
    STARTUPINFOW  startup;
Duane Clark's avatar
Duane Clark committed
316
    PROCESS_INFORMATION info;
317
    UINT_PTR retval = SE_ERR_NOASSOC;
318 319
    UINT gcdret = 0;
    WCHAR curdir[MAX_PATH];
320
    DWORD dwCreationFlags;
321
    const WCHAR *lpDirectory = NULL;
Duane Clark's avatar
Duane Clark committed
322

323
    TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
324 325 326 327 328 329 330 331 332 333

    /* make sure we don't fail the CreateProcess if the calling app passes in
     * a bad working directory */
    if (psei->lpDirectory && psei->lpDirectory[0])
    {
        DWORD attr = GetFileAttributesW(psei->lpDirectory);
        if (attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_DIRECTORY)
            lpDirectory = psei->lpDirectory;
    }

334 335
    /* ShellExecute specifies the command from psei->lpDirectory
     * if present. Not from the current dir as CreateProcess does */
336
    if( lpDirectory )
337
        if( ( gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
338 339
            if( !SetCurrentDirectoryW( lpDirectory))
                ERR("cannot set directory %s\n", debugstr_w(lpDirectory));
340 341
    ZeroMemory(&startup,sizeof(STARTUPINFOW));
    startup.cb = sizeof(STARTUPINFOW);
Duane Clark's avatar
Duane Clark committed
342
    startup.dwFlags = STARTF_USESHOWWINDOW;
343
    startup.wShowWindow = psei->nShow;
344
    dwCreationFlags = CREATE_UNICODE_ENVIRONMENT;
345
    if (!(psei->fMask & SEE_MASK_NO_CONSOLE))
346 347
        dwCreationFlags |= CREATE_NEW_CONSOLE;
    if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, dwCreationFlags, env,
348
                       lpDirectory, &startup, &info))
Duane Clark's avatar
Duane Clark committed
349
    {
350 351 352
        /* Give 30 seconds to the app to come up, if desired. Probably only needed
           when starting app immediately before making a DDE connection. */
        if (shWait)
353
            if (WaitForInputIdle( info.hProcess, 30000 ) == WAIT_FAILED)
354
                WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
355
        retval = 33;
356 357
        if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
            psei_out->hProcess = info.hProcess;
358 359 360 361
        else
            CloseHandle( info.hProcess );
        CloseHandle( info.hThread );
    }
362
    else if ((retval = GetLastError()) >= 32)
363
    {
364
        TRACE("CreateProcess returned error %ld\n", retval);
365
        retval = ERROR_BAD_FORMAT;
Duane Clark's avatar
Duane Clark committed
366 367
    }

368
    TRACE("returning %lu\n", retval);
369

370
    psei_out->hInstApp = (HINSTANCE)retval;
371
    if( gcdret )
372 373 374
        if( !SetCurrentDirectoryW( curdir))
            ERR("cannot return to directory %s\n", debugstr_w(curdir));

Duane Clark's avatar
Duane Clark committed
375
    return retval;
376 377
}

378 379

/***********************************************************************
380
 *           SHELL_BuildEnvW	[Internal]
381 382 383 384
 *
 * Build the environment for the new process, adding the specified
 * path to the PATH variable. Returned pointer must be freed by caller.
 */
385
static void *SHELL_BuildEnvW( const WCHAR *path )
386
{
387 388 389 390
    static const WCHAR wPath[] = {'P','A','T','H','=',0};
    WCHAR *strings, *new_env;
    WCHAR *p, *p2;
    int total = strlenW(path) + 1;
391 392
    BOOL got_path = FALSE;

393
    if (!(strings = GetEnvironmentStringsW())) return NULL;
394 395 396
    p = strings;
    while (*p)
    {
397 398
        int len = strlenW(p) + 1;
        if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
399 400 401 402 403 404
        total += len;
        p += len;
    }
    if (!got_path) total += 5;  /* we need to create PATH */
    total++;  /* terminating null */

405
    if (!(new_env = heap_alloc( total * sizeof(WCHAR) )))
406
    {
407
        FreeEnvironmentStringsW( strings );
408 409 410 411 412 413
        return NULL;
    }
    p = strings;
    p2 = new_env;
    while (*p)
    {
414 415 416
        int len = strlenW(p) + 1;
        memcpy( p2, p, len * sizeof(WCHAR) );
        if (!strncmpiW( p, wPath, 5 ))
417 418
        {
            p2[len - 1] = ';';
419 420
            strcpyW( p2 + len, path );
            p2 += strlenW(path) + 1;
421 422 423 424 425 426
        }
        p += len;
        p2 += len;
    }
    if (!got_path)
    {
427 428 429
        strcpyW( p2, wPath );
        strcatW( p2, path );
        p2 += strlenW(p2) + 1;
430 431
    }
    *p2 = 0;
432
    FreeEnvironmentStringsW( strings );
433 434 435 436
    return new_env;
}


437
/***********************************************************************
438
 *           SHELL_TryAppPathW	[Internal]
439 440 441 442 443 444
 *
 * Helper function for SHELL_FindExecutable
 * @param lpResult - pointer to a buffer of size MAX_PATH
 * On entry: szName is a filename (probably without path separators).
 * On exit: if szName found in "App Path", place full path in lpResult, and return true
 */
445
static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
446
{
447 448 449
    static const WCHAR wszKeyAppPaths[] = {'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','\\','A','p','p',' ','P','a','t','h','s','\\',0};
    static const WCHAR wPath[] = {'P','a','t','h',0};
450
    HKEY hkApp = 0;
451
    WCHAR buffer[1024];
452
    LONG len;
453
    LONG res;
454 455
    BOOL found = FALSE;

456
    if (env) *env = NULL;
457 458 459
    strcpyW(buffer, wszKeyAppPaths);
    strcatW(buffer, szName);
    res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
460
    if (res) goto end;
461

462
    len = MAX_PATH*sizeof(WCHAR);
463
    res = RegQueryValueW(hkApp, NULL, lpResult, &len);
464
    if (res) goto end;
465 466
    found = TRUE;

467 468 469
    if (env)
    {
        DWORD count = sizeof(buffer);
470 471
        if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
            *env = SHELL_BuildEnvW( buffer );
472 473
    }

474 475 476 477 478
end:
    if (hkApp) RegCloseKey(hkApp);
    return found;
}

479
/*************************************************************************
480
 *	SHELL_FindExecutableByVerb [Internal]
481 482 483
 *
 * called from SHELL_FindExecutable or SHELL_execute_class
 * in/out:
484
 *      classname a buffer, big enough, to get the key name to do actually the
485 486 487
 *              command   "WordPad.Document.1\\shell\\open\\command"
 *              passed as "WordPad.Document.1"
 * in:
488
 *      lpVerb the operation on it (open)
489 490 491 492 493 494 495 496
 *      commandlen the size of command buffer (in bytes)
 * out:
 *      command a buffer, to store the command to do the
 *              operation on the file
 *      key a buffer, big enough, to get the key name to do actually the
 *              command "WordPad.Document.1\\shell\\open\\command"
 *              Can be NULL
 */
497
static UINT SHELL_FindExecutableByVerb(LPCWSTR lpVerb, LPWSTR key, LPWSTR classname, LPWSTR command, LONG commandlen)
498 499
{
    static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
500 501 502
    HKEY hkeyClass;
    WCHAR verb[MAX_PATH];

503
    if (RegOpenKeyExW(HKEY_CLASSES_ROOT, classname, 0, 0x02000000, &hkeyClass))
504
        return SE_ERR_NOASSOC;
505
    if (!HCR_GetDefaultVerbW(hkeyClass, lpVerb, verb, ARRAY_SIZE(verb)))
506
        return SE_ERR_NOASSOC;
507
    RegCloseKey(hkeyClass);
508 509

    /* Looking for ...buffer\shell\<verb>\command */
510 511 512
    strcatW(classname, wszShell);
    strcatW(classname, verb);
    strcatW(classname, wCommand);
513

514
    if (RegQueryValueW(HKEY_CLASSES_ROOT, classname, command,
515 516 517
                       &commandlen) == ERROR_SUCCESS)
    {
	commandlen /= sizeof(WCHAR);
518
        if (key) strcpyW(key, classname);
519 520 521 522 523 524 525 526 527 528 529 530 531
#if 0
        LPWSTR tmp;
        WCHAR param[256];
	LONG paramlen = sizeof(param);
        static const WCHAR wSpace[] = {' ',0};

        /* FIXME: it seems all Windows version don't behave the same here.
         * the doc states that this ddeexec information can be found after
         * the exec names.
         * on Win98, it doesn't appear, but I think it does on Win2k
         */
	/* Get the parameters needed by the application
	   from the associated ddeexec key */
532
	tmp = strstrW(classname, wCommand);
533
	tmp[0] = '\0';
534 535
	strcatW(classname, wDdeexec);
	if (RegQueryValueW(HKEY_CLASSES_ROOT, classname, param,
536 537 538 539 540 541 542 543 544 545 546 547 548 549
				     &paramlen) == ERROR_SUCCESS)
	{
	    paramlen /= sizeof(WCHAR);
            strcatW(command, wSpace);
            strcatW(command, param);
            commandlen += paramlen;
	}
#endif

	command[commandlen] = '\0';

	return 33; /* FIXME see SHELL_FindExecutable() */
    }

550
    return SE_ERR_NOASSOC;
551 552
}

553 554 555 556
/*************************************************************************
 *	SHELL_FindExecutable [Internal]
 *
 * Utility for code sharing between FindExecutable and ShellExecute
557
 * in:
558
 *      lpFile the name of a file
559
 *      lpVerb the operation on it (open)
560 561 562 563 564 565 566
 * out:
 *      lpResult a buffer, big enough :-(, to store the command to do the
 *              operation on the file
 *      key a buffer, big enough, to get the key name to do actually the
 *              command (it'll be used afterwards for more information
 *              on the operation)
 */
567
static UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpVerb,
568
                                 LPWSTR lpResult, int resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
569
{
570 571 572 573
    static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
    static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
    static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
    WCHAR *extension = NULL; /* pointer to file extension */
574 575
    WCHAR classname[256];     /* registry name for this file type */
    LONG  classnamelen = sizeof(classname); /* length of above */
576
    WCHAR command[1024];     /* command from registry */
577
    WCHAR wBuffer[256];      /* Used to GetProfileString */
578
    UINT  retval = SE_ERR_NOASSOC;
579
    WCHAR *tok;              /* token pointer */
580
    WCHAR xlpFile[256];      /* result of SearchPath */
581
    DWORD attribs;           /* file attributes */
582

583
    TRACE("%s\n", debugstr_w(lpFile));
584

585 586 587
    if (!lpResult)
        return ERROR_INVALID_PARAMETER;

588
    xlpFile[0] = '\0';
589
    lpResult[0] = '\0'; /* Start off with an empty return string */
590
    if (key) *key = '\0';
591

592
    /* trap NULL parameters on entry */
593
    if (!lpFile)
594
    {
595 596
        WARN("(lpFile=%s,lpResult=%s): NULL parameter\n",
             debugstr_w(lpFile), debugstr_w(lpResult));
597
        return ERROR_FILE_NOT_FOUND; /* File not found. Close enough, I guess. */
598
    }
599

600
    if (SHELL_TryAppPathW( lpFile, lpResult, env ))
601
    {
602
        TRACE("found %s via App Paths\n", debugstr_w(lpResult));
603 604 605
        return 33;
    }

606
    if (SearchPathW(lpPath, lpFile, wszExe, ARRAY_SIZE(xlpFile), xlpFile, NULL))
607
    {
608
        TRACE("SearchPathW returned non-zero\n");
609
        lpFile = xlpFile;
610 611
        /* The file was found in the application-supplied default directory (or the system search path) */
    }
612
    else if (lpPath && SearchPathW(NULL, lpFile, wszExe, ARRAY_SIZE(xlpFile), xlpFile, NULL))
613 614 615 616
    {
        TRACE("SearchPathW returned non-zero\n");
        lpFile = xlpFile;
        /* The file was found in one of the directories in the system-wide search path */
617
    }
618

619 620
    attribs = GetFileAttributesW(lpFile);
    if (attribs!=INVALID_FILE_ATTRIBUTES && (attribs&FILE_ATTRIBUTE_DIRECTORY))
621
    {
622
       strcpyW(classname, wszFolder);
623
    }
624
    else
625
    {
626 627 628 629 630 631
        /* Did we get something? Anything? */
        if (xlpFile[0]==0)
        {
            TRACE("Returning SE_ERR_FNF\n");
            return SE_ERR_FNF;
        }
632 633 634 635 636 637 638
        /* First thing we need is the file's extension */
        extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
        /* File->Run in progman uses */
        /* .\FILE.EXE :( */
        TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));

        if (extension == NULL || extension[1]==0)
639
        {
640 641
            WARN("Returning SE_ERR_NOASSOC\n");
            return SE_ERR_NOASSOC;
642
        }
643

644 645
        /* Three places to check: */
        /* 1. win.ini, [windows], programs (NB no leading '.') */
646
        /* 2. Registry, HKEY_CLASS_ROOT\<classname>\shell\open\command */
647 648 649 650 651 652 653 654
        /* 3. win.ini, [extensions], extension (NB no leading '.' */
        /* All I know of the order is that registry is checked before */
        /* extensions; however, it'd make sense to check the programs */
        /* section first, so that's what happens here. */

        /* See if it's a program - if GetProfileString fails, we skip this
         * section. Actually, if GetProfileString fails, we've probably
         * got a lot more to worry about than running a program... */
655
        if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, ARRAY_SIZE(wBuffer)) > 0)
656 657 658 659
        {
            CharLowerW(wBuffer);
            tok = wBuffer;
            while (*tok)
660
            {
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
                WCHAR *p = tok;
                while (*p && *p != ' ' && *p != '\t') p++;
                if (*p)
                {
                    *p++ = 0;
                    while (*p == ' ' || *p == '\t') p++;
                }

                if (strcmpiW(tok, &extension[1]) == 0) /* have to skip the leading "." */
                {
                    strcpyW(lpResult, xlpFile);
                    /* Need to perhaps check that the file has a path
                     * attached */
                    TRACE("found %s\n", debugstr_w(lpResult));
                    return 33;
676
                    /* Greater than 32 to indicate success */
677 678
                }
                tok = p;
679 680
            }
        }
681

682
        /* Check registry */
683 684
        if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, classname,
                           &classnamelen) == ERROR_SUCCESS)
685
        {
686
            classnamelen /= sizeof(WCHAR);
687
            if (classnamelen == ARRAY_SIZE(classname))
688 689 690
		classnamelen--;
            classname[classnamelen] = '\0';
            TRACE("File type: %s\n", debugstr_w(classname));
691
        }
692 693
        else
        {
694
            *classname = '\0';
695
        }
696
    }
697

698
    if (*classname)
699
    {
700 701
        /* pass the verb string to SHELL_FindExecutableByVerb() */
        retval = SHELL_FindExecutableByVerb(lpVerb, key, classname, command, sizeof(command));
702 703

	if (retval > 32)
704
	{
705 706 707 708
	    DWORD finishedLen;
	    SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args, &finishedLen);
	    if (finishedLen > resultLen)
		ERR("Argify buffer not large enough.. truncated\n");
709 710 711 712 713 714 715 716 717 718 719 720

	    /* Remove double quotation marks and command line arguments */
	    if (*lpResult == '"')
	    {
		WCHAR *p = lpResult;
		while (*(p + 1) != '"')
		{
		    *p = *(p + 1);
		    p++;
		}
		*p = '\0';
	    }
721 722
            else
            {
723
                /* Truncate on first space */
724 725 726 727 728
		WCHAR *p = lpResult;
		while (*p != ' ' && *p != '\0')
                    p++;
                *p='\0';
            }
729 730 731 732
	}
    }
    else /* Check win.ini */
    {
733 734
	static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};

735 736
	/* Toss the leading dot */
	extension++;
737
	if (GetProfileStringW(wExtensions, extension, wszEmpty, command, ARRAY_SIZE(command)) > 0)
738
        {
739
            if (*command)
740
            {
741 742
                strcpyW(lpResult, command);
                tok = strchrW(lpResult, '^'); /* should be ^.extension? */
743 744 745
                if (tok != NULL)
                {
                    tok[0] = '\0';
746 747 748
                    strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
                    tok = strchrW(command, '^'); /* see above */
                    if ((tok != NULL) && (strlenW(tok)>5))
749
                    {
750
                        strcatW(lpResult, &tok[5]);
751 752 753 754 755 756
                    }
                }
                retval = 33; /* FIXME - see above */
            }
        }
    }
757

758
    TRACE("returning %s\n", debugstr_w(lpResult));
759 760 761 762 763 764
    return retval;
}

/******************************************************************
 *		dde_cb
 *
765
 * callback for the DDE connection. not really useful
766
 */
767
static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
768 769
                                HSZ hsz1, HSZ hsz2, HDDEDATA hData,
                                ULONG_PTR dwData1, ULONG_PTR dwData2)
770
{
771
    TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
772
           uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
773
    return NULL;
774 775 776 777 778 779 780
}

/******************************************************************
 *		dde_connect
 *
 * ShellExecute helper. Used to do an operation with a DDE connection
 *
781
 * Handles both the direct connection (try #1), and if it fails,
782 783 784
 * launching an application and trying (#2) to connect to it
 *
 */
785
static unsigned dde_connect(const WCHAR* key, const WCHAR* start, WCHAR* ddeexec,
786
                            const WCHAR* lpFile, WCHAR *env,
787
			    LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
788
                            const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
789
{
790 791
    static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
    static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
792 793
    WCHAR       regkey[256];
    WCHAR *     endkey = regkey + strlenW(key);
794 795 796
    WCHAR       app[256], topic[256], ifexec[256], static_res[256];
    WCHAR *     dynamic_res=NULL;
    WCHAR *     res;
797
    LONG        applen, topiclen, ifexeclen;
798
    WCHAR *     exec;
799 800
    DWORD       ddeInst = 0;
    DWORD       tid;
801
    DWORD       resultLen, endkeyLen;
802 803
    HSZ         hszApp, hszTopic;
    HCONV       hConv;
804
    HDDEDATA    hDdeData;
805
    unsigned    ret = SE_ERR_NOASSOC;
806
    BOOL unicode = !(GetVersion() & 0x80000000);
807

808
    if (strlenW(key) + 1 > ARRAY_SIZE(regkey))
809 810 811 812
    {
        FIXME("input parameter %s larger than buffer\n", debugstr_w(key));
        return 2;
    }
813
    strcpyW(regkey, key);
814
    endkeyLen = ARRAY_SIZE(regkey) - (endkey - regkey);
815 816 817 818 819
    if (strlenW(wApplication) + 1 > endkeyLen)
    {
        FIXME("endkey %s overruns buffer\n", debugstr_w(wApplication));
        return 2;
    }
820
    strcpyW(endkey, wApplication);
821
    applen = sizeof(app);
822
    if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, app, &applen) != ERROR_SUCCESS)
823
    {
824 825
        WCHAR command[1024], fullpath[MAX_PATH];
        static const WCHAR wSo[] = { '.','s','o',0 };
826
        int sizeSo = ARRAY_SIZE(wSo);
827 828 829 830 831 832
        LPWSTR ptr = NULL;
        DWORD ret = 0;

        /* Get application command from start string and find filename of application */
        if (*start == '"')
        {
833
            if (strlenW(start + 1) + 1 > ARRAY_SIZE(command))
834 835 836 837 838
            {
                FIXME("size of input parameter %s larger than buffer\n",
                      debugstr_w(start + 1));
                return 2;
            }
839 840 841
            strcpyW(command, start+1);
            if ((ptr = strchrW(command, '"')))
                *ptr = 0;
842
            ret = SearchPathW(NULL, command, wszExe, ARRAY_SIZE(fullpath), fullpath, &ptr);
843 844 845
        }
        else
        {
846 847 848
            LPCWSTR p;
            LPWSTR space;
            for (p=start; (space=strchrW(p, ' ')); p=space+1)
849 850 851 852
            {
                int idx = space-start;
                memcpy(command, start, idx*sizeof(WCHAR));
                command[idx] = '\0';
853
                if ((ret = SearchPathW(NULL, command, wszExe, ARRAY_SIZE(fullpath), fullpath, &ptr)))
854 855 856
                    break;
            }
            if (!ret)
857
                ret = SearchPathW(NULL, start, wszExe, ARRAY_SIZE(fullpath), fullpath, &ptr);
858 859 860 861 862 863 864
        }

        if (!ret)
        {
            ERR("Unable to find application path for command %s\n", debugstr_w(start));
            return ERROR_ACCESS_DENIED;
        }
865
        if (strlenW(ptr) + 1 > ARRAY_SIZE(app))
866 867 868 869
        {
            FIXME("size of found path %s larger than buffer\n", debugstr_w(ptr));
            return 2;
        }
870 871 872 873 874 875 876 877 878 879 880
        strcpyW(app, ptr);

        /* Remove extensions (including .so) */
        ptr = app + strlenW(app) - (sizeSo-1);
        if (strlenW(app) >= sizeSo &&
            !strcmpW(ptr, wSo))
            *ptr = 0;

        ptr = strrchrW(app, '.');
        assert(ptr);
        *ptr = 0;
881
    }
882

883 884 885 886 887
    if (strlenW(wTopic) + 1 > endkeyLen)
    {
        FIXME("endkey %s overruns buffer\n", debugstr_w(wTopic));
        return 2;
    }
888
    strcpyW(endkey, wTopic);
889
    topiclen = sizeof(topic);
890
    if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, topic, &topiclen) != ERROR_SUCCESS)
891
    {
892 893
        static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
        strcpyW(topic, wSystem);
894
    }
895

896
    if (unicode)
897
    {
898 899 900 901 902 903 904
        if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
            return 2;
    }
    else
    {
        if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
            return 2;
905
    }
906

907 908
    hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
    hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
909

910 911 912 913
    hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
    exec = ddeexec;
    if (!hConv)
    {
914
        static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
915
        TRACE("Launching %s\n", debugstr_w(start));
916
        ret = execfunc(start, env, TRUE, psei, psei_out);
917
        if (ret <= 32)
918 919 920 921 922 923 924
        {
            TRACE("Couldn't launch\n");
            goto error;
        }
        hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
        if (!hConv)
        {
925
            TRACE("Couldn't connect. ret=%d\n", ret);
926 927 928
            DdeUninitialize(ddeInst);
            SetLastError(ERROR_DDE_FAIL);
            return 30; /* whatever */
929
        }
930 931 932 933 934
        if (strlenW(wIfexec) + 1 > endkeyLen)
        {
            FIXME("endkey %s overruns buffer\n", debugstr_w(wIfexec));
            return 2;
        }
935
        strcpyW(endkey, wIfexec);
936
        ifexeclen = sizeof(ifexec);
937
        if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, ifexec, &ifexeclen) == ERROR_SUCCESS)
938 939 940 941
        {
            exec = ifexec;
        }
    }
942

943 944
    SHELL_ArgifyW(static_res, ARRAY_SIZE(static_res), exec, lpFile, pidl, szCommandline, &resultLen);
    if (resultLen > ARRAY_SIZE(static_res))
945
    {
946
        res = dynamic_res = heap_alloc(resultLen * sizeof(WCHAR));
947 948 949 950
        SHELL_ArgifyW(dynamic_res, resultLen, exec, lpFile, pidl, szCommandline, NULL);
    }
    else
        res = static_res;
951
    TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
952

953 954 955
    /* It's documented in the KB 330337 that IE has a bug and returns
     * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
     */
956 957
    if (unicode)
        hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
958
                                         XTYP_EXECUTE, 30000, &tid);
959 960 961
    else
    {
        DWORD lenA = WideCharToMultiByte(CP_ACP, 0, res, -1, NULL, 0, NULL, NULL);
962
        char *resA = heap_alloc(lenA);
963 964 965
        WideCharToMultiByte(CP_ACP, 0, res, -1, resA, lenA, NULL, NULL);
        hDdeData = DdeClientTransaction( (LPBYTE)resA, lenA, hConv, 0L, 0,
                                         XTYP_EXECUTE, 10000, &tid );
966
        heap_free(resA);
967
    }
968 969 970 971 972 973
    if (hDdeData)
        DdeFreeDataHandle(hDdeData);
    else
        WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
    ret = 33;

974
    heap_free(dynamic_res);
975

976
    DdeDisconnect(hConv);
977

978 979
 error:
    DdeUninitialize(ddeInst);
980

981 982 983
    return ret;
}

Duane Clark's avatar
Duane Clark committed
984 985 986
/*************************************************************************
 *	execute_from_key [Internal]
 */
987
static UINT_PTR execute_from_key(LPCWSTR key, LPCWSTR lpFile, WCHAR *env, LPCWSTR szCommandline,
988
                             LPCWSTR executable_name,
989
			     SHELL_ExecuteW32 execfunc,
990
                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
991
{
992 993 994 995
    static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
    static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
    WCHAR cmd[256], param[1024], ddeexec[256];
    LONG cmdlen = sizeof(cmd), ddeexeclen = sizeof(ddeexec);
996
    UINT_PTR retval = SE_ERR_NOASSOC;
997 998
    DWORD resultLen;
    LPWSTR tmp;
999

1000 1001 1002
    TRACE("%s %s %s %s %s\n", debugstr_w(key), debugstr_w(lpFile), debugstr_w(env),
           debugstr_w(szCommandline), debugstr_w(executable_name));

1003
    cmd[0] = '\0';
1004
    param[0] = '\0';
1005

1006
    /* Get the application from the registry */
1007
    if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
1008 1009 1010 1011 1012
    {
        TRACE("got cmd: %s\n", debugstr_w(cmd));

        /* Is there a replace() function anywhere? */
        cmdlen /= sizeof(WCHAR);
1013 1014
        if (cmdlen >= ARRAY_SIZE(cmd))
            cmdlen = ARRAY_SIZE(cmd) - 1;
1015
        cmd[cmdlen] = '\0';
1016 1017
        SHELL_ArgifyW(param, ARRAY_SIZE(param), cmd, lpFile, psei->lpIDList, szCommandline, &resultLen);
        if (resultLen > ARRAY_SIZE(param))
1018
            ERR("Argify buffer not large enough, truncating\n");
1019
    }
1020

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    /* Get the parameters needed by the application
       from the associated ddeexec key */
    tmp = strstrW(key, wCommand);
    assert(tmp);
    strcpyW(tmp, wDdeexec);

    if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ddeexec, &ddeexeclen) == ERROR_SUCCESS)
    {
        TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(ddeexec));
        if (!param[0]) strcpyW(param, executable_name);
        retval = dde_connect(key, param, ddeexec, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
    }
    else if (param[0])
    {
1035
        TRACE("executing: %s\n", debugstr_w(param));
1036 1037 1038
        retval = execfunc(param, env, FALSE, psei, psei_out);
    }
    else
1039
        WARN("Nothing appropriate found for %s\n", debugstr_w(key));
1040 1041 1042 1043 1044 1045 1046 1047

    return retval;
}

/*************************************************************************
 * FindExecutableA			[SHELL32.@]
 */
HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
{
    HINSTANCE retval;
    WCHAR *wFile = NULL, *wDirectory = NULL;
    WCHAR wResult[MAX_PATH];

    if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
    if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);

    retval = FindExecutableW(wFile, wDirectory, wResult);
    WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
1058 1059
    SHFree( wFile );
    SHFree( wDirectory );
1060 1061

    TRACE("returning %s\n", lpResult);
Kevin Koltzau's avatar
Kevin Koltzau committed
1062
    return retval;
1063 1064 1065 1066
}

/*************************************************************************
 * FindExecutableW			[SHELL32.@]
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
 *
 * This function returns the executable associated with the specified file
 * for the default verb.
 *
 * PARAMS
 *  lpFile   [I] The file to find the association for. This must refer to
 *               an existing file otherwise FindExecutable fails and returns
 *               SE_ERR_FNF.
 *  lpResult [O] Points to a buffer into which the executable path is
 *               copied. This parameter must not be NULL otherwise
 *               FindExecutable() segfaults. The buffer must be of size at
 *               least MAX_PATH characters.
 *
 * RETURNS
 *  A value greater than 32 on success, less than or equal to 32 otherwise.
 *  See the SE_ERR_* constants.
 *
 * NOTES
 *  On Windows XP and 2003, FindExecutable() seems to first convert the
 *  filename into 8.3 format, thus taking into account only the first three
 *  characters of the extension, and expects to find an association for those.
 *  However other Windows versions behave sanely.
1089 1090
 */
HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
1091
{
1092
    UINT_PTR retval = SE_ERR_NOASSOC;
1093
    WCHAR old_dir[1024];
1094
    WCHAR res[MAX_PATH];
1095

1096
    TRACE("File %s, Dir %s\n", debugstr_w(lpFile), debugstr_w(lpDirectory));
1097 1098

    lpResult[0] = '\0'; /* Start off with an empty return string */
1099 1100
    if (lpFile == NULL)
	return (HINSTANCE)SE_ERR_FNF;
1101 1102 1103

    if (lpDirectory)
    {
1104
        GetCurrentDirectoryW(ARRAY_SIZE(old_dir), old_dir);
1105
        SetCurrentDirectoryW(lpDirectory);
1106
    }
1107

1108 1109 1110 1111
    retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, res, MAX_PATH, NULL, NULL, NULL, NULL);

    if (retval > 32)
        strcpyW(lpResult, res);
1112

1113
    TRACE("returning %s\n", debugstr_w(lpResult));
1114
    if (lpDirectory)
1115
        SetCurrentDirectoryW(old_dir);
1116
    return (HINSTANCE)retval;
1117 1118
}

1119
/* FIXME: is this already implemented somewhere else? */
1120
static HKEY ShellExecute_GetClassKey( const SHELLEXECUTEINFOW *sei )
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
{
    LPCWSTR ext = NULL, lpClass = NULL;
    LPWSTR cls = NULL;
    DWORD type = 0, sz = 0;
    HKEY hkey = 0;
    LONG r;

    if (sei->fMask & SEE_MASK_CLASSALL)
        return sei->hkeyClass;
 
    if (sei->fMask & SEE_MASK_CLASSNAME)
        lpClass = sei->lpClass;
    else
    {
        ext = PathFindExtensionW( sei->lpFile );
        TRACE("ext = %s\n", debugstr_w( ext ) );
        if (!ext)
            return hkey;

        r = RegOpenKeyW( HKEY_CLASSES_ROOT, ext, &hkey );
        if (r != ERROR_SUCCESS )
            return hkey;

        r = RegQueryValueExW( hkey, NULL, 0, &type, NULL, &sz );
        if ( r == ERROR_SUCCESS && type == REG_SZ )
        {
            sz += sizeof (WCHAR);
1148
            cls = heap_alloc( sz );
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
            cls[0] = 0;
            RegQueryValueExW( hkey, NULL, 0, &type, (LPBYTE) cls, &sz );
        }

        RegCloseKey( hkey );
        lpClass = cls;
    }

    TRACE("class = %s\n", debugstr_w(lpClass) );

    hkey = 0;
    if ( lpClass )
        RegOpenKeyW( HKEY_CLASSES_ROOT, lpClass, &hkey );

1163
    heap_free( cls );
1164 1165 1166 1167

    return hkey;
}

1168
static HRESULT shellex_get_dataobj( LPSHELLEXECUTEINFOW sei, IDataObject **dataobj )
1169 1170 1171 1172
{
    LPCITEMIDLIST pidllast = NULL;
    IShellFolder *shf = NULL;
    LPITEMIDLIST pidl = NULL;
1173
    HRESULT r = SE_ERR_DLLNOTFOUND;
1174 1175 1176 1177 1178 1179

    if (sei->fMask & SEE_MASK_CLASSALL)
        pidl = sei->lpIDList;
    else
    {
        WCHAR fullpath[MAX_PATH];
1180
        BOOL ret;
1181 1182

        fullpath[0] = 0;
1183 1184
        ret = GetFullPathNameW( sei->lpFile, MAX_PATH, fullpath, NULL );
        if (!ret)
1185 1186 1187 1188 1189 1190 1191 1192 1193
            goto end;

        pidl = ILCreateFromPathW( fullpath );
    }

    r = SHBindToParent( pidl, &IID_IShellFolder, (LPVOID*)&shf, &pidllast );
    if ( FAILED( r ) )
        goto end;

1194 1195
    r = IShellFolder_GetUIObjectOf( shf, NULL, 1, &pidllast,
                                &IID_IDataObject, NULL, (void**)dataobj );
1196 1197 1198 1199 1200 1201

end:
    if ( pidl != sei->lpIDList )
        ILFree( pidl );
    if ( shf )
        IShellFolder_Release( shf );
1202
    return r;
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
}

static HRESULT shellex_run_context_menu_default( IShellExtInit *obj,
                                                 LPSHELLEXECUTEINFOW sei )
{
    IContextMenu *cm = NULL;
    CMINVOKECOMMANDINFOEX ici;
    MENUITEMINFOW info;
    WCHAR string[0x80];
    INT i, n, def = -1;
    HMENU hmenu = 0;
    HRESULT r;

    TRACE("%p %p\n", obj, sei );

    r = IShellExtInit_QueryInterface( obj, &IID_IContextMenu, (LPVOID*) &cm );
    if ( FAILED( r ) )
        return r;

    hmenu = CreateMenu();
    if ( !hmenu )
        goto end;

    /* the number of the last menu added is returned in r */
    r = IContextMenu_QueryContextMenu( cm, hmenu, 0, 0x20, 0x7fff, CMF_DEFAULTONLY );
    if ( FAILED( r ) )
        goto end;

    n = GetMenuItemCount( hmenu );
    for ( i = 0; i < n; i++ )
    {
        memset( &info, 0, sizeof info );
        info.cbSize = sizeof info;
        info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_STATE | MIIM_DATA | MIIM_ID;
        info.dwTypeData = string;
1238
        info.cch = ARRAY_SIZE(string);
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        string[0] = 0;
        GetMenuItemInfoW( hmenu, i, TRUE, &info );

        TRACE("menu %d %s %08x %08lx %08x %08x\n", i, debugstr_w(string),
            info.fState, info.dwItemData, info.fType, info.wID );
        if ( ( !sei->lpVerb && (info.fState & MFS_DEFAULT) ) ||
             ( sei->lpVerb && !lstrcmpiW( sei->lpVerb, string ) ) )
        {
            def = i;
            break;
        }
    }

    r = E_FAIL;
    if ( def == -1 )
        goto end;

    memset( &ici, 0, sizeof ici );
    ici.cbSize = sizeof ici;
1258
    ici.fMask = CMIC_MASK_UNICODE | (sei->fMask & (SEE_MASK_NO_CONSOLE|SEE_MASK_NOASYNC|SEE_MASK_ASYNCOK|SEE_MASK_FLAG_NO_UI));
1259 1260 1261 1262 1263 1264 1265
    ici.nShow = sei->nShow;
    ici.lpVerb = MAKEINTRESOURCEA( def );
    ici.hwnd = sei->hwnd;
    ici.lpParametersW = sei->lpParameters;
    
    r = IContextMenu_InvokeCommand( cm, (LPCMINVOKECOMMANDINFO) &ici );

1266
    TRACE("invoke command returned %08x\n", r );
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

end:
    if ( hmenu )
        DestroyMenu( hmenu );
    if ( cm )
        IContextMenu_Release( cm );
    return r;
}

static HRESULT shellex_load_object_and_run( HKEY hkey, LPCGUID guid, LPSHELLEXECUTEINFOW sei )
{
    IDataObject *dataobj = NULL;
    IObjectWithSite *ows = NULL;
    IShellExtInit *obj = NULL;
    HRESULT r;

    TRACE("%p %s %p\n", hkey, debugstr_guid( guid ), sei );

    r = CoInitialize( NULL );
    if ( FAILED( r ) )
        goto end;

    r = CoCreateInstance( guid, NULL, CLSCTX_INPROC_SERVER,
                           &IID_IShellExtInit, (LPVOID*)&obj );
    if ( FAILED( r ) )
    {
1293
        ERR("failed %08x\n", r );
1294 1295 1296
        goto end;
    }

1297 1298
    r = shellex_get_dataobj( sei, &dataobj );
    if ( FAILED( r ) )
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    {
        ERR("failed to get data object\n");
        goto end;
    }

    r = IShellExtInit_Initialize( obj, NULL, dataobj, hkey );
    if ( FAILED( r ) )
        goto end;

    r = IShellExtInit_QueryInterface( obj, &IID_IObjectWithSite, (LPVOID*) &ows );
    if ( FAILED( r ) )
        goto end;

    IObjectWithSite_SetSite( ows, NULL );

    r = shellex_run_context_menu_default( obj, sei );

end:
    if ( ows )
        IObjectWithSite_Release( ows );
    if ( dataobj )
        IDataObject_Release( dataobj );
    if ( obj )
        IShellExtInit_Release( obj );
    CoUninitialize();
    return r;
}


/*************************************************************************
 *	ShellExecute_FromContextMenu [Internal]
 */
static LONG ShellExecute_FromContextMenu( LPSHELLEXECUTEINFOW sei )
{
    static const WCHAR szcm[] = { 's','h','e','l','l','e','x','\\',
        'C','o','n','t','e','x','t','M','e','n','u','H','a','n','d','l','e','r','s',0 };
    HKEY hkey, hkeycm = 0;
    WCHAR szguid[39];
    HRESULT hr;
    GUID guid;
    DWORD i;
    LONG r;

    TRACE("%s\n", debugstr_w(sei->lpFile) );

    hkey = ShellExecute_GetClassKey( sei );
    if ( !hkey )
        return ERROR_FUNCTION_FAILED;

    r = RegOpenKeyW( hkey, szcm, &hkeycm );
    if ( r == ERROR_SUCCESS )
    {
        i = 0;
        while ( 1 )
        {
1354
            r = RegEnumKeyW( hkeycm, i++, szguid, ARRAY_SIZE(szguid));
1355 1356
            if ( r != ERROR_SUCCESS )
                break;
1357

1358
            hr = CLSIDFromString( szguid, &guid );
1359 1360 1361 1362 1363 1364 1365
            if (SUCCEEDED(hr))
            {
                /* stop at the first one that succeeds in running */
                hr = shellex_load_object_and_run( hkey, &guid, sei );
                if ( SUCCEEDED( hr ) )
                    break;
            }
1366 1367 1368 1369 1370 1371 1372 1373 1374
        }
        RegCloseKey( hkeycm );
    }

    if ( hkey != sei->hkeyClass )
        RegCloseKey( hkey );
    return r;
}

1375 1376
static UINT_PTR SHELL_quote_and_execute( LPCWSTR wcmd, LPCWSTR wszParameters, LPCWSTR lpstrProtocol, LPCWSTR wszApplicationName, LPWSTR env, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc );

1377 1378
static UINT_PTR SHELL_execute_class( LPCWSTR wszApplicationName, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
{
1379
    static const WCHAR wQuote[] = {'"',0};
1380
    static const WCHAR wSpace[] = {' ',0};
1381
    WCHAR execCmd[1024], classname[1024];
1382 1383 1384 1385 1386 1387
    /* launch a document by fileclass like 'WordPad.Document.1' */
    /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
    /* FIXME: wcmd should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
    ULONG cmask=(psei->fMask & SEE_MASK_CLASSALL);
    DWORD resultLen;
    BOOL done;
1388
    UINT_PTR rslt;
1389

1390 1391 1392 1393
  /* FIXME: remove following block when SHELL_quote_and_execute supports hkeyClass parameter */
  if (cmask != SEE_MASK_CLASSNAME)
  {
    WCHAR wcmd[1024];
1394 1395 1396 1397 1398 1399 1400 1401 1402
    HCR_GetExecuteCommandW((cmask == SEE_MASK_CLASSKEY) ? psei->hkeyClass : NULL,
                           (cmask == SEE_MASK_CLASSNAME) ? psei->lpClass: NULL,
                           psei->lpVerb,
                           execCmd, sizeof(execCmd));

    /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
    TRACE("SEE_MASK_CLASSNAME->%s, doc->%s\n", debugstr_w(execCmd), debugstr_w(wszApplicationName));

    wcmd[0] = '\0';
1403
    done = SHELL_ArgifyW(wcmd, ARRAY_SIZE(wcmd), execCmd, wszApplicationName, psei->lpIDList, NULL, &resultLen);
1404 1405 1406
    if (!done && wszApplicationName[0])
    {
        strcatW(wcmd, wSpace);
1407 1408 1409 1410 1411 1412 1413 1414
        if (*wszApplicationName != '"')
        {
            strcatW(wcmd, wQuote);
            strcatW(wcmd, wszApplicationName);
            strcatW(wcmd, wQuote);
        }
        else
            strcatW(wcmd, wszApplicationName);
1415
    }
1416
    if (resultLen > ARRAY_SIZE(wcmd))
1417 1418
        ERR("Argify buffer not large enough... truncating\n");
    return execfunc(wcmd, NULL, FALSE, psei, psei_out);
1419 1420
  }

1421 1422
    strcpyW(classname, psei->lpClass);
    rslt = SHELL_FindExecutableByVerb(psei->lpVerb, NULL, classname, execCmd, sizeof(execCmd));
1423

1424
    TRACE("SHELL_FindExecutableByVerb returned %u (%s, %s)\n", (unsigned int)rslt, debugstr_w(classname), debugstr_w(execCmd));
1425 1426
    if (33 > rslt)
        return rslt;
1427
    rslt = SHELL_quote_and_execute( execCmd, wszEmpty, classname,
1428 1429 1430
                                      wszApplicationName, NULL, psei,
                                      psei_out, execfunc );
    return rslt;
1431 1432
}

1433
static void SHELL_translate_idlist( LPSHELLEXECUTEINFOW sei, LPWSTR wszParameters, DWORD parametersLen, LPWSTR wszApplicationName, DWORD dwApplicationNameLen )
1434 1435 1436 1437 1438
{
    static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r','.','e','x','e',0};
    WCHAR buffer[MAX_PATH];

    /* last chance to translate IDList: now also allow CLSID paths */
1439
    if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW(sei->lpIDList, buffer, ARRAY_SIZE(buffer)))) {
1440 1441
        if (buffer[0]==':' && buffer[1]==':') {
            /* open shell folder for the specified class GUID */
1442
            if (strlenW(buffer) + 1 > parametersLen)
1443 1444 1445
                ERR("parameters len exceeds buffer size (%i > %i), truncating\n",
                    lstrlenW(buffer) + 1, parametersLen);
            lstrcpynW(wszParameters, buffer, parametersLen);
1446
            if (strlenW(wExplorer) > dwApplicationNameLen)
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
                ERR("application len exceeds buffer size (%i > %i), truncating\n",
                    lstrlenW(wExplorer) + 1, dwApplicationNameLen);
            lstrcpynW(wszApplicationName, wExplorer, dwApplicationNameLen);

            sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
        } else {
            WCHAR target[MAX_PATH];
            DWORD attribs;
            DWORD resultLen;
            /* Check if we're executing a directory and if so use the
               handler for the Folder class */
            strcpyW(target, buffer);
            attribs = GetFileAttributesW(buffer);
            if (attribs != INVALID_FILE_ATTRIBUTES &&
                (attribs & FILE_ATTRIBUTE_DIRECTORY) &&
                HCR_GetExecuteCommandW(0, wszFolder,
                                       sei->lpVerb,
                                       buffer, sizeof(buffer))) {
                SHELL_ArgifyW(wszApplicationName, dwApplicationNameLen,
                              buffer, target, sei->lpIDList, NULL, &resultLen);
                if (resultLen > dwApplicationNameLen)
                    ERR("Argify buffer not large enough... truncating\n");
            }
            sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
        }
    }
}

1475
static UINT_PTR SHELL_quote_and_execute( LPCWSTR wcmd, LPCWSTR wszParameters, LPCWSTR wszKeyname, LPCWSTR wszApplicationName, LPWSTR env, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1476 1477 1478 1479
{
    static const WCHAR wQuote[] = {'"',0};
    static const WCHAR wSpace[] = {' ',0};
    UINT_PTR retval;
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    DWORD len;
    WCHAR *wszQuotedCmd;

    /* Length of quotes plus length of command plus NULL terminator */
    len = 2 + lstrlenW(wcmd) + 1;
    if (wszParameters[0])
    {
        /* Length of space plus length of parameters */
        len += 1 + lstrlenW(wszParameters);
    }
1490
    wszQuotedCmd = heap_alloc(len * sizeof(WCHAR));
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
    /* Must quote to handle case where cmd contains spaces,
     * else security hole if malicious user creates executable file "C:\\Program"
     */
    strcpyW(wszQuotedCmd, wQuote);
    strcatW(wszQuotedCmd, wcmd);
    strcatW(wszQuotedCmd, wQuote);
    if (wszParameters[0]) {
        strcatW(wszQuotedCmd, wSpace);
        strcatW(wszQuotedCmd, wszParameters);
    }
1501 1502 1503
    TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(psei->lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(wszKeyname));
    if (*wszKeyname)
        retval = execute_from_key(wszKeyname, wszApplicationName, env, psei->lpParameters, wcmd, execfunc, psei, psei_out);
1504 1505
    else
        retval = execfunc(wszQuotedCmd, env, FALSE, psei, psei_out);
1506
    heap_free(wszQuotedCmd);
1507 1508 1509
    return retval;
}

1510
static UINT_PTR SHELL_execute_url( LPCWSTR lpFile, LPCWSTR wcmd, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1511 1512 1513
{
    static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
    static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
1514 1515
    UINT_PTR retval;
    WCHAR *lpstrProtocol;
1516 1517
    LPCWSTR lpstrRes;
    INT iSize;
1518
    DWORD len;
1519 1520 1521 1522 1523 1524 1525 1526

    lpstrRes = strchrW(lpFile, ':');
    if (lpstrRes)
        iSize = lpstrRes - lpFile;
    else
        iSize = strlenW(lpFile);

    TRACE("Got URL: %s\n", debugstr_w(lpFile));
1527
    /* Looking for ...<protocol>\shell\<lpVerb>\command */
1528
    len = iSize + lstrlenW(wShell) + lstrlenW(wCommand) + 1;
1529
    if (psei->lpVerb && *psei->lpVerb)
1530 1531 1532
        len += lstrlenW(psei->lpVerb);
    else
        len += lstrlenW(wszOpen);
1533
    lpstrProtocol = heap_alloc(len * sizeof(WCHAR));
1534 1535 1536
    memcpy(lpstrProtocol, lpFile, iSize*sizeof(WCHAR));
    lpstrProtocol[iSize] = '\0';
    strcatW(lpstrProtocol, wShell);
1537
    strcatW(lpstrProtocol, psei->lpVerb && *psei->lpVerb ? psei->lpVerb: wszOpen);
1538 1539
    strcatW(lpstrProtocol, wCommand);

1540 1541
    retval = execute_from_key(lpstrProtocol, lpFile, NULL, psei->lpParameters,
                              wcmd, execfunc, psei, psei_out);
1542
    heap_free(lpstrProtocol);
1543
    return retval;
1544 1545
}

1546 1547 1548 1549 1550
static void do_error_dialog( UINT_PTR retval, HWND hwnd )
{
    WCHAR msg[2048];
    int error_code=GetLastError();

1551
    if (retval == SE_ERR_NOASSOC)
1552
        LoadStringW(shell32_hInstance, IDS_SHLEXEC_NOASSOC, msg, ARRAY_SIZE(msg));
1553
    else
1554
        FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code, 0, msg, ARRAY_SIZE(msg), NULL);
1555 1556 1557 1558

    MessageBoxW(hwnd, msg, NULL, MB_ICONERROR);
}

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
static WCHAR *expand_environment( const WCHAR *str )
{
    WCHAR *buf;
    DWORD len;

    len = ExpandEnvironmentStringsW(str, NULL, 0);
    if (!len) return NULL;

    buf = heap_alloc(len * sizeof(WCHAR));
    if (!buf) return NULL;

    len = ExpandEnvironmentStringsW(str, buf, len);
    if (!len)
    {
        heap_free(buf);
        return NULL;
    }
    return buf;
}

1579
/*************************************************************************
1580
 *	SHELL_execute [Internal]
1581
 */
1582
static BOOL SHELL_execute( LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc )
1583
{
1584 1585
    static const WCHAR wWww[] = {'w','w','w',0};
    static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
1586 1587
    static const DWORD unsupportedFlags =
        SEE_MASK_INVOKEIDLIST  | SEE_MASK_ICON         | SEE_MASK_HOTKEY |
1588
        SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT |
1589
        SEE_MASK_UNICODE       | SEE_MASK_ASYNCOK      | SEE_MASK_HMONITOR;
1590

1591
    WCHAR parametersBuffer[1024], dirBuffer[MAX_PATH], wcmdBuffer[1024];
1592
    WCHAR *wszApplicationName, *wszParameters, *wszDir, *wcmd = NULL;
1593
    DWORD dwApplicationNameLen = MAX_PATH+2;
1594 1595
    DWORD parametersLen = ARRAY_SIZE(parametersBuffer);
    DWORD wcmdLen = ARRAY_SIZE(wcmdBuffer);
1596
    DWORD len;
1597
    SHELLEXECUTEINFOW sei_tmp;	/* modifiable copy of SHELLEXECUTEINFO struct */
1598
    WCHAR *env;
1599
    WCHAR wszKeyname[256];
1600
    LPCWSTR lpFile;
1601
    UINT_PTR retval = SE_ERR_NOASSOC;
1602

1603
    /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
1604
    sei_tmp = *sei;
1605

1606
    TRACE("mask=0x%08x hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
1607 1608 1609
            sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
            debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
            debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
1610 1611
            ((sei_tmp.fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME) ?
                debugstr_w(sei_tmp.lpClass) : "not used");
1612

1613
    sei->hProcess = NULL;
1614

1615
    /* make copies of all path/command strings */
1616
    if (!sei_tmp.lpFile)
1617
    {
1618
        wszApplicationName = heap_alloc(dwApplicationNameLen*sizeof(WCHAR));
1619
        *wszApplicationName = '\0';
1620
    }
1621
    else if (*sei_tmp.lpFile == '\"' && sei_tmp.lpFile[(len = strlenW(sei_tmp.lpFile))-1] == '\"')
1622
    {
1623
        if(len-1 >= dwApplicationNameLen) dwApplicationNameLen = len;
1624
        wszApplicationName = heap_alloc(dwApplicationNameLen*sizeof(WCHAR));
1625 1626 1627
        memcpy(wszApplicationName, sei_tmp.lpFile+1, len*sizeof(WCHAR));
        if(len > 2)
            wszApplicationName[len-2] = '\0';
1628
        TRACE("wszApplicationName=%s\n",debugstr_w(wszApplicationName));
1629 1630 1631
    } else {
        DWORD l = strlenW(sei_tmp.lpFile)+1;
        if(l > dwApplicationNameLen) dwApplicationNameLen = l+1;
1632
        wszApplicationName = heap_alloc(dwApplicationNameLen*sizeof(WCHAR));
1633
        memcpy(wszApplicationName, sei_tmp.lpFile, l*sizeof(WCHAR));
1634
    }
1635

1636
    wszParameters = parametersBuffer;
1637
    if (sei_tmp.lpParameters)
1638 1639 1640 1641
    {
        len = lstrlenW(sei_tmp.lpParameters) + 1;
        if (len > parametersLen)
        {
1642
            wszParameters = heap_alloc(len * sizeof(WCHAR));
1643 1644
            parametersLen = len;
        }
1645
	strcpyW(wszParameters, sei_tmp.lpParameters);
1646
    }
1647
    else
1648
	*wszParameters = '\0';
1649

1650
    wszDir = dirBuffer;
1651
    if (sei_tmp.lpDirectory)
1652 1653
    {
        len = lstrlenW(sei_tmp.lpDirectory) + 1;
1654
        if (len > ARRAY_SIZE(dirBuffer))
1655
            wszDir = heap_alloc(len * sizeof(WCHAR));
1656
	strcpyW(wszDir, sei_tmp.lpDirectory);
1657
    }
1658 1659 1660 1661 1662
    else
	*wszDir = '\0';

    /* adjust string pointers to point to the new buffers */
    sei_tmp.lpFile = wszApplicationName;
1663
    sei_tmp.lpParameters = wszParameters;
1664 1665
    sei_tmp.lpDirectory = wszDir;

1666
    if (sei_tmp.fMask & unsupportedFlags)
1667
    {
1668
        FIXME("flags ignored: 0x%08x\n", sei_tmp.fMask & unsupportedFlags);
1669 1670 1671
    }

    /* process the IDList */
1672
    if (sei_tmp.fMask & SEE_MASK_IDLIST)
1673
    {
1674 1675 1676 1677 1678 1679
	IShellExecuteHookW* pSEH;

	HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);

	if (SUCCEEDED(hr))
	{
1680
	    hr = IShellExecuteHookW_Execute(pSEH, &sei_tmp);
1681 1682 1683

	    IShellExecuteHookW_Release(pSEH);

1684
	    if (hr == S_OK) {
1685
                heap_free(wszApplicationName);
1686
                if (wszParameters != parametersBuffer)
1687
                    heap_free(wszParameters);
1688
                if (wszDir != dirBuffer)
1689
                    heap_free(wszDir);
1690
		return TRUE;
1691
            }
1692 1693
	}

1694
        SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName);
1695
        TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1696 1697
    }

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    if (sei_tmp.fMask & SEE_MASK_DOENVSUBST)
    {
        WCHAR *tmp;

        tmp = expand_environment(sei_tmp.lpFile);
        if (!tmp)
        {
            retval = SE_ERR_OOM;
            goto end;
        }
        heap_free(wszApplicationName);
        sei_tmp.lpFile = wszApplicationName = tmp;

        tmp = expand_environment(sei_tmp.lpDirectory);
        if (!tmp)
        {
            retval = SE_ERR_OOM;
            goto end;
        }
        if (wszDir != dirBuffer)
            heap_free(wszDir);
        sei_tmp.lpDirectory = wszDir = tmp;
    }

1722 1723 1724
    if ( ERROR_SUCCESS == ShellExecute_FromContextMenu( &sei_tmp ) )
    {
        sei->hInstApp = (HINSTANCE) 33;
1725
        heap_free(wszApplicationName);
1726
        if (wszParameters != parametersBuffer)
1727
            heap_free(wszParameters);
1728
        if (wszDir != dirBuffer)
1729
            heap_free(wszDir);
1730 1731 1732
        return TRUE;
    }

1733
    if (sei_tmp.fMask & SEE_MASK_CLASSALL)
1734
    {
1735 1736
        retval = SHELL_execute_class( wszApplicationName, &sei_tmp, sei,
                                      execfunc );
1737 1738
        if (retval <= 32 && !(sei_tmp.fMask & SEE_MASK_FLAG_NO_UI))
            do_error_dialog(retval, sei_tmp.hwnd);
1739
        heap_free(wszApplicationName);
1740
        if (wszParameters != parametersBuffer)
1741
            heap_free(wszParameters);
1742
        if (wszDir != dirBuffer)
1743
            heap_free(wszDir);
1744
        return retval > 32;
1745 1746
    }

1747 1748 1749
    /* Has the IDList not yet been translated? */
    if (sei_tmp.fMask & SEE_MASK_IDLIST)
    {
1750 1751 1752 1753
        SHELL_translate_idlist( &sei_tmp, wszParameters,
                                parametersLen,
                                wszApplicationName,
                                dwApplicationNameLen );
1754 1755
    }

1756 1757
    /* convert file URLs */
    if (UrlIsFileUrlW(sei_tmp.lpFile))
1758 1759
    {
        LPWSTR buf;
1760 1761 1762
        DWORD size;

        size = MAX_PATH;
1763
        buf = heap_alloc(size * sizeof(WCHAR));
1764
        if (!buf || FAILED(PathCreateFromUrlW(sei_tmp.lpFile, buf, &size, 0))) {
1765
            heap_free(buf);
1766
            return SE_ERR_OOM;
1767
        }
1768

1769
        heap_free(wszApplicationName);
1770 1771 1772
        wszApplicationName = buf;
        sei_tmp.lpFile = wszApplicationName;
    }
1773 1774 1775 1776 1777 1778
    else /* or expand environment strings (not both!) */
    {
        len = ExpandEnvironmentStringsW(sei_tmp.lpFile, NULL, 0);
        if (len>0)
        {
            LPWSTR buf;
1779
            buf = heap_alloc((len + 1) * sizeof(WCHAR));
1780 1781

            ExpandEnvironmentStringsW(sei_tmp.lpFile, buf, len + 1);
1782
            heap_free(wszApplicationName);
1783 1784 1785 1786 1787
            wszApplicationName = buf;

            sei_tmp.lpFile = wszApplicationName;
        }
    }
1788 1789

    if (*sei_tmp.lpDirectory)
1790 1791 1792 1793 1794 1795
    {
        len = ExpandEnvironmentStringsW(sei_tmp.lpDirectory, NULL, 0);
        if (len > 0)
        {
            LPWSTR buf;
            len++;
1796
            buf = heap_alloc(len * sizeof(WCHAR));
1797
            ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buf, len);
1798
            if (wszDir != dirBuffer)
1799
                heap_free(wszDir);
1800 1801
            wszDir = buf;
            sei_tmp.lpDirectory = wszDir;
1802 1803
        }
    }
1804

Duane Clark's avatar
Duane Clark committed
1805
    /* Else, try to execute the filename */
1806
    TRACE("execute:%s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1807
    lpFile = sei_tmp.lpFile;
1808
    wcmd = wcmdBuffer;
1809
    len = lstrlenW(wszApplicationName) + 3;
1810 1811 1812 1813
    if (sei_tmp.lpParameters[0])
        len += 1 + lstrlenW(wszParameters);
    if (len > wcmdLen)
    {
1814
        wcmd = heap_alloc(len * sizeof(WCHAR));
1815 1816
        wcmdLen = len;
    }
1817 1818 1819 1820 1821
    wcmd[0] = '\"';
    len = lstrlenW(wszApplicationName);
    memcpy(wcmd+1, wszApplicationName, len * sizeof(WCHAR));
    len++;
    wcmd[len++] = '\"';
1822
    wcmd[len] = 0;
1823
    if (sei_tmp.lpParameters[0]) {
1824 1825
        wcmd[len++] = ' ';
        strcpyW(wcmd+len, wszParameters);
1826 1827
    }

1828
    retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1829
    if (retval > 32) {
1830
        heap_free(wszApplicationName);
1831
        if (wszParameters != parametersBuffer)
1832
            heap_free(wszParameters);
1833
        if (wszDir != dirBuffer)
1834
            heap_free(wszDir);
1835
        if (wcmd != wcmdBuffer)
1836
            heap_free(wcmd);
Duane Clark's avatar
Duane Clark committed
1837
        return TRUE;
1838
    }
1839

Duane Clark's avatar
Duane Clark committed
1840
    /* Else, try to find the executable */
1841
    wcmd[0] = '\0';
1842
    retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, wcmdLen, wszKeyname, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
1843 1844
    if (retval > 32)  /* Found */
    {
1845
        retval = SHELL_quote_and_execute( wcmd, wszParameters, wszKeyname,
1846 1847
                                          wszApplicationName, env, &sei_tmp,
                                          sei, execfunc );
1848
        heap_free( env );
1849
    }
1850 1851 1852 1853 1854
    else if (PathIsDirectoryW(lpFile))
    {
        static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r',0};
        static const WCHAR wQuote[] = {'"',0};
        WCHAR wExec[MAX_PATH];
1855
        WCHAR * lpQuotedFile = heap_alloc( sizeof(WCHAR) * (strlenW(lpFile) + 3) );
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867

        if (lpQuotedFile)
        {
            retval = SHELL_FindExecutable( sei_tmp.lpDirectory, wExplorer,
                                           wszOpen, wExec, MAX_PATH,
                                           NULL, &env, NULL, NULL );
            if (retval > 32)
            {
                strcpyW(lpQuotedFile, wQuote);
                strcatW(lpQuotedFile, lpFile);
                strcatW(lpQuotedFile, wQuote);
                retval = SHELL_quote_and_execute( wExec, lpQuotedFile,
1868
                                                  wszKeyname,
1869 1870
                                                  wszApplicationName, env,
                                                  &sei_tmp, sei, execfunc );
1871
                heap_free( env );
1872
            }
1873
            heap_free( lpQuotedFile );
1874 1875 1876 1877
        }
        else
            retval = 0; /* Out of memory */
    }
1878
    else if (PathIsURLW(lpFile))    /* File not found, check for URL */
1879
    {
1880
        retval = SHELL_execute_url( lpFile, wcmd, &sei_tmp, sei, execfunc );
1881 1882
    }
    /* Check if file specified is in the form www.??????.*** */
1883
    else if (!strncmpiW(lpFile, wWww, 3))
1884
    {
1885
        /* if so, prefix lpFile with http:// and call ShellExecute */
1886 1887 1888
        WCHAR lpstrTmpFile[256];
        strcpyW(lpstrTmpFile, wHttp);
        strcatW(lpstrTmpFile, lpFile);
Kevin Koltzau's avatar
Kevin Koltzau committed
1889
        retval = (UINT_PTR)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1890 1891
    }

1892
end:
1893
    TRACE("retval %lu\n", retval);
1894

1895
    heap_free(wszApplicationName);
1896
    if (wszParameters != parametersBuffer)
1897
        heap_free(wszParameters);
1898
    if (wszDir != dirBuffer)
1899
        heap_free(wszDir);
1900
    if (wcmd != wcmdBuffer)
1901
        heap_free(wcmd);
1902

1903
    sei->hInstApp = (HINSTANCE)(retval > 32 ? 33 : retval);
1904 1905 1906

    if (retval <= 32 && !(sei_tmp.fMask & SEE_MASK_FLAG_NO_UI))
        do_error_dialog(retval, sei_tmp.hwnd);
1907
    return retval > 32;
1908 1909
}

1910 1911 1912
/*************************************************************************
 * ShellExecuteA			[SHELL32.290]
 */
1913 1914
HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpVerb, LPCSTR lpFile,
                               LPCSTR lpParameters, LPCSTR lpDirectory, INT iShowCmd)
1915
{
1916 1917
    SHELLEXECUTEINFOA sei;

1918
    TRACE("%p,%s,%s,%s,%s,%d\n",
1919
          hWnd, debugstr_a(lpVerb), debugstr_a(lpFile),
1920
          debugstr_a(lpParameters), debugstr_a(lpDirectory), iShowCmd);
1921

1922
    sei.cbSize = sizeof(sei);
1923
    sei.fMask = SEE_MASK_FLAG_NO_UI;
1924
    sei.hwnd = hWnd;
1925
    sei.lpVerb = lpVerb;
1926 1927 1928 1929 1930 1931 1932 1933
    sei.lpFile = lpFile;
    sei.lpParameters = lpParameters;
    sei.lpDirectory = lpDirectory;
    sei.nShow = iShowCmd;
    sei.lpIDList = 0;
    sei.lpClass = 0;
    sei.hkeyClass = 0;
    sei.dwHotKey = 0;
1934
    sei.hProcess = 0;
1935

1936
    ShellExecuteExA (&sei);
1937 1938 1939 1940 1941 1942 1943
    return sei.hInstApp;
}

/*************************************************************************
 * ShellExecuteExA				[SHELL32.292]
 *
 */
1944
BOOL WINAPI DECLSPEC_HOTPATCH ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1945
{
1946 1947 1948
    SHELLEXECUTEINFOW seiW;
    BOOL ret;
    WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1949 1950 1951

    TRACE("%p\n", sei);

1952
    memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1953 1954

    if (sei->lpVerb)
1955
	seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1956 1957

    if (sei->lpFile)
1958
        seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1959 1960

    if (sei->lpParameters)
1961
        seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1962 1963

    if (sei->lpDirectory)
1964
        seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1965

1966
    if ((sei->fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME && sei->lpClass)
1967
        seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1968
    else
1969
        seiW.lpClass = NULL;
1970

1971
    ret = SHELL_execute( &seiW, SHELL_ExecuteW );
1972

1973 1974
    sei->hInstApp = seiW.hInstApp;

1975 1976 1977
    if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
        sei->hProcess = seiW.hProcess;

1978 1979 1980 1981 1982
    SHFree(wVerb);
    SHFree(wFile);
    SHFree(wParameters);
    SHFree(wDirectory);
    SHFree(wClass);
1983 1984

    return ret;
1985 1986
}

1987 1988 1989 1990
/*************************************************************************
 * ShellExecuteExW				[SHELL32.293]
 *
 */
1991
BOOL WINAPI DECLSPEC_HOTPATCH ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1992
{
1993
    return SHELL_execute( sei, SHELL_ExecuteW );
1994 1995
}

1996 1997 1998
/*************************************************************************
 * ShellExecuteW			[SHELL32.294]
 * from shellapi.h
1999
 * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpVerb,
2000
 * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
2001
 */
2002
HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpVerb, LPCWSTR lpFile,
2003 2004
                               LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
{
2005
    SHELLEXECUTEINFOW sei;
2006

2007 2008
    TRACE("\n");
    sei.cbSize = sizeof(sei);
2009
    sei.fMask = SEE_MASK_FLAG_NO_UI;
2010
    sei.hwnd = hwnd;
2011
    sei.lpVerb = lpVerb;
2012 2013 2014 2015 2016 2017 2018 2019
    sei.lpFile = lpFile;
    sei.lpParameters = lpParameters;
    sei.lpDirectory = lpDirectory;
    sei.nShow = nShowCmd;
    sei.lpIDList = 0;
    sei.lpClass = 0;
    sei.hkeyClass = 0;
    sei.dwHotKey = 0;
2020
    sei.hProcess = 0;
2021

2022
    SHELL_execute( &sei, SHELL_ExecuteW );
2023 2024
    return sei.hInstApp;
}
2025

2026 2027 2028 2029 2030
/*************************************************************************
 * WOWShellExecute			[SHELL32.@]
 *
 * FIXME: the callback function most likely doesn't work the same way on Windows.
 */
2031
HINSTANCE WINAPI WOWShellExecute(HWND hWnd, LPCSTR lpVerb,LPCSTR lpFile,
2032 2033 2034 2035 2036 2037
                                 LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd, void *callback)
{
    SHELLEXECUTEINFOW seiW;
    WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL;
    HANDLE hProcess = 0;

2038
    seiW.lpVerb = lpVerb ? __SHCloneStrAtoW(&wVerb, lpVerb) : NULL;
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    seiW.lpFile = lpFile ? __SHCloneStrAtoW(&wFile, lpFile) : NULL;
    seiW.lpParameters = lpParameters ? __SHCloneStrAtoW(&wParameters, lpParameters) : NULL;
    seiW.lpDirectory = lpDirectory ? __SHCloneStrAtoW(&wDirectory, lpDirectory) : NULL;

    seiW.cbSize = sizeof(seiW);
    seiW.fMask = 0;
    seiW.hwnd = hWnd;
    seiW.nShow = iShowCmd;
    seiW.lpIDList = 0;
    seiW.lpClass = 0;
    seiW.hkeyClass = 0;
    seiW.dwHotKey = 0;
    seiW.hProcess = hProcess;

    SHELL_execute( &seiW, callback );

    SHFree(wVerb);
    SHFree(wFile);
    SHFree(wParameters);
    SHFree(wDirectory);
    return seiW.hInstApp;
}

2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
/*************************************************************************
 * ShellExec_RunDLLW        [SHELL32.@]
 */
void WINAPI ShellExec_RunDLLW(HWND hwnd, HINSTANCE instance, WCHAR *cmdline, int cmdshow)
{
    BOOL in_single_quotes = FALSE, in_double_quotes = FALSE;
    WCHAR *args;

    TRACE("%p, %p, %s, %d\n", hwnd, instance, debugstr_w(cmdline), cmdshow);

    /* Replace the first whitespace character in the command line string with a
       null terminator to separate the program name from the program arguments */
    for (args = cmdline; *args; args++)
    {
        switch (*args)
        {
        case '\\':
            args++; /* skip the next character */
            break;
        case '\'':
            if (!in_double_quotes)
                in_single_quotes = !in_single_quotes;
            break;
        case '"':
            if (!in_single_quotes)
                in_double_quotes = !in_double_quotes;
            break;
        case ' ':
        case '\t':
            if (!in_single_quotes && !in_double_quotes)
            {
                *args = 0;
                args++;
                goto execute;
            }
        }
    }

execute:
    ShellExecuteW(hwnd, NULL, cmdline, args, NULL, cmdshow);
}

/*************************************************************************
 * ShellExec_RunDLLA        [SHELL32.@]
 */
void WINAPI ShellExec_RunDLLA(HWND hwnd, HINSTANCE instance, CHAR *cmdline, int cmdshow)
{
    WCHAR *cmdlineW;
    ShellExec_RunDLLW(hwnd, instance, __SHCloneStrAtoW(&cmdlineW, cmdline), cmdshow);
    SHFree(cmdlineW);
}

2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
/*************************************************************************
 * OpenAs_RunDLLA          [SHELL32.@]
 */
void WINAPI OpenAs_RunDLLA(HWND hwnd, HINSTANCE hinst, LPCSTR cmdline, int cmdshow)
{
    FIXME("%p, %p, %s, %d\n", hwnd, hinst, debugstr_a(cmdline), cmdshow);
}

/*************************************************************************
 * OpenAs_RunDLLW          [SHELL32.@]
 */
void WINAPI OpenAs_RunDLLW(HWND hwnd, HINSTANCE hinst, LPCWSTR cmdline, int cmdshow)
{
    FIXME("%p, %p, %s, %d\n", hwnd, hinst, debugstr_w(cmdline), cmdshow);
}
2129 2130 2131 2132 2133 2134 2135 2136 2137

/*************************************************************************
 * RegenerateUserEnvironment          [SHELL32.@]
 */
BOOL WINAPI RegenerateUserEnvironment(WCHAR *wunknown, BOOL bunknown)
{
    FIXME("stub: %p, %d\n", wunknown, bunknown);
    return FALSE;
}