- Check if the temp directory exist, if not use the current directory.
[reactos.git] / reactos / subsys / system / cmd / cmd.c
1 /* $Id: cmd.c,v 1.15 2004/06/06 17:33:13 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
131 #include "config.h"
132
133 #include <windows.h>
134 #include <tchar.h>
135 #include <string.h>
136 #include <stdlib.h>
137 #include <ctype.h>
138 #include <stdio.h>
139 #include <winnt.h>
140 #include <winternl.h>
141
142 #ifndef NT_SUCCESS
143 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
144 #endif
145
146 #include "cmd.h"
147 #include "batch.h"
148
149 typedef NTSTATUS (STDCALL *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
150 PVOID, ULONG, PULONG);
151 typedef NTSTATUS (STDCALL *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
152
153 BOOL bExit = FALSE; /* indicates EXIT was typed */
154 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
155 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
156 BOOL bIgnoreEcho = FALSE; /* Ignore 'newline' before 'cls' */
157 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
158 BOOL bChildProcessRunning = FALSE;
159 DWORD dwChildProcessId = 0;
160 OSVERSIONINFO osvi;
161 HANDLE hIn;
162 HANDLE hOut;
163 HANDLE hConsole;
164
165 static NtQueryInformationProcessProc NtQueryInformationProcessPtr;
166 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr;
167 static BOOL NtDllChecked = FALSE;
168
169 #ifdef INCLUDE_CMD_COLOR
170 WORD wColor; /* current color */
171 WORD wDefColor; /* default color */
172 #endif
173
174 /*
175 * is character a delimeter when used on first word?
176 *
177 */
178
179 static BOOL IsDelimiter (TCHAR c)
180 {
181 return (c == _T('/') || c == _T('=') || c == _T('\0') || _istspace (c));
182 }
183
184 /*
185 * Is a process a console process?
186 */
187 static BOOL IsConsoleProcess(HANDLE Process)
188 {
189 NTSTATUS Status;
190 PROCESS_BASIC_INFORMATION Info;
191 PEB ProcessPeb;
192 ULONG BytesRead;
193 HMODULE NtDllModule;
194
195 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
196 build process. So don't link implicitly against ntdll.dll, load it
197 dynamically instead */
198 if (! NtDllChecked)
199 {
200 NtDllChecked = TRUE;
201 NtDllModule = LoadLibrary(_T("ntdll.dll"));
202 if (NULL == NtDllModule)
203 {
204 /* Probably non-WinNT system. Just wait for the commands
205 to finish. */
206 NtQueryInformationProcessPtr = NULL;
207 NtReadVirtualMemoryPtr = NULL;
208 return TRUE;
209 }
210 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)
211 GetProcAddress(NtDllModule, "NtQueryInformationProcess");
212 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)
213 GetProcAddress(NtDllModule, "NtReadVirtualMemory");
214 }
215
216 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
217 {
218 return TRUE;
219 }
220
221 Status = NtQueryInformationProcessPtr(Process, ProcessBasicInformation,
222 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
223 if (! NT_SUCCESS(Status))
224 {
225 #ifdef _DEBUG
226 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status);
227 #endif
228 return TRUE;
229 }
230 Status = NtReadVirtualMemoryPtr(Process, Info.PebBaseAddress, &ProcessPeb,
231 sizeof(PEB), &BytesRead);
232 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
233 {
234 #ifdef _DEBUG
235 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status, BytesRead);
236 #endif
237 return TRUE;
238 }
239
240 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubSystem;
241 }
242
243
244 /*
245 * This command (in first) was not found in the command table
246 *
247 * first - first word on command line
248 * rest - rest of command line
249 */
250
251 static VOID
252 Execute (LPTSTR full, LPTSTR first, LPTSTR rest)
253 {
254 TCHAR szFullName[MAX_PATH];
255 #ifndef __REACTOS__
256 TCHAR szWindowTitle[MAX_PATH];
257 #endif
258 DWORD dwExitCode = 0;
259
260 #ifdef _DEBUG
261 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first, rest);
262 #endif
263
264 /* check for a drive change */
265 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
266 {
267 BOOL working = TRUE;
268 if (!SetCurrentDirectory(first))
269 /* Guess they changed disc or something, handle that gracefully and get to root */
270 {
271 TCHAR str[4];
272 str[0]=first[0];
273 str[1]=_T(':');
274 str[2]=_T('\\');
275 str[3]=0;
276 working = SetCurrentDirectory(str);
277 }
278
279 if (!working) ConErrPuts (INVALIDDRIVE);
280
281 return;
282 }
283
284 /* get the PATH environment variable and parse it */
285 /* search the PATH environment variable for the binary */
286 if (!SearchForExecutable (first, szFullName))
287 {
288 error_bad_command ();
289 return;
290 }
291
292 #ifndef __REACTOS__
293 GetConsoleTitle (szWindowTitle, MAX_PATH);
294 #endif
295
296 /* check if this is a .BAT or .CMD file */
297 if (!_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".bat")) ||
298 !_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".cmd")))
299 {
300 #ifdef _DEBUG
301 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName, rest);
302 #endif
303 Batch (szFullName, first, rest);
304 }
305 else
306 {
307 /* exec the program */
308 PROCESS_INFORMATION prci;
309 STARTUPINFO stui;
310
311 #ifdef _DEBUG
312 DebugPrintf (_T("[EXEC: %s %s]\n"), full, rest);
313 #endif
314 /* build command line for CreateProcess() */
315
316 /* fill startup info */
317 memset (&stui, 0, sizeof (STARTUPINFO));
318 stui.cb = sizeof (STARTUPINFO);
319 stui.dwFlags = STARTF_USESHOWWINDOW;
320 stui.wShowWindow = SW_SHOWDEFAULT;
321
322 // return console to standard mode
323 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE),
324 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
325
326 if (CreateProcess (szFullName,
327 full,
328 NULL,
329 NULL,
330 TRUE,
331 CREATE_NEW_PROCESS_GROUP,
332 NULL,
333 NULL,
334 &stui,
335 &prci))
336 {
337 if (IsConsoleProcess(prci.hProcess))
338 {
339 /* FIXME: Protect this with critical section */
340 bChildProcessRunning = TRUE;
341 dwChildProcessId = prci.dwProcessId;
342
343 WaitForSingleObject (prci.hProcess, INFINITE);
344
345 /* FIXME: Protect this with critical section */
346 bChildProcessRunning = FALSE;
347
348 GetExitCodeProcess (prci.hProcess, &dwExitCode);
349 nErrorLevel = (INT)dwExitCode;
350 }
351 CloseHandle (prci.hThread);
352 CloseHandle (prci.hProcess);
353 }
354 else
355 {
356 ErrorMessage (GetLastError (),
357 _T("Error executing CreateProcess()!!\n"));
358 }
359 // restore console mode
360 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
361 ENABLE_PROCESSED_INPUT );
362 }
363
364 #ifndef __REACTOS__
365 SetConsoleTitle (szWindowTitle);
366 #endif
367 }
368
369
370 /*
371 * look through the internal commands and determine whether or not this
372 * command is one of them. If it is, call the command. If not, call
373 * execute to run it as an external program.
374 *
375 * line - the command line of the program to run
376 *
377 */
378
379 static VOID
380 DoCommand (LPTSTR line)
381 {
382 TCHAR com[CMDLINE_LENGTH]; /* the first word in the command */
383 LPTSTR cp = com;
384 LPTSTR cstart;
385 LPTSTR rest; /* pointer to the rest of the command line */
386 INT cl;
387 LPCOMMAND cmdptr;
388
389 #ifdef _DEBUG
390 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line);
391 #endif /* DEBUG */
392
393 /* Skip over initial white space */
394 while (_istspace (*line))
395 line++;
396 rest = line;
397
398 cstart = rest;
399
400 /* Anything to do ? */
401 if (*rest)
402 {
403 if (*rest == _T('"'))
404 {
405 /* treat quoted words specially */
406
407 rest++;
408
409 while(*rest != _T('\0') && *rest != _T('"'))
410 *cp++ = _totlower (*rest++);
411 if (*rest == _T('"'))
412 rest++;
413 }
414 else
415 {
416 while (!IsDelimiter (*rest))
417 *cp++ = _totlower (*rest++);
418 }
419
420
421 /* Terminate first word */
422 *cp = _T('\0');
423
424 /* commands are limited to MAX_PATH */
425 if(_tcslen(com) > MAX_PATH)
426 {
427 error_bad_command();
428 return;
429 }
430
431 /* Skip over whitespace to rest of line */
432 while (_istspace (*rest))
433 rest++;
434
435 /* Scan internal command table */
436 for (cmdptr = cmds;; cmdptr++)
437 {
438 /* If end of table execute ext cmd */
439 if (cmdptr->name == NULL)
440 {
441 Execute (line, com, rest);
442 break;
443 }
444
445 if (!_tcscmp (com, cmdptr->name))
446 {
447 cmdptr->func (com, rest);
448 break;
449 }
450
451 /* The following code handles the case of commands like CD which
452 * are recognised even when the command name and parameter are
453 * not space separated.
454 *
455 * e.g dir..
456 * cd\freda
457 */
458
459 /* Get length of command name */
460 cl = _tcslen (cmdptr->name);
461
462 if ((cmdptr->flags & CMD_SPECIAL) &&
463 (!_tcsncmp (cmdptr->name, com, cl)) &&
464 (_tcschr (_T("\\.-"), *(com + cl))))
465 {
466 /* OK its one of the specials...*/
467
468 /* Terminate first word properly */
469 com[cl] = _T('\0');
470
471 /* Call with new rest */
472 cmdptr->func (com, cstart + cl);
473 break;
474 }
475 }
476 }
477 }
478
479
480 /*
481 * process the command line and execute the appropriate functions
482 * full input/output redirection and piping are supported
483 */
484
485 VOID ParseCommandLine (LPTSTR cmd)
486 {
487 TCHAR cmdline[CMDLINE_LENGTH];
488 LPTSTR s;
489 #ifdef FEATURE_REDIRECTION
490 TCHAR in[CMDLINE_LENGTH] = _T("");
491 TCHAR out[CMDLINE_LENGTH] = _T("");
492 TCHAR err[CMDLINE_LENGTH] = _T("");
493 TCHAR szTempPath[MAX_PATH] = _T(".\\");
494 TCHAR szFileName[2][MAX_PATH] = {_T(""), _T("")};
495 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
496 LPTSTR t = NULL;
497 INT num = 0;
498 INT nRedirFlags = 0;
499 INT Length;
500 UINT Attributes;
501
502 HANDLE hOldConIn;
503 HANDLE hOldConOut;
504 HANDLE hOldConErr;
505 #endif /* FEATURE_REDIRECTION */
506
507 _tcscpy (cmdline, cmd);
508 s = &cmdline[0];
509
510 #ifdef _DEBUG
511 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s);
512 #endif /* DEBUG */
513
514 #ifdef FEATURE_ALIASES
515 /* expand all aliases */
516 ExpandAlias (s, CMDLINE_LENGTH);
517 #endif /* FEATURE_ALIAS */
518
519 #ifdef FEATURE_REDIRECTION
520 /* find the temp path to store temporary files */
521 Length = GetTempPath (MAX_PATH, szTempPath);
522 if (Length > 0 && Length < MAX_PATH)
523 {
524 Attributes = GetFileAttributes(szTempPath);
525 if (Attributes == 0xffffffff ||
526 !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
527 {
528 Length = 0;
529 }
530 }
531 if (Length == 0 || Length >= MAX_PATH)
532 {
533 _tcscpy(szTempPath, _T(".\\"));
534 }
535 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
536 _tcscat (szTempPath, _T("\\"));
537
538 /* get the redirections from the command line */
539 num = GetRedirection (s, in, out, err, &nRedirFlags);
540
541 /* more efficient, but do we really need to do this? */
542 for (t = in; _istspace (*t); t++)
543 ;
544 _tcscpy (in, t);
545
546 for (t = out; _istspace (*t); t++)
547 ;
548 _tcscpy (out, t);
549
550 for (t = err; _istspace (*t); t++)
551 ;
552 _tcscpy (err, t);
553
554 /* Set up the initial conditions ... */
555 /* preserve STDIN, STDOUT and STDERR handles */
556 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
557 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
558 hOldConErr = GetStdHandle (STD_ERROR_HANDLE);
559
560 /* redirect STDIN */
561 if (in[0])
562 {
563 HANDLE hFile;
564 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
565
566 hFile = CreateFile (in, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
567 FILE_ATTRIBUTE_NORMAL, NULL);
568 if (hFile == INVALID_HANDLE_VALUE)
569 {
570 ConErrPrintf (_T("Can't redirect input from file %s\n"), in);
571 return;
572 }
573
574 if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
575 {
576 ConErrPrintf (_T("Can't redirect input from file %s\n"), in);
577 return;
578 }
579 #ifdef _DEBUG
580 DebugPrintf (_T("Input redirected from: %s\n"), in);
581 #endif
582 }
583
584 /* Now do all but the last pipe command */
585 *szFileName[0] = _T('\0');
586 hFile[0] = INVALID_HANDLE_VALUE;
587
588 while (num-- > 1)
589 {
590 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
591
592 /* Create unique temporary file name */
593 GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
594
595 /* Set current stdout to temporary file */
596 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
597 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
598
599 if (hFile[1] == INVALID_HANDLE_VALUE){
600 ConErrPrintf (_T("Error creating temporary file for pipe data\n"));
601 return;
602 }
603
604 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
605
606 DoCommand (s);
607
608 /* close stdout file */
609 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
610 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
611 {
612 CloseHandle (hFile[1]);
613 hFile[1] = INVALID_HANDLE_VALUE;
614 }
615
616 /* close old stdin file */
617 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
618 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
619 {
620 /* delete old stdin file, if it is a real file */
621 CloseHandle (hFile[0]);
622 hFile[0] = INVALID_HANDLE_VALUE;
623 DeleteFile (szFileName[0]);
624 *szFileName[0] = _T('\0');
625 }
626
627 /* copy stdout file name to stdin file name */
628 _tcscpy (szFileName[0], szFileName[1]);
629 *szFileName[1] = _T('\0');
630
631 /* open new stdin file */
632 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
633 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
634 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
635
636 s = s + _tcslen (s) + 1;
637 }
638
639 /* Now set up the end conditions... */
640 /* redirect STDOUT */
641 if (out[0])
642 {
643 /* Final output to here */
644 HANDLE hFile;
645 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
646
647 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_READ, &sa,
648 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
649 FILE_ATTRIBUTE_NORMAL, NULL);
650 if (hFile == INVALID_HANDLE_VALUE)
651 {
652 ConErrPrintf (_T("Can't redirect to file %s\n"), out);
653 return;
654 }
655
656 if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
657 {
658 ConErrPrintf (_T("Can't redirect to file %s\n"), out);
659 return;
660 }
661
662 if (nRedirFlags & OUTPUT_APPEND)
663 {
664 LONG lHighPos = 0;
665
666 if (GetFileType (hFile) == FILE_TYPE_DISK)
667 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
668 }
669 #ifdef _DEBUG
670 DebugPrintf (_T("Output redirected to: %s\n"), out);
671 #endif
672 }
673 else if (hOldConOut != INVALID_HANDLE_VALUE)
674 {
675 /* Restore original stdout */
676 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
677 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
678 if (hOldConOut != hOut)
679 CloseHandle (hOut);
680 hOldConOut = INVALID_HANDLE_VALUE;
681 }
682
683 /* redirect STDERR */
684 if (err[0])
685 {
686 /* Final output to here */
687 HANDLE hFile;
688 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
689
690 if (!_tcscmp (err, out))
691 {
692 #ifdef _DEBUG
693 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
694 #endif
695 DuplicateHandle (GetCurrentProcess (),
696 GetStdHandle (STD_OUTPUT_HANDLE),
697 GetCurrentProcess (),
698 &hFile, 0, TRUE, DUPLICATE_SAME_ACCESS);
699 }
700 else
701 {
702 hFile = CreateFile (err,
703 GENERIC_WRITE,
704 0,
705 &sa,
706 (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
707 FILE_ATTRIBUTE_NORMAL,
708 NULL);
709 if (hFile == INVALID_HANDLE_VALUE)
710 {
711 ConErrPrintf (_T("Can't redirect to file %s\n"), err);
712 return;
713 }
714 }
715 if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
716 {
717 ConErrPrintf (_T("Can't redirect to file %s\n"), err);
718 return;
719 }
720
721 if (nRedirFlags & ERROR_APPEND)
722 {
723 LONG lHighPos = 0;
724
725 if (GetFileType (hFile) == FILE_TYPE_DISK)
726 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
727 }
728 #ifdef _DEBUG
729 DebugPrintf (_T("Error redirected to: %s\n"), err);
730 #endif
731 }
732 else if (hOldConErr != INVALID_HANDLE_VALUE)
733 {
734 /* Restore original stderr */
735 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
736 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
737 if (hOldConErr != hErr)
738 CloseHandle (hErr);
739 hOldConErr = INVALID_HANDLE_VALUE;
740 }
741 #endif
742
743 /* process final command */
744 DoCommand (s);
745
746 #ifdef FEATURE_REDIRECTION
747 /* close old stdin file */
748 #if 0 /* buggy implementation */
749 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
750 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
751 (hFile[0] != hOldConIn))
752 {
753 /* delete old stdin file, if it is a real file */
754 CloseHandle (hFile[0]);
755 hFile[0] = INVALID_HANDLE_VALUE;
756 DeleteFile (szFileName[0]);
757 *szFileName[0] = _T('\0');
758 }
759
760 /* Restore original STDIN */
761 if (hOldConIn != INVALID_HANDLE_VALUE)
762 {
763 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
764 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
765 if (hOldConIn != hIn)
766 CloseHandle (hIn);
767 hOldConIn = INVALID_HANDLE_VALUE;
768 }
769 else
770 {
771 #ifdef _DEBUG
772 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out);
773 #endif
774 }
775 #endif /* buggy implementation */
776
777
778 if (hOldConIn != INVALID_HANDLE_VALUE)
779 {
780 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
781 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
782 if (hIn == INVALID_HANDLE_VALUE)
783 {
784 #ifdef _DEBUG
785 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
786 #endif
787 }
788 else
789 {
790 if (GetFileType (hIn) == FILE_TYPE_DISK)
791 {
792 if (hFile[0] == hIn)
793 {
794 CloseHandle (hFile[0]);
795 hFile[0] = INVALID_HANDLE_VALUE;
796 DeleteFile (szFileName[0]);
797 *szFileName[0] = _T('\0');
798 }
799 else
800 {
801 #ifdef _DEBUG
802 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
803 #endif
804 }
805 }
806 }
807 }
808
809
810 /* Restore original STDOUT */
811 if (hOldConOut != INVALID_HANDLE_VALUE)
812 {
813 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
814 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
815 if (hOldConOut != hOut)
816 CloseHandle (hOut);
817 hOldConOut = INVALID_HANDLE_VALUE;
818 }
819
820 /* Restore original STDERR */
821 if (hOldConErr != INVALID_HANDLE_VALUE)
822 {
823 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
824 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
825 if (hOldConErr != hErr)
826 CloseHandle (hErr);
827 hOldConErr = INVALID_HANDLE_VALUE;
828 }
829 #endif /* FEATURE_REDIRECTION */
830 }
831
832
833 /*
834 * do the prompt/input/process loop
835 *
836 */
837
838 static INT
839 ProcessInput (BOOL bFlag)
840 {
841 TCHAR commandline[CMDLINE_LENGTH];
842 TCHAR readline[CMDLINE_LENGTH];
843 LPTSTR tp = NULL;
844 LPTSTR ip;
845 LPTSTR cp;
846 BOOL bEchoThisLine;
847
848 do
849 {
850 /* if no batch input then... */
851 if (!(ip = ReadBatchLine (&bEchoThisLine)))
852 {
853 if (bFlag)
854 return 0;
855
856 ReadCommand (readline, CMDLINE_LENGTH);
857 ip = readline;
858 bEchoThisLine = FALSE;
859 }
860
861 cp = commandline;
862 while (*ip)
863 {
864 if (*ip == _T('%'))
865 {
866 switch (*++ip)
867 {
868 case _T('%'):
869 *cp++ = *ip++;
870 break;
871
872 case _T('0'):
873 case _T('1'):
874 case _T('2'):
875 case _T('3'):
876 case _T('4'):
877 case _T('5'):
878 case _T('6'):
879 case _T('7'):
880 case _T('8'):
881 case _T('9'):
882 if ((tp = FindArg (*ip - _T('0'))))
883 {
884 cp = _stpcpy (cp, tp);
885 ip++;
886 }
887 else
888 *cp++ = _T('%');
889 break;
890
891 case _T('?'):
892 cp += _stprintf (cp, _T("%u"), nErrorLevel);
893 ip++;
894 break;
895
896 default:
897 tp = _tcschr(ip, _T('%'));
898 if ((tp != NULL) &&
899 (tp <= _tcschr(ip, _T(' ')) - 1))
900 {
901 TCHAR evar[512];
902 *tp = _T('\0');
903
904 /* FIXME: This is just a quick hack!! */
905 /* Do a proper memory allocation!! */
906 if (GetEnvironmentVariable (ip, evar, 512))
907 cp = _stpcpy (cp, evar);
908
909 ip = tp + 1;
910 }
911 else
912 {
913 *cp++ = _T('%');
914 }
915 break;
916 }
917 continue;
918 }
919
920 if (_istcntrl (*ip))
921 *ip = _T(' ');
922 *cp++ = *ip++;
923 }
924
925 *cp = _T('\0');
926
927 /* strip trailing spaces */
928 while ((--cp >= commandline) && _istspace (*cp));
929
930 *(cp + 1) = _T('\0');
931
932 /* JPP 19980807 */
933 /* Echo batch file line */
934 if (bEchoThisLine)
935 {
936 PrintPrompt ();
937 ConOutPuts (commandline);
938 }
939
940 if (*commandline)
941 {
942 ParseCommandLine (commandline);
943 if (bEcho && !bIgnoreEcho)
944 ConOutChar ('\n');
945 bIgnoreEcho = FALSE;
946 }
947 }
948 while (!bCanExit || !bExit);
949
950 return 0;
951 }
952
953
954 /*
955 * control-break handler.
956 */
957 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
958 {
959 if ((dwCtrlType != CTRL_C_EVENT) &&
960 (dwCtrlType != CTRL_BREAK_EVENT))
961 return FALSE;
962
963 if (bChildProcessRunning == TRUE)
964 {
965 GenerateConsoleCtrlEvent (CTRL_C_EVENT,
966 dwChildProcessId);
967 return TRUE;
968 }
969
970 /* FIXME: Handle batch files */
971
972 /* FIXME: Print "^C" */
973
974
975 return TRUE;
976 }
977
978
979 VOID AddBreakHandler (VOID)
980 {
981 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
982 }
983
984
985 VOID RemoveBreakHandler (VOID)
986 {
987 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
988 }
989
990
991 /*
992 * show commands and options that are available.
993 *
994 */
995 #if 0
996 static VOID
997 ShowCommands (VOID)
998 {
999 /* print command list */
1000 ConOutPrintf (_T("\nInternal commands available:\n"));
1001 PrintCommandList ();
1002
1003 /* print feature list */
1004 ConOutPuts (_T("\nFeatures available:"));
1005 #ifdef FEATURE_ALIASES
1006 ConOutPuts (_T(" [aliases]"));
1007 #endif
1008 #ifdef FEATURE_HISTORY
1009 ConOutPuts (_T(" [history]"));
1010 #endif
1011 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1012 ConOutPuts (_T(" [unix filename completion]"));
1013 #endif
1014 #ifdef FEATURE_DIRECTORY_STACK
1015 ConOutPuts (_T(" [directory stack]"));
1016 #endif
1017 #ifdef FEATURE_REDIRECTION
1018 ConOutPuts (_T(" [redirections and piping]"));
1019 #endif
1020 ConOutChar (_T('\n'));
1021 }
1022 #endif
1023
1024 /*
1025 * set up global initializations and process parameters
1026 *
1027 * argc - number of parameters to command.com
1028 * argv - command-line parameters
1029 *
1030 */
1031 static VOID
1032 Initialize (int argc, TCHAR* argv[])
1033 {
1034 TCHAR commandline[CMDLINE_LENGTH];
1035 TCHAR ModuleName[_MAX_PATH + 1];
1036 INT i;
1037 //INT len;
1038 //TCHAR *ptr, *cmdLine;
1039
1040
1041 #ifdef _DEBUG
1042 INT x;
1043
1044 DebugPrintf (_T("[command args:\n"));
1045 for (x = 0; x < argc; x++)
1046 {
1047 DebugPrintf (_T("%d. %s\n"), x, argv[x]);
1048 }
1049 DebugPrintf (_T("]\n"));
1050 #endif
1051
1052 /* get version information */
1053 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1054 GetVersionEx (&osvi);
1055
1056 InitLocale ();
1057
1058 /* get default input and output console handles */
1059 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1060 hIn = GetStdHandle (STD_INPUT_HANDLE);
1061
1062
1063 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1064 {
1065 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
1066 "\n"
1067 "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
1068 "\n"
1069 " /C command Runs the specified command and terminates.\n"
1070 " /K command Runs the specified command and remains.\n"
1071 " /P CMD becomes permanent and runs autoexec.bat\n"
1072 " (cannot be terminated).\n"
1073 " /T:bf Sets the background/foreground color (see COLOR command)."));
1074 ExitProcess (0);
1075 }
1076 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1077
1078 #ifdef INCLUDE_CMD_CHDIR
1079 InitLastPath ();
1080 #endif
1081
1082 #ifdef FATURE_ALIASES
1083 InitializeAlias ();
1084 #endif
1085
1086 if (argc >= 2)
1087 {
1088 for (i = 1; i < argc; i++)
1089 {
1090 if (!_tcsicmp (argv[i], _T("/p")))
1091 {
1092 if (!IsValidFileName (_T("\\autoexec.bat")))
1093 {
1094 #ifdef INCLUDE_CMD_DATE
1095 cmd_date (_T(""), _T(""));
1096 #endif
1097 #ifdef INCLUDE_CMD_TIME
1098 cmd_time (_T(""), _T(""));
1099 #endif
1100 }
1101 else
1102 {
1103 ParseCommandLine (_T("\\autoexec.bat"));
1104 }
1105 bCanExit = FALSE;
1106 }
1107 else if (!_tcsicmp (argv[i], _T("/c")))
1108 {
1109 /* This just runs a program and exits */
1110 ++i;
1111 if (i < argc)
1112 {
1113 _tcscpy (commandline, argv[i]);
1114 while (++i < argc)
1115 {
1116 _tcscat (commandline, _T(" "));
1117 _tcscat (commandline, argv[i]);
1118 }
1119
1120 ParseCommandLine(commandline);
1121 ExitProcess (ProcessInput (TRUE));
1122 }
1123 else
1124 {
1125 ExitProcess (0);
1126 }
1127 }
1128 else if (!_tcsicmp (argv[i], _T("/k")))
1129 {
1130 /* This just runs a program and remains */
1131 ++i;
1132 if (i < argc)
1133 {
1134 _tcscpy (commandline, argv[i]);
1135 while (++i < argc)
1136 {
1137 _tcscat (commandline, _T(" "));
1138 _tcscat (commandline, argv[i]);
1139 }
1140
1141 ParseCommandLine(commandline);
1142 }
1143 }
1144 #ifdef INCLUDE_CMD_COLOR
1145 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1146 {
1147 /* process /t (color) argument */
1148 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1149 wColor = wDefColor;
1150 SetScreenColor (wColor, TRUE);
1151 }
1152 #endif
1153 }
1154 }
1155
1156 /* run cmdstart.bat */
1157 if (IsValidFileName (_T("cmdstart.bat")))
1158 {
1159 ParseCommandLine (_T("cmdstart.bat"));
1160 }
1161 else if (IsValidFileName (_T("\\cmdstart.bat")))
1162 {
1163 ParseCommandLine (_T("\\cmdstart.bat"));
1164 }
1165 #ifndef __REACTOS__
1166 else
1167 {
1168 /* try to run cmdstart.bat from install dir */
1169 LPTSTR p;
1170
1171 _tcscpy (commandline, argv[0]);
1172 p = _tcsrchr (commandline, _T('\\')) + 1;
1173 _tcscpy (p, _T("cmdstart.bat"));
1174
1175 if (IsValidFileName (_T("commandline")))
1176 {
1177 ConErrPrintf (_T("Running %s...\n", commandline));
1178 ParseCommandLine (commandline);
1179 }
1180 }
1181 #endif
1182
1183 #ifdef FEATURE_DIR_STACK
1184 /* initialize directory stack */
1185 InitDirectoryStack ();
1186 #endif
1187
1188
1189 #ifdef FEATURE_HISTORY
1190 /*initialize history*/
1191 InitHistory();
1192 #endif
1193
1194 /* Set COMSPEC environment variable */
1195 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1196 {
1197 ModuleName[_MAX_PATH] = _T('\0');
1198 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1199 }
1200
1201 /* add ctrl break handler */
1202 AddBreakHandler ();
1203 }
1204
1205
1206 static VOID Cleanup (int argc, TCHAR *argv[])
1207 {
1208 /* run cmdexit.bat */
1209 if (IsValidFileName (_T("cmdexit.bat")))
1210 {
1211 ConErrPrintf (_T("Running cmdexit.bat...\n"));
1212 ParseCommandLine (_T("cmdexit.bat"));
1213 }
1214 else if (IsValidFileName (_T("\\cmdexit.bat")))
1215 {
1216 ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
1217 ParseCommandLine (_T("\\cmdexit.bat"));
1218 }
1219 #ifndef __REACTOS__
1220 else
1221 {
1222 /* try to run cmdexit.bat from install dir */
1223 TCHAR commandline[CMDLINE_LENGTH];
1224 LPTSTR p;
1225
1226 _tcscpy (commandline, argv[0]);
1227 p = _tcsrchr (commandline, _T('\\')) + 1;
1228 _tcscpy (p, _T("cmdexit.bat"));
1229
1230 if (IsValidFileName (_T("commandline")))
1231 {
1232 ConErrPrintf (_T("Running %s...\n"), commandline);
1233 ParseCommandLine (commandline);
1234 }
1235 }
1236 #endif
1237
1238 #ifdef FEATURE_ALIASES
1239 DestroyAlias ();
1240 #endif
1241
1242 #ifdef FEATURE_DIECTORY_STACK
1243 /* destroy directory stack */
1244 DestroyDirectoryStack ();
1245 #endif
1246
1247 #ifdef INCLUDE_CMD_CHDIR
1248 FreeLastPath ();
1249 #endif
1250
1251 #ifdef FEATURE_HISTORY
1252 CleanHistory();
1253 #endif
1254
1255
1256 /* remove ctrl break handler */
1257 RemoveBreakHandler ();
1258 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1259 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1260 }
1261
1262 #ifdef __REACTOS__
1263 #ifdef _UNICODE
1264 PWCHAR * _CommandLineToArgvW(PWCHAR lpCmdLine, int *pNumArgs)
1265 {
1266 PWCHAR * argvw = NULL;
1267 PWCHAR ptr = lpCmdLine;
1268 PWCHAR str;
1269 int len;
1270 int NumArgs;
1271
1272 NumArgs = 0;
1273
1274 while(lpCmdLine && *lpCmdLine)
1275 {
1276 while (iswspace(*lpCmdLine)) lpCmdLine++;
1277 if (*lpCmdLine)
1278 {
1279 if ((NumArgs % 10)==0)
1280 {
1281 PWCHAR * old_argvw = argvw;
1282 argvw = malloc((NumArgs + 10) * sizeof(PWCHAR));
1283 memcpy(argvw, old_argvw, NumArgs * sizeof(PWCHAR));
1284 free(old_argvw);
1285 }
1286 ptr = wcschr(lpCmdLine, L' ');
1287 if (ptr)
1288 {
1289 len = ptr - lpCmdLine;
1290 }
1291 else
1292 {
1293 len = wcslen(lpCmdLine);
1294 }
1295 str = malloc((len + 1) * sizeof(WCHAR));
1296 memcpy(str, lpCmdLine, len * sizeof(WCHAR));
1297 str[len] = 0;
1298 argvw[NumArgs]=str;
1299 NumArgs++;
1300 lpCmdLine = ptr;
1301 }
1302 }
1303 *pNumArgs = NumArgs;
1304 return argvw;
1305 }
1306 #endif
1307 #endif
1308
1309 /*
1310 * main function
1311 */
1312 #ifdef _UNICODE
1313 int main(void)
1314 #else
1315 int main (int argc, char *argv[])
1316 #endif
1317 {
1318 CONSOLE_SCREEN_BUFFER_INFO Info;
1319 INT nExitCode;
1320 #ifdef _UNICODE
1321 PWCHAR * argv;
1322 int argc=0;
1323 #ifdef __REACTOS__
1324 argv = _CommandLineToArgvW(GetCommandLineW(), &argc);
1325 #else
1326 argv = CommandLineToArgvW(GetCommandLineW(), &argc);
1327 #endif
1328 #endif
1329
1330 SetFileApisToOEM();
1331
1332 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1333 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1334 OPEN_EXISTING, 0, NULL);
1335 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1336 {
1337 ConErrPrintf (_T("GetConsoleScreenBufferInfo: Error: %ld\n"), GetLastError());
1338 return(1);
1339 }
1340 wColor = Info.wAttributes;
1341 wDefColor = wColor;
1342
1343 /* check switches on command-line */
1344 Initialize(argc, argv);
1345
1346 /* call prompt routine */
1347 nExitCode = ProcessInput(FALSE);
1348
1349 /* do the cleanup */
1350 Cleanup(argc, argv);
1351
1352 return(nExitCode);
1353 }
1354
1355 /* EOF */