2 * CMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 D A Pickles
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.
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.
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
23 * - Cannot handle parameters in quotes
24 * - Lots of functionality missing from builtins
29 #include "wine/debug.h"
31 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
33 const char * const inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
34 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
35 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
36 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
37 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL",
38 "ENDLOCAL", "SETLOCAL", "PUSHD", "POPD", "ASSOC", "EXIT" };
42 int echo_mode = 1, verify_mode = 0;
43 static int opt_c, opt_k, opt_s;
44 const char nyi[] = "Not Yet Implemented\n\n";
45 const char newline[] = "\n";
46 const char version_string[] = "CMD Version " PACKAGE_VERSION "\n\n";
47 const char anykey[] = "Press Return key to continue: ";
48 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
49 BATCH_CONTEXT *context = NULL;
50 extern struct env_stack *pushd_directories;
52 static char *WCMD_expand_envvar(char *start);
54 /*****************************************************************************
55 * Main entry point. This is a console application so we have a main() not a
59 int main (int argc, char *argv[])
67 opt_c=opt_k=opt_q=opt_s=0;
71 if ((*argv)[0]!='/' || (*argv)[1]=='\0') {
77 if (tolower(c)=='c') {
79 } else if (tolower(c)=='q') {
81 } else if (tolower(c)=='k') {
83 } else if (tolower(c)=='s') {
85 } else if (tolower(c)=='t' || tolower(c)=='x' || tolower(c)=='y') {
86 /* Ignored for compatibility with Windows */
91 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
94 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
102 if (opt_c || opt_k) {
107 /* opt_s left unflagged if the command starts with and contains exactly
108 * one quoted string (exactly two quote characters). The quoted string
109 * must be an executable name that has whitespace and must not have the
110 * following characters: &<>()@^| */
112 /* Build the command to execute */
115 for (arg = argv; *arg; arg++)
117 int has_space,bcount;
123 if( !*a ) has_space=1;
128 if (*a==' ' || *a=='\t') {
130 } else if (*a=='"') {
131 /* doubling of '\' preceding a '"',
132 * plus escaping of said '"'
141 len+=(a-*arg)+1 /* for the separating space */;
144 len+=2; /* for the quotes */
152 /* check argv[0] for a space and invalid characters */
157 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
158 || *p=='@' || *p=='^' || *p=='|') {
168 cmd = HeapAlloc(GetProcessHeap(), 0, len);
173 for (arg = argv; *arg; arg++)
175 int has_space,has_quote;
178 /* Check for quotes and spaces in this argument */
179 has_space=has_quote=0;
181 if( !*a ) has_space=1;
183 if (*a==' ' || *a=='\t') {
187 } else if (*a=='"') {
195 /* Now transfer it to the command line */
212 /* Double all the '\\' preceding this '"', plus one */
213 for (i=0;i<=bcount;i++)
232 p--; /* remove last space */
235 /* strip first and last quote characters if opt_s; check for invalid
236 * executable is done later */
237 if (opt_s && *cmd=='\"')
238 WCMD_opt_s_strip_quotes(cmd);
242 /* If we do a "wcmd /c command", we don't want to allocate a new
243 * console since the command returns immediately. Rather, we use
244 * the currently allocated input and output handles. This allows
245 * us to pipe to and read from the command interpreter.
247 if (strchr(cmd,'|') != NULL)
250 WCMD_process_command(cmd);
251 HeapFree(GetProcessHeap(), 0, cmd);
255 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
256 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
257 SetConsoleTitle("Wine Command Prompt");
260 WCMD_process_command(cmd);
261 HeapFree(GetProcessHeap(), 0, cmd);
265 * If there is an AUTOEXEC.BAT file, try to execute it.
268 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
269 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
270 if (h != INVALID_HANDLE_VALUE) {
273 WCMD_batch ((char *)"\\autoexec.bat", (char *)"\\autoexec.bat", 0, NULL, INVALID_HANDLE_VALUE);
278 * Loop forever getting commands and executing them.
284 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
286 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
287 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
288 if (lstrlen (string) != 0) {
289 if (strchr(string,'|') != NULL) {
293 WCMD_process_command (string);
301 /*****************************************************************************
302 * Process one command. If the command is EXIT this routine does not return.
303 * We will recurse through here executing batch files.
307 void WCMD_process_command (char *command)
309 char *cmd, *p, *s, *t;
311 DWORD count, creationDisposition;
314 SECURITY_ATTRIBUTES sa;
316 HANDLE old_stdin = INVALID_HANDLE_VALUE;
317 HANDLE old_stdout = INVALID_HANDLE_VALUE;
319 /* Move copy of the command onto the heap so it can be expanded */
320 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING );
321 strcpy(new_cmd, command);
323 /* For commands in a context (batch program): */
324 /* Expand environment variables in a batch file %{0-9} first */
325 /* including support for any ~ modifiers */
327 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
328 /* names allowing environment variable overrides */
329 /* NOTE: To support the %PATH:xxx% syntax, also perform */
330 /* manual expansion of environment variables here */
333 while ((p = strchr(p, '%'))) {
336 /* Replace %~ modifications if in batch program */
337 if (context && *(p+1) == '~') {
338 WCMD_HandleTildaModifiers(&p, NULL);
341 /* Replace use of %0...%9 if in batch program*/
342 } else if (context && (i >= 0) && (i <= 9)) {
344 t = WCMD_parameter (context -> command, i + context -> shift_count, NULL);
349 /* Replace use of %* if in batch program*/
350 } else if (context && *(p+1)=='*') {
351 char *startOfParms = NULL;
353 t = WCMD_parameter (context -> command, 1, &startOfParms);
354 if (startOfParms != NULL) strcpy (p, startOfParms);
360 p = WCMD_expand_envvar(p);
365 /* In a batch program, unknown variables are replace by nothing */
366 /* so remove any remaining %var% */
369 while ((p = strchr(p, '%'))) {
370 s = strchr(p+1, '%');
380 /* Show prompt before batch line IF echo is on and in batch program */
381 if (echo_mode && (cmd[0] != '@')) {
383 WCMD_output_asis ( cmd);
384 WCMD_output_asis ( "\n");
389 * Changing default drive has to be handled as a special case.
392 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
393 status = SetCurrentDirectory (cmd);
394 if (!status) WCMD_print_error ();
395 HeapFree( GetProcessHeap(), 0, cmd );
399 /* Don't issue newline WCMD_output (newline); @JED*/
401 sa.nLength = sizeof(sa);
402 sa.lpSecurityDescriptor = NULL;
403 sa.bInheritHandle = TRUE;
405 * Redirect stdin and/or stdout if required.
408 if ((p = strchr(cmd,'<')) != NULL) {
409 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
410 FILE_ATTRIBUTE_NORMAL, NULL);
411 if (h == INVALID_HANDLE_VALUE) {
413 HeapFree( GetProcessHeap(), 0, cmd );
416 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
417 SetStdHandle (STD_INPUT_HANDLE, h);
419 if ((p = strchr(cmd,'>')) != NULL) {
422 creationDisposition = OPEN_ALWAYS;
426 creationDisposition = CREATE_ALWAYS;
428 h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
429 FILE_ATTRIBUTE_NORMAL, NULL);
430 if (h == INVALID_HANDLE_VALUE) {
432 HeapFree( GetProcessHeap(), 0, cmd );
435 if (SetFilePointer (h, 0, NULL, FILE_END) ==
436 INVALID_SET_FILE_POINTER) {
439 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
440 SetStdHandle (STD_OUTPUT_HANDLE, h);
442 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
445 * Strip leading whitespaces, and a '@' if supplied
447 whichcmd = WCMD_strtrim_leading_spaces(cmd);
448 WINE_TRACE("Command: '%s'\n", cmd);
449 if (whichcmd[0] == '@') whichcmd++;
452 * Check if the command entered is internal. If it is, pass the rest of the
453 * line down to the command. If not try to run a program.
457 while (IsCharAlphaNumeric(whichcmd[count])) {
460 for (i=0; i<=WCMD_EXIT; i++) {
461 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
462 whichcmd, count, inbuilt[i], -1) == 2) break;
464 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
465 WCMD_parse (p, quals, param1, param2);
469 WCMD_setshow_attrib ();
476 WCMD_setshow_default ();
479 WCMD_clear_screen ();
488 WCMD_setshow_date ();
498 WCMD_echo(&whichcmd[count]);
523 WCMD_setshow_path (p);
529 WCMD_setshow_prompt ();
548 WCMD_setshow_env (p);
554 WCMD_setshow_time ();
557 if (strlen(&whichcmd[count]) > 0)
558 WCMD_title(&whichcmd[count+1]);
585 WCMD_run_program (whichcmd, 0);
587 HeapFree( GetProcessHeap(), 0, cmd );
588 if (old_stdin != INVALID_HANDLE_VALUE) {
589 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
590 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
592 if (old_stdout != INVALID_HANDLE_VALUE) {
593 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
594 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
598 static void init_msvcrt_io_block(STARTUPINFO* st)
601 /* fetch the parent MSVCRT info block if any, so that the child can use the
602 * same handles as its grand-father
604 st_p.cb = sizeof(STARTUPINFO);
605 GetStartupInfo(&st_p);
606 st->cbReserved2 = st_p.cbReserved2;
607 st->lpReserved2 = st_p.lpReserved2;
608 if (st_p.cbReserved2 && st_p.lpReserved2)
610 /* Override the entries for fd 0,1,2 if we happened
611 * to change those std handles (this depends on the way wcmd sets
612 * it's new input & output handles)
614 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
615 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
618 unsigned num = *(unsigned*)st_p.lpReserved2;
619 char* flags = (char*)(ptr + sizeof(unsigned));
620 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
622 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
623 st->cbReserved2 = sz;
624 st->lpReserved2 = ptr;
626 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
627 if (num <= 0 || (flags[0] & WX_OPEN))
629 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
632 if (num <= 1 || (flags[1] & WX_OPEN))
634 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
637 if (num <= 2 || (flags[2] & WX_OPEN))
639 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
647 /******************************************************************************
650 * Execute a command line as an external program. Must allow recursion.
653 * Manual testing under windows shows PATHEXT plays a key part in this,
654 * and the search algorithm and precedence appears to be as follows.
657 * If directory supplied on command, just use that directory
658 * If extension supplied on command, look for that explicit name first
659 * Otherwise, search in each directory on the path
661 * If extension supplied on command, look for that explicit name first
662 * Then look for supplied name .* (even if extension supplied, so
663 * 'garbage.exe' will match 'garbage.exe.cmd')
664 * If any found, cycle through PATHEXT looking for name.exe one by one
666 * Once a match has been found, it is launched - Code currently uses
667 * findexecutable to acheive this which is left untouched.
670 void WCMD_run_program (char *command, int called) {
673 char pathtosearch[MAX_PATH];
675 char stemofsearch[MAX_PATH];
677 char pathext[MAXSTRING];
678 BOOL extensionsupplied = FALSE;
679 BOOL launched = FALSE;
684 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
685 if (!(*param1) && !(*param2))
688 /* Calculate the search path and stem to search for */
689 if (strpbrk (param1, "/\\:") == NULL) { /* No explicit path given, search path */
690 strcpy(pathtosearch,".;");
691 len = GetEnvironmentVariable ("PATH", &pathtosearch[2], sizeof(pathtosearch)-2);
692 if ((len == 0) || (len >= sizeof(pathtosearch) - 2)) {
693 lstrcpy (pathtosearch, ".");
695 if (strchr(param1, '.') != NULL) extensionsupplied = TRUE;
696 strcpy(stemofsearch, param1);
700 /* Convert eg. ..\fred to include a directory by removing file part */
701 GetFullPathName(param1, MAX_PATH, pathtosearch, NULL);
702 lastSlash = strrchr(pathtosearch, '\\');
703 if (lastSlash) *lastSlash = 0x00;
704 if (strchr(lastSlash, '.') != NULL) extensionsupplied = TRUE;
705 strcpy(stemofsearch, lastSlash+1);
708 /* Now extract PATHEXT */
709 len = GetEnvironmentVariable ("PATHEXT", pathext, sizeof(pathext));
710 if ((len == 0) || (len >= sizeof(pathext))) {
711 lstrcpy (pathext, ".bat;.com;.cmd;.exe");
714 /* Loop through the search path, dir by dir */
715 pathposn = pathtosearch;
716 while (!launched && pathposn) {
718 char thisDir[MAX_PATH] = "";
722 /* Work on the first directory on the search path */
723 pos = strchr(pathposn, ';');
725 strncpy(thisDir, pathposn, (pos-pathposn));
726 thisDir[(pos-pathposn)] = 0x00;
730 strcpy(thisDir, pathposn);
734 /* Since you can have eg. ..\.. on the path, need to expand
735 to full information */
736 strcpy(temp, thisDir);
737 GetFullPathName(temp, MAX_PATH, thisDir, NULL);
739 /* 1. If extension supplied, see if that file exists */
740 strcat(thisDir, "\\");
741 strcat(thisDir, stemofsearch);
742 pos = &thisDir[strlen(thisDir)]; /* Pos = end of name */
744 if (GetFileAttributes(thisDir) != INVALID_FILE_ATTRIBUTES) {
748 /* 2. Any .* matches? */
751 WIN32_FIND_DATA finddata;
753 strcat(thisDir,".*");
754 h = FindFirstFile(thisDir, &finddata);
756 if (h != INVALID_HANDLE_VALUE) {
758 char *thisExt = pathext;
760 /* 3. Yes - Try each path ext */
762 char *nextExt = strchr(thisExt, ';');
765 strncpy(pos, thisExt, (nextExt-thisExt));
766 pos[(nextExt-thisExt)] = 0x00;
769 strcpy(pos, thisExt);
773 if (GetFileAttributes(thisDir) != INVALID_FILE_ATTRIBUTES) {
781 /* Once found, launch it */
784 PROCESS_INFORMATION pe;
788 char *ext = strrchr( thisDir, '.' );
791 /* Special case BAT and CMD */
792 if (ext && !strcasecmp(ext, ".bat")) {
793 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
795 } else if (ext && !strcasecmp(ext, ".cmd")) {
796 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
800 /* thisDir contains the file to be launched, but with what?
801 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
802 hinst = FindExecutable (param1, NULL, temp);
803 if ((INT_PTR)hinst < 32)
806 console = SHGetFileInfo (temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
808 ZeroMemory (&st, sizeof(STARTUPINFO));
809 st.cb = sizeof(STARTUPINFO);
810 init_msvcrt_io_block(&st);
812 /* Launch the process and if a CUI wait on it to complete */
813 status = CreateProcess (thisDir, command, NULL, NULL, TRUE,
814 0, NULL, NULL, &st, &pe);
815 if ((opt_c || opt_k) && !opt_s && !status
816 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
817 /* strip first and last quote characters and try again */
818 WCMD_opt_s_strip_quotes(command);
820 WCMD_run_program(command, called);
825 /* If a command fails to launch, it sets errorlevel 9009 - which
826 does not seem to have any associated constant definition */
830 if (!console) errorlevel = 0;
833 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
834 GetExitCodeProcess (pe.hProcess, &errorlevel);
835 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
837 CloseHandle(pe.hProcess);
838 CloseHandle(pe.hThread);
844 /* Not found anywhere - give up */
845 SetLastError(ERROR_FILE_NOT_FOUND);
848 /* If a command fails to launch, it sets errorlevel 9009 - which
849 does not seem to have any associated constant definition */
855 /******************************************************************************
858 * Display the prompt on STDout
862 void WCMD_show_prompt (void) {
865 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
869 len = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
870 if ((len == 0) || (len >= sizeof(prompt_string))) {
871 lstrcpy (prompt_string, "$P$G");
883 switch (toupper(*p)) {
897 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
916 status = GetCurrentDirectory (sizeof(curdir), curdir);
922 status = GetCurrentDirectory (sizeof(curdir), curdir);
935 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
939 lstrcat (q, version_string);
946 if (pushd_directories) {
947 memset(q, '+', pushd_directories->stackdepth);
948 q = q + pushd_directories->stackdepth;
956 WCMD_output_asis (out_string);
959 /****************************************************************************
962 * Print the message for GetLastError
965 void WCMD_print_error (void) {
970 error_code = GetLastError ();
971 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
972 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
974 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
975 error_code, GetLastError());
978 WCMD_output_asis (lpMsgBuf);
979 LocalFree ((HLOCAL)lpMsgBuf);
980 WCMD_output_asis (newline);
984 /*******************************************************************
985 * WCMD_parse - parse a command into parameters and qualifiers.
987 * On exit, all qualifiers are concatenated into q, the first string
988 * not beginning with "/" is in p1 and the
989 * second in p2. Any subsequent non-qualifier strings are lost.
990 * Parameters in quotes are handled.
993 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
997 *q = *p1 = *p2 = '\0';
1002 while ((*s != '\0') && (*s != ' ') && *s != '/') {
1003 *q++ = toupper (*s++);
1013 while ((*s != '\0') && (*s != '"')) {
1014 if (p == 0) *p1++ = *s++;
1015 else if (p == 1) *p2++ = *s++;
1018 if (p == 0) *p1 = '\0';
1019 if (p == 1) *p2 = '\0';
1026 while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
1027 if (p == 0) *p1++ = *s++;
1028 else if (p == 1) *p2++ = *s++;
1031 if (p == 0) *p1 = '\0';
1032 if (p == 1) *p2 = '\0';
1038 /*******************************************************************
1039 * WCMD_output - send output to current standard output device.
1043 void WCMD_output (const char *format, ...) {
1049 va_start(ap,format);
1050 ret = vsnprintf (string, sizeof( string), format, ap);
1052 if( ret >= sizeof( string)) {
1053 WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
1054 string[sizeof( string) -1] = '\0';
1056 WCMD_output_asis(string);
1060 static int line_count;
1061 static int max_height;
1062 static BOOL paged_mode;
1064 void WCMD_enter_paged_mode(void)
1066 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
1068 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
1069 max_height = consoleInfo.dwSize.Y;
1073 line_count = 5; /* keep 5 lines from previous output */
1076 void WCMD_leave_paged_mode(void)
1081 /*******************************************************************
1082 * WCMD_output_asis - send output to current standard output device.
1083 * without formatting eg. when message contains '%'
1086 void WCMD_output_asis (const char *message) {
1093 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
1094 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
1095 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
1097 if (++line_count >= max_height - 1) {
1099 WCMD_output_asis (anykey);
1100 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1103 } while ((message = ptr) != NULL);
1105 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
1110 /***************************************************************************
1111 * WCMD_strtrim_leading_spaces
1113 * Remove leading spaces from a string. Return a pointer to the first
1114 * non-space character. Does not modify the input string
1117 char *WCMD_strtrim_leading_spaces (char *string) {
1122 while (*ptr == ' ') ptr++;
1126 /*************************************************************************
1127 * WCMD_strtrim_trailing_spaces
1129 * Remove trailing spaces from a string. This routine modifies the input
1130 * string by placing a null after the last non-space character
1133 void WCMD_strtrim_trailing_spaces (char *string) {
1137 ptr = string + lstrlen (string) - 1;
1138 while ((*ptr == ' ') && (ptr >= string)) {
1144 /*************************************************************************
1145 * WCMD_opt_s_strip_quotes
1147 * Remove first and last quote characters, preserving all other text
1150 void WCMD_opt_s_strip_quotes(char *cmd) {
1151 char *src = cmd + 1, *dest = cmd, *lastq = NULL;
1152 while((*dest=*src) != '\0') {
1159 while ((*dest++=*lastq++) != 0)
1164 /*************************************************************************
1167 * Handle pipes within a command - the DOS way using temporary files.
1170 void WCMD_pipe (char *command) {
1173 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
1175 GetTempPath (sizeof(temp_path), temp_path);
1176 GetTempFileName (temp_path, "CMD", 0, temp_file);
1177 p = strchr(command, '|');
1179 wsprintf (temp_cmd, "%s > %s", command, temp_file);
1180 WCMD_process_command (temp_cmd);
1182 while ((p = strchr(command, '|'))) {
1184 GetTempFileName (temp_path, "CMD", 0, temp_file2);
1185 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
1186 WCMD_process_command (temp_cmd);
1187 DeleteFile (temp_file);
1188 lstrcpy (temp_file, temp_file2);
1191 wsprintf (temp_cmd, "%s < %s", command, temp_file);
1192 WCMD_process_command (temp_cmd);
1193 DeleteFile (temp_file);
1196 /*************************************************************************
1197 * WCMD_expand_envvar
1199 * Expands environment variables, allowing for character substitution
1201 static char *WCMD_expand_envvar(char *start) {
1202 char *endOfVar = NULL, *s;
1203 char *colonpos = NULL;
1204 char thisVar[MAXSTRING];
1205 char thisVarContents[MAXSTRING];
1206 char savedchar = 0x00;
1209 /* Find the end of the environment variable, and extract name */
1210 endOfVar = strchr(start+1, '%');
1211 if (endOfVar == NULL) {
1212 /* FIXME: Some special conditions here depending opn whether
1213 in batch, complex or not, and whether env var exists or not! */
1216 strncpy(thisVar, start, (endOfVar - start)+1);
1217 thisVar[(endOfVar - start)+1] = 0x00;
1218 colonpos = strchr(thisVar+1, ':');
1220 /* If there's complex substitution, just need %var% for now
1221 to get the expanded data to play with */
1224 savedchar = *(colonpos+1);
1225 *(colonpos+1) = 0x00;
1228 /* Expand to contents, if unchanged, return */
1229 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
1230 /* override if existing env var called that name */
1231 if ((CompareString (LOCALE_USER_DEFAULT,
1232 NORM_IGNORECASE | SORT_STRINGSORT,
1233 thisVar, 12, "%ERRORLEVEL%", -1) == 2) &&
1234 (GetEnvironmentVariable("ERRORLEVEL", thisVarContents, 1) == 0) &&
1235 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1236 sprintf(thisVarContents, "%d", errorlevel);
1237 len = strlen(thisVarContents);
1239 } else if ((CompareString (LOCALE_USER_DEFAULT,
1240 NORM_IGNORECASE | SORT_STRINGSORT,
1241 thisVar, 6, "%DATE%", -1) == 2) &&
1242 (GetEnvironmentVariable("DATE", thisVarContents, 1) == 0) &&
1243 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1245 GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
1246 NULL, thisVarContents, MAXSTRING);
1247 len = strlen(thisVarContents);
1249 } else if ((CompareString (LOCALE_USER_DEFAULT,
1250 NORM_IGNORECASE | SORT_STRINGSORT,
1251 thisVar, 6, "%TIME%", -1) == 2) &&
1252 (GetEnvironmentVariable("TIME", thisVarContents, 1) == 0) &&
1253 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1254 GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
1255 NULL, thisVarContents, MAXSTRING);
1256 len = strlen(thisVarContents);
1258 } else if ((CompareString (LOCALE_USER_DEFAULT,
1259 NORM_IGNORECASE | SORT_STRINGSORT,
1260 thisVar, 4, "%CD%", -1) == 2) &&
1261 (GetEnvironmentVariable("CD", thisVarContents, 1) == 0) &&
1262 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1263 GetCurrentDirectory (MAXSTRING, thisVarContents);
1264 len = strlen(thisVarContents);
1266 } else if ((CompareString (LOCALE_USER_DEFAULT,
1267 NORM_IGNORECASE | SORT_STRINGSORT,
1268 thisVar, 8, "%RANDOM%", -1) == 2) &&
1269 (GetEnvironmentVariable("RANDOM", thisVarContents, 1) == 0) &&
1270 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1271 sprintf(thisVarContents, "%d", rand() % 32768);
1272 len = strlen(thisVarContents);
1276 len = ExpandEnvironmentStrings(thisVar, thisVarContents,
1277 sizeof(thisVarContents));
1283 /* In a batch program, unknown env vars are replaced with nothing,
1284 note syntax %garbage:1,3% results in anything after the ':'
1286 From the command line, you just get back what you entered */
1287 if (lstrcmpi(thisVar, thisVarContents) == 0) {
1289 /* Restore the complex part after the compare */
1292 *(colonpos+1) = savedchar;
1295 s = strdup (endOfVar + 1);
1297 /* Command line - just ignore this */
1298 if (context == NULL) return endOfVar+1;
1300 /* Batch - replace unknown env var with nothing */
1301 if (colonpos == NULL) {
1305 len = strlen(thisVar);
1306 thisVar[len-1] = 0x00;
1307 /* If %:...% supplied, : is retained */
1308 if (colonpos == thisVar+1) {
1309 strcpy (start, colonpos);
1311 strcpy (start, colonpos+1);
1320 /* See if we need to do complex substitution (any ':'s), if not
1321 then our work here is done */
1322 if (colonpos == NULL) {
1323 s = strdup (endOfVar + 1);
1324 strcpy (start, thisVarContents);
1330 /* Restore complex bit */
1332 *(colonpos+1) = savedchar;
1335 Handle complex substitutions:
1336 xxx=yyy (replace xxx with yyy)
1337 *xxx=yyy (replace up to and including xxx with yyy)
1338 ~x (from x chars in)
1339 ~-x (from x chars from the end)
1340 ~x,y (from x chars in for y characters)
1341 ~x,-y (from x chars in until y characters from the end)
1344 /* ~ is substring manipulation */
1345 if (savedchar == '~') {
1347 int substrposition, substrlength;
1348 char *commapos = strchr(colonpos+2, ',');
1351 substrposition = atol(colonpos+2);
1352 if (commapos) substrlength = atol(commapos+1);
1354 s = strdup (endOfVar + 1);
1357 if (substrposition >= 0) {
1358 startCopy = &thisVarContents[min(substrposition, len)];
1360 startCopy = &thisVarContents[max(0, len+substrposition-1)];
1363 if (commapos == NULL) {
1364 strcpy (start, startCopy); /* Copy the lot */
1365 } else if (substrlength < 0) {
1367 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
1368 if (copybytes > len) copybytes = len;
1369 else if (copybytes < 0) copybytes = 0;
1370 strncpy (start, startCopy, copybytes); /* Copy the lot */
1371 start[copybytes] = 0x00;
1373 strncpy (start, startCopy, substrlength); /* Copy the lot */
1374 start[substrlength] = 0x00;
1381 /* search and replace manipulation */
1383 char *equalspos = strstr(colonpos, "=");
1384 char *replacewith = equalspos+1;
1389 s = strdup (endOfVar + 1);
1390 if (equalspos == NULL) return start+1;
1392 /* Null terminate both strings */
1393 thisVar[strlen(thisVar)-1] = 0x00;
1396 /* Since we need to be case insensitive, copy the 2 buffers */
1397 searchIn = strdup(thisVarContents);
1398 CharUpperBuff(searchIn, strlen(thisVarContents));
1399 searchFor = strdup(colonpos+1);
1400 CharUpperBuff(searchFor, strlen(colonpos+1));
1403 /* Handle wildcard case */
1404 if (*(colonpos+1) == '*') {
1405 /* Search for string to replace */
1406 found = strstr(searchIn, searchFor+1);
1409 /* Do replacement */
1410 strcpy(start, replacewith);
1411 strcat(start, thisVarContents + (found-searchIn) + strlen(searchFor+1));
1416 strcpy(start, thisVarContents);
1421 /* Loop replacing all instances */
1422 char *lastFound = searchIn;
1423 char *outputposn = start;
1426 while ((found = strstr(lastFound, searchFor))) {
1428 thisVarContents + (lastFound-searchIn),
1429 (found - lastFound));
1430 outputposn = outputposn + (found - lastFound);
1432 strcat(outputposn, replacewith);
1433 outputposn = outputposn + strlen(replacewith);
1434 lastFound = found + strlen(searchFor);
1437 thisVarContents + (lastFound-searchIn));
1438 strcat(outputposn, s);