cmd: Fix silly local variables indentation that breaks diff -p.
[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 #include <shellapi.h>
39
40 void WCMD_execute (char *orig_command, char *parameter, char *substitution);
41
42 struct env_stack
43 {
44   struct env_stack *next;
45   WCHAR *strings;
46 };
47
48 struct env_stack *saved_environment;
49 struct env_stack *pushd_directories;
50
51 extern HINSTANCE hinst;
52 extern char *inbuilt[];
53 extern int echo_mode, verify_mode;
54 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
55 extern BATCH_CONTEXT *context;
56 extern DWORD errorlevel;
57
58
59
60 /****************************************************************************
61  * WCMD_clear_screen
62  *
63  * Clear the terminal screen.
64  */
65
66 void WCMD_clear_screen (void) {
67
68   /* Emulate by filling the screen from the top left to bottom right with
69         spaces, then moving the cursor to the top left afterwards */
70   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
71   HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
72
73   if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
74   {
75       COORD topLeft;
76       DWORD screenSize;
77
78       screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
79
80       topLeft.X = 0;
81       topLeft.Y = 0;
82       FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
83       SetConsoleCursorPosition(hStdOut, topLeft);
84   }
85 }
86
87 /****************************************************************************
88  * WCMD_change_tty
89  *
90  * Change the default i/o device (ie redirect STDin/STDout).
91  */
92
93 void WCMD_change_tty (void) {
94
95   WCMD_output (nyi);
96
97 }
98
99 /****************************************************************************
100  * WCMD_copy
101  *
102  * Copy a file or wildcarded set.
103  * FIXME: No wildcard support
104  */
105
106 void WCMD_copy (void) {
107
108   DWORD count;
109   WIN32_FIND_DATA fd;
110   HANDLE hff;
111   BOOL force, status;
112   static const char overwrite[] = "Overwrite file (Y/N)?";
113   char string[8], outpath[MAX_PATH], inpath[MAX_PATH], *infile, copycmd[3];
114   DWORD len;
115
116   if (param1[0] == 0x00) {
117     WCMD_output ("Argument missing\n");
118     return;
119   }
120
121   if ((strchr(param1,'*') != NULL) && (strchr(param1,'%') != NULL)) {
122     WCMD_output ("Wildcards not yet supported\n");
123     return;
124   }
125
126   /* If no destination supplied, assume current directory */
127   if (param2[0] == 0x00) {
128       strcpy(param2, ".");
129   }
130
131   GetFullPathName (param2, sizeof(outpath), outpath, NULL);
132   if (outpath[strlen(outpath) - 1] == '\\')
133       outpath[strlen(outpath) - 1] = '\0';
134   hff = FindFirstFile (outpath, &fd);
135   if (hff != INVALID_HANDLE_VALUE) {
136     if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
137       GetFullPathName (param1, sizeof(inpath), inpath, &infile);
138       strcat (outpath, "\\");
139       strcat (outpath, infile);
140     }
141     FindClose (hff);
142   }
143
144   /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
145   if (strstr (quals, "/-Y"))
146     force = FALSE;
147   else if (strstr (quals, "/Y"))
148     force = TRUE;
149   else {
150     len = GetEnvironmentVariable ("COPYCMD", copycmd, sizeof(copycmd));
151     force = (len && len < sizeof(copycmd) && ! lstrcmpi (copycmd, "/Y"));
152   }
153
154   if (!force) {
155     hff = FindFirstFile (outpath, &fd);
156     if (hff != INVALID_HANDLE_VALUE) {
157       FindClose (hff);
158       WCMD_output (overwrite);
159       ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
160       if (toupper(string[0]) == 'Y') force = TRUE;
161     }
162     else force = TRUE;
163   }
164   if (force) {
165     status = CopyFile (param1, outpath, FALSE);
166     if (!status) WCMD_print_error ();
167   }
168 }
169
170 /****************************************************************************
171  * WCMD_create_dir
172  *
173  * Create a directory.
174  *
175  * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
176  * they do not already exist.
177  */
178
179 BOOL create_full_path(CHAR* path)
180 {
181     int len;
182     CHAR *new_path;
183     BOOL ret = TRUE;
184
185     new_path = HeapAlloc(GetProcessHeap(),0,strlen(path)+1);
186     strcpy(new_path,path);
187
188     while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
189         new_path[len - 1] = 0;
190
191     while (!CreateDirectory(new_path,NULL))
192     {
193         CHAR *slash;
194         DWORD last_error = GetLastError();
195         if (last_error == ERROR_ALREADY_EXISTS)
196             break;
197
198         if (last_error != ERROR_PATH_NOT_FOUND)
199         {
200             ret = FALSE;
201             break;
202         }
203
204         if (!(slash = strrchr(new_path,'\\')) && ! (slash = strrchr(new_path,'/')))
205         {
206             ret = FALSE;
207             break;
208         }
209
210         len = slash - new_path;
211         new_path[len] = 0;
212         if (!create_full_path(new_path))
213         {
214             ret = FALSE;
215             break;
216         }
217         new_path[len] = '\\';
218     }
219     HeapFree(GetProcessHeap(),0,new_path);
220     return ret;
221 }
222
223 void WCMD_create_dir (void) {
224
225     if (param1[0] == 0x00) {
226         WCMD_output ("Argument missing\n");
227         return;
228     }
229     if (!create_full_path(param1)) WCMD_print_error ();
230 }
231
232 /****************************************************************************
233  * WCMD_delete
234  *
235  * Delete a file or wildcarded set.
236  *
237  * Note on /A:
238  *  - Testing shows /A is repeatable, eg. /a-r /ar matches all files
239  *  - Each set is a pattern, eg /ahr /as-r means
240  *         readonly+hidden OR nonreadonly system files
241  *  - The '-' applies to a single field, ie /a:-hr means read only
242  *         non-hidden files
243  */
244
245 void WCMD_delete (int recurse) {
246
247   WIN32_FIND_DATA fd;
248   HANDLE hff;
249   char fpath[MAX_PATH];
250   char *p;
251
252   if (param1[0] == 0x00) {
253     WCMD_output ("Argument missing\n");
254     return;
255   }
256
257   /* If filename part of parameter is * or *.*, prompt unless
258      /Q supplied.                                            */
259   if ((strstr (quals, "/Q") == NULL) && (strstr (quals, "/P") == NULL)) {
260
261     char drive[10];
262     char dir[MAX_PATH];
263     char fname[MAX_PATH];
264     char ext[MAX_PATH];
265
266     /* Convert path into actual directory spec */
267     GetFullPathName (param1, sizeof(fpath), fpath, NULL);
268     WCMD_splitpath(fpath, drive, dir, fname, ext);
269
270     /* Only prompt for * and *.*, not *a, a*, *.a* etc */
271     if ((strcmp(fname, "*") == 0) &&
272         (*ext == 0x00 || (strcmp(ext, ".*") == 0))) {
273       BOOL  ok;
274       char  question[MAXSTRING];
275
276       /* Ask for confirmation */
277       sprintf(question, "%s, ", fpath);
278       ok = WCMD_ask_confirm(question, TRUE);
279
280       /* Abort if answer is 'N' */
281       if (!ok) return;
282     }
283   }
284
285   hff = FindFirstFile (param1, &fd);
286   if (hff == INVALID_HANDLE_VALUE) {
287     WCMD_output ("%s :File Not Found\n",param1);
288     return;
289   }
290   /* Support del <dirname> by just deleting all files dirname\* */
291   if ((strchr(param1,'*') == NULL) && (strchr(param1,'?') == NULL)
292         && (!recurse) && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
293     strcat (param1, "\\*");
294     FindClose(hff);
295     WCMD_delete (1);
296     return;
297
298   } else {
299
300     /* Build the filename to delete as <supplied directory>\<findfirst filename> */
301     strcpy (fpath, param1);
302     do {
303       p = strrchr (fpath, '\\');
304       if (p != NULL) {
305         *++p = '\0';
306         strcat (fpath, fd.cFileName);
307       }
308       else strcpy (fpath, fd.cFileName);
309       if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
310         BOOL  ok = TRUE;
311         char *nextA = strstr (quals, "/A");
312
313         /* Handle attribute matching (/A) */
314         if (nextA != NULL) {
315           ok = FALSE;
316           while (nextA != NULL && !ok) {
317
318             char *thisA = (nextA+2);
319             BOOL  stillOK = TRUE;
320
321             /* Skip optional : */
322             if (*thisA == ':') thisA++;
323
324             /* Parse each of the /A[:]xxx in turn */
325             while (*thisA && *thisA != '/') {
326               BOOL negate    = FALSE;
327               BOOL attribute = FALSE;
328
329               /* Match negation of attribute first */
330               if (*thisA == '-') {
331                 negate=TRUE;
332                 thisA++;
333               }
334
335               /* Match attribute */
336               switch (*thisA) {
337               case 'R': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
338                         break;
339               case 'H': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
340                         break;
341               case 'S': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM);
342                         break;
343               case 'A': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE);
344                         break;
345               default:
346                   WCMD_output ("Syntax error\n");
347               }
348
349               /* Now check result, keeping a running boolean about whether it
350                  matches all parsed attribues so far                         */
351               if (attribute && !negate) {
352                   stillOK = stillOK;
353               } else if (!attribute && negate) {
354                   stillOK = stillOK;
355               } else {
356                   stillOK = FALSE;
357               }
358               thisA++;
359             }
360
361             /* Save the running total as the final result */
362             ok = stillOK;
363
364             /* Step on to next /A set */
365             nextA = strstr (nextA+1, "/A");
366           }
367         }
368
369         /* /P means prompt for each file */
370         if (ok && strstr (quals, "/P") != NULL) {
371           char  question[MAXSTRING];
372
373           /* Ask for confirmation */
374           sprintf(question, "%s, Delete", fpath);
375           ok = WCMD_ask_confirm(question, FALSE);
376         }
377
378         /* Only proceed if ok to */
379         if (ok) {
380
381           /* If file is read only, and /F supplied, delete it */
382           if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
383               strstr (quals, "/F") != NULL) {
384               SetFileAttributes(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
385           }
386
387           /* Now do the delete */
388           if (!DeleteFile (fpath)) WCMD_print_error ();
389         }
390
391       }
392     } while (FindNextFile(hff, &fd) != 0);
393     FindClose (hff);
394   }
395 }
396
397 /****************************************************************************
398  * WCMD_echo
399  *
400  * Echo input to the screen (or not). We don't try to emulate the bugs
401  * in DOS (try typing "ECHO ON AGAIN" for an example).
402  */
403
404 void WCMD_echo (const char *command) {
405
406   static const char eon[] = "Echo is ON\n", eoff[] = "Echo is OFF\n";
407   int count;
408
409   if ((command[0] == '.') && (command[1] == 0)) {
410     WCMD_output (newline);
411     return;
412   }
413   if (command[0]==' ')
414     command++;
415   count = strlen(command);
416   if (count == 0) {
417     if (echo_mode) WCMD_output (eon);
418     else WCMD_output (eoff);
419     return;
420   }
421   if (lstrcmpi(command, "ON") == 0) {
422     echo_mode = 1;
423     return;
424   }
425   if (lstrcmpi(command, "OFF") == 0) {
426     echo_mode = 0;
427     return;
428   }
429   WCMD_output_asis (command);
430   WCMD_output (newline);
431
432 }
433
434 /**************************************************************************
435  * WCMD_for
436  *
437  * Batch file loop processing.
438  * FIXME: We don't exhaustively check syntax. Any command which works in MessDOS
439  * will probably work here, but the reverse is not necessarily the case...
440  */
441
442 void WCMD_for (char *p) {
443
444   WIN32_FIND_DATA fd;
445   HANDLE hff;
446   char *cmd, *item;
447   char set[MAX_PATH], param[MAX_PATH];
448   int i;
449
450   if (lstrcmpi (WCMD_parameter (p, 1, NULL), "in")
451         || lstrcmpi (WCMD_parameter (p, 3, NULL), "do")
452         || (param1[0] != '%')) {
453     WCMD_output ("Syntax error\n");
454     return;
455   }
456   lstrcpyn (set, WCMD_parameter (p, 2, NULL), sizeof(set));
457   WCMD_parameter (p, 4, &cmd);
458   lstrcpy (param, param1);
459
460 /*
461  *      If the parameter within the set has a wildcard then search for matching files
462  *      otherwise do a literal substitution.
463  */
464
465   i = 0;
466   while (*(item = WCMD_parameter (set, i, NULL))) {
467     if (strpbrk (item, "*?")) {
468       hff = FindFirstFile (item, &fd);
469       if (hff == INVALID_HANDLE_VALUE) {
470         return;
471       }
472       do {
473         WCMD_execute (cmd, param, fd.cFileName);
474       } while (FindNextFile(hff, &fd) != 0);
475       FindClose (hff);
476 }
477     else {
478       WCMD_execute (cmd, param, item);
479     }
480     i++;
481   }
482 }
483
484 /*****************************************************************************
485  * WCMD_Execute
486  *
487  *      Execute a command after substituting variable text for the supplied parameter
488  */
489
490 void WCMD_execute (char *orig_cmd, char *param, char *subst) {
491
492   char *new_cmd, *p, *s, *dup;
493   int size;
494
495   size = lstrlen (orig_cmd);
496   new_cmd = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, size);
497   dup = s = strdup (orig_cmd);
498
499   while ((p = strstr (s, param))) {
500     *p = '\0';
501     size += lstrlen (subst);
502     new_cmd = (char *) LocalReAlloc ((HANDLE)new_cmd, size, 0);
503     strcat (new_cmd, s);
504     strcat (new_cmd, subst);
505     s = p + lstrlen (param);
506   }
507   strcat (new_cmd, s);
508   WCMD_process_command (new_cmd);
509   free (dup);
510   LocalFree ((HANDLE)new_cmd);
511 }
512
513
514 /**************************************************************************
515  * WCMD_give_help
516  *
517  *      Simple on-line help. Help text is stored in the resource file.
518  */
519
520 void WCMD_give_help (char *command) {
521
522   int i;
523   char buffer[2048];
524
525   command = WCMD_strtrim_leading_spaces(command);
526   if (lstrlen(command) == 0) {
527     LoadString (hinst, 1000, buffer, sizeof(buffer));
528     WCMD_output_asis (buffer);
529   }
530   else {
531     for (i=0; i<=WCMD_EXIT; i++) {
532       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
533           param1, -1, inbuilt[i], -1) == 2) {
534         LoadString (hinst, i, buffer, sizeof(buffer));
535         WCMD_output_asis (buffer);
536         return;
537       }
538     }
539     WCMD_output ("No help available for %s\n", param1);
540   }
541   return;
542 }
543
544 /****************************************************************************
545  * WCMD_go_to
546  *
547  * Batch file jump instruction. Not the most efficient algorithm ;-)
548  * Prints error message if the specified label cannot be found - the file pointer is
549  * then at EOF, effectively stopping the batch file.
550  * FIXME: DOS is supposed to allow labels with spaces - we don't.
551  */
552
553 void WCMD_goto (void) {
554
555   char string[MAX_PATH];
556
557   if (param1[0] == 0x00) {
558     WCMD_output ("Argument missing\n");
559     return;
560   }
561   if (context != NULL) {
562     char *paramStart = param1;
563
564     /* Handle special :EOF label */
565     if (lstrcmpi (":eof", param1) == 0) {
566       context -> skip_rest = TRUE;
567       return;
568     }
569
570     /* Support goto :label as well as goto label */
571     if (*paramStart == ':') paramStart++;
572
573     SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
574     while (WCMD_fgets (string, sizeof(string), context -> h)) {
575       if ((string[0] == ':') && (lstrcmpi (&string[1], paramStart) == 0)) return;
576     }
577     WCMD_output ("Target to GOTO not found\n");
578   }
579   return;
580 }
581
582 /*****************************************************************************
583  * WCMD_pushd
584  *
585  *      Push a directory onto the stack
586  */
587
588 void WCMD_pushd (void) {
589     struct env_stack *curdir;
590     BOOL   status;
591     WCHAR *thisdir;
592
593     curdir  = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
594     thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
595     if( !curdir || !thisdir ) {
596       LocalFree(curdir);
597       LocalFree(thisdir);
598       WCMD_output ("out of memory\n");
599       return;
600     }
601
602     GetCurrentDirectoryW (1024, thisdir);
603     status = SetCurrentDirectoryA (param1);
604     if (!status) {
605       WCMD_print_error ();
606       LocalFree(curdir);
607       LocalFree(thisdir);
608       return;
609     } else {
610       curdir -> next    = pushd_directories;
611       curdir -> strings = thisdir;
612       pushd_directories = curdir;
613     }
614 }
615
616
617 /*****************************************************************************
618  * WCMD_popd
619  *
620  *      Pop a directory from the stack
621  */
622
623 void WCMD_popd (void) {
624     struct env_stack *temp = pushd_directories;
625
626     if (!pushd_directories)
627       return;
628
629     /* pop the old environment from the stack, and make it the current dir */
630     pushd_directories = temp->next;
631     SetCurrentDirectoryW(temp->strings);
632     LocalFree (temp->strings);
633     LocalFree (temp);
634 }
635
636 /****************************************************************************
637  * WCMD_if
638  *
639  * Batch file conditional.
640  * FIXME: Much more syntax checking needed!
641  */
642
643 void WCMD_if (char *p) {
644
645   int negate = 0, test = 0;
646   char condition[MAX_PATH], *command, *s;
647
648   if (!lstrcmpi (param1, "not")) {
649     negate = 1;
650     lstrcpy (condition, param2);
651   }
652   else {
653     lstrcpy (condition, param1);
654   }
655   if (!lstrcmpi (condition, "errorlevel")) {
656     if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
657     WCMD_parameter (p, 2+negate, &command);
658   }
659   else if (!lstrcmpi (condition, "exist")) {
660     if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
661         test = 1;
662     }
663     WCMD_parameter (p, 2+negate, &command);
664   }
665   else if (!lstrcmpi (condition, "defined")) {
666     if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
667         test = 1;
668     }
669     WCMD_parameter (p, 2+negate, &command);
670   }
671   else if ((s = strstr (p, "=="))) {
672     s += 2;
673     if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
674     WCMD_parameter (s, 1, &command);
675   }
676   else {
677     WCMD_output ("Syntax error\n");
678     return;
679   }
680   if (test != negate) {
681     command = strdup (command);
682     WCMD_process_command (command);
683     free (command);
684   }
685 }
686
687 /****************************************************************************
688  * WCMD_move
689  *
690  * Move a file, directory tree or wildcarded set of files.
691  * FIXME: Needs input and output files to be fully specified.
692  */
693
694 void WCMD_move (void) {
695
696   int status;
697   char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
698   WIN32_FIND_DATA fd;
699   HANDLE hff;
700
701   if (param1[0] == 0x00) {
702     WCMD_output ("Argument missing\n");
703     return;
704   }
705
706   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
707     WCMD_output ("Wildcards not yet supported\n");
708     return;
709   }
710
711   /* If no destination supplied, assume current directory */
712   if (param2[0] == 0x00) {
713       strcpy(param2, ".");
714   }
715
716   /* If 2nd parm is directory, then use original filename */
717   GetFullPathName (param2, sizeof(outpath), outpath, NULL);
718   if (outpath[strlen(outpath) - 1] == '\\')
719       outpath[strlen(outpath) - 1] = '\0';
720   hff = FindFirstFile (outpath, &fd);
721   if (hff != INVALID_HANDLE_VALUE) {
722     if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
723       GetFullPathName (param1, sizeof(inpath), inpath, &infile);
724       strcat (outpath, "\\");
725       strcat (outpath, infile);
726     }
727     FindClose (hff);
728   }
729
730   status = MoveFile (param1, outpath);
731   if (!status) WCMD_print_error ();
732 }
733
734 /****************************************************************************
735  * WCMD_pause
736  *
737  * Wait for keyboard input.
738  */
739
740 void WCMD_pause (void) {
741
742   DWORD count;
743   char string[32];
744
745   WCMD_output (anykey);
746   ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
747 }
748
749 /****************************************************************************
750  * WCMD_remove_dir
751  *
752  * Delete a directory.
753  */
754
755 void WCMD_remove_dir (void) {
756
757   if (param1[0] == 0x00) {
758     WCMD_output ("Argument missing\n");
759     return;
760   }
761
762   /* If subdirectory search not supplied, just try to remove
763      and report error if it fails (eg if it contains a file) */
764   if (strstr (quals, "/S") == NULL) {
765     if (!RemoveDirectory (param1)) WCMD_print_error ();
766
767   /* Otherwise use ShFileOp to recursively remove a directory */
768   } else {
769
770     SHFILEOPSTRUCT lpDir;
771
772     /* Ask first */
773     if (strstr (quals, "/Q") == NULL) {
774       BOOL  ok;
775       char  question[MAXSTRING];
776
777       /* Ask for confirmation */
778       sprintf(question, "%s, ", param1);
779       ok = WCMD_ask_confirm(question, TRUE);
780
781       /* Abort if answer is 'N' */
782       if (!ok) return;
783     }
784
785     /* Do the delete */
786     lpDir.hwnd   = NULL;
787     lpDir.pTo    = NULL;
788     lpDir.pFrom  = param1;
789     lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
790     lpDir.wFunc  = FO_DELETE;
791     if (SHFileOperationA(&lpDir)) WCMD_print_error ();
792   }
793 }
794
795 /****************************************************************************
796  * WCMD_rename
797  *
798  * Rename a file.
799  * FIXME: Needs input and output files to be fully specified.
800  */
801
802 void WCMD_rename (void) {
803
804   int status;
805
806   if (param1[0] == 0x00 || param2[0] == 0x00) {
807     WCMD_output ("Argument missing\n");
808     return;
809   }
810   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
811     WCMD_output ("Wildcards not yet supported\n");
812     return;
813   }
814   status = MoveFile (param1, param2);
815   if (!status) WCMD_print_error ();
816 }
817
818 /*****************************************************************************
819  * WCMD_dupenv
820  *
821  * Make a copy of the environment.
822  */
823 static WCHAR *WCMD_dupenv( const WCHAR *env )
824 {
825   WCHAR *env_copy;
826   int len;
827
828   if( !env )
829     return NULL;
830
831   len = 0;
832   while ( env[len] )
833     len += (lstrlenW(&env[len]) + 1);
834
835   env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
836   if (!env_copy)
837   {
838     WCMD_output ("out of memory\n");
839     return env_copy;
840   }
841   memcpy (env_copy, env, len*sizeof (WCHAR));
842   env_copy[len] = 0;
843
844   return env_copy;
845 }
846
847 /*****************************************************************************
848  * WCMD_setlocal
849  *
850  *  setlocal pushes the environment onto a stack
851  *  Save the environment as unicode so we don't screw anything up.
852  */
853 void WCMD_setlocal (const char *s) {
854   WCHAR *env;
855   struct env_stack *env_copy;
856
857   /* DISABLEEXTENSIONS ignored */
858
859   env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
860   if( !env_copy )
861   {
862     WCMD_output ("out of memory\n");
863     return;
864   }
865
866   env = GetEnvironmentStringsW ();
867
868   env_copy->strings = WCMD_dupenv (env);
869   if (env_copy->strings)
870   {
871     env_copy->next = saved_environment;
872     saved_environment = env_copy;
873   }
874   else
875     LocalFree (env_copy);
876
877   FreeEnvironmentStringsW (env);
878 }
879
880 /*****************************************************************************
881  * WCMD_strchrW
882  */
883 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
884 {
885    while(*str)
886    {
887      if(*str == ch)
888        return str;
889      str++;
890    }
891    return NULL;
892 }
893
894 /*****************************************************************************
895  * WCMD_endlocal
896  *
897  *  endlocal pops the environment off a stack
898  */
899 void WCMD_endlocal (void) {
900   WCHAR *env, *old, *p;
901   struct env_stack *temp;
902   int len, n;
903
904   if (!saved_environment)
905     return;
906
907   /* pop the old environment from the stack */
908   temp = saved_environment;
909   saved_environment = temp->next;
910
911   /* delete the current environment, totally */
912   env = GetEnvironmentStringsW ();
913   old = WCMD_dupenv (GetEnvironmentStringsW ());
914   len = 0;
915   while (old[len]) {
916     n = lstrlenW(&old[len]) + 1;
917     p = WCMD_strchrW(&old[len], '=');
918     if (p)
919     {
920       *p++ = 0;
921       SetEnvironmentVariableW (&old[len], NULL);
922     }
923     len += n;
924   }
925   LocalFree (old);
926   FreeEnvironmentStringsW (env);
927
928   /* restore old environment */
929   env = temp->strings;
930   len = 0;
931   while (env[len]) {
932     n = lstrlenW(&env[len]) + 1;
933     p = WCMD_strchrW(&env[len], '=');
934     if (p)
935     {
936       *p++ = 0;
937       SetEnvironmentVariableW (&env[len], p);
938     }
939     len += n;
940   }
941   LocalFree (env);
942   LocalFree (temp);
943 }
944
945 /*****************************************************************************
946  * WCMD_setshow_attrib
947  *
948  * Display and optionally sets DOS attributes on a file or directory
949  *
950  * FIXME: Wine currently uses the Unix stat() function to get file attributes.
951  * As a result only the Readonly flag is correctly reported, the Archive bit
952  * is always set and the rest are not implemented. We do the Right Thing anyway.
953  *
954  * FIXME: No SET functionality.
955  *
956  */
957
958 void WCMD_setshow_attrib (void) {
959
960   DWORD count;
961   HANDLE hff;
962   WIN32_FIND_DATA fd;
963   char flags[9] = {"        "};
964
965   if (param1[0] == '-') {
966     WCMD_output (nyi);
967     return;
968   }
969
970   if (lstrlen(param1) == 0) {
971     GetCurrentDirectory (sizeof(param1), param1);
972     strcat (param1, "\\*");
973   }
974
975   hff = FindFirstFile (param1, &fd);
976   if (hff == INVALID_HANDLE_VALUE) {
977     WCMD_output ("%s: File Not Found\n",param1);
978   }
979   else {
980     do {
981       if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
982         if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
983           flags[0] = 'H';
984         }
985         if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
986           flags[1] = 'S';
987         }
988         if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
989           flags[2] = 'A';
990         }
991         if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
992           flags[3] = 'R';
993         }
994         if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
995           flags[4] = 'T';
996         }
997         if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
998           flags[5] = 'C';
999         }
1000         WCMD_output ("%s   %s\n", flags, fd.cFileName);
1001         for (count=0; count < 8; count++) flags[count] = ' ';
1002       }
1003     } while (FindNextFile(hff, &fd) != 0);
1004   }
1005   FindClose (hff);
1006 }
1007
1008 /*****************************************************************************
1009  * WCMD_setshow_default
1010  *
1011  *      Set/Show the current default directory
1012  */
1013
1014 void WCMD_setshow_default (void) {
1015
1016   BOOL status;
1017   char string[1024];
1018
1019   if (strlen(param1) == 0) {
1020     GetCurrentDirectory (sizeof(string), string);
1021     strcat (string, "\n");
1022     WCMD_output (string);
1023   }
1024   else {
1025     status = SetCurrentDirectory (param1);
1026     if (!status) {
1027       WCMD_print_error ();
1028       return;
1029     }
1030    }
1031   return;
1032 }
1033
1034 /****************************************************************************
1035  * WCMD_setshow_date
1036  *
1037  * Set/Show the system date
1038  * FIXME: Can't change date yet
1039  */
1040
1041 void WCMD_setshow_date (void) {
1042
1043   char curdate[64], buffer[64];
1044   DWORD count;
1045
1046   if (lstrlen(param1) == 0) {
1047     if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1048                 curdate, sizeof(curdate))) {
1049       WCMD_output ("Current Date is %s\nEnter new date: ", curdate);
1050       ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1051       if (count > 2) {
1052         WCMD_output (nyi);
1053       }
1054     }
1055     else WCMD_print_error ();
1056   }
1057   else {
1058     WCMD_output (nyi);
1059   }
1060 }
1061
1062 /****************************************************************************
1063  * WCMD_compare
1064  */
1065 static int WCMD_compare( const void *a, const void *b )
1066 {
1067     int r;
1068     const char * const *str_a = a, * const *str_b = b;
1069     r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1070           *str_a, -1, *str_b, -1 );
1071     if( r == CSTR_LESS_THAN ) return -1;
1072     if( r == CSTR_GREATER_THAN ) return 1;
1073     return 0;
1074 }
1075
1076 /****************************************************************************
1077  * WCMD_setshow_sortenv
1078  *
1079  * sort variables into order for display
1080  * Optionally only display those who start with a stub
1081  * returns the count displayed
1082  */
1083 static int WCMD_setshow_sortenv(const char *s, const char *stub)
1084 {
1085   UINT count=0, len=0, i, displayedcount=0, stublen=0;
1086   const char **str;
1087
1088   if (stub) stublen = strlen(stub);
1089
1090   /* count the number of strings, and the total length */
1091   while ( s[len] ) {
1092     len += (lstrlen(&s[len]) + 1);
1093     count++;
1094   }
1095
1096   /* add the strings to an array */
1097   str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
1098   if( !str )
1099     return 0;
1100   str[0] = s;
1101   for( i=1; i<count; i++ )
1102     str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
1103
1104   /* sort the array */
1105   qsort( str, count, sizeof (char*), WCMD_compare );
1106
1107   /* print it */
1108   for( i=0; i<count; i++ ) {
1109     if (!stub || CompareString (LOCALE_USER_DEFAULT,
1110                                 NORM_IGNORECASE | SORT_STRINGSORT,
1111                                 str[i], stublen, stub, -1) == 2) {
1112       WCMD_output_asis(str[i]);
1113       WCMD_output_asis("\n");
1114       displayedcount++;
1115     }
1116   }
1117
1118   LocalFree( str );
1119   return displayedcount;
1120 }
1121
1122 /****************************************************************************
1123  * WCMD_setshow_env
1124  *
1125  * Set/Show the environment variables
1126  */
1127
1128 void WCMD_setshow_env (char *s) {
1129
1130   LPVOID env;
1131   char *p;
1132   int status;
1133
1134   if (strlen(param1) == 0) {
1135     env = GetEnvironmentStrings ();
1136     WCMD_setshow_sortenv( env, NULL );
1137   }
1138   else {
1139     p = strchr (s, '=');
1140     if (p == NULL) {
1141       env = GetEnvironmentStrings ();
1142       if (WCMD_setshow_sortenv( env, s ) == 0) {
1143         WCMD_output ("Environment variable %s not defined\n", s);
1144       }
1145       return;
1146     }
1147     *p++ = '\0';
1148
1149     if (strlen(p) == 0) p = NULL;
1150     status = SetEnvironmentVariable (s, p);
1151     if ((!status) & (GetLastError() != ERROR_ENVVAR_NOT_FOUND)) WCMD_print_error();
1152   }
1153 }
1154
1155 /****************************************************************************
1156  * WCMD_setshow_path
1157  *
1158  * Set/Show the path environment variable
1159  */
1160
1161 void WCMD_setshow_path (char *command) {
1162
1163   char string[1024];
1164   DWORD status;
1165
1166   if (strlen(param1) == 0) {
1167     status = GetEnvironmentVariable ("PATH", string, sizeof(string));
1168     if (status != 0) {
1169       WCMD_output_asis ( "PATH=");
1170       WCMD_output_asis ( string);
1171       WCMD_output_asis ( "\n");
1172     }
1173     else {
1174       WCMD_output ("PATH not found\n");
1175     }
1176   }
1177   else {
1178     if (*command == '=') command++; /* Skip leading '=' */
1179     status = SetEnvironmentVariable ("PATH", command);
1180     if (!status) WCMD_print_error();
1181   }
1182 }
1183
1184 /****************************************************************************
1185  * WCMD_setshow_prompt
1186  *
1187  * Set or show the command prompt.
1188  */
1189
1190 void WCMD_setshow_prompt (void) {
1191
1192   char *s;
1193
1194   if (strlen(param1) == 0) {
1195     SetEnvironmentVariable ("PROMPT", NULL);
1196   }
1197   else {
1198     s = param1;
1199     while ((*s == '=') || (*s == ' ')) s++;
1200     if (strlen(s) == 0) {
1201       SetEnvironmentVariable ("PROMPT", NULL);
1202     }
1203     else SetEnvironmentVariable ("PROMPT", s);
1204   }
1205 }
1206
1207 /****************************************************************************
1208  * WCMD_setshow_time
1209  *
1210  * Set/Show the system time
1211  * FIXME: Can't change time yet
1212  */
1213
1214 void WCMD_setshow_time (void) {
1215
1216   char curtime[64], buffer[64];
1217   DWORD count;
1218   SYSTEMTIME st;
1219
1220   if (strlen(param1) == 0) {
1221     GetLocalTime(&st);
1222     if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1223                 curtime, sizeof(curtime))) {
1224       WCMD_output ("Current Time is %s\nEnter new time: ", curtime);
1225       ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1226       if (count > 2) {
1227         WCMD_output (nyi);
1228       }
1229     }
1230     else WCMD_print_error ();
1231   }
1232   else {
1233     WCMD_output (nyi);
1234   }
1235 }
1236
1237 /****************************************************************************
1238  * WCMD_shift
1239  *
1240  * Shift batch parameters.
1241  */
1242
1243 void WCMD_shift (void) {
1244
1245   if (context != NULL) context -> shift_count++;
1246
1247 }
1248
1249 /****************************************************************************
1250  * WCMD_title
1251  *
1252  * Set the console title
1253  */
1254 void WCMD_title (char *command) {
1255   SetConsoleTitle(command);
1256 }
1257
1258 /****************************************************************************
1259  * WCMD_type
1260  *
1261  * Copy a file to standard output.
1262  */
1263
1264 void WCMD_type (void) {
1265
1266   HANDLE h;
1267   char buffer[512];
1268   DWORD count;
1269
1270   if (param1[0] == 0x00) {
1271     WCMD_output ("Argument missing\n");
1272     return;
1273   }
1274   h = CreateFile (param1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1275                 FILE_ATTRIBUTE_NORMAL, NULL);
1276   if (h == INVALID_HANDLE_VALUE) {
1277     WCMD_print_error ();
1278     return;
1279   }
1280   while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1281     if (count == 0) break;      /* ReadFile reports success on EOF! */
1282     buffer[count] = 0;
1283     WCMD_output_asis (buffer);
1284   }
1285   CloseHandle (h);
1286 }
1287
1288 /****************************************************************************
1289  * WCMD_verify
1290  *
1291  * Display verify flag.
1292  * FIXME: We don't actually do anything with the verify flag other than toggle
1293  * it...
1294  */
1295
1296 void WCMD_verify (char *command) {
1297
1298   static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1299   int count;
1300
1301   count = strlen(command);
1302   if (count == 0) {
1303     if (verify_mode) WCMD_output (von);
1304     else WCMD_output (voff);
1305     return;
1306   }
1307   if (lstrcmpi(command, "ON") == 0) {
1308     verify_mode = 1;
1309     return;
1310   }
1311   else if (lstrcmpi(command, "OFF") == 0) {
1312     verify_mode = 0;
1313     return;
1314   }
1315   else WCMD_output ("Verify must be ON or OFF\n");
1316 }
1317
1318 /****************************************************************************
1319  * WCMD_version
1320  *
1321  * Display version info.
1322  */
1323
1324 void WCMD_version (void) {
1325
1326   WCMD_output (version_string);
1327
1328 }
1329
1330 /****************************************************************************
1331  * WCMD_volume
1332  *
1333  * Display volume info and/or set volume label. Returns 0 if error.
1334  */
1335
1336 int WCMD_volume (int mode, char *path) {
1337
1338   DWORD count, serial;
1339   char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1340   BOOL status;
1341
1342   if (lstrlen(path) == 0) {
1343     status = GetCurrentDirectory (sizeof(curdir), curdir);
1344     if (!status) {
1345       WCMD_print_error ();
1346       return 0;
1347     }
1348     status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1349         NULL, NULL, 0);
1350   }
1351   else {
1352     if ((path[1] != ':') || (lstrlen(path) != 2)) {
1353       WCMD_output_asis("Syntax Error\n\n");
1354       return 0;
1355     }
1356     wsprintf (curdir, "%s\\", path);
1357     status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1358         NULL, NULL, 0);
1359   }
1360   if (!status) {
1361     WCMD_print_error ();
1362     return 0;
1363   }
1364   WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1365         curdir[0], label, HIWORD(serial), LOWORD(serial));
1366   if (mode) {
1367     WCMD_output ("Volume label (11 characters, ENTER for none)?");
1368     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1369     if (count > 1) {
1370       string[count-1] = '\0';           /* ReadFile output is not null-terminated! */
1371       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1372     }
1373     if (lstrlen(path) != 0) {
1374       if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1375     }
1376     else {
1377       if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1378     }
1379   }
1380   return 1;
1381 }
1382
1383 /**************************************************************************
1384  * WCMD_exit
1385  *
1386  * Exit either the process, or just this batch program
1387  *
1388  */
1389
1390 void WCMD_exit (void) {
1391
1392     int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1393
1394     if (context && lstrcmpi(quals, "/B") == 0) {
1395         errorlevel = rc;
1396         context -> skip_rest = TRUE;
1397     } else {
1398         ExitProcess(rc);
1399     }
1400 }
1401
1402 /**************************************************************************
1403  * WCMD_ask_confirm
1404  *
1405  * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
1406  * answer.
1407  *
1408  * Returns True if Y answer is selected
1409  *
1410  */
1411 BOOL WCMD_ask_confirm (char *message, BOOL showSureText) {
1412
1413     char  msgbuffer[MAXSTRING];
1414     char  Ybuffer[MAXSTRING];
1415     char  Nbuffer[MAXSTRING];
1416     char  answer[MAX_PATH] = "";
1417     DWORD count = 0;
1418
1419     /* Load the translated 'Are you sure', plus valid answers */
1420     LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer));
1421     LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer));
1422     LoadString (hinst, WCMD_NO, Nbuffer, sizeof(Nbuffer));
1423
1424     /* Loop waiting on a Y or N */
1425     while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
1426       WCMD_output_asis (message);
1427       if (showSureText) {
1428         WCMD_output_asis (msgbuffer);
1429       }
1430       WCMD_output_asis (" (");
1431       WCMD_output_asis (Ybuffer);
1432       WCMD_output_asis ("/");
1433       WCMD_output_asis (Nbuffer);
1434       WCMD_output_asis (")?");
1435       ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer),
1436                 &count, NULL);
1437       answer[0] = toupper(answer[0]);
1438     }
1439
1440     /* Return the answer */
1441     return (answer[0] == Ybuffer[0]);
1442 }