several changes to make cmd compile and link again
[reactos.git] / rosapps / 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 <ekohl@abo.rhein-zeitung.de>)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
90 *
91 * 13-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
94 *
95 * 07-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
96 * Added help text ("cmd /?").
97 *
98 * 25-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
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 <ekohl@abo.rhein-zeitung.de>)
105 * Replaced spawnl() by CreateProcess().
106 */
107
108 #include "config.h"
109
110 #include <windows.h>
111 #include <tchar.h>
112 #include <string.h>
113 #include <stdlib.h>
114 #include <ctype.h>
115 #include <stdio.h>
116
117 #include "cmd.h"
118 #include "batch.h"
119
120
121 #define CMDLINE_LENGTH 512
122
123
124 BOOL bExit = FALSE; /* indicates EXIT was typed */
125 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
126 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
127 BOOL bIgnoreEcho = FALSE; /* Ignore 'newline' before 'cls' */
128 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
129 OSVERSIONINFO osvi;
130 HANDLE hIn;
131 HANDLE hOut;
132
133 #ifdef INCLUDE_CMD_COLOR
134 WORD wColor = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN; /* current color */
135 WORD wDefColor = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN; /* default color */
136 #endif
137
138
139 extern COMMAND cmds[]; /* The internal command table */
140
141
142 /*
143 * is character a delimeter when used on first word?
144 *
145 */
146
147 static BOOL IsDelimiter (TCHAR c)
148 {
149 return (c == _T('/') || c == _T('=') || c == _T('\0') || _istspace (c));
150 }
151
152
153 /*
154 * This command (in first) was not found in the command table
155 *
156 * first - first word on command line
157 * rest - rest of command line
158 */
159
160 static VOID
161 Execute (LPTSTR first, LPTSTR rest)
162 {
163 TCHAR szFullName[MAX_PATH];
164
165 /* check for a drive change */
166 if (!_tcscmp (first + 1, _T(":")) && _istalpha (*first))
167 {
168 TCHAR szPath[MAX_PATH];
169
170 _tcscpy (szPath, _T("A:"));
171 szPath[0] = _totupper (*first);
172 SetCurrentDirectory (szPath);
173 GetCurrentDirectory (MAX_PATH, szPath);
174 if (szPath[0] != (TCHAR)_totupper (*first))
175 ConErrPuts (INVALIDDRIVE);
176
177 return;
178 }
179
180 /* get the PATH environment variable and parse it */
181 /* search the PATH environment variable for the binary */
182 if (!SearchForExecutable (first, szFullName))
183 {
184 error_bad_command ();
185 return;
186 }
187
188 /* check if this is a .BAT or .CMD file */
189 if (!_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".bat")) ||
190 !_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".cmd")))
191 {
192 #ifdef _DEBUG
193 DebugPrintf ("[BATCH: %s %s]\n", szFullName, rest);
194 #endif
195 Batch (szFullName, first, rest);
196 }
197 else
198 {
199 /* exec the program */
200 TCHAR szFullCmdLine [1024];
201 PROCESS_INFORMATION prci;
202 STARTUPINFO stui;
203 // DWORD dwError = 0;
204
205 #ifdef _DEBUG
206 DebugPrintf ("[EXEC: %s %s]\n", szFullName, rest);
207 #endif
208 /* build command line for CreateProcess() */
209 _tcscpy (szFullCmdLine, szFullName);
210 _tcscat (szFullCmdLine, _T(" "));
211 _tcscat (szFullCmdLine, rest);
212
213 /* fill startup info */
214 memset (&stui, 0, sizeof (STARTUPINFO));
215 stui.cb = sizeof (STARTUPINFO);
216 stui.dwFlags = STARTF_USESHOWWINDOW;
217 stui.wShowWindow = SW_SHOWDEFAULT;
218
219 if (CreateProcess (NULL, szFullCmdLine, NULL, NULL, FALSE,
220 0, NULL, NULL, &stui, &prci))
221 {
222 DWORD dwExitCode;
223 WaitForSingleObject (prci.hProcess, INFINITE);
224 GetExitCodeProcess (prci.hProcess, &dwExitCode);
225 nErrorLevel = (INT)dwExitCode;
226 CloseHandle (prci.hThread);
227 CloseHandle (prci.hProcess);
228 }
229 else
230 {
231 ErrorMessage (GetLastError (),
232 "Error executing CreateProcess()!!\n");
233 }
234 }
235 }
236
237
238 /*
239 * look through the internal commands and determine whether or not this
240 * command is one of them. If it is, call the command. If not, call
241 * execute to run it as an external program.
242 *
243 * line - the command line of the program to run
244 *
245 */
246
247 static VOID
248 DoCommand (LPTSTR line)
249 {
250 TCHAR com[MAX_PATH]; /* the first word in the command */
251 LPTSTR cp = com;
252 LPTSTR cstart;
253 LPTSTR rest = line; /* pointer to the rest of the command line */
254 INT cl;
255 LPCOMMAND cmdptr;
256
257 /* Skip over initial white space */
258 while (isspace (*rest))
259 rest++;
260
261 cstart = rest;
262
263 /* Anything to do ? */
264 if (*rest)
265 {
266 /* Copy over 1st word as lower case */
267 while (!IsDelimiter (*rest))
268 *cp++ = _totlower (*rest++);
269
270 /* Terminate first word */
271 *cp = _T('\0');
272
273 /* Skip over whitespace to rest of line */
274 while (_istspace (*rest))
275 rest++;
276
277 /* Scan internal command table */
278 for (cmdptr = cmds;; cmdptr++)
279 {
280 /* If end of table execute ext cmd */
281 if (cmdptr->name == NULL)
282 {
283 Execute (com, rest);
284 break;
285 }
286
287 if (!_tcscmp (com, cmdptr->name))
288 {
289 cmdptr->func (com, rest);
290 break;
291 }
292
293 /* The following code handles the case of commands like CD which
294 * are recognised even when the command name and parameter are
295 * not space separated.
296 *
297 * e.g dir..
298 * cd\freda
299 */
300
301 /* Get length of command name */
302 cl = _tcslen (cmdptr->name);
303
304 if ((cmdptr->flags & CMD_SPECIAL) &&
305 (!_tcsncmp (cmdptr->name, com, cl)) &&
306 (_tcschr (_T("\\.-"), *(com + cl))))
307 {
308 /* OK its one of the specials...*/
309
310 /* Terminate first word properly */
311 com[cl] = _T('\0');
312
313 /* Call with new rest */
314 cmdptr->func (com, cstart + cl);
315 break;
316 }
317 }
318 }
319 }
320
321
322 /*
323 * process the command line and execute the appropriate functions
324 * full input/output redirection and piping are supported
325 */
326
327 VOID ParseCommandLine (LPTSTR s)
328 {
329 #ifdef FEATURE_REDIRECTION
330 TCHAR in[CMDLINE_LENGTH] = "";
331 TCHAR out[CMDLINE_LENGTH] = "";
332 TCHAR err[CMDLINE_LENGTH] = "";
333 TCHAR szTempPath[MAX_PATH] = _T(".\\");
334 TCHAR szFileName[2][MAX_PATH] = {"", ""};
335 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
336 LPTSTR t = NULL;
337 INT num = 0;
338 INT nRedirFlags = 0;
339
340 HANDLE hOldConIn;
341 HANDLE hOldConOut;
342 HANDLE hOldConErr;
343 #endif /* FEATURE_REDIRECTION */
344
345 #ifdef _DEBUG
346 DebugPrintf ("ParseCommandLine: (\'%s\')]\n", s);
347 #endif /* _DEBUG */
348
349 #ifdef FEATURE_ALIASES
350 /* expand all aliases */
351 ExpandAlias (s, CMDLINE_LENGTH);
352 #endif /* FEATURE_ALIAS */
353
354 #ifdef FEATURE_REDIRECTION
355 /* find the temp path to store temporary files */
356 GetTempPath (MAX_PATH, szTempPath);
357 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
358 _tcscat (szTempPath, _T("\\"));
359
360 /* get the redirections from the command line */
361 num = GetRedirection (s, in, out, err, &nRedirFlags);
362
363 /* more efficient, but do we really need to do this? */
364 for (t = in; _istspace (*t); t++)
365 ;
366 _tcscpy (in, t);
367
368 for (t = out; _istspace (*t); t++)
369 ;
370 _tcscpy (out, t);
371
372 for (t = err; _istspace (*t); t++)
373 ;
374 _tcscpy (err, t);
375
376 /* Set up the initial conditions ... */
377 /* preserve STDIN, STDOUT and STDERR handles */
378 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
379 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
380 hOldConErr = GetStdHandle (STD_ERROR_HANDLE);
381
382 /* redirect STDIN */
383 if (in[0])
384 {
385 HANDLE hFile;
386
387 hFile = CreateFile (in, GENERIC_READ, 0, NULL, OPEN_EXISTING,
388 FILE_ATTRIBUTE_NORMAL, NULL);
389 if (hFile == INVALID_HANDLE_VALUE)
390 {
391 ConErrPrintf ("Can't redirect input from file %s\n", in);
392 return;
393 }
394
395 if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
396 {
397 ConErrPrintf ("Can't redirect input from file %s\n", in);
398 return;
399 }
400 #ifdef _DEBUG
401 DebugPrintf (_T("Input redirected from: %s\n"), in);
402 #endif
403 }
404
405 /* Now do all but the last pipe command */
406 *szFileName[0] = '\0';
407 hFile[0] = INVALID_HANDLE_VALUE;
408
409 while (num-- > 1)
410 {
411 /* Create unique temporary file name */
412 GetTempFileName (szTempPath, "CMD", 0, szFileName[1]);
413
414 /* Set current stdout to temporary file */
415 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, NULL,
416 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
417 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
418
419 DoCommand (s);
420
421 /* close stdout file */
422 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
423 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
424 {
425 CloseHandle (hFile[1]);
426 hFile[1] = INVALID_HANDLE_VALUE;
427 }
428
429 /* close old stdin file */
430 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
431 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
432 {
433 /* delete old stdin file, if it is a real file */
434 CloseHandle (hFile[0]);
435 hFile[0] = INVALID_HANDLE_VALUE;
436 DeleteFile (szFileName[0]);
437 *szFileName[0] = _T('\0');
438 }
439
440 /* copy stdout file name to stdin file name */
441 _tcscpy (szFileName[0], szFileName[1]);
442 *szFileName[1] = _T('\0');
443
444 /* open new stdin file */
445 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, NULL,
446 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
447 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
448
449 s = s + _tcslen (s) + 1;
450 }
451
452 /* Now set up the end conditions... */
453 /* redirect STDOUT */
454 if (out[0])
455 {
456 /* Final output to here */
457 HANDLE hFile;
458
459 hFile = CreateFile (out, GENERIC_WRITE, 0, NULL,
460 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
461 FILE_ATTRIBUTE_NORMAL, NULL);
462 if (hFile == INVALID_HANDLE_VALUE)
463 {
464 ConErrPrintf ("Can't redirect to file %s\n", out);
465 return;
466 }
467
468 if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
469 {
470 ConErrPrintf ("Can't redirect to file %s\n", out);
471 return;
472 }
473
474 if (nRedirFlags & OUTPUT_APPEND)
475 {
476 LONG lHighPos = 0;
477
478 if (GetFileType (hFile) == FILE_TYPE_DISK)
479 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
480 }
481 #ifdef _DEBUG
482 DebugPrintf (_T("Output redirected to: %s\n"), out);
483 #endif
484 }
485 else if (hOldConOut != INVALID_HANDLE_VALUE)
486 {
487 /* Restore original stdout */
488 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
489 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
490 if (hOldConOut != hOut)
491 CloseHandle (hOut);
492 hOldConOut = INVALID_HANDLE_VALUE;
493 }
494
495 /* redirect STDERR */
496 if (err[0])
497 {
498 /* Final output to here */
499 HANDLE hFile;
500
501 if (!_tcscmp (err, out))
502 {
503 #ifdef _DEBUG
504 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
505 #endif
506 DuplicateHandle (GetCurrentProcess (), GetStdHandle (STD_OUTPUT_HANDLE), GetCurrentProcess (),
507 &hFile, 0, TRUE, DUPLICATE_SAME_ACCESS);
508 }
509 else
510 {
511 hFile =
512 CreateFile (err, GENERIC_WRITE, 0, NULL,
513 (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
514 FILE_ATTRIBUTE_NORMAL, NULL);
515 if (hFile == INVALID_HANDLE_VALUE)
516 {
517 ConErrPrintf ("Can't redirect to file %s\n", err);
518 return;
519 }
520 }
521 if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
522 {
523 ConErrPrintf ("Can't redirect to file %s\n", err);
524 return;
525 }
526
527 if (nRedirFlags & ERROR_APPEND)
528 {
529 LONG lHighPos = 0;
530
531 if (GetFileType (hFile) == FILE_TYPE_DISK)
532 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
533 }
534 #ifdef _DEBUG
535 DebugPrintf (_T("Error redirected to: %s\n"), err);
536 #endif
537 }
538 else if (hOldConErr != INVALID_HANDLE_VALUE)
539 {
540 /* Restore original stderr */
541 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
542 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
543 if (hOldConErr != hErr)
544 CloseHandle (hErr);
545 hOldConErr = INVALID_HANDLE_VALUE;
546 }
547 #endif
548
549 /* process final command */
550 DoCommand (s);
551
552 #ifdef FEATURE_REDIRECTION
553 /* close old stdin file */
554 #if 0 /* buggy implementation */
555 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
556 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
557 (hFile[0] != hOldConIn))
558 {
559 /* delete old stdin file, if it is a real file */
560 CloseHandle (hFile[0]);
561 hFile[0] = INVALID_HANDLE_VALUE;
562 DeleteFile (szFileName[0]);
563 *szFileName[0] = _T('\0');
564 }
565
566 /* Restore original STDIN */
567 if (hOldConIn != INVALID_HANDLE_VALUE)
568 {
569 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
570 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
571 if (hOldConIn != hIn)
572 CloseHandle (hIn);
573 hOldConIn = INVALID_HANDLE_VALUE;
574 }
575 else
576 {
577 #ifdef _DEBUG
578 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out);
579 #endif
580 }
581 #endif /* buggy implementation */
582
583
584 if (hOldConIn != INVALID_HANDLE_VALUE)
585 {
586 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
587 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
588 if (hIn == INVALID_HANDLE_VALUE)
589 {
590 #ifdef _DEBUG
591 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
592 #endif
593 }
594 else
595 {
596 if (GetFileType (hIn) == FILE_TYPE_DISK)
597 {
598 if (hFile[0] == hIn)
599 {
600 CloseHandle (hFile[0]);
601 hFile[0] = INVALID_HANDLE_VALUE;
602 DeleteFile (szFileName[0]);
603 *szFileName[0] = _T('\0');
604 }
605 else
606 {
607 #ifdef _DEBUG
608 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
609 #endif
610
611 }
612 }
613 }
614 }
615
616
617 /* Restore original STDOUT */
618 if (hOldConOut != INVALID_HANDLE_VALUE)
619 {
620 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
621 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
622 if (hOldConOut != hOut)
623 CloseHandle (hOut);
624 hOldConOut = INVALID_HANDLE_VALUE;
625 }
626
627 /* Restore original STDERR */
628 if (hOldConErr != INVALID_HANDLE_VALUE)
629 {
630 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
631 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
632 if (hOldConErr != hErr)
633 CloseHandle (hErr);
634 hOldConErr = INVALID_HANDLE_VALUE;
635 }
636 #endif /* FEATURE_REDIRECTION */
637 }
638
639
640 /*
641 * do the prompt/input/process loop
642 *
643 */
644
645 static INT
646 ProcessInput (BOOL bFlag)
647 {
648 TCHAR commandline[CMDLINE_LENGTH];
649 TCHAR readline[CMDLINE_LENGTH];
650 LPTSTR tp;
651 LPTSTR ip;
652 LPTSTR cp;
653
654 /* JPP 19980807 - changed name so not to conflict with echo global */
655 BOOL bEchoThisLine;
656
657 do
658 {
659 /* if no batch input then... */
660 if (!(ip = ReadBatchLine (&bEchoThisLine)))
661 {
662 if (bFlag)
663 return 0;
664
665 ReadCommand (readline, CMDLINE_LENGTH);
666 ip = readline;
667 bEchoThisLine = FALSE;
668 }
669
670 cp = commandline;
671 while (*ip)
672 {
673 if (*ip == _T('%'))
674 {
675 switch (*++ip)
676 {
677 case _T('%'):
678 *cp++ = *ip++;
679 break;
680
681 case _T('0'):
682 case _T('1'):
683 case _T('2'):
684 case _T('3'):
685 case _T('4'):
686 case _T('5'):
687 case _T('6'):
688 case _T('7'):
689 case _T('8'):
690 case _T('9'):
691 if ((tp = FindArg (*ip - _T('0'))))
692 {
693 cp = stpcpy (cp, tp);
694 ip++;
695 }
696 else
697 *cp++ = _T('%');
698 break;
699
700 case _T('?'):
701 cp += _stprintf (cp, _T("%u"), nErrorLevel);
702 ip++;
703 break;
704
705 default:
706 if ((tp = _tcschr (ip, _T('%'))))
707 {
708 char evar[512];
709 *tp = _T('\0');
710
711 /* FIXME: This is just a quick hack!! */
712 /* Do a proper memory allocation!! */
713 if (GetEnvironmentVariable (ip, evar, 512))
714 cp = stpcpy (cp, evar);
715
716 ip = tp + 1;
717 }
718 break;
719 }
720 continue;
721 }
722
723 if (_istcntrl (*ip))
724 *ip = _T(' ');
725 *cp++ = *ip++;
726 }
727
728 *cp = _T('\0');
729
730 /* strip trailing spaces */
731 while ((--cp >= commandline) && _istspace (*cp))
732 ;
733
734 *(cp + 1) = _T('\0');
735
736 /* JPP 19980807 */
737 /* Echo batch file line */
738 if (bEchoThisLine)
739 {
740 PrintPrompt ();
741 ConOutPuts (commandline);
742 }
743
744 if (*commandline)
745 {
746 ParseCommandLine (commandline);
747 if (bEcho && !bIgnoreEcho)
748 ConOutChar ('\n');
749 bIgnoreEcho = FALSE;
750 }
751 }
752 while (!bCanExit || !bExit);
753
754 return 0;
755 }
756
757
758 /*
759 * control-break handler.
760 */
761 BOOL BreakHandler (DWORD dwCtrlType)
762 {
763 if ((dwCtrlType == CTRL_C_EVENT) ||
764 (dwCtrlType == CTRL_BREAK_EVENT))
765 {
766 bCtrlBreak = TRUE; /* indicate the break condition */
767 return TRUE;
768 }
769 return FALSE;
770 }
771
772
773 /*
774 * show commands and options that are available.
775 *
776 */
777 static VOID
778 ShowCommands (VOID)
779 {
780 LPCOMMAND cmdptr;
781 INT y;
782
783 ConOutPrintf (_T("\nInternal commands available:\n"));
784 y = 0;
785 cmdptr = cmds;
786 while (cmdptr->name)
787 {
788 if (++y == 8)
789 {
790 ConOutPuts (cmdptr->name);
791 y = 0;
792 }
793 else
794 ConOutPrintf (_T("%-10s"), cmdptr->name);
795
796 cmdptr++;
797 }
798
799 if (y != 0)
800 ConOutChar ('\n');
801
802 /* print feature list */
803 ConOutPuts ("\nFeatures available:");
804 #ifdef FEATURE_ALIASES
805 ConOutPuts (" [aliases]");
806 #endif
807 #ifdef FEATURE_HISTORY
808 ConOutPuts (" [history]");
809 #endif
810 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
811 ConOutPuts (" [unix filename completion]");
812 #endif
813 #ifdef FEATURE_DIRECTORY_STACK
814 ConOutPuts (" [directory stack]");
815 #endif
816 #ifdef FEATURE_REDIRECTION
817 ConOutPuts (" [redirections and piping]");
818 #endif
819 ConOutChar ('\n');
820 }
821
822
823 /*
824 * set up global initializations and process parameters
825 *
826 * argc - number of parameters to command.com
827 * argv - command-line parameters
828 *
829 */
830 static VOID Initialize (int argc, char *argv[])
831 {
832 INT i;
833
834 /* Added by Rob Lake 06/16/98. This enables the command.com
835 * to run the autoexec.bat at startup */
836
837 #ifdef _DEBUG
838 INT x;
839
840 DebugPrintf ("[command args:\n");
841 for (x = 0; x < argc; x++)
842 {
843 DebugPrintf ("%d. %s\n", x, argv[x]);
844 }
845 DebugPrintf ("]\n");
846 #endif
847
848 /* get version information */
849 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
850 GetVersionEx (&osvi);
851
852 InitLocale ();
853
854 /* get default input and output console handles */
855 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
856 hIn = GetStdHandle (STD_INPUT_HANDLE);
857
858 #ifdef INCLUDE_CMD_CHDIR
859 InitLastPath ();
860 #endif
861
862 if (argc >= 2)
863 {
864 if (!_tcsncmp (argv[1], _T("/?"), 2))
865 {
866 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter\n\n"
867 "CMD [/P][/C]...\n\n"
868 " /P ...\n"
869 " /C ..."));
870 ExitProcess (0);
871 }
872 else
873 {
874 for (i = 1; i < argc; i++)
875 {
876 if (!_tcsicmp (argv[i], _T("/p")))
877 {
878 if (!IsValidFileName (_T("\\autoexec.bat")))
879 {
880 #ifdef INCLUDE_CMD_DATE
881 cmd_date ("", "");
882 #endif
883 #ifdef INCLUDE_CMD_TIME
884 cmd_time ("", "");
885 #endif
886 }
887 else
888 ParseCommandLine ("\\autoexec.bat");
889 bCanExit = FALSE;
890 }
891 else if (!_tcsicmp (argv[i], _T("/c")))
892 {
893 /* This just runs a program and exits, RL: 06/16,21/98 */
894 char commandline[CMDLINE_LENGTH];
895 ++i;
896 strcpy(commandline, argv[i]);
897 while (argv[++i])
898 {
899 strcat(commandline, " ");
900 strcat(commandline, argv[i]);
901 }
902
903 ParseCommandLine(commandline);
904
905 /* HBP_003 { Fix return value when /C used }*/
906 ExitProcess (ProcessInput (TRUE));
907 }
908
909 #ifdef INCLUDE_CMD_COLOR
910 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
911 {
912 /* process /t (color) argument */
913 wDefColor = (WORD)strtoul (&argv[i][3], NULL, 16);
914 wColor = wDefColor;
915 }
916 #endif
917 }
918 }
919 }
920
921 #ifdef FEATURE_DIR_STACK
922 /* initialize directory stack */
923 InitDirectoryStack ();
924 #endif
925
926 #ifdef INCLUDE_CMD_COLOR
927 /* set default colors */
928 SetScreenColor (wColor);
929 #endif
930
931 ShortVersion ();
932 ShowCommands ();
933
934 /* Set COMSPEC environment variable */
935 #ifndef __REACTOS__
936 if (argv)
937 SetEnvironmentVariable (_T("COMSPEC"), argv[0]);
938 #endif
939
940 /* add ctrl handler */
941 #if 0
942 SetConsoleCtrlHandler (NULL, TRUE);
943 #endif
944 }
945
946
947 static VOID Cleanup (VOID)
948 {
949
950 #ifdef FEATURE_DIECTORY_STACK
951 /* destroy directory stack */
952 DestroyDirectoryStack ();
953 #endif
954
955 #ifdef INCLUDE_CMD_CHDIR
956 FreeLastPath ();
957 #endif
958
959 /* remove ctrl handler */
960 #if 0
961 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)&BreakHandler, FALSE);
962 #endif
963 }
964
965
966 /*
967 * main function
968 */
969 int main (int argc, char *argv[])
970 {
971 INT nExitCode;
972
973 AllocConsole ();
974 #ifndef __REACTOS__
975 SetFileApisToOEM ();
976 #endif
977
978 #ifdef __REACTOS__
979 SetCurrentDirectory (_T("C:\\"));
980 #endif
981
982 /* check switches on command-line */
983 Initialize (argc, argv);
984
985 /* call prompt routine */
986 nExitCode = ProcessInput (FALSE);
987
988 /* do the cleanup */
989 Cleanup ();
990 FreeConsole ();
991
992 return nExitCode;
993 // return 0;
994 }