Optimization: null terminate string buffers instead of filling them
[wine.git] / dlls / shell32 / shlexec.c
blob48e934b9d60a92451917a5d96300c178611aa765
1 /*
2 * Shell Library Functions
4 * Copyright 1998 Marcus Meissner
5 * Copyright 2002 Eric Pouech
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.
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.
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
22 #include "config.h"
23 #include "wine/port.h"
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>
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"
47 #include "wine/winbase16.h"
48 #include "shell32_main.h"
49 #include "undocshell.h"
51 #include "wine/debug.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(exec);
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};
61 /***********************************************************************
62 * SHELL_ArgifyW [Internal]
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)
76 * FIXME: use 'len'
78 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args)
80 WCHAR xlpFile[1024];
81 BOOL done = FALSE;
82 PWSTR res = out;
83 PCWSTR cmd;
84 LPVOID pv;
86 while (*fmt)
88 if (*fmt == '%')
90 switch (*++fmt)
92 case '\0':
93 case '%':
94 *res++ = '%';
95 break;
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)
109 if (*fmt == '*')
111 *res++ = '"';
112 while(*args)
113 *res++ = *args++;
114 *res++ = '"';
116 else
118 while(*args && !isspace(*args))
119 *res++ = *args++;
121 while(isspace(*args))
122 ++args;
124 break;
126 /* else fall through */
127 case '1':
128 if (!done || (*fmt == '1'))
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;
136 /* Add double quotation marks unless we already have them (e.g.: "%1" %* for exefile) */
137 if (res==out || res[-1]!='"')
139 *res++ = '"';
140 strcpyW(res, cmd);
141 res += strlenW(cmd);
142 *res++ = '"';
144 else
146 strcpyW(res, cmd);
147 res += strlenW(cmd);
150 break;
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.
157 case 'l':
158 case 'L':
159 if (lpFile) {
160 strcpyW(res, lpFile);
161 res += strlenW(lpFile);
163 break;
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);
173 break;
175 default: FIXME("Unknown escape sequence %%%c\n", *fmt);
177 fmt++;
178 done = TRUE;
180 else
181 *res++ = *fmt++;
184 *res = '\0';
186 return done;
189 /*************************************************************************
190 * SHELL_ExecuteW [Internal]
193 static UINT SHELL_ExecuteW(const WCHAR *lpCmd, void *env, BOOL shWait,
194 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
196 STARTUPINFOW startup;
197 PROCESS_INFORMATION info;
198 UINT retval = 31;
199 UINT gcdret = 0;
200 WCHAR curdir[MAX_PATH];
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))
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 ) == WAIT_FAILED)
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 );
228 else if ((retval = GetLastError()) >= 32)
230 FIXME("Strange error set by CreateProcess: %d\n", retval);
231 retval = ERROR_BAD_FORMAT;
234 TRACE("returning %u\n", retval);
236 psei_out->hInstApp = (HINSTANCE)retval;
237 if( gcdret )
238 if( !SetCurrentDirectoryW( curdir))
239 ERR("cannot return to directory %s\n", debugstr_w(curdir));
241 return retval;
245 /***********************************************************************
246 * SHELL_BuildEnvW [Internal]
248 * Build the environment for the new process, adding the specified
249 * path to the PATH variable. Returned pointer must be freed by caller.
251 static void *SHELL_BuildEnvW( const WCHAR *path )
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;
259 if (!(strings = GetEnvironmentStringsW())) return NULL;
260 p = strings;
261 while (*p)
263 int len = strlenW(p) + 1;
264 if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
265 total += len;
266 p += len;
268 if (!got_path) total += 5; /* we need to create PATH */
269 total++; /* terminating null */
271 if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
273 FreeEnvironmentStringsW( strings );
274 return NULL;
276 p = strings;
277 p2 = new_env;
278 while (*p)
280 int len = strlenW(p) + 1;
281 memcpy( p2, p, len * sizeof(WCHAR) );
282 if (!strncmpiW( p, wPath, 5 ))
284 p2[len - 1] = ';';
285 strcpyW( p2 + len, path );
286 p2 += strlenW(path) + 1;
288 p += len;
289 p2 += len;
291 if (!got_path)
293 strcpyW( p2, wPath );
294 strcatW( p2, path );
295 p2 += strlenW(p2) + 1;
297 *p2 = 0;
298 FreeEnvironmentStringsW( strings );
299 return new_env;
303 /***********************************************************************
304 * SHELL_TryAppPathW [Internal]
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
311 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, void**env)
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;
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;
328 len = MAX_PATH*sizeof(WCHAR);
329 res = RegQueryValueW(hkApp, NULL, lpResult, &len);
330 if (res) goto end;
331 found = TRUE;
333 if (env)
335 DWORD count = sizeof(buffer);
336 if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
337 *env = SHELL_BuildEnvW( buffer );
340 end:
341 if (hkApp) RegCloseKey(hkApp);
342 return found;
345 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
347 static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
349 /* Looking for ...buffer\shell\<verb>\command */
350 strcatW(filetype, wszShell);
351 strcatW(filetype, lpOperation);
352 strcatW(filetype, wCommand);
354 if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
355 &commandlen) == ERROR_SUCCESS)
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};
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
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)
378 paramlen /= sizeof(WCHAR);
379 strcatW(command, wSpace);
380 strcatW(command, param);
381 commandlen += paramlen;
383 #endif
385 command[commandlen] = '\0';
387 return 33; /* FIXME see SHELL_FindExecutable() */
390 return 31; /* default - 'No association was found' */
393 /*************************************************************************
394 * SHELL_FindExecutable [Internal]
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)
407 UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
408 LPWSTR lpResult, int resultLen, LPWSTR key, void **env, LPITEMIDLIST pidl, LPCWSTR args)
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]; /* result of SearchPath */
423 TRACE("%s\n", (lpFile != NULL) ? debugstr_w(lpFile) : "-");
425 xlpFile[0] = '\0';
426 lpResult[0] = '\0'; /* Start off with an empty return string */
427 if (key) *key = '\0';
429 /* trap NULL parameters on entry */
430 if ((lpFile == NULL) || (lpResult == NULL) || (lpOperation == NULL))
432 WARN("(lpFile=%s,lpResult=%s,lpOperation=%s): NULL parameter\n",
433 debugstr_w(lpFile), debugstr_w(lpOperation), debugstr_w(lpResult));
434 return 2; /* File not found. Close enough, I guess. */
437 if (SHELL_TryAppPathW( lpFile, lpResult, env ))
439 TRACE("found %s via App Paths\n", debugstr_w(lpResult));
440 return 33;
443 if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
445 TRACE("SearchPathW returned non-zero\n");
446 lpFile = xlpFile;
447 /* Hey, isn't this value ignored? Why make this call? Shouldn't we return here? --dank*/
450 /* First thing we need is the file's extension */
451 extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
452 /* File->Run in progman uses */
453 /* .\FILE.EXE :( */
454 TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
456 if ((extension == NULL) || (extension == &xlpFile[strlenW(xlpFile)]))
458 WARN("Returning 31 - No association\n");
459 return 31; /* no association */
462 /* Make local copy & lowercase it for reg & 'programs=' lookup */
463 lstrcpynW(wtmpext, extension, 5);
464 CharLowerW(wtmpext);
465 TRACE("%s file\n", debugstr_w(wtmpext));
467 /* Three places to check: */
468 /* 1. win.ini, [windows], programs (NB no leading '.') */
469 /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
470 /* 3. win.ini, [extensions], extension (NB no leading '.' */
471 /* All I know of the order is that registry is checked before */
472 /* extensions; however, it'd make sense to check the programs */
473 /* section first, so that's what happens here. */
475 /* See if it's a program - if GetProfileString fails, we skip this
476 * section. Actually, if GetProfileString fails, we've probably
477 * got a lot more to worry about than running a program... */
478 if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
480 CharLowerW(wBuffer);
481 tok = wBuffer;
482 while (*tok)
484 WCHAR *p = tok;
485 while (*p && *p != ' ' && *p != '\t') p++;
486 if (*p)
488 *p++ = 0;
489 while (*p == ' ' || *p == '\t') p++;
492 if (strcmpW(tok, &wtmpext[1]) == 0) /* have to skip the leading "." */
494 strcpyW(lpResult, xlpFile);
495 /* Need to perhaps check that the file has a path
496 * attached */
497 TRACE("found %s\n", debugstr_w(lpResult));
498 return 33;
500 /* Greater than 32 to indicate success FIXME According to the
501 * docs, I should be returning a handle for the
502 * executable. Does this mean I'm supposed to open the
503 * executable file or something? More RTFM, I guess... */
505 tok = p;
509 /* Check registry */
510 if (RegQueryValueW(HKEY_CLASSES_ROOT, wtmpext, filetype,
511 &filetypelen) == ERROR_SUCCESS)
513 filetypelen /= sizeof(WCHAR);
514 filetype[filetypelen] = '\0';
515 TRACE("File type: %s\n", debugstr_w(filetype));
518 if (*filetype)
520 if (lpOperation)
522 /* pass the operation string to SHELL_FindExecutableByOperation() */
523 filetype[filetypelen] = '\0';
524 retval = SHELL_FindExecutableByOperation(lpPath, lpFile, lpOperation, key, filetype, command, sizeof(command));
526 else
528 WCHAR operation[MAX_PATH];
529 HKEY hkey;
531 /* Looking for ...buffer\shell\<operation>\command */
532 strcatW(filetype, wszShell);
534 /* enumerate the operation subkeys in the registry and search for one with an associated command */
535 if (RegOpenKeyW(HKEY_CLASSES_ROOT, filetype, &hkey) == ERROR_SUCCESS)
537 int idx = 0;
538 for(;; ++idx)
540 if (RegEnumKeyW(hkey, idx, operation, MAX_PATH) != ERROR_SUCCESS)
541 break;
543 filetype[filetypelen] = '\0';
544 retval = SHELL_FindExecutableByOperation(lpPath, lpFile, operation, key, filetype, command, sizeof(command));
546 if (retval > 32)
547 break;
549 RegCloseKey(hkey);
553 if (retval > 32)
555 SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args);
557 /* Remove double quotation marks and command line arguments */
558 if (*lpResult == '"')
560 WCHAR *p = lpResult;
561 while (*(p + 1) != '"')
563 *p = *(p + 1);
564 p++;
566 *p = '\0';
570 else /* Check win.ini */
572 static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
573 static const WCHAR wEmpty[] = {0};
575 /* Toss the leading dot */
576 extension++;
577 if (GetProfileStringW(wExtensions, extension, wEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
579 if (strlenW(command) != 0)
581 strcpyW(lpResult, command);
582 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
583 if (tok != NULL)
585 tok[0] = '\0';
586 strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
587 tok = strchrW(command, '^'); /* see above */
588 if ((tok != NULL) && (strlenW(tok)>5))
590 strcatW(lpResult, &tok[5]);
593 retval = 33; /* FIXME - see above */
598 TRACE("returning %s\n", debugstr_w(lpResult));
599 return retval;
602 /******************************************************************
603 * dde_cb
605 * callback for the DDE connection. not really usefull
607 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
608 HSZ hsz1, HSZ hsz2,
609 HDDEDATA hData, DWORD dwData1, DWORD dwData2)
611 return NULL;
614 /******************************************************************
615 * dde_connect
617 * ShellExecute helper. Used to do an operation with a DDE connection
619 * Handles both the direct connection (try #1), and if it fails,
620 * launching an application and trying (#2) to connect to it
623 static unsigned dde_connect(WCHAR* key, WCHAR* start, WCHAR* ddeexec,
624 const WCHAR* lpFile, void *env,
625 LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
626 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
628 static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
629 static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
630 WCHAR * endkey = key + strlenW(key);
631 WCHAR app[256], topic[256], ifexec[256], res[256];
632 LONG applen, topiclen, ifexeclen;
633 WCHAR * exec;
634 DWORD ddeInst = 0;
635 DWORD tid;
636 HSZ hszApp, hszTopic;
637 HCONV hConv;
638 unsigned ret = 31;
640 strcpyW(endkey, wApplication);
641 applen = sizeof(app);
642 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, app, &applen) != ERROR_SUCCESS)
644 FIXME("default app name NIY %s\n", debugstr_w(key));
645 return 2;
648 strcpyW(endkey, wTopic);
649 topiclen = sizeof(topic);
650 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, topic, &topiclen) != ERROR_SUCCESS)
652 static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
653 strcpyW(topic, wSystem);
656 if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
658 return 2;
661 hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINANSI);
662 hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINANSI);
664 hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
665 exec = ddeexec;
666 if (!hConv)
668 static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
669 TRACE("Launching '%s'\n", debugstr_w(start));
670 ret = execfunc(start, env, TRUE, psei, psei_out);
671 if (ret < 32)
673 TRACE("Couldn't launch\n");
674 goto error;
676 hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
677 if (!hConv)
679 TRACE("Couldn't connect. ret=%d\n", ret);
680 DdeUninitialize(ddeInst);
681 SetLastError(ERROR_DDE_FAIL);
682 return 30; /* whatever */
684 strcpyW(endkey, wIfexec);
685 ifexeclen = sizeof(ifexec);
686 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ifexec, &ifexeclen) == ERROR_SUCCESS)
688 exec = ifexec;
692 SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline);
693 TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
695 ret = (DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
696 XTYP_EXECUTE, 10000, &tid) != DMLERR_NO_ERROR) ? 31 : 33;
697 DdeDisconnect(hConv);
699 error:
700 DdeUninitialize(ddeInst);
702 return ret;
705 /*************************************************************************
706 * execute_from_key [Internal]
708 static UINT execute_from_key(LPWSTR key, LPCWSTR lpFile, void *env, LPCWSTR szCommandline,
709 SHELL_ExecuteW32 execfunc,
710 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
712 WCHAR cmd[1024];
713 LONG cmdlen = sizeof(cmd);
714 UINT retval = 31;
716 cmd[0] = '\0';
718 /* Get the application for the registry */
719 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
721 static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
722 static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
723 LPWSTR tmp;
724 WCHAR param[256];
725 LONG paramlen = sizeof(param);
727 param[0] = '\0';
729 /* Get the parameters needed by the application
730 from the associated ddeexec key */
731 tmp = strstrW(key, wCommand);
732 assert(tmp);
733 strcpyW(tmp, wDdeexec);
735 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, param, &paramlen) == ERROR_SUCCESS)
737 TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(param));
738 retval = dde_connect(key, cmd, param, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
740 else
742 /* Is there a replace() function anywhere? */
743 cmdlen /= sizeof(WCHAR);
744 cmd[cmdlen] = '\0';
745 SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline);
746 retval = execfunc(param, env, FALSE, psei, psei_out);
749 else TRACE("ooch\n");
751 return retval;
754 /*************************************************************************
755 * FindExecutableA [SHELL32.@]
757 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
759 HINSTANCE retval;
760 WCHAR *wFile = NULL, *wDirectory = NULL;
761 WCHAR wResult[MAX_PATH];
763 if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
764 if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
766 retval = FindExecutableW(wFile, wDirectory, wResult);
767 WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
768 if (wFile) SHFree( wFile );
769 if (wDirectory) SHFree( wDirectory );
771 TRACE("returning %s\n", lpResult);
772 return (HINSTANCE)retval;
775 /*************************************************************************
776 * FindExecutableW [SHELL32.@]
778 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
780 UINT retval = 31; /* default - 'No association was found' */
781 WCHAR old_dir[1024];
783 TRACE("File %s, Dir %s\n",
784 (lpFile != NULL ? debugstr_w(lpFile) : "-"), (lpDirectory != NULL ? debugstr_w(lpDirectory) : "-"));
786 lpResult[0] = '\0'; /* Start off with an empty return string */
788 /* trap NULL parameters on entry */
789 if ((lpFile == NULL) || (lpResult == NULL))
791 /* FIXME - should throw a warning, perhaps! */
792 return (HINSTANCE)2; /* File not found. Close enough, I guess. */
795 if (lpDirectory)
797 GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
798 SetCurrentDirectoryW(lpDirectory);
801 retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
803 TRACE("returning %s\n", debugstr_w(lpResult));
804 if (lpDirectory)
805 SetCurrentDirectoryW(old_dir);
806 return (HINSTANCE)retval;
809 /*************************************************************************
810 * ShellExecuteExW32 [Internal]
812 BOOL WINAPI ShellExecuteExW32 (LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc)
814 static const WCHAR wQuote[] = {'"',0};
815 static const WCHAR wSpace[] = {' ',0};
816 static const WCHAR wWww[] = {'w','w','w',0};
817 static const WCHAR wFile[] = {'f','i','l','e',0};
818 static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
820 WCHAR wszApplicationName[MAX_PATH+2], wszCommandline[1024], wszDir[MAX_PATH];
821 SHELLEXECUTEINFOW sei_tmp; /* modifyable copy of SHELLEXECUTEINFO struct */
822 WCHAR wfileName[MAX_PATH];
823 void *env;
824 WCHAR lpstrProtocol[256];
825 LPCWSTR lpFile;
826 UINT retval = 31;
827 WCHAR wcmd[1024];
828 WCHAR buffer[MAX_PATH];
829 BOOL done;
831 /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
832 memcpy(&sei_tmp, sei, sizeof(sei_tmp));
834 TRACE("mask=0x%08lx hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
835 sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
836 debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
837 debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
838 (sei_tmp.fMask & SEE_MASK_CLASSNAME) ? debugstr_w(sei_tmp.lpClass) : "not used");
840 sei->hProcess = NULL;
842 /* make copies of all path/command strings */
843 if (sei_tmp.lpFile)
844 strcpyW(wszApplicationName, sei_tmp.lpFile);
845 else
846 *wszApplicationName = '\0';
848 if (sei_tmp.lpParameters)
849 strcpyW(wszCommandline, sei_tmp.lpParameters);
850 else
851 *wszCommandline = '\0';
853 if (sei_tmp.lpDirectory)
854 strcpyW(wszDir, sei_tmp.lpDirectory);
855 else
856 *wszDir = '\0';
858 /* adjust string pointers to point to the new buffers */
859 sei_tmp.lpFile = wszApplicationName;
860 sei_tmp.lpParameters = wszCommandline;
861 sei_tmp.lpDirectory = wszDir;
863 if (sei_tmp.fMask & (SEE_MASK_INVOKEIDLIST | SEE_MASK_ICON | SEE_MASK_HOTKEY |
864 SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT |
865 SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI | SEE_MASK_UNICODE |
866 SEE_MASK_NO_CONSOLE | SEE_MASK_ASYNCOK | SEE_MASK_HMONITOR ))
868 FIXME("flags ignored: 0x%08lx\n", sei_tmp.fMask);
871 /* process the IDList */
872 if (sei_tmp.fMask & SEE_MASK_IDLIST)
874 IShellExecuteHookW* pSEH;
876 HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
878 if (SUCCEEDED(hr))
880 hr = IShellExecuteHookW_Execute(pSEH, sei);
882 IShellExecuteHookW_Release(pSEH);
884 if (hr == S_OK)
885 return TRUE;
888 wszApplicationName[0] = '"';
889 SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName+1);
890 strcatW(wszApplicationName, wQuote);
891 TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
894 if (sei_tmp.fMask & (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY))
896 /* launch a document by fileclass like 'WordPad.Document.1' */
897 /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
898 /* FIXME: szCommandline should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
899 HCR_GetExecuteCommandW((sei_tmp.fMask & SEE_MASK_CLASSKEY) ? sei_tmp.hkeyClass : NULL,
900 (sei_tmp.fMask & SEE_MASK_CLASSNAME) ? sei_tmp.lpClass: NULL,
901 (sei_tmp.lpVerb) ? sei_tmp.lpVerb : wszOpen,
902 wszCommandline, sizeof(wszCommandline)/sizeof(WCHAR));
904 /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
905 TRACE("SEE_MASK_CLASSNAME->'%s', doc->'%s'\n", debugstr_w(wszCommandline), debugstr_w(wszApplicationName));
907 wcmd[0] = '\0';
908 done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), wszCommandline, wszApplicationName, sei_tmp.lpIDList, NULL);
909 if (!done && wszApplicationName[0])
911 strcatW(wcmd, wSpace);
912 strcatW(wcmd, wszApplicationName);
914 retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
915 if (retval > 32)
916 return TRUE;
917 else
918 return FALSE;
921 /* expand environment strings */
922 if (ExpandEnvironmentStringsW(sei_tmp.lpFile, buffer, MAX_PATH))
923 lstrcpyW(wszApplicationName, buffer);
925 if (*sei_tmp.lpParameters)
926 if (ExpandEnvironmentStringsW(sei_tmp.lpParameters, buffer, MAX_PATH))
927 lstrcpyW(wszCommandline, buffer);
929 if (*sei_tmp.lpDirectory)
930 if (ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buffer, MAX_PATH))
931 lstrcpyW(wszDir, buffer);
933 /* Else, try to execute the filename */
934 TRACE("execute:'%s','%s','%s'\n", debugstr_w(wszApplicationName), debugstr_w(wszCommandline), debugstr_w(wszDir));
936 strcpyW(wfileName, wszApplicationName);
937 lpFile = wfileName;
938 if (wszCommandline[0]) {
939 strcatW(wszApplicationName, wSpace);
940 strcatW(wszApplicationName, wszCommandline);
943 retval = execfunc(wszApplicationName, NULL, FALSE, &sei_tmp, sei);
944 if (retval > 32)
945 return TRUE;
947 /* Else, try to find the executable */
948 wcmd[0] = '\0';
949 retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, 1024, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
950 if (retval > 32) /* Found */
952 WCHAR wszQuotedCmd[MAX_PATH+2];
953 /* Must quote to handle case where cmd contains spaces,
954 * else security hole if malicious user creates executable file "C:\\Program"
956 strcpyW(wszQuotedCmd, wQuote);
957 strcatW(wszQuotedCmd, wcmd);
958 strcatW(wszQuotedCmd, wQuote);
959 if (wszCommandline[0]) {
960 strcatW(wszQuotedCmd, wSpace);
961 strcatW(wszQuotedCmd, wszCommandline);
963 TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(sei_tmp.lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
964 if (*lpstrProtocol)
965 retval = execute_from_key(lpstrProtocol, wszApplicationName, env, sei_tmp.lpParameters, execfunc, &sei_tmp, sei);
966 else
967 retval = execfunc(wszQuotedCmd, env, FALSE, &sei_tmp, sei);
968 if (env) HeapFree( GetProcessHeap(), 0, env );
970 else if (PathIsURLW((LPWSTR)lpFile)) /* File not found, check for URL */
972 static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
973 static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
974 LPWSTR lpstrRes;
975 INT iSize;
977 lpstrRes = strchrW(lpFile, ':');
978 if (lpstrRes)
979 iSize = lpstrRes - lpFile;
980 else
981 iSize = strlenW(lpFile);
983 TRACE("Got URL: %s\n", debugstr_w(lpFile));
984 /* Looking for ...protocol\shell\lpOperation\command */
985 strncpyW(lpstrProtocol, lpFile, iSize);
986 lpstrProtocol[iSize] = '\0';
987 strcatW(lpstrProtocol, wShell);
988 strcatW(lpstrProtocol, sei_tmp.lpVerb? sei_tmp.lpVerb: wszOpen);
989 strcatW(lpstrProtocol, wCommand);
991 /* Remove File Protocol from lpFile */
992 /* In the case file://path/file */
993 if (!strncmpiW(lpFile, wFile, iSize))
995 lpFile += iSize;
996 while (*lpFile == ':') lpFile++;
998 retval = execute_from_key(lpstrProtocol, lpFile, NULL, sei_tmp.lpParameters, execfunc, &sei_tmp, sei);
1000 /* Check if file specified is in the form www.??????.*** */
1001 else if (!strncmpiW(lpFile, wWww, 3))
1003 /* if so, append lpFile http:// and call ShellExecute */
1004 WCHAR lpstrTmpFile[256];
1005 strcpyW(lpstrTmpFile, wHttp);
1006 strcatW(lpstrTmpFile, lpFile);
1007 retval = (UINT)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1010 TRACE("retval %u\n", retval);
1012 if (retval <= 32)
1014 sei->hInstApp = (HINSTANCE)retval;
1015 return FALSE;
1018 sei->hInstApp = (HINSTANCE)33;
1019 return TRUE;
1022 /*************************************************************************
1023 * ShellExecuteA [SHELL32.290]
1025 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1026 LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1028 SHELLEXECUTEINFOA sei;
1029 HANDLE hProcess = 0;
1031 TRACE("\n");
1032 sei.cbSize = sizeof(sei);
1033 sei.fMask = 0;
1034 sei.hwnd = hWnd;
1035 sei.lpVerb = lpOperation;
1036 sei.lpFile = lpFile;
1037 sei.lpParameters = lpParameters;
1038 sei.lpDirectory = lpDirectory;
1039 sei.nShow = iShowCmd;
1040 sei.lpIDList = 0;
1041 sei.lpClass = 0;
1042 sei.hkeyClass = 0;
1043 sei.dwHotKey = 0;
1044 sei.hProcess = hProcess;
1046 ShellExecuteExA (&sei);
1047 return sei.hInstApp;
1050 /*************************************************************************
1051 * ShellExecuteEx [SHELL32.291]
1054 BOOL WINAPI ShellExecuteExAW (LPVOID sei)
1056 if (SHELL_OsIsUnicode())
1057 return ShellExecuteExW32 (sei, SHELL_ExecuteW);
1058 return ShellExecuteExA (sei);
1061 /*************************************************************************
1062 * ShellExecuteExA [SHELL32.292]
1065 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1067 SHELLEXECUTEINFOW seiW;
1068 BOOL ret;
1069 WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1071 TRACE("%p\n", sei);
1073 memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1075 if (sei->lpVerb)
1076 seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1078 if (sei->lpFile)
1079 seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1081 if (sei->lpParameters)
1082 seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1084 if (sei->lpDirectory)
1085 seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1087 if ((sei->fMask & SEE_MASK_CLASSNAME) && sei->lpClass)
1088 seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1089 else
1090 seiW.lpClass = NULL;
1092 ret = ShellExecuteExW32 (&seiW, SHELL_ExecuteW);
1094 sei->hInstApp = seiW.hInstApp;
1096 if (wVerb) SHFree(wVerb);
1097 if (wFile) SHFree(wFile);
1098 if (wParameters) SHFree(wParameters);
1099 if (wDirectory) SHFree(wDirectory);
1100 if (wClass) SHFree(wClass);
1102 return ret;
1105 /*************************************************************************
1106 * ShellExecuteExW [SHELL32.293]
1109 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1111 return ShellExecuteExW32 (sei, SHELL_ExecuteW);
1114 /*************************************************************************
1115 * ShellExecuteW [SHELL32.294]
1116 * from shellapi.h
1117 * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1118 * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1120 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1121 LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1123 SHELLEXECUTEINFOW sei;
1124 HANDLE hProcess = 0;
1126 TRACE("\n");
1127 sei.cbSize = sizeof(sei);
1128 sei.fMask = 0;
1129 sei.hwnd = hwnd;
1130 sei.lpVerb = lpOperation;
1131 sei.lpFile = lpFile;
1132 sei.lpParameters = lpParameters;
1133 sei.lpDirectory = lpDirectory;
1134 sei.nShow = nShowCmd;
1135 sei.lpIDList = 0;
1136 sei.lpClass = 0;
1137 sei.hkeyClass = 0;
1138 sei.dwHotKey = 0;
1139 sei.hProcess = hProcess;
1141 ShellExecuteExW32 (&sei, SHELL_ExecuteW);
1142 return sei.hInstApp;