cmd.exe: setlocal and endlocal should preserve drive and directory.
[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 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     GetCurrentDirectoryW (1024, thisdir);
623     errorlevel = 0;
624     WCMD_setshow_default(command);
625     if (errorlevel) {
626       LocalFree(curdir);
627       LocalFree(thisdir);
628       return;
629     } else {
630       curdir -> next    = pushd_directories;
631       curdir -> strings = thisdir;
632       if (pushd_directories == NULL) {
633         curdir -> stackdepth = 1;
634       } else {
635         curdir -> stackdepth = pushd_directories -> stackdepth + 1;
636       }
637       pushd_directories = curdir;
638     }
639 }
640
641
642 /*****************************************************************************
643  * WCMD_popd
644  *
645  *      Pop a directory from the stack
646  */
647
648 void WCMD_popd (void) {
649     struct env_stack *temp = pushd_directories;
650
651     if (!pushd_directories)
652       return;
653
654     /* pop the old environment from the stack, and make it the current dir */
655     pushd_directories = temp->next;
656     SetCurrentDirectoryW(temp->strings);
657     LocalFree (temp->strings);
658     LocalFree (temp);
659 }
660
661 /****************************************************************************
662  * WCMD_if
663  *
664  * Batch file conditional.
665  * FIXME: Much more syntax checking needed!
666  */
667
668 void WCMD_if (char *p) {
669
670   int negate = 0, test = 0;
671   char condition[MAX_PATH], *command, *s;
672
673   if (!lstrcmpi (param1, "not")) {
674     negate = 1;
675     lstrcpy (condition, param2);
676   }
677   else {
678     lstrcpy (condition, param1);
679   }
680   if (!lstrcmpi (condition, "errorlevel")) {
681     if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
682     WCMD_parameter (p, 2+negate, &command);
683   }
684   else if (!lstrcmpi (condition, "exist")) {
685     if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
686         test = 1;
687     }
688     WCMD_parameter (p, 2+negate, &command);
689   }
690   else if (!lstrcmpi (condition, "defined")) {
691     if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
692         test = 1;
693     }
694     WCMD_parameter (p, 2+negate, &command);
695   }
696   else if ((s = strstr (p, "=="))) {
697     s += 2;
698     if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
699     WCMD_parameter (s, 1, &command);
700   }
701   else {
702     WCMD_output ("Syntax error\n");
703     return;
704   }
705   if (test != negate) {
706     command = strdup (command);
707     WCMD_process_command (command);
708     free (command);
709   }
710 }
711
712 /****************************************************************************
713  * WCMD_move
714  *
715  * Move a file, directory tree or wildcarded set of files.
716  * FIXME: Needs input and output files to be fully specified.
717  */
718
719 void WCMD_move (void) {
720
721   int status;
722   char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
723   WIN32_FIND_DATA fd;
724   HANDLE hff;
725
726   if (param1[0] == 0x00) {
727     WCMD_output ("Argument missing\n");
728     return;
729   }
730
731   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
732     WCMD_output ("Wildcards not yet supported\n");
733     return;
734   }
735
736   /* If no destination supplied, assume current directory */
737   if (param2[0] == 0x00) {
738       strcpy(param2, ".");
739   }
740
741   /* If 2nd parm is directory, then use original filename */
742   GetFullPathName (param2, sizeof(outpath), outpath, NULL);
743   if (outpath[strlen(outpath) - 1] == '\\')
744       outpath[strlen(outpath) - 1] = '\0';
745   hff = FindFirstFile (outpath, &fd);
746   if (hff != INVALID_HANDLE_VALUE) {
747     if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
748       GetFullPathName (param1, sizeof(inpath), inpath, &infile);
749       strcat (outpath, "\\");
750       strcat (outpath, infile);
751     }
752     FindClose (hff);
753   }
754
755   status = MoveFile (param1, outpath);
756   if (!status) WCMD_print_error ();
757 }
758
759 /****************************************************************************
760  * WCMD_pause
761  *
762  * Wait for keyboard input.
763  */
764
765 void WCMD_pause (void) {
766
767   DWORD count;
768   char string[32];
769
770   WCMD_output (anykey);
771   ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
772 }
773
774 /****************************************************************************
775  * WCMD_remove_dir
776  *
777  * Delete a directory.
778  */
779
780 void WCMD_remove_dir (char *command) {
781
782   int   argno         = 0;
783   int   argsProcessed = 0;
784   char *argN          = command;
785
786   /* Loop through all args */
787   while (argN) {
788     char *thisArg = WCMD_parameter (command, argno++, &argN);
789     if (argN && argN[0] != '/') {
790       WINE_TRACE("rd: Processing arg %s (quals:%s)\n", thisArg, quals);
791       argsProcessed++;
792
793       /* If subdirectory search not supplied, just try to remove
794          and report error if it fails (eg if it contains a file) */
795       if (strstr (quals, "/S") == NULL) {
796         if (!RemoveDirectory (thisArg)) WCMD_print_error ();
797
798       /* Otherwise use ShFileOp to recursively remove a directory */
799       } else {
800
801         SHFILEOPSTRUCT lpDir;
802
803         /* Ask first */
804         if (strstr (quals, "/Q") == NULL) {
805           BOOL  ok;
806           char  question[MAXSTRING];
807
808           /* Ask for confirmation */
809           sprintf(question, "%s, ", thisArg);
810           ok = WCMD_ask_confirm(question, TRUE);
811
812           /* Abort if answer is 'N' */
813           if (!ok) return;
814         }
815
816         /* Do the delete */
817         lpDir.hwnd   = NULL;
818         lpDir.pTo    = NULL;
819         lpDir.pFrom  = thisArg;
820         lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
821         lpDir.wFunc  = FO_DELETE;
822         if (SHFileOperationA(&lpDir)) WCMD_print_error ();
823       }
824     }
825   }
826
827   /* Handle no valid args */
828   if (argsProcessed == 0) {
829     WCMD_output ("Argument missing\n");
830     return;
831   }
832
833 }
834
835 /****************************************************************************
836  * WCMD_rename
837  *
838  * Rename a file.
839  * FIXME: Needs input and output files to be fully specified.
840  */
841
842 void WCMD_rename (void) {
843
844   int status;
845
846   if (param1[0] == 0x00 || param2[0] == 0x00) {
847     WCMD_output ("Argument missing\n");
848     return;
849   }
850   if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
851     WCMD_output ("Wildcards not yet supported\n");
852     return;
853   }
854   status = MoveFile (param1, param2);
855   if (!status) WCMD_print_error ();
856 }
857
858 /*****************************************************************************
859  * WCMD_dupenv
860  *
861  * Make a copy of the environment.
862  */
863 static WCHAR *WCMD_dupenv( const WCHAR *env )
864 {
865   WCHAR *env_copy;
866   int len;
867
868   if( !env )
869     return NULL;
870
871   len = 0;
872   while ( env[len] )
873     len += (lstrlenW(&env[len]) + 1);
874
875   env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
876   if (!env_copy)
877   {
878     WCMD_output ("out of memory\n");
879     return env_copy;
880   }
881   memcpy (env_copy, env, len*sizeof (WCHAR));
882   env_copy[len] = 0;
883
884   return env_copy;
885 }
886
887 /*****************************************************************************
888  * WCMD_setlocal
889  *
890  *  setlocal pushes the environment onto a stack
891  *  Save the environment as unicode so we don't screw anything up.
892  */
893 void WCMD_setlocal (const char *s) {
894   WCHAR *env;
895   struct env_stack *env_copy;
896   char cwd[MAX_PATH];
897
898   /* DISABLEEXTENSIONS ignored */
899
900   env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
901   if( !env_copy )
902   {
903     WCMD_output ("out of memory\n");
904     return;
905   }
906
907   env = GetEnvironmentStringsW ();
908
909   env_copy->strings = WCMD_dupenv (env);
910   if (env_copy->strings)
911   {
912     env_copy->next = saved_environment;
913     saved_environment = env_copy;
914
915     /* Save the current drive letter */
916     GetCurrentDirectory (MAX_PATH, cwd);
917     env_copy->cwd = cwd[0];
918   }
919   else
920     LocalFree (env_copy);
921
922   FreeEnvironmentStringsW (env);
923
924 }
925
926 /*****************************************************************************
927  * WCMD_strchrW
928  */
929 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
930 {
931    while(*str)
932    {
933      if(*str == ch)
934        return str;
935      str++;
936    }
937    return NULL;
938 }
939
940 /*****************************************************************************
941  * WCMD_endlocal
942  *
943  *  endlocal pops the environment off a stack
944  *  Note: When searching for '=', search from char position 1, to handle
945  *        special internal environment variables =C:, =D: etc
946  */
947 void WCMD_endlocal (void) {
948   WCHAR *env, *old, *p;
949   struct env_stack *temp;
950   int len, n;
951
952   if (!saved_environment)
953     return;
954
955   /* pop the old environment from the stack */
956   temp = saved_environment;
957   saved_environment = temp->next;
958
959   /* delete the current environment, totally */
960   env = GetEnvironmentStringsW ();
961   old = WCMD_dupenv (GetEnvironmentStringsW ());
962   len = 0;
963   while (old[len]) {
964     n = lstrlenW(&old[len]) + 1;
965     p = WCMD_strchrW(&old[len] + 1, '=');
966     if (p)
967     {
968       *p++ = 0;
969       SetEnvironmentVariableW (&old[len], NULL);
970     }
971     len += n;
972   }
973   LocalFree (old);
974   FreeEnvironmentStringsW (env);
975
976   /* restore old environment */
977   env = temp->strings;
978   len = 0;
979   while (env[len]) {
980     n = lstrlenW(&env[len]) + 1;
981     p = WCMD_strchrW(&env[len] + 1, '=');
982     if (p)
983     {
984       *p++ = 0;
985       SetEnvironmentVariableW (&env[len], p);
986     }
987     len += n;
988   }
989
990   /* Restore current drive letter */
991   if (IsCharAlpha(temp->cwd)) {
992     char envvar[4];
993     char cwd[MAX_PATH];
994     sprintf(envvar, "=%c:", temp->cwd);
995     if (GetEnvironmentVariable(envvar, cwd, MAX_PATH)) {
996       WINE_TRACE("Resetting cwd to %s\n", cwd);
997       SetCurrentDirectory(cwd);
998     }
999   }
1000
1001   LocalFree (env);
1002   LocalFree (temp);
1003 }
1004
1005 /*****************************************************************************
1006  * WCMD_setshow_attrib
1007  *
1008  * Display and optionally sets DOS attributes on a file or directory
1009  *
1010  * FIXME: Wine currently uses the Unix stat() function to get file attributes.
1011  * As a result only the Readonly flag is correctly reported, the Archive bit
1012  * is always set and the rest are not implemented. We do the Right Thing anyway.
1013  *
1014  * FIXME: No SET functionality.
1015  *
1016  */
1017
1018 void WCMD_setshow_attrib (void) {
1019
1020   DWORD count;
1021   HANDLE hff;
1022   WIN32_FIND_DATA fd;
1023   char flags[9] = {"        "};
1024
1025   if (param1[0] == '-') {
1026     WCMD_output (nyi);
1027     return;
1028   }
1029
1030   if (lstrlen(param1) == 0) {
1031     GetCurrentDirectory (sizeof(param1), param1);
1032     strcat (param1, "\\*");
1033   }
1034
1035   hff = FindFirstFile (param1, &fd);
1036   if (hff == INVALID_HANDLE_VALUE) {
1037     WCMD_output ("%s: File Not Found\n",param1);
1038   }
1039   else {
1040     do {
1041       if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1042         if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
1043           flags[0] = 'H';
1044         }
1045         if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
1046           flags[1] = 'S';
1047         }
1048         if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
1049           flags[2] = 'A';
1050         }
1051         if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
1052           flags[3] = 'R';
1053         }
1054         if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
1055           flags[4] = 'T';
1056         }
1057         if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
1058           flags[5] = 'C';
1059         }
1060         WCMD_output ("%s   %s\n", flags, fd.cFileName);
1061         for (count=0; count < 8; count++) flags[count] = ' ';
1062       }
1063     } while (FindNextFile(hff, &fd) != 0);
1064   }
1065   FindClose (hff);
1066 }
1067
1068 /*****************************************************************************
1069  * WCMD_setshow_default
1070  *
1071  *      Set/Show the current default directory
1072  */
1073
1074 void WCMD_setshow_default (char *command) {
1075
1076   BOOL status;
1077   char string[1024];
1078   char *pos;
1079   WIN32_FIND_DATA fd;
1080   HANDLE hff;
1081
1082   WINE_TRACE("Request change to directory '%s'\n", command);
1083   if (strlen(command) == 0) {
1084     GetCurrentDirectory (sizeof(string), string);
1085     strcat (string, "\n");
1086     WCMD_output (string);
1087   }
1088   else {
1089     /* Remove any double quotes, which may be in the
1090        middle, eg. cd "C:\Program Files"\Microsoft is ok */
1091     pos = string;
1092     while (*command) {
1093       if (*command != '"') *pos++ = *command;
1094       command++;
1095     }
1096     *pos = 0x00;
1097
1098     /* Search for approprate directory */
1099     WINE_TRACE("Looking for directory '%s'\n", string);
1100     hff = FindFirstFile (string, &fd);
1101     while (hff != INVALID_HANDLE_VALUE) {
1102       if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1103         char fpath[MAX_PATH];
1104         char drive[10];
1105         char dir[MAX_PATH];
1106         char fname[MAX_PATH];
1107         char ext[MAX_PATH];
1108
1109         /* Convert path into actual directory spec */
1110         GetFullPathName (string, sizeof(fpath), fpath, NULL);
1111         WCMD_splitpath(fpath, drive, dir, fname, ext);
1112
1113         /* Rebuild path */
1114         sprintf(string, "%s%s%s", drive, dir, fd.cFileName);
1115
1116         FindClose(hff);
1117         hff = INVALID_HANDLE_VALUE;
1118         break;
1119       }
1120
1121       /* Step on to next match */
1122       if (FindNextFile(hff, &fd) == 0) {
1123         FindClose(hff);
1124         hff = INVALID_HANDLE_VALUE;
1125         break;
1126       }
1127     }
1128
1129     /* Change to that directory */
1130     WINE_TRACE("Really changing to directory '%s'\n", string);
1131
1132     status = SetCurrentDirectory (string);
1133     if (!status) {
1134       errorlevel = 1;
1135       WCMD_print_error ();
1136       return;
1137     }
1138
1139     /* Set special =C: type environment variable */
1140     if ((string[1] == ':') && IsCharAlpha (string[0])) {
1141       char env[4];
1142       strcpy(env, "=");
1143       strncpy(env+1, string, 2);
1144       env[3] = 0x00;
1145       SetEnvironmentVariable(env, string);
1146     }
1147
1148    }
1149   return;
1150 }
1151
1152 /****************************************************************************
1153  * WCMD_setshow_date
1154  *
1155  * Set/Show the system date
1156  * FIXME: Can't change date yet
1157  */
1158
1159 void WCMD_setshow_date (void) {
1160
1161   char curdate[64], buffer[64];
1162   DWORD count;
1163
1164   if (lstrlen(param1) == 0) {
1165     if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1166                 curdate, sizeof(curdate))) {
1167       WCMD_output ("Current Date is %s\n", curdate);
1168       if (strstr (quals, "/T") == NULL) {
1169         WCMD_output("Enter new date: ");
1170         ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1171         if (count > 2) {
1172           WCMD_output (nyi);
1173         }
1174       }
1175     }
1176     else WCMD_print_error ();
1177   }
1178   else {
1179     WCMD_output (nyi);
1180   }
1181 }
1182
1183 /****************************************************************************
1184  * WCMD_compare
1185  */
1186 static int WCMD_compare( const void *a, const void *b )
1187 {
1188     int r;
1189     const char * const *str_a = a, * const *str_b = b;
1190     r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1191           *str_a, -1, *str_b, -1 );
1192     if( r == CSTR_LESS_THAN ) return -1;
1193     if( r == CSTR_GREATER_THAN ) return 1;
1194     return 0;
1195 }
1196
1197 /****************************************************************************
1198  * WCMD_setshow_sortenv
1199  *
1200  * sort variables into order for display
1201  * Optionally only display those who start with a stub
1202  * returns the count displayed
1203  */
1204 static int WCMD_setshow_sortenv(const char *s, const char *stub)
1205 {
1206   UINT count=0, len=0, i, displayedcount=0, stublen=0;
1207   const char **str;
1208
1209   if (stub) stublen = strlen(stub);
1210
1211   /* count the number of strings, and the total length */
1212   while ( s[len] ) {
1213     len += (lstrlen(&s[len]) + 1);
1214     count++;
1215   }
1216
1217   /* add the strings to an array */
1218   str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
1219   if( !str )
1220     return 0;
1221   str[0] = s;
1222   for( i=1; i<count; i++ )
1223     str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
1224
1225   /* sort the array */
1226   qsort( str, count, sizeof (char*), WCMD_compare );
1227
1228   /* print it */
1229   for( i=0; i<count; i++ ) {
1230     if (!stub || CompareString (LOCALE_USER_DEFAULT,
1231                                 NORM_IGNORECASE | SORT_STRINGSORT,
1232                                 str[i], stublen, stub, -1) == 2) {
1233       /* Don't display special internal variables */
1234       if (str[i][0] != '=') {
1235         WCMD_output_asis(str[i]);
1236         WCMD_output_asis("\n");
1237         displayedcount++;
1238       }
1239     }
1240   }
1241
1242   LocalFree( str );
1243   return displayedcount;
1244 }
1245
1246 /****************************************************************************
1247  * WCMD_setshow_env
1248  *
1249  * Set/Show the environment variables
1250  */
1251
1252 void WCMD_setshow_env (char *s) {
1253
1254   LPVOID env;
1255   char *p;
1256   int status;
1257
1258   if (strlen(param1) == 0) {
1259     env = GetEnvironmentStrings ();
1260     WCMD_setshow_sortenv( env, NULL );
1261   }
1262   else {
1263     p = strchr (s, '=');
1264     if (p == NULL) {
1265       env = GetEnvironmentStrings ();
1266       if (WCMD_setshow_sortenv( env, s ) == 0) {
1267         WCMD_output ("Environment variable %s not defined\n", s);
1268       }
1269       return;
1270     }
1271     *p++ = '\0';
1272
1273     if (strlen(p) == 0) p = NULL;
1274     status = SetEnvironmentVariable (s, p);
1275     if ((!status) & (GetLastError() != ERROR_ENVVAR_NOT_FOUND)) WCMD_print_error();
1276   }
1277 }
1278
1279 /****************************************************************************
1280  * WCMD_setshow_path
1281  *
1282  * Set/Show the path environment variable
1283  */
1284
1285 void WCMD_setshow_path (char *command) {
1286
1287   char string[1024];
1288   DWORD status;
1289
1290   if (strlen(param1) == 0) {
1291     status = GetEnvironmentVariable ("PATH", string, sizeof(string));
1292     if (status != 0) {
1293       WCMD_output_asis ( "PATH=");
1294       WCMD_output_asis ( string);
1295       WCMD_output_asis ( "\n");
1296     }
1297     else {
1298       WCMD_output ("PATH not found\n");
1299     }
1300   }
1301   else {
1302     if (*command == '=') command++; /* Skip leading '=' */
1303     status = SetEnvironmentVariable ("PATH", command);
1304     if (!status) WCMD_print_error();
1305   }
1306 }
1307
1308 /****************************************************************************
1309  * WCMD_setshow_prompt
1310  *
1311  * Set or show the command prompt.
1312  */
1313
1314 void WCMD_setshow_prompt (void) {
1315
1316   char *s;
1317
1318   if (strlen(param1) == 0) {
1319     SetEnvironmentVariable ("PROMPT", NULL);
1320   }
1321   else {
1322     s = param1;
1323     while ((*s == '=') || (*s == ' ')) s++;
1324     if (strlen(s) == 0) {
1325       SetEnvironmentVariable ("PROMPT", NULL);
1326     }
1327     else SetEnvironmentVariable ("PROMPT", s);
1328   }
1329 }
1330
1331 /****************************************************************************
1332  * WCMD_setshow_time
1333  *
1334  * Set/Show the system time
1335  * FIXME: Can't change time yet
1336  */
1337
1338 void WCMD_setshow_time (void) {
1339
1340   char curtime[64], buffer[64];
1341   DWORD count;
1342   SYSTEMTIME st;
1343
1344   if (strlen(param1) == 0) {
1345     GetLocalTime(&st);
1346     if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1347                 curtime, sizeof(curtime))) {
1348       WCMD_output ("Current Time is %s\n", curtime);
1349       if (strstr (quals, "/T") == NULL) {
1350         WCMD_output ("Enter new time: ", curtime);
1351         ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1352         if (count > 2) {
1353           WCMD_output (nyi);
1354         }
1355       }
1356     }
1357     else WCMD_print_error ();
1358   }
1359   else {
1360     WCMD_output (nyi);
1361   }
1362 }
1363
1364 /****************************************************************************
1365  * WCMD_shift
1366  *
1367  * Shift batch parameters.
1368  */
1369
1370 void WCMD_shift (void) {
1371
1372   if (context != NULL) context -> shift_count++;
1373
1374 }
1375
1376 /****************************************************************************
1377  * WCMD_title
1378  *
1379  * Set the console title
1380  */
1381 void WCMD_title (char *command) {
1382   SetConsoleTitle(command);
1383 }
1384
1385 /****************************************************************************
1386  * WCMD_type
1387  *
1388  * Copy a file to standard output.
1389  */
1390
1391 void WCMD_type (void) {
1392
1393   HANDLE h;
1394   char buffer[512];
1395   DWORD count;
1396
1397   if (param1[0] == 0x00) {
1398     WCMD_output ("Argument missing\n");
1399     return;
1400   }
1401   h = CreateFile (param1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1402                 FILE_ATTRIBUTE_NORMAL, NULL);
1403   if (h == INVALID_HANDLE_VALUE) {
1404     WCMD_print_error ();
1405     return;
1406   }
1407   while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1408     if (count == 0) break;      /* ReadFile reports success on EOF! */
1409     buffer[count] = 0;
1410     WCMD_output_asis (buffer);
1411   }
1412   CloseHandle (h);
1413 }
1414
1415 /****************************************************************************
1416  * WCMD_verify
1417  *
1418  * Display verify flag.
1419  * FIXME: We don't actually do anything with the verify flag other than toggle
1420  * it...
1421  */
1422
1423 void WCMD_verify (char *command) {
1424
1425   static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1426   int count;
1427
1428   count = strlen(command);
1429   if (count == 0) {
1430     if (verify_mode) WCMD_output (von);
1431     else WCMD_output (voff);
1432     return;
1433   }
1434   if (lstrcmpi(command, "ON") == 0) {
1435     verify_mode = 1;
1436     return;
1437   }
1438   else if (lstrcmpi(command, "OFF") == 0) {
1439     verify_mode = 0;
1440     return;
1441   }
1442   else WCMD_output ("Verify must be ON or OFF\n");
1443 }
1444
1445 /****************************************************************************
1446  * WCMD_version
1447  *
1448  * Display version info.
1449  */
1450
1451 void WCMD_version (void) {
1452
1453   WCMD_output (version_string);
1454
1455 }
1456
1457 /****************************************************************************
1458  * WCMD_volume
1459  *
1460  * Display volume info and/or set volume label. Returns 0 if error.
1461  */
1462
1463 int WCMD_volume (int mode, char *path) {
1464
1465   DWORD count, serial;
1466   char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1467   BOOL status;
1468
1469   if (lstrlen(path) == 0) {
1470     status = GetCurrentDirectory (sizeof(curdir), curdir);
1471     if (!status) {
1472       WCMD_print_error ();
1473       return 0;
1474     }
1475     status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1476         NULL, NULL, 0);
1477   }
1478   else {
1479     if ((path[1] != ':') || (lstrlen(path) != 2)) {
1480       WCMD_output_asis("Syntax Error\n\n");
1481       return 0;
1482     }
1483     wsprintf (curdir, "%s\\", path);
1484     status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1485         NULL, NULL, 0);
1486   }
1487   if (!status) {
1488     WCMD_print_error ();
1489     return 0;
1490   }
1491   WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1492         curdir[0], label, HIWORD(serial), LOWORD(serial));
1493   if (mode) {
1494     WCMD_output ("Volume label (11 characters, ENTER for none)?");
1495     ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1496     if (count > 1) {
1497       string[count-1] = '\0';           /* ReadFile output is not null-terminated! */
1498       if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1499     }
1500     if (lstrlen(path) != 0) {
1501       if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1502     }
1503     else {
1504       if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1505     }
1506   }
1507   return 1;
1508 }
1509
1510 /**************************************************************************
1511  * WCMD_exit
1512  *
1513  * Exit either the process, or just this batch program
1514  *
1515  */
1516
1517 void WCMD_exit (void) {
1518
1519     int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1520
1521     if (context && lstrcmpi(quals, "/B") == 0) {
1522         errorlevel = rc;
1523         context -> skip_rest = TRUE;
1524     } else {
1525         ExitProcess(rc);
1526     }
1527 }
1528
1529 /**************************************************************************
1530  * WCMD_ask_confirm
1531  *
1532  * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
1533  * answer.
1534  *
1535  * Returns True if Y answer is selected
1536  *
1537  */
1538 BOOL WCMD_ask_confirm (char *message, BOOL showSureText) {
1539
1540     char  msgbuffer[MAXSTRING];
1541     char  Ybuffer[MAXSTRING];
1542     char  Nbuffer[MAXSTRING];
1543     char  answer[MAX_PATH] = "";
1544     DWORD count = 0;
1545
1546     /* Load the translated 'Are you sure', plus valid answers */
1547     LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer));
1548     LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer));
1549     LoadString (hinst, WCMD_NO, Nbuffer, sizeof(Nbuffer));
1550
1551     /* Loop waiting on a Y or N */
1552     while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
1553       WCMD_output_asis (message);
1554       if (showSureText) {
1555         WCMD_output_asis (msgbuffer);
1556       }
1557       WCMD_output_asis (" (");
1558       WCMD_output_asis (Ybuffer);
1559       WCMD_output_asis ("/");
1560       WCMD_output_asis (Nbuffer);
1561       WCMD_output_asis (")?");
1562       ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer),
1563                 &count, NULL);
1564       answer[0] = toupper(answer[0]);
1565     }
1566
1567     /* Return the answer */
1568     return (answer[0] == Ybuffer[0]);
1569 }
1570
1571 /*****************************************************************************
1572  * WCMD_assoc
1573  *
1574  *      Lists or sets file associations
1575  */
1576 void WCMD_assoc (char *command) {
1577
1578     HKEY    key;
1579     DWORD   accessOptions = KEY_READ;
1580     char   *newValue;
1581     LONG    rc = ERROR_SUCCESS;
1582     char    keyValue[MAXSTRING];
1583     DWORD   valueLen = MAXSTRING;
1584     HKEY    readKey;
1585
1586
1587     /* See if parameter includes '=' */
1588     errorlevel = 0;
1589     newValue = strchr(command, '=');
1590     if (newValue) accessOptions |= KEY_WRITE;
1591
1592     /* Open a key to HKEY_CLASSES_ROOT for enumerating */
1593     if (RegOpenKeyEx(HKEY_CLASSES_ROOT, "", 0,
1594                      accessOptions, &key) != ERROR_SUCCESS) {
1595       WINE_FIXME("Unexpected failure opening HKCR key: %d\n", GetLastError());
1596       return;
1597     }
1598
1599     /* If no parameters then list all associations */
1600     if (*command == 0x00) {
1601       int index = 0;
1602
1603       /* Enumerate all the keys */
1604       while (rc != ERROR_NO_MORE_ITEMS) {
1605         char  keyName[MAXSTRING];
1606         DWORD nameLen;
1607
1608         /* Find the next value */
1609         nameLen = MAXSTRING;
1610         rc = RegEnumKeyEx(key, index++,
1611                           keyName, &nameLen,
1612                           NULL, NULL, NULL, NULL);
1613
1614         if (rc == ERROR_SUCCESS) {
1615
1616           /* Only interested in extension ones */
1617           if (keyName[0] == '.') {
1618
1619             if (RegOpenKeyEx(key, keyName, 0,
1620                              accessOptions, &readKey) == ERROR_SUCCESS) {
1621
1622               rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1623                                    (LPBYTE)keyValue, &valueLen);
1624               WCMD_output_asis(keyName);
1625               WCMD_output_asis("=");
1626               /* If no default value found, leave line empty after '=' */
1627               if (rc == ERROR_SUCCESS) {
1628                 WCMD_output_asis(keyValue);
1629               }
1630               WCMD_output_asis("\n");
1631             }
1632           }
1633         }
1634       }
1635       RegCloseKey(readKey);
1636
1637     } else {
1638
1639       /* Parameter supplied - if no '=' on command line, its a query */
1640       if (newValue == NULL) {
1641         char *space;
1642
1643         /* Query terminates the parameter at the first space */
1644         strcpy(keyValue, command);
1645         space = strchr(keyValue, ' ');
1646         if (space) *space=0x00;
1647
1648         if (RegOpenKeyEx(key, keyValue, 0,
1649                          accessOptions, &readKey) == ERROR_SUCCESS) {
1650
1651           rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1652                                (LPBYTE)keyValue, &valueLen);
1653           WCMD_output_asis(command);
1654           WCMD_output_asis("=");
1655           /* If no default value found, leave line empty after '=' */
1656           if (rc == ERROR_SUCCESS) WCMD_output_asis(keyValue);
1657           WCMD_output_asis("\n");
1658           RegCloseKey(readKey);
1659
1660         } else {
1661           char  msgbuffer[MAXSTRING];
1662           char  outbuffer[MAXSTRING];
1663
1664           /* Load the translated 'File association not found' */
1665           LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1666           sprintf(outbuffer, msgbuffer, keyValue);
1667           WCMD_output_asis(outbuffer);
1668           errorlevel = 2;
1669         }
1670
1671       /* Not a query - its a set or clear of a value */
1672       } else {
1673
1674         /* Get pointer to new value */
1675         *newValue = 0x00;
1676         newValue++;
1677
1678         /* If nothing after '=' then clear value */
1679         if (*newValue == 0x00) {
1680
1681           rc = RegDeleteKey(key, command);
1682           if (rc == ERROR_SUCCESS) {
1683             WINE_TRACE("HKCR Key '%s' deleted\n", command);
1684
1685           } else if (rc != ERROR_FILE_NOT_FOUND) {
1686             WCMD_print_error();
1687             errorlevel = 2;
1688
1689           } else {
1690             char  msgbuffer[MAXSTRING];
1691             char  outbuffer[MAXSTRING];
1692
1693             /* Load the translated 'File association not found' */
1694             LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1695             sprintf(outbuffer, msgbuffer, keyValue);
1696             WCMD_output_asis(outbuffer);
1697             errorlevel = 2;
1698           }
1699
1700         /* It really is a set value = contents */
1701         } else {
1702           rc = RegCreateKeyEx(key, command, 0, NULL, REG_OPTION_NON_VOLATILE,
1703                               accessOptions, NULL, &readKey, NULL);
1704           if (rc == ERROR_SUCCESS) {
1705             rc = RegSetValueEx(readKey, NULL, 0, REG_SZ,
1706                                  (LPBYTE)newValue, strlen(newValue));
1707             RegCloseKey(readKey);
1708           }
1709
1710           if (rc != ERROR_SUCCESS) {
1711             WCMD_print_error();
1712             errorlevel = 2;
1713           } else {
1714             WCMD_output_asis(command);
1715             WCMD_output_asis("=");
1716             WCMD_output_asis(newValue);
1717             WCMD_output_asis("\n");
1718           }
1719         }
1720       }
1721     }
1722
1723     /* Clean up */
1724     RegCloseKey(key);
1725 }
1726
1727 /****************************************************************************
1728  * WCMD_color
1729  *
1730  * Clear the terminal screen.
1731  */
1732
1733 void WCMD_color (void) {
1734
1735   /* Emulate by filling the screen from the top left to bottom right with
1736         spaces, then moving the cursor to the top left afterwards */
1737   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
1738   HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1739
1740   if (param1[0] != 0x00 && strlen(param1) > 2) {
1741     WCMD_output ("Argument invalid\n");
1742     return;
1743   }
1744
1745   if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
1746   {
1747       COORD topLeft;
1748       DWORD screenSize;
1749       DWORD color = 0;
1750
1751       screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
1752
1753       topLeft.X = 0;
1754       topLeft.Y = 0;
1755
1756       /* Convert the color hex digits */
1757       if (param1[0] == 0x00) {
1758         color = defaultColor;
1759       } else {
1760         color = strtoul(param1, NULL, 16);
1761       }
1762
1763       /* Fail if fg == bg color */
1764       if (((color & 0xF0) >> 4) == (color & 0x0F)) {
1765         errorlevel = 1;
1766         return;
1767       }
1768
1769       /* Set the current screen contents and ensure all future writes
1770          remain this color                                             */
1771       FillConsoleOutputAttribute(hStdOut, color, screenSize, topLeft, &screenSize);
1772       SetConsoleTextAttribute(hStdOut, color);
1773   }
1774 }