Exemple #1
0
int cmd_type(char *param)
{
    char buf[256];
    char **argv;
    int argc, opts, ec = E_None;
    int fd, len;

    if((argv = scanCmdline(param, 0, 0, &argc, &opts)) == 0)
        return 1;

    /* Because no option was passed into scanCmdline() no
    	option can have been processed */
    assert(opts == 0);

    if(!argc) {
        error_req_param_missing();
        ec = E_Useage;
        goto errRet;
    }

    for(argc = 0; argv[argc]; ++argc) {
        if((fd = devopen(argv[argc], O_RDONLY)) == 0) {
            error_sfile_not_found(argv[argc]);
            ec = E_Other;
            break;
        }

        while((len = dos_read(fd, buf, sizeof(buf))) >= 0) {
            char *bufp, *p;
            if(cbreak) {
                dos_close(fd);
                ec = E_CBreak;
                goto errRet;
            }
            bufp = buf;
            for(p = buf; p < buf+len; p++) {
                if(*p == 26) break; /* CTRL-Z */
                if(*p == '\r' || *p == '\n') {
                    if(p > bufp) dos_write(1, bufp, p - bufp);
                    if(*p == '\n') dos_write(1, "\r\n", 2);
                    bufp = p + 1;
                }
            }
            dos_write(1, bufp, p - bufp);
            if (len < sizeof(buf) || *p == 26) break;
        }
        dos_close(fd);
        if(cbreak) {
            ec = E_CBreak;
            break;
        }
    }

errRet:
    freep(argv);

    return ec;
}
Exemple #2
0
int cmd_type(char *rest)
{
  char buf[256];
  char **argv;
  int argc, opts, ec = E_None;
  FILE *f;

  if((argv = scanCmdline(rest, 0, 0, &argc, &opts)) == 0)
    return 1;

  /* Because no option was passed into scanCmdline() no
    option can have been processed */
  assert(opts == 0);

  if(!argc) {
    error_req_param_missing();
    ec = E_Useage;
    goto errRet;
  }

  for(argc = 0; argv[argc]; ++argc) {
    if ((f = fdevopen(rest, "rt")) == 0)
    {
    error_sfile_not_found(rest);
    ec = E_Other;
    break;
    }

    while (fgets(buf, sizeof(buf), f))
    {
      if(cbreak) {
      fclose(f);
        ec = E_CBreak;
      goto errRet;
    }
    fputs(buf, stdout);
    }
    fclose(f);
    if(cbreak) {
      ec = E_CBreak;
      break;
    }
  }

errRet:
  freep(argv);

  return ec;
}
Exemple #3
0
static int directory_handler(char *rest,
                      int (*func) (const char *), char *fctname)
{ char **argv, *dir;
  int argc, opts;

  assert(func);

  if((argv = scanCmdline(rest, NULL, NULL, &argc, &opts)) == NULL)
    return 1;


  /* if doing a CD and no parameters given, print out current directory */
  if (func == chdir && argc == 0)
  {
    if((dir = dfnpath(0)) == NULL) {
      error_out_of_memory();
      freep(argv);
      return 1;
    }
    else {
      puts(dir);
      free(dir);
    }
  } else if(argc != 1) {
  error_req_param_missing();
    freep(argv);
    return 1;
  }
  else {
    assert(argv[0]);
    dir = strchr(argv[0], '\0');
  /* take off trailing \ if any, but ONLY if dir is not the root dir */
    if(dir > &argv[0][1] && *--dir == '\\' && dir[-1] != ':')
      *dir = '\0';

    dprintf(("%s: '%s'\n", fctname, argv[0]));
    if (func(argv[0]) != 0)
    {
      perror(fctname);
      freep(argv);
      return 1;
    }
  }

  freep(argv);
  return 0;
}
Exemple #4
0
int cmd_rename(char *rest)
{ char **argv;
  int argc, opts, ec = E_None;

  if((argv = scanCmdline(rest, 0, 0, &argc, &opts)) == 0)
    return 1;

  if(argc < 2) {
    error_req_param_missing();
    ec = E_Useage;
  }
  else if(argc > 2) {
    error_too_many_parameters(rest);
    ec = E_Useage;
  }
  else if (rename(argv[0], argv[1]) != 0)
  {
    perror("rename");
    ec = E_Other;
  }

  freep(argv);
  return ec;
}
Exemple #5
0
INT CommandMsgbox (LPTSTR param)
{
    //used to parse command line
    LPTSTR tmp;

    //used to find window title (used as messagebox title)
    //and to find window handle to pass to MessageBox
    HWND hWnd;
    TCHAR buff[128];

    //these are MessabeBox() parameters
    LPTSTR title, prompt = "";
    UINT uType = U_TYPE_INIT;

    /* set default title to window title */
    GetConsoleTitle(buff, 128);
    title = buff;

    if (_tcsncmp (param, _T("/?"), 2) == 0)
    {
        ConOutResPaging(TRUE,STRING_MSGBOX_HELP);
        return 0;
    }

    //yes here things are quite massed up :)

    //skip spaces
    while(_istspace(*param))
        param++;

    //search for type of messagebox (ok, okcancel, ...)
    if (_tcsnicmp(param, _T("ok "), 3) == 0)
    {
        uType |= MB_ICONEXCLAMATION | MB_OK;
        param += 3;
    }
    else if (_tcsnicmp(param, _T("okcancel "), 9) == 0)
    {
        uType |= MB_ICONQUESTION | MB_OKCANCEL;
        param += 9;
    }
    else if (_tcsnicmp(param, _T("yesno "), 6) == 0)
    {
        uType |= MB_ICONQUESTION | MB_YESNO;
        param += 6;
    }
    else if (_tcsnicmp(param, _T("yesnocancel "), 12) == 0)
    {
        uType |= MB_ICONQUESTION | MB_YESNOCANCEL;
        param += 12;
    }
    else
    {
#ifdef _SYNTAX_CHECK
        error_req_param_missing ();
        return 1;
#else
        uType |= MB_ICONEXCLAMATION | MB_OK;
#endif
    }

    //skip spaces
    while(_istspace(*param))
        param++;

#ifdef _SYNTAX_CHECK
    //if reached end of string
    //it is an error becuase we do not yet have prompt
    if (*param == 0)
    {
        error_req_param_missing ();
        return 1;
    }
#endif

    //search for "title"
    tmp = param;

    if (*param == '"')
    {
        tmp = _tcschr(param + 1, '"');
        if (tmp)
        {
            *tmp = 0;
            title = param + 1;
            tmp++;
            param = tmp;
        }
    }

    //skip spaces
    while(_istspace(*param))
        param++;

#ifdef _SYNTAX_CHECK
    //get prompt
    if (*param == 0)
    {
        error_req_param_missing ();
        return 1;
    }
#endif

    prompt = param;

    hWnd=GetConsoleWindow ();

    switch (MessageBox(hWnd, prompt, title, uType))
    {
        case IDYES:
        case IDOK:
            nErrorLevel = 10;
            break;

        case IDNO:
            nErrorLevel = 11;
            break;

        case IDCANCEL:
            nErrorLevel = 12;
            break;
    }

    return 0;
}
Exemple #6
0
INT CommandDelete (LPTSTR param)
{
	/*cmd is the command that was given, in this case it will always be "del" or "delete"
	param is whatever is given after the command*/

	LPTSTR *arg = NULL;
	INT args;
	INT i;
	INT   nEvalArgs = 0; /* nunber of evaluated arguments */
	DWORD dwFlags = 0;
	DWORD dwAttrFlags = 0;
	DWORD dwFiles = 0;
	LONG ch;
	TCHAR szOrginalArg[MAX_PATH];

	/*checks the first two chars of param to see if it is /?
	this however allows the following command to not show help
	"del frog.txt /?" */

        if (!StringsLoaded)
        {
                LoadStrings();
        }

	if (!_tcsncmp (param, _T("/?"), 2))
	{
		ConOutResPaging(TRUE,STRING_DEL_HELP1);
		return 0;
	}

	nErrorLevel = 0;

	arg = split (param, &args, FALSE);

	if (args == 0)
	{
		/* only command given */
		error_req_param_missing ();
		freep (arg);
		return 1;
	}
	/* check for options anywhere in command line */
	for (i = 0; i < args; i++)
	{
		if (*arg[i] == _T('/'))
		{
			/*found a command, but check to make sure it has something after it*/
			if (_tcslen (arg[i]) >= 2)
			{
				ch = _totupper (arg[i][1]);
				if (ch == _T('N'))
				{
					dwFlags |= DEL_NOTHING;
				}
				else if (ch == _T('P'))
				{
					dwFlags |= DEL_PROMPT;
				}
				else if (ch == _T('Q'))
				{
					dwFlags |= DEL_QUIET;
				}
				else if (ch == _T('F'))
				{
					dwFlags |= DEL_FORCE;
				}
				else if (ch == _T('S'))
				{
					dwFlags |= DEL_SUBDIR;
				}
				else if (ch == _T('T'))
				{
					dwFlags |= DEL_TOTAL;
				}
				else if (ch == _T('W'))
				{
					dwFlags |= DEL_WIPE;
				}
				else if (ch == _T('Y'))
				{
					dwFlags |= DEL_YES;
				}
				else if (ch == _T('A'))
				{

					dwFlags |= DEL_ATTRIBUTES;
					/*the proper syntax for /A has a min of 4 chars
					i.e. /A:R or /A:-H */
					if (_tcslen (arg[i]) < 4)
					{
						error_invalid_parameter_format(arg[i]);
						return 0;
					}
					ch = _totupper (arg[i][3]);
					if (_tcslen (arg[i]) == 4)
					{
						if(ch == _T('A'))
						{
							dwAttrFlags |= ATTR_ARCHIVE;
						}
						if(ch == _T('H'))
						{
							dwAttrFlags |= ATTR_HIDDEN;
						}
						if(ch == _T('S'))
						{
							dwAttrFlags |= ATTR_SYSTEM;
						}
						if(ch == _T('R'))
						{
							dwAttrFlags |= ATTR_READ_ONLY;
						}
					}
					if (_tcslen (arg[i]) == 5)
					{
						if(ch == _T('-'))
						{
							ch = _totupper (arg[i][4]);
							if(ch == _T('A'))
							{
								dwAttrFlags |= ATTR_N_ARCHIVE;
							}
							if(ch == _T('H'))
							{
								dwAttrFlags |= ATTR_N_HIDDEN;
							}
							if(ch == _T('S'))
							{
								dwAttrFlags |= ATTR_N_SYSTEM;
							}
							if(ch == _T('R'))
							{
								dwAttrFlags |= ATTR_N_READ_ONLY;
							}
						}
					}
				}
			}

			nEvalArgs++;
		}
	}

	/* there are only options on the command line --> error!!!
	there is the same number of args as there is flags, so none of the args were filenames*/
	if (args == nEvalArgs)
	{
		error_req_param_missing ();
		freep (arg);
		return 1;
	}

	/* keep quiet within batch files */
	if (bc != NULL)
		dwFlags |= DEL_QUIET;

	/* check for filenames anywhere in command line */
	for (i = 0; i < args && !(dwFiles & 0x80000000); i++)
	{

                /*this checks to see if it isnt a flag, if it isnt, we assume it is a file name*/
		if((*arg[i] == _T('/')) || (*arg[i] == _T('-')))
			continue;

		/* We want to make a copies of the argument */
		if(_tcslen(arg[i]) == 2 && arg[i][1] == _T(':'))
		{
			/* Check for C: D: ... */
			GetRootPath(arg[i],szOrginalArg,MAX_PATH);
		}
		else
		{
			_tcscpy(szOrginalArg,arg[i]);
		}
                dwFiles += ProcessDirectory(szOrginalArg, &dwFlags, dwAttrFlags);

        }

	freep (arg);

	/*Based on MS cmd, we only tell what files are being deleted when /S is used */
	if (dwFlags & DEL_TOTAL)
	{
                dwFiles &= 0x7fffffff;
		if (dwFiles < 2)
		{
                        ConOutResPrintf(STRING_DEL_HELP3, dwFiles);
		}
		else
		{
			ConOutResPrintf(STRING_DEL_HELP4, dwFiles);
		}
	}

	return 0;
}
Exemple #7
0
INT cmd_rmdir (LPTSTR param)
{
    TCHAR ch;
    INT args;
    INT dirCount;
    LPTSTR *arg;
    INT i;
    BOOL RD_SUB = FALSE;
    BOOL RD_QUIET = FALSE;
    INT res;
    INT nError = 0;
    TCHAR szFullPath[MAX_PATH];

    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_RMDIR_HELP);
        return 0;
    }

    arg = split (param, &args, FALSE, FALSE);
    dirCount = 0;

    /* check for options anywhere in command line */
    for (i = 0; i < args; i++)
    {
        if (*arg[i] == _T('/'))
        {
            /*found a command, but check to make sure it has something after it*/
            if (_tcslen (arg[i]) == 2)
            {
                ch = _totupper (arg[i][1]);

                if (ch == _T('S'))
                {
                    RD_SUB = TRUE;
                }
                else if (ch == _T('Q'))
                {
                    RD_QUIET = TRUE;
                }
            }
        }
        else
        {
            dirCount++;
        }
    }

    if (dirCount == 0)
    {
        /* No folder to remove */
        error_req_param_missing();
        freep(arg);
        return 1;
    }

    for (i = 0; i < args; i++)
    {
        if (*arg[i] == _T('/'))
            continue;

        if (RD_SUB)
        {
            /* ask if they want to delete evrything in the folder */
            if (!RD_QUIET)
            {
                res = FilePromptYNA (STRING_DEL_HELP2);
                if (res == PROMPT_NO || res == PROMPT_BREAK)
                {
                    nError = 1;
                    continue;
                }
                if (res == PROMPT_ALL)
                    RD_QUIET = TRUE;
            }
            /* get the folder name */
            GetFullPathName(arg[i],MAX_PATH,szFullPath,NULL);

            /* remove trailing \ if any, but ONLY if dir is not the root dir */
            if (_tcslen (szFullPath) >= 2 && szFullPath[_tcslen (szFullPath) - 1] == _T('\\'))
                szFullPath[_tcslen(szFullPath) - 1] = _T('\0');

            res = DeleteFolder(szFullPath);
        }
        else
        {
            res = RemoveDirectory(arg[i]);
        }

        if (!res)
        {
            /* Couldn't delete the folder, print out the error */
            nError = GetLastError();
            ErrorMessage(nError, _T("RD"));
        }
    }

    freep (arg);
    return nError;
}
Exemple #8
0
int cmd_del(char *rest)
{
  int ec = E_None;    /* exit code */
  int i;
  unsigned count = 0;

  struct ffblk f;

  /* Make fullname somewhat larger to ensure that appending
     a matched name, one backslash and one hope. */
  char fullname[MAXPATH + sizeof(f.ff_name) + 2],
   *p, *q;
  int len;

  char **arg;
  int argc, optc;

  /* initialize options */
  optP = 0;

  if((arg = scanCmdline(rest, opt_del, 0, &argc, &optc)) == 0)
    return E_Other;

  if(!argc) {
      error_req_param_missing();
      ec = E_Useage;
     }
  else {
    i = 0;
    do {
      assert(arg[i]);

    /* Get the pattern fully-qualified */
    /* Note: An absolute path always contains:
       A:\\
       --> It's always three bytes long at minimum
       and always contains a backslash */
    p = dfnexpand(arg[i], 0);
    assert(strlen(p) >= 3);
    if ((len = strlen(p)) >= MAXPATH)
    {
      error_filename_too_long(p);
      free(p);
     ec = E_Other;
     goto errRet;
    }
    strcpy(fullname, p);        /* Operating over a local buffer simplifies
                     the process; rather than keep the pattern
                     within dynamic memory */
    free(p);
    p = fullname + len;

    /* check if it is a directory */
    if(dfnstat(fullname) & DFN_DIRECTORY)
    {
      if (p[-1] != '\\')
      *p++ = '\\';
    }

    if (p[-1] == '\\')    /* delete a whole directory */
      p = stpcpy(p, "*.*");

    /* p := address to copy the filename to to form the fully-qualified
     filename */
    /* There is at least one backslash within fullname, because of dfnexpand() */
    while (*--p != '\\') ;
    ++p;

    /* make sure user is sure if all files are to be
     * deleted */
    if (!optP && *p == '*' && ((q = strchr(p, '.')) == 0 || q[1] == '*'))
    {
    displayString(TEXT_MSG_DELETE_ALL);
    if (vcgetcstr("YN\n\r") != 'Y')
    {
      ec = E_Other;
      goto errRet;
    }
    }

    if (FINDFIRST(fullname, &f, FA_ARCH))
    {
    error_sfile_not_found(fullname);
    }
    else do {
    strcpy(p, f.ff_name);       /* Make the full path */

    if (optP)
    {
      printf("%s, Delete(Y/N)?", fullname);
      switch (vcgetcstr("YN\n\r"))
      {
      case '\3':             /* ^Break pressed */
        ec = E_CBreak;
        goto errRet;
      case 'Y':
        break;                /* yes, delete */
      default:
        continue;             /* no, don't delete */
      }
    }
    else if (cbreak) {           /* is also probed for in vcgetstr() */
        ec = E_CBreak;
      goto errRet;
    }

#ifdef NODEL
  /* define NODEL if you want to debug */
    puts(fullname);
#else
    if (unlink(fullname) != 0)
    {
      perror(fullname);   /* notify the user */
    }
    else ++count;
#endif

    } while (FINDNEXT(&f) == 0);
    } while(++i < argc);
  }

errRet:

    if(echo) {
      dispCount(count, "no file", "one file", "%u files");
      puts(" removed.");
    }

    freep(arg);
  return ec;
}
Exemple #9
0
INT cmd_type (LPTSTR param)
{
	TCHAR  buff[256];
	HANDLE hFile, hConsoleOut;
	DWORD  dwRet;
	INT    argc,i;
	LPTSTR *argv;
	LPTSTR errmsg;
	BOOL bPaging = FALSE;
	BOOL bFirstTime = TRUE;

	hConsoleOut=GetStdHandle (STD_OUTPUT_HANDLE);

	if (!_tcsncmp (param, _T("/?"), 2))
	{
		ConOutResPaging(TRUE,STRING_TYPE_HELP1);
		return 0;
	}

	if (!*param)
	{
		error_req_param_missing ();
		return 1;
	}

	argv = split (param, &argc, TRUE);

	for(i = 0; i < argc; i++)
	{
		if(*argv[i] == _T('/') && _tcslen(argv[i]) >= 2 && _totupper(argv[i][1]) == _T('P'))
		{
			bPaging = TRUE;
		}
	}

	for (i = 0; i < argc; i++)
	{
		if (_T('/') == argv[i][0] && _totupper(argv[i][1]) != _T('P'))
		{
			ConErrResPrintf(STRING_TYPE_ERROR1, argv[i] + 1);
			continue;
		}

    	nErrorLevel = 0;

		hFile = CreateFile(argv[i],
			GENERIC_READ,
			FILE_SHARE_READ,NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,NULL);

		if(hFile == INVALID_HANDLE_VALUE)
		{
			FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
			               FORMAT_MESSAGE_IGNORE_INSERTS |
			               FORMAT_MESSAGE_FROM_SYSTEM,
			               NULL,
			               GetLastError(),
			               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			               (LPTSTR) &errmsg,
			               0,
			               NULL);
			ConErrPrintf (_T("%s - %s"), argv[i], errmsg);
			LocalFree (errmsg);
			nErrorLevel = 1;
			continue;
		}

		if (bPaging)
		{
			while (FileGetString (hFile, buff, sizeof(buff) / sizeof(TCHAR)))
			{
				if (ConOutPrintfPaging(bFirstTime, _T("%s"), buff) == 1)
				{
					bCtrlBreak = FALSE;
					CloseHandle(hFile);
					freep(argv);
					return 0;
				}
				bFirstTime = FALSE;
			}
		}
		else
		{
			while (ReadFile(hFile, buff, sizeof(buff), &dwRet, NULL) && dwRet > 0)
			{
				WriteFile(hConsoleOut, buff, dwRet, &dwRet, NULL);
				if (bCtrlBreak)
				{
					bCtrlBreak = FALSE;
					CloseHandle(hFile);
					freep(argv);
					return 0;
				}
			}
		}

		CloseHandle(hFile);
	}

	freep (argv);

	return 0;
}
Exemple #10
0
INT CommandScreen (LPTSTR param)
{
	SHORT x,y;
	BOOL bSkipText = FALSE;

	if (_tcsncmp (param, _T("/?"), 2) == 0)
	{
		ConOutResPaging(TRUE,STRING_SCREEN_HELP);
		return 0;
	}

	nErrorLevel = 0;

	//get row
	while(_istspace(*param))
		param++;

	if(!(*param))
	{
		error_req_param_missing ();
		return 1;
	}

	y = _ttoi(param);
	if (y<0 || y>(maxy-1))
	{
		ConOutResPuts(STRING_SCREEN_ROW);

		return 1;
	}

	//get col
	if(!(param = _tcschr(param,_T(' '))))
	{
		error_req_param_missing ();
		return 1;
	}

	while(_istspace(*param))
		param++;

	if(!(*param))
	{
		error_req_param_missing ();
		return 1;
	}

	x = _ttoi(param);
	if (x<0 || x>(maxx-1))
	{
		ConErrResPuts(STRING_SCREEN_COL);
		return 1;
	}

	//get text
	if(!(param = _tcschr(param,_T(' '))))
	{
		bSkipText = TRUE;
	}
	else
	{
		while(_istspace(*param))
			param++;

		if(!(*param))
		{
			bSkipText = TRUE;
		}
	}

	bIgnoreEcho = TRUE;

	if(bSkipText)
		x=0;


	SetCursorXY(x,y);

	if(!(bSkipText))
		ConOutPuts(param);

	return 0;
}
Exemple #11
0
INT cmd_move (LPTSTR param)
{
	LPTSTR *arg;
	INT argc, i, nFiles;
	LPTSTR pszDest;
	TCHAR szDestPath[MAX_PATH];
	TCHAR szFullDestPath[MAX_PATH];
	TCHAR szSrcDirPath[MAX_PATH];
	TCHAR szSrcPath[MAX_PATH];
	TCHAR szFullSrcPath[MAX_PATH];
	DWORD dwFlags = 0;
	INT nOverwrite = 0;
	WIN32_FIND_DATA findBuffer;
	HANDLE hFile;
	
	/* used only when source and destination  directories are on different volume*/
	HANDLE hDestFile;
	WIN32_FIND_DATA findDestBuffer;
	TCHAR szMoveDest[MAX_PATH];
	TCHAR szMoveSrc[MAX_PATH];
	LPTSTR pszDestDirPointer;
	LPTSTR pszSrcDirPointer;
	INT nDirLevel = 0;
	
	LPTSTR pszFile;
	BOOL OnlyOneFile;
	BOOL FoundFile;
	BOOL MoveStatus;
	DWORD dwMoveFlags = 0;
	DWORD dwMoveStatusFlags = 0;


	if (!_tcsncmp (param, _T("/?"), 2))
	{
#if 0
		ConOutPuts (_T("Moves files and renames files and directories.\n\n"
			"To move one or more files:\n"
			"MOVE [/N][/Y|/-Y][drive:][path]filename1[,...] destination\n"
			"\n"
			"To rename a directory:\n"
			"MOVE [/N][/Y|/-Y][drive:][path]dirname1 dirname2\n"
			"\n"
			"  [drive:][path]filename1  Specifies the location and name of the file\n"
			"                           or files you want to move.\n"
			"  /N                       Nothing. Don everthing but move files or direcories.\n"
			"  /Y\n"
			"  /-Y\n"
			"..."));
#else
		ConOutResPaging(TRUE,STRING_MOVE_HELP2);
#endif
		return 0;
	}

	nErrorLevel = 0;
	arg = splitspace(param, &argc);

	/* read options */
	for (i = 0; i < argc; i++)
	{
		if (!_tcsicmp(arg[i], _T("/N")))
			dwFlags |= MOVE_NOTHING;
		else if (!_tcsicmp(arg[i], _T("/Y")))
			dwFlags |= MOVE_OVER_YES;
		else if (!_tcsicmp(arg[i], _T("/-Y")))
			dwFlags |= MOVE_OVER_NO;
		else
			break;
	}
	nFiles = argc - i;

	if (nFiles < 1)
	{
		/* there must be at least one pathspec */
		error_req_param_missing();
		freep(arg);
		return 1;
	}

	if (nFiles > 2)
	{
		/* there are more than two pathspecs */
		error_too_many_parameters(param);
		freep(arg);
		return 1;
	}

	/* If no destination is given, default to current directory */
	pszDest = (nFiles == 1) ? _T(".") : arg[i + 1];

	/* check for wildcards in source and destination */
	if (_tcschr(pszDest, _T('*')) != NULL || _tcschr(pszDest, _T('?')) != NULL)
	{
		/* '*'/'?' in dest, this doesnt happen.  give folder name instead*/
		error_invalid_parameter_format(pszDest);
		freep(arg);
		return 1;
	}
	if (_tcschr(arg[i], _T('*')) != NULL || _tcschr(arg[i], _T('?')) != NULL)
	{
		dwMoveStatusFlags |= MOVE_SOURCE_HAS_WILD;
	}
	
	
	/* get destination */
	GetFullPathName (pszDest, MAX_PATH, szDestPath, NULL);
	TRACE ("Destination: %s\n", debugstr_aw(szDestPath));
	
	/* get source folder */
	GetFullPathName(arg[i], MAX_PATH, szSrcDirPath, &pszFile);
	if (pszFile != NULL)
		*pszFile = _T('\0');
	TRACE ("Source Folder: %s\n", debugstr_aw(szSrcDirPath));
	
	hFile = FindFirstFile (arg[i], &findBuffer);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ErrorMessage (GetLastError (), arg[i]);
		freep (arg);
		return 1;
		
	}

	/* check for special cases "." and ".." and if found skip them */
	FoundFile = TRUE;
	while(FoundFile &&
		  (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
		   _tcscmp(findBuffer.cFileName,_T("..")) == 0))
		FoundFile = FindNextFile (hFile, &findBuffer);
	
	if (!FoundFile)
	{
		/* what? we don't have anything to move? */
		error_file_not_found();
		FindClose(hFile);
		freep(arg);
		return 1;
	}
	
	OnlyOneFile = TRUE;
	/* check if there can be found files as files have first priority */
	if (findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		dwMoveStatusFlags |= MOVE_SOURCE_IS_DIR;
	else
		dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
	while(OnlyOneFile && FindNextFile(hFile,&findBuffer))
	{
		if (!(findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			ConOutPrintf(_T(""));
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) OnlyOneFile = FALSE;
			else
			{	/* this has been done this way so that we don't disturb other settings if they have been set before this */
				dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
				dwMoveStatusFlags &= ~MOVE_SOURCE_IS_DIR;
			}
		}
	}
	FindClose(hFile);

	TRACE ("Do we have only one file: %s\n", OnlyOneFile ? "TRUE" : "FALSE");

	/* we have to start again to be sure we don't miss any files or folders*/
	hFile = FindFirstFile (arg[i], &findBuffer);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		ErrorMessage (GetLastError (), arg[i]);
		freep (arg);
		return 1;
		
	}
	
	/* check for special cases "." and ".." and if found skip them */
	FoundFile = TRUE;
	while(FoundFile &&
		  (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
		   _tcscmp(findBuffer.cFileName,_T("..")) == 0))
		FoundFile = FindNextFile (hFile, &findBuffer);
	
	if (!FoundFile)
	{
		/* huh? somebody removed files and/or folders which were there */
		error_file_not_found();
		FindClose(hFile);
		freep(arg);
		return 1;
	}
	
	/* check if source and destination paths are on different volumes */
	if (szSrcDirPath[0] != szDestPath[0])
		dwMoveStatusFlags |= MOVE_PATHS_ON_DIF_VOL;
	
	/* move it */
	do
	{
		TRACE ("Found file/directory: %s\n", debugstr_aw(findBuffer.cFileName));
		nOverwrite = 1;
		dwMoveFlags = 0;
		dwMoveStatusFlags &= ~MOVE_DEST_IS_FILE &
							~MOVE_DEST_IS_DIR &
							~MOVE_SRC_CURRENT_IS_DIR &
							~MOVE_DEST_EXISTS;
		_tcscpy(szFullSrcPath,szSrcDirPath);
		if(szFullSrcPath[_tcslen(szFullSrcPath) -  1] != _T('\\'))
			_tcscat (szFullSrcPath, _T("\\"));
		_tcscat(szFullSrcPath,findBuffer.cFileName);
		_tcscpy(szSrcPath, szFullSrcPath);
		
		if (IsExistingDirectory(szSrcPath))
		{
			/* source is directory */
			
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE)
			{
				dwMoveStatusFlags |= MOVE_SRC_CURRENT_IS_DIR; /* source is file but at the current round we found a directory */
				continue;
			}
			TRACE ("Source is dir: %s\n", debugstr_aw(szSrcPath));
			dwMoveFlags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
		}
		
		/* if source is file we don't need to do anything special */
		
		if (IsExistingDirectory(szDestPath))
		{
			/* destination is existing directory */
			TRACE ("Destination is directory: %s\n", debugstr_aw(szDestPath));
			
			dwMoveStatusFlags |= MOVE_DEST_IS_DIR;
			
			/*build the dest string(accounts for *)*/
			_tcscpy (szFullDestPath, szDestPath);
			/*check to see if there is an ending slash, if not add one*/
			if(szFullDestPath[_tcslen(szFullDestPath) -  1] != _T('\\'))
				_tcscat (szFullDestPath, _T("\\"));
			_tcscat (szFullDestPath, findBuffer.cFileName);
			
			if (IsExistingFile(szFullDestPath) || IsExistingDirectory(szFullDestPath))
				dwMoveStatusFlags |= MOVE_DEST_EXISTS;
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
			
		}
		if (IsExistingFile(szDestPath))
		{
			/* destination is a file */
			TRACE ("Destination is file: %s\n", debugstr_aw(szDestPath));
			
			dwMoveStatusFlags |= MOVE_DEST_IS_FILE | MOVE_DEST_EXISTS;
			_tcscpy (szFullDestPath, szDestPath);
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
			
		}
		
		TRACE ("Move Status Flags: 0x%X\n",dwMoveStatusFlags);
		
		if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
			dwMoveStatusFlags & MOVE_DEST_IS_DIR &&
			dwMoveStatusFlags & MOVE_SOURCE_HAS_WILD)
		{
			/* We are not allowed to have existing source and destination dir when there is wildcard in source */
			error_syntax(NULL);
			FindClose(hFile);
			freep(arg);
			return 1;
		}
			
		if (!(dwMoveStatusFlags & (MOVE_DEST_IS_FILE | MOVE_DEST_IS_DIR)))
		{
			/* destination doesn't exist */
			_tcscpy (szFullDestPath, szDestPath);
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) dwMoveStatusFlags |= MOVE_DEST_IS_FILE;
			if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) dwMoveStatusFlags |= MOVE_DEST_IS_DIR;
			
			dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
		}
		
		if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE &&
			dwMoveStatusFlags & MOVE_DEST_IS_FILE &&
			!OnlyOneFile)
		{
			/*source has many files but there is only one destination file*/
			error_invalid_parameter_format(pszDest);
			FindClose(hFile);
			freep (arg);
			return 1;
		}
		
		/*checks to make sure user wanted/wants the override*/
		if((dwFlags & MOVE_OVER_NO) &&
		   (dwMoveStatusFlags & MOVE_DEST_EXISTS))
			continue;
		if(!(dwFlags & MOVE_OVER_YES) &&
		    (dwMoveStatusFlags & MOVE_DEST_EXISTS))
			nOverwrite = MoveOverwrite (szFullDestPath);
		if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
			continue;
		if (nOverwrite == PROMPT_ALL)
			dwFlags |= MOVE_OVER_YES;
		
			
		ConOutPrintf (_T("%s => %s "), szSrcPath, szFullDestPath);
		
		/* are we really supposed to do something */
		if (dwFlags & MOVE_NOTHING)
			continue;
		
		/*move the file*/
		if (!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
			dwMoveStatusFlags & MOVE_PATHS_ON_DIF_VOL))
			/* we aren't moving source folder to different drive */
			MoveStatus = MoveFileEx (szSrcPath, szFullDestPath, dwMoveFlags);
		else
		{	/* we are moving source folder to different drive */
			_tcscpy(szMoveDest, szFullDestPath);
			_tcscpy(szMoveSrc, szSrcPath);
			DeleteFile(szMoveDest);
			MoveStatus = CreateDirectory(szMoveDest, NULL); /* we use default security settings */
			if (MoveStatus)
			{
				_tcscat(szMoveDest,_T("\\"));
				_tcscat(szMoveSrc,_T("\\"));
				nDirLevel = 0;
				pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
				pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
				_tcscpy(pszSrcDirPointer,_T("*.*"));
				hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
				if (hDestFile == INVALID_HANDLE_VALUE)
					MoveStatus = FALSE;
				else
				{
					BOOL FirstTime = TRUE;
					FoundFile = TRUE;
					MoveStatus = FALSE;
					while(FoundFile)
					{
						if (FirstTime)
							FirstTime = FALSE;
						else
							FoundFile = FindNextFile (hDestFile, &findDestBuffer);
						
						if (!FoundFile)
						{	/* Nothing to do in this folder so we stop working on it */
							FindClose(hDestFile);
							(pszSrcDirPointer)--;
							(pszDestDirPointer)--;
							_tcscpy(pszSrcDirPointer,_T(""));
							_tcscpy(pszDestDirPointer,_T(""));
							if (nDirLevel > 0)
							{
								TCHAR szTempPath[MAX_PATH];
								INT nDiff;

								FoundFile = TRUE; /* we need to continue our seek for files */
								nDirLevel--;
								RemoveDirectory(szMoveSrc);
								GetDirectory(szMoveSrc,szTempPath,0);
								nDiff = _tcslen(szMoveSrc) - _tcslen(szTempPath);
								pszSrcDirPointer = pszSrcDirPointer - nDiff;
								_tcscpy(pszSrcDirPointer,_T(""));
								GetDirectory(szMoveDest,szTempPath,0);
								nDiff = _tcslen(szMoveDest) - _tcslen(szTempPath);
								pszDestDirPointer = pszDestDirPointer - nDiff;
								_tcscpy(pszDestDirPointer,_T(""));
								if(szMoveSrc[_tcslen(szMoveSrc) -  1] != _T('\\'))
									_tcscat (szMoveSrc, _T("\\"));
								if(szMoveDest[_tcslen(szMoveDest) -  1] != _T('\\'))
									_tcscat (szMoveDest, _T("\\"));
								pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
								pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
								_tcscpy(pszSrcDirPointer,_T("*.*"));
								hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
								if (hDestFile == INVALID_HANDLE_VALUE)
									continue;
								FirstTime = TRUE;
							}
							else
							{
								MoveStatus = TRUE; /* we moved everything so lets tell user about it */
								RemoveDirectory(szMoveSrc);
							}
							continue;
						}
						
						/* if we find "." or ".." we'll skip them */
						if (_tcscmp(findDestBuffer.cFileName,_T(".")) == 0 ||
							_tcscmp(findDestBuffer.cFileName,_T("..")) == 0)
							continue;
					
						_tcscpy(pszSrcDirPointer, findDestBuffer.cFileName);
						_tcscpy(pszDestDirPointer, findDestBuffer.cFileName);
						if (IsExistingFile(szMoveSrc))
						{
							FoundFile = CopyFile(szMoveSrc, szMoveDest, FALSE);
							if (!FoundFile) continue;
							DeleteFile(szMoveSrc);
						}
						else
						{
							FindClose(hDestFile);
							CreateDirectory(szMoveDest, NULL);
							_tcscat(szMoveDest,_T("\\"));
							_tcscat(szMoveSrc,_T("\\"));
							nDirLevel++;
							pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
							pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
							_tcscpy(pszSrcDirPointer,_T("*.*"));
							hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
							if (hDestFile == INVALID_HANDLE_VALUE)
							{
								FoundFile = FALSE;
								continue;
							}
							FirstTime = TRUE;
						}
					}
				}
			}
		}
		if (MoveStatus)
			ConOutResPrintf(STRING_MOVE_ERROR1);
		else
			ConOutResPrintf(STRING_MOVE_ERROR2);
	}
	while ((!OnlyOneFile || dwMoveStatusFlags & MOVE_SRC_CURRENT_IS_DIR ) &&
			!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) &&
			FindNextFile (hFile, &findBuffer));
	FindClose (hFile);
	
	freep (arg);
	return 0;
}
Exemple #12
0
INT CommandExpand (LPTSTR param)
{
	/*cmd is the command that was given, in this case it will always be "expand"
	param is whatever is given after the command*/

	LPTSTR *arg = NULL;
	INT args;
	INT i;
	INT   nEvalArgs = 0; /* nunber of evaluated arguments */
	DWORD dwFlags = 0;
	DWORD dwAttrFlags = 0;
	DWORD dwFiles = 0;
	LONG ch;
	TCHAR szOrginalArg[MAX_PATH];

	/*checks the first two chars of param to see if it is /?
	this however allows the following command to not show help
	"expand frog.cab /?" */

    if (!StringsLoaded)
    {
            LoadStrings();
    }

	if (!_tcsncmp (param, _T("/?"), 2))
	{
		//ConOutResPaging(TRUE,STRING_DEL_HELP1);
		return 0;
	}

	nErrorLevel = 0;

	arg = split (param, &args, FALSE);

	if (args == 0)
	{
		/* only command given */
		error_req_param_missing ();
		freep (arg);
		return 1;
	}
	/* check for options anywhere in command line */
	for (i = 0; i < args; i++)
	{
		if (*arg[i] == _T('-'))
		{
			/*found a command, but check to make sure it has something after it*/
			if (_tcslen (arg[i]) >= 2)
			{
				ch = _totupper (arg[i][1]);
				if (ch == _T('R'))
				{
					dwFlags |= EXPAND_RENAME;
				}
				else if (ch == _T('D'))
				{
					dwFlags |= EXPAND_DISPLAY;
				}
				else if (ch == _T('F'))
				{
					dwFlags |= EXPAND_FILES;
				}
				else if (ch == _T('Y'))
				{
					dwFlags |= EXPAND_YES;
				}

			}

			nEvalArgs++;
		}
	}

	/* there are only options on the command line --> error!!!
	there is the same number of args as there is flags, so none of the args were filenames*/
	if (args == nEvalArgs)
	{
		error_req_param_missing ();
		freep (arg);
		return 1;
	}

	/* check for filenames anywhere in command line */
	for (i = 0; i < args && !(dwFiles & 0x80000000); i++)
	{

        /*this checks to see if it isnt a flag, if it isnt, we assume it is a file name*/
		if((*arg[i] == _T('/')) || (*arg[i] == _T('-')))
			continue;

		/* We want to make a copies of the argument */


	freep (arg);

	/*Based on MS cmd, we only tell what files are being deleted when /S is used */
	if (dwFlags & DEL_TOTAL)
	{
                dwFiles &= 0x7fffffff;
		if (dwFiles < 2)
		{
                        ConOutResPrintf(STRING_DEL_HELP3, dwFiles);
		}
		else
		{
			ConOutResPrintf(STRING_DEL_HELP4, dwFiles);
		}
	}

	return 0;



}