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