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