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