shlexec.c 18.5 KB
Newer Older
1 2 3
/*
 * 				Shell Library Functions
 *
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <assert.h>

#include "windef.h"
#include "winerror.h"
#include "winreg.h"
#include "shellapi.h"
#include "shlobj.h"
#include "shlwapi.h"
#include "ddeml.h"

#include "wine/winbase16.h"
#include "shell32_main.h"

41
#include "wine/debug.h"
42

43
WINE_DEFAULT_DEBUG_CHANNEL(exec);
44 45 46

/* this function is supposed to expand the escape sequences found in the registry
 * some diving reported that the following were used:
47
 * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
48
 + + %*         seem to report to all parameter (or all remaining, ie after removing
49 50
 *              the already used %1 %2...)
 * + %L         seems to be %1 as long filename followed by the 8+3 variation
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
 * + %l         unknown
 * + %S         unknown
 * + %I         unknown
 */
static void argify(char* res, int len, const char* fmt, const char* lpFile)
{
    char        xlpFile[1024];

    while (*fmt)
    {
        if (*fmt == '%')
        {
            switch (*++fmt)
            {
            case '\0':
66 67
            case '%':
                *res++ = '%';
68
                break;
69
            case '1':
70 71
                if (SearchPathA(NULL, lpFile, ".exe", sizeof(xlpFile), xlpFile, NULL))
                {
72 73
                    strcpy(res, xlpFile);
                    res += strlen(xlpFile);
74 75 76
                }
                else
                {
77 78
                    strcpy(res, lpFile);
                    res += strlen(lpFile);
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
                }
                break;
            default: FIXME("Unknown escape sequence %%%c\n", *fmt);
            }
            fmt++;
        }
        else
            *res++ = *fmt++;
    }
    *res = '\0';
}

/*************************************************************************
 *	SHELL_FindExecutable [Internal]
 *
 * Utility for code sharing between FindExecutable and ShellExecute
95
 * in:
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
 *      lpFile the name of a file
 *      lpOperation the operation on it (open)
 * 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)
 */
static HINSTANCE SHELL_FindExecutable(LPCSTR lpFile, LPCSTR lpOperation,
                                      LPSTR lpResult, LPSTR key)
{
    char *extension = NULL; /* pointer to file extension */
    char tmpext[5];         /* local copy to mung as we please */
    char filetype[256];     /* registry name for this filetype */
    LONG filetypelen = 256; /* length of above */
    char command[256];      /* command from registry */
    LONG commandlen = 256;  /* This is the most DOS can handle :) */
    char buffer[256];       /* Used to GetProfileString */
    HINSTANCE retval = 31;  /* default - 'No association was found' */
    char *tok;              /* token pointer */
    int i;                  /* random counter */
    char xlpFile[256] = ""; /* result of SearchPath */
119

120
    TRACE("%s\n", (lpFile != NULL) ? lpFile : "-");
121

122
    lpResult[0] = '\0'; /* Start off with an empty return string */
123

124 125 126 127 128 129 130
    /* trap NULL parameters on entry */
    if ((lpFile == NULL) || (lpResult == NULL) || (lpOperation == NULL))
    {
        WARN("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
             lpFile, lpOperation, lpResult);
        return 2; /* File not found. Close enough, I guess. */
    }
131

132 133 134 135 136
    if (SearchPathA(NULL, lpFile, ".exe", sizeof(xlpFile), xlpFile, NULL))
    {
        TRACE("SearchPathA returned non-zero\n");
        lpFile = xlpFile;
    }
137

138 139 140 141 142
    /* First thing we need is the file's extension */
    extension = strrchr(xlpFile, '.'); /* Assume last "." is the one; */
                                       /* File->Run in progman uses */
                                       /* .\FILE.EXE :( */
    TRACE("xlpFile=%s,extension=%s\n", xlpFile, extension);
143

144 145 146 147 148
    if ((extension == NULL) || (extension == &xlpFile[strlen(xlpFile)]))
    {
        WARN("Returning 31 - No association\n");
        return 31; /* no association */
    }
149

150 151 152 153
    /* Make local copy & lowercase it for reg & 'programs=' lookup */
    lstrcpynA(tmpext, extension, 5);
    CharLowerA(tmpext);
    TRACE("%s file\n", tmpext);
154

155 156 157 158 159 160 161
    /* Three places to check: */
    /* 1. win.ini, [windows], programs (NB no leading '.') */
    /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
    /* 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. */
162

163 164 165 166 167 168 169 170 171
    if (key) *key = '\0';

    /* 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... */
    if (GetProfileStringA("windows", "programs", "exe pif bat com",
                          buffer, sizeof(buffer)) > 0)
    {
        for (i = 0;i<strlen(buffer); i++) buffer[i] = tolower(buffer[i]);
172

173 174 175 176 177 178 179 180 181 182
        tok = strtok(buffer, " \t"); /* ? */
        while (tok!= NULL)
        {
            if (strcmp(tok, &tmpext[1]) == 0) /* have to skip the leading "." */
            {
                strcpy(lpResult, xlpFile);
                /* Need to perhaps check that the file has a path
                 * attached */
                TRACE("found %s\n", lpResult);
                return 33;
183

184 185 186 187 188 189 190 191
		/* Greater than 32 to indicate success FIXME According to the
		 * docs, I should be returning a handle for the
		 * executable. Does this mean I'm supposed to open the
		 * executable file or something? More RTFM, I guess... */
            }
            tok = strtok(NULL, " \t");
        }
    }
192

193 194 195 196 197 198
    /* Check registry */
    if (RegQueryValueA(HKEY_CLASSES_ROOT, tmpext, filetype,
                       &filetypelen) == ERROR_SUCCESS)
    {
	filetype[filetypelen] = '\0';
	TRACE("File type: %s\n", filetype);
199

200 201 202 203
	/* Looking for ...buffer\shell\lpOperation\command */
	strcat(filetype, "\\shell\\");
	strcat(filetype, lpOperation);
	strcat(filetype, "\\command");
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218
	if (RegQueryValueA(HKEY_CLASSES_ROOT, filetype, command,
                           &commandlen) == ERROR_SUCCESS)
	{
            if (key) strcpy(key, filetype);
#if 0
            LPSTR tmp;
            char param[256];
	    LONG paramlen = 256;

            /* 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
             */
219 220
	    /* Get the parameters needed by the application
	       from the associated ddeexec key */
221 222 223
	    tmp = strstr(filetype, "command");
	    tmp[0] = '\0';
	    strcat(filetype, "ddeexec");
224

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
	    if (RegQueryValueA(HKEY_CLASSES_ROOT, filetype, param, &paramlen) == ERROR_SUCCESS)
	    {
                strcat(command, " ");
                strcat(command, param);
                commandlen += paramlen;
	    }
#endif
	    command[commandlen] = '\0';
            argify(lpResult, sizeof(lpResult), command, xlpFile);
	    retval = 33; /* FIXME see above */
	}
    }
    else /* Check win.ini */
    {
	/* Toss the leading dot */
	extension++;
	if (GetProfileStringA("extensions", extension, "", command,
                              sizeof(command)) > 0)
        {
            if (strlen(command) != 0)
            {
                strcpy(lpResult, command);
                tok = strstr(lpResult, "^"); /* should be ^.extension? */
                if (tok != NULL)
                {
                    tok[0] = '\0';
                    strcat(lpResult, xlpFile); /* what if no dir in xlpFile? */
                    tok = strstr(command, "^"); /* see above */
                    if ((tok != NULL) && (strlen(tok)>5))
                    {
                        strcat(lpResult, &tok[5]);
                    }
                }
                retval = 33; /* FIXME - see above */
            }
        }
    }
262

263 264 265 266 267 268 269 270 271
    TRACE("returning %s\n", lpResult);
    return retval;
}

/******************************************************************
 *		dde_cb
 *
 * callback for the DDE connection. not really usefull
 */
272
static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
273 274 275 276 277 278 279 280 281 282 283
                                HSZ hsz1, HSZ hsz2,
                                HDDEDATA hData, DWORD dwData1, DWORD dwData2)
{
    return (HDDEDATA)0;
}

/******************************************************************
 *		dde_connect
 *
 * ShellExecute helper. Used to do an operation with a DDE connection
 *
284
 * Handles both the direct connection (try #1), and if it fails,
285 286 287
 * launching an application and trying (#2) to connect to it
 *
 */
288 289
static unsigned dde_connect(char* key, char* start, char* ddeexec,
                            const char* lpFile,
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
                            int iCmdShow, BOOL is32)
{
    char*       endkey = key + strlen(key);
    char        app[256], topic[256], ifexec[256], res[256];
    LONG        applen, topiclen, ifexeclen;
    char*       exec;
    DWORD       ddeInst = 0;
    DWORD       tid;
    HSZ         hszApp, hszTopic;
    HCONV       hConv;
    unsigned    ret = 31;

    strcpy(endkey, "\\application");
    applen = sizeof(app);
    if (RegQueryValueA(HKEY_CLASSES_ROOT, key, app, &applen) != ERROR_SUCCESS)
    {
        FIXME("default app name NIY %s\n", key);
        return 2;
    }
309

310 311 312 313 314 315
    strcpy(endkey, "\\topic");
    topiclen = sizeof(topic);
    if (RegQueryValueA(HKEY_CLASSES_ROOT, key, topic, &topiclen) != ERROR_SUCCESS)
    {
        strcpy(topic, "System");
    }
316

317 318 319 320
    if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
    {
        return 2;
    }
321

322 323
    hszApp = DdeCreateStringHandleA(ddeInst, app, CP_WINANSI);
    hszTopic = DdeCreateStringHandleA(ddeInst, topic, CP_WINANSI);
324

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
    exec = ddeexec;
    if (!hConv)
    {
        TRACE("Launching '%s'\n", start);
        ret = (is32) ? WinExec(start, iCmdShow) : WinExec16(start, iCmdShow);
        if (ret < 32)
        {
            TRACE("Couldn't launch\n");
            goto error;
        }
        hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
        if (!hConv)
        {
            ret = 30; /* whatever */
            goto error;
        }
        strcpy(endkey, "\\ifexec");
        ifexeclen = sizeof(ifexec);
        if (RegQueryValueA(HKEY_CLASSES_ROOT, key, ifexec, &ifexeclen) == ERROR_SUCCESS)
        {
            exec = ifexec;
        }
    }
349

350 351
    argify(res, sizeof(res), exec, lpFile);
    TRACE("%s %s => %s\n", exec, lpFile, res);
352 353

    ret = (DdeClientTransaction(res, strlen(res) + 1, hConv, 0L, 0,
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                                XTYP_EXECUTE, 10000, &tid) != DMLERR_NO_ERROR) ? 31 : 32;
    DdeDisconnect(hConv);
 error:
    DdeUninitialize(ddeInst);
    return ret;
}

static HINSTANCE execute_from_key(LPSTR key, LPCSTR lpFile, INT iShowCmd, BOOL is32)
{
    char cmd[1024] = "";
    LONG cmdlen = sizeof(cmd);
    HINSTANCE retval = 31;

    /* Get the application for the registry */
    if (RegQueryValueA(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
    {
        LPSTR tmp;
        char param[256] = "";
        LONG paramlen = 256;
373 374 375

        /* Get the parameters needed by the application
           from the associated ddeexec key */
376 377 378
        tmp = strstr(key, "command");
        assert(tmp);
        strcpy(tmp, "ddeexec");
379

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        if (RegQueryValueA(HKEY_CLASSES_ROOT, key, param, &paramlen) == ERROR_SUCCESS)
        {
            TRACE("Got ddeexec %s => %s\n", key, param);
            retval = dde_connect(key, cmd, param, lpFile, iShowCmd, is32);
        }
        else
        {
            /* Is there a replace() function anywhere? */
            cmd[cmdlen] = '\0';
            argify(param, sizeof(param), cmd, lpFile);

            retval = (is32) ? WinExec(param, iShowCmd) : WinExec16(param, iShowCmd);
        }
    }
    else TRACE("ooch\n");

    return retval;
}

399 400
static HINSTANCE SHELL_Execute(HWND hWnd, LPCSTR lpOperation, LPCSTR lpFile,
                               LPCSTR lpParameters, LPCSTR lpDirectory,
401 402 403 404 405
                               INT iShowCmd, BOOL is32)
{
    HINSTANCE retval = 31;
    char old_dir[1024];
    char cmd[1024];
406

407 408
    TRACE("(%04x,'%s','%s','%s','%s',%x)\n",
          hWnd, lpOperation ? lpOperation:"<null>", lpFile ? lpFile:"<null>",
409
          lpParameters ? lpParameters : "<null>",
410
          lpDirectory ? lpDirectory : "<null>", iShowCmd);
411

412 413 414
    if (lpFile == NULL) return 0; /* should not happen */
    if (lpOperation == NULL) /* default is open */
        lpOperation = "open";
415

416 417 418 419 420
    if (lpDirectory)
    {
        GetCurrentDirectoryA(sizeof(old_dir), old_dir);
        SetCurrentDirectoryA(lpDirectory);
    }
421 422

    /* First try to execute lpFile with lpParameters directly */
423
    strcpy(cmd, lpFile);
424
    if (lpParameters)
425 426 427 428
    {
        strcat(cmd, " ");
        strcat(cmd, lpParameters);
    }
429

430
    retval = (is32) ? WinExec(cmd, iShowCmd) : WinExec16(cmd, iShowCmd);
431

432 433 434
    /* Unable to execute lpFile directly
       Check if we can match an application to lpFile */
    if (retval < 32)
435
    {
436 437 438 439
        char lpstrProtocol[256];

        cmd[0] = '\0';
        retval = SHELL_FindExecutable(lpFile, lpOperation, cmd, lpstrProtocol);
440

441 442 443 444 445 446 447 448 449 450 451 452
        if (retval > 32)  /* Found */
        {
            TRACE("%s/%s => %s/%s\n", lpFile, lpOperation, cmd, lpstrProtocol);
            if (*lpstrProtocol)
                retval = execute_from_key(lpstrProtocol, lpFile, iShowCmd, is32);
            else
                retval = (is32) ? WinExec(cmd, iShowCmd) : WinExec16(cmd, iShowCmd);
        }
        else if (PathIsURLA((LPSTR)lpFile))    /* File not found, check for URL */
        {
            LPSTR lpstrRes;
            INT iSize;
453

454 455
            lpstrRes = strchr(lpFile, ':');
            iSize = lpstrRes - lpFile;
456

457 458 459 460 461 462 463
            TRACE("Got URL: %s\n", lpFile);
            /* Looking for ...protocol\shell\lpOperation\command */
            strncpy(lpstrProtocol, lpFile, iSize);
            lpstrProtocol[iSize] = '\0';
            strcat(lpstrProtocol, "\\shell\\");
            strcat(lpstrProtocol, lpOperation);
            strcat(lpstrProtocol, "\\command");
464

465 466 467 468 469 470 471
            /* Remove File Protocol from lpFile */
            /* In the case file://path/file     */
            if (!strncasecmp(lpFile, "file", iSize))
            {
                lpFile += iSize;
                while (*lpFile == ':') lpFile++;
            }
472

473
            retval = execute_from_key(lpstrProtocol, lpFile, iShowCmd, is32);
474
        }
475 476 477
        /* Check if file specified is in the form www.??????.*** */
        else if (!strncasecmp(lpFile, "www", 3))
        {
478
            /* if so, append lpFile http:// and call ShellExecute */
479 480 481 482 483 484 485 486 487 488 489 490 491 492
            char lpstrTmpFile[256] = "http://" ;
            strcat(lpstrTmpFile, lpFile);
            retval = ShellExecuteA(hWnd, lpOperation, lpstrTmpFile, NULL, NULL, 0);
        }
    }
    if (lpDirectory)
        SetCurrentDirectoryA(old_dir);
    return retval;
}

/*************************************************************************
 * FindExecutableA			[SHELL32.@]
 */
HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
493
{
494 495
    HINSTANCE retval = 31;    /* default - 'No association was found' */
    char old_dir[1024];
496 497

    TRACE("File %s, Dir %s\n",
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
          (lpFile != NULL ? lpFile : "-"), (lpDirectory != NULL ? lpDirectory : "-"));

    lpResult[0] = '\0'; /* Start off with an empty return string */

    /* trap NULL parameters on entry */
    if ((lpFile == NULL) || (lpResult == NULL))
    {
        /* FIXME - should throw a warning, perhaps! */
	return 2; /* File not found. Close enough, I guess. */
    }

    if (lpDirectory)
    {
        GetCurrentDirectoryA(sizeof(old_dir), old_dir);
        SetCurrentDirectoryA(lpDirectory);
    }
514

515
    retval = SHELL_FindExecutable(lpFile, "open", lpResult, NULL);
516

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    TRACE("returning %s\n", lpResult);
    if (lpDirectory)
        SetCurrentDirectoryA(old_dir);
    return retval;
}

/*************************************************************************
 * FindExecutableW			[SHELL32.@]
 */
HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
{
    FIXME("(%p,%p,%p): stub\n", lpFile, lpDirectory, lpResult);
    return 31;    /* default - 'No association was found' */
}

/*************************************************************************
 *				ShellExecute		[SHELL.20]
 */
HINSTANCE16 WINAPI ShellExecute16( HWND16 hWnd, LPCSTR lpOperation,
                                   LPCSTR lpFile, LPCSTR lpParameters,
                                   LPCSTR lpDirectory, INT16 iShowCmd )
538 539
{
    return (HINSTANCE16)SHELL_Execute(hWnd, lpOperation, lpFile,
540 541 542 543 544 545
                                      lpParameters, lpDirectory, iShowCmd, FALSE );
}

/*************************************************************************
 * ShellExecuteA			[SHELL32.290]
 */
546
HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
547 548 549 550 551 552 553 554 555 556
                               LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
{
    TRACE("\n");
    return SHELL_Execute( hWnd, lpOperation, lpFile, lpParameters,
                          lpDirectory, iShowCmd, TRUE );
}

/*************************************************************************
 * ShellExecuteW			[SHELL32.294]
 * from shellapi.h
557 558
 * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
 * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
559
 */
560
HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
561 562 563 564 565 566
                               LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
{
       FIXME(": stub\n");
       return 0;
}