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