Esempio n. 1
0
int __cdecl compare(const void *arg1,const void *arg2)
{
    FileName * File1;
    FileName * File2;
    INT ret;

    File1 = cmd_alloc(sizeof(FileName));
    if (!File1)
        return 0;

    File2 = cmd_alloc(sizeof(FileName));
    if (!File2)
    {
        cmd_free(File1);
        return 0;
    }

    memcpy(File1,arg1,sizeof(FileName));
    memcpy(File2,arg2,sizeof(FileName));

    /* ret = _tcsicmp(File1->Name, File2->Name); */
    ret = lstrcmpi(File1->Name, File2->Name);

    cmd_free(File1);
    cmd_free(File2);
    return ret;
}
Esempio n. 2
0
static VOID
PrintAlias (VOID)
{
    LPTSTR Aliases;
    LPTSTR ptr;
    DWORD len;

    len = GetConsoleAliasesLength(_T("cmd.exe"));
    if (len == 0)
        return;

    /* allocate memory for an extra \0 char to make parsing easier */
    ptr = cmd_alloc(len + sizeof(TCHAR));
    if (!ptr)
    {
        WARN("Cannot allocate memory for ptr!\n");
        return;
    }

    Aliases = ptr;

    ZeroMemory(Aliases, len + sizeof(TCHAR));

    if (GetConsoleAliases(Aliases, len, _T("cmd.exe")) != 0)
    {
        while (*Aliases != '\0')
        {
            ConOutPrintf(_T("%s\n"), Aliases);
            Aliases = Aliases + lstrlen(Aliases);
            Aliases++;
        }
    }
    cmd_free(ptr);
}
Esempio n. 3
0
VOID InitHistory(VOID)
{
	size=0;

	Top = cmd_alloc(sizeof(HIST_ENTRY));
	Bottom = cmd_alloc(sizeof(HIST_ENTRY));

	Top->prev = Bottom;
	Top->next = NULL;
	Top->string = NULL;

	Bottom->prev = NULL;
	Bottom->next = Top;
	Bottom->string = NULL;

	curr_ptr=Bottom;
}
Esempio n. 4
0
static
VOID add_at_bottom(LPTSTR string)
{


	LPHIST_ENTRY tmp;


	/*delete first entry if maximum number of entries is reached*/
	while(size>=max_size)
		del(Top->prev);

	while (_istspace(*string))
		string++;

	if (*string==_T('\0'))
		return;


	/*if new entry is the same than the last do not add it*/
	if(size)
		if(_tcscmp(string,Bottom->next->string)==0)
			return;


	/*fill bottom with string, it will become Bottom->next*/
	Bottom->string=cmd_alloc((_tcslen(string)+1)*sizeof(TCHAR));
	_tcscpy(Bottom->string,string);

	/*save Bottom value*/
	tmp=Bottom;


	/*create new void Bottom*/
	Bottom=cmd_alloc(sizeof(HIST_ENTRY));
	Bottom->next=tmp;
	Bottom->prev=NULL;
	Bottom->string=NULL;

	tmp->prev=Bottom;

	/*set new size*/
	size++;

}
Esempio n. 5
0
static VOID ConWrite(TCHAR *str, DWORD len, DWORD nStdHandle)
{
	DWORD dwWritten;
	HANDLE hOutput = GetStdHandle(nStdHandle);

	if (WriteConsole(hOutput, str, len, &dwWritten, NULL))
		return;

	/* We're writing to a file or pipe instead of the console. Convert the
	 * string from TCHARs to the desired output format, if the two differ */
	if (bUnicodeOutput)
	{
#ifndef _UNICODE
		WCHAR *buffer = cmd_alloc(len * sizeof(WCHAR));
		if (!buffer)
		{
			error_out_of_memory();
			return;
		}
		len = MultiByteToWideChar(OutputCodePage, 0, str, len, buffer, len);
		str = (PVOID)buffer;
#endif
		WriteFile(hOutput, str, len * sizeof(WCHAR), &dwWritten, NULL);
#ifndef _UNICODE
		cmd_free(buffer);
#endif
	}
	else
	{
#ifdef _UNICODE
		CHAR *buffer = cmd_alloc(len * MB_LEN_MAX * sizeof(CHAR));
		if (!buffer)
		{
			error_out_of_memory();
			return;
		}
		len = WideCharToMultiByte(OutputCodePage, 0, str, len, buffer, len * MB_LEN_MAX, NULL, NULL);
		str = (PVOID)buffer;
#endif
		WriteFile(hOutput, str, len, &dwWritten, NULL);
#ifdef _UNICODE
		cmd_free(buffer);
#endif
	}
}
Esempio n. 6
0
static INT
PrintAllAssociations()
{
    DWORD return_val = 0;
    HKEY hKey = NULL;
    DWORD numKeys = 0;

    DWORD extLength = 0;
    LPTSTR extName = NULL;
    DWORD keyCtr = 0;

    return_val = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Classes"), 0, KEY_READ, &hKey);

    if (return_val != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        return -1;
    }

    return_val = RegQueryInfoKey(hKey, NULL, NULL, NULL, &numKeys, &extLength, NULL, NULL, NULL, NULL, NULL, NULL);

    if (return_val != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        return -2;
    }

    extLength++;
    extName = cmd_alloc(extLength * sizeof(TCHAR));

    for(keyCtr = 0; keyCtr < numKeys; keyCtr++)
    {
        DWORD buffer_size = extLength;
        return_val = RegEnumKeyEx(hKey, keyCtr, extName, &buffer_size, NULL, NULL, NULL, NULL);

        if (return_val == ERROR_SUCCESS || return_val == ERROR_MORE_DATA)
        {
            if (*extName == _T('.'))
                PrintAssociation(extName);
        }
        else
        {
            cmd_free(extName);
            RegCloseKey(hKey);
            return -1;
        }
    }

    RegCloseKey(hKey);

    if (extName)
        cmd_free(extName);

    return numKeys;
}
Esempio n. 7
0
bool ConsoleManager::RunCommand(char* buf) 
{

	if (strcmp(buf, "user") == 0) {
		go_user();
	}

	//! exit command
	if (strcmp(buf, "exit") == 0) {
		return true;
	}

	//! clear screen
	else if (strcmp(buf, "cls") == 0) {
		console.Clear();
	}

	//! help
	else if (strcmp(buf, "help") == 0) {

		console.Print("Orange OS Console Help\n");		
		console.Print(" - exit: quits and halts the system\n");
		console.Print(" - cls: clears the display\n");
		console.Print(" - help: displays this message\n");
		console.Print(" - read: reads a file\n");
		console.Print(" - reset: Resets and recalibrates floppy for reading\n");
		console.Print(" - proc: Run process\n");		
	}

	//! read sector
	else if (strcmp(buf, "read") == 0) {
		cmd_read();
	}
	else if (strcmp(buf, "memstate") == 0) {
		cmd_memstate();
	}
	else if (strcmp(buf, "alloc") == 0) {
		cmd_alloc();
	}
	else if (strcmp(buf, "memtask") == 0) {
		cmd_memtask();
	}

	//! run process
	else if (strcmp(buf, "proc") == 0) {
		cmd_proc();
	}
	else
	{
		console.Print("Unknown Command\n");
	}

	return false;
}
Esempio n. 8
0
INT CommandAssoc (LPTSTR param)
{
    /* print help */
    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_ASSOC_HELP);
        return 0;
    }

    nErrorLevel = 0;

    if (_tcslen(param) == 0)
        PrintAllAssociations();
    else
    {
        LPTSTR lpEqualSign = _tcschr(param, _T('='));
        if (lpEqualSign != NULL)
        {
            LPTSTR fileType = lpEqualSign + 1;
            LPTSTR extension = cmd_alloc((lpEqualSign - param + 1) * sizeof(TCHAR));

            _tcsncpy(extension, param, lpEqualSign - param);
            extension[lpEqualSign - param] = (TCHAR)0;

            if (_tcslen(fileType) == 0)
            /* if the equal sign is the last character
            in the string, then delete the key */
            {
                RemoveAssociation(extension);
            }
            else
            /* otherwise, add the key and print out the association*/
            {
                AddAssociation( extension, fileType);
                PrintAssociation(extension);
            }

            cmd_free(extension);
        }
        else
        {
            /* no equal sign, print all associations */
            INT retval = PrintAssociation(param);

            if (retval == 0)	/* if nothing printed out */
                ConOutResPrintf(STRING_ASSOC_ERROR, param);
        }
    }

    return 0;
}
Esempio n. 9
0
INT cmd_path (LPTSTR param)
{

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

	nErrorLevel = 0;

	/* if param is empty, display the PATH environment variable */
	if (!param || !*param)
	{
		DWORD  dwBuffer;
		LPTSTR pszBuffer;

		pszBuffer = (LPTSTR)cmd_alloc (ENV_BUFFER_SIZE * sizeof(TCHAR));
		dwBuffer = GetEnvironmentVariable (_T("PATH"), pszBuffer, ENV_BUFFER_SIZE);
		if (dwBuffer == 0)
		{
			cmd_free(pszBuffer);
			ConOutResPrintf(STRING_VOL_HELP2, _T("PATH"));
			return 0;
		}
		else if (dwBuffer > ENV_BUFFER_SIZE)
		{
			pszBuffer = (LPTSTR)cmd_realloc (pszBuffer, dwBuffer * sizeof (TCHAR));
			GetEnvironmentVariable (_T("PATH"), pszBuffer, dwBuffer);
		}

		ConOutPrintf (_T("PATH=%s\n"), pszBuffer);
		cmd_free (pszBuffer);

		return 0;
	}

	/* skip leading '=' */
	if (*param == _T('='))
		param++;

	/* set PATH environment variable */
	if (!SetEnvironmentVariable (_T("PATH"), param))
	{
		nErrorLevel = 1;
		return 1;
	}

	return 0;
}
Esempio n. 10
0
static void cmd_pool_oper(void)
{
    int32_t ret = OPER_OK;

    printf("command pool test!\n");

    if((ret = cmd_pool_create()) != OPER_OK)
    {
        printf("Create command pool fail!\n");
    }
    else
    {
        cmd_t* cmd_buf[5];
        int32_t i = 0;
        int32_t count = 0;
        
        printf("Create command pool success!!!\n");

        memset(cmd_buf,0,sizeof(cmd_buf));

        for(i = 0; i < 5; i++)
        {
            printf("alloc \n");
            if(cmd_alloc(&cmd_buf[i]) != OPER_OK)
            {
                printf("Alloc buffer fail : %d\n",i);
                count = i;
                break;
            }
            cmd_buf[i]->fd = i+1;
            strcpy((char*)cmd_buf[i]->data,"hello");
        }

        printf("Alloc complete success!\n");
//        if(i >= 5)    count = i;
        
        for(i = 0 ; i < 5; i++)
        {
            printf("command %d fd : %d,data : %s\n",(i+1),cmd_buf[i]->fd,(char*)cmd_buf[i]->data);
            cmd_free(cmd_buf[i]);
        }

        if((ret = cmd_pool_destroy()) != OPER_OK)
            printf("command pool destroy fail, still in use\n");
        else
            printf("command pool destroy success!\n");
    }
    
}
Esempio n. 11
0
LPTSTR BatchParams (LPTSTR s1, LPTSTR s2)
{
    LPTSTR dp = (LPTSTR)cmd_alloc ((_tcslen(s1) + _tcslen(s2) + 3) * sizeof (TCHAR));

    /* JPP 20-Jul-1998 added error checking */
    if (dp == NULL)
    {
        error_out_of_memory();
        return NULL;
    }

    if (s1 && *s1)
    {
        s1 = _stpcpy (dp, s1);
        *s1++ = _T('\0');
    }
    else
        s1 = dp;

    while (*s2)
    {
        BOOL inquotes = FALSE;

        /* Find next parameter */
        while (_istspace(*s2) || (*s2 && _tcschr(_T(",;="), *s2)))
            s2++;
        if (!*s2)
            break;

        /* Copy it */
        do
        {
            if (!inquotes && (_istspace(*s2) || _tcschr(_T(",;="), *s2)))
                break;
            inquotes ^= (*s2 == _T('"'));
            *s1++ = *s2++;
        } while (*s2);
        *s1++ = _T('\0');
    }

    *s1 = _T('\0');

    return dp;
}
Esempio n. 12
0
/*
 * Load batch file into memory
 *
 */
void BatchFile2Mem(HANDLE hBatchFile)
{
    TRACE ("BatchFile2Mem ()\n");

    bc->memsize = GetFileSize(hBatchFile, NULL);
    bc->mem     = (char *)cmd_alloc(bc->memsize+1);		/* 1 extra for '\0' */

    /* if memory is available, read it in and close the file */
    if (bc->mem != NULL)
    {
        TRACE ("BatchFile2Mem memory %08x - %08x\n",bc->mem,bc->memsize);
        SetFilePointer (hBatchFile, 0, NULL, FILE_BEGIN);
        ReadFile(hBatchFile, (LPVOID)bc->mem, bc->memsize,  &bc->memsize, NULL);
        bc->mem[bc->memsize]='\0';  /* end this, so you can dump it as a string */
        bc->memfree=TRUE;           /* this one needs to be freed */
    }
    else
    {
        bc->memsize=0;              /* this will prevent mem being accessed */
        bc->memfree=FALSE;
    }
    bc->mempos = 0;                 /* set position to the start */
}
Esempio n. 13
0
VOID ConInString (LPTSTR lpInput, DWORD dwLength)
{
	DWORD dwOldMode;
	DWORD dwRead = 0;
	HANDLE hFile;

	LPTSTR p;
	PCHAR pBuf;

#ifdef _UNICODE
	pBuf = (PCHAR)cmd_alloc(dwLength - 1);
#else
	pBuf = lpInput;
#endif
	ZeroMemory (lpInput, dwLength * sizeof(TCHAR));
	hFile = GetStdHandle (STD_INPUT_HANDLE);
	GetConsoleMode (hFile, &dwOldMode);

	SetConsoleMode (hFile, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);

	ReadFile (hFile, (PVOID)pBuf, dwLength - 1, &dwRead, NULL);

#ifdef _UNICODE
	MultiByteToWideChar(InputCodePage, 0, pBuf, dwRead, lpInput, dwLength - 1);
	cmd_free(pBuf);
#endif
	for (p = lpInput; *p; p++)
	{
		if (*p == _T('\x0d'))
		{
			*p = _T('\0');
			break;
		}
	}

	SetConsoleMode (hFile, dwOldMode);
}
Esempio n. 14
0
static INT
PushDirectory (LPTSTR pszPath)
{
	LPDIRENTRY lpDir = cmd_alloc(FIELD_OFFSET(DIRENTRY, szPath[_tcslen(pszPath) + 1]));
	if (!lpDir)
	{
		error_out_of_memory ();
		return -1;
	}

	lpDir->prev = NULL;
	lpDir->next = lpStackTop;
	if (lpStackTop == NULL)
		lpStackBottom = lpDir;
	else
		lpStackTop->prev = lpDir;
	lpStackTop = lpDir;

	_tcscpy(lpDir->szPath, pszPath);

	nStackDepth++;

	return nErrorLevel = 0;
}
Esempio n. 15
0
static VOID ConWrite(TCHAR *str, DWORD len, DWORD nStdHandle)
{
    DWORD dwWritten;
    HANDLE hOutput = GetStdHandle(nStdHandle);
    PVOID p;

    /* Check whether we are writing to a console and if so, write to it */
    if (IsConsoleHandle(hOutput))
    {
        if (WriteConsole(hOutput, str, len, &dwWritten, NULL))
            return;
    }

    /* We're writing to a file or pipe instead of the console. Convert the
     * string from TCHARs to the desired output format, if the two differ */
    if (bUnicodeOutput)
    {
#ifndef _UNICODE
        WCHAR *buffer = cmd_alloc(len * sizeof(WCHAR));
        if (!buffer)
        {
            error_out_of_memory();
            return;
        }
        len = (DWORD)MultiByteToWideChar(OutputCodePage, 0, str, (INT)len, buffer, (INT)len);
        str = (PVOID)buffer;
#endif
        /*
         * Find any newline character in the buffer,
         * send the part BEFORE the newline, then send
         * a carriage-return + newline, and then send
         * the remaining part of the buffer.
         *
         * This fixes output in files and serial console.
         */
        while (str && *(PWCHAR)str && len > 0)
        {
            p = wcspbrk((PWCHAR)str, L"\r\n");
            if (p)
            {
                len -= ((PWCHAR)p - (PWCHAR)str) + 1;
                WriteFile(hOutput, str, ((PWCHAR)p - (PWCHAR)str) * sizeof(WCHAR), &dwWritten, NULL);
                WriteFile(hOutput, L"\r\n", 2 * sizeof(WCHAR), &dwWritten, NULL);
                str = (PVOID)((PWCHAR)p + 1);
            }
            else
            {
                WriteFile(hOutput, str, len * sizeof(WCHAR), &dwWritten, NULL);
                break;
            }
        }

        // WriteFile(hOutput, str, len * sizeof(WCHAR), &dwWritten, NULL);
#ifndef _UNICODE
        cmd_free(buffer);
#endif
    }
    else
    {
#ifdef _UNICODE
        CHAR *buffer = cmd_alloc(len * MB_LEN_MAX * sizeof(CHAR));
        if (!buffer)
        {
            error_out_of_memory();
            return;
        }
        len = WideCharToMultiByte(OutputCodePage, 0, str, len, buffer, len * MB_LEN_MAX, NULL, NULL);
        str = (PVOID)buffer;
#endif
        /*
         * Find any newline character in the buffer,
         * send the part BEFORE the newline, then send
         * a carriage-return + newline, and then send
         * the remaining part of the buffer.
         *
         * This fixes output in files and serial console.
         */
        while (str && *(PCHAR)str && len > 0)
        {
            p = strpbrk((PCHAR)str, "\r\n");
            if (p)
            {
                len -= ((PCHAR)p - (PCHAR)str) + 1;
                WriteFile(hOutput, str, ((PCHAR)p - (PCHAR)str), &dwWritten, NULL);
                WriteFile(hOutput, "\r\n", 2, &dwWritten, NULL);
                str = (PVOID)((PCHAR)p + 1);
            }
            else
            {
                WriteFile(hOutput, str, len, &dwWritten, NULL);
                break;
            }
        }

        // WriteFile(hOutput, str, len, &dwWritten, NULL);
#ifdef _UNICODE
        cmd_free(buffer);
#endif
    }
}
Esempio n. 16
0
/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
*/
static void yy_reduce(
  yyParser *yypParser,         /* The parser */
  int yyruleno                 /* Number of the rule by which to reduce */
){
  int yygoto;                     /* The next state */
  int yyact;                      /* The next action */
  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
  yyStackEntry *yymsp;            /* The top of the parser's stack */
  int yysize;                     /* Amount to pop the stack */
  LineParserARG_FETCH;
  yymsp = &yypParser->yystack[yypParser->yyidx];
#ifndef NDEBUG
  if( yyTraceFILE && yyruleno>=0 
        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
      yyRuleName[yyruleno]);
  }
#endif /* NDEBUG */

  /* Silence complaints from purify about yygotominor being uninitialized
  ** in some cases when it is copied into the stack after the following
  ** switch.  yygotominor is uninitialized when a rule reduces that does
  ** not set the value of its left-hand side nonterminal.  Leaving the
  ** value of the nonterminal uninitialized is utterly harmless as long
  ** as the value is never used.  So really the only thing this code
  ** accomplishes is to quieten purify.  
  **
  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
  ** without this code, their parser segfaults.  I'm not sure what there
  ** parser is doing to make this happen.  This is the second bug report
  ** from wireshark this week.  Clearly they are stressing Lemon in ways
  ** that it has not been previously stressed...  (SQLite ticket #2172)
  */
  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  yygotominor = yyzerominor;


  switch( yyruleno ){
  /* Beginning here are the reduction cases.  A typical example
  ** follows:
  **   case 0:
  **  #line <lineno> <grammarfile>
  **     { ... }           // User supplied code
  **  #line <lineno> <thisfile>
  **     break;
  */
      case 0: /* redirection ::= REDIRECT_INPUT_FROM_FILE ARGUMENT */
#line 51 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy4 = redir_alloc();
    BREAK_IF_ERRNO
    yygotominor.yy4->left_fd = redir_parse_left_fd(yymsp[-1].minor.yy0, 1, STDIN_FILENO);
    yygotominor.yy4->type = REDIRECT_INPUT_FROM_FILE;
    yygotominor.yy4->right_file = yymsp[0].minor.yy0;
}
#line 770 "line_parser.c"
        break;
      case 1: /* redirection ::= REDIRECT_INPUT_FROM_FILE_DESCRIPTOR ARGUMENT */
#line 59 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy4 = redir_alloc();
    BREAK_IF_ERRNO
    yygotominor.yy4->left_fd = redir_parse_left_fd(yymsp[-1].minor.yy0, 2, STDIN_FILENO);
    yygotominor.yy4->type = REDIRECT_INPUT_FROM_FILE_DESCRIPTOR;
    yygotominor.yy4->right_fd = redir_parse_fd(yymsp[0].minor.yy0);
    free(yymsp[0].minor.yy0);
}
#line 783 "line_parser.c"
        break;
      case 2: /* redirection ::= REDIRECT_OUTPUT_TO_FILE ARGUMENT */
#line 68 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy4 = redir_alloc();
    BREAK_IF_ERRNO
    yygotominor.yy4->left_fd = redir_parse_left_fd(yymsp[-1].minor.yy0, 1, STDOUT_FILENO);
    yygotominor.yy4->type = REDIRECT_OUTPUT_TO_FILE;
    yygotominor.yy4->right_file = yymsp[0].minor.yy0;
}
#line 795 "line_parser.c"
        break;
      case 3: /* redirection ::= REDIRECT_OUTPUT_TO_FILE_DESCRIPTOR ARGUMENT */
#line 76 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy4 = redir_alloc();
    BREAK_IF_ERRNO
    yygotominor.yy4->left_fd = redir_parse_left_fd(yymsp[-1].minor.yy0, 2, STDOUT_FILENO);
    yygotominor.yy4->type = REDIRECT_OUTPUT_TO_FILE_DESCRIPTOR;
    yygotominor.yy4->right_fd = redir_parse_fd(yymsp[0].minor.yy0);
    free(yymsp[0].minor.yy0);
}
#line 808 "line_parser.c"
        break;
      case 4: /* redirection ::= REDIRECT_OUTPUT_APPEND_TO_FILE ARGUMENT */
#line 85 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy4 = redir_alloc();
    BREAK_IF_ERRNO
    yygotominor.yy4->left_fd = redir_parse_left_fd(yymsp[-1].minor.yy0, 2, STDOUT_FILENO);
    yygotominor.yy4->type = REDIRECT_OUTPUT_APPEND_TO_FILE;
    yygotominor.yy4->right_file = yymsp[0].minor.yy0;
}
#line 820 "line_parser.c"
        break;
      case 5: /* command ::= ARGUMENT */
#line 94 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy2 = cmd_alloc();
    BREAK_IF_ERRNO
    strarr_append(&(yygotominor.yy2->args), yymsp[0].minor.yy0);
}
#line 830 "line_parser.c"
        break;
      case 6: /* command ::= redirection */
#line 100 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy2 = cmd_alloc();
    BREAK_IF_ERRNO
    ptrarr_append(&(yygotominor.yy2->redirs), yymsp[0].minor.yy4);
}
#line 840 "line_parser.c"
        break;
      case 7: /* command ::= command ARGUMENT */
#line 106 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy2 = yymsp[-1].minor.yy2;
    strarr_append(&(yygotominor.yy2->args), yymsp[0].minor.yy0);
}
#line 849 "line_parser.c"
        break;
      case 8: /* command ::= command redirection */
#line 111 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy2 = yymsp[-1].minor.yy2;
    ptrarr_append(&(yygotominor.yy2->redirs), yymsp[0].minor.yy4);
}
#line 858 "line_parser.c"
        break;
      case 9: /* commandList ::= command */
#line 117 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = cmd_list_alloc();
    BREAK_IF_ERRNO
    ptrarr_append(&(yygotominor.yy13->cmds), yymsp[0].minor.yy2);
}
#line 868 "line_parser.c"
        break;
      case 10: /* commandList ::= commandList PIPE command */
#line 123 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-2].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), PIPE);
    ptrarr_append(&(yygotominor.yy13->cmds), yymsp[0].minor.yy2);
  yy_destructor(yypParser,7,&yymsp[-1].minor);
}
#line 879 "line_parser.c"
        break;
      case 11: /* commandList ::= commandList OR command */
#line 129 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-2].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), OR);
    ptrarr_append(&(yygotominor.yy13->cmds), yymsp[0].minor.yy2);
  yy_destructor(yypParser,8,&yymsp[-1].minor);
}
#line 890 "line_parser.c"
        break;
      case 12: /* commandList ::= commandList AND command */
#line 135 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-2].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), AND);
    ptrarr_append(&(yygotominor.yy13->cmds), yymsp[0].minor.yy2);
  yy_destructor(yypParser,9,&yymsp[-1].minor);
}
#line 901 "line_parser.c"
        break;
      case 13: /* commandList ::= commandList BACKGROUND command */
#line 141 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-2].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), BACKGROUND);
    ptrarr_append(&(yygotominor.yy13->cmds), yymsp[0].minor.yy2);
  yy_destructor(yypParser,10,&yymsp[-1].minor);
}
#line 912 "line_parser.c"
        break;
      case 14: /* commandList ::= commandList BACKGROUND */
#line 147 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-1].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), BACKGROUND);
  yy_destructor(yypParser,10,&yymsp[0].minor);
}
#line 922 "line_parser.c"
        break;
      case 15: /* commandList ::= commandList SEMICOLON command */
#line 152 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-2].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), SEMICOLON);
    ptrarr_append(&(yygotominor.yy13->cmds), yymsp[0].minor.yy2);
  yy_destructor(yypParser,11,&yymsp[-1].minor);
}
#line 933 "line_parser.c"
        break;
      case 16: /* commandList ::= commandList SEMICOLON */
#line 158 "line_parser.y"
{
    BREAK_IF_ERRNO
    yygotominor.yy13 = yymsp[-1].minor.yy13;
    intarr_append(&(yygotominor.yy13->ops), SEMICOLON);
  yy_destructor(yypParser,11,&yymsp[0].minor);
}
#line 943 "line_parser.c"
        break;
      case 17: /* start ::= commandList */
#line 164 "line_parser.y"
{
    BREAK_IF_ERRNO
    // Save our AST from being freed by Lemon!
    *cmd_list_p = yymsp[0].minor.yy13;
}
#line 952 "line_parser.c"
        break;
      default:
        break;
  };
  yygoto = yyRuleInfo[yyruleno].lhs;
  yysize = yyRuleInfo[yyruleno].nrhs;
  yypParser->yyidx -= yysize;
  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  if( yyact < YYNSTATE ){
#ifdef NDEBUG
    /* If we are not debugging and the reduce action popped at least
    ** one element off the stack, then we can push the new element back
    ** onto the stack here, and skip the stack overflow test in yy_shift().
    ** That gives a significant speed improvement. */
    if( yysize ){
      yypParser->yyidx++;
      yymsp -= yysize-1;
      yymsp->stateno = (YYACTIONTYPE)yyact;
      yymsp->major = (YYCODETYPE)yygoto;
      yymsp->minor = yygotominor;
    }else
#endif
    {
      yy_shift(yypParser,yyact,yygoto,&yygotominor);
    }
  }else{
    assert( yyact == YYNSTATE + YYNRULE + 1 );
    yy_accept(yypParser);
  }
}
Esempio n. 17
0
/*
 * DirReadParameters
 *
 * Parse the parameters and switches of the command line and exports them
 */
static BOOL
DirReadParam(LPTSTR Line,				/* [IN] The line with the parameters & switches */
			LPTSTR** params,			/* [OUT] The parameters after parsing */
			LPINT entries,				/* [OUT] The number of parameters after parsing */
			LPDIRSWITCHFLAGS lpFlags)	/* [IN/OUT] The flags after calculating switches */
{
	TCHAR cCurSwitch;	/* The current switch */
	TCHAR cCurChar;		/* Current examing character */
	TCHAR cCurUChar;	/* Current upper examing character */
	BOOL bNegative;		/* Negative switch */
	BOOL bPNegative;	/* Negative switch parameter */
	BOOL bIntoQuotes;	/* A flag showing if we are in quotes (") */
	LPTSTR ptrStart;	/* A pointer to the first character of a parameter */
	LPTSTR ptrEnd;		/* A pointer to the last character of a parameter */
	BOOL bOrderByNoPar;	/* A flag to indicate /O with no switch parameter */
	LPTSTR temp;

	/* Initialize parameter array */
	*params = NULL;
	*entries = 0;

	/* Initialize variables; */
	cCurSwitch = _T(' ');
	bNegative = FALSE;
	bPNegative = FALSE;

	/* We suppose that switch parameters
	   were given to avoid setting them to default
	   if the switch was not given */
	bOrderByNoPar = FALSE;

	/* Main Loop (see README_DIR.txt) */
	/* scan the command line char per char, and we process its char */
	while (*Line)
	{
		/* we save current character as it is and its upper case */
		cCurChar = *Line;
		cCurUChar = _totupper(*Line);

		/* 1st section (see README_DIR.txt) */
		/* When a switch is expecting */
		if (cCurSwitch == _T('/'))
		{
			while (*Line == _T(' '))
				Line++;

			bNegative = (*Line == _T('-'));
			Line += bNegative;

			cCurChar = *Line;
			cCurUChar = _totupper(*Line);

			if ((cCurUChar == _T('A')) ||(cCurUChar == _T('T')) || (cCurUChar == _T('O')))
			{
				/* If positive, prepare for parameters... if negative, reset to defaults */
				switch (cCurUChar)
				{
				case _T('A'):
					lpFlags->stAttribs.dwAttribVal = 0L;
					lpFlags->stAttribs.dwAttribMask = 0L;
					if (bNegative)
						lpFlags->stAttribs.dwAttribMask = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
					break;
				case _T('T'):
					if (bNegative)
						lpFlags->stTimeField.eTimeField = TF_MODIFIEDDATE;
					break;
				case _T('O'):
					bOrderByNoPar = !bNegative;
					lpFlags->stOrderBy.sCriteriaCount = 0;
					break;
				}

				if (!bNegative)
				{
					/* Positive switch, so it can take parameters. */
					cCurSwitch = cCurUChar;
					Line++;
					/* Skip optional leading colon */
					if (*Line == _T(':'))
						Line++;
					continue;
				}
			}
			else if (cCurUChar == _T('L'))
				lpFlags->bLowerCase = ! bNegative;
			else if (cCurUChar == _T('B'))
				lpFlags->bBareFormat = ! bNegative;
			else if (cCurUChar == _T('C'))
				lpFlags->bTSeperator = ! bNegative;
			else if (cCurUChar == _T('W'))
				lpFlags->bWideList = ! bNegative;
			else if (cCurUChar == _T('D'))
				lpFlags->bWideListColSort = ! bNegative;
			else if (cCurUChar == _T('N'))
				lpFlags->bNewLongList = ! bNegative;
			else if (cCurUChar == _T('P'))
				lpFlags->bPause = ! bNegative;
			else if (cCurUChar == _T('Q'))
				lpFlags->bUser = ! bNegative;
			else if (cCurUChar == _T('S'))
				lpFlags->bRecursive = ! bNegative;
			else if (cCurUChar == _T('X'))
				lpFlags->bShortName = ! bNegative;
			else if (cCurChar == _T('4'))
				lpFlags->b4Digit = ! bNegative;
			else if (cCurChar == _T('?'))
			{
				DirHelp();
				return FALSE;
			}
			else
			{
				error_invalid_switch ((TCHAR)_totupper (*Line));
				return FALSE;
			}

			/* Make sure there's no extra characters at the end of the switch */
			if (Line[1] && Line[1] != _T('/') && Line[1] != _T(' '))
			{
				error_parameter_format(Line[1]);
				return FALSE;
			}

			cCurSwitch = _T(' ');
		}
		else if (cCurSwitch == _T(' '))
		{
			/* 2nd section (see README_DIR.txt) */
			/* We are expecting parameter or the unknown */

			if (cCurChar == _T('/'))
				cCurSwitch = _T('/');
			else if (cCurChar == _T(' '))
				/* do nothing */;
			else
			{
				/* This is a file/directory name parameter. Find its end */
				ptrStart = Line;
				bIntoQuotes = FALSE;
				while (*Line)
				{
					if (!bIntoQuotes && (*Line == _T('/') || *Line == _T(' ')))
						break;
					bIntoQuotes ^= (*Line == _T('"'));
					Line++;
				}
				ptrEnd = Line;

				/* Copy it to the entries list */
				temp = cmd_alloc((ptrEnd - ptrStart + 1) * sizeof (TCHAR));
				if(!temp)
					return FALSE;
				memcpy(temp, ptrStart, (ptrEnd - ptrStart) * sizeof (TCHAR));
				temp[ptrEnd - ptrStart] = _T('\0');
				StripQuotes(temp);
				if(!add_entry(entries, params, temp))
				{
					cmd_free(temp);
					freep(*params);
					return FALSE;
				}

				cmd_free(temp);
				continue;
			}
		}
		else
		{
			/* 3rd section (see README_DIR.txt) */
			/* We are waiting for switch parameters */

			/* Check if there are no more switch parameters */
			if ((cCurChar == _T('/')) || ( cCurChar == _T(' ')))
			{
				/* Wrong desicion path, reprocess current character */
				cCurSwitch = _T(' ');
				continue;
			}
			/* Process parameter switch */
			switch(cCurSwitch)
			{
			case _T('A'):	/* Switch parameters for /A (attributes filter) */
				if(cCurChar == _T('-'))
					bPNegative = TRUE;
				else if(cCurUChar == _T('D'))
				{
					lpFlags->stAttribs.dwAttribMask |= FILE_ATTRIBUTE_DIRECTORY;
					if (bPNegative)
						lpFlags->stAttribs.dwAttribVal &= ~FILE_ATTRIBUTE_DIRECTORY;
					else
						lpFlags->stAttribs.dwAttribVal |= FILE_ATTRIBUTE_DIRECTORY;
				}
				else if(cCurUChar == _T('R'))
				{
					lpFlags->stAttribs.dwAttribMask |= FILE_ATTRIBUTE_READONLY;
					if (bPNegative)
						lpFlags->stAttribs.dwAttribVal &= ~FILE_ATTRIBUTE_READONLY;
					else
						lpFlags->stAttribs.dwAttribVal |= FILE_ATTRIBUTE_READONLY;
				}
				else if(cCurUChar == _T('H'))
				{
					lpFlags->stAttribs.dwAttribMask |= FILE_ATTRIBUTE_HIDDEN;
					if (bPNegative)
						lpFlags->stAttribs.dwAttribVal &= ~FILE_ATTRIBUTE_HIDDEN;
					else
						lpFlags->stAttribs.dwAttribVal |= FILE_ATTRIBUTE_HIDDEN;
				}
				else if(cCurUChar == _T('A'))
				{
					lpFlags->stAttribs.dwAttribMask |= FILE_ATTRIBUTE_ARCHIVE;
					if (bPNegative)
						lpFlags->stAttribs.dwAttribVal &= ~FILE_ATTRIBUTE_ARCHIVE;
					else
						lpFlags->stAttribs.dwAttribVal |= FILE_ATTRIBUTE_ARCHIVE;
				}
				else if(cCurUChar == _T('S'))
				{
					lpFlags->stAttribs.dwAttribMask |= FILE_ATTRIBUTE_SYSTEM;
					if (bPNegative)
						lpFlags->stAttribs.dwAttribVal &= ~FILE_ATTRIBUTE_SYSTEM;
					else
						lpFlags->stAttribs.dwAttribVal |= FILE_ATTRIBUTE_SYSTEM;
				}
				else
				{
					error_parameter_format((TCHAR)_totupper (*Line));
					return FALSE;
				}
				break;
			case _T('T'):	/* Switch parameters for /T (time field) */
				if(cCurUChar == _T('C'))
					lpFlags->stTimeField.eTimeField= TF_CREATIONDATE ;
				else if(cCurUChar == _T('A'))
					lpFlags->stTimeField.eTimeField= TF_LASTACCESSEDDATE ;
				else if(cCurUChar == _T('W'))
					lpFlags->stTimeField.eTimeField= TF_MODIFIEDDATE  ;
				else
				{
					error_parameter_format((TCHAR)_totupper (*Line));
					return FALSE;
				}
				break;
			case _T('O'):	/* Switch parameters for /O (order) */
				/* Ok a switch parameter was given */
				bOrderByNoPar = FALSE;

				if(cCurChar == _T('-'))
					bPNegative = TRUE;
				else if(cCurUChar == _T('N'))
				{
					if (lpFlags->stOrderBy.sCriteriaCount < 3) lpFlags->stOrderBy.sCriteriaCount++;
					lpFlags->stOrderBy.bCriteriaRev[lpFlags->stOrderBy.sCriteriaCount - 1] = bPNegative;
					lpFlags->stOrderBy.eCriteria[lpFlags->stOrderBy.sCriteriaCount - 1] = ORDER_NAME;
				}
				else if(cCurUChar == _T('S'))
				{
					if (lpFlags->stOrderBy.sCriteriaCount < 3) lpFlags->stOrderBy.sCriteriaCount++;
					lpFlags->stOrderBy.bCriteriaRev[lpFlags->stOrderBy.sCriteriaCount - 1] = bPNegative;
					lpFlags->stOrderBy.eCriteria[lpFlags->stOrderBy.sCriteriaCount - 1] = ORDER_SIZE;
				}
				else if(cCurUChar == _T('G'))
				{
					if (lpFlags->stOrderBy.sCriteriaCount < 3) lpFlags->stOrderBy.sCriteriaCount++;
					lpFlags->stOrderBy.bCriteriaRev[lpFlags->stOrderBy.sCriteriaCount - 1] = bPNegative;
					lpFlags->stOrderBy.eCriteria[lpFlags->stOrderBy.sCriteriaCount - 1] = ORDER_DIRECTORY;
				}
				else if(cCurUChar == _T('E'))
				{
					if (lpFlags->stOrderBy.sCriteriaCount < 3) lpFlags->stOrderBy.sCriteriaCount++;
					lpFlags->stOrderBy.bCriteriaRev[lpFlags->stOrderBy.sCriteriaCount - 1] = bPNegative;
					lpFlags->stOrderBy.eCriteria[lpFlags->stOrderBy.sCriteriaCount - 1] = ORDER_EXTENSION;
				}
				else if(cCurUChar == _T('D'))
				{
					if (lpFlags->stOrderBy.sCriteriaCount < 3) lpFlags->stOrderBy.sCriteriaCount++;
					lpFlags->stOrderBy.bCriteriaRev[lpFlags->stOrderBy.sCriteriaCount - 1] = bPNegative;
					lpFlags->stOrderBy.eCriteria[lpFlags->stOrderBy.sCriteriaCount - 1] = ORDER_TIME;
				}

				else
				{
					error_parameter_format((TCHAR)_totupper (*Line));
					return FALSE;
				}


			}
			/* We check if we calculated the negative value and realese the flag */
			if ((cCurChar != _T('-')) && bPNegative)
				bPNegative = FALSE;
		}

		Line++;
	}

	/* /O with no switch parameters acts like /O:GN */
	if (bOrderByNoPar)
	{
		lpFlags->stOrderBy.sCriteriaCount = 2;
		lpFlags->stOrderBy.eCriteria[0] = ORDER_DIRECTORY;
		lpFlags->stOrderBy.bCriteriaRev[0] = FALSE;
		lpFlags->stOrderBy.eCriteria[1] = ORDER_NAME;
		lpFlags->stOrderBy.bCriteriaRev[1] = FALSE;
	}

	return TRUE;
}
Esempio n. 18
0
INT cmd_copy(LPTSTR param)
{
    LPTSTR *arg;
    INT argc, i, nFiles, nOverwrite = 0, nSrc = -1, nDes = -1;
    /* this is the path up to the folder of the src and dest ie C:\windows\ */
    TCHAR szDestPath[MAX_PATH];
    TCHAR szSrcPath[MAX_PATH];
    DWORD dwFlags = 0;
    /* If this is the type of copy where we are adding files */
    BOOL bAppend = FALSE;
    WIN32_FIND_DATA findBuffer;
    HANDLE hFile = NULL;
    BOOL bTouch = FALSE;
    /* Used when something like "copy c*.exe d*.exe" during the process of
       figuring out the new name */
    /* Pointer to keep track of how far through the append input(file1+file2+file3) we are */
    TCHAR  * appendPointer = _T("\0");
    /* The full path to src and dest.  This has drive letter, folders, and filename */
    TCHAR tmpDestPath[MAX_PATH];
    TCHAR tmpSrcPath[MAX_PATH];
    /* A bool on weather or not the destination name will be taking from the input */
    BOOL bSrcName = FALSE;
    /* Seems like a waste but it is a pointer used to copy from input to PreserveName */
    TCHAR * UseThisName;
    /* for CMDCOPY env */
    TCHAR *evar;
    int size;
    TCHAR * szTouch;
    BOOL bHasWildcard, bDone = FALSE, bMoreFiles = FALSE;
    BOOL bMultipleSource = FALSE, bMultipleDest = FALSE;


    /* Show help/usage info */
    if (!_tcsncmp(param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE, STRING_COPY_HELP2);
        return 0;
    }

    nErrorLevel = 0;

    /* Get the envor value if it exists */
    evar = cmd_alloc(512 * sizeof(TCHAR));
    if (evar == NULL)
        size = 0;
    else
        size = GetEnvironmentVariable (_T("COPYCMD"), evar, 512);

    if (size > 512)
    {
        TCHAR *old_evar = evar;
        evar = cmd_realloc(evar,size * sizeof(TCHAR) );
        if (evar!=NULL)
            size = GetEnvironmentVariable (_T("COPYCMD"), evar, size);
        else
        {
            size=0;
            evar = old_evar;
        }
    }

    /* check see if we did get any env variable */
    if (size != 0)
    {
        int t = 0;

        /* scan and set the flags */
        for (t = 0; t < size; t++)
        {
            if (_tcsncicmp(_T("/A"),&evar[t],2) == 0)
            {
                dwFlags |=COPY_ASCII;
                t++;
            }
            else if (_tcsncicmp(_T("/B"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_BINARY;
                t++;
            }
            else if (_tcsncicmp(_T("/D"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_DECRYPT;
                t++;
            }
            else if (_tcsncicmp(_T("/V"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_VERIFY;
                t++;
            }
            else if (_tcsncicmp(_T("/N"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_SHORTNAME;
                t++;
            }
            else if (_tcsncicmp(_T("/Y"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_NO_PROMPT;
                t++;
            }
            else if (_tcsncicmp(_T("/-Y"),&evar[t],3) == 0)
            {
                dwFlags |= COPY_PROMPT;
                t+=2;
            }
            else if (_tcsncicmp(_T("/Z"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_PROMPT;
                t++;
            }
        }
    }
    cmd_free(evar);


    /* Split the user input into array */
    arg = split(param, &argc, FALSE, TRUE);
    nFiles = argc;

    /* Read switches and count files */
    for (i = 0; i < argc; i++)
    {
        if (*arg[i] == _T('/'))
        {
            if (_tcslen(arg[i]) >= 2)
            {
                switch (_totupper(arg[i][1]))
                {
                    case _T('A'):
                        dwFlags |= COPY_ASCII;
                        break;

                    case _T('B'):
                        dwFlags |= COPY_BINARY;
                        break;

                    case _T('D'):
                        dwFlags |= COPY_DECRYPT;
                        break;

                    case _T('V'):
                        dwFlags |= COPY_VERIFY;
                        break;

                    case _T('N'):
                        dwFlags |= COPY_SHORTNAME;
                        break;

                    case _T('Y'):
                        dwFlags |= COPY_NO_PROMPT;
                        dwFlags &= ~COPY_PROMPT;
                        break;

                    case _T('-'):
                        if (_tcslen(arg[i]) >= 3)
                            if (_totupper(arg[i][2]) == _T('Y'))
                            {
                                dwFlags &= ~COPY_NO_PROMPT;
                                dwFlags |= COPY_PROMPT;
                            }

                            break;

                    case _T('Z'):
                        dwFlags |= COPY_RESTART;
                        break;

                    default:
                        /* Invalid switch */
                        ConOutResPrintf(STRING_ERROR_INVALID_SWITCH, _totupper(arg[i][1]));
                        nErrorLevel = 1;
                        freep (arg);
                        return 1;
                        break;
                }
            }
            /* If it was a switch, subtract from total arguments */
            nFiles--;
        }
        else
        {
            /* If it isn't a switch then it is the source or destination */
            if (nSrc == -1)
            {
                nSrc = i;
            }
            else if (*arg[i] == _T('+'))
            {
                /* Next file should be appended */
                bMoreFiles = TRUE;
                nFiles -= 1;
            }
            else if (bMoreFiles)
            {
                /* Add this file to the source string
                   this way we can do all checks
                    directly on source string later on */
                TCHAR * ptr;
                int length = (_tcslen(arg[nSrc]) + _tcslen(arg[i]) + 2) * sizeof(TCHAR);
                ptr = cmd_alloc(length);
                if (ptr)
                {
                    _tcscpy(ptr, arg[nSrc]);
                    _tcscat(ptr, _T("|"));
                    _tcscat(ptr, arg[i]);
                    cmd_free(arg[nSrc]);
                    arg[nSrc] = ptr;
                    nFiles -= 1;
                }

                bMoreFiles = FALSE;
            }
            else if (nDes == -1)
            {
                nDes = i;
            }
        }
    }

    /* keep quiet within batch files */
    if (bc != NULL)
    {
        dwFlags |= COPY_NO_PROMPT;
        dwFlags &= ~COPY_PROMPT;
    }

    if (nFiles < 1)
    {
        /* There are not enough files, there has to be at least 1 */
        ConOutResPuts(STRING_ERROR_REQ_PARAM_MISSING);
        freep(arg);
        return 1;
    }

    if (nFiles > 2)
    {
        /* There are too many file names in command */
        ConErrResPrintf(STRING_ERROR_TOO_MANY_PARAMETERS,_T(""));
        nErrorLevel = 1;
        freep(arg);
        return 1;
    }

    if ((_tcschr(arg[nSrc], _T('|')) != NULL) ||
        (_tcschr(arg[nSrc], _T('*')) != NULL) ||
        (_tcschr(arg[nSrc], _T('?')) != NULL) ||
        IsExistingDirectory(arg[nSrc]))
    {
        bMultipleSource = TRUE;
    }

    /* Reusing the number of files variable */
    nFiles = 0;

    /* Check if no destination argument is passed */
    if (nDes == -1)
    {
        /* If no destination was entered then just use
        the current directory as the destination */
        GetCurrentDirectory(MAX_PATH, szDestPath);
    }
    else
    {
        /* Check if the destination is 'x:' */
        if ((arg[nDes][1] == _T(':')) && (arg[nDes][2] == _T('\0')))
        {
            GetRootPath(arg[nDes], szDestPath, MAX_PATH);
        }
        else
        {
            /* If the user entered two file names then form the full string path */
            GetFullPathName(arg[nDes], MAX_PATH, szDestPath, NULL);
        }

        /* Make sure there is an ending slash to the path if the dest is a folder */
        if ((_tcschr(szDestPath, _T('*')) == NULL) &&
            IsExistingDirectory(szDestPath))
        {
            bMultipleDest = TRUE;
            if (szDestPath[_tcslen(szDestPath) -  1] != _T('\\'))
                _tcscat(szDestPath, _T("\\"));
        }

        /* Check if the destination uses wildcards */
        if ((_tcschr(arg[nDes], _T('*')) != NULL) ||
            (_tcschr(arg[nDes], _T('?')) != NULL))
        {
            bMultipleDest = TRUE;
        }
    }

    if (nDes != -1) /* you can only append files when there is a destination */
    {
        if (bMultipleSource && !bMultipleDest)
        {
            /* We have multiple source files, but not multiple destination
               files. This means we are appending the soruce files. */
            bAppend = TRUE;
            if (_tcschr(arg[nSrc], _T('|')) != NULL)
                appendPointer = arg[nSrc];
        }
    }

    /* Save the name the user entered */
    UseThisName = _tcsrchr(szDestPath,_T('\\'));
    if (UseThisName)
    {
        /* Split the name from the path */
        *UseThisName++ = _T('\0');

        /* Check if the dest path ends with '\*' or '\' */
        if (((UseThisName[0] == _T('*')) && (UseThisName[1] == _T('\0'))) ||
            (UseThisName[0] == _T('\0')))
        {
            /* In this case we will be using the same name as the source file
            for the destination file because destination is a folder */
            bSrcName = TRUE;
            UseThisName = NULL;
        }
    }
    else
    {
        /* Something's seriously wrong! */
        UseThisName = szDestPath;
    }

    do
    {
        /* Get the full string of the path to the source file */
        if (_tcschr(arg[nSrc], _T('|')) != NULL)
        {
            /* Reset the source path */
            szSrcPath[0] = _T('\0');

            /* Loop through the source file name and copy all
            the chars one at a time until it gets too + */
            while(TRUE)
            {
                if (appendPointer[0] == _T('|'))
                {
                    /* Skip the | and go to the next file name */
                    appendPointer++;
                    break;
                }
                else if (appendPointer[0] == _T('\0'))
                {
                    bDone = TRUE;
                    break;
                }

                _tcsncat(szSrcPath, appendPointer, 1);
                appendPointer++;
            }

            if (_tcschr(arg[nSrc], _T(',')) != NULL)
            {
                /* Only time there is a , in the source is when they are using touch
                   Cant have a destination and can only have on ,, at the end of the string
                    Cant have more then one file name */
                szTouch = _tcsstr(arg[nSrc], _T("|"));
                if (_tcsncmp(szTouch,_T("|,,\0"), 4) || (nDes != -1))
                {
                    ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT,arg[nSrc]);
                    nErrorLevel = 1;
                    freep (arg);
                    return 1;
                }
                bTouch = TRUE;
                bDone = TRUE;
            }
        }
        else
        {
            bDone = TRUE;
            _tcscpy(szSrcPath, arg[nSrc]);
        }

        /* "x:" is not a valid source path format. */
        if ((szSrcPath[1] == _T(':')) && (szSrcPath[2] == _T('\0')))
        {
            ConOutPrintf(_T("%s\n"), szSrcPath);
            ConOutFormatMessage(ERROR_FILE_NOT_FOUND, szSrcPath);
            nErrorLevel = 1;
            break;
        }


        /* From this point on, we can assume that the shortest path is 3 letters long
        and that would be [DriveLetter]:\ */

        /* Check if the path has a wildcard */
        bHasWildcard = (_tcschr(szSrcPath, _T('*')) != NULL);

        /* If there is no * in the path name and it is a folder then we will
           need to add a wildcard to the pathname so FindFirstFile comes up
           with all the files in that folder */
        if (!bHasWildcard && IsExistingDirectory(szSrcPath))
        {
            /* If it doesnt have a \ at the end already then on needs to be added */
            if (szSrcPath[_tcslen(szSrcPath) -  1] != _T('\\'))
                _tcscat(szSrcPath, _T("\\"));
            _tcscat(szSrcPath, _T("*"));
            bHasWildcard = TRUE;
        }

        /* If the path ends with '\' add a wildcard at the end */
        if (szSrcPath[_tcslen(szSrcPath) -  1] == _T('\\'))
        {
            _tcscat(szSrcPath, _T("*"));
            bHasWildcard = TRUE;
        }

        /* Get a list of all the files */
        hFile = FindFirstFile(szSrcPath, &findBuffer);

        /* If it couldnt open the file handle, print out the error */
        if (hFile == INVALID_HANDLE_VALUE)
        {
            /* only print source name when more then one file */
            if (bMultipleSource)
                ConOutPrintf(_T("%s\n"), szSrcPath);

            ConOutFormatMessage(GetLastError(), szSrcPath);
            freep(arg);
            nErrorLevel = 1;
            return 1;
        }

        /* Strip the paths back to the folder they are in */
        for (i = (_tcslen(szSrcPath) -  1); i > -1; i--)
            if (szSrcPath[i] != _T('\\'))
                szSrcPath[i] = _T('\0');
            else
                break;

        do
        {
            /* Check Breaker */
            if (CheckCtrlBreak(BREAK_INPUT))
            {
                FindClose(hFile);
                freep(arg);
                return 1;
            }

            /* Set the override to yes each new file */
            nOverwrite = 1;

            /* Ignore the . and .. files */
            if (!_tcscmp(findBuffer.cFileName, _T("."))  ||
                !_tcscmp(findBuffer.cFileName, _T("..")) ||
                findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                continue;
            }

            /* Copy the base folder over to a tmp string */
            _tcscpy(tmpDestPath, szDestPath);
            _tcscat(tmpDestPath, _T("\\"));

            /* Can't put a file into a folder that isn't there */
            if (_tcscmp(tmpDestPath, _T("\\\\.\\")) &&
                !IsExistingDirectory(tmpDestPath))
            {
                FindClose(hFile);
                ConOutFormatMessage(GetLastError(), szSrcPath);
                freep(arg);
                nErrorLevel = 1;
                return 1;
            }

            /* Copy over the destination path name */
            if (bSrcName)
                _tcscat(tmpDestPath, findBuffer.cFileName);
            else
            {
                /* If there is no wildcard you can use the name the user entered */
                if ((_tcschr(UseThisName, _T('*')) == NULL) &&
                    (_tcschr(UseThisName, _T('?')) == NULL))
                {
                    _tcscat(tmpDestPath, UseThisName);
                }
                else
                {
                    TCHAR DoneFile[MAX_PATH];

                    BuildFileName(findBuffer.cFileName,
                                  UseThisName,
                                  DoneFile);


                    /* Add the filename to the tmp string path */
                    _tcscat(tmpDestPath, DoneFile);
                }
            }

            /* Build the string path to the source file */
            _tcscpy(tmpSrcPath,szSrcPath);
            _tcscat (tmpSrcPath, findBuffer.cFileName);

            /* Check to see if the file is the same file */
            if (!bTouch && !_tcscmp(tmpSrcPath, tmpDestPath))
            {
                ConOutResPrintf(STRING_COPY_ERROR2);

                nErrorLevel = 1;
                break;
            }

            /* only print source name when more then one file */
            if (bMultipleSource)
                ConOutPrintf(_T("%s\n"), tmpSrcPath);

            /* Handle any overriding / prompting that needs to be done */
            if (((!(dwFlags & COPY_NO_PROMPT) && IsExistingFile (tmpDestPath)) || dwFlags & COPY_PROMPT) && !bTouch)
                nOverwrite = CopyOverwrite(tmpDestPath);
            if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
                continue;
            if (nOverwrite == PROMPT_ALL || (nOverwrite == PROMPT_YES && bAppend))
                dwFlags |= COPY_NO_PROMPT;

            /* Tell weather the copy was successful or not */
            if (copy(tmpSrcPath,tmpDestPath, bAppend, dwFlags, bTouch))
            {
                nFiles++;
                //LoadString(CMD_ModuleHandle, STRING_MOVE_ERROR1, szMsg, RC_STRING_MAX_SIZE);
            }
            else
            {
                /* print out the error message */
                ConOutResPrintf(STRING_COPY_ERROR3);
                ConOutFormatMessage (GetLastError(), szSrcPath);
                nErrorLevel = 1;
            }

        /* Loop through all wildcard files */
        } while (FindNextFile(hFile, &findBuffer));

    /* Loop through all files in src string with a + */
    } while(!bDone);

    /* print out the number of files copied */
    ConOutResPrintf(STRING_COPY_FILE, bAppend ? 1 : nFiles);

    if (hFile) FindClose(hFile);

    if (arg != NULL)
        freep(arg);

    return 0;
}
Esempio n. 19
0
command_t *
cmd_parse(parsestate_t *parsestate)
{
	int i = 0;
	command_t *cmd = cmd_alloc();
	if (!cmd)
		return NULL;

	while (1) {

		// Read the next token from 'parsestate'.
		token_t token;
		parse_gettoken(parsestate, &token);

		// Normal tokens go in the cmd->argv[] array.
		// Redirection file names go into cmd->redirect_filename[].
		// Open parenthesis tokens indicate a subshell command.
		// Other tokens complete the current command
		// and are not actually part of it;
		// we use parse_ungettoken() to save those tokens for later.

		switch (token.type) {
		case TOK_NORMAL:
                    // Overflow on normal tokens
			if (i >= MAXTOKENS || cmd->subshell)
				goto error;
			cmd->argv[i] = strdup(token.buffer);
			i++;
			break;
		case TOK_LESS_THAN:
		case TOK_GREATER_THAN:
		case TOK_2_GREATER_THAN: {
			int fd = token.type - TOK_LESS_THAN;
			// Can't redirect nothing
			if (i == 0 && !cmd->subshell)
				goto error;
            // Redirection tokens (<, >, 2>) must be followed by
            // TOK_NORMAL tokens containing file names.
			parse_gettoken(parsestate, &token);
			if (token.type != TOK_NORMAL)
				goto error;
			free(cmd->redirect_filename[fd]);
			cmd->redirect_filename[fd] = strdup(token.buffer);
			break;
		}
		case TOK_OPEN_PAREN:

             // EXERCISE: Handle parentheses.
             // NOTE the following:
             //     --Parentheses in the shell do not act like
             //     mathematical parentheses.
             //     --In particular, a parenthesized subcommand cannot
             //     be part of the same command as other normal tokens.
             //     For example, "echo ( echo foo )",
             //                  "( echo foo ) echo", and
             //                  "(echo foo) (echo foo)"
             //
             //     are all syntax errors.  (You should figure out
             //     exactly how to check for this kind of error. Try
             //     interacting with the actual 'bash' shell for some
             //     ideas.)
             //
             // Some hints for the code:
             //     --An open parenthesis should recursively call
             //     cmd_line_parse(). The command_t structure has a slot
             //     you can use.
             //     --'goto error' when you encounter an error,
             //     which frees the current command and returns NULL.
             //     --You will need to adjust the logic in the "done:"
             //     block, below. Otherwise, a subshell will be regarded as
             //     an error (why?)
             //     --You don't have to write a lot of code here, but
             //     you will have to understand how the pieces that you
             //     have been given fit together. (It may be helpful to
             //     look over cmdparse.h again.)
            /* Your code here. */
			cmd->subshell = cmd_line_parse(parsestate, 1);
			if(!cmd->subshell){
				goto error;
			}

			break;
		default:
			parse_ungettoken(parsestate);
			goto done;
		}
	}

 done:
	// NULL-terminate the argv list
	cmd->argv[i] = 0;

	if (i == 0 && !cmd->subshell) {
		/* Empty command */
		cmd_free(cmd);
		return NULL;
	} else
		return cmd;

 error:
	cmd_free(cmd);
	return NULL;
}
Esempio n. 20
0
bool workflow_try_compile( workflow_type * script , const subst_list_type * context) {
  if (util_file_exists( script->src_file )) {
    const char * src_file = script->src_file;
    char * tmp_file = NULL;
    bool   update = false;
    if (context != NULL) {
      tmp_file = util_alloc_tmp_file("/tmp" , "ert-workflow" , false );
      update = subst_list_filter_file( context , script->src_file , tmp_file );
      if (update) {
        script->compiled = false;
        src_file = tmp_file;
      } else {
        remove( tmp_file );
        free( tmp_file );
        tmp_file = NULL;
      }
    }

    {
      time_t src_mtime = util_file_mtime( script->src_file );
      if (script->compiled) {
        if (util_difftime_seconds( src_mtime , script->compile_time ) > 0 )
          return true;
        else {
          // Script has been compiled succesfully, but then changed afterwards.
          // We try to recompile; if that fails we are left with 'nothing'.
        }
      }
    }

    {
      // Try to compile
      config_parser_type * config_compiler = workflow_joblist_get_compiler( script->joblist );
      script->compiled = false;
      workflow_clear( script );
      {
        config_content_type * content = config_parse( config_compiler , src_file , WORKFLOW_COMMENT_STRING , WORKFLOW_INCLUDE , NULL , CONFIG_UNRECOGNIZED_ERROR , true );

        if (config_content_is_valid( content )) {
          int cmd_line;
          for (cmd_line = 0; cmd_line < config_content_get_size(content); cmd_line++) {
            const config_content_node_type * node = config_content_iget_node( content , cmd_line );
            const char * jobname = config_content_node_get_kw( node );
            const workflow_job_type * job = workflow_joblist_get_job( script->joblist , jobname );
            cmd_type * cmd = cmd_alloc( job , config_content_node_get_stringlist( node ));

            workflow_add_cmd( script , cmd );
          }
          script->compiled = true;
        } else
          workflow_store_error( script , config_content_get_errors( content ));

        config_content_free( content );
      }
    }

    if (tmp_file != NULL) {
      if (script->compiled)
        remove( tmp_file );
      free( tmp_file );
    }
  }

  // It is legal to remove the script after successfull compilation but
  // then the context will not be applied at subsequent invocations.
  return script->compiled;
}
Esempio n. 21
0
BOOL
SearchForExecutable (LPCTSTR pFileName, LPTSTR pFullName)
{
    static TCHAR pszDefaultPathExt[] = _T(".com;.exe;.bat;.cmd");
    LPTSTR pszPathExt, pszPath;
    LPTSTR pCh;
    DWORD  dwBuffer;
    TRACE ("SearchForExecutable: \'%s\'\n", debugstr_aw(pFileName));

    /* load environment variable PATHEXT */
    pszPathExt = (LPTSTR)cmd_alloc (ENV_BUFFER_SIZE * sizeof(TCHAR));
    dwBuffer = GetEnvironmentVariable (_T("PATHEXT"), pszPathExt, ENV_BUFFER_SIZE);
    if (dwBuffer > ENV_BUFFER_SIZE)
    {
        LPTSTR pszOldPathExt = pszPathExt;
        pszPathExt = (LPTSTR)cmd_realloc (pszPathExt, dwBuffer * sizeof (TCHAR));
        if (pszPathExt == NULL)
        {
            cmd_free(pszOldPathExt);
            return FALSE;
        }
        GetEnvironmentVariable (_T("PATHEXT"), pszPathExt, dwBuffer);
        _tcslwr(pszPathExt);
    }
    else if (0 == dwBuffer)
    {
        _tcscpy(pszPathExt, pszDefaultPathExt);
    }
    else
    {
        _tcslwr(pszPathExt);
    }

    /* Check if valid directly on specified path */
    if (SearchForExecutableSingle(pFileName, pFullName, pszPathExt, NULL))
    {
        cmd_free(pszPathExt);
        return TRUE;
    }

    /* If an explicit directory was given, stop here - no need to search PATH. */
    if (pFileName[1] == _T(':') || _tcschr(pFileName, _T('\\')))
    {
        cmd_free(pszPathExt);
        return FALSE;
    }

    /* load environment variable PATH into buffer */
    pszPath = (LPTSTR)cmd_alloc (ENV_BUFFER_SIZE * sizeof(TCHAR));
    dwBuffer = GetEnvironmentVariable (_T("PATH"), pszPath, ENV_BUFFER_SIZE);
    if (dwBuffer > ENV_BUFFER_SIZE)
    {
        LPTSTR pszOldPath = pszPath;
        pszPath = (LPTSTR)cmd_realloc (pszPath, dwBuffer * sizeof (TCHAR));
        if (pszPath == NULL)
        {
            cmd_free(pszOldPath);
            cmd_free(pszPathExt);
            return FALSE;
        }
        GetEnvironmentVariable (_T("PATH"), pszPath, dwBuffer);
    }

    TRACE ("SearchForExecutable(): Loaded PATH: %s\n", debugstr_aw(pszPath));

    /* search in PATH */
    pCh = _tcstok(pszPath, _T(";"));
    while (pCh)
    {
        if (SearchForExecutableSingle(pFileName, pFullName, pszPathExt, pCh))
        {
            cmd_free(pszPath);
            cmd_free(pszPathExt);
            return TRUE;
        }
        pCh = _tcstok(NULL, _T(";"));
    }

    cmd_free(pszPath);
    cmd_free(pszPathExt);
    return FALSE;
}
Esempio n. 22
0
static INT
PrintAssociation(LPTSTR extension)
{
    DWORD return_val;
    HKEY hKey = NULL, hInsideKey = NULL;

    DWORD fileTypeLength = 0;
    LPTSTR fileType = NULL;

    return_val = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Classes"), 0, KEY_READ, &hKey);

    if (return_val != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        return -1;
    }

    return_val = RegOpenKeyEx(hKey, extension, 0, KEY_READ, &hInsideKey);

    if (return_val != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        RegCloseKey(hInsideKey);
        return 0;
    }

    /* obtain string length */
    return_val = RegQueryValueEx(hInsideKey, NULL, NULL, NULL, NULL, &fileTypeLength);

    if (return_val == ERROR_FILE_NOT_FOUND)	/* no default value, don't display */
    {
        RegCloseKey(hInsideKey);
        RegCloseKey(hKey);
        return 0;
    }

    if (return_val != ERROR_SUCCESS)
    {
        RegCloseKey(hInsideKey);
        RegCloseKey(hKey);
        return -2;
    }

    fileType = cmd_alloc(fileTypeLength * sizeof(TCHAR));

    /* obtain actual file type */
    return_val = RegQueryValueEx(hInsideKey, NULL, NULL, NULL, (LPBYTE) fileType, &fileTypeLength);

    RegCloseKey(hInsideKey);
    RegCloseKey(hKey);

    if (return_val != ERROR_SUCCESS)
    {
        cmd_free(fileType);
        return -2;
    }

    if (fileTypeLength != 0)	/* if there is a default key, display relevant information */
    {
        ConOutPrintf(_T("%s=%s\n"), extension, fileType);
    }

    if (fileTypeLength)
        cmd_free(fileType);

    return 1;
}
Esempio n. 23
0
/* specified routines */
VOID ExpandAlias (LPTSTR cmd, INT maxlen)
{
    LPTSTR buffer;
    TCHAR *position, *in, *out;
    LPTSTR Token;
    LPTSTR tmp;

    tmp = cmd_dup(cmd);
    if (!tmp)
        return;

    /* first part is the macro name */
    position = tmp + _tcscspn(tmp, _T(" \n"));
    if (position == tmp)
    {
        cmd_free(tmp);
        return;
    }
    *position++ = _T('\0');
    position += _tcsspn(position, _T(" "));

    buffer = cmd_alloc(maxlen);
    if (!buffer)
    {
        WARN("Cannot allocate memory for alias buffer!\n");
        cmd_free(tmp);
        return;
    }

    if (GetConsoleAlias(tmp, buffer, maxlen, _T("cmd.exe")) == 0)
    {
        cmd_free(tmp);
        cmd_free(buffer);
        return;
    }

    in = buffer;
    out = cmd;
    while (*in)
    {
        if (*in == _T('$'))
        {
            Token = position;
            if (in[1] >= _T('1') && in[1] <= _T('9'))
            {
                /* Copy a single space-delimited token from the input line */
                INT num;
                for (num = in[1] - _T('1'); num > 0; num--)
                {
                    Token += _tcscspn(Token, _T(" \n"));
                    Token += _tcsspn(Token, _T(" "));
                }
                while (!_tcschr(_T(" \n"), *Token))
                {
                    if (out >= &cmd[maxlen - 1])
                        break;
                    *out++ = *Token++;
                }
                in += 2;
                continue;
            }
            else if (in[1] == _T('*'))
            {
                /* Copy the entire remainder of the line */
                while (*Token && *Token != _T('\n'))
                {
                    if (out >= &cmd[maxlen - 1])
                        break;
                    *out++ = *Token++;
                }
                in += 2;
                continue;
            }
        }
        if (out >= &cmd[maxlen - 1])
            break;
        *out++ = *in++;
    }
    *out++ = _T('\n');
    *out = _T('\0');

    cmd_free(buffer);
    cmd_free(tmp);
}