Beispiel #1
0
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, 
    HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
    lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT

#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
    HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
    HRESULT hRes = CoInitialize(NULL);
#endif
    _ASSERTE(SUCCEEDED(hRes));
    _Module.Init(ObjectMap, hInstance, &LIBID_ETSMANAGERLib);
    _Module.dwThreadID = GetCurrentThreadId();
    TCHAR szTokens[] = _T("-/");

    int nRet = 0;
    BOOL bRun = TRUE;
    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (lstrcmpi(lpszToken, _T("UnregServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_ETSManager, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
            bRun = FALSE;
            break;
        }
        if (lstrcmpi(lpszToken, _T("RegServer"))==0)
        {
            _Module.UpdateRegistryFromResource(IDR_ETSManager, TRUE);
            nRet = _Module.RegisterServer(TRUE);
            bRun = FALSE;
            break;
        }
        lpszToken = FindOneOf(lpszToken, szTokens);
    }

    if (bRun)
    {
        _Module.StartMonitor();
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, 
            REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
        _ASSERTE(SUCCEEDED(hRes));
        hRes = CoResumeClassObjects();
#else
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, 
            REGCLS_MULTIPLEUSE);
#endif
        _ASSERTE(SUCCEEDED(hRes));

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

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

    _Module.Term();
    CoUninitialize();
    return nRet;
}
int wasapi_init(cubeb ** context, char const * context_name)
{
  HRESULT hr;
  IMMDeviceEnumerator * enumerator = NULL;

  hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  if (FAILED(hr)) {
    LOG("Could not init COM.");
    return CUBEB_ERROR;
  }

  cubeb * ctx = (cubeb *)calloc(1, sizeof(cubeb));

  ctx->ops = &wasapi_ops;

  hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
                        NULL, CLSCTX_INPROC_SERVER,
                        IID_PPV_ARGS(&enumerator));
  if (FAILED(hr)) {
    LOG("Could not get device enumerator.");
    wasapi_destroy(ctx);
    return CUBEB_ERROR;
  }

  /* eMultimedia is okay for now ("Music, movies, narration, [...]").
   * We will need to change this when we distinguish streams by use-case, other
   * possible values being eConsole ("Games, system notification sounds [...]")
   * and eCommunication ("Voice communication"). */
  hr = enumerator->GetDefaultAudioEndpoint(eRender,
                                           eMultimedia,
                                           &ctx->device);
  if (FAILED(hr)) {
    LOG("Could not get default audio endpoint.");
    SafeRelease(enumerator);
    wasapi_destroy(ctx);
    return CUBEB_ERROR;
  }

  ctx->mmcss_module = LoadLibraryA("Avrt.dll");

  if (ctx->mmcss_module) {
    ctx->set_mm_thread_characteristics =
      (set_mm_thread_characteristics_function) GetProcAddress(
          ctx->mmcss_module, "AvSetMmThreadCharacteristicsA");
    ctx->revert_mm_thread_characteristics =
      (revert_mm_thread_characteristics_function) GetProcAddress(
          ctx->mmcss_module, "AvRevertMmThreadCharacteristics");
    if (!(ctx->set_mm_thread_characteristics && ctx->revert_mm_thread_characteristics)) {
      LOG("Could not load AvSetMmThreadCharacteristics or AvRevertMmThreadCharacteristics: %d", GetLastError());
      FreeLibrary(ctx->mmcss_module);
    }
  } else {
    // This is not a fatal error, but we might end up glitching when
    // the system is under high load.
    LOG("Could not load Avrt.dll");
    ctx->set_mm_thread_characteristics = &set_mm_thread_characteristics_noop;
    ctx->revert_mm_thread_characteristics = &revert_mm_thread_characteristics_noop;
  }
  
  SafeRelease(enumerator);

  *context = ctx;

  return CUBEB_OK;
}
Beispiel #3
0
// Initialisation of the CXAudio2 engine
void CXAudio2::Init(const CXAudio2SetupParameters& params)
{
	// Copy parameters
	numChannels = params.numChannels;
	maxFrequencyRatio = params.maxFrequencyRatio;
	SetCommandBatching(params.commandBatching);
	SetCacheMode(params.cacheMode);
	SetCacheLimit(params.cacheLimit);

	// Initialize COM
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

#ifdef _DEBUG
	// Request debug XAudio2 engine
	hr = XAudio2Create(&pXAudio2, XAUDIO2_DEBUG_ENGINE,	XAUDIO2_DEFAULT_PROCESSOR);
#else
	// Request standard XAudio2 engine
	hr = XAudio2Create(&pXAudio2, 0,					XAUDIO2_DEFAULT_PROCESSOR);
#endif

	// XAudio2Create failed
	if (FAILED(hr))
		throw CXAudio2Error(hr, "Failed to create XAudio2");

	// Mastering limiter & volume meter effect chain for mastering voice
	XAUDIO2_EFFECT_DESCRIPTOR descriptor[2];
	int count = 0;

	// Create the mastering limiter if enabled
	if (params.limiter_enable) {
		IUnknown* pLimiter;
		hr = CreateFX(__uuidof(FXMasteringLimiter), &pLimiter);

		if (FAILED(hr))
			throw CXAudio2Error(hr, "Failed to create mastering limiter");

		descriptor[0].InitialState = true;
		descriptor[0].OutputChannels = 2;
		descriptor[0].pEffect = pLimiter;

		// Write volume meter to next descriptor
		count++;
	}

	// Create the volume meter for the mastering voice
#ifdef _DEBUG
	hr = XAudio2CreateVolumeMeter(&(master.pVolumeMeter), XAUDIO2FX_DEBUG);
#else
	hr = XAudio2CreateVolumeMeter(&(master.pVolumeMeter), 0);
#endif

	if (FAILED(hr))
		throw CXAudio2Error(hr, "Failed to create XAudio2 volume meter");

	// Set up the effect chain to apply the volume metering to the mastering voice
	descriptor[count].InitialState = true;
	descriptor[count].OutputChannels = 2;
	descriptor[count].pEffect = master.pVolumeMeter;
	master.volumeMeterEffectIndex = count;
	count++;

	XAUDIO2_EFFECT_CHAIN chain;
	chain.EffectCount = count;
	chain.pEffectDescriptors = descriptor;

	// Create stereo mastering voice
	hr = pXAudio2->CreateMasteringVoice(&(master.pMaster), 2, XAUDIO2_DEFAULT_SAMPLERATE, 
										0, 0, &chain);

	if (FAILED(hr))
		throw CXAudio2Error(hr, "Failed to create XAudio2 mastering voice");

	// Get the device details
	pXAudio2->GetDeviceDetails(0, &deviceDetails);

	// Set up the channel strip
	channels.reserve(numChannels);

	for (int i = 0; i < numChannels; i++)
		channels.push_back(Channel(this, i));

	// Set the master volume as per parameters; -3.0dB by default to help prevent clipping
	master.SetVolume(params.masterGain);
}
Beispiel #4
0
HRESULT InitMFStreamer()
{
	printf("InitMFStreamer.\n");

	CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	CHECK_HR(InitVPXEncoder(&_vpxConfig, &_vpxCodec, WIDTH, HEIGHT), L"Failed to intialise the VPX encoder.\n");

	// Create an attribute store to hold the search criteria.
	CHECK_HR(MFCreateAttributes(&videoConfig, 1), L"Error creating video configuation.");
	//CHECK_HR(MFCreateAttributes(&audioConfig, 1), L"Error creating audio configuation.");;

	// Request video capture devices.
	CHECK_HR(videoConfig->SetGUID(
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), L"Error initialising video configuration object.");

	// Request audio capture devices.
	/*CHECK_HR(audioConfig->SetGUID(
	MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
	MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID), L"Error initialising audio configuration object.");*/

	// Enumerate the devices,
	CHECK_HR(MFEnumDeviceSources(videoConfig, &videoDevices, &videoDeviceCount), L"Error enumerating video devices.");
	//CHECK_HR(MFEnumDeviceSources(audioConfig, &audioDevices, &audioDeviceCount), L"Error enumerating audio devices.");

	//printf("Video device Count: %i, Audio device count: %i.\n", videoDeviceCount, audioDeviceCount);
	printf("Video device Count: %i.\n", videoDeviceCount);

	CHECK_HR(videoDevices[0]->ActivateObject(IID_PPV_ARGS(&videoSource)), L"Error activating video device.");
	//CHECK_HR(audioDevices[0]->ActivateObject(IID_PPV_ARGS(&audioSource)), L"Error activating audio device.");

	// Initialize the Media Foundation platform.
	CHECK_HR(MFStartup(MF_VERSION), L"Error on Media Foundation startup.");

	/*WCHAR *pwszFileName = L"sample.mp4";
	IMFSinkWriter *pWriter;*/

	/*CHECK_HR(MFCreateSinkWriterFromURL(
	pwszFileName,
	NULL,
	NULL,
	&pWriter), L"Error creating mp4 sink writer.");*/

	// Create the source readers.
	CHECK_HR(MFCreateSourceReaderFromMediaSource(
		videoSource,
		videoConfig,
		&videoReader), L"Error creating video source reader.");

	//ListModes(videoReader);

	/*CHECK_HR(MFCreateSourceReaderFromMediaSource(
	audioSource,
	audioConfig,
	&audioReader), L"Error creating audio source reader.");*/

	FindVideoMode(videoReader, MF_INPUT_FORMAT, WIDTH, HEIGHT, desiredInputVideoType);

	if (desiredInputVideoType == NULL) {
		printf("The specified media type could not be found for the MF video reader.\n");
	}
	else {
		CHECK_HR(videoReader->SetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, desiredInputVideoType),
			L"Error setting video reader media type.\n");

		CHECK_HR(videoReader->GetCurrentMediaType(
			(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
			&videoType), L"Error retrieving current media type from first video stream.");
		CMediaTypeTrace *videoTypeMediaTrace = new CMediaTypeTrace(videoType);

		printf("Video input media type: %s.\n", videoTypeMediaTrace->GetString());

		LONG pStride = 0;
		GetDefaultStride(videoType, &pStride);
		printf("Stride %i.\n", pStride);
			
		/*printf("Press any key to continue...");
		getchar();*/

		/*audioReader->GetCurrentMediaType(
		(DWORD)MF_SOURCE_READER_FIRST_AUDIO_STREAM,
		&audioType);*/
		//CMediaTypeTrace *audioTypeMediaTrace = new CMediaTypeTrace(audioType);
		//printf("Audio input media type: %s.\n", audioTypeMediaTrace->GetString());

		//printf("Configuring H.264 sink.\n");

		// Set up the H.264 sink.
		/*CHECK_HR(ConfigureEncoder(videoType, &videoStreamIndex, &audioStreamIndex, pWriter), L"Error configuring encoder.");
		printf("Video stream index %i, audio stream index %i.\n", videoStreamIndex, audioStreamIndex);*/

		// Register the color converter DSP for this process, in the video 
		// processor category. This will enable the sink writer to enumerate
		// the color converter when the sink writer attempts to match the
		// media types.
		CHECK_HR(MFTRegisterLocalByCLSID(
			__uuidof(CColorConvertDMO),
			MFT_CATEGORY_VIDEO_PROCESSOR,
			L"",
			MFT_ENUM_FLAG_SYNCMFT,
			0,
			NULL,
			0,
			NULL
			), L"Error registering colour converter DSP.");

		// Add the input types to the H.264 sink writer.
		/*CHECK_HR(pWriter->SetInputMediaType(videoStreamIndex, videoType, NULL), L"Error setting the sink writer video input type.");
		videoType->Release();
		CHECK_HR(pWriter->SetInputMediaType(audioStreamIndex, audioType, NULL), L"Error setting the sink writer audio input type.");
		audioType->Release();*/

		//CHECK_HR(pWriter->BeginWriting(), L"Failed to begin writing on the H.264 sink.");

		//InitializeCriticalSection(&critsec);
	}
}
Beispiel #5
0
// Function name	: RedirectInputThread
// Description	    : 
// Return type		: void 
// Argument         : RedirectInputThreadArg *arg
void RedirectInputThread(RedirectInputThreadArg *arg)
{
	IRemoteShell *pLaunch=NULL;
	HRESULT hr=S_OK;
	HANDLE hObject[2];
	long error=0;
	BSTR berror_msg;
	DWORD ret_val;

	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

	berror_msg = SysAllocString(L"");
	CoGetInterfaceAndReleaseStream (*arg->ppStream, IID_IRemoteShell, (void**) &pLaunch);
	delete arg->ppStream;

	DWORD dwThreadID;
	HANDLE hRSIThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadStdinThread, NULL, 0, &dwThreadID);

	hObject[0] = arg->hEvent;
	hObject[1] = g_hBufferEvent1;

	berror_msg = SysAllocString(L"");
	while (true)
	{
		ret_val = WaitForMultipleObjects(2, hObject, FALSE, INFINITE);
		if (ret_val == WAIT_OBJECT_0+1)
		{
			if (g_num_read > 0)
			{
				SAFEARRAYBOUND bound;
				VARIANT vInput;
				void *pBuf;

				VariantInit(&vInput);
				bound.lLbound = 0;
				bound.cElements = g_num_read;
				vInput.vt = VT_UI1 | VT_ARRAY;
				vInput.parray = SafeArrayCreate(VT_UI1, 1, &bound);

				SafeArrayAccessData(vInput.parray, &pBuf);
				memcpy(pBuf, g_pBuffer, g_num_read);
				SafeArrayUnaccessData(vInput.parray);

				error = 0;
				hr = pLaunch->PutProcessInput(vInput, &error, &berror_msg);
				if (FAILED(hr))
				{
					VariantClear(&vInput);
					printf("PutInteractiveInput failed: %d\n", hr);
					PrintError(hr);
					break;
				}
				if (error)
				{
					VariantClear(&vInput);
					if (wcslen(berror_msg) < 1)
						wprintf(L"PutInteractiveInput failed: %d %s\n", error, berror_msg);
					else
						wprintf(L"PutInteractiveInput failed: %s\n", berror_msg);
					break;
				}
				VariantClear(&vInput);
			}
			ResetEvent(g_hBufferEvent1);
			SetEvent(g_hBufferEvent2);
		}
		else
		{
			//printf("g_hFinishedEvent signalled\n");
		    TerminateThread(hRSIThread, 0);
			break;
		}
	}

	pLaunch->Release();
	CoUninitialize();
}
Beispiel #6
0
/*! 
  \brief Tries to open the wan (dialup, vpn...) adapter, and immediately closes it.
  \return TRUE on success.
*/
BOOLEAN WanPacketTestAdapter()
{
	PBLOB_TABLE pBlobTable = NULL;
	HBLOB hFilterBlob = NULL;
	BOOLEAN retVal;
	DWORD i;
	HRESULT hResult;

	if ( g_hModule == NULL)
	{
		g_hModule = LoadLibrary("npp\\ndisnpp.dll");
	}

	if ( g_hModule == NULL)
	{
		return FALSE;
	}

	hResult = CoInitialize(NULL);

	//
 	// if  the calling thread has already initialized COM with a 
 	// different threading model, we have this error
 	// however, we are able to support another threading model,
 	// so we try to initialize COM with another threading model.
 	// This new call should succeed with S_FALSE.
 	//
 	if (hResult == RPC_E_CHANGED_MODE)
	{
		hResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
	
		//MULTITHREADED threading is only supported on Windows 2000
		if (hResult == RPC_E_CHANGED_MODE && IsWindows2000())
		{
			hResult = CoInitializeEx(NULL, COINIT_MULTITHREADED);
		}
	}

	if (hResult != S_OK && hResult != S_FALSE)
		return FALSE;

	if ( CreateBlob(&hFilterBlob) != NMERR_SUCCESS )
	{
		CoUninitialize();
		return FALSE;
	}
	
	if ( SetBoolInBlob(hFilterBlob, OWNER_NPP, CATEGORY_CONFIG, TAG_INTERFACE_REALTIME_CAPTURE, TRUE) != NMERR_SUCCESS )
	{
		DestroyBlob( hFilterBlob);
		CoUninitialize();
		return FALSE;
	}

	if ( SetBoolInBlob(hFilterBlob, OWNER_NPP, CATEGORY_LOCATION, TAG_RAS, TRUE) != NMERR_SUCCESS )
	{
		DestroyBlob( hFilterBlob);
		CoUninitialize();
		return FALSE;
	}

	if ( GetNPPBlobTable(hFilterBlob, &pBlobTable) != NMERR_SUCCESS )
	{
		DestroyBlob( hFilterBlob);
		CoUninitialize();
		return FALSE;
	}

	DestroyBlob (hFilterBlob);

	if (pBlobTable->dwNumBlobs == 1)
		retVal = TRUE;
	else
		retVal = FALSE;

	for ( i = 0 ; i < pBlobTable->dwNumBlobs ; i++ )
		DestroyBlob(pBlobTable->hBlobs[i]);
		
	GlobalFree(pBlobTable);	
	CoUninitialize();
			
	return retVal;
}
int APIENTRY _tWinMain(HINSTANCE hInstance,
                       HINSTANCE /*hPrevInstance*/,
                       LPTSTR    lpCmdLine,
                       int       /*nCmdShow*/)
{
    SetDllDirectory(L"");
    SetTaskIDPerUUID();
    CRegStdDWORD loc = CRegStdDWORD(L"Software\\TortoiseGit\\LanguageID", 1033);
    long langId = loc;
    CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

    CLangDll langDLL;
    hResource = langDLL.Init(L"TortoiseIDiff", langId);
    if (!hResource)
        hResource = hInstance;

    git_libgit2_init();

    CCmdLineParser parser(lpCmdLine);

    if (parser.HasKey(L"?") || parser.HasKey(L"help"))
    {
        TCHAR buf[1024] = { 0 };
        LoadString(hResource, IDS_COMMANDLINEHELP, buf, _countof(buf));
        MessageBox(nullptr, buf, L"TortoiseIDiff", MB_ICONINFORMATION);
        langDLL.Close();
        return 0;
    }


    MSG msg;
    hInst = hInstance;

    INITCOMMONCONTROLSEX used = {
        sizeof(INITCOMMONCONTROLSEX),
        ICC_STANDARD_CLASSES | ICC_BAR_CLASSES | ICC_WIN95_CLASSES
    };
    InitCommonControlsEx(&used);

    // load the cursors we need
    curHand = static_cast<HCURSOR>(LoadImage(hInst, MAKEINTRESOURCE(IDC_PANCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE));
    curHandDown = static_cast<HCURSOR>(LoadImage(hInst, MAKEINTRESOURCE(IDC_PANDOWNCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE));

    auto mainWindow = std::make_unique<CMainWindow>(hResource);
    mainWindow->SetRegistryPath(L"Software\\TortoiseGit\\TortoiseIDiffWindowPos");
    std::wstring leftfile = parser.HasVal(L"left") ? parser.GetVal(L"left") : L"";
    std::wstring rightfile = parser.HasVal(L"right") ? parser.GetVal(L"right") : L"";
    if ((leftfile.empty()) && (lpCmdLine[0] != 0))
    {
        int nArgs;
        LPWSTR * szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
        if (szArglist)
        {
            if (nArgs == 3)
            {
                // Four parameters:
                // [0]: Program name
                // [1]: left file
                // [2]: right file
                if (PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]))
                {
                    leftfile = szArglist[1];
                    rightfile = szArglist[2];
                }
            }
        }

        // Free memory allocated for CommandLineToArgvW arguments.
        LocalFree(szArglist);
    }
    mainWindow->SetLeft(leftfile.c_str(), parser.HasVal(L"lefttitle") ? parser.GetVal(L"lefttitle") : L"");
    mainWindow->SetRight(rightfile.c_str(), parser.HasVal(L"righttitle") ? parser.GetVal(L"righttitle") : L"");
    if (parser.HasVal(L"base"))
        mainWindow->SetSelectionImage(FileTypeBase, parser.GetVal(L"base"), parser.HasVal(L"basetitle") ? parser.GetVal(L"basetitle") : L"");
    if (parser.HasVal(L"mine"))
        mainWindow->SetSelectionImage(FileTypeMine, parser.GetVal(L"mine"), parser.HasVal(L"minetitle") ? parser.GetVal(L"minetitle") : L"");
    if (parser.HasVal(L"theirs"))
        mainWindow->SetSelectionImage(FileTypeTheirs, parser.GetVal(L"theirs"), parser.HasVal(L"theirstitle") ? parser.GetVal(L"theirstitle") : L"");
    if (parser.HasVal(L"result"))
        mainWindow->SetSelectionResult(parser.GetVal(L"result"));
    mainWindow->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? reinterpret_cast<HWND>(parser.GetLongLongVal(L"resolvemsghwnd")) : 0;
    mainWindow->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? static_cast<WPARAM>(parser.GetLongLongVal(L"resolvemsgwparam")) : 0;
    mainWindow->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? static_cast<LPARAM>(parser.GetLongLongVal(L"resolvemsglparam")) : 0;
    if (mainWindow->RegisterAndCreateWindow())
    {
        HACCEL hAccelTable = LoadAccelerators(hResource, MAKEINTRESOURCE(IDR_TORTOISEIDIFF));
        if (!parser.HasVal(L"left") && parser.HasVal(L"base") && !parser.HasVal(L"mine") && !parser.HasVal(L"theirs"))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_FILE_OPEN, 0);
        }
        if (parser.HasKey(L"overlay"))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_OVERLAPIMAGES, 0);
        }
        if (parser.HasKey(L"fit"))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0);
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0);
        }
        if (parser.HasKey(L"fitwidth"))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0);
        }
        if (parser.HasKey(L"fitheight"))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0);
        }
        if (parser.HasKey(L"showinfo"))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_IMAGEINFO, 0);
        }
        // Main message loop:
        while (GetMessage(&msg, nullptr, 0, 0))
        {
            if (!TranslateAccelerator(*mainWindow, hAccelTable, &msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
        return static_cast<int>(msg.wParam);
    }
    langDLL.Close();
    DestroyCursor(curHand);
    DestroyCursor(curHandDown);
    CoUninitialize();
    git_libgit2_shutdown();
    return 1;
}
Beispiel #8
0
void Shortcut_Init (void)
{
   CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
}
Beispiel #9
0
//int init_vfw_encoder(char *dll_name, BITMAPINFOHEADER *input_bih, BITMAPINFOHEADER *output_bih)
static BITMAPINFOHEADER* vfw_open_encoder(char *dll_name, char *compdatafile, BITMAPINFOHEADER *input_bih,unsigned int out_fourcc)
{
  HRESULT ret;
  BITMAPINFOHEADER* output_bih=NULL;
  int temp_len;
  FILE *fd=NULL;
  char *drvdata=NULL;
  struct stat st;

//sh_video = malloc(sizeof(sh_video_t));

  mp_msg(MSGT_WIN32,MSGL_V,"======= Win32 (VFW) VIDEO Encoder init =======\n");
  CoInitRes = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
//  memset(&sh_video->o_bih, 0, sizeof(BITMAPINFOHEADER));
//  output_bih->biSize = sizeof(BITMAPINFOHEADER);

//  encoder_hic = ICOpen( 0x63646976, out_fourcc, ICMODE_COMPRESS);
    encoder_hic = ICOpen( (long) dll_name, out_fourcc, ICMODE_COMPRESS);
  if(!encoder_hic){
    mp_msg(MSGT_WIN32,MSGL_ERR,"ICOpen failed! unknown codec / wrong parameters?\n");
    return NULL;
  }
  mp_msg(MSGT_WIN32,MSGL_INFO,"HIC: %x\n", encoder_hic);

#if 1
{
  ICINFO icinfo;

  ret = ICGetInfo(encoder_hic, &icinfo, sizeof(ICINFO));
  mp_msg(MSGT_WIN32,MSGL_INFO,"%ld - %ld - %d\n", ret, icinfo.dwSize, sizeof(ICINFO));
  mp_msg(MSGT_WIN32,MSGL_INFO,MSGTR_MPCODECS_CompressorType, icinfo.fccType);
  mp_msg(MSGT_WIN32,MSGL_INFO,MSGTR_MPCODECS_CompressorSubtype, icinfo.fccHandler);
  mp_msg(MSGT_WIN32,MSGL_INFO,MSGTR_MPCODECS_CompressorFlags,
    icinfo.dwFlags, icinfo.dwVersion, icinfo.dwVersionICM);
//printf("Compressor name: %s\n", icinfo.szName);
//printf("Compressor description: %s\n", icinfo.szDescription);

mp_msg(MSGT_WIN32,MSGL_INFO,MSGTR_MPCODECS_Flags);
if (icinfo.dwFlags & VIDCF_QUALITY)
    mp_msg(MSGT_WIN32,MSGL_INFO,MSGTR_MPCODECS_Quality);
if (icinfo.dwFlags & VIDCF_FASTTEMPORALD)
    mp_msg(MSGT_WIN32,MSGL_INFO," fast-decompr");
if (icinfo.dwFlags & VIDCF_QUALITYTIME)
    mp_msg(MSGT_WIN32,MSGL_INFO," temp-quality");
mp_msg(MSGT_WIN32,MSGL_INFO,"\n");
}
#endif

  if(compdatafile){
    if (!strncmp(compdatafile, "dialog", 6)){
      if (ICSendMessage(encoder_hic, ICM_CONFIGURE, -1, 0) != ICERR_OK){
        mp_msg(MSGT_WIN32,MSGL_ERR,"Compressor doesn't have a configure dialog!\n");
        return NULL;
      }
      if (ICSendMessage(encoder_hic, ICM_CONFIGURE, 0, 0) != ICERR_OK){
        mp_msg(MSGT_WIN32,MSGL_ERR,"Compressor configure dialog failed!\n");
        return NULL;
      }
    }
    else {
      if (stat(compdatafile, &st) < 0){
        mp_msg(MSGT_WIN32,MSGL_ERR,"Compressor data file not found!\n");
        return NULL;
      }
      fd = fopen(compdatafile, "rb");
      if (!fd){
        mp_msg(MSGT_WIN32,MSGL_ERR,"Cannot open Compressor data file!\n");
        return NULL;
      }
      drvdata = (char *) malloc(st.st_size);
      if (fread(drvdata, st.st_size, 1, fd) != 1) {
        mp_msg(MSGT_WIN32,MSGL_ERR,"Cannot read Compressor data file!\n");
        fclose(fd);
        free(drvdata);
        return NULL;
      }
      fclose(fd);
      mp_msg(MSGT_WIN32,MSGL_ERR,"Compressor data %d bytes\n", st.st_size);
      if (!(temp_len = (unsigned int) ICSendMessage(encoder_hic, ICM_SETSTATE, (LPARAM) drvdata, (int) st.st_size))){
        mp_msg(MSGT_WIN32,MSGL_ERR,"ICSetState failed!\n");
        free(drvdata);
        return NULL;
      }
      free(drvdata);
      mp_msg(MSGT_WIN32,MSGL_INFO,"ICSetState ret: %d\n", temp_len);
    }
  }

  temp_len = ICCompressGetFormatSize(encoder_hic, input_bih);
  mp_msg(MSGT_WIN32,MSGL_INFO,"ICCompressGetFormatSize ret: %d\n", temp_len);

  if (temp_len < sizeof(BITMAPINFOHEADER)) temp_len=sizeof(BITMAPINFOHEADER);

  output_bih = malloc(temp_len+4);
  memset(output_bih,0,temp_len);
  output_bih->biSize = temp_len; //sizeof(BITMAPINFOHEADER);

  return output_bih;
}
Beispiel #10
0
WMI::WMI()
{
    wbem = NULL;
    result = S_OK;
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
}
Beispiel #11
0
int main() {
	int argc;
	wchar_t **_argv;
	wchar_t **env;
	int si = 0;
	__wgetmainargs(&argc, &_argv, &env, _CRT_glob, &si);
#else
int wmain(int argc, wchar_t *_argv[]) {
#endif
	char **argv = (char**)malloc(argc*sizeof(char*));
	for (int i=0; i<argc; i++) {
		int len = WideCharToMultiByte(CP_UTF8, 0, _argv[i], -1, NULL, 0, NULL, NULL);
		if (!len) {
			std::cout << "Failed to translate commandline to Unicode" << std::endl;
			return 1;
		}
		char *temp = (char*)malloc(len*sizeof(char));
		len = WideCharToMultiByte(CP_UTF8, 0, _argv[i], -1, temp, len, NULL, NULL);
		if (!len) {
			std::cout << "Failed to translate commandline to Unicode" << std::endl;
			return 1;
		}
		argv[i] = temp;
	}
#else /* defined(_WIN32) && !defined(__MINGW32__) */
int main(int argc, char *argv[]) {
#endif /* defined(_WIN32) && !defined(__MINGW32__) */
	try {
		ParseCMDLine(argc, argv);
	} catch (const char *Error) {
		std::cout << std::endl << Error << std::endl;
		return 1;
	} catch (std::string Error) {
		std::cout << std::endl << Error << std::endl;
		return 1;
	} catch (...) {
		std::cout << std::endl << "Unknown error" << std::endl;
		return 1;
	}

#ifdef _WIN32
	if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) {
		std::cout << "COM initialization failure" << std::endl;
		return 1;
	}
#endif /* _WIN32 */

	FFMS_Init(0, 1);

	switch (Verbose) {
		case 0: FFMS_SetLogLevel(AV_LOG_QUIET); break;
		case 1: FFMS_SetLogLevel(AV_LOG_WARNING); break;
		case 2: FFMS_SetLogLevel(AV_LOG_INFO); break;
		case 3:	FFMS_SetLogLevel(AV_LOG_VERBOSE); break;
		default: FFMS_SetLogLevel(AV_LOG_DEBUG); // if user used -v 4 or more times, he deserves the spam
	}

	try {
		DoIndexing();
	} catch (const char *Error) {
		std::cout << Error << std::endl;
		if (Index)
			FFMS_DestroyIndex(Index);
		return 1;
	} catch (std::string Error) {
		std::cout << std::endl << Error << std::endl;
		if (Index)
			FFMS_DestroyIndex(Index);
		return 1;
	} catch (...) {
		std::cout << std::endl << "Unknown error" << std::endl;
		if (Index)
			FFMS_DestroyIndex(Index);
		return 1;
	}

	if (Index)
		FFMS_DestroyIndex(Index);
#ifdef _WIN32
	CoUninitialize();
#endif
	return 0;
}
Beispiel #12
0
int
main (int argc, char *argv[])
{
	int i;
	int ret;

        // BEGIN NEW CODE
        server *fake_serv;
        GIOChannel *channel;
        session *sess;
        // END NEW CODE

#ifdef WIN32
	HRESULT coinit_result;
#endif

	srand ((unsigned int) time (NULL)); /* CL: do this only once! */

	/* We must check for the config dir parameter, otherwise load_config() will behave incorrectly.
	 * load_config() must come before fe_args() because fe_args() calls gtk_init() which needs to
	 * know the language which is set in the config. The code below is copy-pasted from fe_args()
	 * for the most part. */
	if (argc >= 2)
	{
		for (i = 1; i < argc; i++)
		{
			if ((strcmp (argv[i], "-d") == 0 || strcmp (argv[i], "--cfgdir") == 0)
				&& i + 1 < argc)
			{
				xdir = g_strdup (argv[i + 1]);
			}
			else if (strncmp (argv[i], "--cfgdir=", 9) == 0)
			{
				xdir = g_strdup (argv[i] + 9);
			}

			if (xdir != NULL)
			{
				if (xdir[strlen (xdir) - 1] == G_DIR_SEPARATOR)
				{
					xdir[strlen (xdir) - 1] = 0;
				}
				break;
			}
		}
	}

#if ! GLIB_CHECK_VERSION (2, 36, 0)
        // RFM: Don't think we hit this
	g_type_init ();
#endif

	if (check_config_dir () == 0)
	{
		if (load_config () != 0)
			load_default_config ();
	} else
	{
		/* this is probably the first run */
		load_default_config ();
		make_config_dirs ();
		make_dcc_dirs ();
	}

	/* we MUST do this after load_config () AND before fe_init (thus gtk_init) otherwise it will fail */
	// RFM: Does nothing on *NIX
        set_locale ();

        // RFM: Parses some command line crap. Not important
	ret = fe_args (argc, argv);
	if (ret != -1)
		return ret;
	
#ifdef USE_DBUS
	hexchat_remote ();
#endif

#ifdef USE_LIBPROXY
        // RFM: Not using
	libproxy_factory = px_proxy_factory_new();
#endif

#ifdef WIN32
	coinit_result = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);
	if (SUCCEEDED (coinit_result))
	{
		CoInitializeSecurity (NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
	}
#endif

        // RFM: Inits some fe-text stuff
	fe_init ();

        // RFM: Pretty sure this just allows us to save chats...
	/* This is done here because cfgfiles.c is too early in
	* the startup process to use gtk functions. */
	if (g_access (get_xdir (), W_OK) != 0)
	{
		char buf[2048];

		g_snprintf (buf, sizeof(buf),
			_("You do not have write access to %s. Nothing from this session can be saved."),
			get_xdir ());
		fe_message (buf, FE_MSG_ERROR);
	}

        // RFM: Checks if root on *NIX 
#ifndef WIN32
#ifndef __EMX__
	/* OS/2 uses UID 0 all the time */
	if (getuid () == 0)
		fe_message (_("* Running IRC as root is stupid! You should\n"
			      "  create a User Account and use that to login.\n"), FE_MSG_WARN|FE_MSG_WAIT);
#endif
#endif /* !WIN32 */

        // RFM: Loads a bunch of configure options
	xchat_init ();

        // BEGIN NEW CODE
        fake_serv = server_new();
        fake_serv->sok = STDIN_FILENO;
        //        fake_serv->pos = 0; //??? 
        sess = session_new(fake_serv, "fake_sess", SESS_CHANNEL, 0);
        fake_serv->server_session = sess;
        fake_serv->front_session = sess;
        channel = g_io_channel_unix_new(STDIN_FILENO);
        g_io_add_watch(channel, G_IO_IN, (GIOFunc)server_read, fake_serv);
        //g_io_add_watch(channel, G_IO_IN, (GIOFunc)io_callback, fake_serv);
        g_io_channel_unref(channel);
        // END NEW CODE

	fe_main ();

#ifdef WIN32
	if (SUCCEEDED (coinit_result))
	{
		CoUninitialize ();
	}
#endif

#ifdef USE_LIBPROXY
	px_proxy_factory_free(libproxy_factory);
#endif

#ifdef WIN32
	WSACleanup ();
#endif

	return 0;
}
Beispiel #13
0
CFilterPosition::CFilterPosition(void)
{
    CoInitializeEx(NULL, NULL);
    this->p_IsInitialized = FALSE;
}
void main(int argc, char**argv)
{
	std::wcout << L"\n ===================================\n";
	std::wcout << L"\n  TextFinderComponent C++ Interface ";
	std::wcout << L"\n ===================================\n";

	HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

	if (!SUCCEEDED(hr))
	{
		std::wcout << L"\n  could not initialize COM";
	}

	try
	{
		CComQIPtr<ITextCompCOM> TextFinderComp;

		TextFinderComp.CoCreateInstance(CLSID_TextCompCOM);
		
		if (TextFinderComp != 0)
		{
			std::wcout << L"\n =============================================================\n";

			std::wcout << "The Text Component Interface was successfully initialized" << std::endl;

			std::wcout << L"\n =============================================================\n";

			InputArgumentParser parser;

			if (parser.parseCommandLineArgs2TextCompArguments(argc, argv))
			{
				HRESULT h0 = TextFinderComp->InitializeComponent();

				HRESULT h1 = TextFinderComp->SetSearchPath(CComBSTR(parser.getDirectoryPath().c_str()));

				BSTR allPatterns;
				BSTR recursion;

				allPatterns = convertstdSTR2BSTR(bool2String(true)) ;    //By default find all patterns
				
				recursion = convertstdSTR2BSTR(bool2String(false)) ;  // By default Recursion is disabled

				if (parser.getRecursionFlag())
				{
					recursion = convertstdSTR2BSTR(bool2String(true));
				}

				if (!parser.getAllPatternsFlag())
				{
					allPatterns = convertstdSTR2BSTR(bool2String(false));
				}

				HRESULT h2 = TextFinderComp->SetSpecialSearchClause(recursion, allPatterns);

				HRESULT h3 = TextFinderComp->SetFilePatterns(convertVector2CCOMSafeArray(parser.getFilePatterns()).GetSafeArrayPtr());

				HRESULT h4 = TextFinderComp->SetTextPatterns(convertVector2CCOMSafeArray(parser.getTextPatterns()).GetSafeArrayPtr());

				if (SUCCEEDED(h0) && SUCCEEDED(h1) && SUCCEEDED(h2) && SUCCEEDED(h3) && SUCCEEDED(h4))
				{
					
					SAFEARRAY files;
				
					SAFEARRAY* pFiles = &files;

					TextFinderComp->GetQualifyingFileList(&pFiles);

					CComSafeArray<BSTR> Files;

					Files.Attach(pFiles);	

					std::wcout << L"\n =============================================================\n";
					std::wcout << L"\n =============================================================\n";

					std::wcout<<"The Qualifying Files from the Text Search Component via C++ COM interface"<<std::endl;

					displayCCOMBSTRFiles(Files);

					std::cout << "End of C++ Client for Text Search Component" << std::endl;

					std::wcout << L"\n =============================================================\n";

				}
			}

			else
			{
				parser.displayIllegalArgumentMessage();
			}

		}

	}
	catch (std::exception& ex)
	{
		std::wcout << L"\n  Exception Encountered during COM Stuff .. Contact Admin and Bug Him!" << ex.what() << L"\n\n";
		return;
	}

	std::wcout << L"\n\n";
	CoUninitialize();
}
Beispiel #15
0
void ALDeviceList::Enumerate()
{
    char *devices;
    int major, minor, index;
    const char *actualDeviceName;

    Msg("SOUND: OpenAL: enumerate devices...");
    // have a set of vectors storing the device list, selection status, spec version #, and XRAM support status
    // -- empty all the lists and reserve space for 10 devices
    m_devices.clear				();

    CoUninitialize();
    // grab function pointers for 1.0-API functions, and if successful proceed to enumerate all devices
    if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))
    {
        Msg("SOUND: OpenAL: EnumerationExtension Present");

        devices				= (char *)alcGetString(NULL, ALC_DEVICE_SPECIFIER);
        Msg					("devices %s",devices);
        m_defaultDeviceName	= (char *)alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
        Msg("SOUND: OpenAL: system  default SndDevice name is %s", m_defaultDeviceName.c_str());

        // ManowaR
        // "Generic Hardware" device on software AC'97 codecs introduce
        // high CPU usage ( up to 30% ) as a consequence - freezes, FPS drop
        // So if default device is "Generic Hardware" which maps to DirectSound3D interface
        // We re-assign it to "Generic Software" to get use of old good DirectSound interface
        // This makes 3D-sound processing unusable on cheap AC'97 codecs
        // Also we assume that if "Generic Hardware" exists, than "Generic Software" is also exists
        // Maybe wrong

        if(0==stricmp(m_defaultDeviceName.c_str(),AL_GENERIC_HARDWARE))
        {
            m_defaultDeviceName			= AL_GENERIC_SOFTWARE;
            Msg("SOUND: OpenAL: default SndDevice name set to %s", m_defaultDeviceName.c_str());
        }

        index				= 0;
        // go through device list (each device terminated with a single NULL, list terminated with double NULL)
        while (*devices != NULL)
        {
            ALCdevice *device		= alcOpenDevice(devices);
            if (device)
            {
                ALCcontext *context = alcCreateContext(device, NULL);
                if (context)
                {
                    alcMakeContextCurrent(context);
                    // if new actual device name isn't already in the list, then add it...
                    actualDeviceName = alcGetString(device, ALC_DEVICE_SPECIFIER);

                    if ( (actualDeviceName != NULL) && xr_strlen(actualDeviceName)>0 )
                    {
                        alcGetIntegerv					(device, ALC_MAJOR_VERSION, sizeof(int), &major);
                        alcGetIntegerv					(device, ALC_MINOR_VERSION, sizeof(int), &minor);
                        m_devices.push_back				(ALDeviceDesc(actualDeviceName,minor,major));
                        m_devices.back().xram			= (alIsExtensionPresent("EAX-RAM") == TRUE);
                        m_devices.back().eax			= (alIsExtensionPresent("EAX2.0") == TRUE);
                        // KD: disable unwanted eax flag to force eax on all devices
                        m_devices.back().eax_unwanted	= 0;/*((0==xr_strcmp(actualDeviceName,AL_GENERIC_HARDWARE))||
														   (0==xr_strcmp(actualDeviceName,AL_GENERIC_SOFTWARE)));*/
                        ++index;
                    }
                    alcDestroyContext(context);
                } else
                    Msg("SOUND: OpenAL: cant create context for %s",device);
                alcCloseDevice(device);
            } else
                Msg("SOUND: OpenAL: cant open device %s",devices);

            devices		+= xr_strlen(devices) + 1;
        }
    } else
        Msg("SOUND: OpenAL: EnumerationExtension NOT Present");

    ResetFilters();

    if(0!=GetNumDevices())
        Msg("SOUND: OpenAL: All available devices:");

    int majorVersion, minorVersion;
    for (int i = 0; i < GetNumDevices(); i++)
    {
        GetDeviceVersion		(i, &majorVersion, &minorVersion);
        Msg	("%d. %s, Spec Version %d.%d %s",
             i+1,
             GetDeviceName(i).c_str(),
             majorVersion,
             minorVersion,
             (GetDeviceName(i)==m_defaultDeviceName)? "(default)":"" );
    }
    CoInitializeEx (NULL, COINIT_MULTITHREADED);
}
int wmain(int argc, wchar_t* argv[])
{
    HRESULT hr = S_OK;
    HANDLE completionEvent = NULL;
    IXpsPrintJob* job = NULL;
    IXpsPrintJobStream* jobStream = NULL;
    IXpsOMObjectFactory* xpsFactory = NULL;
    IOpcPartUri* partUri = NULL;
    IXpsOMPackageWriter* packageWriter = NULL;
    XPS_SIZE pageSize = {816, 1056};
    IXpsOMPage* xpsPage = NULL;
    IXpsOMFontResource* fontResource = NULL;
    XPS_POINT origin = {50.0f, 200.0f};
    XPS_JOB_STATUS jobStatus = {};

    if (argc < 2 || argc > 3)
    {
        Usage(argv[0]);
        return 1;
    }

    if (FAILED(hr = CoInitializeEx(0, COINIT_MULTITHREADED)))
    {
        fwprintf(stderr, L"ERROR: CoInitializeEx failed with HRESULT 0x%X\n", hr);
        return 1;
    }

    if (SUCCEEDED(hr))
    {
        completionEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
        if (!completionEvent)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            fwprintf(stderr, L"ERROR: Could not create competion event: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = StartXpsPrintJob(
                    argv[1],
                    NULL,
                    argc == 3 ? argv[2] : NULL,
                    NULL,
                    completionEvent,
                    NULL,
                    0,
                    &job,
                    &jobStream,
                    NULL
                    )))
        {
            fwprintf(stderr, L"ERROR: Could not start XPS print job: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = CoCreateInstance(
                    __uuidof(XpsOMObjectFactory),
                    NULL,
                    CLSCTX_INPROC_SERVER,
                    __uuidof(IXpsOMObjectFactory),
                    reinterpret_cast<void**>(&xpsFactory)
                    )
                )
            )
        {
            fwprintf(stderr, L"ERROR: Could not create XPS OM Object Factory: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = xpsFactory->CreatePartUri(L"/FixedDocumentSequence.fdseq", &partUri)))
        {
            fwprintf(stderr, L"ERROR: Could not create part URI: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = xpsFactory->CreatePackageWriterOnStream(
                    jobStream,
                    TRUE,
                    XPS_INTERLEAVING_ON,
                    partUri,
                    NULL,
                    NULL,
                    NULL,
                    NULL,
                    &packageWriter
                    )
                )
           )
        {
            fwprintf(stderr, L"ERROR: Could not create package writer: 0x%X\n", hr);
        }
    }

    if (partUri)
    {
        partUri->Release();
        partUri = NULL;
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = xpsFactory->CreatePartUri(L"/Documents/1/FixedDocument.fdoc", &partUri)))
        {
            fwprintf(stderr, L"ERROR: Could not create part URI: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = packageWriter->StartNewDocument(partUri, NULL, NULL, NULL, NULL)))
        {
            fwprintf(stderr, L"ERROR: Could not start new document: 0x%X\n", hr);
        }
    }

    if (partUri)
    {
        partUri->Release();
        partUri = NULL;
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = xpsFactory->CreatePartUri(L"/Documents/1/Pages/1.fpage", &partUri)))
        {
            fwprintf(stderr, L"ERROR: Could not create part URI: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = xpsFactory->CreatePage(&pageSize, L"en-US", partUri, &xpsPage)))
        {
            fwprintf(stderr, L"ERROR: Could not create page: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = CreateFontResourceForFont(xpsFactory, g_fontName, &fontResource)))
        {
            // Error already reported.
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = AddGlyphs(
                    xpsFactory,
                    xpsPage,
                    fontResource,
                    L"XPS",
                    &origin,
                    72.0f,
                    XPS_STYLE_SIMULATION_NONE)))
        {
            // Error already reported.
        }
    }

    if (SUCCEEDED(hr))
    {
        origin.x = 420.0f;
        origin.y = 300.0f;

        if (FAILED(hr = AddGlyphs(
                    xpsFactory,
                    xpsPage,
                    fontResource,
                    L"Print with Confidence",
                    &origin,
                    36.0f,
                    XPS_STYLE_SIMULATION_ITALIC)))
        {
            // Error already reported.
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = packageWriter->AddPage(
                    xpsPage,
                    &pageSize,
                    NULL,
                    NULL,
                    NULL,
                    NULL
                    )))
        {
            fwprintf(stderr, L"ERROR: Could not add page to document: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = packageWriter->Close()))
        {
            fwprintf(stderr, L"ERROR: Could not close package writer: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = jobStream->Close()))
        {
            fwprintf(stderr, L"ERROR: Could not close job stream: %08X\n", hr);
        }
    }
    else
    {
        // Only cancel the job if we succeeded in creating one in the first place.
        if (job)
        {
            // Tell the XPS Print API that we're giving up.  Don't overwrite hr with the return from
            // this function.
            job->Cancel();
        }
    }


    if (SUCCEEDED(hr))
    {
        wprintf(L"Waiting for job completion...\n");

        if (WaitForSingleObject(completionEvent, INFINITE) != WAIT_OBJECT_0)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            fwprintf(stderr, L"ERROR: Wait for completion event failed: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        if (FAILED(hr = job->GetJobStatus(&jobStatus)))
        {
            fwprintf(stderr, L"ERROR: Could not get job status: %08X\n", hr);
        }
    }

    if (SUCCEEDED(hr))
    {
        switch (jobStatus.completion)
        {
            case XPS_JOB_COMPLETED:
                break;
            case XPS_JOB_CANCELLED:
                fwprintf(stderr, L"ERROR: job was cancelled\n");
                hr = E_FAIL;
                break;
            case XPS_JOB_FAILED:
                fwprintf(stderr, L"ERROR: Print job failed: %08X\n", jobStatus.jobStatus);
                hr = E_FAIL;
                break;
            default:
                fwprintf(stderr, L"ERROR: unexpected failure\n");
                hr = E_UNEXPECTED;
                break;
        }
    }

    if (SUCCEEDED(hr))
    {
        wprintf(L"Done!\n");
    }

    if (fontResource)
    {
        fontResource->Release();
        fontResource = NULL;
    }

    if (xpsPage)
    {
        xpsPage->Release();
        xpsPage = NULL;
    }

    if (packageWriter)
    {
        packageWriter->Release();
        packageWriter = NULL;
    }

    if (partUri)
    {
        partUri->Release();
        partUri = NULL;
    }

    if (xpsFactory)
    {
        xpsFactory->Release();
        xpsFactory = NULL;
    }

    if (jobStream)
    {
        jobStream->Release();
        jobStream = NULL;
    }

    if (job)
    {
        job->Release();
        job = NULL;
    }

    if (completionEvent)
    {
        CloseHandle(completionEvent);
        completionEvent = NULL;
    }

    CoUninitialize();

    return SUCCEEDED(hr) ? 0 : 1;
}
Beispiel #17
0
//+---------------------------------------------------------------------------
//
// Function:  HrGetINetCfg
//
// Purpose:   Initialize COM, create and initialize INetCfg.
//            Obtain write lock if indicated.
//
// Arguments:
//    fGetWriteLock [in]  whether to get write lock
//    ppnc          [in]  pointer to pointer to INetCfg object
//
// Returns:   S_OK on success, otherwise an error code
//
// Notes:
//
HRESULT HrGetINetCfg(IN BOOL fGetWriteLock,
                     INetCfg** ppnc)
{
    HRESULT hr=S_OK;

    // Initialize the output parameters.
    *ppnc = NULL;

    // initialize COM
    hr = CoInitializeEx(NULL,
                        COINIT_DISABLE_OLE1DDE | COINIT_APARTMENTTHREADED );

    if (SUCCEEDED(hr))
    {
        // Create the object implementing INetCfg.
        //
        INetCfg* pnc;
        hr = CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER,
                              IID_INetCfg, (void**)&pnc);
        if (SUCCEEDED(hr))
        {
            INetCfgLock * pncLock = NULL;
            if (fGetWriteLock)
            {
                // Get the locking interface
                hr = pnc->QueryInterface(IID_INetCfgLock,
                                         (LPVOID *)&pncLock);
                if (SUCCEEDED(hr))
                {
                    // Attempt to lock the INetCfg for read/write
                    static const ULONG c_cmsTimeout = 15000;
                    static const WCHAR c_szSampleNetcfgApp[] =
                        L"Sample Netcfg Application (netcfg.exe)";
                    PWSTR szLockedBy;

                    hr = pncLock->AcquireWriteLock(c_cmsTimeout,
                                                   c_szSampleNetcfgApp,
                                                   &szLockedBy);
                    if (S_FALSE == hr)
                    {
                        hr = NETCFG_E_NO_WRITE_LOCK;
                    }
                }
            }

            if (SUCCEEDED(hr))
            {
                // Initialize the INetCfg object.
                //
                hr = pnc->Initialize(NULL);
                if (SUCCEEDED(hr))
                {
                    *ppnc = pnc;
                    pnc->AddRef();
                }
                else
                {
                    // initialize failed, if obtained lock, release it
                    if (pncLock)
                    {
                        pncLock->ReleaseWriteLock();
                    }
                }
            }
            ReleaseObj(pncLock);
            ReleaseObj(pnc);
        }

        if (FAILED(hr))
        {
            CoUninitialize();
        }
    }

    return hr;
}
/******************************Public*Routine******************************\
* OpenMovie
*
\**************************************************************************/
HRESULT
CMovie::OpenMovie(
    TCHAR *lpFileName
    )
{
    IUnknown        *pUnk;
    HRESULT         hres;
    WCHAR           FileName[MAX_PATH];

    // Check input string
    if (lpFileName == NULL)
        return E_POINTER;

    hres = StringCchCopyW(FileName, NUMELMS(FileName), lpFileName);

    hres = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    if(hres == S_FALSE)
        CoUninitialize();

    hres = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
                            IID_IUnknown, (LPVOID *)&pUnk);

    if(SUCCEEDED(hres))
    {
        m_Mode = MOVIE_OPENED;
        hres = pUnk->QueryInterface(IID_IFilterGraph, (LPVOID *)&m_Fg);
        if(FAILED(hres))
        {
            pUnk->Release();
            return hres;
        }

        hres = AddVideoMixingRendererToFG();
        if(FAILED(hres))
        {
            m_Fg->Release(); m_Fg = NULL;
            return hres;
        }

        hres = pUnk->QueryInterface(IID_IGraphBuilder, (LPVOID *)&m_Gb);
        if(FAILED(hres))
        {
            pUnk->Release();
            m_Fg->Release(); m_Fg = NULL;
            m_Wc->Release(); m_Wc = NULL;
            return hres;
        }

        hres = RenderFileToVideoRenderer( m_Gb, FileName, TRUE);
        if(FAILED(hres))
        {
            pUnk->Release();
            m_Fg->Release(); m_Fg = NULL;
            m_Wc->Release(); m_Wc = NULL;
            m_Gb->Release(); m_Gb = NULL;
            return hres;
        }

        hres = m_Wc->QueryInterface(IID_IVMRMixerControl9, (LPVOID *) &m_pMixControl);
        if(FAILED(hres))
        {
            pUnk->Release();
            m_Fg->Release(); m_Fg = NULL;
            m_Wc->Release(); m_Wc = NULL;
            m_Gb->Release(); m_Gb = NULL;
            m_pMixControl = NULL;
            return hres;
        }

        hres = pUnk->QueryInterface(IID_IMediaControl, (LPVOID *)&m_Mc);
        if(FAILED(hres))
        {
            pUnk->Release();
            m_Fg->Release(); m_Fg = NULL;
            m_Wc->Release(); m_Wc = NULL;
            m_Gb->Release(); m_Gb = NULL;
            return hres;
        }

        //
        // Not being able to get the IMediaEvent interface doesn't
        // necessarly mean that we can't play the graph.
        //
        pUnk->QueryInterface(IID_IMediaEvent, (LPVOID *)&m_Me);
        GetMovieEventHandle();

        pUnk->QueryInterface(IID_IMediaSeeking, (LPVOID *)&m_Ms);
        pUnk->Release();
        return S_OK;
    }
    else
    {
        m_Fg = NULL;
    }

    return hres;
}
Beispiel #19
0
int wmi_initialize() {

	// Initialize default value
	locator = NULL;
	services = NULL;
	//enumerator = NULL;

	// Initialize COM

	HRESULT result = CoInitializeEx(0, COINIT_MULTITHREADED);
	
	if (FAILED(result)) {
        log_err("Failed to initialize COM library. Error code = %x", result);
        return -1;
    }

	// Set general COM security levels

	result = CoInitializeSecurity(
        NULL, 
        -1,                          // COM authentication
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        NULL                         // Reserved
    );

	if (FAILED(result)) {
       log_err("Failed to initialize security. Error code = %x", result);
        CoUninitialize();
        return -1;
    }

	// Obtain the initial locator to WMI

	result = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &locator);
 
    if (FAILED(result)) {
       log_err("Failed to create IWbemLocator object. Error code = %x", result);
        CoUninitialize();
        return -1;                 // Program has failed.
    }

	// Connect to WMI through the IWbemLocator::ConnectServer method

	// Connect to the root\cimv2 namespace with
    // the current user and obtain pointer 'services'
    // to make IWbemServices calls.

	result = locator->ConnectServer(
         _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (for example, Kerberos)
         0,                       // Context object 
         &services                // pointer to IWbemServices proxy
    );

	if (FAILED(result)) {
        log_err("Could not connect. Error code = %x", result);
        locator->Release();     
        CoUninitialize();
        return -1;
    }

	//std::cout << "Connected to ROOT\\CIMV2 WMI namespace" << std::endl;

	// Set security levels on the proxy

	result = CoSetProxyBlanket(
       services,                        // Indicates the proxy to set
       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // client identity
       EOAC_NONE                    // proxy capabilities 
    );

	if (FAILED(result)) {
        log_err("Could not set proxy blanket. Error code = %x", result);
        services->Release();
        locator->Release();     
        CoUninitialize();
        return -1;
    }

	get_initial_values();

	_initialized = 1;
	return 0;
}
Beispiel #20
0
INT WINAPI wWinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ PWSTR lpCmdLine,
    _In_ INT nCmdShow
    )
{
    PROPSHEETPAGE propSheetPage = { sizeof(PROPSHEETPAGE) };
    PROPSHEETHEADER propSheetHeader = { sizeof(PROPSHEETHEADER) };
    HPROPSHEETPAGE pages[5];

    if (!NT_SUCCESS(PhInitializePhLibEx(0, 0, 0)))
        return 1;

    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

    PhApplicationName = L"Process Hacker - Setup";
    PhGuiSupportInitialization();
    PvpInitializeDpi();

    propSheetHeader.dwFlags =
        PSH_NOAPPLYNOW |
        PSH_NOCONTEXTHELP |
        PSH_USECALLBACK |
        PSH_WIZARD_LITE;
    propSheetHeader.hInstance = PhLibImageBase;
    propSheetHeader.pszIcon = MAKEINTRESOURCE(IDI_ICON1);
    propSheetHeader.pfnCallback = MainPropSheet_Callback;
    propSheetHeader.phpage = pages;

    // page
    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
    propSheetPage.dwFlags = PSP_USETITLE;
    propSheetPage.pszTitle = PhApplicationName;
    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG1);
    propSheetPage.pfnDlgProc = PropSheetPage1_WndProc;
    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);

    // page
    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
    propSheetPage.dwFlags = PSP_USETITLE;
    propSheetPage.pszTitle = PhApplicationName;
    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG2);
    propSheetPage.pfnDlgProc = PropSheetPage2_WndProc;
    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);

    // page
    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG3);
    propSheetPage.pfnDlgProc = PropSheetPage3_WndProc;
    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);

    // page
    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
    propSheetPage.dwFlags = PSP_USETITLE;
    propSheetPage.pszTitle = PhApplicationName;
    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG4);
    propSheetPage.pfnDlgProc = PropSheetPage4_WndProc;
    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);

    // page
    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
    propSheetPage.dwFlags = PSP_USETITLE;
    propSheetPage.pszTitle = PhApplicationName;
    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG5);
    propSheetPage.pfnDlgProc = PropSheetPage5_WndProc;
    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);

    PhModalPropertySheet(&propSheetHeader);

    return EXIT_SUCCESS;
}
static void EnterMTA(void)
{
    HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (unlikely(FAILED(hr)))
        abort();
}
Beispiel #22
0
/*! 
  \brief Opens the wan (dialup, vpn...) adapter.
  \return If the function succeeds, the return value is the pointer to a properly initialized WAN_ADAPTER structure,
   otherwise the return value is NULL.
*/
PWAN_ADAPTER WanPacketOpenAdapter()
{
	PWAN_ADAPTER pWanAdapter = NULL;
	PBLOB_TABLE pBlobTable = NULL;
	HBLOB hFilterBlob = NULL;
	HRESULT hResult;
	DWORD i;

	if ( g_hModule == NULL)
	{
		g_hModule = LoadLibrary("npp\\ndisnpp.dll");
	}

	if ( g_hModule == NULL)
	{
		return NULL;
	}

	hResult = CoInitialize(NULL);

	//
 	// if  the calling thread has already initialized COM with a 
 	// different threading model, we have this error
 	// however, we are able to support another threading model,
 	// so we try to initialize COM with another threading model.
 	// This new call should succeed with S_FALSE.
 	//
 	if (hResult == RPC_E_CHANGED_MODE)
	{
		hResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
	
		//MULTITHREADED threading is only supported on Windows 2000
		if (hResult == RPC_E_CHANGED_MODE && IsWindows2000())
		{
			hResult = CoInitializeEx(NULL, COINIT_MULTITHREADED);
		}
	}

	if (hResult != S_OK && hResult != S_FALSE)
		return NULL;

	pWanAdapter = (PWAN_ADAPTER)GlobalAlloc(GPTR, sizeof (WAN_ADAPTER));

	if ( pWanAdapter == NULL )
		goto error;
	
	memset(pWanAdapter, 0, sizeof(WAN_ADAPTER));
	
	if ( CreateBlob(&hFilterBlob) != NMERR_SUCCESS )
	{
		goto error;
	}
	
	if ( SetBoolInBlob(hFilterBlob, OWNER_NPP, CATEGORY_CONFIG, TAG_INTERFACE_REALTIME_CAPTURE, TRUE) != NMERR_SUCCESS )
	{
		DestroyBlob( hFilterBlob);
		goto error;
	}

	if ( SetBoolInBlob(hFilterBlob, OWNER_NPP, CATEGORY_LOCATION, TAG_RAS, TRUE) != NMERR_SUCCESS )
	{
		DestroyBlob( hFilterBlob);
		goto error;
	}

	if ( GetNPPBlobTable(hFilterBlob, &pBlobTable) != NMERR_SUCCESS )
	{
		DestroyBlob( hFilterBlob);
		goto error;
	}

	DestroyBlob (hFilterBlob);

	if ( pBlobTable->dwNumBlobs == 0 || pBlobTable->dwNumBlobs > 1)
	{
		///fixme.....
		for ( i = 0 ; i < pBlobTable->dwNumBlobs ; i++ )
			DestroyBlob(pBlobTable->hBlobs[i]);
		
		GlobalFree(pBlobTable);
		goto error;
	}

	pWanAdapter->hCaptureBlob = pBlobTable->hBlobs[0];

	GlobalFree(pBlobTable);

	InitializeCriticalSection(&pWanAdapter->CriticalSection);

	pWanAdapter->hReadEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	if ( pWanAdapter->hReadEvent == NULL )
		goto error;

	pWanAdapter->MemEx.buffer = (PUCHAR)GlobalAlloc(GPTR, DEFAULT_MEM_EX_SIZE);
	if (pWanAdapter->MemEx.buffer == NULL)
		goto error;
	
	pWanAdapter->MemEx.size = DEFAULT_MEM_EX_SIZE;
	pWanAdapter->Tme.active = TME_NONE_ACTIVE;

	if (CreateNPPInterface(pWanAdapter->hCaptureBlob, IID_IRTC, (void**) &pWanAdapter->pIRTC) == NMERR_SUCCESS && pWanAdapter->pIRTC != NULL) 
	{
		//create OK
		if (pWanAdapter->pIRTC->Connect(pWanAdapter->hCaptureBlob, NULL, WanPacketReceiverCallback, (LPVOID)pWanAdapter , NULL) == NMERR_SUCCESS)
		{
			//connect OK
			if (pWanAdapter->pIRTC->Start() == NMERR_SUCCESS)
			{
				return pWanAdapter;
			}
			else
			{
				pWanAdapter->pIRTC->Disconnect();
				pWanAdapter->pIRTC->Release();
				goto error;
			}
		}
		else
		{
			pWanAdapter->pIRTC->Release();
			goto error;
		}
	}
	else
	{
		goto error;
	}

	//awfully never reached
//	return NULL;

error:

	if (pWanAdapter != NULL)
	{
		if (pWanAdapter->hReadEvent != NULL)
			CloseHandle(pWanAdapter->hReadEvent);

		DeleteCriticalSection(&pWanAdapter->CriticalSection);
		if (pWanAdapter->hCaptureBlob)
			DestroyBlob(pWanAdapter->hCaptureBlob);

		GlobalFree(pWanAdapter);
	}

	CoUninitialize();
	
	return NULL;
}
Beispiel #23
0
JNIEXPORT void JNICALL Java_com_jacob2_com_ComThread_doCoInitialize
  (JNIEnv *env, jclass cls, jint mode)
{
  int threadModel = mode;
  CoInitializeEx(NULL, threadModel);
}
INT WINAPI wWinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ PWSTR lpCmdLine,
    _In_ INT nCmdShow
)
{
    LONG result;
#ifdef DEBUG
    PHP_BASE_THREAD_DBG dbg;
#endif

    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
#ifndef DEBUG
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif

    PhInstanceHandle = (HINSTANCE)NtCurrentPeb()->ImageBaseAddress;

    if (!NT_SUCCESS(PhInitializePhLib()))
        return 1;
    if (!PhInitializeAppSystem())
        return 1;

    PhInitializeCommonControls();

    if (PhCurrentTokenQueryHandle)
    {
        PTOKEN_USER tokenUser;

        if (NT_SUCCESS(PhGetTokenUser(PhCurrentTokenQueryHandle, &tokenUser)))
        {
            PhCurrentUserName = PhGetSidFullName(tokenUser->User.Sid, TRUE, NULL);
            PhFree(tokenUser);
        }
    }

    PhLocalSystemName = PhGetSidFullName(&PhSeLocalSystemSid, TRUE, NULL);

    // There has been a report of the above call failing.
    if (!PhLocalSystemName)
        PhLocalSystemName = PhCreateString(L"NT AUTHORITY\\SYSTEM");

    PhApplicationFileName = PhGetApplicationFileName();
    PhApplicationDirectory = PhGetApplicationDirectory();

    // Just in case
    if (!PhApplicationFileName)
        PhApplicationFileName = PhCreateString(L"ProcessHacker.exe");
    if (!PhApplicationDirectory)
        PhApplicationDirectory = PhReferenceEmptyString();

    PhpProcessStartupParameters();
    PhSettingsInitialization();
    PhpEnablePrivileges();

    if (PhStartupParameters.RunAsServiceMode)
    {
        RtlExitUserProcess(PhRunAsServiceStart(PhStartupParameters.RunAsServiceMode));
    }

    PhpInitializeSettings();

    // Activate a previous instance if required.
    if (PhGetIntegerSetting(L"AllowOnlyOneInstance") &&
            !PhStartupParameters.NewInstance &&
            !PhStartupParameters.ShowOptions &&
            !PhStartupParameters.CommandMode &&
            !PhStartupParameters.PhSvc)
    {
        PhActivatePreviousInstance();
    }

    if (PhGetIntegerSetting(L"EnableKph") && !PhStartupParameters.NoKph && !PhIsExecutingInWow64())
        PhInitializeKph();

    if (PhStartupParameters.CommandMode && PhStartupParameters.CommandType && PhStartupParameters.CommandAction)
    {
        NTSTATUS status;

        status = PhCommandModeStart();

        if (!NT_SUCCESS(status) && !PhStartupParameters.Silent)
        {
            PhShowStatus(NULL, L"Unable to execute the command", status, 0);
        }

        RtlExitUserProcess(status);
    }

#ifdef DEBUG
    dbg.ClientId = NtCurrentTeb()->ClientId;
    dbg.StartAddress = wWinMain;
    dbg.Parameter = NULL;
    InsertTailList(&PhDbgThreadListHead, &dbg.ListEntry);
    TlsSetValue(PhDbgThreadDbgTlsIndex, &dbg);
#endif

    PhInitializeAutoPool(&BaseAutoPool);

    PhEmInitialization();
    PhGuiSupportInitialization();
    PhTreeNewInitialization();
    PhGraphControlInitialization();
    PhHexEditInitialization();
    PhColorBoxInitialization();

    PhSmallIconSize.X = GetSystemMetrics(SM_CXSMICON);
    PhSmallIconSize.Y = GetSystemMetrics(SM_CYSMICON);
    PhLargeIconSize.X = GetSystemMetrics(SM_CXICON);
    PhLargeIconSize.Y = GetSystemMetrics(SM_CYICON);

    if (PhStartupParameters.ShowOptions)
    {
        // Elevated options dialog for changing the value of Replace Task Manager with Process Hacker.
        PhShowOptionsDialog(PhStartupParameters.WindowHandle);
        RtlExitUserProcess(STATUS_SUCCESS);
    }

#ifndef DEBUG
    if (PhIsExecutingInWow64() && !PhStartupParameters.PhSvc)
    {
        PhShowWarning(
            NULL,
            L"You are attempting to run the 32-bit version of Process Hacker on 64-bit Windows. "
            L"Most features will not work correctly.\n\n"
            L"Please run the 64-bit version of Process Hacker instead."
        );
    }
#endif

    PhPluginsEnabled = PhGetIntegerSetting(L"EnablePlugins") && !PhStartupParameters.NoPlugins;

    if (PhPluginsEnabled)
    {
        PhPluginsInitialization();
        PhLoadPlugins();
    }

    if (PhStartupParameters.PhSvc)
    {
        MSG message;

        // Turn the feedback cursor off.
        PostMessage(NULL, WM_NULL, 0, 0);
        GetMessage(&message, NULL, 0, 0);

        RtlExitUserProcess(PhSvcMain(NULL, NULL, NULL));
    }

    // Create a mutant for the installer.
    {
        HANDLE mutantHandle;
        OBJECT_ATTRIBUTES oa;
        UNICODE_STRING mutantName;

        RtlInitUnicodeString(&mutantName, L"\\BaseNamedObjects\\ProcessHacker2Mutant");
        InitializeObjectAttributes(
            &oa,
            &mutantName,
            0,
            NULL,
            NULL
        );

        NtCreateMutant(&mutantHandle, MUTANT_ALL_ACCESS, &oa, FALSE);
    }

    // Set priority.
    {
        PROCESS_PRIORITY_CLASS priorityClass;

        priorityClass.Foreground = FALSE;
        priorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_HIGH;

        if (PhStartupParameters.PriorityClass != 0)
            priorityClass.PriorityClass = (UCHAR)PhStartupParameters.PriorityClass;

        NtSetInformationProcess(NtCurrentProcess(), ProcessPriorityClass, &priorityClass, sizeof(PROCESS_PRIORITY_CLASS));
    }

    if (!PhMainWndInitialization(nCmdShow))
    {
        PhShowError(NULL, L"Unable to initialize the main window.");
        return 1;
    }

    PhDrainAutoPool(&BaseAutoPool);

    result = PhMainMessageLoop();
    RtlExitUserProcess(result);
}
int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hInstP, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg={0};
    WNDCLASS wc;

    // Initialize COM
    if(FAILED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)))
    {
        Msg(TEXT("CoInitialize Failed!\r\n"));   
        exit(1);
    } 

    // Register the window class
    ZeroMemory(&wc, sizeof wc);
    wc.lpfnWndProc   = WndMainProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASSNAME;
    wc.lpszMenuName  = NULL;
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hIcon         = NULL;
    if(!RegisterClass(&wc))
    {
        Msg(TEXT("RegisterClass Failed! Error=0x%x\r\n"), GetLastError());
        CoUninitialize();
        exit(1);
    }

    // Create the main window.  The WS_CLIPCHILDREN style is required.
    ghApp = CreateWindow(CLASSNAME, APPLICATIONNAME,
                         WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_CLIPCHILDREN,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         DEFAULT_VIDEO_WIDTH, DEFAULT_VIDEO_HEIGHT,
                         0, 0, hInstance, 0);

    if(ghApp)
    {
        HRESULT hr;

        // Create DirectShow graph and start capturing video
        hr = CaptureVideo();
        if (FAILED (hr))
        {
            CloseInterfaces();
            DestroyWindow(ghApp);
        }
        else
        {
            // Don't display the main window until the DirectShow
            // preview graph has been created.  Once video data is
            // being received and processed, the window will appear
            // and immediately have useful video data to display.
            // Otherwise, it will be black until video data arrives.
            ShowWindow(ghApp, nCmdShow);
        }       

        // Main message loop
        while(GetMessage(&msg,NULL,0,0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    // Release COM
    CoUninitialize();

    return (int) msg.wParam;
}
Beispiel #26
0
HRESULT SetupForIsXInputDevice()
{
	IWbemLocator *pIWbemLocator = NULL;
	IEnumWbemClassObject *pEnumDevices = NULL;
	IWbemClassObject *pDevices[20] = {0};
	IWbemServices *pIWbemServices = NULL;
	BSTR bstrNamespace = NULL;
	BSTR bstrDeviceID = NULL;
	BSTR bstrClassName = NULL;
	DWORD uReturned = 0;
	BOOL bIsXinputDevice = FALSE;
	UINT iDevice = 0;
	VARIANT var;
	HRESULT hr;

	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	bCleanupCOM = SUCCEEDED(hr);
	
	// Create WMI
	hr = CoCreateInstance( &CLSID_WbemContext,
		NULL,
		CLSCTX_INPROC_SERVER,
		&IID_IWbemContext,
		(LPVOID*) &pIWbemLocator);
	if( FAILED(hr) || pIWbemLocator == NULL )
		goto bail;

	bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto bail;
	bstrClassName = SysAllocString( L"Win32_PNPEntity" );   if( bstrClassName == NULL ) goto bail;
	bstrDeviceID  = SysAllocString( L"DeviceID" );          if( bstrDeviceID == NULL )  goto bail;

	// Connect to WMI 	
	hr = IWbemLocator_ConnectServer(pIWbemLocator, bstrNamespace, NULL, NULL, NULL, 
		0L, NULL, NULL, &pIWbemServices );

	if( FAILED(hr) || pIWbemServices == NULL )
		goto bail;

	// Switch security level to IMPERSONATE
	CoSetProxyBlanket( (IUnknown *)pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
		RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );                    

	hr = IWbemServices_CreateInstanceEnum( pIWbemServices, bstrClassName, 0, NULL, &pEnumDevices ); 
	if( FAILED(hr) || pEnumDevices == NULL )
		goto bail;

	// Loop over all devices
	for(;;)
	{
		// Get 20 at a time		
		hr = IEnumWbemClassObject_Next( pEnumDevices, 10000, 20, pDevices, &uReturned );
		if( FAILED(hr) || 
			uReturned == 0 )
			break;

		for( iDevice=0; iDevice<uReturned; iDevice++ )
		{
			// For each device, get its device ID
			hr = IWbemClassObject_Get( pDevices[iDevice], bstrDeviceID, 0L, &var, NULL, NULL );
			if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )
			{
				// Check if the device ID contains "IG_".  If it does, then it's an XInput device
				// This information can not be found from DirectInput 
				if( wcsstr( var.bstrVal, L"IG_" ) )
				{
					// If it does, then get the VID/PID from var.bstrVal
					DWORD dwPid = 0, dwVid = 0;
					WCHAR* strVid;
					WCHAR* strPid;
					DWORD dwVidPid;
					XINPUT_DEVICE_NODE* pNewNode;

					strVid = wcsstr( var.bstrVal, L"VID_" );
					if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
						dwVid = 0;
					strPid = wcsstr( var.bstrVal, L"PID_" );
					if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
						dwPid = 0;

					dwVidPid = MAKELONG( dwVid, dwPid );

					// Add the VID/PID to a linked list
					pNewNode = malloc(sizeof(XINPUT_DEVICE_NODE));
					if( pNewNode )
					{
						pNewNode->dwVidPid = dwVidPid;
						pNewNode->pNext = (struct XINPUT_DEVICE_NODE *)g_pXInputDeviceList;
						g_pXInputDeviceList = pNewNode;
					}
				}
			}
			SAFE_RELEASE( pDevices[iDevice] );
		}
	}

bail:
	if(bstrNamespace)
		SysFreeString(bstrNamespace);
	if(bstrDeviceID)
		SysFreeString(bstrDeviceID);
	if(bstrClassName)
		SysFreeString(bstrClassName);
	for( iDevice=0; iDevice<20; iDevice++ )
		SAFE_RELEASE( pDevices[iDevice] );
	SAFE_RELEASE( pEnumDevices );
	SAFE_RELEASE( pIWbemLocator );
	SAFE_RELEASE( pIWbemServices );

	return hr;
}
//
// Main entry point of the sample
//
int wmain()
{
    wprintf(L"Copyright (c) Microsoft Corporation.  All rights reserved.\n");
    wprintf(L"CreateBundle sample\n\n");

    HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

    if (SUCCEEDED(hr))
    {
        // Create a bundle writer object
        IAppxBundleWriter* bundleWriter = NULL;

        wprintf(L"\nCreating bundle writer\n\n");

        hr = GetBundleWriter(OutputBundlePath, &bundleWriter);

        // Add all payload packages to the package writer
        for (int i = 0; SUCCEEDED(hr) && (i < PayloadPackagesCount); i++)
        {
            IStream* payloadPackageStream = NULL;

            wprintf(L"Adding payload package: %s\n", PayloadPackagesName[i]);

            hr = GetFileStream(DataPath, PayloadPackagesName[i], &payloadPackageStream);

            if (SUCCEEDED(hr))
            {
                bundleWriter->AddPayloadPackage(
                    PayloadPackagesName[i],
                    payloadPackageStream);
            }

            if (payloadPackageStream != NULL)
            {
                payloadPackageStream->Release();
                payloadPackageStream = NULL;
            }
        }

        // Close the bundle writer to flush the output stream
        if (SUCCEEDED(hr))
        {
            hr = bundleWriter->Close();
        }

        // Clean up allocated resources
        if (bundleWriter != NULL)
        {
            bundleWriter->Release();
            bundleWriter = NULL;
        }
        CoUninitialize();
    }

    if (SUCCEEDED(hr))
    {
        wprintf(L"\nBundle successfully saved to %s.\n", OutputBundlePath);
    }
    else
    {
        wprintf(L"\nBundle creation failed with HRESULT 0x%08X.\n", hr);
    }
    return SUCCEEDED(hr) ? 0 : 1;
}
Beispiel #28
0
PWMIUT InitWMI(PGLOBAL g, char *nsp, char *classname)
{
  IWbemLocator *loc;
  char         *p;
  HRESULT       res;
  PWMIUT        wp = (PWMIUT)PlugSubAlloc(g, NULL, sizeof(WMIUTIL));

  if (trace)
    htrc("WMIColumns class %s space %s\n", SVP(classname), SVP(nsp));

  /*********************************************************************/
  /*  Set default values for the namespace and class name.             */
  /*********************************************************************/
  if (!nsp)
    nsp = "root\\cimv2";

  if (!classname) {
    if (!stricmp(nsp, "root\\cimv2"))
      classname = "ComputerSystemProduct";
    else if (!stricmp(nsp, "root\\cli"))
      classname = "Msft_CliAlias";
    else {
      strcpy(g->Message, "Missing class name");
      return NULL;
      } // endif classname

    } // endif classname

  /*********************************************************************/
  /*  Initialize WMI.                                                  */
  /*********************************************************************/
//res = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

  if (FAILED(res)) {
    sprintf(g->Message, "Failed to initialize COM library. " 
            "Error code = %p", res);
    return NULL;
    } // endif res

#if 0 // irrelevant for a DLL
  res = CoInitializeSecurity(NULL, -1, NULL, NULL,
                       RPC_C_AUTHN_LEVEL_CONNECT,
                       RPC_C_IMP_LEVEL_IMPERSONATE,
                       NULL, EOAC_NONE, NULL);
  
  if (res != RPC_E_TOO_LATE && FAILED(res)) {
    sprintf(g->Message, "Failed to initialize security. " 
            "Error code = %p", res);
    CoUninitialize();
    return NULL;
    }  // endif Res
#endif // 0

  res = CoCreateInstance(CLSID_WbemLocator, NULL, 
                         CLSCTX_INPROC_SERVER, IID_IWbemLocator, 
                         (void**) &loc);
  if (FAILED(res)) {
    sprintf(g->Message, "Failed to create Locator. " 
            "Error code = %p", res);
    CoUninitialize();
    return NULL;
    }  // endif res
    
  res = loc->ConnectServer(_bstr_t(nsp), 
                    NULL, NULL, NULL, 0, NULL, NULL, &wp->Svc);

  if (FAILED(res)) {
    sprintf(g->Message, "Could not connect. Error code = %p", res); 
    loc->Release();     
    CoUninitialize();
    return NULL;
    }  // endif res

  loc->Release();

  if (trace)
    htrc("Successfully connected to namespace.\n");

  /*********************************************************************/
  /*  Perform a full class object retrieval.                           */
  /*********************************************************************/
  p = (char*)PlugSubAlloc(g, NULL, strlen(classname) + 7);

  if (strchr(classname, '_'))
    strcpy(p, classname);
  else
    strcat(strcpy(p, "Win32_"), classname);

  res = wp->Svc->GetObject(bstr_t(p), 0, 0, &wp->Cobj, 0);

  if (FAILED(res)) {
    sprintf(g->Message, "failed GetObject %s in %s\n", classname, nsp);
    wp->Svc->Release();
    wp->Svc = NULL;    // MUST be set to NULL  (why?)
    return NULL;
    }  // endif res

  return wp;
} // end of InitWMI
Beispiel #29
0
		}
	}
	return FALSE;
}

/**
 * Initialise the WMI client that will connect to the local machine WMI
 * namespace. It will return TRUE if the connection was successful, FALSE
 * otherwise.
 */
int wmi_initialize(const wchar_t *query_namespace, IWbemServices **services) {
	BSTR namespace;
	IWbemLocator *locator = NULL;
	int result;

	HRESULT hresult = CoInitializeEx(0, COINIT_MULTITHREADED);

	if (FAILED(hresult)) {
		return FALSE;
	}

	hresult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
		RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);

	if (FAILED(hresult)) {
		CoUninitialize();

		return FALSE;
	}

	hresult = CoCreateInstance(&CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
Beispiel #30
-1
/*
 * Background thread to check for updates
 */
static DWORD WINAPI CheckForUpdatesThread(LPVOID param)
{
	BOOL releases_only, found_new_version = FALSE;
	int status = 0;
	const char* server_url = RUFUS_URL "/";
	int i, j, k, verbose = 0, verpos[4];
	static const char* archname[] = {"win_x86", "win_x64"};
	static const char* channel[] = {"release", "beta"};		// release channel
	const char* accept_types[] = {"*/*\0", NULL};
	DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus;
	char* buf = NULL;
	char agent[64], hostname[64], urlpath[128], mime[32];
	OSVERSIONINFOA os_version = {sizeof(OSVERSIONINFOA), 0, 0, 0, 0, ""};
	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;
	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,
		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};
	SYSTEMTIME ServerTime, LocalTime;
	FILETIME FileTime;
	int64_t local_time = 0, reg_time, server_time, update_interval;

	update_check_in_progress = TRUE;
	verbose = ReadRegistryKey32(REGKEY_HKCU, REGKEY_VERBOSE_UPDATES);
	// Without this the FileDialog will produce error 0x8001010E when compiled for Vista or later
	IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));
	// Unless the update was forced, wait a while before performing the update check
	if (!force_update_check) {
		// It would of course be a lot nicer to use a timer and wake the thread, but my
		// development time is limited and this is FASTER to implement.
		do {
			for (i=0; (i<30) && (!force_update_check); i++)
				Sleep(500);
		} while ((!force_update_check) && ((iso_op_in_progress || format_op_in_progress || (dialog_showing>0))));
		if (!force_update_check) {
			if ((ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL) == -1)) {
				vuprintf("Check for updates disabled, as per registry settings.\n");
				goto out;
			}
			reg_time = ReadRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE);
			update_interval = (int64_t)ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL);
			if (update_interval == 0) {
				WriteRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL);
				update_interval = DEFAULT_UPDATE_INTERVAL;
			}
			GetSystemTime(&LocalTime);
			if (!SystemTimeToFileTime(&LocalTime, &FileTime))
				goto out;
			local_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;
			vvuprintf("Local time: %" PRId64 "\n", local_time);
			if (local_time < reg_time + update_interval) {
				vuprintf("Next update check in %" PRId64 " seconds.\n", reg_time + update_interval - local_time);
				goto out;
			}
		}
	}

	PrintStatus(3000, TRUE, MSG_243);
	status++;	// 1

	if (!GetVersionExA(&os_version)) {
		uprintf("Could not read Windows version - Check for updates cancelled.\n");
		goto out;
	}

	if ((!InternetCrackUrlA(server_url, (DWORD)safe_strlen(server_url), 0, &UrlParts)) || (!InternetGetConnectedState(&dwFlags, 0)))
		goto out;
	hostname[sizeof(hostname)-1] = 0;

	safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]);
	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hSession == NULL)
		goto out;
	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);
	if (hConnection == NULL)
		goto out;

	status++;	// 2
	releases_only = !GetRegistryKeyBool(REGKEY_HKCU, REGKEY_INCLUDE_BETAS);

	for (k=0; (k<(releases_only?1:(int)ARRAYSIZE(channel))) && (!found_new_version); k++) {
		uprintf("Checking %s channel...\n", channel[k]);
		// At this stage we can query the server for various update version files.
		// We first try to lookup for "<appname>_<os_arch>_<os_version_major>_<os_version_minor>.ver"
		// and then remove each each of the <os_> components until we find our match. For instance, we may first
		// look for rufus_win_x64_6.2.ver (Win8 x64) but only get a match for rufus_win_x64_6.ver (Vista x64 or later)
		// This allows sunsetting OS versions (eg XP) or providing different downloads for different archs/groups.
		safe_sprintf(urlpath, sizeof(urlpath), "%s%s%s_%s_%d.%d.ver", APPLICATION_NAME, (k==0)?"":"_",
			(k==0)?"":channel[k], archname[is_x64()?1:0], os_version.dwMajorVersion, os_version.dwMinorVersion);
		vuprintf("Base update check: %s\n", urlpath);
		for (i=0, j=(int)safe_strlen(urlpath)-5; (j>0)&&(i<ARRAYSIZE(verpos)); j--) {
			if ((urlpath[j] == '.') || (urlpath[j] == '_')) {
				verpos[i++] = j;
			}
		}
		if (i != ARRAYSIZE(verpos)) {
			uprintf("Broken code in CheckForUpdatesThread()!\n");
			goto out;
		}

		UrlParts.lpszUrlPath = urlpath;
		UrlParts.dwUrlPathLength = sizeof(urlpath);
		for (i=0; i<ARRAYSIZE(verpos); i++) {
			vvuprintf("Trying %s\n", UrlParts.lpszUrlPath);
			hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types,
				INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES|
				INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL);
			if ((hRequest == NULL) || (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)))
				goto out;

			// Ensure that we get a text file
			dwSize = sizeof(dwStatus);
			dwStatus = 404;
			HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL);
			if (dwStatus == 200) 
				break;
			InternetCloseHandle(hRequest);
			hRequest = NULL;
			safe_strcpy(&urlpath[verpos[i]], 5, ".ver");
		}
		if (dwStatus != 200) {
			vuprintf("Could not find a %s version file on server %s", channel[k], server_url);
			if ((releases_only) || (k+1 >= ARRAYSIZE(channel)))
				goto out;
			continue;
		}
		vuprintf("Found match for %s on server %s", urlpath, server_url);

		dwSize = sizeof(mime);
		HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_TYPE, (LPVOID)&mime, &dwSize, NULL);
		if (strcmp(mime, "text/plain") != 0)
			goto out;

		// We also get a date from Apache, which we'll use to avoid out of sync check,
		// in case some set their clock way into the future and back.
		// On the other hand, if local clock is set way back in the past, we will never check.
		dwSize = sizeof(ServerTime);
		// If we can't get a date we can trust, don't bother...
		if ( (!HttpQueryInfoA(hRequest, HTTP_QUERY_DATE|HTTP_QUERY_FLAG_SYSTEMTIME, (LPVOID)&ServerTime, &dwSize, NULL))
			|| (!SystemTimeToFileTime(&ServerTime, &FileTime)) )
			goto out;
		server_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;
		vvuprintf("Server time: %" PRId64 "\n", server_time);
		// Always store the server response time - the only clock we trust!
		WriteRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE, server_time);
		// Might as well let the user know
		if (!force_update_check) {
			if ((local_time > server_time + 600) || (local_time < server_time - 600)) {
				uprintf("IMPORTANT: Your local clock is more than 10 minutes in the %s. Unless you fix this, " APPLICATION_NAME " may not be able to check for updates...", 
					(local_time > server_time + 600)?"future":"past");
			}
		}

		dwSize = sizeof(dwTotalSize);
		if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL))
			goto out;

		safe_free(buf);
		// Make sure the file is NUL terminated
		buf = (char*)calloc(dwTotalSize+1, 1);
		if (buf == NULL) goto out;
		// This is a version file - we should be able to gulp it down in one go
		if (!InternetReadFile(hRequest, buf, dwTotalSize, &dwDownloaded) || (dwDownloaded != dwTotalSize))
			goto out;

		status++;
		vuprintf("Successfully downloaded version file (%d bytes)\n", dwTotalSize);

		parse_update(buf, dwTotalSize+1);

		vuprintf("UPDATE DATA:\n");
		vuprintf("  version: %d.%d.%d.%d (%s)\n", update.version[0], update.version[1], 
			update.version[2], update.version[3], channel[k]);
		vuprintf("  platform_min: %d.%d\n", update.platform_min[0], update.platform_min[1]);
		vuprintf("  url: %s\n", update.download_url);

		found_new_version = ((to_uint64_t(update.version) > to_uint64_t(rufus_version)) || (force_update))
			&& ( (os_version.dwMajorVersion > update.platform_min[0])
			  || ( (os_version.dwMajorVersion == update.platform_min[0]) && (os_version.dwMinorVersion >= update.platform_min[1])) );
		uprintf("N%sew %s version found%c\n", found_new_version?"":"o n", channel[k], found_new_version?'!':'.');
	}

out:
	safe_free(buf);
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnection) InternetCloseHandle(hConnection);
	if (hSession) InternetCloseHandle(hSession);
	switch(status) {
	case 1:
		PrintStatus(3000, TRUE, MSG_244);
		break;
	case 2:
		PrintStatus(3000, TRUE, MSG_245);
		break;
	case 3:
	case 4:
		PrintStatus(3000, FALSE, found_new_version?MSG_246:MSG_247);
	default:
		break;
	}
	// Start the new download after cleanup
	if (found_new_version) {
		// User may have started an operation while we were checking
		while ((!force_update_check) && (iso_op_in_progress || format_op_in_progress || (dialog_showing>0))) {
			Sleep(15000);
		}
		DownloadNewVersion();
	}
	force_update_check = FALSE;
	update_check_in_progress = FALSE;
	ExitThread(0);
}