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