2 * WCMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 D A Pickles
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * - Cannot handle parameters in quotes
24 * - Lots of functionality missing from builtins
29 char *inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
30 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
31 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
32 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
33 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL", "EXIT" };
37 int echo_mode = 1, verify_mode = 0;
38 char nyi[] = "Not Yet Implemented\n\n";
39 char newline[] = "\n";
40 char version_string[] = "WCMD Version 0.17\n\n";
41 char anykey[] = "Press Return key to continue: ";
42 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
43 BATCH_CONTEXT *context = NULL;
45 /*****************************************************************************
46 * Main entry point. This is a console application so we have a main() not a
50 int main (int argc, char *argv[])
56 int opt_c, opt_k, opt_q;
62 if (lstrcmpi(*argv,"/c")==0) {
66 } else if (lstrcmpi(*argv,"/q")==0) {
68 } else if (lstrcmpi(*argv,"/k")==0) {
72 } else if (lstrcmpi(*argv,"/t")==0 || lstrcmpi(*argv,"/x")==0 ||
73 lstrcmpi(*argv,"/y")==0) {
74 /* Ignored for compatibility with Windows */
90 /* Build the command to execute */
92 for (arg = argv; *arg; arg++)
100 if( !*a ) has_space=1;
105 if (*a==' ' || *a=='\t') {
107 } else if (*a=='"') {
108 /* doubling of '\' preceeding a '"',
109 * plus escaping of said '"'
117 len+=(a-*arg)+1 /* for the separating space */;
119 len+=2; /* for the quotes */
122 cmd = HeapAlloc(GetProcessHeap(), 0, len);
127 for (arg = argv; *arg; arg++)
129 int has_space,has_quote;
132 /* Check for quotes and spaces in this argument */
133 has_space=has_quote=0;
135 if( !*a ) has_space=1;
137 if (*a==' ' || *a=='\t') {
141 } else if (*a=='"') {
149 /* Now transfer it to the command line */
166 /* Double all the '\\' preceeding this '"', plus one */
167 for (i=0;i<=bcount;i++)
186 p--; /* remove last space */
191 /* If we do a "wcmd /c command", we don't want to allocate a new
192 * console since the command returns immediately. Rather, we use
193 * the currently allocated input and output handles. This allows
194 * us to pipe to and read from the command interpreter.
196 if (strchr(cmd,'|') != NULL)
199 WCMD_process_command(cmd);
200 HeapFree(GetProcessHeap(), 0, cmd);
204 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
205 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
206 SetConsoleTitle("Wine Command Prompt");
209 WCMD_process_command(cmd);
210 HeapFree(GetProcessHeap(), 0, cmd);
214 * If there is an AUTOEXEC.BAT file, try to execute it.
217 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
218 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
219 if (h != INVALID_HANDLE_VALUE) {
222 WCMD_batch_command (string);
227 * Loop forever getting commands and executing them.
233 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
235 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
236 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
237 if (lstrlen (string) != 0) {
238 if (strchr(string,'|') != NULL) {
242 WCMD_process_command (string);
250 /*****************************************************************************
251 * Process one command. If the command is EXIT this routine does not return.
252 * We will recurse through here executing batch files.
256 void WCMD_process_command (char *command)
261 HANDLE old_stdin = 0, old_stdout = 0, h;
263 SECURITY_ATTRIBUTES sa;
266 * Expand up environment variables.
268 len = ExpandEnvironmentStrings (command, NULL, 0);
269 cmd = HeapAlloc( GetProcessHeap(), 0, len );
270 status = ExpandEnvironmentStrings (command, cmd, len);
273 HeapFree( GetProcessHeap(), 0, cmd );
278 * Changing default drive has to be handled as a special case.
281 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
282 status = SetCurrentDirectory (cmd);
283 if (!status) WCMD_print_error ();
284 HeapFree( GetProcessHeap(), 0, cmd );
288 /* Dont issue newline WCMD_output (newline); @JED*/
290 sa.nLength = sizeof(sa);
291 sa.lpSecurityDescriptor = NULL;
292 sa.bInheritHandle = TRUE;
294 * Redirect stdin and/or stdout if required.
297 if ((p = strchr(cmd,'<')) != NULL) {
298 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
299 FILE_ATTRIBUTE_NORMAL, NULL);
300 if (h == INVALID_HANDLE_VALUE) {
302 HeapFree( GetProcessHeap(), 0, cmd );
305 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
306 SetStdHandle (STD_INPUT_HANDLE, h);
308 if ((p = strchr(cmd,'>')) != NULL) {
309 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_WRITE, 0, &sa, CREATE_ALWAYS,
310 FILE_ATTRIBUTE_NORMAL, NULL);
311 if (h == INVALID_HANDLE_VALUE) {
313 HeapFree( GetProcessHeap(), 0, cmd );
316 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
317 SetStdHandle (STD_OUTPUT_HANDLE, h);
320 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
323 * Strip leading whitespaces, and a '@' if supplied
325 whichcmd = WCMD_strtrim_leading_spaces(cmd);
326 if (whichcmd[0] == '@') whichcmd++;
329 * Check if the command entered is internal. If it is, pass the rest of the
330 * line down to the command. If not try to run a program.
334 while (IsCharAlphaNumeric(whichcmd[count])) {
337 for (i=0; i<=WCMD_EXIT; i++) {
338 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
339 whichcmd, count, inbuilt[i], -1) == 2) break;
341 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
342 WCMD_parse (p, quals, param1, param2);
346 WCMD_setshow_attrib ();
349 WCMD_batch (param1, p, 1);
353 WCMD_setshow_default ();
356 WCMD_clear_screen ();
365 WCMD_setshow_date ();
375 /* Use the unstripped version of the following data - step over the space */
376 /* but only if a parameter follows */
377 if (strlen(&whichcmd[count]) > 0)
378 WCMD_echo(&whichcmd[count+1]);
380 WCMD_echo(&whichcmd[count]);
405 WCMD_setshow_path (p);
411 WCMD_setshow_prompt ();
424 WCMD_setshow_env (p);
430 WCMD_setshow_time ();
433 if (strlen(&whichcmd[count]) > 0)
434 WCMD_title(&whichcmd[count+1]);
451 WCMD_run_program (whichcmd);
453 HeapFree( GetProcessHeap(), 0, cmd );
455 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
456 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
459 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
460 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
464 /******************************************************************************
467 * Execute a command line as an external program. If no extension given then
468 * precedence is given to .BAT files. Must allow recursion.
470 * FIXME: Case sensitivity in suffixes!
473 void WCMD_run_program (char *command) {
476 PROCESS_INFORMATION pe;
482 char filetorun[MAX_PATH];
484 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
485 if (!(*param1) && !(*param2))
487 if (strpbrk (param1, "/\\:") == NULL) { /* No explicit path given */
488 char *ext = strrchr( param1, '.' );
489 if (!ext || !strcasecmp( ext, ".bat"))
491 if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
492 WCMD_batch (filetorun, command, 0);
496 if (!ext || !strcasecmp( ext, ".cmd"))
498 if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
499 WCMD_batch (filetorun, command, 0);
504 else { /* Explicit path given */
505 char *ext = strrchr( param1, '.' );
506 if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
508 WCMD_batch (param1, command, 0);
512 if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
515 strcpy (filetorun, param1);
516 strcat (filetorun, ".bat");
517 h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
518 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
519 if (h != INVALID_HANDLE_VALUE) {
521 WCMD_batch (param1, command, 0);
527 /* No batch file found, assume executable */
529 hinst = FindExecutable (param1, NULL, filetorun);
530 if ((int)hinst < 32) {
534 console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
535 ZeroMemory (&st, sizeof(STARTUPINFO));
536 st.cb = sizeof(STARTUPINFO);
537 status = CreateProcess (NULL, command, NULL, NULL, TRUE,
538 0, NULL, NULL, &st, &pe);
543 if (!console) errorlevel = 0;
546 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
547 GetExitCodeProcess (pe.hProcess, &errorlevel);
548 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
550 CloseHandle(pe.hProcess);
551 CloseHandle(pe.hThread);
554 /******************************************************************************
557 * Display the prompt on STDout
561 void WCMD_show_prompt (void) {
564 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
567 status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
568 if ((status == 0) || (status > sizeof(prompt_string))) {
569 lstrcpy (prompt_string, "$P$G");
581 switch (toupper(*p)) {
589 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
602 status = GetCurrentDirectory (sizeof(curdir), curdir);
608 status = GetCurrentDirectory (sizeof(curdir), curdir);
618 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
622 lstrcat (q, version_string);
633 WCMD_output (out_string);
636 /****************************************************************************
639 * Print the message for GetLastError
642 void WCMD_print_error (void) {
647 error_code = GetLastError ();
648 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
649 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
651 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
652 error_code, GetLastError());
655 WCMD_output (lpMsgBuf);
656 LocalFree ((HLOCAL)lpMsgBuf);
657 WCMD_output (newline);
661 /*******************************************************************
662 * WCMD_parse - parse a command into parameters and qualifiers.
664 * On exit, all qualifiers are concatenated into q, the first string
665 * not beginning with "/" is in p1 and the
666 * second in p2. Any subsequent non-qualifier strings are lost.
667 * Parameters in quotes are handled.
670 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
674 *q = *p1 = *p2 = '\0';
679 while ((*s != '\0') && (*s != ' ') && *s != '/') {
680 *q++ = toupper (*s++);
689 while ((*s != '\0') && (*s != '"')) {
690 if (p == 0) *p1++ = *s++;
691 else if (p == 1) *p2++ = *s++;
694 if (p == 0) *p1 = '\0';
695 if (p == 1) *p2 = '\0';
702 while ((*s != '\0') && (*s != ' ')) {
703 if (p == 0) *p1++ = *s++;
704 else if (p == 1) *p2++ = *s++;
707 if (p == 0) *p1 = '\0';
708 if (p == 1) *p2 = '\0';
714 /*******************************************************************
715 * WCMD_output - send output to current standard output device.
719 void WCMD_output (char *format, ...) {
725 vsprintf (string, format, ap);
727 WCMD_output_asis(string);
731 static int line_count;
732 static int max_height;
733 static BOOL paged_mode;
735 void WCMD_enter_paged_mode(void)
737 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
739 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
740 max_height = consoleInfo.dwSize.Y;
744 line_count = 5; /* keep 5 lines from previous output */
747 void WCMD_leave_paged_mode(void)
752 /*******************************************************************
753 * WCMD_output_asis - send output to current standard output device.
754 * without formatting eg. when message contains '%'
757 void WCMD_output_asis (char *message) {
764 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
765 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
766 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
768 if (++line_count >= max_height - 1) {
770 WCMD_output_asis (anykey);
771 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
774 } while ((message = ptr) != NULL);
776 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
781 /***************************************************************************
782 * WCMD_strtrim_leading_spaces
784 * Remove leading spaces from a string. Return a pointer to the first
785 * non-space character. Does not modify the input string
788 char *WCMD_strtrim_leading_spaces (char *string) {
793 while (*ptr == ' ') ptr++;
797 /*************************************************************************
798 * WCMD_strtrim_trailing_spaces
800 * Remove trailing spaces from a string. This routine modifies the input
801 * string by placing a null after the last non-space character
804 void WCMD_strtrim_trailing_spaces (char *string) {
808 ptr = string + lstrlen (string) - 1;
809 while ((*ptr == ' ') && (ptr >= string)) {
815 /*************************************************************************
818 * Handle pipes within a command - the DOS way using temporary files.
821 void WCMD_pipe (char *command) {
824 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
826 GetTempPath (sizeof(temp_path), temp_path);
827 GetTempFileName (temp_path, "WCMD", 0, temp_file);
828 p = strchr(command, '|');
830 wsprintf (temp_cmd, "%s > %s", command, temp_file);
831 WCMD_process_command (temp_cmd);
833 while ((p = strchr(command, '|'))) {
835 GetTempFileName (temp_path, "WCMD", 0, temp_file2);
836 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
837 WCMD_process_command (temp_cmd);
838 DeleteFile (temp_file);
839 lstrcpy (temp_file, temp_file2);
842 wsprintf (temp_cmd, "%s < %s", command, temp_file);
843 WCMD_process_command (temp_cmd);
844 DeleteFile (temp_file);