cmd: Avoid checking whether we're in console mode for every read.
[wine] / programs / cmd / batch.c
1 /*
2  * CMD - Wine-compatible command line interface - batch interface.
3  *
4  * Copyright (C) 1999 D A Pickles
5  * Copyright (C) 2007 J Edmeades
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "wcmd.h"
23 #include "wine/debug.h"
24
25 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
26
27 extern WCHAR quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
28 extern BATCH_CONTEXT *context;
29 extern DWORD errorlevel;
30
31 /****************************************************************************
32  * WCMD_batch
33  *
34  * Open and execute a batch file.
35  * On entry *command includes the complete command line beginning with the name
36  * of the batch file (if a CALL command was entered the CALL has been removed).
37  * *file is the name of the file, which might not exist and may not have the
38  * .BAT suffix on. Called is 1 for a CALL, 0 otherwise.
39  *
40  * We need to handle recursion correctly, since one batch program might call another.
41  * So parameters for this batch file are held in a BATCH_CONTEXT structure.
42  *
43  * To support call within the same batch program, another input parameter is
44  * a label to goto once opened.
45  */
46
47 void WCMD_batch (WCHAR *file, WCHAR *command, int called, WCHAR *startLabel, HANDLE pgmHandle) {
48
49   HANDLE h = INVALID_HANDLE_VALUE;
50   BATCH_CONTEXT *prev_context;
51
52   if (startLabel == NULL) {
53     h = CreateFileW (file, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
54                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
55     if (h == INVALID_HANDLE_VALUE) {
56       SetLastError (ERROR_FILE_NOT_FOUND);
57       WCMD_print_error ();
58       return;
59     }
60   } else {
61     DuplicateHandle(GetCurrentProcess(), pgmHandle,
62                     GetCurrentProcess(), &h,
63                     0, FALSE, DUPLICATE_SAME_ACCESS);
64   }
65
66 /*
67  *      Create a context structure for this batch file.
68  */
69
70   prev_context = context;
71   context = LocalAlloc (LMEM_FIXED, sizeof (BATCH_CONTEXT));
72   context -> h = h;
73   context->batchfileW = WCMD_strdupW(file);
74   context -> command = command;
75   memset(context -> shift_count, 0x00, sizeof(context -> shift_count));
76   context -> prev_context = prev_context;
77   context -> skip_rest = FALSE;
78
79   /* If processing a call :label, 'goto' the label in question */
80   if (startLabel) {
81     strcpyW(param1, startLabel);
82     WCMD_goto(NULL);
83   }
84
85 /*
86  *      Work through the file line by line. Specific batch commands are processed here,
87  *      the rest are handled by the main command processor.
88  */
89
90   while (context -> skip_rest == FALSE) {
91       CMD_LIST *toExecute = NULL;         /* Commands left to be executed */
92       if (!WCMD_ReadAndParseLine(NULL, &toExecute, h, FALSE))
93         break;
94       WCMD_process_commands(toExecute, FALSE, NULL, NULL);
95       WCMD_free_commands(toExecute);
96       toExecute = NULL;
97   }
98   CloseHandle (h);
99
100 /*
101  *      If invoked by a CALL, we return to the context of our caller. Otherwise return
102  *      to the caller's caller.
103  */
104
105   HeapFree(GetProcessHeap(), 0, context->batchfileW);
106   LocalFree (context);
107   if ((prev_context != NULL) && (!called)) {
108     prev_context -> skip_rest = TRUE;
109     context = prev_context;
110   }
111   context = prev_context;
112 }
113
114 /*******************************************************************
115  * WCMD_parameter
116  *
117  * Extracts a delimited parameter from an input string
118  *
119  * PARAMS
120  *  s     [I] input string, non NULL
121  *  n     [I] # of the (possibly double quotes-delimited) parameter to return
122  *            Starts at 0
123  *  where [O] if non NULL, pointer to the start of the nth parameter in s,
124  *            potentially a " character
125  *  end   [O] if non NULL, pointer to the last char of
126  *            the nth parameter in s, potentially a " character
127  *
128  * RETURNS
129  *  Success: Returns the nth delimited parameter found in s.
130  *           *where points to the start of the param, possibly a starting
131  *           double quotes character
132  *  Failure: Returns an empty string if the param is not found.
133  *           *where is set to NULL
134  *
135  * NOTES
136  *  Return value is stored in static storage, hence is overwritten
137  *  after each call.
138  *  Doesn't include any potentially delimiting double quotes
139  */
140 WCHAR *WCMD_parameter (WCHAR *s, int n, WCHAR **where, WCHAR **end) {
141     int curParamNb = 0;
142     static WCHAR param[MAX_PATH];
143     WCHAR *p = s, *q;
144     BOOL quotesDelimited;
145
146     if (where != NULL) *where = NULL;
147     if (end != NULL) *end = NULL;
148     param[0] = '\0';
149     while (TRUE) {
150         while (*p && ((*p == ' ') || (*p == ',') || (*p == '=') || (*p == '\t')))
151             p++;
152         if (*p == '\0') return param;
153
154         quotesDelimited = (*p == '"');
155         if (where != NULL && curParamNb == n) *where = p;
156
157         if (quotesDelimited) {
158             q = ++p;
159             while (*p && *p != '"') p++;
160         } else {
161             q = p;
162             while (*p && (*p != ' ') && (*p != ',') && (*p != '=') && (*p != '\t'))
163                 p++;
164         }
165         if (curParamNb == n) {
166             memcpy(param, q, (p - q) * sizeof(WCHAR));
167             param[p-q] = '\0';
168             if (end) *end = p - 1 + quotesDelimited;
169             return param;
170         }
171         if (quotesDelimited && *p == '"') p++;
172         curParamNb++;
173     }
174 }
175
176 /****************************************************************************
177  * WCMD_fgets
178  *
179  * Get one line from a batch file/console. We can't use the native f* functions because
180  * of the filename syntax differences between DOS and Unix. Also need to lose
181  * the LF (or CRLF) from the line.
182  */
183
184 WCHAR *WCMD_fgets(WCHAR *s, int noChars, HANDLE h, BOOL is_console_handle)
185 {
186   DWORD bytes, charsRead;
187   BOOL status;
188   WCHAR *p;
189
190   p = s;
191   if (is_console_handle) {
192     status = ReadConsoleW(h, s, noChars, &charsRead, NULL);
193     if (!status) return NULL;
194     s[charsRead-2] = '\0'; /* Strip \r\n */
195     return p;
196   }
197
198   /* TODO: More intelligent buffering for reading lines from files */
199   do {
200     status = WCMD_ReadFile (h, s, 1, &bytes, NULL);
201     if ((status == 0) || ((bytes == 0) && (s == p))) return NULL;
202     if (*s == '\n') bytes = 0;
203     else if (*s != '\r') {
204       s++;
205       noChars--;
206     }
207     *s = '\0';
208   } while ((bytes == 1) && (noChars > 1));
209   return p;
210 }
211
212 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
213 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
214 {
215         const WCHAR* end; /* end of processed string */
216         const WCHAR* p;  /* search pointer */
217         const WCHAR* s;  /* copy pointer */
218
219         /* extract drive name */
220         if (path[0] && path[1]==':') {
221                 if (drv) {
222                         *drv++ = *path++;
223                         *drv++ = *path++;
224                         *drv = '\0';
225                 }
226         } else if (drv)
227                 *drv = '\0';
228
229         end = path + strlenW(path);
230
231         /* search for begin of file extension */
232         for(p=end; p>path && *--p!='\\' && *p!='/'; )
233                 if (*p == '.') {
234                         end = p;
235                         break;
236                 }
237
238         if (ext)
239                 for(s=end; (*ext=*s++); )
240                         ext++;
241
242         /* search for end of directory name */
243         for(p=end; p>path; )
244                 if (*--p=='\\' || *p=='/') {
245                         p++;
246                         break;
247                 }
248
249         if (name) {
250                 for(s=p; s<end; )
251                         *name++ = *s++;
252
253                 *name = '\0';
254         }
255
256         if (dir) {
257                 for(s=path; s<p; )
258                         *dir++ = *s++;
259
260                 *dir = '\0';
261         }
262 }
263
264 /****************************************************************************
265  * WCMD_HandleTildaModifiers
266  *
267  * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
268  *    %~xxxxxV  (V=0-9 or A-Z)
269  * Where xxxx is any combination of:
270  *    ~ - Removes quotes
271  *    f - Fully qualified path (assumes current dir if not drive\dir)
272  *    d - drive letter
273  *    p - path
274  *    n - filename
275  *    x - file extension
276  *    s - path with shortnames
277  *    a - attributes
278  *    t - date/time
279  *    z - size
280  *    $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
281  *                   qualified path
282  *
283  *  To work out the length of the modifier:
284  *
285  *  Note: In the case of %0-9 knowing the end of the modifier is easy,
286  *    but in a for loop, the for end WCHARacter may also be a modifier
287  *    eg. for %a in (c:\a.a) do echo XXX
288  *             where XXX = %~a    (just ~)
289  *                         %~aa   (~ and attributes)
290  *                         %~aaxa (~, attributes and extension)
291  *                   BUT   %~aax  (~ and attributes followed by 'x')
292  *
293  *  Hence search forwards until find an invalid modifier, and then
294  *  backwards until find for variable or 0-9
295  */
296 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
297                                const WCHAR *forValue, BOOL justFors) {
298
299 #define NUMMODIFIERS 11
300   static const WCHAR validmodifiers[NUMMODIFIERS] = {
301         '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
302   };
303   static const WCHAR space[] = {' ', '\0'};
304
305   WIN32_FILE_ATTRIBUTE_DATA fileInfo;
306   WCHAR  outputparam[MAX_PATH];
307   WCHAR  finaloutput[MAX_PATH];
308   WCHAR  fullfilename[MAX_PATH];
309   WCHAR  thisoutput[MAX_PATH];
310   WCHAR  *pos            = *start+1;
311   WCHAR  *firstModifier  = pos;
312   WCHAR  *lastModifier   = NULL;
313   int   modifierLen     = 0;
314   BOOL  finished        = FALSE;
315   int   i               = 0;
316   BOOL  exists          = TRUE;
317   BOOL  skipFileParsing = FALSE;
318   BOOL  doneModifier    = FALSE;
319
320   /* Search forwards until find invalid character modifier */
321   while (!finished) {
322
323     /* Work on the previous character */
324     if (lastModifier != NULL) {
325
326       for (i=0; i<NUMMODIFIERS; i++) {
327         if (validmodifiers[i] == *lastModifier) {
328
329           /* Special case '$' to skip until : found */
330           if (*lastModifier == '$') {
331             while (*pos != ':' && *pos) pos++;
332             if (*pos == 0x00) return; /* Invalid syntax */
333             pos++;                    /* Skip ':'       */
334           }
335           break;
336         }
337       }
338
339       if (i==NUMMODIFIERS) {
340         finished = TRUE;
341       }
342     }
343
344     /* Save this one away */
345     if (!finished) {
346       lastModifier = pos;
347       pos++;
348     }
349   }
350
351   while (lastModifier > firstModifier) {
352     WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
353                wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
354
355     if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
356       /* Its a valid parameter identifier - OK */
357       break;
358
359     } else if (forVariable && *lastModifier == *(forVariable+1)) {
360       /* Its a valid parameter identifier - OK */
361       break;
362
363     } else {
364       lastModifier--;
365     }
366   }
367   if (lastModifier == firstModifier) return; /* Invalid syntax */
368
369   /* Extract the parameter to play with */
370   if (*lastModifier == '0') {
371     strcpyW(outputparam, context->batchfileW);
372   } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
373     strcpyW(outputparam,
374             WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
375                             NULL, NULL));
376   } else {
377     strcpyW(outputparam, forValue);
378   }
379
380   /* So now, firstModifier points to beginning of modifiers, lastModifier
381      points to the variable just after the modifiers. Process modifiers
382      in a specific order, remembering there could be duplicates           */
383   modifierLen = lastModifier - firstModifier;
384   finaloutput[0] = 0x00;
385
386   /* Useful for debugging purposes: */
387   /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
388              (modifierLen), (modifierLen), firstModifier, *lastModifier,
389              outputparam);*/
390
391   /* 1. Handle '~' : Strip surrounding quotes */
392   if (outputparam[0]=='"' &&
393       memchrW(firstModifier, '~', modifierLen) != NULL) {
394     int len = strlenW(outputparam);
395     if (outputparam[len-1] == '"') {
396         outputparam[len-1]=0x00;
397         len = len - 1;
398     }
399     memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
400   }
401
402   /* 2. Handle the special case of a $ */
403   if (memchrW(firstModifier, '$', modifierLen) != NULL) {
404     /* Special Case: Search envar specified in $[envvar] for outputparam
405        Note both $ and : are guaranteed otherwise check above would fail */
406     WCHAR *begin = strchrW(firstModifier, '$') + 1;
407     WCHAR *end   = strchrW(firstModifier, ':');
408     WCHAR env[MAX_PATH];
409     WCHAR fullpath[MAX_PATH];
410
411     /* Extract the env var */
412     memcpy(env, begin, (end-begin) * sizeof(WCHAR));
413     env[(end-begin)] = 0x00;
414
415     /* If env var not found, return empty string */
416     if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
417         (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
418       finaloutput[0] = 0x00;
419       outputparam[0] = 0x00;
420       skipFileParsing = TRUE;
421     }
422   }
423
424   /* After this, we need full information on the file,
425     which is valid not to exist.  */
426   if (!skipFileParsing) {
427     if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
428       return;
429
430     exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
431                                   &fileInfo);
432
433     /* 2. Handle 'a' : Output attributes */
434     if (exists &&
435         memchrW(firstModifier, 'a', modifierLen) != NULL) {
436
437       WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
438       doneModifier = TRUE;
439       strcpyW(thisoutput, defaults);
440       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
441         thisoutput[0]='d';
442       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
443         thisoutput[1]='r';
444       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
445         thisoutput[2]='a';
446       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
447         thisoutput[3]='h';
448       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
449         thisoutput[4]='s';
450       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
451         thisoutput[5]='c';
452       /* FIXME: What are 6 and 7? */
453       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
454         thisoutput[8]='l';
455       strcatW(finaloutput, thisoutput);
456     }
457
458     /* 3. Handle 't' : Date+time */
459     if (exists &&
460         memchrW(firstModifier, 't', modifierLen) != NULL) {
461
462       SYSTEMTIME systime;
463       int datelen;
464
465       doneModifier = TRUE;
466       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
467
468       /* Format the time */
469       FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
470       GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
471                         NULL, thisoutput, MAX_PATH);
472       strcatW(thisoutput, space);
473       datelen = strlenW(thisoutput);
474       GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
475                         NULL, (thisoutput+datelen), MAX_PATH-datelen);
476       strcatW(finaloutput, thisoutput);
477     }
478
479     /* 4. Handle 'z' : File length */
480     if (exists &&
481         memchrW(firstModifier, 'z', modifierLen) != NULL) {
482       /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
483       ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
484                                   fileInfo.nFileSizeLow;
485       static const WCHAR fmt[] = {'%','u','\0'};
486
487       doneModifier = TRUE;
488       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
489       wsprintfW(thisoutput, fmt, fullsize);
490       strcatW(finaloutput, thisoutput);
491     }
492
493     /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
494     if (memchrW(firstModifier, 's', modifierLen) != NULL) {
495       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
496       /* Don't flag as doneModifier - %~s on its own is processed later */
497       GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
498     }
499
500     /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
501     /*      Note this overrides d,p,n,x                                 */
502     if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
503       doneModifier = TRUE;
504       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
505       strcatW(finaloutput, fullfilename);
506     } else {
507
508       WCHAR drive[10];
509       WCHAR dir[MAX_PATH];
510       WCHAR fname[MAX_PATH];
511       WCHAR ext[MAX_PATH];
512       BOOL doneFileModifier = FALSE;
513
514       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
515
516       /* Split into components */
517       WCMD_splitpath(fullfilename, drive, dir, fname, ext);
518
519       /* 5. Handle 'd' : Drive Letter */
520       if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
521         strcatW(finaloutput, drive);
522         doneModifier = TRUE;
523         doneFileModifier = TRUE;
524       }
525
526       /* 6. Handle 'p' : Path */
527       if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
528         strcatW(finaloutput, dir);
529         doneModifier = TRUE;
530         doneFileModifier = TRUE;
531       }
532
533       /* 7. Handle 'n' : Name */
534       if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
535         strcatW(finaloutput, fname);
536         doneModifier = TRUE;
537         doneFileModifier = TRUE;
538       }
539
540       /* 8. Handle 'x' : Ext */
541       if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
542         strcatW(finaloutput, ext);
543         doneModifier = TRUE;
544         doneFileModifier = TRUE;
545       }
546
547       /* If 's' but no other parameter, dump the whole thing */
548       if (!doneFileModifier &&
549           memchrW(firstModifier, 's', modifierLen) != NULL) {
550         doneModifier = TRUE;
551         if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
552         strcatW(finaloutput, outputparam);
553       }
554     }
555   }
556
557   /* If No other modifier processed,  just add in parameter */
558   if (!doneModifier) strcpyW(finaloutput, outputparam);
559
560   /* Finish by inserting the replacement into the string */
561   WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
562 }
563
564 /*******************************************************************
565  * WCMD_call - processes a batch call statement
566  *
567  *      If there is a leading ':', calls within this batch program
568  *      otherwise launches another program.
569  */
570 void WCMD_call (WCHAR *command) {
571
572   /* Run other program if no leading ':' */
573   if (*command != ':') {
574     WCMD_run_program(command, 1);
575   } else {
576
577     WCHAR gotoLabel[MAX_PATH];
578
579     strcpyW(gotoLabel, param1);
580
581     if (context) {
582
583       LARGE_INTEGER li;
584
585       /* Save the current file position, call the same file,
586          restore position                                    */
587       li.QuadPart = 0;
588       li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
589                      &li.u.HighPart, FILE_CURRENT);
590
591       WCMD_batch (param1, command, 1, gotoLabel, context->h);
592
593       SetFilePointer(context -> h, li.u.LowPart,
594                      &li.u.HighPart, FILE_BEGIN);
595     } else {
596       WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));
597     }
598   }
599 }