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