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