Call IShellExecuteHook interface for ShellExecute() calls with ID
[wine] / dlls / shell32 / shlexec.c
1 /*
2  *                              Shell Library Functions
3  *
4  * Copyright 1998 Marcus Meissner
5  * Copyright 2002 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #include <ctype.h>
33 #include <assert.h>
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winerror.h"
38 #include "winreg.h"
39 #include "wownt32.h"
40 #include "shellapi.h"
41 #include "wingdi.h"
42 #include "winuser.h"
43 #include "shlobj.h"
44 #include "shlwapi.h"
45 #include "ddeml.h"
46
47 #include "wine/winbase16.h"
48 #include "shell32_main.h"
49 #include "undocshell.h"
50
51 #include "wine/debug.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(exec);
54
55 static const WCHAR wszOpen[] = {'o','p','e','n',0};
56 static const WCHAR wszExe[] = {'.','e','x','e',0};
57 static const WCHAR wszILPtr[] = {':','%','p',0};
58 static const WCHAR wszShell[] = {'\\','s','h','e','l','l','\\',0};
59
60
61 /***********************************************************************
62  *      SHELL_ArgifyW [Internal]
63  *
64  * this function is supposed to expand the escape sequences found in the registry
65  * some diving reported that the following were used:
66  * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
67  *      %1 file
68  *      %2 printer
69  *      %3 driver
70  *      %4 port
71  * %I address of a global item ID (explorer switch /idlist)
72  * %L seems to be %1 as long filename followed by the 8+3 variation
73  * %S ???
74  * %* all following parameters (see batfile)
75  *
76  * FIXME: use 'len'
77  */
78 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args)
79 {
80     WCHAR   xlpFile[1024];
81     BOOL    done = FALSE;
82     PWSTR   res = out;
83     PCWSTR  cmd;
84     LPVOID  pv;
85
86     while (*fmt)
87     {
88         if (*fmt == '%')
89         {
90             switch (*++fmt)
91             {
92             case '\0':
93             case '%':
94                 *res++ = '%';
95                 break;
96
97             case '2':
98             case '3':
99             case '4':
100             case '5':
101             case '6':
102             case '7':
103             case '8':
104             case '9':
105             case '0':
106             case '*':
107                 if (args)
108                 {
109                     if (*fmt == '*')
110                     {
111                         *res++ = '"';
112                         while(*args)
113                             *res++ = *args++;
114                         *res++ = '"';
115                     }
116                     else
117                     {
118                         while(*args && !isspace(*args))
119                             *res++ = *args++;
120
121                         while(isspace(*args))
122                             ++args;
123                     }
124                     break;
125                 }
126                 /* else fall through */
127             case '1':
128                 if (!done || (*fmt == '1'))
129                 {
130                     /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
131                     if (SearchPathW(NULL, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
132                         cmd = xlpFile;
133                     else
134                         cmd = lpFile;
135
136                     /* Add double quotation marks unless we already have them (e.g.: "%1" %* for exefile) */
137                     if (res==out || res[-1]!='"')
138                     {
139                         *res++ = '"';
140                         strcpyW(res, cmd);
141                         res += strlenW(cmd);
142                         *res++ = '"';
143                     }
144                     else
145                     {
146                         strcpyW(res, cmd);
147                         res += strlenW(cmd);
148                     }
149                 }
150                 break;
151
152             /*
153              * IE uses this alot for activating things such as windows media
154              * player. This is not verified to be fully correct but it appears
155              * to work just fine.
156              */
157             case 'l':
158             case 'L':
159                 if (lpFile) {
160                     strcpyW(res, lpFile);
161                     res += strlenW(lpFile);
162                 }
163                 break;
164
165             case 'i':
166             case 'I':
167                 if (pidl) {
168                     HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
169                     pv = SHLockShared(hmem, 0);
170                     res += sprintfW(res, wszILPtr, pv);
171                     SHUnlockShared(pv);
172                 }
173                 break;
174
175             default: FIXME("Unknown escape sequence %%%c\n", *fmt);
176             }
177             fmt++;
178             done = TRUE;
179         }
180         else
181             *res++ = *fmt++;
182     }
183
184     *res = '\0';
185
186     return done;
187 }
188
189 /*************************************************************************
190  *      SHELL_ExecuteW [Internal]
191  *
192  */
193 static UINT SHELL_ExecuteW(const WCHAR *lpCmd, void *env, BOOL shWait,
194                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
195 {
196     STARTUPINFOW  startup;
197     PROCESS_INFORMATION info;
198     UINT retval = 31;
199     UINT gcdret = 0;
200     WCHAR curdir[MAX_PATH];
201
202     TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
203     /* ShellExecute specifies the command from psei->lpDirectory
204      * if present. Not from the current dir as CreateProcess does */
205     if( psei->lpDirectory && psei->lpDirectory[0] )
206         if( ( gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
207             if( !SetCurrentDirectoryW( psei->lpDirectory))
208                 ERR("cannot set directory %s\n", debugstr_w(psei->lpDirectory));
209     ZeroMemory(&startup,sizeof(STARTUPINFOW));
210     startup.cb = sizeof(STARTUPINFOW);
211     startup.dwFlags = STARTF_USESHOWWINDOW;
212     startup.wShowWindow = psei->nShow;
213     if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, 0,
214                        env, *psei->lpDirectory? psei->lpDirectory: NULL, &startup, &info))
215     {
216         /* Give 30 seconds to the app to come up, if desired. Probably only needed
217            when starting app immediately before making a DDE connection. */
218         if (shWait)
219             if (WaitForInputIdle( info.hProcess, 30000 ) == -1)
220                 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
221         retval = 33;
222         if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
223             psei_out->hProcess = info.hProcess;
224         else
225             CloseHandle( info.hProcess );
226         CloseHandle( info.hThread );
227     }
228     else if ((retval = GetLastError()) >= 32)
229     {
230         FIXME("Strange error set by CreateProcess: %d\n", retval);
231         retval = ERROR_BAD_FORMAT;
232     }
233
234     TRACE("returning %u\n", retval);
235
236     psei_out->hInstApp = (HINSTANCE)retval;
237     if( gcdret ) 
238         if( !SetCurrentDirectoryW( curdir))
239             ERR("cannot return to directory %s\n", debugstr_w(curdir));
240
241     return retval;
242 }
243
244
245 /***********************************************************************
246  *           SHELL_BuildEnvW    [Internal]
247  *
248  * Build the environment for the new process, adding the specified
249  * path to the PATH variable. Returned pointer must be freed by caller.
250  */
251 static void *SHELL_BuildEnvW( const WCHAR *path )
252 {
253     static const WCHAR wPath[] = {'P','A','T','H','=',0};
254     WCHAR *strings, *new_env;
255     WCHAR *p, *p2;
256     int total = strlenW(path) + 1;
257     BOOL got_path = FALSE;
258
259     if (!(strings = GetEnvironmentStringsW())) return NULL;
260     p = strings;
261     while (*p)
262     {
263         int len = strlenW(p) + 1;
264         if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
265         total += len;
266         p += len;
267     }
268     if (!got_path) total += 5;  /* we need to create PATH */
269     total++;  /* terminating null */
270
271     if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
272     {
273         FreeEnvironmentStringsW( strings );
274         return NULL;
275     }
276     p = strings;
277     p2 = new_env;
278     while (*p)
279     {
280         int len = strlenW(p) + 1;
281         memcpy( p2, p, len * sizeof(WCHAR) );
282         if (!strncmpiW( p, wPath, 5 ))
283         {
284             p2[len - 1] = ';';
285             strcpyW( p2 + len, path );
286             p2 += strlenW(path) + 1;
287         }
288         p += len;
289         p2 += len;
290     }
291     if (!got_path)
292     {
293         strcpyW( p2, wPath );
294         strcatW( p2, path );
295         p2 += strlenW(p2) + 1;
296     }
297     *p2 = 0;
298     FreeEnvironmentStringsW( strings );
299     return new_env;
300 }
301
302
303 /***********************************************************************
304  *           SHELL_TryAppPathW  [Internal]
305  *
306  * Helper function for SHELL_FindExecutable
307  * @param lpResult - pointer to a buffer of size MAX_PATH
308  * On entry: szName is a filename (probably without path separators).
309  * On exit: if szName found in "App Path", place full path in lpResult, and return true
310  */
311 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, void**env)
312 {
313     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',
314         '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','A','p','p',' ','P','a','t','h','s','\\',0};
315     static const WCHAR wPath[] = {'P','a','t','h',0};
316     HKEY hkApp = 0;
317     WCHAR buffer[1024];
318     LONG len;
319     LONG res;
320     BOOL found = FALSE;
321
322     if (env) *env = NULL;
323     strcpyW(buffer, wszKeyAppPaths);
324     strcatW(buffer, szName);
325     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
326     if (res) goto end;
327
328     len = MAX_PATH*sizeof(WCHAR);
329     res = RegQueryValueW(hkApp, NULL, lpResult, &len);
330     if (res) goto end;
331     found = TRUE;
332
333     if (env)
334     {
335         DWORD count = sizeof(buffer);
336         if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
337             *env = SHELL_BuildEnvW( buffer );
338     }
339
340 end:
341     if (hkApp) RegCloseKey(hkApp);
342     return found;
343 }
344
345 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
346 {
347     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
348
349     /* Looking for ...buffer\shell\<verb>\command */
350     strcatW(filetype, wszShell);
351     strcatW(filetype, lpOperation);
352     strcatW(filetype, wCommand);
353
354     if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
355                        &commandlen) == ERROR_SUCCESS)
356     {
357         commandlen /= sizeof(WCHAR);
358         if (key) strcpyW(key, filetype);
359 #if 0
360         LPWSTR tmp;
361         WCHAR param[256];
362         LONG paramlen = sizeof(param);
363         static const WCHAR wSpace[] = {' ',0};
364
365         /* FIXME: it seems all Windows version don't behave the same here.
366          * the doc states that this ddeexec information can be found after
367          * the exec names.
368          * on Win98, it doesn't appear, but I think it does on Win2k
369          */
370         /* Get the parameters needed by the application
371            from the associated ddeexec key */
372         tmp = strstrW(filetype, wCommand);
373         tmp[0] = '\0';
374         strcatW(filetype, wDdeexec);
375         if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, param,
376                                      &paramlen) == ERROR_SUCCESS)
377         {
378             paramlen /= sizeof(WCHAR);
379             strcatW(command, wSpace);
380             strcatW(command, param);
381             commandlen += paramlen;
382         }
383 #endif
384
385         command[commandlen] = '\0';
386
387         return 33; /* FIXME see SHELL_FindExecutable() */
388     }
389
390     return 31;  /* default - 'No association was found' */
391 }
392
393 /*************************************************************************
394  *      SHELL_FindExecutable [Internal]
395  *
396  * Utility for code sharing between FindExecutable and ShellExecute
397  * in:
398  *      lpFile the name of a file
399  *      lpOperation the operation on it (open)
400  * out:
401  *      lpResult a buffer, big enough :-(, to store the command to do the
402  *              operation on the file
403  *      key a buffer, big enough, to get the key name to do actually the
404  *              command (it'll be used afterwards for more information
405  *              on the operation)
406  */
407 UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
408                                  LPWSTR lpResult, int resultLen, LPWSTR key, void **env, LPITEMIDLIST pidl, LPCWSTR args)
409 {
410     static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
411     static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
412     static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
413     WCHAR *extension = NULL; /* pointer to file extension */
414     WCHAR wtmpext[5];        /* local copy to mung as we please */
415     WCHAR filetype[256];     /* registry name for this filetype */
416     LONG  filetypelen = sizeof(filetype); /* length of above */
417     WCHAR command[256];      /* command from registry */
418     WCHAR wBuffer[256];      /* Used to GetProfileString */
419     UINT  retval = 31;       /* default - 'No association was found' */
420     WCHAR *tok;              /* token pointer */
421     WCHAR xlpFile[256] = {0}; /* result of SearchPath */
422
423     TRACE("%s\n", (lpFile != NULL) ? debugstr_w(lpFile) : "-");
424
425     lpResult[0] = '\0'; /* Start off with an empty return string */
426     if (key) *key = '\0';
427
428     /* trap NULL parameters on entry */
429     if ((lpFile == NULL) || (lpResult == NULL) || (lpOperation == NULL))
430     {
431         WARN("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
432              debugstr_w(lpFile), debugstr_w(lpOperation), debugstr_w(lpResult));
433         return 2; /* File not found. Close enough, I guess. */
434     }
435
436     if (SHELL_TryAppPathW( lpFile, lpResult, env ))
437     {
438         TRACE("found %s via App Paths\n", debugstr_w(lpResult));
439         return 33;
440     }
441
442     if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
443     {
444         TRACE("SearchPathW returned non-zero\n");
445         lpFile = xlpFile;
446         /* Hey, isn't this value ignored?  Why make this call?  Shouldn't we return here?  --dank*/
447     }
448
449     /* First thing we need is the file's extension */
450     extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
451                                        /* File->Run in progman uses */
452                                        /* .\FILE.EXE :( */
453     TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
454
455     if ((extension == NULL) || (extension == &xlpFile[strlenW(xlpFile)]))
456     {
457         WARN("Returning 31 - No association\n");
458         return 31; /* no association */
459     }
460
461     /* Make local copy & lowercase it for reg & 'programs=' lookup */
462     lstrcpynW(wtmpext, extension, 5);
463     CharLowerW(wtmpext);
464     TRACE("%s file\n", debugstr_w(wtmpext));
465
466     /* Three places to check: */
467     /* 1. win.ini, [windows], programs (NB no leading '.') */
468     /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
469     /* 3. win.ini, [extensions], extension (NB no leading '.' */
470     /* All I know of the order is that registry is checked before */
471     /* extensions; however, it'd make sense to check the programs */
472     /* section first, so that's what happens here. */
473
474     /* See if it's a program - if GetProfileString fails, we skip this
475      * section. Actually, if GetProfileString fails, we've probably
476      * got a lot more to worry about than running a program... */
477     if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
478     {
479         CharLowerW(wBuffer);
480         tok = wBuffer;
481         while (*tok)
482         {
483             WCHAR *p = tok;
484             while (*p && *p != ' ' && *p != '\t') p++;
485             if (*p)
486             {
487                 *p++ = 0;
488                 while (*p == ' ' || *p == '\t') p++;
489             }
490
491             if (strcmpW(tok, &wtmpext[1]) == 0) /* have to skip the leading "." */
492             {
493                 strcpyW(lpResult, xlpFile);
494                 /* Need to perhaps check that the file has a path
495                  * attached */
496                 TRACE("found %s\n", debugstr_w(lpResult));
497                 return 33;
498
499                 /* Greater than 32 to indicate success FIXME According to the
500                  * docs, I should be returning a handle for the
501                  * executable. Does this mean I'm supposed to open the
502                  * executable file or something? More RTFM, I guess... */
503             }
504             tok = p;
505         }
506     }
507
508     /* Check registry */
509     if (RegQueryValueW(HKEY_CLASSES_ROOT, wtmpext, filetype, 
510                         &filetypelen) == ERROR_SUCCESS)
511     {
512         filetypelen /= sizeof(WCHAR);
513         filetype[filetypelen] = '\0';
514         TRACE("File type: %s\n", debugstr_w(filetype));
515     }
516
517     if (*filetype)
518     {
519         if (lpOperation)
520         {
521             /* pass the operation string to SHELL_FindExecutableByOperation() */
522             filetype[filetypelen] = '\0';
523             retval = SHELL_FindExecutableByOperation(lpPath, lpFile, lpOperation, key, filetype, command, sizeof(command));
524         }
525         else
526         {
527             WCHAR operation[MAX_PATH];
528             HKEY hkey;
529
530             /* Looking for ...buffer\shell\<operation>\command */
531             strcatW(filetype, wszShell);
532
533             /* enumerate the operation subkeys in the registry and search for one with an associated command */
534             if (RegOpenKeyW(HKEY_CLASSES_ROOT, filetype, &hkey) == ERROR_SUCCESS)
535             {
536                 int idx = 0;
537                 for(;; ++idx)
538                 {
539                     if (RegEnumKeyW(hkey, idx, operation, MAX_PATH) != ERROR_SUCCESS)
540                         break;
541
542                     filetype[filetypelen] = '\0';
543                     retval = SHELL_FindExecutableByOperation(lpPath, lpFile, operation, key, filetype, command, sizeof(command));
544
545                     if (retval > 32)
546                         break;
547             }
548                 RegCloseKey(hkey);
549             }
550         }
551
552         if (retval > 32)
553         {
554             SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args);
555
556             /* Remove double quotation marks and command line arguments */
557             if (*lpResult == '"')
558             {
559                 WCHAR *p = lpResult;
560                 while (*(p + 1) != '"')
561                 {
562                     *p = *(p + 1);
563                     p++;
564                 }
565                 *p = '\0';
566             }
567         }
568     }
569     else /* Check win.ini */
570     {
571         static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
572         static const WCHAR wEmpty[] = {0};
573
574         /* Toss the leading dot */
575         extension++;
576         if (GetProfileStringW(wExtensions, extension, wEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
577         {
578             if (strlenW(command) != 0)
579             {
580                 strcpyW(lpResult, command);
581                 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
582                 if (tok != NULL)
583                 {
584                     tok[0] = '\0';
585                     strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
586                     tok = strchrW(command, '^'); /* see above */
587                     if ((tok != NULL) && (strlenW(tok)>5))
588                     {
589                         strcatW(lpResult, &tok[5]);
590                     }
591                 }
592                 retval = 33; /* FIXME - see above */
593             }
594         }
595     }
596
597     TRACE("returning %s\n", debugstr_w(lpResult));
598     return retval;
599 }
600
601 /******************************************************************
602  *              dde_cb
603  *
604  * callback for the DDE connection. not really usefull
605  */
606 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
607                                 HSZ hsz1, HSZ hsz2,
608                                 HDDEDATA hData, DWORD dwData1, DWORD dwData2)
609 {
610     return NULL;
611 }
612
613 /******************************************************************
614  *              dde_connect
615  *
616  * ShellExecute helper. Used to do an operation with a DDE connection
617  *
618  * Handles both the direct connection (try #1), and if it fails,
619  * launching an application and trying (#2) to connect to it
620  *
621  */
622 static unsigned dde_connect(WCHAR* key, WCHAR* start, WCHAR* ddeexec,
623                             const WCHAR* lpFile, void *env,
624                             LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
625                             LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
626 {
627     static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
628     static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
629     WCHAR *     endkey = key + strlenW(key);
630     WCHAR       app[256], topic[256], ifexec[256], res[256];
631     LONG        applen, topiclen, ifexeclen;
632     WCHAR *     exec;
633     DWORD       ddeInst = 0;
634     DWORD       tid;
635     HSZ         hszApp, hszTopic;
636     HCONV       hConv;
637     unsigned    ret = 31;
638
639     strcpyW(endkey, wApplication);
640     applen = sizeof(app);
641     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, app, &applen) != ERROR_SUCCESS)
642     {
643         FIXME("default app name NIY %s\n", debugstr_w(key));
644         return 2;
645     }
646
647     strcpyW(endkey, wTopic);
648     topiclen = sizeof(topic);
649     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, topic, &topiclen) != ERROR_SUCCESS)
650     {
651         static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
652         strcpyW(topic, wSystem);
653     }
654
655     if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
656     {
657         return 2;
658     }
659
660     hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINANSI);
661     hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINANSI);
662
663     hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
664     exec = ddeexec;
665     if (!hConv)
666     {
667         static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
668         TRACE("Launching '%s'\n", debugstr_w(start));
669         ret = execfunc(start, env, TRUE, psei, psei_out);
670         if (ret < 32)
671         {
672             TRACE("Couldn't launch\n");
673             goto error;
674         }
675         hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
676         if (!hConv)
677         {
678             TRACE("Couldn't connect. ret=%d\n", ret);
679             DdeUninitialize(ddeInst);
680             SetLastError(ERROR_DDE_FAIL);
681             return 30; /* whatever */
682         }
683         strcpyW(endkey, wIfexec);
684         ifexeclen = sizeof(ifexec);
685         if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ifexec, &ifexeclen) == ERROR_SUCCESS)
686         {
687             exec = ifexec;
688         }
689     }
690
691     SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline);
692     TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
693
694     ret = (DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
695                                 XTYP_EXECUTE, 10000, &tid) != DMLERR_NO_ERROR) ? 31 : 33;
696     DdeDisconnect(hConv);
697
698  error:
699     DdeUninitialize(ddeInst);
700
701     return ret;
702 }
703
704 /*************************************************************************
705  *      execute_from_key [Internal]
706  */
707 static UINT execute_from_key(LPWSTR key, LPCWSTR lpFile, void *env, LPCWSTR szCommandline,
708                              SHELL_ExecuteW32 execfunc,
709                              LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
710 {
711     WCHAR cmd[1024] = {0};
712     LONG cmdlen = sizeof(cmd);
713     UINT retval = 31;
714
715     /* Get the application for the registry */
716     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
717     {
718         static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
719         static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
720         LPWSTR tmp;
721         WCHAR param[256] = {0};
722         LONG paramlen = sizeof(param);
723
724         /* Get the parameters needed by the application
725            from the associated ddeexec key */
726         tmp = strstrW(key, wCommand);
727         assert(tmp);
728         strcpyW(tmp, wDdeexec);
729
730         if (RegQueryValueW(HKEY_CLASSES_ROOT, key, param, &paramlen) == ERROR_SUCCESS)
731         {
732             TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(param));
733             retval = dde_connect(key, cmd, param, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
734         }
735         else
736         {
737             /* Is there a replace() function anywhere? */
738             cmdlen /= sizeof(WCHAR);
739             cmd[cmdlen] = '\0';
740             SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline);
741             retval = execfunc(param, env, FALSE, psei, psei_out);
742         }
743     }
744     else TRACE("ooch\n");
745
746     return retval;
747 }
748
749 /*************************************************************************
750  * FindExecutableA                      [SHELL32.@]
751  */
752 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
753 {
754     HINSTANCE retval;
755     WCHAR *wFile = NULL, *wDirectory = NULL;
756     WCHAR wResult[MAX_PATH];
757
758     if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
759     if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
760
761     retval = FindExecutableW(wFile, wDirectory, wResult);
762     WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
763     if (wFile) SHFree( wFile );
764     if (wDirectory) SHFree( wDirectory );
765
766     TRACE("returning %s\n", lpResult);
767     return (HINSTANCE)retval;
768 }
769
770 /*************************************************************************
771  * FindExecutableW                      [SHELL32.@]
772  */
773 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
774 {
775     UINT retval = 31;    /* default - 'No association was found' */
776     WCHAR old_dir[1024];
777
778     TRACE("File %s, Dir %s\n",
779           (lpFile != NULL ? debugstr_w(lpFile) : "-"), (lpDirectory != NULL ? debugstr_w(lpDirectory) : "-"));
780
781     lpResult[0] = '\0'; /* Start off with an empty return string */
782
783     /* trap NULL parameters on entry */
784     if ((lpFile == NULL) || (lpResult == NULL))
785     {
786         /* FIXME - should throw a warning, perhaps! */
787         return (HINSTANCE)2; /* File not found. Close enough, I guess. */
788     }
789
790     if (lpDirectory)
791     {
792         GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
793         SetCurrentDirectoryW(lpDirectory);
794     }
795
796     retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
797
798     TRACE("returning %s\n", debugstr_w(lpResult));
799     if (lpDirectory)
800         SetCurrentDirectoryW(old_dir);
801     return (HINSTANCE)retval;
802 }
803
804 /*************************************************************************
805  *      ShellExecuteExW32 [Internal]
806  */
807 BOOL WINAPI ShellExecuteExW32 (LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc)
808 {
809     static const WCHAR wQuote[] = {'"',0};
810     static const WCHAR wSpace[] = {' ',0};
811     static const WCHAR wWww[] = {'w','w','w',0};
812     static const WCHAR wFile[] = {'f','i','l','e',0};
813     static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
814
815     WCHAR wszApplicationName[MAX_PATH+2], wszCommandline[1024], wszDir[MAX_PATH];
816     SHELLEXECUTEINFOW sei_tmp;  /* modifyable copy of SHELLEXECUTEINFO struct */
817     WCHAR wfileName[MAX_PATH];
818     void *env;
819     WCHAR lpstrProtocol[256];
820     LPCWSTR lpFile;
821     UINT retval = 31;
822     WCHAR wcmd[1024];
823     WCHAR buffer[MAX_PATH];
824     BOOL done;
825
826     /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
827     memcpy(&sei_tmp, sei, sizeof(sei_tmp));
828
829     TRACE("mask=0x%08lx hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
830             sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
831             debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
832             debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
833             (sei_tmp.fMask & SEE_MASK_CLASSNAME) ? debugstr_w(sei_tmp.lpClass) : "not used");
834
835     sei->hProcess = NULL;
836
837     /* make copies of all path/command strings */
838     if (sei_tmp.lpFile)
839         strcpyW(wszApplicationName, sei_tmp.lpFile);
840     else
841         *wszApplicationName = '\0';
842
843     if (sei_tmp.lpParameters)
844         strcpyW(wszCommandline, sei_tmp.lpParameters);
845     else
846         *wszCommandline = '\0';
847
848     if (sei_tmp.lpDirectory)
849         strcpyW(wszDir, sei_tmp.lpDirectory);
850     else
851         *wszDir = '\0';
852
853     /* adjust string pointers to point to the new buffers */
854     sei_tmp.lpFile = wszApplicationName;
855     sei_tmp.lpParameters = wszCommandline;
856     sei_tmp.lpDirectory = wszDir;
857
858     if (sei_tmp.fMask & (SEE_MASK_INVOKEIDLIST | SEE_MASK_ICON | SEE_MASK_HOTKEY |
859         SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT |
860         SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI | SEE_MASK_UNICODE |
861         SEE_MASK_NO_CONSOLE | SEE_MASK_ASYNCOK | SEE_MASK_HMONITOR ))
862     {
863         FIXME("flags ignored: 0x%08lx\n", sei_tmp.fMask);
864     }
865
866     /* process the IDList */
867     if (sei_tmp.fMask & SEE_MASK_IDLIST)
868     {
869         IShellExecuteHookW* pSEH;
870
871         HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
872
873         if (SUCCEEDED(hr))
874         {
875             hr = IShellExecuteHookW_Execute(pSEH, sei);
876
877             IShellExecuteHookW_Release(pSEH);
878
879             if (hr == S_OK)
880                 return TRUE;
881         }
882
883         wszApplicationName[0] = '"';
884         SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName+1);
885         strcatW(wszApplicationName, wQuote);
886         TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
887     }
888
889     if (sei_tmp.fMask & (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY))
890     {
891         /* launch a document by fileclass like 'WordPad.Document.1' */
892         /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
893         /* FIXME: szCommandline should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
894         HCR_GetExecuteCommandW((sei_tmp.fMask & SEE_MASK_CLASSKEY) ? sei_tmp.hkeyClass : NULL,
895                                (sei_tmp.fMask & SEE_MASK_CLASSNAME) ? sei_tmp.lpClass: NULL,
896                                (sei_tmp.lpVerb) ? sei_tmp.lpVerb : wszOpen,
897                                wszCommandline, sizeof(wszCommandline)/sizeof(WCHAR));
898
899         /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
900         TRACE("SEE_MASK_CLASSNAME->'%s', doc->'%s'\n", debugstr_w(wszCommandline), debugstr_w(wszApplicationName));
901
902         wcmd[0] = '\0';
903         done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), wszCommandline, wszApplicationName, sei_tmp.lpIDList, NULL);
904         if (!done && wszApplicationName[0])
905         {
906             strcatW(wcmd, wSpace);
907             strcatW(wcmd, wszApplicationName);
908         }
909         retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
910         if (retval > 32)
911             return TRUE;
912         else
913             return FALSE;
914     }
915
916     /* expand environment strings */
917     if (ExpandEnvironmentStringsW(sei_tmp.lpFile, buffer, MAX_PATH))
918         lstrcpyW(wszApplicationName, buffer);
919
920     if (*sei_tmp.lpParameters)
921         if (ExpandEnvironmentStringsW(sei_tmp.lpParameters, buffer, MAX_PATH))
922             lstrcpyW(wszCommandline, buffer);
923
924     if (*sei_tmp.lpDirectory)
925         if (ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buffer, MAX_PATH))
926             lstrcpyW(wszDir, buffer);
927
928     /* Else, try to execute the filename */
929     TRACE("execute:'%s','%s','%s'\n", debugstr_w(wszApplicationName), debugstr_w(wszCommandline), debugstr_w(wszDir));
930
931     strcpyW(wfileName, wszApplicationName);
932     lpFile = wfileName;
933     if (wszCommandline[0]) {
934         strcatW(wszApplicationName, wSpace);
935         strcatW(wszApplicationName, wszCommandline);
936     }
937
938     retval = execfunc(wszApplicationName, NULL, FALSE, &sei_tmp, sei);
939     if (retval > 32)
940         return TRUE;
941
942     /* Else, try to find the executable */
943     wcmd[0] = '\0';
944     retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, 1024, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
945     if (retval > 32)  /* Found */
946     {
947         WCHAR wszQuotedCmd[MAX_PATH+2];
948         /* Must quote to handle case where cmd contains spaces, 
949          * else security hole if malicious user creates executable file "C:\\Program"
950          */
951         strcpyW(wszQuotedCmd, wQuote);
952         strcatW(wszQuotedCmd, wcmd);
953         strcatW(wszQuotedCmd, wQuote);
954         if (wszCommandline[0]) {
955             strcatW(wszQuotedCmd, wSpace);
956             strcatW(wszQuotedCmd, wszCommandline);
957         }
958         TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(sei_tmp.lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
959         if (*lpstrProtocol)
960             retval = execute_from_key(lpstrProtocol, wszApplicationName, env, sei_tmp.lpParameters, execfunc, &sei_tmp, sei);
961         else
962             retval = execfunc(wszQuotedCmd, env, FALSE, &sei_tmp, sei);
963         if (env) HeapFree( GetProcessHeap(), 0, env );
964     }
965     else if (PathIsURLW((LPWSTR)lpFile))    /* File not found, check for URL */
966     {
967         static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
968         static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
969         LPWSTR lpstrRes;
970         INT iSize;
971
972         lpstrRes = strchrW(lpFile, ':');
973         if (lpstrRes)
974             iSize = lpstrRes - lpFile;
975         else
976             iSize = strlenW(lpFile);
977
978         TRACE("Got URL: %s\n", debugstr_w(lpFile));
979         /* Looking for ...protocol\shell\lpOperation\command */
980         strncpyW(lpstrProtocol, lpFile, iSize);
981         lpstrProtocol[iSize] = '\0';
982         strcatW(lpstrProtocol, wShell);
983         strcatW(lpstrProtocol, sei_tmp.lpVerb? sei_tmp.lpVerb: wszOpen);
984         strcatW(lpstrProtocol, wCommand);
985
986         /* Remove File Protocol from lpFile */
987         /* In the case file://path/file     */
988         if (!strncmpiW(lpFile, wFile, iSize))
989         {
990             lpFile += iSize;
991             while (*lpFile == ':') lpFile++;
992         }
993         retval = execute_from_key(lpstrProtocol, lpFile, NULL, sei_tmp.lpParameters, execfunc, &sei_tmp, sei);
994     }
995     /* Check if file specified is in the form www.??????.*** */
996     else if (!strncmpiW(lpFile, wWww, 3))
997     {
998         /* if so, append lpFile http:// and call ShellExecute */
999         WCHAR lpstrTmpFile[256];
1000         strcpyW(lpstrTmpFile, wHttp);
1001         strcatW(lpstrTmpFile, lpFile);
1002         retval = (UINT)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1003     }
1004
1005     TRACE("retval %u\n", retval);
1006
1007     if (retval <= 32)
1008     {
1009         sei->hInstApp = (HINSTANCE)retval;
1010         return FALSE;
1011     }
1012
1013     sei->hInstApp = (HINSTANCE)33;
1014     return TRUE;
1015 }
1016
1017 /*************************************************************************
1018  * ShellExecuteA                        [SHELL32.290]
1019  */
1020 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1021                                LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1022 {
1023     SHELLEXECUTEINFOA sei;
1024     HANDLE hProcess = 0;
1025
1026     TRACE("\n");
1027     sei.cbSize = sizeof(sei);
1028     sei.fMask = 0;
1029     sei.hwnd = hWnd;
1030     sei.lpVerb = lpOperation;
1031     sei.lpFile = lpFile;
1032     sei.lpParameters = lpParameters;
1033     sei.lpDirectory = lpDirectory;
1034     sei.nShow = iShowCmd;
1035     sei.lpIDList = 0;
1036     sei.lpClass = 0;
1037     sei.hkeyClass = 0;
1038     sei.dwHotKey = 0;
1039     sei.hProcess = hProcess;
1040
1041     ShellExecuteExA (&sei);
1042     return sei.hInstApp;
1043 }
1044
1045 /*************************************************************************
1046  * ShellExecuteEx                               [SHELL32.291]
1047  *
1048  */
1049 BOOL WINAPI ShellExecuteExAW (LPVOID sei)
1050 {
1051     if (SHELL_OsIsUnicode())
1052         return ShellExecuteExW32 (sei, SHELL_ExecuteW);
1053     return ShellExecuteExA (sei);
1054 }
1055
1056 /*************************************************************************
1057  * ShellExecuteExA                              [SHELL32.292]
1058  *
1059  */
1060 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1061 {
1062     SHELLEXECUTEINFOW seiW;
1063     BOOL ret;
1064     WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1065
1066     TRACE("%p\n", sei);
1067
1068     memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1069
1070     if (sei->lpVerb)
1071         seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1072
1073     if (sei->lpFile)
1074         seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1075
1076     if (sei->lpParameters)
1077         seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1078
1079     if (sei->lpDirectory)
1080         seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1081
1082     if ((sei->fMask & SEE_MASK_CLASSNAME) && sei->lpClass)
1083         seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1084     else
1085         seiW.lpClass = NULL;
1086
1087     ret = ShellExecuteExW32 (&seiW, SHELL_ExecuteW);
1088
1089     sei->hInstApp = seiW.hInstApp;
1090
1091     if (wVerb) SHFree(wVerb);
1092     if (wFile) SHFree(wFile);
1093     if (wParameters) SHFree(wParameters);
1094     if (wDirectory) SHFree(wDirectory);
1095     if (wClass) SHFree(wClass);
1096
1097     return ret;
1098 }
1099
1100 /*************************************************************************
1101  * ShellExecuteExW                              [SHELL32.293]
1102  *
1103  */
1104 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1105 {
1106     return  ShellExecuteExW32 (sei, SHELL_ExecuteW);
1107 }
1108
1109 /*************************************************************************
1110  * ShellExecuteW                        [SHELL32.294]
1111  * from shellapi.h
1112  * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1113  * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1114  */
1115 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1116                                LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1117 {
1118     SHELLEXECUTEINFOW sei;
1119     HANDLE hProcess = 0;
1120
1121     TRACE("\n");
1122     sei.cbSize = sizeof(sei);
1123     sei.fMask = 0;
1124     sei.hwnd = hwnd;
1125     sei.lpVerb = lpOperation;
1126     sei.lpFile = lpFile;
1127     sei.lpParameters = lpParameters;
1128     sei.lpDirectory = lpDirectory;
1129     sei.nShow = nShowCmd;
1130     sei.lpIDList = 0;
1131     sei.lpClass = 0;
1132     sei.hkeyClass = 0;
1133     sei.dwHotKey = 0;
1134     sei.hProcess = hProcess;
1135
1136     ShellExecuteExW32 (&sei, SHELL_ExecuteW);
1137     return sei.hInstApp;
1138 }