// Handles launching the game indirectly via steam
void LaunchSelfViaSteam(const char *params)
{
	// calculate the details of our launch
	char appPath[MAX_PATH];
	::GetModuleFileName((HINSTANCE)GetModuleHandle(NULL), appPath, sizeof(appPath));

	// strip out the exe name
	char *slash = strrchr(appPath, '\\');
	if (slash)
	{
		*slash = '\0';
	}

	// save out our details to the registry
	HKEY hKey;
	if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam", &hKey))
	{
		DWORD dwType = REG_SZ;
		DWORD dwSize = static_cast<DWORD>( strlen(appPath) + 1 );
		RegSetValueEx(hKey, "TempAppPath", NULL, dwType, (LPBYTE)appPath, dwSize);
		dwSize = static_cast<DWORD>( strlen(params) + 1 );
		RegSetValueEx(hKey, "TempAppCmdLine", NULL, dwType, (LPBYTE)params, dwSize);
		// clear out the appID (since we don't know it yet)
		dwType = REG_DWORD;
		int appID = -1;
		RegSetValueEx(hKey, "TempAppID", NULL, dwType, (LPBYTE)&appID, sizeof(appID));
		RegCloseKey(hKey);
	}

	// search for an active steam instance
	HWND hwnd = ::FindWindow("Valve_SteamIPC_Class", "Hidden Window");
	if (hwnd)
	{
		::PostMessage(hwnd, WM_USER + 3, 0, 0);
	}
	else
	{
		// couldn't find steam, find and launch it

		// first, search backwards through our current set of directories
		char steamExe[MAX_PATH] = "";
		char dir[MAX_PATH];

		if (::GetCurrentDirectoryA(sizeof(dir), dir))
		{
			char *slash = strrchr(dir, '\\');
			while (slash)
			{
				// see if steam_dev.exe is in the directory first
				slash[1] = 0;
				strcat(slash, "steam_dev.exe");
				FILE *f = fopen(dir, "rb");
				if (f)
				{
					// found it
					fclose(f);
					strcpy(steamExe, dir);
					break;
				}

				// see if steam.exe is in the directory
				slash[1] = 0;
				strcat(slash, "steam.exe");
				f = fopen(dir, "rb");
				if (f)
				{
					// found it
					fclose(f);
					strcpy(steamExe, dir);
					break;
				}

				// kill the string at the slash
				slash[0] = 0;

				// move to the previous slash
				slash = strrchr(dir, '\\');
			}
		}

		if (!steamExe[0])
		{
			// still not found, use the one in the registry
			HKEY hKey;
			if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam", &hKey))
			{
				DWORD dwType;
				DWORD dwSize = sizeof(steamExe);
				RegQueryValueEx(hKey, "SteamExe", NULL, &dwType, (LPBYTE)steamExe, &dwSize);
				RegCloseKey(hKey);
			}
		}

		if (!steamExe[0])
		{
			// still no path, error
			::MessageBox(NULL, "Error running game: could not find steam.exe to launch", "Fatal Error", MB_OK | MB_ICONERROR);
			return;
		}

		// fix any slashes
		for (char *slash = steamExe; *slash; slash++)
		{
			if (*slash == '/')
			{
				*slash = '\\';
			}
		}

		// change to the steam directory
		strcpy(dir, steamExe);
		char *delimiter = strrchr(dir, '\\');
		if (delimiter)
		{
			*delimiter = 0;
			_chdir(dir);
		}

		// exec steam.exe, in silent mode, with the launch app param
		char *args[4] = { steamExe, "-silent", "-applaunch", '\0' };
		_spawnv(_P_NOWAIT, steamExe, args);
	}
}
void CWE78_OS_Command_Injection__char_file_w32_spawnv_53d_badSink(char * data)
{
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink(char * data)
{
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__char_file_w32_spawnv_67b_goodG2BSink(CWE78_OS_Command_Injection__char_file_w32_spawnv_67_structType myStruct)
{
    char * data = myStruct.structFirst;
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
Exemple #5
0
int
execCmd (execCmd_t *execCmdInp, int stdOutFd, int stdErrFd)
{
    char cmdPath[LONG_NAME_LEN];
    char *av[LONG_NAME_LEN];
    int status;
    char *cmdDir;

    cmdDir = getenv("irodsServerCmdDir");
    if (cmdDir) {
        if (cmdDir[strlen(cmdDir)-1] == '/') {
            cmdDir[strlen(cmdDir)-1] = 0;
        }
    }
    else {
        cmdDir = CMD_DIR;
    }

    snprintf (cmdPath, LONG_NAME_LEN, "%s/%s", cmdDir, execCmdInp->cmd); 

    initCmdArg (av, execCmdInp->cmdArgv, cmdPath);

    closeAllL1desc (ThisComm);

#ifndef windows_platform
    /* set up the pipe as the stdin, stdout and stderr */
  
    close (0);
    close (1);
    close (2);

    dup2 (stdOutFd, 0);
    dup2 (stdOutFd, 1);
    dup2 (stdErrFd, 2);
    close (stdOutFd);
    close (stdErrFd);

#ifdef RUN_SERVER_AS_ROOT
    /* if we're running with root real uid, drop all root
       privilege and setuid() to the irods service user
       before running the request command */
    status = dropRootPrivilege();
    if (status < 0) {
        return (status);
    }
#endif

    status = execv (av[0], av);

#else /* Windows: Can Windows redirect the stdin, etc, to a pipe? */
	status = _spawnv(_P_NOWAIT, av[0], av);
#endif

    return (status);
}
void badSink(vector<char *> dataVector)
{
    /* copy data out of dataVector */
    char * data = dataVector[2];
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
static void goodG2B2()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    CWE78_OS_Command_Injection__char_environment_w32_spawnv_22_goodG2B2Global = 1; /* true */
    data = CWE78_OS_Command_Injection__char_environment_w32_spawnv_22_goodG2B2Source(data);
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
void CWE78_OS_Command_Injection__char_file_w32_spawnv_21_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    badStatic = 1; /* true */
    data = badSource(data);
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
static void goodG2B1()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    goodG2B1Static = 0; /* false */
    data = goodG2B1Source(data);
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
Exemple #10
0
int main( int argc, char** argv ) {
 if ( argc < 2 ) puts( "err2out is stdERR TO stdOUT redirector, version 2.2\nCopyright (c) 2002-2003 Denis Ryzhkov ( Creon )\nhttp://creon.cjb.net/?soft/err2out\n\nExamples:\nerr2out \"C:\\Program Files\\jdk\\bin\\javac\" Some.java | more\nerr2out \"C:\\Program Files\\jdk\\bin\\javac\" Some.java > err.txt\nerr2out \"C:\\Program Files\\jdk\\bin\\javac\" Some.java >> err.txt" );
 else {
  _dup2( 1, 2 ); // redirect 2=stderr to 1=stdout
  char** argz = new char*[ argc ]; // -argv[ 0 ], +end0
  argz[ argc - 1 ] = 0; // end0
  for ( int i = 0; i < argc - 1; i++ )
   sprintf( argz[ i ] = new char[ strlen( argv[ i + 1 ] ) + 3 ], // \" \" \000
     "\"%s\"", argv[ i + 1 ] );
  _spawnv( _P_WAIT, argv[ 1 ], argz );
  for ( i = 0; i < argc - 1; i++ ) delete[] argz[ i ];
  delete[] argz;
 }
 return 0;
}
Exemple #11
0
/* ------------------------------------------------------------------------------------ 
 *  spawn jobs on local machine
 * ------------------------------------------------------------------------------------ */
extern int AMUDP_SPMDLocalSpawn(int nproc, int argc, char **argv) {
  /* just a simple fork/exec */
  int i;

  if (!AMUDP_SPMDSpawnRunning) {
    AMUDP_Err("Spawn functions should never be run directly - only passed to AMUDP_SPMDStartup()"); 
    return FALSE;
  }

  for (i = 0; i < nproc; i++) {
    #if PLATFORM_OS_MSWINDOWS && !PLATFORM_OS_CYGWIN
      if (_spawnv(_P_NOWAIT, argv[0], argv) == -1)
        AMUDP_FatalErr("failed _spawnv()");
    #elif PLATFORM_ARCH_CRAYX1
      { char **nargv = (char **)AMUDP_malloc(sizeof(char *)*(argc+2));
        nargv[0] = argv[0];
        memcpy(nargv+1,argv,argc*sizeof(char *));
        nargv[argc+1] = NULL;
        if (execsp(nargv, environ, NULL) == -1)
          AMUDP_FatalErr("failed execsp()");
      }
    #else
      int forkRet = fork();
      if (forkRet == -1) {
        perror("fork");
        return FALSE;
      } else if (forkRet != 0) continue;  /*  this is the parent, will go back to the top of the loop */
      else {  /*  this is the child - exec the new process */
        /*  could close some resources here (like AMUDP_SPMDListenSocket) but not strictly necessary */

        #if 0
          /*  put new process in a separate process group */
          if (setsid() == -1) perror("setsid"); 
        #endif

        /*  exec the program, with the given arguments  */
        execv(argv[0], argv);

        /*  if execv returns, an error occurred */
        perror("execv");
        _exit(1); /*  use _exit() to prevent corrupting parent's io buffers */
      } /*  child */
    #endif
  }
  return TRUE;
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    if(5==5)
    {
        /* FIX: Append a fixed string to data (not user / external input) */
        strcat(data, "*.*");
    }
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
void CWE78_OS_Command_Injection__char_console_w32_spawnv_12_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    if(globalReturnsTrueOrFalse())
    {
        {
            /* Read input from the console */
            size_t dataLen = strlen(data);
            /* if there is room in data, read into it from the console */
            if (100-dataLen > 1)
            {
                /* POTENTIAL FLAW: Read data from the console */
                if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
                {
                    /* The next few lines remove the carriage return from the string that is
                     * inserted by fgets() */
                    dataLen = strlen(data);
                    if (dataLen > 0 && data[dataLen-1] == '\n')
                    {
                        data[dataLen-1] = '\0';
                    }
                }
                else
                {
                    printLine("fgets() failed");
                    /* Restore NUL terminator if fgets fails */
                    data[dataLen] = '\0';
                }
            }
        }
    }
    else
    {
        /* FIX: Append a fixed string to data (not user / external input) */
        strcat(data, "*.*");
    }
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
Exemple #14
0
int
main(int argc, char **argv) 
{
    char **new_argv;
    int k, code;
    new_argv = xmalloc( (argc+2) * sizeof (char *) );
    new_argv[0] = add_to_file_dir("","\\@PROG@");
    new_argv[1] = "@ARGV1@";
    for (k=1; k < argc; k++) new_argv[k+1] = argv[k];
    new_argv[argc+1] = NULL;
    new_argv = prepare_spawn (new_argv);
    code = _spawnv(_P_WAIT, new_argv[0] , (const char **) new_argv );
    if (code == -1) {
        perror("@ARGV1@: Cannot exec @PROG@");
        exit(127);
    }
    else exit(code);
}
void LaunchVConfig()
{
#if defined( _WIN32 ) && !defined( _X360 )
	char vconfigExe[MAX_PATH];
	FileSystem_GetExecutableDir( vconfigExe, sizeof( vconfigExe ) );
	Q_AppendSlash( vconfigExe, sizeof( vconfigExe ) );
	Q_strncat( vconfigExe, "vconfig.exe", sizeof( vconfigExe ), COPY_ALL_CHARACTERS );

	char *argv[] =
	{
		vconfigExe,
		"-allowdebug",
		NULL
	};

	_spawnv( _P_NOWAIT, vconfigExe, argv );
#elif defined( _X360 )
	Msg( "Launching vconfig.exe not supported\n" );
#endif
}
Exemple #16
0
API_EXPORT(int) os_spawnv(int mode, const char *cmdname,
			  const char *const *argv)
{
    int n;
    char **aszArgs;
    const char *szArg;
    char *szCmd;
    char *s;
    
    szCmd = _alloca(strlen(cmdname)+1);
    strcpy(szCmd, cmdname);
    for (s = szCmd; *s; ++s) {
        if (*s == '/') {
            *s = '\\';
	}
    }

    for (n = 0; argv[n]; ++n)
        ;

    aszArgs = _alloca((n + 1) * sizeof(const char *));

    for (n = 0; szArg = argv[n]; ++n) {
        if (strchr(szArg, ' ')) {
            int l = strlen(szArg);

            aszArgs[n] = _alloca(l + 2 + 1);
            aszArgs[n][0] = '"';
            strcpy(&aszArgs[n][1], szArg);
            aszArgs[n][l + 1] = '"';
            aszArgs[n][l + 2] = '\0';
        }
        else {
            aszArgs[n] = (char *)szArg;
        }
    }

    aszArgs[n] = NULL;

    return _spawnv(mode, szCmd, aszArgs);
}
int main(int argc, char* argv[]) {
        char *args[ARG_BUF_SIZE];
        char base_path[PATH_BUF_SIZE + 1];
        char script_path[PATH_BUF_SIZE + 1];
        char shell_path[PATH_BUF_SIZE + 1];
        char env_path[ENV_VAR_SIZE];
        int argi;

        _fullpath(shell_path, argv[0], PATH_BUF_SIZE);
        strcpy(script_path, shell_path);
        strcpy(base_path, shell_path);

        parent(shell_path);
        strcat(shell_path, "\\sh.exe");

        remove_extension(script_path);
        parent(base_path);

        args[0] = shell_path;
        args[1] = "--norc";
        args[2] = script_path;

        /* Any parameters passed on the command line will be passed through to the shell script */
        for (argi = 0; argi < MIN(argc - 1, ARG_BUF_SIZE); argi++) {
                printf("%s\n", argv[argi + 1]);
                args[argi + NUM_EXEC_ARGS] = argv[argi + 1];
        }
        /* Signal the end of the argument list */
        args[argi + NUM_EXEC_ARGS] = NULL;

        /* Add this executable's directory to the path */
        strcpy(env_path, "PATH=");
        strcat(env_path, getenv("PATH"));
        strcat(env_path, ";");
        strcat(env_path, base_path);
        _putenv(env_path);

        _spawnv(_P_WAIT, args[0], &args[1]);

        _flushall();
}
void bad()
{
    char * data;
    char * &dataRef = data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    {
        /* Read input from the console */
        size_t dataLen = strlen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgets() */
                dataLen = strlen(data);
                if (dataLen > 0 && data[dataLen-1] == '\n')
                {
                    data[dataLen-1] = '\0';
                }
            }
            else
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                data[dataLen] = '\0';
            }
        }
    }
    {
        char * data = dataRef;
        {
            char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
            /* spawnv - specify the path where the command is located */
            /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
            _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
        }
    }
}
/* goodG2B1() - use goodsource and badsink by changing the 5==5 to 5!=5 */
static void goodG2B1()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    if(5!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Append a fixed string to data (not user / external input) */
        strcat(data, "*.*");
    }
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
void bad()
{
    char * data;
    char * &dataRef = data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    {
        /* Read input from a file */
        size_t dataLen = strlen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (100-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                {
                    printLine("fgets() failed");
                    /* Restore NUL terminator if fgets fails */
                    data[dataLen] = '\0';
                }
                fclose(pFile);
            }
        }
    }
    {
        char * data = dataRef;
        {
            char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
            /* spawnv - specify the path where the command is located */
            /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
            _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
        }
    }
}
Exemple #21
0
/* ConnectToSkypeAPI
 * 
 * Purpose: Establish a connection to the Skype API
 * Params : ForceRestart - Kill Skype if it's running before restarting
 * Returns: 0 - Connecting succeeded
 *		   -1 - Something went wrong
 */
void ConnectToSkypeAPI(void *ForceRestart) {
	BOOL SkypeLaunched=FALSE;
	int counter=0, i, j;
	char *args[5];
	char *SkypeOptions[]={"/notray", "/nosplash", "/minimized"};
	char *szFuncName="ConnectToSkypeAPI";

	ResetEvent(SkypeReady);
	AttachStatus=-1;
	if ((BOOL)ForceRestart) {
		HANDLE hProc;
		DWORD dwPID=0;

		if (!hSkypeWnd) {
			OUTPUT("I can't kill Skype, as I don't even have its window handle!");
			return;
		}
		GetWindowThreadProcessId(hSkypeWnd, &dwPID);
		LOG(("%s: Shutting down Skype as it was not behaving the way it should...", szFuncName));
		if (hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, FALSE, dwPID)) {

			// Try to shutdown Skype the nice way by asking it to close
			EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM) dwPID);

			if(WaitForSingleObject(hProc, 10000)!=WAIT_OBJECT_0) {
				// Try it the hard way by killing it
				LOG(("%s: I tried it the nice way, but you were not listening! Now DIIIIEEE!", szFuncName));
				if (!TerminateProcess(hProc,0)) {
					OUTPUT("Argh, process refused to die, it's too mighty for me, I've given up");
					CloseHandle(hProc);
					return;
				}
				LOG(("%s: Process killed! >:)", szFuncName));
			}
			CloseHandle(hProc);
		}
	}
	do {
		/*	To initiate communication, Client should broadcast windows message
			('SkypeControlAPIDiscover') to all windows in the system, specifying its own
			window handle in wParam parameter.
		 */
		LOG(("%s: Sending discover message..", szFuncName));
		SendMessageTimeout(HWND_BROADCAST, ControlAPIDiscover, (WPARAM)hWnd, 0, SMTO_ABORTIFHUNG, 3000, NULL);
		LOG(("%s: Discover message sent, waiting for Skype to become ready..", szFuncName));

		/*	In response, Skype responds with
			message 'SkypeControlAPIAttach' to the handle specified, and indicates
			connection status
			SkypeReady is set if there is an answer by Skype other than API_AVAILABLE.
			If there is no answer after 3 seconds, launch Skype as it's propably
			not running.
		*/
		if (WaitForSingleObject(SkypeReady, 3000)==WAIT_TIMEOUT &&
			AttachStatus!=SKYPECONTROLAPI_ATTACH_PENDING_AUTHORIZATION) 
		{
			if (hWnd==NULL) {
				LOG(("%s: hWnd of SkypeDispatchWindow not yet set..", szFuncName));
				continue;
			}
			if (!SkypeLaunched && skype_path) {
				LOG(("%s: Starting Skype, as it's not running", szFuncName));
				args[0]=skype_path;
				j=1;
				for (i=0; i<3; i++) {
					args[j]=SkypeOptions[i];
					LOG(("%s: Using Skype parameter: ", szFuncName, args[j]));
					j++;
				}
				args[j]=NULL;
				_spawnv(_P_NOWAIT, skype_path, args);
				ResetEvent(SkypeReady);
				SkypeLaunched=TRUE;
				LOG(("%s: Skype process started.", szFuncName));
				// Skype launching iniciated, keep sending Discover messages until it responds.
				continue;
			} else {
				LOG(("%s: Check if Skype was launchable..", szFuncName));
				if (!skype_path) {
					OUTPUT("There was no correct path for Skype application");
					bail_out(1);
					return;
				}
				LOG("%s: Trying to attach: #%d", szFuncName, counter));
				counter++;
				if (counter==5) {
					OUTPUT("ERROR: Skype not running / too old / working!");
					bail_out(1);
					return;
				}
			}
		}
		LOG(("%s: Attachstatus %d", szFuncName, AttachStatus));
	} while (AttachStatus==SKYPECONTROLAPI_ATTACH_API_AVAILABLE || AttachStatus==-1);
	
	while (AttachStatus==SKYPECONTROLAPI_ATTACH_PENDING_AUTHORIZATION) Sleep(1000);
	LOG(("%s: Attachstatus %d", szFuncName, AttachStatus));
	if (AttachStatus!=SKYPECONTROLAPI_ATTACH_SUCCESS) {
		switch(AttachStatus) {
			case SKYPECONTROLAPI_ATTACH_REFUSED:
				OUTPUT("Skype refused the connection :(");
				break;
			case SKYPECONTROLAPI_ATTACH_NOT_AVAILABLE:
				OUTPUT("The Skype API is not available");
				break;
			default:
				LOG(("%s: ERROR: AttachStatus: %d", szFuncName, AttachStatus));
				OUTPUT("Wheee, Skype won't let me use the API. :(");
		}
		bail_out(1);
		return;
	}
	OUTPUT("Attached to Skype successfully.");
	if (!WatchDogRunning)
		if (_beginthread(WatchDogTimer, 0, NULL)==-1) {
			OUTPUT("Cannot start Watchdog.");
			bail_out(1);
		}
	return;
}
bool RunCommands(CCommandArray& Commands, LPCTSTR pszOrigDocName)
{
	s_bRunsCommands = true;

	char szCurDir[MAX_PATH];
	_getcwd(szCurDir, MAX_PATH);

	procWnd.GetReady();

	// cut up document name into file and extension components.
	//  create two sets of buffers - one set with the long filename
	//  and one set with the 8.3 format.

	char szDocLongPath[MAX_PATH] = {0}, szDocLongName[MAX_PATH] = {0}, 
		szDocLongExt[MAX_PATH] = {0};
	char szDocShortPath[MAX_PATH] = {0}, szDocShortName[MAX_PATH] = {0}, 
		szDocShortExt[MAX_PATH] = {0};

	GetFullPathName(pszOrigDocName, MAX_PATH, szDocLongPath, NULL);
	GetShortPathName(pszOrigDocName, szDocShortPath, MAX_PATH);

	// split them up
	char *p = strrchr(szDocLongPath, '.');
	if(p && strrchr(szDocLongPath, '\\') < p && strrchr(szDocLongPath, '/') < p)
	{
		// got the extension
		strcpy(szDocLongExt, p+1);
		p[0] = 0;
	}

	p = strrchr(szDocLongPath, '\\');
	if(!p)
		p = strrchr(szDocLongPath, '/');
	if(p)
	{
		// got the filepart
		strcpy(szDocLongName, p+1);
		p[0] = 0;
	}

	// split the short part up
	p = strrchr(szDocShortPath, '.');
	if(p && strrchr(szDocShortPath, '\\') < p && strrchr(szDocShortPath, '/') < p)
	{
		// got the extension
		strcpy(szDocShortExt, p+1);
		p[0] = 0;
	}

	p = strrchr(szDocShortPath, '\\');
	if(!p)
		p = strrchr(szDocShortPath, '/');
	if(p)
	{
		// got the filepart
		strcpy(szDocShortName, p+1);
		p[0] = 0;
	}

	int iSize = Commands.GetSize(), i = 0;
	char *ppParms[32];
	while(iSize--)
	{
		CCOMMAND &cmd = Commands[i++];

		// anything there?
		if((!cmd.szRun[0] && !cmd.iSpecialCmd) || !cmd.bEnable)
			continue;

		// set name pointers for long filenames
		pszDocExt = szDocLongExt;
		pszDocName = szDocLongName;
		pszDocPath = szDocLongPath;
		
		char szNewParms[MAX_PATH*5], szNewRun[MAX_PATH*5];

		// HACK: force the spawnv call for launching the game
		if (!Q_stricmp(cmd.szRun, "$game_exe"))
		{
			cmd.bUseProcessWnd = FALSE;
		}

		FixGameVars(cmd.szRun, szNewRun, TRUE);
		FixGameVars(cmd.szParms, szNewParms, TRUE);

		CString strTmp;
		strTmp.Format("\r\n"
			"** Executing...\r\n"
			"** Command: %s\r\n"
			"** Parameters: %s\r\n\r\n", szNewRun, szNewParms);
		procWnd.Append(strTmp);
		
		// create a parameter list (not always required)
		if(!cmd.bUseProcessWnd || cmd.iSpecialCmd)
		{
			char *p = szNewParms;
			ppParms[0] = szNewRun;
			int iArg = 1;
			BOOL bDone = FALSE;
			while(p[0])
			{
				ppParms[iArg++] = p;
				while(p[0])
				{
					if(p[0] == ' ')
					{
						// found a space-separator
						p[0] = 0;

						p++;

						// skip remaining white space
						while (*p == ' ')
							p++;

						break;
					}

					// found the beginning of a quoted parameters
					if(p[0] == '\"')
					{
						while(1)
						{
							p++;
							if(p[0] == '\"')
							{
								// found the end
								if(p[1] == 0)
									bDone = TRUE;
								p[1] = 0;	// kick its ass
								p += 2;

								// skip remaining white space
								while (*p == ' ')
									p++;

								break;
							}
						}
						break;
					}

					// else advance p
					++p;
				}

				if(!p[0] || bDone)
					break;	// done.
			}

			ppParms[iArg] = NULL;

			if(cmd.iSpecialCmd)
			{
				BOOL bError = FALSE;
				LPCTSTR pszError = "";

				if(cmd.iSpecialCmd == CCCopyFile && iArg == 3)
				{
					RemoveQuotes(ppParms[1]);
					RemoveQuotes(ppParms[2]);
					
					// don't copy if we're already there
					if (stricmp(ppParms[1], ppParms[2]) && 					
							(!CopyFile(ppParms[1], ppParms[2], FALSE)))
					{
						bError = TRUE;
						pszError = GetErrorString();
					}
				}
				else if(cmd.iSpecialCmd == CCDelFile && iArg == 2)
				{
					RemoveQuotes(ppParms[1]);
					if(!DeleteFile(ppParms[1]))
					{
						bError = TRUE;
						pszError = GetErrorString();
					}
				}
				else if(cmd.iSpecialCmd == CCRenameFile && iArg == 3)
				{
					RemoveQuotes(ppParms[1]);
					RemoveQuotes(ppParms[2]);
					if(rename(ppParms[1], ppParms[2]))
					{
						bError = TRUE;
						pszError = strerror(errno);
					}
				}
				else if(cmd.iSpecialCmd == CCChangeDir && iArg == 2)
				{
					RemoveQuotes(ppParms[1]);
					if(mychdir(ppParms[1]) == -1)
					{
						bError = TRUE;
						pszError = strerror(errno);
					}
				}

				if(bError)
				{
					CString str;
					str.Format("The command failed. Windows reported the error:\r\n"
						"  \"%s\"\r\n", pszError);
					procWnd.Append(str);
					procWnd.SetForegroundWindow();
					str += "\r\nDo you want to continue?";
					if(AfxMessageBox(str, MB_YESNO) == IDNO)
						break;
				}
			}
			else
			{
				// Change to the game exe folder before spawning the engine.
				// This is necessary for Steam to find the correct Steam DLL (it
				// uses the current working directory to search).
				char szDir[MAX_PATH];
				Q_strncpy(szDir, szNewRun, sizeof(szDir));
				Q_StripFilename(szDir);

				mychdir(szDir);

				// YWB Force asynchronous operation so that engine doesn't hang on
				//  exit???  Seems to work.
				// spawnv doesn't like quotes
				RemoveQuotes(szNewRun);
				_spawnv(/*cmd.bNoWait ?*/ _P_NOWAIT /*: P_WAIT*/, szNewRun, 
					(const char *const *)ppParms);
			}
		}
		else
		{
			procWnd.Execute(szNewRun, szNewParms);
		}

		// check for existence?
		if(cmd.bEnsureCheck)
		{
			char szFile[MAX_PATH];
			FixGameVars(cmd.szEnsureFn, szFile, FALSE);
			if(GetFileAttributes(szFile) == 0xFFFFFFFF)
			{
				// not there!
				CString str;
				str.Format("The file '%s' was not built.\n"
					"Do you want to continue?", szFile);
				procWnd.SetForegroundWindow();
				if(AfxMessageBox(str, MB_YESNO) == IDNO)
					break;	// outta here
			}
		}
	}

	mychdir(szCurDir);

	s_bRunsCommands = false;

	return TRUE;
}
Exemple #23
0
int
main(int argc, char *argv[])
{
#ifdef WINDOWS
    HANDLE hchild;
    int child;
#else
    pid_t child;
#endif
    int rc;
    int arg_offs = 1;
    const char *outfile = NULL;
    const char *pidfile = NULL;

    if (argc < 2) {
        return usage(argv[0]);
    }
    while (argv[arg_offs][0] == '-') {
        if (strcmp(argv[arg_offs], "-env") == 0) {
            if (argc <= arg_offs + 2)
                return usage(argv[0]);
#if VERBOSE
            fprintf(stderr, "setting env var \"%s\" to \"%s\"\n", argv[arg_offs + 1],
                    argv[arg_offs + 2]);
#endif
#ifdef WINDOWS
            rc = SetEnvironmentVariable(argv[arg_offs + 1], argv[arg_offs + 2]);
#else
            rc = setenv(argv[arg_offs + 1], argv[arg_offs + 2], 1 /*overwrite*/);
#endif
            if (rc != 0 ||
                strcmp(mygetenv(argv[arg_offs + 1]), argv[arg_offs + 2]) != 0) {
                fprintf(stderr, "error in setenv of \"%s\" to \"%s\"\n",
                        argv[arg_offs + 1], argv[arg_offs + 2]);
                fprintf(stderr, "setenv returned %d\n", rc);
                fprintf(stderr, "env var \"%s\" is now \"%s\"\n", argv[arg_offs + 1],
                        mygetenv(argv[arg_offs + 1]));
                exit(1);
            }
            arg_offs += 3;
        } else if (strcmp(argv[arg_offs], "-out") == 0) {
            if (argc <= arg_offs + 1)
                return usage(argv[0]);
            outfile = argv[arg_offs + 1];
            arg_offs += 2;
        } else if (strcmp(argv[arg_offs], "-pid") == 0) {
            if (argc <= arg_offs + 1)
                return usage(argv[0]);
            pidfile = argv[arg_offs + 1];
            arg_offs += 2;
        } else {
            return usage(argv[0]);
        }
        if (argc - arg_offs < 1)
            return usage(argv[0]);
    }

#ifdef UNIX
    child = fork();
    if (child < 0) {
        perror("ERROR on fork");
    } else if (child == 0) {
        /* redirect std{out,err} */
        redirect_stdouterr(outfile);
        execv(argv[arg_offs], argv + arg_offs /*include app*/);
        fprintf(stderr, "execv of %s FAILED", argv[arg_offs]);
        exit(1);
    }
    /* else, parent, and we continue below */
    if (pidfile == NULL)
        printf("%d\n", child);
#else
    /* redirect std{out,err} */
    redirect_stdouterr(outfile);
    /* Do we want _P_DETACH instead of _P_NOWAIT?  _P_DETACH doesn't return the
     * child handle though.
     */
    hchild = (HANDLE)_spawnv(_P_NOWAIT, argv[arg_offs], argv + arg_offs /*include app*/);
    if (hchild == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "_spawnv of %s FAILED", argv[arg_offs]);
        exit(1);
    }
    child = process_id_from_handle(hchild);
#endif
    if (pidfile != NULL) {
        FILE *f = fopen(pidfile, "w");
        if (f == NULL) {
            perror("open pidfile failed");
            exit(1);
        }
        fprintf(f, "%d\n", child);
        fclose(f);
    }
    return 0;
}
Exemple #24
0
static int make_sofile(int kflag, char *so_file, char **o_files)
{
#if	!defined(WIN32)
    int		pid;
#endif
    extern int	unlink(const char *);

    struct stat	stat_o, stat_so;

    int		status;
    int		ac, i;
    char	**ofs;
    char	*av[64];		/* hope that this is enough! */

    if(stat(so_file, &stat_so) == 0) {		/* hmmm, so_file exists */
	ofs	= o_files;
	while(*ofs) {
	    if(stat(*ofs, &stat_o) == -1 || stat_so.st_mtime <= stat_o.st_mtime)
		break;
	    ++ofs;
	}
	if(*ofs == (char *)NULL)
	    return(0);
    }

#if	defined(USE_WIN32)
    ac	 =	0;
    av[ac++] =	"LINK";
    av[ac++] =	"/FORCE:UNRESOLVED";
    av[ac++] =	"/DLL";

    sprintf(chararray, "/OUT:%s", so_file);
    av[ac++] =	strdup(chararray);

    for(i=0 ; i<nlinkerflags ; ++i)		/* add any -L or -l switches */
	av[ac++] =	linkerflags[i];

    if(!vflag)
	av[ac++] = "/NOLOGO";

    ofs	 =	o_files;
    while(*ofs)
	av[ac++] = *ofs++;

    av[ac  ] =	(char *)NULL;

    if(dflag) {
	fputs(av[0], stderr);
	for(i=2 ; i<ac ; i++)
	    fprintf(stderr," %s",av[i]);
	fputc('\n',stderr);
    }
    else
	fprintf(stderr,"linking %s\n", so_file);

    status  = _spawnv(_P_WAIT, av[0], &av[1]);
    if(status != 0) {
	if(status == -1)
	    fprintf(stderr,"%s: spawn of %s unsuccessful: %s\n",
				argv0,av[0],_sys_errlist[(int)errno]);
	exit(1);
    }

#else
    unlink(so_file);
    switch (pid = fork()) {
    case -1 :
	fprintf(stderr,"%s: cannot fork\n",argv0);
	exit(1);
	break;
    case 0 :
	ac	 =	0;
	ac	 =	add_link_args(ac, av, kflag);
	av[ac++] =	"-o";
	av[ac++] =	so_file;

	ofs	 =	o_files;
	while(*ofs)
	    av[ac++] =	*ofs++;

	for(i=0 ; i<nlinkerflags ; ++i)	/* add any -L or -l switches */
	    av[ac++] =	linkerflags[i];
	av[ac  ] =	(char *)NULL;

	if(dflag) {
	    fputs(av[0], stderr);
	    for(i=2 ; i<ac ; i++)
		fprintf(stderr," %s",av[i]);
	    fputc('\n',stderr);
	}
	else
	    fprintf(stderr,"linking %s\n", so_file);

	execvp(av[0], &av[1]);
	fprintf(stderr,"%s: cannot exec %s\n",argv0,av[0]);
	exit(1);
        break;
    default :
	while(wait(&status) != pid)
	    ;
	break;
    }
#endif

#if	defined(UNLINK_SO_LOCATIONS)
    unlink("so_locations");
#endif
    if(status != 0) {
	unlink(so_file);
	exit(1);
    }
    return(0);
}
Exemple #25
0
/* ------------------------------------------------------------------------------------ 
 *  spawn jobs on local machine
 * ------------------------------------------------------------------------------------ */
extern int AMUDP_SPMDLocalSpawn(int nproc, int argc, char **argv, char **extra_env) {
  /* just a simple fork/exec */
  int i;

  if (!AMUDP_SPMDSpawnRunning) {
    AMUDP_Err("Spawn functions should never be run directly - only passed to AMUDP_SPMDStartup()"); 
    return FALSE;
  }

  /* Temporarily assume values from extra_env[] (which we modify in-place) */
  char **save_env = NULL;
  int envc = 0;
  if (extra_env && extra_env[0]) {
    for (envc=0; extra_env[envc]; ++envc) {/*empty*/}
    save_env = (char **)AMUDP_malloc(sizeof(char *)*envc);
    for (i=0;i<envc;++i) {
      char *var = extra_env[i];
      char *delim = strchr(var,'=');
      AMUDP_assert(delim);
      *delim = '\0';
      save_env[i] = getenv(var);
      setenv(var,delim+1,1);
    }
  }

  for (i = 0; i < nproc; i++) {
    #if PLATFORM_OS_MSWINDOWS && !PLATFORM_OS_CYGWIN
      if (_spawnv(_P_NOWAIT, argv[0], argv) == -1)
        AMUDP_FatalErr("failed _spawnv()");
    #elif PLATFORM_ARCH_CRAYX1
      { char **nargv = (char **)AMUDP_malloc(sizeof(char *)*(argc+2));
        nargv[0] = argv[0];
        memcpy(nargv+1,argv,argc*sizeof(char *));
        nargv[argc+1] = NULL;
        if (execsp(nargv, environ, NULL) == -1)
          AMUDP_FatalErr("failed execsp()");
      }
    #else
      int forkRet = fork();
      if (forkRet == -1) {
        perror("fork");
        return FALSE;
      } else if (forkRet != 0) continue;  /*  this is the parent, will go back to the top of the loop */
      else {  /*  this is the child - exec the new process */
        /*  could close some resources here (like AMUDP_SPMDListenSocket) but not strictly necessary */

        #if 0
          /*  put new process in a separate process group */
          if (setsid() == -1) perror("setsid"); 
        #endif

        /*  exec the program, with the given arguments  */
        execv(argv[0], argv);

        /*  if execv returns, an error occurred */
        perror("execv");
        _exit(1); /*  use _exit() to prevent corrupting parent's io buffers */
      } /*  child */
    #endif
  }

  /* Restore saved environment var(s) */
  for (i=0;i<envc;++i) {
    char *name = extra_env[i];
    if (save_env[i]) {
      setenv(name,save_env[i],1);
    } else {
      unsetenv(name);
    }
    /* Revert our in-place modification of extra_env[]: */
    name[strlen(name)] = '=';
  }
  AMUDP_free(save_env);

  return TRUE;
}
Exemple #26
0
intptr_t __cdecl spawnv(int mode,const char *_Filename,char *const _ArgList[])
{
  return _spawnv(mode, _Filename,(const char *const *)_ArgList);
}
bool
ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args,
                               uint32_t argCount, NPVariant *result)
/*
name : method name
args : arguments
argCount : number of arguments
result : return value
*/
{
	NPIdentifier test_id = NPN_GetStringIdentifier("test");
	if (name == test_id) {
		printf("temp = %s\n",getTemporaryPath());
		printf("home = %s\n",getHomePath());
		printf("firefox = %s\n",getFirefoxPath());
		printf("conf = %s\n",getConfPath());
		printf("classpath = %s\n",getClassPath());
		printf("spawn = %s\n",getSpawnPath());
		VOID_TO_NPVARIANT(*result);
		return true;
	}

	NPError err;
	if (!this->HasMethod(name))
		return false;
	VOID_TO_NPVARIANT(*result);

	//login.jsp test
	NPIdentifier doSignature_id = NPN_GetStringIdentifier("doSignature");
	NPIdentifier getPublicKeyContent_id = NPN_GetStringIdentifier("getPublicKeyContent");


	NPObject* sWindowNPObj;

	if ((err = NPN_GetValue(mNpp, NPNVWindowNPObject, &sWindowNPObj)) != NPERR_NO_ERROR) {
		printf("Error in getting NPNVWindowNPObject: %d\n",err);
		return false;
	}

	const char *tmpdir = getTemporaryPath();
	const char *classpath = getClassPath();
	const char *spawnpath = getSpawnPath();

	if (name == doSignature_id) {
		if ((argCount == 2) && (NPVARIANT_IS_STRING(args[0])) && (NPVARIANT_IS_STRING(args[1]))) {
			char *randomStr = NULL;
			char *tpmPass = NULL;
			NPString n_randomStr = NPVARIANT_TO_STRING(args[0]);
			NPString n_tpmPass = NPVARIANT_TO_STRING(args[1]);
			m_strFromNP(&randomStr,n_randomStr);
			m_strFromNP(&tpmPass,n_tpmPass);
			printf("input = %s, %s",randomStr, tpmPass);

			char* ret = NULL;
			char *fname = tempnam(tmpdir,"jni");
			if (fname == NULL)
				fname = "tmp";
			char* margs[12];
			margs[0] = (char*) spawn_file;
			margs[1] = "--file";
			margs[2] = fname;
			margs[3] = "--method";
			margs[4] = "doSignature";
			margs[5] = "--classpath";
			margs[6] = (char*) classpath;
			margs[7] = "--args";
			margs[8] = "2";
			margs[9] = randomStr;
			margs[10] = tpmPass;
			margs[11] = NULL;
			// in windows use registry to find Firefox directory
			// in other OS, use path _spawnvp
			int rval = _spawnv(_P_WAIT,spawnpath,margs);
			if (rval) {
				fprintf(stderr,"error = %d\n",rval);
			}
			else {
				ret = getFileContent(fname);
				if (ret) {
					STRINGZ_TO_NPVARIANT(ret,*result); 
				}
				else {
					fprintf(stderr,"cannot read output file");
				}
				unlink(fname);
			}
			free(fname);
		}
		else {
			NPString str;
			str.UTF8Characters = "alert('usage: doSignature(String, String)');";
			str.UTF8Length = strlen(str.UTF8Characters);
			NPN_Evaluate(this->mNpp, sWindowNPObj, &str, NULL);
		}
	}
	else if (name == getPublicKeyContent_id) {
		if (argCount == 0) {
			char *ret = NULL;
			char *fname = tempnam(tmpdir,"jni");
			if (fname == NULL)
				fname = "tmp";
			char* margs[8];
			margs[0] = (char*) spawn_file;
			margs[1] = "--file";
			margs[2] = fname;
			margs[3] = "--method";
			margs[4] = "getPublicKeyContent";
			margs[5] = "--classpath";
			margs[6] = (char*) classpath;
			margs[7] = NULL;
			int rval = _spawnv(_P_WAIT,spawnpath,margs);
			if (rval) {
				fprintf(stderr,"error = %d\n",rval);
			}
			else {
				ret = getFileContent(fname);
				if (ret) {
					STRINGZ_TO_NPVARIANT(ret,*result); 
				}
				else {
					fprintf(stderr,"cannot read output file");
				}
				unlink(fname);
			}
			free(fname);
		}
		else {
			NPString str;
			str.UTF8Characters = "alert('usage: getPublicKeyContent()');";
			str.UTF8Length = strlen(str.UTF8Characters);
			NPN_Evaluate(this->mNpp, sWindowNPObj, &str, NULL);
		}
	}
	NPN_ReleaseObject(sWindowNPObj);
  return true;
}
Exemple #28
0
void main( int argc, char *argv[] ) {
  cout << " Confy V" << Confy_Version << "." << Confy_Revision
       << " --- Copyright 1999 TM Productions" << endl;

  if( argc < 4 )
    Help();

  if( argv[1][0] == '?' )
    Help();

  // Argument Tests
  char * dest = argv[1];
  char * user = argv[2];
  bool   plugins_only = false;

  bool   use_executable = false;
  char   executable[ MAX_PATH_LENGTH ] = "";

  bool   use_dash_c = false;
  char   dash_c[ MAX_PATH_LENGTH ] = "-c";   // Oddly enough, this is correct (ie: "-clw.cfg").  Weird.

  bool   use_flags = false;
  char   flags[ 1024 ] = "";

  bool   use_scene = false;
  char   scene[ MAX_PATH_LENGTH ] = "";

  bool   stop = false;
  for( int first_plugin_cfg = 3; first_plugin_cfg < argc; first_plugin_cfg++ ) {
    switch( argv[first_plugin_cfg][1] ) {
    // Specify Config Path for Layout
    case 'c':
      if( ++first_plugin_cfg >= argc ) {
        cerr << " ERROR: No config file following arguemnt -c!" << endl;
        cerr << " Type Confy ? for help" << endl;
        exit(20);
      }

      use_dash_c = true;
      strcat( dash_c, argv[ first_plugin_cfg ] );

      if( !DirInfo::Exists( argv[ first_plugin_cfg ] ) ) {
        cerr << " ERROR: The -c config file \"" << dash_c << "\" doesn't exist!" << endl;
        cerr << " Type Confy ? for help" << endl;
        exit(20);
      }
      break;

    // Executable
    case 'e':
      if( ++first_plugin_cfg >= argc ) {
        cerr << " ERROR: No executable following argument -e!" << endl;
        cerr << " Type Confy ? for help" << endl;
        exit(20);
      }

      use_executable = true;
      strcpy( executable, argv[ first_plugin_cfg ] );

      if( !DirInfo::Exists( executable ) ) {
        cerr << " ERROR: The executable \"" << executable << "\" doesn't exist!" << endl;
        cerr << " Type Confy ? for help" << endl;
        exit(20);
      }
      break;

    // Flags
    case 'f':
      if( ++first_plugin_cfg >= argc ) {
        cerr << " ERROR: No flags following argument -f!" << endl;
        cerr << " Type Confy ? for help" << endl;
        exit(20);
      }

      use_flags = true;
      strcpy( flags, argv[ first_plugin_cfg ] );

    // Plug-ins Only
    case 'p':
      plugins_only = true;
      break;

    // Scene/Object to pass to Lightwave/Modeler on load
    case 's':
      if( ++first_plugin_cfg >= argc ) {
        cerr << " ERROR: No scene/object file following argument -s!" << endl;
        cerr << " Type Confy ? for help" << endl;
        exit(20);
      }

      use_scene = true;
      strcpy( scene, argv[ first_plugin_cfg ] );

      break;

    // End of options
    default:                   // This is probably the first plugin config file
      stop = true;
      break;
    }

    if( stop )
      break;
  }

  // Test Arguments For Validity
  if( first_plugin_cfg >= argc ) {
    cerr << " ERROR: No plug-in configs specified!" << endl;
    cerr << " Type Confy ? for help" << endl;
    exit( 20 );
  }

  if( use_scene && !use_executable ) {
    cerr << " ERROR:  using -s requires -e" << endl;
    cerr << " Type Confy ? for help" << endl;
    exit(20);
  }

  // Display Settings
  cout << "-Settings:" << endl;
  cout << "  Destination Config:             \"" << dest << "\"" << endl;
  cout << "  User Config:                    \"" << user << "\"" << endl;

  if( plugins_only )
    cout << "  Adding plug-ins only; no settings will be replaced" << endl;

  if( use_executable )
    cout << "  Executable to launch:           \"" << executable << "\"" << endl;

  if( use_scene )
    cout << "  Scene to load into Lightwave:   \"" << scene << "\"" << endl;

  cout << "  Settings and Plug-In Config 0:  \"" << argv[ first_plugin_cfg ] << "\"" << endl;
  for( int i = first_plugin_cfg+1; i < argc; i++ ) 
    cout << "  Plug-In Config " << i-first_plugin_cfg << ":               \"" << argv[ i ] << "\"" << endl;

  // Config Variable Setup
  DynArray< char * >   settings[ num_settings_group_ids ];
  char                 buffer[ 8192 ];
  char               * plugin_type;
  char               * new_name, * old_name;
  unsigned int         j;
  pifstream            in;
  bool                 error = false;
  
  config_type_ids      cfg_type = config_unknown, new_type;
  int                  cfg_version = -1, new_version;
  DynArray< char * > * user_settings_loc = &settings[ user_settings_pre ];

  // ---
  // Load the User Config Settings
  // ---
  try {
    cout << "-Loading User Config..." << endl;
    cfg_type = OpenConfig( user, in );
    if( cfg_type != config_unknown ) {
      cfg_version = GetConfigVersion( in, cfg_type );
      if( cfg_version == -1 )
        throw false;
    }

    if( cfg_type == config_layout ) {
      cout << " User config file is a Layout config, version " << cfg_version << endl;
    } else if( cfg_type == config_modeler ) {
      cout << " User config file is a Modeler config, version " << cfg_version << endl;
    } else {
      cout << " Unknown config file type; L6 config?" << endl;
    }

    while( true ) {
      // Read in a new line
      in.getline( buffer, 8192 );

      // Error Test
      if( (in.fail() || in.bad()) && !in.eof() ) {
        cerr << " ERROR:  File error reading from user config file; aborting" << endl;
        throw false;
      }

      // See if there are any plug-ins here and skip them
      if( strncmp( "Plugin ", buffer, 7 ) == 0 ) {
        user_settings_loc = &settings[ user_settings_post ];
      } else {
        // Add the prev. line to the appropriate array
        user_settings_loc->Add( strdup( buffer ) );
      }

      // EOF test
      if( in.eof() )
        break;
    };

    // ---
    // Load the Plug-In Configs
    // ---
    user_settings_loc = &settings[ user_settings_pre ];
    for( int k=first_plugin_cfg; k < argc; k++ ) {
      cout << "-Loading Plugin Config " << k - first_plugin_cfg << ":  \"" << argv[k] << "\"..." << endl;

      in.close();
      new_type = OpenConfig( argv[ k ], in );
      if( new_type == config_bad ) {
        cerr << " ERROR:  Error opening config file; aborting" << endl;
        throw false;
      } else if( new_type == config_unknown ) {
        if( cfg_type != new_type ) {
          cerr << " ERROR:  Attempting to merge unknown config file (not a .cfg?); aborting" << endl;
          throw false;
        }
      } else if( new_type != cfg_type ) {
        cerr << " ERROR:  Illegal attempt to merge Modeler and Layout configs file; aborting" << endl;
        throw false;
      }

      if( new_type != config_unknown ) {
        new_version = GetConfigVersion( in, cfg_type );
        if( cfg_version != new_version ) {
          cerr << " ERROR:  The configuration files are not the same version; aborting" << endl;
          throw false;
        }
      }

      while( true ) {
        // Read in a new line
        in.getline( buffer, 8192 );

        // Error Test
        if( (in.fail() || in.bad()) && !in.eof() ) {
          cerr << " ERROR:  File error reading from plug-in config file \""
               << argv[ k ] << "\"; aborting" << endl;
          throw false;
        }

        // Update the user config options
        if( !plugins_only && (k == first_plugin_cfg) )
          UpdateUser( buffer, *user_settings_loc, cfg_type );

        // See if there's a plug-in here and store it
        if( strncmp( "Plugin ", buffer, 7 ) == 0 ) {           // The space is so we don't confuse this with 
          user_settings_loc = &settings[ user_settings_post ];

          plugin_type = StringTools::FindWord( buffer, 1 );
          if( plugin_type == NULL ) {
            cerr << " WARNING:  Missing plug-in identifier after keyword \"" << buffer
                 << "\" (config " << k - first_plugin_cfg << ")" << endl;
          } else {
            for( i = 0; i < num_plugin_ids; i++ ) {
              // Figure out what group it's in
              if( strncmp( plugin_type, settings_group_strings[i], strlen( settings_group_strings[i] ) ) == 0 ) {
                break;
              }
            }

            // Test for unknown plug-in types
            if( i == num_plugin_ids ) {
              cerr << " WARNING:  Unknown plug-in type found in this line: \"" << buffer
                   << "\" (config " << k - first_plugin_cfg << ")" << endl;
              settings[ plugins_other ].Add( strdup( buffer ) );
            }

            // See if this plug-in is a duplicate
            new_name = StringTools::FindWord( buffer, 2 );         // This should be the name of the plug-in as found in the .p file
            if( new_name == NULL ) {
              cerr << " WARNING:  The following line contains invalid plug-in information: \"" << buffer
                    << "\" (config " << k - first_plugin_cfg << ")" << endl;
            } else {
              for( j=0; j < settings[i].NumElements(); j++ ) {
                old_name = StringTools::FindWord( settings[i][j], 2 );
                if( old_name == NULL ) {
                  cerr << " WARNING:  The following plug-in line is invalid \"" << buffer << "\"; skipping";
                } else {
                  if( strncmp( old_name, new_name, StringTools::FindWordLength( old_name ) ) == 0 ) {
                    if( StringTools::FindWordLength( old_name ) == StringTools::FindWordLength( new_name ) ) {  // make sure the words are equal length; gets around strncmp() failing on things like "Metaform_Shaper" and "Metaform_Shaper(FASTER)"
                      cerr << " WARNING:  The following plug-in is already in the config: \"" << buffer
                           << "\"; replacing existing with this (config " << k - first_plugin_cfg << ")" << endl;
                      delete settings[i][j];
                      settings[i][j] = strdup( buffer );
                      break;
                    }
                  }
                }
              }

              // Not a duplicate; add it to the end
              if( j == settings[i].NumElements() ) {
                settings[i].Add( strdup( buffer ) );
              }
            }

          }
        }

        // EOF test
        if( in.eof() )
          break;
      };
    }

    in.close();

    // ---
    // Backup the existing config, if needed
    // ---
    if( DirInfo::Exists( dest ) ) {
      char backup[ MAX_PATH_LENGTH ];
      char extension[ MAX_FILENAME_LENGTH ];

      // Generate the backup name
      strcpy( backup, dest );
      char * ext = DirStrings::HasExtension( backup ); // Find any extension
      if( ext ) {                                      // Strip the extension
        strcpy( extension, ext );
        *ext = '\0';
      }
      strcat( backup, "-backup" );                     // Append "-backup"
      strcat( backup, extension );                     // Put the extension back

      cout << "-Destination configs already exists; backing up original as \"" << backup << "\"" << endl;

      // Delete any existing backup file so we can rename this one
      if( DirInfo::Exists( backup ) ) {
        if( DirInfo::Delete( backup ) != DI_DELETE_OK ) {
          cerr << " ERROR:  Unable to remove previously existing backup; aborting" << endl;
          throw false;
        }
      }

      // Rename the existing config
      if( DirInfo::Rename( dest, backup ) != DI_RENAME_OK ) {
        cerr << " ERROR:  Unable to rename existing config as backup; aborting" << endl;
        throw false;
      }
    }


    // ---
    // Output the final config
    // ---
    cout << "-Writing Composite Config \"" << dest << "\"..." << endl;
    ofstream out( dest );
    if( !out ) {
      cerr << " ERROR:  Unable to open output config \"" << dest << "\"; aborting" << endl;
      throw false;
    }

    // Pre-Plugin Settings
    for( j = 0; j < settings[ user_settings_pre ].NumElements(); j++ ) {
      if( settings[ user_settings_pre ][j][0] != '\0' )   // Skip any possible blank lines
        out << settings[ user_settings_pre ][j] << endl;
    }

    // Plug-ins
    for( i = 0; i < num_plugin_ids; i++ ) {
      for( j = 0; j < settings[i].NumElements(); j++ )
        out << settings[i][j] << endl;
    }

    // Post-Plugin Settings
    for( j = 0; j < settings[ user_settings_post ].NumElements(); j++ ) {
      if( settings[ user_settings_post ][j][0] != '\0' )   // Skip any possible blank lines
        out << settings[ user_settings_post ][j] << endl;
    }

  } catch( bool ) {
    error = true;  // We're just here so the clean-up code gets called on errors
  }

  // Free the memory used by the strings
  if( !error )
    cout << "-Cleaning up..." << endl;
  for( i=0; i < num_settings_group_ids; i++ ) {
    for( j = 0; j < settings[i].NumElements(); j++ )
      free( settings[i][j] );
  }

  if( !error ) {
    if( use_executable ) {
      cout << "-Launching \"" << executable << "\"..." << endl;

      // Change the working dir
      char cwd[ MAX_PATH_LENGTH ];
      strcpy( cwd, executable );
      *DirStrings::HasFile( cwd ) = '\0';
      if( cwd[0] != '\0' )
        DirInfo::ChangeWorkingDir( cwd );

      // Build the argument list
      char *exec_args[128];
      int a1 = 0;
      exec_args[ a1++ ] = strdup( DirStrings::GetFilePart( executable ) );

      if( use_dash_c )           // -c option
        exec_args[ a1++ ] = strdup( dash_c );

      if( use_flags ) {          // User-defined flags
        int j = 0;
        strcpy( buffer, flags );

        do {
          if( StringTools::IsolateWord( flags, buffer, j++ )[0] != '\0' )
            exec_args[ a1++ ] = strdup( buffer );

          if( a1 > 126 ) {
            cerr << "  ERROR:  More than 127 arguments being paseed to executable; aborting" << endl;
            exec_args[ a1-1 ] = '\0';
            for( i = 0; exec_args[i] != NULL; i++ )
              free( exec_args[i] );
            return;
          }
        } while( buffer[0] != '\0' );
      }

      if( use_scene )
        exec_args[ a1++ ] = strdup( scene );

      exec_args[ a1++ ] = NULL;          // NULL-terminate the array

      // Display the argument string
      cout << "  Argument String For Executable:  " << endl;
      cout << "  ";
      for( unsigned int i = 0; exec_args[i] != NULL; i++ )
        cout << " " << exec_args[i];
      cout << endl;

      // Run the program asynchronously
      _spawnv( _P_NOWAIT, executable, exec_args );

      // Free the argument list
      for( i = 0; exec_args[i] != NULL; i++ )
        free( exec_args[i] );
    }

    cout << "-Complete!" << endl;
  }
}
Components::Deployment::ComponentServer_ptr
ServerActivatorImpl::create_component_server (const ::Components::ConfigValues& config)
throw (Components::CreateFailure, Components::Deployment::InvalidConfiguration, CORBA::SystemException)
{
	QedoLock lock (cs_activation_mutex_);
	std::cout << "ServerActivatorImpl: create_component_server() called" << std::endl;

	CORBA::String_var my_string_ref;


	try
	{
		my_string_ref = orb_->object_to_string (this->_this());
	}
	catch (CORBA::SystemException&)
	{
		std::cerr << "ServerActivatorImpl: Cannot stringify my object reference" << std::endl;
		throw Components::CreateFailure();
	}

#ifdef _WIN32
	int component_server_pid;
	char *args[17];
	const char* prog;
	int args_nr=0;

	if (enable_terminal_)
	{
		prog = "c:/winnt/system32/cmd.exe";
		args[args_nr++] = "cmd";
		args[args_nr++] = "/c";
		args[args_nr++] = "start";
		args[args_nr++] = "qcs.exe";
	}
	else
	{
		prog = "qcs.exe";
		args[args_nr++] = "qcs.exe";
	}

	if (debug_mode_)
	{
		args[args_nr++] = "--debug";
	}

	if (verbose_mode_)
	{
		args[args_nr++] = "--verbose";
	}

	args[args_nr++] = "--csa_ref";
	args[args_nr++] = my_string_ref.inout();

	args[args_nr] = 0;

	component_server_pid = _spawnv(_P_NOWAIT, prog, args);

	if (component_server_pid < 0)
	{
		std::cerr << "ServerActivatorImpl: Cannot spawn Component Server process" << std::endl;
		std::cerr << "ServerActivatorImpl: " << strerror(errno) << std::endl;
		throw Components::CreateFailure();
	}

#else

	pid_t component_server_pid;

	switch (component_server_pid = fork())
	{
		case 0 : /* child process */
		{
			char *args[17];
			const char* prog;
			int args_nr=0;


			if (enable_terminal_)
			{
				args[args_nr++] = "xterm";
				args[args_nr++] = "-e";
				args[args_nr++] = "qcs.sh";
				prog = "xterm";
			}
			else
			{
				args[args_nr++] = "qcs";
				prog = "qcs";
			}

			if (debug_mode_)
			{
				args[args_nr++] = "--debug";
			}

			if (verbose_mode_)
			{
				args[args_nr++] = "--verbose";
			}

			args[args_nr++] = "--csa_ref";
			args[args_nr++] = my_string_ref.inout();

			args[args_nr] = 0;

			long err = execvp (prog,args);
			if (err == -1) 
			{
				std::cerr << "ServerActivatorImpl: execvp() for component server failed" << std::endl;
				std::cerr << "ServerActivatorImpl: Error  was: " << strerror (errno) << std::endl;
				throw Components::CreateFailure();
			}

		}
			break;
		default : /* parent process */
			break;
		case -1 : /* error in fork */
			{
				std::cerr << "ServerActivatorImpl: Cannot spawn Component Server process" << std::endl;
				std::cerr << "ServerActivatorImpl: " << strerror(errno) << std::endl;
				throw Components::CreateFailure();
			}
			break;
	}

#endif

	cs_activation_cond_.wait (cs_activation_mutex_);

//#endif

	if (CORBA::is_nil (last_created_component_server_))
	{
		// cerr << "ServerActivatorImpl: Component Server has not been created" << endl;
		throw Components::CreateFailure();
	}

	ComponentServerEntry e;
	e.server = Components::Deployment::ComponentServer::_duplicate(last_created_component_server_);
	e.pid = component_server_pid;

	Qedo::QedoLock l(component_servers_mutex_);

	component_servers_.push_back(e);

	return Components::Deployment::ComponentServer::_duplicate(last_created_component_server_);
}
void CWE78_OS_Command_Injection__char_listen_socket_w32_spawnv_08_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    if(staticReturnsTrue())
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            char *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            size_t dataLen = strlen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(char)] = '\0';
                /* Eliminate CRLF */
                replace = strchr(data, '\r');
                if (replace)
                {
                    *replace = '\0';
                }
                replace = strchr(data, '\n');
                if (replace)
                {
                    *replace = '\0';
                }
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* spawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}