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