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