- The separator (slash or back slash), exepostfix and exeprefix are initialized from...
[reactos.git] / reactos / subsys / system / 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 * 22-Oct-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
108 * Added break handler.
109 *
110 * 15-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
111 * Fixed current directory
112 *
113 * 28-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
114 * Restore window title after program/batch execution
115 *
116 * 03-Feb-2001 (Eric Kohl <ekohl@rz-online.de>)
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 (Hartmut Birr)
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 <malloc.h>
146 #include "resource.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; /* Ignore 'newline' before 'cls' */
160 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
161 BOOL bChildProcessRunning = FALSE;
162 DWORD dwChildProcessId = 0;
163 OSVERSIONINFO osvi;
164 HANDLE hIn;
165 HANDLE hOut;
166 HANDLE hConsole;
167 HANDLE CMD_ModuleHandle;
168 HMODULE NtDllModule;
169
170 static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
171 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
172
173 #ifdef INCLUDE_CMD_COLOR
174 WORD wColor; /* current color */
175 WORD wDefColor; /* default color */
176 #endif
177
178 /*
179 * is character a delimeter when used on first word?
180 *
181 */
182
183 static BOOL IsDelimiter (TCHAR c)
184 {
185 return (c == _T('/') || c == _T('=') || c == _T('\0') || _istspace (c));
186 }
187
188 /*
189 * Is a process a console process?
190 */
191 static BOOL IsConsoleProcess(HANDLE Process)
192 {
193 NTSTATUS Status;
194 PROCESS_BASIC_INFORMATION Info;
195 PEB ProcessPeb;
196 ULONG BytesRead;
197
198 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
199 {
200 return TRUE;
201 }
202
203 Status = NtQueryInformationProcessPtr (
204 Process, ProcessBasicInformation,
205 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
206 if (! NT_SUCCESS(Status))
207 {
208 #ifdef _DEBUG
209 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status);
210 #endif
211 return TRUE;
212 }
213 Status = NtReadVirtualMemoryPtr (
214 Process, Info.PebBaseAddress, &ProcessPeb,
215 sizeof(PEB), &BytesRead);
216 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
217 {
218 #ifdef _DEBUG
219 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status, BytesRead);
220 #endif
221 return TRUE;
222 }
223
224 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubSystem;
225 }
226
227
228
229 #ifdef _UNICODE
230 #define SHELLEXECUTETEXT "ShellExecuteW"
231 #else
232 #define SHELLEXECUTETEXT "ShellExecuteA"
233 #endif
234
235 typedef HINSTANCE (WINAPI *MYEX)(
236 HWND hwnd,
237 LPCTSTR lpOperation,
238 LPCTSTR lpFile,
239 LPCTSTR lpParameters,
240 LPCTSTR lpDirectory,
241 INT nShowCmd
242 );
243
244
245
246 static BOOL RunFile(LPTSTR filename)
247 {
248 HMODULE hShell32;
249 MYEX hShExt;
250 HINSTANCE ret;
251
252 #ifdef _DEBUG
253 DebugPrintf (_T("RunFile(%s)\n"), filename);
254 #endif
255 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
256 if (!hShell32)
257 {
258 #ifdef _DEBUG
259 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
260 #endif
261 return FALSE;
262 }
263
264 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
265 if (!hShExt)
266 {
267 #ifdef _DEBUG
268 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
269 #endif
270 FreeLibrary(hShell32);
271 return FALSE;
272 }
273
274 #ifdef _DEBUG
275 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt);
276 #endif
277
278 ret = (hShExt)(NULL, _T("open"), filename, NULL, NULL, SW_SHOWNORMAL);
279
280 #ifdef _DEBUG
281 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD)ret);
282 #endif
283
284 FreeLibrary(hShell32);
285 return (((DWORD)ret) > 32);
286 }
287
288
289
290 /*
291 * This command (in first) was not found in the command table
292 *
293 * Full - whole command line
294 * First - first word on command line
295 * Rest - rest of command line
296 */
297
298 static VOID
299 Execute (LPTSTR Full, LPTSTR First, LPTSTR Rest)
300 {
301 TCHAR *szFullName=NULL;
302 TCHAR *first = NULL;
303 TCHAR *rest = NULL;
304 TCHAR *full = NULL;
305 TCHAR *dot = NULL;
306 TCHAR szWindowTitle[MAX_PATH];
307 DWORD dwExitCode = 0;
308
309 #ifdef _DEBUG
310 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first, rest);
311 #endif
312
313 /* we need biger buffer that First, Rest, Full are already
314 need rewrite some code to use realloc when it need instead
315 of add 512bytes extra */
316
317 first = malloc ( (_tcslen(First) + 512) * sizeof(TCHAR));
318 if (first == NULL)
319 {
320 error_out_of_memory();
321 return ;
322 }
323
324 rest = malloc ( (_tcslen(Rest) + 512) * sizeof(TCHAR));
325 if (rest == NULL)
326 {
327 free (first);
328 error_out_of_memory();
329 return ;
330 }
331
332 full = malloc ( (_tcslen(Full) + 512) * sizeof(TCHAR));
333 if (full == NULL)
334 {
335 free (first);
336 free (rest);
337 error_out_of_memory();
338 return ;
339 }
340
341 szFullName = malloc ( (_tcslen(Full) + 512) * sizeof(TCHAR));
342 if (full == NULL)
343 {
344 free (first);
345 free (rest);
346 free (full);
347 error_out_of_memory();
348 return ;
349 }
350
351
352 /* Though it was already parsed once, we have a different set of rules
353 for parsing before we pass to CreateProccess */
354 if(!_tcschr(Full,_T('\"')))
355 {
356 _tcscpy(first,First);
357 _tcscpy(rest,Rest);
358 _tcscpy(full,Full);
359 }
360 else
361 {
362 UINT i = 0;
363 BOOL bInside = FALSE;
364 rest[0] = _T('\0');
365 full[0] = _T('\0');
366 first[0] = _T('\0');
367 _tcscpy(first,Full);
368 /* find the end of the command and start of the args */
369 for(i = 0; i < _tcslen(first); i++)
370 {
371 if(!_tcsncmp(&first[i], _T("\""), 1))
372 bInside = !bInside;
373 if(!_tcsncmp(&first[i], _T(" "), 1) && !bInside)
374 {
375 _tcscpy(rest,&first[i]);
376 first[i] = _T('\0');
377 break;
378 }
379
380 }
381 i = 0;
382 /* remove any slashes */
383 while(i < _tcslen(first))
384 {
385 if(first[i] == _T('\"'))
386 memmove(&first[i],&first[i + 1], _tcslen(&first[i]) * sizeof(TCHAR));
387 else
388 i++;
389 }
390 /* Drop quotes around it just in case there is a space */
391 _tcscpy(full,_T("\""));
392 _tcscat(full,first);
393 _tcscat(full,_T("\" "));
394 _tcscat(full,rest);
395 }
396
397 /* check for a drive change */
398 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
399 {
400 BOOL working = TRUE;
401 if (!SetCurrentDirectory(first))
402 /* Guess they changed disc or something, handle that gracefully and get to root */
403 {
404 TCHAR str[4];
405 str[0]=first[0];
406 str[1]=_T(':');
407 str[2]=_T('\\');
408 str[3]=0;
409 working = SetCurrentDirectory(str);
410 }
411
412 if (!working) ConErrResPuts (STRING_FREE_ERROR1);
413
414 free (first);
415 free (rest);
416 free (full);
417 free (szFullName);
418
419 return;
420 }
421
422 /* get the PATH environment variable and parse it */
423 /* search the PATH environment variable for the binary */
424 if (!SearchForExecutable (first, szFullName))
425 {
426 error_bad_command ();
427 free (first);
428 free (rest);
429 free (full);
430 free (szFullName);
431 return;
432
433 }
434
435 GetConsoleTitle (szWindowTitle, MAX_PATH);
436
437 /* check if this is a .BAT or .CMD file */
438 dot = _tcsrchr (szFullName, _T('.'));
439 if (dot && (!_tcsicmp (dot, _T(".bat")) || !_tcsicmp (dot, _T(".cmd"))))
440 {
441 #ifdef _DEBUG
442 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName, rest);
443 #endif
444 Batch (szFullName, first, rest);
445 }
446 else
447 {
448 /* exec the program */
449 PROCESS_INFORMATION prci;
450 STARTUPINFO stui;
451
452 #ifdef _DEBUG
453 DebugPrintf (_T("[EXEC: %s %s]\n"), full, rest);
454 #endif
455 /* build command line for CreateProcess() */
456
457 /* fill startup info */
458 memset (&stui, 0, sizeof (STARTUPINFO));
459 stui.cb = sizeof (STARTUPINFO);
460 stui.dwFlags = STARTF_USESHOWWINDOW;
461 stui.wShowWindow = SW_SHOWDEFAULT;
462
463 // return console to standard mode
464 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE),
465 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
466
467 if (CreateProcess (szFullName,
468 full,
469 NULL,
470 NULL,
471 TRUE,
472 CREATE_NEW_PROCESS_GROUP,
473 NULL,
474 NULL,
475 &stui,
476 &prci))
477 {
478 if (IsConsoleProcess(prci.hProcess))
479 {
480 /* FIXME: Protect this with critical section */
481 bChildProcessRunning = TRUE;
482 dwChildProcessId = prci.dwProcessId;
483
484 WaitForSingleObject (prci.hProcess, INFINITE);
485
486 /* FIXME: Protect this with critical section */
487 bChildProcessRunning = FALSE;
488
489 GetExitCodeProcess (prci.hProcess, &dwExitCode);
490 nErrorLevel = (INT)dwExitCode;
491 }
492 CloseHandle (prci.hThread);
493 CloseHandle (prci.hProcess);
494 }
495 else
496 {
497 #ifdef _DEBUG
498 DebugPrintf (_T("[ShellExecute: %s]\n"), full);
499 #endif
500 // See if we can run this with ShellExecute() ie myfile.xls
501 if (!RunFile(full))
502 {
503 #ifdef _DEBUG
504 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full);
505 #endif
506 error_bad_command ();
507 }
508 }
509 // restore console mode
510 SetConsoleMode (
511 GetStdHandle( STD_INPUT_HANDLE ),
512 ENABLE_PROCESSED_INPUT );
513 }
514
515 /* Get code page if it has been change */
516 InputCodePage= GetConsoleCP();
517 OutputCodePage = GetConsoleOutputCP();
518 SetConsoleTitle (szWindowTitle);
519
520 free(first);
521 free(rest);
522 free(full);
523 free (szFullName);
524 }
525
526
527 /*
528 * look through the internal commands and determine whether or not this
529 * command is one of them. If it is, call the command. If not, call
530 * execute to run it as an external program.
531 *
532 * line - the command line of the program to run
533 *
534 */
535
536 static VOID
537 DoCommand (LPTSTR line)
538 {
539 TCHAR *com = NULL; /* the first word in the command */
540 TCHAR *cp = NULL;
541 LPTSTR cstart;
542 LPTSTR rest; /* pointer to the rest of the command line */
543 INT cl;
544 LPCOMMAND cmdptr;
545
546 #ifdef _DEBUG
547 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line);
548 #endif /* DEBUG */
549
550 com = malloc( (_tcslen(line) +512)*sizeof(TCHAR) );
551 if (com == NULL)
552 {
553 error_out_of_memory();
554 return;
555 }
556
557 cp = com;
558 /* Skip over initial white space */
559 while (_istspace (*line))
560 line++;
561 rest = line;
562
563 cstart = rest;
564
565 /* Anything to do ? */
566 if (*rest)
567 {
568 if (*rest == _T('"'))
569 {
570 /* treat quoted words specially */
571
572 rest++;
573
574 while(*rest != _T('\0') && *rest != _T('"'))
575 *cp++ = _totlower (*rest++);
576 if (*rest == _T('"'))
577 rest++;
578 }
579 else
580 {
581 while (!IsDelimiter (*rest))
582 *cp++ = _totlower (*rest++);
583 }
584
585
586 /* Terminate first word */
587 *cp = _T('\0');
588
589 /* Do not limit commands to MAX_PATH */
590 /*
591 if(_tcslen(com) > MAX_PATH)
592 {
593 error_bad_command();
594 free(com);
595 return;
596 }
597 */
598
599 /* Skip over whitespace to rest of line */
600 while (_istspace (*rest))
601 rest++;
602
603 /* Scan internal command table */
604 for (cmdptr = cmds;; cmdptr++)
605 {
606 /* If end of table execute ext cmd */
607 if (cmdptr->name == NULL)
608 {
609 Execute (line, com, rest);
610 break;
611 }
612
613 if (!_tcscmp (com, cmdptr->name))
614 {
615 cmdptr->func (com, rest);
616 break;
617 }
618
619 /* The following code handles the case of commands like CD which
620 * are recognised even when the command name and parameter are
621 * not space separated.
622 *
623 * e.g dir..
624 * cd\freda
625 */
626
627 /* Get length of command name */
628 cl = _tcslen (cmdptr->name);
629
630 if ((cmdptr->flags & CMD_SPECIAL) &&
631 (!_tcsncmp (cmdptr->name, com, cl)) &&
632 (_tcschr (_T("\\.-"), *(com + cl))))
633 {
634 /* OK its one of the specials...*/
635
636 /* Terminate first word properly */
637 com[cl] = _T('\0');
638
639 /* Call with new rest */
640 cmdptr->func (com, cstart + cl);
641 break;
642 }
643 }
644 }
645 free(com);
646 }
647
648
649 /*
650 * process the command line and execute the appropriate functions
651 * full input/output redirection and piping are supported
652 */
653
654 VOID ParseCommandLine (LPTSTR cmd)
655 {
656 TCHAR szMsg[RC_STRING_MAX_SIZE];
657 TCHAR cmdline[CMDLINE_LENGTH];
658 LPTSTR s;
659 #ifdef FEATURE_REDIRECTION
660 TCHAR in[CMDLINE_LENGTH] = _T("");
661 TCHAR out[CMDLINE_LENGTH] = _T("");
662 TCHAR err[CMDLINE_LENGTH] = _T("");
663 TCHAR szTempPath[MAX_PATH] = _T(".\\");
664 TCHAR szFileName[2][MAX_PATH] = {_T(""), _T("")};
665 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
666 LPTSTR t = NULL;
667 INT num = 0;
668 INT nRedirFlags = 0;
669 INT Length;
670 UINT Attributes;
671 BOOL bNewBatch = TRUE;
672 HANDLE hOldConIn;
673 HANDLE hOldConOut;
674 HANDLE hOldConErr;
675 #endif /* FEATURE_REDIRECTION */
676
677 _tcscpy (cmdline, cmd);
678 s = &cmdline[0];
679
680 #ifdef _DEBUG
681 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s);
682 #endif /* DEBUG */
683
684 #ifdef FEATURE_ALIASES
685 /* expand all aliases */
686 ExpandAlias (s, CMDLINE_LENGTH);
687 #endif /* FEATURE_ALIAS */
688
689 #ifdef FEATURE_REDIRECTION
690 /* find the temp path to store temporary files */
691 Length = GetTempPath (MAX_PATH, szTempPath);
692 if (Length > 0 && Length < MAX_PATH)
693 {
694 Attributes = GetFileAttributes(szTempPath);
695 if (Attributes == 0xffffffff ||
696 !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
697 {
698 Length = 0;
699 }
700 }
701 if (Length == 0 || Length >= MAX_PATH)
702 {
703 _tcscpy(szTempPath, _T(".\\"));
704 }
705 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
706 _tcscat (szTempPath, _T("\\"));
707
708 /* get the redirections from the command line */
709 num = GetRedirection (s, in, out, err, &nRedirFlags);
710
711 /* more efficient, but do we really need to do this? */
712 for (t = in; _istspace (*t); t++)
713 ;
714 _tcscpy (in, t);
715
716 for (t = out; _istspace (*t); t++)
717 ;
718 _tcscpy (out, t);
719
720 for (t = err; _istspace (*t); t++)
721 ;
722 _tcscpy (err, t);
723
724 if(bc && !_tcslen (in) && _tcslen (bc->In))
725 _tcscpy(in, bc->In);
726 if(bc && !out[0] && _tcslen(bc->Out))
727 {
728 nRedirFlags |= OUTPUT_APPEND;
729 _tcscpy(out, bc->Out);
730 }
731 if(bc && !_tcslen (err) && _tcslen (bc->Err))
732 {
733 nRedirFlags |= ERROR_APPEND;
734 _tcscpy(err, bc->Err);
735 }
736
737
738 /* Set up the initial conditions ... */
739 /* preserve STDIN, STDOUT and STDERR handles */
740 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
741 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
742 hOldConErr = GetStdHandle (STD_ERROR_HANDLE);
743
744 /* redirect STDIN */
745 if (in[0])
746 {
747 HANDLE hFile;
748 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
749
750 /* we need make sure the LastError msg is zero before calling CreateFile */
751 SetLastError(0);
752
753 /* Set up pipe for the standard input handler */
754 hFile = CreateFile (in, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
755 FILE_ATTRIBUTE_NORMAL, NULL);
756 if (hFile == INVALID_HANDLE_VALUE)
757 {
758 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
759 ConErrPrintf(szMsg, in);
760 return;
761 }
762
763 if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
764 {
765 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
766 ConErrPrintf(szMsg, in);
767 return;
768 }
769 #ifdef _DEBUG
770 DebugPrintf (_T("Input redirected from: %s\n"), in);
771 #endif
772 }
773
774 /* Now do all but the last pipe command */
775 *szFileName[0] = _T('\0');
776 hFile[0] = INVALID_HANDLE_VALUE;
777
778 while (num-- > 1)
779 {
780 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
781
782 /* Create unique temporary file name */
783 GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
784
785 /* we need make sure the LastError msg is zero before calling CreateFile */
786 SetLastError(0);
787
788 /* Set current stdout to temporary file */
789 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
790 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
791
792 if (hFile[1] == INVALID_HANDLE_VALUE)
793 {
794 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR2, szMsg, RC_STRING_MAX_SIZE);
795 ConErrPrintf(szMsg);
796 return;
797 }
798
799 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
800
801 DoCommand (s);
802
803 /* close stdout file */
804 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
805 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
806 {
807 CloseHandle (hFile[1]);
808 hFile[1] = INVALID_HANDLE_VALUE;
809 }
810
811 /* close old stdin file */
812 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
813 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
814 {
815 /* delete old stdin file, if it is a real file */
816 CloseHandle (hFile[0]);
817 hFile[0] = INVALID_HANDLE_VALUE;
818 DeleteFile (szFileName[0]);
819 *szFileName[0] = _T('\0');
820 }
821
822 /* copy stdout file name to stdin file name */
823 _tcscpy (szFileName[0], szFileName[1]);
824 *szFileName[1] = _T('\0');
825
826 /* we need make sure the LastError msg is zero before calling CreateFile */
827 SetLastError(0);
828
829 /* open new stdin file */
830 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
831 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
832 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
833
834 s = s + _tcslen (s) + 1;
835 }
836
837 /* Now set up the end conditions... */
838 /* redirect STDOUT */
839 if (out[0])
840 {
841 /* Final output to here */
842 HANDLE hFile;
843 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
844
845 /* we need make sure the LastError msg is zero before calling CreateFile */
846 SetLastError(0);
847
848 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
849 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
850 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
851
852 if (hFile == INVALID_HANDLE_VALUE)
853 {
854 INT size = _tcslen(out)-1;
855
856 if (out[size] != _T(':'))
857 {
858 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
859 ConErrPrintf(szMsg, out);
860 return;
861 }
862
863 out[size]=_T('\0');
864 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
865 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
866 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
867
868 if (hFile == INVALID_HANDLE_VALUE)
869 {
870 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
871 ConErrPrintf(szMsg, out);
872 return;
873 }
874
875 }
876
877 if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
878 {
879 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
880 ConErrPrintf(szMsg, out);
881 return;
882 }
883
884 if (nRedirFlags & OUTPUT_APPEND)
885 {
886 LONG lHighPos = 0;
887
888 if (GetFileType (hFile) == FILE_TYPE_DISK)
889 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
890 }
891 #ifdef _DEBUG
892 DebugPrintf (_T("Output redirected to: %s\n"), out);
893 #endif
894 }
895 else if (hOldConOut != INVALID_HANDLE_VALUE)
896 {
897 /* Restore original stdout */
898 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
899 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
900 if (hOldConOut != hOut)
901 CloseHandle (hOut);
902 hOldConOut = INVALID_HANDLE_VALUE;
903 }
904
905 /* redirect STDERR */
906 if (err[0])
907 {
908 /* Final output to here */
909 HANDLE hFile;
910 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
911
912 if (!_tcscmp (err, out))
913 {
914 #ifdef _DEBUG
915 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
916 #endif
917 DuplicateHandle (GetCurrentProcess (),
918 GetStdHandle (STD_OUTPUT_HANDLE),
919 GetCurrentProcess (),
920 &hFile, 0, TRUE, DUPLICATE_SAME_ACCESS);
921 }
922 else
923 {
924 hFile = CreateFile (err,
925 GENERIC_WRITE,
926 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
927 &sa,
928 (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
929 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
930 NULL);
931 if (hFile == INVALID_HANDLE_VALUE)
932 {
933 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
934 ConErrPrintf(szMsg, err);
935 return;
936 }
937 }
938
939 if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
940 {
941 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
942 ConErrPrintf(szMsg, err);
943 return;
944 }
945
946 if (nRedirFlags & ERROR_APPEND)
947 {
948 LONG lHighPos = 0;
949
950 if (GetFileType (hFile) == FILE_TYPE_DISK)
951 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
952 }
953 #ifdef _DEBUG
954 DebugPrintf (_T("Error redirected to: %s\n"), err);
955 #endif
956 }
957 else if (hOldConErr != INVALID_HANDLE_VALUE)
958 {
959 /* Restore original stderr */
960 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
961 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
962 if (hOldConErr != hErr)
963 CloseHandle (hErr);
964 hOldConErr = INVALID_HANDLE_VALUE;
965 }
966
967 if(bc)
968 bNewBatch = FALSE;
969 #endif
970
971 /* process final command */
972 DoCommand (s);
973
974 #ifdef FEATURE_REDIRECTION
975 if(bNewBatch && bc)
976 AddBatchRedirection(in, out, err);
977 /* close old stdin file */
978 #if 0 /* buggy implementation */
979 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
980 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
981 (hFile[0] != hOldConIn))
982 {
983 /* delete old stdin file, if it is a real file */
984 CloseHandle (hFile[0]);
985 hFile[0] = INVALID_HANDLE_VALUE;
986 DeleteFile (szFileName[0]);
987 *szFileName[0] = _T('\0');
988 }
989
990 /* Restore original STDIN */
991 if (hOldConIn != INVALID_HANDLE_VALUE)
992 {
993 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
994 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
995 if (hOldConIn != hIn)
996 CloseHandle (hIn);
997 hOldConIn = INVALID_HANDLE_VALUE;
998 }
999 else
1000 {
1001 #ifdef _DEBUG
1002 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out);
1003 #endif
1004 }
1005 #endif /* buggy implementation */
1006
1007
1008 if (hOldConIn != INVALID_HANDLE_VALUE)
1009 {
1010 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1011 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
1012 if (hIn == INVALID_HANDLE_VALUE)
1013 {
1014 #ifdef _DEBUG
1015 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
1016 #endif
1017 }
1018 else
1019 {
1020 if (GetFileType (hIn) == FILE_TYPE_DISK)
1021 {
1022 if (hFile[0] == hIn)
1023 {
1024 CloseHandle (hFile[0]);
1025 hFile[0] = INVALID_HANDLE_VALUE;
1026 DeleteFile (szFileName[0]);
1027 *szFileName[0] = _T('\0');
1028 }
1029 else
1030 {
1031 #ifdef _DEBUG
1032 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1033 #endif
1034 }
1035 }
1036 }
1037 }
1038
1039
1040 /* Restore original STDOUT */
1041 if (hOldConOut != INVALID_HANDLE_VALUE)
1042 {
1043 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1044 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
1045 if (hOldConOut != hOut)
1046 CloseHandle (hOut);
1047 hOldConOut = INVALID_HANDLE_VALUE;
1048 }
1049
1050 /* Restore original STDERR */
1051 if (hOldConErr != INVALID_HANDLE_VALUE)
1052 {
1053 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
1054 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
1055 if (hOldConErr != hErr)
1056 CloseHandle (hErr);
1057 hOldConErr = INVALID_HANDLE_VALUE;
1058 }
1059 #endif /* FEATURE_REDIRECTION */
1060 }
1061
1062 BOOL
1063 GrowIfNecessary ( UINT needed, LPTSTR* ret, UINT* retlen )
1064 {
1065 if ( *ret && needed < *retlen )
1066 return TRUE;
1067 *retlen = needed;
1068 if ( *ret )
1069 free ( *ret );
1070 *ret = (LPTSTR)malloc ( *retlen * sizeof(TCHAR) );
1071 if ( !*ret )
1072 SetLastError ( ERROR_OUTOFMEMORY );
1073 return *ret != NULL;
1074 }
1075
1076 LPCTSTR
1077 GetEnvVarOrSpecial ( LPCTSTR varName )
1078 {
1079 static LPTSTR ret = NULL;
1080 static UINT retlen = 0;
1081 UINT size;
1082
1083 size = GetEnvironmentVariable ( varName, ret, retlen );
1084 if ( size > retlen )
1085 {
1086 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
1087 return NULL;
1088 size = GetEnvironmentVariable ( varName, ret, retlen );
1089 }
1090 if ( size )
1091 return ret;
1092
1093 /* env var doesn't exist, look for a "special" one */
1094 /* %CD% */
1095 if (_tcsicmp(varName,_T("cd")) ==0)
1096 {
1097 size = GetCurrentDirectory ( retlen, ret );
1098 if ( size > retlen )
1099 {
1100 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
1101 return NULL;
1102 size = GetCurrentDirectory ( retlen, ret );
1103 }
1104 if ( !size )
1105 return NULL;
1106 return ret;
1107 }
1108 /* %TIME% */
1109 else if (_tcsicmp(varName,_T("time")) ==0)
1110 {
1111 SYSTEMTIME t;
1112 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1113 return NULL;
1114 GetSystemTime(&t);
1115 _sntprintf ( ret, retlen, _T("%02d%c%02d%c%02d%c%02d"),
1116 t.wHour, cTimeSeparator, t.wMinute, cTimeSeparator,
1117 t.wSecond, cDecimalSeparator, t.wMilliseconds );
1118 return ret;
1119 }
1120 /* %DATE% */
1121 else if (_tcsicmp(varName,_T("date")) ==0)
1122 {
1123 LPTSTR tmp;
1124
1125 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1126 return NULL;
1127 size = GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, _T("ddd"), ret, retlen );
1128 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1129 if ( !size )
1130 return NULL;
1131 tmp = ret + _tcslen(ret);
1132 *tmp++ = _T(' ');
1133 size = GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, tmp, retlen-(tmp-ret));
1134 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1135 if ( !size )
1136 return NULL;
1137 return ret;
1138 }
1139
1140 /* %RANDOM% */
1141 else if (_tcsicmp(varName,_T("random")) ==0)
1142 {
1143 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1144 return NULL;
1145 /* Get random number */
1146 _itot(rand(),ret,10);
1147 return ret;
1148 }
1149
1150 /* %CMDCMDLINE% */
1151 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
1152 {
1153 return GetCommandLine();
1154 }
1155
1156 /* %CMDEXTVERSION% */
1157 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
1158 {
1159 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1160 return NULL;
1161 /* Set version number to 2 */
1162 _itot(2,ret,10);
1163 return ret;
1164 }
1165
1166 /* %ERRORLEVEL% */
1167 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
1168 {
1169 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1170 return NULL;
1171 _itot(nErrorLevel,ret,10);
1172 return ret;
1173 }
1174
1175 return _T(""); /* not found - return empty string */
1176 }
1177
1178 LPCTSTR
1179 GetParsedEnvVar ( LPCTSTR varName, UINT* varNameLen, BOOL ModeSetA )
1180 {
1181 static LPTSTR ret = NULL;
1182 static UINT retlen = 0;
1183 LPTSTR p, tmp;
1184 UINT size;
1185
1186 if ( varNameLen )
1187 *varNameLen = 0;
1188 SetLastError(0);
1189 if ( *varName++ != '%' )
1190 return NULL;
1191 switch ( *varName )
1192 {
1193 case _T('0'):
1194 case _T('1'):
1195 case _T('2'):
1196 case _T('3'):
1197 case _T('4'):
1198 case _T('5'):
1199 case _T('6'):
1200 case _T('7'):
1201 case _T('8'):
1202 case _T('9'):
1203 if ((tmp = FindArg (*varName - _T('0'))))
1204 {
1205 if ( varNameLen )
1206 *varNameLen = 2;
1207 if ( !*tmp )
1208 return _T("");
1209 if ( !GrowIfNecessary ( _tcslen(tmp)+1, &ret, &retlen ) )
1210 return NULL;
1211 _tcscpy ( ret, tmp );
1212 return ret;
1213 }
1214 if ( !GrowIfNecessary ( 3, &ret, &retlen ) )
1215 return NULL;
1216 ret[0] = _T('%');
1217 ret[1] = *varName;
1218 ret[2] = 0;
1219 if ( varNameLen )
1220 *varNameLen = 2;
1221 return ret;
1222
1223 case _T('%'):
1224 if ( !GrowIfNecessary ( 2, &ret, &retlen ) )
1225 return NULL;
1226 ret[0] = _T('%');
1227 ret[1] = 0;
1228 if ( varNameLen )
1229 *varNameLen = 2;
1230 return ret;
1231
1232 case _T('?'):
1233 /* TODO FIXME 10 is only max size for 32-bit */
1234 if ( !GrowIfNecessary ( 11, &ret, &retlen ) )
1235 return NULL;
1236 _sntprintf ( ret, retlen, _T("%u"), nErrorLevel);
1237 ret[retlen-1] = 0;
1238 if ( varNameLen )
1239 *varNameLen = 2;
1240 return ret;
1241 }
1242 if ( ModeSetA )
1243 {
1244 /* HACK for set/a */
1245 if ( !GrowIfNecessary ( 2, &ret, &retlen ) )
1246 return NULL;
1247 ret[0] = _T('%');
1248 ret[1] = 0;
1249 if ( varNameLen )
1250 *varNameLen = 1;
1251 return ret;
1252 }
1253 p = _tcschr ( varName, _T('%') );
1254 if ( !p )
1255 {
1256 SetLastError ( ERROR_INVALID_PARAMETER );
1257 return NULL;
1258 }
1259 size = p-varName;
1260 if ( varNameLen )
1261 *varNameLen = size + 2;
1262 p = alloca ( (size+1) * sizeof(TCHAR) );
1263 memmove ( p, varName, size * sizeof(TCHAR) );
1264 p[size] = 0;
1265 varName = p;
1266 return GetEnvVarOrSpecial ( varName );
1267 }
1268
1269
1270 /*
1271 * do the prompt/input/process loop
1272 *
1273 */
1274
1275 static INT
1276 ProcessInput (BOOL bFlag)
1277 {
1278 TCHAR commandline[CMDLINE_LENGTH];
1279 TCHAR readline[CMDLINE_LENGTH];
1280 LPTSTR ip;
1281 LPTSTR cp;
1282 LPCTSTR tmp;
1283 BOOL bEchoThisLine;
1284 BOOL bModeSetA;
1285
1286 do
1287 {
1288 /* if no batch input then... */
1289 if (!(ip = ReadBatchLine (&bEchoThisLine)))
1290 {
1291 if (bFlag)
1292 return 0;
1293
1294 ReadCommand (readline, CMDLINE_LENGTH);
1295 ip = readline;
1296 bEchoThisLine = FALSE;
1297 }
1298
1299 /* skip leading blanks */
1300 while ( _istspace(*ip) )
1301 ++ip;
1302
1303 cp = commandline;
1304 bModeSetA = FALSE;
1305 while (*ip)
1306 {
1307 if ( *ip == _T('%') )
1308 {
1309 UINT envNameLen;
1310 LPCTSTR envVal = GetParsedEnvVar ( ip, &envNameLen, bModeSetA );
1311 if ( !envVal )
1312 return 1;
1313 ip += envNameLen;
1314 cp = _stpcpy ( cp, envVal );
1315 continue;
1316 }
1317
1318 if (_istcntrl (*ip))
1319 *ip = _T(' ');
1320 *cp++ = *ip++;
1321
1322 /* HACK HACK HACK check whether bModeSetA needs to be toggled */
1323 *cp = 0;
1324 tmp = commandline;
1325 tmp += _tcsspn(tmp,_T(" \t"));
1326 /* first we find and skip and pre-redirections... */
1327 while ( _tcschr(_T("<>"),*tmp)
1328 || !_tcsncmp(tmp,_T("1>"),2)
1329 || !_tcsncmp(tmp,_T("2>"),2) )
1330 {
1331 if ( _istdigit(*tmp) )
1332 tmp += 2;
1333 else
1334 tmp++;
1335 tmp += _tcsspn(tmp,_T(" \t"));
1336 if ( *tmp == _T('\"') )
1337 {
1338 tmp = _tcschr(tmp+1,_T('\"'));
1339 if ( tmp )
1340 ++tmp;
1341 }
1342 else
1343 tmp = _tcspbrk(tmp,_T(" \t"));
1344 tmp += _tcsspn(tmp,_T(" \t"));
1345 }
1346 /* we should now be pointing to the actual command
1347 * (if there is one yet)*/
1348 if ( tmp )
1349 {
1350 /* if we're currently substituting ( which is default )
1351 * check to see if we've parsed out a set/a. if so, we
1352 * need to disable substitution until we come across a
1353 * redirection */
1354 if ( !bModeSetA )
1355 {
1356 /* look for set /a */
1357 if ( !_tcsnicmp(tmp,_T("set"),3) )
1358 {
1359 tmp += 3;
1360 tmp += _tcsspn(tmp,_T(" \t"));
1361 if ( !_tcsnicmp(tmp,_T("/a"),2) )
1362 bModeSetA = TRUE;
1363 }
1364 }
1365 /* if we're not currently substituting, it means we're
1366 * already inside a set /a. now we need to look for
1367 * a redirection in order to turn redirection back on */
1368 else
1369 {
1370 /* look for redirector of some kind after the command */
1371 while ( (tmp = _tcspbrk ( tmp, _T("^<>|") )) )
1372 {
1373 if ( *tmp == _T('^') )
1374 {
1375 if ( _tcschr(_T("<>|&"), *++tmp ) && *tmp )
1376 ++tmp;
1377 }
1378 else
1379 {
1380 bModeSetA = FALSE;
1381 break;
1382 }
1383 }
1384 }
1385 }
1386 }
1387
1388 *cp = _T('\0');
1389
1390 /* strip trailing spaces */
1391 while ((--cp >= commandline) && _istspace (*cp));
1392
1393 *(cp + 1) = _T('\0');
1394
1395 /* JPP 19980807 */
1396 /* Echo batch file line */
1397 if (bEchoThisLine)
1398 {
1399 PrintPrompt ();
1400 ConOutPuts (commandline);
1401 }
1402
1403 if (*commandline)
1404 {
1405 ParseCommandLine (commandline);
1406 if (bEcho && !bIgnoreEcho)
1407 ConOutChar ('\n');
1408 bIgnoreEcho = FALSE;
1409 }
1410 }
1411 while (!bCanExit || !bExit);
1412
1413 return 0;
1414 }
1415
1416
1417 /*
1418 * control-break handler.
1419 */
1420 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1421 {
1422
1423 if ((dwCtrlType != CTRL_C_EVENT) &&
1424 (dwCtrlType != CTRL_BREAK_EVENT))
1425 return FALSE;
1426
1427 if (bChildProcessRunning == TRUE)
1428 {
1429 GenerateConsoleCtrlEvent (CTRL_C_EVENT,
1430 dwChildProcessId);
1431 return TRUE;
1432 }
1433
1434 /* FIXME: Handle batch files */
1435
1436 /* FIXME: Print "^C" */
1437
1438
1439 return TRUE;
1440 }
1441
1442
1443 VOID AddBreakHandler (VOID)
1444 {
1445 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1446 }
1447
1448
1449 VOID RemoveBreakHandler (VOID)
1450 {
1451 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1452 }
1453
1454
1455 /*
1456 * show commands and options that are available.
1457 *
1458 */
1459 #if 0
1460 static VOID
1461 ShowCommands (VOID)
1462 {
1463 /* print command list */
1464 ConOutResPuts(STRING_CMD_HELP1);
1465 PrintCommandList();
1466
1467 /* print feature list */
1468 ConOutResPuts(STRING_CMD_HELP2);
1469
1470 #ifdef FEATURE_ALIASES
1471 ConOutResPuts(STRING_CMD_HELP3);
1472 #endif
1473 #ifdef FEATURE_HISTORY
1474 ConOutResPuts(STRING_CMD_HELP4);
1475 #endif
1476 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1477 ConOutResPuts(STRING_CMD_HELP5);
1478 #endif
1479 #ifdef FEATURE_DIRECTORY_STACK
1480 ConOutResPuts(STRING_CMD_HELP6);
1481 #endif
1482 #ifdef FEATURE_REDIRECTION
1483 ConOutResPuts(STRING_CMD_HELP7);
1484 #endif
1485 ConOutChar(_T('\n'));
1486 }
1487 #endif
1488
1489 /*
1490 * set up global initializations and process parameters
1491 *
1492 * argc - number of parameters to command.com
1493 * argv - command-line parameters
1494 *
1495 */
1496 static VOID
1497 Initialize (int argc, TCHAR* argv[])
1498 {
1499 TCHAR commandline[CMDLINE_LENGTH];
1500 TCHAR ModuleName[_MAX_PATH + 1];
1501 INT i;
1502 TCHAR lpBuffer[2];
1503
1504 //INT len;
1505 //TCHAR *ptr, *cmdLine;
1506
1507 /* get version information */
1508 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1509 GetVersionEx (&osvi);
1510
1511 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1512 * build process. So don't link implicitly against ntdll.dll, load it
1513 * dynamically instead */
1514
1515 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1516 {
1517 /* ntdll is always present on NT */
1518 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1519 }
1520 else
1521 {
1522 /* not all 9x versions have a ntdll.dll, try to load it */
1523 NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
1524 }
1525
1526 if (NtDllModule != NULL)
1527 {
1528 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1529 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1530 }
1531
1532
1533 #ifdef _DEBUG
1534 DebugPrintf (_T("[command args:\n"));
1535 for (i = 0; i < argc; i++)
1536 {
1537 DebugPrintf (_T("%d. %s\n"), i, argv[i]);
1538 }
1539 DebugPrintf (_T("]\n"));
1540 #endif
1541
1542 InitLocale ();
1543
1544 /* get default input and output console handles */
1545 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1546 hIn = GetStdHandle (STD_INPUT_HANDLE);
1547
1548 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1549 for you can change the EnvirommentVariable for prompt before cmd start
1550 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1551 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1552 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer, sizeof(lpBuffer) / sizeof(lpBuffer[0])) == 0)
1553 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1554
1555
1556 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1557 {
1558 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1559 ExitProcess(0);
1560 }
1561 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1562
1563 #ifdef INCLUDE_CMD_CHDIR
1564 InitLastPath ();
1565 #endif
1566
1567 #ifdef FATURE_ALIASES
1568 InitializeAlias ();
1569 #endif
1570
1571 if (argc >= 2)
1572 {
1573 for (i = 1; i < argc; i++)
1574 {
1575 if (!_tcsicmp (argv[i], _T("/p")))
1576 {
1577 if (!IsExistingFile (_T("\\autoexec.bat")))
1578 {
1579 #ifdef INCLUDE_CMD_DATE
1580 cmd_date (_T(""), _T(""));
1581 #endif
1582 #ifdef INCLUDE_CMD_TIME
1583 cmd_time (_T(""), _T(""));
1584 #endif
1585 }
1586 else
1587 {
1588 ParseCommandLine (_T("\\autoexec.bat"));
1589 }
1590 bCanExit = FALSE;
1591 }
1592 else if (!_tcsicmp (argv[i], _T("/c")))
1593 {
1594 /* This just runs a program and exits */
1595 ++i;
1596 if (i < argc)
1597 {
1598 _tcscpy (commandline, argv[i]);
1599 while (++i < argc)
1600 {
1601 _tcscat (commandline, _T(" "));
1602 _tcscat (commandline, argv[i]);
1603 }
1604
1605 ParseCommandLine(commandline);
1606 ExitProcess (ProcessInput (TRUE));
1607 }
1608 else
1609 {
1610 ExitProcess (0);
1611 }
1612 }
1613 else if (!_tcsicmp (argv[i], _T("/k")))
1614 {
1615 /* This just runs a program and remains */
1616 ++i;
1617 if (i < argc)
1618 {
1619 _tcscpy (commandline, _T("\""));
1620 _tcscat (commandline, argv[i]);
1621 _tcscat (commandline, _T("\""));
1622 while (++i < argc)
1623 {
1624 _tcscat (commandline, _T(" "));
1625 _tcscat (commandline, argv[i]);
1626 }
1627 ParseCommandLine(commandline);
1628 }
1629 }
1630 #ifdef INCLUDE_CMD_COLOR
1631 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1632 {
1633 /* process /t (color) argument */
1634 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1635 wColor = wDefColor;
1636 SetScreenColor (wColor, TRUE);
1637 }
1638 #endif
1639 }
1640 }
1641
1642 /* run cmdstart.bat */
1643 if (IsExistingFile (_T("cmdstart.bat")))
1644 {
1645 ParseCommandLine (_T("cmdstart.bat"));
1646 }
1647 else if (IsExistingFile (_T("\\cmdstart.bat")))
1648 {
1649 ParseCommandLine (_T("\\cmdstart.bat"));
1650 }
1651
1652 #ifdef FEATURE_DIR_STACK
1653 /* initialize directory stack */
1654 InitDirectoryStack ();
1655 #endif
1656
1657
1658 #ifdef FEATURE_HISTORY
1659 /*initialize history*/
1660 InitHistory();
1661 #endif
1662
1663 /* Set COMSPEC environment variable */
1664 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1665 {
1666 ModuleName[_MAX_PATH] = _T('\0');
1667 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1668 }
1669
1670 /* add ctrl break handler */
1671 AddBreakHandler ();
1672 }
1673
1674
1675 static VOID Cleanup (int argc, TCHAR *argv[])
1676 {
1677 /* run cmdexit.bat */
1678 if (IsExistingFile (_T("cmdexit.bat")))
1679 {
1680 ConErrResPuts(STRING_CMD_ERROR5);
1681
1682 ParseCommandLine (_T("cmdexit.bat"));
1683 }
1684 else if (IsExistingFile (_T("\\cmdexit.bat")))
1685 {
1686 ConErrResPuts (STRING_CMD_ERROR5);
1687 ParseCommandLine (_T("\\cmdexit.bat"));
1688 }
1689
1690 #ifdef FEATURE_ALIASES
1691 DestroyAlias ();
1692 #endif
1693
1694 #ifdef FEATURE_DIECTORY_STACK
1695 /* destroy directory stack */
1696 DestroyDirectoryStack ();
1697 #endif
1698
1699 #ifdef INCLUDE_CMD_CHDIR
1700 FreeLastPath ();
1701 #endif
1702
1703 #ifdef FEATURE_HISTORY
1704 CleanHistory();
1705 #endif
1706
1707
1708 /* remove ctrl break handler */
1709 RemoveBreakHandler ();
1710 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1711 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1712
1713 if (NtDllModule != NULL)
1714 {
1715 FreeLibrary(NtDllModule);
1716 }
1717 }
1718
1719 /*
1720 * main function
1721 */
1722 #ifdef _UNICODE
1723 int _main(void)
1724 #else
1725 int _main (int argc, char *argv[])
1726 #endif
1727 {
1728 TCHAR startPath[MAX_PATH];
1729 CONSOLE_SCREEN_BUFFER_INFO Info;
1730 INT nExitCode;
1731 #ifdef _UNICODE
1732 PWCHAR * argv;
1733 int argc=0;
1734 argv = CommandLineToArgvW(GetCommandLineW(), &argc);
1735 #endif
1736
1737 GetCurrentDirectory(MAX_PATH,startPath);
1738 _tchdir(startPath);
1739
1740 SetFileApisToOEM();
1741 InputCodePage= 0;
1742 OutputCodePage = 0;
1743
1744 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1745 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1746 OPEN_EXISTING, 0, NULL);
1747 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1748 {
1749 ConErrFormatMessage(GetLastError());
1750 return(1);
1751 }
1752 wColor = Info.wAttributes;
1753 wDefColor = wColor;
1754
1755 InputCodePage= GetConsoleCP();
1756 OutputCodePage = GetConsoleOutputCP();
1757 CMD_ModuleHandle = GetModuleHandle(NULL);
1758
1759 /* check switches on command-line */
1760 Initialize(argc, argv);
1761
1762 /* call prompt routine */
1763 nExitCode = ProcessInput(FALSE);
1764
1765 /* do the cleanup */
1766 Cleanup(argc, argv);
1767
1768 return(nExitCode);
1769 }
1770
1771 /* EOF */