cmd.exe: Support exit [/b] returncode.
[wine] / programs / cmd / builtins.c
1 /*
2  * CMD - Wine-compatible command line interface - built-in functions.
3  *
4  * Copyright (C) 1999 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  * NOTES:
23  * On entry to each function, global variables quals, param1, param2 contain
24  * the qualifiers (uppercased and concatenated) and parameters entered, with
25  * environment-variable and batch parameter substitution already done.
26  */
27
28 /*
29  * FIXME:
30  * - No support for pipes, shell parameters
31  * - Lots of functionality missing from builtins
32  * - Messages etc need international support
33  */
34
35 #define WIN32_LEAN_AND_MEAN
36
37 #include "wcmd.h"
38
39 void WCMD_execute (char *orig_command, char *parameter, char *substitution);
40
41 struct env_stack
42 {
43   struct env_stack *next;
44   WCHAR *strings;
45 };
46
47 struct env_stack *saved_environment;
48
49 extern HINSTANCE hinst;
50 extern char *inbuilt[];
51 extern int echo_mode, verify_mode;
52 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
53 extern BATCH_CONTEXT *context;
54 extern DWORD errorlevel;
55
56
57
58 /****************************************************************************
59  * WCMD_clear_screen
60  *
61  * Clear the terminal screen.
62  */
63
64 void WCMD_clear_screen (void) {
65
66   /* Emulate by filling the screen from the top left to bottom right with
67         spaces, then moving the cursor to the top left afterwards */
68   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
69   HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
70
71   if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
72   {
73       COORD topLeft;
74       DWORD screenSize;
75
76       screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
77
78       topLeft.X = 0;
79       topLeft.Y = 0;
80       FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
81       SetConsoleCursorPosition(hStdOut, topLeft);
82   }
83 }
84
85 /****************************************************************************
86  * WCMD_change_tty
87  *
88  * Change the default i/o device (ie redirect STDin/STDout).
89  */
90
91 void WCMD_change_tty (void) {
92
93   WCMD_output (nyi);
94
95 }
96
97 /****************************************************************************
98  * WCMD_copy
99  *
100  * Copy a file or wildcarded set.
101  * FIXME: No wildcard support
102  */
103
104 void WCMD_copy (void) {
105
106 DWORD count;
107 WIN32_FIND_DATA fd;
108 HANDLE hff;
109 BOOL force, status;
110 static const char overwrite[] = "Overwrite file (Y/N)?";
111 char string[8], outpath[MAX_PATH], inpath[MAX_PATH], *infile;
112
113   if (param1[0] == 0x00) {
114     WCMD_output ("Argument missing\n");
115     return;
116   }
117
118   if ((strchr(param1,'*') != NULL) && (strchr(param1,'%') != NULL)) {
119     WCMD_output ("Wildcards not yet supported\n");
120     return;
121   }
122
123   /* If no destination supplied, assume current directory */
124   if (param2[0] == 0x00) {
125       strcpy(param2, ".");
126   }
127
128   GetFullPathName (param2, sizeof(outpath), outpath, NULL);
129   if (outpath[strlen(outpath) - 1] == '\\')
130       outpath[strlen(outpath) - 1] = '\0';
131   hff = FindFirstFile (outpath, &fd);
132   if (hff != INVALID_HANDLE_VALUE) {
133     if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
134       GetFullPathName (param1, sizeof(inpath), inpath, &infile);
135       strcat (outpath, "\\");
136       strcat (outpath, infile);
137     }
138     FindClose (hff);
139   }
140
141   force = (strstr (quals, "/Y") != NULL);
142   if (!force) {
143     hff = FindFirstFile (outpath, &fd);
144     if (hff != INVALID_HANDLE_VALUE) {
145       FindClose (hff);
146       WCMD_output (overwrite);
147       ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
148       if (toupper(string[0]) == 'Y') force = TRUE;
149     }
150     else force = TRUE;
151   }
152   if (force) {
153     status = CopyFile (param1, outpath, FALSE);
154     if (!status) WCMD_print_error ();
155   }
156 }
157
158 /****************************************************************************
159  * WCMD_create_dir
160  *
161  * Create a directory.
162  *
163  * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
164  * they do not already exist.
165  */
166
167 BOOL create_full_path(CHAR* path)
168 {
169     int len;
170     CHAR *new_path;
171     BOOL ret = TRUE;
172
173     new_path = HeapAlloc(GetProcessHeap(),0,strlen(path)+1);
174     strcpy(new_path,path);
175
176     while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
177         new_path[len - 1] = 0;
178
179     while (!CreateDirectory(new_path,NULL))
180     {
181         CHAR *slash;
182         DWORD last_error = GetLastError();
183         if (last_error == ERROR_ALREADY_EXISTS)
184             break;
185
186         if (last_error != ERROR_PATH_NOT_FOUND)
187         {
188             ret = FALSE;
189             break;
190         }
191
192         if (!(slash = strrchr(new_path,'\\')) && ! (slash = strrchr(new_path,'/')))
193         {
194             ret = FALSE;
195             break;
196         }
197
198         len = slash - new_path;
199         new_path[len] = 0;
200         if (!create_full_path(new_path))
201         {
202             ret = FALSE;
203             break;
204         }
205         new_path[len] = '\\';
206     }
207     HeapFree(GetProcessHeap(),0,new_path);
208     return ret;
209 }
210
211 void WCMD_create_dir (void) {
212
213     if (param1[0] == 0x00) {
214         WCMD_output ("Argument missing\n");
215         return;
216     }
217     if (!create_full_path(param1)) WCMD_print_error ();
218 }
219
220 /****************************************************************************
221  * WCMD_delete
222  *
223  * Delete a file or wildcarded set.
224  *
225  */
226
227 void WCMD_delete (int recurse) {
228
229 WIN32_FIND_DATA fd;
230 HANDLE hff;
231 char fpath[MAX_PATH];
232 char *p;
233
234   if (param1[0] == 0x00) {
235     WCMD_output ("Argument missing\n");
236     return;
237   }
238   hff = FindFirstFile (param1, &fd);
239   if (hff == INVALID_HANDLE_VALUE) {
240     WCMD_output ("%s :File Not Found\n",param1);
241     return;
242   }
243   if ((strchr(param1,'*') == NULL) && (strchr(param1,'?') == NULL)
244         && (!recurse) && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
245     strcat (param1, "\\*");
246     FindClose(hff);
247     WCMD_delete (1);
248     return;
249   }
250   if ((strchr(param1,'*') != NULL) || (strchr(param1,'?') != NULL)) {
251     strcpy (fpath, param1);
252     do {
253       p = strrchr (fpath, '\\');
254       if (p != NULL) {
255         *++p = '\0';
256         strcat (fpath, fd.cFileName);
257       }
258       else strcpy (fpath, fd.cFileName);
259       if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
260         if (!DeleteFile (fpath)) WCMD_print_error ();
261       }
262     } while (FindNextFile(hff, &fd) != 0);
263     FindClose (hff);
264   }
265   else {
266     if (!DeleteFile (param1)) WCMD_print_error ();
267     FindClose (hff);
268   }
269 }
270
271 /****************************************************************************
272  * WCMD_echo
273  *
274  * Echo input to the screen (or not). We don't try to emulate the bugs
275  * in DOS (try typing "ECHO ON AGAIN" for an example).
276  */
277
278 void WCMD_echo (const char *command) {
279
280 static const char eon[] = "Echo is ON\n", eoff[] = "Echo is OFF\n";
281 int count;
282
283   if ((command[0] == '.') && (command[1] == 0)) {
284     WCMD_output (newline);
285     return;
286   }
287   if (command[0]==' ')
288     command++;
289   count = strlen(command);
290   if (count == 0) {
291     if (echo_mode) WCMD_output (eon);
292     else WCMD_output (eoff);
293     return;
294   }
295   if (lstrcmpi(command, "ON") == 0) {
296     echo_mode = 1;
297     return;
298   }
299   if (lstrcmpi(command, "OFF") == 0) {
300     echo_mode = 0;
301     return;
302   }
303   WCMD_output_asis (command);
304   WCMD_output (newline);
305
306 }
307
308 /**************************************************************************
309  * WCMD_for
310  *
311  * Batch file loop processing.
312  * FIXME: We don't exhaustively check syntax. Any command which works in MessDOS
313  * will probably work here, but the reverse is not necessarily the case...
314  */
315
316 void WCMD_for (char *p) {
317
318 WIN32_FIND_DATA fd;
319 HANDLE hff;
320 char *cmd, *item;
321 char set[MAX_PATH], param[MAX_PATH];
322 int i;
323
324   if (lstrcmpi (WCMD_parameter (p, 1, NULL), "in")
325         || lstrcmpi (WCMD_parameter (p, 3, NULL), "do")
326         || (param1[0] != '%')) {
327     WCMD_output ("Syntax error\n");
328     return;
329   }
330   lstrcpyn (set, WCMD_parameter (p, 2, NULL), sizeof(set));
331   WCMD_parameter (p, 4, &cmd);
332   lstrcpy (param, param1);
333
334 /*
335  *      If the parameter within the set has a wildcard then search for matching files
336  *      otherwise do a literal substitution.
337  */
338
339   i = 0;
340   while (*(item = WCMD_parameter (set, i, NULL))) {
341     if (strpbrk (item, "*?")) {
342       hff = FindFirstFile (item, &fd);
343       if (hff == INVALID_HANDLE_VALUE) {
344         return;
345       }
346       do {
347         WCMD_execute (cmd, param, fd.cFileName);
348       } while (FindNextFile(hff, &fd) != 0);
349       FindClose (hff);
350 }
351     else {
352       WCMD_execute (cmd, param, item);
353     }
354     i++;
355   }
356 }
357
358 /*****************************************************************************
359  * WCMD_Execute
360  *
361  *      Execute a command after substituting variable text for the supplied parameter
362  */
363
364 void WCMD_execute (char *orig_cmd, char *param, char *subst) {
365
366 char *new_cmd, *p, *s, *dup;
367 int size;
368
369   size = lstrlen (orig_cmd);
370   new_cmd = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, size);
371   dup = s = strdup (orig_cmd);
372
373   while ((p = strstr (s, param))) {
374     *p = '\0';
375     size += lstrlen (subst);
376     new_cmd = (char *) LocalReAlloc ((HANDLE)new_cmd, size, 0);
377     strcat (new_cmd, s);
378     strcat (new_cmd, subst);
379     s = p + lstrlen (param);
380   }
381   strcat (new_cmd, s);
382   WCMD_process_command (new_cmd);
383   free (dup);
384   LocalFree ((HANDLE)new_cmd);
385 }
386
387
388 /**************************************************************************
389  * WCMD_give_help
390  *
391  *      Simple on-line help. Help text is stored in the resource file.
392  */
393
394 void WCMD_give_help (char *command) {
395
396 int i;
397 char buffer[2048];
398
399   command = WCMD_strtrim_leading_spaces(command);
400   if (lstrlen(command) == 0) {
401     LoadString (hinst, 1000, buffer, sizeof(buffer));
402     WCMD_output_asis (buffer);
403   }
404   else {
405     for (i=0; i<=WCMD_EXIT; i++) {
406       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
407           param1, -1, inbuilt[i], -1) == 2) {
408         LoadString (hinst, i, buffer, sizeof(buffer));
409         WCMD_output_asis (buffer);
410         return;
411       }
412     }
413     WCMD_output ("No help available for %s\n", param1);
414   }
415   return;
416 }
417
418 /****************************************************************************
419  * WCMD_go_to
420  *
421  * Batch file jump instruction. Not the most efficient algorithm ;-)
422  * Prints error message if the specified label cannot be found - the file pointer is
423  * then at EOF, effectively stopping the batch file.
424  * FIXME: DOS is supposed to allow labels with spaces - we don't.
425  */
426
427 void WCMD_goto (void) {
428
429 char string[MAX_PATH];
430
431   if (param1[0] == 0x00) {
432     WCMD_output ("Argument missing\n");
433     return;
434   }
435   if (context != NULL) {
436     SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
437     while (WCMD_fgets (string, sizeof(string), context -> h)) {
438       if ((string[0] == ':') && (lstrcmpi (&string[1], param1) == 0)) return;
439     }
440     WCMD_output ("Target to GOTO not found\n");
441   }
442   return;
443 }
444
445
446 /****************************************************************************
447  * WCMD_if
448  *
449  * Batch file conditional.
450  * FIXME: Much more syntax checking needed!
451  */
452
453 void WCMD_if (char *p) {
454
455 int negate = 0, test = 0;
456 char condition[MAX_PATH], *command, *s;
457
458   if (!lstrcmpi (param1, "not")) {
459     negate = 1;
460     lstrcpy (condition, param2);
461 }
462   else {
463     lstrcpy (condition, param1);
464   }
465   if (!lstrcmpi (condition, "errorlevel")) {
466     if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
467     WCMD_parameter (p, 2+negate, &command);
468   }
469   else if (!lstrcmpi (condition, "exist")) {
470     if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
471         test = 1;
472     }
473     WCMD_parameter (p, 2+negate, &command);
474   }
475   else if (!lstrcmpi (condition, "defined")) {
476     if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
477         test = 1;
478     }
479     WCMD_parameter (p, 2+negate, &command);
480   }
481   else if ((s = strstr (p, "=="))) {
482     s += 2;
483     if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
484     WCMD_parameter (s, 1, &command);
485   }
486   else {
487     WCMD_output ("Syntax error\n");
488     return;
489   }
490   if (test != negate) {
491     command = strdup (command);
492     WCMD_process_command (command);
493     free (command);
494   }
495 }
496
497 /****************************************************************************
498  * WCMD_move
499  *
500  * Move a file, directory tree or wildcarded set of files.
501  * FIXME: Needs input and output files to be fully specified.
502  */
503
504 void WCMD_move (void) {
505
506 int status;
507 char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
508 WIN32_FIND_DATA fd;
509 HANDLE hff;
510
511   if (param1[0] == 0x00) {
512     WCMD_output ("Argument missing\n");
513     return;
514   }
515
516   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
517     WCMD_output ("Wildcards not yet supported\n");
518     return;
519   }
520
521   /* If no destination supplied, assume current directory */
522   if (param2[0] == 0x00) {
523       strcpy(param2, ".");
524   }
525
526   /* If 2nd parm is directory, then use original filename */
527   GetFullPathName (param2, sizeof(outpath), outpath, NULL);
528   if (outpath[strlen(outpath) - 1] == '\\')
529       outpath[strlen(outpath) - 1] = '\0';
530   hff = FindFirstFile (outpath, &fd);
531   if (hff != INVALID_HANDLE_VALUE) {
532     if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
533       GetFullPathName (param1, sizeof(inpath), inpath, &infile);
534       strcat (outpath, "\\");
535       strcat (outpath, infile);
536     }
537     FindClose (hff);
538   }
539
540   status = MoveFile (param1, outpath);
541   if (!status) WCMD_print_error ();
542 }
543
544 /****************************************************************************
545  * WCMD_pause
546  *
547  * Wait for keyboard input.
548  */
549
550 void WCMD_pause (void) {
551
552 DWORD count;
553 char string[32];
554
555   WCMD_output (anykey);
556   ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
557 }
558
559 /****************************************************************************
560  * WCMD_remove_dir
561  *
562  * Delete a directory.
563  */
564
565 void WCMD_remove_dir (void) {
566
567   if (param1[0] == 0x00) {
568     WCMD_output ("Argument missing\n");
569     return;
570   }
571   if (!RemoveDirectory (param1)) WCMD_print_error ();
572 }
573
574 /****************************************************************************
575  * WCMD_rename
576  *
577  * Rename a file.
578  * FIXME: Needs input and output files to be fully specified.
579  */
580
581 void WCMD_rename (void) {
582
583 int status;
584
585   if (param1[0] == 0x00 || param2[0] == 0x00) {
586     WCMD_output ("Argument missing\n");
587     return;
588   }
589   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
590     WCMD_output ("Wildcards not yet supported\n");
591     return;
592   }
593   status = MoveFile (param1, param2);
594   if (!status) WCMD_print_error ();
595 }
596
597 /*****************************************************************************
598  * WCMD_dupenv
599  *
600  * Make a copy of the environment.
601  */
602 static WCHAR *WCMD_dupenv( const WCHAR *env )
603 {
604   WCHAR *env_copy;
605   int len;
606
607   if( !env )
608     return NULL;
609
610   len = 0;
611   while ( env[len] )
612     len += (lstrlenW(&env[len]) + 1);
613
614   env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
615   if (!env_copy)
616   {
617     WCMD_output ("out of memory\n");
618     return env_copy;
619   }
620   memcpy (env_copy, env, len*sizeof (WCHAR));
621   env_copy[len] = 0;
622
623   return env_copy;
624 }
625
626 /*****************************************************************************
627  * WCMD_setlocal
628  *
629  *  setlocal pushes the environment onto a stack
630  *  Save the environment as unicode so we don't screw anything up.
631  */
632 void WCMD_setlocal (const char *s) {
633   WCHAR *env;
634   struct env_stack *env_copy;
635
636   /* DISABLEEXTENSIONS ignored */
637
638   env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
639   if( !env_copy )
640   {
641     WCMD_output ("out of memory\n");
642     return;
643   }
644
645   env = GetEnvironmentStringsW ();
646
647   env_copy->strings = WCMD_dupenv (env);
648   if (env_copy->strings)
649   {
650     env_copy->next = saved_environment;
651     saved_environment = env_copy;
652   }
653   else
654     LocalFree (env_copy);
655
656   FreeEnvironmentStringsW (env);
657 }
658
659 /*****************************************************************************
660  * WCMD_strchrW
661  */
662 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
663 {
664    while(*str)
665    {
666      if(*str == ch)
667        return str;
668      str++;
669    }
670    return NULL;
671 }
672
673 /*****************************************************************************
674  * WCMD_endlocal
675  *
676  *  endlocal pops the environment off a stack
677  */
678 void WCMD_endlocal (void) {
679   WCHAR *env, *old, *p;
680   struct env_stack *temp;
681   int len, n;
682
683   if (!saved_environment)
684     return;
685
686   /* pop the old environment from the stack */
687   temp = saved_environment;
688   saved_environment = temp->next;
689
690   /* delete the current environment, totally */
691   env = GetEnvironmentStringsW ();
692   old = WCMD_dupenv (GetEnvironmentStringsW ());
693   len = 0;
694   while (old[len]) {
695     n = lstrlenW(&old[len]) + 1;
696     p = WCMD_strchrW(&old[len], '=');
697     if (p)
698     {
699       *p++ = 0;
700       SetEnvironmentVariableW (&old[len], NULL);
701     }
702     len += n;
703   }
704   LocalFree (old);
705   FreeEnvironmentStringsW (env);
706   
707   /* restore old environment */
708   env = temp->strings;
709   len = 0;
710   while (env[len]) {
711     n = lstrlenW(&env[len]) + 1;
712     p = WCMD_strchrW(&env[len], '=');
713     if (p)
714     {
715       *p++ = 0;
716       SetEnvironmentVariableW (&env[len], p);
717     }
718     len += n;
719   }
720   LocalFree (env);
721   LocalFree (temp);
722 }
723
724 /*****************************************************************************
725  * WCMD_setshow_attrib
726  *
727  * Display and optionally sets DOS attributes on a file or directory
728  *
729  * FIXME: Wine currently uses the Unix stat() function to get file attributes.
730  * As a result only the Readonly flag is correctly reported, the Archive bit
731  * is always set and the rest are not implemented. We do the Right Thing anyway.
732  *
733  * FIXME: No SET functionality.
734  *
735  */
736
737 void WCMD_setshow_attrib (void) {
738
739 DWORD count;
740 HANDLE hff;
741 WIN32_FIND_DATA fd;
742 char flags[9] = {"        "};
743
744   if (param1[0] == '-') {
745     WCMD_output (nyi);
746     return;
747   }
748
749   if (lstrlen(param1) == 0) {
750     GetCurrentDirectory (sizeof(param1), param1);
751     strcat (param1, "\\*");
752   }
753
754   hff = FindFirstFile (param1, &fd);
755   if (hff == INVALID_HANDLE_VALUE) {
756     WCMD_output ("%s: File Not Found\n",param1);
757   }
758   else {
759     do {
760       if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
761         if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
762           flags[0] = 'H';
763         }
764         if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
765           flags[1] = 'S';
766         }
767         if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
768           flags[2] = 'A';
769         }
770         if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
771           flags[3] = 'R';
772         }
773         if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
774           flags[4] = 'T';
775         }
776         if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
777           flags[5] = 'C';
778         }
779         WCMD_output ("%s   %s\n", flags, fd.cFileName);
780         for (count=0; count < 8; count++) flags[count] = ' ';
781       }
782     } while (FindNextFile(hff, &fd) != 0);
783   }
784   FindClose (hff);
785 }
786
787 /*****************************************************************************
788  * WCMD_setshow_default
789  *
790  *      Set/Show the current default directory
791  */
792
793 void WCMD_setshow_default (void) {
794
795 BOOL status;
796 char string[1024];
797
798   if (strlen(param1) == 0) {
799     GetCurrentDirectory (sizeof(string), string);
800     strcat (string, "\n");
801     WCMD_output (string);
802   }
803   else {
804     status = SetCurrentDirectory (param1);
805     if (!status) {
806       WCMD_print_error ();
807       return;
808     }
809    }
810   return;
811 }
812
813 /****************************************************************************
814  * WCMD_setshow_date
815  *
816  * Set/Show the system date
817  * FIXME: Can't change date yet
818  */
819
820 void WCMD_setshow_date (void) {
821
822 char curdate[64], buffer[64];
823 DWORD count;
824
825   if (lstrlen(param1) == 0) {
826     if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
827                 curdate, sizeof(curdate))) {
828       WCMD_output ("Current Date is %s\nEnter new date: ", curdate);
829       ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
830       if (count > 2) {
831         WCMD_output (nyi);
832       }
833     }
834     else WCMD_print_error ();
835   }
836   else {
837     WCMD_output (nyi);
838   }
839 }
840
841 /****************************************************************************
842  * WCMD_compare
843  */
844 static int WCMD_compare( const void *a, const void *b )
845 {
846     int r;
847     const char * const *str_a = a, * const *str_b = b;
848     r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
849           *str_a, -1, *str_b, -1 );
850     if( r == CSTR_LESS_THAN ) return -1;
851     if( r == CSTR_GREATER_THAN ) return 1;
852     return 0;
853 }
854
855 /****************************************************************************
856  * WCMD_setshow_sortenv
857  *
858  * sort variables into order for display
859  */
860 static void WCMD_setshow_sortenv(const char *s)
861 {
862   UINT count=0, len=0, i;
863   const char **str;
864
865   /* count the number of strings, and the total length */
866   while ( s[len] ) {
867     len += (lstrlen(&s[len]) + 1);
868     count++;
869   }
870
871   /* add the strings to an array */
872   str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
873   if( !str )
874     return;
875   str[0] = s;
876   for( i=1; i<count; i++ )
877     str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
878
879   /* sort the array */
880   qsort( str, count, sizeof (char*), WCMD_compare );
881
882   /* print it */
883   for( i=0; i<count; i++ ) {
884       WCMD_output_asis(str[i]);
885       WCMD_output_asis("\n");
886   }
887
888   LocalFree( str );
889 }
890
891 /****************************************************************************
892  * WCMD_setshow_env
893  *
894  * Set/Show the environment variables
895  */
896
897 void WCMD_setshow_env (char *s) {
898
899 LPVOID env;
900 char *p;
901 int status;
902 char buffer[1048];
903
904   if (strlen(param1) == 0) {
905     env = GetEnvironmentStrings ();
906     WCMD_setshow_sortenv( env );
907   }
908   else {
909     p = strchr (s, '=');
910     if (p == NULL) {
911
912       /* FIXME: Emulate Win98 for now, ie "SET C" looks ONLY for an
913          environment variable C, whereas on NT it shows ALL variables
914          starting with C.
915        */
916       status = GetEnvironmentVariable(s, buffer, sizeof(buffer));
917       if (status) {
918         WCMD_output_asis( s);
919         WCMD_output_asis( "=");
920         WCMD_output_asis( buffer);
921         WCMD_output_asis( "\n");
922       } else {
923         WCMD_output ("Environment variable %s not defined\n", s);
924       }
925       return;
926     }
927     *p++ = '\0';
928
929     if (strlen(p) == 0) p = NULL;
930     status = SetEnvironmentVariable (s, p);
931     if ((!status) & (GetLastError() != ERROR_ENVVAR_NOT_FOUND)) WCMD_print_error();
932   }
933   /* WCMD_output (newline);   @JED*/
934 }
935
936 /****************************************************************************
937  * WCMD_setshow_path
938  *
939  * Set/Show the path environment variable
940  */
941
942 void WCMD_setshow_path (char *command) {
943
944 char string[1024];
945 DWORD status;
946
947   if (strlen(param1) == 0) {
948     status = GetEnvironmentVariable ("PATH", string, sizeof(string));
949     if (status != 0) {
950       WCMD_output_asis ( "PATH=");
951       WCMD_output_asis ( string);
952       WCMD_output_asis ( "\n");
953     }
954     else {
955       WCMD_output ("PATH not found\n");
956     }
957   }
958   else {
959     status = SetEnvironmentVariable ("PATH", command);
960     if (!status) WCMD_print_error();
961   }
962 }
963
964 /****************************************************************************
965  * WCMD_setshow_prompt
966  *
967  * Set or show the command prompt.
968  */
969
970 void WCMD_setshow_prompt (void) {
971
972 char *s;
973
974   if (strlen(param1) == 0) {
975     SetEnvironmentVariable ("PROMPT", NULL);
976   }
977   else {
978     s = param1;
979     while ((*s == '=') || (*s == ' ')) s++;
980     if (strlen(s) == 0) {
981       SetEnvironmentVariable ("PROMPT", NULL);
982     }
983     else SetEnvironmentVariable ("PROMPT", s);
984   }
985 }
986
987 /****************************************************************************
988  * WCMD_setshow_time
989  *
990  * Set/Show the system time
991  * FIXME: Can't change time yet
992  */
993
994 void WCMD_setshow_time (void) {
995
996 char curtime[64], buffer[64];
997 DWORD count;
998 SYSTEMTIME st;
999
1000   if (strlen(param1) == 0) {
1001     GetLocalTime(&st);
1002     if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1003                 curtime, sizeof(curtime))) {
1004       WCMD_output ("Current Time is %s\nEnter new time: ", curtime);
1005       ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1006       if (count > 2) {
1007         WCMD_output (nyi);
1008       }
1009     }
1010     else WCMD_print_error ();
1011   }
1012   else {
1013     WCMD_output (nyi);
1014   }
1015 }
1016
1017 /****************************************************************************
1018  * WCMD_shift
1019  *
1020  * Shift batch parameters.
1021  */
1022
1023 void WCMD_shift (void) {
1024
1025   if (context != NULL) context -> shift_count++;
1026
1027 }
1028
1029 /****************************************************************************
1030  * WCMD_title
1031  *
1032  * Set the console title
1033  */
1034 void WCMD_title (char *command) {
1035   SetConsoleTitle(command);
1036 }
1037
1038 /****************************************************************************
1039  * WCMD_type
1040  *
1041  * Copy a file to standard output.
1042  */
1043
1044 void WCMD_type (void) {
1045
1046 HANDLE h;
1047 char buffer[512];
1048 DWORD count;
1049
1050   if (param1[0] == 0x00) {
1051     WCMD_output ("Argument missing\n");
1052     return;
1053   }
1054   h = CreateFile (param1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1055                 FILE_ATTRIBUTE_NORMAL, NULL);
1056   if (h == INVALID_HANDLE_VALUE) {
1057     WCMD_print_error ();
1058     return;
1059   }
1060   while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1061     if (count == 0) break;      /* ReadFile reports success on EOF! */
1062     buffer[count] = 0;
1063     WCMD_output_asis (buffer);
1064   }
1065   CloseHandle (h);
1066 }
1067
1068 /****************************************************************************
1069  * WCMD_verify
1070  *
1071  * Display verify flag.
1072  * FIXME: We don't actually do anything with the verify flag other than toggle
1073  * it...
1074  */
1075
1076 void WCMD_verify (char *command) {
1077
1078 static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1079 int count;
1080
1081   count = strlen(command);
1082   if (count == 0) {
1083     if (verify_mode) WCMD_output (von);
1084     else WCMD_output (voff);
1085     return;
1086   }
1087   if (lstrcmpi(command, "ON") == 0) {
1088     verify_mode = 1;
1089     return;
1090   }
1091   else if (lstrcmpi(command, "OFF") == 0) {
1092     verify_mode = 0;
1093     return;
1094   }
1095   else WCMD_output ("Verify must be ON or OFF\n");
1096 }
1097
1098 /****************************************************************************
1099  * WCMD_version
1100  *
1101  * Display version info.
1102  */
1103
1104 void WCMD_version (void) {
1105
1106   WCMD_output (version_string);
1107
1108 }
1109
1110 /****************************************************************************
1111  * WCMD_volume
1112  *
1113  * Display volume info and/or set volume label. Returns 0 if error.
1114  */
1115
1116 int WCMD_volume (int mode, char *path) {
1117
1118 DWORD count, serial;
1119 char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1120 BOOL status;
1121
1122   if (lstrlen(path) == 0) {
1123     status = GetCurrentDirectory (sizeof(curdir), curdir);
1124     if (!status) {
1125       WCMD_print_error ();
1126       return 0;
1127     }
1128     status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1129         NULL, NULL, 0);
1130   }
1131   else {
1132     if ((path[1] != ':') || (lstrlen(path) != 2)) {
1133       WCMD_output_asis("Syntax Error\n\n");
1134       return 0;
1135     }
1136     wsprintf (curdir, "%s\\", path);
1137     status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1138         NULL, NULL, 0);
1139   }
1140   if (!status) {
1141     WCMD_print_error ();
1142     return 0;
1143   }
1144   WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1145         curdir[0], label, HIWORD(serial), LOWORD(serial));
1146   if (mode) {
1147     WCMD_output ("Volume label (11 characters, ENTER for none)?");
1148     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1149     if (count > 1) {
1150       string[count-1] = '\0';           /* ReadFile output is not null-terminated! */
1151       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1152     }
1153     if (lstrlen(path) != 0) {
1154       if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1155     }
1156     else {
1157       if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1158     }
1159   }
1160   return 1;
1161 }
1162
1163 /**************************************************************************
1164  * WCMD_exit
1165  *
1166  * Exit either the process, or just this batch program
1167  *
1168  */
1169
1170 void WCMD_exit (void) {
1171
1172     int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1173
1174     if (context && lstrcmpi(quals, "/B") == 0) {
1175         errorlevel = rc;
1176         context -> skip_rest = TRUE;
1177     } else {
1178         ExitProcess(rc);
1179     }
1180 }