- Fixed the compilation as unicode.
[reactos.git] / reactos / subsys / system / cmd / cmd.c
1 /* $Id: cmd.c,v 1.19 2004/08/22 20:47:20 hbirr Exp $
2 *
3 * CMD.C - command-line interface.
4 *
5 *
6 * History:
7 *
8 * 17 Jun 1994 (Tim Norman)
9 * started.
10 *
11 * 08 Aug 1995 (Matt Rains)
12 * I have cleaned up the source code. changes now bring this source
13 * into guidelines for recommended programming practice.
14 *
15 * A added the the standard FreeDOS GNU licence test to the
16 * initialize() function.
17 *
18 * Started to replace puts() with printf(). this will help
19 * standardize output. please follow my lead.
20 *
21 * I have added some constants to help making changes easier.
22 *
23 * 15 Dec 1995 (Tim Norman)
24 * major rewrite of the code to make it more efficient and add
25 * redirection support (finally!)
26 *
27 * 06 Jan 1996 (Tim Norman)
28 * finished adding redirection support! Changed to use our own
29 * exec code (MUCH thanks to Svante Frey!!)
30 *
31 * 29 Jan 1996 (Tim Norman)
32 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
33 * suggestion of Steffan Kaiser
34 *
35 * changed "file not found" error message to "bad command or
36 * filename" thanks to Dustin Norman for noticing that confusing
37 * message!
38 *
39 * changed the format to call internal commands (again) so that if
40 * they want to split their commands, they can do it themselves
41 * (none of the internal functions so far need that much power, anyway)
42 *
43 * 27 Aug 1996 (Tim Norman)
44 * added in support for Oliver Mueller's ALIAS command
45 *
46 * 14 Jun 1997 (Steffan Kaiser)
47 * added ctrl-break handling and error level
48 *
49 * 16 Jun 1998 (Rob Lake)
50 * Runs command.com if /P is specified in command line. Command.com
51 * also stays permanent. If /C is in the command line, starts the
52 * program next in the line.
53 *
54 * 21 Jun 1998 (Rob Lake)
55 * Fixed up /C so that arguments for the program
56 *
57 * 08-Jul-1998 (John P. Price)
58 * Now sets COMSPEC environment variable
59 * misc clean up and optimization
60 * added date and time commands
61 * changed to using spawnl instead of exec. exec does not copy the
62 * environment to the child process!
63 *
64 * 14 Jul 1998 (Hans B Pufal)
65 * Reorganised source to be more efficient and to more closely
66 * follow MS-DOS conventions. (eg %..% environment variable
67 * replacement works form command line as well as batch file.
68 *
69 * New organisation also properly support nested batch files.
70 *
71 * New command table structure is half way towards providing a
72 * system in which COMMAND will find out what internal commands
73 * are loaded
74 *
75 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
76 * Fixed return value when called with /C option
77 *
78 * 27 Jul 1998 John P. Price
79 * added config.h include
80 *
81 * 28 Jul 1998 John P. Price
82 * added showcmds function to show commands and options available
83 *
84 * 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
85 * Fixed carrage return output to better match MSDOS with echo
86 * on or off. (marked with "JPP 19980708")
87 *
88 * 07-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
89 * First ReactOS release.
90 * Extended length of commandline buffers to 512.
91 *
92 * 13-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
93 * Added COMSPEC environment variable.
94 * Added "/t" support (color) on cmd command line.
95 *
96 * 07-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
97 * Added help text ("cmd /?").
98 *
99 * 25-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
100 * Unicode and redirection safe!
101 * Fixed redirections and piping.
102 * Piping is based on temporary files, but basic support
103 * for anonymous pipes already exists.
104 *
105 * 27-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
106 * Replaced spawnl() by CreateProcess().
107 *
108 * 22-Oct-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
109 * Added break handler.
110 *
111 * 15-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
112 * Fixed current directory
113 *
114 * 28-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
115 * Restore window title after program/batch execution
116 *
117 * 03-Feb-2001 (Eric Kohl <ekohl@rz-online.de>)
118 * Workaround because argc[0] is NULL under ReactOS
119 *
120 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
121 * %envvar% replacement conflicted with for.
122 *
123 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
124 * Make MakeSureDirectoryPathExistsEx unicode safe.
125 *
126 * 28-Mai-2004 (Hartmut Birr)
127 * Removed MakeSureDirectoryPathExistsEx.
128 * Use the current directory if GetTempPath fails.
129 *
130 * 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
131 * Added ShellExecute call when all else fails to be able to "launch" any file.
132 */
133
134 #include "config.h"
135
136 #include "precomp.h"
137 #include <tchar.h>
138 #include <string.h>
139 #include <stdlib.h>
140 #include <ctype.h>
141 #include <stdio.h>
142 #include <winnt.h>
143 #include <winternl.h>
144
145 #ifndef NT_SUCCESS
146 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
147 #endif
148
149 #include "batch.h"
150
151 #include <shellapi.h>
152
153 typedef NTSTATUS (STDCALL *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
154 PVOID, ULONG, PULONG);
155 typedef NTSTATUS (STDCALL *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
156
157 BOOL bExit = FALSE; /* indicates EXIT was typed */
158 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
159 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
160 BOOL bIgnoreEcho = FALSE; /* Ignore 'newline' before 'cls' */
161 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
162 BOOL bChildProcessRunning = FALSE;
163 DWORD dwChildProcessId = 0;
164 OSVERSIONINFO osvi;
165 HANDLE hIn;
166 HANDLE hOut;
167 HANDLE hConsole;
168
169 static NtQueryInformationProcessProc NtQueryInformationProcessPtr;
170 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr;
171 static BOOL NtDllChecked = FALSE;
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 HMODULE NtDllModule;
198
199 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
200 build process. So don't link implicitly against ntdll.dll, load it
201 dynamically instead */
202 if (! NtDllChecked)
203 {
204 NtDllChecked = TRUE;
205 NtDllModule = LoadLibrary(_T("ntdll.dll"));
206 if (NULL == NtDllModule)
207 {
208 /* Probably non-WinNT system. Just wait for the commands
209 to finish. */
210 NtQueryInformationProcessPtr = NULL;
211 NtReadVirtualMemoryPtr = NULL;
212 return TRUE;
213 }
214 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)
215 GetProcAddress(NtDllModule, "NtQueryInformationProcess");
216 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)
217 GetProcAddress(NtDllModule, "NtReadVirtualMemory");
218 }
219
220 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
221 {
222 return TRUE;
223 }
224
225 Status = NtQueryInformationProcessPtr(Process, ProcessBasicInformation,
226 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
227 if (! NT_SUCCESS(Status))
228 {
229 #ifdef _DEBUG
230 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status);
231 #endif
232 return TRUE;
233 }
234 Status = NtReadVirtualMemoryPtr(Process, Info.PebBaseAddress, &ProcessPeb,
235 sizeof(PEB), &BytesRead);
236 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
237 {
238 #ifdef _DEBUG
239 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status, BytesRead);
240 #endif
241 return TRUE;
242 }
243
244 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubSystem;
245 }
246
247
248
249 #ifdef _UNICODE
250 #define SHELLEXECUTETEXT "ShellExecuteW"
251 #else
252 #define SHELLEXECUTETEXT "ShellExecuteA"
253 #endif
254
255 typedef HINSTANCE (WINAPI *MYEX)(
256 HWND hwnd,
257 LPCTSTR lpOperation,
258 LPCTSTR lpFile,
259 LPCTSTR lpParameters,
260 LPCTSTR lpDirectory,
261 INT nShowCmd
262 );
263
264
265
266 static BOOL RunFile(LPTSTR filename)
267 {
268 HMODULE hShell32;
269 MYEX hShExt;
270 HINSTANCE ret;
271
272 #ifdef _DEBUG
273 DebugPrintf (_T("RunFile(%s)\n"), filename);
274 #endif
275 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
276 if (!hShell32)
277 {
278 #ifdef _DEBUG
279 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
280 #endif
281 return FALSE;
282 }
283
284 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
285 if (!hShExt)
286 {
287 #ifdef _DEBUG
288 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
289 #endif
290 FreeLibrary(hShell32);
291 return FALSE;
292 }
293
294 #ifdef _DEBUG
295 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt);
296 #endif
297
298 ret = (hShExt)(NULL, _T("open"), filename, NULL, NULL, SW_SHOWNORMAL);
299
300 #ifdef _DEBUG
301 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD)ret);
302 #endif
303
304 FreeLibrary(hShell32);
305 return (((DWORD)ret) > 32);
306 }
307
308
309
310 /*
311 * This command (in first) was not found in the command table
312 *
313 * first - first word on command line
314 * rest - rest of command line
315 */
316
317 static VOID
318 Execute (LPTSTR full, LPTSTR first, LPTSTR rest)
319 {
320 TCHAR szFullName[MAX_PATH];
321 #ifndef __REACTOS__
322 TCHAR szWindowTitle[MAX_PATH];
323 #endif
324 DWORD dwExitCode = 0;
325
326 #ifdef _DEBUG
327 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first, rest);
328 #endif
329
330 /* check for a drive change */
331 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
332 {
333 BOOL working = TRUE;
334 if (!SetCurrentDirectory(first))
335 /* Guess they changed disc or something, handle that gracefully and get to root */
336 {
337 TCHAR str[4];
338 str[0]=first[0];
339 str[1]=_T(':');
340 str[2]=_T('\\');
341 str[3]=0;
342 working = SetCurrentDirectory(str);
343 }
344
345 if (!working) ConErrPuts (INVALIDDRIVE);
346
347 return;
348 }
349
350 /* get the PATH environment variable and parse it */
351 /* search the PATH environment variable for the binary */
352 if (!SearchForExecutable (first, szFullName))
353 {
354 error_bad_command ();
355 return;
356 }
357
358 #ifndef __REACTOS__
359 GetConsoleTitle (szWindowTitle, MAX_PATH);
360 #endif
361
362 /* check if this is a .BAT or .CMD file */
363 if (!_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".bat")) ||
364 !_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".cmd")))
365 {
366 #ifdef _DEBUG
367 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName, rest);
368 #endif
369 Batch (szFullName, first, rest);
370 }
371 else
372 {
373 /* exec the program */
374 PROCESS_INFORMATION prci;
375 STARTUPINFO stui;
376
377 #ifdef _DEBUG
378 DebugPrintf (_T("[EXEC: %s %s]\n"), full, rest);
379 #endif
380 /* build command line for CreateProcess() */
381
382 /* fill startup info */
383 memset (&stui, 0, sizeof (STARTUPINFO));
384 stui.cb = sizeof (STARTUPINFO);
385 stui.dwFlags = STARTF_USESHOWWINDOW;
386 stui.wShowWindow = SW_SHOWDEFAULT;
387
388 // return console to standard mode
389 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE),
390 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
391
392 if (CreateProcess (szFullName,
393 full,
394 NULL,
395 NULL,
396 TRUE,
397 CREATE_NEW_PROCESS_GROUP,
398 NULL,
399 NULL,
400 &stui,
401 &prci))
402 {
403 if (IsConsoleProcess(prci.hProcess))
404 {
405 /* FIXME: Protect this with critical section */
406 bChildProcessRunning = TRUE;
407 dwChildProcessId = prci.dwProcessId;
408
409 WaitForSingleObject (prci.hProcess, INFINITE);
410
411 /* FIXME: Protect this with critical section */
412 bChildProcessRunning = FALSE;
413
414 GetExitCodeProcess (prci.hProcess, &dwExitCode);
415 nErrorLevel = (INT)dwExitCode;
416 }
417 CloseHandle (prci.hThread);
418 CloseHandle (prci.hProcess);
419 }
420 else
421 {
422 #ifdef _DEBUG
423 DebugPrintf (_T("[ShellExecute: %s]\n"), full);
424 #endif
425 // See if we can run this with ShellExecute() ie myfile.xls
426 if (!RunFile(full))
427 {
428 #ifdef _DEBUG
429 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full);
430 #endif
431 error_bad_command ();
432 }
433 }
434 // restore console mode
435 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
436 ENABLE_PROCESSED_INPUT );
437 }
438
439 #ifndef __REACTOS__
440 SetConsoleTitle (szWindowTitle);
441 #endif
442 }
443
444
445 /*
446 * look through the internal commands and determine whether or not this
447 * command is one of them. If it is, call the command. If not, call
448 * execute to run it as an external program.
449 *
450 * line - the command line of the program to run
451 *
452 */
453
454 static VOID
455 DoCommand (LPTSTR line)
456 {
457 TCHAR com[CMDLINE_LENGTH]; /* the first word in the command */
458 LPTSTR cp = com;
459 LPTSTR cstart;
460 LPTSTR rest; /* pointer to the rest of the command line */
461 INT cl;
462 LPCOMMAND cmdptr;
463
464 #ifdef _DEBUG
465 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line);
466 #endif /* DEBUG */
467
468 /* Skip over initial white space */
469 while (_istspace (*line))
470 line++;
471 rest = line;
472
473 cstart = rest;
474
475 /* Anything to do ? */
476 if (*rest)
477 {
478 if (*rest == _T('"'))
479 {
480 /* treat quoted words specially */
481
482 rest++;
483
484 while(*rest != _T('\0') && *rest != _T('"'))
485 *cp++ = _totlower (*rest++);
486 if (*rest == _T('"'))
487 rest++;
488 }
489 else
490 {
491 while (!IsDelimiter (*rest))
492 *cp++ = _totlower (*rest++);
493 }
494
495
496 /* Terminate first word */
497 *cp = _T('\0');
498
499 /* commands are limited to MAX_PATH */
500 if(_tcslen(com) > MAX_PATH)
501 {
502 error_bad_command();
503 return;
504 }
505
506 /* Skip over whitespace to rest of line */
507 while (_istspace (*rest))
508 rest++;
509
510 /* Scan internal command table */
511 for (cmdptr = cmds;; cmdptr++)
512 {
513 /* If end of table execute ext cmd */
514 if (cmdptr->name == NULL)
515 {
516 Execute (line, com, rest);
517 break;
518 }
519
520 if (!_tcscmp (com, cmdptr->name))
521 {
522 cmdptr->func (com, rest);
523 break;
524 }
525
526 /* The following code handles the case of commands like CD which
527 * are recognised even when the command name and parameter are
528 * not space separated.
529 *
530 * e.g dir..
531 * cd\freda
532 */
533
534 /* Get length of command name */
535 cl = _tcslen (cmdptr->name);
536
537 if ((cmdptr->flags & CMD_SPECIAL) &&
538 (!_tcsncmp (cmdptr->name, com, cl)) &&
539 (_tcschr (_T("\\.-"), *(com + cl))))
540 {
541 /* OK its one of the specials...*/
542
543 /* Terminate first word properly */
544 com[cl] = _T('\0');
545
546 /* Call with new rest */
547 cmdptr->func (com, cstart + cl);
548 break;
549 }
550 }
551 }
552 }
553
554
555 /*
556 * process the command line and execute the appropriate functions
557 * full input/output redirection and piping are supported
558 */
559
560 VOID ParseCommandLine (LPTSTR cmd)
561 {
562 TCHAR cmdline[CMDLINE_LENGTH];
563 LPTSTR s;
564 #ifdef FEATURE_REDIRECTION
565 TCHAR in[CMDLINE_LENGTH] = _T("");
566 TCHAR out[CMDLINE_LENGTH] = _T("");
567 TCHAR err[CMDLINE_LENGTH] = _T("");
568 TCHAR szTempPath[MAX_PATH] = _T(".\\");
569 TCHAR szFileName[2][MAX_PATH] = {_T(""), _T("")};
570 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
571 LPTSTR t = NULL;
572 INT num = 0;
573 INT nRedirFlags = 0;
574 INT Length;
575 UINT Attributes;
576
577 HANDLE hOldConIn;
578 HANDLE hOldConOut;
579 HANDLE hOldConErr;
580 #endif /* FEATURE_REDIRECTION */
581
582 _tcscpy (cmdline, cmd);
583 s = &cmdline[0];
584
585 #ifdef _DEBUG
586 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s);
587 #endif /* DEBUG */
588
589 #ifdef FEATURE_ALIASES
590 /* expand all aliases */
591 ExpandAlias (s, CMDLINE_LENGTH);
592 #endif /* FEATURE_ALIAS */
593
594 #ifdef FEATURE_REDIRECTION
595 /* find the temp path to store temporary files */
596 Length = GetTempPath (MAX_PATH, szTempPath);
597 if (Length > 0 && Length < MAX_PATH)
598 {
599 Attributes = GetFileAttributes(szTempPath);
600 if (Attributes == 0xffffffff ||
601 !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
602 {
603 Length = 0;
604 }
605 }
606 if (Length == 0 || Length >= MAX_PATH)
607 {
608 _tcscpy(szTempPath, _T(".\\"));
609 }
610 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
611 _tcscat (szTempPath, _T("\\"));
612
613 /* get the redirections from the command line */
614 num = GetRedirection (s, in, out, err, &nRedirFlags);
615
616 /* more efficient, but do we really need to do this? */
617 for (t = in; _istspace (*t); t++)
618 ;
619 _tcscpy (in, t);
620
621 for (t = out; _istspace (*t); t++)
622 ;
623 _tcscpy (out, t);
624
625 for (t = err; _istspace (*t); t++)
626 ;
627 _tcscpy (err, t);
628
629 /* Set up the initial conditions ... */
630 /* preserve STDIN, STDOUT and STDERR handles */
631 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
632 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
633 hOldConErr = GetStdHandle (STD_ERROR_HANDLE);
634
635 /* redirect STDIN */
636 if (in[0])
637 {
638 HANDLE hFile;
639 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
640
641 hFile = CreateFile (in, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
642 FILE_ATTRIBUTE_NORMAL, NULL);
643 if (hFile == INVALID_HANDLE_VALUE)
644 {
645 ConErrPrintf (_T("Can't redirect input from file %s\n"), in);
646 return;
647 }
648
649 if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
650 {
651 ConErrPrintf (_T("Can't redirect input from file %s\n"), in);
652 return;
653 }
654 #ifdef _DEBUG
655 DebugPrintf (_T("Input redirected from: %s\n"), in);
656 #endif
657 }
658
659 /* Now do all but the last pipe command */
660 *szFileName[0] = _T('\0');
661 hFile[0] = INVALID_HANDLE_VALUE;
662
663 while (num-- > 1)
664 {
665 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
666
667 /* Create unique temporary file name */
668 GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
669
670 /* Set current stdout to temporary file */
671 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
672 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
673
674 if (hFile[1] == INVALID_HANDLE_VALUE){
675 ConErrPrintf (_T("Error creating temporary file for pipe data\n"));
676 return;
677 }
678
679 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
680
681 DoCommand (s);
682
683 /* close stdout file */
684 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
685 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
686 {
687 CloseHandle (hFile[1]);
688 hFile[1] = INVALID_HANDLE_VALUE;
689 }
690
691 /* close old stdin file */
692 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
693 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
694 {
695 /* delete old stdin file, if it is a real file */
696 CloseHandle (hFile[0]);
697 hFile[0] = INVALID_HANDLE_VALUE;
698 DeleteFile (szFileName[0]);
699 *szFileName[0] = _T('\0');
700 }
701
702 /* copy stdout file name to stdin file name */
703 _tcscpy (szFileName[0], szFileName[1]);
704 *szFileName[1] = _T('\0');
705
706 /* open new stdin file */
707 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
708 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
709 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
710
711 s = s + _tcslen (s) + 1;
712 }
713
714 /* Now set up the end conditions... */
715 /* redirect STDOUT */
716 if (out[0])
717 {
718 /* Final output to here */
719 HANDLE hFile;
720 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
721
722 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_READ, &sa,
723 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
724 FILE_ATTRIBUTE_NORMAL, NULL);
725 if (hFile == INVALID_HANDLE_VALUE)
726 {
727 ConErrPrintf (_T("Can't redirect to file %s\n"), out);
728 return;
729 }
730
731 if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
732 {
733 ConErrPrintf (_T("Can't redirect to file %s\n"), out);
734 return;
735 }
736
737 if (nRedirFlags & OUTPUT_APPEND)
738 {
739 LONG lHighPos = 0;
740
741 if (GetFileType (hFile) == FILE_TYPE_DISK)
742 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
743 }
744 #ifdef _DEBUG
745 DebugPrintf (_T("Output redirected to: %s\n"), out);
746 #endif
747 }
748 else if (hOldConOut != INVALID_HANDLE_VALUE)
749 {
750 /* Restore original stdout */
751 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
752 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
753 if (hOldConOut != hOut)
754 CloseHandle (hOut);
755 hOldConOut = INVALID_HANDLE_VALUE;
756 }
757
758 /* redirect STDERR */
759 if (err[0])
760 {
761 /* Final output to here */
762 HANDLE hFile;
763 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
764
765 if (!_tcscmp (err, out))
766 {
767 #ifdef _DEBUG
768 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
769 #endif
770 DuplicateHandle (GetCurrentProcess (),
771 GetStdHandle (STD_OUTPUT_HANDLE),
772 GetCurrentProcess (),
773 &hFile, 0, TRUE, DUPLICATE_SAME_ACCESS);
774 }
775 else
776 {
777 hFile = CreateFile (err,
778 GENERIC_WRITE,
779 0,
780 &sa,
781 (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
782 FILE_ATTRIBUTE_NORMAL,
783 NULL);
784 if (hFile == INVALID_HANDLE_VALUE)
785 {
786 ConErrPrintf (_T("Can't redirect to file %s\n"), err);
787 return;
788 }
789 }
790 if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
791 {
792 ConErrPrintf (_T("Can't redirect to file %s\n"), err);
793 return;
794 }
795
796 if (nRedirFlags & ERROR_APPEND)
797 {
798 LONG lHighPos = 0;
799
800 if (GetFileType (hFile) == FILE_TYPE_DISK)
801 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
802 }
803 #ifdef _DEBUG
804 DebugPrintf (_T("Error redirected to: %s\n"), err);
805 #endif
806 }
807 else if (hOldConErr != INVALID_HANDLE_VALUE)
808 {
809 /* Restore original stderr */
810 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
811 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
812 if (hOldConErr != hErr)
813 CloseHandle (hErr);
814 hOldConErr = INVALID_HANDLE_VALUE;
815 }
816 #endif
817
818 /* process final command */
819 DoCommand (s);
820
821 #ifdef FEATURE_REDIRECTION
822 /* close old stdin file */
823 #if 0 /* buggy implementation */
824 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
825 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
826 (hFile[0] != hOldConIn))
827 {
828 /* delete old stdin file, if it is a real file */
829 CloseHandle (hFile[0]);
830 hFile[0] = INVALID_HANDLE_VALUE;
831 DeleteFile (szFileName[0]);
832 *szFileName[0] = _T('\0');
833 }
834
835 /* Restore original STDIN */
836 if (hOldConIn != INVALID_HANDLE_VALUE)
837 {
838 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
839 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
840 if (hOldConIn != hIn)
841 CloseHandle (hIn);
842 hOldConIn = INVALID_HANDLE_VALUE;
843 }
844 else
845 {
846 #ifdef _DEBUG
847 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out);
848 #endif
849 }
850 #endif /* buggy implementation */
851
852
853 if (hOldConIn != INVALID_HANDLE_VALUE)
854 {
855 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
856 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
857 if (hIn == INVALID_HANDLE_VALUE)
858 {
859 #ifdef _DEBUG
860 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
861 #endif
862 }
863 else
864 {
865 if (GetFileType (hIn) == FILE_TYPE_DISK)
866 {
867 if (hFile[0] == hIn)
868 {
869 CloseHandle (hFile[0]);
870 hFile[0] = INVALID_HANDLE_VALUE;
871 DeleteFile (szFileName[0]);
872 *szFileName[0] = _T('\0');
873 }
874 else
875 {
876 #ifdef _DEBUG
877 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
878 #endif
879 }
880 }
881 }
882 }
883
884
885 /* Restore original STDOUT */
886 if (hOldConOut != INVALID_HANDLE_VALUE)
887 {
888 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
889 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
890 if (hOldConOut != hOut)
891 CloseHandle (hOut);
892 hOldConOut = INVALID_HANDLE_VALUE;
893 }
894
895 /* Restore original STDERR */
896 if (hOldConErr != INVALID_HANDLE_VALUE)
897 {
898 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
899 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
900 if (hOldConErr != hErr)
901 CloseHandle (hErr);
902 hOldConErr = INVALID_HANDLE_VALUE;
903 }
904 #endif /* FEATURE_REDIRECTION */
905 }
906
907
908 /*
909 * do the prompt/input/process loop
910 *
911 */
912
913 static INT
914 ProcessInput (BOOL bFlag)
915 {
916 TCHAR commandline[CMDLINE_LENGTH];
917 TCHAR readline[CMDLINE_LENGTH];
918 LPTSTR tp = NULL;
919 LPTSTR ip;
920 LPTSTR cp;
921 BOOL bEchoThisLine;
922
923 do
924 {
925 /* if no batch input then... */
926 if (!(ip = ReadBatchLine (&bEchoThisLine)))
927 {
928 if (bFlag)
929 return 0;
930
931 ReadCommand (readline, CMDLINE_LENGTH);
932 ip = readline;
933 bEchoThisLine = FALSE;
934 }
935
936 cp = commandline;
937 while (*ip)
938 {
939 if (*ip == _T('%'))
940 {
941 switch (*++ip)
942 {
943 case _T('%'):
944 *cp++ = *ip++;
945 break;
946
947 case _T('0'):
948 case _T('1'):
949 case _T('2'):
950 case _T('3'):
951 case _T('4'):
952 case _T('5'):
953 case _T('6'):
954 case _T('7'):
955 case _T('8'):
956 case _T('9'):
957 if ((tp = FindArg (*ip - _T('0'))))
958 {
959 cp = _stpcpy (cp, tp);
960 ip++;
961 }
962 else
963 *cp++ = _T('%');
964 break;
965
966 case _T('?'):
967 cp += _stprintf (cp, _T("%u"), nErrorLevel);
968 ip++;
969 break;
970
971 default:
972 tp = _tcschr(ip, _T('%'));
973 if ((tp != NULL) &&
974 (tp <= _tcschr(ip, _T(' ')) - 1))
975 {
976 TCHAR evar[512];
977 *tp = _T('\0');
978
979 /* FIXME: This is just a quick hack!! */
980 /* Do a proper memory allocation!! */
981 if (GetEnvironmentVariable (ip, evar, 512))
982 cp = _stpcpy (cp, evar);
983
984 ip = tp + 1;
985 }
986 else
987 {
988 *cp++ = _T('%');
989 }
990 break;
991 }
992 continue;
993 }
994
995 if (_istcntrl (*ip))
996 *ip = _T(' ');
997 *cp++ = *ip++;
998 }
999
1000 *cp = _T('\0');
1001
1002 /* strip trailing spaces */
1003 while ((--cp >= commandline) && _istspace (*cp));
1004
1005 *(cp + 1) = _T('\0');
1006
1007 /* JPP 19980807 */
1008 /* Echo batch file line */
1009 if (bEchoThisLine)
1010 {
1011 PrintPrompt ();
1012 ConOutPuts (commandline);
1013 }
1014
1015 if (*commandline)
1016 {
1017 ParseCommandLine (commandline);
1018 if (bEcho && !bIgnoreEcho)
1019 ConOutChar ('\n');
1020 bIgnoreEcho = FALSE;
1021 }
1022 }
1023 while (!bCanExit || !bExit);
1024
1025 return 0;
1026 }
1027
1028
1029 /*
1030 * control-break handler.
1031 */
1032 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1033 {
1034 if ((dwCtrlType != CTRL_C_EVENT) &&
1035 (dwCtrlType != CTRL_BREAK_EVENT))
1036 return FALSE;
1037
1038 if (bChildProcessRunning == TRUE)
1039 {
1040 GenerateConsoleCtrlEvent (CTRL_C_EVENT,
1041 dwChildProcessId);
1042 return TRUE;
1043 }
1044
1045 /* FIXME: Handle batch files */
1046
1047 /* FIXME: Print "^C" */
1048
1049
1050 return TRUE;
1051 }
1052
1053
1054 VOID AddBreakHandler (VOID)
1055 {
1056 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1057 }
1058
1059
1060 VOID RemoveBreakHandler (VOID)
1061 {
1062 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1063 }
1064
1065
1066 /*
1067 * show commands and options that are available.
1068 *
1069 */
1070 #if 0
1071 static VOID
1072 ShowCommands (VOID)
1073 {
1074 /* print command list */
1075 ConOutPrintf (_T("\nInternal commands available:\n"));
1076 PrintCommandList ();
1077
1078 /* print feature list */
1079 ConOutPuts (_T("\nFeatures available:"));
1080 #ifdef FEATURE_ALIASES
1081 ConOutPuts (_T(" [aliases]"));
1082 #endif
1083 #ifdef FEATURE_HISTORY
1084 ConOutPuts (_T(" [history]"));
1085 #endif
1086 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1087 ConOutPuts (_T(" [unix filename completion]"));
1088 #endif
1089 #ifdef FEATURE_DIRECTORY_STACK
1090 ConOutPuts (_T(" [directory stack]"));
1091 #endif
1092 #ifdef FEATURE_REDIRECTION
1093 ConOutPuts (_T(" [redirections and piping]"));
1094 #endif
1095 ConOutChar (_T('\n'));
1096 }
1097 #endif
1098
1099 /*
1100 * set up global initializations and process parameters
1101 *
1102 * argc - number of parameters to command.com
1103 * argv - command-line parameters
1104 *
1105 */
1106 static VOID
1107 Initialize (int argc, TCHAR* argv[])
1108 {
1109 TCHAR commandline[CMDLINE_LENGTH];
1110 TCHAR ModuleName[_MAX_PATH + 1];
1111 INT i;
1112 //INT len;
1113 //TCHAR *ptr, *cmdLine;
1114
1115
1116 #ifdef _DEBUG
1117 INT x;
1118
1119 DebugPrintf (_T("[command args:\n"));
1120 for (x = 0; x < argc; x++)
1121 {
1122 DebugPrintf (_T("%d. %s\n"), x, argv[x]);
1123 }
1124 DebugPrintf (_T("]\n"));
1125 #endif
1126
1127 /* get version information */
1128 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1129 GetVersionEx (&osvi);
1130
1131 InitLocale ();
1132
1133 /* get default input and output console handles */
1134 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1135 hIn = GetStdHandle (STD_INPUT_HANDLE);
1136
1137
1138 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1139 {
1140 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
1141 "\n"
1142 "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
1143 "\n"
1144 " /C command Runs the specified command and terminates.\n"
1145 " /K command Runs the specified command and remains.\n"
1146 " /P CMD becomes permanent and runs autoexec.bat\n"
1147 " (cannot be terminated).\n"
1148 " /T:bf Sets the background/foreground color (see COLOR command)."));
1149 ExitProcess (0);
1150 }
1151 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1152
1153 #ifdef INCLUDE_CMD_CHDIR
1154 InitLastPath ();
1155 #endif
1156
1157 #ifdef FATURE_ALIASES
1158 InitializeAlias ();
1159 #endif
1160
1161 if (argc >= 2)
1162 {
1163 for (i = 1; i < argc; i++)
1164 {
1165 if (!_tcsicmp (argv[i], _T("/p")))
1166 {
1167 if (!IsValidFileName (_T("\\autoexec.bat")))
1168 {
1169 #ifdef INCLUDE_CMD_DATE
1170 cmd_date (_T(""), _T(""));
1171 #endif
1172 #ifdef INCLUDE_CMD_TIME
1173 cmd_time (_T(""), _T(""));
1174 #endif
1175 }
1176 else
1177 {
1178 ParseCommandLine (_T("\\autoexec.bat"));
1179 }
1180 bCanExit = FALSE;
1181 }
1182 else if (!_tcsicmp (argv[i], _T("/c")))
1183 {
1184 /* This just runs a program and exits */
1185 ++i;
1186 if (i < argc)
1187 {
1188 _tcscpy (commandline, argv[i]);
1189 while (++i < argc)
1190 {
1191 _tcscat (commandline, _T(" "));
1192 _tcscat (commandline, argv[i]);
1193 }
1194
1195 ParseCommandLine(commandline);
1196 ExitProcess (ProcessInput (TRUE));
1197 }
1198 else
1199 {
1200 ExitProcess (0);
1201 }
1202 }
1203 else if (!_tcsicmp (argv[i], _T("/k")))
1204 {
1205 /* This just runs a program and remains */
1206 ++i;
1207 if (i < argc)
1208 {
1209 _tcscpy (commandline, argv[i]);
1210 while (++i < argc)
1211 {
1212 _tcscat (commandline, _T(" "));
1213 _tcscat (commandline, argv[i]);
1214 }
1215
1216 ParseCommandLine(commandline);
1217 }
1218 }
1219 #ifdef INCLUDE_CMD_COLOR
1220 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1221 {
1222 /* process /t (color) argument */
1223 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1224 wColor = wDefColor;
1225 SetScreenColor (wColor, TRUE);
1226 }
1227 #endif
1228 }
1229 }
1230
1231 /* run cmdstart.bat */
1232 if (IsValidFileName (_T("cmdstart.bat")))
1233 {
1234 ParseCommandLine (_T("cmdstart.bat"));
1235 }
1236 else if (IsValidFileName (_T("\\cmdstart.bat")))
1237 {
1238 ParseCommandLine (_T("\\cmdstart.bat"));
1239 }
1240 #ifndef __REACTOS__
1241 else
1242 {
1243 /* try to run cmdstart.bat from install dir */
1244 LPTSTR p;
1245
1246 _tcscpy (commandline, argv[0]);
1247 p = _tcsrchr (commandline, _T('\\')) + 1;
1248 _tcscpy (p, _T("cmdstart.bat"));
1249
1250 if (IsValidFileName (_T("commandline")))
1251 {
1252 ConErrPrintf (_T("Running %s...\n", commandline));
1253 ParseCommandLine (commandline);
1254 }
1255 }
1256 #endif
1257
1258 #ifdef FEATURE_DIR_STACK
1259 /* initialize directory stack */
1260 InitDirectoryStack ();
1261 #endif
1262
1263
1264 #ifdef FEATURE_HISTORY
1265 /*initialize history*/
1266 InitHistory();
1267 #endif
1268
1269 /* Set COMSPEC environment variable */
1270 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1271 {
1272 ModuleName[_MAX_PATH] = _T('\0');
1273 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1274 }
1275
1276 /* add ctrl break handler */
1277 AddBreakHandler ();
1278 }
1279
1280
1281 static VOID Cleanup (int argc, TCHAR *argv[])
1282 {
1283 /* run cmdexit.bat */
1284 if (IsValidFileName (_T("cmdexit.bat")))
1285 {
1286 ConErrPrintf (_T("Running cmdexit.bat...\n"));
1287 ParseCommandLine (_T("cmdexit.bat"));
1288 }
1289 else if (IsValidFileName (_T("\\cmdexit.bat")))
1290 {
1291 ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
1292 ParseCommandLine (_T("\\cmdexit.bat"));
1293 }
1294 #ifndef __REACTOS__
1295 else
1296 {
1297 /* try to run cmdexit.bat from install dir */
1298 TCHAR commandline[CMDLINE_LENGTH];
1299 LPTSTR p;
1300
1301 _tcscpy (commandline, argv[0]);
1302 p = _tcsrchr (commandline, _T('\\')) + 1;
1303 _tcscpy (p, _T("cmdexit.bat"));
1304
1305 if (IsValidFileName (_T("commandline")))
1306 {
1307 ConErrPrintf (_T("Running %s...\n"), commandline);
1308 ParseCommandLine (commandline);
1309 }
1310 }
1311 #endif
1312
1313 #ifdef FEATURE_ALIASES
1314 DestroyAlias ();
1315 #endif
1316
1317 #ifdef FEATURE_DIECTORY_STACK
1318 /* destroy directory stack */
1319 DestroyDirectoryStack ();
1320 #endif
1321
1322 #ifdef INCLUDE_CMD_CHDIR
1323 FreeLastPath ();
1324 #endif
1325
1326 #ifdef FEATURE_HISTORY
1327 CleanHistory();
1328 #endif
1329
1330
1331 /* remove ctrl break handler */
1332 RemoveBreakHandler ();
1333 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1334 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1335 }
1336
1337 #ifdef __REACTOS__
1338 #ifdef _UNICODE
1339 PWCHAR * _CommandLineToArgvW(PWCHAR lpCmdLine, int *pNumArgs)
1340 {
1341 PWCHAR * argvw = NULL;
1342 PWCHAR ptr = lpCmdLine;
1343 PWCHAR str;
1344 int len;
1345 int NumArgs;
1346
1347 NumArgs = 0;
1348
1349 while(lpCmdLine && *lpCmdLine)
1350 {
1351 while (iswspace(*lpCmdLine)) lpCmdLine++;
1352 if (*lpCmdLine)
1353 {
1354 if ((NumArgs % 10)==0)
1355 {
1356 PWCHAR * old_argvw = argvw;
1357 argvw = malloc((NumArgs + 10) * sizeof(PWCHAR));
1358 memcpy(argvw, old_argvw, NumArgs * sizeof(PWCHAR));
1359 free(old_argvw);
1360 }
1361 ptr = wcschr(lpCmdLine, L' ');
1362 if (ptr)
1363 {
1364 len = ptr - lpCmdLine;
1365 }
1366 else
1367 {
1368 len = wcslen(lpCmdLine);
1369 }
1370 str = malloc((len + 1) * sizeof(WCHAR));
1371 memcpy(str, lpCmdLine, len * sizeof(WCHAR));
1372 str[len] = 0;
1373 argvw[NumArgs]=str;
1374 NumArgs++;
1375 lpCmdLine = ptr;
1376 }
1377 }
1378 *pNumArgs = NumArgs;
1379 return argvw;
1380 }
1381 #endif
1382 #endif
1383
1384 /*
1385 * main function
1386 */
1387 #ifdef _UNICODE
1388 int main(void)
1389 #else
1390 int main (int argc, char *argv[])
1391 #endif
1392 {
1393 CONSOLE_SCREEN_BUFFER_INFO Info;
1394 INT nExitCode;
1395 #ifdef _UNICODE
1396 PWCHAR * argv;
1397 int argc=0;
1398 #ifdef __REACTOS__
1399 argv = _CommandLineToArgvW(GetCommandLineW(), &argc);
1400 #else
1401 argv = CommandLineToArgvW(GetCommandLineW(), &argc);
1402 #endif
1403 #endif
1404
1405 SetFileApisToOEM();
1406
1407 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1408 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1409 OPEN_EXISTING, 0, NULL);
1410 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1411 {
1412 ConOutFormatMessage(GetLastError());
1413 return(1);
1414 }
1415 wColor = Info.wAttributes;
1416 wDefColor = wColor;
1417
1418 /* check switches on command-line */
1419 Initialize(argc, argv);
1420
1421 /* call prompt routine */
1422 nExitCode = ProcessInput(FALSE);
1423
1424 /* do the cleanup */
1425 Cleanup(argc, argv);
1426
1427 return(nExitCode);
1428 }
1429
1430 /* EOF */