[SHELL32] lpDirectory must have priority in ShellExecuteEx (#681)
[reactos.git] / dll / win32 / shell32 / shlexec.cpp
1 /*
2 * Shell Library Functions
3 *
4 * Copyright 1998 Marcus Meissner
5 * Copyright 2002 Eric Pouech
6 * Copyright 2018 Katayama Hirofumi MZ
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 */
22
23 #include "precomp.h"
24
25 WINE_DEFAULT_DEBUG_CHANNEL(exec);
26
27 static const WCHAR wszOpen[] = L"open";
28 static const WCHAR wszExe[] = L".exe";
29
30 #define SEE_MASK_CLASSALL (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY)
31
32 typedef UINT_PTR (*SHELL_ExecuteW32)(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
33 const SHELLEXECUTEINFOW *sei, LPSHELLEXECUTEINFOW sei_out);
34
35 static void ParseNoTildeEffect(PWSTR &res, LPCWSTR &args, DWORD &len, DWORD &used, int argNum)
36 {
37 bool firstCharQuote = false;
38 bool quotes_opened = false;
39 bool backslash_encountered = false;
40
41 for (int curArg = 0; curArg <= argNum && *args; ++curArg)
42 {
43 firstCharQuote = false;
44 if (*args == '"')
45 {
46 quotes_opened = true;
47 firstCharQuote = true;
48 args++;
49 }
50
51 while(*args)
52 {
53 if (*args == '\\')
54 {
55 // if we found a backslash then flip the variable
56 backslash_encountered = !backslash_encountered;
57 }
58 else if (*args == '"')
59 {
60 if (quotes_opened)
61 {
62 if (*(args + 1) != '"')
63 {
64 quotes_opened = false;
65 args++;
66 break;
67 }
68 else
69 {
70 args++;
71 }
72 }
73 else
74 {
75 quotes_opened = true;
76 }
77
78 backslash_encountered = false;
79 }
80 else
81 {
82 backslash_encountered = false;
83 if (*args == ' ' && !firstCharQuote)
84 break;
85 }
86
87 if (curArg == argNum)
88 {
89 used++;
90 if (used < len)
91 *res++ = *args;
92 }
93
94 args++;
95 }
96
97 while(*args == ' ')
98 ++args;
99 }
100 }
101
102 static void ParseTildeEffect(PWSTR &res, LPCWSTR &args, DWORD &len, DWORD &used, int argNum)
103 {
104 bool quotes_opened = false;
105 bool backslash_encountered = false;
106
107 for (int curArg = 0; curArg <= argNum && *args; ++curArg)
108 {
109 while(*args)
110 {
111 if (*args == '\\')
112 {
113 // if we found a backslash then flip the variable
114 backslash_encountered = !backslash_encountered;
115 }
116 else if (*args == '"')
117 {
118 if (quotes_opened)
119 {
120 if (*(args + 1) != '"')
121 {
122 quotes_opened = false;
123 }
124 else
125 {
126 args++;
127 }
128 }
129 else
130 {
131 quotes_opened = true;
132 }
133
134 backslash_encountered = false;
135 }
136 else
137 {
138 backslash_encountered = false;
139 if (*args == ' ' && !quotes_opened && curArg != argNum)
140 break;
141 }
142
143 if (curArg == argNum)
144 {
145 used++;
146 if (used < len)
147 *res++ = *args;
148 }
149
150 args++;
151 }
152 }
153 }
154
155 /***********************************************************************
156 * SHELL_ArgifyW [Internal]
157 *
158 * this function is supposed to expand the escape sequences found in the registry
159 * some diving reported that the following were used:
160 * + %1, %2... seem to report to parameter of index N in ShellExecute pmts
161 * %1 file
162 * %2 printer
163 * %3 driver
164 * %4 port
165 * %I address of a global item ID (explorer switch /idlist)
166 * %L seems to be %1 as long filename followed by the 8+3 variation
167 * %S ???
168 * %* all following parameters (see batfile)
169 *
170 * The way we parse the command line arguments was determined through extensive
171 * testing and can be summed up by the following rules"
172 *
173 * - %2
174 * - if first letter is " break on first non literal " and include any white spaces
175 * - if first letter is NOT " break on first " or white space
176 * - if " is opened any pair of consecutive " results in ONE literal "
177 *
178 * - %~2
179 * - use rules from here http://www.autohotkey.net/~deleyd/parameters/parameters.htm
180 */
181
182 static BOOL SHELL_ArgifyW(WCHAR* out, DWORD len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args, DWORD* out_len, const WCHAR* lpDir)
183 {
184 WCHAR xlpFile[1024];
185 BOOL done = FALSE;
186 BOOL found_p1 = FALSE;
187 PWSTR res = out;
188 PCWSTR cmd;
189 DWORD used = 0;
190 bool tildeEffect = false;
191
192 TRACE("Before parsing: %p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
193 debugstr_w(lpFile), pidl, args);
194
195 while (*fmt)
196 {
197 if (*fmt == '%')
198 {
199 switch (*++fmt)
200 {
201 case '\0':
202 case '%':
203 {
204 used++;
205 if (used < len)
206 *res++ = '%';
207 };
208 break;
209
210 case '*':
211 {
212 if (args)
213 {
214 if (*fmt == '*')
215 {
216 used++;
217 while(*args)
218 {
219 used++;
220 if (used < len)
221 *res++ = *args++;
222 else
223 args++;
224 }
225 used++;
226 break;
227 }
228 }
229 };
230 break;
231
232 case '~':
233
234 case '2':
235 case '3':
236 case '4':
237 case '5':
238 case '6':
239 case '7':
240 case '8':
241 case '9':
242 //case '0':
243 {
244 if (*fmt == '~')
245 {
246 fmt++;
247 tildeEffect = true;
248 }
249
250 if (args)
251 {
252 if (tildeEffect)
253 {
254 ParseTildeEffect(res, args, len, used, *fmt - '2');
255 tildeEffect = false;
256 }
257 else
258 {
259 ParseNoTildeEffect(res, args, len, used, *fmt - '2');
260 }
261 }
262 };
263 break;
264
265 case '1':
266 if (!done || (*fmt == '1'))
267 {
268 /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
269 if (SearchPathW(lpDir, lpFile, wszExe, sizeof(xlpFile) / sizeof(WCHAR), xlpFile, NULL))
270 cmd = xlpFile;
271 else
272 cmd = lpFile;
273
274 used += wcslen(cmd);
275 if (used < len)
276 {
277 wcscpy(res, cmd);
278 res += wcslen(cmd);
279 }
280 }
281 found_p1 = TRUE;
282 break;
283
284 /*
285 * IE uses this a lot for activating things such as windows media
286 * player. This is not verified to be fully correct but it appears
287 * to work just fine.
288 */
289 case 'l':
290 case 'L':
291 if (lpFile)
292 {
293 used += wcslen(lpFile);
294 if (used < len)
295 {
296 wcscpy(res, lpFile);
297 res += wcslen(lpFile);
298 }
299 }
300 found_p1 = TRUE;
301 break;
302
303 case 'i':
304 case 'I':
305 if (pidl)
306 {
307 DWORD chars = 0;
308 /* %p should not exceed 8, maybe 16 when looking forward to 64bit.
309 * allowing a buffer of 100 should more than exceed all needs */
310 WCHAR buf[100];
311 LPVOID pv;
312 HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
313 pv = SHLockShared(hmem, 0);
314 chars = swprintf(buf, L":%p", pv);
315
316 if (chars >= sizeof(buf) / sizeof(WCHAR))
317 ERR("pidl format buffer too small!\n");
318
319 used += chars;
320
321 if (used < len)
322 {
323 wcscpy(res, buf);
324 res += chars;
325 }
326 SHUnlockShared(pv);
327 }
328 found_p1 = TRUE;
329 break;
330
331 default:
332 /*
333 * Check if this is an env-variable here...
334 */
335
336 /* Make sure that we have at least one more %.*/
337 if (strchrW(fmt, '%'))
338 {
339 WCHAR tmpBuffer[1024];
340 PWSTR tmpB = tmpBuffer;
341 WCHAR tmpEnvBuff[MAX_PATH];
342 DWORD envRet;
343
344 while (*fmt != '%')
345 *tmpB++ = *fmt++;
346 *tmpB++ = 0;
347
348 TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
349
350 envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
351 if (envRet == 0 || envRet > MAX_PATH)
352 {
353 used += wcslen(tmpBuffer);
354 if (used < len)
355 {
356 wcscpy( res, tmpBuffer );
357 res += wcslen(tmpBuffer);
358 }
359 }
360 else
361 {
362 used += wcslen(tmpEnvBuff);
363 if (used < len)
364 {
365 wcscpy( res, tmpEnvBuff );
366 res += wcslen(tmpEnvBuff);
367 }
368 }
369 }
370 done = TRUE;
371 break;
372 }
373 /* Don't skip past terminator (catch a single '%' at the end) */
374 if (*fmt != '\0')
375 {
376 fmt++;
377 }
378 }
379 else
380 {
381 used ++;
382 if (used < len)
383 *res++ = *fmt++;
384 else
385 fmt++;
386 }
387 }
388
389 used++;
390 if (res - out < static_cast<int>(len))
391 *res = '\0';
392 else
393 out[len-1] = '\0';
394
395 TRACE("used %i of %i space\n", used, len);
396 if (out_len)
397 *out_len = used;
398
399 TRACE("After parsing: %p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
400 debugstr_w(lpFile), pidl, args);
401
402 return found_p1;
403 }
404
405 static HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
406 {
407 STRRET strret;
408 CComPtr<IShellFolder> desktop;
409
410 HRESULT hr = SHGetDesktopFolder(&desktop);
411
412 if (SUCCEEDED(hr))
413 {
414 hr = desktop->GetDisplayNameOf(pidl, SHGDN_FORPARSING, &strret);
415
416 if (SUCCEEDED(hr))
417 StrRetToStrNW(pszPath, uOutSize, &strret, pidl);
418 }
419
420 return hr;
421 }
422
423 /*************************************************************************
424 * SHELL_ExecuteW [Internal]
425 *
426 */
427 static UINT_PTR SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
428 const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
429 {
430 STARTUPINFOW startup;
431 PROCESS_INFORMATION info;
432 UINT_PTR retval = SE_ERR_NOASSOC;
433 UINT gcdret = 0;
434 WCHAR curdir[MAX_PATH];
435 DWORD dwCreationFlags;
436 const WCHAR *lpDirectory = NULL;
437
438 TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
439
440 /* make sure we don't fail the CreateProcess if the calling app passes in
441 * a bad working directory */
442 if (psei->lpDirectory && psei->lpDirectory[0])
443 {
444 DWORD attr = GetFileAttributesW(psei->lpDirectory);
445 if (attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_DIRECTORY)
446 lpDirectory = psei->lpDirectory;
447 }
448
449 /* ShellExecute specifies the command from psei->lpDirectory
450 * if present. Not from the current dir as CreateProcess does */
451 if (lpDirectory)
452 if ((gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
453 if (!SetCurrentDirectoryW( lpDirectory))
454 ERR("cannot set directory %s\n", debugstr_w(lpDirectory));
455
456 ZeroMemory(&startup, sizeof(STARTUPINFOW));
457 startup.cb = sizeof(STARTUPINFOW);
458 startup.dwFlags = STARTF_USESHOWWINDOW;
459 startup.wShowWindow = psei->nShow;
460 dwCreationFlags = CREATE_UNICODE_ENVIRONMENT;
461 if (!(psei->fMask & SEE_MASK_NO_CONSOLE))
462 dwCreationFlags |= CREATE_NEW_CONSOLE;
463 startup.lpTitle = (LPWSTR)(psei->fMask & (SEE_MASK_HASLINKNAME | SEE_MASK_HASTITLE) ? psei->lpClass : NULL);
464
465 if (psei->fMask & SEE_MASK_HASLINKNAME)
466 startup.dwFlags |= STARTF_TITLEISLINKNAME;
467
468 if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, dwCreationFlags, env,
469 lpDirectory, &startup, &info))
470 {
471 /* Give 30 seconds to the app to come up, if desired. Probably only needed
472 when starting app immediately before making a DDE connection. */
473 if (shWait)
474 if (WaitForInputIdle(info.hProcess, 30000) == WAIT_FAILED)
475 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
476 retval = 33;
477
478 if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
479 psei_out->hProcess = info.hProcess;
480 else
481 CloseHandle( info.hProcess );
482 CloseHandle( info.hThread );
483 }
484 else if ((retval = GetLastError()) >= 32)
485 {
486 WARN("CreateProcess returned error %ld\n", retval);
487 retval = ERROR_BAD_FORMAT;
488 }
489
490 TRACE("returning %lu\n", retval);
491
492 psei_out->hInstApp = (HINSTANCE)retval;
493
494 if (gcdret)
495 if (!SetCurrentDirectoryW(curdir))
496 ERR("cannot return to directory %s\n", debugstr_w(curdir));
497
498 return retval;
499 }
500
501
502 /***********************************************************************
503 * SHELL_BuildEnvW [Internal]
504 *
505 * Build the environment for the new process, adding the specified
506 * path to the PATH variable. Returned pointer must be freed by caller.
507 */
508 static LPWSTR SHELL_BuildEnvW( const WCHAR *path )
509 {
510 static const WCHAR wPath[] = L"PATH=";
511 WCHAR *strings, *new_env;
512 WCHAR *p, *p2;
513 int total = wcslen(path) + 1;
514 BOOL got_path = FALSE;
515
516 if (!(strings = GetEnvironmentStringsW())) return NULL;
517 p = strings;
518 while (*p)
519 {
520 int len = wcslen(p) + 1;
521 if (!_wcsnicmp( p, wPath, 5 )) got_path = TRUE;
522 total += len;
523 p += len;
524 }
525 if (!got_path) total += 5; /* we need to create PATH */
526 total++; /* terminating null */
527
528 if (!(new_env = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, total * sizeof(WCHAR))))
529 {
530 FreeEnvironmentStringsW(strings);
531 return NULL;
532 }
533 p = strings;
534 p2 = new_env;
535 while (*p)
536 {
537 int len = wcslen(p) + 1;
538 memcpy(p2, p, len * sizeof(WCHAR));
539 if (!_wcsnicmp( p, wPath, 5 ))
540 {
541 p2[len - 1] = ';';
542 wcscpy( p2 + len, path );
543 p2 += wcslen(path) + 1;
544 }
545 p += len;
546 p2 += len;
547 }
548 if (!got_path)
549 {
550 wcscpy(p2, wPath);
551 wcscat(p2, path);
552 p2 += wcslen(p2) + 1;
553 }
554 *p2 = 0;
555 FreeEnvironmentStringsW(strings);
556 return new_env;
557 }
558
559
560 /***********************************************************************
561 * SHELL_TryAppPathW [Internal]
562 *
563 * Helper function for SHELL_FindExecutable
564 * @param lpResult - pointer to a buffer of size MAX_PATH
565 * On entry: szName is a filename (probably without path separators).
566 * On exit: if szName found in "App Path", place full path in lpResult, and return true
567 */
568 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
569 {
570 HKEY hkApp = 0;
571 WCHAR buffer[1024];
572 LONG len;
573 LONG res;
574 BOOL found = FALSE;
575
576 if (env) *env = NULL;
577 wcscpy(buffer, L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\");
578 wcscat(buffer, szName);
579 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
580 if (res)
581 {
582 // Add ".exe" extension, if extension does not exists
583 if (PathAddExtensionW(buffer, wszExe))
584 {
585 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
586 }
587 if (res) goto end;
588 }
589
590 len = MAX_PATH * sizeof(WCHAR);
591 res = RegQueryValueW(hkApp, NULL, lpResult, &len);
592 if (res) goto end;
593 found = TRUE;
594
595 if (env)
596 {
597 DWORD count = sizeof(buffer);
598 if (!RegQueryValueExW(hkApp, L"Path", NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
599 *env = SHELL_BuildEnvW(buffer);
600 }
601
602 end:
603 if (hkApp) RegCloseKey(hkApp);
604 return found;
605 }
606
607 /*************************************************************************
608 * SHELL_FindExecutableByVerb [Internal]
609 *
610 * called from SHELL_FindExecutable or SHELL_execute_class
611 * in/out:
612 * classname a buffer, big enough, to get the key name to do actually the
613 * command "WordPad.Document.1\\shell\\open\\command"
614 * passed as "WordPad.Document.1"
615 * in:
616 * lpVerb the operation on it (open)
617 * commandlen the size of command buffer (in bytes)
618 * out:
619 * command a buffer, to store the command to do the
620 * operation on the file
621 * key a buffer, big enough, to get the key name to do actually the
622 * command "WordPad.Document.1\\shell\\open\\command"
623 * Can be NULL
624 */
625 static UINT SHELL_FindExecutableByVerb(LPCWSTR lpVerb, LPWSTR key, LPWSTR classname, LPWSTR command, LONG commandlen)
626 {
627 static const WCHAR wCommand[] = L"\\command";
628 HKEY hkeyClass;
629 WCHAR verb[MAX_PATH];
630
631 if (RegOpenKeyExW(HKEY_CLASSES_ROOT, classname, 0, 0x02000000, &hkeyClass))
632 return SE_ERR_NOASSOC;
633 if (!HCR_GetDefaultVerbW(hkeyClass, lpVerb, verb, sizeof(verb) / sizeof(verb[0])))
634 return SE_ERR_NOASSOC;
635 RegCloseKey(hkeyClass);
636
637 /* Looking for ...buffer\shell\<verb>\command */
638 wcscat(classname, L"\\shell\\");
639 wcscat(classname, verb);
640 wcscat(classname, wCommand);
641
642 if (RegQueryValueW(HKEY_CLASSES_ROOT, classname, command,
643 &commandlen) == ERROR_SUCCESS)
644 {
645 commandlen /= sizeof(WCHAR);
646 if (key) wcscpy(key, classname);
647 #if 0
648 LPWSTR tmp;
649 WCHAR param[256];
650 LONG paramlen = sizeof(param);
651 static const WCHAR wSpace[] = {' ', 0};
652
653 /* FIXME: it seems all Windows version don't behave the same here.
654 * the doc states that this ddeexec information can be found after
655 * the exec names.
656 * on Win98, it doesn't appear, but I think it does on Win2k
657 */
658 /* Get the parameters needed by the application
659 from the associated ddeexec key */
660 tmp = strstrW(classname, wCommand);
661 tmp[0] = '\0';
662 wcscat(classname, wDdeexec);
663 if (RegQueryValueW(HKEY_CLASSES_ROOT, classname, param,
664 &paramlen) == ERROR_SUCCESS)
665 {
666 paramlen /= sizeof(WCHAR);
667 wcscat(command, wSpace);
668 wcscat(command, param);
669 commandlen += paramlen;
670 }
671 #endif
672
673 command[commandlen] = '\0';
674
675 return 33; /* FIXME see SHELL_FindExecutable() */
676 }
677
678 return SE_ERR_NOASSOC;
679 }
680
681 /*************************************************************************
682 * SHELL_FindExecutable [Internal]
683 *
684 * Utility for code sharing between FindExecutable and ShellExecute
685 * in:
686 * lpFile the name of a file
687 * lpVerb the operation on it (open)
688 * out:
689 * lpResult a buffer, big enough :-(, to store the command to do the
690 * operation on the file
691 * key a buffer, big enough, to get the key name to do actually the
692 * command (it'll be used afterwards for more information
693 * on the operation)
694 */
695 static UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpVerb,
696 LPWSTR lpResult, DWORD resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
697 {
698 WCHAR *extension = NULL; /* pointer to file extension */
699 WCHAR classname[256]; /* registry name for this file type */
700 LONG classnamelen = sizeof(classname); /* length of above */
701 WCHAR command[1024]; /* command from registry */
702 WCHAR wBuffer[256]; /* Used to GetProfileString */
703 UINT retval = SE_ERR_NOASSOC;
704 WCHAR *tok; /* token pointer */
705 WCHAR xlpFile[256]; /* result of SearchPath */
706 DWORD attribs; /* file attributes */
707
708 TRACE("%s\n", debugstr_w(lpFile));
709
710 if (!lpResult)
711 return ERROR_INVALID_PARAMETER;
712
713 xlpFile[0] = '\0';
714 lpResult[0] = '\0'; /* Start off with an empty return string */
715 if (key) *key = '\0';
716
717 /* trap NULL parameters on entry */
718 if (!lpFile)
719 {
720 WARN("(lpFile=%s,lpResult=%s): NULL parameter\n",
721 debugstr_w(lpFile), debugstr_w(lpResult));
722 return ERROR_FILE_NOT_FOUND; /* File not found. Close enough, I guess. */
723 }
724
725 if (SHELL_TryAppPathW( lpFile, lpResult, env ))
726 {
727 TRACE("found %s via App Paths\n", debugstr_w(lpResult));
728 return 33;
729 }
730
731 if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile) / sizeof(WCHAR), xlpFile, NULL))
732 {
733 TRACE("SearchPathW returned non-zero\n");
734 lpFile = xlpFile;
735 /* The file was found in the application-supplied default directory (or the system search path) */
736 }
737 else if (lpPath && SearchPathW(NULL, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
738 {
739 TRACE("SearchPathW returned non-zero\n");
740 lpFile = xlpFile;
741 /* The file was found in one of the directories in the system-wide search path */
742 }
743
744 attribs = GetFileAttributesW(lpFile);
745 if (attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY))
746 {
747 wcscpy(classname, L"Folder");
748 }
749 else
750 {
751 /* Did we get something? Anything? */
752 if (xlpFile[0] == 0)
753 {
754 TRACE("Returning SE_ERR_FNF\n");
755 return SE_ERR_FNF;
756 }
757 /* First thing we need is the file's extension */
758 extension = wcsrchr(xlpFile, '.'); /* Assume last "." is the one; */
759 /* File->Run in progman uses */
760 /* .\FILE.EXE :( */
761 TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
762
763 if (extension == NULL || extension[1] == 0)
764 {
765 WARN("Returning SE_ERR_NOASSOC\n");
766 return SE_ERR_NOASSOC;
767 }
768
769 /* Three places to check: */
770 /* 1. win.ini, [windows], programs (NB no leading '.') */
771 /* 2. Registry, HKEY_CLASS_ROOT\<classname>\shell\open\command */
772 /* 3. win.ini, [extensions], extension (NB no leading '.' */
773 /* All I know of the order is that registry is checked before */
774 /* extensions; however, it'd make sense to check the programs */
775 /* section first, so that's what happens here. */
776
777 /* See if it's a program - if GetProfileString fails, we skip this
778 * section. Actually, if GetProfileString fails, we've probably
779 * got a lot more to worry about than running a program... */
780 if (GetProfileStringW(L"windows", L"programs", L"exe pif bat cmd com", wBuffer, sizeof(wBuffer) / sizeof(WCHAR)) > 0)
781 {
782 CharLowerW(wBuffer);
783 tok = wBuffer;
784 while (*tok)
785 {
786 WCHAR *p = tok;
787 while (*p && *p != ' ' && *p != '\t') p++;
788 if (*p)
789 {
790 *p++ = 0;
791 while (*p == ' ' || *p == '\t') p++;
792 }
793
794 if (wcsicmp(tok, &extension[1]) == 0) /* have to skip the leading "." */
795 {
796 wcscpy(lpResult, xlpFile);
797 /* Need to perhaps check that the file has a path
798 * attached */
799 TRACE("found %s\n", debugstr_w(lpResult));
800 return 33;
801 /* Greater than 32 to indicate success */
802 }
803 tok = p;
804 }
805 }
806
807 /* Check registry */
808 if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, classname,
809 &classnamelen) == ERROR_SUCCESS)
810 {
811 classnamelen /= sizeof(WCHAR);
812 if (classnamelen == sizeof(classname) / sizeof(WCHAR))
813 classnamelen--;
814
815 classname[classnamelen] = '\0';
816 TRACE("File type: %s\n", debugstr_w(classname));
817 }
818 else
819 {
820 *classname = '\0';
821 }
822 }
823
824 if (*classname)
825 {
826 /* pass the verb string to SHELL_FindExecutableByVerb() */
827 retval = SHELL_FindExecutableByVerb(lpVerb, key, classname, command, sizeof(command));
828
829 if (retval > 32)
830 {
831 DWORD finishedLen;
832 SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args, &finishedLen, lpPath);
833 if (finishedLen > resultLen)
834 ERR("Argify buffer not large enough.. truncated\n");
835 /* Remove double quotation marks and command line arguments */
836 if (*lpResult == '"')
837 {
838 WCHAR *p = lpResult;
839 while (*(p + 1) != '"')
840 {
841 *p = *(p + 1);
842 p++;
843 }
844 *p = '\0';
845 }
846 else
847 {
848 /* Truncate on first space */
849 WCHAR *p = lpResult;
850 while (*p != ' ' && *p != '\0')
851 p++;
852 *p = '\0';
853 }
854 }
855 }
856 else /* Check win.ini */
857 {
858 /* Toss the leading dot */
859 extension++;
860 if (GetProfileStringW(L"extensions", extension, L"", command, sizeof(command) / sizeof(WCHAR)) > 0)
861 {
862 if (wcslen(command) != 0)
863 {
864 wcscpy(lpResult, command);
865 tok = wcschr(lpResult, '^'); /* should be ^.extension? */
866 if (tok != NULL)
867 {
868 tok[0] = '\0';
869 wcscat(lpResult, xlpFile); /* what if no dir in xlpFile? */
870 tok = wcschr(command, '^'); /* see above */
871 if ((tok != NULL) && (wcslen(tok) > 5))
872 {
873 wcscat(lpResult, &tok[5]);
874 }
875 }
876 retval = 33; /* FIXME - see above */
877 }
878 }
879 }
880
881 TRACE("returning %s\n", debugstr_w(lpResult));
882 return retval;
883 }
884
885 /******************************************************************
886 * dde_cb
887 *
888 * callback for the DDE connection. not really useful
889 */
890 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
891 HSZ hsz1, HSZ hsz2, HDDEDATA hData,
892 ULONG_PTR dwData1, ULONG_PTR dwData2)
893 {
894 TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
895 uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
896 return NULL;
897 }
898
899 /******************************************************************
900 * dde_connect
901 *
902 * ShellExecute helper. Used to do an operation with a DDE connection
903 *
904 * Handles both the direct connection (try #1), and if it fails,
905 * launching an application and trying (#2) to connect to it
906 *
907 */
908 static unsigned dde_connect(const WCHAR* key, const WCHAR* start, WCHAR* ddeexec,
909 const WCHAR* lpFile, WCHAR *env,
910 LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
911 const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
912 {
913 WCHAR regkey[256];
914 WCHAR * endkey = regkey + wcslen(key);
915 WCHAR app[256], topic[256], ifexec[256], static_res[256];
916 WCHAR * dynamic_res=NULL;
917 WCHAR * res;
918 LONG applen, topiclen, ifexeclen;
919 WCHAR * exec;
920 DWORD ddeInst = 0;
921 DWORD tid;
922 DWORD resultLen, endkeyLen;
923 HSZ hszApp, hszTopic;
924 HCONV hConv;
925 HDDEDATA hDdeData;
926 unsigned ret = SE_ERR_NOASSOC;
927 BOOL unicode = !(GetVersion() & 0x80000000);
928
929 if (strlenW(key) + 1 > sizeof(regkey) / sizeof(regkey[0]))
930 {
931 FIXME("input parameter %s larger than buffer\n", debugstr_w(key));
932 return 2;
933 }
934 wcscpy(regkey, key);
935 static const WCHAR wApplication[] = L"\\application";
936 endkeyLen = sizeof(regkey) / sizeof(regkey[0]) - (endkey - regkey);
937 if (strlenW(wApplication) + 1 > endkeyLen)
938 {
939 FIXME("endkey %s overruns buffer\n", debugstr_w(wApplication));
940 return 2;
941 }
942 wcscpy(endkey, wApplication);
943 applen = sizeof(app);
944 if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, app, &applen) != ERROR_SUCCESS)
945 {
946 WCHAR command[1024], fullpath[MAX_PATH];
947 static const WCHAR wSo[] = L".so";
948 DWORD sizeSo = sizeof(wSo) / sizeof(WCHAR);
949 LPWSTR ptr = NULL;
950 DWORD ret = 0;
951
952 /* Get application command from start string and find filename of application */
953 if (*start == '"')
954 {
955 if (strlenW(start + 1) + 1 > sizeof(command) / sizeof(command[0]))
956 {
957 FIXME("size of input parameter %s larger than buffer\n",
958 debugstr_w(start + 1));
959 return 2;
960 }
961 wcscpy(command, start + 1);
962 if ((ptr = wcschr(command, '"')))
963 * ptr = 0;
964 ret = SearchPathW(NULL, command, wszExe, sizeof(fullpath) / sizeof(WCHAR), fullpath, &ptr);
965 }
966 else
967 {
968 LPCWSTR p;
969 LPWSTR space;
970 for (p = start; (space = const_cast<LPWSTR>(strchrW(p, ' '))); p = space + 1)
971 {
972 int idx = space - start;
973 memcpy(command, start, idx * sizeof(WCHAR));
974 command[idx] = '\0';
975 if ((ret = SearchPathW(NULL, command, wszExe, sizeof(fullpath) / sizeof(WCHAR), fullpath, &ptr)))
976 break;
977 }
978 if (!ret)
979 ret = SearchPathW(NULL, start, wszExe, sizeof(fullpath) / sizeof(WCHAR), fullpath, &ptr);
980 }
981
982 if (!ret)
983 {
984 ERR("Unable to find application path for command %s\n", debugstr_w(start));
985 return ERROR_ACCESS_DENIED;
986 }
987 if (strlenW(ptr) + 1 > sizeof(app) / sizeof(app[0]))
988 {
989 FIXME("size of found path %s larger than buffer\n", debugstr_w(ptr));
990 return 2;
991 }
992 wcscpy(app, ptr);
993
994 /* Remove extensions (including .so) */
995 ptr = app + wcslen(app) - (sizeSo - 1);
996 if (wcslen(app) >= sizeSo &&
997 !wcscmp(ptr, wSo))
998 *ptr = 0;
999
1000 ptr = const_cast<LPWSTR>(strrchrW(app, '.'));
1001 assert(ptr);
1002 *ptr = 0;
1003 }
1004
1005 static const WCHAR wTopic[] = L"\\topic";
1006 if (strlenW(wTopic) + 1 > endkeyLen)
1007 {
1008 FIXME("endkey %s overruns buffer\n", debugstr_w(wTopic));
1009 return 2;
1010 }
1011 wcscpy(endkey, wTopic);
1012 topiclen = sizeof(topic);
1013 if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, topic, &topiclen) != ERROR_SUCCESS)
1014 {
1015 wcscpy(topic, L"System");
1016 }
1017
1018 if (unicode)
1019 {
1020 if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
1021 return 2;
1022 }
1023 else
1024 {
1025 if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
1026 return 2;
1027 }
1028
1029 hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
1030 hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
1031
1032 hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
1033 exec = ddeexec;
1034 if (!hConv)
1035 {
1036 TRACE("Launching %s\n", debugstr_w(start));
1037 ret = execfunc(start, env, TRUE, psei, psei_out);
1038 if (ret <= 32)
1039 {
1040 TRACE("Couldn't launch\n");
1041 goto error;
1042 }
1043 hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
1044 if (!hConv)
1045 {
1046 TRACE("Couldn't connect. ret=%d\n", ret);
1047 DdeUninitialize(ddeInst);
1048 SetLastError(ERROR_DDE_FAIL);
1049 return 30; /* whatever */
1050 }
1051 static const WCHAR wIfexec[] = L"\\ifexec";
1052 if (strlenW(wIfexec) + 1 > endkeyLen)
1053 {
1054 FIXME("endkey %s overruns buffer\n", debugstr_w(wIfexec));
1055 return 2;
1056 }
1057 strcpyW(endkey, wIfexec);
1058 ifexeclen = sizeof(ifexec);
1059 if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, ifexec, &ifexeclen) == ERROR_SUCCESS)
1060 {
1061 exec = ifexec;
1062 }
1063 }
1064
1065 SHELL_ArgifyW(static_res, sizeof(static_res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline, &resultLen, NULL);
1066 if (resultLen > sizeof(static_res)/sizeof(WCHAR))
1067 {
1068 res = dynamic_res = static_cast<WCHAR *>(HeapAlloc(GetProcessHeap(), 0, resultLen * sizeof(WCHAR)));
1069 SHELL_ArgifyW(dynamic_res, resultLen, exec, lpFile, pidl, szCommandline, NULL, NULL);
1070 }
1071 else
1072 res = static_res;
1073 TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
1074
1075 /* It's documented in the KB 330337 that IE has a bug and returns
1076 * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
1077 */
1078 if (unicode)
1079 hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0, XTYP_EXECUTE, 30000, &tid);
1080 else
1081 {
1082 DWORD lenA = WideCharToMultiByte(CP_ACP, 0, res, -1, NULL, 0, NULL, NULL);
1083 char *resA = (LPSTR)HeapAlloc(GetProcessHeap(), 0, lenA);
1084 WideCharToMultiByte(CP_ACP, 0, res, -1, resA, lenA, NULL, NULL);
1085 hDdeData = DdeClientTransaction( (LPBYTE)resA, lenA, hConv, 0L, 0,
1086 XTYP_EXECUTE, 10000, &tid );
1087 HeapFree(GetProcessHeap(), 0, resA);
1088 }
1089 if (hDdeData)
1090 DdeFreeDataHandle(hDdeData);
1091 else
1092 WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
1093 ret = 33;
1094
1095 HeapFree(GetProcessHeap(), 0, dynamic_res);
1096
1097 DdeDisconnect(hConv);
1098
1099 error:
1100 DdeUninitialize(ddeInst);
1101
1102 return ret;
1103 }
1104
1105 /*************************************************************************
1106 * execute_from_key [Internal]
1107 */
1108 static UINT_PTR execute_from_key(LPCWSTR key, LPCWSTR lpFile, WCHAR *env,
1109 LPCWSTR szCommandline, LPCWSTR executable_name,
1110 SHELL_ExecuteW32 execfunc,
1111 LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
1112 {
1113 WCHAR cmd[256], param[1024], ddeexec[256];
1114 DWORD cmdlen = sizeof(cmd), ddeexeclen = sizeof(ddeexec);
1115 UINT_PTR retval = SE_ERR_NOASSOC;
1116 DWORD resultLen;
1117 LPWSTR tmp;
1118
1119 TRACE("%s %s %s %s %s\n", debugstr_w(key), debugstr_w(lpFile), debugstr_w(env),
1120 debugstr_w(szCommandline), debugstr_w(executable_name));
1121
1122 cmd[0] = '\0';
1123 param[0] = '\0';
1124
1125 /* Get the application from the registry */
1126 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, (LONG *)&cmdlen) == ERROR_SUCCESS)
1127 {
1128 TRACE("got cmd: %s\n", debugstr_w(cmd));
1129
1130 /* Is there a replace() function anywhere? */
1131 cmdlen /= sizeof(WCHAR);
1132 if (cmdlen >= sizeof(cmd) / sizeof(WCHAR))
1133 cmdlen = sizeof(cmd) / sizeof(WCHAR) - 1;
1134 cmd[cmdlen] = '\0';
1135 SHELL_ArgifyW(param, sizeof(param) / sizeof(WCHAR), cmd, lpFile, (LPITEMIDLIST)psei->lpIDList, szCommandline, &resultLen,
1136 (psei->lpDirectory && *psei->lpDirectory) ? psei->lpDirectory : NULL);
1137 if (resultLen > sizeof(param) / sizeof(WCHAR))
1138 ERR("Argify buffer not large enough, truncating\n");
1139 }
1140
1141 /* Get the parameters needed by the application
1142 from the associated ddeexec key */
1143 tmp = const_cast<LPWSTR>(strstrW(key, L"command"));
1144 assert(tmp);
1145 wcscpy(tmp, L"ddeexec");
1146
1147 if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ddeexec, (LONG *)&ddeexeclen) == ERROR_SUCCESS)
1148 {
1149 TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(ddeexec));
1150 if (!param[0]) strcpyW(param, executable_name);
1151 retval = dde_connect(key, param, ddeexec, lpFile, env, szCommandline, (LPITEMIDLIST)psei->lpIDList, execfunc, psei, psei_out);
1152 }
1153 else if (param[0])
1154 {
1155 TRACE("executing: %s\n", debugstr_w(param));
1156 retval = execfunc(param, env, FALSE, psei, psei_out);
1157 }
1158 else
1159 WARN("Nothing appropriate found for %s\n", debugstr_w(key));
1160
1161 return retval;
1162 }
1163
1164 /*************************************************************************
1165 * FindExecutableA [SHELL32.@]
1166 */
1167 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
1168 {
1169 HINSTANCE retval;
1170 WCHAR *wFile = NULL, *wDirectory = NULL;
1171 WCHAR wResult[MAX_PATH];
1172
1173 if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
1174 if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
1175
1176 retval = FindExecutableW(wFile, wDirectory, wResult);
1177 WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
1178 SHFree(wFile);
1179 SHFree(wDirectory);
1180
1181 TRACE("returning %s\n", lpResult);
1182 return retval;
1183 }
1184
1185 /*************************************************************************
1186 * FindExecutableW [SHELL32.@]
1187 *
1188 * This function returns the executable associated with the specified file
1189 * for the default verb.
1190 *
1191 * PARAMS
1192 * lpFile [I] The file to find the association for. This must refer to
1193 * an existing file otherwise FindExecutable fails and returns
1194 * SE_ERR_FNF.
1195 * lpResult [O] Points to a buffer into which the executable path is
1196 * copied. This parameter must not be NULL otherwise
1197 * FindExecutable() segfaults. The buffer must be of size at
1198 * least MAX_PATH characters.
1199 *
1200 * RETURNS
1201 * A value greater than 32 on success, less than or equal to 32 otherwise.
1202 * See the SE_ERR_* constants.
1203 *
1204 * NOTES
1205 * On Windows XP and 2003, FindExecutable() seems to first convert the
1206 * filename into 8.3 format, thus taking into account only the first three
1207 * characters of the extension, and expects to find an association for those.
1208 * However other Windows versions behave sanely.
1209 */
1210 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
1211 {
1212 UINT_PTR retval = SE_ERR_NOASSOC;
1213 WCHAR old_dir[1024];
1214 WCHAR res[MAX_PATH];
1215
1216 TRACE("File %s, Dir %s\n", debugstr_w(lpFile), debugstr_w(lpDirectory));
1217
1218 lpResult[0] = '\0'; /* Start off with an empty return string */
1219 if (lpFile == NULL)
1220 return (HINSTANCE)SE_ERR_FNF;
1221
1222 if (lpDirectory)
1223 {
1224 GetCurrentDirectoryW(sizeof(old_dir) / sizeof(WCHAR), old_dir);
1225 SetCurrentDirectoryW(lpDirectory);
1226 }
1227
1228 retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, res, MAX_PATH, NULL, NULL, NULL, NULL);
1229 if (retval > 32)
1230 strcpyW(lpResult, res);
1231
1232 TRACE("returning %s\n", debugstr_w(lpResult));
1233 if (lpDirectory)
1234 SetCurrentDirectoryW(old_dir);
1235 return (HINSTANCE)retval;
1236 }
1237
1238 /* FIXME: is this already implemented somewhere else? */
1239 static HKEY ShellExecute_GetClassKey(const SHELLEXECUTEINFOW *sei)
1240 {
1241 LPCWSTR ext = NULL, lpClass = NULL;
1242 LPWSTR cls = NULL;
1243 DWORD type = 0, sz = 0;
1244 HKEY hkey = 0;
1245 LONG r;
1246
1247 if (sei->fMask & SEE_MASK_CLASSALL)
1248 return sei->hkeyClass;
1249
1250 if (sei->fMask & SEE_MASK_CLASSNAME)
1251 lpClass = sei->lpClass;
1252 else
1253 {
1254 ext = PathFindExtensionW(sei->lpFile);
1255 TRACE("ext = %s\n", debugstr_w(ext));
1256 if (!ext)
1257 return hkey;
1258
1259 r = RegOpenKeyW(HKEY_CLASSES_ROOT, ext, &hkey);
1260 if (r != ERROR_SUCCESS)
1261 return hkey;
1262
1263 r = RegQueryValueExW(hkey, NULL, 0, &type, NULL, &sz);
1264 if (r == ERROR_SUCCESS && type == REG_SZ)
1265 {
1266 sz += sizeof (WCHAR);
1267 cls = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, sz);
1268 cls[0] = 0;
1269 RegQueryValueExW(hkey, NULL, 0, &type, (LPBYTE) cls, &sz);
1270 }
1271
1272 RegCloseKey( hkey );
1273 lpClass = cls;
1274 }
1275
1276 TRACE("class = %s\n", debugstr_w(lpClass));
1277
1278 hkey = 0;
1279 if (lpClass)
1280 RegOpenKeyW( HKEY_CLASSES_ROOT, lpClass, &hkey);
1281
1282 HeapFree(GetProcessHeap(), 0, cls);
1283
1284 return hkey;
1285 }
1286
1287 static IDataObject *shellex_get_dataobj( LPSHELLEXECUTEINFOW sei )
1288 {
1289 LPCITEMIDLIST pidllast = NULL;
1290 CComPtr<IDataObject> dataobj;
1291 CComPtr<IShellFolder> shf;
1292 LPITEMIDLIST pidl = NULL;
1293 HRESULT r;
1294
1295 if (sei->fMask & SEE_MASK_CLASSALL)
1296 pidl = (LPITEMIDLIST)sei->lpIDList;
1297 else
1298 {
1299 WCHAR fullpath[MAX_PATH];
1300 BOOL ret;
1301
1302 fullpath[0] = 0;
1303 ret = GetFullPathNameW(sei->lpFile, MAX_PATH, fullpath, NULL);
1304 if (!ret)
1305 goto end;
1306
1307 pidl = ILCreateFromPathW(fullpath);
1308 }
1309
1310 r = SHBindToParent(pidl, IID_PPV_ARG(IShellFolder, &shf), &pidllast);
1311 if (FAILED(r))
1312 goto end;
1313
1314 shf->GetUIObjectOf(NULL, 1, &pidllast, IID_NULL_PPV_ARG(IDataObject, &dataobj));
1315
1316 end:
1317 if (pidl != sei->lpIDList)
1318 ILFree(pidl);
1319 return dataobj.Detach();
1320 }
1321
1322 static HRESULT shellex_run_context_menu_default(IShellExtInit *obj,
1323 LPSHELLEXECUTEINFOW sei)
1324 {
1325 CComPtr<IContextMenu> cm = NULL;
1326 CMINVOKECOMMANDINFOEX ici;
1327 MENUITEMINFOW info;
1328 WCHAR string[0x80];
1329 INT i, n, def = -1;
1330 HMENU hmenu = 0;
1331 HRESULT r;
1332
1333 TRACE("%p %p\n", obj, sei);
1334
1335 r = obj->QueryInterface(IID_PPV_ARG(IContextMenu, &cm));
1336 if (FAILED(r))
1337 return r;
1338
1339 hmenu = CreateMenu();
1340 if (!hmenu)
1341 goto end;
1342
1343 /* the number of the last menu added is returned in r */
1344 r = cm->QueryContextMenu(hmenu, 0, 0x20, 0x7fff, CMF_DEFAULTONLY);
1345 if (FAILED(r))
1346 goto end;
1347
1348 n = GetMenuItemCount(hmenu);
1349 for (i = 0; i < n; i++)
1350 {
1351 memset(&info, 0, sizeof(info));
1352 info.cbSize = sizeof info;
1353 info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_STATE | MIIM_DATA | MIIM_ID;
1354 info.dwTypeData = string;
1355 info.cch = sizeof string;
1356 string[0] = 0;
1357 GetMenuItemInfoW(hmenu, i, TRUE, &info);
1358
1359 TRACE("menu %d %s %08x %08lx %08x %08x\n", i, debugstr_w(string),
1360 info.fState, info.dwItemData, info.fType, info.wID);
1361 if ((!sei->lpVerb && (info.fState & MFS_DEFAULT)) ||
1362 (sei->lpVerb && !lstrcmpiW(sei->lpVerb, string)))
1363 {
1364 def = i;
1365 break;
1366 }
1367 }
1368
1369 r = E_FAIL;
1370 if (def == -1)
1371 goto end;
1372
1373 memset(&ici, 0, sizeof ici);
1374 ici.cbSize = sizeof ici;
1375 ici.fMask = CMIC_MASK_UNICODE | (sei->fMask & (SEE_MASK_NO_CONSOLE | SEE_MASK_NOASYNC | SEE_MASK_ASYNCOK | SEE_MASK_FLAG_NO_UI));
1376 ici.nShow = sei->nShow;
1377 ici.lpVerb = MAKEINTRESOURCEA(def);
1378 ici.hwnd = sei->hwnd;
1379 ici.lpParametersW = sei->lpParameters;
1380
1381 r = cm->InvokeCommand((LPCMINVOKECOMMANDINFO)&ici);
1382
1383 TRACE("invoke command returned %08x\n", r);
1384
1385 end:
1386 if (hmenu)
1387 DestroyMenu( hmenu );
1388 return r;
1389 }
1390
1391 static HRESULT shellex_load_object_and_run(HKEY hkey, LPCGUID guid, LPSHELLEXECUTEINFOW sei)
1392 {
1393 // Can not use CComPtr here because of CoUninitialize at the end, before the destructors would run.
1394 IDataObject *dataobj = NULL;
1395 IObjectWithSite *ows = NULL;
1396 IShellExtInit *obj = NULL;
1397 HRESULT r;
1398
1399 TRACE("%p %s %p\n", hkey, debugstr_guid(guid), sei);
1400
1401 r = CoInitialize(NULL);
1402 if (FAILED(r))
1403 goto end;
1404
1405 r = CoCreateInstance(*guid, NULL, CLSCTX_INPROC_SERVER,
1406 IID_PPV_ARG(IShellExtInit, &obj));
1407 if (FAILED(r))
1408 {
1409 ERR("failed %08x\n", r);
1410 goto end;
1411 }
1412
1413 dataobj = shellex_get_dataobj(sei);
1414 if (!dataobj)
1415 {
1416 ERR("failed to get data object\n");
1417 r = E_FAIL;
1418 goto end;
1419 }
1420
1421 r = obj->Initialize(NULL, dataobj, hkey);
1422 if (FAILED(r))
1423 goto end;
1424
1425 r = obj->QueryInterface(IID_PPV_ARG(IObjectWithSite, &ows));
1426 if (FAILED(r))
1427 goto end;
1428
1429 ows->SetSite(NULL);
1430
1431 r = shellex_run_context_menu_default(obj, sei);
1432
1433 end:
1434 if (ows)
1435 ows->Release();
1436 if (dataobj)
1437 dataobj->Release();
1438 if (obj)
1439 obj->Release();
1440 CoUninitialize();
1441 return r;
1442 }
1443
1444
1445 /*************************************************************************
1446 * ShellExecute_FromContextMenu [Internal]
1447 */
1448 static LONG ShellExecute_FromContextMenu( LPSHELLEXECUTEINFOW sei )
1449 {
1450 HKEY hkey, hkeycm = 0;
1451 WCHAR szguid[39];
1452 HRESULT hr;
1453 GUID guid;
1454 DWORD i;
1455 LONG r;
1456
1457 TRACE("%s\n", debugstr_w(sei->lpFile));
1458
1459 hkey = ShellExecute_GetClassKey(sei);
1460 if (!hkey)
1461 return ERROR_FUNCTION_FAILED;
1462
1463 r = RegOpenKeyW(hkey, L"shellex\\ContextMenuHandlers", &hkeycm);
1464 if (r == ERROR_SUCCESS)
1465 {
1466 i = 0;
1467 while (1)
1468 {
1469 r = RegEnumKeyW(hkeycm, i++, szguid, sizeof(szguid) / sizeof(szguid[0]));
1470 if (r != ERROR_SUCCESS)
1471 break;
1472
1473 hr = CLSIDFromString(szguid, &guid);
1474 if (SUCCEEDED(hr))
1475 {
1476 /* stop at the first one that succeeds in running */
1477 hr = shellex_load_object_and_run(hkey, &guid, sei);
1478 if (SUCCEEDED(hr))
1479 break;
1480 }
1481 }
1482 RegCloseKey(hkeycm);
1483 }
1484
1485 if (hkey != sei->hkeyClass)
1486 RegCloseKey(hkey);
1487 return r;
1488 }
1489
1490 static UINT_PTR SHELL_quote_and_execute(LPCWSTR wcmd, LPCWSTR wszParameters, LPCWSTR lpstrProtocol, LPCWSTR wszApplicationName, LPWSTR env, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc);
1491
1492 static UINT_PTR SHELL_execute_class(LPCWSTR wszApplicationName, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc)
1493 {
1494 WCHAR execCmd[1024], classname[1024];
1495 /* launch a document by fileclass like 'WordPad.Document.1' */
1496 /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
1497 /* FIXME: wcmd should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
1498 ULONG cmask = (psei->fMask & SEE_MASK_CLASSALL);
1499 DWORD resultLen;
1500 BOOL done;
1501 UINT_PTR rslt;
1502
1503 /* FIXME: remove following block when SHELL_quote_and_execute supports hkeyClass parameter */
1504 if (cmask != SEE_MASK_CLASSNAME)
1505 {
1506 WCHAR wcmd[1024];
1507 HCR_GetExecuteCommandW((cmask == SEE_MASK_CLASSKEY) ? psei->hkeyClass : NULL,
1508 (cmask == SEE_MASK_CLASSNAME) ? psei->lpClass : NULL,
1509 psei->lpVerb,
1510 execCmd, sizeof(execCmd));
1511
1512 /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
1513 TRACE("SEE_MASK_CLASSNAME->%s, doc->%s\n", debugstr_w(execCmd), debugstr_w(wszApplicationName));
1514
1515 wcmd[0] = '\0';
1516 done = SHELL_ArgifyW(wcmd, sizeof(wcmd) / sizeof(WCHAR), execCmd, wszApplicationName, (LPITEMIDLIST)psei->lpIDList, NULL, &resultLen,
1517 (psei->lpDirectory && *psei->lpDirectory) ? psei->lpDirectory : NULL);
1518 if (!done && wszApplicationName[0])
1519 {
1520 strcatW(wcmd, L" ");
1521 if (*wszApplicationName != '"')
1522 {
1523 strcatW(wcmd, L"\"");
1524 strcatW(wcmd, wszApplicationName);
1525 strcatW(wcmd, L"\"");
1526 }
1527 else
1528 strcatW(wcmd, wszApplicationName);
1529 }
1530 if (resultLen > sizeof(wcmd) / sizeof(WCHAR))
1531 ERR("Argify buffer not large enough... truncating\n");
1532 return execfunc(wcmd, NULL, FALSE, psei, psei_out);
1533 }
1534
1535 strcpyW(classname, psei->lpClass);
1536 rslt = SHELL_FindExecutableByVerb(psei->lpVerb, NULL, classname, execCmd, sizeof(execCmd));
1537
1538 TRACE("SHELL_FindExecutableByVerb returned %u (%s, %s)\n", (unsigned int)rslt, debugstr_w(classname), debugstr_w(execCmd));
1539 if (33 > rslt)
1540 return rslt;
1541 rslt = SHELL_quote_and_execute( execCmd, L"", classname,
1542 wszApplicationName, NULL, psei,
1543 psei_out, execfunc );
1544 return rslt;
1545
1546 }
1547
1548 static BOOL SHELL_translate_idlist(LPSHELLEXECUTEINFOW sei, LPWSTR wszParameters, DWORD parametersLen, LPWSTR wszApplicationName, DWORD dwApplicationNameLen)
1549 {
1550 static const WCHAR wExplorer[] = L"explorer.exe";
1551 WCHAR buffer[MAX_PATH];
1552 BOOL appKnownSingular = FALSE;
1553
1554 /* last chance to translate IDList: now also allow CLSID paths */
1555 if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW((LPCITEMIDLIST)sei->lpIDList, buffer, sizeof(buffer)/sizeof(WCHAR)))) {
1556 if (buffer[0] == ':' && buffer[1] == ':') {
1557 /* open shell folder for the specified class GUID */
1558 if (strlenW(buffer) + 1 > parametersLen)
1559 ERR("parameters len exceeds buffer size (%i > %i), truncating\n",
1560 lstrlenW(buffer) + 1, parametersLen);
1561 lstrcpynW(wszParameters, buffer, parametersLen);
1562 if (strlenW(wExplorer) > dwApplicationNameLen)
1563 ERR("application len exceeds buffer size (%i > %i), truncating\n",
1564 lstrlenW(wExplorer) + 1, dwApplicationNameLen);
1565 lstrcpynW(wszApplicationName, wExplorer, dwApplicationNameLen);
1566 appKnownSingular = TRUE;
1567
1568 sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
1569 } else {
1570 WCHAR target[MAX_PATH];
1571 DWORD attribs;
1572 DWORD resultLen;
1573 /* Check if we're executing a directory and if so use the
1574 handler for the Folder class */
1575 strcpyW(target, buffer);
1576 attribs = GetFileAttributesW(buffer);
1577 if (attribs != INVALID_FILE_ATTRIBUTES &&
1578 (attribs & FILE_ATTRIBUTE_DIRECTORY) &&
1579 HCR_GetExecuteCommandW(0, L"Folder",
1580 sei->lpVerb,
1581 buffer, sizeof(buffer))) {
1582 SHELL_ArgifyW(wszApplicationName, dwApplicationNameLen,
1583 buffer, target, (LPITEMIDLIST)sei->lpIDList, NULL, &resultLen,
1584 (sei->lpDirectory && *sei->lpDirectory) ? sei->lpDirectory : NULL);
1585 if (resultLen > dwApplicationNameLen)
1586 ERR("Argify buffer not large enough... truncating\n");
1587 appKnownSingular = FALSE;
1588 }
1589 sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
1590 }
1591 }
1592 return appKnownSingular;
1593 }
1594
1595 static UINT_PTR SHELL_quote_and_execute(LPCWSTR wcmd, LPCWSTR wszParameters, LPCWSTR wszKeyname, LPCWSTR wszApplicationName, LPWSTR env, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc)
1596 {
1597 UINT_PTR retval;
1598 DWORD len;
1599 WCHAR *wszQuotedCmd;
1600
1601 /* Length of quotes plus length of command plus NULL terminator */
1602 len = 2 + lstrlenW(wcmd) + 1;
1603 if (wszParameters[0])
1604 {
1605 /* Length of space plus length of parameters */
1606 len += 1 + lstrlenW(wszParameters);
1607 }
1608 wszQuotedCmd = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1609 /* Must quote to handle case where cmd contains spaces,
1610 * else security hole if malicious user creates executable file "C:\\Program"
1611 */
1612 strcpyW(wszQuotedCmd, L"\"");
1613 strcatW(wszQuotedCmd, wcmd);
1614 strcatW(wszQuotedCmd, L"\"");
1615 if (wszParameters[0])
1616 {
1617 strcatW(wszQuotedCmd, L" ");
1618 strcatW(wszQuotedCmd, wszParameters);
1619 }
1620
1621 TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(psei->lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(wszKeyname));
1622
1623 if (*wszKeyname)
1624 retval = execute_from_key(wszKeyname, wszApplicationName, env, psei->lpParameters, wcmd, execfunc, psei, psei_out);
1625 else
1626 retval = execfunc(wszQuotedCmd, env, FALSE, psei, psei_out);
1627 HeapFree(GetProcessHeap(), 0, wszQuotedCmd);
1628 return retval;
1629 }
1630
1631 static UINT_PTR SHELL_execute_url(LPCWSTR lpFile, LPCWSTR wcmd, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc)
1632 {
1633 static const WCHAR wShell[] = L"\\shell\\";
1634 static const WCHAR wCommand[] = L"\\command";
1635 UINT_PTR retval;
1636 WCHAR *lpstrProtocol;
1637 LPCWSTR lpstrRes;
1638 INT iSize;
1639 DWORD len;
1640
1641 lpstrRes = strchrW(lpFile, ':');
1642 if (lpstrRes)
1643 iSize = lpstrRes - lpFile;
1644 else
1645 iSize = strlenW(lpFile);
1646
1647 TRACE("Got URL: %s\n", debugstr_w(lpFile));
1648 /* Looking for ...<protocol>\shell\<lpVerb>\command */
1649 len = iSize + lstrlenW(wShell) + lstrlenW(wCommand) + 1;
1650 if (psei->lpVerb && *psei->lpVerb)
1651 len += lstrlenW(psei->lpVerb);
1652 else
1653 len += lstrlenW(wszOpen);
1654 lpstrProtocol = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1655 memcpy(lpstrProtocol, lpFile, iSize * sizeof(WCHAR));
1656 lpstrProtocol[iSize] = '\0';
1657 strcatW(lpstrProtocol, wShell);
1658 strcatW(lpstrProtocol, psei->lpVerb && *psei->lpVerb ? psei->lpVerb : wszOpen);
1659 strcatW(lpstrProtocol, wCommand);
1660
1661 retval = execute_from_key(lpstrProtocol, lpFile, NULL, psei->lpParameters,
1662 wcmd, execfunc, psei, psei_out);
1663 HeapFree(GetProcessHeap(), 0, lpstrProtocol);
1664 return retval;
1665 }
1666
1667 static void do_error_dialog(UINT_PTR retval, HWND hwnd, WCHAR* filename)
1668 {
1669 WCHAR msg[2048];
1670 DWORD_PTR msgArguments[3] = { (DWORD_PTR)filename, 0, 0 };
1671 DWORD error_code;
1672
1673 error_code = GetLastError();
1674 if (retval == SE_ERR_NOASSOC)
1675 LoadStringW(shell32_hInstance, IDS_SHLEXEC_NOASSOC, msg, sizeof(msg) / sizeof(WCHAR));
1676 else
1677 FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1678 NULL,
1679 error_code,
1680 LANG_USER_DEFAULT,
1681 msg,
1682 sizeof(msg) / sizeof(WCHAR),
1683 (va_list*)msgArguments);
1684
1685 MessageBoxW(hwnd, msg, NULL, MB_ICONERROR);
1686 }
1687
1688 static WCHAR *expand_environment( const WCHAR *str )
1689 {
1690 WCHAR *buf;
1691 DWORD len;
1692
1693 len = ExpandEnvironmentStringsW(str, NULL, 0);
1694 if (!len) return NULL;
1695
1696 buf = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1697 if (!buf) return NULL;
1698
1699 len = ExpandEnvironmentStringsW(str, buf, len);
1700 if (!len)
1701 {
1702 HeapFree(GetProcessHeap(), 0, buf);
1703 return NULL;
1704 }
1705 return buf;
1706 }
1707
1708 /*************************************************************************
1709 * SHELL_execute [Internal]
1710 */
1711 static BOOL SHELL_execute(LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc)
1712 {
1713 static const DWORD unsupportedFlags =
1714 SEE_MASK_INVOKEIDLIST | SEE_MASK_ICON | SEE_MASK_HOTKEY |
1715 SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT |
1716 SEE_MASK_UNICODE | SEE_MASK_ASYNCOK | SEE_MASK_HMONITOR;
1717
1718 WCHAR parametersBuffer[1024], dirBuffer[MAX_PATH], wcmdBuffer[1024];
1719 WCHAR *wszApplicationName, *wszParameters, *wszDir, *wcmd;
1720 DWORD dwApplicationNameLen = MAX_PATH + 2;
1721 DWORD parametersLen = sizeof(parametersBuffer) / sizeof(WCHAR);
1722 DWORD dirLen = sizeof(dirBuffer) / sizeof(WCHAR);
1723 DWORD wcmdLen = sizeof(wcmdBuffer) / sizeof(WCHAR);
1724 DWORD len;
1725 SHELLEXECUTEINFOW sei_tmp; /* modifiable copy of SHELLEXECUTEINFO struct */
1726 WCHAR wfileName[MAX_PATH];
1727 WCHAR *env;
1728 WCHAR wszKeyname[256];
1729 LPCWSTR lpFile;
1730 UINT_PTR retval = SE_ERR_NOASSOC;
1731 BOOL appKnownSingular = FALSE;
1732
1733 /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
1734 sei_tmp = *sei;
1735
1736 TRACE("mask=0x%08x hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
1737 sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
1738 debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
1739 debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
1740 ((sei_tmp.fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME) ?
1741 debugstr_w(sei_tmp.lpClass) : "not used");
1742
1743 sei->hProcess = NULL;
1744
1745 /* make copies of all path/command strings */
1746 if (!sei_tmp.lpFile)
1747 {
1748 wszApplicationName = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen * sizeof(WCHAR));
1749 *wszApplicationName = '\0';
1750 }
1751 else if (*sei_tmp.lpFile == '\"' && sei_tmp.lpFile[(len = strlenW(sei_tmp.lpFile))-1] == '\"')
1752 {
1753 if(len-1 >= dwApplicationNameLen)
1754 dwApplicationNameLen = len;
1755
1756 wszApplicationName = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen * sizeof(WCHAR));
1757 memcpy(wszApplicationName, sei_tmp.lpFile + 1, len * sizeof(WCHAR));
1758
1759 if(len > 2)
1760 wszApplicationName[len-2] = '\0';
1761 appKnownSingular = TRUE;
1762
1763 TRACE("wszApplicationName=%s\n", debugstr_w(wszApplicationName));
1764 }
1765 else
1766 {
1767 DWORD l = strlenW(sei_tmp.lpFile) + 1;
1768 if(l > dwApplicationNameLen) dwApplicationNameLen = l + 1;
1769 wszApplicationName = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen * sizeof(WCHAR));
1770 memcpy(wszApplicationName, sei_tmp.lpFile, l * sizeof(WCHAR));
1771 }
1772
1773 wszParameters = parametersBuffer;
1774 if (sei_tmp.lpParameters)
1775 {
1776 len = lstrlenW(sei_tmp.lpParameters) + 1;
1777 if (len > parametersLen)
1778 {
1779 wszParameters = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1780 parametersLen = len;
1781 }
1782 strcpyW(wszParameters, sei_tmp.lpParameters);
1783 }
1784 else
1785 *wszParameters = L'\0';
1786
1787 wszDir = dirBuffer;
1788 if (sei_tmp.lpDirectory)
1789 {
1790 len = lstrlenW(sei_tmp.lpDirectory) + 1;
1791 if (len > dirLen)
1792 {
1793 wszDir = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1794 dirLen = len;
1795 }
1796 strcpyW(wszDir, sei_tmp.lpDirectory);
1797 }
1798 else
1799 *wszDir = L'\0';
1800
1801 /* adjust string pointers to point to the new buffers */
1802 sei_tmp.lpFile = wszApplicationName;
1803 sei_tmp.lpParameters = wszParameters;
1804 sei_tmp.lpDirectory = wszDir;
1805
1806 if (sei_tmp.fMask & unsupportedFlags)
1807 {
1808 FIXME("flags ignored: 0x%08x\n", sei_tmp.fMask & unsupportedFlags);
1809 }
1810
1811 /* process the IDList */
1812 if (sei_tmp.fMask & SEE_MASK_IDLIST)
1813 {
1814 CComPtr<IShellExecuteHookW> pSEH;
1815
1816 HRESULT hr = SHBindToParent((LPCITEMIDLIST)sei_tmp.lpIDList, IID_PPV_ARG(IShellExecuteHookW, &pSEH), NULL);
1817
1818 if (SUCCEEDED(hr))
1819 {
1820 hr = pSEH->Execute(&sei_tmp);
1821
1822 if (hr == S_OK)
1823 {
1824 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1825 if (wszParameters != parametersBuffer)
1826 HeapFree(GetProcessHeap(), 0, wszParameters);
1827 if (wszDir != dirBuffer)
1828 HeapFree(GetProcessHeap(), 0, wszDir);
1829 return TRUE;
1830 }
1831 }
1832
1833 SHGetPathFromIDListW((LPCITEMIDLIST)sei_tmp.lpIDList, wszApplicationName);
1834 appKnownSingular = TRUE;
1835 TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1836 }
1837
1838 if (sei_tmp.fMask & SEE_MASK_DOENVSUBST)
1839 {
1840 WCHAR *tmp;
1841
1842 tmp = expand_environment(sei_tmp.lpFile);
1843 if (!tmp)
1844 {
1845 return FALSE;
1846 }
1847 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1848 sei_tmp.lpFile = wszApplicationName = tmp;
1849
1850 tmp = expand_environment(sei_tmp.lpDirectory);
1851 if (!tmp)
1852 {
1853 return FALSE;
1854 }
1855 if (wszDir != dirBuffer) HeapFree(GetProcessHeap(), 0, wszDir);
1856 sei_tmp.lpDirectory = wszDir = tmp;
1857 }
1858
1859 if (ERROR_SUCCESS == ShellExecute_FromContextMenu(&sei_tmp))
1860 {
1861 sei->hInstApp = (HINSTANCE) 33;
1862 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1863 if (wszParameters != parametersBuffer)
1864 HeapFree(GetProcessHeap(), 0, wszParameters);
1865 if (wszDir != dirBuffer)
1866 HeapFree(GetProcessHeap(), 0, wszDir);
1867 return TRUE;
1868 }
1869
1870 if (sei_tmp.fMask & SEE_MASK_CLASSALL)
1871 {
1872 retval = SHELL_execute_class(wszApplicationName, &sei_tmp, sei, execfunc);
1873 if (retval <= 32 && !(sei_tmp.fMask & SEE_MASK_FLAG_NO_UI))
1874 {
1875 OPENASINFO Info;
1876
1877 //FIXME
1878 // need full path
1879
1880 Info.pcszFile = wszApplicationName;
1881 Info.pcszClass = NULL;
1882 Info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_EXEC;
1883
1884 //if (SHOpenWithDialog(sei_tmp.hwnd, &Info) != S_OK)
1885 DBG_UNREFERENCED_LOCAL_VARIABLE(Info);
1886 do_error_dialog(retval, sei_tmp.hwnd, wszApplicationName);
1887 }
1888 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1889 if (wszParameters != parametersBuffer)
1890 HeapFree(GetProcessHeap(), 0, wszParameters);
1891 if (wszDir != dirBuffer)
1892 HeapFree(GetProcessHeap(), 0, wszDir);
1893 return retval > 32;
1894 }
1895
1896 /* Has the IDList not yet been translated? */
1897 if (sei_tmp.fMask & SEE_MASK_IDLIST)
1898 {
1899 appKnownSingular = SHELL_translate_idlist( &sei_tmp, wszParameters,
1900 parametersLen,
1901 wszApplicationName,
1902 dwApplicationNameLen );
1903 }
1904
1905 /* convert file URLs */
1906 if (UrlIsFileUrlW(sei_tmp.lpFile))
1907 {
1908 LPWSTR buf;
1909 DWORD size;
1910
1911 size = MAX_PATH;
1912 buf = static_cast<LPWSTR>(HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)));
1913 if (!buf || FAILED(PathCreateFromUrlW(sei_tmp.lpFile, buf, &size, 0)))
1914 {
1915 HeapFree(GetProcessHeap(), 0, buf);
1916 return SE_ERR_OOM;
1917 }
1918
1919 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1920 wszApplicationName = buf;
1921 sei_tmp.lpFile = wszApplicationName;
1922 }
1923 else /* or expand environment strings (not both!) */
1924 {
1925 len = ExpandEnvironmentStringsW(sei_tmp.lpFile, NULL, 0);
1926 if (len > 0)
1927 {
1928 LPWSTR buf;
1929 buf = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1930
1931 ExpandEnvironmentStringsW(sei_tmp.lpFile, buf, len + 1);
1932 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1933 wszApplicationName = buf;
1934 /* appKnownSingular unmodified */
1935
1936 sei_tmp.lpFile = wszApplicationName;
1937 }
1938 }
1939
1940 if (*sei_tmp.lpDirectory)
1941 {
1942 len = ExpandEnvironmentStringsW(sei_tmp.lpDirectory, NULL, 0);
1943 if (len > 0)
1944 {
1945 LPWSTR buf;
1946 len++;
1947 buf = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1948 ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buf, len);
1949 if (wszDir != dirBuffer)
1950 HeapFree(GetProcessHeap(), 0, wszDir);
1951 wszDir = buf;
1952 sei_tmp.lpDirectory = wszDir;
1953 }
1954 }
1955
1956 /* Else, try to execute the filename */
1957 TRACE("execute: %s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1958
1959 /* separate out command line arguments from executable file name */
1960 if (!*sei_tmp.lpParameters && !appKnownSingular)
1961 {
1962 /* If the executable path is quoted, handle the rest of the command line as parameters. */
1963 if (sei_tmp.lpFile[0] == L'"')
1964 {
1965 LPWSTR src = wszApplicationName/*sei_tmp.lpFile*/ + 1;
1966 LPWSTR dst = wfileName;
1967 LPWSTR end;
1968
1969 /* copy the unquoted executable path to 'wfileName' */
1970 while(*src && *src != L'"')
1971 *dst++ = *src++;
1972
1973 *dst = L'\0';
1974
1975 if (*src == L'"')
1976 {
1977 end = ++src;
1978
1979 while(isspaceW(*src))
1980 ++src;
1981 }
1982 else
1983 end = src;
1984
1985 /* copy the parameter string to 'wszParameters' */
1986 strcpyW(wszParameters, src);
1987
1988 /* terminate previous command string after the quote character */
1989 *end = L'\0';
1990 lpFile = wfileName;
1991 }
1992 else
1993 {
1994 /* If the executable name is not quoted, we have to use this search loop here,
1995 that in CreateProcess() is not sufficient because it does not handle shell links. */
1996 WCHAR buffer[MAX_PATH], xlpFile[MAX_PATH];
1997 LPWSTR space, s;
1998
1999 LPWSTR beg = wszApplicationName/*sei_tmp.lpFile*/;
2000 for(s = beg; (space = const_cast<LPWSTR>(strchrW(s, L' '))); s = space + 1)
2001 {
2002 int idx = space - sei_tmp.lpFile;
2003 memcpy(buffer, sei_tmp.lpFile, idx * sizeof(WCHAR));
2004 buffer[idx] = '\0';
2005
2006 /*FIXME This finds directory paths if the targeted file name contains spaces. */
2007 if (SearchPathW(*sei_tmp.lpDirectory ? sei_tmp.lpDirectory : NULL, buffer, wszExe, sizeof(xlpFile) / sizeof(xlpFile[0]), xlpFile, NULL))
2008 {
2009 /* separate out command from parameter string */
2010 LPCWSTR p = space + 1;
2011
2012 while(isspaceW(*p))
2013 ++p;
2014
2015 strcpyW(wszParameters, p);
2016 *space = L'\0';
2017
2018 break;
2019 }
2020 }
2021
2022 lpFile = sei_tmp.lpFile;
2023 }
2024 }
2025 else
2026 lpFile = sei_tmp.lpFile;
2027
2028 wcmd = wcmdBuffer;
2029 len = lstrlenW(wszApplicationName) + 3;
2030 if (sei_tmp.lpParameters[0])
2031 len += 1 + lstrlenW(wszParameters);
2032 if (len > wcmdLen)
2033 {
2034 wcmd = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2035 wcmdLen = len;
2036 }
2037 swprintf(wcmd, L"\"%s\"", wszApplicationName);
2038 if (sei_tmp.lpParameters[0])
2039 {
2040 strcatW(wcmd, L" ");
2041 strcatW(wcmd, wszParameters);
2042 }
2043
2044 retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
2045 if (retval > 32)
2046 {
2047 HeapFree(GetProcessHeap(), 0, wszApplicationName);
2048 if (wszParameters != parametersBuffer)
2049 HeapFree(GetProcessHeap(), 0, wszParameters);
2050 if (wszDir != dirBuffer)
2051 HeapFree(GetProcessHeap(), 0, wszDir);
2052 if (wcmd != wcmdBuffer)
2053 HeapFree(GetProcessHeap(), 0, wcmd);
2054 return TRUE;
2055 }
2056
2057 /* Else, try to find the executable */
2058 wcmd[0] = L'\0';
2059 retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, wcmdLen, wszKeyname, &env, (LPITEMIDLIST)sei_tmp.lpIDList, sei_tmp.lpParameters);
2060 if (retval > 32) /* Found */
2061 {
2062 retval = SHELL_quote_and_execute(wcmd, wszParameters, wszKeyname,
2063 wszApplicationName, env, &sei_tmp,
2064 sei, execfunc);
2065 HeapFree(GetProcessHeap(), 0, env);
2066 }
2067 else if (PathIsDirectoryW(lpFile))
2068 {
2069 WCHAR wExec[MAX_PATH];
2070 WCHAR * lpQuotedFile = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * (strlenW(lpFile) + 3));
2071
2072 if (lpQuotedFile)
2073 {
2074 retval = SHELL_FindExecutable(sei_tmp.lpDirectory, L"explorer",
2075 wszOpen, wExec, MAX_PATH,
2076 NULL, &env, NULL, NULL);
2077 if (retval > 32)
2078 {
2079 swprintf(lpQuotedFile, L"\"%s\"", lpFile);
2080 retval = SHELL_quote_and_execute(wExec, lpQuotedFile,
2081 wszKeyname,
2082 wszApplicationName, env,
2083 &sei_tmp, sei, execfunc);
2084 HeapFree(GetProcessHeap(), 0, env);
2085 }
2086 HeapFree(GetProcessHeap(), 0, lpQuotedFile);
2087 }
2088 else
2089 retval = 0; /* Out of memory */
2090 }
2091 else if (PathIsURLW(lpFile)) /* File not found, check for URL */
2092 {
2093 retval = SHELL_execute_url(lpFile, wcmd, &sei_tmp, sei, execfunc );
2094 }
2095 /* Check if file specified is in the form www.??????.*** */
2096 else if (!strncmpiW(lpFile, L"www", 3))
2097 {
2098 /* if so, prefix lpFile with http:// and call ShellExecute */
2099 WCHAR lpstrTmpFile[256];
2100 strcpyW(lpstrTmpFile, L"http://");
2101 strcatW(lpstrTmpFile, lpFile);
2102 retval = (UINT_PTR)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
2103 }
2104
2105 TRACE("retval %lu\n", retval);
2106
2107 if (retval <= 32 && !(sei_tmp.fMask & SEE_MASK_FLAG_NO_UI))
2108 {
2109 OPENASINFO Info;
2110
2111 //FIXME
2112 // need full path
2113
2114 Info.pcszFile = wszApplicationName;
2115 Info.pcszClass = NULL;
2116 Info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_EXEC;
2117
2118 //if (SHOpenWithDialog(sei_tmp.hwnd, &Info) != S_OK)
2119 DBG_UNREFERENCED_LOCAL_VARIABLE(Info);
2120 do_error_dialog(retval, sei_tmp.hwnd, wszApplicationName);
2121 }
2122
2123 HeapFree(GetProcessHeap(), 0, wszApplicationName);
2124 if (wszParameters != parametersBuffer)
2125 HeapFree(GetProcessHeap(), 0, wszParameters);
2126 if (wszDir != dirBuffer)
2127 HeapFree(GetProcessHeap(), 0, wszDir);
2128 if (wcmd != wcmdBuffer)
2129 HeapFree(GetProcessHeap(), 0, wcmd);
2130
2131 sei->hInstApp = (HINSTANCE)(retval > 32 ? 33 : retval);
2132
2133 return retval > 32;
2134 }
2135
2136 /*************************************************************************
2137 * ShellExecuteA [SHELL32.290]
2138 */
2139 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpVerb, LPCSTR lpFile,
2140 LPCSTR lpParameters, LPCSTR lpDirectory, INT iShowCmd)
2141 {
2142 SHELLEXECUTEINFOA sei;
2143
2144 TRACE("%p,%s,%s,%s,%s,%d\n",
2145 hWnd, debugstr_a(lpVerb), debugstr_a(lpFile),
2146 debugstr_a(lpParameters), debugstr_a(lpDirectory), iShowCmd);
2147
2148 sei.cbSize = sizeof(sei);
2149 sei.fMask = SEE_MASK_FLAG_NO_UI;
2150 sei.hwnd = hWnd;
2151 sei.lpVerb = lpVerb;
2152 sei.lpFile = lpFile;
2153 sei.lpParameters = lpParameters;
2154 sei.lpDirectory = lpDirectory;
2155 sei.nShow = iShowCmd;
2156 sei.lpIDList = 0;
2157 sei.lpClass = 0;
2158 sei.hkeyClass = 0;
2159 sei.dwHotKey = 0;
2160 sei.hProcess = 0;
2161
2162 ShellExecuteExA(&sei);
2163 return sei.hInstApp;
2164 }
2165
2166 /*************************************************************************
2167 * ShellExecuteExA [SHELL32.292]
2168 *
2169 */
2170 BOOL
2171 WINAPI
2172 DECLSPEC_HOTPATCH
2173 ShellExecuteExA(LPSHELLEXECUTEINFOA sei)
2174 {
2175 SHELLEXECUTEINFOW seiW;
2176 BOOL ret;
2177 WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
2178
2179 TRACE("%p\n", sei);
2180
2181 memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
2182
2183 if (sei->lpVerb)
2184 seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
2185
2186 if (sei->lpFile)
2187 seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
2188
2189 if (sei->lpParameters)
2190 seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
2191
2192 if (sei->lpDirectory)
2193 seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
2194
2195 if ((sei->fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME && sei->lpClass)
2196 seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
2197 else
2198 seiW.lpClass = NULL;
2199
2200 ret = SHELL_execute(&seiW, SHELL_ExecuteW);
2201
2202 sei->hInstApp = seiW.hInstApp;
2203
2204 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
2205 sei->hProcess = seiW.hProcess;
2206
2207 SHFree(wVerb);
2208 SHFree(wFile);
2209 SHFree(wParameters);
2210 SHFree(wDirectory);
2211 SHFree(wClass);
2212
2213 return ret;
2214 }
2215
2216 /*************************************************************************
2217 * ShellExecuteExW [SHELL32.293]
2218 *
2219 */
2220 BOOL
2221 WINAPI
2222 DECLSPEC_HOTPATCH
2223 ShellExecuteExW(LPSHELLEXECUTEINFOW sei)
2224 {
2225 return SHELL_execute(sei, SHELL_ExecuteW);
2226 }
2227
2228 /*************************************************************************
2229 * ShellExecuteW [SHELL32.294]
2230 * from shellapi.h
2231 * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpVerb,
2232 * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
2233 */
2234 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpVerb, LPCWSTR lpFile,
2235 LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
2236 {
2237 SHELLEXECUTEINFOW sei;
2238
2239 TRACE("\n");
2240 sei.cbSize = sizeof(sei);
2241 sei.fMask = SEE_MASK_FLAG_NO_UI;
2242 sei.hwnd = hwnd;
2243 sei.lpVerb = lpVerb;
2244 sei.lpFile = lpFile;
2245 sei.lpParameters = lpParameters;
2246 sei.lpDirectory = lpDirectory;
2247 sei.nShow = nShowCmd;
2248 sei.lpIDList = 0;
2249 sei.lpClass = 0;
2250 sei.hkeyClass = 0;
2251 sei.dwHotKey = 0;
2252 sei.hProcess = 0;
2253
2254 SHELL_execute(&sei, SHELL_ExecuteW);
2255 return sei.hInstApp;
2256 }
2257
2258 /*************************************************************************
2259 * WOWShellExecute [SHELL32.@]
2260 *
2261 * FIXME: the callback function most likely doesn't work the same way on Windows.
2262 */
2263 EXTERN_C HINSTANCE WINAPI WOWShellExecute(HWND hWnd, LPCSTR lpVerb, LPCSTR lpFile,
2264 LPCSTR lpParameters, LPCSTR lpDirectory, INT iShowCmd, void *callback)
2265 {
2266 SHELLEXECUTEINFOW seiW;
2267 WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL;
2268 HANDLE hProcess = 0;
2269
2270 seiW.lpVerb = lpVerb ? __SHCloneStrAtoW(&wVerb, lpVerb) : NULL;
2271 seiW.lpFile = lpFile ? __SHCloneStrAtoW(&wFile, lpFile) : NULL;
2272 seiW.lpParameters = lpParameters ? __SHCloneStrAtoW(&wParameters, lpParameters) : NULL;
2273 seiW.lpDirectory = lpDirectory ? __SHCloneStrAtoW(&wDirectory, lpDirectory) : NULL;
2274
2275 seiW.cbSize = sizeof(seiW);
2276 seiW.fMask = 0;
2277 seiW.hwnd = hWnd;
2278 seiW.nShow = iShowCmd;
2279 seiW.lpIDList = 0;
2280 seiW.lpClass = 0;
2281 seiW.hkeyClass = 0;
2282 seiW.dwHotKey = 0;
2283 seiW.hProcess = hProcess;
2284
2285 SHELL_execute(&seiW, (SHELL_ExecuteW32)callback);
2286
2287 SHFree(wVerb);
2288 SHFree(wFile);
2289 SHFree(wParameters);
2290 SHFree(wDirectory);
2291 return seiW.hInstApp;
2292 }
2293
2294 /*************************************************************************
2295 * OpenAs_RunDLLW [SHELL32.@]
2296 */
2297 EXTERN_C void WINAPI
2298 OpenAs_RunDLLW(HWND hwnd, HINSTANCE hinst, LPCWSTR cmdline, int cmdshow)
2299 {
2300 OPENASINFO info;
2301 TRACE("%p, %p, %s, %d\n", hwnd, hinst, debugstr_w(cmdline), cmdshow);
2302
2303 ZeroMemory(&info, sizeof(info));
2304 info.pcszFile = cmdline;
2305 info.pcszClass = NULL;
2306 info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_REGISTER_EXT | OAIF_EXEC;
2307
2308 SHOpenWithDialog(hwnd, &info);
2309 }
2310
2311 /*************************************************************************
2312 * OpenAs_RunDLLA [SHELL32.@]
2313 */
2314 EXTERN_C void WINAPI
2315 OpenAs_RunDLLA(HWND hwnd, HINSTANCE hinst, LPCSTR cmdline, int cmdshow)
2316 {
2317 LPWSTR pszCmdLineW = NULL;
2318 TRACE("%p, %p, %s, %d\n", hwnd, hinst, debugstr_a(cmdline), cmdshow);
2319
2320 if (cmdline)
2321 __SHCloneStrAtoW(&pszCmdLineW, cmdline);
2322 OpenAs_RunDLLW(hwnd, hinst, pszCmdLineW, cmdshow);
2323 SHFree(pszCmdLineW);
2324 }