974fd3e6266a1e76f5a9898ac15f126875233a25
[reactos.git] / base / shell / cmd / cmd.c
1 /*
2 * CMD.C - command-line interface.
3 *
4 *
5 * History:
6 *
7 * 17 Jun 1994 (Tim Norman)
8 * started.
9 *
10 * 08 Aug 1995 (Matt Rains)
11 * I have cleaned up the source code. changes now bring this source
12 * into guidelines for recommended programming practice.
13 *
14 * A added the the standard FreeDOS GNU licence test to the
15 * initialize() function.
16 *
17 * Started to replace puts() with printf(). this will help
18 * standardize output. please follow my lead.
19 *
20 * I have added some constants to help making changes easier.
21 *
22 * 15 Dec 1995 (Tim Norman)
23 * major rewrite of the code to make it more efficient and add
24 * redirection support (finally!)
25 *
26 * 06 Jan 1996 (Tim Norman)
27 * finished adding redirection support! Changed to use our own
28 * exec code (MUCH thanks to Svante Frey!!)
29 *
30 * 29 Jan 1996 (Tim Norman)
31 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
32 * suggestion of Steffan Kaiser
33 *
34 * changed "file not found" error message to "bad command or
35 * filename" thanks to Dustin Norman for noticing that confusing
36 * message!
37 *
38 * changed the format to call internal commands (again) so that if
39 * they want to split their commands, they can do it themselves
40 * (none of the internal functions so far need that much power, anyway)
41 *
42 * 27 Aug 1996 (Tim Norman)
43 * added in support for Oliver Mueller's ALIAS command
44 *
45 * 14 Jun 1997 (Steffan Kaiser)
46 * added ctrl-break handling and error level
47 *
48 * 16 Jun 1998 (Rob Lake)
49 * Runs command.com if /P is specified in command line. Command.com
50 * also stays permanent. If /C is in the command line, starts the
51 * program next in the line.
52 *
53 * 21 Jun 1998 (Rob Lake)
54 * Fixed up /C so that arguments for the program
55 *
56 * 08-Jul-1998 (John P. Price)
57 * Now sets COMSPEC environment variable
58 * misc clean up and optimization
59 * added date and time commands
60 * changed to using spawnl instead of exec. exec does not copy the
61 * environment to the child process!
62 *
63 * 14 Jul 1998 (Hans B Pufal)
64 * Reorganised source to be more efficient and to more closely
65 * follow MS-DOS conventions. (eg %..% environment variable
66 * replacement works form command line as well as batch file.
67 *
68 * New organisation also properly support nested batch files.
69 *
70 * New command table structure is half way towards providing a
71 * system in which COMMAND will find out what internal commands
72 * are loaded
73 *
74 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
75 * Fixed return value when called with /C option
76 *
77 * 27 Jul 1998 John P. Price
78 * added config.h include
79 *
80 * 28 Jul 1998 John P. Price
81 * added showcmds function to show commands and options available
82 *
83 * 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
84 * Fixed carriage return output to better match MSDOS with echo
85 * on or off. (marked with "JPP 19980708")
86 *
87 * 07-Dec-1998 (Eric Kohl)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
90 *
91 * 13-Dec-1998 (Eric Kohl)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
94 *
95 * 07-Jan-1999 (Eric Kohl)
96 * Added help text ("cmd /?").
97 *
98 * 25-Jan-1999 (Eric Kohl)
99 * Unicode and redirection safe!
100 * Fixed redirections and piping.
101 * Piping is based on temporary files, but basic support
102 * for anonymous pipes already exists.
103 *
104 * 27-Jan-1999 (Eric Kohl)
105 * Replaced spawnl() by CreateProcess().
106 *
107 * 22-Oct-1999 (Eric Kohl)
108 * Added break handler.
109 *
110 * 15-Dec-1999 (Eric Kohl)
111 * Fixed current directory
112 *
113 * 28-Dec-1999 (Eric Kohl)
114 * Restore window title after program/batch execution
115 *
116 * 03-Feb-2001 (Eric Kohl)
117 * Workaround because argc[0] is NULL under ReactOS
118 *
119 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
120 * %envvar% replacement conflicted with for.
121 *
122 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
123 * Make MakeSureDirectoryPathExistsEx unicode safe.
124 *
125 * 28-Mai-2004
126 * Removed MakeSureDirectoryPathExistsEx.
127 * Use the current directory if GetTempPath fails.
128 *
129 * 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
130 * Added ShellExecute call when all else fails to be able to "launch" any file.
131 *
132 * 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
133 * Remove all hardcode string to En.rc
134 *
135 * 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
136 * Add 'help' command (list all commands plus description)
137 *
138 * 06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
139 * translate '%errorlevel%' to the internal value.
140 * Add proper memory alloc ProcessInput, the error
141 * handling for memory handling need to be improve
142 */
143
144 #include "precomp.h"
145 #include <reactos/buildno.h>
146 #include <reactos/version.h>
147
148 typedef NTSTATUS (WINAPI *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
149 PVOID, ULONG, PULONG);
150 typedef NTSTATUS (WINAPI *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
151
152 BOOL bExit = FALSE; /* indicates EXIT was typed */
153 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
154 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
155 BOOL bIgnoreEcho = FALSE; /* Set this to TRUE to prevent a newline, when executing a command */
156 static BOOL bWaitForCommand = FALSE; /* When we are executing something passed on the commandline after /c or /k */
157 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
158 CRITICAL_SECTION ChildProcessRunningLock;
159 BOOL bDisableBatchEcho = FALSE;
160 BOOL bEnableExtensions = TRUE;
161 BOOL bDelayedExpansion = FALSE;
162 BOOL bTitleSet = FALSE;
163 DWORD dwChildProcessId = 0;
164 LPTSTR lpOriginalEnvironment;
165 HANDLE CMD_ModuleHandle;
166
167 static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
168 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
169
170 /*
171 * Default output file stream translation mode is UTF8, but CMD switches
172 * allow to change it to either UTF16 (/U) or ANSI (/A).
173 */
174 CON_STREAM_MODE OutputStreamMode = UTF8Text; // AnsiText;
175
176 #ifdef INCLUDE_CMD_COLOR
177 WORD wDefColor = 0; /* Default color */
178 #endif
179
180 /*
181 * convert
182 *
183 * insert commas into a number
184 */
185 INT
186 ConvertULargeInteger(ULONGLONG num, LPTSTR des, UINT len, BOOL bPutSeparator)
187 {
188 TCHAR temp[39]; /* maximum length with nNumberGroups == 1 */
189 UINT n, iTarget;
190
191 if (len <= 1)
192 return 0;
193
194 n = 0;
195 iTarget = nNumberGroups;
196 if (!nNumberGroups)
197 bPutSeparator = FALSE;
198
199 do
200 {
201 if (iTarget == n && bPutSeparator)
202 {
203 iTarget += nNumberGroups + 1;
204 temp[38 - n++] = cThousandSeparator;
205 }
206 temp[38 - n++] = (TCHAR)(num % 10) + _T('0');
207 num /= 10;
208 } while (num > 0);
209 if (n > len-1)
210 n = len-1;
211
212 memcpy(des, temp + 39 - n, n * sizeof(TCHAR));
213 des[n] = _T('\0');
214
215 return n;
216 }
217
218 /*
219 * Is a process a console process?
220 */
221 static BOOL IsConsoleProcess(HANDLE Process)
222 {
223 NTSTATUS Status;
224 PROCESS_BASIC_INFORMATION Info;
225 PEB ProcessPeb;
226 ULONG BytesRead;
227
228 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
229 {
230 return TRUE;
231 }
232
233 Status = NtQueryInformationProcessPtr (
234 Process, ProcessBasicInformation,
235 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
236 if (! NT_SUCCESS(Status))
237 {
238 WARN ("NtQueryInformationProcess failed with status %08x\n", Status);
239 return TRUE;
240 }
241 Status = NtReadVirtualMemoryPtr (
242 Process, Info.PebBaseAddress, &ProcessPeb,
243 sizeof(PEB), &BytesRead);
244 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
245 {
246 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status, BytesRead);
247 return TRUE;
248 }
249
250 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubsystem;
251 }
252
253
254
255 #ifdef _UNICODE
256 #define SHELLEXECUTETEXT "ShellExecuteExW"
257 #else
258 #define SHELLEXECUTETEXT "ShellExecuteExA"
259 #endif
260
261 typedef BOOL (WINAPI *MYEX)(LPSHELLEXECUTEINFO lpExecInfo);
262
263 HANDLE RunFile(DWORD flags, LPTSTR filename, LPTSTR params,
264 LPTSTR directory, INT show)
265 {
266 SHELLEXECUTEINFO sei;
267 HMODULE hShell32;
268 MYEX hShExt;
269 BOOL ret;
270
271 TRACE ("RunFile(%s)\n", debugstr_aw(filename));
272 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
273 if (!hShell32)
274 {
275 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
276 return NULL;
277 }
278
279 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
280 if (!hShExt)
281 {
282 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
283 FreeLibrary(hShell32);
284 return NULL;
285 }
286
287 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt);
288
289 memset(&sei, 0, sizeof sei);
290 sei.cbSize = sizeof sei;
291 sei.fMask = flags;
292 sei.lpFile = filename;
293 sei.lpParameters = params;
294 sei.lpDirectory = directory;
295 sei.nShow = show;
296 ret = hShExt(&sei);
297
298 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret);
299
300 FreeLibrary(hShell32);
301 return ret ? sei.hProcess : NULL;
302 }
303
304
305
306 /*
307 * This command (in first) was not found in the command table
308 *
309 * Full - buffer to hold whole command line
310 * First - first word on command line
311 * Rest - rest of command line
312 */
313 static INT
314 Execute(LPTSTR Full, LPTSTR First, LPTSTR Rest, PARSED_COMMAND *Cmd)
315 {
316 TCHAR szFullName[MAX_PATH];
317 TCHAR *first, *rest, *dot;
318 TCHAR szWindowTitle[MAX_PATH];
319 TCHAR szNewTitle[MAX_PATH*2];
320 DWORD dwExitCode = 0;
321 TCHAR *FirstEnd;
322 TCHAR szFullCmdLine[CMDLINE_LENGTH];
323
324 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First), debugstr_aw(Rest));
325
326 /* Though it was already parsed once, we have a different set of rules
327 for parsing before we pass to CreateProcess */
328 if (First[0] == _T('/') || (First[0] && First[1] == _T(':')))
329 {
330 /* Use the entire first word as the program name (no change) */
331 FirstEnd = First + _tcslen(First);
332 }
333 else
334 {
335 /* If present in the first word, spaces and ,;=/ end the program
336 * name and become the beginning of its parameters. */
337 BOOL bInside = FALSE;
338 for (FirstEnd = First; *FirstEnd; FirstEnd++)
339 {
340 if (!bInside && (_istspace(*FirstEnd) || _tcschr(_T(",;=/"), *FirstEnd)))
341 break;
342 bInside ^= *FirstEnd == _T('"');
343 }
344 }
345
346 /* Copy the new first/rest into the buffer */
347 first = Full;
348 rest = &Full[FirstEnd - First + 1];
349 _tcscpy(rest, FirstEnd);
350 _tcscat(rest, Rest);
351 *FirstEnd = _T('\0');
352 _tcscpy(first, First);
353
354 /* check for a drive change */
355 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
356 {
357 BOOL working = TRUE;
358 if (!SetCurrentDirectory(first))
359 /* Guess they changed disc or something, handle that gracefully and get to root */
360 {
361 TCHAR str[4];
362 str[0]=first[0];
363 str[1]=_T(':');
364 str[2]=_T('\\');
365 str[3]=0;
366 working = SetCurrentDirectory(str);
367 }
368
369 if (!working) ConErrResPuts (STRING_FREE_ERROR1);
370 return !working;
371 }
372
373 /* get the PATH environment variable and parse it */
374 /* search the PATH environment variable for the binary */
375 StripQuotes(First);
376 if (!SearchForExecutable(First, szFullName))
377 {
378 error_bad_command(first);
379 return 1;
380 }
381
382 /* Save the original console title and build a new one */
383 GetConsoleTitle(szWindowTitle, ARRAYSIZE(szWindowTitle));
384 bTitleSet = FALSE;
385 StringCchPrintf(szNewTitle, ARRAYSIZE(szNewTitle),
386 _T("%s - %s%s"), szWindowTitle, First, Rest);
387 ConSetTitle(szNewTitle);
388
389 /* check if this is a .BAT or .CMD file */
390 dot = _tcsrchr (szFullName, _T('.'));
391 if (dot && (!_tcsicmp (dot, _T(".bat")) || !_tcsicmp (dot, _T(".cmd"))))
392 {
393 while (*rest == _T(' '))
394 rest++;
395 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName), debugstr_aw(rest));
396 dwExitCode = Batch(szFullName, first, rest, Cmd);
397 }
398 else
399 {
400 /* exec the program */
401 PROCESS_INFORMATION prci;
402 STARTUPINFO stui;
403
404 /* build command line for CreateProcess(): FullName + " " + rest */
405 BOOL quoted = !!_tcschr(First, ' ');
406 _tcscpy(szFullCmdLine, quoted ? _T("\"") : _T(""));
407 _tcsncat(szFullCmdLine, First, CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
408 _tcsncat(szFullCmdLine, quoted ? _T("\"") : _T(""), CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
409
410 if (*rest)
411 {
412 _tcsncat(szFullCmdLine, _T(" "), CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
413 _tcsncat(szFullCmdLine, rest, CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
414 }
415
416 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine));
417
418 /* fill startup info */
419 memset (&stui, 0, sizeof (STARTUPINFO));
420 stui.cb = sizeof (STARTUPINFO);
421 stui.dwFlags = STARTF_USESHOWWINDOW;
422 stui.wShowWindow = SW_SHOWDEFAULT;
423
424 /* Set the console to standard mode */
425 SetConsoleMode(ConStreamGetOSHandle(StdIn),
426 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
427
428 if (CreateProcess(szFullName,
429 szFullCmdLine,
430 NULL,
431 NULL,
432 TRUE,
433 0,
434 NULL,
435 NULL,
436 &stui,
437 &prci))
438 {
439 CloseHandle(prci.hThread);
440 }
441 else
442 {
443 // See if we can run this with ShellExecute() ie myfile.xls
444 prci.hProcess = RunFile(SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
445 szFullName,
446 rest,
447 NULL,
448 SW_SHOWNORMAL);
449 }
450
451 if (prci.hProcess != NULL)
452 {
453 if (bc != NULL || bWaitForCommand || IsConsoleProcess(prci.hProcess))
454 {
455 /* when processing a batch file or starting console processes: execute synchronously */
456 EnterCriticalSection(&ChildProcessRunningLock);
457 dwChildProcessId = prci.dwProcessId;
458
459 WaitForSingleObject(prci.hProcess, INFINITE);
460
461 LeaveCriticalSection(&ChildProcessRunningLock);
462
463 GetExitCodeProcess(prci.hProcess, &dwExitCode);
464 nErrorLevel = (INT)dwExitCode;
465 }
466 CloseHandle(prci.hProcess);
467 }
468 else
469 {
470 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full));
471 error_bad_command(first);
472 dwExitCode = 1;
473 }
474
475 /* Restore our default console mode */
476 SetConsoleMode(ConStreamGetOSHandle(StdIn),
477 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
478 SetConsoleMode(ConStreamGetOSHandle(StdOut),
479 ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
480 }
481
482 /* Update our local codepage cache */
483 {
484 UINT uNewInputCodePage = GetConsoleCP();
485 UINT uNewOutputCodePage = GetConsoleOutputCP();
486
487 if ((InputCodePage != uNewInputCodePage) ||
488 (OutputCodePage != uNewOutputCodePage))
489 {
490 /* Update the locale as well */
491 InitLocale();
492 }
493
494 InputCodePage = uNewInputCodePage;
495 OutputCodePage = uNewOutputCodePage;
496
497 /* Update the streams codepage cache as well */
498 ConStreamSetCacheCodePage(StdIn , InputCodePage );
499 ConStreamSetCacheCodePage(StdOut, OutputCodePage);
500 ConStreamSetCacheCodePage(StdErr, OutputCodePage);
501 }
502
503 /* Restore the original console title */
504 if (!bTitleSet)
505 ConSetTitle(szWindowTitle);
506
507 return dwExitCode;
508 }
509
510
511 /*
512 * look through the internal commands and determine whether or not this
513 * command is one of them. If it is, call the command. If not, call
514 * execute to run it as an external program.
515 *
516 * first - first word on command line
517 * rest - rest of command line
518 */
519 INT
520 DoCommand(LPTSTR first, LPTSTR rest, PARSED_COMMAND *Cmd)
521 {
522 TCHAR *com;
523 TCHAR *cp;
524 LPTSTR param; /* pointer to command's parameters */
525 INT cl;
526 LPCOMMAND cmdptr;
527 BOOL nointernal = FALSE;
528 INT ret;
529
530 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first), debugstr_aw(rest));
531
532 /* full command line */
533 com = cmd_alloc((_tcslen(first) + _tcslen(rest) + 2) * sizeof(TCHAR));
534 if (com == NULL)
535 {
536 error_out_of_memory();
537 return 1;
538 }
539
540 /* If present in the first word, these characters end the name of an
541 * internal command and become the beginning of its parameters. */
542 cp = first + _tcscspn(first, _T("\t +,/;=[]"));
543
544 for (cl = 0; cl < (cp - first); cl++)
545 {
546 /* These characters do it too, but if one of them is present,
547 * then we check to see if the word is a file name and skip
548 * checking for internal commands if so.
549 * This allows running programs with names like "echo.exe" */
550 if (_tcschr(_T(".:\\"), first[cl]))
551 {
552 TCHAR tmp = *cp;
553 *cp = _T('\0');
554 nointernal = IsExistingFile(first);
555 *cp = tmp;
556 break;
557 }
558 }
559
560 /* Scan internal command table */
561 for (cmdptr = cmds; !nointernal && cmdptr->name; cmdptr++)
562 {
563 if (!_tcsnicmp(first, cmdptr->name, cl) && cmdptr->name[cl] == _T('\0'))
564 {
565 _tcscpy(com, first);
566 _tcscat(com, rest);
567 param = &com[cl];
568
569 /* Skip over whitespace to rest of line, exclude 'echo' command */
570 if (_tcsicmp(cmdptr->name, _T("echo")) != 0)
571 while (_istspace(*param))
572 param++;
573 ret = cmdptr->func(param);
574 cmd_free(com);
575 return ret;
576 }
577 }
578
579 ret = Execute(com, first, rest, Cmd);
580 cmd_free(com);
581 return ret;
582 }
583
584
585 /*
586 * process the command line and execute the appropriate functions
587 * full input/output redirection and piping are supported
588 */
589 INT ParseCommandLine(LPTSTR cmd)
590 {
591 INT Ret = 0;
592 PARSED_COMMAND *Cmd = ParseCommand(cmd);
593 if (Cmd)
594 {
595 Ret = ExecuteCommand(Cmd);
596 FreeCommand(Cmd);
597 }
598 return Ret;
599 }
600
601 /* Execute a command without waiting for it to finish. If it's an internal
602 * command or batch file, we must create a new cmd.exe process to handle it.
603 * TODO: For now, this just always creates a cmd.exe process.
604 * This works, but is inefficient for running external programs,
605 * which could just be run directly. */
606 static HANDLE
607 ExecuteAsync(PARSED_COMMAND *Cmd)
608 {
609 TCHAR CmdPath[MAX_PATH];
610 TCHAR CmdParams[CMDLINE_LENGTH], *ParamsEnd;
611 STARTUPINFO stui;
612 PROCESS_INFORMATION prci;
613
614 /* Get the path to cmd.exe */
615 GetModuleFileName(NULL, CmdPath, ARRAYSIZE(CmdPath));
616
617 /* Build the parameter string to pass to cmd.exe */
618 ParamsEnd = _stpcpy(CmdParams, _T("/S/D/C\""));
619 ParamsEnd = Unparse(Cmd, ParamsEnd, &CmdParams[CMDLINE_LENGTH - 2]);
620 if (!ParamsEnd)
621 {
622 error_out_of_memory();
623 return NULL;
624 }
625 _tcscpy(ParamsEnd, _T("\""));
626
627 memset(&stui, 0, sizeof stui);
628 stui.cb = sizeof(STARTUPINFO);
629 if (!CreateProcess(CmdPath, CmdParams, NULL, NULL, TRUE, 0,
630 NULL, NULL, &stui, &prci))
631 {
632 ErrorMessage(GetLastError(), NULL);
633 return NULL;
634 }
635
636 CloseHandle(prci.hThread);
637 return prci.hProcess;
638 }
639
640 static INT
641 ExecutePipeline(PARSED_COMMAND *Cmd)
642 {
643 #ifdef FEATURE_REDIRECTION
644 HANDLE hInput = NULL;
645 HANDLE hOldConIn = GetStdHandle(STD_INPUT_HANDLE);
646 HANDLE hOldConOut = GetStdHandle(STD_OUTPUT_HANDLE);
647 HANDLE hProcess[MAXIMUM_WAIT_OBJECTS];
648 INT nProcesses = 0;
649 DWORD dwExitCode;
650
651 /* Do all but the last pipe command */
652 do
653 {
654 HANDLE hPipeRead, hPipeWrite;
655 if (nProcesses > (MAXIMUM_WAIT_OBJECTS - 2))
656 {
657 error_too_many_parameters(_T("|"));
658 goto failed;
659 }
660
661 /* Create the pipe that this process will write into.
662 * Make the handles non-inheritable initially, because this
663 * process shouldn't inherit the reading handle. */
664 if (!CreatePipe(&hPipeRead, &hPipeWrite, NULL, 0))
665 {
666 error_no_pipe();
667 goto failed;
668 }
669
670 /* The writing side of the pipe is STDOUT for this process */
671 SetHandleInformation(hPipeWrite, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
672 SetStdHandle(STD_OUTPUT_HANDLE, hPipeWrite);
673
674 /* Execute it (error check is done later for easier cleanup) */
675 hProcess[nProcesses] = ExecuteAsync(Cmd->Subcommands);
676 CloseHandle(hPipeWrite);
677 if (hInput)
678 CloseHandle(hInput);
679
680 /* The reading side of the pipe will be STDIN for the next process */
681 SetHandleInformation(hPipeRead, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
682 SetStdHandle(STD_INPUT_HANDLE, hPipeRead);
683 hInput = hPipeRead;
684
685 if (!hProcess[nProcesses])
686 goto failed;
687 nProcesses++;
688
689 Cmd = Cmd->Subcommands->Next;
690 } while (Cmd->Type == C_PIPE);
691
692 /* The last process uses the original STDOUT */
693 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
694 hProcess[nProcesses] = ExecuteAsync(Cmd);
695 if (!hProcess[nProcesses])
696 goto failed;
697 nProcesses++;
698 CloseHandle(hInput);
699 SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
700
701 /* Wait for all processes to complete */
702 EnterCriticalSection(&ChildProcessRunningLock);
703 WaitForMultipleObjects(nProcesses, hProcess, TRUE, INFINITE);
704 LeaveCriticalSection(&ChildProcessRunningLock);
705
706 /* Use the exit code of the last process in the pipeline */
707 GetExitCodeProcess(hProcess[nProcesses - 1], &dwExitCode);
708 nErrorLevel = (INT)dwExitCode;
709
710 while (--nProcesses >= 0)
711 CloseHandle(hProcess[nProcesses]);
712 return nErrorLevel;
713
714 failed:
715 if (hInput)
716 CloseHandle(hInput);
717 while (--nProcesses >= 0)
718 {
719 TerminateProcess(hProcess[nProcesses], 0);
720 CloseHandle(hProcess[nProcesses]);
721 }
722 SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
723 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
724 #endif
725
726 return nErrorLevel;
727 }
728
729 INT
730 ExecuteCommand(PARSED_COMMAND *Cmd)
731 {
732 PARSED_COMMAND *Sub;
733 LPTSTR First, Rest;
734 INT Ret = 0;
735
736 if (!PerformRedirection(Cmd->Redirections))
737 return 1;
738
739 switch (Cmd->Type)
740 {
741 case C_COMMAND:
742 Ret = 1;
743 First = DoDelayedExpansion(Cmd->Command.First);
744 if (First)
745 {
746 Rest = DoDelayedExpansion(Cmd->Command.Rest);
747 if (Rest)
748 {
749 Ret = DoCommand(First, Rest, Cmd);
750 cmd_free(Rest);
751 }
752 cmd_free(First);
753 }
754 break;
755 case C_QUIET:
756 case C_BLOCK:
757 case C_MULTI:
758 for (Sub = Cmd->Subcommands; Sub; Sub = Sub->Next)
759 Ret = ExecuteCommand(Sub);
760 break;
761 case C_IFFAILURE:
762 Sub = Cmd->Subcommands;
763 Ret = ExecuteCommand(Sub);
764 if (Ret != 0)
765 {
766 nErrorLevel = Ret;
767 Ret = ExecuteCommand(Sub->Next);
768 }
769 break;
770 case C_IFSUCCESS:
771 Sub = Cmd->Subcommands;
772 Ret = ExecuteCommand(Sub);
773 if (Ret == 0)
774 Ret = ExecuteCommand(Sub->Next);
775 break;
776 case C_PIPE:
777 Ret = ExecutePipeline(Cmd);
778 break;
779 case C_IF:
780 Ret = ExecuteIf(Cmd);
781 break;
782 case C_FOR:
783 Ret = ExecuteFor(Cmd);
784 break;
785 }
786
787 UndoRedirection(Cmd->Redirections, NULL);
788 return Ret;
789 }
790
791 LPTSTR
792 GetEnvVar(LPCTSTR varName)
793 {
794 static LPTSTR ret = NULL;
795 UINT size;
796
797 cmd_free(ret);
798 ret = NULL;
799 size = GetEnvironmentVariable(varName, NULL, 0);
800 if (size > 0)
801 {
802 ret = cmd_alloc(size * sizeof(TCHAR));
803 if (ret != NULL)
804 GetEnvironmentVariable(varName, ret, size + 1);
805 }
806 return ret;
807 }
808
809 LPCTSTR
810 GetEnvVarOrSpecial(LPCTSTR varName)
811 {
812 static TCHAR ret[MAX_PATH];
813
814 LPTSTR var = GetEnvVar(varName);
815 if (var)
816 return var;
817
818 /* env var doesn't exist, look for a "special" one */
819 /* %CD% */
820 if (_tcsicmp(varName,_T("cd")) ==0)
821 {
822 GetCurrentDirectory(MAX_PATH, ret);
823 return ret;
824 }
825 /* %TIME% */
826 else if (_tcsicmp(varName,_T("time")) ==0)
827 {
828 return GetTimeString();
829 }
830 /* %DATE% */
831 else if (_tcsicmp(varName,_T("date")) ==0)
832 {
833 return GetDateString();
834 }
835
836 /* %RANDOM% */
837 else if (_tcsicmp(varName,_T("random")) ==0)
838 {
839 /* Get random number */
840 _itot(rand(),ret,10);
841 return ret;
842 }
843
844 /* %CMDCMDLINE% */
845 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
846 {
847 return GetCommandLine();
848 }
849
850 /* %CMDEXTVERSION% */
851 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
852 {
853 /* Set version number to 2 */
854 _itot(2,ret,10);
855 return ret;
856 }
857
858 /* %ERRORLEVEL% */
859 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
860 {
861 _itot(nErrorLevel,ret,10);
862 return ret;
863 }
864
865 return NULL;
866 }
867
868 /* Handle the %~var syntax */
869 static LPTSTR
870 GetEnhancedVar(TCHAR **pFormat, LPTSTR (*GetVar)(TCHAR, BOOL *))
871 {
872 static const TCHAR ModifierTable[] = _T("dpnxfsatz");
873 enum {
874 M_DRIVE = 1, /* D: drive letter */
875 M_PATH = 2, /* P: path */
876 M_NAME = 4, /* N: filename */
877 M_EXT = 8, /* X: extension */
878 M_FULL = 16, /* F: full path (drive+path+name+ext) */
879 M_SHORT = 32, /* S: full path (drive+path+name+ext), use short names */
880 M_ATTR = 64, /* A: attributes */
881 M_TIME = 128, /* T: modification time */
882 M_SIZE = 256, /* Z: file size */
883 } Modifiers = 0;
884
885 TCHAR *Format, *FormatEnd;
886 TCHAR *PathVarName = NULL;
887 LPTSTR Variable;
888 TCHAR *VarEnd;
889 BOOL VariableIsParam0;
890 TCHAR FullPath[MAX_PATH];
891 TCHAR FixedPath[MAX_PATH], *Filename, *Extension;
892 HANDLE hFind;
893 WIN32_FIND_DATA w32fd;
894 TCHAR *In, *Out;
895
896 static TCHAR Result[CMDLINE_LENGTH];
897
898 /* There is ambiguity between modifier characters and FOR variables;
899 * the rule that cmd uses is to pick the longest possible match.
900 * For example, if there is a %n variable, then out of %~anxnd,
901 * %~anxn will be substituted rather than just %~an. */
902
903 /* First, go through as many modifier characters as possible */
904 FormatEnd = Format = *pFormat;
905 while (*FormatEnd && _tcschr(ModifierTable, _totlower(*FormatEnd)))
906 FormatEnd++;
907
908 if (*FormatEnd == _T('$'))
909 {
910 /* $PATH: syntax */
911 PathVarName = FormatEnd + 1;
912 FormatEnd = _tcschr(PathVarName, _T(':'));
913 if (!FormatEnd)
914 return NULL;
915
916 /* Must be immediately followed by the variable */
917 Variable = GetVar(*++FormatEnd, &VariableIsParam0);
918 if (!Variable)
919 return NULL;
920 }
921 else
922 {
923 /* Backtrack if necessary to get a variable name match */
924 while (!(Variable = GetVar(*FormatEnd, &VariableIsParam0)))
925 {
926 if (FormatEnd == Format)
927 return NULL;
928 FormatEnd--;
929 }
930 }
931
932 for (; Format < FormatEnd && *Format != _T('$'); Format++)
933 Modifiers |= 1 << (_tcschr(ModifierTable, _totlower(*Format)) - ModifierTable);
934
935 *pFormat = FormatEnd + 1;
936
937 /* Exclude the leading and trailing quotes */
938 VarEnd = &Variable[_tcslen(Variable)];
939 if (*Variable == _T('"'))
940 {
941 Variable++;
942 if (VarEnd > Variable && VarEnd[-1] == _T('"'))
943 VarEnd--;
944 }
945
946 if ((char *)VarEnd - (char *)Variable >= sizeof Result)
947 return _T("");
948 memcpy(Result, Variable, (char *)VarEnd - (char *)Variable);
949 Result[VarEnd - Variable] = _T('\0');
950
951 if (PathVarName)
952 {
953 /* $PATH: syntax - search the directories listed in the
954 * specified environment variable for the file */
955 LPTSTR PathVar;
956 FormatEnd[-1] = _T('\0');
957 PathVar = GetEnvVar(PathVarName);
958 FormatEnd[-1] = _T(':');
959 if (!PathVar ||
960 !SearchPath(PathVar, Result, NULL, MAX_PATH, FullPath, NULL))
961 {
962 return _T("");
963 }
964 }
965 else if (Modifiers == 0)
966 {
967 /* For plain %~var with no modifiers, just return the variable without quotes */
968 return Result;
969 }
970 else if (VariableIsParam0)
971 {
972 /* Special case: If the variable is %0 and modifier characters are present,
973 * use the batch file's path (which includes the .bat/.cmd extension)
974 * rather than the actual %0 variable (which might not). */
975 _tcscpy(FullPath, bc->BatchFilePath);
976 }
977 else
978 {
979 /* Convert the variable, now without quotes, to a full path */
980 if (!GetFullPathName(Result, MAX_PATH, FullPath, NULL))
981 return _T("");
982 }
983
984 /* Next step is to change the path to fix letter case (e.g.
985 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
986 * replace long filenames with short. */
987
988 In = FullPath;
989 Out = FixedPath;
990
991 /* Copy drive letter */
992 *Out++ = *In++;
993 *Out++ = *In++;
994 *Out++ = *In++;
995 /* Loop over each \-separated component in the path */
996 do {
997 TCHAR *Next = _tcschr(In, _T('\\'));
998 if (Next)
999 *Next++ = _T('\0');
1000 /* Use FindFirstFile to get the correct name */
1001 if (Out + _tcslen(In) + 1 >= &FixedPath[MAX_PATH])
1002 return _T("");
1003 _tcscpy(Out, In);
1004 hFind = FindFirstFile(FixedPath, &w32fd);
1005 /* If it doesn't exist, just leave the name as it was given */
1006 if (hFind != INVALID_HANDLE_VALUE)
1007 {
1008 LPTSTR FixedComponent = w32fd.cFileName;
1009 if (*w32fd.cAlternateFileName &&
1010 ((Modifiers & M_SHORT) || !_tcsicmp(In, w32fd.cAlternateFileName)))
1011 {
1012 FixedComponent = w32fd.cAlternateFileName;
1013 }
1014 FindClose(hFind);
1015
1016 if (Out + _tcslen(FixedComponent) + 1 >= &FixedPath[MAX_PATH])
1017 return _T("");
1018 _tcscpy(Out, FixedComponent);
1019 }
1020 Filename = Out;
1021 Out += _tcslen(Out);
1022 *Out++ = _T('\\');
1023
1024 In = Next;
1025 } while (In != NULL);
1026 Out[-1] = _T('\0');
1027
1028 /* Build the result string. Start with attributes, modification time, and
1029 * file size. If the file didn't exist, these fields will all be empty. */
1030 Out = Result;
1031 if (hFind != INVALID_HANDLE_VALUE)
1032 {
1033 if (Modifiers & M_ATTR)
1034 {
1035 static const struct {
1036 TCHAR Character;
1037 WORD Value;
1038 } *Attrib, Table[] = {
1039 { _T('d'), FILE_ATTRIBUTE_DIRECTORY },
1040 { _T('r'), FILE_ATTRIBUTE_READONLY },
1041 { _T('a'), FILE_ATTRIBUTE_ARCHIVE },
1042 { _T('h'), FILE_ATTRIBUTE_HIDDEN },
1043 { _T('s'), FILE_ATTRIBUTE_SYSTEM },
1044 { _T('c'), FILE_ATTRIBUTE_COMPRESSED },
1045 { _T('o'), FILE_ATTRIBUTE_OFFLINE },
1046 { _T('t'), FILE_ATTRIBUTE_TEMPORARY },
1047 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT },
1048 };
1049 for (Attrib = Table; Attrib != &Table[9]; Attrib++)
1050 {
1051 *Out++ = w32fd.dwFileAttributes & Attrib->Value
1052 ? Attrib->Character
1053 : _T('-');
1054 }
1055 *Out++ = _T(' ');
1056 }
1057 if (Modifiers & M_TIME)
1058 {
1059 FILETIME ft;
1060 SYSTEMTIME st;
1061 FileTimeToLocalFileTime(&w32fd.ftLastWriteTime, &ft);
1062 FileTimeToSystemTime(&ft, &st);
1063
1064 Out += FormatDate(Out, &st, TRUE);
1065 *Out++ = _T(' ');
1066 Out += FormatTime(Out, &st);
1067 *Out++ = _T(' ');
1068 }
1069 if (Modifiers & M_SIZE)
1070 {
1071 ULARGE_INTEGER Size;
1072 Size.LowPart = w32fd.nFileSizeLow;
1073 Size.HighPart = w32fd.nFileSizeHigh;
1074 Out += _stprintf(Out, _T("%I64u "), Size.QuadPart);
1075 }
1076 }
1077
1078 /* When using the path-searching syntax or the S modifier,
1079 * at least part of the file path is always included.
1080 * If none of the DPNX modifiers are present, include the full path */
1081 if (PathVarName || (Modifiers & M_SHORT))
1082 if ((Modifiers & (M_DRIVE | M_PATH | M_NAME | M_EXT)) == 0)
1083 Modifiers |= M_FULL;
1084
1085 /* Now add the requested parts of the name.
1086 * With the F modifier, add all parts to form the full path. */
1087 Extension = _tcsrchr(Filename, _T('.'));
1088 if (Modifiers & (M_DRIVE | M_FULL))
1089 {
1090 *Out++ = FixedPath[0];
1091 *Out++ = FixedPath[1];
1092 }
1093 if (Modifiers & (M_PATH | M_FULL))
1094 {
1095 memcpy(Out, &FixedPath[2], (char *)Filename - (char *)&FixedPath[2]);
1096 Out += Filename - &FixedPath[2];
1097 }
1098 if (Modifiers & (M_NAME | M_FULL))
1099 {
1100 while (*Filename && Filename != Extension)
1101 *Out++ = *Filename++;
1102 }
1103 if (Modifiers & (M_EXT | M_FULL))
1104 {
1105 if (Extension)
1106 Out = _stpcpy(Out, Extension);
1107 }
1108
1109 /* Trim trailing space which otherwise would appear as a
1110 * result of using the A/T/Z modifiers but no others. */
1111 while (Out != &Result[0] && Out[-1] == _T(' '))
1112 Out--;
1113 *Out = _T('\0');
1114
1115 return Result;
1116 }
1117
1118 LPCTSTR
1119 GetBatchVar(TCHAR *varName, UINT *varNameLen)
1120 {
1121 LPCTSTR ret;
1122 TCHAR *varNameEnd;
1123 BOOL dummy;
1124
1125 *varNameLen = 1;
1126
1127 switch ( *varName )
1128 {
1129 case _T('~'):
1130 varNameEnd = varName + 1;
1131 ret = GetEnhancedVar(&varNameEnd, FindArg);
1132 if (!ret)
1133 {
1134 error_syntax(varName);
1135 return NULL;
1136 }
1137 *varNameLen = varNameEnd - varName;
1138 return ret;
1139 case _T('0'):
1140 case _T('1'):
1141 case _T('2'):
1142 case _T('3'):
1143 case _T('4'):
1144 case _T('5'):
1145 case _T('6'):
1146 case _T('7'):
1147 case _T('8'):
1148 case _T('9'):
1149 return FindArg(*varName, &dummy);
1150
1151 case _T('*'):
1152 //
1153 // Copy over the raw params(not including the batch file name
1154 //
1155 return bc->raw_params;
1156
1157 case _T('%'):
1158 return _T("%");
1159 }
1160 return NULL;
1161 }
1162
1163 BOOL
1164 SubstituteVars(TCHAR *Src, TCHAR *Dest, TCHAR Delim)
1165 {
1166 #define APPEND(From, Length) { \
1167 if (Dest + (Length) > DestEnd) \
1168 goto too_long; \
1169 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1170 Dest += Length; }
1171 #define APPEND1(Char) { \
1172 if (Dest >= DestEnd) \
1173 goto too_long; \
1174 *Dest++ = Char; }
1175
1176 TCHAR *DestEnd = Dest + CMDLINE_LENGTH - 1;
1177 const TCHAR *Var;
1178 int VarLength;
1179 TCHAR *SubstStart;
1180 TCHAR EndChr;
1181 while (*Src)
1182 {
1183 if (*Src != Delim)
1184 {
1185 APPEND1(*Src++)
1186 continue;
1187 }
1188
1189 Src++;
1190 if (bc && Delim == _T('%'))
1191 {
1192 UINT NameLen;
1193 Var = GetBatchVar(Src, &NameLen);
1194 if (Var != NULL)
1195 {
1196 VarLength = _tcslen(Var);
1197 APPEND(Var, VarLength)
1198 Src += NameLen;
1199 continue;
1200 }
1201 }
1202
1203 /* Find the end of the variable name. A colon (:) will usually
1204 * end the name and begin the optional modifier, but not if it
1205 * is immediately followed by the delimiter (%VAR:%). */
1206 SubstStart = Src;
1207 while (*Src != Delim && !(*Src == _T(':') && Src[1] != Delim))
1208 {
1209 if (!*Src)
1210 goto bad_subst;
1211 Src++;
1212 }
1213
1214 EndChr = *Src;
1215 *Src = _T('\0');
1216 Var = GetEnvVarOrSpecial(SubstStart);
1217 *Src++ = EndChr;
1218 if (Var == NULL)
1219 {
1220 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1221 if (bc)
1222 continue;
1223 goto bad_subst;
1224 }
1225 VarLength = _tcslen(Var);
1226
1227 if (EndChr == Delim)
1228 {
1229 /* %VAR% - use as-is */
1230 APPEND(Var, VarLength)
1231 }
1232 else if (*Src == _T('~'))
1233 {
1234 /* %VAR:~[start][,length]% - substring
1235 * Negative values are offsets from the end */
1236 int Start = _tcstol(Src + 1, &Src, 0);
1237 int End = VarLength;
1238 if (Start < 0)
1239 Start += VarLength;
1240 Start = max(Start, 0);
1241 Start = min(Start, VarLength);
1242 if (*Src == _T(','))
1243 {
1244 End = _tcstol(Src + 1, &Src, 0);
1245 End += (End < 0) ? VarLength : Start;
1246 End = max(End, Start);
1247 End = min(End, VarLength);
1248 }
1249 if (*Src++ != Delim)
1250 goto bad_subst;
1251 APPEND(&Var[Start], End - Start);
1252 }
1253 else
1254 {
1255 /* %VAR:old=new% - replace all occurrences of old with new
1256 * %VAR:*old=new% - replace first occurrence only,
1257 * and remove everything before it */
1258 TCHAR *Old, *New;
1259 DWORD OldLength, NewLength;
1260 BOOL Star = FALSE;
1261 int LastMatch = 0, i = 0;
1262
1263 if (*Src == _T('*'))
1264 {
1265 Star = TRUE;
1266 Src++;
1267 }
1268
1269 /* the string to replace may contain the delimiter */
1270 Src = _tcschr(Old = Src, _T('='));
1271 if (Src == NULL)
1272 goto bad_subst;
1273 OldLength = Src++ - Old;
1274 if (OldLength == 0)
1275 goto bad_subst;
1276
1277 Src = _tcschr(New = Src, Delim);
1278 if (Src == NULL)
1279 goto bad_subst;
1280 NewLength = Src++ - New;
1281
1282 while (i < VarLength)
1283 {
1284 if (_tcsnicmp(&Var[i], Old, OldLength) == 0)
1285 {
1286 if (!Star)
1287 APPEND(&Var[LastMatch], i - LastMatch)
1288 APPEND(New, NewLength)
1289 i += OldLength;
1290 LastMatch = i;
1291 if (Star)
1292 break;
1293 continue;
1294 }
1295 i++;
1296 }
1297 APPEND(&Var[LastMatch], VarLength - LastMatch)
1298 }
1299 continue;
1300
1301 bad_subst:
1302 Src = SubstStart;
1303 if (!bc)
1304 APPEND1(Delim)
1305 }
1306 *Dest = _T('\0');
1307 return TRUE;
1308 too_long:
1309 ConOutResPrintf(STRING_ALIAS_ERROR);
1310 nErrorLevel = 9023;
1311 return FALSE;
1312 #undef APPEND
1313 #undef APPEND1
1314 }
1315
1316 /* Search the list of FOR contexts for a variable */
1317 static LPTSTR FindForVar(TCHAR Var, BOOL *IsParam0)
1318 {
1319 FOR_CONTEXT *Ctx;
1320 *IsParam0 = FALSE;
1321 for (Ctx = fc; Ctx != NULL; Ctx = Ctx->prev)
1322 {
1323 if ((UINT)(Var - Ctx->firstvar) < Ctx->varcount)
1324 return Ctx->values[Var - Ctx->firstvar];
1325 }
1326 return NULL;
1327 }
1328
1329 BOOL
1330 SubstituteForVars(TCHAR *Src, TCHAR *Dest)
1331 {
1332 TCHAR *DestEnd = &Dest[CMDLINE_LENGTH - 1];
1333 while (*Src)
1334 {
1335 if (Src[0] == _T('%'))
1336 {
1337 BOOL Dummy;
1338 LPTSTR End = &Src[2];
1339 LPTSTR Value = NULL;
1340
1341 if (Src[1] == _T('~'))
1342 Value = GetEnhancedVar(&End, FindForVar);
1343
1344 if (!Value)
1345 Value = FindForVar(Src[1], &Dummy);
1346
1347 if (Value)
1348 {
1349 if (Dest + _tcslen(Value) > DestEnd)
1350 return FALSE;
1351 Dest = _stpcpy(Dest, Value);
1352 Src = End;
1353 continue;
1354 }
1355 }
1356 /* Not a variable; just copy the character */
1357 if (Dest >= DestEnd)
1358 return FALSE;
1359 *Dest++ = *Src++;
1360 }
1361 *Dest = _T('\0');
1362 return TRUE;
1363 }
1364
1365 LPTSTR
1366 DoDelayedExpansion(LPTSTR Line)
1367 {
1368 TCHAR Buf1[CMDLINE_LENGTH];
1369 TCHAR Buf2[CMDLINE_LENGTH];
1370
1371 /* First, substitute FOR variables */
1372 if (!SubstituteForVars(Line, Buf1))
1373 return NULL;
1374
1375 if (!bDelayedExpansion || !_tcschr(Buf1, _T('!')))
1376 return cmd_dup(Buf1);
1377
1378 /* FIXME: Delayed substitutions actually aren't quite the same as
1379 * immediate substitutions. In particular, it's possible to escape
1380 * the exclamation point using ^. */
1381 if (!SubstituteVars(Buf1, Buf2, _T('!')))
1382 return NULL;
1383 return cmd_dup(Buf2);
1384 }
1385
1386
1387 /*
1388 * do the prompt/input/process loop
1389 *
1390 */
1391
1392 BOOL
1393 ReadLine(TCHAR *commandline, BOOL bMore)
1394 {
1395 TCHAR readline[CMDLINE_LENGTH];
1396 LPTSTR ip;
1397
1398 /* if no batch input then... */
1399 if (bc == NULL)
1400 {
1401 if (bMore)
1402 {
1403 ConOutResPrintf(STRING_MORE);
1404 }
1405 else
1406 {
1407 /* JPP 19980807 - if echo off, don't print prompt */
1408 if (bEcho)
1409 {
1410 if (!bIgnoreEcho)
1411 ConOutChar(_T('\n'));
1412 PrintPrompt();
1413 }
1414 }
1415
1416 if (!ReadCommand(readline, CMDLINE_LENGTH - 1))
1417 {
1418 bExit = TRUE;
1419 return FALSE;
1420 }
1421
1422 if (readline[0] == _T('\0'))
1423 ConOutChar(_T('\n'));
1424
1425 if (CheckCtrlBreak(BREAK_INPUT))
1426 return FALSE;
1427
1428 if (readline[0] == _T('\0'))
1429 return FALSE;
1430
1431 ip = readline;
1432 }
1433 else
1434 {
1435 ip = ReadBatchLine();
1436 if (!ip)
1437 return FALSE;
1438 }
1439
1440 return SubstituteVars(ip, commandline, _T('%'));
1441 }
1442
1443 static VOID
1444 ProcessInput(VOID)
1445 {
1446 PARSED_COMMAND *Cmd;
1447
1448 while (!bCanExit || !bExit)
1449 {
1450 /* Reset the Ctrl-Break / Ctrl-C state */
1451 bCtrlBreak = FALSE;
1452
1453 Cmd = ParseCommand(NULL);
1454 if (!Cmd)
1455 continue;
1456
1457 ExecuteCommand(Cmd);
1458 FreeCommand(Cmd);
1459 }
1460 }
1461
1462
1463 /*
1464 * control-break handler.
1465 */
1466 BOOL WINAPI BreakHandler(DWORD dwCtrlType)
1467 {
1468 DWORD dwWritten;
1469 INPUT_RECORD rec;
1470
1471 if ((dwCtrlType != CTRL_C_EVENT) &&
1472 (dwCtrlType != CTRL_BREAK_EVENT))
1473 {
1474 return FALSE;
1475 }
1476
1477 if (!TryEnterCriticalSection(&ChildProcessRunningLock))
1478 {
1479 /* Child process is running and will have received the control event */
1480 return TRUE;
1481 }
1482 else
1483 {
1484 LeaveCriticalSection(&ChildProcessRunningLock);
1485 }
1486
1487 bCtrlBreak = TRUE;
1488
1489 rec.EventType = KEY_EVENT;
1490 rec.Event.KeyEvent.bKeyDown = TRUE;
1491 rec.Event.KeyEvent.wRepeatCount = 1;
1492 rec.Event.KeyEvent.wVirtualKeyCode = _T('C');
1493 rec.Event.KeyEvent.wVirtualScanCode = _T('C') - 35;
1494 rec.Event.KeyEvent.uChar.AsciiChar = _T('C');
1495 rec.Event.KeyEvent.uChar.UnicodeChar = _T('C');
1496 rec.Event.KeyEvent.dwControlKeyState = RIGHT_CTRL_PRESSED;
1497
1498 WriteConsoleInput(ConStreamGetOSHandle(StdIn),
1499 &rec,
1500 1,
1501 &dwWritten);
1502
1503 /* FIXME: Handle batch files */
1504
1505 // ConOutPrintf(_T("^C"));
1506
1507 return TRUE;
1508 }
1509
1510
1511 VOID AddBreakHandler(VOID)
1512 {
1513 SetConsoleCtrlHandler(BreakHandler, TRUE);
1514 }
1515
1516
1517 VOID RemoveBreakHandler(VOID)
1518 {
1519 SetConsoleCtrlHandler(BreakHandler, FALSE);
1520 }
1521
1522
1523 /*
1524 * show commands and options that are available.
1525 *
1526 */
1527 #if 0
1528 static VOID
1529 ShowCommands(VOID)
1530 {
1531 /* print command list */
1532 ConOutResPuts(STRING_CMD_HELP1);
1533 PrintCommandList();
1534
1535 /* print feature list */
1536 ConOutResPuts(STRING_CMD_HELP2);
1537
1538 #ifdef FEATURE_ALIASES
1539 ConOutResPuts(STRING_CMD_HELP3);
1540 #endif
1541 #ifdef FEATURE_HISTORY
1542 ConOutResPuts(STRING_CMD_HELP4);
1543 #endif
1544 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1545 ConOutResPuts(STRING_CMD_HELP5);
1546 #endif
1547 #ifdef FEATURE_DIRECTORY_STACK
1548 ConOutResPuts(STRING_CMD_HELP6);
1549 #endif
1550 #ifdef FEATURE_REDIRECTION
1551 ConOutResPuts(STRING_CMD_HELP7);
1552 #endif
1553 ConOutChar(_T('\n'));
1554 }
1555 #endif
1556
1557
1558 static VOID
1559 LoadRegistrySettings(HKEY hKeyRoot)
1560 {
1561 LONG lRet;
1562 HKEY hKey;
1563 DWORD dwType, len;
1564 /*
1565 * Buffer big enough to hold the string L"4294967295",
1566 * corresponding to the literal 0xFFFFFFFF (MAX_ULONG) in decimal.
1567 */
1568 DWORD Buffer[6];
1569
1570 lRet = RegOpenKeyEx(hKeyRoot,
1571 _T("Software\\Microsoft\\Command Processor"),
1572 0,
1573 KEY_QUERY_VALUE,
1574 &hKey);
1575 if (lRet != ERROR_SUCCESS)
1576 return;
1577
1578 #ifdef INCLUDE_CMD_COLOR
1579 len = sizeof(Buffer);
1580 lRet = RegQueryValueEx(hKey,
1581 _T("DefaultColor"),
1582 NULL,
1583 &dwType,
1584 (LPBYTE)&Buffer,
1585 &len);
1586 if (lRet == ERROR_SUCCESS)
1587 {
1588 /* Overwrite the default attributes */
1589 if (dwType == REG_DWORD)
1590 wDefColor = (WORD)*(PDWORD)Buffer;
1591 else if (dwType == REG_SZ)
1592 wDefColor = (WORD)_tcstol((PTSTR)Buffer, NULL, 0);
1593 }
1594 // else, use the default attributes retrieved before.
1595 #endif
1596
1597 #if 0
1598 len = sizeof(Buffer);
1599 lRet = RegQueryValueEx(hKey,
1600 _T("DisableUNCCheck"),
1601 NULL,
1602 &dwType,
1603 (LPBYTE)&Buffer,
1604 &len);
1605 if (lRet == ERROR_SUCCESS)
1606 {
1607 /* Overwrite the default setting */
1608 if (dwType == REG_DWORD)
1609 bDisableUNCCheck = !!*(PDWORD)Buffer;
1610 else if (dwType == REG_SZ)
1611 bDisableUNCCheck = (_ttol((PTSTR)Buffer) == 1);
1612 }
1613 // else, use the default setting set globally.
1614 #endif
1615
1616 len = sizeof(Buffer);
1617 lRet = RegQueryValueEx(hKey,
1618 _T("DelayedExpansion"),
1619 NULL,
1620 &dwType,
1621 (LPBYTE)&Buffer,
1622 &len);
1623 if (lRet == ERROR_SUCCESS)
1624 {
1625 /* Overwrite the default setting */
1626 if (dwType == REG_DWORD)
1627 bDelayedExpansion = !!*(PDWORD)Buffer;
1628 else if (dwType == REG_SZ)
1629 bDelayedExpansion = (_ttol((PTSTR)Buffer) == 1);
1630 }
1631 // else, use the default setting set globally.
1632
1633 len = sizeof(Buffer);
1634 lRet = RegQueryValueEx(hKey,
1635 _T("EnableExtensions"),
1636 NULL,
1637 &dwType,
1638 (LPBYTE)&Buffer,
1639 &len);
1640 if (lRet == ERROR_SUCCESS)
1641 {
1642 /* Overwrite the default setting */
1643 if (dwType == REG_DWORD)
1644 bEnableExtensions = !!*(PDWORD)Buffer;
1645 else if (dwType == REG_SZ)
1646 bEnableExtensions = (_ttol((PTSTR)Buffer) == 1);
1647 }
1648 // else, use the default setting set globally.
1649
1650 len = sizeof(Buffer);
1651 lRet = RegQueryValueEx(hKey,
1652 _T("CompletionChar"),
1653 NULL,
1654 &dwType,
1655 (LPBYTE)&Buffer,
1656 &len);
1657 if (lRet == ERROR_SUCCESS)
1658 {
1659 /* Overwrite the default setting */
1660 if (dwType == REG_DWORD)
1661 AutoCompletionChar = (TCHAR)*(PDWORD)Buffer;
1662 else if (dwType == REG_SZ)
1663 AutoCompletionChar = (TCHAR)_tcstol((PTSTR)Buffer, NULL, 0);
1664 }
1665 // else, use the default setting set globally.
1666
1667 /* Validity check */
1668 if (IS_COMPLETION_DISABLED(AutoCompletionChar))
1669 {
1670 /* Disable autocompletion */
1671 AutoCompletionChar = 0x20;
1672 }
1673
1674 len = sizeof(Buffer);
1675 lRet = RegQueryValueEx(hKey,
1676 _T("PathCompletionChar"),
1677 NULL,
1678 &dwType,
1679 (LPBYTE)&Buffer,
1680 &len);
1681 if (lRet == ERROR_SUCCESS)
1682 {
1683 /* Overwrite the default setting */
1684 if (dwType == REG_DWORD)
1685 PathCompletionChar = (TCHAR)*(PDWORD)Buffer;
1686 else if (dwType == REG_SZ)
1687 PathCompletionChar = (TCHAR)_tcstol((PTSTR)Buffer, NULL, 0);
1688 }
1689 // else, use the default setting set globally.
1690
1691 /* Validity check */
1692 if (IS_COMPLETION_DISABLED(PathCompletionChar))
1693 {
1694 /* Disable autocompletion */
1695 PathCompletionChar = 0x20;
1696 }
1697
1698 /* Adjust completion chars */
1699 if (PathCompletionChar >= 0x20 && AutoCompletionChar < 0x20)
1700 PathCompletionChar = AutoCompletionChar;
1701 else if (AutoCompletionChar >= 0x20 && PathCompletionChar < 0x20)
1702 AutoCompletionChar = PathCompletionChar;
1703
1704 RegCloseKey(hKey);
1705 }
1706
1707 static VOID
1708 ExecuteAutoRunFile(HKEY hKeyRoot)
1709 {
1710 LONG lRet;
1711 HKEY hKey;
1712 DWORD dwType, len;
1713 TCHAR AutoRun[2048];
1714
1715 lRet = RegOpenKeyEx(hKeyRoot,
1716 _T("Software\\Microsoft\\Command Processor"),
1717 0,
1718 KEY_QUERY_VALUE,
1719 &hKey);
1720 if (lRet != ERROR_SUCCESS)
1721 return;
1722
1723 len = sizeof(AutoRun);
1724 lRet = RegQueryValueEx(hKey,
1725 _T("AutoRun"),
1726 NULL,
1727 &dwType,
1728 (LPBYTE)&AutoRun,
1729 &len);
1730 if ((lRet == ERROR_SUCCESS) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
1731 {
1732 if (*AutoRun)
1733 ParseCommandLine(AutoRun);
1734 }
1735
1736 RegCloseKey(hKey);
1737 }
1738
1739 /* Get the command that comes after a /C or /K switch */
1740 static VOID
1741 GetCmdLineCommand(TCHAR *commandline, TCHAR *ptr, BOOL AlwaysStrip)
1742 {
1743 TCHAR *LastQuote;
1744
1745 while (_istspace(*ptr))
1746 ptr++;
1747
1748 /* Remove leading quote, find final quote */
1749 if (*ptr == _T('"') &&
1750 (LastQuote = _tcsrchr(++ptr, _T('"'))) != NULL)
1751 {
1752 TCHAR *Space;
1753 /* Under certain circumstances, all quotes are preserved.
1754 * CMD /? documents these conditions as follows:
1755 * 1. No /S switch
1756 * 2. Exactly two quotes
1757 * 3. No "special characters" between the quotes
1758 * (CMD /? says &<>()@^| but parentheses did not
1759 * trigger this rule when I tested them.)
1760 * 4. Whitespace exists between the quotes
1761 * 5. Enclosed string is an executable filename
1762 */
1763 *LastQuote = _T('\0');
1764 for (Space = ptr + 1; Space < LastQuote; Space++)
1765 {
1766 if (_istspace(*Space)) /* Rule 4 */
1767 {
1768 if (!AlwaysStrip && /* Rule 1 */
1769 !_tcspbrk(ptr, _T("\"&<>@^|")) && /* Rules 2, 3 */
1770 SearchForExecutable(ptr, commandline)) /* Rule 5 */
1771 {
1772 /* All conditions met: preserve both the quotes */
1773 *LastQuote = _T('"');
1774 _tcscpy(commandline, ptr - 1);
1775 return;
1776 }
1777 break;
1778 }
1779 }
1780
1781 /* The conditions were not met: remove both the
1782 * leading quote and the last quote */
1783 _tcscpy(commandline, ptr);
1784 _tcscpy(&commandline[LastQuote - ptr], LastQuote + 1);
1785 return;
1786 }
1787
1788 /* No quotes; just copy */
1789 _tcscpy(commandline, ptr);
1790 }
1791
1792
1793 /*
1794 * Set up global initializations and process parameters
1795 */
1796 static VOID
1797 Initialize(VOID)
1798 {
1799 HMODULE NtDllModule;
1800 TCHAR commandline[CMDLINE_LENGTH];
1801 TCHAR ModuleName[_MAX_PATH + 1];
1802 // INT nExitCode;
1803
1804 HANDLE hIn, hOut;
1805
1806 TCHAR *ptr, *cmdLine, option = 0;
1807 BOOL AlwaysStrip = FALSE;
1808 BOOL AutoRun = TRUE;
1809
1810 /* Get version information */
1811 InitOSVersion();
1812
1813 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1814 * build process. So don't link implicitly against ntdll.dll, load it
1815 * dynamically instead */
1816 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1817 if (NtDllModule != NULL)
1818 {
1819 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1820 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1821 }
1822
1823 /* Load the registry settings */
1824 LoadRegistrySettings(HKEY_LOCAL_MACHINE);
1825 LoadRegistrySettings(HKEY_CURRENT_USER);
1826
1827 /* Initialize our locale */
1828 InitLocale();
1829
1830 /* Initialize prompt support */
1831 InitPrompt();
1832
1833 #ifdef FEATURE_DIR_STACK
1834 /* Initialize directory stack */
1835 InitDirectoryStack();
1836 #endif
1837
1838 #ifdef FEATURE_HISTORY
1839 /* Initialize history */
1840 InitHistory();
1841 #endif
1842
1843 /* Set COMSPEC environment variable */
1844 if (GetModuleFileName(NULL, ModuleName, ARRAYSIZE(ModuleName)) != 0)
1845 {
1846 ModuleName[_MAX_PATH] = _T('\0');
1847 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1848 }
1849
1850 /* Add ctrl break handler */
1851 AddBreakHandler();
1852
1853 /* Set our default console mode */
1854 hOut = ConStreamGetOSHandle(StdOut);
1855 hIn = ConStreamGetOSHandle(StdIn);
1856 SetConsoleMode(hOut, 0); // Reinitialize the console output mode
1857 SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
1858 SetConsoleMode(hIn , ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
1859
1860 cmdLine = GetCommandLine();
1861 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine));
1862
1863 for (ptr = cmdLine; *ptr; ptr++)
1864 {
1865 if (*ptr == _T('/'))
1866 {
1867 option = _totupper(ptr[1]);
1868 if (option == _T('?'))
1869 {
1870 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1871 nErrorLevel = 1;
1872 bExit = TRUE;
1873 return;
1874 }
1875 else if (option == _T('P'))
1876 {
1877 if (!IsExistingFile (_T("\\autoexec.bat")))
1878 {
1879 #ifdef INCLUDE_CMD_DATE
1880 cmd_date (_T(""));
1881 #endif
1882 #ifdef INCLUDE_CMD_TIME
1883 cmd_time (_T(""));
1884 #endif
1885 }
1886 else
1887 {
1888 ParseCommandLine (_T("\\autoexec.bat"));
1889 }
1890 bCanExit = FALSE;
1891 }
1892 else if (option == _T('A'))
1893 {
1894 OutputStreamMode = AnsiText;
1895 }
1896 else if (option == _T('C') || option == _T('K') || option == _T('R'))
1897 {
1898 /* Remainder of command line is a command to be run */
1899 break;
1900 }
1901 else if (option == _T('D'))
1902 {
1903 AutoRun = FALSE;
1904 }
1905 else if (option == _T('Q'))
1906 {
1907 bDisableBatchEcho = TRUE;
1908 }
1909 else if (option == _T('S'))
1910 {
1911 AlwaysStrip = TRUE;
1912 }
1913 #ifdef INCLUDE_CMD_COLOR
1914 else if (!_tcsnicmp(ptr, _T("/T:"), 3))
1915 {
1916 /* Process /T (color) argument; overwrite any previous settings */
1917 wDefColor = (WORD)_tcstoul(&ptr[3], &ptr, 16);
1918 }
1919 #endif
1920 else if (option == _T('U'))
1921 {
1922 OutputStreamMode = UTF16Text;
1923 }
1924 else if (option == _T('V'))
1925 {
1926 // FIXME: Check validity of the parameter given to V !
1927 bDelayedExpansion = _tcsnicmp(&ptr[2], _T(":OFF"), 4);
1928 }
1929 else if (option == _T('E'))
1930 {
1931 // FIXME: Check validity of the parameter given to E !
1932 bEnableExtensions = _tcsnicmp(&ptr[2], _T(":OFF"), 4);
1933 }
1934 else if (option == _T('X'))
1935 {
1936 /* '/X' is identical to '/E:ON' */
1937 bEnableExtensions = TRUE;
1938 }
1939 else if (option == _T('Y'))
1940 {
1941 /* '/Y' is identical to '/E:OFF' */
1942 bEnableExtensions = FALSE;
1943 }
1944 }
1945 }
1946
1947 #ifdef INCLUDE_CMD_COLOR
1948 if (wDefColor == 0)
1949 {
1950 /*
1951 * If we still do not have the console colour attribute set,
1952 * retrieve the default one.
1953 */
1954 ConGetDefaultAttributes(&wDefColor);
1955 }
1956
1957 if (wDefColor != 0)
1958 ConSetScreenColor(ConStreamGetOSHandle(StdOut), wDefColor, TRUE);
1959 #endif
1960
1961 /* Reset the output Standard Streams translation modes and codepage caches */
1962 // ConStreamSetMode(StdIn , OutputStreamMode, InputCodePage );
1963 ConStreamSetMode(StdOut, OutputStreamMode, OutputCodePage);
1964 ConStreamSetMode(StdErr, OutputStreamMode, OutputCodePage);
1965
1966 if (!*ptr)
1967 {
1968 /* If neither /C or /K was given, display a simple version string */
1969 ConOutChar(_T('\n'));
1970 ConOutResPrintf(STRING_REACTOS_VERSION,
1971 _T(KERNEL_VERSION_STR),
1972 _T(KERNEL_VERSION_BUILD_STR));
1973 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR) _T(" ReactOS Team.\n"));
1974 }
1975
1976 if (AutoRun)
1977 {
1978 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE);
1979 ExecuteAutoRunFile(HKEY_CURRENT_USER);
1980 }
1981
1982 if (*ptr)
1983 {
1984 /* Do the /C or /K command */
1985 GetCmdLineCommand(commandline, &ptr[2], AlwaysStrip);
1986 bWaitForCommand = TRUE;
1987 /* nExitCode = */ ParseCommandLine(commandline);
1988 bWaitForCommand = FALSE;
1989 if (option != _T('K'))
1990 {
1991 // nErrorLevel = nExitCode;
1992 bExit = TRUE;
1993 }
1994 }
1995 }
1996
1997
1998 static VOID Cleanup(VOID)
1999 {
2000 /* Run cmdexit.bat */
2001 if (IsExistingFile(_T("cmdexit.bat")))
2002 {
2003 ConErrResPuts(STRING_CMD_ERROR5);
2004 ParseCommandLine(_T("cmdexit.bat"));
2005 }
2006 else if (IsExistingFile(_T("\\cmdexit.bat")))
2007 {
2008 ConErrResPuts(STRING_CMD_ERROR5);
2009 ParseCommandLine(_T("\\cmdexit.bat"));
2010 }
2011
2012 #ifdef FEATURE_DIRECTORY_STACK
2013 /* Destroy directory stack */
2014 DestroyDirectoryStack();
2015 #endif
2016
2017 #ifdef FEATURE_HISTORY
2018 CleanHistory();
2019 #endif
2020
2021 /* Free GetEnvVar's buffer */
2022 GetEnvVar(NULL);
2023
2024 /* Remove ctrl break handler */
2025 RemoveBreakHandler();
2026
2027 /* Restore the default console mode */
2028 SetConsoleMode(ConStreamGetOSHandle(StdIn),
2029 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
2030 SetConsoleMode(ConStreamGetOSHandle(StdOut),
2031 ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2032
2033 DeleteCriticalSection(&ChildProcessRunningLock);
2034 }
2035
2036 /*
2037 * main function
2038 */
2039 int _tmain(int argc, const TCHAR *argv[])
2040 {
2041 TCHAR startPath[MAX_PATH];
2042
2043 InitializeCriticalSection(&ChildProcessRunningLock);
2044 lpOriginalEnvironment = DuplicateEnvironment();
2045
2046 GetCurrentDirectory(ARRAYSIZE(startPath), startPath);
2047 _tchdir(startPath);
2048
2049 SetFileApisToOEM();
2050 InputCodePage = GetConsoleCP();
2051 OutputCodePage = GetConsoleOutputCP();
2052
2053 /* Initialize the Console Standard Streams */
2054 ConStreamInit(StdIn , GetStdHandle(STD_INPUT_HANDLE) , /*OutputStreamMode*/ AnsiText, InputCodePage);
2055 ConStreamInit(StdOut, GetStdHandle(STD_OUTPUT_HANDLE), OutputStreamMode, OutputCodePage);
2056 ConStreamInit(StdErr, GetStdHandle(STD_ERROR_HANDLE) , OutputStreamMode, OutputCodePage);
2057
2058 CMD_ModuleHandle = GetModuleHandle(NULL);
2059
2060 /* Perform general initialization, parse switches on command-line */
2061 Initialize();
2062
2063 /* Call prompt routine */
2064 ProcessInput();
2065
2066 /* Do the cleanup */
2067 Cleanup();
2068
2069 cmd_free(lpOriginalEnvironment);
2070
2071 cmd_exit(nErrorLevel);
2072 return nErrorLevel;
2073 }
2074
2075 /* EOF */