%foo% where foo is not a envir var should be returned as %foo% not as "".
[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 0, /* CREATE_NEW_PROCESS_GROUP */
473 NULL,
474 NULL,
475 &stui,
476 &prci))
477
478 {
479 if (IsConsoleProcess(prci.hProcess))
480 {
481 /* FIXME: Protect this with critical section */
482 bChildProcessRunning = TRUE;
483 dwChildProcessId = prci.dwProcessId;
484
485 WaitForSingleObject (prci.hProcess, INFINITE);
486
487 /* FIXME: Protect this with critical section */
488 bChildProcessRunning = FALSE;
489
490 GetExitCodeProcess (prci.hProcess, &dwExitCode);
491 nErrorLevel = (INT)dwExitCode;
492 }
493 CloseHandle (prci.hThread);
494 CloseHandle (prci.hProcess);
495 }
496 else
497 {
498 #ifdef _DEBUG
499 DebugPrintf (_T("[ShellExecute: %s]\n"), full);
500 #endif
501 // See if we can run this with ShellExecute() ie myfile.xls
502 if (!RunFile(full))
503 {
504 #ifdef _DEBUG
505 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full);
506 #endif
507 error_bad_command ();
508 }
509 }
510 // restore console mode
511 SetConsoleMode (
512 GetStdHandle( STD_INPUT_HANDLE ),
513 ENABLE_PROCESSED_INPUT );
514 }
515
516 /* Get code page if it has been change */
517 InputCodePage= GetConsoleCP();
518 OutputCodePage = GetConsoleOutputCP();
519 SetConsoleTitle (szWindowTitle);
520
521 free(first);
522 free(rest);
523 free(full);
524 free (szFullName);
525 }
526
527
528 /*
529 * look through the internal commands and determine whether or not this
530 * command is one of them. If it is, call the command. If not, call
531 * execute to run it as an external program.
532 *
533 * line - the command line of the program to run
534 *
535 */
536
537 static VOID
538 DoCommand (LPTSTR line)
539 {
540 TCHAR *com = NULL; /* the first word in the command */
541 TCHAR *cp = NULL;
542 LPTSTR cstart;
543 LPTSTR rest; /* pointer to the rest of the command line */
544 INT cl;
545 LPCOMMAND cmdptr;
546
547 #ifdef _DEBUG
548 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line);
549 #endif /* DEBUG */
550
551 com = malloc( (_tcslen(line) +512)*sizeof(TCHAR) );
552 if (com == NULL)
553 {
554 error_out_of_memory();
555 return;
556 }
557
558 cp = com;
559 /* Skip over initial white space */
560 while (_istspace (*line))
561 line++;
562 rest = line;
563
564 cstart = rest;
565
566 /* Anything to do ? */
567 if (*rest)
568 {
569 if (*rest == _T('"'))
570 {
571 /* treat quoted words specially */
572
573 rest++;
574
575 while(*rest != _T('\0') && *rest != _T('"'))
576 *cp++ = _totlower (*rest++);
577 if (*rest == _T('"'))
578 rest++;
579 }
580 else
581 {
582 while (!IsDelimiter (*rest))
583 *cp++ = _totlower (*rest++);
584 }
585
586
587 /* Terminate first word */
588 *cp = _T('\0');
589
590 /* Do not limit commands to MAX_PATH */
591 /*
592 if(_tcslen(com) > MAX_PATH)
593 {
594 error_bad_command();
595 free(com);
596 return;
597 }
598 */
599
600 /* Skip over whitespace to rest of line */
601 while (_istspace (*rest))
602 rest++;
603
604 /* Scan internal command table */
605 for (cmdptr = cmds;; cmdptr++)
606 {
607 /* If end of table execute ext cmd */
608 if (cmdptr->name == NULL)
609 {
610 Execute (line, com, rest);
611 break;
612 }
613
614 if (!_tcscmp (com, cmdptr->name))
615 {
616 cmdptr->func (com, rest);
617 break;
618 }
619
620 /* The following code handles the case of commands like CD which
621 * are recognised even when the command name and parameter are
622 * not space separated.
623 *
624 * e.g dir..
625 * cd\freda
626 */
627
628 /* Get length of command name */
629 cl = _tcslen (cmdptr->name);
630
631 if ((cmdptr->flags & CMD_SPECIAL) &&
632 (!_tcsncmp (cmdptr->name, com, cl)) &&
633 (_tcschr (_T("\\.-"), *(com + cl))))
634 {
635 /* OK its one of the specials...*/
636
637 /* Terminate first word properly */
638 com[cl] = _T('\0');
639
640 /* Call with new rest */
641 cmdptr->func (com, cstart + cl);
642 break;
643 }
644 }
645 }
646 /* Just in case a CTRL+C slipped through a command */
647 bCtrlBreak = FALSE;
648 free(com);
649 }
650
651
652 /*
653 * process the command line and execute the appropriate functions
654 * full input/output redirection and piping are supported
655 */
656
657 VOID ParseCommandLine (LPTSTR cmd)
658 {
659 TCHAR szMsg[RC_STRING_MAX_SIZE];
660 TCHAR cmdline[CMDLINE_LENGTH];
661 LPTSTR s;
662 #ifdef FEATURE_REDIRECTION
663 TCHAR in[CMDLINE_LENGTH] = _T("");
664 TCHAR out[CMDLINE_LENGTH] = _T("");
665 TCHAR err[CMDLINE_LENGTH] = _T("");
666 TCHAR szTempPath[MAX_PATH] = _T(".\\");
667 TCHAR szFileName[2][MAX_PATH] = {_T(""), _T("")};
668 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
669 LPTSTR t = NULL;
670 INT num = 0;
671 INT nRedirFlags = 0;
672 INT Length;
673 UINT Attributes;
674 BOOL bNewBatch = TRUE;
675 HANDLE hOldConIn;
676 HANDLE hOldConOut;
677 HANDLE hOldConErr;
678 #endif /* FEATURE_REDIRECTION */
679
680 _tcscpy (cmdline, cmd);
681 s = &cmdline[0];
682
683 #ifdef _DEBUG
684 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s);
685 #endif /* DEBUG */
686
687 #ifdef FEATURE_ALIASES
688 /* expand all aliases */
689 ExpandAlias (s, CMDLINE_LENGTH);
690 #endif /* FEATURE_ALIAS */
691
692 #ifdef FEATURE_REDIRECTION
693 /* find the temp path to store temporary files */
694 Length = GetTempPath (MAX_PATH, szTempPath);
695 if (Length > 0 && Length < MAX_PATH)
696 {
697 Attributes = GetFileAttributes(szTempPath);
698 if (Attributes == 0xffffffff ||
699 !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
700 {
701 Length = 0;
702 }
703 }
704 if (Length == 0 || Length >= MAX_PATH)
705 {
706 _tcscpy(szTempPath, _T(".\\"));
707 }
708 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
709 _tcscat (szTempPath, _T("\\"));
710
711 /* get the redirections from the command line */
712 num = GetRedirection (s, in, out, err, &nRedirFlags);
713
714 /* more efficient, but do we really need to do this? */
715 for (t = in; _istspace (*t); t++)
716 ;
717 _tcscpy (in, t);
718
719 for (t = out; _istspace (*t); t++)
720 ;
721 _tcscpy (out, t);
722
723 for (t = err; _istspace (*t); t++)
724 ;
725 _tcscpy (err, t);
726
727 if(bc && !_tcslen (in) && _tcslen (bc->In))
728 _tcscpy(in, bc->In);
729 if(bc && !out[0] && _tcslen(bc->Out))
730 {
731 nRedirFlags |= OUTPUT_APPEND;
732 _tcscpy(out, bc->Out);
733 }
734 if(bc && !_tcslen (err) && _tcslen (bc->Err))
735 {
736 nRedirFlags |= ERROR_APPEND;
737 _tcscpy(err, bc->Err);
738 }
739
740
741 /* Set up the initial conditions ... */
742 /* preserve STDIN, STDOUT and STDERR handles */
743 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
744 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
745 hOldConErr = GetStdHandle (STD_ERROR_HANDLE);
746
747 /* redirect STDIN */
748 if (in[0])
749 {
750 HANDLE hFile;
751 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
752
753 /* we need make sure the LastError msg is zero before calling CreateFile */
754 SetLastError(0);
755
756 /* Set up pipe for the standard input handler */
757 hFile = CreateFile (in, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
758 FILE_ATTRIBUTE_NORMAL, NULL);
759 if (hFile == INVALID_HANDLE_VALUE)
760 {
761 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
762 ConErrPrintf(szMsg, in);
763 return;
764 }
765
766 if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
767 {
768 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
769 ConErrPrintf(szMsg, in);
770 return;
771 }
772 #ifdef _DEBUG
773 DebugPrintf (_T("Input redirected from: %s\n"), in);
774 #endif
775 }
776
777 /* Now do all but the last pipe command */
778 *szFileName[0] = _T('\0');
779 hFile[0] = INVALID_HANDLE_VALUE;
780
781 while (num-- > 1)
782 {
783 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
784
785 /* Create unique temporary file name */
786 GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
787
788 /* we need make sure the LastError msg is zero before calling CreateFile */
789 SetLastError(0);
790
791 /* Set current stdout to temporary file */
792 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
793 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
794
795 if (hFile[1] == INVALID_HANDLE_VALUE)
796 {
797 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR2, szMsg, RC_STRING_MAX_SIZE);
798 ConErrPrintf(szMsg);
799 return;
800 }
801
802 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
803
804 DoCommand (s);
805
806 /* close stdout file */
807 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
808 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
809 {
810 CloseHandle (hFile[1]);
811 hFile[1] = INVALID_HANDLE_VALUE;
812 }
813
814 /* close old stdin file */
815 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
816 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
817 {
818 /* delete old stdin file, if it is a real file */
819 CloseHandle (hFile[0]);
820 hFile[0] = INVALID_HANDLE_VALUE;
821 DeleteFile (szFileName[0]);
822 *szFileName[0] = _T('\0');
823 }
824
825 /* copy stdout file name to stdin file name */
826 _tcscpy (szFileName[0], szFileName[1]);
827 *szFileName[1] = _T('\0');
828
829 /* we need make sure the LastError msg is zero before calling CreateFile */
830 SetLastError(0);
831
832 /* open new stdin file */
833 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
834 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
835 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
836
837 s = s + _tcslen (s) + 1;
838 }
839
840 /* Now set up the end conditions... */
841 /* redirect STDOUT */
842 if (out[0])
843 {
844 /* Final output to here */
845 HANDLE hFile;
846 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
847
848 /* we need make sure the LastError msg is zero before calling CreateFile */
849 SetLastError(0);
850
851 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
852 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
853 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
854
855 if (hFile == INVALID_HANDLE_VALUE)
856 {
857 INT size = _tcslen(out)-1;
858
859 if (out[size] != _T(':'))
860 {
861 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
862 ConErrPrintf(szMsg, out);
863 return;
864 }
865
866 out[size]=_T('\0');
867 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
868 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
869 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
870
871 if (hFile == INVALID_HANDLE_VALUE)
872 {
873 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
874 ConErrPrintf(szMsg, out);
875 return;
876 }
877
878 }
879
880 if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
881 {
882 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
883 ConErrPrintf(szMsg, out);
884 return;
885 }
886
887 if (nRedirFlags & OUTPUT_APPEND)
888 {
889 LONG lHighPos = 0;
890
891 if (GetFileType (hFile) == FILE_TYPE_DISK)
892 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
893 }
894 #ifdef _DEBUG
895 DebugPrintf (_T("Output redirected to: %s\n"), out);
896 #endif
897 }
898 else if (hOldConOut != INVALID_HANDLE_VALUE)
899 {
900 /* Restore original stdout */
901 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
902 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
903 if (hOldConOut != hOut)
904 CloseHandle (hOut);
905 hOldConOut = INVALID_HANDLE_VALUE;
906 }
907
908 /* redirect STDERR */
909 if (err[0])
910 {
911 /* Final output to here */
912 HANDLE hFile;
913 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
914
915 if (!_tcscmp (err, out))
916 {
917 #ifdef _DEBUG
918 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
919 #endif
920 DuplicateHandle (GetCurrentProcess (),
921 GetStdHandle (STD_OUTPUT_HANDLE),
922 GetCurrentProcess (),
923 &hFile, 0, TRUE, DUPLICATE_SAME_ACCESS);
924 }
925 else
926 {
927 hFile = CreateFile (err,
928 GENERIC_WRITE,
929 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
930 &sa,
931 (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
932 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
933 NULL);
934 if (hFile == INVALID_HANDLE_VALUE)
935 {
936 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
937 ConErrPrintf(szMsg, err);
938 return;
939 }
940 }
941
942 if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
943 {
944 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
945 ConErrPrintf(szMsg, err);
946 return;
947 }
948
949 if (nRedirFlags & ERROR_APPEND)
950 {
951 LONG lHighPos = 0;
952
953 if (GetFileType (hFile) == FILE_TYPE_DISK)
954 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
955 }
956 #ifdef _DEBUG
957 DebugPrintf (_T("Error redirected to: %s\n"), err);
958 #endif
959 }
960 else if (hOldConErr != INVALID_HANDLE_VALUE)
961 {
962 /* Restore original stderr */
963 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
964 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
965 if (hOldConErr != hErr)
966 CloseHandle (hErr);
967 hOldConErr = INVALID_HANDLE_VALUE;
968 }
969
970 if(bc)
971 bNewBatch = FALSE;
972 #endif
973
974 /* process final command */
975 DoCommand (s);
976
977 #ifdef FEATURE_REDIRECTION
978 if(bNewBatch && bc)
979 AddBatchRedirection(in, out, err);
980 /* close old stdin file */
981 #if 0 /* buggy implementation */
982 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
983 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
984 (hFile[0] != hOldConIn))
985 {
986 /* delete old stdin file, if it is a real file */
987 CloseHandle (hFile[0]);
988 hFile[0] = INVALID_HANDLE_VALUE;
989 DeleteFile (szFileName[0]);
990 *szFileName[0] = _T('\0');
991 }
992
993 /* Restore original STDIN */
994 if (hOldConIn != INVALID_HANDLE_VALUE)
995 {
996 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
997 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
998 if (hOldConIn != hIn)
999 CloseHandle (hIn);
1000 hOldConIn = INVALID_HANDLE_VALUE;
1001 }
1002 else
1003 {
1004 #ifdef _DEBUG
1005 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out);
1006 #endif
1007 }
1008 #endif /* buggy implementation */
1009
1010
1011 if (hOldConIn != INVALID_HANDLE_VALUE)
1012 {
1013 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1014 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
1015 if (hIn == INVALID_HANDLE_VALUE)
1016 {
1017 #ifdef _DEBUG
1018 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
1019 #endif
1020 }
1021 else
1022 {
1023 if (GetFileType (hIn) == FILE_TYPE_DISK)
1024 {
1025 if (hFile[0] == hIn)
1026 {
1027 CloseHandle (hFile[0]);
1028 hFile[0] = INVALID_HANDLE_VALUE;
1029 DeleteFile (szFileName[0]);
1030 *szFileName[0] = _T('\0');
1031 }
1032 else
1033 {
1034 #ifdef _DEBUG
1035 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1036 #endif
1037 }
1038 }
1039 }
1040 }
1041
1042
1043 /* Restore original STDOUT */
1044 if (hOldConOut != INVALID_HANDLE_VALUE)
1045 {
1046 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1047 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
1048 if (hOldConOut != hOut)
1049 CloseHandle (hOut);
1050 hOldConOut = INVALID_HANDLE_VALUE;
1051 }
1052
1053 /* Restore original STDERR */
1054 if (hOldConErr != INVALID_HANDLE_VALUE)
1055 {
1056 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
1057 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
1058 if (hOldConErr != hErr)
1059 CloseHandle (hErr);
1060 hOldConErr = INVALID_HANDLE_VALUE;
1061 }
1062 #endif /* FEATURE_REDIRECTION */
1063 }
1064
1065 BOOL
1066 GrowIfNecessary ( UINT needed, LPTSTR* ret, UINT* retlen )
1067 {
1068 if ( *ret && needed < *retlen )
1069 return TRUE;
1070 *retlen = needed;
1071 if ( *ret )
1072 free ( *ret );
1073 *ret = (LPTSTR)malloc ( *retlen * sizeof(TCHAR) );
1074 if ( !*ret )
1075 SetLastError ( ERROR_OUTOFMEMORY );
1076 return *ret != NULL;
1077 }
1078
1079 LPCTSTR
1080 GetEnvVarOrSpecial ( LPCTSTR varName )
1081 {
1082 static LPTSTR ret = NULL;
1083 static UINT retlen = 0;
1084 UINT size;
1085
1086 size = GetEnvironmentVariable ( varName, ret, retlen );
1087 if ( size > retlen )
1088 {
1089 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
1090 return NULL;
1091 size = GetEnvironmentVariable ( varName, ret, retlen );
1092 }
1093 if ( size )
1094 return ret;
1095
1096 /* env var doesn't exist, look for a "special" one */
1097 /* %CD% */
1098 if (_tcsicmp(varName,_T("cd")) ==0)
1099 {
1100 size = GetCurrentDirectory ( retlen, ret );
1101 if ( size > retlen )
1102 {
1103 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
1104 return NULL;
1105 size = GetCurrentDirectory ( retlen, ret );
1106 }
1107 if ( !size )
1108 return NULL;
1109 return ret;
1110 }
1111 /* %TIME% */
1112 else if (_tcsicmp(varName,_T("time")) ==0)
1113 {
1114 SYSTEMTIME t;
1115 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1116 return NULL;
1117 GetSystemTime(&t);
1118 _sntprintf ( ret, retlen, _T("%02d%c%02d%c%02d%c%02d"),
1119 t.wHour, cTimeSeparator, t.wMinute, cTimeSeparator,
1120 t.wSecond, cDecimalSeparator, t.wMilliseconds );
1121 return ret;
1122 }
1123 /* %DATE% */
1124 else if (_tcsicmp(varName,_T("date")) ==0)
1125 {
1126 LPTSTR tmp;
1127
1128 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1129 return NULL;
1130 size = GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, _T("ddd"), ret, retlen );
1131 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1132 if ( !size )
1133 return NULL;
1134 tmp = ret + _tcslen(ret);
1135 *tmp++ = _T(' ');
1136 size = GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, tmp, retlen-(tmp-ret));
1137 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1138 if ( !size )
1139 return NULL;
1140 return ret;
1141 }
1142
1143 /* %RANDOM% */
1144 else if (_tcsicmp(varName,_T("random")) ==0)
1145 {
1146 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1147 return NULL;
1148 /* Get random number */
1149 _itot(rand(),ret,10);
1150 return ret;
1151 }
1152
1153 /* %CMDCMDLINE% */
1154 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
1155 {
1156 return GetCommandLine();
1157 }
1158
1159 /* %CMDEXTVERSION% */
1160 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
1161 {
1162 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1163 return NULL;
1164 /* Set version number to 2 */
1165 _itot(2,ret,10);
1166 return ret;
1167 }
1168
1169 /* %ERRORLEVEL% */
1170 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
1171 {
1172 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1173 return NULL;
1174 _itot(nErrorLevel,ret,10);
1175 return ret;
1176 }
1177
1178 GrowIfNecessary(_tcslen(varName) + 2, &ret, &retlen);
1179 _stprintf(ret,_T("%%%s%%"),varName);
1180 return ret; /* not found - return orginal string */
1181 }
1182
1183 LPCTSTR
1184 GetParsedEnvVar ( LPCTSTR varName, UINT* varNameLen, BOOL ModeSetA )
1185 {
1186 static LPTSTR ret = NULL;
1187 static UINT retlen = 0;
1188 LPTSTR p, tmp;
1189 UINT size;
1190
1191 if ( varNameLen )
1192 *varNameLen = 0;
1193 SetLastError(0);
1194 if ( *varName++ != '%' )
1195 return NULL;
1196 switch ( *varName )
1197 {
1198 case _T('0'):
1199 case _T('1'):
1200 case _T('2'):
1201 case _T('3'):
1202 case _T('4'):
1203 case _T('5'):
1204 case _T('6'):
1205 case _T('7'):
1206 case _T('8'):
1207 case _T('9'):
1208 if ((tmp = FindArg (*varName - _T('0'))))
1209 {
1210 if ( varNameLen )
1211 *varNameLen = 2;
1212 if ( !*tmp )
1213 return _T("");
1214 if ( !GrowIfNecessary ( _tcslen(tmp)+1, &ret, &retlen ) )
1215 return NULL;
1216 _tcscpy ( ret, tmp );
1217 return ret;
1218 }
1219 if ( !GrowIfNecessary ( 3, &ret, &retlen ) )
1220 return NULL;
1221 ret[0] = _T('%');
1222 ret[1] = *varName;
1223 ret[2] = 0;
1224 if ( varNameLen )
1225 *varNameLen = 2;
1226 return ret;
1227
1228 case _T('%'):
1229 if ( !GrowIfNecessary ( 2, &ret, &retlen ) )
1230 return NULL;
1231 ret[0] = _T('%');
1232 ret[1] = 0;
1233 if ( varNameLen )
1234 *varNameLen = 2;
1235 return ret;
1236
1237 case _T('?'):
1238 /* TODO FIXME 10 is only max size for 32-bit */
1239 if ( !GrowIfNecessary ( 11, &ret, &retlen ) )
1240 return NULL;
1241 _sntprintf ( ret, retlen, _T("%u"), nErrorLevel);
1242 ret[retlen-1] = 0;
1243 if ( varNameLen )
1244 *varNameLen = 2;
1245 return ret;
1246 }
1247 if ( ModeSetA )
1248 {
1249 /* HACK for set/a */
1250 if ( !GrowIfNecessary ( 2, &ret, &retlen ) )
1251 return NULL;
1252 ret[0] = _T('%');
1253 ret[1] = 0;
1254 if ( varNameLen )
1255 *varNameLen = 1;
1256 return ret;
1257 }
1258 p = _tcschr ( varName, _T('%') );
1259 if ( !p )
1260 {
1261 SetLastError ( ERROR_INVALID_PARAMETER );
1262 return NULL;
1263 }
1264 size = p-varName;
1265 if ( varNameLen )
1266 *varNameLen = size + 2;
1267 p = alloca ( (size+1) * sizeof(TCHAR) );
1268 memmove ( p, varName, size * sizeof(TCHAR) );
1269 p[size] = 0;
1270 varName = p;
1271 return GetEnvVarOrSpecial ( varName );
1272 }
1273
1274
1275 /*
1276 * do the prompt/input/process loop
1277 *
1278 */
1279
1280 static INT
1281 ProcessInput (BOOL bFlag)
1282 {
1283 TCHAR commandline[CMDLINE_LENGTH];
1284 TCHAR readline[CMDLINE_LENGTH];
1285 LPTSTR ip;
1286 LPTSTR cp;
1287 LPCTSTR tmp;
1288 BOOL bEchoThisLine;
1289 BOOL bModeSetA;
1290 BOOL bIsBatch;
1291
1292 do
1293 {
1294 /* if no batch input then... */
1295 if (!(ip = ReadBatchLine (&bEchoThisLine)))
1296 {
1297 if (bFlag)
1298 return 0;
1299
1300 ReadCommand (readline, CMDLINE_LENGTH);
1301 ip = readline;
1302 bEchoThisLine = FALSE;
1303 bIsBatch = FALSE;
1304 }
1305 else
1306 {
1307 bIsBatch = TRUE;
1308 }
1309
1310 /* skip leading blanks */
1311 while ( _istspace(*ip) )
1312 ++ip;
1313
1314 cp = commandline;
1315 bModeSetA = FALSE;
1316 while (*ip)
1317 {
1318 if ( *ip == _T('%') )
1319 {
1320 UINT envNameLen;
1321 LPCTSTR envVal = GetParsedEnvVar ( ip, &envNameLen, bModeSetA );
1322 if ( !envVal )
1323 return 1;
1324 ip += envNameLen;
1325 cp = _stpcpy ( cp, envVal );
1326 continue;
1327 }
1328
1329 if (_istcntrl (*ip))
1330 *ip = _T(' ');
1331 *cp++ = *ip++;
1332
1333 /* HACK HACK HACK check whether bModeSetA needs to be toggled */
1334 *cp = 0;
1335 tmp = commandline;
1336 tmp += _tcsspn(tmp,_T(" \t"));
1337 /* first we find and skip and pre-redirections... */
1338 while ( _tcschr(_T("<>"),*tmp)
1339 || !_tcsncmp(tmp,_T("1>"),2)
1340 || !_tcsncmp(tmp,_T("2>"),2) )
1341 {
1342 if ( _istdigit(*tmp) )
1343 tmp += 2;
1344 else
1345 tmp++;
1346 tmp += _tcsspn(tmp,_T(" \t"));
1347 if ( *tmp == _T('\"') )
1348 {
1349 tmp = _tcschr(tmp+1,_T('\"'));
1350 if ( tmp )
1351 ++tmp;
1352 }
1353 else
1354 tmp = _tcspbrk(tmp,_T(" \t"));
1355 tmp += _tcsspn(tmp,_T(" \t"));
1356 }
1357 /* we should now be pointing to the actual command
1358 * (if there is one yet)*/
1359 if ( tmp )
1360 {
1361 /* if we're currently substituting ( which is default )
1362 * check to see if we've parsed out a set/a. if so, we
1363 * need to disable substitution until we come across a
1364 * redirection */
1365 if ( !bModeSetA )
1366 {
1367 /* look for set /a */
1368 if ( !_tcsnicmp(tmp,_T("set"),3) )
1369 {
1370 tmp += 3;
1371 tmp += _tcsspn(tmp,_T(" \t"));
1372 if ( !_tcsnicmp(tmp,_T("/a"),2) )
1373 bModeSetA = TRUE;
1374 }
1375 }
1376 /* if we're not currently substituting, it means we're
1377 * already inside a set /a. now we need to look for
1378 * a redirection in order to turn redirection back on */
1379 else
1380 {
1381 /* look for redirector of some kind after the command */
1382 while ( (tmp = _tcspbrk ( tmp, _T("^<>|") )) )
1383 {
1384 if ( *tmp == _T('^') )
1385 {
1386 if ( _tcschr(_T("<>|&"), *++tmp ) && *tmp )
1387 ++tmp;
1388 }
1389 else
1390 {
1391 bModeSetA = FALSE;
1392 break;
1393 }
1394 }
1395 }
1396 }
1397 }
1398
1399 *cp = _T('\0');
1400
1401 /* strip trailing spaces */
1402 while ((--cp >= commandline) && _istspace (*cp));
1403
1404 *(cp + 1) = _T('\0');
1405
1406 /* JPP 19980807 */
1407 /* Echo batch file line */
1408 if (bEchoThisLine)
1409 {
1410 PrintPrompt ();
1411 ConOutPuts (commandline);
1412 }
1413
1414 if (*commandline)
1415 {
1416 ParseCommandLine (commandline);
1417 if (bEcho && !bIgnoreEcho && (!bIsBatch || bEchoThisLine))
1418 ConOutChar ('\n');
1419 bIgnoreEcho = FALSE;
1420 }
1421 }
1422 while (!bCanExit || !bExit);
1423
1424 return 0;
1425 }
1426
1427
1428 /*
1429 * control-break handler.
1430 */
1431 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1432 {
1433
1434 static BOOL SelfGenerated = FALSE;
1435
1436 if ((dwCtrlType != CTRL_C_EVENT) &&
1437 (dwCtrlType != CTRL_BREAK_EVENT))
1438 {
1439 return FALSE;
1440 }
1441 else
1442 {
1443 if(SelfGenerated)
1444 {
1445 SelfGenerated = FALSE;
1446 return TRUE;
1447 }
1448 }
1449
1450 if (bChildProcessRunning == TRUE)
1451 {
1452 SelfGenerated = TRUE;
1453 GenerateConsoleCtrlEvent (dwCtrlType, 0);
1454 return TRUE;
1455 }
1456
1457 bCtrlBreak = TRUE;
1458 /* FIXME: Handle batch files */
1459
1460 //ConOutPrintf(_T("^C"));
1461
1462
1463 return TRUE;
1464 }
1465
1466
1467 VOID AddBreakHandler (VOID)
1468 {
1469 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1470 }
1471
1472
1473 VOID RemoveBreakHandler (VOID)
1474 {
1475 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1476 }
1477
1478
1479 /*
1480 * show commands and options that are available.
1481 *
1482 */
1483 #if 0
1484 static VOID
1485 ShowCommands (VOID)
1486 {
1487 /* print command list */
1488 ConOutResPuts(STRING_CMD_HELP1);
1489 PrintCommandList();
1490
1491 /* print feature list */
1492 ConOutResPuts(STRING_CMD_HELP2);
1493
1494 #ifdef FEATURE_ALIASES
1495 ConOutResPuts(STRING_CMD_HELP3);
1496 #endif
1497 #ifdef FEATURE_HISTORY
1498 ConOutResPuts(STRING_CMD_HELP4);
1499 #endif
1500 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1501 ConOutResPuts(STRING_CMD_HELP5);
1502 #endif
1503 #ifdef FEATURE_DIRECTORY_STACK
1504 ConOutResPuts(STRING_CMD_HELP6);
1505 #endif
1506 #ifdef FEATURE_REDIRECTION
1507 ConOutResPuts(STRING_CMD_HELP7);
1508 #endif
1509 ConOutChar(_T('\n'));
1510 }
1511 #endif
1512
1513 /*
1514 * set up global initializations and process parameters
1515 *
1516 * argc - number of parameters to command.com
1517 * argv - command-line parameters
1518 *
1519 */
1520 static VOID
1521 Initialize (int argc, TCHAR* argv[])
1522 {
1523 TCHAR commandline[CMDLINE_LENGTH];
1524 TCHAR ModuleName[_MAX_PATH + 1];
1525 INT i;
1526 TCHAR lpBuffer[2];
1527
1528 //INT len;
1529 //TCHAR *ptr, *cmdLine;
1530
1531 /* get version information */
1532 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1533 GetVersionEx (&osvi);
1534
1535 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1536 * build process. So don't link implicitly against ntdll.dll, load it
1537 * dynamically instead */
1538
1539 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1540 {
1541 /* ntdll is always present on NT */
1542 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1543 }
1544 else
1545 {
1546 /* not all 9x versions have a ntdll.dll, try to load it */
1547 NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
1548 }
1549
1550 if (NtDllModule != NULL)
1551 {
1552 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1553 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1554 }
1555
1556
1557 #ifdef _DEBUG
1558 DebugPrintf (_T("[command args:\n"));
1559 for (i = 0; i < argc; i++)
1560 {
1561 DebugPrintf (_T("%d. %s\n"), i, argv[i]);
1562 }
1563 DebugPrintf (_T("]\n"));
1564 #endif
1565
1566 InitLocale ();
1567
1568 /* get default input and output console handles */
1569 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1570 hIn = GetStdHandle (STD_INPUT_HANDLE);
1571
1572 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1573 for you can change the EnvirommentVariable for prompt before cmd start
1574 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1575 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1576 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer, sizeof(lpBuffer) / sizeof(lpBuffer[0])) == 0)
1577 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1578
1579
1580 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1581 {
1582 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1583 ExitProcess(0);
1584 }
1585 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1586
1587 #ifdef INCLUDE_CMD_CHDIR
1588 InitLastPath ();
1589 #endif
1590
1591 #ifdef FATURE_ALIASES
1592 InitializeAlias ();
1593 #endif
1594
1595 if (argc >= 2)
1596 {
1597 for (i = 1; i < argc; i++)
1598 {
1599 if (!_tcsicmp (argv[i], _T("/p")))
1600 {
1601 if (!IsExistingFile (_T("\\autoexec.bat")))
1602 {
1603 #ifdef INCLUDE_CMD_DATE
1604 cmd_date (_T(""), _T(""));
1605 #endif
1606 #ifdef INCLUDE_CMD_TIME
1607 cmd_time (_T(""), _T(""));
1608 #endif
1609 }
1610 else
1611 {
1612 ParseCommandLine (_T("\\autoexec.bat"));
1613 }
1614 bCanExit = FALSE;
1615 }
1616 else if (!_tcsicmp (argv[i], _T("/c")))
1617 {
1618 /* This just runs a program and exits */
1619 ++i;
1620 if (i < argc)
1621 {
1622 _tcscpy (commandline, argv[i]);
1623 while (++i < argc)
1624 {
1625 _tcscat (commandline, _T(" "));
1626 _tcscat (commandline, argv[i]);
1627 }
1628
1629 ParseCommandLine(commandline);
1630 ExitProcess (ProcessInput (TRUE));
1631 }
1632 else
1633 {
1634 ExitProcess (0);
1635 }
1636 }
1637 else if (!_tcsicmp (argv[i], _T("/k")))
1638 {
1639 /* This just runs a program and remains */
1640 ++i;
1641 if (i < argc)
1642 {
1643 _tcscpy (commandline, _T("\""));
1644 _tcscat (commandline, argv[i]);
1645 _tcscat (commandline, _T("\""));
1646 while (++i < argc)
1647 {
1648 _tcscat (commandline, _T(" "));
1649 _tcscat (commandline, argv[i]);
1650 }
1651 ParseCommandLine(commandline);
1652 }
1653 }
1654 #ifdef INCLUDE_CMD_COLOR
1655 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1656 {
1657 /* process /t (color) argument */
1658 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1659 wColor = wDefColor;
1660 SetScreenColor (wColor, TRUE);
1661 }
1662 #endif
1663 }
1664 }
1665
1666 /* run cmdstart.bat */
1667 if (IsExistingFile (_T("cmdstart.bat")))
1668 {
1669 ParseCommandLine (_T("cmdstart.bat"));
1670 }
1671 else if (IsExistingFile (_T("\\cmdstart.bat")))
1672 {
1673 ParseCommandLine (_T("\\cmdstart.bat"));
1674 }
1675
1676 #ifdef FEATURE_DIR_STACK
1677 /* initialize directory stack */
1678 InitDirectoryStack ();
1679 #endif
1680
1681
1682 #ifdef FEATURE_HISTORY
1683 /*initialize history*/
1684 InitHistory();
1685 #endif
1686
1687 /* Set COMSPEC environment variable */
1688 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1689 {
1690 ModuleName[_MAX_PATH] = _T('\0');
1691 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1692 }
1693
1694 /* add ctrl break handler */
1695 AddBreakHandler ();
1696 }
1697
1698
1699 static VOID Cleanup (int argc, TCHAR *argv[])
1700 {
1701 /* run cmdexit.bat */
1702 if (IsExistingFile (_T("cmdexit.bat")))
1703 {
1704 ConErrResPuts(STRING_CMD_ERROR5);
1705
1706 ParseCommandLine (_T("cmdexit.bat"));
1707 }
1708 else if (IsExistingFile (_T("\\cmdexit.bat")))
1709 {
1710 ConErrResPuts (STRING_CMD_ERROR5);
1711 ParseCommandLine (_T("\\cmdexit.bat"));
1712 }
1713
1714 #ifdef FEATURE_ALIASES
1715 DestroyAlias ();
1716 #endif
1717
1718 #ifdef FEATURE_DIECTORY_STACK
1719 /* destroy directory stack */
1720 DestroyDirectoryStack ();
1721 #endif
1722
1723 #ifdef INCLUDE_CMD_CHDIR
1724 FreeLastPath ();
1725 #endif
1726
1727 #ifdef FEATURE_HISTORY
1728 CleanHistory();
1729 #endif
1730
1731
1732 /* remove ctrl break handler */
1733 RemoveBreakHandler ();
1734 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1735 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1736
1737 if (NtDllModule != NULL)
1738 {
1739 FreeLibrary(NtDllModule);
1740 }
1741 }
1742
1743 /*
1744 * main function
1745 */
1746 #ifdef _UNICODE
1747 int _main(void)
1748 #else
1749 int _main (int argc, char *argv[])
1750 #endif
1751 {
1752 TCHAR startPath[MAX_PATH];
1753 CONSOLE_SCREEN_BUFFER_INFO Info;
1754 INT nExitCode;
1755 #ifdef _UNICODE
1756 PWCHAR * argv;
1757 int argc=0;
1758 argv = CommandLineToArgvW(GetCommandLineW(), &argc);
1759 #endif
1760
1761 GetCurrentDirectory(MAX_PATH,startPath);
1762 _tchdir(startPath);
1763
1764 SetFileApisToOEM();
1765 InputCodePage= 0;
1766 OutputCodePage = 0;
1767
1768 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1769 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1770 OPEN_EXISTING, 0, NULL);
1771 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1772 {
1773 ConErrFormatMessage(GetLastError());
1774 return(1);
1775 }
1776 wColor = Info.wAttributes;
1777 wDefColor = wColor;
1778
1779 InputCodePage= GetConsoleCP();
1780 OutputCodePage = GetConsoleOutputCP();
1781 CMD_ModuleHandle = GetModuleHandle(NULL);
1782
1783 /* check switches on command-line */
1784 Initialize(argc, argv);
1785
1786 /* call prompt routine */
1787 nExitCode = ProcessInput(FALSE);
1788
1789 /* do the cleanup */
1790 Cleanup(argc, argv);
1791
1792 return(nExitCode);
1793 }
1794
1795 /* EOF */