builtins.c 82.2 KB
Newer Older
1
/*
2
 * CMD - Wine-compatible command line interface - built-in functions.
3
 *
4
 * Copyright (C) 1999 D A Pickles
5
 * Copyright (C) 2007 J Edmeades
6
 *
7 8 9 10 11 12 13 14 15 16 17 18
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 23
 */

/*
 * NOTES:
24 25 26 27 28 29 30
 * On entry to each function, global variables quals, param1, param2 contain
 * the qualifiers (uppercased and concatenated) and parameters entered, with
 * environment-variable and batch parameter substitution already done.
 */

/*
 * FIXME:
31
 * - No support for pipes, shell parameters
32 33 34 35
 * - Lots of functionality missing from builtins
 * - Messages etc need international support
 */

36 37
#define WIN32_LEAN_AND_MEAN

38
#include "wcmd.h"
39
#include <shellapi.h>
40 41 42
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(cmd);
43

44 45
static void WCMD_part_execute(CMD_LIST **commands, WCHAR *firstcmd, WCHAR *variable,
                               WCHAR *value, BOOL isIF, BOOL conditionTRUE);
46

47
struct env_stack *saved_environment;
48
struct env_stack *pushd_directories;
49

50
extern HINSTANCE hinst;
51
extern WCHAR inbuilt[][10];
52
extern int echo_mode, verify_mode, defaultColor;
53
extern WCHAR quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
54
extern BATCH_CONTEXT *context;
55
extern DWORD errorlevel;
56

57 58 59 60 61 62 63 64 65 66 67
static const WCHAR dotW[]    = {'.','\0'};
static const WCHAR dotdotW[] = {'.','.','\0'};
static const WCHAR slashW[]  = {'\\','\0'};
static const WCHAR starW[]   = {'*','\0'};
static const WCHAR equalW[]  = {'=','\0'};
static const WCHAR fslashW[] = {'/','\0'};
static const WCHAR onW[]  = {'O','N','\0'};
static const WCHAR offW[] = {'O','F','F','\0'};
static const WCHAR parmY[] = {'/','Y','\0'};
static const WCHAR parmNoY[] = {'/','-','Y','\0'};
static const WCHAR nullW[] = {'\0'};
68 69 70 71 72 73 74

/****************************************************************************
 * WCMD_clear_screen
 *
 * Clear the terminal screen.
 */

75
void WCMD_clear_screen (void) {
76

77 78 79 80
  /* Emulate by filling the screen from the top left to bottom right with
        spaces, then moving the cursor to the top left afterwards */
  CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
81

82 83 84
  if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
  {
      COORD topLeft;
Mike McCormack's avatar
Mike McCormack committed
85 86
      DWORD screenSize;

87
      screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
88

89 90 91 92 93
      topLeft.X = 0;
      topLeft.Y = 0;
      FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
      SetConsoleCursorPosition(hStdOut, topLeft);
  }
94 95 96 97 98 99 100 101
}

/****************************************************************************
 * WCMD_change_tty
 *
 * Change the default i/o device (ie redirect STDin/STDout).
 */

102
void WCMD_change_tty (void) {
103

104
  WCMD_output (WCMD_LoadMessage(WCMD_NYI));
105 106 107 108 109 110 111

}

/****************************************************************************
 * WCMD_copy
 *
 * Copy a file or wildcarded set.
112
 * FIXME: Add support for a+b+c type syntax
113 114
 */

115
void WCMD_copy (void) {
116

117 118 119
  WIN32_FIND_DATA fd;
  HANDLE hff;
  BOOL force, status;
120
  WCHAR outpath[MAX_PATH], srcpath[MAX_PATH], copycmd[3];
121
  DWORD len;
122
  static const WCHAR copyCmdW[] = {'C','O','P','Y','C','M','D','\0'};
123 124 125 126 127 128 129 130
  BOOL copyToDir = FALSE;
  BOOL copyFromDir = FALSE;
  WCHAR srcspec[MAX_PATH];
  DWORD attribs;
  WCHAR drive[10];
  WCHAR dir[MAX_PATH];
  WCHAR fname[MAX_PATH];
  WCHAR ext[MAX_PATH];
131

132
  if (param1[0] == 0x00) {
133
    WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
134 135 136
    return;
  }

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  /* Convert source into full spec */
  WINE_TRACE("Copy source (supplied): '%s'\n", wine_dbgstr_w(param1));
  GetFullPathName (param1, sizeof(srcpath)/sizeof(WCHAR), srcpath, NULL);
  if (srcpath[strlenW(srcpath) - 1] == '\\')
      srcpath[strlenW(srcpath) - 1] = '\0';

  if ((strchrW(srcpath,'*') == NULL) && (strchrW(srcpath,'?') == NULL)) {
    attribs = GetFileAttributes(srcpath);
  } else {
    attribs = 0;
  }
  strcpyW(srcspec, srcpath);

  /* If a directory, then add \* on the end when searching */
  if (attribs & FILE_ATTRIBUTE_DIRECTORY) {
    strcatW(srcpath, slashW);
    copyFromDir = TRUE;
    strcatW(srcspec, slashW);
    strcatW(srcspec, starW);
  } else {
    WCMD_splitpath(srcpath, drive, dir, fname, ext);
    strcpyW(srcpath, drive);
    strcatW(srcpath, dir);
160
  }
161

162 163
  WINE_TRACE("Copy source (calculated): path: '%s'\n", wine_dbgstr_w(srcpath));

164
  /* If no destination supplied, assume current directory */
165
  WINE_TRACE("Copy destination (supplied): '%s'\n", wine_dbgstr_w(param2));
166
  if (param2[0] == 0x00) {
167
      strcpyW(param2, dotW);
168 169
  }

170 171 172
  GetFullPathName (param2, sizeof(outpath)/sizeof(WCHAR), outpath, NULL);
  if (outpath[strlenW(outpath) - 1] == '\\')
      outpath[strlenW(outpath) - 1] = '\0';
173
  attribs = GetFileAttributes(outpath);
174
  if (attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY)) {
175 176
    strcatW (outpath, slashW);
    copyToDir = TRUE;
177
  }
178 179
  WINE_TRACE("Copy destination (calculated): '%s'(%d)\n",
             wine_dbgstr_w(outpath), copyToDir);
180

181
  /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
182
  if (strstrW (quals, parmNoY))
183
    force = FALSE;
184
  else if (strstrW (quals, parmY))
185 186
    force = TRUE;
  else {
187 188
    len = GetEnvironmentVariable (copyCmdW, copycmd, sizeof(copycmd)/sizeof(WCHAR));
    force = (len && len < (sizeof(copycmd)/sizeof(WCHAR)) && ! lstrcmpiW (copycmd, parmY));
189 190
  }

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  /* Loop through all source files */
  WINE_TRACE("Searching for: '%s'\n", wine_dbgstr_w(srcspec));
  hff = FindFirstFile (srcspec, &fd);
  if (hff != INVALID_HANDLE_VALUE) {
      do {
        WCHAR outname[MAX_PATH];
        WCHAR srcname[MAX_PATH];
        BOOL  overwrite = force;

        /* Destination is either supplied filename, or source name in
           supplied destination directory                             */
        strcpyW(outname, outpath);
        if (copyToDir) strcatW(outname, fd.cFileName);
        strcpyW(srcname, srcpath);
        strcatW(srcname, fd.cFileName);

        WINE_TRACE("Copying from : '%s'\n", wine_dbgstr_w(srcname));
        WINE_TRACE("Copying to : '%s'\n", wine_dbgstr_w(outname));

        /* Skip . and .., and directories */
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
          overwrite = FALSE;
          WINE_TRACE("Skipping directories\n");
        }

        /* Prompt before overwriting */
        else if (!overwrite) {
          attribs = GetFileAttributes(outname);
          if (attribs != INVALID_FILE_ATTRIBUTES) {
            WCHAR buffer[MAXSTRING];
            wsprintf(buffer, WCMD_LoadMessage(WCMD_OVERWRITE), outname);
            overwrite = WCMD_ask_confirm(buffer, FALSE, NULL);
          }
          else overwrite = TRUE;
        }

        /* Do the copy as appropriate */
        if (overwrite) {
          status = CopyFile (srcname, outname, FALSE);
          if (!status) WCMD_print_error ();
        }

      } while (FindNextFile(hff, &fd) != 0);
234
      FindClose (hff);
235 236 237
  } else {
      status = ERROR_FILE_NOT_FOUND;
      WCMD_print_error ();
238 239 240 241 242 243 244
  }
}

/****************************************************************************
 * WCMD_create_dir
 *
 * Create a directory.
245 246 247
 *
 * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
 * they do not already exist.
248 249
 */

250
static BOOL create_full_path(WCHAR* path)
251 252
{
    int len;
253
    WCHAR *new_path;
254 255
    BOOL ret = TRUE;

256 257
    new_path = HeapAlloc(GetProcessHeap(),0,(strlenW(path) * sizeof(WCHAR))+1);
    strcpyW(new_path,path);
258

259
    while ((len = strlenW(new_path)) && new_path[len - 1] == '\\')
260 261 262 263
        new_path[len - 1] = 0;

    while (!CreateDirectory(new_path,NULL))
    {
264
        WCHAR *slash;
265 266 267 268 269 270 271 272 273 274
        DWORD last_error = GetLastError();
        if (last_error == ERROR_ALREADY_EXISTS)
            break;

        if (last_error != ERROR_PATH_NOT_FOUND)
        {
            ret = FALSE;
            break;
        }

275
        if (!(slash = strrchrW(new_path,'\\')) && ! (slash = strrchrW(new_path,'/')))
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        {
            ret = FALSE;
            break;
        }

        len = slash - new_path;
        new_path[len] = 0;
        if (!create_full_path(new_path))
        {
            ret = FALSE;
            break;
        }
        new_path[len] = '\\';
    }
    HeapFree(GetProcessHeap(),0,new_path);
    return ret;
}

294
void WCMD_create_dir (void) {
295

296
    if (param1[0] == 0x00) {
297
        WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
298 299
        return;
    }
300
    if (!create_full_path(param1)) WCMD_print_error ();
301 302 303 304 305 306 307
}

/****************************************************************************
 * WCMD_delete
 *
 * Delete a file or wildcarded set.
 *
308 309 310 311 312 313
 * Note on /A:
 *  - Testing shows /A is repeatable, eg. /a-r /ar matches all files
 *  - Each set is a pattern, eg /ahr /as-r means
 *         readonly+hidden OR nonreadonly system files
 *  - The '-' applies to a single field, ie /a:-hr means read only
 *         non-hidden files
314 315
 */

316
BOOL WCMD_delete (WCHAR *command, BOOL expectDir) {
317

318 319
    int   argno         = 0;
    int   argsProcessed = 0;
320
    WCHAR *argN          = command;
321
    BOOL  foundAny      = FALSE;
322 323 324 325 326
    static const WCHAR parmA[] = {'/','A','\0'};
    static const WCHAR parmQ[] = {'/','Q','\0'};
    static const WCHAR parmP[] = {'/','P','\0'};
    static const WCHAR parmS[] = {'/','S','\0'};
    static const WCHAR parmF[] = {'/','F','\0'};
327 328 329

    /* If not recursing, clear error flag */
    if (expectDir) errorlevel = 0;
330

331 332
    /* Loop through all args */
    while (argN) {
333 334
      WCHAR *thisArg = WCMD_parameter (command, argno++, &argN);
      WCHAR argCopy[MAX_PATH];
335

336
      if (argN && argN[0] != '/') {
337

338 339
        WIN32_FIND_DATA fd;
        HANDLE hff;
340 341
        WCHAR fpath[MAX_PATH];
        WCHAR *p;
342 343
        BOOL handleParm = TRUE;
        BOOL found = FALSE;
344
        static const WCHAR anyExt[]= {'.','*','\0'};
345

346 347 348
        strcpyW(argCopy, thisArg);
        WINE_TRACE("del: Processing arg %s (quals:%s)\n",
                   wine_dbgstr_w(argCopy), wine_dbgstr_w(quals));
349
        argsProcessed++;
350

351 352
        /* If filename part of parameter is * or *.*, prompt unless
           /Q supplied.                                            */
353
        if ((strstrW (quals, parmQ) == NULL) && (strstrW (quals, parmP) == NULL)) {
354

355 356 357 358
          WCHAR drive[10];
          WCHAR dir[MAX_PATH];
          WCHAR fname[MAX_PATH];
          WCHAR ext[MAX_PATH];
359

360
          /* Convert path into actual directory spec */
361
          GetFullPathName (argCopy, sizeof(fpath)/sizeof(WCHAR), fpath, NULL);
362
          WCMD_splitpath(fpath, drive, dir, fname, ext);
363

364
          /* Only prompt for * and *.*, not *a, a*, *.a* etc */
365 366
          if ((strcmpW(fname, starW) == 0) &&
              (*ext == 0x00 || (strcmpW(ext, anyExt) == 0))) {
367
            BOOL  ok;
368 369
            WCHAR  question[MAXSTRING];
            static const WCHAR fmt[] = {'%','s',' ','\0'};
370

371 372 373
            /* Note: Flag as found, to avoid file not found message */
            found = TRUE;

374
            /* Ask for confirmation */
375
            wsprintf(question, fmt, fpath);
376
            ok = WCMD_ask_confirm(question, TRUE, NULL);
377

378 379 380 381
            /* Abort if answer is 'N' */
            if (!ok) continue;
          }
        }
382

383 384
        /* First, try to delete in the current directory */
        hff = FindFirstFile (argCopy, &fd);
385
        if (hff == INVALID_HANDLE_VALUE) {
386 387 388
          handleParm = FALSE;
        } else {
          found = TRUE;
389
        }
390

391
        /* Support del <dirname> by just deleting all files dirname\* */
392
        if (handleParm && (strchrW(argCopy,'*') == NULL) && (strchrW(argCopy,'?') == NULL)
393
		&& (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
394 395 396 397 398
          WCHAR modifiedParm[MAX_PATH];
          static const WCHAR slashStar[] = {'\\','*','\0'};

          strcpyW(modifiedParm, argCopy);
          strcatW(modifiedParm, slashStar);
399
          FindClose(hff);
400 401
          found = TRUE;
          WCMD_delete(modifiedParm, FALSE);
402

403
        } else if (handleParm) {
404 405

          /* Build the filename to delete as <supplied directory>\<findfirst filename> */
406
          strcpyW (fpath, argCopy);
407
          do {
408
            p = strrchrW (fpath, '\\');
409 410
            if (p != NULL) {
              *++p = '\0';
411
              strcatW (fpath, fd.cFileName);
412
            }
413
            else strcpyW (fpath, fd.cFileName);
414 415
            if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
              BOOL  ok = TRUE;
416
              WCHAR *nextA = strstrW (quals, parmA);
417 418 419 420 421 422

              /* Handle attribute matching (/A) */
              if (nextA != NULL) {
                ok = FALSE;
                while (nextA != NULL && !ok) {

423
                  WCHAR *thisA = (nextA+2);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
                  BOOL  stillOK = TRUE;

                  /* Skip optional : */
                  if (*thisA == ':') thisA++;

                  /* Parse each of the /A[:]xxx in turn */
                  while (*thisA && *thisA != '/') {
                    BOOL negate    = FALSE;
                    BOOL attribute = FALSE;

                    /* Match negation of attribute first */
                    if (*thisA == '-') {
                      negate=TRUE;
                      thisA++;
                    }

                    /* Match attribute */
                    switch (*thisA) {
                    case 'R': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
                              break;
                    case 'H': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
                              break;
                    case 'S': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM);
                              break;
                    case 'A': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE);
                              break;
                    default:
451
                        WCMD_output (WCMD_LoadMessage(WCMD_SYNTAXERR));
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                    }

                    /* Now check result, keeping a running boolean about whether it
                       matches all parsed attribues so far                         */
                    if (attribute && !negate) {
                        stillOK = stillOK;
                    } else if (!attribute && negate) {
                        stillOK = stillOK;
                    } else {
                        stillOK = FALSE;
                    }
                    thisA++;
                  }

                  /* Save the running total as the final result */
                  ok = stillOK;

                  /* Step on to next /A set */
470
                  nextA = strstrW (nextA+1, parmA);
471 472
                }
              }
473

474
              /* /P means prompt for each file */
475 476
              if (ok && strstrW (quals, parmP) != NULL) {
                WCHAR  question[MAXSTRING];
477

478
                /* Ask for confirmation */
479
                wsprintf(question, WCMD_LoadMessage(WCMD_DELPROMPT), fpath);
480
                ok = WCMD_ask_confirm(question, FALSE, NULL);
481
              }
482

483 484
              /* Only proceed if ok to */
              if (ok) {
485

486 487
                /* If file is read only, and /F supplied, delete it */
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
488
                    strstrW (quals, parmF) != NULL) {
489 490
                    SetFileAttributes(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
                }
491

492 493 494
                /* Now do the delete */
                if (!DeleteFile (fpath)) WCMD_print_error ();
              }
495

496 497 498
            }
          } while (FindNextFile(hff, &fd) != 0);
          FindClose (hff);
499
        }
500

501
        /* Now recurse into all subdirectories handling the parameter in the same way */
502
        if (strstrW (quals, parmS) != NULL) {
503

504
          WCHAR thisDir[MAX_PATH];
505 506
          int cPos;

507 508 509 510
          WCHAR drive[10];
          WCHAR dir[MAX_PATH];
          WCHAR fname[MAX_PATH];
          WCHAR ext[MAX_PATH];
511 512

          /* Convert path into actual directory spec */
513
          GetFullPathName (argCopy, sizeof(thisDir)/sizeof(WCHAR), thisDir, NULL);
514 515
          WCMD_splitpath(thisDir, drive, dir, fname, ext);

516 517 518
          strcpyW(thisDir, drive);
          strcatW(thisDir, dir);
          cPos = strlenW(thisDir);
519

520
          WINE_TRACE("Searching recursively in '%s'\n", wine_dbgstr_w(thisDir));
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

          /* Append '*' to the directory */
          thisDir[cPos] = '*';
          thisDir[cPos+1] = 0x00;

          hff = FindFirstFile (thisDir, &fd);

          /* Remove residual '*' */
          thisDir[cPos] = 0x00;

          if (hff != INVALID_HANDLE_VALUE) {
            DIRECTORY_STACK *allDirs = NULL;
            DIRECTORY_STACK *lastEntry = NULL;

            do {
              if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
537 538
                  (strcmpW(fd.cFileName, dotdotW) != 0) &&
                  (strcmpW(fd.cFileName, dotW) != 0)) {
539 540

                DIRECTORY_STACK *nextDir;
541
                WCHAR subParm[MAX_PATH];
542 543

                /* Work out search parameter in sub dir */
544 545 546 547 548 549
                strcpyW (subParm, thisDir);
                strcatW (subParm, fd.cFileName);
                strcatW (subParm, slashW);
                strcatW (subParm, fname);
                strcatW (subParm, ext);
                WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(subParm));
550 551

                /* Allocate memory, add to list */
552
                nextDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
553 554 555 556
                if (allDirs == NULL) allDirs = nextDir;
                if (lastEntry != NULL) lastEntry->next = nextDir;
                lastEntry = nextDir;
                nextDir->next = NULL;
557 558 559
                nextDir->dirName = HeapAlloc(GetProcessHeap(),0,
                                             (strlenW(subParm)+1) * sizeof(WCHAR));
                strcpyW(nextDir->dirName, subParm);
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
              }
            } while (FindNextFile(hff, &fd) != 0);
            FindClose (hff);

            /* Go through each subdir doing the delete */
            while (allDirs != NULL) {
              DIRECTORY_STACK *tempDir;

              tempDir = allDirs->next;
              found |= WCMD_delete (allDirs->dirName, FALSE);

              HeapFree(GetProcessHeap(),0,allDirs->dirName);
              HeapFree(GetProcessHeap(),0,allDirs);
              allDirs = tempDir;
            }
          }
        }
        /* Keep running total to see if any found, and if not recursing
           issue error message                                         */
        if (expectDir) {
          if (!found) {
            errorlevel = 1;
582
            WCMD_output (WCMD_LoadMessage(WCMD_FILENOTFOUND), argCopy);
583 584 585
          }
        }
        foundAny |= found;
586
      }
587 588 589 590
    }

    /* Handle no valid args */
    if (argsProcessed == 0) {
591
      WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
592
    }
593 594

    return foundAny;
595 596 597 598 599 600 601 602 603
}

/****************************************************************************
 * WCMD_echo
 *
 * Echo input to the screen (or not). We don't try to emulate the bugs
 * in DOS (try typing "ECHO ON AGAIN" for an example).
 */

604
void WCMD_echo (const WCHAR *command) {
605

606
  int count;
607

608 609 610 611 612 613
  if ((command[0] == '.') && (command[1] == 0)) {
    WCMD_output (newline);
    return;
  }
  if (command[0]==' ')
    command++;
614
  count = strlenW(command);
615
  if (count == 0) {
616 617
    if (echo_mode) WCMD_output (WCMD_LoadMessage(WCMD_ECHOPROMPT), onW);
    else WCMD_output (WCMD_LoadMessage(WCMD_ECHOPROMPT), offW);
618 619
    return;
  }
620
  if (lstrcmpiW(command, onW) == 0) {
621 622 623
    echo_mode = 1;
    return;
  }
624
  if (lstrcmpiW(command, offW) == 0) {
625 626 627
    echo_mode = 0;
    return;
  }
628
  WCMD_output_asis (command);
629 630 631 632
  WCMD_output (newline);

}

633
/**************************************************************************
634 635 636
 * WCMD_for
 *
 * Batch file loop processing.
637 638 639 640 641 642
 *
 * On entry: cmdList       contains the syntax up to the set
 *           next cmdList and all in that bracket contain the set data
 *           next cmdlist  contains the DO cmd
 *           following that is either brackets or && entries (as per if)
 *
643 644
 */

645
void WCMD_for (WCHAR *p, CMD_LIST **cmdList) {
646

647 648 649
  WIN32_FIND_DATA fd;
  HANDLE hff;
  int i;
650 651
  const WCHAR inW[] = {'i', 'n', ' ', '\0'};
  const WCHAR doW[] = {'d', 'o', ' ', '\0'};
652 653 654 655 656
  CMD_LIST *setStart, *thisSet, *cmdStart, *cmdEnd;
  WCHAR variable[4];
  WCHAR *firstCmd;
  int thisDepth;

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
  WCHAR *curPos = p;
  BOOL   expandDirs  = FALSE;
  BOOL   useNumbers  = FALSE;
  BOOL   doRecursive = FALSE;
  BOOL   doFileset   = FALSE;
  LONG   numbers[3] = {0,0,0}; /* Defaults to 0 in native */
  int    itemNum;
  CMD_LIST *thisCmdStart;


  /* Handle optional qualifiers (multiple are allowed) */
  while (*curPos && *curPos == '/') {
      WINE_TRACE("Processing qualifier at %s\n", wine_dbgstr_w(curPos));
      curPos++;
      switch (toupperW(*curPos)) {
      case 'D': curPos++; expandDirs = TRUE; break;
      case 'L': curPos++; useNumbers = TRUE; break;

      /* Recursive is special case - /R can have an optional path following it                */
      /* filenamesets are another special case - /F can have an optional options following it */
      case 'R':
      case 'F':
          {
              BOOL isRecursive = (*curPos == 'R');

              if (isRecursive) doRecursive = TRUE;
              else doFileset = TRUE;

              /* Skip whitespace */
              curPos++;
              while (*curPos && *curPos==' ') curPos++;

              /* Next parm is either qualifier, path/options or variable -
                 only care about it if it is the path/options              */
              if (*curPos && *curPos != '/' && *curPos != '%') {
                  if (isRecursive) WINE_FIXME("/R needs to handle supplied root\n");
                  else WINE_FIXME("/F needs to handle options\n");
              }
              break;
          }
      default:
          WINE_FIXME("for qualifier '%c' unhandled\n", *curPos);
          curPos++;
      }

      /* Skip whitespace between qualifiers */
      while (*curPos && *curPos==' ') curPos++;
  }

  /* Skip whitespace before variable */
  while (*curPos && *curPos==' ') curPos++;

  /* Ensure line continues with variable */
  if (!*curPos || *curPos != '%') {
      WCMD_output (WCMD_LoadMessage(WCMD_SYNTAXERR));
      return;
  }

  /* Variable should follow */
  i = 0;
  while (curPos[i] && curPos[i]!=' ') i++;
  memcpy(&variable[0], curPos, i*sizeof(WCHAR));
  variable[i] = 0x00;
  WINE_TRACE("Variable identified as %s\n", wine_dbgstr_w(variable));
  curPos = &curPos[i];

  /* Skip whitespace before IN */
  while (*curPos && *curPos==' ') curPos++;

  /* Ensure line continues with IN */
  if (!*curPos || lstrcmpiW (curPos, inW)) {
      WCMD_output (WCMD_LoadMessage(WCMD_SYNTAXERR));
      return;
730
  }
731

732 733 734 735 736 737 738 739 740 741 742 743 744
  /* Save away where the set of data starts and the variable */
  thisDepth = (*cmdList)->bracketDepth;
  *cmdList = (*cmdList)->nextcommand;
  setStart = (*cmdList);

  /* Skip until the close bracket */
  WINE_TRACE("Searching %p as the set\n", *cmdList);
  while (*cmdList &&
         (*cmdList)->command != NULL &&
         (*cmdList)->bracketDepth > thisDepth) {
    WINE_TRACE("Skipping %p which is part of the set\n", *cmdList);
    *cmdList = (*cmdList)->nextcommand;
  }
745

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
  /* Skip the close bracket, if there is one */
  if (*cmdList) *cmdList = (*cmdList)->nextcommand;

  /* Syntax error if missing close bracket, or nothing following it
     and once we have the complete set, we expect a DO              */
  WINE_TRACE("Looking for 'do' in %p\n", *cmdList);
  if ((*cmdList == NULL) ||
      (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
                            (*cmdList)->command, 3, doW, -1) != 2)) {
      WCMD_output (WCMD_LoadMessage(WCMD_SYNTAXERR));
      return;
  }

  /* Save away the starting position for the commands (and offset for the
     first one                                                           */
  cmdStart = *cmdList;
  cmdEnd   = *cmdList;
  firstCmd = (*cmdList)->command + 3; /* Skip 'do ' */
764
  itemNum  = 0;
765 766 767 768 769 770 771 772 773

  thisSet = setStart;
  /* Loop through all set entries */
  while (thisSet &&
         thisSet->command != NULL &&
         thisSet->bracketDepth >= thisDepth) {

    /* Loop through all entries on the same line */
    WCHAR *item;
774
    WCHAR *itemStart;
775 776 777

    WINE_TRACE("Processing for set %p\n", thisSet);
    i = 0;
778
    while (*(item = WCMD_parameter (thisSet->command, i, &itemStart))) {
779 780 781 782 783 784

      /*
       * If the parameter within the set has a wildcard then search for matching files
       * otherwise do a literal substitution.
       */
      static const WCHAR wildcards[] = {'*','?','\0'};
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
      thisCmdStart = cmdStart;

      itemNum++;
      WINE_TRACE("Processing for item %d '%s'\n", itemNum, wine_dbgstr_w(item));

      if (!useNumbers && !doFileset) {
          if (strpbrkW (item, wildcards)) {
            hff = FindFirstFile (item, &fd);
            if (hff != INVALID_HANDLE_VALUE) {
              do {
                BOOL isDirectory = FALSE;

                if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) isDirectory = TRUE;

                /* Handle as files or dirs appropriately, but ignore . and .. */
                if (isDirectory == expandDirs &&
                    (strcmpW(fd.cFileName, dotdotW) != 0) &&
                    (strcmpW(fd.cFileName, dotW) != 0))
                {
                  thisCmdStart = cmdStart;
                  WINE_TRACE("Processing FOR filename %s\n", wine_dbgstr_w(fd.cFileName));
                  WCMD_part_execute (&thisCmdStart, firstCmd, variable,
                                               fd.cFileName, FALSE, TRUE);
                }
809

810 811
              } while (FindNextFile(hff, &fd) != 0);
              FindClose (hff);
812
            }
813 814 815
          } else {
            WCMD_part_execute(&thisCmdStart, firstCmd, variable, item, FALSE, TRUE);
          }
816

817 818 819 820 821
      } else if (useNumbers) {
          /* Convert the first 3 numbers to signed longs and save */
          if (itemNum <=3) numbers[itemNum-1] = atolW(item);
          /* else ignore them! */

822 823
      /* Filesets - either a list of files, or a command to run and parse the output */
      } else if (doFileset && *itemStart != '"') {
824 825

          HANDLE input;
826
          WCHAR temp_file[MAX_PATH];
827 828 829 830

          WINE_TRACE("Processing for filespec from item %d '%s'\n", itemNum,
                     wine_dbgstr_w(item));

831 832 833
          /* If backquote or single quote, we need to launch that command
             and parse the results - use a temporary file                 */
          if (*itemStart == '`' || *itemStart == '\'') {
834

835
              WCHAR temp_path[MAX_PATH], temp_cmd[MAXSTRING];
836
              static const WCHAR redirOut[] = {'>','%','s','\0'};
837 838 839 840 841 842 843 844 845 846 847
              static const WCHAR cmdW[]     = {'C','M','D','\0'};

              /* Remove trailing character */
              itemStart[strlenW(itemStart)-1] = 0x00;

              /* Get temp filename */
              GetTempPath (sizeof(temp_path)/sizeof(WCHAR), temp_path);
              GetTempFileName (temp_path, cmdW, 0, temp_file);

              /* Execute program and redirect output */
              wsprintf (temp_cmd, redirOut, (itemStart+1), temp_file);
848
              WCMD_execute (itemStart, temp_cmd, NULL, NULL, NULL);
849 850 851 852 853 854 855 856 857 858 859 860

              /* Open the file, read line by line and process */
              input = CreateFile (temp_file, GENERIC_READ, FILE_SHARE_READ,
                                  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
          } else {

              /* Open the file, read line by line and process */
              input = CreateFile (item, GENERIC_READ, FILE_SHARE_READ,
                                  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
          }

          /* Process the input file */
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
          if (input == INVALID_HANDLE_VALUE) {
            WCMD_print_error ();
            WCMD_output (WCMD_LoadMessage(WCMD_READFAIL), item);
            errorlevel = 1;
            return; /* FOR loop aborts at first failure here */

          } else {

            WCHAR buffer[MAXSTRING] = {'\0'};
            WCHAR *where, *parm;

            while (WCMD_fgets (buffer, sizeof(buffer)/sizeof(WCHAR), input)) {

              /* Skip blank lines*/
              parm = WCMD_parameter (buffer, 0, &where);
              WINE_TRACE("Parsed parameter: %s from %s\n", wine_dbgstr_w(parm),
                         wine_dbgstr_w(buffer));

              if (where) {
880 881
                  /* FIXME: The following should be moved into its own routine and
                     reused for the string literal parsing below                  */
882 883 884 885 886 887 888 889 890 891
                  thisCmdStart = cmdStart;
                  WCMD_part_execute(&thisCmdStart, firstCmd, variable, parm, FALSE, TRUE);
                  cmdEnd = thisCmdStart;
              }

              buffer[0] = 0x00;

            }
            CloseHandle (input);
          }
892

893 894 895 896 897
          /* Delete the temporary file */
          if (*itemStart == '`' || *itemStart == '\'') {
              DeleteFile (temp_file);
          }

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
      /* Filesets - A string literal */
      } else if (doFileset && *itemStart == '"') {
          WCHAR buffer[MAXSTRING] = {'\0'};
          WCHAR *where, *parm;

          /* Skip blank lines, and re-extract parameter now string has quotes removed */
          strcpyW(buffer, item);
          parm = WCMD_parameter (buffer, 0, &where);
          WINE_TRACE("Parsed parameter: %s from %s\n", wine_dbgstr_w(parm),
                       wine_dbgstr_w(buffer));

          if (where) {
              /* FIXME: The following should be moved into its own routine and
                 reused for the string literal parsing below                  */
              thisCmdStart = cmdStart;
              WCMD_part_execute(&thisCmdStart, firstCmd, variable, parm, FALSE, TRUE);
              cmdEnd = thisCmdStart;
          }
916
      }
917 918 919 920

      WINE_TRACE("Post-command, cmdEnd = %p\n", cmdEnd);
      cmdEnd = thisCmdStart;
      i++;
921
    }
922 923 924 925 926

    /* Move onto the next set line */
    thisSet = thisSet->nextcommand;
  }

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
  /* If /L is provided, now run the for loop */
  if (useNumbers) {
      WCHAR thisNum[20];
      static const WCHAR fmt[] = {'%','d','\0'};

      WINE_TRACE("FOR /L provided range from %d to %d step %d\n",
                 numbers[0], numbers[2], numbers[1]);
      for (i=numbers[0];
           (numbers[1]<0)? i>numbers[2] : i<numbers[2];
           i=i + numbers[1]) {

          sprintfW(thisNum, fmt, i);
          WINE_TRACE("Processing FOR number %s\n", wine_dbgstr_w(thisNum));

          thisCmdStart = cmdStart;
          WCMD_part_execute(&thisCmdStart, firstCmd, variable, thisNum, FALSE, TRUE);
          cmdEnd = thisCmdStart;
      }
  }

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
  /* When the loop ends, either something like a GOTO or EXIT /b has terminated
     all processing, OR it should be pointing to the end of && processing OR
     it should be pointing at the NULL end of bracket for the DO. The return
     value needs to be the NEXT command to execute, which it either is, or
     we need to step over the closing bracket                                  */
  *cmdList = cmdEnd;
  if (cmdEnd && cmdEnd->command == NULL) *cmdList = cmdEnd->nextcommand;
}


/*****************************************************************************
 * WCMD_part_execute
 *
 * Execute a command, and any && or bracketed follow on to the command. The
 * first command to be executed may not be at the front of the
962
 * commands->thiscommand string (eg. it may point after a DO or ELSE)
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
 */
void WCMD_part_execute(CMD_LIST **cmdList, WCHAR *firstcmd, WCHAR *variable,
                       WCHAR *value, BOOL isIF, BOOL conditionTRUE) {

  CMD_LIST *curPosition = *cmdList;
  int myDepth = (*cmdList)->bracketDepth;

  WINE_TRACE("cmdList(%p), firstCmd(%p), with '%s'='%s', doIt(%d)\n",
             cmdList, wine_dbgstr_w(firstcmd),
             wine_dbgstr_w(variable), wine_dbgstr_w(value),
             conditionTRUE);

  /* Skip leading whitespace between condition and the command */
  while (firstcmd && *firstcmd && (*firstcmd==' ' || *firstcmd=='\t')) firstcmd++;

  /* Process the first command, if there is one */
  if (conditionTRUE && firstcmd && *firstcmd) {
    WCHAR *command = WCMD_strdupW(firstcmd);
981
    WCMD_execute (firstcmd, (*cmdList)->redirects, variable, value, cmdList);
982 983 984 985
    free (command);
  }


986
  /* If it didn't move the position, step to next command */
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;

  /* Process any other parts of the command */
  if (*cmdList) {
    BOOL processThese = TRUE;

    if (isIF) processThese = conditionTRUE;

    while (*cmdList) {
      const WCHAR ifElse[] = {'e','l','s','e',' ','\0'};

      /* execute all appropriate commands */
      curPosition = *cmdList;

      WINE_TRACE("Processing cmdList(%p) - &(%d) bd(%d / %d)\n",
                 *cmdList,
                 (*cmdList)->isAmphersand,
                 (*cmdList)->bracketDepth, myDepth);

      /* Execute any appended to the statement with &&'s */
      if ((*cmdList)->isAmphersand) {
        if (processThese) {
1009 1010
          WCMD_execute ((*cmdList)->command, (*cmdList)->redirects, variable,
                        value, cmdList);
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        }
        if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;

      /* Execute any appended to the statement with (...) */
      } else if ((*cmdList)->bracketDepth > myDepth) {
        if (processThese) {
          *cmdList = WCMD_process_commands(*cmdList, TRUE, variable, value);
          WINE_TRACE("Back from processing commands, (next = %p)\n", *cmdList);
        }
        if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;

      /* End of the command - does 'ELSE ' follow as the next command? */
      } else {
        if (isIF && CompareString (LOCALE_USER_DEFAULT,
                                   NORM_IGNORECASE | SORT_STRINGSORT,
                           (*cmdList)->command, 5, ifElse, -1) == 2) {

          /* Swap between if and else processing */
          processThese = !processThese;

          /* Process the ELSE part */
          if (processThese) {
            WCHAR *cmd = ((*cmdList)->command) + strlenW(ifElse);

            /* Skip leading whitespace between condition and the command */
            while (*cmd && (*cmd==' ' || *cmd=='\t')) cmd++;
            if (*cmd) {
1038
              WCMD_execute (cmd, (*cmdList)->redirects, variable, value, cmdList);
1039 1040 1041 1042 1043 1044 1045 1046
            }
          }
          if (curPosition == *cmdList) *cmdList = (*cmdList)->nextcommand;
        } else {
          WINE_TRACE("Found end of this IF statement (next = %p)\n", *cmdList);
          break;
        }
      }
1047 1048
    }
  }
1049
  return;
1050 1051
}

1052 1053 1054 1055 1056 1057
/**************************************************************************
 * WCMD_give_help
 *
 *	Simple on-line help. Help text is stored in the resource file.
 */

1058
void WCMD_give_help (WCHAR *command) {
1059

1060
  int i;
1061 1062

  command = WCMD_strtrim_leading_spaces(command);
1063
  if (strlenW(command) == 0) {
1064
    WCMD_output_asis (WCMD_LoadMessage(WCMD_ALLHELP));
1065 1066 1067 1068
  }
  else {
    for (i=0; i<=WCMD_EXIT; i++) {
      if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1069
	  param1, -1, inbuilt[i], -1) == 2) {
1070
	WCMD_output_asis (WCMD_LoadMessage(i));
1071
	return;
1072 1073
      }
    }
1074
    WCMD_output (WCMD_LoadMessage(WCMD_NOCMDHELP), param1);
1075 1076 1077 1078
  }
  return;
}

1079 1080 1081 1082 1083 1084 1085 1086 1087
/****************************************************************************
 * WCMD_go_to
 *
 * Batch file jump instruction. Not the most efficient algorithm ;-)
 * Prints error message if the specified label cannot be found - the file pointer is
 * then at EOF, effectively stopping the batch file.
 * FIXME: DOS is supposed to allow labels with spaces - we don't.
 */

1088
void WCMD_goto (CMD_LIST **cmdList) {
1089

1090
  WCHAR string[MAX_PATH];
1091

1092
  /* Do not process any more parts of a processed multipart or multilines command */
1093
  if (cmdList) *cmdList = NULL;
1094

1095
  if (param1[0] == 0x00) {
1096
    WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
1097 1098
    return;
  }
1099
  if (context != NULL) {
1100 1101
    WCHAR *paramStart = param1;
    static const WCHAR eofW[] = {':','e','o','f','\0'};
1102 1103

    /* Handle special :EOF label */
1104
    if (lstrcmpiW (eofW, param1) == 0) {
1105 1106 1107 1108
      context -> skip_rest = TRUE;
      return;
    }

1109 1110 1111
    /* Support goto :label as well as goto label */
    if (*paramStart == ':') paramStart++;

1112
    SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
1113 1114
    while (WCMD_fgets (string, sizeof(string)/sizeof(WCHAR), context -> h)) {
      if ((string[0] == ':') && (lstrcmpiW (&string[1], paramStart) == 0)) return;
1115
    }
1116
    WCMD_output (WCMD_LoadMessage(WCMD_NOTARGET));
1117 1118 1119 1120
  }
  return;
}

1121 1122 1123 1124 1125 1126
/*****************************************************************************
 * WCMD_pushd
 *
 *	Push a directory onto the stack
 */

1127
void WCMD_pushd (WCHAR *command) {
1128 1129
    struct env_stack *curdir;
    WCHAR *thisdir;
1130
    static const WCHAR parmD[] = {'/','D','\0'};
1131

1132
    if (strchrW(command, '/') != NULL) {
1133 1134 1135 1136 1137
      SetLastError(ERROR_INVALID_PARAMETER);
      WCMD_print_error();
      return;
    }

1138 1139 1140 1141 1142
    curdir  = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
    thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
    if( !curdir || !thisdir ) {
      LocalFree(curdir);
      LocalFree(thisdir);
1143
      WINE_ERR ("out of memory\n");
1144 1145 1146
      return;
    }

1147
    /* Change directory using CD code with /D parameter */
1148
    strcpyW(quals, parmD);
1149
    GetCurrentDirectoryW (1024, thisdir);
1150 1151 1152
    errorlevel = 0;
    WCMD_setshow_default(command);
    if (errorlevel) {
1153 1154 1155 1156 1157 1158
      LocalFree(curdir);
      LocalFree(thisdir);
      return;
    } else {
      curdir -> next    = pushd_directories;
      curdir -> strings = thisdir;
1159
      if (pushd_directories == NULL) {
1160
        curdir -> u.stackdepth = 1;
1161
      } else {
1162
        curdir -> u.stackdepth = pushd_directories -> u.stackdepth + 1;
1163
      }
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
      pushd_directories = curdir;
    }
}


/*****************************************************************************
 * WCMD_popd
 *
 *	Pop a directory from the stack
 */

void WCMD_popd (void) {
    struct env_stack *temp = pushd_directories;

    if (!pushd_directories)
      return;

    /* pop the old environment from the stack, and make it the current dir */
    pushd_directories = temp->next;
    SetCurrentDirectoryW(temp->strings);
    LocalFree (temp->strings);
    LocalFree (temp);
}
1187

1188 1189 1190 1191
/****************************************************************************
 * WCMD_if
 *
 * Batch file conditional.
1192 1193 1194 1195 1196 1197 1198 1199
 *
 * On entry, cmdlist will point to command containing the IF, and optionally
 *   the first command to execute (if brackets not found)
 *   If &&'s were found, this may be followed by a record flagged as isAmpersand
 *   If ('s were found, execute all within that bracket
 *   Command may optionally be followed by an ELSE - need to skip instructions
 *   in the else using the same logic
 *
1200
 * FIXME: Much more syntax checking needed!
1201 1202
 */

1203
void WCMD_if (WCHAR *p, CMD_LIST **cmdList) {
1204

1205
  int negate = 0, test = 0;
1206 1207 1208 1209 1210 1211 1212 1213
  WCHAR condition[MAX_PATH], *command, *s;
  static const WCHAR notW[]    = {'n','o','t','\0'};
  static const WCHAR errlvlW[] = {'e','r','r','o','r','l','e','v','e','l','\0'};
  static const WCHAR existW[]  = {'e','x','i','s','t','\0'};
  static const WCHAR defdW[]   = {'d','e','f','i','n','e','d','\0'};
  static const WCHAR eqeqW[]   = {'=','=','\0'};

  if (!lstrcmpiW (param1, notW)) {
1214
    negate = 1;
1215
    strcpyW (condition, param2);
1216
  }
1217
  else {
1218
    strcpyW (condition, param1);
1219
  }
1220 1221
  WINE_TRACE("Condition: %s\n", wine_dbgstr_w(condition));

1222 1223
  if (!lstrcmpiW (condition, errlvlW)) {
    if (errorlevel >= atoiW(WCMD_parameter (p, 1+negate, NULL))) test = 1;
1224
    WCMD_parameter (p, 2+negate, &command);
1225
  }
1226 1227
  else if (!lstrcmpiW (condition, existW)) {
    if (GetFileAttributes(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
1228
        test = 1;
1229
    }
1230
    WCMD_parameter (p, 2+negate, &command);
1231
  }
1232 1233
  else if (!lstrcmpiW (condition, defdW)) {
    if (GetEnvironmentVariable(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
1234 1235 1236 1237
        test = 1;
    }
    WCMD_parameter (p, 2+negate, &command);
  }
1238
  else if ((s = strstrW (p, eqeqW))) {
1239
    s += 2;
1240
    if (!lstrcmpiW (condition, WCMD_parameter (s, 0, NULL))) test = 1;
1241
    WCMD_parameter (s, 1, &command);
1242 1243
  }
  else {
1244
    WCMD_output (WCMD_LoadMessage(WCMD_SYNTAXERR));
1245 1246
    return;
  }
1247 1248 1249

  /* Process rest of IF statement which is on the same line
     Note: This may process all or some of the cmdList (eg a GOTO) */
1250
  WCMD_part_execute(cmdList, command, NULL, NULL, TRUE, (test != negate));
1251 1252 1253 1254 1255 1256 1257 1258
}

/****************************************************************************
 * WCMD_move
 *
 * Move a file, directory tree or wildcarded set of files.
 */

1259
void WCMD_move (void) {
1260

1261
  int             status;
1262
  WIN32_FIND_DATA fd;
1263
  HANDLE          hff;
1264 1265 1266 1267 1268 1269
  WCHAR            input[MAX_PATH];
  WCHAR            output[MAX_PATH];
  WCHAR            drive[10];
  WCHAR            dir[MAX_PATH];
  WCHAR            fname[MAX_PATH];
  WCHAR            ext[MAX_PATH];
1270

1271
  if (param1[0] == 0x00) {
1272
    WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
1273 1274 1275
    return;
  }

1276 1277
  /* If no destination supplied, assume current directory */
  if (param2[0] == 0x00) {
1278
      strcpyW(param2, dotW);
1279 1280 1281
  }

  /* If 2nd parm is directory, then use original filename */
1282
  /* Convert partial path to full path */
1283 1284 1285 1286
  GetFullPathName (param1, sizeof(input)/sizeof(WCHAR), input, NULL);
  GetFullPathName (param2, sizeof(output)/sizeof(WCHAR), output, NULL);
  WINE_TRACE("Move from '%s'('%s') to '%s'\n", wine_dbgstr_w(input),
             wine_dbgstr_w(param1), wine_dbgstr_w(output));
1287 1288 1289 1290 1291 1292

  /* Split into components */
  WCMD_splitpath(input, drive, dir, fname, ext);

  hff = FindFirstFile (input, &fd);
  while (hff != INVALID_HANDLE_VALUE) {
1293 1294
    WCHAR  dest[MAX_PATH];
    WCHAR  src[MAX_PATH];
1295 1296
    DWORD attribs;

1297
    WINE_TRACE("Processing file '%s'\n", wine_dbgstr_w(fd.cFileName));
1298 1299

    /* Build src & dest name */
1300 1301
    strcpyW(src, drive);
    strcatW(src, dir);
1302 1303 1304 1305 1306

    /* See if dest is an existing directory */
    attribs = GetFileAttributes(output);
    if (attribs != INVALID_FILE_ATTRIBUTES &&
       (attribs & FILE_ATTRIBUTE_DIRECTORY)) {
1307 1308 1309
      strcpyW(dest, output);
      strcatW(dest, slashW);
      strcatW(dest, fd.cFileName);
1310
    } else {
1311
      strcpyW(dest, output);
1312 1313
    }

1314
    strcatW(src, fd.cFileName);
1315

1316 1317
    WINE_TRACE("Source '%s'\n", wine_dbgstr_w(src));
    WINE_TRACE("Dest   '%s'\n", wine_dbgstr_w(dest));
1318 1319

    /* Check if file is read only, otherwise move it */
1320
    attribs = GetFileAttributes(src);
1321 1322 1323 1324 1325
    if ((attribs != INVALID_FILE_ATTRIBUTES) &&
        (attribs & FILE_ATTRIBUTE_READONLY)) {
      SetLastError(ERROR_ACCESS_DENIED);
      status = 0;
    } else {
1326 1327 1328
      BOOL ok = TRUE;

      /* If destination exists, prompt unless /Y supplied */
1329
      if (GetFileAttributes(dest) != INVALID_FILE_ATTRIBUTES) {
1330
        BOOL force = FALSE;
1331
        WCHAR copycmd[MAXSTRING];
1332 1333 1334
        int len;

        /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
1335
        if (strstrW (quals, parmNoY))
1336
          force = FALSE;
1337
        else if (strstrW (quals, parmY))
1338 1339
          force = TRUE;
        else {
1340 1341 1342 1343
          const WCHAR copyCmdW[] = {'C','O','P','Y','C','M','D','\0'};
          len = GetEnvironmentVariable (copyCmdW, copycmd, sizeof(copycmd)/sizeof(WCHAR));
          force = (len && len < (sizeof(copycmd)/sizeof(WCHAR))
                       && ! lstrcmpiW (copycmd, parmY));
1344 1345 1346 1347
        }

        /* Prompt if overwriting */
        if (!force) {
1348 1349
          WCHAR  question[MAXSTRING];
          WCHAR  yesChar[10];
1350

1351
          strcpyW(yesChar, WCMD_LoadMessage(WCMD_YES));
1352 1353

          /* Ask for confirmation */
1354
          wsprintf(question, WCMD_LoadMessage(WCMD_OVERWRITE), dest);
1355
          ok = WCMD_ask_confirm(question, FALSE, NULL);
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

          /* So delete the destination prior to the move */
          if (ok) {
            if (!DeleteFile (dest)) {
              WCMD_print_error ();
              errorlevel = 1;
              ok = FALSE;
            }
          }
        }
      }

      if (ok) {
        status = MoveFile (src, dest);
      } else {
        status = 1; /* Anything other than 0 to prevent error msg below */
      }
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    }

    if (!status) {
      WCMD_print_error ();
      errorlevel = 1;
    }

    /* Step on to next match */
    if (FindNextFile(hff, &fd) == 0) {
      FindClose(hff);
      hff = INVALID_HANDLE_VALUE;
      break;
    }
  }
1387 1388 1389 1390 1391 1392 1393 1394
}

/****************************************************************************
 * WCMD_pause
 *
 * Wait for keyboard input.
 */

1395
void WCMD_pause (void) {
1396

1397
  DWORD count;
1398
  WCHAR string[32];
1399 1400

  WCMD_output (anykey);
1401 1402
  WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), string,
                 sizeof(string)/sizeof(WCHAR), &count, NULL);
1403 1404 1405 1406 1407 1408 1409 1410
}

/****************************************************************************
 * WCMD_remove_dir
 *
 * Delete a directory.
 */

1411
void WCMD_remove_dir (WCHAR *command) {
1412

1413 1414
  int   argno         = 0;
  int   argsProcessed = 0;
1415 1416 1417
  WCHAR *argN          = command;
  static const WCHAR parmS[] = {'/','S','\0'};
  static const WCHAR parmQ[] = {'/','Q','\0'};
1418

1419 1420
  /* Loop through all args */
  while (argN) {
1421
    WCHAR *thisArg = WCMD_parameter (command, argno++, &argN);
1422
    if (argN && argN[0] != '/') {
1423 1424
      WINE_TRACE("rd: Processing arg %s (quals:%s)\n", wine_dbgstr_w(thisArg),
                 wine_dbgstr_w(quals));
1425
      argsProcessed++;
1426

1427 1428
      /* If subdirectory search not supplied, just try to remove
         and report error if it fails (eg if it contains a file) */
1429
      if (strstrW (quals, parmS) == NULL) {
1430
        if (!RemoveDirectory (thisArg)) WCMD_print_error ();
1431

1432 1433
      /* Otherwise use ShFileOp to recursively remove a directory */
      } else {
1434

1435
        SHFILEOPSTRUCT lpDir;
1436

1437
        /* Ask first */
1438
        if (strstrW (quals, parmQ) == NULL) {
1439
          BOOL  ok;
1440 1441
          WCHAR  question[MAXSTRING];
          static const WCHAR fmt[] = {'%','s',' ','\0'};
1442

1443
          /* Ask for confirmation */
1444
          wsprintf(question, fmt, thisArg);
1445
          ok = WCMD_ask_confirm(question, TRUE, NULL);
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

          /* Abort if answer is 'N' */
          if (!ok) return;
        }

        /* Do the delete */
        lpDir.hwnd   = NULL;
        lpDir.pTo    = NULL;
        lpDir.pFrom  = thisArg;
        lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
        lpDir.wFunc  = FO_DELETE;
1457
        if (SHFileOperation(&lpDir)) WCMD_print_error ();
1458
      }
1459
    }
1460
  }
1461

1462 1463
  /* Handle no valid args */
  if (argsProcessed == 0) {
1464
    WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
1465
    return;
1466
  }
1467

1468 1469 1470 1471 1472 1473 1474 1475
}

/****************************************************************************
 * WCMD_rename
 *
 * Rename a file.
 */

1476
void WCMD_rename (void) {
1477

1478 1479 1480
  int             status;
  HANDLE          hff;
  WIN32_FIND_DATA fd;
1481 1482 1483 1484 1485 1486
  WCHAR            input[MAX_PATH];
  WCHAR           *dotDst = NULL;
  WCHAR            drive[10];
  WCHAR            dir[MAX_PATH];
  WCHAR            fname[MAX_PATH];
  WCHAR            ext[MAX_PATH];
1487
  DWORD           attribs;
1488

1489 1490 1491
  errorlevel = 0;

  /* Must be at least two args */
1492
  if (param1[0] == 0x00 || param2[0] == 0x00) {
1493
    WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
1494
    errorlevel = 1;
1495 1496
    return;
  }
1497 1498

  /* Destination cannot contain a drive letter or directory separator */
1499
  if ((strchrW(param1,':') != NULL) || (strchrW(param1,'\\') != NULL)) {
1500 1501 1502 1503 1504 1505 1506
      SetLastError(ERROR_INVALID_PARAMETER);
      WCMD_print_error();
      errorlevel = 1;
      return;
  }

  /* Convert partial path to full path */
1507 1508 1509 1510
  GetFullPathName (param1, sizeof(input)/sizeof(WCHAR), input, NULL);
  WINE_TRACE("Rename from '%s'('%s') to '%s'\n", wine_dbgstr_w(input),
             wine_dbgstr_w(param1), wine_dbgstr_w(param2));
  dotDst = strchrW(param2, '.');
1511 1512 1513 1514 1515 1516

  /* Split into components */
  WCMD_splitpath(input, drive, dir, fname, ext);

  hff = FindFirstFile (input, &fd);
  while (hff != INVALID_HANDLE_VALUE) {
1517 1518 1519
    WCHAR  dest[MAX_PATH];
    WCHAR  src[MAX_PATH];
    WCHAR *dotSrc = NULL;
1520 1521
    int   dirLen;

1522
    WINE_TRACE("Processing file '%s'\n", wine_dbgstr_w(fd.cFileName));
1523 1524 1525 1526 1527 1528 1529

    /* FIXME: If dest name or extension is *, replace with filename/ext
       part otherwise use supplied name. This supports:
          ren *.fred *.jim
          ren jim.* fred.* etc
       However, windows has a more complex algorithum supporting eg
          ?'s and *'s mid name                                         */
1530
    dotSrc = strchrW(fd.cFileName, '.');
1531 1532

    /* Build src & dest name */
1533 1534 1535 1536 1537
    strcpyW(src, drive);
    strcatW(src, dir);
    strcpyW(dest, src);
    dirLen = strlenW(src);
    strcatW(src, fd.cFileName);
1538 1539 1540

    /* Build name */
    if (param2[0] == '*') {
1541
      strcatW(dest, fd.cFileName);
1542 1543
      if (dotSrc) dest[dirLen + (dotSrc - fd.cFileName)] = 0x00;
    } else {
1544
      strcatW(dest, param2);
1545 1546 1547 1548 1549
      if (dotDst) dest[dirLen + (dotDst - param2)] = 0x00;
    }

    /* Build Extension */
    if (dotDst && (*(dotDst+1)=='*')) {
1550
      if (dotSrc) strcatW(dest, dotSrc);
1551
    } else if (dotDst) {
1552
      if (dotDst) strcatW(dest, dotDst);
1553 1554
    }

1555 1556
    WINE_TRACE("Source '%s'\n", wine_dbgstr_w(src));
    WINE_TRACE("Dest   '%s'\n", wine_dbgstr_w(dest));
1557 1558

    /* Check if file is read only, otherwise move it */
1559
    attribs = GetFileAttributes(src);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    if ((attribs != INVALID_FILE_ATTRIBUTES) &&
        (attribs & FILE_ATTRIBUTE_READONLY)) {
      SetLastError(ERROR_ACCESS_DENIED);
      status = 0;
    } else {
      status = MoveFile (src, dest);
    }

    if (!status) {
      WCMD_print_error ();
      errorlevel = 1;
    }

    /* Step on to next match */
    if (FindNextFile(hff, &fd) == 0) {
      FindClose(hff);
      hff = INVALID_HANDLE_VALUE;
      break;
    }
1579 1580 1581
  }
}

1582 1583 1584 1585 1586
/*****************************************************************************
 * WCMD_dupenv
 *
 * Make a copy of the environment.
 */
1587
static WCHAR *WCMD_dupenv( const WCHAR *env )
1588 1589 1590 1591 1592 1593 1594 1595 1596
{
  WCHAR *env_copy;
  int len;

  if( !env )
    return NULL;

  len = 0;
  while ( env[len] )
1597
    len += (strlenW(&env[len]) + 1);
1598 1599 1600 1601

  env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
  if (!env_copy)
  {
1602
    WINE_ERR("out of memory\n");
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    return env_copy;
  }
  memcpy (env_copy, env, len*sizeof (WCHAR));
  env_copy[len] = 0;

  return env_copy;
}

/*****************************************************************************
 * WCMD_setlocal
 *
 *  setlocal pushes the environment onto a stack
 *  Save the environment as unicode so we don't screw anything up.
 */
1617
void WCMD_setlocal (const WCHAR *s) {
1618 1619
  WCHAR *env;
  struct env_stack *env_copy;
1620
  WCHAR cwd[MAX_PATH];
1621 1622 1623 1624 1625 1626

  /* DISABLEEXTENSIONS ignored */

  env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
  if( !env_copy )
  {
1627
    WINE_ERR ("out of memory\n");
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    return;
  }

  env = GetEnvironmentStringsW ();

  env_copy->strings = WCMD_dupenv (env);
  if (env_copy->strings)
  {
    env_copy->next = saved_environment;
    saved_environment = env_copy;
1638 1639 1640

    /* Save the current drive letter */
    GetCurrentDirectory (MAX_PATH, cwd);
1641
    env_copy->u.cwd = cwd[0];
1642 1643 1644 1645 1646
  }
  else
    LocalFree (env_copy);

  FreeEnvironmentStringsW (env);
1647

1648 1649 1650 1651 1652 1653
}

/*****************************************************************************
 * WCMD_endlocal
 *
 *  endlocal pops the environment off a stack
1654
 *  Note: When searching for '=', search from WCHAR position 1, to handle
1655
 *        special internal environment variables =C:, =D: etc
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
 */
void WCMD_endlocal (void) {
  WCHAR *env, *old, *p;
  struct env_stack *temp;
  int len, n;

  if (!saved_environment)
    return;

  /* pop the old environment from the stack */
  temp = saved_environment;
  saved_environment = temp->next;

  /* delete the current environment, totally */
  env = GetEnvironmentStringsW ();
  old = WCMD_dupenv (GetEnvironmentStringsW ());
  len = 0;
  while (old[len]) {
1674 1675
    n = strlenW(&old[len]) + 1;
    p = strchrW(&old[len] + 1, '=');
1676 1677 1678 1679 1680 1681 1682 1683 1684
    if (p)
    {
      *p++ = 0;
      SetEnvironmentVariableW (&old[len], NULL);
    }
    len += n;
  }
  LocalFree (old);
  FreeEnvironmentStringsW (env);
1685

1686 1687 1688 1689
  /* restore old environment */
  env = temp->strings;
  len = 0;
  while (env[len]) {
1690 1691
    n = strlenW(&env[len]) + 1;
    p = strchrW(&env[len] + 1, '=');
1692 1693 1694 1695 1696 1697 1698
    if (p)
    {
      *p++ = 0;
      SetEnvironmentVariableW (&env[len], p);
    }
    len += n;
  }
1699 1700

  /* Restore current drive letter */
1701
  if (IsCharAlpha(temp->u.cwd)) {
1702 1703 1704 1705 1706
    WCHAR envvar[4];
    WCHAR cwd[MAX_PATH];
    static const WCHAR fmt[] = {'=','%','c',':','\0'};

    wsprintf(envvar, fmt, temp->u.cwd);
1707
    if (GetEnvironmentVariable(envvar, cwd, MAX_PATH)) {
1708
      WINE_TRACE("Resetting cwd to %s\n", wine_dbgstr_w(cwd));
1709 1710 1711 1712
      SetCurrentDirectory(cwd);
    }
  }

1713 1714 1715 1716
  LocalFree (env);
  LocalFree (temp);
}

1717 1718 1719 1720 1721 1722 1723 1724 1725
/*****************************************************************************
 * WCMD_setshow_attrib
 *
 * Display and optionally sets DOS attributes on a file or directory
 *
 * FIXME: Wine currently uses the Unix stat() function to get file attributes.
 * As a result only the Readonly flag is correctly reported, the Archive bit
 * is always set and the rest are not implemented. We do the Right Thing anyway.
 *
1726 1727
 * FIXME: No SET functionality.
 *
1728 1729
 */

1730
void WCMD_setshow_attrib (void) {
1731

1732 1733 1734
  DWORD count;
  HANDLE hff;
  WIN32_FIND_DATA fd;
1735
  WCHAR flags[9] = {' ',' ',' ',' ',' ',' ',' ',' ','\0'};
1736

1737
  if (param1[0] == '-') {
1738
    WCMD_output (WCMD_LoadMessage(WCMD_NYI));
1739 1740 1741
    return;
  }

1742 1743 1744 1745 1746
  if (strlenW(param1) == 0) {
    static const WCHAR slashStarW[]  = {'\\','*','\0'};

    GetCurrentDirectory (sizeof(param1)/sizeof(WCHAR), param1);
    strcatW (param1, slashStarW);
1747 1748 1749 1750
  }

  hff = FindFirstFile (param1, &fd);
  if (hff == INVALID_HANDLE_VALUE) {
1751
    WCMD_output (WCMD_LoadMessage(WCMD_FILENOTFOUND), param1);
1752 1753 1754 1755
  }
  else {
    do {
      if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1756
        static const WCHAR fmt[] = {'%','s',' ',' ',' ','%','s','\n','\0'};
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
	  flags[0] = 'H';
	}
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
	  flags[1] = 'S';
	}
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
	  flags[2] = 'A';
	}
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
	  flags[3] = 'R';
	}
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
	  flags[4] = 'T';
	}
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
	  flags[5] = 'C';
	}
1775
        WCMD_output (fmt, flags, fd.cFileName);
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
	for (count=0; count < 8; count++) flags[count] = ' ';
      }
    } while (FindNextFile(hff, &fd) != 0);
  }
  FindClose (hff);
}

/*****************************************************************************
 * WCMD_setshow_default
 *
 *	Set/Show the current default directory
 */

1789
void WCMD_setshow_default (WCHAR *command) {
1790

1791
  BOOL status;
1792 1793 1794
  WCHAR string[1024];
  WCHAR cwd[1024];
  WCHAR *pos;
1795 1796
  WIN32_FIND_DATA fd;
  HANDLE hff;
1797
  static const WCHAR parmD[] = {'/','D','\0'};
1798

1799
  WINE_TRACE("Request change to directory '%s'\n", wine_dbgstr_w(command));
1800 1801 1802 1803

  /* Skip /D and trailing whitespace if on the front of the command line */
  if (CompareString (LOCALE_USER_DEFAULT,
                     NORM_IGNORECASE | SORT_STRINGSORT,
1804
                     command, 2, parmD, -1) == 2) {
1805 1806 1807 1808
    command += 2;
    while (*command && *command==' ') command++;
  }

1809 1810 1811
  GetCurrentDirectory (sizeof(cwd)/sizeof(WCHAR), cwd);
  if (strlenW(command) == 0) {
    strcatW (cwd, newline);
1812
    WCMD_output (cwd);
1813 1814
  }
  else {
1815 1816 1817 1818 1819 1820 1821 1822 1823
    /* Remove any double quotes, which may be in the
       middle, eg. cd "C:\Program Files"\Microsoft is ok */
    pos = string;
    while (*command) {
      if (*command != '"') *pos++ = *command;
      command++;
    }
    *pos = 0x00;

1824
    /* Search for approprate directory */
1825
    WINE_TRACE("Looking for directory '%s'\n", wine_dbgstr_w(string));
1826 1827 1828
    hff = FindFirstFile (string, &fd);
    while (hff != INVALID_HANDLE_VALUE) {
      if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1829 1830 1831 1832 1833 1834
        WCHAR fpath[MAX_PATH];
        WCHAR drive[10];
        WCHAR dir[MAX_PATH];
        WCHAR fname[MAX_PATH];
        WCHAR ext[MAX_PATH];
        static const WCHAR fmt[] = {'%','s','%','s','%','s','\0'};
1835 1836

        /* Convert path into actual directory spec */
1837
        GetFullPathName (string, sizeof(fpath)/sizeof(WCHAR), fpath, NULL);
1838 1839 1840
        WCMD_splitpath(fpath, drive, dir, fname, ext);

        /* Rebuild path */
1841
        wsprintf(string, fmt, drive, dir, fd.cFileName);
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855

        FindClose(hff);
        hff = INVALID_HANDLE_VALUE;
        break;
      }

      /* Step on to next match */
      if (FindNextFile(hff, &fd) == 0) {
        FindClose(hff);
        hff = INVALID_HANDLE_VALUE;
        break;
      }
    }

1856
    /* Change to that directory */
1857
    WINE_TRACE("Really changing to directory '%s'\n", wine_dbgstr_w(string));
1858

1859
    status = SetCurrentDirectory (string);
1860
    if (!status) {
1861
      errorlevel = 1;
1862 1863
      WCMD_print_error ();
      return;
1864 1865 1866 1867
    } else {

      /* Restore old directory if drive letter would change, and
           CD x:\directory /D (or pushd c:\directory) not supplied */
1868
      if ((strstrW(quals, parmD) == NULL) &&
1869 1870 1871
          (param1[1] == ':') && (toupper(param1[0]) != toupper(cwd[0]))) {
        SetCurrentDirectory(cwd);
      }
1872
    }
1873

1874 1875 1876 1877
    /* Set special =C: type environment variable, for drive letter of
       change of directory, even if path was restored due to missing
       /D (allows changing drive letter when not resident on that
       drive                                                          */
1878
    if ((string[1] == ':') && IsCharAlpha (string[0])) {
1879 1880 1881
      WCHAR env[4];
      strcpyW(env, equalW);
      memcpy(env+1, string, 2 * sizeof(WCHAR));
1882
      env[3] = 0x00;
1883
      WINE_TRACE("Setting '%s' to '%s'\n", wine_dbgstr_w(env), wine_dbgstr_w(string));
1884 1885 1886
      SetEnvironmentVariable(env, string);
    }

1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
   }
  return;
}

/****************************************************************************
 * WCMD_setshow_date
 *
 * Set/Show the system date
 * FIXME: Can't change date yet
 */

1898
void WCMD_setshow_date (void) {
1899

1900
  WCHAR curdate[64], buffer[64];
1901
  DWORD count;
1902
  static const WCHAR parmT[] = {'/','T','\0'};
1903

1904
  if (strlenW(param1) == 0) {
1905
    if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1906
		curdate, sizeof(curdate)/sizeof(WCHAR))) {
1907
      WCMD_output (WCMD_LoadMessage(WCMD_CURRENTDATE), curdate);
1908
      if (strstrW (quals, parmT) == NULL) {
1909
        WCMD_output (WCMD_LoadMessage(WCMD_NEWDATE));
1910 1911
        WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE),
                       buffer, sizeof(buffer)/sizeof(WCHAR), &count, NULL);
1912
        if (count > 2) {
1913
          WCMD_output (WCMD_LoadMessage(WCMD_NYI));
1914
        }
1915 1916 1917 1918 1919
      }
    }
    else WCMD_print_error ();
  }
  else {
1920
    WCMD_output (WCMD_LoadMessage(WCMD_NYI));
1921 1922 1923
  }
}

1924 1925 1926
/****************************************************************************
 * WCMD_compare
 */
1927
static int WCMD_compare( const void *a, const void *b )
1928 1929
{
    int r;
1930
    const WCHAR * const *str_a = a, * const *str_b = b;
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
    r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
	  *str_a, -1, *str_b, -1 );
    if( r == CSTR_LESS_THAN ) return -1;
    if( r == CSTR_GREATER_THAN ) return 1;
    return 0;
}

/****************************************************************************
 * WCMD_setshow_sortenv
 *
 * sort variables into order for display
1942 1943
 * Optionally only display those who start with a stub
 * returns the count displayed
1944
 */
1945
static int WCMD_setshow_sortenv(const WCHAR *s, const WCHAR *stub)
1946
{
1947
  UINT count=0, len=0, i, displayedcount=0, stublen=0;
1948
  const WCHAR **str;
1949

1950
  if (stub) stublen = strlenW(stub);
1951

1952 1953
  /* count the number of strings, and the total length */
  while ( s[len] ) {
1954
    len += (strlenW(&s[len]) + 1);
1955 1956 1957 1958
    count++;
  }

  /* add the strings to an array */
1959
  str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (WCHAR*) );
1960
  if( !str )
1961
    return 0;
1962 1963
  str[0] = s;
  for( i=1; i<count; i++ )
1964
    str[i] = str[i-1] + strlenW(str[i-1]) + 1;
1965 1966

  /* sort the array */
1967
  qsort( str, count, sizeof (WCHAR*), WCMD_compare );
1968 1969

  /* print it */
1970
  for( i=0; i<count; i++ ) {
1971 1972 1973
    if (!stub || CompareString (LOCALE_USER_DEFAULT,
                                NORM_IGNORECASE | SORT_STRINGSORT,
                                str[i], stublen, stub, -1) == 2) {
1974 1975 1976
      /* Don't display special internal variables */
      if (str[i][0] != '=') {
        WCMD_output_asis(str[i]);
1977
        WCMD_output_asis(newline);
1978 1979
        displayedcount++;
      }
1980
    }
1981
  }
1982 1983

  LocalFree( str );
1984
  return displayedcount;
1985 1986
}

1987 1988 1989 1990 1991 1992
/****************************************************************************
 * WCMD_setshow_env
 *
 * Set/Show the environment variables
 */

1993
void WCMD_setshow_env (WCHAR *s) {
1994

1995
  LPVOID env;
1996
  WCHAR *p;
1997
  int status;
1998
  static const WCHAR parmP[] = {'/','P','\0'};
1999

2000
  errorlevel = 0;
2001
  if (param1[0] == 0x00 && quals[0] == 0x00) {
2002
    env = GetEnvironmentStrings ();
2003
    WCMD_setshow_sortenv( env, NULL );
2004
    return;
2005
  }
2006 2007 2008 2009

  /* See if /P supplied, and if so echo the prompt, and read in a reply */
  if (CompareString (LOCALE_USER_DEFAULT,
                     NORM_IGNORECASE | SORT_STRINGSORT,
2010 2011
                     s, 2, parmP, -1) == 2) {
    WCHAR string[MAXSTRING];
2012 2013 2014 2015 2016 2017
    DWORD count;

    s += 2;
    while (*s && *s==' ') s++;

    /* If no parameter, or no '=' sign, return an error */
2018
    if (!(*s) || ((p = strchrW (s, '=')) == NULL )) {
2019
      WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
2020 2021 2022 2023 2024
      return;
    }

    /* Output the prompt */
    *p++ = '\0';
2025
    if (strlenW(p) != 0) WCMD_output(p);
2026 2027

    /* Read the reply */
2028 2029
    WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), string,
                   sizeof(string)/sizeof(WCHAR), &count, NULL);
2030 2031 2032
    if (count > 1) {
      string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
      if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
2033 2034
      WINE_TRACE("set /p: Setting var '%s' to '%s'\n", wine_dbgstr_w(s),
                 wine_dbgstr_w(string));
2035 2036 2037 2038
      status = SetEnvironmentVariable (s, string);
    }

  } else {
2039
    DWORD gle;
2040
    p = strchrW (s, '=');
2041
    if (p == NULL) {
2042 2043
      env = GetEnvironmentStrings ();
      if (WCMD_setshow_sortenv( env, s ) == 0) {
2044
        WCMD_output (WCMD_LoadMessage(WCMD_MISSINGENV), s);
2045
        errorlevel = 1;
2046
      }
2047 2048 2049
      return;
    }
    *p++ = '\0';
2050

2051
    if (strlenW(p) == 0) p = NULL;
2052
    status = SetEnvironmentVariable (s, p);
2053 2054 2055 2056
    gle = GetLastError();
    if ((!status) & (gle == ERROR_ENVVAR_NOT_FOUND)) {
      errorlevel = 1;
    } else if ((!status)) WCMD_print_error();
2057 2058 2059 2060 2061 2062 2063 2064 2065
  }
}

/****************************************************************************
 * WCMD_setshow_path
 *
 * Set/Show the path environment variable
 */

2066
void WCMD_setshow_path (WCHAR *command) {
2067

2068
  WCHAR string[1024];
2069
  DWORD status;
2070 2071
  static const WCHAR pathW[] = {'P','A','T','H','\0'};
  static const WCHAR pathEqW[] = {'P','A','T','H','=','\0'};
2072

2073 2074
  if (strlenW(param1) == 0) {
    status = GetEnvironmentVariable (pathW, string, sizeof(string)/sizeof(WCHAR));
2075
    if (status != 0) {
2076
      WCMD_output_asis ( pathEqW);
2077
      WCMD_output_asis ( string);
2078
      WCMD_output_asis ( newline);
2079 2080
    }
    else {
2081
      WCMD_output (WCMD_LoadMessage(WCMD_NOPATH));
2082 2083 2084
    }
  }
  else {
2085
    if (*command == '=') command++; /* Skip leading '=' */
2086
    status = SetEnvironmentVariable (pathW, command);
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
    if (!status) WCMD_print_error();
  }
}

/****************************************************************************
 * WCMD_setshow_prompt
 *
 * Set or show the command prompt.
 */

2097
void WCMD_setshow_prompt (void) {
2098

2099 2100
  WCHAR *s;
  static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2101

2102 2103
  if (strlenW(param1) == 0) {
    SetEnvironmentVariable (promptW, NULL);
2104 2105 2106 2107
  }
  else {
    s = param1;
    while ((*s == '=') || (*s == ' ')) s++;
2108 2109
    if (strlenW(s) == 0) {
      SetEnvironmentVariable (promptW, NULL);
2110
    }
2111
    else SetEnvironmentVariable (promptW, s);
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
  }
}

/****************************************************************************
 * WCMD_setshow_time
 *
 * Set/Show the system time
 * FIXME: Can't change time yet
 */

2122
void WCMD_setshow_time (void) {
2123

2124
  WCHAR curtime[64], buffer[64];
2125 2126
  DWORD count;
  SYSTEMTIME st;
2127
  static const WCHAR parmT[] = {'/','T','\0'};
2128

2129
  if (strlenW(param1) == 0) {
2130 2131
    GetLocalTime(&st);
    if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
2132
		curtime, sizeof(curtime)/sizeof(WCHAR))) {
2133
      WCMD_output (WCMD_LoadMessage(WCMD_CURRENTDATE), curtime);
2134
      if (strstrW (quals, parmT) == NULL) {
2135
        WCMD_output (WCMD_LoadMessage(WCMD_NEWTIME));
2136 2137
        WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer,
                       sizeof(buffer)/sizeof(WCHAR), &count, NULL);
2138
        if (count > 2) {
2139
          WCMD_output (WCMD_LoadMessage(WCMD_NYI));
2140
        }
2141 2142 2143 2144 2145
      }
    }
    else WCMD_print_error ();
  }
  else {
2146
    WCMD_output (WCMD_LoadMessage(WCMD_NYI));
2147 2148 2149 2150 2151 2152 2153
  }
}

/****************************************************************************
 * WCMD_shift
 *
 * Shift batch parameters.
2154
 * Optional /n says where to start shifting (n=0-8)
2155 2156
 */

2157
void WCMD_shift (WCHAR *command) {
2158
  int start;
2159

2160
  if (context != NULL) {
2161
    WCHAR *pos = strchrW(command, '/');
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
    int   i;

    if (pos == NULL) {
      start = 0;
    } else if (*(pos+1)>='0' && *(pos+1)<='8') {
      start = (*(pos+1) - '0');
    } else {
      SetLastError(ERROR_INVALID_PARAMETER);
      WCMD_print_error();
      return;
    }

    WINE_TRACE("Shifting variables, starting at %d\n", start);
    for (i=start;i<=8;i++) {
      context -> shift_count[i] = context -> shift_count[i+1] + 1;
    }
    context -> shift_count[9] = context -> shift_count[9] + 1;
  }
2180 2181 2182

}

2183 2184 2185 2186 2187
/****************************************************************************
 * WCMD_title
 *
 * Set the console title
 */
2188
void WCMD_title (WCHAR *command) {
2189 2190 2191
  SetConsoleTitle(command);
}

2192 2193 2194 2195 2196 2197
/****************************************************************************
 * WCMD_type
 *
 * Copy a file to standard output.
 */

2198
void WCMD_type (WCHAR *command) {
2199

2200
  int   argno         = 0;
2201
  WCHAR *argN          = command;
2202
  BOOL  writeHeaders  = FALSE;
2203

2204
  if (param1[0] == 0x00) {
2205
    WCMD_output (WCMD_LoadMessage(WCMD_NOARG));
2206 2207
    return;
  }
2208 2209 2210 2211 2212 2213

  if (param2[0] != 0x00) writeHeaders = TRUE;

  /* Loop through all args */
  errorlevel = 0;
  while (argN) {
2214
    WCHAR *thisArg = WCMD_parameter (command, argno++, &argN);
2215 2216

    HANDLE h;
2217
    WCHAR buffer[512];
2218 2219 2220 2221
    DWORD count;

    if (!argN) break;

2222
    WINE_TRACE("type: Processing arg '%s'\n", wine_dbgstr_w(thisArg));
2223 2224 2225 2226
    h = CreateFile (thisArg, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL, NULL);
    if (h == INVALID_HANDLE_VALUE) {
      WCMD_print_error ();
2227
      WCMD_output (WCMD_LoadMessage(WCMD_READFAIL), thisArg);
2228 2229 2230
      errorlevel = 1;
    } else {
      if (writeHeaders) {
2231 2232
        static const WCHAR fmt[] = {'\n','%','s','\n','\n','\0'};
        WCMD_output(fmt, thisArg);
2233
      }
2234
      while (WCMD_ReadFile (h, buffer, sizeof(buffer)/sizeof(WCHAR), &count, NULL)) {
2235 2236 2237 2238 2239 2240
        if (count == 0) break;	/* ReadFile reports success on EOF! */
        buffer[count] = 0;
        WCMD_output_asis (buffer);
      }
      CloseHandle (h);
    }
2241 2242 2243
  }
}

2244 2245 2246 2247 2248 2249
/****************************************************************************
 * WCMD_more
 *
 * Output either a file or stdin to screen in pages
 */

2250
void WCMD_more (WCHAR *command) {
2251 2252

  int   argno         = 0;
2253
  WCHAR *argN          = command;
2254
  BOOL  useinput      = FALSE;
2255 2256 2257
  WCHAR  moreStr[100];
  WCHAR  moreStrPage[100];
  WCHAR  buffer[512];
2258
  DWORD count;
2259 2260 2261 2262 2263
  static const WCHAR moreStart[] = {'-','-',' ','\0'};
  static const WCHAR moreFmt[]   = {'%','s',' ','-','-','\n','\0'};
  static const WCHAR moreFmt2[]  = {'%','s',' ','(','%','2','.','2','d','%','%',
                                    ')',' ','-','-','\n','\0'};
  static const WCHAR conInW[]    = {'C','O','N','I','N','$','\0'};
2264 2265 2266

  /* Prefix the NLS more with '-- ', then load the text */
  errorlevel = 0;
2267 2268 2269
  strcpyW(moreStr, moreStart);
  LoadString (hinst, WCMD_MORESTR, &moreStr[3],
              (sizeof(moreStr)/sizeof(WCHAR))-3);
2270 2271 2272 2273 2274 2275 2276 2277

  if (param1[0] == 0x00) {

    /* Wine implements pipes via temporary files, and hence stdin is
       effectively reading from the file. This means the prompts for
       more are satistied by the next line from the input (file). To
       avoid this, ensure stdin is to the console                    */
    HANDLE hstdin  = GetStdHandle(STD_INPUT_HANDLE);
2278
    HANDLE hConIn = CreateFile(conInW, GENERIC_READ | GENERIC_WRITE,
2279 2280 2281 2282 2283 2284 2285
                         FILE_SHARE_READ, NULL, OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL, 0);
    SetStdHandle(STD_INPUT_HANDLE, hConIn);

    /* Warning: No easy way of ending the stream (ctrl+z on windows) so
       once you get in this bit unless due to a pipe, its going to end badly...  */
    useinput = TRUE;
2286
    wsprintf(moreStrPage, moreFmt, moreStr);
2287 2288

    WCMD_enter_paged_mode(moreStrPage);
2289
    while (WCMD_ReadFile (hstdin, buffer, (sizeof(buffer)/sizeof(WCHAR))-1, &count, NULL)) {
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
      if (count == 0) break;	/* ReadFile reports success on EOF! */
      buffer[count] = 0;
      WCMD_output_asis (buffer);
    }
    WCMD_leave_paged_mode();

    /* Restore stdin to what it was */
    SetStdHandle(STD_INPUT_HANDLE, hstdin);
    CloseHandle(hConIn);

    return;
  } else {
    BOOL needsPause = FALSE;

    /* Loop through all args */
    WCMD_enter_paged_mode(moreStrPage);

    while (argN) {
2308
      WCHAR *thisArg = WCMD_parameter (command, argno++, &argN);
2309 2310 2311 2312 2313 2314 2315
      HANDLE h;

      if (!argN) break;

      if (needsPause) {

        /* Wait */
2316
        wsprintf(moreStrPage, moreFmt2, moreStr, 100);
2317 2318
        WCMD_leave_paged_mode();
        WCMD_output_asis(moreStrPage);
2319 2320
        WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer,
                       sizeof(buffer)/sizeof(WCHAR), &count, NULL);
2321 2322 2323 2324
        WCMD_enter_paged_mode(moreStrPage);
      }


2325
      WINE_TRACE("more: Processing arg '%s'\n", wine_dbgstr_w(thisArg));
2326 2327 2328 2329
      h = CreateFile (thisArg, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL, NULL);
      if (h == INVALID_HANDLE_VALUE) {
        WCMD_print_error ();
2330
        WCMD_output (WCMD_LoadMessage(WCMD_READFAIL), thisArg);
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
        errorlevel = 1;
      } else {
        ULONG64 curPos  = 0;
        ULONG64 fileLen = 0;
        WIN32_FILE_ATTRIBUTE_DATA   fileInfo;

        /* Get the file size */
        GetFileAttributesEx(thisArg, GetFileExInfoStandard, (void*)&fileInfo);
        fileLen = (((ULONG64)fileInfo.nFileSizeHigh) << 32) + fileInfo.nFileSizeLow;

        needsPause = TRUE;
2342
        while (WCMD_ReadFile (h, buffer, (sizeof(buffer)/sizeof(WCHAR))-1, &count, NULL)) {
2343 2344 2345 2346 2347
          if (count == 0) break;	/* ReadFile reports success on EOF! */
          buffer[count] = 0;
          curPos += count;

          /* Update % count (would be used in WCMD_output_asis as prompt) */
2348
          wsprintf(moreStrPage, moreFmt2, moreStr, (int) min(99, (curPos * 100)/fileLen));
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359

          WCMD_output_asis (buffer);
        }
        CloseHandle (h);
      }
    }

    WCMD_leave_paged_mode();
  }
}

2360 2361 2362 2363
/****************************************************************************
 * WCMD_verify
 *
 * Display verify flag.
2364 2365
 * FIXME: We don't actually do anything with the verify flag other than toggle
 * it...
2366 2367
 */

2368
void WCMD_verify (WCHAR *command) {
2369

2370
  int count;
2371

2372
  count = strlenW(command);
2373
  if (count == 0) {
2374 2375
    if (verify_mode) WCMD_output (WCMD_LoadMessage(WCMD_VERIFYPROMPT), onW);
    else WCMD_output (WCMD_LoadMessage(WCMD_VERIFYPROMPT), offW);
2376 2377
    return;
  }
2378
  if (lstrcmpiW(command, onW) == 0) {
2379 2380 2381
    verify_mode = 1;
    return;
  }
2382
  else if (lstrcmpiW(command, offW) == 0) {
2383 2384 2385
    verify_mode = 0;
    return;
  }
2386
  else WCMD_output (WCMD_LoadMessage(WCMD_VERIFYERR));
2387 2388 2389 2390 2391 2392 2393 2394
}

/****************************************************************************
 * WCMD_version
 *
 * Display version info.
 */

2395
void WCMD_version (void) {
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406

  WCMD_output (version_string);

}

/****************************************************************************
 * WCMD_volume
 *
 * Display volume info and/or set volume label. Returns 0 if error.
 */

2407
int WCMD_volume (int mode, WCHAR *path) {
2408

2409
  DWORD count, serial;
2410
  WCHAR string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
2411
  BOOL status;
2412

2413 2414
  if (strlenW(path) == 0) {
    status = GetCurrentDirectory (sizeof(curdir)/sizeof(WCHAR), curdir);
2415 2416 2417 2418
    if (!status) {
      WCMD_print_error ();
      return 0;
    }
2419 2420
    status = GetVolumeInformation (NULL, label, sizeof(label)/sizeof(WCHAR),
                                   &serial, NULL, NULL, NULL, 0);
2421 2422
  }
  else {
2423 2424
    static const WCHAR fmt[] = {'%','s','\\','\0'};
    if ((path[1] != ':') || (strlenW(path) != 2)) {
2425
      WCMD_output (WCMD_LoadMessage(WCMD_SYNTAXERR));
2426 2427
      return 0;
    }
2428 2429 2430
    wsprintf (curdir, fmt, path);
    status = GetVolumeInformation (curdir, label, sizeof(label)/sizeof(WCHAR),
                                   &serial, NULL,
2431 2432 2433 2434 2435 2436
    	NULL, NULL, 0);
  }
  if (!status) {
    WCMD_print_error ();
    return 0;
  }
2437
  WCMD_output (WCMD_LoadMessage(WCMD_VOLUMEDETAIL),
2438 2439
    	curdir[0], label, HIWORD(serial), LOWORD(serial));
  if (mode) {
2440
    WCMD_output (WCMD_LoadMessage(WCMD_VOLUMEPROMPT));
2441 2442
    WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), string,
                   sizeof(string)/sizeof(WCHAR), &count, NULL);
2443 2444 2445 2446
    if (count > 1) {
      string[count-1] = '\0';		/* ReadFile output is not null-terminated! */
      if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
    }
2447
    if (strlenW(path) != 0) {
2448 2449 2450 2451 2452 2453 2454 2455
      if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
    }
    else {
      if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
    }
  }
  return 1;
}
2456 2457 2458 2459 2460 2461 2462 2463

/**************************************************************************
 * WCMD_exit
 *
 * Exit either the process, or just this batch program
 *
 */

2464
void WCMD_exit (CMD_LIST **cmdList) {
2465

2466 2467
    static const WCHAR parmB[] = {'/','B','\0'};
    int rc = atoiW(param1); /* Note: atoi of empty parameter is 0 */
2468

2469
    if (context && lstrcmpiW(quals, parmB) == 0) {
2470 2471
        errorlevel = rc;
        context -> skip_rest = TRUE;
2472
        *cmdList = NULL;
2473 2474 2475 2476
    } else {
        ExitProcess(rc);
    }
}
2477 2478 2479 2480 2481 2482 2483

/**************************************************************************
 * WCMD_ask_confirm
 *
 * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
 * answer.
 *
2484 2485 2486
 * Returns True if Y (or A) answer is selected
 *         If optionAll contains a pointer, ALL is allowed, and if answered
 *                   set to TRUE
2487 2488
 *
 */
2489
BOOL WCMD_ask_confirm (WCHAR *message, BOOL showSureText, BOOL *optionAll) {
2490

2491 2492 2493 2494 2495
    WCHAR  msgbuffer[MAXSTRING];
    WCHAR  Ybuffer[MAXSTRING];
    WCHAR  Nbuffer[MAXSTRING];
    WCHAR  Abuffer[MAXSTRING];
    WCHAR  answer[MAX_PATH] = {'\0'};
2496 2497 2498
    DWORD count = 0;

    /* Load the translated 'Are you sure', plus valid answers */
2499 2500 2501 2502
    LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer)/sizeof(WCHAR));
    LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer)/sizeof(WCHAR));
    LoadString (hinst, WCMD_NO,  Nbuffer, sizeof(Nbuffer)/sizeof(WCHAR));
    LoadString (hinst, WCMD_ALL, Abuffer, sizeof(Abuffer)/sizeof(WCHAR));
2503 2504 2505

    /* Loop waiting on a Y or N */
    while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
2506 2507 2508
      static const WCHAR startBkt[] = {' ','(','\0'};
      static const WCHAR endBkt[]   = {')','?','\0'};

2509
      WCMD_output_asis (message);
2510 2511 2512
      if (showSureText) {
        WCMD_output_asis (msgbuffer);
      }
2513
      WCMD_output_asis (startBkt);
2514
      WCMD_output_asis (Ybuffer);
2515
      WCMD_output_asis (fslashW);
2516
      WCMD_output_asis (Nbuffer);
2517
      if (optionAll) {
2518
          WCMD_output_asis (fslashW);
2519 2520
          WCMD_output_asis (Abuffer);
      }
2521 2522 2523
      WCMD_output_asis (endBkt);
      WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer,
                     sizeof(answer)/sizeof(WCHAR), &count, NULL);
2524
      answer[0] = toupperW(answer[0]);
2525 2526 2527
    }

    /* Return the answer */
2528 2529
    return ((answer[0] == Ybuffer[0]) ||
            (optionAll && (answer[0] == Abuffer[0])));
2530
}
2531 2532 2533 2534

/*****************************************************************************
 * WCMD_assoc
 *
2535 2536
 *	Lists or sets file associations  (assoc = TRUE)
 *      Lists or sets file types         (assoc = FALSE)
2537
 */
2538
void WCMD_assoc (WCHAR *command, BOOL assoc) {
2539 2540 2541

    HKEY    key;
    DWORD   accessOptions = KEY_READ;
2542
    WCHAR   *newValue;
2543
    LONG    rc = ERROR_SUCCESS;
2544
    WCHAR    keyValue[MAXSTRING];
2545 2546
    DWORD   valueLen = MAXSTRING;
    HKEY    readKey;
2547 2548
    static const WCHAR shOpCmdW[] = {'\\','S','h','e','l','l','\\',
                                     'O','p','e','n','\\','C','o','m','m','a','n','d','\0'};
2549 2550 2551

    /* See if parameter includes '=' */
    errorlevel = 0;
2552
    newValue = strchrW(command, '=');
2553 2554 2555
    if (newValue) accessOptions |= KEY_WRITE;

    /* Open a key to HKEY_CLASSES_ROOT for enumerating */
2556
    if (RegOpenKeyEx(HKEY_CLASSES_ROOT, nullW, 0,
2557 2558 2559 2560 2561
                     accessOptions, &key) != ERROR_SUCCESS) {
      WINE_FIXME("Unexpected failure opening HKCR key: %d\n", GetLastError());
      return;
    }

2562
    /* If no parameters then list all associations */
2563 2564 2565 2566 2567
    if (*command == 0x00) {
      int index = 0;

      /* Enumerate all the keys */
      while (rc != ERROR_NO_MORE_ITEMS) {
2568
        WCHAR  keyName[MAXSTRING];
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
        DWORD nameLen;

        /* Find the next value */
        nameLen = MAXSTRING;
        rc = RegEnumKeyEx(key, index++,
                          keyName, &nameLen,
                          NULL, NULL, NULL, NULL);

        if (rc == ERROR_SUCCESS) {

2579 2580 2581 2582 2583
          /* Only interested in extension ones if assoc, or others
             if not assoc                                          */
          if ((keyName[0] == '.' && assoc) ||
              (!(keyName[0] == '.') && (!assoc)))
          {
2584 2585 2586
            WCHAR subkey[MAXSTRING];
            strcpyW(subkey, keyName);
            if (!assoc) strcatW(subkey, shOpCmdW);
2587

2588
            if (RegOpenKeyEx(key, subkey, 0,
2589 2590
                             accessOptions, &readKey) == ERROR_SUCCESS) {

2591
              valueLen = sizeof(keyValue)/sizeof(WCHAR);
2592 2593 2594
              rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
                                   (LPBYTE)keyValue, &valueLen);
              WCMD_output_asis(keyName);
2595
              WCMD_output_asis(equalW);
2596 2597 2598 2599
              /* If no default value found, leave line empty after '=' */
              if (rc == ERROR_SUCCESS) {
                WCMD_output_asis(keyValue);
              }
2600
              WCMD_output_asis(newline);
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
            }
          }
        }
      }
      RegCloseKey(readKey);

    } else {

      /* Parameter supplied - if no '=' on command line, its a query */
      if (newValue == NULL) {
2611 2612
        WCHAR *space;
        WCHAR subkey[MAXSTRING];
2613 2614

        /* Query terminates the parameter at the first space */
2615 2616
        strcpyW(keyValue, command);
        space = strchrW(keyValue, ' ');
2617 2618
        if (space) *space=0x00;

2619
        /* Set up key name */
2620 2621
        strcpyW(subkey, keyValue);
        if (!assoc) strcatW(subkey, shOpCmdW);
2622 2623

        if (RegOpenKeyEx(key, subkey, 0,
2624 2625 2626 2627 2628
                         accessOptions, &readKey) == ERROR_SUCCESS) {

          rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
                               (LPBYTE)keyValue, &valueLen);
          WCMD_output_asis(command);
2629
          WCMD_output_asis(equalW);
2630 2631
          /* If no default value found, leave line empty after '=' */
          if (rc == ERROR_SUCCESS) WCMD_output_asis(keyValue);
2632
          WCMD_output_asis(newline);
2633 2634 2635
          RegCloseKey(readKey);

        } else {
2636 2637
          WCHAR  msgbuffer[MAXSTRING];
          WCHAR  outbuffer[MAXSTRING];
2638 2639

          /* Load the translated 'File association not found' */
2640
          if (assoc) {
2641
            LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer)/sizeof(WCHAR));
2642
          } else {
2643
            LoadString (hinst, WCMD_NOFTYPE, msgbuffer, sizeof(msgbuffer)/sizeof(WCHAR));
2644
          }
2645
          wsprintf(outbuffer, msgbuffer, keyValue);
2646 2647 2648 2649 2650 2651 2652
          WCMD_output_asis(outbuffer);
          errorlevel = 2;
        }

      /* Not a query - its a set or clear of a value */
      } else {

2653
        WCHAR subkey[MAXSTRING];
2654

2655 2656 2657 2658
        /* Get pointer to new value */
        *newValue = 0x00;
        newValue++;

2659
        /* Set up key name */
2660 2661
        strcpyW(subkey, command);
        if (!assoc) strcatW(subkey, shOpCmdW);
2662 2663

        /* If nothing after '=' then clear value - only valid for ASSOC */
2664 2665
        if (*newValue == 0x00) {

2666 2667
          if (assoc) rc = RegDeleteKey(key, command);
          if (assoc && rc == ERROR_SUCCESS) {
2668
            WINE_TRACE("HKCR Key '%s' deleted\n", wine_dbgstr_w(command));
2669

2670
          } else if (assoc && rc != ERROR_FILE_NOT_FOUND) {
2671 2672 2673 2674
            WCMD_print_error();
            errorlevel = 2;

          } else {
2675 2676
            WCHAR  msgbuffer[MAXSTRING];
            WCHAR  outbuffer[MAXSTRING];
2677 2678

            /* Load the translated 'File association not found' */
2679
            if (assoc) {
2680 2681
              LoadString (hinst, WCMD_NOASSOC, msgbuffer,
                          sizeof(msgbuffer)/sizeof(WCHAR));
2682
            } else {
2683 2684
              LoadString (hinst, WCMD_NOFTYPE, msgbuffer,
                          sizeof(msgbuffer)/sizeof(WCHAR));
2685
            }
2686
            wsprintf(outbuffer, msgbuffer, keyValue);
2687 2688 2689 2690 2691 2692
            WCMD_output_asis(outbuffer);
            errorlevel = 2;
          }

        /* It really is a set value = contents */
        } else {
2693
          rc = RegCreateKeyEx(key, subkey, 0, NULL, REG_OPTION_NON_VOLATILE,
2694 2695 2696
                              accessOptions, NULL, &readKey, NULL);
          if (rc == ERROR_SUCCESS) {
            rc = RegSetValueEx(readKey, NULL, 0, REG_SZ,
2697
                                 (LPBYTE)newValue, strlenW(newValue));
2698 2699 2700 2701 2702 2703 2704 2705
            RegCloseKey(readKey);
          }

          if (rc != ERROR_SUCCESS) {
            WCMD_print_error();
            errorlevel = 2;
          } else {
            WCMD_output_asis(command);
2706
            WCMD_output_asis(equalW);
2707
            WCMD_output_asis(newValue);
2708
            WCMD_output_asis(newline);
2709 2710 2711 2712 2713 2714 2715 2716
          }
        }
      }
    }

    /* Clean up */
    RegCloseKey(key);
}
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730

/****************************************************************************
 * WCMD_color
 *
 * Clear the terminal screen.
 */

void WCMD_color (void) {

  /* Emulate by filling the screen from the top left to bottom right with
        spaces, then moving the cursor to the top left afterwards */
  CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

2731
  if (param1[0] != 0x00 && strlenW(param1) > 2) {
2732
    WCMD_output (WCMD_LoadMessage(WCMD_ARGERR));
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
    return;
  }

  if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
  {
      COORD topLeft;
      DWORD screenSize;
      DWORD color = 0;

      screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);

      topLeft.X = 0;
      topLeft.Y = 0;

      /* Convert the color hex digits */
      if (param1[0] == 0x00) {
        color = defaultColor;
      } else {
2751
        color = strtoulW(param1, NULL, 16);
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
      }

      /* Fail if fg == bg color */
      if (((color & 0xF0) >> 4) == (color & 0x0F)) {
        errorlevel = 1;
        return;
      }

      /* Set the current screen contents and ensure all future writes
         remain this color                                             */
      FillConsoleOutputAttribute(hStdOut, color, screenSize, topLeft, &screenSize);
      SetConsoleTextAttribute(hStdOut, color);
  }
}