Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / shell32 / shlexec.c
blob5c37902a3f11b8bd8359e279ba558346ec0ab151
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 #define COBJMACROS
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"
45 #include "wine/winbase16.h"
46 #include "shell32_main.h"
47 #include "pidl.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(exec);
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};
60 #define SEE_MASK_CLASSALL (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY)
63 /***********************************************************************
64 * SHELL_ArgifyW [Internal]
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)
79 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args, DWORD* out_len)
81 WCHAR xlpFile[1024];
82 BOOL done = FALSE;
83 BOOL found_p1 = FALSE;
84 PWSTR res = out;
85 PCWSTR cmd;
86 DWORD used = 0;
88 TRACE("%p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
89 debugstr_w(lpFile), pidl, args);
91 while (*fmt)
93 if (*fmt == '%')
95 switch (*++fmt)
97 case '\0':
98 case '%':
99 used++;
100 if (used < len)
101 *res++ = '%';
102 break;
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)
116 if (*fmt == '*')
118 used++;
119 if (used < len)
120 *res++ = '"';
121 while(*args)
123 used++;
124 if (used < len)
125 *res++ = *args++;
126 else
127 args++;
129 used++;
130 if (used < len)
131 *res++ = '"';
133 else
135 while(*args && !isspace(*args))
137 used++;
138 if (used < len)
139 *res++ = *args++;
140 else
141 args++;
144 while(isspace(*args))
145 ++args;
147 break;
149 /* else fall through */
150 case '1':
151 if (!done || (*fmt == '1'))
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;
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 != '"')
164 used++;
165 if (used < len)
166 *res++ = '"';
167 used += strlenW(cmd);
168 if (used < len)
170 strcpyW(res, cmd);
171 res += strlenW(cmd);
173 used++;
174 if (used < len)
175 *res++ = '"';
177 else
179 used += strlenW(cmd);
180 if (used < len)
182 strcpyW(res, cmd);
183 res += strlenW(cmd);
187 found_p1 = TRUE;
188 break;
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.
195 case 'l':
196 case 'L':
197 if (lpFile) {
198 used += strlenW(lpFile);
199 if (used < len)
201 strcpyW(res, lpFile);
202 res += strlenW(lpFile);
205 found_p1 = TRUE;
206 break;
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)
224 strcpyW(res,buf);
225 res += chars;
227 SHUnlockShared(pv);
229 found_p1 = TRUE;
230 break;
232 default:
234 * Check if this is an env-variable here...
237 /* Make sure that we have at least one more %.*/
238 if (strchrW(fmt, '%'))
240 WCHAR tmpBuffer[1024];
241 PWSTR tmpB = tmpBuffer;
242 WCHAR tmpEnvBuff[MAX_PATH];
243 DWORD envRet;
245 while (*fmt != '%')
246 *tmpB++ = *fmt++;
247 *tmpB++ = 0;
249 TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
251 envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
252 if (envRet == 0 || envRet > MAX_PATH)
254 used += strlenW(tmpBuffer);
255 if (used < len)
257 strcpyW( res, tmpBuffer );
258 res += strlenW(tmpBuffer);
261 else
263 used += strlenW(tmpEnvBuff);
264 if (used < len)
266 strcpyW( res, tmpEnvBuff );
267 res += strlenW(tmpEnvBuff);
271 done = TRUE;
272 break;
274 /* Don't skip past terminator (catch a single '%' at the end) */
275 if (*fmt != '\0')
277 fmt++;
280 else
282 used ++;
283 if (used < len)
284 *res++ = *fmt++;
285 else
286 fmt++;
290 *res = '\0';
291 TRACE("used %i of %i space\n",used,len);
292 if (out_len)
293 *out_len = used;
295 return found_p1;
298 static HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
300 STRRET strret;
301 IShellFolder* desktop;
303 HRESULT hr = SHGetDesktopFolder(&desktop);
305 if (SUCCEEDED(hr)) {
306 hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
308 if (SUCCEEDED(hr))
309 StrRetToStrNW(pszPath, uOutSize, &strret, pidl);
311 IShellFolder_Release(desktop);
314 return hr;
317 /*************************************************************************
318 * SHELL_ExecuteW [Internal]
321 static UINT_PTR SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
322 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
324 STARTUPINFOW startup;
325 PROCESS_INFORMATION info;
326 UINT_PTR retval = SE_ERR_NOASSOC;
327 UINT gcdret = 0;
328 WCHAR curdir[MAX_PATH];
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))
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 );
357 else if ((retval = GetLastError()) >= 32)
359 TRACE("CreateProcess returned error %d\n", retval);
360 retval = ERROR_BAD_FORMAT;
363 TRACE("returning %u\n", retval);
365 psei_out->hInstApp = (HINSTANCE)retval;
366 if( gcdret )
367 if( !SetCurrentDirectoryW( curdir))
368 ERR("cannot return to directory %s\n", debugstr_w(curdir));
370 return retval;
374 * Helper function for ShellExecuteExA
375 * In order to prevent opening of particular extension types
377 static BOOL verify_extension_permission(const WCHAR* ext)
379 static const WCHAR AppDefaultsW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
380 'A','p','p','D','e','f','a','u','l','t','s',0};
381 static const WCHAR DenyShellExecuteW[] = {'D','e','n','y','S','h','e','l','l','E','x','e','c','u','t','e',0};
382 WCHAR buffer[MAX_PATH];
383 WCHAR *filename;
384 HKEY hkey,appkey;
385 int RC;
386 DWORD type,count;
388 if(!GetModuleFileNameW(0,buffer,MAX_PATH))
389 return TRUE;
391 filename = PathFindFileNameW(buffer);
392 /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe */
393 if (RegOpenKeyW( HKEY_CURRENT_USER, AppDefaultsW, &hkey ))
394 return TRUE;
396 if (RegOpenKeyW( hkey, filename, &appkey )) appkey = 0;
397 RegCloseKey( hkey );
399 if (!appkey)
400 return TRUE;
402 RC = TRUE;
403 count = sizeof(buffer);
404 if (!RegQueryValueExW(appkey,DenyShellExecuteW,NULL,&type,(LPBYTE)buffer,&count))
406 WCHAR *s,*e;
407 int lext;
409 buffer[count / sizeof(WCHAR)] = 0;
410 ext++; /* Skip the '.' */
411 lext=strlenW(ext);
412 s=buffer;
413 while (*s) {
414 e=strchrW(s,';');
415 if (!e)
416 e=s+strlenW(s);
417 if ((e-s==lext) && (strncmpiW(ext,s,lext)==0))
419 RC=FALSE;
420 break;
422 s=(*e?e+1:e);
425 RegCloseKey(appkey);
426 return RC;
430 /***********************************************************************
431 * SHELL_BuildEnvW [Internal]
433 * Build the environment for the new process, adding the specified
434 * path to the PATH variable. Returned pointer must be freed by caller.
436 static void *SHELL_BuildEnvW( const WCHAR *path )
438 static const WCHAR wPath[] = {'P','A','T','H','=',0};
439 WCHAR *strings, *new_env;
440 WCHAR *p, *p2;
441 int total = strlenW(path) + 1;
442 BOOL got_path = FALSE;
444 if (!(strings = GetEnvironmentStringsW())) return NULL;
445 p = strings;
446 while (*p)
448 int len = strlenW(p) + 1;
449 if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
450 total += len;
451 p += len;
453 if (!got_path) total += 5; /* we need to create PATH */
454 total++; /* terminating null */
456 if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
458 FreeEnvironmentStringsW( strings );
459 return NULL;
461 p = strings;
462 p2 = new_env;
463 while (*p)
465 int len = strlenW(p) + 1;
466 memcpy( p2, p, len * sizeof(WCHAR) );
467 if (!strncmpiW( p, wPath, 5 ))
469 p2[len - 1] = ';';
470 strcpyW( p2 + len, path );
471 p2 += strlenW(path) + 1;
473 p += len;
474 p2 += len;
476 if (!got_path)
478 strcpyW( p2, wPath );
479 strcatW( p2, path );
480 p2 += strlenW(p2) + 1;
482 *p2 = 0;
483 FreeEnvironmentStringsW( strings );
484 return new_env;
488 /***********************************************************************
489 * SHELL_TryAppPathW [Internal]
491 * Helper function for SHELL_FindExecutable
492 * @param lpResult - pointer to a buffer of size MAX_PATH
493 * On entry: szName is a filename (probably without path separators).
494 * On exit: if szName found in "App Path", place full path in lpResult, and return true
496 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
498 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',
499 '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','A','p','p',' ','P','a','t','h','s','\\',0};
500 static const WCHAR wPath[] = {'P','a','t','h',0};
501 HKEY hkApp = 0;
502 WCHAR buffer[1024];
503 LONG len;
504 LONG res;
505 BOOL found = FALSE;
507 if (env) *env = NULL;
508 strcpyW(buffer, wszKeyAppPaths);
509 strcatW(buffer, szName);
510 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
511 if (res) goto end;
513 len = MAX_PATH*sizeof(WCHAR);
514 res = RegQueryValueW(hkApp, NULL, lpResult, &len);
515 if (res) goto end;
516 found = TRUE;
518 if (env)
520 DWORD count = sizeof(buffer);
521 if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
522 *env = SHELL_BuildEnvW( buffer );
525 end:
526 if (hkApp) RegCloseKey(hkApp);
527 return found;
530 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
532 static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
533 HKEY hkeyClass;
534 WCHAR verb[MAX_PATH];
536 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, filetype, 0, 0x02000000, &hkeyClass))
537 return SE_ERR_NOASSOC;
538 if (!HCR_GetDefaultVerbW(hkeyClass, lpOperation, verb, sizeof(verb)))
539 return SE_ERR_NOASSOC;
540 RegCloseKey(hkeyClass);
542 /* Looking for ...buffer\shell\<verb>\command */
543 strcatW(filetype, wszShell);
544 strcatW(filetype, verb);
545 strcatW(filetype, wCommand);
547 if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
548 &commandlen) == ERROR_SUCCESS)
550 commandlen /= sizeof(WCHAR);
551 if (key) strcpyW(key, filetype);
552 #if 0
553 LPWSTR tmp;
554 WCHAR param[256];
555 LONG paramlen = sizeof(param);
556 static const WCHAR wSpace[] = {' ',0};
558 /* FIXME: it seems all Windows version don't behave the same here.
559 * the doc states that this ddeexec information can be found after
560 * the exec names.
561 * on Win98, it doesn't appear, but I think it does on Win2k
563 /* Get the parameters needed by the application
564 from the associated ddeexec key */
565 tmp = strstrW(filetype, wCommand);
566 tmp[0] = '\0';
567 strcatW(filetype, wDdeexec);
568 if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, param,
569 &paramlen) == ERROR_SUCCESS)
571 paramlen /= sizeof(WCHAR);
572 strcatW(command, wSpace);
573 strcatW(command, param);
574 commandlen += paramlen;
576 #endif
578 command[commandlen] = '\0';
580 return 33; /* FIXME see SHELL_FindExecutable() */
583 return SE_ERR_NOASSOC;
586 /*************************************************************************
587 * SHELL_FindExecutable [Internal]
589 * Utility for code sharing between FindExecutable and ShellExecute
590 * in:
591 * lpFile the name of a file
592 * lpOperation the operation on it (open)
593 * out:
594 * lpResult a buffer, big enough :-(, to store the command to do the
595 * operation on the file
596 * key a buffer, big enough, to get the key name to do actually the
597 * command (it'll be used afterwards for more information
598 * on the operation)
600 UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
601 LPWSTR lpResult, int resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
603 static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
604 static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
605 static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
606 WCHAR *extension = NULL; /* pointer to file extension */
607 WCHAR filetype[256]; /* registry name for this filetype */
608 LONG filetypelen = sizeof(filetype); /* length of above */
609 WCHAR command[1024]; /* command from registry */
610 WCHAR wBuffer[256]; /* Used to GetProfileString */
611 UINT retval = SE_ERR_NOASSOC;
612 WCHAR *tok; /* token pointer */
613 WCHAR xlpFile[256]; /* result of SearchPath */
614 DWORD attribs; /* file attributes */
616 TRACE("%s\n", debugstr_w(lpFile));
618 if (!lpResult)
619 return ERROR_INVALID_PARAMETER;
621 xlpFile[0] = '\0';
622 lpResult[0] = '\0'; /* Start off with an empty return string */
623 if (key) *key = '\0';
625 /* trap NULL parameters on entry */
626 if (!lpFile)
628 WARN("(lpFile=%s,lpResult=%s): NULL parameter\n",
629 debugstr_w(lpFile), debugstr_w(lpResult));
630 return ERROR_FILE_NOT_FOUND; /* File not found. Close enough, I guess. */
633 if (SHELL_TryAppPathW( lpFile, lpResult, env ))
635 TRACE("found %s via App Paths\n", debugstr_w(lpResult));
636 return 33;
639 if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
641 TRACE("SearchPathW returned non-zero\n");
642 lpFile = xlpFile;
643 /* Hey, isn't this value ignored? Why make this call? Shouldn't we return here? --dank*/
646 attribs = GetFileAttributesW(lpFile);
647 if (attribs!=INVALID_FILE_ATTRIBUTES && (attribs&FILE_ATTRIBUTE_DIRECTORY))
649 strcpyW(filetype, wszFolder);
650 filetypelen = 6; /* strlen("Folder") */
652 else
654 /* First thing we need is the file's extension */
655 extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
656 /* File->Run in progman uses */
657 /* .\FILE.EXE :( */
658 TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
660 if (extension == NULL || extension[1]==0)
662 WARN("Returning SE_ERR_NOASSOC\n");
663 return SE_ERR_NOASSOC;
666 if (!verify_extension_permission(extension)) return 31; /* no association */
668 /* Three places to check: */
669 /* 1. win.ini, [windows], programs (NB no leading '.') */
670 /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
671 /* 3. win.ini, [extensions], extension (NB no leading '.' */
672 /* All I know of the order is that registry is checked before */
673 /* extensions; however, it'd make sense to check the programs */
674 /* section first, so that's what happens here. */
676 /* See if it's a program - if GetProfileString fails, we skip this
677 * section. Actually, if GetProfileString fails, we've probably
678 * got a lot more to worry about than running a program... */
679 if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
681 CharLowerW(wBuffer);
682 tok = wBuffer;
683 while (*tok)
685 WCHAR *p = tok;
686 while (*p && *p != ' ' && *p != '\t') p++;
687 if (*p)
689 *p++ = 0;
690 while (*p == ' ' || *p == '\t') p++;
693 if (strcmpiW(tok, &extension[1]) == 0) /* have to skip the leading "." */
695 strcpyW(lpResult, xlpFile);
696 /* Need to perhaps check that the file has a path
697 * attached */
698 TRACE("found %s\n", debugstr_w(lpResult));
699 return 33;
701 /* Greater than 32 to indicate success FIXME According to the
702 * docs, I should be returning a handle for the
703 * executable. Does this mean I'm supposed to open the
704 * executable file or something? More RTFM, I guess... */
706 tok = p;
710 /* Check registry */
711 if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, filetype,
712 &filetypelen) == ERROR_SUCCESS)
714 filetypelen /= sizeof(WCHAR);
715 filetype[filetypelen] = '\0';
716 TRACE("File type: %s\n", debugstr_w(filetype));
718 else
720 *filetype = '\0';
721 filetypelen = 0;
725 if (*filetype)
727 /* pass the operation string to SHELL_FindExecutableByOperation() */
728 filetype[filetypelen] = '\0';
729 retval = SHELL_FindExecutableByOperation(lpOperation, key, filetype, command, sizeof(command));
731 if (retval > 32)
733 DWORD finishedLen;
734 SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args, &finishedLen);
735 if (finishedLen > resultLen)
736 ERR("Argify buffer not large enough.. truncated\n");
738 /* Remove double quotation marks and command line arguments */
739 if (*lpResult == '"')
741 WCHAR *p = lpResult;
742 while (*(p + 1) != '"')
744 *p = *(p + 1);
745 p++;
747 *p = '\0';
749 else
751 /* Truncate on first space, like Windows:
752 * http://support.microsoft.com/?scid=kb%3Ben-us%3B140724
754 WCHAR *p = lpResult;
755 while (*p != ' ' && *p != '\0')
756 p++;
757 *p='\0';
761 else /* Check win.ini */
763 static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
765 /* Toss the leading dot */
766 extension++;
767 if (GetProfileStringW(wExtensions, extension, wszEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
769 if (strlenW(command) != 0)
771 strcpyW(lpResult, command);
772 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
773 if (tok != NULL)
775 tok[0] = '\0';
776 strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
777 tok = strchrW(command, '^'); /* see above */
778 if ((tok != NULL) && (strlenW(tok)>5))
780 strcatW(lpResult, &tok[5]);
783 retval = 33; /* FIXME - see above */
788 TRACE("returning %s\n", debugstr_w(lpResult));
789 return retval;
792 /******************************************************************
793 * dde_cb
795 * callback for the DDE connection. not really useful
797 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
798 HSZ hsz1, HSZ hsz2, HDDEDATA hData,
799 ULONG_PTR dwData1, ULONG_PTR dwData2)
801 TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
802 uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
803 return NULL;
806 /******************************************************************
807 * dde_connect
809 * ShellExecute helper. Used to do an operation with a DDE connection
811 * Handles both the direct connection (try #1), and if it fails,
812 * launching an application and trying (#2) to connect to it
815 static unsigned dde_connect(WCHAR* key, const WCHAR* start, WCHAR* ddeexec,
816 const WCHAR* lpFile, WCHAR *env,
817 LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
818 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
820 static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
821 static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
822 WCHAR * endkey = key + strlenW(key);
823 WCHAR app[256], topic[256], ifexec[256], res[256];
824 LONG applen, topiclen, ifexeclen;
825 WCHAR * exec;
826 DWORD ddeInst = 0;
827 DWORD tid;
828 DWORD resultLen;
829 HSZ hszApp, hszTopic;
830 HCONV hConv;
831 HDDEDATA hDdeData;
832 unsigned ret = SE_ERR_NOASSOC;
833 BOOL unicode = !(GetVersion() & 0x80000000);
835 strcpyW(endkey, wApplication);
836 applen = sizeof(app);
837 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, app, &applen) != ERROR_SUCCESS)
839 FIXME("default app name NIY %s\n", debugstr_w(key));
840 return 2;
843 strcpyW(endkey, wTopic);
844 topiclen = sizeof(topic);
845 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, topic, &topiclen) != ERROR_SUCCESS)
847 static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
848 strcpyW(topic, wSystem);
851 if (unicode)
853 if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
854 return 2;
856 else
858 if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
859 return 2;
862 hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
863 hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
865 hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
866 exec = ddeexec;
867 if (!hConv)
869 static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
870 TRACE("Launching %s\n", debugstr_w(start));
871 ret = execfunc(start, env, TRUE, psei, psei_out);
872 if (ret <= 32)
874 TRACE("Couldn't launch\n");
875 goto error;
877 hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
878 if (!hConv)
880 TRACE("Couldn't connect. ret=%d\n", ret);
881 DdeUninitialize(ddeInst);
882 SetLastError(ERROR_DDE_FAIL);
883 return 30; /* whatever */
885 strcpyW(endkey, wIfexec);
886 ifexeclen = sizeof(ifexec);
887 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ifexec, &ifexeclen) == ERROR_SUCCESS)
889 exec = ifexec;
893 SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline, &resultLen);
894 if (resultLen > sizeof(res)/sizeof(WCHAR))
895 ERR("Argify buffer not large enough, truncated\n");
896 TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
898 /* It's documented in the KB 330337 that IE has a bug and returns
899 * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
901 if (unicode)
902 hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
903 XTYP_EXECUTE, 30000, &tid);
904 else
906 DWORD lenA = WideCharToMultiByte(CP_ACP, 0, res, -1, NULL, 0, NULL, NULL);
907 char *resA = HeapAlloc(GetProcessHeap(), 0, lenA);
908 WideCharToMultiByte(CP_ACP, 0, res, -1, resA, lenA, NULL, NULL);
909 hDdeData = DdeClientTransaction( (LPBYTE)resA, lenA, hConv, 0L, 0,
910 XTYP_EXECUTE, 10000, &tid );
911 HeapFree(GetProcessHeap(), 0, resA);
913 if (hDdeData)
914 DdeFreeDataHandle(hDdeData);
915 else
916 WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
917 ret = 33;
919 DdeDisconnect(hConv);
921 error:
922 DdeUninitialize(ddeInst);
924 return ret;
927 /*************************************************************************
928 * execute_from_key [Internal]
930 static UINT_PTR execute_from_key(LPWSTR key, LPCWSTR lpFile, WCHAR *env, LPCWSTR szCommandline,
931 LPCWSTR executable_name,
932 SHELL_ExecuteW32 execfunc,
933 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
935 WCHAR cmd[256];
936 LONG cmdlen = sizeof(cmd);
937 UINT_PTR retval = SE_ERR_NOASSOC;
939 TRACE("%s %s %s %s %s\n", debugstr_w(key), debugstr_w(lpFile), debugstr_w(env),
940 debugstr_w(szCommandline), debugstr_w(executable_name));
942 cmd[0] = '\0';
944 /* Get the application from the registry */
945 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
947 WCHAR param[1024];
948 DWORD resultLen;
950 TRACE("got cmd: %s\n", debugstr_w(cmd));
952 param[0] = '\0';
954 /* Is there a replace() function anywhere? */
955 cmdlen /= sizeof(WCHAR);
956 cmd[cmdlen] = '\0';
957 if (!SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline, &resultLen) && lpFile[0])
959 /* looks like there is no %1 param in the cmd, add one */
960 static const WCHAR oneW[] = { ' ','\"','%','1','\"',0 };
961 strcatW(cmd, oneW);
962 SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline, &resultLen);
964 if (resultLen > sizeof(param)/sizeof(WCHAR))
965 ERR("Argify buffer not large enough, truncating\n");
967 TRACE("executing: %s\n", debugstr_w(param));
968 retval = execfunc(param, env, FALSE, psei, psei_out);
970 else
972 static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
973 static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
974 LPWSTR tmp;
975 WCHAR param[256];
976 LONG paramlen = sizeof(param);
978 param[0] = '\0';
980 /* Get the parameters needed by the application
981 from the associated ddeexec key */
982 tmp = strstrW(key, wCommand);
983 assert(tmp);
984 strcpyW(tmp, wDdeexec);
986 TRACE("trying ddeexec cmd: %s\n", debugstr_w(key));
988 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, param, &paramlen) == ERROR_SUCCESS)
990 TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(param));
991 retval = dde_connect(key, executable_name, param, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
993 else
994 WARN("Nothing appropriate found for %s\n", debugstr_w(key));
997 return retval;
1000 /*************************************************************************
1001 * FindExecutableA [SHELL32.@]
1003 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
1005 HINSTANCE retval;
1006 WCHAR *wFile = NULL, *wDirectory = NULL;
1007 WCHAR wResult[MAX_PATH];
1009 if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
1010 if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
1012 retval = FindExecutableW(wFile, wDirectory, wResult);
1013 WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
1014 SHFree( wFile );
1015 SHFree( wDirectory );
1017 TRACE("returning %s\n", lpResult);
1018 return retval;
1021 static UINT_PTR SHELL_CrossOverFallback(const WCHAR* lpFile, const WCHAR* lpVerb, WCHAR* cmdFormat, int cmdFormatSize)
1023 /* See if there is a native association for this file.
1024 * This is a CodeWeavers only hack.
1026 * But before that, check that this is not the file we just opened
1027 * in order to avoid native -> wine -> native association loops.
1029 UINT_PTR retval = SE_ERR_NOASSOC;
1030 static const WCHAR NoCrossOverFallbackW[] = {'N','O','C','R','O','S','S','O','V','E','R','F','A','L','L','B','A','C','K',0};
1031 WCHAR* nofallback=NULL;
1032 int size=GetEnvironmentVariableW(NoCrossOverFallbackW, NULL, 0);
1033 if (size)
1035 nofallback=HeapAlloc(GetProcessHeap(), 0, size*sizeof(*nofallback));
1036 GetEnvironmentVariableW(NoCrossOverFallbackW, nofallback, size);
1037 TRACE("NoCrossOverFallback=%s\n", debugstr_w(nofallback));
1039 if (!nofallback || strcmpW(nofallback, lpFile) != 0)
1041 WCHAR szFallback[MAX_PATH] = {'C','r','o','s','s','O','v','e','r','F','a','l','l','b','a','c','k',0};
1043 TRACE("Trying CrossOverFallback, verb=%s\n", debugstr_w(lpVerb));
1044 retval=SHELL_FindExecutableByOperation(lpVerb, NULL, szFallback, cmdFormat, cmdFormatSize);
1046 if (nofallback)
1047 HeapFree(GetProcessHeap(), 0, nofallback);
1048 TRACE("CrossOverFallback returning %d\n", retval);
1049 return retval;
1052 /*************************************************************************
1053 * FindExecutableW [SHELL32.@]
1055 * This function returns the executable associated with the specified file
1056 * for the default verb.
1058 * PARAMS
1059 * lpFile [I] The file to find the association for. This must refer to
1060 * an existing file otherwise FindExecutable fails and returns
1061 * SE_ERR_FNF.
1062 * lpResult [O] Points to a buffer into which the executable path is
1063 * copied. This parameter must not be NULL otherwise
1064 * FindExecutable() segfaults. The buffer must be of size at
1065 * least MAX_PATH characters.
1067 * RETURNS
1068 * A value greater than 32 on success, less than or equal to 32 otherwise.
1069 * See the SE_ERR_* constants.
1071 * NOTES
1072 * On Windows XP and 2003, FindExecutable() seems to first convert the
1073 * filename into 8.3 format, thus taking into account only the first three
1074 * characters of the extension, and expects to find an association for those.
1075 * However other Windows versions behave sanely.
1077 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
1079 UINT_PTR retval = SE_ERR_NOASSOC;
1080 WCHAR old_dir[1024];
1082 TRACE("File %s, Dir %s\n", debugstr_w(lpFile), debugstr_w(lpDirectory));
1084 lpResult[0] = '\0'; /* Start off with an empty return string */
1085 if (lpFile == NULL)
1086 return (HINSTANCE)SE_ERR_FNF;
1088 if (lpDirectory)
1090 GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
1091 SetCurrentDirectoryW(lpDirectory);
1094 retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
1096 if (retval <= 32)
1098 retval=SHELL_CrossOverFallback(lpFile, wszOpen, lpResult, MAX_PATH*sizeof(*lpResult));
1099 if (retval > 32)
1101 /* Remove double quotation marks and command line arguments */
1102 if (*lpResult == '"')
1104 WCHAR *p = lpResult;
1105 while (*(p + 1) != '"')
1107 *p = *(p + 1);
1108 p++;
1110 *p = '\0';
1112 else
1114 /* Truncate on first space, like Windows:
1115 * http://support.microsoft.com/?scid=kb%3Ben-us%3B140724
1117 WCHAR *p = lpResult;
1118 while (*p != ' ' && *p != '\0')
1119 p++;
1120 *p='\0';
1125 TRACE("returning %s\n", debugstr_w(lpResult));
1126 if (lpDirectory)
1127 SetCurrentDirectoryW(old_dir);
1128 return (HINSTANCE)retval;
1131 /* FIXME: is this already implemented somewhere else? */
1132 static HKEY ShellExecute_GetClassKey( LPSHELLEXECUTEINFOW sei )
1134 LPCWSTR ext = NULL, lpClass = NULL;
1135 LPWSTR cls = NULL;
1136 DWORD type = 0, sz = 0;
1137 HKEY hkey = 0;
1138 LONG r;
1140 if (sei->fMask & SEE_MASK_CLASSALL)
1141 return sei->hkeyClass;
1143 if (sei->fMask & SEE_MASK_CLASSNAME)
1144 lpClass = sei->lpClass;
1145 else
1147 ext = PathFindExtensionW( sei->lpFile );
1148 TRACE("ext = %s\n", debugstr_w( ext ) );
1149 if (!ext)
1150 return hkey;
1152 r = RegOpenKeyW( HKEY_CLASSES_ROOT, ext, &hkey );
1153 if (r != ERROR_SUCCESS )
1154 return hkey;
1156 r = RegQueryValueExW( hkey, NULL, 0, &type, NULL, &sz );
1157 if ( r == ERROR_SUCCESS && type == REG_SZ )
1159 sz += sizeof (WCHAR);
1160 cls = HeapAlloc( GetProcessHeap(), 0, sz );
1161 cls[0] = 0;
1162 RegQueryValueExW( hkey, NULL, 0, &type, (LPBYTE) cls, &sz );
1165 RegCloseKey( hkey );
1166 lpClass = cls;
1169 TRACE("class = %s\n", debugstr_w(lpClass) );
1171 hkey = 0;
1172 if ( lpClass )
1173 RegOpenKeyW( HKEY_CLASSES_ROOT, lpClass, &hkey );
1175 HeapFree( GetProcessHeap(), 0, cls );
1177 return hkey;
1180 static IDataObject *shellex_get_dataobj( LPSHELLEXECUTEINFOW sei )
1182 LPCITEMIDLIST pidllast = NULL;
1183 IDataObject *dataobj = NULL;
1184 IShellFolder *shf = NULL;
1185 LPITEMIDLIST pidl = NULL;
1186 HRESULT r;
1188 if (sei->fMask & SEE_MASK_CLASSALL)
1189 pidl = sei->lpIDList;
1190 else
1192 WCHAR fullpath[MAX_PATH];
1194 fullpath[0] = 0;
1195 r = GetFullPathNameW( sei->lpFile, MAX_PATH, fullpath, NULL );
1196 if (!r)
1197 goto end;
1199 pidl = ILCreateFromPathW( fullpath );
1202 r = SHBindToParent( pidl, &IID_IShellFolder, (LPVOID*)&shf, &pidllast );
1203 if ( FAILED( r ) )
1204 goto end;
1206 IShellFolder_GetUIObjectOf( shf, NULL, 1, &pidllast,
1207 &IID_IDataObject, NULL, (LPVOID*) &dataobj );
1209 end:
1210 if ( pidl != sei->lpIDList )
1211 ILFree( pidl );
1212 if ( shf )
1213 IShellFolder_Release( shf );
1214 return dataobj;
1217 static HRESULT shellex_run_context_menu_default( IShellExtInit *obj,
1218 LPSHELLEXECUTEINFOW sei )
1220 IContextMenu *cm = NULL;
1221 CMINVOKECOMMANDINFOEX ici;
1222 MENUITEMINFOW info;
1223 WCHAR string[0x80];
1224 INT i, n, def = -1;
1225 HMENU hmenu = 0;
1226 HRESULT r;
1228 TRACE("%p %p\n", obj, sei );
1230 r = IShellExtInit_QueryInterface( obj, &IID_IContextMenu, (LPVOID*) &cm );
1231 if ( FAILED( r ) )
1232 return r;
1234 hmenu = CreateMenu();
1235 if ( !hmenu )
1236 goto end;
1238 /* the number of the last menu added is returned in r */
1239 r = IContextMenu_QueryContextMenu( cm, hmenu, 0, 0x20, 0x7fff, CMF_DEFAULTONLY );
1240 if ( FAILED( r ) )
1241 goto end;
1243 n = GetMenuItemCount( hmenu );
1244 for ( i = 0; i < n; i++ )
1246 memset( &info, 0, sizeof info );
1247 info.cbSize = sizeof info;
1248 info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_STATE | MIIM_DATA | MIIM_ID;
1249 info.dwTypeData = string;
1250 info.cch = sizeof string;
1251 string[0] = 0;
1252 GetMenuItemInfoW( hmenu, i, TRUE, &info );
1254 TRACE("menu %d %s %08x %08lx %08x %08x\n", i, debugstr_w(string),
1255 info.fState, info.dwItemData, info.fType, info.wID );
1256 if ( ( !sei->lpVerb && (info.fState & MFS_DEFAULT) ) ||
1257 ( sei->lpVerb && !lstrcmpiW( sei->lpVerb, string ) ) )
1259 def = i;
1260 break;
1264 r = E_FAIL;
1265 if ( def == -1 )
1266 goto end;
1268 memset( &ici, 0, sizeof ici );
1269 ici.cbSize = sizeof ici;
1270 ici.fMask = CMIC_MASK_UNICODE;
1271 ici.nShow = sei->nShow;
1272 ici.lpVerb = MAKEINTRESOURCEA( def );
1273 ici.hwnd = sei->hwnd;
1274 ici.lpParametersW = sei->lpParameters;
1276 r = IContextMenu_InvokeCommand( cm, (LPCMINVOKECOMMANDINFO) &ici );
1278 TRACE("invoke command returned %08x\n", r );
1280 end:
1281 if ( hmenu )
1282 DestroyMenu( hmenu );
1283 if ( cm )
1284 IContextMenu_Release( cm );
1285 return r;
1288 static HRESULT shellex_load_object_and_run( HKEY hkey, LPCGUID guid, LPSHELLEXECUTEINFOW sei )
1290 IDataObject *dataobj = NULL;
1291 IObjectWithSite *ows = NULL;
1292 IShellExtInit *obj = NULL;
1293 HRESULT r;
1295 TRACE("%p %s %p\n", hkey, debugstr_guid( guid ), sei );
1297 r = CoInitialize( NULL );
1298 if ( FAILED( r ) )
1299 goto end;
1301 r = CoCreateInstance( guid, NULL, CLSCTX_INPROC_SERVER,
1302 &IID_IShellExtInit, (LPVOID*)&obj );
1303 if ( FAILED( r ) )
1305 ERR("failed %08x\n", r );
1306 goto end;
1309 dataobj = shellex_get_dataobj( sei );
1310 if ( !dataobj )
1312 ERR("failed to get data object\n");
1313 goto end;
1316 r = IShellExtInit_Initialize( obj, NULL, dataobj, hkey );
1317 if ( FAILED( r ) )
1318 goto end;
1320 r = IShellExtInit_QueryInterface( obj, &IID_IObjectWithSite, (LPVOID*) &ows );
1321 if ( FAILED( r ) )
1322 goto end;
1324 IObjectWithSite_SetSite( ows, NULL );
1326 r = shellex_run_context_menu_default( obj, sei );
1328 end:
1329 if ( ows )
1330 IObjectWithSite_Release( ows );
1331 if ( dataobj )
1332 IDataObject_Release( dataobj );
1333 if ( obj )
1334 IShellExtInit_Release( obj );
1335 CoUninitialize();
1336 return r;
1340 /*************************************************************************
1341 * ShellExecute_FromContextMenu [Internal]
1343 static LONG ShellExecute_FromContextMenu( LPSHELLEXECUTEINFOW sei )
1345 static const WCHAR szcm[] = { 's','h','e','l','l','e','x','\\',
1346 'C','o','n','t','e','x','t','M','e','n','u','H','a','n','d','l','e','r','s',0 };
1347 HKEY hkey, hkeycm = 0;
1348 WCHAR szguid[39];
1349 HRESULT hr;
1350 GUID guid;
1351 DWORD i;
1352 LONG r;
1354 TRACE("%s\n", debugstr_w(sei->lpFile) );
1356 hkey = ShellExecute_GetClassKey( sei );
1357 if ( !hkey )
1358 return ERROR_FUNCTION_FAILED;
1360 r = RegOpenKeyW( hkey, szcm, &hkeycm );
1361 if ( r == ERROR_SUCCESS )
1363 i = 0;
1364 while ( 1 )
1366 r = RegEnumKeyW( hkeycm, i++, szguid, 39 );
1367 if ( r != ERROR_SUCCESS )
1368 break;
1370 hr = CLSIDFromString( szguid, &guid );
1371 if (SUCCEEDED(hr))
1373 /* stop at the first one that succeeds in running */
1374 hr = shellex_load_object_and_run( hkey, &guid, sei );
1375 if ( SUCCEEDED( hr ) )
1376 break;
1379 RegCloseKey( hkeycm );
1382 if ( hkey != sei->hkeyClass )
1383 RegCloseKey( hkey );
1384 return r;
1387 /*************************************************************************
1388 * SHELL_execute [Internal]
1390 BOOL SHELL_execute( LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc )
1392 static const WCHAR wQuote[] = {'"',0};
1393 static const WCHAR wSpace[] = {' ',0};
1394 static const WCHAR wWww[] = {'w','w','w',0};
1395 static const WCHAR wFile[] = {'f','i','l','e',0};
1396 static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
1397 static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r','.','e','x','e',0};
1398 static const DWORD unsupportedFlags =
1399 SEE_MASK_INVOKEIDLIST | SEE_MASK_ICON | SEE_MASK_HOTKEY |
1400 SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI |
1401 SEE_MASK_UNICODE | SEE_MASK_NO_CONSOLE | SEE_MASK_ASYNCOK |
1402 SEE_MASK_HMONITOR;
1404 WCHAR *wszApplicationName, wszParameters[1024], wszDir[MAX_PATH];
1405 DWORD dwApplicationNameLen = MAX_PATH+2;
1406 DWORD len;
1407 SHELLEXECUTEINFOW sei_tmp; /* modifiable copy of SHELLEXECUTEINFO struct */
1408 WCHAR wfileName[MAX_PATH];
1409 WCHAR *env;
1410 WCHAR lpstrProtocol[256];
1411 LPCWSTR lpFile;
1412 UINT_PTR retval = SE_ERR_NOASSOC;
1413 WCHAR wcmd[1024];
1414 WCHAR buffer[MAX_PATH];
1415 BOOL done;
1416 BOOL appKnownSingular = FALSE;
1418 /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
1419 memcpy(&sei_tmp, sei, sizeof(sei_tmp));
1421 TRACE("mask=0x%08x hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
1422 sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
1423 debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
1424 debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
1425 ((sei_tmp.fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME) ?
1426 debugstr_w(sei_tmp.lpClass) : "not used");
1428 sei->hProcess = NULL;
1430 /* make copies of all path/command strings */
1431 if (!sei_tmp.lpFile)
1433 wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1434 *wszApplicationName = '\0';
1436 else if (*sei_tmp.lpFile == '\"')
1438 DWORD l = strlenW(sei_tmp.lpFile+1);
1439 if(l >= dwApplicationNameLen) dwApplicationNameLen = l+1;
1440 wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1441 memcpy(wszApplicationName, sei_tmp.lpFile+1, (l+1)*sizeof(WCHAR));
1442 if (wszApplicationName[l-1] == '\"')
1443 wszApplicationName[l-1] = '\0';
1444 appKnownSingular = TRUE;
1445 TRACE("wszApplicationName=%s\n",debugstr_w(wszApplicationName));
1446 } else {
1447 DWORD l = strlenW(sei_tmp.lpFile)+1;
1448 if(l > dwApplicationNameLen) dwApplicationNameLen = l+1;
1449 wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1450 memcpy(wszApplicationName, sei_tmp.lpFile, l*sizeof(WCHAR));
1453 if (sei_tmp.lpParameters)
1454 strcpyW(wszParameters, sei_tmp.lpParameters);
1455 else
1456 *wszParameters = '\0';
1458 if (sei_tmp.lpDirectory)
1459 strcpyW(wszDir, sei_tmp.lpDirectory);
1460 else
1461 *wszDir = '\0';
1463 /* adjust string pointers to point to the new buffers */
1464 sei_tmp.lpFile = wszApplicationName;
1465 sei_tmp.lpParameters = wszParameters;
1466 sei_tmp.lpDirectory = wszDir;
1468 if (sei_tmp.fMask & unsupportedFlags)
1470 FIXME("flags ignored: 0x%08x\n", sei_tmp.fMask & unsupportedFlags);
1473 /* process the IDList */
1474 if (sei_tmp.fMask & SEE_MASK_IDLIST)
1476 IShellExecuteHookW* pSEH;
1478 HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
1480 if (SUCCEEDED(hr))
1482 hr = IShellExecuteHookW_Execute(pSEH, &sei_tmp);
1484 IShellExecuteHookW_Release(pSEH);
1486 if (hr == S_OK) {
1487 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1488 return TRUE;
1492 SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName);
1493 appKnownSingular = TRUE;
1494 TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1497 if ( ERROR_SUCCESS == ShellExecute_FromContextMenu( &sei_tmp ) )
1499 sei->hInstApp = (HINSTANCE) 33;
1500 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1501 return TRUE;
1504 if (sei_tmp.fMask & SEE_MASK_CLASSALL)
1506 /* launch a document by fileclass like 'WordPad.Document.1' */
1507 /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
1508 /* FIXME: szCommandline should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
1509 ULONG cmask=(sei_tmp.fMask & SEE_MASK_CLASSALL);
1510 DWORD resultLen;
1511 HCR_GetExecuteCommandW((cmask == SEE_MASK_CLASSKEY) ? sei_tmp.hkeyClass : NULL,
1512 (cmask == SEE_MASK_CLASSNAME) ? sei_tmp.lpClass: NULL,
1513 sei_tmp.lpVerb,
1514 wszParameters, sizeof(wszParameters)/sizeof(WCHAR));
1516 /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
1517 TRACE("SEE_MASK_CLASSNAME->%s, doc->%s\n", debugstr_w(wszParameters), debugstr_w(wszApplicationName));
1519 wcmd[0] = '\0';
1520 done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), wszParameters, wszApplicationName, sei_tmp.lpIDList, NULL, &resultLen);
1521 if (!done && wszApplicationName[0])
1523 /* looks like there is no %1 param in the cmd, add one */
1524 static const WCHAR oneW[] = { ' ','\"','%','1','\"',0 };
1525 strcatW(wszParameters, oneW);
1526 SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), wszParameters, wszApplicationName, sei_tmp.lpIDList, NULL, &resultLen);
1528 if (resultLen > sizeof(wcmd)/sizeof(WCHAR))
1529 ERR("Argify buffer not large enough... truncating\n");
1530 retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1532 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1533 return retval > 32;
1536 /* Has the IDList not yet been translated? */
1537 if (sei_tmp.fMask & SEE_MASK_IDLIST)
1539 /* last chance to translate IDList: now also allow CLSID paths */
1540 if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW(sei_tmp.lpIDList, buffer, sizeof(buffer)))) {
1541 if (buffer[0]==':' && buffer[1]==':') {
1542 /* open shell folder for the specified class GUID */
1543 strcpyW(wszParameters, buffer);
1544 strcpyW(wszApplicationName, wExplorer);
1545 appKnownSingular = TRUE;
1547 sei_tmp.fMask &= ~SEE_MASK_INVOKEIDLIST;
1548 } else {
1549 WCHAR target[MAX_PATH];
1550 DWORD attribs;
1551 DWORD resultLen;
1552 /* Check if we're executing a directory and if so use the
1553 handler for the Folder class */
1554 strcpyW(target, buffer);
1555 attribs = GetFileAttributesW(buffer);
1556 if (attribs != INVALID_FILE_ATTRIBUTES &&
1557 (attribs & FILE_ATTRIBUTE_DIRECTORY) &&
1558 HCR_GetExecuteCommandW(0, wszFolder,
1559 sei_tmp.lpVerb,
1560 buffer, sizeof(buffer))) {
1561 SHELL_ArgifyW(wszApplicationName, dwApplicationNameLen,
1562 buffer, target, sei_tmp.lpIDList, NULL, &resultLen);
1563 if (resultLen > dwApplicationNameLen)
1564 ERR("Argify buffer not large enough... truncating\n");
1565 appKnownSingular = FALSE;
1567 sei_tmp.fMask &= ~SEE_MASK_INVOKEIDLIST;
1572 /* expand environment strings */
1573 len = ExpandEnvironmentStringsW(sei_tmp.lpFile, NULL, 0);
1574 if (len>0)
1576 LPWSTR buf;
1577 buf = HeapAlloc(GetProcessHeap(),0,(len+1)*sizeof(WCHAR));
1579 ExpandEnvironmentStringsW(sei_tmp.lpFile, buf, len+1);
1580 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1581 dwApplicationNameLen = len+1;
1582 wszApplicationName = buf;
1583 /* appKnownSingular unmodified */
1585 sei_tmp.lpFile = wszApplicationName;
1588 if (*sei_tmp.lpParameters)
1590 len = ExpandEnvironmentStringsW(sei_tmp.lpParameters, NULL, 0);
1591 if (len > 0)
1593 LPWSTR buf;
1594 len++;
1595 buf = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
1596 ExpandEnvironmentStringsW(sei_tmp.lpParameters, buf, len);
1597 if (len > 1024)
1598 ERR("Parameters exceeds buffer size (%i > 1024)\n",len);
1599 lstrcpynW(wszParameters, buf, min(1024,len));
1600 HeapFree(GetProcessHeap(),0,buf);
1604 if (*sei_tmp.lpDirectory)
1606 len = ExpandEnvironmentStringsW(sei_tmp.lpDirectory, NULL, 0);
1607 if (len > 0)
1609 LPWSTR buf;
1610 len++;
1611 buf = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
1612 ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buf, len);
1613 if (len > 1024)
1614 ERR("Directory exceeds buffer size (%i > 1024)\n",len);
1615 lstrcpynW(wszDir, buf, min(1024,len));
1616 HeapFree(GetProcessHeap(),0,buf);
1620 /* Else, try to execute the filename */
1621 TRACE("execute:%s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1623 /* separate out command line arguments from executable file name */
1624 if (!*sei_tmp.lpParameters && !appKnownSingular) {
1625 /* If the executable path is quoted, handle the rest of the command line as parameters. */
1626 if (sei_tmp.lpFile[0] == '"') {
1627 LPWSTR src = wszApplicationName/*sei_tmp.lpFile*/ + 1;
1628 LPWSTR dst = wfileName;
1629 LPWSTR end;
1631 /* copy the unquoted executable path to 'wfileName' */
1632 while(*src && *src!='"')
1633 *dst++ = *src++;
1635 *dst = '\0';
1637 if (*src == '"') {
1638 end = ++src;
1640 while(isspace(*src))
1641 ++src;
1642 } else
1643 end = src;
1645 /* copy the parameter string to 'wszParameters' */
1646 strcpyW(wszParameters, src);
1648 /* terminate previous command string after the quote character */
1649 *end = '\0';
1651 else
1653 /* If the executable name is not quoted, we have to use this search loop here,
1654 that in CreateProcess() is not sufficient because it does not handle shell links. */
1655 WCHAR buffer[MAX_PATH], xlpFile[MAX_PATH];
1656 LPWSTR space, s;
1658 LPWSTR beg = wszApplicationName/*sei_tmp.lpFile*/;
1659 for(s=beg; (space=strchrW(s, ' ')); s=space+1) {
1660 int idx = space-sei_tmp.lpFile;
1661 memcpy(buffer, sei_tmp.lpFile, idx * sizeof(WCHAR));
1662 buffer[idx] = '\0';
1664 /*FIXME This finds directory paths if the targeted file name contains spaces. */
1665 if (SearchPathW(*sei_tmp.lpDirectory? sei_tmp.lpDirectory: NULL, buffer, wszExe, sizeof(xlpFile), xlpFile, NULL))
1667 /* separate out command from parameter string */
1668 LPCWSTR p = space + 1;
1670 while(isspaceW(*p))
1671 ++p;
1673 strcpyW(wszParameters, p);
1674 *space = '\0';
1676 break;
1680 strcpyW(wfileName, sei_tmp.lpFile);
1682 } else
1683 strcpyW(wfileName, sei_tmp.lpFile);
1685 lpFile = wfileName;
1687 strcpyW(wcmd, wszApplicationName);
1688 if (sei_tmp.lpParameters[0]) {
1689 strcatW(wcmd, wSpace);
1690 strcatW(wcmd, wszParameters);
1693 retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1694 if (retval > 32) {
1695 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1696 return TRUE;
1699 /* Else, try to find the executable */
1700 wcmd[0] = '\0';
1701 retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, 1024, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
1702 if (retval > 32) /* Found */
1704 WCHAR wszQuotedCmd[MAX_PATH+2];
1705 /* Must quote to handle case where cmd contains spaces,
1706 * else security hole if malicious user creates executable file "C:\\Program"
1708 strcpyW(wszQuotedCmd, wQuote);
1709 strcatW(wszQuotedCmd, wcmd);
1710 strcatW(wszQuotedCmd, wQuote);
1711 if (wszParameters[0]) {
1712 strcatW(wszQuotedCmd, wSpace);
1713 strcatW(wszQuotedCmd, wszParameters);
1715 TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(sei_tmp.lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
1716 if (*lpstrProtocol)
1717 retval = execute_from_key(lpstrProtocol, wszApplicationName, env, sei_tmp.lpParameters, wcmd, execfunc, &sei_tmp, sei);
1718 else
1719 retval = execfunc(wszQuotedCmd, env, FALSE, &sei_tmp, sei);
1720 HeapFree( GetProcessHeap(), 0, env );
1722 else if (PathIsURLW(lpFile)) /* File not found, check for URL */
1724 static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
1725 static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
1726 LPWSTR lpstrRes;
1727 INT iSize;
1729 lpstrRes = strchrW(lpFile, ':');
1730 if (lpstrRes)
1731 iSize = lpstrRes - lpFile;
1732 else
1733 iSize = strlenW(lpFile);
1735 TRACE("Got URL: %s\n", debugstr_w(lpFile));
1736 /* Looking for ...protocol\shell\lpOperation\command */
1737 memcpy(lpstrProtocol, lpFile, iSize*sizeof(WCHAR));
1738 lpstrProtocol[iSize] = '\0';
1739 strcatW(lpstrProtocol, wShell);
1740 strcatW(lpstrProtocol, sei_tmp.lpVerb? sei_tmp.lpVerb: wszOpen);
1741 strcatW(lpstrProtocol, wCommand);
1743 /* Remove File Protocol from lpFile */
1744 /* In the case file://path/file */
1745 if (!strncmpiW(lpFile, wFile, iSize))
1747 lpFile += iSize;
1748 while (*lpFile == ':') lpFile++;
1750 retval = execute_from_key(lpstrProtocol, lpFile, NULL, sei_tmp.lpParameters, wcmd, execfunc, &sei_tmp, sei);
1752 /* Check if file specified is in the form www.??????.*** */
1753 else if (!strncmpiW(lpFile, wWww, 3))
1755 /* if so, append lpFile http:// and call ShellExecute */
1756 WCHAR lpstrTmpFile[256];
1757 strcpyW(lpstrTmpFile, wHttp);
1758 strcatW(lpstrTmpFile, lpFile);
1759 retval = (UINT_PTR)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1761 else
1763 WCHAR wCmdFormat[1024];
1764 retval=SHELL_CrossOverFallback(lpFile, sei_tmp.lpVerb, wCmdFormat, sizeof(wCmdFormat));
1765 if (retval > 32)
1768 WCHAR wCommandLine[1024];
1769 DWORD len;
1770 TRACE("wCmdFormat=%s\n", debugstr_w(wCmdFormat));
1771 SHELL_ArgifyW(wCommandLine, 1024, wCmdFormat, lpFile, sei_tmp.lpIDList, NULL, &len);
1772 TRACE("wCommandLine=%s\n", debugstr_w(wCommandLine));
1773 sei_tmp.fMask|=SEE_MASK_NOCLOSEPROCESS;
1774 retval = execfunc(wCommandLine, env, FALSE, &sei_tmp, sei);
1775 if (retval > 32)
1777 DWORD retcode;
1778 WaitForSingleObject(sei->hProcess, INFINITE);
1779 GetExitCodeProcess(sei->hProcess, &retcode);
1780 CloseHandle(sei->hProcess);
1781 sei->hProcess=NULL;
1782 TRACE("CrossOverFallback returned %d\n", retcode);
1783 retval=(retcode == 0 ? 33 : 31);
1788 TRACE("retval %u\n", retval);
1790 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1792 sei->hInstApp = (HINSTANCE)(retval > 32 ? 33 : retval);
1793 return retval > 32;
1796 /*************************************************************************
1797 * ShellExecuteA [SHELL32.290]
1799 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1800 LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1802 SHELLEXECUTEINFOA sei;
1804 TRACE("%p,%s,%s,%s,%s,%d\n",
1805 hWnd, debugstr_a(lpOperation), debugstr_a(lpFile),
1806 debugstr_a(lpParameters), debugstr_a(lpDirectory), iShowCmd);
1808 sei.cbSize = sizeof(sei);
1809 sei.fMask = 0;
1810 sei.hwnd = hWnd;
1811 sei.lpVerb = lpOperation;
1812 sei.lpFile = lpFile;
1813 sei.lpParameters = lpParameters;
1814 sei.lpDirectory = lpDirectory;
1815 sei.nShow = iShowCmd;
1816 sei.lpIDList = 0;
1817 sei.lpClass = 0;
1818 sei.hkeyClass = 0;
1819 sei.dwHotKey = 0;
1820 sei.hProcess = 0;
1822 ShellExecuteExA (&sei);
1823 return sei.hInstApp;
1826 /*************************************************************************
1827 * ShellExecuteExA [SHELL32.292]
1830 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1832 SHELLEXECUTEINFOW seiW;
1833 BOOL ret;
1834 WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1836 TRACE("%p\n", sei);
1838 memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1840 if (sei->lpVerb)
1841 seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1843 if (sei->lpFile)
1844 seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1846 if (sei->lpParameters)
1847 seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1849 if (sei->lpDirectory)
1850 seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1852 if ((sei->fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME && sei->lpClass)
1853 seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1854 else
1855 seiW.lpClass = NULL;
1857 ret = SHELL_execute( &seiW, SHELL_ExecuteW );
1859 sei->hInstApp = seiW.hInstApp;
1861 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
1862 sei->hProcess = seiW.hProcess;
1864 SHFree(wVerb);
1865 SHFree(wFile);
1866 SHFree(wParameters);
1867 SHFree(wDirectory);
1868 SHFree(wClass);
1870 return ret;
1873 /*************************************************************************
1874 * ShellExecuteExW [SHELL32.293]
1877 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1879 return SHELL_execute( sei, SHELL_ExecuteW );
1882 /*************************************************************************
1883 * ShellExecuteW [SHELL32.294]
1884 * from shellapi.h
1885 * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1886 * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1888 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1889 LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1891 SHELLEXECUTEINFOW sei;
1893 TRACE("\n");
1894 sei.cbSize = sizeof(sei);
1895 sei.fMask = 0;
1896 sei.hwnd = hwnd;
1897 sei.lpVerb = lpOperation;
1898 sei.lpFile = lpFile;
1899 sei.lpParameters = lpParameters;
1900 sei.lpDirectory = lpDirectory;
1901 sei.nShow = nShowCmd;
1902 sei.lpIDList = 0;
1903 sei.lpClass = 0;
1904 sei.hkeyClass = 0;
1905 sei.dwHotKey = 0;
1906 sei.hProcess = 0;
1908 SHELL_execute( &sei, SHELL_ExecuteW );
1909 return sei.hInstApp;