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