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