Prepare for adding new tests.
[wine] / dlls / shell32 / shlexec.c
1 /*
2  *                              Shell Library Functions
3  *
4  * Copyright 1998 Marcus Meissner
5  * Copyright 2002 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #include <ctype.h>
33 #include <assert.h>
34
35 #define COBJMACROS
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winreg.h"
41 #include "winuser.h"
42 #include "shlwapi.h"
43 #include "ddeml.h"
44
45 #include "wine/winbase16.h"
46 #include "shell32_main.h"
47 #include "pidl.h"
48
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(exec);
52
53 static const WCHAR wszOpen[] = {'o','p','e','n',0};
54 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 static const WCHAR wszFolder[] = {'F','o','l','d','e','r',0};
58 static const WCHAR wszEmpty[] = {0};
59
60
61 /***********************************************************************
62  *      SHELL_ArgifyW [Internal]
63  *
64  * this function is supposed to expand the escape sequences found in the registry
65  * some diving reported that the following were used:
66  * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
67  *      %1 file
68  *      %2 printer
69  *      %3 driver
70  *      %4 port
71  * %I address of a global item ID (explorer switch /idlist)
72  * %L seems to be %1 as long filename followed by the 8+3 variation
73  * %S ???
74  * %* all following parameters (see batfile)
75  *
76  * FIXME: use 'len'
77  * FIXME: Careful of going over string boundaries. No checking is done to 'res'...
78  */
79 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args)
80 {
81     WCHAR   xlpFile[1024];
82     BOOL    done = FALSE;
83     PWSTR   res = out;
84     PCWSTR  cmd;
85     LPVOID  pv;
86
87     TRACE("%p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
88           debugstr_w(lpFile), pidl, args);
89
90     while (*fmt)
91     {
92         if (*fmt == '%')
93         {
94             switch (*++fmt)
95             {
96             case '\0':
97             case '%':
98                 *res++ = '%';
99                 break;
100
101             case '2':
102             case '3':
103             case '4':
104             case '5':
105             case '6':
106             case '7':
107             case '8':
108             case '9':
109             case '0':
110             case '*':
111                 if (args)
112                 {
113                     if (*fmt == '*')
114                     {
115                         *res++ = '"';
116                         while(*args)
117                             *res++ = *args++;
118                         *res++ = '"';
119                     }
120                     else
121                     {
122                         while(*args && !isspace(*args))
123                             *res++ = *args++;
124
125                         while(isspace(*args))
126                             ++args;
127                     }
128                     break;
129                 }
130                 /* else fall through */
131             case '1':
132                 if (!done || (*fmt == '1'))
133                 {
134                     /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
135                     if (SearchPathW(NULL, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
136                         cmd = xlpFile;
137                     else
138                         cmd = lpFile;
139
140                     /* Add double quotation marks unless we already have them
141                        (e.g.: "file://%1" %* for exefile) or unless the arg is already
142                        enclosed in double quotation marks */
143                     if ((res == out || *(fmt + 1) != '"') && *cmd != '"')
144                     {
145                         *res++ = '"';
146                         strcpyW(res, cmd);
147                         res += strlenW(cmd);
148                         *res++ = '"';
149                     }
150                     else
151                     {
152                         strcpyW(res, cmd);
153                         res += strlenW(cmd);
154                     }
155                 }
156                 break;
157
158             /*
159              * IE uses this a lot for activating things such as windows media
160              * player. This is not verified to be fully correct but it appears
161              * to work just fine.
162              */
163             case 'l':
164             case 'L':
165                 if (lpFile) {
166                     strcpyW(res, lpFile);
167                     res += strlenW(lpFile);
168                 }
169                 break;
170
171             case 'i':
172             case 'I':
173                 if (pidl) {
174                     HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
175                     pv = SHLockShared(hmem, 0);
176                     res += sprintfW(res, wszILPtr, pv);
177                     SHUnlockShared(pv);
178                 }
179                 break;
180
181             default:
182                 /*
183                  * Check if this is an env-variable here...
184                  */
185
186                 /* Make sure that we have at least one more %.*/
187                 if (strchrW(fmt, '%'))
188                 {
189                     WCHAR   tmpBuffer[1024];
190                     PWSTR   tmpB = tmpBuffer;
191                     WCHAR   tmpEnvBuff[MAX_PATH];
192                     DWORD   envRet;
193
194                     while (*fmt != '%')
195                         *tmpB++ = *fmt++;
196                     *tmpB++ = 0;
197
198                     TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
199
200                     envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
201                     if (envRet == 0 || envRet > MAX_PATH)
202                         strcpyW( res, tmpBuffer );
203                     else
204                         strcpyW( res, tmpEnvBuff );
205                     res += strlenW(res);
206                 }
207                 done = TRUE;
208                 break;
209             }
210             /* Don't skip past terminator (catch a single '%' at the end) */
211             if (*fmt != '\0')
212             {
213                 fmt++;
214             }
215         }
216         else
217             *res++ = *fmt++;
218     }
219
220     *res = '\0';
221
222     return done;
223 }
224
225 HRESULT SHELL_GetPathFromIDListForExecuteA(LPCITEMIDLIST pidl, LPSTR pszPath, UINT uOutSize)
226 {
227     STRRET strret;
228     IShellFolder* desktop;
229
230     HRESULT hr = SHGetDesktopFolder(&desktop);
231
232     if (SUCCEEDED(hr)) {
233         hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
234
235         if (SUCCEEDED(hr))
236             StrRetToStrNA(pszPath, uOutSize, &strret, pidl);
237
238         IShellFolder_Release(desktop);
239     }
240
241     return hr;
242 }
243
244 HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
245 {
246     STRRET strret;
247     IShellFolder* desktop;
248
249     HRESULT hr = SHGetDesktopFolder(&desktop);
250
251     if (SUCCEEDED(hr)) {
252         hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
253
254         if (SUCCEEDED(hr))
255             StrRetToStrNW(pszPath, uOutSize, &strret, pidl);
256
257         IShellFolder_Release(desktop);
258     }
259
260     return hr;
261 }
262
263 /*************************************************************************
264  *      SHELL_ResolveShortCutW [Internal]
265  *      read shortcut file at 'wcmd'
266  */
267 static HRESULT SHELL_ResolveShortCutW(LPWSTR wcmd, LPWSTR wargs, LPWSTR wdir, HWND hwnd, LPCWSTR lpVerb, int* pshowcmd, LPITEMIDLIST* ppidl)
268 {
269     IShellFolder* psf;
270
271     HRESULT hr = SHGetDesktopFolder(&psf);
272
273     *ppidl = NULL;
274
275     if (SUCCEEDED(hr)) {
276         LPITEMIDLIST pidl;
277         ULONG l;
278
279         hr = IShellFolder_ParseDisplayName(psf, 0, 0, wcmd, &l, &pidl, 0);
280
281         if (SUCCEEDED(hr)) {
282             IShellLinkW* psl;
283
284             hr = IShellFolder_GetUIObjectOf(psf, NULL, 1, (LPCITEMIDLIST*)&pidl, &IID_IShellLinkW, NULL, (LPVOID*)&psl);
285
286             if (SUCCEEDED(hr)) {
287                 hr = IShellLinkW_Resolve(psl, hwnd, 0);
288
289                 if (SUCCEEDED(hr)) {
290                     hr = IShellLinkW_GetPath(psl, wcmd, MAX_PATH, NULL, SLGP_UNCPRIORITY);
291
292                     if (SUCCEEDED(hr)) {
293                         if (!*wcmd) {
294                             /* We could not translate the PIDL in the shell link into a valid file system path - so return the PIDL instead. */
295                             hr = IShellLinkW_GetIDList(psl, ppidl);
296
297                             if (SUCCEEDED(hr) && *ppidl) {
298                                 /* We got a PIDL instead of a file system path - try to translate it. */
299                                 if (SHGetPathFromIDListW(*ppidl, wcmd)) {
300                                     SHFree(*ppidl);
301                                     *ppidl = NULL;
302                                 }
303                             }
304                         }
305
306                         if (SUCCEEDED(hr)) {
307                             /* get command line arguments, working directory and display mode if available */
308                             IShellLinkW_GetWorkingDirectory(psl, wdir, MAX_PATH);
309                             IShellLinkW_GetArguments(psl, wargs, MAX_PATH);
310                             IShellLinkW_GetShowCmd(psl, pshowcmd);
311                         }
312                     }
313                 }
314
315                 IShellLinkW_Release(psl);
316             }
317
318             SHFree(pidl);
319         }
320
321         IShellFolder_Release(psf);
322     }
323
324     return hr;
325 }
326
327 /*************************************************************************
328  *      SHELL_ExecuteW [Internal]
329  *
330  */
331 static UINT SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
332                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
333 {
334     STARTUPINFOW  startup;
335     PROCESS_INFORMATION info;
336     UINT retval = 31;
337     UINT gcdret = 0;
338     WCHAR curdir[MAX_PATH];
339
340     TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
341     /* ShellExecute specifies the command from psei->lpDirectory
342      * if present. Not from the current dir as CreateProcess does */
343     if( psei->lpDirectory && psei->lpDirectory[0] )
344         if( ( gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
345             if( !SetCurrentDirectoryW( psei->lpDirectory))
346                 ERR("cannot set directory %s\n", debugstr_w(psei->lpDirectory));
347     ZeroMemory(&startup,sizeof(STARTUPINFOW));
348     startup.cb = sizeof(STARTUPINFOW);
349     startup.dwFlags = STARTF_USESHOWWINDOW;
350     startup.wShowWindow = psei->nShow;
351     if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT,
352                        env, *psei->lpDirectory? psei->lpDirectory: NULL, &startup, &info))
353     {
354         /* Give 30 seconds to the app to come up, if desired. Probably only needed
355            when starting app immediately before making a DDE connection. */
356         if (shWait)
357             if (WaitForInputIdle( info.hProcess, 30000 ) == WAIT_FAILED)
358                 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
359         retval = 33;
360         if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
361             psei_out->hProcess = info.hProcess;
362         else
363             CloseHandle( info.hProcess );
364         CloseHandle( info.hThread );
365     }
366     else if ((retval = GetLastError()) >= 32)
367     {
368         TRACE("CreateProcess returned error %d\n", retval);
369         retval = ERROR_BAD_FORMAT;
370     }
371
372     TRACE("returning %u\n", retval);
373
374     psei_out->hInstApp = (HINSTANCE)retval;
375     if( gcdret )
376         if( !SetCurrentDirectoryW( curdir))
377             ERR("cannot return to directory %s\n", debugstr_w(curdir));
378
379     return retval;
380 }
381
382
383 /***********************************************************************
384  *           SHELL_BuildEnvW    [Internal]
385  *
386  * Build the environment for the new process, adding the specified
387  * path to the PATH variable. Returned pointer must be freed by caller.
388  */
389 static void *SHELL_BuildEnvW( const WCHAR *path )
390 {
391     static const WCHAR wPath[] = {'P','A','T','H','=',0};
392     WCHAR *strings, *new_env;
393     WCHAR *p, *p2;
394     int total = strlenW(path) + 1;
395     BOOL got_path = FALSE;
396
397     if (!(strings = GetEnvironmentStringsW())) return NULL;
398     p = strings;
399     while (*p)
400     {
401         int len = strlenW(p) + 1;
402         if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
403         total += len;
404         p += len;
405     }
406     if (!got_path) total += 5;  /* we need to create PATH */
407     total++;  /* terminating null */
408
409     if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
410     {
411         FreeEnvironmentStringsW( strings );
412         return NULL;
413     }
414     p = strings;
415     p2 = new_env;
416     while (*p)
417     {
418         int len = strlenW(p) + 1;
419         memcpy( p2, p, len * sizeof(WCHAR) );
420         if (!strncmpiW( p, wPath, 5 ))
421         {
422             p2[len - 1] = ';';
423             strcpyW( p2 + len, path );
424             p2 += strlenW(path) + 1;
425         }
426         p += len;
427         p2 += len;
428     }
429     if (!got_path)
430     {
431         strcpyW( p2, wPath );
432         strcatW( p2, path );
433         p2 += strlenW(p2) + 1;
434     }
435     *p2 = 0;
436     FreeEnvironmentStringsW( strings );
437     return new_env;
438 }
439
440
441 /***********************************************************************
442  *           SHELL_TryAppPathW  [Internal]
443  *
444  * Helper function for SHELL_FindExecutable
445  * @param lpResult - pointer to a buffer of size MAX_PATH
446  * On entry: szName is a filename (probably without path separators).
447  * On exit: if szName found in "App Path", place full path in lpResult, and return true
448  */
449 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
450 {
451     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',
452         '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','A','p','p',' ','P','a','t','h','s','\\',0};
453     static const WCHAR wPath[] = {'P','a','t','h',0};
454     HKEY hkApp = 0;
455     WCHAR buffer[1024];
456     LONG len;
457     LONG res;
458     BOOL found = FALSE;
459
460     if (env) *env = NULL;
461     strcpyW(buffer, wszKeyAppPaths);
462     strcatW(buffer, szName);
463     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
464     if (res) goto end;
465
466     len = MAX_PATH*sizeof(WCHAR);
467     res = RegQueryValueW(hkApp, NULL, lpResult, &len);
468     if (res) goto end;
469     found = TRUE;
470
471     if (env)
472     {
473         DWORD count = sizeof(buffer);
474         if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
475             *env = SHELL_BuildEnvW( buffer );
476     }
477
478 end:
479     if (hkApp) RegCloseKey(hkApp);
480     return found;
481 }
482
483 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
484 {
485     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
486
487     /* Looking for ...buffer\shell\<verb>\command */
488     strcatW(filetype, wszShell);
489     strcatW(filetype, lpOperation);
490     strcatW(filetype, wCommand);
491
492     if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
493                        &commandlen) == ERROR_SUCCESS)
494     {
495         commandlen /= sizeof(WCHAR);
496         if (key) strcpyW(key, filetype);
497 #if 0
498         LPWSTR tmp;
499         WCHAR param[256];
500         LONG paramlen = sizeof(param);
501         static const WCHAR wSpace[] = {' ',0};
502
503         /* FIXME: it seems all Windows version don't behave the same here.
504          * the doc states that this ddeexec information can be found after
505          * the exec names.
506          * on Win98, it doesn't appear, but I think it does on Win2k
507          */
508         /* Get the parameters needed by the application
509            from the associated ddeexec key */
510         tmp = strstrW(filetype, wCommand);
511         tmp[0] = '\0';
512         strcatW(filetype, wDdeexec);
513         if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, param,
514                                      &paramlen) == ERROR_SUCCESS)
515         {
516             paramlen /= sizeof(WCHAR);
517             strcatW(command, wSpace);
518             strcatW(command, param);
519             commandlen += paramlen;
520         }
521 #endif
522
523         command[commandlen] = '\0';
524
525         return 33; /* FIXME see SHELL_FindExecutable() */
526     }
527
528     return 31;  /* default - 'No association was found' */
529 }
530
531 /*************************************************************************
532  *      SHELL_FindExecutable [Internal]
533  *
534  * Utility for code sharing between FindExecutable and ShellExecute
535  * in:
536  *      lpFile the name of a file
537  *      lpOperation the operation on it (open)
538  * out:
539  *      lpResult a buffer, big enough :-(, to store the command to do the
540  *              operation on the file
541  *      key a buffer, big enough, to get the key name to do actually the
542  *              command (it'll be used afterwards for more information
543  *              on the operation)
544  */
545 UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
546                                  LPWSTR lpResult, int resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
547 {
548     static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
549     static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
550     static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
551     WCHAR *extension = NULL; /* pointer to file extension */
552     WCHAR filetype[256];     /* registry name for this filetype */
553     LONG  filetypelen = sizeof(filetype); /* length of above */
554     WCHAR command[1024];     /* command from registry */
555     WCHAR wBuffer[256];      /* Used to GetProfileString */
556     UINT  retval = 31;       /* default - 'No association was found' */
557     WCHAR *tok;              /* token pointer */
558     WCHAR xlpFile[256];      /* result of SearchPath */
559     DWORD attribs;           /* file attributes */
560
561     TRACE("%s\n", (lpFile != NULL) ? debugstr_w(lpFile) : "-");
562
563     xlpFile[0] = '\0';
564     lpResult[0] = '\0'; /* Start off with an empty return string */
565     if (key) *key = '\0';
566
567     /* trap NULL parameters on entry */
568     if ((lpFile == NULL) || (lpResult == NULL) || (lpOperation == NULL))
569     {
570         WARN("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
571              debugstr_w(lpFile), debugstr_w(lpOperation), debugstr_w(lpResult));
572         return 2; /* File not found. Close enough, I guess. */
573     }
574
575     if (SHELL_TryAppPathW( lpFile, lpResult, env ))
576     {
577         TRACE("found %s via App Paths\n", debugstr_w(lpResult));
578         return 33;
579     }
580
581     if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
582     {
583         TRACE("SearchPathW returned non-zero\n");
584         lpFile = xlpFile;
585         /* Hey, isn't this value ignored?  Why make this call?  Shouldn't we return here?  --dank*/
586     }
587
588     attribs = GetFileAttributesW(lpFile);
589     if (attribs!=INVALID_FILE_ATTRIBUTES && (attribs&FILE_ATTRIBUTE_DIRECTORY))
590     {
591        strcpyW(filetype, wszFolder);
592        filetypelen = 6;    /* strlen("Folder") */
593     }
594     else
595     {
596         /* First thing we need is the file's extension */
597         extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
598         /* File->Run in progman uses */
599         /* .\FILE.EXE :( */
600         TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
601
602         if (extension == NULL || extension[1]==0)
603         {
604             WARN("Returning 31 - No association\n");
605             return 31; /* no association */
606         }
607
608         /* Three places to check: */
609         /* 1. win.ini, [windows], programs (NB no leading '.') */
610         /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
611         /* 3. win.ini, [extensions], extension (NB no leading '.' */
612         /* All I know of the order is that registry is checked before */
613         /* extensions; however, it'd make sense to check the programs */
614         /* section first, so that's what happens here. */
615
616         /* See if it's a program - if GetProfileString fails, we skip this
617          * section. Actually, if GetProfileString fails, we've probably
618          * got a lot more to worry about than running a program... */
619         if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
620         {
621             CharLowerW(wBuffer);
622             tok = wBuffer;
623             while (*tok)
624             {
625                 WCHAR *p = tok;
626                 while (*p && *p != ' ' && *p != '\t') p++;
627                 if (*p)
628                 {
629                     *p++ = 0;
630                     while (*p == ' ' || *p == '\t') p++;
631                 }
632
633                 if (strcmpiW(tok, &extension[1]) == 0) /* have to skip the leading "." */
634                 {
635                     strcpyW(lpResult, xlpFile);
636                     /* Need to perhaps check that the file has a path
637                      * attached */
638                     TRACE("found %s\n", debugstr_w(lpResult));
639                     return 33;
640
641                     /* Greater than 32 to indicate success FIXME According to the
642                      * docs, I should be returning a handle for the
643                      * executable. Does this mean I'm supposed to open the
644                      * executable file or something? More RTFM, I guess... */
645                 }
646                 tok = p;
647             }
648         }
649
650         /* Check registry */
651         if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, filetype,
652                            &filetypelen) == ERROR_SUCCESS)
653         {
654             filetypelen /= sizeof(WCHAR);
655             filetype[filetypelen] = '\0';
656             TRACE("File type: %s\n", debugstr_w(filetype));
657         }
658     }
659
660     if (*filetype)
661     {
662         if (lpOperation)
663         {
664             /* pass the operation string to SHELL_FindExecutableByOperation() */
665             filetype[filetypelen] = '\0';
666             retval = SHELL_FindExecutableByOperation(lpPath, lpFile, lpOperation, key, filetype, command, sizeof(command));
667         }
668         else
669         {
670             WCHAR operation[MAX_PATH];
671             HKEY hkey;
672
673             /* Looking for ...buffer\shell\<operation>\command */
674             strcatW(filetype, wszShell);
675
676             /* enumerate the operation subkeys in the registry and search for one with an associated command */
677             if (RegOpenKeyW(HKEY_CLASSES_ROOT, filetype, &hkey) == ERROR_SUCCESS)
678             {
679                 int idx = 0;
680                 for(;; ++idx)
681                 {
682                     if (RegEnumKeyW(hkey, idx, operation, MAX_PATH) != ERROR_SUCCESS)
683                         break;
684
685                     filetype[filetypelen] = '\0';
686                     retval = SHELL_FindExecutableByOperation(lpPath, lpFile, operation, key, filetype, command, sizeof(command));
687
688                     if (retval > 32)
689                         break;
690             }
691                 RegCloseKey(hkey);
692             }
693         }
694
695         if (retval > 32)
696         {
697             SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args);
698
699             /* Remove double quotation marks and command line arguments */
700             if (*lpResult == '"')
701             {
702                 WCHAR *p = lpResult;
703                 while (*(p + 1) != '"')
704                 {
705                     *p = *(p + 1);
706                     p++;
707                 }
708                 *p = '\0';
709             }
710         }
711     }
712     else /* Check win.ini */
713     {
714         static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
715
716         /* Toss the leading dot */
717         extension++;
718         if (GetProfileStringW(wExtensions, extension, wszEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
719         {
720             if (strlenW(command) != 0)
721             {
722                 strcpyW(lpResult, command);
723                 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
724                 if (tok != NULL)
725                 {
726                     tok[0] = '\0';
727                     strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
728                     tok = strchrW(command, '^'); /* see above */
729                     if ((tok != NULL) && (strlenW(tok)>5))
730                     {
731                         strcatW(lpResult, &tok[5]);
732                     }
733                 }
734                 retval = 33; /* FIXME - see above */
735             }
736         }
737     }
738
739     TRACE("returning %s\n", debugstr_w(lpResult));
740     return retval;
741 }
742
743 /******************************************************************
744  *              dde_cb
745  *
746  * callback for the DDE connection. not really usefull
747  */
748 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
749                                 HSZ hsz1, HSZ hsz2, HDDEDATA hData,
750                                 ULONG_PTR dwData1, ULONG_PTR dwData2)
751 {
752     TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
753            uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
754     return NULL;
755 }
756
757 /******************************************************************
758  *              dde_connect
759  *
760  * ShellExecute helper. Used to do an operation with a DDE connection
761  *
762  * Handles both the direct connection (try #1), and if it fails,
763  * launching an application and trying (#2) to connect to it
764  *
765  */
766 static unsigned dde_connect(WCHAR* key, WCHAR* start, WCHAR* ddeexec,
767                             const WCHAR* lpFile, WCHAR *env,
768                             LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
769                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
770 {
771     static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
772     static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
773     WCHAR *     endkey = key + strlenW(key);
774     WCHAR       app[256], topic[256], ifexec[256], res[256];
775     LONG        applen, topiclen, ifexeclen;
776     WCHAR *     exec;
777     DWORD       ddeInst = 0;
778     DWORD       tid;
779     HSZ         hszApp, hszTopic;
780     HCONV       hConv;
781     HDDEDATA    hDdeData;
782     unsigned    ret = 31;
783
784     strcpyW(endkey, wApplication);
785     applen = sizeof(app);
786     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, app, &applen) != ERROR_SUCCESS)
787     {
788         FIXME("default app name NIY %s\n", debugstr_w(key));
789         return 2;
790     }
791
792     strcpyW(endkey, wTopic);
793     topiclen = sizeof(topic);
794     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, topic, &topiclen) != ERROR_SUCCESS)
795     {
796         static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
797         strcpyW(topic, wSystem);
798     }
799
800     if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
801     {
802         return 2;
803     }
804
805     hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
806     hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
807
808     hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
809     exec = ddeexec;
810     if (!hConv)
811     {
812         static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
813         TRACE("Launching '%s'\n", debugstr_w(start));
814         ret = execfunc(start, env, TRUE, psei, psei_out);
815         if (ret < 32)
816         {
817             TRACE("Couldn't launch\n");
818             goto error;
819         }
820         hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
821         if (!hConv)
822         {
823             TRACE("Couldn't connect. ret=%d\n", ret);
824             DdeUninitialize(ddeInst);
825             SetLastError(ERROR_DDE_FAIL);
826             return 30; /* whatever */
827         }
828         strcpyW(endkey, wIfexec);
829         ifexeclen = sizeof(ifexec);
830         if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ifexec, &ifexeclen) == ERROR_SUCCESS)
831         {
832             exec = ifexec;
833         }
834     }
835
836     SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline);
837     TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
838
839     /* It's documented in the KB 330337 that IE has a bug and returns
840      * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
841      */
842     hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
843                                      XTYP_EXECUTE, 10000, &tid);
844     if (hDdeData)
845         DdeFreeDataHandle(hDdeData);
846     else
847         WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
848     ret = 33;
849
850     DdeDisconnect(hConv);
851
852  error:
853     DdeUninitialize(ddeInst);
854
855     return ret;
856 }
857
858 /*************************************************************************
859  *      execute_from_key [Internal]
860  */
861 static UINT execute_from_key(LPWSTR key, LPCWSTR lpFile, WCHAR *env, LPCWSTR szCommandline,
862                              SHELL_ExecuteW32 execfunc,
863                              LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
864 {
865     WCHAR cmd[1024];
866     LONG cmdlen = sizeof(cmd);
867     UINT retval = 31;
868
869     cmd[0] = '\0';
870
871     /* Get the application for the registry */
872     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
873     {
874         static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
875         static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
876         LPWSTR tmp;
877         WCHAR param[256];
878         LONG paramlen = sizeof(param);
879
880         param[0] = '\0';
881
882         /* Get the parameters needed by the application
883            from the associated ddeexec key */
884         tmp = strstrW(key, wCommand);
885         assert(tmp);
886         strcpyW(tmp, wDdeexec);
887
888         if (RegQueryValueW(HKEY_CLASSES_ROOT, key, param, &paramlen) == ERROR_SUCCESS)
889         {
890             TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(param));
891             retval = dde_connect(key, cmd, param, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
892         }
893         else
894         {
895             /* Is there a replace() function anywhere? */
896             cmdlen /= sizeof(WCHAR);
897             cmd[cmdlen] = '\0';
898             SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline);
899             retval = execfunc(param, env, FALSE, psei, psei_out);
900         }
901     }
902     else TRACE("ooch\n");
903
904     return retval;
905 }
906
907 /*************************************************************************
908  * FindExecutableA                      [SHELL32.@]
909  */
910 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
911 {
912     HINSTANCE retval;
913     WCHAR *wFile = NULL, *wDirectory = NULL;
914     WCHAR wResult[MAX_PATH];
915
916     if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
917     if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
918
919     retval = FindExecutableW(wFile, wDirectory, wResult);
920     WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
921     if (wFile) SHFree( wFile );
922     if (wDirectory) SHFree( wDirectory );
923
924     TRACE("returning %s\n", lpResult);
925     return (HINSTANCE)retval;
926 }
927
928 /*************************************************************************
929  * FindExecutableW                      [SHELL32.@]
930  */
931 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
932 {
933     UINT retval = 31;    /* default - 'No association was found' */
934     WCHAR old_dir[1024];
935
936     TRACE("File %s, Dir %s\n",
937           (lpFile != NULL ? debugstr_w(lpFile) : "-"), (lpDirectory != NULL ? debugstr_w(lpDirectory) : "-"));
938
939     lpResult[0] = '\0'; /* Start off with an empty return string */
940
941     /* trap NULL parameters on entry */
942     if ((lpFile == NULL) || (lpResult == NULL))
943     {
944         /* FIXME - should throw a warning, perhaps! */
945         return (HINSTANCE)2; /* File not found. Close enough, I guess. */
946     }
947
948     if (lpDirectory)
949     {
950         GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
951         SetCurrentDirectoryW(lpDirectory);
952     }
953
954     retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
955
956     TRACE("returning %s\n", debugstr_w(lpResult));
957     if (lpDirectory)
958         SetCurrentDirectoryW(old_dir);
959     return (HINSTANCE)retval;
960 }
961
962 /*************************************************************************
963  *      ShellExecuteExW32 [Internal]
964  */
965 BOOL WINAPI ShellExecuteExW32 (LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc)
966 {
967     static const WCHAR wQuote[] = {'"',0};
968     static const WCHAR wSpace[] = {' ',0};
969     static const WCHAR wWww[] = {'w','w','w',0};
970     static const WCHAR wFile[] = {'f','i','l','e',0};
971     static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
972     static const WCHAR wExtLnk[] = {'.','l','n','k',0};
973     static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r','.','e','x','e',0};
974     static const DWORD unsupportedFlags =
975         SEE_MASK_INVOKEIDLIST  | SEE_MASK_ICON         | SEE_MASK_HOTKEY |
976         SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI |
977         SEE_MASK_UNICODE       | SEE_MASK_NO_CONSOLE   | SEE_MASK_ASYNCOK |
978         SEE_MASK_HMONITOR;
979
980     WCHAR wszApplicationName[MAX_PATH+2], wszParameters[1024], wszDir[MAX_PATH];
981     SHELLEXECUTEINFOW sei_tmp;  /* modifiable copy of SHELLEXECUTEINFO struct */
982     WCHAR wfileName[MAX_PATH];
983     WCHAR *env;
984     WCHAR lpstrProtocol[256];
985     LPCWSTR lpFile;
986     UINT retval = 31;
987     WCHAR wcmd[1024];
988     WCHAR buffer[MAX_PATH];
989     const WCHAR* ext;
990     BOOL done;
991
992     /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
993     memcpy(&sei_tmp, sei, sizeof(sei_tmp));
994
995     TRACE("mask=0x%08lx hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
996             sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
997             debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
998             debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
999             (sei_tmp.fMask & SEE_MASK_CLASSNAME) ? debugstr_w(sei_tmp.lpClass) : "not used");
1000
1001     sei->hProcess = NULL;
1002
1003     /* make copies of all path/command strings */
1004     if (sei_tmp.lpFile)
1005         strcpyW(wszApplicationName, sei_tmp.lpFile);
1006     else
1007         *wszApplicationName = '\0';
1008
1009     if (sei_tmp.lpParameters)
1010         strcpyW(wszParameters, sei_tmp.lpParameters);
1011     else
1012         *wszParameters = '\0';
1013
1014     if (sei_tmp.lpDirectory)
1015         strcpyW(wszDir, sei_tmp.lpDirectory);
1016     else
1017         *wszDir = '\0';
1018
1019     /* adjust string pointers to point to the new buffers */
1020     sei_tmp.lpFile = wszApplicationName;
1021     sei_tmp.lpParameters = wszParameters;
1022     sei_tmp.lpDirectory = wszDir;
1023
1024     if (sei_tmp.fMask & unsupportedFlags)
1025     {
1026         FIXME("flags ignored: 0x%08lx\n", sei_tmp.fMask & unsupportedFlags);
1027     }
1028
1029     /* process the IDList */
1030     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1031     {
1032         IShellExecuteHookW* pSEH;
1033
1034         HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
1035
1036         if (SUCCEEDED(hr))
1037         {
1038             hr = IShellExecuteHookW_Execute(pSEH, sei);
1039
1040             IShellExecuteHookW_Release(pSEH);
1041
1042             if (hr == S_OK)
1043                 return TRUE;
1044         }
1045
1046         wszApplicationName[0] = '"';
1047         SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName+1);
1048         strcatW(wszApplicationName, wQuote);
1049         TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1050     }
1051
1052     if (sei_tmp.fMask & (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY))
1053     {
1054         /* launch a document by fileclass like 'WordPad.Document.1' */
1055         /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
1056         /* FIXME: szCommandline should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
1057         HCR_GetExecuteCommandW((sei_tmp.fMask & SEE_MASK_CLASSKEY) ? sei_tmp.hkeyClass : NULL,
1058                                (sei_tmp.fMask & SEE_MASK_CLASSNAME) ? sei_tmp.lpClass: NULL,
1059                                (sei_tmp.lpVerb) ? sei_tmp.lpVerb : wszOpen,
1060                                wszParameters, sizeof(wszParameters)/sizeof(WCHAR));
1061
1062         /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
1063         TRACE("SEE_MASK_CLASSNAME->'%s', doc->'%s'\n", debugstr_w(wszParameters), debugstr_w(wszApplicationName));
1064
1065         wcmd[0] = '\0';
1066         done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), wszParameters, wszApplicationName, sei_tmp.lpIDList, NULL);
1067         if (!done && wszApplicationName[0])
1068         {
1069             strcatW(wcmd, wSpace);
1070             strcatW(wcmd, wszApplicationName);
1071         }
1072         retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1073         if (retval > 32)
1074             return TRUE;
1075         else
1076             return FALSE;
1077     }
1078
1079
1080     /* resolve shell shortcuts */
1081     ext = PathFindExtensionW(sei_tmp.lpFile);
1082
1083     if (ext && !strncmpiW(ext, wExtLnk, sizeof(wExtLnk) / sizeof(WCHAR) - 1) &&
1084         (ext[sizeof(wExtLnk) / sizeof(WCHAR) - 1] == '\0' ||
1085          (sei_tmp.lpFile[0] == '"' && ext[sizeof(wExtLnk) / sizeof(WCHAR) - 1] == '"')))        /* or check for: shell_attribs & SFGAO_LINK */
1086     {
1087         HRESULT hr;
1088         BOOL Quoted;
1089
1090         if (wszApplicationName[0] == '"')
1091         {
1092             if (wszApplicationName[strlenW(wszApplicationName) - 1] == '"')
1093             {
1094                 wszApplicationName[strlenW(wszApplicationName) - 1] = '\0';
1095                 Quoted = TRUE;
1096             }
1097             else
1098             {
1099                 Quoted = FALSE;
1100             }
1101         }
1102         else
1103         {
1104             Quoted = FALSE;
1105         }
1106         /* expand paths before reading shell link */
1107         if (ExpandEnvironmentStringsW(Quoted ? sei_tmp.lpFile + 1 : sei_tmp.lpFile, buffer, MAX_PATH))
1108             lstrcpyW(Quoted ? wszApplicationName + 1 : wszApplicationName/*sei_tmp.lpFile*/, buffer);
1109
1110         if (*sei_tmp.lpParameters)
1111             if (ExpandEnvironmentStringsW(sei_tmp.lpParameters, buffer, MAX_PATH))
1112                 lstrcpyW(wszParameters/*sei_tmp.lpParameters*/, buffer);
1113
1114         hr = SHELL_ResolveShortCutW((LPWSTR)(Quoted ? sei_tmp.lpFile + 1 : sei_tmp.lpFile),
1115                                     (LPWSTR)sei_tmp.lpParameters, (LPWSTR)sei_tmp.lpDirectory,
1116                                     sei_tmp.hwnd, sei_tmp.lpVerb?sei_tmp.lpVerb:wszEmpty, &sei_tmp.nShow, (LPITEMIDLIST*)&sei_tmp.lpIDList);
1117         if (Quoted)
1118         {
1119             wszApplicationName[strlenW(wszApplicationName) + 1] = '\0';
1120             wszApplicationName[strlenW(wszApplicationName)] = '"';
1121         }
1122
1123         if (sei->lpIDList)
1124             sei->fMask |= SEE_MASK_IDLIST;
1125
1126         if (SUCCEEDED(hr))
1127         {
1128             /* repeat IDList processing if needed */
1129             if (sei_tmp.fMask & SEE_MASK_IDLIST)
1130             {
1131                 IShellExecuteHookW* pSEH;
1132
1133                 HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
1134
1135                 if (SUCCEEDED(hr))
1136                 {
1137                     hr = IShellExecuteHookW_Execute(pSEH, sei);
1138
1139                     IShellExecuteHookW_Release(pSEH);
1140
1141                     if (hr == S_OK)
1142                         return TRUE;
1143                 }
1144
1145                 TRACE("-- idlist=%p (%s)\n", debugstr_w(sei_tmp.lpIDList), debugstr_w(sei_tmp.lpFile));
1146             }
1147         }
1148     }
1149
1150
1151     /* Has the IDList not yet been translated? */
1152     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1153     {
1154         /* last chance to translate IDList: now also allow CLSID paths */
1155         if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW(sei_tmp.lpIDList, buffer, sizeof(buffer)))) {
1156             if (buffer[0]==':' && buffer[1]==':') {
1157                 /* open shell folder for the specified class GUID */
1158                 strcpyW(wszParameters, buffer);
1159                 strcpyW(wszApplicationName, wExplorer);
1160
1161                 sei_tmp.fMask &= ~SEE_MASK_INVOKEIDLIST;
1162             } else if (HCR_GetExecuteCommandW(0, wszFolder, sei_tmp.lpVerb?sei_tmp.lpVerb:wszOpen, buffer, sizeof(buffer))) {
1163                 SHELL_ArgifyW(wszApplicationName, sizeof(wszApplicationName)/sizeof(WCHAR), buffer, NULL, sei_tmp.lpIDList, NULL);
1164
1165                 sei_tmp.fMask &= ~SEE_MASK_INVOKEIDLIST;
1166             }
1167         }
1168     }
1169
1170     /* expand environment strings */
1171     if (ExpandEnvironmentStringsW(sei_tmp.lpFile, buffer, MAX_PATH))
1172         lstrcpyW(wszApplicationName, buffer);
1173
1174     if (*sei_tmp.lpParameters)
1175         if (ExpandEnvironmentStringsW(sei_tmp.lpParameters, buffer, MAX_PATH))
1176             lstrcpyW(wszParameters, buffer);
1177
1178     if (*sei_tmp.lpDirectory)
1179         if (ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buffer, MAX_PATH))
1180             lstrcpyW(wszDir, buffer);
1181
1182     /* Else, try to execute the filename */
1183     TRACE("execute:%s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1184
1185     /* separate out command line arguments from executable file name */
1186     if (!*sei_tmp.lpParameters) {
1187         /* If the executable path is quoted, handle the rest of the command line as parameters. */
1188         if (sei_tmp.lpFile[0] == '"') {
1189             LPWSTR src = wszApplicationName/*sei_tmp.lpFile*/ + 1;
1190             LPWSTR dst = wfileName;
1191             LPWSTR end;
1192
1193             /* copy the unquoted executable path to 'wfileName' */
1194             while(*src && *src!='"')
1195                 *dst++ = *src++;
1196
1197             *dst = '\0';
1198
1199             if (*src == '"') {
1200                 end = ++src;
1201
1202                 while(isspace(*src))
1203                     ++src;
1204             } else
1205                 end = src;
1206
1207             /* copy the parameter string to 'wszParameters' */
1208             strcpyW(wszParameters, src);
1209
1210             /* terminate previous command string after the quote character */
1211             *end = '\0';
1212         }
1213         else
1214         {
1215             /* If the executable name is not quoted, we have to use this search loop here,
1216                that in CreateProcess() is not sufficient because it does not handle shell links. */
1217             WCHAR buffer[MAX_PATH], xlpFile[MAX_PATH];
1218             LPWSTR space, s;
1219
1220             LPWSTR beg = wszApplicationName/*sei_tmp.lpFile*/;
1221             for(s=beg; (space=strchrW(s, ' ')); s=space+1) {
1222                 int idx = space-sei_tmp.lpFile;
1223                 memcpy(buffer, sei_tmp.lpFile, idx * sizeof(WCHAR));
1224                 buffer[idx] = '\0';
1225
1226                 /*FIXME This finds directory paths if the targeted file name contains spaces. */
1227                 if (SearchPathW(*sei_tmp.lpDirectory? sei_tmp.lpDirectory: NULL, buffer, wszExe, sizeof(xlpFile), xlpFile, NULL))
1228                 {
1229                     /* separate out command from parameter string */
1230                     LPCWSTR p = space + 1;
1231
1232                     while(isspaceW(*p))
1233                         ++p;
1234
1235                     strcpyW(wszParameters, p);
1236                     *space = '\0';
1237
1238                     break;
1239                 }
1240             }
1241
1242             strcpyW(wfileName, sei_tmp.lpFile);
1243         }
1244     } else
1245         strcpyW(wfileName, sei_tmp.lpFile);
1246
1247     lpFile = wfileName;
1248
1249     if (sei_tmp.lpParameters[0]) {
1250         strcatW(wszApplicationName, wSpace);
1251         strcatW(wszApplicationName, wszParameters);
1252     }
1253
1254     /* We set the default to open, and that should generally work.
1255        But that is not really the way the MS docs say to do it. */
1256     if (!sei_tmp.lpVerb)
1257         sei_tmp.lpVerb = wszOpen;
1258
1259     retval = execfunc(wszApplicationName, NULL, FALSE, &sei_tmp, sei);
1260     if (retval > 32)
1261         return TRUE;
1262
1263     /* Else, try to find the executable */
1264     wcmd[0] = '\0';
1265     retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, 1024, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
1266     if (retval > 32)  /* Found */
1267     {
1268         WCHAR wszQuotedCmd[MAX_PATH+2];
1269         /* Must quote to handle case where cmd contains spaces,
1270          * else security hole if malicious user creates executable file "C:\\Program"
1271          */
1272         strcpyW(wszQuotedCmd, wQuote);
1273         strcatW(wszQuotedCmd, wcmd);
1274         strcatW(wszQuotedCmd, wQuote);
1275         if (wszParameters[0]) {
1276             strcatW(wszQuotedCmd, wSpace);
1277             strcatW(wszQuotedCmd, wszParameters);
1278         }
1279         TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(sei_tmp.lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
1280         if (*lpstrProtocol)
1281             retval = execute_from_key(lpstrProtocol, wszApplicationName, env, sei_tmp.lpParameters, execfunc, &sei_tmp, sei);
1282         else
1283             retval = execfunc(wszQuotedCmd, env, FALSE, &sei_tmp, sei);
1284         HeapFree( GetProcessHeap(), 0, env );
1285     }
1286     else if (PathIsURLW((LPWSTR)lpFile))    /* File not found, check for URL */
1287     {
1288         static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
1289         static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
1290         LPWSTR lpstrRes;
1291         INT iSize;
1292
1293         lpstrRes = strchrW(lpFile, ':');
1294         if (lpstrRes)
1295             iSize = lpstrRes - lpFile;
1296         else
1297             iSize = strlenW(lpFile);
1298
1299         TRACE("Got URL: %s\n", debugstr_w(lpFile));
1300         /* Looking for ...protocol\shell\lpOperation\command */
1301         memcpy(lpstrProtocol, lpFile, iSize*sizeof(WCHAR));
1302         lpstrProtocol[iSize] = '\0';
1303         strcatW(lpstrProtocol, wShell);
1304         strcatW(lpstrProtocol, sei_tmp.lpVerb? sei_tmp.lpVerb: wszOpen);
1305         strcatW(lpstrProtocol, wCommand);
1306
1307         /* Remove File Protocol from lpFile */
1308         /* In the case file://path/file     */
1309         if (!strncmpiW(lpFile, wFile, iSize))
1310         {
1311             lpFile += iSize;
1312             while (*lpFile == ':') lpFile++;
1313         }
1314         retval = execute_from_key(lpstrProtocol, lpFile, NULL, sei_tmp.lpParameters, execfunc, &sei_tmp, sei);
1315     }
1316     /* Check if file specified is in the form www.??????.*** */
1317     else if (!strncmpiW(lpFile, wWww, 3))
1318     {
1319         /* if so, append lpFile http:// and call ShellExecute */
1320         WCHAR lpstrTmpFile[256];
1321         strcpyW(lpstrTmpFile, wHttp);
1322         strcatW(lpstrTmpFile, lpFile);
1323         retval = (UINT)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1324     }
1325
1326     TRACE("retval %u\n", retval);
1327
1328     if (retval <= 32)
1329     {
1330         sei->hInstApp = (HINSTANCE)retval;
1331         return FALSE;
1332     }
1333
1334     sei->hInstApp = (HINSTANCE)33;
1335     return TRUE;
1336 }
1337
1338 /*************************************************************************
1339  * ShellExecuteA                        [SHELL32.290]
1340  */
1341 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1342                                LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1343 {
1344     SHELLEXECUTEINFOA sei;
1345     HANDLE hProcess = 0;
1346
1347     TRACE("%p,%s,%s,%s,%s,%d\n",
1348            hWnd, lpOperation, lpFile, lpParameters, lpDirectory, iShowCmd);
1349
1350     sei.cbSize = sizeof(sei);
1351     sei.fMask = 0;
1352     sei.hwnd = hWnd;
1353     sei.lpVerb = lpOperation;
1354     sei.lpFile = lpFile;
1355     sei.lpParameters = lpParameters;
1356     sei.lpDirectory = lpDirectory;
1357     sei.nShow = iShowCmd;
1358     sei.lpIDList = 0;
1359     sei.lpClass = 0;
1360     sei.hkeyClass = 0;
1361     sei.dwHotKey = 0;
1362     sei.hProcess = hProcess;
1363
1364     ShellExecuteExA (&sei);
1365     return sei.hInstApp;
1366 }
1367
1368 /*************************************************************************
1369  * ShellExecuteExA                              [SHELL32.292]
1370  *
1371  */
1372 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1373 {
1374     SHELLEXECUTEINFOW seiW;
1375     BOOL ret;
1376     WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1377
1378     TRACE("%p\n", sei);
1379
1380     memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1381
1382     if (sei->lpVerb)
1383         seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1384
1385     if (sei->lpFile)
1386         seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1387
1388     if (sei->lpParameters)
1389         seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1390
1391     if (sei->lpDirectory)
1392         seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1393
1394     if ((sei->fMask & SEE_MASK_CLASSNAME) && sei->lpClass)
1395         seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1396     else
1397         seiW.lpClass = NULL;
1398
1399     ret = ShellExecuteExW32 (&seiW, SHELL_ExecuteW);
1400
1401     sei->hInstApp = seiW.hInstApp;
1402
1403     if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
1404         sei->hProcess = seiW.hProcess;
1405
1406     if (wVerb) SHFree(wVerb);
1407     if (wFile) SHFree(wFile);
1408     if (wParameters) SHFree(wParameters);
1409     if (wDirectory) SHFree(wDirectory);
1410     if (wClass) SHFree(wClass);
1411
1412     return ret;
1413 }
1414
1415 /*************************************************************************
1416  * ShellExecuteExW                              [SHELL32.293]
1417  *
1418  */
1419 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1420 {
1421     return  ShellExecuteExW32 (sei, SHELL_ExecuteW);
1422 }
1423
1424 /*************************************************************************
1425  * ShellExecuteW                        [SHELL32.294]
1426  * from shellapi.h
1427  * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1428  * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1429  */
1430 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1431                                LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1432 {
1433     SHELLEXECUTEINFOW sei;
1434     HANDLE hProcess = 0;
1435
1436     TRACE("\n");
1437     sei.cbSize = sizeof(sei);
1438     sei.fMask = 0;
1439     sei.hwnd = hwnd;
1440     sei.lpVerb = lpOperation;
1441     sei.lpFile = lpFile;
1442     sei.lpParameters = lpParameters;
1443     sei.lpDirectory = lpDirectory;
1444     sei.nShow = nShowCmd;
1445     sei.lpIDList = 0;
1446     sei.lpClass = 0;
1447     sei.hkeyClass = 0;
1448     sei.dwHotKey = 0;
1449     sei.hProcess = hProcess;
1450
1451     ShellExecuteExW32 (&sei, SHELL_ExecuteW);
1452     return sei.hInstApp;
1453 }