Release 20030408.
[wine/gsoc-2012-control.git] / programs / wcmd / wcmdmain.c
blob6f660cf15335c720ad73dff59d9dd954badb6a2d
1 /*
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
22 * FIXME:
23 * - Cannot handle parameters in quotes
24 * - Lots of functionality missing from builtins
27 #include "wcmd.h"
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" };
35 HINSTANCE hinst;
36 DWORD errorlevel;
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 any 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
47 * winmain().
50 int main (int argc, char *argv[]) {
52 char string[1024], args[MAX_PATH], param[MAX_PATH];
53 int i;
54 DWORD count;
55 HANDLE h;
57 args[0] = param[0] = '\0';
58 if (argc > 1) {
59 /* interpreter options must come before the command to execute.
60 * Any options after the command are command options, not interpreter options.
62 for (i=1; i<argc && argv[i][0] == '/'; i++)
63 strcat (args, argv[i]);
64 for (; i<argc; i++) {
65 strcat (param, argv[i]);
66 strcat (param, " ");
70 /* If we do a "wcmd /c command", we don't want to allocate a new
71 * console since the command returns immediately. Rather, we use
72 * the surrently allocated input and output handles. This allows
73 * us to pipe to and read from the command interpreter.
75 if (strstr(args, "/c") != NULL) {
76 WCMD_process_command (param);
77 return 0;
80 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT |
81 ENABLE_PROCESSED_INPUT);
82 SetConsoleTitle("Wine Command Prompt");
85 * Execute any command-line options.
88 if (strstr(args, "/q") != NULL) {
89 WCMD_echo ("OFF");
92 if (strstr(args, "/k") != NULL) {
93 WCMD_process_command (param);
97 * If there is an AUTOEXEC.BAT file, try to execute it.
100 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
101 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
102 if (h != INVALID_HANDLE_VALUE) {
103 CloseHandle (h);
104 #if 0
105 WCMD_batch_command (string);
106 #endif
110 * Loop forever getting commands and executing them.
113 WCMD_version ();
114 while (TRUE) {
115 WCMD_show_prompt ();
116 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
117 if (count > 1) {
118 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
119 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
120 if (lstrlen (string) != 0) {
121 if (strchr(string,'|') != NULL) {
122 WCMD_pipe (string);
124 else {
125 WCMD_process_command (string);
133 /*****************************************************************************
134 * Process one command. If the command is EXIT this routine does not return.
135 * We will recurse through here executing batch files.
139 void WCMD_process_command (char *command) {
141 char cmd[1024];
142 char *p;
143 int status, i;
144 DWORD count;
145 HANDLE old_stdin = 0, old_stdout = 0, h;
146 char *whichcmd;
150 * Expand up environment variables.
153 status = ExpandEnvironmentStrings (command, cmd, sizeof(cmd));
154 if (!status) {
155 WCMD_print_error ();
156 return;
160 * Changing default drive has to be handled as a special case.
163 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
164 status = SetCurrentDirectory (cmd);
165 if (!status) WCMD_print_error ();
166 return;
169 /* Dont issue newline WCMD_output (newline); @JED*/
172 * Redirect stdin and/or stdout if required.
175 if ((p = strchr(cmd,'<')) != NULL) {
176 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
177 FILE_ATTRIBUTE_NORMAL, NULL);
178 if (h == INVALID_HANDLE_VALUE) {
179 WCMD_print_error ();
180 return;
182 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
183 SetStdHandle (STD_INPUT_HANDLE, h);
185 if ((p = strchr(cmd,'>')) != NULL) {
186 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
187 FILE_ATTRIBUTE_NORMAL, NULL);
188 if (h == INVALID_HANDLE_VALUE) {
189 WCMD_print_error ();
190 return;
192 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
193 SetStdHandle (STD_OUTPUT_HANDLE, h);
194 *--p = '\0';
196 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
199 * Strip leading whitespaces, and a '@' if supplied
201 whichcmd = WCMD_strtrim_leading_spaces(cmd);
202 if (whichcmd[0] == '@') whichcmd++;
205 * Check if the command entered is internal. If it is, pass the rest of the
206 * line down to the command. If not try to run a program.
209 count = 0;
210 while (IsCharAlphaNumeric(whichcmd[count])) {
211 count++;
213 for (i=0; i<=WCMD_EXIT; i++) {
214 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
215 whichcmd, count, inbuilt[i], -1) == 2) break;
217 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
218 WCMD_parse (p, quals, param1, param2);
219 switch (i) {
221 case WCMD_ATTRIB:
222 WCMD_setshow_attrib ();
223 break;
224 case WCMD_CALL:
225 WCMD_batch (param1, p, 1);
226 break;
227 case WCMD_CD:
228 case WCMD_CHDIR:
229 WCMD_setshow_default ();
230 break;
231 case WCMD_CLS:
232 WCMD_clear_screen ();
233 break;
234 case WCMD_COPY:
235 WCMD_copy ();
236 break;
237 case WCMD_CTTY:
238 WCMD_change_tty ();
239 break;
240 case WCMD_DATE:
241 WCMD_setshow_date ();
242 break;
243 case WCMD_DEL:
244 case WCMD_ERASE:
245 WCMD_delete (0);
246 break;
247 case WCMD_DIR:
248 WCMD_directory ();
249 break;
250 case WCMD_ECHO:
251 /* Use the unstripped version of the following data - step over the space */
252 /* but only if a parameter follows */
253 if (strlen(&whichcmd[count]) > 0)
254 WCMD_echo(&whichcmd[count+1]);
255 else
256 WCMD_echo(&whichcmd[count]);
257 break;
258 case WCMD_FOR:
259 WCMD_for (p);
260 break;
261 case WCMD_GOTO:
262 WCMD_goto ();
263 break;
264 case WCMD_HELP:
265 WCMD_give_help (p);
266 break;
267 case WCMD_IF:
268 WCMD_if (p);
269 break;
270 case WCMD_LABEL:
271 WCMD_volume (1, p);
272 break;
273 case WCMD_MD:
274 case WCMD_MKDIR:
275 WCMD_create_dir ();
276 break;
277 case WCMD_MOVE:
278 WCMD_move ();
279 break;
280 case WCMD_PATH:
281 WCMD_setshow_path (p);
282 break;
283 case WCMD_PAUSE:
284 WCMD_pause ();
285 break;
286 case WCMD_PROMPT:
287 WCMD_setshow_prompt ();
288 break;
289 case WCMD_REM:
290 break;
291 case WCMD_REN:
292 case WCMD_RENAME:
293 WCMD_rename ();
294 break;
295 case WCMD_RD:
296 case WCMD_RMDIR:
297 WCMD_remove_dir ();
298 break;
299 case WCMD_SET:
300 WCMD_setshow_env (p);
301 break;
302 case WCMD_SHIFT:
303 WCMD_shift ();
304 break;
305 case WCMD_TIME:
306 WCMD_setshow_time ();
307 break;
308 case WCMD_TITLE:
309 if (strlen(&whichcmd[count]) > 0)
310 WCMD_title(&whichcmd[count+1]);
311 break;
312 case WCMD_TYPE:
313 WCMD_type ();
314 break;
315 case WCMD_VER:
316 WCMD_version ();
317 break;
318 case WCMD_VERIFY:
319 WCMD_verify (p);
320 break;
321 case WCMD_VOL:
322 WCMD_volume (0, p);
323 break;
324 case WCMD_EXIT:
325 ExitProcess (0);
326 default:
327 WCMD_run_program (whichcmd);
329 if (old_stdin) {
330 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
331 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
333 if (old_stdout) {
334 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
335 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
339 /******************************************************************************
340 * WCMD_run_program
342 * Execute a command line as an external program. If no extension given then
343 * precedence is given to .BAT files. Must allow recursion.
345 * FIXME: Case sensitivity in suffixes!
348 void WCMD_run_program (char *command) {
350 STARTUPINFO st;
351 PROCESS_INFORMATION pe;
352 SHFILEINFO psfi;
353 DWORD console;
354 BOOL status;
355 HANDLE h;
356 HINSTANCE hinst;
357 char filetorun[MAX_PATH];
359 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
360 if (!(*param1) && !(*param2))
361 return;
362 if (strpbrk (param1, "\\:") == NULL) { /* No explicit path given */
363 if ((strchr (param1, '.') == NULL) || (strstr (param1, ".bat") != NULL)) {
364 if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
365 WCMD_batch (filetorun, command, 0);
366 return;
369 if ((strchr (param1, '.') == NULL) || (strstr (param1, ".cmd") != NULL)) {
370 if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
371 WCMD_batch (filetorun, command, 0);
372 return;
376 else { /* Explicit path given */
377 if ((strstr (param1, ".bat") != NULL) ||
378 (strstr (param1, ".cmd") != NULL)) {
379 WCMD_batch (param1, command, 0);
380 return;
382 if (strchr (param1, '.') == NULL) {
383 strcpy (filetorun, param1);
384 strcat (filetorun, ".bat");
385 h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
386 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
387 if (h != INVALID_HANDLE_VALUE) {
388 CloseHandle (h);
389 WCMD_batch (param1, command, 0);
390 return;
395 /* No batch file found, assume executable */
397 hinst = FindExecutable (param1, NULL, filetorun);
398 if ((int)hinst < 32) {
399 WCMD_print_error ();
400 return;
402 console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
403 ZeroMemory (&st, sizeof(STARTUPINFO));
404 st.cb = sizeof(STARTUPINFO);
405 status = CreateProcess (NULL, command, NULL, NULL, FALSE,
406 0, NULL, NULL, &st, &pe);
407 if (!status) {
408 WCMD_print_error ();
409 return;
411 if (!console) errorlevel = 0;
412 else
414 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
415 GetExitCodeProcess (pe.hProcess, &errorlevel);
416 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
420 /******************************************************************************
421 * WCMD_show_prompt
423 * Display the prompt on STDout
427 void WCMD_show_prompt (void) {
429 int status;
430 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
431 char *p, *q;
433 status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
434 if ((status == 0) || (status > sizeof(prompt_string))) {
435 lstrcpy (prompt_string, "$P$G");
437 p = prompt_string;
438 q = out_string;
439 *q = '\0';
440 while (*p != '\0') {
441 if (*p != '$') {
442 *q++ = *p++;
443 *q = '\0';
445 else {
446 p++;
447 switch (toupper(*p)) {
448 case '$':
449 *q++ = '$';
450 break;
451 case 'B':
452 *q++ = '|';
453 break;
454 case 'D':
455 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
456 while (*q) q++;
457 break;
458 case 'E':
459 *q++ = '\E';
460 break;
461 case 'G':
462 *q++ = '>';
463 break;
464 case 'L':
465 *q++ = '<';
466 break;
467 case 'N':
468 status = GetCurrentDirectory (sizeof(curdir), curdir);
469 if (status) {
470 *q++ = curdir[0];
472 break;
473 case 'P':
474 status = GetCurrentDirectory (sizeof(curdir), curdir);
475 if (status) {
476 lstrcat (q, curdir);
477 while (*q) q++;
479 break;
480 case 'Q':
481 *q++ = '=';
482 break;
483 case 'T':
484 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
485 while (*q) q++;
486 break;
487 case 'V':
488 lstrcat (q, version_string);
489 while (*q) q++;
490 break;
491 case '_':
492 *q++ = '\n';
493 break;
495 p++;
496 *q = '\0';
499 WCMD_output (out_string);
502 /****************************************************************************
503 * WCMD_print_error
505 * Print the message for GetLastError
508 void WCMD_print_error (void) {
509 LPVOID lpMsgBuf;
510 DWORD error_code;
511 int status;
513 error_code = GetLastError ();
514 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
515 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
516 if (!status) {
517 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
518 error_code, GetLastError());
519 return;
521 WCMD_output (lpMsgBuf);
522 LocalFree ((HLOCAL)lpMsgBuf);
523 WCMD_output (newline);
524 return;
527 /*******************************************************************
528 * WCMD_parse - parse a command into parameters and qualifiers.
530 * On exit, all qualifiers are concatenated into q, the first string
531 * not beginning with "/" is in p1 and the
532 * second in p2. Any subsequent non-qualifier strings are lost.
533 * Parameters in quotes are handled.
536 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
538 int p = 0;
540 *q = *p1 = *p2 = '\0';
541 while (TRUE) {
542 switch (*s) {
543 case '/':
544 *q++ = *s++;
545 while ((*s != '\0') && (*s != ' ') && *s != '/') {
546 *q++ = toupper (*s++);
548 *q = '\0';
549 break;
550 case ' ':
551 s++;
552 break;
553 case '"':
554 s++;
555 while ((*s != '\0') && (*s != '"')) {
556 if (p == 0) *p1++ = *s++;
557 else if (p == 1) *p2++ = *s++;
558 else s++;
560 if (p == 0) *p1 = '\0';
561 if (p == 1) *p2 = '\0';
562 p++;
563 if (*s == '"') s++;
564 break;
565 case '\0':
566 return;
567 default:
568 while ((*s != '\0') && (*s != ' ')) {
569 if (p == 0) *p1++ = *s++;
570 else if (p == 1) *p2++ = *s++;
571 else s++;
573 if (p == 0) *p1 = '\0';
574 if (p == 1) *p2 = '\0';
575 p++;
580 /*******************************************************************
581 * WCMD_output - send output to current standard output device.
585 void WCMD_output (char *format, ...) {
587 va_list ap;
588 char string[1024];
590 va_start(ap,format);
591 vsprintf (string, format, ap);
592 va_end(ap);
593 WCMD_output_asis(string);
597 static int line_count;
598 static int max_height;
599 static BOOL paged_mode;
601 void WCMD_enter_paged_mode(void)
603 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
605 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
606 max_height = consoleInfo.dwSize.Y;
607 else
608 max_height = 25;
609 paged_mode = TRUE;
610 line_count = 5; /* keep 5 lines from previous output */
613 void WCMD_leave_paged_mode(void)
615 paged_mode = FALSE;
618 /*******************************************************************
619 * WCMD_output_asis - send output to current standard output device.
620 * without formatting eg. when message contains '%'
623 void WCMD_output_asis (char *message) {
624 DWORD count;
625 char* ptr;
626 char string[1024];
628 if (paged_mode) {
629 do {
630 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
631 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
632 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
633 if (ptr) {
634 if (++line_count >= max_height - 1) {
635 line_count = 0;
636 WCMD_output_asis (anykey);
637 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
640 } while ((message = ptr) != NULL);
641 } else {
642 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
647 /***************************************************************************
648 * WCMD_strtrim_leading_spaces
650 * Remove leading spaces from a string. Return a pointer to the first
651 * non-space character. Does not modify the input string
654 char *WCMD_strtrim_leading_spaces (char *string) {
656 char *ptr;
658 ptr = string;
659 while (*ptr == ' ') ptr++;
660 return ptr;
663 /*************************************************************************
664 * WCMD_strtrim_trailing_spaces
666 * Remove trailing spaces from a string. This routine modifies the input
667 * string by placing a null after the last non-space character
670 void WCMD_strtrim_trailing_spaces (char *string) {
672 char *ptr;
674 ptr = string + lstrlen (string) - 1;
675 while ((*ptr == ' ') && (ptr >= string)) {
676 *ptr = '\0';
677 ptr--;
681 /*************************************************************************
682 * WCMD_pipe
684 * Handle pipes within a command - the DOS way using temporary files.
687 void WCMD_pipe (char *command) {
689 char *p;
690 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
692 GetTempPath (sizeof(temp_path), temp_path);
693 GetTempFileName (temp_path, "WCMD", 0, temp_file);
694 p = strchr(command, '|');
695 *p++ = '\0';
696 wsprintf (temp_cmd, "%s > %s", command, temp_file);
697 WCMD_process_command (temp_cmd);
698 command = p;
699 while ((p = strchr(command, '|'))) {
700 *p++ = '\0';
701 GetTempFileName (temp_path, "WCMD", 0, temp_file2);
702 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
703 WCMD_process_command (temp_cmd);
704 DeleteFile (temp_file);
705 lstrcpy (temp_file, temp_file2);
706 command = p;
708 wsprintf (temp_cmd, "%s < %s", command, temp_file);
709 WCMD_process_command (temp_cmd);
710 DeleteFile (temp_file);