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