ntdll: Avoid the close-on-exec race with recvmsg() on kernels that support this.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 "shell32_main.h"
46 #include "pidl.h"
47 #include "shresdef.h"
48
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(exec);
52
53 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 typedef UINT_PTR (*SHELL_ExecuteW32)(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
63                             const SHELLEXECUTEINFOW *sei, LPSHELLEXECUTEINFOW sei_out);
64
65
66 /***********************************************************************
67  *      SHELL_ArgifyW [Internal]
68  *
69  * this function is supposed to expand the escape sequences found in the registry
70  * some diving reported that the following were used:
71  * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
72  *      %1 file
73  *      %2 printer
74  *      %3 driver
75  *      %4 port
76  * %I address of a global item ID (explorer switch /idlist)
77  * %L seems to be %1 as long filename followed by the 8+3 variation
78  * %S ???
79  * %* all following parameters (see batfile)
80  *
81  */
82 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args, DWORD* out_len)
83 {
84     WCHAR   xlpFile[1024];
85     BOOL    done = FALSE;
86     BOOL    found_p1 = FALSE;
87     PWSTR   res = out;
88     PCWSTR  cmd;
89     DWORD   used = 0;
90
91     TRACE("%p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
92           debugstr_w(lpFile), pidl, args);
93
94     while (*fmt)
95     {
96         if (*fmt == '%')
97         {
98             switch (*++fmt)
99             {
100             case '\0':
101             case '%':
102                 used++;
103                 if (used < len)
104                     *res++ = '%';
105                 break;
106
107             case '2':
108             case '3':
109             case '4':
110             case '5':
111             case '6':
112             case '7':
113             case '8':
114             case '9':
115             case '0':
116             case '*':
117                 if (args)
118                 {
119                     if (*fmt == '*')
120                     {
121                         used++;
122                         if (used < len)
123                             *res++ = '"';
124                         while(*args)
125                         {
126                             used++;
127                             if (used < len)
128                                 *res++ = *args++;
129                             else
130                                 args++;
131                         }
132                         used++;
133                         if (used < len)
134                             *res++ = '"';
135                     }
136                     else
137                     {
138                         while(*args && !isspace(*args))
139                         {
140                             used++;
141                             if (used < len)
142                                 *res++ = *args++;
143                             else
144                                 args++;
145                         }
146
147                         while(isspace(*args))
148                             ++args;
149                     }
150                     break;
151                 }
152                 /* else fall through */
153             case '1':
154                 if (!done || (*fmt == '1'))
155                 {
156                     /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
157                     if (SearchPathW(NULL, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
158                         cmd = xlpFile;
159                     else
160                         cmd = lpFile;
161
162                     used += strlenW(cmd);
163                     if (used < len)
164                     {
165                         strcpyW(res, cmd);
166                         res += strlenW(cmd);
167                     }
168                 }
169                 found_p1 = TRUE;
170                 break;
171
172             /*
173              * IE uses this a lot for activating things such as windows media
174              * player. This is not verified to be fully correct but it appears
175              * to work just fine.
176              */
177             case 'l':
178             case 'L':
179                 if (lpFile) {
180                     used += strlenW(lpFile);
181                     if (used < len)
182                     {
183                         strcpyW(res, lpFile);
184                         res += strlenW(lpFile);
185                     }
186                 }
187                 found_p1 = TRUE;
188                 break;
189
190             case 'i':
191             case 'I':
192                 if (pidl) {
193                     INT chars = 0;
194                     /* %p should not exceed 8, maybe 16 when looking forward to 64bit.
195                      * allowing a buffer of 100 should more than exceed all needs */
196                     WCHAR buf[100];
197                     LPVOID  pv;
198                     HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
199                     pv = SHLockShared(hmem, 0);
200                     chars = sprintfW(buf, wszILPtr, pv);
201                     if (chars >= sizeof(buf)/sizeof(WCHAR))
202                         ERR("pidl format buffer too small!\n");
203                     used += chars;
204                     if (used < len)
205                     {
206                         strcpyW(res,buf);
207                         res += chars;
208                     }
209                     SHUnlockShared(pv);
210                 }
211                 found_p1 = TRUE;
212                 break;
213
214             default:
215                 /*
216                  * Check if this is an env-variable here...
217                  */
218
219                 /* Make sure that we have at least one more %.*/
220                 if (strchrW(fmt, '%'))
221                 {
222                     WCHAR   tmpBuffer[1024];
223                     PWSTR   tmpB = tmpBuffer;
224                     WCHAR   tmpEnvBuff[MAX_PATH];
225                     DWORD   envRet;
226
227                     while (*fmt != '%')
228                         *tmpB++ = *fmt++;
229                     *tmpB++ = 0;
230
231                     TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
232
233                     envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
234                     if (envRet == 0 || envRet > MAX_PATH)
235                     {
236                         used += strlenW(tmpBuffer);
237                         if (used < len)
238                         {
239                             strcpyW( res, tmpBuffer );
240                             res += strlenW(tmpBuffer);
241                         }
242                     }
243                     else
244                     {
245                         used += strlenW(tmpEnvBuff);
246                         if (used < len)
247                         {
248                             strcpyW( res, tmpEnvBuff );
249                             res += strlenW(tmpEnvBuff);
250                         }
251                     }
252                 }
253                 done = TRUE;
254                 break;
255             }
256             /* Don't skip past terminator (catch a single '%' at the end) */
257             if (*fmt != '\0')
258             {
259                 fmt++;
260             }
261         }
262         else
263         {
264             used ++;
265             if (used < len) 
266                 *res++ = *fmt++;
267             else
268                 fmt++;
269         }
270     }
271
272     *res = '\0';
273     TRACE("used %i of %i space\n",used,len);
274     if (out_len)
275         *out_len = used;
276
277     return found_p1;
278 }
279
280 static HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
281 {
282     STRRET strret;
283     IShellFolder* desktop;
284
285     HRESULT hr = SHGetDesktopFolder(&desktop);
286
287     if (SUCCEEDED(hr)) {
288         hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
289
290         if (SUCCEEDED(hr))
291             StrRetToStrNW(pszPath, uOutSize, &strret, pidl);
292
293         IShellFolder_Release(desktop);
294     }
295
296     return hr;
297 }
298
299 /*************************************************************************
300  *      SHELL_ExecuteW [Internal]
301  *
302  */
303 static UINT_PTR SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
304                             const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
305 {
306     STARTUPINFOW  startup;
307     PROCESS_INFORMATION info;
308     UINT_PTR retval = SE_ERR_NOASSOC;
309     UINT gcdret = 0;
310     WCHAR curdir[MAX_PATH];
311     DWORD dwCreationFlags;
312     const WCHAR *lpDirectory = NULL;
313
314     TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
315
316     /* make sure we don't fail the CreateProcess if the calling app passes in
317      * a bad working directory */
318     if (psei->lpDirectory && psei->lpDirectory[0])
319     {
320         DWORD attr = GetFileAttributesW(psei->lpDirectory);
321         if (attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_DIRECTORY)
322             lpDirectory = psei->lpDirectory;
323     }
324
325     /* ShellExecute specifies the command from psei->lpDirectory
326      * if present. Not from the current dir as CreateProcess does */
327     if( lpDirectory )
328         if( ( gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
329             if( !SetCurrentDirectoryW( lpDirectory))
330                 ERR("cannot set directory %s\n", debugstr_w(lpDirectory));
331     ZeroMemory(&startup,sizeof(STARTUPINFOW));
332     startup.cb = sizeof(STARTUPINFOW);
333     startup.dwFlags = STARTF_USESHOWWINDOW;
334     startup.wShowWindow = psei->nShow;
335     dwCreationFlags = CREATE_UNICODE_ENVIRONMENT;
336     if (psei->fMask & SEE_MASK_NO_CONSOLE)
337         dwCreationFlags |= CREATE_NEW_CONSOLE;
338     if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, dwCreationFlags, env,
339                        lpDirectory, &startup, &info))
340     {
341         /* Give 30 seconds to the app to come up, if desired. Probably only needed
342            when starting app immediately before making a DDE connection. */
343         if (shWait)
344             if (WaitForInputIdle( info.hProcess, 30000 ) == WAIT_FAILED)
345                 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
346         retval = 33;
347         if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
348             psei_out->hProcess = info.hProcess;
349         else
350             CloseHandle( info.hProcess );
351         CloseHandle( info.hThread );
352     }
353     else if ((retval = GetLastError()) >= 32)
354     {
355         TRACE("CreateProcess returned error %ld\n", retval);
356         retval = ERROR_BAD_FORMAT;
357     }
358
359     TRACE("returning %lu\n", retval);
360
361     psei_out->hInstApp = (HINSTANCE)retval;
362     if( gcdret )
363         if( !SetCurrentDirectoryW( curdir))
364             ERR("cannot return to directory %s\n", debugstr_w(curdir));
365
366     return retval;
367 }
368
369
370 /***********************************************************************
371  *           SHELL_BuildEnvW    [Internal]
372  *
373  * Build the environment for the new process, adding the specified
374  * path to the PATH variable. Returned pointer must be freed by caller.
375  */
376 static void *SHELL_BuildEnvW( const WCHAR *path )
377 {
378     static const WCHAR wPath[] = {'P','A','T','H','=',0};
379     WCHAR *strings, *new_env;
380     WCHAR *p, *p2;
381     int total = strlenW(path) + 1;
382     BOOL got_path = FALSE;
383
384     if (!(strings = GetEnvironmentStringsW())) return NULL;
385     p = strings;
386     while (*p)
387     {
388         int len = strlenW(p) + 1;
389         if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
390         total += len;
391         p += len;
392     }
393     if (!got_path) total += 5;  /* we need to create PATH */
394     total++;  /* terminating null */
395
396     if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
397     {
398         FreeEnvironmentStringsW( strings );
399         return NULL;
400     }
401     p = strings;
402     p2 = new_env;
403     while (*p)
404     {
405         int len = strlenW(p) + 1;
406         memcpy( p2, p, len * sizeof(WCHAR) );
407         if (!strncmpiW( p, wPath, 5 ))
408         {
409             p2[len - 1] = ';';
410             strcpyW( p2 + len, path );
411             p2 += strlenW(path) + 1;
412         }
413         p += len;
414         p2 += len;
415     }
416     if (!got_path)
417     {
418         strcpyW( p2, wPath );
419         strcatW( p2, path );
420         p2 += strlenW(p2) + 1;
421     }
422     *p2 = 0;
423     FreeEnvironmentStringsW( strings );
424     return new_env;
425 }
426
427
428 /***********************************************************************
429  *           SHELL_TryAppPathW  [Internal]
430  *
431  * Helper function for SHELL_FindExecutable
432  * @param lpResult - pointer to a buffer of size MAX_PATH
433  * On entry: szName is a filename (probably without path separators).
434  * On exit: if szName found in "App Path", place full path in lpResult, and return true
435  */
436 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
437 {
438     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',
439         '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','A','p','p',' ','P','a','t','h','s','\\',0};
440     static const WCHAR wPath[] = {'P','a','t','h',0};
441     HKEY hkApp = 0;
442     WCHAR buffer[1024];
443     LONG len;
444     LONG res;
445     BOOL found = FALSE;
446
447     if (env) *env = NULL;
448     strcpyW(buffer, wszKeyAppPaths);
449     strcatW(buffer, szName);
450     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
451     if (res) goto end;
452
453     len = MAX_PATH*sizeof(WCHAR);
454     res = RegQueryValueW(hkApp, NULL, lpResult, &len);
455     if (res) goto end;
456     found = TRUE;
457
458     if (env)
459     {
460         DWORD count = sizeof(buffer);
461         if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
462             *env = SHELL_BuildEnvW( buffer );
463     }
464
465 end:
466     if (hkApp) RegCloseKey(hkApp);
467     return found;
468 }
469
470 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
471 {
472     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
473     HKEY hkeyClass;
474     WCHAR verb[MAX_PATH];
475
476     if (RegOpenKeyExW(HKEY_CLASSES_ROOT, filetype, 0, 0x02000000, &hkeyClass))
477         return SE_ERR_NOASSOC;
478     if (!HCR_GetDefaultVerbW(hkeyClass, lpOperation, verb, sizeof(verb)/sizeof(verb[0])))
479         return SE_ERR_NOASSOC;
480     RegCloseKey(hkeyClass);
481
482     /* Looking for ...buffer\shell\<verb>\command */
483     strcatW(filetype, wszShell);
484     strcatW(filetype, verb);
485     strcatW(filetype, wCommand);
486
487     if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
488                        &commandlen) == ERROR_SUCCESS)
489     {
490         commandlen /= sizeof(WCHAR);
491         if (key) strcpyW(key, filetype);
492 #if 0
493         LPWSTR tmp;
494         WCHAR param[256];
495         LONG paramlen = sizeof(param);
496         static const WCHAR wSpace[] = {' ',0};
497
498         /* FIXME: it seems all Windows version don't behave the same here.
499          * the doc states that this ddeexec information can be found after
500          * the exec names.
501          * on Win98, it doesn't appear, but I think it does on Win2k
502          */
503         /* Get the parameters needed by the application
504            from the associated ddeexec key */
505         tmp = strstrW(filetype, wCommand);
506         tmp[0] = '\0';
507         strcatW(filetype, wDdeexec);
508         if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, param,
509                                      &paramlen) == ERROR_SUCCESS)
510         {
511             paramlen /= sizeof(WCHAR);
512             strcatW(command, wSpace);
513             strcatW(command, param);
514             commandlen += paramlen;
515         }
516 #endif
517
518         command[commandlen] = '\0';
519
520         return 33; /* FIXME see SHELL_FindExecutable() */
521     }
522
523     return SE_ERR_NOASSOC;
524 }
525
526 /*************************************************************************
527  *      SHELL_FindExecutable [Internal]
528  *
529  * Utility for code sharing between FindExecutable and ShellExecute
530  * in:
531  *      lpFile the name of a file
532  *      lpOperation the operation on it (open)
533  * out:
534  *      lpResult a buffer, big enough :-(, to store the command to do the
535  *              operation on the file
536  *      key a buffer, big enough, to get the key name to do actually the
537  *              command (it'll be used afterwards for more information
538  *              on the operation)
539  */
540 static UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
541                                  LPWSTR lpResult, int resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
542 {
543     static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
544     static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
545     static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
546     WCHAR *extension = NULL; /* pointer to file extension */
547     WCHAR filetype[256];     /* registry name for this filetype */
548     LONG  filetypelen = sizeof(filetype); /* length of above */
549     WCHAR command[1024];     /* command from registry */
550     WCHAR wBuffer[256];      /* Used to GetProfileString */
551     UINT  retval = SE_ERR_NOASSOC;
552     WCHAR *tok;              /* token pointer */
553     WCHAR xlpFile[256];      /* result of SearchPath */
554     DWORD attribs;           /* file attributes */
555
556     TRACE("%s\n", debugstr_w(lpFile));
557
558     if (!lpResult)
559         return ERROR_INVALID_PARAMETER;
560
561     xlpFile[0] = '\0';
562     lpResult[0] = '\0'; /* Start off with an empty return string */
563     if (key) *key = '\0';
564
565     /* trap NULL parameters on entry */
566     if (!lpFile)
567     {
568         WARN("(lpFile=%s,lpResult=%s): NULL parameter\n",
569              debugstr_w(lpFile), debugstr_w(lpResult));
570         return ERROR_FILE_NOT_FOUND; /* File not found. Close enough, I guess. */
571     }
572
573     if (SHELL_TryAppPathW( lpFile, lpResult, env ))
574     {
575         TRACE("found %s via App Paths\n", debugstr_w(lpResult));
576         return 33;
577     }
578
579     if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
580     {
581         TRACE("SearchPathW returned non-zero\n");
582         lpFile = xlpFile;
583         /* Hey, isn't this value ignored?  Why make this call?  Shouldn't we return here?  --dank*/
584     }
585
586     attribs = GetFileAttributesW(lpFile);
587     if (attribs!=INVALID_FILE_ATTRIBUTES && (attribs&FILE_ATTRIBUTE_DIRECTORY))
588     {
589        strcpyW(filetype, wszFolder);
590        filetypelen = 6;    /* strlen("Folder") */
591     }
592     else
593     {
594         /* Did we get something? Anything? */
595         if (xlpFile[0]==0)
596         {
597             TRACE("Returning SE_ERR_FNF\n");
598             return SE_ERR_FNF;
599         }
600         /* First thing we need is the file's extension */
601         extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
602         /* File->Run in progman uses */
603         /* .\FILE.EXE :( */
604         TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
605
606         if (extension == NULL || extension[1]==0)
607         {
608             WARN("Returning SE_ERR_NOASSOC\n");
609             return SE_ERR_NOASSOC;
610         }
611
612         /* Three places to check: */
613         /* 1. win.ini, [windows], programs (NB no leading '.') */
614         /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
615         /* 3. win.ini, [extensions], extension (NB no leading '.' */
616         /* All I know of the order is that registry is checked before */
617         /* extensions; however, it'd make sense to check the programs */
618         /* section first, so that's what happens here. */
619
620         /* See if it's a program - if GetProfileString fails, we skip this
621          * section. Actually, if GetProfileString fails, we've probably
622          * got a lot more to worry about than running a program... */
623         if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
624         {
625             CharLowerW(wBuffer);
626             tok = wBuffer;
627             while (*tok)
628             {
629                 WCHAR *p = tok;
630                 while (*p && *p != ' ' && *p != '\t') p++;
631                 if (*p)
632                 {
633                     *p++ = 0;
634                     while (*p == ' ' || *p == '\t') p++;
635                 }
636
637                 if (strcmpiW(tok, &extension[1]) == 0) /* have to skip the leading "." */
638                 {
639                     strcpyW(lpResult, xlpFile);
640                     /* Need to perhaps check that the file has a path
641                      * attached */
642                     TRACE("found %s\n", debugstr_w(lpResult));
643                     return 33;
644                     /* Greater than 32 to indicate success */
645                 }
646                 tok = p;
647             }
648         }
649
650         /* Check registry */
651         if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, filetype,
652                            &filetypelen) == ERROR_SUCCESS)
653         {
654             filetypelen /= sizeof(WCHAR);
655             if (filetypelen == sizeof(filetype)/sizeof(WCHAR))
656                 filetypelen--;
657             filetype[filetypelen] = '\0';
658             TRACE("File type: %s\n", debugstr_w(filetype));
659         }
660         else
661         {
662             *filetype = '\0';
663             filetypelen = 0;
664         }
665     }
666
667     if (*filetype)
668     {
669         /* pass the operation string to SHELL_FindExecutableByOperation() */
670         filetype[filetypelen] = '\0';
671         retval = SHELL_FindExecutableByOperation(lpOperation, key, filetype, command, sizeof(command));
672
673         if (retval > 32)
674         {
675             DWORD finishedLen;
676             SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args, &finishedLen);
677             if (finishedLen > resultLen)
678                 ERR("Argify buffer not large enough.. truncated\n");
679
680             /* Remove double quotation marks and command line arguments */
681             if (*lpResult == '"')
682             {
683                 WCHAR *p = lpResult;
684                 while (*(p + 1) != '"')
685                 {
686                     *p = *(p + 1);
687                     p++;
688                 }
689                 *p = '\0';
690             }
691             else
692             {
693                 /* Truncate on first space */
694                 WCHAR *p = lpResult;
695                 while (*p != ' ' && *p != '\0')
696                     p++;
697                 *p='\0';
698             }
699         }
700     }
701     else /* Check win.ini */
702     {
703         static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
704
705         /* Toss the leading dot */
706         extension++;
707         if (GetProfileStringW(wExtensions, extension, wszEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
708         {
709             if (strlenW(command) != 0)
710             {
711                 strcpyW(lpResult, command);
712                 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
713                 if (tok != NULL)
714                 {
715                     tok[0] = '\0';
716                     strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
717                     tok = strchrW(command, '^'); /* see above */
718                     if ((tok != NULL) && (strlenW(tok)>5))
719                     {
720                         strcatW(lpResult, &tok[5]);
721                     }
722                 }
723                 retval = 33; /* FIXME - see above */
724             }
725         }
726     }
727
728     TRACE("returning %s\n", debugstr_w(lpResult));
729     return retval;
730 }
731
732 /******************************************************************
733  *              dde_cb
734  *
735  * callback for the DDE connection. not really useful
736  */
737 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
738                                 HSZ hsz1, HSZ hsz2, HDDEDATA hData,
739                                 ULONG_PTR dwData1, ULONG_PTR dwData2)
740 {
741     TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
742            uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
743     return NULL;
744 }
745
746 /******************************************************************
747  *              dde_connect
748  *
749  * ShellExecute helper. Used to do an operation with a DDE connection
750  *
751  * Handles both the direct connection (try #1), and if it fails,
752  * launching an application and trying (#2) to connect to it
753  *
754  */
755 static unsigned dde_connect(const WCHAR* key, const WCHAR* start, WCHAR* ddeexec,
756                             const WCHAR* lpFile, WCHAR *env,
757                             LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
758                             const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
759 {
760     static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
761     static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
762     WCHAR       regkey[256];
763     WCHAR *     endkey = regkey + strlenW(key);
764     WCHAR       app[256], topic[256], ifexec[256], res[256];
765     LONG        applen, topiclen, ifexeclen;
766     WCHAR *     exec;
767     DWORD       ddeInst = 0;
768     DWORD       tid;
769     DWORD       resultLen;
770     HSZ         hszApp, hszTopic;
771     HCONV       hConv;
772     HDDEDATA    hDdeData;
773     unsigned    ret = SE_ERR_NOASSOC;
774     BOOL unicode = !(GetVersion() & 0x80000000);
775
776     strcpyW(regkey, key);
777     strcpyW(endkey, wApplication);
778     applen = sizeof(app);
779     if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, app, &applen) != ERROR_SUCCESS)
780     {
781         WCHAR command[1024], fullpath[MAX_PATH];
782         static const WCHAR wSo[] = { '.','s','o',0 };
783         int sizeSo = sizeof(wSo)/sizeof(WCHAR);
784         LPWSTR ptr = NULL;
785         DWORD ret = 0;
786
787         /* Get application command from start string and find filename of application */
788         if (*start == '"')
789         {
790             strcpyW(command, start+1);
791             if ((ptr = strchrW(command, '"')))
792                 *ptr = 0;
793             ret = SearchPathW(NULL, command, wszExe, sizeof(fullpath)/sizeof(WCHAR), fullpath, &ptr);
794         }
795         else
796         {
797             LPWSTR p,space;
798             for (p=(LPWSTR)start; (space=strchrW(p, ' ')); p=space+1)
799             {
800                 int idx = space-start;
801                 memcpy(command, start, idx*sizeof(WCHAR));
802                 command[idx] = '\0';
803                 if ((ret = SearchPathW(NULL, command, wszExe, sizeof(fullpath)/sizeof(WCHAR), fullpath, &ptr)))
804                     break;
805             }
806             if (!ret)
807                 ret = SearchPathW(NULL, start, wszExe, sizeof(fullpath)/sizeof(WCHAR), fullpath, &ptr);
808         }
809
810         if (!ret)
811         {
812             ERR("Unable to find application path for command %s\n", debugstr_w(start));
813             return ERROR_ACCESS_DENIED;
814         }
815         strcpyW(app, ptr);
816
817         /* Remove extensions (including .so) */
818         ptr = app + strlenW(app) - (sizeSo-1);
819         if (strlenW(app) >= sizeSo &&
820             !strcmpW(ptr, wSo))
821             *ptr = 0;
822
823         ptr = strrchrW(app, '.');
824         assert(ptr);
825         *ptr = 0;
826     }
827
828     strcpyW(endkey, wTopic);
829     topiclen = sizeof(topic);
830     if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, topic, &topiclen) != ERROR_SUCCESS)
831     {
832         static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
833         strcpyW(topic, wSystem);
834     }
835
836     if (unicode)
837     {
838         if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
839             return 2;
840     }
841     else
842     {
843         if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
844             return 2;
845     }
846
847     hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
848     hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
849
850     hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
851     exec = ddeexec;
852     if (!hConv)
853     {
854         static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
855         TRACE("Launching %s\n", debugstr_w(start));
856         ret = execfunc(start, env, TRUE, psei, psei_out);
857         if (ret <= 32)
858         {
859             TRACE("Couldn't launch\n");
860             goto error;
861         }
862         hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
863         if (!hConv)
864         {
865             TRACE("Couldn't connect. ret=%d\n", ret);
866             DdeUninitialize(ddeInst);
867             SetLastError(ERROR_DDE_FAIL);
868             return 30; /* whatever */
869         }
870         strcpyW(endkey, wIfexec);
871         ifexeclen = sizeof(ifexec);
872         if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, ifexec, &ifexeclen) == ERROR_SUCCESS)
873         {
874             exec = ifexec;
875         }
876     }
877
878     SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline, &resultLen);
879     if (resultLen > sizeof(res)/sizeof(WCHAR))
880         ERR("Argify buffer not large enough, truncated\n");
881     TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
882
883     /* It's documented in the KB 330337 that IE has a bug and returns
884      * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
885      */
886     if (unicode)
887         hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
888                                          XTYP_EXECUTE, 30000, &tid);
889     else
890     {
891         DWORD lenA = WideCharToMultiByte(CP_ACP, 0, res, -1, NULL, 0, NULL, NULL);
892         char *resA = HeapAlloc(GetProcessHeap(), 0, lenA);
893         WideCharToMultiByte(CP_ACP, 0, res, -1, resA, lenA, NULL, NULL);
894         hDdeData = DdeClientTransaction( (LPBYTE)resA, lenA, hConv, 0L, 0,
895                                          XTYP_EXECUTE, 10000, &tid );
896         HeapFree(GetProcessHeap(), 0, resA);
897     }
898     if (hDdeData)
899         DdeFreeDataHandle(hDdeData);
900     else
901         WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
902     ret = 33;
903
904     DdeDisconnect(hConv);
905
906  error:
907     DdeUninitialize(ddeInst);
908
909     return ret;
910 }
911
912 /*************************************************************************
913  *      execute_from_key [Internal]
914  */
915 static UINT_PTR execute_from_key(LPCWSTR key, LPCWSTR lpFile, WCHAR *env, LPCWSTR szCommandline,
916                              LPCWSTR executable_name,
917                              SHELL_ExecuteW32 execfunc,
918                              LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
919 {
920     static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
921     static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
922     WCHAR cmd[256], param[1024], ddeexec[256];
923     LONG cmdlen = sizeof(cmd), ddeexeclen = sizeof(ddeexec);
924     UINT_PTR retval = SE_ERR_NOASSOC;
925     DWORD resultLen;
926     LPWSTR tmp;
927
928     TRACE("%s %s %s %s %s\n", debugstr_w(key), debugstr_w(lpFile), debugstr_w(env),
929            debugstr_w(szCommandline), debugstr_w(executable_name));
930
931     cmd[0] = '\0';
932     param[0] = '\0';
933
934     /* Get the application from the registry */
935     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
936     {
937         TRACE("got cmd: %s\n", debugstr_w(cmd));
938
939         /* Is there a replace() function anywhere? */
940         cmdlen /= sizeof(WCHAR);
941         if (cmdlen >= sizeof(cmd)/sizeof(WCHAR))
942             cmdlen = sizeof(cmd)/sizeof(WCHAR)-1;
943         cmd[cmdlen] = '\0';
944         SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline, &resultLen);
945         if (resultLen > sizeof(param)/sizeof(WCHAR))
946             ERR("Argify buffer not large enough, truncating\n");
947     }
948
949     /* Get the parameters needed by the application
950        from the associated ddeexec key */
951     tmp = strstrW(key, wCommand);
952     assert(tmp);
953     strcpyW(tmp, wDdeexec);
954
955     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ddeexec, &ddeexeclen) == ERROR_SUCCESS)
956     {
957         TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(ddeexec));
958         if (!param[0]) strcpyW(param, executable_name);
959         retval = dde_connect(key, param, ddeexec, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
960     }
961     else if (param[0])
962     {
963         TRACE("executing: %s\n", debugstr_w(param));
964         retval = execfunc(param, env, FALSE, psei, psei_out);
965     }
966     else
967         WARN("Nothing appropriate found for %s\n", debugstr_w(key));
968
969     return retval;
970 }
971
972 /*************************************************************************
973  * FindExecutableA                      [SHELL32.@]
974  */
975 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
976 {
977     HINSTANCE retval;
978     WCHAR *wFile = NULL, *wDirectory = NULL;
979     WCHAR wResult[MAX_PATH];
980
981     if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
982     if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
983
984     retval = FindExecutableW(wFile, wDirectory, wResult);
985     WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
986     SHFree( wFile );
987     SHFree( wDirectory );
988
989     TRACE("returning %s\n", lpResult);
990     return retval;
991 }
992
993 /*************************************************************************
994  * FindExecutableW                      [SHELL32.@]
995  *
996  * This function returns the executable associated with the specified file
997  * for the default verb.
998  *
999  * PARAMS
1000  *  lpFile   [I] The file to find the association for. This must refer to
1001  *               an existing file otherwise FindExecutable fails and returns
1002  *               SE_ERR_FNF.
1003  *  lpResult [O] Points to a buffer into which the executable path is
1004  *               copied. This parameter must not be NULL otherwise
1005  *               FindExecutable() segfaults. The buffer must be of size at
1006  *               least MAX_PATH characters.
1007  *
1008  * RETURNS
1009  *  A value greater than 32 on success, less than or equal to 32 otherwise.
1010  *  See the SE_ERR_* constants.
1011  *
1012  * NOTES
1013  *  On Windows XP and 2003, FindExecutable() seems to first convert the
1014  *  filename into 8.3 format, thus taking into account only the first three
1015  *  characters of the extension, and expects to find an association for those.
1016  *  However other Windows versions behave sanely.
1017  */
1018 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
1019 {
1020     UINT_PTR retval = SE_ERR_NOASSOC;
1021     WCHAR old_dir[1024];
1022
1023     TRACE("File %s, Dir %s\n", debugstr_w(lpFile), debugstr_w(lpDirectory));
1024
1025     lpResult[0] = '\0'; /* Start off with an empty return string */
1026     if (lpFile == NULL)
1027         return (HINSTANCE)SE_ERR_FNF;
1028
1029     if (lpDirectory)
1030     {
1031         GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
1032         SetCurrentDirectoryW(lpDirectory);
1033     }
1034
1035     retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
1036
1037     TRACE("returning %s\n", debugstr_w(lpResult));
1038     if (lpDirectory)
1039         SetCurrentDirectoryW(old_dir);
1040     return (HINSTANCE)retval;
1041 }
1042
1043 /* FIXME: is this already implemented somewhere else? */
1044 static HKEY ShellExecute_GetClassKey( const SHELLEXECUTEINFOW *sei )
1045 {
1046     LPCWSTR ext = NULL, lpClass = NULL;
1047     LPWSTR cls = NULL;
1048     DWORD type = 0, sz = 0;
1049     HKEY hkey = 0;
1050     LONG r;
1051
1052     if (sei->fMask & SEE_MASK_CLASSALL)
1053         return sei->hkeyClass;
1054  
1055     if (sei->fMask & SEE_MASK_CLASSNAME)
1056         lpClass = sei->lpClass;
1057     else
1058     {
1059         ext = PathFindExtensionW( sei->lpFile );
1060         TRACE("ext = %s\n", debugstr_w( ext ) );
1061         if (!ext)
1062             return hkey;
1063
1064         r = RegOpenKeyW( HKEY_CLASSES_ROOT, ext, &hkey );
1065         if (r != ERROR_SUCCESS )
1066             return hkey;
1067
1068         r = RegQueryValueExW( hkey, NULL, 0, &type, NULL, &sz );
1069         if ( r == ERROR_SUCCESS && type == REG_SZ )
1070         {
1071             sz += sizeof (WCHAR);
1072             cls = HeapAlloc( GetProcessHeap(), 0, sz );
1073             cls[0] = 0;
1074             RegQueryValueExW( hkey, NULL, 0, &type, (LPBYTE) cls, &sz );
1075         }
1076
1077         RegCloseKey( hkey );
1078         lpClass = cls;
1079     }
1080
1081     TRACE("class = %s\n", debugstr_w(lpClass) );
1082
1083     hkey = 0;
1084     if ( lpClass )
1085         RegOpenKeyW( HKEY_CLASSES_ROOT, lpClass, &hkey );
1086
1087     HeapFree( GetProcessHeap(), 0, cls );
1088
1089     return hkey;
1090 }
1091
1092 static IDataObject *shellex_get_dataobj( LPSHELLEXECUTEINFOW sei )
1093 {
1094     LPCITEMIDLIST pidllast = NULL;
1095     IDataObject *dataobj = NULL;
1096     IShellFolder *shf = NULL;
1097     LPITEMIDLIST pidl = NULL;
1098     HRESULT r;
1099
1100     if (sei->fMask & SEE_MASK_CLASSALL)
1101         pidl = sei->lpIDList;
1102     else
1103     {
1104         WCHAR fullpath[MAX_PATH];
1105         BOOL ret;
1106
1107         fullpath[0] = 0;
1108         ret = GetFullPathNameW( sei->lpFile, MAX_PATH, fullpath, NULL );
1109         if (!ret)
1110             goto end;
1111
1112         pidl = ILCreateFromPathW( fullpath );
1113     }
1114
1115     r = SHBindToParent( pidl, &IID_IShellFolder, (LPVOID*)&shf, &pidllast );
1116     if ( FAILED( r ) )
1117         goto end;
1118
1119     IShellFolder_GetUIObjectOf( shf, NULL, 1, &pidllast,
1120                                 &IID_IDataObject, NULL, (LPVOID*) &dataobj );
1121
1122 end:
1123     if ( pidl != sei->lpIDList )
1124         ILFree( pidl );
1125     if ( shf )
1126         IShellFolder_Release( shf );
1127     return dataobj;
1128 }
1129
1130 static HRESULT shellex_run_context_menu_default( IShellExtInit *obj,
1131                                                  LPSHELLEXECUTEINFOW sei )
1132 {
1133     IContextMenu *cm = NULL;
1134     CMINVOKECOMMANDINFOEX ici;
1135     MENUITEMINFOW info;
1136     WCHAR string[0x80];
1137     INT i, n, def = -1;
1138     HMENU hmenu = 0;
1139     HRESULT r;
1140
1141     TRACE("%p %p\n", obj, sei );
1142
1143     r = IShellExtInit_QueryInterface( obj, &IID_IContextMenu, (LPVOID*) &cm );
1144     if ( FAILED( r ) )
1145         return r;
1146
1147     hmenu = CreateMenu();
1148     if ( !hmenu )
1149         goto end;
1150
1151     /* the number of the last menu added is returned in r */
1152     r = IContextMenu_QueryContextMenu( cm, hmenu, 0, 0x20, 0x7fff, CMF_DEFAULTONLY );
1153     if ( FAILED( r ) )
1154         goto end;
1155
1156     n = GetMenuItemCount( hmenu );
1157     for ( i = 0; i < n; i++ )
1158     {
1159         memset( &info, 0, sizeof info );
1160         info.cbSize = sizeof info;
1161         info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_STATE | MIIM_DATA | MIIM_ID;
1162         info.dwTypeData = string;
1163         info.cch = sizeof string;
1164         string[0] = 0;
1165         GetMenuItemInfoW( hmenu, i, TRUE, &info );
1166
1167         TRACE("menu %d %s %08x %08lx %08x %08x\n", i, debugstr_w(string),
1168             info.fState, info.dwItemData, info.fType, info.wID );
1169         if ( ( !sei->lpVerb && (info.fState & MFS_DEFAULT) ) ||
1170              ( sei->lpVerb && !lstrcmpiW( sei->lpVerb, string ) ) )
1171         {
1172             def = i;
1173             break;
1174         }
1175     }
1176
1177     r = E_FAIL;
1178     if ( def == -1 )
1179         goto end;
1180
1181     memset( &ici, 0, sizeof ici );
1182     ici.cbSize = sizeof ici;
1183     ici.fMask = CMIC_MASK_UNICODE | (sei->fMask & (SEE_MASK_NOASYNC|SEE_MASK_ASYNCOK|SEE_MASK_FLAG_NO_UI));
1184     ici.nShow = sei->nShow;
1185     ici.lpVerb = MAKEINTRESOURCEA( def );
1186     ici.hwnd = sei->hwnd;
1187     ici.lpParametersW = sei->lpParameters;
1188     
1189     r = IContextMenu_InvokeCommand( cm, (LPCMINVOKECOMMANDINFO) &ici );
1190
1191     TRACE("invoke command returned %08x\n", r );
1192
1193 end:
1194     if ( hmenu )
1195         DestroyMenu( hmenu );
1196     if ( cm )
1197         IContextMenu_Release( cm );
1198     return r;
1199 }
1200
1201 static HRESULT shellex_load_object_and_run( HKEY hkey, LPCGUID guid, LPSHELLEXECUTEINFOW sei )
1202 {
1203     IDataObject *dataobj = NULL;
1204     IObjectWithSite *ows = NULL;
1205     IShellExtInit *obj = NULL;
1206     HRESULT r;
1207
1208     TRACE("%p %s %p\n", hkey, debugstr_guid( guid ), sei );
1209
1210     r = CoInitialize( NULL );
1211     if ( FAILED( r ) )
1212         goto end;
1213
1214     r = CoCreateInstance( guid, NULL, CLSCTX_INPROC_SERVER,
1215                            &IID_IShellExtInit, (LPVOID*)&obj );
1216     if ( FAILED( r ) )
1217     {
1218         ERR("failed %08x\n", r );
1219         goto end;
1220     }
1221
1222     dataobj = shellex_get_dataobj( sei );
1223     if ( !dataobj )
1224     {
1225         ERR("failed to get data object\n");
1226         goto end;
1227     }
1228
1229     r = IShellExtInit_Initialize( obj, NULL, dataobj, hkey );
1230     if ( FAILED( r ) )
1231         goto end;
1232
1233     r = IShellExtInit_QueryInterface( obj, &IID_IObjectWithSite, (LPVOID*) &ows );
1234     if ( FAILED( r ) )
1235         goto end;
1236
1237     IObjectWithSite_SetSite( ows, NULL );
1238
1239     r = shellex_run_context_menu_default( obj, sei );
1240
1241 end:
1242     if ( ows )
1243         IObjectWithSite_Release( ows );
1244     if ( dataobj )
1245         IDataObject_Release( dataobj );
1246     if ( obj )
1247         IShellExtInit_Release( obj );
1248     CoUninitialize();
1249     return r;
1250 }
1251
1252
1253 /*************************************************************************
1254  *      ShellExecute_FromContextMenu [Internal]
1255  */
1256 static LONG ShellExecute_FromContextMenu( LPSHELLEXECUTEINFOW sei )
1257 {
1258     static const WCHAR szcm[] = { 's','h','e','l','l','e','x','\\',
1259         'C','o','n','t','e','x','t','M','e','n','u','H','a','n','d','l','e','r','s',0 };
1260     HKEY hkey, hkeycm = 0;
1261     WCHAR szguid[39];
1262     HRESULT hr;
1263     GUID guid;
1264     DWORD i;
1265     LONG r;
1266
1267     TRACE("%s\n", debugstr_w(sei->lpFile) );
1268
1269     hkey = ShellExecute_GetClassKey( sei );
1270     if ( !hkey )
1271         return ERROR_FUNCTION_FAILED;
1272
1273     r = RegOpenKeyW( hkey, szcm, &hkeycm );
1274     if ( r == ERROR_SUCCESS )
1275     {
1276         i = 0;
1277         while ( 1 )
1278         {
1279             r = RegEnumKeyW( hkeycm, i++, szguid, sizeof(szguid)/sizeof(szguid[0]) );
1280             if ( r != ERROR_SUCCESS )
1281                 break;
1282
1283             hr = CLSIDFromString( szguid, &guid );
1284             if (SUCCEEDED(hr))
1285             {
1286                 /* stop at the first one that succeeds in running */
1287                 hr = shellex_load_object_and_run( hkey, &guid, sei );
1288                 if ( SUCCEEDED( hr ) )
1289                     break;
1290             }
1291         }
1292         RegCloseKey( hkeycm );
1293     }
1294
1295     if ( hkey != sei->hkeyClass )
1296         RegCloseKey( hkey );
1297     return r;
1298 }
1299
1300 static UINT_PTR SHELL_execute_class( LPCWSTR wszApplicationName, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1301 {
1302     static const WCHAR wSpace[] = {' ',0};
1303     WCHAR execCmd[1024], wcmd[1024];
1304     /* launch a document by fileclass like 'WordPad.Document.1' */
1305     /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
1306     /* FIXME: wcmd should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
1307     ULONG cmask=(psei->fMask & SEE_MASK_CLASSALL);
1308     DWORD resultLen;
1309     BOOL done;
1310
1311     HCR_GetExecuteCommandW((cmask == SEE_MASK_CLASSKEY) ? psei->hkeyClass : NULL,
1312                            (cmask == SEE_MASK_CLASSNAME) ? psei->lpClass: NULL,
1313                            psei->lpVerb,
1314                            execCmd, sizeof(execCmd));
1315
1316     /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
1317     TRACE("SEE_MASK_CLASSNAME->%s, doc->%s\n", debugstr_w(execCmd), debugstr_w(wszApplicationName));
1318
1319     wcmd[0] = '\0';
1320     done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), execCmd, wszApplicationName, psei->lpIDList, NULL, &resultLen);
1321     if (!done && wszApplicationName[0])
1322     {
1323         strcatW(wcmd, wSpace);
1324         strcatW(wcmd, wszApplicationName);
1325     }
1326     if (resultLen > sizeof(wcmd)/sizeof(WCHAR))
1327         ERR("Argify buffer not large enough... truncating\n");
1328     return execfunc(wcmd, NULL, FALSE, psei, psei_out);
1329 }
1330
1331 static BOOL SHELL_translate_idlist( LPSHELLEXECUTEINFOW sei, LPWSTR wszParameters, DWORD parametersLen, LPWSTR wszApplicationName, DWORD dwApplicationNameLen )
1332 {
1333     static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r','.','e','x','e',0};
1334     WCHAR buffer[MAX_PATH];
1335     BOOL appKnownSingular = FALSE;
1336
1337     /* last chance to translate IDList: now also allow CLSID paths */
1338     if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW(sei->lpIDList, buffer, sizeof(buffer)))) {
1339         if (buffer[0]==':' && buffer[1]==':') {
1340             /* open shell folder for the specified class GUID */
1341             if (strlenW(buffer) + 1 > parametersLen)
1342                 ERR("parameters len exceeds buffer size (%i > %i), truncating\n",
1343                     lstrlenW(buffer) + 1, parametersLen);
1344             lstrcpynW(wszParameters, buffer, parametersLen);
1345             if (strlenW(wExplorer) > dwApplicationNameLen)
1346                 ERR("application len exceeds buffer size (%i > %i), truncating\n",
1347                     lstrlenW(wExplorer) + 1, dwApplicationNameLen);
1348             lstrcpynW(wszApplicationName, wExplorer, dwApplicationNameLen);
1349             appKnownSingular = TRUE;
1350
1351             sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
1352         } else {
1353             WCHAR target[MAX_PATH];
1354             DWORD attribs;
1355             DWORD resultLen;
1356             /* Check if we're executing a directory and if so use the
1357                handler for the Folder class */
1358             strcpyW(target, buffer);
1359             attribs = GetFileAttributesW(buffer);
1360             if (attribs != INVALID_FILE_ATTRIBUTES &&
1361                 (attribs & FILE_ATTRIBUTE_DIRECTORY) &&
1362                 HCR_GetExecuteCommandW(0, wszFolder,
1363                                        sei->lpVerb,
1364                                        buffer, sizeof(buffer))) {
1365                 SHELL_ArgifyW(wszApplicationName, dwApplicationNameLen,
1366                               buffer, target, sei->lpIDList, NULL, &resultLen);
1367                 if (resultLen > dwApplicationNameLen)
1368                     ERR("Argify buffer not large enough... truncating\n");
1369                 appKnownSingular = FALSE;
1370             }
1371             sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
1372         }
1373     }
1374     return appKnownSingular;
1375 }
1376
1377 static UINT_PTR SHELL_quote_and_execute( LPCWSTR wcmd, LPCWSTR wszParameters, LPCWSTR lpstrProtocol, LPCWSTR wszApplicationName, LPWSTR env, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1378 {
1379     static const WCHAR wQuote[] = {'"',0};
1380     static const WCHAR wSpace[] = {' ',0};
1381     UINT_PTR retval;
1382     DWORD len;
1383     WCHAR *wszQuotedCmd;
1384
1385     /* Length of quotes plus length of command plus NULL terminator */
1386     len = 2 + lstrlenW(wcmd) + 1;
1387     if (wszParameters[0])
1388     {
1389         /* Length of space plus length of parameters */
1390         len += 1 + lstrlenW(wszParameters);
1391     }
1392     wszQuotedCmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1393     /* Must quote to handle case where cmd contains spaces,
1394      * else security hole if malicious user creates executable file "C:\\Program"
1395      */
1396     strcpyW(wszQuotedCmd, wQuote);
1397     strcatW(wszQuotedCmd, wcmd);
1398     strcatW(wszQuotedCmd, wQuote);
1399     if (wszParameters[0]) {
1400         strcatW(wszQuotedCmd, wSpace);
1401         strcatW(wszQuotedCmd, wszParameters);
1402     }
1403     TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(psei->lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
1404     if (*lpstrProtocol)
1405         retval = execute_from_key(lpstrProtocol, wszApplicationName, env, psei->lpParameters, wcmd, execfunc, psei, psei_out);
1406     else
1407         retval = execfunc(wszQuotedCmd, env, FALSE, psei, psei_out);
1408     HeapFree(GetProcessHeap(), 0, wszQuotedCmd);
1409     return retval;
1410 }
1411
1412 static UINT_PTR SHELL_execute_url( LPCWSTR lpFile, LPCWSTR wFile, LPCWSTR wcmd, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1413 {
1414     static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
1415     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
1416     UINT_PTR retval;
1417     WCHAR *lpstrProtocol;
1418     LPCWSTR lpstrRes;
1419     INT iSize;
1420     DWORD len;
1421
1422     lpstrRes = strchrW(lpFile, ':');
1423     if (lpstrRes)
1424         iSize = lpstrRes - lpFile;
1425     else
1426         iSize = strlenW(lpFile);
1427
1428     TRACE("Got URL: %s\n", debugstr_w(lpFile));
1429     /* Looking for ...protocol\shell\lpOperation\command */
1430     len = iSize + lstrlenW(wShell) + lstrlenW(wCommand) + 1;
1431     if (psei->lpVerb)
1432         len += lstrlenW(psei->lpVerb);
1433     else
1434         len += lstrlenW(wszOpen);
1435     lpstrProtocol = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1436     memcpy(lpstrProtocol, lpFile, iSize*sizeof(WCHAR));
1437     lpstrProtocol[iSize] = '\0';
1438     strcatW(lpstrProtocol, wShell);
1439     strcatW(lpstrProtocol, psei->lpVerb? psei->lpVerb: wszOpen);
1440     strcatW(lpstrProtocol, wCommand);
1441
1442     /* Remove File Protocol from lpFile */
1443     /* In the case file://path/file     */
1444     if (!strncmpiW(lpFile, wFile, iSize))
1445     {
1446         lpFile += iSize;
1447         while (*lpFile == ':') lpFile++;
1448     }
1449     retval = execute_from_key(lpstrProtocol, lpFile, NULL, psei->lpParameters,
1450                               wcmd, execfunc, psei, psei_out);
1451     HeapFree(GetProcessHeap(), 0, lpstrProtocol);
1452     return retval;
1453 }
1454
1455 static void do_error_dialog( UINT_PTR retval, HWND hwnd )
1456 {
1457     WCHAR msg[2048];
1458     int error_code=GetLastError();
1459
1460     if (retval == SE_ERR_NOASSOC)
1461         LoadStringW(shell32_hInstance, IDS_SHLEXEC_NOASSOC, msg, sizeof(msg)/sizeof(WCHAR));
1462     else
1463         FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code, 0, msg, sizeof(msg)/sizeof(WCHAR), NULL);
1464
1465     MessageBoxW(hwnd, msg, NULL, MB_ICONERROR);
1466 }
1467
1468 /*************************************************************************
1469  *      SHELL_execute [Internal]
1470  */
1471 static BOOL SHELL_execute( LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc )
1472 {
1473     static const WCHAR wSpace[] = {' ',0};
1474     static const WCHAR wWww[] = {'w','w','w',0};
1475     static const WCHAR wFile[] = {'f','i','l','e',0};
1476     static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
1477     static const DWORD unsupportedFlags =
1478         SEE_MASK_INVOKEIDLIST  | SEE_MASK_ICON         | SEE_MASK_HOTKEY |
1479         SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT |
1480         SEE_MASK_UNICODE       | SEE_MASK_ASYNCOK      | SEE_MASK_HMONITOR;
1481
1482     WCHAR parametersBuffer[1024], dirBuffer[MAX_PATH], wcmdBuffer[1024];
1483     WCHAR *wszApplicationName, *wszParameters, *wszDir, *wcmd;
1484     DWORD dwApplicationNameLen = MAX_PATH+2;
1485     DWORD parametersLen = sizeof(parametersBuffer) / sizeof(WCHAR);
1486     DWORD dirLen = sizeof(dirBuffer) / sizeof(WCHAR);
1487     DWORD wcmdLen = sizeof(wcmdBuffer) / sizeof(WCHAR);
1488     DWORD len;
1489     SHELLEXECUTEINFOW sei_tmp;  /* modifiable copy of SHELLEXECUTEINFO struct */
1490     WCHAR wfileName[MAX_PATH];
1491     WCHAR *env;
1492     WCHAR lpstrProtocol[256];
1493     LPCWSTR lpFile;
1494     UINT_PTR retval = SE_ERR_NOASSOC;
1495     BOOL appKnownSingular = FALSE;
1496
1497     /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
1498     sei_tmp = *sei;
1499
1500     TRACE("mask=0x%08x hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
1501             sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
1502             debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
1503             debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
1504             ((sei_tmp.fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME) ?
1505                 debugstr_w(sei_tmp.lpClass) : "not used");
1506
1507     sei->hProcess = NULL;
1508
1509     /* make copies of all path/command strings */
1510     if (!sei_tmp.lpFile)
1511     {
1512         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1513         *wszApplicationName = '\0';
1514     }
1515     else if (*sei_tmp.lpFile == '\"')
1516     {
1517         DWORD l = strlenW(sei_tmp.lpFile+1);
1518         if(l >= dwApplicationNameLen) dwApplicationNameLen = l+1;
1519         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1520         memcpy(wszApplicationName, sei_tmp.lpFile+1, (l+1)*sizeof(WCHAR));
1521         if (wszApplicationName[l-1] == '\"')
1522             wszApplicationName[l-1] = '\0';
1523         appKnownSingular = TRUE;
1524         TRACE("wszApplicationName=%s\n",debugstr_w(wszApplicationName));
1525     } else {
1526         DWORD l = strlenW(sei_tmp.lpFile)+1;
1527         if(l > dwApplicationNameLen) dwApplicationNameLen = l+1;
1528         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1529         memcpy(wszApplicationName, sei_tmp.lpFile, l*sizeof(WCHAR));
1530     }
1531
1532     wszParameters = parametersBuffer;
1533     if (sei_tmp.lpParameters)
1534     {
1535         len = lstrlenW(sei_tmp.lpParameters) + 1;
1536         if (len > parametersLen)
1537         {
1538             wszParameters = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1539             parametersLen = len;
1540         }
1541         strcpyW(wszParameters, sei_tmp.lpParameters);
1542     }
1543     else
1544         *wszParameters = '\0';
1545
1546     wszDir = dirBuffer;
1547     if (sei_tmp.lpDirectory)
1548     {
1549         len = lstrlenW(sei_tmp.lpDirectory) + 1;
1550         if (len > dirLen)
1551         {
1552             wszDir = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1553             dirLen = len;
1554         }
1555         strcpyW(wszDir, sei_tmp.lpDirectory);
1556     }
1557     else
1558         *wszDir = '\0';
1559
1560     /* adjust string pointers to point to the new buffers */
1561     sei_tmp.lpFile = wszApplicationName;
1562     sei_tmp.lpParameters = wszParameters;
1563     sei_tmp.lpDirectory = wszDir;
1564
1565     if (sei_tmp.fMask & unsupportedFlags)
1566     {
1567         FIXME("flags ignored: 0x%08x\n", sei_tmp.fMask & unsupportedFlags);
1568     }
1569
1570     /* process the IDList */
1571     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1572     {
1573         IShellExecuteHookW* pSEH;
1574
1575         HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
1576
1577         if (SUCCEEDED(hr))
1578         {
1579             hr = IShellExecuteHookW_Execute(pSEH, &sei_tmp);
1580
1581             IShellExecuteHookW_Release(pSEH);
1582
1583             if (hr == S_OK) {
1584                 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1585                 if (wszParameters != parametersBuffer)
1586                     HeapFree(GetProcessHeap(), 0, wszParameters);
1587                 if (wszDir != dirBuffer)
1588                     HeapFree(GetProcessHeap(), 0, wszDir);
1589                 return TRUE;
1590             }
1591         }
1592
1593         SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName);
1594         appKnownSingular = TRUE;
1595         TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1596     }
1597
1598     if ( ERROR_SUCCESS == ShellExecute_FromContextMenu( &sei_tmp ) )
1599     {
1600         sei->hInstApp = (HINSTANCE) 33;
1601         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1602         if (wszParameters != parametersBuffer)
1603             HeapFree(GetProcessHeap(), 0, wszParameters);
1604         if (wszDir != dirBuffer)
1605             HeapFree(GetProcessHeap(), 0, wszDir);
1606         return TRUE;
1607     }
1608
1609     if (sei_tmp.fMask & SEE_MASK_CLASSALL)
1610     {
1611         retval = SHELL_execute_class( wszApplicationName, &sei_tmp, sei,
1612                                       execfunc );
1613         if (retval <= 32 && !(sei_tmp.fMask & SEE_MASK_FLAG_NO_UI))
1614             do_error_dialog(retval, sei_tmp.hwnd);
1615         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1616         if (wszParameters != parametersBuffer)
1617             HeapFree(GetProcessHeap(), 0, wszParameters);
1618         if (wszDir != dirBuffer)
1619             HeapFree(GetProcessHeap(), 0, wszDir);
1620         return retval > 32;
1621     }
1622
1623     /* Has the IDList not yet been translated? */
1624     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1625     {
1626         appKnownSingular = SHELL_translate_idlist( &sei_tmp, wszParameters,
1627                                                    parametersLen,
1628                                                    wszApplicationName,
1629                                                    dwApplicationNameLen );
1630     }
1631
1632     /* expand environment strings */
1633     len = ExpandEnvironmentStringsW(sei_tmp.lpFile, NULL, 0);
1634     if (len>0)
1635     {
1636         LPWSTR buf;
1637         buf = HeapAlloc(GetProcessHeap(),0,(len+1)*sizeof(WCHAR));
1638
1639         ExpandEnvironmentStringsW(sei_tmp.lpFile, buf, len+1);
1640         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1641         dwApplicationNameLen = len+1;
1642         wszApplicationName = buf;
1643         /* appKnownSingular unmodified */
1644
1645         sei_tmp.lpFile = wszApplicationName;
1646     }
1647
1648     if (*sei_tmp.lpParameters)
1649     {
1650         len = ExpandEnvironmentStringsW(sei_tmp.lpParameters, NULL, 0);
1651         if (len > 0)
1652         {
1653             LPWSTR buf;
1654             len++;
1655             buf = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
1656             ExpandEnvironmentStringsW(sei_tmp.lpParameters, buf, len);
1657             if (wszParameters != parametersBuffer)
1658                 HeapFree(GetProcessHeap(), 0, wszParameters);
1659             wszParameters = buf;
1660             parametersLen = len;
1661             sei_tmp.lpParameters = wszParameters;
1662         }
1663     }
1664
1665     if (*sei_tmp.lpDirectory)
1666     {
1667         len = ExpandEnvironmentStringsW(sei_tmp.lpDirectory, NULL, 0);
1668         if (len > 0)
1669         {
1670             LPWSTR buf;
1671             len++;
1672             buf = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
1673             ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buf, len);
1674             if (wszDir != dirBuffer)
1675                 HeapFree(GetProcessHeap(), 0, wszDir);
1676             wszDir = buf;
1677             sei_tmp.lpDirectory = wszDir;
1678         }
1679     }
1680
1681     /* Else, try to execute the filename */
1682     TRACE("execute:%s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1683
1684     /* separate out command line arguments from executable file name */
1685     if (!*sei_tmp.lpParameters && !appKnownSingular) {
1686         /* If the executable path is quoted, handle the rest of the command line as parameters. */
1687         if (sei_tmp.lpFile[0] == '"') {
1688             LPWSTR src = wszApplicationName/*sei_tmp.lpFile*/ + 1;
1689             LPWSTR dst = wfileName;
1690             LPWSTR end;
1691
1692             /* copy the unquoted executable path to 'wfileName' */
1693             while(*src && *src!='"')
1694                 *dst++ = *src++;
1695
1696             *dst = '\0';
1697
1698             if (*src == '"') {
1699                 end = ++src;
1700
1701                 while(isspace(*src))
1702                     ++src;
1703             } else
1704                 end = src;
1705
1706             /* copy the parameter string to 'wszParameters' */
1707             strcpyW(wszParameters, src);
1708
1709             /* terminate previous command string after the quote character */
1710             *end = '\0';
1711         }
1712         else
1713         {
1714             /* If the executable name is not quoted, we have to use this search loop here,
1715                that in CreateProcess() is not sufficient because it does not handle shell links. */
1716             WCHAR buffer[MAX_PATH], xlpFile[MAX_PATH];
1717             LPWSTR space, s;
1718
1719             LPWSTR beg = wszApplicationName/*sei_tmp.lpFile*/;
1720             for(s=beg; (space=strchrW(s, ' ')); s=space+1) {
1721                 int idx = space-sei_tmp.lpFile;
1722                 memcpy(buffer, sei_tmp.lpFile, idx * sizeof(WCHAR));
1723                 buffer[idx] = '\0';
1724
1725                 /*FIXME This finds directory paths if the targeted file name contains spaces. */
1726                 if (SearchPathW(*sei_tmp.lpDirectory? sei_tmp.lpDirectory: NULL, buffer, wszExe, sizeof(xlpFile)/sizeof(xlpFile[0]), xlpFile, NULL))
1727                 {
1728                     /* separate out command from parameter string */
1729                     LPCWSTR p = space + 1;
1730
1731                     while(isspaceW(*p))
1732                         ++p;
1733
1734                     strcpyW(wszParameters, p);
1735                     *space = '\0';
1736
1737                     break;
1738                 }
1739             }
1740
1741            lstrcpynW(wfileName, sei_tmp.lpFile,sizeof(wfileName)/sizeof(WCHAR));
1742         }
1743     } else
1744        lstrcpynW(wfileName, sei_tmp.lpFile,sizeof(wfileName)/sizeof(WCHAR));
1745
1746     lpFile = wfileName;
1747
1748     wcmd = wcmdBuffer;
1749     len = lstrlenW(wszApplicationName) + 1;
1750     if (sei_tmp.lpParameters[0])
1751         len += 1 + lstrlenW(wszParameters);
1752     if (len > wcmdLen)
1753     {
1754         wcmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1755         wcmdLen = len;
1756     }
1757     strcpyW(wcmd, wszApplicationName);
1758     if (sei_tmp.lpParameters[0]) {
1759         strcatW(wcmd, wSpace);
1760         strcatW(wcmd, wszParameters);
1761     }
1762
1763     retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1764     if (retval > 32) {
1765         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1766         if (wszParameters != parametersBuffer)
1767             HeapFree(GetProcessHeap(), 0, wszParameters);
1768         if (wszDir != dirBuffer)
1769             HeapFree(GetProcessHeap(), 0, wszDir);
1770         if (wcmd != wcmdBuffer)
1771             HeapFree(GetProcessHeap(), 0, wcmd);
1772         return TRUE;
1773     }
1774
1775     /* Else, try to find the executable */
1776     wcmd[0] = '\0';
1777     retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, wcmdLen, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
1778     if (retval > 32)  /* Found */
1779     {
1780         retval = SHELL_quote_and_execute( wcmd, wszParameters, lpstrProtocol,
1781                                           wszApplicationName, env, &sei_tmp,
1782                                           sei, execfunc );
1783         HeapFree( GetProcessHeap(), 0, env );
1784     }
1785     else if (PathIsDirectoryW(lpFile))
1786     {
1787         static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r',0};
1788         static const WCHAR wQuote[] = {'"',0};
1789         WCHAR wExec[MAX_PATH];
1790         WCHAR * lpQuotedFile = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR) * (strlenW(lpFile) + 3) );
1791
1792         if (lpQuotedFile)
1793         {
1794             retval = SHELL_FindExecutable( sei_tmp.lpDirectory, wExplorer,
1795                                            wszOpen, wExec, MAX_PATH,
1796                                            NULL, &env, NULL, NULL );
1797             if (retval > 32)
1798             {
1799                 strcpyW(lpQuotedFile, wQuote);
1800                 strcatW(lpQuotedFile, lpFile);
1801                 strcatW(lpQuotedFile, wQuote);
1802                 retval = SHELL_quote_and_execute( wExec, lpQuotedFile,
1803                                                   lpstrProtocol,
1804                                                   wszApplicationName, env,
1805                                                   &sei_tmp, sei, execfunc );
1806                 HeapFree( GetProcessHeap(), 0, env );
1807             }
1808             HeapFree( GetProcessHeap(), 0, lpQuotedFile );
1809         }
1810         else
1811             retval = 0; /* Out of memory */
1812     }
1813     else if (PathIsURLW(lpFile))    /* File not found, check for URL */
1814     {
1815         retval = SHELL_execute_url( lpFile, wFile, wcmd, &sei_tmp, sei, execfunc );
1816     }
1817     /* Check if file specified is in the form www.??????.*** */
1818     else if (!strncmpiW(lpFile, wWww, 3))
1819     {
1820         /* if so, append lpFile http:// and call ShellExecute */
1821         WCHAR lpstrTmpFile[256];
1822         strcpyW(lpstrTmpFile, wHttp);
1823         strcatW(lpstrTmpFile, lpFile);
1824         retval = (UINT_PTR)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1825     }
1826
1827     TRACE("retval %lu\n", retval);
1828
1829     HeapFree(GetProcessHeap(), 0, wszApplicationName);
1830     if (wszParameters != parametersBuffer)
1831         HeapFree(GetProcessHeap(), 0, wszParameters);
1832     if (wszDir != dirBuffer)
1833         HeapFree(GetProcessHeap(), 0, wszDir);
1834     if (wcmd != wcmdBuffer)
1835         HeapFree(GetProcessHeap(), 0, wcmd);
1836
1837     sei->hInstApp = (HINSTANCE)(retval > 32 ? 33 : retval);
1838
1839     if (retval <= 32 && !(sei_tmp.fMask & SEE_MASK_FLAG_NO_UI))
1840         do_error_dialog(retval, sei_tmp.hwnd);
1841     return retval > 32;
1842 }
1843
1844 /*************************************************************************
1845  * ShellExecuteA                        [SHELL32.290]
1846  */
1847 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1848                                LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1849 {
1850     SHELLEXECUTEINFOA sei;
1851
1852     TRACE("%p,%s,%s,%s,%s,%d\n",
1853           hWnd, debugstr_a(lpOperation), debugstr_a(lpFile),
1854           debugstr_a(lpParameters), debugstr_a(lpDirectory), iShowCmd);
1855
1856     sei.cbSize = sizeof(sei);
1857     sei.fMask = SEE_MASK_FLAG_NO_UI;
1858     sei.hwnd = hWnd;
1859     sei.lpVerb = lpOperation;
1860     sei.lpFile = lpFile;
1861     sei.lpParameters = lpParameters;
1862     sei.lpDirectory = lpDirectory;
1863     sei.nShow = iShowCmd;
1864     sei.lpIDList = 0;
1865     sei.lpClass = 0;
1866     sei.hkeyClass = 0;
1867     sei.dwHotKey = 0;
1868     sei.hProcess = 0;
1869
1870     ShellExecuteExA (&sei);
1871     return sei.hInstApp;
1872 }
1873
1874 /*************************************************************************
1875  * ShellExecuteExA                              [SHELL32.292]
1876  *
1877  */
1878 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1879 {
1880     SHELLEXECUTEINFOW seiW;
1881     BOOL ret;
1882     WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1883
1884     TRACE("%p\n", sei);
1885
1886     memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1887
1888     if (sei->lpVerb)
1889         seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1890
1891     if (sei->lpFile)
1892         seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1893
1894     if (sei->lpParameters)
1895         seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1896
1897     if (sei->lpDirectory)
1898         seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1899
1900     if ((sei->fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME && sei->lpClass)
1901         seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1902     else
1903         seiW.lpClass = NULL;
1904
1905     ret = SHELL_execute( &seiW, SHELL_ExecuteW );
1906
1907     sei->hInstApp = seiW.hInstApp;
1908
1909     if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
1910         sei->hProcess = seiW.hProcess;
1911
1912     SHFree(wVerb);
1913     SHFree(wFile);
1914     SHFree(wParameters);
1915     SHFree(wDirectory);
1916     SHFree(wClass);
1917
1918     return ret;
1919 }
1920
1921 /*************************************************************************
1922  * ShellExecuteExW                              [SHELL32.293]
1923  *
1924  */
1925 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1926 {
1927     return SHELL_execute( sei, SHELL_ExecuteW );
1928 }
1929
1930 /*************************************************************************
1931  * ShellExecuteW                        [SHELL32.294]
1932  * from shellapi.h
1933  * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1934  * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1935  */
1936 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1937                                LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1938 {
1939     SHELLEXECUTEINFOW sei;
1940
1941     TRACE("\n");
1942     sei.cbSize = sizeof(sei);
1943     sei.fMask = SEE_MASK_FLAG_NO_UI;
1944     sei.hwnd = hwnd;
1945     sei.lpVerb = lpOperation;
1946     sei.lpFile = lpFile;
1947     sei.lpParameters = lpParameters;
1948     sei.lpDirectory = lpDirectory;
1949     sei.nShow = nShowCmd;
1950     sei.lpIDList = 0;
1951     sei.lpClass = 0;
1952     sei.hkeyClass = 0;
1953     sei.dwHotKey = 0;
1954     sei.hProcess = 0;
1955
1956     SHELL_execute( &sei, SHELL_ExecuteW );
1957     return sei.hInstApp;
1958 }
1959
1960 /*************************************************************************
1961  * WOWShellExecute                      [SHELL32.@]
1962  *
1963  * FIXME: the callback function most likely doesn't work the same way on Windows.
1964  */
1965 HINSTANCE WINAPI WOWShellExecute(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1966                                  LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd, void *callback)
1967 {
1968     SHELLEXECUTEINFOW seiW;
1969     WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL;
1970     HANDLE hProcess = 0;
1971
1972     seiW.lpVerb = lpOperation ? __SHCloneStrAtoW(&wVerb, lpOperation) : NULL;
1973     seiW.lpFile = lpFile ? __SHCloneStrAtoW(&wFile, lpFile) : NULL;
1974     seiW.lpParameters = lpParameters ? __SHCloneStrAtoW(&wParameters, lpParameters) : NULL;
1975     seiW.lpDirectory = lpDirectory ? __SHCloneStrAtoW(&wDirectory, lpDirectory) : NULL;
1976
1977     seiW.cbSize = sizeof(seiW);
1978     seiW.fMask = 0;
1979     seiW.hwnd = hWnd;
1980     seiW.nShow = iShowCmd;
1981     seiW.lpIDList = 0;
1982     seiW.lpClass = 0;
1983     seiW.hkeyClass = 0;
1984     seiW.dwHotKey = 0;
1985     seiW.hProcess = hProcess;
1986
1987     SHELL_execute( &seiW, callback );
1988
1989     SHFree(wVerb);
1990     SHFree(wFile);
1991     SHFree(wParameters);
1992     SHFree(wDirectory);
1993     return seiW.hInstApp;
1994 }
1995
1996 /*************************************************************************
1997  * OpenAs_RunDLLA          [SHELL32.@]
1998  */
1999 void WINAPI OpenAs_RunDLLA(HWND hwnd, HINSTANCE hinst, LPCSTR cmdline, int cmdshow)
2000 {
2001     FIXME("%p, %p, %s, %d\n", hwnd, hinst, debugstr_a(cmdline), cmdshow);
2002 }
2003
2004 /*************************************************************************
2005  * OpenAs_RunDLLW          [SHELL32.@]
2006  */
2007 void WINAPI OpenAs_RunDLLW(HWND hwnd, HINSTANCE hinst, LPCWSTR cmdline, int cmdshow)
2008 {
2009     FIXME("%p, %p, %s, %d\n", hwnd, hinst, debugstr_w(cmdline), cmdshow);
2010 }