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