cmd.exe: Add support for move with simple wildcards.
[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 #include "wine/debug.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
42
43 void WCMD_execute (char *orig_command, char *parameter, char *substitution);
44
45 struct env_stack *saved_environment;
46 struct env_stack *pushd_directories;
47
48 extern HINSTANCE hinst;
49 extern char *inbuilt[];
50 extern int echo_mode, verify_mode, defaultColor;
51 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
52 extern BATCH_CONTEXT *context;
53 extern DWORD errorlevel;
54
55
56
57 /****************************************************************************
58  * WCMD_clear_screen
59  *
60  * Clear the terminal screen.
61  */
62
63 void WCMD_clear_screen (void) {
64
65   /* Emulate by filling the screen from the top left to bottom right with
66         spaces, then moving the cursor to the top left afterwards */
67   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
68   HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
69
70   if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
71   {
72       COORD topLeft;
73       DWORD screenSize;
74
75       screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
76
77       topLeft.X = 0;
78       topLeft.Y = 0;
79       FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
80       SetConsoleCursorPosition(hStdOut, topLeft);
81   }
82 }
83
84 /****************************************************************************
85  * WCMD_change_tty
86  *
87  * Change the default i/o device (ie redirect STDin/STDout).
88  */
89
90 void WCMD_change_tty (void) {
91
92   WCMD_output (nyi);
93
94 }
95
96 /****************************************************************************
97  * WCMD_copy
98  *
99  * Copy a file or wildcarded set.
100  * FIXME: No wildcard support
101  */
102
103 void WCMD_copy (void) {
104
105   DWORD count;
106   WIN32_FIND_DATA fd;
107   HANDLE hff;
108   BOOL force, status;
109   static const char overwrite[] = "Overwrite file (Y/N)?";
110   char string[8], outpath[MAX_PATH], inpath[MAX_PATH], *infile, copycmd[3];
111   DWORD len;
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   /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
142   if (strstr (quals, "/-Y"))
143     force = FALSE;
144   else if (strstr (quals, "/Y"))
145     force = TRUE;
146   else {
147     len = GetEnvironmentVariable ("COPYCMD", copycmd, sizeof(copycmd));
148     force = (len && len < sizeof(copycmd) && ! lstrcmpi (copycmd, "/Y"));
149   }
150
151   if (!force) {
152     hff = FindFirstFile (outpath, &fd);
153     if (hff != INVALID_HANDLE_VALUE) {
154       FindClose (hff);
155       WCMD_output (overwrite);
156       ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
157       if (toupper(string[0]) == 'Y') force = TRUE;
158     }
159     else force = TRUE;
160   }
161   if (force) {
162     status = CopyFile (param1, outpath, FALSE);
163     if (!status) WCMD_print_error ();
164   }
165 }
166
167 /****************************************************************************
168  * WCMD_create_dir
169  *
170  * Create a directory.
171  *
172  * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
173  * they do not already exist.
174  */
175
176 static BOOL create_full_path(CHAR* path)
177 {
178     int len;
179     CHAR *new_path;
180     BOOL ret = TRUE;
181
182     new_path = HeapAlloc(GetProcessHeap(),0,strlen(path)+1);
183     strcpy(new_path,path);
184
185     while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
186         new_path[len - 1] = 0;
187
188     while (!CreateDirectory(new_path,NULL))
189     {
190         CHAR *slash;
191         DWORD last_error = GetLastError();
192         if (last_error == ERROR_ALREADY_EXISTS)
193             break;
194
195         if (last_error != ERROR_PATH_NOT_FOUND)
196         {
197             ret = FALSE;
198             break;
199         }
200
201         if (!(slash = strrchr(new_path,'\\')) && ! (slash = strrchr(new_path,'/')))
202         {
203             ret = FALSE;
204             break;
205         }
206
207         len = slash - new_path;
208         new_path[len] = 0;
209         if (!create_full_path(new_path))
210         {
211             ret = FALSE;
212             break;
213         }
214         new_path[len] = '\\';
215     }
216     HeapFree(GetProcessHeap(),0,new_path);
217     return ret;
218 }
219
220 void WCMD_create_dir (void) {
221
222     if (param1[0] == 0x00) {
223         WCMD_output ("Argument missing\n");
224         return;
225     }
226     if (!create_full_path(param1)) WCMD_print_error ();
227 }
228
229 /****************************************************************************
230  * WCMD_delete
231  *
232  * Delete a file or wildcarded set.
233  *
234  * Note on /A:
235  *  - Testing shows /A is repeatable, eg. /a-r /ar matches all files
236  *  - Each set is a pattern, eg /ahr /as-r means
237  *         readonly+hidden OR nonreadonly system files
238  *  - The '-' applies to a single field, ie /a:-hr means read only
239  *         non-hidden files
240  */
241
242 void WCMD_delete (char *command) {
243
244     int   argno         = 0;
245     int   argsProcessed = 0;
246     char *argN          = command;
247
248     /* Loop through all args */
249     while (argN) {
250       char *thisArg = WCMD_parameter (command, argno++, &argN);
251       if (argN && argN[0] != '/') {
252
253         WIN32_FIND_DATA fd;
254         HANDLE hff;
255         char fpath[MAX_PATH];
256         char *p;
257
258
259         WINE_TRACE("del: Processing arg %s (quals:%s)\n", thisArg, quals);
260         argsProcessed++;
261
262         /* If filename part of parameter is * or *.*, prompt unless
263            /Q supplied.                                            */
264         if ((strstr (quals, "/Q") == NULL) && (strstr (quals, "/P") == NULL)) {
265
266           char drive[10];
267           char dir[MAX_PATH];
268           char fname[MAX_PATH];
269           char ext[MAX_PATH];
270
271           /* Convert path into actual directory spec */
272           GetFullPathName (thisArg, sizeof(fpath), fpath, NULL);
273           WCMD_splitpath(fpath, drive, dir, fname, ext);
274
275           /* Only prompt for * and *.*, not *a, a*, *.a* etc */
276           if ((strcmp(fname, "*") == 0) &&
277               (*ext == 0x00 || (strcmp(ext, ".*") == 0))) {
278             BOOL  ok;
279             char  question[MAXSTRING];
280
281             /* Ask for confirmation */
282             sprintf(question, "%s, ", fpath);
283             ok = WCMD_ask_confirm(question, TRUE);
284
285             /* Abort if answer is 'N' */
286             if (!ok) continue;
287           }
288         }
289
290         hff = FindFirstFile (thisArg, &fd);
291         if (hff == INVALID_HANDLE_VALUE) {
292           WCMD_output ("%s :File Not Found\n", thisArg);
293           continue;
294         }
295         /* Support del <dirname> by just deleting all files dirname\* */
296         if ((strchr(thisArg,'*') == NULL) && (strchr(thisArg,'?') == NULL)
297                 && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
298           char modifiedParm[MAX_PATH];
299           strcpy(modifiedParm, thisArg);
300           strcat(modifiedParm, "\\*");
301           FindClose(hff);
302           WCMD_delete(modifiedParm);
303           continue;
304
305         } else {
306
307           /* Build the filename to delete as <supplied directory>\<findfirst filename> */
308           strcpy (fpath, thisArg);
309           do {
310             p = strrchr (fpath, '\\');
311             if (p != NULL) {
312               *++p = '\0';
313               strcat (fpath, fd.cFileName);
314             }
315             else strcpy (fpath, fd.cFileName);
316             if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
317               BOOL  ok = TRUE;
318               char *nextA = strstr (quals, "/A");
319
320               /* Handle attribute matching (/A) */
321               if (nextA != NULL) {
322                 ok = FALSE;
323                 while (nextA != NULL && !ok) {
324
325                   char *thisA = (nextA+2);
326                   BOOL  stillOK = TRUE;
327
328                   /* Skip optional : */
329                   if (*thisA == ':') thisA++;
330
331                   /* Parse each of the /A[:]xxx in turn */
332                   while (*thisA && *thisA != '/') {
333                     BOOL negate    = FALSE;
334                     BOOL attribute = FALSE;
335
336                     /* Match negation of attribute first */
337                     if (*thisA == '-') {
338                       negate=TRUE;
339                       thisA++;
340                     }
341
342                     /* Match attribute */
343                     switch (*thisA) {
344                     case 'R': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
345                               break;
346                     case 'H': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
347                               break;
348                     case 'S': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM);
349                               break;
350                     case 'A': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE);
351                               break;
352                     default:
353                         WCMD_output ("Syntax error\n");
354                     }
355
356                     /* Now check result, keeping a running boolean about whether it
357                        matches all parsed attribues so far                         */
358                     if (attribute && !negate) {
359                         stillOK = stillOK;
360                     } else if (!attribute && negate) {
361                         stillOK = stillOK;
362                     } else {
363                         stillOK = FALSE;
364                     }
365                     thisA++;
366                   }
367
368                   /* Save the running total as the final result */
369                   ok = stillOK;
370
371                   /* Step on to next /A set */
372                   nextA = strstr (nextA+1, "/A");
373                 }
374               }
375
376               /* /P means prompt for each file */
377               if (ok && strstr (quals, "/P") != NULL) {
378                 char  question[MAXSTRING];
379
380                 /* Ask for confirmation */
381                 sprintf(question, "%s, Delete", fpath);
382                 ok = WCMD_ask_confirm(question, FALSE);
383               }
384
385               /* Only proceed if ok to */
386               if (ok) {
387
388                 /* If file is read only, and /F supplied, delete it */
389                 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
390                     strstr (quals, "/F") != NULL) {
391                     SetFileAttributes(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
392                 }
393
394                 /* Now do the delete */
395                 if (!DeleteFile (fpath)) WCMD_print_error ();
396               }
397
398             }
399           } while (FindNextFile(hff, &fd) != 0);
400           FindClose (hff);
401         }
402       }
403     }
404
405     /* Handle no valid args */
406     if (argsProcessed == 0) {
407       WCMD_output ("Argument missing\n");
408       return;
409     }
410 }
411
412 /****************************************************************************
413  * WCMD_echo
414  *
415  * Echo input to the screen (or not). We don't try to emulate the bugs
416  * in DOS (try typing "ECHO ON AGAIN" for an example).
417  */
418
419 void WCMD_echo (const char *command) {
420
421   static const char eon[] = "Echo is ON\n", eoff[] = "Echo is OFF\n";
422   int count;
423
424   if ((command[0] == '.') && (command[1] == 0)) {
425     WCMD_output (newline);
426     return;
427   }
428   if (command[0]==' ')
429     command++;
430   count = strlen(command);
431   if (count == 0) {
432     if (echo_mode) WCMD_output (eon);
433     else WCMD_output (eoff);
434     return;
435   }
436   if (lstrcmpi(command, "ON") == 0) {
437     echo_mode = 1;
438     return;
439   }
440   if (lstrcmpi(command, "OFF") == 0) {
441     echo_mode = 0;
442     return;
443   }
444   WCMD_output_asis (command);
445   WCMD_output (newline);
446
447 }
448
449 /**************************************************************************
450  * WCMD_for
451  *
452  * Batch file loop processing.
453  * FIXME: We don't exhaustively check syntax. Any command which works in MessDOS
454  * will probably work here, but the reverse is not necessarily the case...
455  */
456
457 void WCMD_for (char *p) {
458
459   WIN32_FIND_DATA fd;
460   HANDLE hff;
461   char *cmd, *item;
462   char set[MAX_PATH], param[MAX_PATH];
463   int i;
464
465   if (lstrcmpi (WCMD_parameter (p, 1, NULL), "in")
466         || lstrcmpi (WCMD_parameter (p, 3, NULL), "do")
467         || (param1[0] != '%')) {
468     WCMD_output ("Syntax error\n");
469     return;
470   }
471   lstrcpyn (set, WCMD_parameter (p, 2, NULL), sizeof(set));
472   WCMD_parameter (p, 4, &cmd);
473   lstrcpy (param, param1);
474
475 /*
476  *      If the parameter within the set has a wildcard then search for matching files
477  *      otherwise do a literal substitution.
478  */
479
480   i = 0;
481   while (*(item = WCMD_parameter (set, i, NULL))) {
482     if (strpbrk (item, "*?")) {
483       hff = FindFirstFile (item, &fd);
484       if (hff == INVALID_HANDLE_VALUE) {
485         return;
486       }
487       do {
488         WCMD_execute (cmd, param, fd.cFileName);
489       } while (FindNextFile(hff, &fd) != 0);
490       FindClose (hff);
491 }
492     else {
493       WCMD_execute (cmd, param, item);
494     }
495     i++;
496   }
497 }
498
499 /*****************************************************************************
500  * WCMD_Execute
501  *
502  *      Execute a command after substituting variable text for the supplied parameter
503  */
504
505 void WCMD_execute (char *orig_cmd, char *param, char *subst) {
506
507   char *new_cmd, *p, *s, *dup;
508   int size;
509
510   size = lstrlen (orig_cmd);
511   new_cmd = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, size);
512   dup = s = strdup (orig_cmd);
513
514   while ((p = strstr (s, param))) {
515     *p = '\0';
516     size += lstrlen (subst);
517     new_cmd = (char *) LocalReAlloc ((HANDLE)new_cmd, size, 0);
518     strcat (new_cmd, s);
519     strcat (new_cmd, subst);
520     s = p + lstrlen (param);
521   }
522   strcat (new_cmd, s);
523   WCMD_process_command (new_cmd);
524   free (dup);
525   LocalFree ((HANDLE)new_cmd);
526 }
527
528
529 /**************************************************************************
530  * WCMD_give_help
531  *
532  *      Simple on-line help. Help text is stored in the resource file.
533  */
534
535 void WCMD_give_help (char *command) {
536
537   int i;
538   char buffer[2048];
539
540   command = WCMD_strtrim_leading_spaces(command);
541   if (lstrlen(command) == 0) {
542     LoadString (hinst, 1000, buffer, sizeof(buffer));
543     WCMD_output_asis (buffer);
544   }
545   else {
546     for (i=0; i<=WCMD_EXIT; i++) {
547       if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
548           param1, -1, inbuilt[i], -1) == 2) {
549         LoadString (hinst, i, buffer, sizeof(buffer));
550         WCMD_output_asis (buffer);
551         return;
552       }
553     }
554     WCMD_output ("No help available for %s\n", param1);
555   }
556   return;
557 }
558
559 /****************************************************************************
560  * WCMD_go_to
561  *
562  * Batch file jump instruction. Not the most efficient algorithm ;-)
563  * Prints error message if the specified label cannot be found - the file pointer is
564  * then at EOF, effectively stopping the batch file.
565  * FIXME: DOS is supposed to allow labels with spaces - we don't.
566  */
567
568 void WCMD_goto (void) {
569
570   char string[MAX_PATH];
571
572   if (param1[0] == 0x00) {
573     WCMD_output ("Argument missing\n");
574     return;
575   }
576   if (context != NULL) {
577     char *paramStart = param1;
578
579     /* Handle special :EOF label */
580     if (lstrcmpi (":eof", param1) == 0) {
581       context -> skip_rest = TRUE;
582       return;
583     }
584
585     /* Support goto :label as well as goto label */
586     if (*paramStart == ':') paramStart++;
587
588     SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
589     while (WCMD_fgets (string, sizeof(string), context -> h)) {
590       if ((string[0] == ':') && (lstrcmpi (&string[1], paramStart) == 0)) return;
591     }
592     WCMD_output ("Target to GOTO not found\n");
593   }
594   return;
595 }
596
597 /*****************************************************************************
598  * WCMD_pushd
599  *
600  *      Push a directory onto the stack
601  */
602
603 void WCMD_pushd (char *command) {
604     struct env_stack *curdir;
605     WCHAR *thisdir;
606
607     if (strchr(command, '/') != NULL) {
608       SetLastError(ERROR_INVALID_PARAMETER);
609       WCMD_print_error();
610       return;
611     }
612
613     curdir  = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
614     thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
615     if( !curdir || !thisdir ) {
616       LocalFree(curdir);
617       LocalFree(thisdir);
618       WCMD_output ("out of memory\n");
619       return;
620     }
621
622     /* Change directory using CD code with /D parameter */
623     strcpy(quals, "/D");
624     GetCurrentDirectoryW (1024, thisdir);
625     errorlevel = 0;
626     WCMD_setshow_default(command);
627     if (errorlevel) {
628       LocalFree(curdir);
629       LocalFree(thisdir);
630       return;
631     } else {
632       curdir -> next    = pushd_directories;
633       curdir -> strings = thisdir;
634       if (pushd_directories == NULL) {
635         curdir -> u.stackdepth = 1;
636       } else {
637         curdir -> u.stackdepth = pushd_directories -> u.stackdepth + 1;
638       }
639       pushd_directories = curdir;
640     }
641 }
642
643
644 /*****************************************************************************
645  * WCMD_popd
646  *
647  *      Pop a directory from the stack
648  */
649
650 void WCMD_popd (void) {
651     struct env_stack *temp = pushd_directories;
652
653     if (!pushd_directories)
654       return;
655
656     /* pop the old environment from the stack, and make it the current dir */
657     pushd_directories = temp->next;
658     SetCurrentDirectoryW(temp->strings);
659     LocalFree (temp->strings);
660     LocalFree (temp);
661 }
662
663 /****************************************************************************
664  * WCMD_if
665  *
666  * Batch file conditional.
667  * FIXME: Much more syntax checking needed!
668  */
669
670 void WCMD_if (char *p) {
671
672   int negate = 0, test = 0;
673   char condition[MAX_PATH], *command, *s;
674
675   if (!lstrcmpi (param1, "not")) {
676     negate = 1;
677     lstrcpy (condition, param2);
678   }
679   else {
680     lstrcpy (condition, param1);
681   }
682   if (!lstrcmpi (condition, "errorlevel")) {
683     if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
684     WCMD_parameter (p, 2+negate, &command);
685   }
686   else if (!lstrcmpi (condition, "exist")) {
687     if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
688         test = 1;
689     }
690     WCMD_parameter (p, 2+negate, &command);
691   }
692   else if (!lstrcmpi (condition, "defined")) {
693     if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
694         test = 1;
695     }
696     WCMD_parameter (p, 2+negate, &command);
697   }
698   else if ((s = strstr (p, "=="))) {
699     s += 2;
700     if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
701     WCMD_parameter (s, 1, &command);
702   }
703   else {
704     WCMD_output ("Syntax error\n");
705     return;
706   }
707   if (test != negate) {
708     command = strdup (command);
709     WCMD_process_command (command);
710     free (command);
711   }
712 }
713
714 /****************************************************************************
715  * WCMD_move
716  *
717  * Move a file, directory tree or wildcarded set of files.
718  * FIXME: Needs input and output files to be fully specified.
719  */
720
721 void WCMD_move (void) {
722
723   int status;
724   char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
725   WIN32_FIND_DATA fd;
726   HANDLE hff;
727
728   if (param1[0] == 0x00) {
729     WCMD_output ("Argument missing\n");
730     return;
731   }
732
733   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
734     WCMD_output ("Wildcards not yet supported\n");
735     return;
736   }
737
738   /* If no destination supplied, assume current directory */
739   if (param2[0] == 0x00) {
740       strcpy(param2, ".");
741   }
742
743   /* If 2nd parm is directory, then use original filename */
744   GetFullPathName (param2, sizeof(outpath), outpath, NULL);
745   if (outpath[strlen(outpath) - 1] == '\\')
746       outpath[strlen(outpath) - 1] = '\0';
747   hff = FindFirstFile (outpath, &fd);
748   if (hff != INVALID_HANDLE_VALUE) {
749     if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
750       GetFullPathName (param1, sizeof(inpath), inpath, &infile);
751       strcat (outpath, "\\");
752       strcat (outpath, infile);
753     }
754     FindClose (hff);
755   }
756
757   status = MoveFile (param1, outpath);
758   if (!status) WCMD_print_error ();
759 }
760
761 /****************************************************************************
762  * WCMD_pause
763  *
764  * Wait for keyboard input.
765  */
766
767 void WCMD_pause (void) {
768
769   DWORD count;
770   char string[32];
771
772   WCMD_output (anykey);
773   ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
774 }
775
776 /****************************************************************************
777  * WCMD_remove_dir
778  *
779  * Delete a directory.
780  */
781
782 void WCMD_remove_dir (char *command) {
783
784   int   argno         = 0;
785   int   argsProcessed = 0;
786   char *argN          = command;
787
788   /* Loop through all args */
789   while (argN) {
790     char *thisArg = WCMD_parameter (command, argno++, &argN);
791     if (argN && argN[0] != '/') {
792       WINE_TRACE("rd: Processing arg %s (quals:%s)\n", thisArg, quals);
793       argsProcessed++;
794
795       /* If subdirectory search not supplied, just try to remove
796          and report error if it fails (eg if it contains a file) */
797       if (strstr (quals, "/S") == NULL) {
798         if (!RemoveDirectory (thisArg)) WCMD_print_error ();
799
800       /* Otherwise use ShFileOp to recursively remove a directory */
801       } else {
802
803         SHFILEOPSTRUCT lpDir;
804
805         /* Ask first */
806         if (strstr (quals, "/Q") == NULL) {
807           BOOL  ok;
808           char  question[MAXSTRING];
809
810           /* Ask for confirmation */
811           sprintf(question, "%s, ", thisArg);
812           ok = WCMD_ask_confirm(question, TRUE);
813
814           /* Abort if answer is 'N' */
815           if (!ok) return;
816         }
817
818         /* Do the delete */
819         lpDir.hwnd   = NULL;
820         lpDir.pTo    = NULL;
821         lpDir.pFrom  = thisArg;
822         lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
823         lpDir.wFunc  = FO_DELETE;
824         if (SHFileOperationA(&lpDir)) WCMD_print_error ();
825       }
826     }
827   }
828
829   /* Handle no valid args */
830   if (argsProcessed == 0) {
831     WCMD_output ("Argument missing\n");
832     return;
833   }
834
835 }
836
837 /****************************************************************************
838  * WCMD_rename
839  *
840  * Rename a file.
841  * FIXME: Needs input and output files to be fully specified.
842  */
843
844 void WCMD_rename (void) {
845
846   int             status;
847   HANDLE          hff;
848   WIN32_FIND_DATA fd;
849   char            input[MAX_PATH];
850   char           *dotDst = NULL;
851   char            drive[10];
852   char            dir[MAX_PATH];
853   char            fname[MAX_PATH];
854   char            ext[MAX_PATH];
855   DWORD           attribs;
856
857   errorlevel = 0;
858
859   /* Must be at least two args */
860   if (param1[0] == 0x00 || param2[0] == 0x00) {
861     WCMD_output ("Argument missing\n");
862     errorlevel = 1;
863     return;
864   }
865
866   /* Destination cannot contain a drive letter or directory separator */
867   if ((strchr(param1,':') != NULL) || (strchr(param1,'\\') != NULL)) {
868       SetLastError(ERROR_INVALID_PARAMETER);
869       WCMD_print_error();
870       errorlevel = 1;
871       return;
872   }
873
874   /* Convert partial path to full path */
875   GetFullPathName (param1, sizeof(input), input, NULL);
876   WINE_TRACE("Rename from '%s'('%s') to '%s'\n", input, param1, param2);
877   dotDst = strchr(param2, '.');
878
879   /* Split into components */
880   WCMD_splitpath(input, drive, dir, fname, ext);
881
882   hff = FindFirstFile (input, &fd);
883   while (hff != INVALID_HANDLE_VALUE) {
884     char  dest[MAX_PATH];
885     char  src[MAX_PATH];
886     char *dotSrc = NULL;
887     int   dirLen;
888
889     WINE_TRACE("Processing file '%s'\n", fd.cFileName);
890
891     /* FIXME: If dest name or extension is *, replace with filename/ext
892        part otherwise use supplied name. This supports:
893           ren *.fred *.jim
894           ren jim.* fred.* etc
895        However, windows has a more complex algorithum supporting eg
896           ?'s and *'s mid name                                         */
897     dotSrc = strchr(fd.cFileName, '.');
898
899     /* Build src & dest name */
900     strcpy(src, drive);
901     strcat(src, dir);
902     strcpy(dest, src);
903     dirLen = strlen(src);
904     strcat(src, fd.cFileName);
905
906     /* Build name */
907     if (param2[0] == '*') {
908       strcat(dest, fd.cFileName);
909       if (dotSrc) dest[dirLen + (dotSrc - fd.cFileName)] = 0x00;
910     } else {
911       strcat(dest, param2);
912       if (dotDst) dest[dirLen + (dotDst - param2)] = 0x00;
913     }
914
915     /* Build Extension */
916     if (dotDst && (*(dotDst+1)=='*')) {
917       if (dotSrc) strcat(dest, dotSrc);
918     } else if (dotDst) {
919       if (dotDst) strcat(dest, dotDst);
920     }
921
922     WINE_TRACE("Source '%s'\n", src);
923     WINE_TRACE("Dest   '%s'\n", dest);
924
925     /* Check if file is read only, otherwise move it */
926     attribs = GetFileAttributesA(src);
927     if ((attribs != INVALID_FILE_ATTRIBUTES) &&
928         (attribs & FILE_ATTRIBUTE_READONLY)) {
929       SetLastError(ERROR_ACCESS_DENIED);
930       status = 0;
931     } else {
932       status = MoveFile (src, dest);
933     }
934
935     if (!status) {
936       WCMD_print_error ();
937       errorlevel = 1;
938     }
939
940     /* Step on to next match */
941     if (FindNextFile(hff, &fd) == 0) {
942       FindClose(hff);
943       hff = INVALID_HANDLE_VALUE;
944       break;
945     }
946   }
947 }
948
949 /*****************************************************************************
950  * WCMD_dupenv
951  *
952  * Make a copy of the environment.
953  */
954 static WCHAR *WCMD_dupenv( const WCHAR *env )
955 {
956   WCHAR *env_copy;
957   int len;
958
959   if( !env )
960     return NULL;
961
962   len = 0;
963   while ( env[len] )
964     len += (lstrlenW(&env[len]) + 1);
965
966   env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
967   if (!env_copy)
968   {
969     WCMD_output ("out of memory\n");
970     return env_copy;
971   }
972   memcpy (env_copy, env, len*sizeof (WCHAR));
973   env_copy[len] = 0;
974
975   return env_copy;
976 }
977
978 /*****************************************************************************
979  * WCMD_setlocal
980  *
981  *  setlocal pushes the environment onto a stack
982  *  Save the environment as unicode so we don't screw anything up.
983  */
984 void WCMD_setlocal (const char *s) {
985   WCHAR *env;
986   struct env_stack *env_copy;
987   char cwd[MAX_PATH];
988
989   /* DISABLEEXTENSIONS ignored */
990
991   env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
992   if( !env_copy )
993   {
994     WCMD_output ("out of memory\n");
995     return;
996   }
997
998   env = GetEnvironmentStringsW ();
999
1000   env_copy->strings = WCMD_dupenv (env);
1001   if (env_copy->strings)
1002   {
1003     env_copy->next = saved_environment;
1004     saved_environment = env_copy;
1005
1006     /* Save the current drive letter */
1007     GetCurrentDirectory (MAX_PATH, cwd);
1008     env_copy->u.cwd = cwd[0];
1009   }
1010   else
1011     LocalFree (env_copy);
1012
1013   FreeEnvironmentStringsW (env);
1014
1015 }
1016
1017 /*****************************************************************************
1018  * WCMD_strchrW
1019  */
1020 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
1021 {
1022    while(*str)
1023    {
1024      if(*str == ch)
1025        return str;
1026      str++;
1027    }
1028    return NULL;
1029 }
1030
1031 /*****************************************************************************
1032  * WCMD_endlocal
1033  *
1034  *  endlocal pops the environment off a stack
1035  *  Note: When searching for '=', search from char position 1, to handle
1036  *        special internal environment variables =C:, =D: etc
1037  */
1038 void WCMD_endlocal (void) {
1039   WCHAR *env, *old, *p;
1040   struct env_stack *temp;
1041   int len, n;
1042
1043   if (!saved_environment)
1044     return;
1045
1046   /* pop the old environment from the stack */
1047   temp = saved_environment;
1048   saved_environment = temp->next;
1049
1050   /* delete the current environment, totally */
1051   env = GetEnvironmentStringsW ();
1052   old = WCMD_dupenv (GetEnvironmentStringsW ());
1053   len = 0;
1054   while (old[len]) {
1055     n = lstrlenW(&old[len]) + 1;
1056     p = WCMD_strchrW(&old[len] + 1, '=');
1057     if (p)
1058     {
1059       *p++ = 0;
1060       SetEnvironmentVariableW (&old[len], NULL);
1061     }
1062     len += n;
1063   }
1064   LocalFree (old);
1065   FreeEnvironmentStringsW (env);
1066
1067   /* restore old environment */
1068   env = temp->strings;
1069   len = 0;
1070   while (env[len]) {
1071     n = lstrlenW(&env[len]) + 1;
1072     p = WCMD_strchrW(&env[len] + 1, '=');
1073     if (p)
1074     {
1075       *p++ = 0;
1076       SetEnvironmentVariableW (&env[len], p);
1077     }
1078     len += n;
1079   }
1080
1081   /* Restore current drive letter */
1082   if (IsCharAlpha(temp->u.cwd)) {
1083     char envvar[4];
1084     char cwd[MAX_PATH];
1085     sprintf(envvar, "=%c:", temp->u.cwd);
1086     if (GetEnvironmentVariable(envvar, cwd, MAX_PATH)) {
1087       WINE_TRACE("Resetting cwd to %s\n", cwd);
1088       SetCurrentDirectory(cwd);
1089     }
1090   }
1091
1092   LocalFree (env);
1093   LocalFree (temp);
1094 }
1095
1096 /*****************************************************************************
1097  * WCMD_setshow_attrib
1098  *
1099  * Display and optionally sets DOS attributes on a file or directory
1100  *
1101  * FIXME: Wine currently uses the Unix stat() function to get file attributes.
1102  * As a result only the Readonly flag is correctly reported, the Archive bit
1103  * is always set and the rest are not implemented. We do the Right Thing anyway.
1104  *
1105  * FIXME: No SET functionality.
1106  *
1107  */
1108
1109 void WCMD_setshow_attrib (void) {
1110
1111   DWORD count;
1112   HANDLE hff;
1113   WIN32_FIND_DATA fd;
1114   char flags[9] = {"        "};
1115
1116   if (param1[0] == '-') {
1117     WCMD_output (nyi);
1118     return;
1119   }
1120
1121   if (lstrlen(param1) == 0) {
1122     GetCurrentDirectory (sizeof(param1), param1);
1123     strcat (param1, "\\*");
1124   }
1125
1126   hff = FindFirstFile (param1, &fd);
1127   if (hff == INVALID_HANDLE_VALUE) {
1128     WCMD_output ("%s: File Not Found\n",param1);
1129   }
1130   else {
1131     do {
1132       if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1133         if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
1134           flags[0] = 'H';
1135         }
1136         if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
1137           flags[1] = 'S';
1138         }
1139         if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
1140           flags[2] = 'A';
1141         }
1142         if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
1143           flags[3] = 'R';
1144         }
1145         if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
1146           flags[4] = 'T';
1147         }
1148         if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
1149           flags[5] = 'C';
1150         }
1151         WCMD_output ("%s   %s\n", flags, fd.cFileName);
1152         for (count=0; count < 8; count++) flags[count] = ' ';
1153       }
1154     } while (FindNextFile(hff, &fd) != 0);
1155   }
1156   FindClose (hff);
1157 }
1158
1159 /*****************************************************************************
1160  * WCMD_setshow_default
1161  *
1162  *      Set/Show the current default directory
1163  */
1164
1165 void WCMD_setshow_default (char *command) {
1166
1167   BOOL status;
1168   char string[1024];
1169   char cwd[1024];
1170   char *pos;
1171   WIN32_FIND_DATA fd;
1172   HANDLE hff;
1173
1174   WINE_TRACE("Request change to directory '%s'\n", command);
1175
1176   /* Skip /D and trailing whitespace if on the front of the command line */
1177   if (CompareString (LOCALE_USER_DEFAULT,
1178                      NORM_IGNORECASE | SORT_STRINGSORT,
1179                      command, 2, "/D", -1) == 2) {
1180     command += 2;
1181     while (*command && *command==' ') command++;
1182   }
1183
1184   GetCurrentDirectory (sizeof(cwd), cwd);
1185   if (strlen(command) == 0) {
1186     strcat (cwd, "\n");
1187     WCMD_output (cwd);
1188   }
1189   else {
1190     /* Remove any double quotes, which may be in the
1191        middle, eg. cd "C:\Program Files"\Microsoft is ok */
1192     pos = string;
1193     while (*command) {
1194       if (*command != '"') *pos++ = *command;
1195       command++;
1196     }
1197     *pos = 0x00;
1198
1199     /* Search for approprate directory */
1200     WINE_TRACE("Looking for directory '%s'\n", string);
1201     hff = FindFirstFile (string, &fd);
1202     while (hff != INVALID_HANDLE_VALUE) {
1203       if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1204         char fpath[MAX_PATH];
1205         char drive[10];
1206         char dir[MAX_PATH];
1207         char fname[MAX_PATH];
1208         char ext[MAX_PATH];
1209
1210         /* Convert path into actual directory spec */
1211         GetFullPathName (string, sizeof(fpath), fpath, NULL);
1212         WCMD_splitpath(fpath, drive, dir, fname, ext);
1213
1214         /* Rebuild path */
1215         sprintf(string, "%s%s%s", drive, dir, fd.cFileName);
1216
1217         FindClose(hff);
1218         hff = INVALID_HANDLE_VALUE;
1219         break;
1220       }
1221
1222       /* Step on to next match */
1223       if (FindNextFile(hff, &fd) == 0) {
1224         FindClose(hff);
1225         hff = INVALID_HANDLE_VALUE;
1226         break;
1227       }
1228     }
1229
1230     /* Change to that directory */
1231     WINE_TRACE("Really changing to directory '%s'\n", string);
1232
1233     status = SetCurrentDirectory (string);
1234     if (!status) {
1235       errorlevel = 1;
1236       WCMD_print_error ();
1237       return;
1238     } else {
1239
1240       /* Restore old directory if drive letter would change, and
1241            CD x:\directory /D (or pushd c:\directory) not supplied */
1242       if ((strstr(quals, "/D") == NULL) &&
1243           (param1[1] == ':') && (toupper(param1[0]) != toupper(cwd[0]))) {
1244         SetCurrentDirectory(cwd);
1245       }
1246     }
1247
1248     /* Set special =C: type environment variable, for drive letter of
1249        change of directory, even if path was restored due to missing
1250        /D (allows changing drive letter when not resident on that
1251        drive                                                          */
1252     if ((string[1] == ':') && IsCharAlpha (string[0])) {
1253       char env[4];
1254       strcpy(env, "=");
1255       strncpy(env+1, string, 2);
1256       env[3] = 0x00;
1257       SetEnvironmentVariable(env, string);
1258     }
1259
1260    }
1261   return;
1262 }
1263
1264 /****************************************************************************
1265  * WCMD_setshow_date
1266  *
1267  * Set/Show the system date
1268  * FIXME: Can't change date yet
1269  */
1270
1271 void WCMD_setshow_date (void) {
1272
1273   char curdate[64], buffer[64];
1274   DWORD count;
1275
1276   if (lstrlen(param1) == 0) {
1277     if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1278                 curdate, sizeof(curdate))) {
1279       WCMD_output ("Current Date is %s\n", curdate);
1280       if (strstr (quals, "/T") == NULL) {
1281         WCMD_output("Enter new date: ");
1282         ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1283         if (count > 2) {
1284           WCMD_output (nyi);
1285         }
1286       }
1287     }
1288     else WCMD_print_error ();
1289   }
1290   else {
1291     WCMD_output (nyi);
1292   }
1293 }
1294
1295 /****************************************************************************
1296  * WCMD_compare
1297  */
1298 static int WCMD_compare( const void *a, const void *b )
1299 {
1300     int r;
1301     const char * const *str_a = a, * const *str_b = b;
1302     r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1303           *str_a, -1, *str_b, -1 );
1304     if( r == CSTR_LESS_THAN ) return -1;
1305     if( r == CSTR_GREATER_THAN ) return 1;
1306     return 0;
1307 }
1308
1309 /****************************************************************************
1310  * WCMD_setshow_sortenv
1311  *
1312  * sort variables into order for display
1313  * Optionally only display those who start with a stub
1314  * returns the count displayed
1315  */
1316 static int WCMD_setshow_sortenv(const char *s, const char *stub)
1317 {
1318   UINT count=0, len=0, i, displayedcount=0, stublen=0;
1319   const char **str;
1320
1321   if (stub) stublen = strlen(stub);
1322
1323   /* count the number of strings, and the total length */
1324   while ( s[len] ) {
1325     len += (lstrlen(&s[len]) + 1);
1326     count++;
1327   }
1328
1329   /* add the strings to an array */
1330   str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
1331   if( !str )
1332     return 0;
1333   str[0] = s;
1334   for( i=1; i<count; i++ )
1335     str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
1336
1337   /* sort the array */
1338   qsort( str, count, sizeof (char*), WCMD_compare );
1339
1340   /* print it */
1341   for( i=0; i<count; i++ ) {
1342     if (!stub || CompareString (LOCALE_USER_DEFAULT,
1343                                 NORM_IGNORECASE | SORT_STRINGSORT,
1344                                 str[i], stublen, stub, -1) == 2) {
1345       /* Don't display special internal variables */
1346       if (str[i][0] != '=') {
1347         WCMD_output_asis(str[i]);
1348         WCMD_output_asis("\n");
1349         displayedcount++;
1350       }
1351     }
1352   }
1353
1354   LocalFree( str );
1355   return displayedcount;
1356 }
1357
1358 /****************************************************************************
1359  * WCMD_setshow_env
1360  *
1361  * Set/Show the environment variables
1362  */
1363
1364 void WCMD_setshow_env (char *s) {
1365
1366   LPVOID env;
1367   char *p;
1368   int status;
1369
1370   errorlevel = 0;
1371   if (param1[0] == 0x00 && quals[0] == 0x00) {
1372     env = GetEnvironmentStrings ();
1373     WCMD_setshow_sortenv( env, NULL );
1374     return;
1375   }
1376
1377   /* See if /P supplied, and if so echo the prompt, and read in a reply */
1378   if (CompareString (LOCALE_USER_DEFAULT,
1379                      NORM_IGNORECASE | SORT_STRINGSORT,
1380                      s, 2, "/P", -1) == 2) {
1381     char string[MAXSTRING];
1382     DWORD count;
1383
1384     s += 2;
1385     while (*s && *s==' ') s++;
1386
1387     /* If no parameter, or no '=' sign, return an error */
1388     if (!(*s) || ((p = strchr (s, '=')) == NULL )) {
1389       WCMD_output ("Argument missing\n");
1390       return;
1391     }
1392
1393     /* Output the prompt */
1394     *p++ = '\0';
1395     if (strlen(p) != 0) WCMD_output(p);
1396
1397     /* Read the reply */
1398     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1399     if (count > 1) {
1400       string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
1401       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1402       WINE_TRACE("set /p: Setting var '%s' to '%s'\n", s, string);
1403       status = SetEnvironmentVariable (s, string);
1404     }
1405
1406   } else {
1407     DWORD gle;
1408     p = strchr (s, '=');
1409     if (p == NULL) {
1410       env = GetEnvironmentStrings ();
1411       if (WCMD_setshow_sortenv( env, s ) == 0) {
1412         WCMD_output ("Environment variable %s not defined\n", s);
1413         errorlevel = 1;
1414       }
1415       return;
1416     }
1417     *p++ = '\0';
1418
1419     if (strlen(p) == 0) p = NULL;
1420     status = SetEnvironmentVariable (s, p);
1421     gle = GetLastError();
1422     if ((!status) & (gle == ERROR_ENVVAR_NOT_FOUND)) {
1423       errorlevel = 1;
1424     } else if ((!status)) WCMD_print_error();
1425   }
1426 }
1427
1428 /****************************************************************************
1429  * WCMD_setshow_path
1430  *
1431  * Set/Show the path environment variable
1432  */
1433
1434 void WCMD_setshow_path (char *command) {
1435
1436   char string[1024];
1437   DWORD status;
1438
1439   if (strlen(param1) == 0) {
1440     status = GetEnvironmentVariable ("PATH", string, sizeof(string));
1441     if (status != 0) {
1442       WCMD_output_asis ( "PATH=");
1443       WCMD_output_asis ( string);
1444       WCMD_output_asis ( "\n");
1445     }
1446     else {
1447       WCMD_output ("PATH not found\n");
1448     }
1449   }
1450   else {
1451     if (*command == '=') command++; /* Skip leading '=' */
1452     status = SetEnvironmentVariable ("PATH", command);
1453     if (!status) WCMD_print_error();
1454   }
1455 }
1456
1457 /****************************************************************************
1458  * WCMD_setshow_prompt
1459  *
1460  * Set or show the command prompt.
1461  */
1462
1463 void WCMD_setshow_prompt (void) {
1464
1465   char *s;
1466
1467   if (strlen(param1) == 0) {
1468     SetEnvironmentVariable ("PROMPT", NULL);
1469   }
1470   else {
1471     s = param1;
1472     while ((*s == '=') || (*s == ' ')) s++;
1473     if (strlen(s) == 0) {
1474       SetEnvironmentVariable ("PROMPT", NULL);
1475     }
1476     else SetEnvironmentVariable ("PROMPT", s);
1477   }
1478 }
1479
1480 /****************************************************************************
1481  * WCMD_setshow_time
1482  *
1483  * Set/Show the system time
1484  * FIXME: Can't change time yet
1485  */
1486
1487 void WCMD_setshow_time (void) {
1488
1489   char curtime[64], buffer[64];
1490   DWORD count;
1491   SYSTEMTIME st;
1492
1493   if (strlen(param1) == 0) {
1494     GetLocalTime(&st);
1495     if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1496                 curtime, sizeof(curtime))) {
1497       WCMD_output ("Current Time is %s\n", curtime);
1498       if (strstr (quals, "/T") == NULL) {
1499         WCMD_output ("Enter new time: ", curtime);
1500         ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1501         if (count > 2) {
1502           WCMD_output (nyi);
1503         }
1504       }
1505     }
1506     else WCMD_print_error ();
1507   }
1508   else {
1509     WCMD_output (nyi);
1510   }
1511 }
1512
1513 /****************************************************************************
1514  * WCMD_shift
1515  *
1516  * Shift batch parameters.
1517  * Optional /n says where to start shifting (n=0-8)
1518  */
1519
1520 void WCMD_shift (char *command) {
1521   int start;
1522
1523   if (context != NULL) {
1524     char *pos = strchr(command, '/');
1525     int   i;
1526
1527     if (pos == NULL) {
1528       start = 0;
1529     } else if (*(pos+1)>='0' && *(pos+1)<='8') {
1530       start = (*(pos+1) - '0');
1531     } else {
1532       SetLastError(ERROR_INVALID_PARAMETER);
1533       WCMD_print_error();
1534       return;
1535     }
1536
1537     WINE_TRACE("Shifting variables, starting at %d\n", start);
1538     for (i=start;i<=8;i++) {
1539       context -> shift_count[i] = context -> shift_count[i+1] + 1;
1540     }
1541     context -> shift_count[9] = context -> shift_count[9] + 1;
1542   }
1543
1544 }
1545
1546 /****************************************************************************
1547  * WCMD_title
1548  *
1549  * Set the console title
1550  */
1551 void WCMD_title (char *command) {
1552   SetConsoleTitle(command);
1553 }
1554
1555 /****************************************************************************
1556  * WCMD_type
1557  *
1558  * Copy a file to standard output.
1559  */
1560
1561 void WCMD_type (char *command) {
1562
1563   int   argno         = 0;
1564   char *argN          = command;
1565   BOOL  writeHeaders  = FALSE;
1566
1567   if (param1[0] == 0x00) {
1568     WCMD_output ("Argument missing\n");
1569     return;
1570   }
1571
1572   if (param2[0] != 0x00) writeHeaders = TRUE;
1573
1574   /* Loop through all args */
1575   errorlevel = 0;
1576   while (argN) {
1577     char *thisArg = WCMD_parameter (command, argno++, &argN);
1578
1579     HANDLE h;
1580     char buffer[512];
1581     DWORD count;
1582
1583     if (!argN) break;
1584
1585     WINE_TRACE("type: Processing arg '%s'\n", thisArg);
1586     h = CreateFile (thisArg, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1587                 FILE_ATTRIBUTE_NORMAL, NULL);
1588     if (h == INVALID_HANDLE_VALUE) {
1589       WCMD_print_error ();
1590       WCMD_output ("%s :Failed\n", thisArg);
1591       errorlevel = 1;
1592     } else {
1593       if (writeHeaders) {
1594         WCMD_output("\n%s\n\n", thisArg);
1595       }
1596       while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1597         if (count == 0) break;  /* ReadFile reports success on EOF! */
1598         buffer[count] = 0;
1599         WCMD_output_asis (buffer);
1600       }
1601       CloseHandle (h);
1602     }
1603   }
1604 }
1605
1606 /****************************************************************************
1607  * WCMD_verify
1608  *
1609  * Display verify flag.
1610  * FIXME: We don't actually do anything with the verify flag other than toggle
1611  * it...
1612  */
1613
1614 void WCMD_verify (char *command) {
1615
1616   static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1617   int count;
1618
1619   count = strlen(command);
1620   if (count == 0) {
1621     if (verify_mode) WCMD_output (von);
1622     else WCMD_output (voff);
1623     return;
1624   }
1625   if (lstrcmpi(command, "ON") == 0) {
1626     verify_mode = 1;
1627     return;
1628   }
1629   else if (lstrcmpi(command, "OFF") == 0) {
1630     verify_mode = 0;
1631     return;
1632   }
1633   else WCMD_output ("Verify must be ON or OFF\n");
1634 }
1635
1636 /****************************************************************************
1637  * WCMD_version
1638  *
1639  * Display version info.
1640  */
1641
1642 void WCMD_version (void) {
1643
1644   WCMD_output (version_string);
1645
1646 }
1647
1648 /****************************************************************************
1649  * WCMD_volume
1650  *
1651  * Display volume info and/or set volume label. Returns 0 if error.
1652  */
1653
1654 int WCMD_volume (int mode, char *path) {
1655
1656   DWORD count, serial;
1657   char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1658   BOOL status;
1659
1660   if (lstrlen(path) == 0) {
1661     status = GetCurrentDirectory (sizeof(curdir), curdir);
1662     if (!status) {
1663       WCMD_print_error ();
1664       return 0;
1665     }
1666     status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1667         NULL, NULL, 0);
1668   }
1669   else {
1670     if ((path[1] != ':') || (lstrlen(path) != 2)) {
1671       WCMD_output_asis("Syntax Error\n\n");
1672       return 0;
1673     }
1674     wsprintf (curdir, "%s\\", path);
1675     status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1676         NULL, NULL, 0);
1677   }
1678   if (!status) {
1679     WCMD_print_error ();
1680     return 0;
1681   }
1682   WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1683         curdir[0], label, HIWORD(serial), LOWORD(serial));
1684   if (mode) {
1685     WCMD_output ("Volume label (11 characters, ENTER for none)?");
1686     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1687     if (count > 1) {
1688       string[count-1] = '\0';           /* ReadFile output is not null-terminated! */
1689       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1690     }
1691     if (lstrlen(path) != 0) {
1692       if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1693     }
1694     else {
1695       if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1696     }
1697   }
1698   return 1;
1699 }
1700
1701 /**************************************************************************
1702  * WCMD_exit
1703  *
1704  * Exit either the process, or just this batch program
1705  *
1706  */
1707
1708 void WCMD_exit (void) {
1709
1710     int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1711
1712     if (context && lstrcmpi(quals, "/B") == 0) {
1713         errorlevel = rc;
1714         context -> skip_rest = TRUE;
1715     } else {
1716         ExitProcess(rc);
1717     }
1718 }
1719
1720 /**************************************************************************
1721  * WCMD_ask_confirm
1722  *
1723  * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
1724  * answer.
1725  *
1726  * Returns True if Y answer is selected
1727  *
1728  */
1729 BOOL WCMD_ask_confirm (char *message, BOOL showSureText) {
1730
1731     char  msgbuffer[MAXSTRING];
1732     char  Ybuffer[MAXSTRING];
1733     char  Nbuffer[MAXSTRING];
1734     char  answer[MAX_PATH] = "";
1735     DWORD count = 0;
1736
1737     /* Load the translated 'Are you sure', plus valid answers */
1738     LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer));
1739     LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer));
1740     LoadString (hinst, WCMD_NO, Nbuffer, sizeof(Nbuffer));
1741
1742     /* Loop waiting on a Y or N */
1743     while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
1744       WCMD_output_asis (message);
1745       if (showSureText) {
1746         WCMD_output_asis (msgbuffer);
1747       }
1748       WCMD_output_asis (" (");
1749       WCMD_output_asis (Ybuffer);
1750       WCMD_output_asis ("/");
1751       WCMD_output_asis (Nbuffer);
1752       WCMD_output_asis (")?");
1753       ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer),
1754                 &count, NULL);
1755       answer[0] = toupper(answer[0]);
1756     }
1757
1758     /* Return the answer */
1759     return (answer[0] == Ybuffer[0]);
1760 }
1761
1762 /*****************************************************************************
1763  * WCMD_assoc
1764  *
1765  *      Lists or sets file associations  (assoc = TRUE)
1766  *      Lists or sets file types         (assoc = FALSE)
1767  */
1768 void WCMD_assoc (char *command, BOOL assoc) {
1769
1770     HKEY    key;
1771     DWORD   accessOptions = KEY_READ;
1772     char   *newValue;
1773     LONG    rc = ERROR_SUCCESS;
1774     char    keyValue[MAXSTRING];
1775     DWORD   valueLen = MAXSTRING;
1776     HKEY    readKey;
1777
1778
1779     /* See if parameter includes '=' */
1780     errorlevel = 0;
1781     newValue = strchr(command, '=');
1782     if (newValue) accessOptions |= KEY_WRITE;
1783
1784     /* Open a key to HKEY_CLASSES_ROOT for enumerating */
1785     if (RegOpenKeyEx(HKEY_CLASSES_ROOT, "", 0,
1786                      accessOptions, &key) != ERROR_SUCCESS) {
1787       WINE_FIXME("Unexpected failure opening HKCR key: %d\n", GetLastError());
1788       return;
1789     }
1790
1791     /* If no parameters then list all associations */
1792     if (*command == 0x00) {
1793       int index = 0;
1794
1795       /* Enumerate all the keys */
1796       while (rc != ERROR_NO_MORE_ITEMS) {
1797         char  keyName[MAXSTRING];
1798         DWORD nameLen;
1799
1800         /* Find the next value */
1801         nameLen = MAXSTRING;
1802         rc = RegEnumKeyEx(key, index++,
1803                           keyName, &nameLen,
1804                           NULL, NULL, NULL, NULL);
1805
1806         if (rc == ERROR_SUCCESS) {
1807
1808           /* Only interested in extension ones if assoc, or others
1809              if not assoc                                          */
1810           if ((keyName[0] == '.' && assoc) ||
1811               (!(keyName[0] == '.') && (!assoc)))
1812           {
1813             char subkey[MAXSTRING];
1814             strcpy(subkey, keyName);
1815             if (!assoc) strcat(subkey, "\\Shell\\Open\\Command");
1816
1817             if (RegOpenKeyEx(key, subkey, 0,
1818                              accessOptions, &readKey) == ERROR_SUCCESS) {
1819
1820               valueLen = sizeof(keyValue);
1821               rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1822                                    (LPBYTE)keyValue, &valueLen);
1823               WCMD_output_asis(keyName);
1824               WCMD_output_asis("=");
1825               /* If no default value found, leave line empty after '=' */
1826               if (rc == ERROR_SUCCESS) {
1827                 WCMD_output_asis(keyValue);
1828               }
1829               WCMD_output_asis("\n");
1830             }
1831           }
1832         }
1833       }
1834       RegCloseKey(readKey);
1835
1836     } else {
1837
1838       /* Parameter supplied - if no '=' on command line, its a query */
1839       if (newValue == NULL) {
1840         char *space;
1841         char subkey[MAXSTRING];
1842
1843         /* Query terminates the parameter at the first space */
1844         strcpy(keyValue, command);
1845         space = strchr(keyValue, ' ');
1846         if (space) *space=0x00;
1847
1848         /* Set up key name */
1849         strcpy(subkey, keyValue);
1850         if (!assoc) strcat(subkey, "\\Shell\\Open\\Command");
1851
1852         if (RegOpenKeyEx(key, subkey, 0,
1853                          accessOptions, &readKey) == ERROR_SUCCESS) {
1854
1855           rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1856                                (LPBYTE)keyValue, &valueLen);
1857           WCMD_output_asis(command);
1858           WCMD_output_asis("=");
1859           /* If no default value found, leave line empty after '=' */
1860           if (rc == ERROR_SUCCESS) WCMD_output_asis(keyValue);
1861           WCMD_output_asis("\n");
1862           RegCloseKey(readKey);
1863
1864         } else {
1865           char  msgbuffer[MAXSTRING];
1866           char  outbuffer[MAXSTRING];
1867
1868           /* Load the translated 'File association not found' */
1869           if (assoc) {
1870             LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1871           } else {
1872             LoadString (hinst, WCMD_NOFTYPE, msgbuffer, sizeof(msgbuffer));
1873           }
1874           sprintf(outbuffer, msgbuffer, keyValue);
1875           WCMD_output_asis(outbuffer);
1876           errorlevel = 2;
1877         }
1878
1879       /* Not a query - its a set or clear of a value */
1880       } else {
1881
1882         char subkey[MAXSTRING];
1883
1884         /* Get pointer to new value */
1885         *newValue = 0x00;
1886         newValue++;
1887
1888         /* Set up key name */
1889         strcpy(subkey, command);
1890         if (!assoc) strcat(subkey, "\\Shell\\Open\\Command");
1891
1892         /* If nothing after '=' then clear value - only valid for ASSOC */
1893         if (*newValue == 0x00) {
1894
1895           if (assoc) rc = RegDeleteKey(key, command);
1896           if (assoc && rc == ERROR_SUCCESS) {
1897             WINE_TRACE("HKCR Key '%s' deleted\n", command);
1898
1899           } else if (assoc && rc != ERROR_FILE_NOT_FOUND) {
1900             WCMD_print_error();
1901             errorlevel = 2;
1902
1903           } else {
1904             char  msgbuffer[MAXSTRING];
1905             char  outbuffer[MAXSTRING];
1906
1907             /* Load the translated 'File association not found' */
1908             if (assoc) {
1909               LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1910             } else {
1911               LoadString (hinst, WCMD_NOFTYPE, msgbuffer, sizeof(msgbuffer));
1912             }
1913             sprintf(outbuffer, msgbuffer, keyValue);
1914             WCMD_output_asis(outbuffer);
1915             errorlevel = 2;
1916           }
1917
1918         /* It really is a set value = contents */
1919         } else {
1920           rc = RegCreateKeyEx(key, subkey, 0, NULL, REG_OPTION_NON_VOLATILE,
1921                               accessOptions, NULL, &readKey, NULL);
1922           if (rc == ERROR_SUCCESS) {
1923             rc = RegSetValueEx(readKey, NULL, 0, REG_SZ,
1924                                  (LPBYTE)newValue, strlen(newValue));
1925             RegCloseKey(readKey);
1926           }
1927
1928           if (rc != ERROR_SUCCESS) {
1929             WCMD_print_error();
1930             errorlevel = 2;
1931           } else {
1932             WCMD_output_asis(command);
1933             WCMD_output_asis("=");
1934             WCMD_output_asis(newValue);
1935             WCMD_output_asis("\n");
1936           }
1937         }
1938       }
1939     }
1940
1941     /* Clean up */
1942     RegCloseKey(key);
1943 }
1944
1945 /****************************************************************************
1946  * WCMD_color
1947  *
1948  * Clear the terminal screen.
1949  */
1950
1951 void WCMD_color (void) {
1952
1953   /* Emulate by filling the screen from the top left to bottom right with
1954         spaces, then moving the cursor to the top left afterwards */
1955   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
1956   HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1957
1958   if (param1[0] != 0x00 && strlen(param1) > 2) {
1959     WCMD_output ("Argument invalid\n");
1960     return;
1961   }
1962
1963   if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
1964   {
1965       COORD topLeft;
1966       DWORD screenSize;
1967       DWORD color = 0;
1968
1969       screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
1970
1971       topLeft.X = 0;
1972       topLeft.Y = 0;
1973
1974       /* Convert the color hex digits */
1975       if (param1[0] == 0x00) {
1976         color = defaultColor;
1977       } else {
1978         color = strtoul(param1, NULL, 16);
1979       }
1980
1981       /* Fail if fg == bg color */
1982       if (((color & 0xF0) >> 4) == (color & 0x0F)) {
1983         errorlevel = 1;
1984         return;
1985       }
1986
1987       /* Set the current screen contents and ensure all future writes
1988          remain this color                                             */
1989       FillConsoleOutputAttribute(hStdOut, color, screenSize, topLeft, &screenSize);
1990       SetConsoleTextAttribute(hStdOut, color);
1991   }
1992 }