59f00eada0a7b87a8b39dfa5d6bafcae00d7d1cf
[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)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
90 *
91 * 13-Dec-1998 (Eric Kohl)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
94 *
95 * 07-Jan-1999 (Eric Kohl)
96 * Added help text ("cmd /?").
97 *
98 * 25-Jan-1999 (Eric Kohl)
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)
105 * Replaced spawnl() by CreateProcess().
106 *
107 * 22-Oct-1999 (Eric Kohl)
108 * Added break handler.
109 *
110 * 15-Dec-1999 (Eric Kohl)
111 * Fixed current directory
112 *
113 * 28-Dec-1999 (Eric Kohl)
114 * Restore window title after program/batch execution
115 *
116 * 03-Feb-2001 (Eric Kohl)
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
146 #ifndef NT_SUCCESS
147 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
148 #endif
149
150 typedef NTSTATUS (WINAPI *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
151 PVOID, ULONG, PULONG);
152 typedef NTSTATUS (WINAPI *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
153
154 BOOL bExit = FALSE; /* indicates EXIT was typed */
155 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
156 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
157 BOOL bIgnoreEcho = FALSE; /* Set this to TRUE to prevent a newline, when executing a command */
158 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
159 BOOL bChildProcessRunning = FALSE;
160 BOOL bUnicodeOutput = FALSE;
161 BOOL bDisableBatchEcho = FALSE;
162 BOOL bDelayedExpansion = FALSE;
163 DWORD dwChildProcessId = 0;
164 OSVERSIONINFO osvi;
165 HANDLE hIn;
166 HANDLE hOut;
167 LPTSTR lpOriginalEnvironment;
168 HANDLE CMD_ModuleHandle;
169
170 static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
171 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
172
173 #ifdef INCLUDE_CMD_COLOR
174 WORD wDefColor; /* default color */
175 #endif
176
177 /*
178 * convert
179 *
180 * insert commas into a number
181 */
182 INT
183 ConvertULargeInteger(ULONGLONG num, LPTSTR des, INT len, BOOL bPutSeperator)
184 {
185 TCHAR temp[39]; /* maximum length with nNumberGroups == 1 */
186 UINT n, iTarget;
187
188 if (len <= 1)
189 return 0;
190
191 n = 0;
192 iTarget = nNumberGroups;
193 if (!nNumberGroups)
194 bPutSeperator = FALSE;
195
196 do
197 {
198 if (iTarget == n && bPutSeperator)
199 {
200 iTarget += nNumberGroups + 1;
201 temp[38 - n++] = cThousandSeparator;
202 }
203 temp[38 - n++] = (TCHAR)(num % 10) + _T('0');
204 num /= 10;
205 } while (num > 0);
206 if (n > len-1)
207 n = len-1;
208
209 memcpy(des, temp + 39 - n, n * sizeof(TCHAR));
210 des[n] = _T('\0');
211
212 return n;
213 }
214
215 /*
216 * Is a process a console process?
217 */
218 static BOOL IsConsoleProcess(HANDLE Process)
219 {
220 NTSTATUS Status;
221 PROCESS_BASIC_INFORMATION Info;
222 PEB ProcessPeb;
223 ULONG BytesRead;
224
225 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
226 {
227 return TRUE;
228 }
229
230 Status = NtQueryInformationProcessPtr (
231 Process, ProcessBasicInformation,
232 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
233 if (! NT_SUCCESS(Status))
234 {
235 WARN ("NtQueryInformationProcess failed with status %08x\n", Status);
236 return TRUE;
237 }
238 Status = NtReadVirtualMemoryPtr (
239 Process, Info.PebBaseAddress, &ProcessPeb,
240 sizeof(PEB), &BytesRead);
241 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
242 {
243 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status, BytesRead);
244 return TRUE;
245 }
246
247 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubsystem;
248 }
249
250
251
252 #ifdef _UNICODE
253 #define SHELLEXECUTETEXT "ShellExecuteExW"
254 #else
255 #define SHELLEXECUTETEXT "ShellExecuteExA"
256 #endif
257
258 typedef BOOL (WINAPI *MYEX)(LPSHELLEXECUTEINFO lpExecInfo);
259
260 HANDLE RunFile(DWORD flags, LPTSTR filename, LPTSTR params,
261 LPTSTR directory, INT show)
262 {
263 SHELLEXECUTEINFO sei;
264 HMODULE hShell32;
265 MYEX hShExt;
266 BOOL ret;
267
268 TRACE ("RunFile(%s)\n", debugstr_aw(filename));
269 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
270 if (!hShell32)
271 {
272 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
273 return NULL;
274 }
275
276 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
277 if (!hShExt)
278 {
279 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
280 FreeLibrary(hShell32);
281 return NULL;
282 }
283
284 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt);
285
286 memset(&sei, 0, sizeof sei);
287 sei.cbSize = sizeof sei;
288 sei.fMask = flags;
289 sei.lpFile = filename;
290 sei.lpParameters = params;
291 sei.lpDirectory = directory;
292 sei.nShow = show;
293 ret = hShExt(&sei);
294
295 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret);
296
297 FreeLibrary(hShell32);
298 return ret ? sei.hProcess : NULL;
299 }
300
301
302
303 /*
304 * This command (in first) was not found in the command table
305 *
306 * Full - buffer to hold whole command line
307 * First - first word on command line
308 * Rest - rest of command line
309 */
310
311 static INT
312 Execute (LPTSTR Full, LPTSTR First, LPTSTR Rest, PARSED_COMMAND *Cmd)
313 {
314 TCHAR szFullName[MAX_PATH];
315 TCHAR *first, *rest, *dot;
316 TCHAR szWindowTitle[MAX_PATH];
317 DWORD dwExitCode = 0;
318 TCHAR *FirstEnd;
319
320 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First), debugstr_aw(Rest));
321
322 /* Though it was already parsed once, we have a different set of rules
323 for parsing before we pass to CreateProccess */
324 if (First[0] == _T('/') || (First[0] && First[1] == _T(':')))
325 {
326 /* Use the entire first word as the program name (no change) */
327 FirstEnd = First + _tcslen(First);
328 }
329 else
330 {
331 /* If present in the first word, spaces and ,;=/ end the program
332 * name and become the beginning of its parameters. */
333 BOOL bInside = FALSE;
334 for (FirstEnd = First; *FirstEnd; FirstEnd++)
335 {
336 if (!bInside && (_istspace(*FirstEnd) || _tcschr(_T(",;=/"), *FirstEnd)))
337 break;
338 bInside ^= *FirstEnd == _T('"');
339 }
340 }
341
342 /* Copy the new first/rest into the buffer */
343 first = Full;
344 rest = &Full[FirstEnd - First + 1];
345 _tcscpy(rest, FirstEnd);
346 _tcscat(rest, Rest);
347 *FirstEnd = _T('\0');
348 _tcscpy(first, First);
349
350 /* check for a drive change */
351 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
352 {
353 BOOL working = TRUE;
354 if (!SetCurrentDirectory(first))
355 /* Guess they changed disc or something, handle that gracefully and get to root */
356 {
357 TCHAR str[4];
358 str[0]=first[0];
359 str[1]=_T(':');
360 str[2]=_T('\\');
361 str[3]=0;
362 working = SetCurrentDirectory(str);
363 }
364
365 if (!working) ConErrResPuts (STRING_FREE_ERROR1);
366 return !working;
367 }
368
369 /* get the PATH environment variable and parse it */
370 /* search the PATH environment variable for the binary */
371 StripQuotes(First);
372 if (!SearchForExecutable(First, szFullName))
373 {
374 error_bad_command(first);
375 return 1;
376 }
377
378 GetConsoleTitle (szWindowTitle, MAX_PATH);
379
380 /* check if this is a .BAT or .CMD file */
381 dot = _tcsrchr (szFullName, _T('.'));
382 if (dot && (!_tcsicmp (dot, _T(".bat")) || !_tcsicmp (dot, _T(".cmd"))))
383 {
384 while (*rest == _T(' '))
385 rest++;
386 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName), debugstr_aw(rest));
387 dwExitCode = Batch(szFullName, first, rest, Cmd);
388 }
389 else
390 {
391 /* exec the program */
392 PROCESS_INFORMATION prci;
393 STARTUPINFO stui;
394
395 /* build command line for CreateProcess(): first + " " + rest */
396 if (*rest)
397 rest[-1] = _T(' ');
398
399 TRACE ("[EXEC: %s]\n", debugstr_aw(Full));
400
401 /* fill startup info */
402 memset (&stui, 0, sizeof (STARTUPINFO));
403 stui.cb = sizeof (STARTUPINFO);
404 stui.dwFlags = STARTF_USESHOWWINDOW;
405 stui.wShowWindow = SW_SHOWDEFAULT;
406
407 // return console to standard mode
408 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE),
409 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
410
411 if (CreateProcess (szFullName,
412 Full,
413 NULL,
414 NULL,
415 TRUE,
416 0, /* CREATE_NEW_PROCESS_GROUP */
417 NULL,
418 NULL,
419 &stui,
420 &prci))
421
422 {
423 CloseHandle(prci.hThread);
424 }
425 else
426 {
427 // See if we can run this with ShellExecute() ie myfile.xls
428 prci.hProcess = RunFile(SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
429 szFullName,
430 rest,
431 NULL,
432 SW_SHOWNORMAL);
433 }
434
435 if (prci.hProcess != NULL)
436 {
437 if (IsConsoleProcess(prci.hProcess))
438 {
439 /* FIXME: Protect this with critical section */
440 bChildProcessRunning = TRUE;
441 dwChildProcessId = prci.dwProcessId;
442
443 WaitForSingleObject (prci.hProcess, INFINITE);
444
445 /* FIXME: Protect this with critical section */
446 bChildProcessRunning = FALSE;
447
448 GetExitCodeProcess (prci.hProcess, &dwExitCode);
449 nErrorLevel = (INT)dwExitCode;
450 }
451 CloseHandle (prci.hProcess);
452 }
453 else
454 {
455 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full));
456 error_bad_command (first);
457 dwExitCode = 1;
458 }
459
460 // restore console mode
461 SetConsoleMode (
462 GetStdHandle( STD_INPUT_HANDLE ),
463 ENABLE_PROCESSED_INPUT );
464 }
465
466 /* Get code page if it has been change */
467 InputCodePage= GetConsoleCP();
468 OutputCodePage = GetConsoleOutputCP();
469 SetConsoleTitle (szWindowTitle);
470
471 return dwExitCode;
472 }
473
474
475 /*
476 * look through the internal commands and determine whether or not this
477 * command is one of them. If it is, call the command. If not, call
478 * execute to run it as an external program.
479 *
480 * first - first word on command line
481 * rest - rest of command line
482 */
483
484 INT
485 DoCommand(LPTSTR first, LPTSTR rest, PARSED_COMMAND *Cmd)
486 {
487 TCHAR *com;
488 TCHAR *cp;
489 LPTSTR param; /* pointer to command's parameters */
490 INT cl;
491 LPCOMMAND cmdptr;
492 BOOL nointernal = FALSE;
493 INT ret;
494
495 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first), debugstr_aw(rest));
496
497 /* full command line */
498 com = cmd_alloc((_tcslen(first) + _tcslen(rest) + 2) * sizeof(TCHAR));
499 if (com == NULL)
500 {
501 error_out_of_memory();
502 return 1;
503 }
504
505 /* If present in the first word, these characters end the name of an
506 * internal command and become the beginning of its parameters. */
507 cp = first + _tcscspn(first, _T("\t +,/;=[]"));
508
509 for (cl = 0; cl < (cp - first); cl++)
510 {
511 /* These characters do it too, but if one of them is present,
512 * then we check to see if the word is a file name and skip
513 * checking for internal commands if so.
514 * This allows running programs with names like "echo.exe" */
515 if (_tcschr(_T(".:\\"), first[cl]))
516 {
517 TCHAR tmp = *cp;
518 *cp = _T('\0');
519 nointernal = IsExistingFile(first);
520 *cp = tmp;
521 break;
522 }
523 }
524
525 /* Scan internal command table */
526 for (cmdptr = cmds; !nointernal && cmdptr->name; cmdptr++)
527 {
528 if (!_tcsnicmp(first, cmdptr->name, cl) && cmdptr->name[cl] == _T('\0'))
529 {
530 _tcscpy(com, first);
531 _tcscat(com, rest);
532 param = &com[cl];
533
534 /* Skip over whitespace to rest of line, exclude 'echo' command */
535 if (_tcsicmp(cmdptr->name, _T("echo")) != 0)
536 while (_istspace(*param))
537 param++;
538 ret = cmdptr->func(param);
539 cmd_free(com);
540 return ret;
541 }
542 }
543
544 ret = Execute(com, first, rest, Cmd);
545 cmd_free(com);
546 return ret;
547 }
548
549
550 /*
551 * process the command line and execute the appropriate functions
552 * full input/output redirection and piping are supported
553 */
554
555 INT ParseCommandLine (LPTSTR cmd)
556 {
557 INT Ret = 0;
558 PARSED_COMMAND *Cmd = ParseCommand(cmd);
559 if (Cmd)
560 {
561 Ret = ExecuteCommand(Cmd);
562 FreeCommand(Cmd);
563 }
564 return Ret;
565 }
566
567 /* Execute a command without waiting for it to finish. If it's an internal
568 * command or batch file, we must create a new cmd.exe process to handle it.
569 * TODO: For now, this just always creates a cmd.exe process.
570 * This works, but is inefficient for running external programs,
571 * which could just be run directly. */
572 static HANDLE
573 ExecuteAsync(PARSED_COMMAND *Cmd)
574 {
575 TCHAR CmdPath[MAX_PATH];
576 TCHAR CmdParams[CMDLINE_LENGTH], *ParamsEnd;
577 STARTUPINFO stui;
578 PROCESS_INFORMATION prci;
579
580 /* Get the path to cmd.exe */
581 GetModuleFileName(NULL, CmdPath, MAX_PATH);
582
583 /* Build the parameter string to pass to cmd.exe */
584 ParamsEnd = _stpcpy(CmdParams, _T("/S/D/C\""));
585 ParamsEnd = Unparse(Cmd, ParamsEnd, &CmdParams[CMDLINE_LENGTH - 2]);
586 if (!ParamsEnd)
587 {
588 error_out_of_memory();
589 return NULL;
590 }
591 _tcscpy(ParamsEnd, _T("\""));
592
593 memset(&stui, 0, sizeof stui);
594 stui.cb = sizeof(STARTUPINFO);
595 if (!CreateProcess(CmdPath, CmdParams, NULL, NULL, TRUE, 0,
596 NULL, NULL, &stui, &prci))
597 {
598 ErrorMessage(GetLastError(), NULL);
599 return NULL;
600 }
601
602 CloseHandle(prci.hThread);
603 return prci.hProcess;
604 }
605
606 static VOID
607 ExecutePipeline(PARSED_COMMAND *Cmd)
608 {
609 #ifdef FEATURE_REDIRECTION
610 HANDLE hInput = NULL;
611 HANDLE hOldConIn = GetStdHandle(STD_INPUT_HANDLE);
612 HANDLE hOldConOut = GetStdHandle(STD_OUTPUT_HANDLE);
613 HANDLE hProcess[MAXIMUM_WAIT_OBJECTS];
614 INT nProcesses = 0;
615 DWORD dwExitCode;
616
617 /* Do all but the last pipe command */
618 do
619 {
620 HANDLE hPipeRead, hPipeWrite;
621 if (nProcesses > (MAXIMUM_WAIT_OBJECTS - 2))
622 {
623 error_too_many_parameters(_T("|"));
624 goto failed;
625 }
626
627 /* Create the pipe that this process will write into.
628 * Make the handles non-inheritable initially, because this
629 * process shouldn't inherit the reading handle. */
630 if (!CreatePipe(&hPipeRead, &hPipeWrite, NULL, 0))
631 {
632 error_no_pipe();
633 goto failed;
634 }
635
636 /* The writing side of the pipe is STDOUT for this process */
637 SetHandleInformation(hPipeWrite, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
638 SetStdHandle(STD_OUTPUT_HANDLE, hPipeWrite);
639
640 /* Execute it (error check is done later for easier cleanup) */
641 hProcess[nProcesses] = ExecuteAsync(Cmd->Subcommands);
642 CloseHandle(hPipeWrite);
643 if (hInput)
644 CloseHandle(hInput);
645
646 /* The reading side of the pipe will be STDIN for the next process */
647 SetHandleInformation(hPipeRead, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
648 SetStdHandle(STD_INPUT_HANDLE, hPipeRead);
649 hInput = hPipeRead;
650
651 if (!hProcess[nProcesses])
652 goto failed;
653 nProcesses++;
654
655 Cmd = Cmd->Subcommands->Next;
656 } while (Cmd->Type == C_PIPE);
657
658 /* The last process uses the original STDOUT */
659 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
660 hProcess[nProcesses] = ExecuteAsync(Cmd);
661 if (!hProcess[nProcesses])
662 goto failed;
663 nProcesses++;
664 CloseHandle(hInput);
665 SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
666
667 /* Wait for all processes to complete */
668 bChildProcessRunning = TRUE;
669 WaitForMultipleObjects(nProcesses, hProcess, TRUE, INFINITE);
670 bChildProcessRunning = FALSE;
671
672 /* Use the exit code of the last process in the pipeline */
673 GetExitCodeProcess(hProcess[nProcesses - 1], &dwExitCode);
674 nErrorLevel = (INT)dwExitCode;
675
676 while (--nProcesses >= 0)
677 CloseHandle(hProcess[nProcesses]);
678 return;
679
680 failed:
681 if (hInput)
682 CloseHandle(hInput);
683 while (--nProcesses >= 0)
684 {
685 TerminateProcess(hProcess[nProcesses], 0);
686 CloseHandle(hProcess[nProcesses]);
687 }
688 SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
689 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
690 #endif
691 }
692
693 INT
694 ExecuteCommand(PARSED_COMMAND *Cmd)
695 {
696 PARSED_COMMAND *Sub;
697 LPTSTR First, Rest;
698 INT Ret = 0;
699
700 if (!PerformRedirection(Cmd->Redirections))
701 return 1;
702
703 switch (Cmd->Type)
704 {
705 case C_COMMAND:
706 Ret = 1;
707 First = DoDelayedExpansion(Cmd->Command.First);
708 if (First)
709 {
710 Rest = DoDelayedExpansion(Cmd->Command.Rest);
711 if (Rest)
712 {
713 Ret = DoCommand(First, Rest, Cmd);
714 cmd_free(Rest);
715 }
716 cmd_free(First);
717 }
718 break;
719 case C_QUIET:
720 case C_BLOCK:
721 case C_MULTI:
722 for (Sub = Cmd->Subcommands; Sub; Sub = Sub->Next)
723 Ret = ExecuteCommand(Sub);
724 break;
725 case C_IFFAILURE:
726 Sub = Cmd->Subcommands;
727 Ret = ExecuteCommand(Sub);
728 if (Ret != 0)
729 {
730 nErrorLevel = Ret;
731 Ret = ExecuteCommand(Sub->Next);
732 }
733 break;
734 case C_IFSUCCESS:
735 Sub = Cmd->Subcommands;
736 Ret = ExecuteCommand(Sub);
737 if (Ret == 0)
738 Ret = ExecuteCommand(Sub->Next);
739 break;
740 case C_PIPE:
741 ExecutePipeline(Cmd);
742 break;
743 case C_IF:
744 Ret = ExecuteIf(Cmd);
745 break;
746 case C_FOR:
747 Ret = ExecuteFor(Cmd);
748 break;
749 }
750
751 UndoRedirection(Cmd->Redirections, NULL);
752 return Ret;
753 }
754
755 LPTSTR
756 GetEnvVar(LPCTSTR varName)
757 {
758 static LPTSTR ret = NULL;
759 UINT size;
760
761 cmd_free(ret);
762 ret = NULL;
763 size = GetEnvironmentVariable(varName, NULL, 0);
764 if (size > 0)
765 {
766 ret = cmd_alloc(size * sizeof(TCHAR));
767 if (ret != NULL)
768 GetEnvironmentVariable(varName, ret, size + 1);
769 }
770 return ret;
771 }
772
773 LPCTSTR
774 GetEnvVarOrSpecial(LPCTSTR varName)
775 {
776 static TCHAR ret[MAX_PATH];
777
778 LPTSTR var = GetEnvVar(varName);
779 if (var)
780 return var;
781
782 /* env var doesn't exist, look for a "special" one */
783 /* %CD% */
784 if (_tcsicmp(varName,_T("cd")) ==0)
785 {
786 GetCurrentDirectory(MAX_PATH, ret);
787 return ret;
788 }
789 /* %TIME% */
790 else if (_tcsicmp(varName,_T("time")) ==0)
791 {
792 return GetTimeString();
793 }
794 /* %DATE% */
795 else if (_tcsicmp(varName,_T("date")) ==0)
796 {
797 return GetDateString();
798 }
799
800 /* %RANDOM% */
801 else if (_tcsicmp(varName,_T("random")) ==0)
802 {
803 /* Get random number */
804 _itot(rand(),ret,10);
805 return ret;
806 }
807
808 /* %CMDCMDLINE% */
809 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
810 {
811 return GetCommandLine();
812 }
813
814 /* %CMDEXTVERSION% */
815 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
816 {
817 /* Set version number to 2 */
818 _itot(2,ret,10);
819 return ret;
820 }
821
822 /* %ERRORLEVEL% */
823 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
824 {
825 _itot(nErrorLevel,ret,10);
826 return ret;
827 }
828
829 return NULL;
830 }
831
832 /* Handle the %~var syntax */
833 static LPTSTR
834 GetEnhancedVar(TCHAR **pFormat, LPTSTR (*GetVar)(TCHAR, BOOL *))
835 {
836 static const TCHAR ModifierTable[] = _T("dpnxfsatz");
837 enum {
838 M_DRIVE = 1, /* D: drive letter */
839 M_PATH = 2, /* P: path */
840 M_NAME = 4, /* N: filename */
841 M_EXT = 8, /* X: extension */
842 M_FULL = 16, /* F: full path (drive+path+name+ext) */
843 M_SHORT = 32, /* S: full path (drive+path+name+ext), use short names */
844 M_ATTR = 64, /* A: attributes */
845 M_TIME = 128, /* T: modification time */
846 M_SIZE = 256, /* Z: file size */
847 } Modifiers = 0;
848
849 TCHAR *Format, *FormatEnd;
850 TCHAR *PathVarName = NULL;
851 LPTSTR Variable;
852 TCHAR *VarEnd;
853 BOOL VariableIsParam0;
854 TCHAR FullPath[MAX_PATH];
855 TCHAR FixedPath[MAX_PATH], *Filename, *Extension;
856 HANDLE hFind;
857 WIN32_FIND_DATA w32fd;
858 TCHAR *In, *Out;
859
860 static TCHAR Result[CMDLINE_LENGTH];
861
862 /* There is ambiguity between modifier characters and FOR variables;
863 * the rule that cmd uses is to pick the longest possible match.
864 * For example, if there is a %n variable, then out of %~anxnd,
865 * %~anxn will be substituted rather than just %~an. */
866
867 /* First, go through as many modifier characters as possible */
868 FormatEnd = Format = *pFormat;
869 while (*FormatEnd && _tcschr(ModifierTable, _totlower(*FormatEnd)))
870 FormatEnd++;
871
872 if (*FormatEnd == _T('$'))
873 {
874 /* $PATH: syntax */
875 PathVarName = FormatEnd + 1;
876 FormatEnd = _tcschr(PathVarName, _T(':'));
877 if (!FormatEnd)
878 return NULL;
879
880 /* Must be immediately followed by the variable */
881 Variable = GetVar(*++FormatEnd, &VariableIsParam0);
882 if (!Variable)
883 return NULL;
884 }
885 else
886 {
887 /* Backtrack if necessary to get a variable name match */
888 while (!(Variable = GetVar(*FormatEnd, &VariableIsParam0)))
889 {
890 if (FormatEnd == Format)
891 return NULL;
892 FormatEnd--;
893 }
894 }
895
896 for (; Format < FormatEnd && *Format != _T('$'); Format++)
897 Modifiers |= 1 << (_tcschr(ModifierTable, _totlower(*Format)) - ModifierTable);
898
899 *pFormat = FormatEnd + 1;
900
901 /* Exclude the leading and trailing quotes */
902 VarEnd = &Variable[_tcslen(Variable)];
903 if (*Variable == _T('"'))
904 {
905 Variable++;
906 if (VarEnd > Variable && VarEnd[-1] == _T('"'))
907 VarEnd--;
908 }
909
910 if ((char *)VarEnd - (char *)Variable >= sizeof Result)
911 return _T("");
912 memcpy(Result, Variable, (char *)VarEnd - (char *)Variable);
913 Result[VarEnd - Variable] = _T('\0');
914
915 if (PathVarName)
916 {
917 /* $PATH: syntax - search the directories listed in the
918 * specified environment variable for the file */
919 LPTSTR PathVar;
920 FormatEnd[-1] = _T('\0');
921 PathVar = GetEnvVar(PathVarName);
922 FormatEnd[-1] = _T(':');
923 if (!PathVar ||
924 !SearchPath(PathVar, Result, NULL, MAX_PATH, FullPath, NULL))
925 {
926 return _T("");
927 }
928 }
929 else if (Modifiers == 0)
930 {
931 /* For plain %~var with no modifiers, just return the variable without quotes */
932 return Result;
933 }
934 else if (VariableIsParam0)
935 {
936 /* Special case: If the variable is %0 and modifier characters are present,
937 * use the batch file's path (which includes the .bat/.cmd extension)
938 * rather than the actual %0 variable (which might not). */
939 _tcscpy(FullPath, bc->BatchFilePath);
940 }
941 else
942 {
943 /* Convert the variable, now without quotes, to a full path */
944 if (!GetFullPathName(Result, MAX_PATH, FullPath, NULL))
945 return _T("");
946 }
947
948 /* Next step is to change the path to fix letter case (e.g.
949 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
950 * replace long filenames with short. */
951
952 In = FullPath;
953 Out = FixedPath;
954
955 /* Copy drive letter */
956 *Out++ = *In++;
957 *Out++ = *In++;
958 *Out++ = *In++;
959 /* Loop over each \-separated component in the path */
960 do {
961 TCHAR *Next = _tcschr(In, _T('\\'));
962 if (Next)
963 *Next++ = _T('\0');
964 /* Use FindFirstFile to get the correct name */
965 if (Out + _tcslen(In) + 1 >= &FixedPath[MAX_PATH])
966 return _T("");
967 _tcscpy(Out, In);
968 hFind = FindFirstFile(FixedPath, &w32fd);
969 /* If it doesn't exist, just leave the name as it was given */
970 if (hFind != INVALID_HANDLE_VALUE)
971 {
972 LPTSTR FixedComponent = w32fd.cFileName;
973 if (*w32fd.cAlternateFileName &&
974 ((Modifiers & M_SHORT) || !_tcsicmp(In, w32fd.cAlternateFileName)))
975 {
976 FixedComponent = w32fd.cAlternateFileName;
977 }
978 FindClose(hFind);
979
980 if (Out + _tcslen(FixedComponent) + 1 >= &FixedPath[MAX_PATH])
981 return _T("");
982 _tcscpy(Out, FixedComponent);
983 }
984 Filename = Out;
985 Out += _tcslen(Out);
986 *Out++ = _T('\\');
987
988 In = Next;
989 } while (In != NULL);
990 Out[-1] = _T('\0');
991
992 /* Build the result string. Start with attributes, modification time, and
993 * file size. If the file didn't exist, these fields will all be empty. */
994 Out = Result;
995 if (hFind != INVALID_HANDLE_VALUE)
996 {
997 if (Modifiers & M_ATTR)
998 {
999 static const struct {
1000 TCHAR Character;
1001 WORD Value;
1002 } *Attrib, Table[] = {
1003 { _T('d'), FILE_ATTRIBUTE_DIRECTORY },
1004 { _T('r'), FILE_ATTRIBUTE_READONLY },
1005 { _T('a'), FILE_ATTRIBUTE_ARCHIVE },
1006 { _T('h'), FILE_ATTRIBUTE_HIDDEN },
1007 { _T('s'), FILE_ATTRIBUTE_SYSTEM },
1008 { _T('c'), FILE_ATTRIBUTE_COMPRESSED },
1009 { _T('o'), FILE_ATTRIBUTE_OFFLINE },
1010 { _T('t'), FILE_ATTRIBUTE_TEMPORARY },
1011 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT },
1012 };
1013 for (Attrib = Table; Attrib != &Table[9]; Attrib++)
1014 {
1015 *Out++ = w32fd.dwFileAttributes & Attrib->Value
1016 ? Attrib->Character
1017 : _T('-');
1018 }
1019 *Out++ = _T(' ');
1020 }
1021 if (Modifiers & M_TIME)
1022 {
1023 FILETIME ft;
1024 SYSTEMTIME st;
1025 FileTimeToLocalFileTime(&w32fd.ftLastWriteTime, &ft);
1026 FileTimeToSystemTime(&ft, &st);
1027
1028 Out += FormatDate(Out, &st, TRUE);
1029 *Out++ = _T(' ');
1030 Out += FormatTime(Out, &st);
1031 *Out++ = _T(' ');
1032 }
1033 if (Modifiers & M_SIZE)
1034 {
1035 ULARGE_INTEGER Size;
1036 Size.LowPart = w32fd.nFileSizeLow;
1037 Size.HighPart = w32fd.nFileSizeHigh;
1038 Out += _stprintf(Out, _T("%I64u "), Size.QuadPart);
1039 }
1040 }
1041
1042 /* When using the path-searching syntax or the S modifier,
1043 * at least part of the file path is always included.
1044 * If none of the DPNX modifiers are present, include the full path */
1045 if (PathVarName || (Modifiers & M_SHORT))
1046 if ((Modifiers & (M_DRIVE | M_PATH | M_NAME | M_EXT)) == 0)
1047 Modifiers |= M_FULL;
1048
1049 /* Now add the requested parts of the name.
1050 * With the F modifier, add all parts to form the full path. */
1051 Extension = _tcsrchr(Filename, _T('.'));
1052 if (Modifiers & (M_DRIVE | M_FULL))
1053 {
1054 *Out++ = FixedPath[0];
1055 *Out++ = FixedPath[1];
1056 }
1057 if (Modifiers & (M_PATH | M_FULL))
1058 {
1059 memcpy(Out, &FixedPath[2], (char *)Filename - (char *)&FixedPath[2]);
1060 Out += Filename - &FixedPath[2];
1061 }
1062 if (Modifiers & (M_NAME | M_FULL))
1063 {
1064 while (*Filename && Filename != Extension)
1065 *Out++ = *Filename++;
1066 }
1067 if (Modifiers & (M_EXT | M_FULL))
1068 {
1069 if (Extension)
1070 Out = _stpcpy(Out, Extension);
1071 }
1072
1073 /* Trim trailing space which otherwise would appear as a
1074 * result of using the A/T/Z modifiers but no others. */
1075 while (Out != &Result[0] && Out[-1] == _T(' '))
1076 Out--;
1077 *Out = _T('\0');
1078
1079 return Result;
1080 }
1081
1082 LPCTSTR
1083 GetBatchVar(TCHAR *varName, UINT *varNameLen)
1084 {
1085 LPCTSTR ret;
1086 TCHAR *varNameEnd;
1087 BOOL dummy;
1088
1089 *varNameLen = 1;
1090
1091 switch ( *varName )
1092 {
1093 case _T('~'):
1094 varNameEnd = varName + 1;
1095 ret = GetEnhancedVar(&varNameEnd, FindArg);
1096 if (!ret)
1097 {
1098 error_syntax(varName);
1099 return NULL;
1100 }
1101 *varNameLen = varNameEnd - varName;
1102 return ret;
1103 case _T('0'):
1104 case _T('1'):
1105 case _T('2'):
1106 case _T('3'):
1107 case _T('4'):
1108 case _T('5'):
1109 case _T('6'):
1110 case _T('7'):
1111 case _T('8'):
1112 case _T('9'):
1113 return FindArg(*varName, &dummy);
1114
1115 case _T('*'):
1116 //
1117 // Copy over the raw params(not including the batch file name
1118 //
1119 return bc->raw_params;
1120
1121 case _T('%'):
1122 return _T("%");
1123 }
1124 return NULL;
1125 }
1126
1127 BOOL
1128 SubstituteVars(TCHAR *Src, TCHAR *Dest, TCHAR Delim)
1129 {
1130 #define APPEND(From, Length) { \
1131 if (Dest + (Length) > DestEnd) \
1132 goto too_long; \
1133 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1134 Dest += Length; }
1135 #define APPEND1(Char) { \
1136 if (Dest >= DestEnd) \
1137 goto too_long; \
1138 *Dest++ = Char; }
1139
1140 TCHAR *DestEnd = Dest + CMDLINE_LENGTH - 1;
1141 const TCHAR *Var;
1142 int VarLength;
1143 TCHAR *SubstStart;
1144 TCHAR EndChr;
1145 while (*Src)
1146 {
1147 if (*Src != Delim)
1148 {
1149 APPEND1(*Src++)
1150 continue;
1151 }
1152
1153 Src++;
1154 if (bc && Delim == _T('%'))
1155 {
1156 UINT NameLen;
1157 Var = GetBatchVar(Src, &NameLen);
1158 if (Var != NULL)
1159 {
1160 VarLength = _tcslen(Var);
1161 APPEND(Var, VarLength)
1162 Src += NameLen;
1163 continue;
1164 }
1165 }
1166
1167 /* Find the end of the variable name. A colon (:) will usually
1168 * end the name and begin the optional modifier, but not if it
1169 * is immediately followed by the delimiter (%VAR:%). */
1170 SubstStart = Src;
1171 while (*Src != Delim && !(*Src == _T(':') && Src[1] != Delim))
1172 {
1173 if (!*Src)
1174 goto bad_subst;
1175 Src++;
1176 }
1177
1178 EndChr = *Src;
1179 *Src = _T('\0');
1180 Var = GetEnvVarOrSpecial(SubstStart);
1181 *Src++ = EndChr;
1182 if (Var == NULL)
1183 {
1184 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1185 if (bc)
1186 continue;
1187 goto bad_subst;
1188 }
1189 VarLength = _tcslen(Var);
1190
1191 if (EndChr == Delim)
1192 {
1193 /* %VAR% - use as-is */
1194 APPEND(Var, VarLength)
1195 }
1196 else if (*Src == _T('~'))
1197 {
1198 /* %VAR:~[start][,length]% - substring
1199 * Negative values are offsets from the end */
1200 int Start = _tcstol(Src + 1, &Src, 0);
1201 int End = VarLength;
1202 if (Start < 0)
1203 Start += VarLength;
1204 Start = max(Start, 0);
1205 Start = min(Start, VarLength);
1206 if (*Src == _T(','))
1207 {
1208 End = _tcstol(Src + 1, &Src, 0);
1209 End += (End < 0) ? VarLength : Start;
1210 End = max(End, Start);
1211 End = min(End, VarLength);
1212 }
1213 if (*Src++ != Delim)
1214 goto bad_subst;
1215 APPEND(&Var[Start], End - Start);
1216 }
1217 else
1218 {
1219 /* %VAR:old=new% - replace all occurrences of old with new
1220 * %VAR:*old=new% - replace first occurrence only,
1221 * and remove everything before it */
1222 TCHAR *Old, *New;
1223 DWORD OldLength, NewLength;
1224 BOOL Star = FALSE;
1225 int LastMatch = 0, i = 0;
1226
1227 if (*Src == _T('*'))
1228 {
1229 Star = TRUE;
1230 Src++;
1231 }
1232
1233 /* the string to replace may contain the delimiter */
1234 Src = _tcschr(Old = Src, _T('='));
1235 if (Src == NULL)
1236 goto bad_subst;
1237 OldLength = Src++ - Old;
1238 if (OldLength == 0)
1239 goto bad_subst;
1240
1241 Src = _tcschr(New = Src, Delim);
1242 if (Src == NULL)
1243 goto bad_subst;
1244 NewLength = Src++ - New;
1245
1246 while (i < VarLength)
1247 {
1248 if (_tcsnicmp(&Var[i], Old, OldLength) == 0)
1249 {
1250 if (!Star)
1251 APPEND(&Var[LastMatch], i - LastMatch)
1252 APPEND(New, NewLength)
1253 i += OldLength;
1254 LastMatch = i;
1255 if (Star)
1256 break;
1257 continue;
1258 }
1259 i++;
1260 }
1261 APPEND(&Var[LastMatch], VarLength - LastMatch)
1262 }
1263 continue;
1264
1265 bad_subst:
1266 Src = SubstStart;
1267 if (!bc)
1268 APPEND1(Delim)
1269 }
1270 *Dest = _T('\0');
1271 return TRUE;
1272 too_long:
1273 ConOutResPrintf(STRING_ALIAS_ERROR);
1274 nErrorLevel = 9023;
1275 return FALSE;
1276 #undef APPEND
1277 #undef APPEND1
1278 }
1279
1280 /* Search the list of FOR contexts for a variable */
1281 static LPTSTR FindForVar(TCHAR Var, BOOL *IsParam0)
1282 {
1283 FOR_CONTEXT *Ctx;
1284 *IsParam0 = FALSE;
1285 for (Ctx = fc; Ctx != NULL; Ctx = Ctx->prev)
1286 if ((UINT)(Var - Ctx->firstvar) < Ctx->varcount)
1287 return Ctx->values[Var - Ctx->firstvar];
1288 return NULL;
1289 }
1290
1291 BOOL
1292 SubstituteForVars(TCHAR *Src, TCHAR *Dest)
1293 {
1294 TCHAR *DestEnd = &Dest[CMDLINE_LENGTH - 1];
1295 while (*Src)
1296 {
1297 if (Src[0] == _T('%'))
1298 {
1299 BOOL Dummy;
1300 LPTSTR End = &Src[2];
1301 LPTSTR Value = NULL;
1302
1303 if (Src[1] == _T('~'))
1304 Value = GetEnhancedVar(&End, FindForVar);
1305
1306 if (!Value)
1307 Value = FindForVar(Src[1], &Dummy);
1308
1309 if (Value)
1310 {
1311 if (Dest + _tcslen(Value) > DestEnd)
1312 return FALSE;
1313 Dest = _stpcpy(Dest, Value);
1314 Src = End;
1315 continue;
1316 }
1317 }
1318 /* Not a variable; just copy the character */
1319 if (Dest >= DestEnd)
1320 return FALSE;
1321 *Dest++ = *Src++;
1322 }
1323 *Dest = _T('\0');
1324 return TRUE;
1325 }
1326
1327 LPTSTR
1328 DoDelayedExpansion(LPTSTR Line)
1329 {
1330 TCHAR Buf1[CMDLINE_LENGTH];
1331 TCHAR Buf2[CMDLINE_LENGTH];
1332
1333 /* First, substitute FOR variables */
1334 if (!SubstituteForVars(Line, Buf1))
1335 return NULL;
1336
1337 if (!bDelayedExpansion || !_tcschr(Buf1, _T('!')))
1338 return cmd_dup(Buf1);
1339
1340 /* FIXME: Delayed substitutions actually aren't quite the same as
1341 * immediate substitutions. In particular, it's possible to escape
1342 * the exclamation point using ^. */
1343 if (!SubstituteVars(Buf1, Buf2, _T('!')))
1344 return NULL;
1345 return cmd_dup(Buf2);
1346 }
1347
1348
1349 /*
1350 * do the prompt/input/process loop
1351 *
1352 */
1353
1354 BOOL
1355 ReadLine (TCHAR *commandline, BOOL bMore)
1356 {
1357 TCHAR readline[CMDLINE_LENGTH];
1358 LPTSTR ip;
1359
1360 /* if no batch input then... */
1361 if (bc == NULL)
1362 {
1363 if (bMore)
1364 {
1365 ConOutResPrintf(STRING_MORE);
1366 }
1367 else
1368 {
1369 /* JPP 19980807 - if echo off, don't print prompt */
1370 if (bEcho)
1371 {
1372 if (!bIgnoreEcho)
1373 ConOutChar('\n');
1374 PrintPrompt();
1375 }
1376 }
1377
1378 if (!ReadCommand(readline, CMDLINE_LENGTH - 1))
1379 {
1380 bExit = TRUE;
1381 return FALSE;
1382 }
1383
1384 if (CheckCtrlBreak(BREAK_INPUT))
1385 {
1386 ConOutPuts(_T("\n"));
1387 return FALSE;
1388 }
1389 ip = readline;
1390 }
1391 else
1392 {
1393 ip = ReadBatchLine();
1394 if (!ip)
1395 return FALSE;
1396 }
1397
1398 return SubstituteVars(ip, commandline, _T('%'));
1399 }
1400
1401 static VOID
1402 ProcessInput()
1403 {
1404 PARSED_COMMAND *Cmd;
1405
1406 while (!bCanExit || !bExit)
1407 {
1408 Cmd = ParseCommand(NULL);
1409 if (!Cmd)
1410 continue;
1411
1412 ExecuteCommand(Cmd);
1413 FreeCommand(Cmd);
1414 }
1415 }
1416
1417
1418 /*
1419 * control-break handler.
1420 */
1421 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1422 {
1423
1424 DWORD dwWritten;
1425 INPUT_RECORD rec;
1426 static BOOL SelfGenerated = FALSE;
1427
1428 if ((dwCtrlType != CTRL_C_EVENT) &&
1429 (dwCtrlType != CTRL_BREAK_EVENT))
1430 {
1431 return FALSE;
1432 }
1433 else
1434 {
1435 if(SelfGenerated)
1436 {
1437 SelfGenerated = FALSE;
1438 return TRUE;
1439 }
1440 }
1441
1442 if (bChildProcessRunning == TRUE)
1443 {
1444 SelfGenerated = TRUE;
1445 GenerateConsoleCtrlEvent (dwCtrlType, 0);
1446 return TRUE;
1447 }
1448
1449
1450 rec.EventType = KEY_EVENT;
1451 rec.Event.KeyEvent.bKeyDown = TRUE;
1452 rec.Event.KeyEvent.wRepeatCount = 1;
1453 rec.Event.KeyEvent.wVirtualKeyCode = _T('C');
1454 rec.Event.KeyEvent.wVirtualScanCode = _T('C') - 35;
1455 rec.Event.KeyEvent.uChar.AsciiChar = _T('C');
1456 rec.Event.KeyEvent.uChar.UnicodeChar = _T('C');
1457 rec.Event.KeyEvent.dwControlKeyState = RIGHT_CTRL_PRESSED;
1458
1459 WriteConsoleInput(
1460 hIn,
1461 &rec,
1462 1,
1463 &dwWritten);
1464
1465 bCtrlBreak = TRUE;
1466 /* FIXME: Handle batch files */
1467
1468 //ConOutPrintf(_T("^C"));
1469
1470
1471 return TRUE;
1472 }
1473
1474
1475 VOID AddBreakHandler (VOID)
1476 {
1477 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1478 }
1479
1480
1481 VOID RemoveBreakHandler (VOID)
1482 {
1483 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1484 }
1485
1486
1487 /*
1488 * show commands and options that are available.
1489 *
1490 */
1491 #if 0
1492 static VOID
1493 ShowCommands (VOID)
1494 {
1495 /* print command list */
1496 ConOutResPuts(STRING_CMD_HELP1);
1497 PrintCommandList();
1498
1499 /* print feature list */
1500 ConOutResPuts(STRING_CMD_HELP2);
1501
1502 #ifdef FEATURE_ALIASES
1503 ConOutResPuts(STRING_CMD_HELP3);
1504 #endif
1505 #ifdef FEATURE_HISTORY
1506 ConOutResPuts(STRING_CMD_HELP4);
1507 #endif
1508 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1509 ConOutResPuts(STRING_CMD_HELP5);
1510 #endif
1511 #ifdef FEATURE_DIRECTORY_STACK
1512 ConOutResPuts(STRING_CMD_HELP6);
1513 #endif
1514 #ifdef FEATURE_REDIRECTION
1515 ConOutResPuts(STRING_CMD_HELP7);
1516 #endif
1517 ConOutChar(_T('\n'));
1518 }
1519 #endif
1520
1521 static VOID
1522 ExecuteAutoRunFile(HKEY hkeyRoot)
1523 {
1524 TCHAR autorun[2048];
1525 DWORD len = sizeof autorun;
1526 HKEY hkey;
1527
1528 if (RegOpenKeyEx(hkeyRoot,
1529 _T("SOFTWARE\\Microsoft\\Command Processor"),
1530 0,
1531 KEY_READ,
1532 &hkey ) == ERROR_SUCCESS)
1533 {
1534 if(RegQueryValueEx(hkey,
1535 _T("AutoRun"),
1536 0,
1537 0,
1538 (LPBYTE)autorun,
1539 &len) == ERROR_SUCCESS)
1540 {
1541 if (*autorun)
1542 ParseCommandLine(autorun);
1543 }
1544 RegCloseKey(hkey);
1545 }
1546 }
1547
1548 /* Get the command that comes after a /C or /K switch */
1549 static VOID
1550 GetCmdLineCommand(TCHAR *commandline, TCHAR *ptr, BOOL AlwaysStrip)
1551 {
1552 TCHAR *LastQuote;
1553
1554 while (_istspace(*ptr))
1555 ptr++;
1556
1557 /* Remove leading quote, find final quote */
1558 if (*ptr == _T('"') &&
1559 (LastQuote = _tcsrchr(++ptr, _T('"'))) != NULL)
1560 {
1561 TCHAR *Space;
1562 /* Under certain circumstances, all quotes are preserved.
1563 * CMD /? documents these conditions as follows:
1564 * 1. No /S switch
1565 * 2. Exactly two quotes
1566 * 3. No "special characters" between the quotes
1567 * (CMD /? says &<>()@^| but parentheses did not
1568 * trigger this rule when I tested them.)
1569 * 4. Whitespace exists between the quotes
1570 * 5. Enclosed string is an executable filename
1571 */
1572 *LastQuote = _T('\0');
1573 for (Space = ptr + 1; Space < LastQuote; Space++)
1574 {
1575 if (_istspace(*Space)) /* Rule 4 */
1576 {
1577 if (!AlwaysStrip && /* Rule 1 */
1578 !_tcspbrk(ptr, _T("\"&<>@^|")) && /* Rules 2, 3 */
1579 SearchForExecutable(ptr, commandline)) /* Rule 5 */
1580 {
1581 /* All conditions met: preserve both the quotes */
1582 *LastQuote = _T('"');
1583 _tcscpy(commandline, ptr - 1);
1584 return;
1585 }
1586 break;
1587 }
1588 }
1589
1590 /* The conditions were not met: remove both the
1591 * leading quote and the last quote */
1592 _tcscpy(commandline, ptr);
1593 _tcscpy(&commandline[LastQuote - ptr], LastQuote + 1);
1594 return;
1595 }
1596
1597 /* No quotes; just copy */
1598 _tcscpy(commandline, ptr);
1599 }
1600
1601 /*
1602 * set up global initializations and process parameters
1603 */
1604 static VOID
1605 Initialize()
1606 {
1607 HMODULE NtDllModule;
1608 TCHAR commandline[CMDLINE_LENGTH];
1609 TCHAR ModuleName[_MAX_PATH + 1];
1610 TCHAR lpBuffer[2];
1611 INT nExitCode;
1612
1613 //INT len;
1614 TCHAR *ptr, *cmdLine, option = 0;
1615 BOOL AlwaysStrip = FALSE;
1616 BOOL AutoRun = TRUE;
1617
1618 /* get version information */
1619 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1620 GetVersionEx (&osvi);
1621
1622 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1623 * build process. So don't link implicitly against ntdll.dll, load it
1624 * dynamically instead */
1625 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1626 if (NtDllModule != NULL)
1627 {
1628 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1629 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1630 }
1631
1632 InitLocale ();
1633
1634 /* get default input and output console handles */
1635 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1636 hIn = GetStdHandle (STD_INPUT_HANDLE);
1637
1638 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1639 for you can change the EnvirommentVariable for prompt before cmd start
1640 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1641 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1642 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer, sizeof(lpBuffer) / sizeof(lpBuffer[0])) == 0)
1643 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1644
1645 #ifdef FEATURE_DIR_STACK
1646 /* initialize directory stack */
1647 InitDirectoryStack ();
1648 #endif
1649
1650 #ifdef FEATURE_HISTORY
1651 /*initialize history*/
1652 InitHistory();
1653 #endif
1654
1655 /* Set COMSPEC environment variable */
1656 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1657 {
1658 ModuleName[_MAX_PATH] = _T('\0');
1659 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1660 }
1661
1662 /* add ctrl break handler */
1663 AddBreakHandler ();
1664
1665
1666 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1667
1668 cmdLine = GetCommandLine();
1669 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine));
1670
1671 for (ptr = cmdLine; *ptr; ptr++)
1672 {
1673 if (*ptr == _T('/'))
1674 {
1675 option = _totupper(ptr[1]);
1676 if (option == _T('?'))
1677 {
1678 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1679 nErrorLevel = 1;
1680 bExit = TRUE;
1681 return;
1682 }
1683 else if (option == _T('P'))
1684 {
1685 if (!IsExistingFile (_T("\\autoexec.bat")))
1686 {
1687 #ifdef INCLUDE_CMD_DATE
1688 cmd_date (_T(""));
1689 #endif
1690 #ifdef INCLUDE_CMD_TIME
1691 cmd_time (_T(""));
1692 #endif
1693 }
1694 else
1695 {
1696 ParseCommandLine (_T("\\autoexec.bat"));
1697 }
1698 bCanExit = FALSE;
1699 }
1700 else if (option == _T('A'))
1701 {
1702 bUnicodeOutput = FALSE;
1703 }
1704 else if (option == _T('C') || option == _T('K') || option == _T('R'))
1705 {
1706 /* Remainder of command line is a command to be run */
1707 break;
1708 }
1709 else if (option == _T('D'))
1710 {
1711 AutoRun = FALSE;
1712 }
1713 else if (option == _T('Q'))
1714 {
1715 bDisableBatchEcho = TRUE;
1716 }
1717 else if (option == _T('S'))
1718 {
1719 AlwaysStrip = TRUE;
1720 }
1721 #ifdef INCLUDE_CMD_COLOR
1722 else if (!_tcsnicmp(ptr, _T("/T:"), 3))
1723 {
1724 /* process /t (color) argument */
1725 wDefColor = (WORD)_tcstoul(&ptr[3], &ptr, 16);
1726 SetScreenColor(wDefColor, TRUE);
1727 }
1728 #endif
1729 else if (option == _T('U'))
1730 {
1731 bUnicodeOutput = TRUE;
1732 }
1733 else if (option == _T('V'))
1734 {
1735 bDelayedExpansion = _tcsnicmp(&ptr[2], _T(":OFF"), 4);
1736 }
1737 }
1738 }
1739
1740 if (!*ptr)
1741 {
1742 /* If neither /C or /K was given, display a simple version string */
1743 ConOutResPrintf(STRING_REACTOS_VERSION,
1744 _T(KERNEL_RELEASE_STR),
1745 _T(KERNEL_VERSION_BUILD_STR));
1746 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR) _T(" ReactOS Team."));
1747 }
1748
1749 if (AutoRun)
1750 {
1751 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE);
1752 ExecuteAutoRunFile(HKEY_CURRENT_USER);
1753 }
1754
1755 if (*ptr)
1756 {
1757 /* Do the /C or /K command */
1758 GetCmdLineCommand(commandline, &ptr[2], AlwaysStrip);
1759 nExitCode = ParseCommandLine(commandline);
1760 if (option != _T('K'))
1761 {
1762 nErrorLevel = nExitCode;
1763 bExit = TRUE;
1764 }
1765 }
1766 }
1767
1768
1769 static VOID Cleanup()
1770 {
1771 /* run cmdexit.bat */
1772 if (IsExistingFile (_T("cmdexit.bat")))
1773 {
1774 ConErrResPuts(STRING_CMD_ERROR5);
1775
1776 ParseCommandLine (_T("cmdexit.bat"));
1777 }
1778 else if (IsExistingFile (_T("\\cmdexit.bat")))
1779 {
1780 ConErrResPuts (STRING_CMD_ERROR5);
1781 ParseCommandLine (_T("\\cmdexit.bat"));
1782 }
1783
1784 #ifdef FEATURE_DIECTORY_STACK
1785 /* destroy directory stack */
1786 DestroyDirectoryStack ();
1787 #endif
1788
1789 #ifdef FEATURE_HISTORY
1790 CleanHistory();
1791 #endif
1792
1793 /* free GetEnvVar's buffer */
1794 GetEnvVar(NULL);
1795
1796 /* remove ctrl break handler */
1797 RemoveBreakHandler ();
1798 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1799 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1800 }
1801
1802 /*
1803 * main function
1804 */
1805 int cmd_main (int argc, const TCHAR *argv[])
1806 {
1807 HANDLE hConsole;
1808 TCHAR startPath[MAX_PATH];
1809 CONSOLE_SCREEN_BUFFER_INFO Info;
1810
1811 lpOriginalEnvironment = DuplicateEnvironment();
1812
1813 GetCurrentDirectory(MAX_PATH,startPath);
1814 _tchdir(startPath);
1815
1816 SetFileApisToOEM();
1817 InputCodePage= 0;
1818 OutputCodePage = 0;
1819
1820 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1821 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1822 OPEN_EXISTING, 0, NULL);
1823 if (hConsole != INVALID_HANDLE_VALUE)
1824 {
1825 if (!GetConsoleScreenBufferInfo(hConsole, &Info))
1826 {
1827 ConErrFormatMessage(GetLastError());
1828 return(1);
1829 }
1830 wDefColor = Info.wAttributes;
1831 CloseHandle(hConsole);
1832 }
1833
1834 InputCodePage= GetConsoleCP();
1835 OutputCodePage = GetConsoleOutputCP();
1836 CMD_ModuleHandle = GetModuleHandle(NULL);
1837
1838 /* check switches on command-line */
1839 Initialize();
1840
1841 /* call prompt routine */
1842 ProcessInput();
1843
1844 /* do the cleanup */
1845 Cleanup();
1846
1847 cmd_free(lpOriginalEnvironment);
1848
1849 cmd_exit(nErrorLevel);
1850 return(nErrorLevel);
1851 }
1852
1853 /* EOF */