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