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