query: Add a stub implementation for LocateCatalogs.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /*
22  * FIXME:
23  * - Cannot handle parameters in quotes
24  * - Lots of functionality missing from builtins
25  */
26
27 #include "config.h"
28 #include "wcmd.h"
29
30 const char * const inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
31                 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
32                 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
33                 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
34                 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL", 
35                 "ENDLOCAL", "SETLOCAL", "EXIT" };
36
37 HINSTANCE hinst;
38 DWORD errorlevel;
39 int echo_mode = 1, verify_mode = 0;
40 const char nyi[] = "Not Yet Implemented\n\n";
41 const char newline[] = "\n";
42 const char version_string[] = "WCMD Version " PACKAGE_VERSION "\n\n";
43 const char anykey[] = "Press Return key to continue: ";
44 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
45 BATCH_CONTEXT *context = NULL;
46 static HANDLE old_stdin = INVALID_HANDLE_VALUE, old_stdout = INVALID_HANDLE_VALUE;
47
48 /*****************************************************************************
49  * Main entry point. This is a console application so we have a main() not a
50  * winmain().
51  */
52
53 int main (int argc, char *argv[])
54 {
55   char string[1024];
56   char* cmd=NULL;
57   DWORD count;
58   HANDLE h;
59   int opt_c, opt_k, opt_q;
60
61   opt_c=opt_k=opt_q=0;
62   while (*argv!=NULL)
63   {
64       char c;
65       if ((*argv)[0]!='/' || (*argv)[1]=='\0') {
66           argv++;
67           continue;
68       }
69
70       c=(*argv)[1];
71       if (tolower(c)=='c') {
72           opt_c=1;
73       } else if (tolower(c)=='q') {
74           opt_q=1;
75       } else if (tolower(c)=='k') {
76           opt_k=1;
77       } else if (tolower(c)=='t' || tolower(c)=='x' || tolower(c)=='y') {
78           /* Ignored for compatibility with Windows */
79       }
80
81       if ((*argv)[2]==0)
82           argv++;
83       else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
84           *argv+=2;
85
86       if (opt_c || opt_k) /* break out of parsing immediately after c or k */
87           break;
88   }
89
90   if (opt_q) {
91     WCMD_echo("OFF");
92   }
93
94   if (opt_c || opt_k) {
95       int len;
96       char** arg;
97       char* p;
98
99       /* Build the command to execute */
100       len = 0;
101       for (arg = argv; *arg; arg++)
102       {
103           int has_space,bcount;
104           char* a;
105
106           has_space=0;
107           bcount=0;
108           a=*arg;
109           if( !*a ) has_space=1;
110           while (*a!='\0') {
111               if (*a=='\\') {
112                   bcount++;
113               } else {
114                   if (*a==' ' || *a=='\t') {
115                       has_space=1;
116                   } else if (*a=='"') {
117                       /* doubling of '\' preceding a '"',
118                        * plus escaping of said '"'
119                        */
120                       len+=2*bcount+1;
121                   }
122                   bcount=0;
123               }
124               a++;
125           }
126           len+=(a-*arg)+1 /* for the separating space */;
127           if (has_space)
128               len+=2; /* for the quotes */
129       }
130
131       cmd = HeapAlloc(GetProcessHeap(), 0, len);
132       if (!cmd)
133           exit(1);
134
135       p = cmd;
136       for (arg = argv; *arg; arg++)
137       {
138           int has_space,has_quote;
139           char* a;
140
141           /* Check for quotes and spaces in this argument */
142           has_space=has_quote=0;
143           a=*arg;
144           if( !*a ) has_space=1;
145           while (*a!='\0') {
146               if (*a==' ' || *a=='\t') {
147                   has_space=1;
148                   if (has_quote)
149                       break;
150               } else if (*a=='"') {
151                   has_quote=1;
152                   if (has_space)
153                       break;
154               }
155               a++;
156           }
157
158           /* Now transfer it to the command line */
159           if (has_space)
160               *p++='"';
161           if (has_quote) {
162               int bcount;
163               char* a;
164
165               bcount=0;
166               a=*arg;
167               while (*a!='\0') {
168                   if (*a=='\\') {
169                       *p++=*a;
170                       bcount++;
171                   } else {
172                       if (*a=='"') {
173                           int i;
174
175                           /* Double all the '\\' preceding this '"', plus one */
176                           for (i=0;i<=bcount;i++)
177                               *p++='\\';
178                           *p++='"';
179                       } else {
180                           *p++=*a;
181                       }
182                       bcount=0;
183                   }
184                   a++;
185               }
186           } else {
187               strcpy(p,*arg);
188               p+=strlen(*arg);
189           }
190           if (has_space)
191               *p++='"';
192           *p++=' ';
193       }
194       if (p > cmd)
195           p--;  /* remove last space */
196       *p = '\0';
197   }
198
199   if (opt_c) {
200       /* If we do a "wcmd /c command", we don't want to allocate a new
201        * console since the command returns immediately. Rather, we use
202        * the currently allocated input and output handles. This allows
203        * us to pipe to and read from the command interpreter.
204        */
205       if (strchr(cmd,'|') != NULL)
206           WCMD_pipe(cmd);
207       else
208           WCMD_process_command(cmd);
209       HeapFree(GetProcessHeap(), 0, cmd);
210       return 0;
211   }
212
213   SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
214                  ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
215   SetConsoleTitle("Wine Command Prompt");
216
217   if (opt_k) {
218       WCMD_process_command(cmd);
219       HeapFree(GetProcessHeap(), 0, cmd);
220   }
221
222 /*
223  *      If there is an AUTOEXEC.BAT file, try to execute it.
224  */
225
226   GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
227   h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
228   if (h != INVALID_HANDLE_VALUE) {
229     CloseHandle (h);
230 #if 0
231     WCMD_batch_command (string);
232 #endif
233   }
234
235 /*
236  *      Loop forever getting commands and executing them.
237  */
238
239   WCMD_version ();
240   while (TRUE) {
241     WCMD_show_prompt ();
242     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
243     if (count > 1) {
244       string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
245       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
246       if (lstrlen (string) != 0) {
247         if (strchr(string,'|') != NULL) {
248           WCMD_pipe (string);
249         }
250         else {
251           WCMD_process_command (string);
252         }
253       }
254     }
255   }
256 }
257
258
259 /*****************************************************************************
260  * Process one command. If the command is EXIT this routine does not return.
261  * We will recurse through here executing batch files.
262  */
263
264
265 void WCMD_process_command (char *command)
266 {
267     char *cmd, *p;
268     int status, i, len;
269     DWORD count, creationDisposition;
270     HANDLE h;
271     char *whichcmd;
272     SECURITY_ATTRIBUTES sa;
273
274 /*
275  *      Expand up environment variables.
276  */
277     len = ExpandEnvironmentStrings (command, NULL, 0);
278     cmd = HeapAlloc( GetProcessHeap(), 0, len );
279     status = ExpandEnvironmentStrings (command, cmd, len);
280     if (!status) {
281       WCMD_print_error ();
282       HeapFree( GetProcessHeap(), 0, cmd );
283       return;
284     }
285
286 /*
287  *      Changing default drive has to be handled as a special case.
288  */
289
290     if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
291       status = SetCurrentDirectory (cmd);
292       if (!status) WCMD_print_error ();
293       HeapFree( GetProcessHeap(), 0, cmd );
294       return;
295     }
296
297     /* Don't issue newline WCMD_output (newline);           @JED*/
298
299     sa.nLength = sizeof(sa);
300     sa.lpSecurityDescriptor = NULL;
301     sa.bInheritHandle = TRUE;
302 /*
303  *      Redirect stdin and/or stdout if required.
304  */
305
306     if ((p = strchr(cmd,'<')) != NULL) {
307       h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
308                 FILE_ATTRIBUTE_NORMAL, NULL);
309       if (h == INVALID_HANDLE_VALUE) {
310         WCMD_print_error ();
311         HeapFree( GetProcessHeap(), 0, cmd );
312         return;
313       }
314       old_stdin = GetStdHandle (STD_INPUT_HANDLE);
315       SetStdHandle (STD_INPUT_HANDLE, h);
316     }
317     if ((p = strchr(cmd,'>')) != NULL) {
318       *p++ = '\0';
319       if ('>' == *p) {
320         creationDisposition = OPEN_ALWAYS;
321         p++;
322       }
323       else {
324         creationDisposition = CREATE_ALWAYS;
325       }
326       h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
327                 FILE_ATTRIBUTE_NORMAL, NULL);
328       if (h == INVALID_HANDLE_VALUE) {
329         WCMD_print_error ();
330         HeapFree( GetProcessHeap(), 0, cmd );
331         return;
332       }
333       if (SetFilePointer (h, 0, NULL, FILE_END) ==
334           INVALID_SET_FILE_POINTER) {
335         WCMD_print_error ();
336       }
337       old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
338       SetStdHandle (STD_OUTPUT_HANDLE, h);
339     }
340     if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
341
342 /*
343  * Strip leading whitespaces, and a '@' if supplied
344  */
345     whichcmd = WCMD_strtrim_leading_spaces(cmd);
346     if (whichcmd[0] == '@') whichcmd++;
347
348 /*
349  *      Check if the command entered is internal. If it is, pass the rest of the
350  *      line down to the command. If not try to run a program.
351  */
352
353     count = 0;
354     while (IsCharAlphaNumeric(whichcmd[count])) {
355       count++;
356     }
357     for (i=0; i<=WCMD_EXIT; i++) {
358       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
359           whichcmd, count, inbuilt[i], -1) == 2) break;
360     }
361     p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
362     WCMD_parse (p, quals, param1, param2);
363     switch (i) {
364
365       case WCMD_ATTRIB:
366         WCMD_setshow_attrib ();
367         break;
368       case WCMD_CALL:
369         WCMD_run_program (p, 1);
370         break;
371       case WCMD_CD:
372       case WCMD_CHDIR:
373         WCMD_setshow_default ();
374         break;
375       case WCMD_CLS:
376         WCMD_clear_screen ();
377         break;
378       case WCMD_COPY:
379         WCMD_copy ();
380         break;
381       case WCMD_CTTY:
382         WCMD_change_tty ();
383         break;
384       case WCMD_DATE:
385         WCMD_setshow_date ();
386         break;
387       case WCMD_DEL:
388       case WCMD_ERASE:
389         WCMD_delete (0);
390         break;
391       case WCMD_DIR:
392         WCMD_directory ();
393         break;
394       case WCMD_ECHO:
395         WCMD_echo(&whichcmd[count]);
396         break;
397       case WCMD_FOR:
398         WCMD_for (p);
399         break;
400       case WCMD_GOTO:
401         WCMD_goto ();
402         break;
403       case WCMD_HELP:
404         WCMD_give_help (p);
405         break;
406       case WCMD_IF:
407         WCMD_if (p);
408         break;
409       case WCMD_LABEL:
410         WCMD_volume (1, p);
411         break;
412       case WCMD_MD:
413       case WCMD_MKDIR:
414         WCMD_create_dir ();
415         break;
416       case WCMD_MOVE:
417         WCMD_move ();
418         break;
419       case WCMD_PATH:
420         WCMD_setshow_path (p);
421         break;
422       case WCMD_PAUSE:
423         WCMD_pause ();
424         break;
425       case WCMD_PROMPT:
426         WCMD_setshow_prompt ();
427         break;
428       case WCMD_REM:
429         break;
430       case WCMD_REN:
431       case WCMD_RENAME:
432         WCMD_rename ();
433         break;
434       case WCMD_RD:
435       case WCMD_RMDIR:
436         WCMD_remove_dir ();
437         break;
438       case WCMD_SETLOCAL:
439         WCMD_setlocal(p);
440         break;
441       case WCMD_ENDLOCAL:
442         WCMD_endlocal();
443         break;
444       case WCMD_SET:
445         WCMD_setshow_env (p);
446         break;
447       case WCMD_SHIFT:
448         WCMD_shift ();
449         break;
450       case WCMD_TIME:
451         WCMD_setshow_time ();
452         break;
453       case WCMD_TITLE:
454         if (strlen(&whichcmd[count]) > 0)
455           WCMD_title(&whichcmd[count+1]);
456         break;
457       case WCMD_TYPE:
458         WCMD_type ();
459         break;
460       case WCMD_VER:
461         WCMD_version ();
462         break;
463       case WCMD_VERIFY:
464         WCMD_verify (p);
465         break;
466       case WCMD_VOL:
467         WCMD_volume (0, p);
468         break;
469       case WCMD_EXIT:
470         ExitProcess (0);
471       default:
472         WCMD_run_program (whichcmd, 0);
473     }
474     HeapFree( GetProcessHeap(), 0, cmd );
475     if (old_stdin != INVALID_HANDLE_VALUE) {
476       CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
477       SetStdHandle (STD_INPUT_HANDLE, old_stdin);
478       old_stdin = INVALID_HANDLE_VALUE;
479     }
480     if (old_stdout != INVALID_HANDLE_VALUE) {
481       CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
482       SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
483       old_stdout = INVALID_HANDLE_VALUE;
484     }
485 }
486
487 static void init_msvcrt_io_block(STARTUPINFO* st)
488 {
489     STARTUPINFO st_p;
490     /* fetch the parent MSVCRT info block if any, so that the child can use the
491      * same handles as its grand-father
492      */
493     st_p.cb = sizeof(STARTUPINFO);
494     GetStartupInfo(&st_p);
495     st->cbReserved2 = st_p.cbReserved2;
496     st->lpReserved2 = st_p.lpReserved2;
497     if (st_p.cbReserved2 && st_p.lpReserved2 &&
498         (old_stdin != INVALID_HANDLE_VALUE || old_stdout != INVALID_HANDLE_VALUE))
499     {
500         /* Override the entries for fd 0,1,2 if we happened
501          * to change those std handles (this depends on the way wcmd sets
502          * it's new input & output handles)
503          */
504         size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
505         BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
506         if (ptr)
507         {
508             unsigned num = *(unsigned*)st_p.lpReserved2;
509             char* flags = (char*)(ptr + sizeof(unsigned));
510             HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
511
512             memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
513             st->cbReserved2 = sz;
514             st->lpReserved2 = ptr;
515
516 #define WX_OPEN 0x01    /* see dlls/msvcrt/file.c */
517             if (num <= 0 || (flags[0] & WX_OPEN))
518             {
519                 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
520                 flags[0] |= WX_OPEN;
521             }
522             if (num <= 1 || (flags[1] & WX_OPEN))
523             {
524                 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
525                 flags[1] |= WX_OPEN;
526             }
527             if (num <= 2 || (flags[2] & WX_OPEN))
528             {
529                 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
530                 flags[2] |= WX_OPEN;
531             }
532 #undef WX_OPEN
533         }
534     }
535 }
536
537 /******************************************************************************
538  * WCMD_run_program
539  *
540  *      Execute a command line as an external program. If no extension given then
541  *      precedence is given to .BAT files. Must allow recursion.
542  *      
543  *      called is 1 if the program was invoked with a CALL command - removed
544  *      from command -. It is only used for batch programs.
545  *
546  *      FIXME: Case sensitivity in suffixes!
547  */
548
549 void WCMD_run_program (char *command, int called) {
550
551 STARTUPINFO st;
552 PROCESS_INFORMATION pe;
553 SHFILEINFO psfi;
554 DWORD console;
555 BOOL status;
556 HANDLE h;
557 HINSTANCE hinst;
558 char filetorun[MAX_PATH];
559
560   WCMD_parse (command, quals, param1, param2);  /* Quick way to get the filename */
561   if (!(*param1) && !(*param2))
562     return;
563   if (strpbrk (param1, "/\\:") == NULL) {  /* No explicit path given */
564     char *ext = strrchr( param1, '.' );
565     if (!ext || !strcasecmp( ext, ".bat"))
566     {
567       if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
568         WCMD_batch (filetorun, command, called);
569         return;
570       }
571     }
572     if (!ext || !strcasecmp( ext, ".cmd"))
573     {
574       if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
575         WCMD_batch (filetorun, command, called);
576         return;
577       }
578     }
579   }
580   else {                                        /* Explicit path given */
581     char *ext = strrchr( param1, '.' );
582     if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
583     {
584       WCMD_batch (param1, command, called);
585       return;
586     }
587
588     if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
589     if (!ext)
590     {
591       strcpy (filetorun, param1);
592       strcat (filetorun, ".bat");
593       h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
594                       NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
595       if (h != INVALID_HANDLE_VALUE) {
596         CloseHandle (h);
597         WCMD_batch (param1, command, called);
598         return;
599       }
600     }
601   }
602
603         /* No batch file found, assume executable */
604
605   hinst = FindExecutable (param1, NULL, filetorun);
606   if ((INT_PTR)hinst < 32)
607     console = 0;
608   else
609     console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
610
611   ZeroMemory (&st, sizeof(STARTUPINFO));
612   st.cb = sizeof(STARTUPINFO);
613   init_msvcrt_io_block(&st);
614
615   status = CreateProcess (NULL, command, NULL, NULL, TRUE, 
616                           0, NULL, NULL, &st, &pe);
617   if (!status) {
618     WCMD_print_error ();
619     return;
620   }
621   if (!console) errorlevel = 0;
622   else
623   {
624       if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
625       GetExitCodeProcess (pe.hProcess, &errorlevel);
626       if (errorlevel == STILL_ACTIVE) errorlevel = 0;
627   }
628   CloseHandle(pe.hProcess);
629   CloseHandle(pe.hThread);
630 }
631
632 /******************************************************************************
633  * WCMD_show_prompt
634  *
635  *      Display the prompt on STDout
636  *
637  */
638
639 void WCMD_show_prompt (void) {
640
641 int status;
642 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
643 char *p, *q;
644
645   status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
646   if ((status == 0) || (status > sizeof(prompt_string))) {
647     lstrcpy (prompt_string, "$P$G");
648   }
649   p = prompt_string;
650   q = out_string;
651   *q = '\0';
652   while (*p != '\0') {
653     if (*p != '$') {
654       *q++ = *p++;
655       *q = '\0';
656     }
657     else {
658       p++;
659       switch (toupper(*p)) {
660         case '$':
661           *q++ = '$';
662           break;
663         case 'B':
664           *q++ = '|';
665           break;
666         case 'D':
667           GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
668           while (*q) q++;
669           break;
670         case 'E':
671           *q++ = '\E';
672           break;
673         case 'G':
674           *q++ = '>';
675           break;
676         case 'L':
677           *q++ = '<';
678           break;
679         case 'N':
680           status = GetCurrentDirectory (sizeof(curdir), curdir);
681           if (status) {
682             *q++ = curdir[0];
683           }
684           break;
685         case 'P':
686           status = GetCurrentDirectory (sizeof(curdir), curdir);
687           if (status) {
688             lstrcat (q, curdir);
689             while (*q) q++;
690           }
691           break;
692         case 'Q':
693           *q++ = '=';
694           break;
695         case 'T':
696           GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
697           while (*q) q++;
698           break;
699        case 'V':
700            lstrcat (q, version_string);
701            while (*q) q++;
702          break;
703         case '_':
704           *q++ = '\n';
705           break;
706       }
707       p++;
708       *q = '\0';
709     }
710   }
711   WCMD_output_asis (out_string);
712 }
713
714 /****************************************************************************
715  * WCMD_print_error
716  *
717  * Print the message for GetLastError
718  */
719
720 void WCMD_print_error (void) {
721 LPVOID lpMsgBuf;
722 DWORD error_code;
723 int status;
724
725   error_code = GetLastError ();
726   status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
727                         NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
728   if (!status) {
729     WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
730                         error_code, GetLastError());
731     return;
732   }
733   WCMD_output_asis (lpMsgBuf);
734   LocalFree ((HLOCAL)lpMsgBuf);
735   WCMD_output_asis (newline);
736   return;
737 }
738
739 /*******************************************************************
740  * WCMD_parse - parse a command into parameters and qualifiers.
741  *
742  *      On exit, all qualifiers are concatenated into q, the first string
743  *      not beginning with "/" is in p1 and the
744  *      second in p2. Any subsequent non-qualifier strings are lost.
745  *      Parameters in quotes are handled.
746  */
747
748 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
749
750 int p = 0;
751
752   *q = *p1 = *p2 = '\0';
753   while (TRUE) {
754     switch (*s) {
755       case '/':
756         *q++ = *s++;
757         while ((*s != '\0') && (*s != ' ') && *s != '/') {
758           *q++ = toupper (*s++);
759         }
760         *q = '\0';
761         break;
762       case ' ':
763       case '\t':
764         s++;
765         break;
766       case '"':
767         s++;
768         while ((*s != '\0') && (*s != '"')) {
769           if (p == 0) *p1++ = *s++;
770           else if (p == 1) *p2++ = *s++;
771           else s++;
772         }
773         if (p == 0) *p1 = '\0';
774         if (p == 1) *p2 = '\0';
775         p++;
776         if (*s == '"') s++;
777         break;
778       case '\0':
779         return;
780       default:
781         while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
782           if (p == 0) *p1++ = *s++;
783           else if (p == 1) *p2++ = *s++;
784           else s++;
785         }
786         if (p == 0) *p1 = '\0';
787         if (p == 1) *p2 = '\0';
788         p++;
789     }
790   }
791 }
792
793 /*******************************************************************
794  * WCMD_output - send output to current standard output device.
795  *
796  */
797
798 void WCMD_output (const char *format, ...) {
799
800 va_list ap;
801 char string[1024];
802 int ret;
803
804   va_start(ap,format);
805   ret = vsnprintf (string, sizeof( string), format, ap);
806   va_end(ap);
807   if( ret >= sizeof( string)) {
808        WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
809        string[sizeof( string) -1] = '\0';
810   }
811   WCMD_output_asis(string);
812 }
813
814
815 static int line_count;
816 static int max_height;
817 static BOOL paged_mode;
818
819 void WCMD_enter_paged_mode(void)
820 {
821 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
822
823   if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
824     max_height = consoleInfo.dwSize.Y;
825   else
826     max_height = 25;
827   paged_mode = TRUE;
828   line_count = 5; /* keep 5 lines from previous output */
829 }
830
831 void WCMD_leave_paged_mode(void)
832 {
833   paged_mode = FALSE;
834 }
835
836 /*******************************************************************
837  * WCMD_output_asis - send output to current standard output device.
838  *        without formatting eg. when message contains '%'
839  */
840
841 void WCMD_output_asis (const char *message) {
842   DWORD count;
843   char* ptr;
844   char string[1024];
845
846   if (paged_mode) {
847     do {
848       if ((ptr = strchr(message, '\n')) != NULL) ptr++;
849       WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, 
850                  (ptr) ? ptr - message : lstrlen(message), &count, NULL);
851       if (ptr) {
852         if (++line_count >= max_height - 1) {
853           line_count = 0;
854           WCMD_output_asis (anykey);
855           ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
856         }
857       }
858     } while ((message = ptr) != NULL);
859   } else {
860       WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
861   }
862 }
863
864
865 /***************************************************************************
866  * WCMD_strtrim_leading_spaces
867  *
868  *      Remove leading spaces from a string. Return a pointer to the first
869  *      non-space character. Does not modify the input string
870  */
871
872 char *WCMD_strtrim_leading_spaces (char *string) {
873
874 char *ptr;
875
876   ptr = string;
877   while (*ptr == ' ') ptr++;
878   return ptr;
879 }
880
881 /*************************************************************************
882  * WCMD_strtrim_trailing_spaces
883  *
884  *      Remove trailing spaces from a string. This routine modifies the input
885  *      string by placing a null after the last non-space character
886  */
887
888 void WCMD_strtrim_trailing_spaces (char *string) {
889
890 char *ptr;
891
892   ptr = string + lstrlen (string) - 1;
893   while ((*ptr == ' ') && (ptr >= string)) {
894     *ptr = '\0';
895     ptr--;
896   }
897 }
898
899 /*************************************************************************
900  * WCMD_pipe
901  *
902  *      Handle pipes within a command - the DOS way using temporary files.
903  */
904
905 void WCMD_pipe (char *command) {
906
907 char *p;
908 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
909
910   GetTempPath (sizeof(temp_path), temp_path);
911   GetTempFileName (temp_path, "WCMD", 0, temp_file);
912   p = strchr(command, '|');
913   *p++ = '\0';
914   wsprintf (temp_cmd, "%s > %s", command, temp_file);
915   WCMD_process_command (temp_cmd);
916   command = p;
917   while ((p = strchr(command, '|'))) {
918     *p++ = '\0';
919     GetTempFileName (temp_path, "WCMD", 0, temp_file2);
920     wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
921     WCMD_process_command (temp_cmd);
922     DeleteFile (temp_file);
923     lstrcpy (temp_file, temp_file2);
924     command = p;
925   }
926   wsprintf (temp_cmd, "%s < %s", command, temp_file);
927   WCMD_process_command (temp_cmd);
928   DeleteFile (temp_file);
929 }