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