Added regedit unit test, a couple minor changes to regedit.
[wine] / programs / wcmd / wcmdmain.c
1 /*
2  * WCMD - Wine-compatible command line interface.
3  *
4  * Copyright (C) 1999 - 2001 D A Pickles
5  *
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.
10  *
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.
15  *
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
19  */
20
21 /*
22  * FIXME:
23  * - Cannot handle parameters in quotes
24  * - Lots of functionality missing from builtins
25  */
26
27 #include "wcmd.h"
28
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"  };
34
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;
44
45 /*****************************************************************************
46  * Main entry point. This is a console application so we have a main() not a
47  * winmain().
48  */
49
50 int main (int argc, char *argv[]) {
51
52 char string[1024], args[MAX_PATH], param[MAX_PATH];
53 int status, i;
54 DWORD count;
55 HANDLE h;
56
57   args[0] = param[0] = '\0';
58   if (argc > 1) {
59     for (i=1; i<argc; i++) {
60       if (argv[i][0] == '/') {
61         strcat (args, argv[i]);
62       }
63       else {
64         strcat (param, argv[i]);
65         strcat (param, " ");
66       }
67     }
68   }
69
70 /*
71  *      Allocate a console and set it up.
72  */
73
74   status = FreeConsole ();
75   if (!status) WCMD_print_error();
76   status = AllocConsole();
77   if (!status) WCMD_print_error();
78   SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT |
79         ENABLE_PROCESSED_INPUT);
80   SetConsoleTitle("Wine Command Prompt");
81
82 /*
83  *      Execute any command-line options.
84  */
85
86   if (strstr(args, "/q") != NULL) {
87     WCMD_echo ("OFF");
88   }
89
90   if (strstr(args, "/c") != NULL) {
91     WCMD_process_command (param);
92     return 0;
93   }
94
95   if (strstr(args, "/k") != NULL) {
96     WCMD_process_command (param);
97   }
98
99 /*
100  *      If there is an AUTOEXEC.BAT file, try to execute it.
101  */
102
103   GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
104   h = CreateFile (string, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
105   if (h != INVALID_HANDLE_VALUE) {
106     CloseHandle (h);
107 #if 0
108     WCMD_batch (string, " ");
109 #endif
110   }
111
112 /*
113  *      Loop forever getting commands and executing them.
114  */
115
116   WCMD_version ();
117   while (TRUE) {
118     WCMD_show_prompt ();
119     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
120     if (count > 1) {
121       string[count-1] = '\0';           /* ReadFile output is not null-terminated! */
122       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
123       if (lstrlen (string) != 0) {
124         if (strchr(string,'|') != NULL) {
125           WCMD_pipe (string);
126         }
127         else {
128           WCMD_process_command (string);
129         }
130       }
131     }
132   }
133 }
134
135
136 /*****************************************************************************
137  * Process one command. If the command is EXIT this routine does not return.
138  * We will recurse through here executing batch files.
139  */
140
141
142 void WCMD_process_command (char *command) {
143
144 char cmd[1024];
145 char *p;
146 int status, i;
147 DWORD count;
148 HANDLE old_stdin = 0, old_stdout = 0, h;
149 char *whichcmd;
150
151
152 /*
153  *      Expand up environment variables.
154  */
155
156     status = ExpandEnvironmentStrings (command, cmd, sizeof(cmd));
157     if (!status) {
158       WCMD_print_error ();
159       return;
160     }
161
162 /*
163  *      Changing default drive has to be handled as a special case.
164  */
165
166     if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
167       status = SetCurrentDirectory (cmd);
168       if (!status) WCMD_print_error ();
169       return;
170     }
171
172     /* Dont issue newline WCMD_output (newline);           @JED*/
173
174 /*
175  *      Redirect stdin and/or stdout if required.
176  */
177
178     if ((p = strchr(cmd,'<')) != NULL) {
179       h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, 0, NULL, OPEN_EXISTING,
180                 FILE_ATTRIBUTE_NORMAL, NULL);
181       if (h == INVALID_HANDLE_VALUE) {
182         WCMD_print_error ();
183         return;
184       }
185       old_stdin = GetStdHandle (STD_INPUT_HANDLE);
186       SetStdHandle (STD_INPUT_HANDLE, h);
187     }
188     if ((p = strchr(cmd,'>')) != NULL) {
189       h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
190                 FILE_ATTRIBUTE_NORMAL, NULL);
191       if (h == INVALID_HANDLE_VALUE) {
192         WCMD_print_error ();
193         return;
194       }
195       old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
196       SetStdHandle (STD_OUTPUT_HANDLE, h);
197       *--p = '\0';
198     }
199     if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
200
201 /*
202  * Strip leading whitespaces, and a '@' if supplied
203  */
204     whichcmd = WCMD_strtrim_leading_spaces(cmd);
205     if (whichcmd[0] == '@') whichcmd++;
206
207 /*
208  *      Check if the command entered is internal. If it is, pass the rest of the
209  *      line down to the command. If not try to run a program.
210  */
211
212     count = 0;
213     while (IsCharAlphaNumeric(whichcmd[count])) {
214       count++;
215     }
216     for (i=0; i<=WCMD_EXIT; i++) {
217       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
218           whichcmd, count, inbuilt[i], -1) == 2) break;
219     }
220     p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
221     WCMD_parse (p, quals, param1, param2);
222     switch (i) {
223
224       case WCMD_ATTRIB:
225         WCMD_setshow_attrib ();
226         break;
227       case WCMD_CALL:
228         WCMD_batch (param1, p, 1);
229         break;
230       case WCMD_CD:
231       case WCMD_CHDIR:
232         WCMD_setshow_default ();
233         break;
234       case WCMD_CLS:
235         WCMD_clear_screen ();
236         break;
237       case WCMD_COPY:
238         WCMD_copy ();
239         break;
240       case WCMD_CTTY:
241         WCMD_change_tty ();
242         break;
243       case WCMD_DATE:
244         WCMD_setshow_date ();
245         break;
246       case WCMD_DEL:
247       case WCMD_ERASE:
248         WCMD_delete (0);
249         break;
250       case WCMD_DIR:
251         WCMD_directory ();
252         break;
253       case WCMD_ECHO:
254         /* Use the unstripped version of the following data - step over the space */
255         /* but only if a parameter follows                                        */
256         if (strlen(&whichcmd[count]) > 0)
257           WCMD_echo(&whichcmd[count+1]);
258         else
259           WCMD_echo(&whichcmd[count]);
260         break;
261       case WCMD_FOR:
262         WCMD_for (p);
263         break;
264       case WCMD_GOTO:
265         WCMD_goto ();
266         break;
267       case WCMD_HELP:
268         WCMD_give_help (p);
269         break;
270       case WCMD_IF:
271         WCMD_if (p);
272         break;
273       case WCMD_LABEL:
274         WCMD_volume (1, p);
275         break;
276       case WCMD_MD:
277       case WCMD_MKDIR:
278         WCMD_create_dir ();
279         break;
280       case WCMD_MOVE:
281         WCMD_move ();
282         break;
283       case WCMD_PATH:
284         WCMD_setshow_path ();
285         break;
286       case WCMD_PAUSE:
287         WCMD_pause ();
288         break;
289       case WCMD_PROMPT:
290         WCMD_setshow_prompt ();
291         break;
292       case WCMD_REM:
293         break;
294       case WCMD_REN:
295       case WCMD_RENAME:
296         WCMD_rename ();
297         break;
298       case WCMD_RD:
299       case WCMD_RMDIR:
300         WCMD_remove_dir ();
301         break;
302       case WCMD_SET:
303         WCMD_setshow_env (p);
304         break;
305       case WCMD_SHIFT:
306         WCMD_shift ();
307         break;
308       case WCMD_TIME:
309         WCMD_setshow_time ();
310         break;
311       case WCMD_TITLE:
312         if (strlen(&whichcmd[count]) > 0)
313           WCMD_title(&whichcmd[count+1]);
314         break;
315       case WCMD_TYPE:
316         WCMD_type ();
317         break;
318       case WCMD_VER:
319         WCMD_version ();
320         break;
321       case WCMD_VERIFY:
322         WCMD_verify (p);
323         break;
324       case WCMD_VOL:
325         WCMD_volume (0, p);
326         break;
327       case WCMD_EXIT:
328         ExitProcess (0);
329       default:
330         WCMD_run_program (whichcmd);
331     };
332     if (old_stdin) {
333       CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
334       SetStdHandle (STD_INPUT_HANDLE, old_stdin);
335     }
336     if (old_stdout) {
337       CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
338       SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
339     }
340   }
341
342 /******************************************************************************
343  * WCMD_run_program
344  *
345  *      Execute a command line as an external program. If no extension given then
346  *      precedence is given to .BAT files. Must allow recursion.
347  *
348  *      FIXME: Case sensitivity in suffixes!
349  */
350
351 void WCMD_run_program (char *command) {
352
353 STARTUPINFO st;
354 PROCESS_INFORMATION pe;
355 SHFILEINFO psfi;
356 DWORD console;
357 BOOL status;
358 HANDLE h;
359 HINSTANCE hinst;
360 char filetorun[MAX_PATH];
361
362   WCMD_parse (command, quals, param1, param2);  /* Quick way to get the filename */
363   if (strpbrk (param1, "\\:") == NULL) {        /* No explicit path given */
364     if ((strchr (param1, '.') == NULL) || (strstr (param1, ".bat") != NULL)) {
365       if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
366         WCMD_batch (filetorun, command, 0);
367         return;
368       }
369     }
370   }
371   else {                                        /* Explicit path given */
372     if (strstr (param1, ".bat") != NULL) {
373       WCMD_batch (param1, command, 0);
374       return;
375     }
376     if (strchr (param1, '.') == NULL) {
377       strcpy (filetorun, param1);
378       strcat (filetorun, ".bat");
379       h = CreateFile (filetorun, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
380       if (h != INVALID_HANDLE_VALUE) {
381         CloseHandle (h);
382         WCMD_batch (param1, command, 0);
383         return;
384       }
385     }
386   }
387
388         /* No batch file found, assume executable */
389
390   hinst = FindExecutable (param1, NULL, filetorun);
391   if ((int)hinst < 32) {
392     WCMD_print_error ();
393     return;
394   }
395   console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
396   if (!console) {
397     WCMD_print_error ();
398     return;
399   }
400   ZeroMemory (&st, sizeof(STARTUPINFO));
401   st.cb = sizeof(STARTUPINFO);
402   status = CreateProcess (NULL, command, NULL, NULL, FALSE,
403                  0, NULL, NULL, &st, &pe);
404   if (!status) {
405     WCMD_print_error ();
406   }
407   if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
408   GetExitCodeProcess (pe.hProcess, &errorlevel);
409   if (errorlevel == STILL_ACTIVE) errorlevel = 0;
410 }
411
412 /******************************************************************************
413  * WCMD_show_prompt
414  *
415  *      Display the prompt on STDout
416  *
417  */
418
419 void WCMD_show_prompt () {
420
421 int status;
422 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
423 char *p, *q;
424
425   status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
426   if ((status == 0) || (status > sizeof(prompt_string))) {
427     lstrcpy (prompt_string, "$N$G");
428   }
429   p = prompt_string;
430   q = out_string;
431   *q = '\0';
432   while (*p != '\0') {
433     if (*p != '$') {
434       *q++ = *p++;
435       *q = '\0';
436     }
437     else {
438       p++;
439       switch (toupper(*p)) {
440         case '$':
441           *q++ = '$';
442           break;
443         case 'B':
444           *q++ = '|';
445           break;
446         case 'D':
447           GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
448           while (*q) q++;
449           break;
450         case 'E':
451           *q++ = '\E';
452           break;
453         case 'G':
454           *q++ = '>';
455           break;
456         case 'L':
457           *q++ = '<';
458           break;
459         case 'N':
460           status = GetCurrentDirectory (sizeof(curdir), curdir);
461           if (status) {
462             *q++ = curdir[0];
463           }
464           break;
465         case 'P':
466           status = GetCurrentDirectory (sizeof(curdir), curdir);
467           if (status) {
468             lstrcat (q, curdir);
469             while (*q) q++;
470           }
471           break;
472         case 'Q':
473           *q++ = '=';
474           break;
475         case 'T':
476           GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
477           while (*q) q++;
478           break;
479         case '_':
480           *q++ = '\n';
481           break;
482       }
483       p++;
484       *q = '\0';
485     }
486   }
487   WCMD_output (out_string);
488 }
489
490 /****************************************************************************
491  * WCMD_print_error
492  *
493  * Print the message for GetLastError
494  */
495
496 void WCMD_print_error () {
497 LPVOID lpMsgBuf;
498 DWORD error_code;
499 int status;
500
501   error_code = GetLastError ();
502   status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
503                         NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
504   if (!status) {
505     WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
506                         error_code, GetLastError());
507     return;
508   }
509   WCMD_output (lpMsgBuf);
510   LocalFree ((HLOCAL)lpMsgBuf);
511   WCMD_output (newline);
512   return;
513 }
514
515 /*******************************************************************
516  * WCMD_parse - parse a command into parameters and qualifiers.
517  *
518  *      On exit, all qualifiers are concatenated into q, the first string
519  *      not beginning with "/" is in p1 and the
520  *      second in p2. Any subsequent non-qualifier strings are lost.
521  *      Parameters in quotes are handled.
522  */
523
524 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
525
526 int p = 0;
527
528   *q = *p1 = *p2 = '\0';
529   while (TRUE) {
530     switch (*s) {
531       case '/':
532         *q++ = *s++;
533         while ((*s != '\0') && (*s != ' ') && *s != '/') {
534           *q++ = toupper (*s++);
535         }
536         *q = '\0';
537         break;
538       case ' ':
539         s++;
540         break;
541       case '"':
542         s++;
543         while ((*s != '\0') && (*s != '"')) {
544           if (p == 0) *p1++ = *s++;
545           else if (p == 1) *p2++ = *s++;
546           else s++;
547         }
548         if (p == 0) *p1 = '\0';
549         if (p == 1) *p2 = '\0';
550         p++;
551         if (*s == '"') s++;
552         break;
553       case '\0':
554         return;
555       default:
556         while ((*s != '\0') && (*s != ' ') && (*s != '/')) {
557           if (p == 0) *p1++ = *s++;
558           else if (p == 1) *p2++ = *s++;
559           else s++;
560         }
561         if (p == 0) *p1 = '\0';
562         if (p == 1) *p2 = '\0';
563         p++;
564     }
565   }
566 }
567
568 /*******************************************************************
569  * WCMD_output - send output to current standard output device.
570  *
571  */
572
573 void WCMD_output (char *format, ...) {
574
575 va_list ap;
576 char string[1024];
577 DWORD count;
578
579   va_start(ap,format);
580   vsprintf (string, format, ap);
581   WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), string, lstrlen(string), &count, NULL);
582   va_end(ap);
583 }
584
585 /*******************************************************************
586  * WCMD_output_asis - send output to current standard output device.
587  *        without formatting eg. when message contains '%'
588  */
589
590 void WCMD_output_asis (char *message) {
591   DWORD count;
592   WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
593 }
594
595
596
597 /***************************************************************************
598  * WCMD_strtrim_leading_spaces
599  *
600  *      Remove leading spaces from a string. Return a pointer to the first
601  *      non-space character. Does not modify the input string
602  */
603
604 char *WCMD_strtrim_leading_spaces (char *string) {
605
606 char *ptr;
607
608   ptr = string;
609   while (*ptr == ' ') ptr++;
610   return ptr;
611 }
612
613 /*************************************************************************
614  * WCMD_strtrim_trailing_spaces
615  *
616  *      Remove trailing spaces from a string. This routine modifies the input
617  *      string by placing a null after the last non-space character
618  */
619
620 void WCMD_strtrim_trailing_spaces (char *string) {
621
622 char *ptr;
623
624   ptr = string + lstrlen (string) - 1;
625   while ((*ptr == ' ') && (ptr >= string)) {
626     *ptr = '\0';
627     ptr--;
628   }
629 }
630
631 /*************************************************************************
632  * WCMD_pipe
633  *
634  *      Handle pipes within a command - the DOS way using temporary files.
635  */
636
637 void WCMD_pipe (char *command) {
638
639 char *p;
640 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
641
642   GetTempPath (sizeof(temp_path), temp_path);
643   GetTempFileName (temp_path, "WCMD", 0, temp_file);
644   p = strchr(command, '|');
645   *p++ = '\0';
646   wsprintf (temp_cmd, "%s > %s", command, temp_file);
647   WCMD_process_command (temp_cmd);
648   command = p;
649   while ((p = strchr(command, '|'))) {
650     *p++ = '\0';
651     GetTempFileName (temp_path, "WCMD", 0, temp_file2);
652     wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
653     WCMD_process_command (temp_cmd);
654     DeleteFile (temp_file);
655     lstrcpy (temp_file, temp_file2);
656     command = p;
657   }
658   wsprintf (temp_cmd, "%s < %s", command, temp_file);
659   WCMD_process_command (temp_cmd);
660   DeleteFile (temp_file);
661 }
662