cmd: Move a global var to the file using it.
[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))
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  *  start [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  *           *start 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  *           *start 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 **start, WCHAR **end) {
141     int curParamNb = 0;
142     static WCHAR param[MAX_PATH];
143     WCHAR *p = s, *q;
144     BOOL quotesDelimited;
145
146     if (start != NULL) *start = 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 (start != NULL && curParamNb == n) *start = 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  * Gets one line from a file/console and puts it into buffer buf
180  * Pre:  buf has size noChars
181  *       1 <= noChars <= MAXSTRING
182  * Post: buf is filled with at most noChars-1 characters, and gets nul-terminated
183          buf does not include EOL terminator
184  * Returns:
185  *       buf on success
186  *       NULL on error or EOF
187  */
188
189 WCHAR *WCMD_fgets(WCHAR *buf, DWORD noChars, HANDLE h)
190 {
191   DWORD charsRead;
192   BOOL status;
193   LARGE_INTEGER filepos;
194   DWORD i;
195
196   /* We can't use the native f* functions because of the filename syntax differences
197      between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */
198
199   if (!WCMD_is_console_handle(h)) {
200     /* Save current file position */
201     filepos.QuadPart = 0;
202     SetFilePointerEx(h, filepos, &filepos, FILE_CURRENT);
203   }
204
205   status = WCMD_ReadFile(h, buf, noChars, &charsRead);
206   if (!status || charsRead == 0) return NULL;
207
208   /* Find first EOL */
209   for (i = 0; i < charsRead; i++) {
210     if (buf[i] == '\n' || buf[i] == '\r')
211       break;
212   }
213
214   if (!WCMD_is_console_handle(h) && i != charsRead) {
215     /* Sets file pointer to the start of the next line, if any */
216     filepos.QuadPart += i + 1 + (buf[i] == '\r' ? 1 : 0);
217     SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);
218   }
219
220   /* Truncate at EOL (or end of buffer) */
221   if (i == noChars)
222     i--;
223
224   buf[i] = '\0';
225
226   return buf;
227 }
228
229 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
230 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
231 {
232         const WCHAR* end; /* end of processed string */
233         const WCHAR* p;  /* search pointer */
234         const WCHAR* s;  /* copy pointer */
235
236         /* extract drive name */
237         if (path[0] && path[1]==':') {
238                 if (drv) {
239                         *drv++ = *path++;
240                         *drv++ = *path++;
241                         *drv = '\0';
242                 }
243         } else if (drv)
244                 *drv = '\0';
245
246         end = path + strlenW(path);
247
248         /* search for begin of file extension */
249         for(p=end; p>path && *--p!='\\' && *p!='/'; )
250                 if (*p == '.') {
251                         end = p;
252                         break;
253                 }
254
255         if (ext)
256                 for(s=end; (*ext=*s++); )
257                         ext++;
258
259         /* search for end of directory name */
260         for(p=end; p>path; )
261                 if (*--p=='\\' || *p=='/') {
262                         p++;
263                         break;
264                 }
265
266         if (name) {
267                 for(s=p; s<end; )
268                         *name++ = *s++;
269
270                 *name = '\0';
271         }
272
273         if (dir) {
274                 for(s=path; s<p; )
275                         *dir++ = *s++;
276
277                 *dir = '\0';
278         }
279 }
280
281 /****************************************************************************
282  * WCMD_HandleTildaModifiers
283  *
284  * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
285  *    %~xxxxxV  (V=0-9 or A-Z)
286  * Where xxxx is any combination of:
287  *    ~ - Removes quotes
288  *    f - Fully qualified path (assumes current dir if not drive\dir)
289  *    d - drive letter
290  *    p - path
291  *    n - filename
292  *    x - file extension
293  *    s - path with shortnames
294  *    a - attributes
295  *    t - date/time
296  *    z - size
297  *    $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
298  *                   qualified path
299  *
300  *  To work out the length of the modifier:
301  *
302  *  Note: In the case of %0-9 knowing the end of the modifier is easy,
303  *    but in a for loop, the for end WCHARacter may also be a modifier
304  *    eg. for %a in (c:\a.a) do echo XXX
305  *             where XXX = %~a    (just ~)
306  *                         %~aa   (~ and attributes)
307  *                         %~aaxa (~, attributes and extension)
308  *                   BUT   %~aax  (~ and attributes followed by 'x')
309  *
310  *  Hence search forwards until find an invalid modifier, and then
311  *  backwards until find for variable or 0-9
312  */
313 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
314                                const WCHAR *forValue, BOOL justFors) {
315
316 #define NUMMODIFIERS 11
317   static const WCHAR validmodifiers[NUMMODIFIERS] = {
318         '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
319   };
320
321   WIN32_FILE_ATTRIBUTE_DATA fileInfo;
322   WCHAR  outputparam[MAX_PATH];
323   WCHAR  finaloutput[MAX_PATH];
324   WCHAR  fullfilename[MAX_PATH];
325   WCHAR  thisoutput[MAX_PATH];
326   WCHAR  *pos            = *start+1;
327   WCHAR  *firstModifier  = pos;
328   WCHAR  *lastModifier   = NULL;
329   int   modifierLen     = 0;
330   BOOL  finished        = FALSE;
331   int   i               = 0;
332   BOOL  exists          = TRUE;
333   BOOL  skipFileParsing = FALSE;
334   BOOL  doneModifier    = FALSE;
335
336   /* Search forwards until find invalid character modifier */
337   while (!finished) {
338
339     /* Work on the previous character */
340     if (lastModifier != NULL) {
341
342       for (i=0; i<NUMMODIFIERS; i++) {
343         if (validmodifiers[i] == *lastModifier) {
344
345           /* Special case '$' to skip until : found */
346           if (*lastModifier == '$') {
347             while (*pos != ':' && *pos) pos++;
348             if (*pos == 0x00) return; /* Invalid syntax */
349             pos++;                    /* Skip ':'       */
350           }
351           break;
352         }
353       }
354
355       if (i==NUMMODIFIERS) {
356         finished = TRUE;
357       }
358     }
359
360     /* Save this one away */
361     if (!finished) {
362       lastModifier = pos;
363       pos++;
364     }
365   }
366
367   while (lastModifier > firstModifier) {
368     WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
369                wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
370
371     if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
372       /* Its a valid parameter identifier - OK */
373       break;
374
375     } else if (forVariable && *lastModifier == *(forVariable+1)) {
376       /* Its a valid parameter identifier - OK */
377       break;
378
379     } else {
380       lastModifier--;
381     }
382   }
383   if (lastModifier == firstModifier) return; /* Invalid syntax */
384
385   /* Extract the parameter to play with */
386   if (*lastModifier == '0') {
387     strcpyW(outputparam, context->batchfileW);
388   } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
389     strcpyW(outputparam,
390             WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
391                             NULL, NULL));
392   } else {
393     strcpyW(outputparam, forValue);
394   }
395
396   /* So now, firstModifier points to beginning of modifiers, lastModifier
397      points to the variable just after the modifiers. Process modifiers
398      in a specific order, remembering there could be duplicates           */
399   modifierLen = lastModifier - firstModifier;
400   finaloutput[0] = 0x00;
401
402   /* Useful for debugging purposes: */
403   /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
404              (modifierLen), (modifierLen), firstModifier, *lastModifier,
405              outputparam);*/
406
407   /* 1. Handle '~' : Strip surrounding quotes */
408   if (outputparam[0]=='"' &&
409       memchrW(firstModifier, '~', modifierLen) != NULL) {
410     int len = strlenW(outputparam);
411     if (outputparam[len-1] == '"') {
412         outputparam[len-1]=0x00;
413         len = len - 1;
414     }
415     memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
416   }
417
418   /* 2. Handle the special case of a $ */
419   if (memchrW(firstModifier, '$', modifierLen) != NULL) {
420     /* Special Case: Search envar specified in $[envvar] for outputparam
421        Note both $ and : are guaranteed otherwise check above would fail */
422     WCHAR *begin = strchrW(firstModifier, '$') + 1;
423     WCHAR *end   = strchrW(firstModifier, ':');
424     WCHAR env[MAX_PATH];
425     WCHAR fullpath[MAX_PATH];
426
427     /* Extract the env var */
428     memcpy(env, begin, (end-begin) * sizeof(WCHAR));
429     env[(end-begin)] = 0x00;
430
431     /* If env var not found, return empty string */
432     if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
433         (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
434       finaloutput[0] = 0x00;
435       outputparam[0] = 0x00;
436       skipFileParsing = TRUE;
437     }
438   }
439
440   /* After this, we need full information on the file,
441     which is valid not to exist.  */
442   if (!skipFileParsing) {
443     if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
444       return;
445
446     exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
447                                   &fileInfo);
448
449     /* 2. Handle 'a' : Output attributes */
450     if (exists &&
451         memchrW(firstModifier, 'a', modifierLen) != NULL) {
452
453       WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
454       doneModifier = TRUE;
455       strcpyW(thisoutput, defaults);
456       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
457         thisoutput[0]='d';
458       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
459         thisoutput[1]='r';
460       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
461         thisoutput[2]='a';
462       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
463         thisoutput[3]='h';
464       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
465         thisoutput[4]='s';
466       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
467         thisoutput[5]='c';
468       /* FIXME: What are 6 and 7? */
469       if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
470         thisoutput[8]='l';
471       strcatW(finaloutput, thisoutput);
472     }
473
474     /* 3. Handle 't' : Date+time */
475     if (exists &&
476         memchrW(firstModifier, 't', modifierLen) != NULL) {
477
478       SYSTEMTIME systime;
479       int datelen;
480
481       doneModifier = TRUE;
482       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
483
484       /* Format the time */
485       FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
486       GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
487                         NULL, thisoutput, MAX_PATH);
488       strcatW(thisoutput, space);
489       datelen = strlenW(thisoutput);
490       GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
491                         NULL, (thisoutput+datelen), MAX_PATH-datelen);
492       strcatW(finaloutput, thisoutput);
493     }
494
495     /* 4. Handle 'z' : File length */
496     if (exists &&
497         memchrW(firstModifier, 'z', modifierLen) != NULL) {
498       /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
499       ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
500                                   fileInfo.nFileSizeLow;
501       static const WCHAR fmt[] = {'%','u','\0'};
502
503       doneModifier = TRUE;
504       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
505       wsprintfW(thisoutput, fmt, fullsize);
506       strcatW(finaloutput, thisoutput);
507     }
508
509     /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
510     if (memchrW(firstModifier, 's', modifierLen) != NULL) {
511       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
512       /* Don't flag as doneModifier - %~s on its own is processed later */
513       GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
514     }
515
516     /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
517     /*      Note this overrides d,p,n,x                                 */
518     if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
519       doneModifier = TRUE;
520       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
521       strcatW(finaloutput, fullfilename);
522     } else {
523
524       WCHAR drive[10];
525       WCHAR dir[MAX_PATH];
526       WCHAR fname[MAX_PATH];
527       WCHAR ext[MAX_PATH];
528       BOOL doneFileModifier = FALSE;
529
530       if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
531
532       /* Split into components */
533       WCMD_splitpath(fullfilename, drive, dir, fname, ext);
534
535       /* 5. Handle 'd' : Drive Letter */
536       if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
537         strcatW(finaloutput, drive);
538         doneModifier = TRUE;
539         doneFileModifier = TRUE;
540       }
541
542       /* 6. Handle 'p' : Path */
543       if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
544         strcatW(finaloutput, dir);
545         doneModifier = TRUE;
546         doneFileModifier = TRUE;
547       }
548
549       /* 7. Handle 'n' : Name */
550       if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
551         strcatW(finaloutput, fname);
552         doneModifier = TRUE;
553         doneFileModifier = TRUE;
554       }
555
556       /* 8. Handle 'x' : Ext */
557       if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
558         strcatW(finaloutput, ext);
559         doneModifier = TRUE;
560         doneFileModifier = TRUE;
561       }
562
563       /* If 's' but no other parameter, dump the whole thing */
564       if (!doneFileModifier &&
565           memchrW(firstModifier, 's', modifierLen) != NULL) {
566         doneModifier = TRUE;
567         if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
568         strcatW(finaloutput, outputparam);
569       }
570     }
571   }
572
573   /* If No other modifier processed,  just add in parameter */
574   if (!doneModifier) strcpyW(finaloutput, outputparam);
575
576   /* Finish by inserting the replacement into the string */
577   WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
578 }
579
580 /*******************************************************************
581  * WCMD_call - processes a batch call statement
582  *
583  *      If there is a leading ':', calls within this batch program
584  *      otherwise launches another program.
585  */
586 void WCMD_call (WCHAR *command) {
587
588   /* Run other program if no leading ':' */
589   if (*command != ':') {
590     WCMD_run_program(command, 1);
591   } else {
592
593     WCHAR gotoLabel[MAX_PATH];
594
595     strcpyW(gotoLabel, param1);
596
597     if (context) {
598
599       LARGE_INTEGER li;
600
601       /* Save the current file position, call the same file,
602          restore position                                    */
603       li.QuadPart = 0;
604       li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
605                      &li.u.HighPart, FILE_CURRENT);
606
607       WCMD_batch (param1, command, 1, gotoLabel, context->h);
608
609       SetFilePointer(context -> h, li.u.LowPart,
610                      &li.u.HighPart, FILE_BEGIN);
611     } else {
612       WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));
613     }
614   }
615 }