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