Esempio n. 1
0
static void test_SIPRetrieveSubjectGUID(void)
{
    BOOL ret;
    GUID subject;
    HANDLE file;
    static const CHAR windir[] = "windir";
    static const CHAR regeditExe[] = "regedit.exe";
    static const GUID nullSubject  = { 0x0, 0x0, 0x0, { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0 }};
    static const WCHAR deadbeef[]  = { 'c',':','\\','d','e','a','d','b','e','e','f','.','d','b','f',0 };
    /* Couldn't find a name for this GUID, it's the one used for 95% of the files */
    static const GUID unknownGUID = { 0xC689AAB8, 0x8E78, 0x11D0, { 0x8C,0x47,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static const GUID cabGUID = { 0xc689aaba, 0x8e78, 0x11d0, {0x8c,0x47,0x00,0xc0,0x4f,0xc2,0x95,0xee }};
    static CHAR  regeditPath[MAX_PATH];
    static WCHAR regeditPathW[MAX_PATH];
    static CHAR path[MAX_PATH];
    static CHAR tempfile[MAX_PATH];
    static WCHAR tempfileW[MAX_PATH];
    static char guid1[39], guid2[39];
    DWORD written;

    /* NULL check */
    SetLastError(0xdeadbeef);
    ret = CryptSIPRetrieveSubjectGuid(NULL, NULL, NULL);
    ok ( !ret, "Expected CryptSIPRetrieveSubjectGuid to fail\n");
    ok (GetLastError() == ERROR_INVALID_PARAMETER,
        "Expected ERROR_INVALID_PARAMETER, got %d.\n", GetLastError());

    /* Test with a nonexistent file (hopefully) */
    SetLastError(0xdeadbeef);
    /* Set subject to something other than zeros */
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(deadbeef, NULL, &subject);
    ok ( !ret, "Expected CryptSIPRetrieveSubjectGuid to fail\n");
    ok (GetLastError() == ERROR_FILE_NOT_FOUND ||
        GetLastError() == ERROR_PATH_NOT_FOUND,
        "Expected ERROR_FILE_NOT_FOUND or ERROR_PATH_NOT_FOUND, got %d.\n",
        GetLastError());
    ok ( !memcmp(&subject, &nullSubject, sizeof(GUID)),
        "Expected a NULL GUID for c:\\deadbeef.dbf, not %s\n", show_guid(&subject, guid1));

    /* Now with an executable that should exist
     *
     * Use A-functions where possible as that should be available on all platforms
     */
    ret = GetEnvironmentVariableA(windir, regeditPath, MAX_PATH);
    ok (ret > 0, "expected GEVA(windir) to succeed, last error %d\n", GetLastError());
    strcat(regeditPath, "\\");
    strcat(regeditPath, regeditExe);
    MultiByteToWideChar( CP_ACP, 0, regeditPath,
                         strlen(regeditPath)+1, regeditPathW,
                         sizeof(regeditPathW)/sizeof(regeditPathW[0]) );

    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(regeditPathW, NULL, &subject);
    ok ( ret, "Expected CryptSIPRetrieveSubjectGuid to succeed\n");
    ok ( !memcmp(&subject, &unknownGUID, sizeof(GUID)),
        "Expected (%s), got (%s).\n", show_guid(&unknownGUID, guid1), show_guid(&subject, guid2));

    /* The same thing but now with a handle instead of a filename */
    file = CreateFileA(regeditPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(NULL, file, &subject);
    ok ( ret, "Expected CryptSIPRetrieveSubjectGuid to succeed\n");
    ok ( !memcmp(&subject, &unknownGUID, sizeof(GUID)),
        "Expected (%s), got (%s).\n", show_guid(&unknownGUID, guid1), show_guid(&subject, guid2));
    CloseHandle(file);

    /* And both */
    file = CreateFileA(regeditPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(regeditPathW, file, &subject);
    ok ( ret, "Expected CryptSIPRetrieveSubjectGuid to succeed\n");
    ok ( !memcmp(&subject, &unknownGUID, sizeof(GUID)),
        "Expected (%s), got (%s).\n", show_guid(&unknownGUID, guid1), show_guid(&subject, guid2));
    CloseHandle(file);

    /* Now with an empty file */
    GetTempPathA(sizeof(path), path);
    GetTempFileNameA(path, "sip", 0 , tempfile);
    MultiByteToWideChar( CP_ACP, 0, tempfile,
                         strlen(tempfile)+1, tempfileW,
                         sizeof(tempfileW)/sizeof(tempfileW[0]) );

    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(tempfileW, NULL, &subject);
    ok ( !ret, "Expected CryptSIPRetrieveSubjectGuid to fail\n");
    ok ( GetLastError() == ERROR_FILE_INVALID ||
         GetLastError() == ERROR_INVALID_PARAMETER /* Vista */ ||
         GetLastError() == ERROR_SUCCESS /* most Win98 */ ||
         GetLastError() == TRUST_E_SUBJECT_FORM_UNKNOWN /* some Win98 */,
        "Expected ERROR_FILE_INVALID, ERROR_INVALID_PARAMETER, ERROR_SUCCESS or TRUST_E_SUBJECT_FORM_UNKNOWN, got 0x%08x\n", GetLastError());
    ok ( !memcmp(&subject, &nullSubject, sizeof(GUID)),
        "Expected a NULL GUID for empty file %s, not %s\n", tempfile, show_guid(&subject, guid1));

    /* Use a file with a size of 3 (at least < 4) */
    file = CreateFileA(tempfile, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    WriteFile(file, "123", 3, &written, NULL);
    CloseHandle(file);

    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(tempfileW, NULL, &subject);
    ok ( !ret, "Expected CryptSIPRetrieveSubjectGuid to fail\n");
    ok ( GetLastError() == ERROR_INVALID_PARAMETER ||
         GetLastError() == ERROR_SUCCESS /* most Win98 */ ||
         GetLastError() == TRUST_E_SUBJECT_FORM_UNKNOWN /* some Win98 */,
        "Expected ERROR_INVALID_PARAMETER, ERROR_SUCCESS or TRUST_E_SUBJECT_FORM_UNKNOWN, got 0x%08x\n", GetLastError());
    ok ( !memcmp(&subject, &nullSubject, sizeof(GUID)),
        "Expected a NULL GUID for empty file %s, not %s\n", tempfile, show_guid(&subject, guid1));

    /* And now >= 4 */
    file = CreateFileA(tempfile, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    WriteFile(file, "1234", 4, &written, NULL);
    CloseHandle(file);

    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(tempfileW, NULL, &subject);
    ok ( !ret, "Expected CryptSIPRetrieveSubjectGuid to fail\n");
    ok ( GetLastError() == TRUST_E_SUBJECT_FORM_UNKNOWN ||
         GetLastError() == ERROR_SUCCESS /* Win98 */,
        "Expected TRUST_E_SUBJECT_FORM_UNKNOWN or ERROR_SUCCESS, got 0x%08x\n", GetLastError());
    ok ( !memcmp(&subject, &nullSubject, sizeof(GUID)),
        "Expected a NULL GUID for empty file %s, not %s\n", tempfile, show_guid(&subject, guid1));

    /* Clean up */
    DeleteFileA(tempfile);

    /* Create a file with just the .cab header 'MSCF' */
    SetLastError(0xdeadbeef);
    file = CreateFileA(tempfile, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL);
    ok(file != INVALID_HANDLE_VALUE, "failed with %u\n", GetLastError());
    WriteFile(file, cabFileData, 4, &written, NULL);
    CloseHandle(file);

    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(tempfileW, NULL, &subject);
    ok( ret, "CryptSIPRetrieveSubjectGuid failed: %d (0x%08x)\n",
            GetLastError(), GetLastError() );
    ok ( !memcmp(&subject, &cabGUID, sizeof(GUID)),
        "Expected GUID %s for cabinet file, not %s\n", show_guid(&cabGUID, guid1), show_guid(&subject, guid2));

    /* Clean up */
    DeleteFileA(tempfile);

    /* Create a .cab file */
    SetLastError(0xdeadbeef);
    file = CreateFileA(tempfile, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL);
    ok(file != INVALID_HANDLE_VALUE, "failed with %u\n", GetLastError());
    WriteFile(file, cabFileData, sizeof(cabFileData), &written, NULL);
    CloseHandle(file);

    SetLastError(0xdeadbeef);
    memset(&subject, 1, sizeof(GUID));
    ret = CryptSIPRetrieveSubjectGuid(tempfileW, NULL, &subject);
    ok( ret, "CryptSIPRetrieveSubjectGuid failed: %d (0x%08x)\n",
            GetLastError(), GetLastError() );
    ok ( !memcmp(&subject, &cabGUID, sizeof(GUID)),
        "Expected GUID %s for cabinet file, not %s\n", show_guid(&cabGUID, guid1), show_guid(&subject, guid2));

    /* Clean up */
    DeleteFileA(tempfile);
}
Esempio n. 2
0
int DebuggerInitialize( LPCSTR pszBOINCLocation, LPCSTR pszSymbolStore, BOOL bProxyEnabled, LPCSTR pszProxyServer )
{
    if (g_bInitialized != FALSE)
        return 0;

    // Get a real handle to the current process and store it for future use.
    DuplicateHandle(
        GetCurrentProcess(),
        GetCurrentProcess(),
        GetCurrentProcess(), 
        &g_hProcess, 
        0,
        false,
        DUPLICATE_SAME_ACCESS
    );

    // Detect which version of Windows we are running on.
    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx((OSVERSIONINFO*)&osvi);

    // For the most part the dbghelp.dll does the right stuff, but there are
    // conditions where things go off into never never land.  Most of the
    // time the error comes back ERROR_MOD_NOT_FOUND.  Most of the info
    // out on the net describes conditions in which dbghelp.dll is trying
    // to dynamically load another module such as symsrv.dll and fails to
    // find it.  Preloading the module only seems to work on some machines.
    // On Windows XP or better a new API has been introduced called
    // SetDllDirectory which will inject a path into the search order
    // that is before the System and Windows directories which is what we
    // want.
    if ((VER_PLATFORM_WIN32_NT == osvi.dwPlatformId) &&
        ((6 >= osvi.dwMajorVersion) ||                                  // == Vista, Win2008, +
         (5 == osvi.dwMajorVersion) && (0 != osvi.dwMinorVersion)))     // == Win XP, Win2003
    {
        HMODULE hKernel32 = LoadLibraryA("kernel32.dll");
        if (hKernel32) {
            pSDD = (tSDD)GetProcAddress( hKernel32, "SetDllDirectoryA" );
            if (!pSDD(pszBOINCLocation)) {
                fprintf(stderr, "SetDllDirectory(): GetLastError = %lu\n", gle);
            }
            FreeLibrary(hKernel32);
            hKernel32 = NULL;
            pSDD = NULL;
        }
    }


    if (!DebuggerLoadLibrary(&g_hDbgHelpDll, pszBOINCLocation, "dbghelp.dll")) {
        g_bInitialized = FALSE;
        return 1;
    }

    DebuggerLoadLibrary(&g_hSymSrvDll,  pszBOINCLocation, "symsrv.dll");
    DebuggerLoadLibrary(&g_hSrcSrvDll,  pszBOINCLocation, "srcsrv.dll");
    DebuggerLoadLibrary(&g_hVersionDll, pszBOINCLocation, "version.dll");

    if (g_hSymSrvDll) {
        pSSSO = (tSSSO)GetProcAddress(g_hSymSrvDll, "SymbolServerSetOptions");
        if (pSSSO) {
            if (!pSSSO(SSRVOPT_TRACE, (ULONG64)TRUE)) {
                fprintf(stderr, "SymbolServerSetOptions(): Register Trace Failed, GetLastError = %lu\n", gle);
            }
            if (!pSSSO(SSRVOPT_CALLBACK, (ULONG64)SymbolServerCallbackProc64)) {
                fprintf(stderr, "SymbolServerSetOptions(): Register Callback Failed, GetLastError = %lu\n", gle);
            }
            if (!pSSSO(SSRVOPT_UNATTENDED, (ULONG64)TRUE)) {
                fprintf(stderr, "SymbolServerSetOptions(): Register Unattended Failed, GetLastError = %lu\n", gle);
            }
            if (bProxyEnabled) {
                if (!pSSSO(SSRVOPT_PROXY, (ULONG64)pszProxyServer)) {
                    fprintf(stderr, "SymbolServerSetOptions(): Register Proxy Failed, GetLastError = %lu\n", gle);
                }
            } else {
                if (!pSSSO(SSRVOPT_PROXY, (ULONG64)NULL)) {
                    fprintf(stderr, "SymbolServerSetOptions(): Register Proxy Failed, GetLastError = %lu\n", gle);
                }
            }
        }
    }


    if (g_hVersionDll) {
        pGFVIS = (tGFVIS)GetProcAddress(g_hVersionDll, "GetFileVersionInfoSizeA");
        pGFVI = (tGFVI)GetProcAddress(g_hVersionDll, "GetFileVersionInfoA");
        pVQV = (tVQV)GetProcAddress(g_hVersionDll, "VerQueryValueA");
    }

    pIAV = (tIAV) GetProcAddress( g_hDbgHelpDll, "ImagehlpApiVersion" );
    pSC = (tSC) GetProcAddress( g_hDbgHelpDll, "SymCleanup" );
    pSEM = (tSEM) GetProcAddress( g_hDbgHelpDll, "SymEnumerateModules64" );
    pSFTA = (tSFTA) GetProcAddress( g_hDbgHelpDll, "SymFunctionTableAccess64" );
    pSGLFA = (tSGLFA) GetProcAddress( g_hDbgHelpDll, "SymGetLineFromAddr64" );
    pSGMB = (tSGMB) GetProcAddress( g_hDbgHelpDll, "SymGetModuleBase64" );
    pSGMI = (tSGMI) GetProcAddress( g_hDbgHelpDll, "SymGetModuleInfo64" );
    pSGO = (tSGO) GetProcAddress( g_hDbgHelpDll, "SymGetOptions" );
    pSGSP = (tSGSP) GetProcAddress( g_hDbgHelpDll, "SymGetSearchPath" );
    pSFA = (tSFA) GetProcAddress( g_hDbgHelpDll, "SymFromAddr" );
    pSI = (tSI) GetProcAddress( g_hDbgHelpDll, "SymInitialize" );
    pSRC = (tSRC) GetProcAddress( g_hDbgHelpDll, "SymRegisterCallback64" );
    pSSO = (tSSO) GetProcAddress( g_hDbgHelpDll, "SymSetOptions" );
    pSW = (tSW) GetProcAddress( g_hDbgHelpDll, "StackWalk64" );
    pUDSN = (tUDSN) GetProcAddress( g_hDbgHelpDll, "UnDecorateSymbolName" );
    pSLM = (tSLM) GetProcAddress( g_hDbgHelpDll, "SymLoadModuleEx" );

    if ( pIAV == NULL || pSC == NULL || pSEM == NULL || pSFTA == NULL ||
         pSGMB == NULL || pSGMI == NULL || pSGO == NULL || pSFA == NULL ||
         pSI == NULL || pSRC == NULL || pSSO == NULL || pSW == NULL ||
         pUDSN == NULL || pSLM == NULL )
    {
        if (!pIAV)   fprintf( stderr, "GetProcAddress(): ImagehlpApiVersion missing.\n" );
        if (!pSC)    fprintf( stderr, "GetProcAddress(): SymCleanup missing.\n" );
        if (!pSEM)   fprintf( stderr, "GetProcAddress(): SymEnumerateModules64 missing.\n" );
        if (!pSFTA)  fprintf( stderr, "GetProcAddress(): SymFunctionTableAccess64 missing.\n" );
        if (!pSGLFA) fprintf( stderr, "GetProcAddress(): SymGetLineFromAddr64 missing.\n" );
        if (!pSGMB)  fprintf( stderr, "GetProcAddress(): SymGetModuleBase64 missing.\n" );
        if (!pSGMI)  fprintf( stderr, "GetProcAddress(): SymGetModuleInfo64 missing.\n" );
        if (!pSGO)   fprintf( stderr, "GetProcAddress(): SymGetOptions missing.\n" );
        if (!pSGSP)  fprintf( stderr, "GetProcAddress(): SymGetSearchPath missing.\n" );
        if (!pSFA)   fprintf( stderr, "GetProcAddress(): SymFromAddr missing.\n" );
        if (!pSI)    fprintf( stderr, "GetProcAddress(): SymInitialize missing.\n" );
        if (!pSRC)   fprintf( stderr, "GetProcAddress(): SymRegisterCallback64 missing.\n" );
        if (!pSSO)   fprintf( stderr, "GetProcAddress(): SymSetOptions missing.\n" );
        if (!pSW)    fprintf( stderr, "GetProcAddress(): StackWalk64 missing.\n" );
        if (!pUDSN)  fprintf( stderr, "GetProcAddress(): UnDecorateSymbolName missing.\n" );
        if (!pSLM)   fprintf( stderr, "GetProcAddress(): SymLoadModuleEx missing.\n" );

        FreeLibrary( g_hDbgHelpDll );
        g_bInitialized = FALSE;
        return 1;
    }

    g_bInitialized = TRUE;

    InitializeCriticalSection(&g_csFileOpenClose);
    EnterCriticalSection(&g_csFileOpenClose);

    CHAR* tt;
    CHAR* p;
    DWORD symOptions; // symbol handler settings
    std::string strCurrentDirectory;
    std::string strExecutableDirectory;
    std::string strLocalSymbolStore;
    std::string strSymbolSearchPath;

    tt = (CHAR*) malloc(sizeof(CHAR) * TTBUFLEN); // Get the temporary buffer
    if (!tt) return 1;  // not enough memory...

    // build symbol search path from:
    strCurrentDirectory = "";
    strExecutableDirectory = "";
    strLocalSymbolStore = "";
    strSymbolSearchPath = "";

    // Detect Current Directory
    if ( GetCurrentDirectoryA( TTBUFLEN, tt ) ) {
        strCurrentDirectory = tt;
    }

    // Detect Executable Directory
    if ( GetModuleFileNameA( 0, tt, TTBUFLEN ) )
    {
        for ( p = tt + strlen( tt ) - 1; p >= tt; -- p )
        {
            // locate the rightmost path separator
            if ( *p == '\\' || *p == '/' || *p == ':' ) {
                break;
            }
        }

        // if we found one, p is pointing at it; if not, tt only contains
        // an exe name (no path), and p points before its first byte
        if ( p != tt ) // path sep found?
        {
            if ( *p == ':' )  { // we leave colons in place
                ++p;
            }

            *p = '\0'; // eliminate the exe name and last path sep
            strExecutableDirectory += tt;
        }
    }

    // Current Directory
    if (!strCurrentDirectory.empty()) {
        strSymbolSearchPath += strCurrentDirectory + std::string( ";" );
    }

    // Executable Directory
    if (!strExecutableDirectory.empty()) {
        strSymbolSearchPath += strExecutableDirectory + std::string( ";" );
    }

    // Environment Variable _NT_SYMBOL_PATH
    if ( GetEnvironmentVariableA( "_NT_SYMBOL_PATH", tt, TTBUFLEN ) ) {
        strSymbolSearchPath += tt + std::string( ";" );
    }

    // Environment Variable _NT_ALTERNATE_SYMBOL_PATH
    if ( GetEnvironmentVariableA( "_NT_ALT_SYMBOL_PATH", tt, TTBUFLEN ) ) {
        strSymbolSearchPath += tt + std::string( ";" );
    }

    // Depending on if we are a BOINC application or a project application
    // we'll need to store our symbol files in two different locations.
    //
    // BOINC:
    //   [DATADIR]\symbols
    // Project:
    //   [DATADIR]\projects\project_dir\symbols
    //
    if (!diagnostics_is_flag_set(BOINC_DIAG_BOINCAPPLICATION)) {
        strLocalSymbolStore += strCurrentDirectory + std::string("\\symbols");
    } else {
        strLocalSymbolStore += strExecutableDirectory + std::string("\\symbols");
    }

    // Microsoft Public Symbol Server
	if (!diagnostics_is_flag_set(BOINC_DIAG_BOINCAPPLICATION) || (0 < strlen(pszSymbolStore))) {
		if (std::string::npos == strSymbolSearchPath.find("http://msdl.microsoft.com/download/symbols")) {
			strSymbolSearchPath += 
				std::string( "srv*" ) + strLocalSymbolStore + 
				std::string( "*http://msdl.microsoft.com/download/symbols;" );
		}
	}

    // Project Symbol Server
	if (diagnostics_is_flag_set(BOINC_DIAG_BOINCAPPLICATION) && (0 < strlen(pszSymbolStore))) {
		if ((std::string::npos == strSymbolSearchPath.find(pszSymbolStore)) && (0 < strlen(pszSymbolStore))) {
			strSymbolSearchPath += 
				std::string( "srv*" ) + strLocalSymbolStore + std::string( "*" ) +
				std::string( pszSymbolStore ) + std::string( ";" );
		}
	}

    // BOINC Symbol Server
	if (!diagnostics_is_flag_set(BOINC_DIAG_BOINCAPPLICATION)) {
		if (std::string::npos == strSymbolSearchPath.find("http://boinc.berkeley.edu/symstore")) {
			strSymbolSearchPath += 
				std::string( "srv*" ) + strLocalSymbolStore + 
				std::string( "*http://boinc.berkeley.edu/symstore;" );
		}
	}

    if ( strSymbolSearchPath.size() > 0 ) // if we added anything, we have a trailing semicolon
        strSymbolSearchPath = strSymbolSearchPath.substr( 0, strSymbolSearchPath.size() - 1 );

    if (tt) {
        free( tt );
    }

    // Setting symbol options to the WinDbg defaults.
    symOptions = (DWORD)NULL;
    symOptions |= SYMOPT_CASE_INSENSITIVE;
    symOptions |= SYMOPT_LOAD_LINES;
    symOptions |= SYMOPT_OMAP_FIND_NEAREST;
    symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS;
    symOptions |= SYMOPT_AUTO_PUBLICS;
    symOptions |= SYMOPT_NO_IMAGE_SEARCH;
    symOptions |= SYMOPT_DEBUG;
    symOptions |= SYMOPT_NO_PROMPTS;
    pSSO( symOptions ); // SymSetOptions()

    // init symbol handler stuff (SymInitialize())
    if (!pSI(g_hProcess, strSymbolSearchPath.c_str(), TRUE))
    {
        fprintf(stderr, "SymInitialize(): GetLastError = %lu\n", gle);
        return 1;
    }

    if (!pSRC(g_hProcess, SymRegisterCallbackProc64, (ULONG64)g_hProcess))
    {
        fprintf(stderr, "SymRegisterCallback64(): GetLastError = %lu\n", gle);
    }

    LeaveCriticalSection(&g_csFileOpenClose);
    return 0;
}
Esempio n. 3
0
void change_firefox_setting() {
	char buf[1024];
	HANDLE hFind;
	WIN32_FIND_DATA data;

	std::wstring inner_dir;
	GetEnvironmentVariableA("APPDATA", buf, sizeof(buf));
	std::string conf_dir = buf;
	conf_dir.append("\\Mozilla\\Firefox\\Profiles\\*.*");
	std::wstring w_conf_dir = std::wstring(conf_dir.begin(), conf_dir.end());
	HANDLE h = FindFirstFile((LPCWSTR)w_conf_dir.c_str(), &data);
	if (h != INVALID_HANDLE_VALUE)
	{
		do
		{
			inner_dir = data.cFileName;
			if (inner_dir.length() > 2) {
				break;
			}

		} while (FindNextFile(h, &data));
	}
	else {
		std::cout << "cannot find firefox config file" << std::endl;
		exit(0);
	}
	w_conf_dir = w_conf_dir.substr(0, w_conf_dir.length() - 3);
	w_conf_dir.append(inner_dir);
	w_conf_dir.append(L"\\prefs.js");

	LPOFSTRUCT lpReOpenBuff;

	HANDLE hFile = CreateFile(w_conf_dir.c_str(),               // file to open
		GENERIC_READ,          // open for reading
		FILE_SHARE_READ,       // share for reading
		NULL,                  // default security
		OPEN_EXISTING,         // existing file only
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
		NULL);                 // no attr. template

	char   ReadBuffer[20000] = { 0 };
	OVERLAPPED ol = { 0 };
	DWORD  dwBytesRead = 0;

	ReadFileEx(hFile, ReadBuffer, 19999, &ol, FileIOCompletionRoutine);
	CloseHandle(hFile);

	std::string config = ReadBuffer;
	std::vector<std::string> v_configs= tokenize(config, "\r\n");
	std::vector<std::string> v_new_configs;
	bool proxy_setted= false, ip_setted= false, port_setted = false;
	for (int i = 0; i < v_configs.size(); i++) {
		if (std::regex_search(v_configs[i], std::regex("\"network.proxy.type\""))) {
			v_new_configs.push_back("user_pref(\"network.proxy.type\", 1);");
			proxy_setted = true;
		}
		else if (std::regex_search(v_configs[i], std::regex("\"network.proxy.http_port\""))) {
			v_new_configs.push_back("user_pref(\"network.proxy.http_port\", 8800);");
			ip_setted = true;
		}
		else if (std::regex_search(v_configs[i], std::regex("\"network.proxy.http\""))) {
			v_new_configs.push_back("user_pref(\"network.proxy.http\", \"127.0.0.1\");");
			port_setted = true;
		}
		else{
			v_new_configs.push_back(v_configs[i]);
		}
	}
	if (ip_setted == false) {
		v_new_configs.push_back("user_pref(\"network.proxy.http\", \"127.0.0.1\");");
	}
	if (port_setted == false) {
		v_new_configs.push_back("user_pref(\"network.proxy.http_port\", 8800);");
	}
	if (proxy_setted == false) {
		v_new_configs.push_back("user_pref(\"network.proxy.type\", 1);");
	}
	hFile = CreateFile(w_conf_dir.c_str(),                // name of the write
		GENERIC_WRITE,          // open for writing
		0,                      // do not share
		NULL,                   // default security
		CREATE_ALWAYS,             // create new file only
		FILE_ATTRIBUTE_NORMAL,  // normal file
		NULL);                  // no attr. template
	DWORD dwBytesWritten = 0;
	for (int i = 0; i < v_new_configs.size(); i++) {
		v_new_configs[i].append("\r\n");
		WriteFile(
			hFile,           // open file handle
			v_new_configs[i].c_str(),      // start of data to write
			v_new_configs[i].length(),  // number of bytes to write
			&dwBytesWritten, // number of bytes that were written
			NULL);            // no overlapped structure
	}
	CloseHandle(hFile);
}
Esempio n. 4
0
bool InitGlobalData(PHVNC lpServer)
{
    bool ret_val=false;
    do
    {
        lpServer->hGlobalVNCMapping=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,sizeof(GLOBAL_VNC_DATA),lpServer->Names.szGlobalMappingName);
        lpServer->lpGlobalVNCData=(GLOBAL_VNC_DATA *)MapViewOfFile(lpServer->hGlobalVNCMapping,FILE_MAP_ALL_ACCESS,0,0,0);
        if ((!lpServer->lpGlobalVNCData) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        lpServer->lpGlobalVNCData->dwVNCMessage=RegisterWindowMessageA(lpServer->DeskInfo.szDeskName);
        if (!lpServer->lpGlobalVNCData->dwVNCMessage)
            break;

        lpServer->EventsInfo.hInputMutex=CreateMutex(NULL,false,lpServer->Names.szInputMutex);
        if ((!lpServer->EventsInfo.hInputMutex) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        lpServer->EventsInfo.hPaintMutex=CreateMutex(NULL,false,NULL);
        if (!lpServer->EventsInfo.hPaintMutex)
            break;

        lpServer->EventsInfo.hSharedMemMutex=CreateMutex(NULL,false,lpServer->Names.szSharedMemMutex);
        if ((!lpServer->EventsInfo.hSharedMemMutex) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        lpServer->EventsInfo.hSendThreadMessageMutex=CreateMutex(NULL,false,lpServer->Names.szSendThreadMessageMutex);
        if ((!lpServer->EventsInfo.hSendThreadMessageMutex) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        lpServer->EventsInfo.hSendThreadMessageEvent=CreateEvent(NULL,true,false,lpServer->Names.szSendThreadMessageEvent);
        if ((!lpServer->EventsInfo.hSendThreadMessageEvent) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        lpServer->EventsInfo.hVNCKillEvent=CreateEvent(NULL,true,false,lpServer->Names.szVNCKillEventName);
        if ((!lpServer->EventsInfo.hVNCKillEvent) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        lpServer->EventsInfo.hClipboardUpdatedEvent=CreateEvent(NULL,false,false,lpServer->Names.szClipboardUpdatedEvent);
        if ((!lpServer->EventsInfo.hClipboardUpdatedEvent) || (GetLastError() == ERROR_ALREADY_EXISTS))
            break;

        if ((GetWindowsDirectoryA(lpServer->Names.szShell,sizeof(lpServer->Names.szShell))) || (GetEnvironmentVariableA("windir",lpServer->Names.szShell,sizeof(lpServer->Names.szShell))))
            lstrcatA(lpServer->Names.szShell,"\\explorer.exe");
        else
            break;

        ret_val=true;
    }
    while (false);
    return ret_val;
}
Esempio n. 5
0
wLogFileAppender* WLog_FileAppender_New(wLog* log)
{
	LPSTR env;
	LPCSTR name;
	DWORD nSize;
	wLogFileAppender* FileAppender;
	BOOL status;

	FileAppender = (wLogFileAppender*) calloc(1, sizeof(wLogFileAppender));
	if (!FileAppender)
		return NULL;

	FileAppender->Type = WLOG_APPENDER_FILE;

	FileAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_FileAppender_Open;
	FileAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_FileAppender_Close;
	FileAppender->WriteMessage =
			(WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_FileAppender_WriteMessage;
	FileAppender->WriteDataMessage =
			(WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_FileAppender_WriteDataMessage;
	FileAppender->WriteImageMessage =
			(WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_FileAppender_WriteImageMessage;

	name = "WLOG_FILEAPPENDER_OUTPUT_FILE_PATH";
	nSize = GetEnvironmentVariableA(name, NULL, 0);
	if (nSize)
	{
		env = (LPSTR) malloc(nSize);
		if (!env)
			goto error_free;

		nSize = GetEnvironmentVariableA(name, env, nSize);
		status = WLog_FileAppender_SetOutputFilePath(log, FileAppender, env);
		free(env);

		if (!status)
			goto error_free;
	}

	name = "WLOG_FILEAPPENDER_OUTPUT_FILE_NAME";
	nSize = GetEnvironmentVariableA(name, NULL, 0);
	if (nSize)
	{
		env = (LPSTR) malloc(nSize);
		if (!env)
			goto error_output_file_name;

		nSize = GetEnvironmentVariableA(name, env, nSize);
		status = WLog_FileAppender_SetOutputFileName(log, FileAppender, env);
		free(env);

		if (!status)
			goto error_output_file_name;
	}

	return FileAppender;

error_output_file_name:
	free(FileAppender->FilePath);
error_free:
	free(FileAppender);
	return NULL;
}
Esempio n. 6
0
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
}
Esempio n. 7
0
/* this function loads the collector dll (BistroJavaCollector) 
 * and the relevant functions.
 * on success: all functions load,     iJIT_DLL_is_missing = 0, return value = 1
 * on failure: all functions are NULL, iJIT_DLL_is_missing = 1, return value = 0
 */ 
static int loadiJIT_Funcs()
{
    static int bDllWasLoaded = 0;
    char *dllName = (char*)rcsid; /* !! Just to avoid unused code elimination */
#if ITT_PLATFORM==ITT_PLATFORM_WIN
    DWORD dNameLength = 0;
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */

    if(bDllWasLoaded)
    {
        /* dll was already loaded, no need to do it for the second time */
        return 1;
    }

    /* Assumes that the DLL will not be found */
    iJIT_DLL_is_missing = 1;
    FUNC_NotifyEvent = NULL;

    if (m_libHandle) 
    {
#if ITT_PLATFORM==ITT_PLATFORM_WIN
        FreeLibrary(m_libHandle);
#else  /* ITT_PLATFORM==ITT_PLATFORM_WIN */
        dlclose(m_libHandle);
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */
        m_libHandle = NULL;
    }

    /* Try to get the dll name from the environment */
#if ITT_PLATFORM==ITT_PLATFORM_WIN
    dNameLength = GetEnvironmentVariableA(NEW_DLL_ENVIRONMENT_VAR, NULL, 0);
    if (dNameLength)
    {
        DWORD envret = 0;
        dllName = (char*)malloc(sizeof(char) * (dNameLength + 1));
        envret = GetEnvironmentVariableA(NEW_DLL_ENVIRONMENT_VAR, 
                                         dllName, dNameLength);
        if (envret)
        {
            /* Try to load the dll from the PATH... */
            m_libHandle = LoadLibraryExA(dllName, 
                                         NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
        }
        free(dllName);
    } else {
        /* Try to use old VS_PROFILER variable */
        dNameLength = GetEnvironmentVariableA(DLL_ENVIRONMENT_VAR, NULL, 0);
        if (dNameLength)
        {
            DWORD envret = 0;
            dllName = (char*)malloc(sizeof(char) * (dNameLength + 1));
            envret = GetEnvironmentVariableA(DLL_ENVIRONMENT_VAR, 
                                             dllName, dNameLength);
            if (envret)
            {
                /* Try to load the dll from the PATH... */
                m_libHandle = LoadLibraryA(dllName);
            }
            free(dllName);
        }
    }
#else  /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    dllName = getenv(NEW_DLL_ENVIRONMENT_VAR);
    if (!dllName)
        dllName = getenv(DLL_ENVIRONMENT_VAR);
#ifdef ANDROID
    if (!dllName)
        dllName = ANDROID_JIT_AGENT_PATH;
#endif
    if (dllName)
    {
        /* Try to load the dll from the PATH... */
        m_libHandle = dlopen(dllName, RTLD_LAZY);
    }
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */

    if (!m_libHandle)
    {
#if ITT_PLATFORM==ITT_PLATFORM_WIN
        m_libHandle = LoadLibraryA(DEFAULT_DLLNAME);
#else  /* ITT_PLATFORM==ITT_PLATFORM_WIN */
        m_libHandle = dlopen(DEFAULT_DLLNAME, RTLD_LAZY);
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    }

    /* if the dll wasn't loaded - exit. */
    if (!m_libHandle)
    {
        iJIT_DLL_is_missing = 1; /* don't try to initialize 
                                  * JIT agent the second time 
                                  */
        return 0;
    }

#if ITT_PLATFORM==ITT_PLATFORM_WIN
    FUNC_NotifyEvent = (TPNotify)GetProcAddress(m_libHandle, "NotifyEvent");
#else  /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    FUNC_NotifyEvent = (TPNotify)dlsym(m_libHandle, "NotifyEvent");
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    if (!FUNC_NotifyEvent) 
    {
        FUNC_Initialize = NULL;
        return 0;
    }

#if ITT_PLATFORM==ITT_PLATFORM_WIN
    FUNC_Initialize = (TPInitialize)GetProcAddress(m_libHandle, "Initialize");
#else  /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    FUNC_Initialize = (TPInitialize)dlsym(m_libHandle, "Initialize");
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    if (!FUNC_Initialize) 
    {
        FUNC_NotifyEvent = NULL;
        return 0;
    }

    executionMode = (iJIT_IsProfilingActiveFlags)FUNC_Initialize();

    bDllWasLoaded = 1;
    iJIT_DLL_is_missing = 0; /* DLL is ok. */

    /*
     * Call Graph mode: init the thread local storage
     * (need to store the virtual stack there).
     */
    if ( executionMode == iJIT_CALLGRAPH_ON )
    {
        /* Allocate a thread local storage slot for the thread "stack" */
        if (!threadLocalStorageHandle)
#if ITT_PLATFORM==ITT_PLATFORM_WIN
            threadLocalStorageHandle = TlsAlloc();
#else  /* ITT_PLATFORM==ITT_PLATFORM_WIN */
        pthread_key_create(&threadLocalStorageHandle, NULL);
#endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */
    }

    return 1;
}
Esempio n. 8
0
static void
AppendEnvironment(
    Tcl_Obj *pathPtr,
    const char *lib)
{
    int pathc;
    WCHAR wBuf[MAX_PATH];
    char buf[MAX_PATH * TCL_UTF_MAX];
    Tcl_Obj *objPtr;
    Tcl_DString ds;
    const char **pathv;
    char *shortlib;

    /*
     * The shortlib value needs to be the tail component of the lib path. For
     * example, "lib/tcl8.4" -> "tcl8.4" while "usr/share/tcl8.5" -> "tcl8.5".
     */

    for (shortlib = (char *) &lib[strlen(lib)-1]; shortlib>lib ; shortlib--) {
	if (*shortlib == '/') {
	    if ((unsigned)(shortlib - lib) == strlen(lib) - 1) {
		Tcl_Panic("last character in lib cannot be '/'");
	    }
	    shortlib++;
	    break;
	}
    }
    if (shortlib == lib) {
	Tcl_Panic("no '/' character found in lib");
    }

    /*
     * The "L" preceeding the TCL_LIBRARY string is used to tell VC++ that
     * this is a unicode string.
     */

    if (GetEnvironmentVariableW(L"TCL_LIBRARY", wBuf, MAX_PATH) == 0) {
	buf[0] = '\0';
	GetEnvironmentVariableA("TCL_LIBRARY", buf, MAX_PATH);
    } else {
	ToUtf(wBuf, buf);
    }

    if (buf[0] != '\0') {
	objPtr = Tcl_NewStringObj(buf, -1);
	Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);

	TclWinNoBackslash(buf);
	Tcl_SplitPath(buf, &pathc, &pathv);

	/*
	 * The lstrcmpi() will work even if pathv[pathc-1] is random UTF-8
	 * chars because I know shortlib is ascii.
	 */

	if ((pathc > 0) && (lstrcmpiA(shortlib, pathv[pathc - 1]) != 0)) {
	    const char *str;

	    /*
	     * TCL_LIBRARY is set but refers to a different tcl installation
	     * than the current version. Try fiddling with the specified
	     * directory to make it refer to this installation by removing the
	     * old "tclX.Y" and substituting the current version string.
	     */

	    pathv[pathc - 1] = shortlib;
	    Tcl_DStringInit(&ds);
	    str = Tcl_JoinPath(pathc, pathv, &ds);
	    objPtr = Tcl_NewStringObj(str, Tcl_DStringLength(&ds));
	    Tcl_DStringFree(&ds);
	} else {
	    objPtr = Tcl_NewStringObj(buf, -1);
	}
	Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
	ckfree((char *) pathv);
    }
}
Esempio n. 9
0
wLog* WLog_New(LPCSTR name, wLog* rootLogger)
{
	wLog* log = NULL;
	char* env = NULL;
	DWORD nSize;
	int iLevel;
	log = (wLog*) calloc(1, sizeof(wLog));

	if (!log)
		return NULL;

	log->Name = _strdup(name);

	if (!log->Name)
		goto out_fail;

	if (!WLog_ParseName(log, name))
		goto out_fail;

	log->Parent = rootLogger;
	log->ChildrenCount = 0;
	log->ChildrenSize = 16;
	log->FilterLevel = -1;

	if (!(log->Children = (wLog**) calloc(log->ChildrenSize, sizeof(wLog*))))
		goto out_fail;

	log->Appender = NULL;

	if (rootLogger)
	{
		log->Level = WLOG_LEVEL_INHERIT;
	}
	else
	{
		log->Level = WLOG_INFO;
		nSize = GetEnvironmentVariableA("WLOG_LEVEL", NULL, 0);

		if (nSize)
		{
			env = (LPSTR) malloc(nSize);

			if (!env)
				goto out_fail;

			if (!GetEnvironmentVariableA("WLOG_LEVEL", env, nSize))
			{
				fprintf(stderr, "WLOG_LEVEL environment variable changed in my back !\n");
				free(env);
				goto out_fail;
			}

			iLevel = WLog_ParseLogLevel(env);
			free(env);

			if (iLevel >= 0)
				log->Level = (DWORD) iLevel;
		}
	}

	iLevel = WLog_GetFilterLogLevel(log);

	if ((iLevel >= 0) && (iLevel != WLOG_LEVEL_INHERIT))
		log->Level = (DWORD) iLevel;

	return log;
out_fail:
	free(log->Children);
	free(log->Name);
	free(log);
	return NULL;
}
Esempio n. 10
0
/* {{{ php_init_config
 */
int php_init_config(void)
{
	char *php_ini_file_name = NULL;
	char *php_ini_search_path = NULL;
	int php_ini_scanned_path_len;
	char *open_basedir;
	int free_ini_search_path = 0;
	zend_file_handle fh;

	zend_hash_init(&configuration_hash, 8, NULL, config_zval_dtor, 1);

	if (sapi_module.ini_defaults) {
		sapi_module.ini_defaults(&configuration_hash);
	}

	zend_llist_init(&extension_lists.engine, sizeof(char *), (llist_dtor_func_t) free_estring, 1);
	zend_llist_init(&extension_lists.functions, sizeof(char *), (llist_dtor_func_t) free_estring, 1);

	open_basedir = PG(open_basedir);

	if (sapi_module.php_ini_path_override) {
		php_ini_file_name = sapi_module.php_ini_path_override;
		php_ini_search_path = sapi_module.php_ini_path_override;
		free_ini_search_path = 0;
	} else if (!sapi_module.php_ini_ignore) {
		int search_path_size;
		char *default_location;
		char *env_location;
		static const char paths_separator[] = { ZEND_PATHS_SEPARATOR, 0 };
#ifdef PHP_WIN32
		char *reg_location;
		char phprc_path[MAXPATHLEN];
#endif

		env_location = getenv("PHPRC");

#ifdef PHP_WIN32
		if (!env_location) {
			char dummybuf;
			int size;

			SetLastError(0);

			/*If the given bugger is not large enough to hold the data, the return value is 
			the buffer size,  in characters, required to hold the string and its terminating 
			null character. We use this return value to alloc the final buffer. */
			size = GetEnvironmentVariableA("PHPRC", &dummybuf, 0);
			if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
				/* The environment variable doesn't exist. */
				env_location = "";
			} else {
				if (size == 0) {
					env_location = "";
				} else {
					size = GetEnvironmentVariableA("PHPRC", phprc_path, size);
					if (size == 0) {
						env_location = "";
					} else {
						env_location = phprc_path;
					}
				}
			}
		}
#else
		if (!env_location) {
			env_location = "";
		}
#endif
		/*
		 * Prepare search path
		 */

		search_path_size = MAXPATHLEN * 4 + (int)strlen(env_location) + 3 + 1;
		php_ini_search_path = (char *) emalloc(search_path_size);
		free_ini_search_path = 1;
		php_ini_search_path[0] = 0;

		/* Add environment location */
		if (env_location[0]) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, env_location, search_path_size);
			php_ini_file_name = env_location;
		}

#ifdef PHP_WIN32
		/* Add registry location */
		reg_location = GetIniPathFromRegistry();
		if (reg_location != NULL) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, reg_location, search_path_size);
			efree(reg_location);
		}
#endif

		/* Add cwd (not with CLI) */
		if (!sapi_module.php_ini_ignore_cwd) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, ".", search_path_size);
		}

		if (PG(php_binary)) {
			char *separator_location, *binary_location;

			binary_location = estrdup(PG(php_binary));
			separator_location = strrchr(binary_location, DEFAULT_SLASH);

			if (separator_location && separator_location != binary_location) {
				*(separator_location) = 0;
			}
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, binary_location, search_path_size);
			efree(binary_location);
		}

		/* Add default location */
#ifdef PHP_WIN32
		default_location = (char *) emalloc(MAXPATHLEN + 1);

		if (0 < GetWindowsDirectory(default_location, MAXPATHLEN)) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, default_location, search_path_size);
		}

		/* For people running under terminal services, GetWindowsDirectory will
		 * return their personal Windows directory, so lets add the system
		 * windows directory too */
		if (0 < GetSystemWindowsDirectory(default_location, MAXPATHLEN)) {
			if (*php_ini_search_path) {
				strlcat(php_ini_search_path, paths_separator, search_path_size);
			}
			strlcat(php_ini_search_path, default_location, search_path_size);
		}
		efree(default_location);

#else
		default_location = PHP_CONFIG_FILE_PATH;
		if (*php_ini_search_path) {
			strlcat(php_ini_search_path, paths_separator, search_path_size);
		}
		strlcat(php_ini_search_path, default_location, search_path_size);
#endif
	}

	PG(open_basedir) = NULL;

	/*
	 * Find and open actual ini file
	 */

	memset(&fh, 0, sizeof(fh));

	/* If SAPI does not want to ignore all ini files OR an overriding file/path is given.
	 * This allows disabling scanning for ini files in the PHP_CONFIG_FILE_SCAN_DIR but still
	 * load an optional ini file. */
	if (!sapi_module.php_ini_ignore || sapi_module.php_ini_path_override) {

		/* Check if php_ini_file_name is a file and can be opened */
		if (php_ini_file_name && php_ini_file_name[0]) {
			zend_stat_t statbuf;

			if (!VCWD_STAT(php_ini_file_name, &statbuf)) {
				if (!((statbuf.st_mode & S_IFMT) == S_IFDIR)) {
					fh.handle.fp = VCWD_FOPEN(php_ini_file_name, "r");
					if (fh.handle.fp) {
						fh.filename = php_ini_opened_path = expand_filepath(php_ini_file_name, NULL);
					}
				}
			}
		}

		/* Otherwise search for php-%sapi-module-name%.ini file in search path */
		if (!fh.handle.fp) {
			const char *fmt = "php-%s.ini";
			char *ini_fname;
			spprintf(&ini_fname, 0, fmt, sapi_module.name);
			fh.handle.fp = php_fopen_with_path(ini_fname, "r", php_ini_search_path, &php_ini_opened_path);
			efree(ini_fname);
			if (fh.handle.fp) {
				fh.filename = php_ini_opened_path;
			}
		}

		/* If still no ini file found, search for php.ini file in search path */
		if (!fh.handle.fp) {
			fh.handle.fp = php_fopen_with_path("php.ini", "r", php_ini_search_path, &php_ini_opened_path);
			if (fh.handle.fp) {
				fh.filename = php_ini_opened_path;
			}
		}
	}

	if (free_ini_search_path) {
		efree(php_ini_search_path);
	}

	PG(open_basedir) = open_basedir;

	if (fh.handle.fp) {
		fh.type = ZEND_HANDLE_FP;
		RESET_ACTIVE_INI_HASH();

		zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash);

		{
			zval tmp;

			ZVAL_NEW_STR(&tmp, zend_string_init(fh.filename, strlen(fh.filename), 1));
			zend_hash_str_update(&configuration_hash, "cfg_file_path", sizeof("cfg_file_path")-1, &tmp);
			if (php_ini_opened_path) {
				efree(php_ini_opened_path);
			}
			php_ini_opened_path = zend_strndup(Z_STRVAL(tmp), Z_STRLEN(tmp));
		}
	}

	/* Check for PHP_INI_SCAN_DIR environment variable to override/set config file scan directory */
	php_ini_scanned_path = getenv("PHP_INI_SCAN_DIR");
	if (!php_ini_scanned_path) {
		/* Or fall back using possible --with-config-file-scan-dir setting (defaults to empty string!) */
		php_ini_scanned_path = PHP_CONFIG_FILE_SCAN_DIR;
	}
	php_ini_scanned_path_len = (int)strlen(php_ini_scanned_path);

	/* Scan and parse any .ini files found in scan path if path not empty. */
	if (!sapi_module.php_ini_ignore && php_ini_scanned_path_len) {
		struct dirent **namelist;
		int ndir, i;
		zend_stat_t sb;
		char ini_file[MAXPATHLEN];
		char *p;
		zend_file_handle fh2;
		zend_llist scanned_ini_list;
		zend_llist_element *element;
		int l, total_l = 0;
		char *bufpath, *debpath, *endpath;
		int lenpath;

		zend_llist_init(&scanned_ini_list, sizeof(char *), (llist_dtor_func_t) free_estring, 1);
		memset(&fh2, 0, sizeof(fh2));

		bufpath = estrdup(php_ini_scanned_path);
		for (debpath = bufpath ; debpath ; debpath=endpath) {
			endpath = strchr(debpath, DEFAULT_DIR_SEPARATOR);
			if (endpath) {
				*(endpath++) = 0;
			}
			if (!debpath[0]) {
				/* empty string means default builtin value
				   to allow "/foo/phd.d:" or ":/foo/php.d" */
				debpath = PHP_CONFIG_FILE_SCAN_DIR;
			}
			lenpath = (int)strlen(debpath);

			if (lenpath > 0 && (ndir = php_scandir(debpath, &namelist, 0, php_alphasort)) > 0) {

				for (i = 0; i < ndir; i++) {

					/* check for any file with .ini extension */
					if (!(p = strrchr(namelist[i]->d_name, '.')) || (p && strcmp(p, ".ini"))) {
						free(namelist[i]);
						continue;
					}
					/* Reset active ini section */
					RESET_ACTIVE_INI_HASH();

					if (IS_SLASH(debpath[lenpath - 1])) {
						snprintf(ini_file, MAXPATHLEN, "%s%s", debpath, namelist[i]->d_name);
					} else {
						snprintf(ini_file, MAXPATHLEN, "%s%c%s", debpath, DEFAULT_SLASH, namelist[i]->d_name);
					}
					if (VCWD_STAT(ini_file, &sb) == 0) {
						if (S_ISREG(sb.st_mode)) {
							if ((fh2.handle.fp = VCWD_FOPEN(ini_file, "r"))) {
								fh2.filename = ini_file;
								fh2.type = ZEND_HANDLE_FP;

								if (zend_parse_ini_file(&fh2, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash) == SUCCESS) {
									/* Here, add it to the list of ini files read */
									l = (int)strlen(ini_file);
									total_l += l + 2;
									p = estrndup(ini_file, l);
									zend_llist_add_element(&scanned_ini_list, &p);
								}
							}
						}
					}
					free(namelist[i]);
				}
				free(namelist);
			}
		}
		efree(bufpath);

		if (total_l) {
			int php_ini_scanned_files_len = (php_ini_scanned_files) ? (int)strlen(php_ini_scanned_files) + 1 : 0;
			php_ini_scanned_files = (char *) realloc(php_ini_scanned_files, php_ini_scanned_files_len + total_l + 1);
			if (!php_ini_scanned_files_len) {
				*php_ini_scanned_files = '\0';
			}
			total_l += php_ini_scanned_files_len;
			for (element = scanned_ini_list.head; element; element = element->next) {
				if (php_ini_scanned_files_len) {
					strlcat(php_ini_scanned_files, ",\n", total_l);
				}
				strlcat(php_ini_scanned_files, *(char **)element->data, total_l);
				strlcat(php_ini_scanned_files, element->next ? ",\n" : "\n", total_l);
			}
		}
		zend_llist_destroy(&scanned_ini_list);
	} else {
		/* Make sure an empty php_ini_scanned_path ends up as NULL */
		php_ini_scanned_path = NULL;
	}

	if (sapi_module.ini_entries) {
		/* Reset active ini section */
		RESET_ACTIVE_INI_HASH();
		zend_parse_ini_string(sapi_module.ini_entries, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash);
	}

	return SUCCESS;
}
Esempio n. 11
0
void StackWalkInit()
{
	HANDLE hProcess = GetCurrentProcess();
	hDbgHelp = LoadLibraryA("dbghelp.dll");

	if (NULL != hDbgHelp)
	{
		char path[NtfsMaxPath] = {0};
		char temp[NtfsMaxPath];
		pSymInitialize            = (pfnSymInitialize)            GetProcAddress(hDbgHelp, "SymInitialize");
		pSymCleanup               = (pfnSymCleanup)               GetProcAddress(hDbgHelp, "SymCleanup");
		pSymGetOptions            = (pfnSymGetOptions)            GetProcAddress(hDbgHelp, "SymGetOptions");
		pSymSetOptions            = (pfnSymSetOptions)            GetProcAddress(hDbgHelp, "SymSetOptions");
		pStackWalk64              = (pfnStackWalk64)              GetProcAddress(hDbgHelp, "StackWalk64");
		pSymGetSymFromAddr64      = (pfnSymGetSymFromAddr64)      GetProcAddress(hDbgHelp, "SymGetSymFromAddr64");
		pSymFunctionTableAccess64 = (pfnSymFunctionTableAccess64) GetProcAddress(hDbgHelp, "SymFunctionTableAccess64");
		pSymGetModuleBase64       = (pfnSymGetModuleBase64)       GetProcAddress(hDbgHelp, "SymGetModuleBase64");
		pSymGetModuleInfo64       = (pfnSymGetModuleInfo64)       GetProcAddress(hDbgHelp, "SymGetModuleInfo64");
		pSymLoadModule64          = (pfnSymLoadModule64)          GetProcAddress(hDbgHelp, "SymLoadModule64");

		if (GetCurrentDirectoryA(NtfsMaxPath, temp))
		{
			temp[NtfsMaxPath - 1] = 0;
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, ";");
		}
		if (GetModuleFileNameA(NULL, temp, NtfsMaxPath))
		{
			temp[NtfsMaxPath - 1] = 0;
			ShortName(temp)[0] = 0;
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, ";");
		}
		if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", temp, NtfsMaxPath))
		{
			temp[NtfsMaxPath - 1] = 0;
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, ";");
		}
		if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", temp, NtfsMaxPath))
		{
			temp[NtfsMaxPath - 1] = 0;
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, ";");
		}
		if (GetEnvironmentVariableA("SYSTEMROOT", temp, NtfsMaxPath))
		{
			temp[NtfsMaxPath - 1] = 0;
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, ";");
			xstrcat(temp, NtfsMaxPath, "\\system32");
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, ";");
		}
		if (GetEnvironmentVariableA("TEMP", temp, NtfsMaxPath))
		{
			temp[NtfsMaxPath - 1] = 0;
			xstrcat(path, NtfsMaxPath, "SRV*");
			xstrcat(path, NtfsMaxPath, temp);
			xstrcat(path, NtfsMaxPath, "\\websymbols*http://msdl.microsoft.com/download/symbols;");
		}
		else
		{
			xstrcat(path, NtfsMaxPath, "SRC*C:\\temp\\websymbols*http://msdl.microsoft.com/download/symbols;");
		}

		if (pSymInitialize(hProcess, path, false))
		{
			DWORD options = pSymGetOptions();
			options |= SYMOPT_DEBUG;
			pSymSetOptions(options);

			LoadModules(hProcess);
		}
	}
}
Esempio n. 12
0
bool checkArgs(int argc, char* argv[], char** inFile, outFormat &out, int &rowStart, int &rowEnd)
{
	char env[256];
	if (argc < 2)
	{
		std::string tmpFile;
		//printf("No input file specified\n");
//#ifdef _DEBUG
#if 1
		*inFile = _strdup("c:\\Users\\David\\Documents\\packets.txt");
		if (GetEnvironmentVariableA("QUERY_STRING", env, 256))
		{
			//printf("<query>%s</query>\n", env);
			parseQueryString(env, rowStart, rowEnd);
		}
		out = XML;
#else
		std::cout << "Filename: ";
		std::getline(std::cin, tmpFile);
		*inFile = _strdup(tmpFile.c_str());
#endif
#ifdef _DEBUG
		printf("inFile is %s\n", *inFile);
#endif
		return true;
		//return false;	//needs an input file
	}
	if (argc>2)
	{
		*inFile = _strdup(argv[1]);

		for (int i = 2; i <= argc; i++)
		{
			if (strcmp(argv[i], "-x") == 0)
			{
				if (out == CSV)
				{
					printf("-x cannot be specified along with -c\n");
					return false;
				}
				else
					out = XML;
				continue;
			}
			if (strcmp(argv[i], "-c") == 0)
			{
				if (out == XML)
				{
					printf("-c cannot be specified along with -x\n");
					return false;
				}
				else
					out = CSV;
				continue;
			}
			if (strncmp(argv[i], "-r", 2) == 0)
			{
				//TODO parse beginning and ending rows
				continue;
			}
			return false;
		}
	}
	return true;
}
Esempio n. 13
0
/*++
Function:
  GetTempPathA

See MSDN.

Notes:
    On Windows, the temp path is determined by the following steps:
    1. The value of the "TMP" environment variable, or if it doesn't exist,
    2. The value of the "TEMP" environment variable, or if it doesn't exist,
    3. The Windows directory.

    On Unix, we follow in spirit:
    1. The value of the "TMPDIR" environment variable, or if it doesn't exist,
    2. The /tmp directory.
    This is the same approach employed by mktemp.

--*/
DWORD
PALAPI
GetTempPathA(
	     IN DWORD nBufferLength,
	     OUT LPSTR lpBuffer)
{
    DWORD dwPathLen = 0;

    PERF_ENTRY(GetTempPathA);
    ENTRY("GetTempPathA(nBufferLength=%u, lpBuffer=%p)\n",
          nBufferLength, lpBuffer);

    if ( !lpBuffer )
    {
        ERROR( "lpBuffer was not a valid pointer.\n" )
        SetLastError( ERROR_INVALID_PARAMETER );
        LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen);
        PERF_EXIT(GetTempPathA);
        return 0;
    }

    /* Try the TMPDIR environment variable. This is the same env var checked by mktemp. */
    dwPathLen = GetEnvironmentVariableA("TMPDIR", lpBuffer, nBufferLength);
    if (dwPathLen > 0)
    {
        /* The env var existed. dwPathLen will be the length without null termination 
         * if the entire value was successfully retrieved, or it'll be the length
         * required to store the value with null termination.
         */
        if (dwPathLen < nBufferLength)
        {
            /* The environment variable fit in the buffer. Make sure it ends with '/'. */
            if (lpBuffer[dwPathLen - 1] != '/')
            {
                /* If adding the slash would still fit in our provided buffer, do it.  Otherwise, 
                 * let the caller know how much space would be needed.
                 */
                if (dwPathLen + 2 <= nBufferLength)
                {
                    lpBuffer[dwPathLen++] = '/';
                    lpBuffer[dwPathLen] = '\0';
                }
                else
                {
                    dwPathLen += 2;
                }
            }
        }
        else /* dwPathLen >= nBufferLength */
        {
            /* The value is too long for the supplied buffer.  dwPathLen will now be the
             * length required to hold the value, but we don't know whether that value
             * is going to be '/' terminated.  Since we'll need enough space for the '/', and since
             * a caller would assume that the dwPathLen we return will be sufficient, 
             * we make sure to account for it in dwPathLen even if that means we end up saying
             * one more byte of space is needed than actually is.
             */
            dwPathLen++;
        }
    }
    else /* env var not found or was empty */
    {
        /* no luck, use /tmp/ */
        const char *defaultDir = "/tmp/";
        int defaultDirLen = strlen(defaultDir);
        if (defaultDirLen < nBufferLength)
        {
            dwPathLen = defaultDirLen;
            strcpy_s(lpBuffer, nBufferLength, defaultDir);
        }
        else
        {
            /* get the required length */
            dwPathLen = defaultDirLen + 1;
        }
    }

    if ( dwPathLen >= nBufferLength )
    {
        ERROR("Buffer is too small, need space for %d characters including null termination\n", dwPathLen);
        SetLastError( ERROR_INSUFFICIENT_BUFFER );
    }

    LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen);
    PERF_EXIT(GetTempPathA);
    return dwPathLen;
}
Esempio n. 14
0
void WINAPI do_it(void)
{
	HANDLE		 hc = NULL;
	UINT_PTR	 dwCaller = 0;
#ifdef _LOGDEBUG
	if ( GetEnvironmentVariableA("APPDATA",logfile_buf,MAX_PATH) > 0 )
	{
		strncat(logfile_buf,"\\",1);
		strncat(logfile_buf,LOG_FILE,strlen((LPCSTR)LOG_FILE));
	}
#endif
	if (!dll_module)
	{
	#ifdef __GNUC__
		dwCaller = (UINT_PTR)__builtin_return_address(0);
	#else
		dwCaller = (UINT_PTR)_ReturnAddress();
	#endif
	}
	if (dwCaller)
	{
		GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)dwCaller, &dll_module);
	}
	if ( read_appint(L"General",L"SafeEx") > 0 )
	{
		init_safed(NULL);
	}
	if ( read_appint(L"General", L"Portable") > 0 )
	{
		env_thread = (HANDLE)_beginthreadex(NULL,0,&init_global_env,NULL,0,NULL);
		if (env_thread) 
		{
			SetThreadPriority(env_thread,THREAD_PRIORITY_HIGHEST);
			init_portable(NULL);
		}
	}
	if ( is_browser() || is_thunderbird() )
	{
		if ( read_appint(L"General",L"GdiBatchLimit") > 0 )
		{
			hc = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId());
			if (hc)
			{
				CloseHandle((HANDLE)_beginthreadex(NULL,0,&GdiSetLimit_tt,hc,0,NULL));
			}
		}
		if ( read_appint(L"General",L"ProcessAffinityMask") > 0 )
		{
			hc = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId());
			if (hc)
			{
				CloseHandle((HANDLE)_beginthreadex(NULL,0,&SetCpuAffinity_tt,hc,0,NULL));
			}
		}
		if ( read_appint(L"General",L"CreateCrashDump") > 0 )
		{
			CloseHandle((HANDLE)_beginthreadex(NULL,0,&init_exeception,NULL,0,NULL));
		}
		if ( read_appint(L"General", L"Bosskey") > 0 )
		{
			CloseHandle((HANDLE)_beginthreadex(NULL,0,&bosskey_thread,&ff_info,0,NULL));
		}
		CloseHandle((HANDLE)_beginthreadex(NULL,0,&SetPluginPath,NULL,0,NULL));
	}
}
char *sendpraat (void *display, const char *programName, long timeOut, const char *text) {
    char nativeProgramName [100];
#if xwin
    char *home, pidFileName [256], messageFileName [256];
    FILE *pidFile;
    long pid, wid = 0;
#elif win
    char homeDirectory [256], messageFileName [256], windowName [256];
    HWND window;
    (void) display;
    (void) timeOut;
#elif mac
    AEDesc programDescriptor;
    AppleEvent event, reply;
    OSErr err;
    UInt32 signature;
    (void) display;
#endif

    /*
     * Clean up from an earlier call.
     */
    errorMessage [0] = '\0';

    /*
     * Handle case differences.
     */
    strcpy (nativeProgramName, programName);
#if xwin
    nativeProgramName [0] = tolower (nativeProgramName [0]);
#else
    nativeProgramName [0] = toupper (nativeProgramName [0]);
#endif

    /*
     * If the text is going to be sent in a file, create its name.
     * The file is going to be written into the preferences directory of the receiving program.
     * On X Window, the name will be something like /home/jane/.praat-dir/message.
     * On Windows, the name will be something like C:\Documents and Settings\Jane\Praat\Message.txt,
     * or C:\Windows\Praat\Message.txt on older systems.
     * On Macintosh, the text is NOT going to be sent in a file.
     */
#if xwin
    if ((home = getenv ("HOME")) == NULL) {
        sprintf (errorMessage, "HOME environment variable not set.");
        return errorMessage;
    }
    sprintf (messageFileName, "%s/.%s-dir/message", home, programName);
#elif win
    if (GetEnvironmentVariableA ("USERPROFILE", homeDirectory, 255)) {
        ;   /* Ready. */
    } else if (GetEnvironmentVariableA ("HOMEDRIVE", homeDirectory, 255)) {
        GetEnvironmentVariableA ("HOMEPATH", homeDirectory + strlen (homeDirectory), 255);
    } else {
        GetWindowsDirectoryA (homeDirectory, 255);
    }
    sprintf (messageFileName, "%s\\%s\\Message.txt", homeDirectory, programName);
#endif

    /*
     * Write the message file (Unix and Windows only).
     */
#if xwin || win
    {
        FILE* messageFile;
        if ((messageFile = fopen (messageFileName, "w")) == NULL) {
            sprintf (errorMessage, "Cannot create message file \"%s\" "
                     "(no privilege to write to directory, or disk full).\n", messageFileName);
            return errorMessage;
        }
#if xwin
        if (timeOut)
            fprintf (messageFile, "#%ld\n", getpid ());   /* Write own process ID for callback. */
#endif
        fprintf (messageFile, "%s", text);
        fclose (messageFile);
    }
#endif

    /*
     * Where shall we send the message?
     */
#if xwin
    /*
     * Get the process ID and the window ID of a running Praat-shell program.
     */
    sprintf (pidFileName, "%s/.%s-dir/pid", home, programName);
    if ((pidFile = fopen (pidFileName, "r")) == NULL) {
        sprintf (errorMessage, "Program %s not running (or a version older than 3.6).", programName);
        return errorMessage;
    }
    if (fscanf (pidFile, "%ld%ld", & pid, & wid) < 1) {
        fclose (pidFile);
        sprintf (errorMessage, "Program %s not running, or disk has been full.", programName);
        return errorMessage;
    }
    fclose (pidFile);
#elif win
    /*
     * Get the window handle of the "Objects" window of a running Praat-shell program.
     */
    sprintf (windowName, "PraatShell1 %s", programName);
    window = FindWindowA (windowName, NULL);
    if (! window) {
        sprintf (errorMessage, "Program %s not running (or an old version).", programName);
        return errorMessage;
    }
#elif mac
    /*
     * Convert the program name to a Macintosh signature.
     * I know of no system routine for this, so I'll just translate the two most common names:
     */
    if (! strcmp (programName, "praat") || ! strcmp (programName, "Praat") || ! strcmp (programName, "PRAAT"))
        signature = 'PpgB';
    else if (! strcmp (programName, "als") || ! strcmp (programName, "Als") || ! strcmp (programName, "ALS"))
        signature = 'CclA';
    else
        signature = 0;
    AECreateDesc (typeApplSignature, & signature, 4, & programDescriptor);
#endif

    /*
     * Send the message.
     */
#if xwin
    /*
     * Be ready to receive notification of completion.
     */
    if (timeOut)
        signal (SIGUSR2, handleCompletion);
    /*
     * Notify running program.
     */
    if (wid != 0) {   /* Praat shell version October 21, 1998 or later? Send event to window. */
        /*
         * Notify main window.
         */
        XEvent event;
        int displaySupplied = display != NULL;
        if (! displaySupplied) {
            display = XOpenDisplay (NULL);
            if (display == NULL) {
                sprintf (errorMessage, "Cannot open display %s.", XDisplayName (NULL));
                return errorMessage;
            }
        }
        event. type = ClientMessage;
        event. xclient. serial = 0;
        event. xclient. send_event = True;
        event. xclient. display = display;
        event. xclient. window = (Window) wid;
        event. xclient. message_type = XInternAtom (display, "SENDPRAAT", False);
        event. xclient. format = 8;   /* No byte swaps. */
        strcpy (& event. xclient.data.b [0], "SENDPRAAT");
        if(! XSendEvent (display, (Window) wid, True, KeyPressMask, & event)) {
            if (! displaySupplied) XCloseDisplay (display);
            sprintf (errorMessage, "Cannot send message to %s (window %ld). "
                     "The program %s may have been started by a different user, "
                     "or may have crashed.", programName, wid, programName);
            return errorMessage;
        }
        if (! displaySupplied) XCloseDisplay (display);
    } else {
        /*
         * Use interrupt mechanism.
         */
        if (kill (pid, SIGUSR1)) {
            sprintf (errorMessage, "Cannot send message to %s (process %ld). "
                     "The program %s may have been started by a different user, "
                     "or may have crashed.", programName, pid, programName);
            return errorMessage;
        }
    }
    /*
     * Wait for the running program to notify us of completion,
     * but do not wait for more than 'timeOut' seconds.
     */
    if (timeOut) {
        signal (SIGALRM, handleTimeOut);
        alarm (timeOut);
        theTimeOut = timeOut;   /* Hand an argument to handleTimeOut () in a static variable. */
        errorMessage [0] = '\0';
        pause ();
        if (errorMessage [0] != '\0') return errorMessage;
    }
#elif win
    /*
     * Notify the running program by sending a WM_USER message to its main window.
     */
    if (SendMessage (window, WM_USER, 0, 0)) {
        sprintf (errorMessage, "Program %s returns error.", programName);   /* BUG? */
        return errorMessage;
    }
#elif mac
    /*
     * Notify the running program by sending it an Apple event of the magic class 758934755.
     */
    AECreateAppleEvent (758934755, 0, & programDescriptor, kAutoGenerateReturnID, 1, & event);
    AEPutParamPtr (& event, 1, typeChar, text, strlen (text) + 1);
#ifdef __MACH__
    err = AESendMessage (& event, & reply,
                         ( timeOut == 0 ? kAENoReply : kAEWaitReply ) | kAECanInteract | kAECanSwitchLayer,
                         timeOut == 0 ? kNoTimeOut : 60 * timeOut);
#else
    err = AESend (& event, & reply,
                  ( timeOut == 0 ? kAENoReply : kAEWaitReply ) | kAECanInteract | kAECanSwitchLayer,
                  kAENormalPriority, timeOut == 0 ? kNoTimeOut : 60 * timeOut, NULL, NULL);
#endif
    if (err != noErr) {
        if (err == procNotFound || err == connectionInvalid)
            sprintf (errorMessage, "Could not send message to program \"%s\".\n"
                     "The program is probably not running (or an old version).", programName);
        else if (err == errAETimeout)
            sprintf (errorMessage, "Message to program \"%s\" timed out "
                     "after %ld seconds, before completion.", programName, timeOut);
        else
            sprintf (errorMessage, "Unexpected sendpraat error %d.\nNotify the author.", err);
    }
    AEDisposeDesc (& programDescriptor);
    AEDisposeDesc (& event);
    AEDisposeDesc (& reply);
#endif

    /*
     * Notify the caller of success (NULL pointer) or failure (string with an error message).
     */
    return errorMessage [0] == '\0' ? NULL : errorMessage;
}
Esempio n. 16
0
wLog* WLog_GetRoot(void)
{
	char* env;
	DWORD nSize;
	DWORD logAppenderType;

	if (!g_RootLog)
	{
		if (!(g_RootLog = WLog_New("", NULL)))
			return NULL;

		g_RootLog->IsRoot = TRUE;
		WLog_ParseFilters();
		logAppenderType = WLOG_APPENDER_CONSOLE;
		nSize = GetEnvironmentVariableA("WLOG_APPENDER", NULL, 0);

		if (nSize)
		{
			env = (LPSTR) malloc(nSize);

			if (!env)
				goto fail;

			if (!GetEnvironmentVariableA("WLOG_APPENDER", env, nSize))
			{
				fprintf(stderr, "WLOG_APPENDER environment variable modified in my back");
				free(env);
				goto fail;
			}

			if (_stricmp(env, "CONSOLE") == 0)
				logAppenderType = WLOG_APPENDER_CONSOLE;
			else if (_stricmp(env, "FILE") == 0)
				logAppenderType = WLOG_APPENDER_FILE;
			else if (_stricmp(env, "BINARY") == 0)
				logAppenderType = WLOG_APPENDER_BINARY;

#ifdef HAVE_SYSLOG_H
			else if (_stricmp(env, "SYSLOG") == 0)
				logAppenderType = WLOG_APPENDER_SYSLOG;

#endif /* HAVE_SYSLOG_H */
#ifdef HAVE_JOURNALD_H
			else if (_stricmp(env, "JOURNALD") == 0)
				logAppenderType = WLOG_APPENDER_JOURNALD;

#endif
			else if (_stricmp(env, "UDP") == 0)
				logAppenderType = WLOG_APPENDER_UDP;

			free(env);
		}

		if (!WLog_SetLogAppenderType(g_RootLog, logAppenderType))
			goto fail;
	}

	return g_RootLog;
fail:
	free(g_RootLog);
	g_RootLog = NULL;
	return NULL;
}
Esempio n. 17
0
/*++
Function:
  GetTempPathA

See MSDN.

Notes:
    On Windows NT/2000, the temp path is determined by the following steps:
    1. The value of the "TMP" environment variable, or if it doesn't exist,
    2. The value of the "TEMP" environment variable, or if it doesn't exist,
    3. The Windows directory.
    
    In this implementation, '/tmp' is used instead of the Windows directory
    in the final step.
    
    Also note that dwPathLen will always be the proper return value, since
    GetEnvironmentVariable and MultiByteToWideChar will both return the
    required size of the buffer if they fail, which is what this function
    should do also.
--*/
DWORD
PALAPI
GetTempPathA(
	     IN DWORD nBufferLength,
	     OUT LPSTR lpBuffer)
{
    DWORD dwPathLen = 0;
    const char *env_var1 = "TMP";
    const char *env_var2 = "TEMP";
    // GetTempPath is supposed to include the trailing slash.
    const char *defaultDir = "/tmp/";

    PERF_ENTRY(GetTempPathA);
    ENTRY("GetTempPathA(nBufferLength=%u, lpBuffer=%p)\n",
          nBufferLength, lpBuffer);

    if ( !lpBuffer )
    {
        ERROR( "lpBuffer was not a valid pointer.\n" )
        SetLastError( ERROR_INVALID_PARAMETER );
        LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen);
        PERF_EXIT(GetTempPathA);
        return 0;
    }
    
    /* try "TMP" */
    dwPathLen = GetEnvironmentVariableA(env_var1, lpBuffer, nBufferLength);
    if ( dwPathLen > 0 )
    {
        goto done;
    }

    /* no luck, try "TEMP" */
    dwPathLen = GetEnvironmentVariableA(env_var2, lpBuffer, nBufferLength);
    if ( dwPathLen > 0 )
    {
        goto done;
    }
    
    /* still no luck, use /tmp */
    if ( strlen(defaultDir) < nBufferLength )
    {
        strcpy(lpBuffer, defaultDir);
        dwPathLen = strlen(defaultDir);
    }
    else
    {
        /* get the required length */
        dwPathLen = strlen(defaultDir) + 1;
    }

done:
    if ( dwPathLen > nBufferLength )
    {
        ERROR("Buffer is too small, need %d characters\n", dwPathLen);
        SetLastError( ERROR_INSUFFICIENT_BUFFER );
    }

    LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen);
    PERF_EXIT(GetTempPathA);
    return dwPathLen;
}
Esempio n. 18
0
static bool isSubJOM()
{
    return GetEnvironmentVariableA("_JOMSRVKEY_", NULL, 0) > 0;
}
int TestWtsApiQuerySessionInformation(int argc, char* argv[])
{
	DWORD index, i;
	DWORD count;
	BOOL bSuccess;
	HANDLE hServer;
	LPSTR pBuffer;
	DWORD sessionId;
	DWORD bytesReturned;
	PWTS_SESSION_INFOA pSessionInfo;

#ifndef _WIN32
	if (!GetEnvironmentVariableA("WTSAPI_LIBRARY", NULL, 0))
	{
		printf("%s: No RDS environment detected, skipping test\n", __FUNCTION__);
		return 0;
	}
#endif

	hServer = WTS_CURRENT_SERVER_HANDLE;

	count = 0;
	pSessionInfo = NULL;

	bSuccess = WTSEnumerateSessionsA(hServer, 0, 1, &pSessionInfo, &count);

	if (!bSuccess)
	{
		printf("WTSEnumerateSessions failed: %d\n", (int) GetLastError());
		return 0;
	}

	printf("WTSEnumerateSessions count: %d\n", (int) count);

	for (index = 0; index < count; index++)
	{
		char* Username;
		char* Domain;
		char* ClientName;
		ULONG ClientBuildNumber;
		USHORT ClientProductId;
		ULONG ClientHardwareId;
		USHORT ClientProtocolType;
		PWTS_CLIENT_DISPLAY ClientDisplay;
		PWTS_CLIENT_ADDRESS ClientAddress;
		WTS_CONNECTSTATE_CLASS ConnectState;

		pBuffer = NULL;
		bytesReturned = 0;

		sessionId = pSessionInfo[index].SessionId;

		printf("[%u] SessionId: %u State: %s (%u) WinstationName: '%s'\n",
				index,
				pSessionInfo[index].SessionId,
				WTSSessionStateToString(pSessionInfo[index].State),
				pSessionInfo[index].State,
				pSessionInfo[index].pWinStationName);

		/* WTSUserName */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSUserName, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSUserName failed: %d\n", (int) GetLastError());
			return -1;
		}

		Username = (char*) pBuffer;
		printf("\tWTSUserName: '******'\n", Username);

		/* WTSDomainName */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSDomainName, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSDomainName failed: %d\n", (int) GetLastError());
			return -1;
		}

		Domain = (char*) pBuffer;
		printf("\tWTSDomainName: '%s'\n", Domain);

		/* WTSConnectState */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSConnectState, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSConnectState failed: %d\n", (int) GetLastError());
			return -1;
		}

		ConnectState = *((WTS_CONNECTSTATE_CLASS*) pBuffer);
		printf("\tWTSConnectState: %u (%s)\n", ConnectState, WTSSessionStateToString(ConnectState));

		/* WTSClientBuildNumber */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientBuildNumber, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientBuildNumber failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientBuildNumber = *((ULONG*) pBuffer);
		printf("\tWTSClientBuildNumber: %u\n", ClientBuildNumber);

		/* WTSClientName */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientName, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientName failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientName = (char*) pBuffer;
		printf("\tWTSClientName: '%s'\n", ClientName);

		/* WTSClientProductId */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientProductId, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientProductId failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientProductId = *((USHORT*) pBuffer);
		printf("\tWTSClientProductId: %u\n", ClientProductId);

		/* WTSClientHardwareId */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientHardwareId, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientHardwareId failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientHardwareId = *((ULONG*) pBuffer);
		printf("\tWTSClientHardwareId: %u\n", ClientHardwareId);

		/* WTSClientAddress */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientAddress, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientAddress failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientAddress = (PWTS_CLIENT_ADDRESS) pBuffer;
		printf("\tWTSClientAddress: AddressFamily: %u Address: ",
				ClientAddress->AddressFamily);
		for (i = 0; i < sizeof(ClientAddress->Address); i++)
			printf("%02X", ClientAddress->Address[i]);
		printf("\n");


		/* WTSClientDisplay */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientDisplay, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientDisplay failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientDisplay = (PWTS_CLIENT_DISPLAY) pBuffer;
		printf("\tWTSClientDisplay: HorizontalResolution: %u VerticalResolution: %u ColorDepth: %u\n",
				ClientDisplay->HorizontalResolution, ClientDisplay->VerticalResolution,
				ClientDisplay->ColorDepth);

		/* WTSClientProtocolType */

		bSuccess = WTSQuerySessionInformationA(hServer, sessionId, WTSClientProtocolType, &pBuffer, &bytesReturned);

		if (!bSuccess)
		{
			printf("WTSQuerySessionInformation WTSClientProtocolType failed: %d\n", (int) GetLastError());
			return -1;
		}

		ClientProtocolType = *((USHORT*) pBuffer);
		printf("\tWTSClientProtocolType: %u\n", ClientProtocolType);
	}

	WTSFreeMemory(pSessionInfo);

	return 0;
}
Esempio n. 20
0
bool EnvironmentImpl::hasImpl(const std::string& name)
{
	DWORD len = GetEnvironmentVariableA(name.c_str(), 0, 0);
	return len > 0;
}
Esempio n. 21
0
inline char * getenv(char const* key) {
  return GetEnvironmentVariableA(key,getenv_buf,getenv_maxch) ? getenv_buf : NULL;
}
Esempio n. 22
0
File: os.hpp Progetto: SlyryD/carmel
inline char * getenv(char const* key) {
  //TODO: thread-safe version of getenv
  return GetEnvironmentVariableA(key, getenv_buf, getenv_maxch) ? getenv_buf : NULL;
}
Esempio n. 23
0
static HRESULT load_mono(LPCWSTR mono_path)
{
    static const WCHAR lib[] = {'\\','l','i','b',0};
    static const WCHAR etc[] = {'\\','e','t','c',0};
    WCHAR mono_dll_path[MAX_PATH+16];
    WCHAR mono_lib_path[MAX_PATH+4], mono_etc_path[MAX_PATH+4];
    char mono_lib_path_a[MAX_PATH], mono_etc_path_a[MAX_PATH];
    int trace_size;
    char trace_setting[256];
    int verbose_size;
    char verbose_setting[256];

    if (is_mono_shutdown)
    {
        ERR("Cannot load Mono after it has been shut down.\n");
        return E_FAIL;
    }

    if (!mono_handle)
    {
        strcpyW(mono_lib_path, mono_path);
        strcatW(mono_lib_path, lib);
        WideCharToMultiByte(CP_UTF8, 0, mono_lib_path, -1, mono_lib_path_a, MAX_PATH, NULL, NULL);

        strcpyW(mono_etc_path, mono_path);
        strcatW(mono_etc_path, etc);
        WideCharToMultiByte(CP_UTF8, 0, mono_etc_path, -1, mono_etc_path_a, MAX_PATH, NULL, NULL);

        if (!find_mono_dll(mono_path, mono_dll_path)) goto fail;

        mono_handle = LoadLibraryW(mono_dll_path);

        if (!mono_handle) goto fail;

#define LOAD_MONO_FUNCTION(x) do { \
    x = (void*)GetProcAddress(mono_handle, #x); \
    if (!x) { \
        goto fail; \
    } \
} while (0);

        LOAD_MONO_FUNCTION(mono_assembly_get_image);
        LOAD_MONO_FUNCTION(mono_assembly_load_from);
        LOAD_MONO_FUNCTION(mono_assembly_open);
        LOAD_MONO_FUNCTION(mono_config_parse);
        LOAD_MONO_FUNCTION(mono_class_from_mono_type);
        LOAD_MONO_FUNCTION(mono_class_from_name);
        LOAD_MONO_FUNCTION(mono_class_get_method_from_name);
        LOAD_MONO_FUNCTION(mono_domain_assembly_open);
        LOAD_MONO_FUNCTION(mono_domain_get);
        LOAD_MONO_FUNCTION(mono_domain_get_by_id);
        LOAD_MONO_FUNCTION(mono_domain_set);
        LOAD_MONO_FUNCTION(mono_domain_set_config);
        LOAD_MONO_FUNCTION(mono_free);
        LOAD_MONO_FUNCTION(mono_image_open);
        LOAD_MONO_FUNCTION(mono_install_assembly_preload_hook);
        LOAD_MONO_FUNCTION(mono_jit_exec);
        LOAD_MONO_FUNCTION(mono_jit_init_version);
        LOAD_MONO_FUNCTION(mono_jit_set_trace_options);
        LOAD_MONO_FUNCTION(mono_marshal_get_vtfixup_ftnptr);
        LOAD_MONO_FUNCTION(mono_object_get_domain);
        LOAD_MONO_FUNCTION(mono_object_get_virtual_method);
        LOAD_MONO_FUNCTION(mono_object_new);
        LOAD_MONO_FUNCTION(mono_object_unbox);
        LOAD_MONO_FUNCTION(mono_profiler_install);
        LOAD_MONO_FUNCTION(mono_reflection_type_from_name);
        LOAD_MONO_FUNCTION(mono_runtime_invoke);
        LOAD_MONO_FUNCTION(mono_runtime_object_init);
        LOAD_MONO_FUNCTION(mono_runtime_quit);
        LOAD_MONO_FUNCTION(mono_set_dirs);
        LOAD_MONO_FUNCTION(mono_set_verbose_level);
        LOAD_MONO_FUNCTION(mono_stringify_assembly_name);
        LOAD_MONO_FUNCTION(mono_string_new);
        LOAD_MONO_FUNCTION(mono_thread_attach);
        LOAD_MONO_FUNCTION(mono_thread_manage);
        LOAD_MONO_FUNCTION(mono_trace_set_assembly);

#undef LOAD_MONO_FUNCTION

#define LOAD_OPT_MONO_FUNCTION(x, default) do { \
    x = (void*)GetProcAddress(mono_handle, #x); \
    if (!x) { \
        x = default; \
    } \
} while (0);

        LOAD_OPT_MONO_FUNCTION(mono_image_open_from_module_handle, image_open_module_handle_dummy);
        LOAD_OPT_MONO_FUNCTION(mono_trace_set_print_handler, set_print_handler_dummy);
        LOAD_OPT_MONO_FUNCTION(mono_trace_set_printerr_handler, set_print_handler_dummy);

#undef LOAD_OPT_MONO_FUNCTION

        mono_profiler_install(NULL, mono_shutdown_callback_fn);

        mono_trace_set_print_handler(mono_print_handler_fn);
        mono_trace_set_printerr_handler(mono_print_handler_fn);

        mono_set_dirs(mono_lib_path_a, mono_etc_path_a);

        mono_config_parse(NULL);

        mono_install_assembly_preload_hook(mono_assembly_preload_hook_fn, NULL);

        trace_size = GetEnvironmentVariableA("WINE_MONO_TRACE", trace_setting, sizeof(trace_setting));

        if (trace_size)
        {
            mono_jit_set_trace_options(trace_setting);
        }

        verbose_size = GetEnvironmentVariableA("WINE_MONO_VERBOSE", verbose_setting, sizeof(verbose_setting));

        if (verbose_size)
        {
            mono_set_verbose_level(verbose_setting[0] - '0');
        }
    }

    return S_OK;

fail:
    ERR("Could not load Mono into this process\n");
    FreeLibrary(mono_handle);
    mono_handle = NULL;
    return E_FAIL;
}
Esempio n. 24
0
	const char* get_environment_variable(const char* name)
	{
		memset(_static_buffer, 0, STATIC_BUFFER_SIZE);
		GetEnvironmentVariableA(name, _static_buffer, STATIC_BUFFER_SIZE);
		return _static_buffer;
	}