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