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