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