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