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