Exemplo n.º 1
0
unsigned long Process::runSync() const
{
	SHELLEXECUTEINFO ShExecInfo = { 0 };
	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb = TEXT("open");
	ShExecInfo.lpFile = _command.c_str();
	ShExecInfo.lpParameters = _args.c_str();
	ShExecInfo.lpDirectory = _curDir.c_str();
	ShExecInfo.nShow = SW_SHOWNORMAL;
	ShExecInfo.hInstApp = NULL;
	
	ShellExecuteEx(&ShExecInfo);
	WaitForSingleObject(ShExecInfo.hProcess, INFINITE);

	unsigned long exitCode;
	if (::GetExitCodeProcess(ShExecInfo.hProcess, &exitCode) == FALSE)
	{
		// throw exception
		throw GetLastErrorAsString(GetLastError());
	}

	return exitCode;
}
Exemplo n.º 2
0
IPlugin* PluginManager::LoadPlugin(std::string file)
{
	std::shared_ptr<PluginInfo> dll = std::make_shared<PluginInfo>();

	Log::Instance().Write("Loading " + StripFile(file));
	file += ".plug";

#if defined(_WIN32)
	dll->mod = LoadLibrary(file.c_str());
#else
	dll->mod = dlopen(file.c_str(),RTLD_NOW);
#endif

	if(dll->mod == nullptr)
	{
		std::string error;
#ifdef _WIN32
		error = GetLastErrorAsString();
#else
		error = dlerror();
#endif
		throw error;
	}

	CREATEPLUGIN pFunct = nullptr;

#ifdef _WIN32
	pFunct = (CREATEPLUGIN)GetProcAddress((HMODULE)(dll->mod),"CreatePlugin");
#else
	pFunct = (CREATEPLUGIN)dlsym(dll->mod,"CreatePlugin");
#endif

	if(pFunct == nullptr)
	{
		throw ("Corrupted Shared Library: "  + file);
	}

	// Create the plugin
	dll->pPlugin = pFunct();

	// Get the type of the plugin
	DLLType type = dll->pPlugin->GetPluginType();
	auto iter = m_plugins.find(type); // see if the plugin is already loaded

	// If it is already loaded
	if(iter != m_plugins.end())
	{
		// replace with new
		iter->second = dll;
	}
	else
	{
		// insert plugin into map
		m_plugins.insert({ type, dll });
	}

	// return the plugin interface
	return dll->pPlugin;
}
Exemplo n.º 3
0
const char* CCONV _RA_InstallIntegration()
{
	SetErrorMode( 0 );
	
#ifdef _DEBUG
	g_hRADLL = LoadLibraryEx( TEXT( "RA_Integration_d.dll" ), nullptr, 0 );
#else
	g_hRADLL = LoadLibrary( TEXT( "RA_Integration.dll" ) );
#endif
	if( g_hRADLL == NULL )
	{
		char buffer[ 1024 ];
		sprintf_s( buffer, 1024, "LoadLibrary failed: %d : %s\n", ::GetLastError(), GetLastErrorAsString().c_str() );

#ifdef UNICODE
		MessageBox( nullptr, Widen( buffer ).c_str(), _T( "Sorry!" ), MB_OK );
#else
		MessageBox( nullptr, buffer, _T( "Sorry!" ), MB_OK );
#endif

		return "0.000";
	}

	//	Install function pointers one by one
 
	_RA_IntegrationVersion	= (const char*(CCONV *)())								GetProcAddress( g_hRADLL, "_RA_IntegrationVersion" );
	_RA_InitI				= (int(CCONV *)(HWND, int, const char*))				GetProcAddress( g_hRADLL, "_RA_InitI" );
	_RA_Shutdown			= (int(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_Shutdown" );
	_RA_UserLoggedIn		= (bool(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_UserLoggedIn" );
	_RA_Username			= (const char*(CCONV *)())								GetProcAddress( g_hRADLL, "_RA_Username" );
	_RA_AttemptLogin		= (void(CCONV *)(bool))									GetProcAddress( g_hRADLL, "_RA_AttemptLogin" );
	_RA_UpdateOverlay		= (int(CCONV *)(ControllerInput*, float, bool, bool))	GetProcAddress( g_hRADLL, "_RA_UpdateOverlay" );
	_RA_UpdatePopups		= (int(CCONV *)(ControllerInput*, float, bool, bool))	GetProcAddress( g_hRADLL, "_RA_UpdatePopups" );
	_RA_RenderOverlay		= (void(CCONV *)(HDC, RECT*))							GetProcAddress( g_hRADLL, "_RA_RenderOverlay" );
	_RA_RenderPopups		= (void(CCONV *)(HDC, RECT*))							GetProcAddress( g_hRADLL, "_RA_RenderPopups" );
	_RA_OnLoadNewRom		= (int(CCONV *)(const BYTE*, unsigned int))				GetProcAddress( g_hRADLL, "_RA_OnLoadNewRom" );
	_RA_InstallMemoryBank	= (void(CCONV *)(int, void*, void*, int))				GetProcAddress( g_hRADLL, "_RA_InstallMemoryBank" );
	_RA_ClearMemoryBanks	= (void(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_ClearMemoryBanks" );
	_RA_UpdateAppTitle		= (void(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_UpdateAppTitle" );
	_RA_HandleHTTPResults	= (void(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_HandleHTTPResults" );
	_RA_ConfirmLoadNewRom	= (bool(CCONV *)(bool))									GetProcAddress( g_hRADLL, "_RA_ConfirmLoadNewRom" );
	_RA_CreatePopupMenu		= (HMENU(CCONV *)(void))								GetProcAddress( g_hRADLL, "_RA_CreatePopupMenu" );
	_RA_InitDirectX			= (void(CCONV *)(void))									GetProcAddress( g_hRADLL, "_RA_InitDirectX" );
	_RA_OnPaint				= (void(CCONV *)(HWND))									GetProcAddress( g_hRADLL, "_RA_OnPaint" );
	_RA_InvokeDialog		= (void(CCONV *)(LPARAM))								GetProcAddress( g_hRADLL, "_RA_InvokeDialog" );
	_RA_SetPaused			= (void(CCONV *)(bool))									GetProcAddress( g_hRADLL, "_RA_SetPaused" );
	_RA_OnLoadState			= (void(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_OnLoadState" );
	_RA_OnSaveState			= (void(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_OnSaveState" );
	_RA_DoAchievementsFrame = (void(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_DoAchievementsFrame" );
	_RA_SetConsoleID		= (int(CCONV *)(unsigned int))							GetProcAddress( g_hRADLL, "_RA_SetConsoleID" );
	_RA_HardcoreModeIsActive= (int(CCONV *)())										GetProcAddress( g_hRADLL, "_RA_HardcoreModeIsActive" );
	_RA_HTTPGetRequestExists= (int(CCONV *)(const char*))							GetProcAddress( g_hRADLL, "_RA_HTTPGetRequestExists" );

	_RA_InstallSharedFunctions = ( void(CCONV *)( bool(*)(), void(*)(), void(*)(), void(*)(char*), void(*)(), void(*)(const char*) ) ) GetProcAddress( g_hRADLL, "_RA_InstallSharedFunctions" );

	return _RA_IntegrationVersion ? _RA_IntegrationVersion() : "0.000";
}
Exemplo n.º 4
0
			HINSTANCE load_library(std::wstring library_path) {
				auto result = static_cast<HINSTANCE>(LoadLibraryW(library_path.c_str()));
				if (!result) {
					std::stringstream msg;
					auto error_info = GetLastErrorAsString( );
					msg << "Could not open library: error no: " << error_info.first << " with message: " << error_info.second;
					throw std::runtime_error( msg.str( ) );
				}
				return result;
			}
Exemplo n.º 5
0
int main()
{
	HMODULE DarkCoreHandle = LoadLibrary("DarkCore.dll");
	if (DarkCoreHandle == NULL){
		std::cout << "------ WARNING DARKCORE.DLL NOT LODED -----\n";
		std::cout << GetLastErrorAsString();
		std::cout << "------ WARNING DARKCORE.DLL NOT LODED -----\n";
	}
	std::cout << "------------- Loaded DarkTests ------------\n";
	SetPlayerName();
	ShowPlayernameLoop();
	return 0;
}
Exemplo n.º 6
0
int _tmain(int argc, _TCHAR* argv[])
{
    if (argc < 3) {
        printf("usage: DetourHook <cmd> <dll>\n");
        return 0;
    }

    LPTSTR cmdLine = argv[1];
    LPSTR dllPath = NULL;

#ifdef UNICODE
    DWORD num = WideCharToMultiByte(CP_OEMCP, NULL, argv[2], -1, NULL, 0, NULL, FALSE);
    dllPath = new CHAR[num];
    WideCharToMultiByte(CP_OEMCP, NULL, argv[2], -1, dllPath, num, NULL, FALSE);
#else
    dllPath = argv[2];
#endif

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    si.cb = sizeof(STARTUPINFO);

    DWORD flags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED;
    if (!DetourCreateProcessWithDll(NULL, cmdLine,
                                    NULL, NULL, FALSE, flags, NULL, NULL, &si, &pi,
                                    dllPath, NULL)) {
        LPSTR errMsg = GetLastErrorAsString();
        printf("failed to create process, error: %s", errMsg);
        LocalFree(errMsg);
    }

    ResumeThread(pi.hThread);
    WaitForSingleObject(pi.hProcess, INFINITE);
    
#ifdef UNICODE
    delete [] dllPath;
#endif

    return 0;
}
Exemplo n.º 7
0
			std::pair<DWORD, std::string> GetLastErrorAsString( ) {
				unsigned long err_no = ::GetLastError( );
				return std::make_pair( err_no, GetLastErrorAsString( err_no ) );
			}
Exemplo n.º 8
0
// Our main test program
int 
main(int argc,TCHAR* argv[], TCHAR* /*envp[]*/)
{
  int nRetCode = 0;

  HMODULE hModule = ::GetModuleHandle(NULL);
  InitializeCriticalSection(&std_stream);

  if(hModule == NULL)
  {
    _tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
    nRetCode = 1;
  }
  else
  {
    // initialize MFC and print and error on failure
    if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
    {
      _tprintf(_T("Fatal Error: MFC initialization failed\n"));
      nRetCode = 1;
    }
    else
    {
      printf("TESTPROGAM: MARLIN SERVER\n");
      printf("=========================\n");
      printf("\n");
      printf("Version string: %s\n",MARLIN_SERVER_VERSION);
      printf("----------------------------------\n");
      printf("\n");

      // See if we must do the standalone WebServiceServer test
      // Or that we should do the flat HTTPServer tests
      if(argc >= 2)
      {
        if(_stricmp(argv[1],"/ws") == 0)
        {
          CString contract = "http://interface.marlin.org/testing/";
          printf("WebServiceServer test for \"%s\"\n",contract.GetString());
          printf("----------------------------------------------------------------\n");
          printf("\n");

          // Test the Interface
          nRetCode = TestWebServiceServer(NULL,contract,logLevel);
        }
      }
      else
      {
        HTTPServer*   server  = nullptr;
        LogAnalysis*  logfile = nullptr;

        if(StartServer(server,logfile))
        {
          // Fire up all of our test sites
          int errors = 0;

          // Individual tests
          errors += Test_CrackURL();
          errors += Test_HTTPTime();
          errors += TestThreadPool(server->GetThreadPool());

          // HTTP tests
          errors += TestBaseSite(server);
          errors += TestSecureSite(server);
          errors += TestClientCertificate(server,true);
          errors += TestCookies(server);
          errors += TestFormData(server);
          errors += TestJsonData(server);
          errors += TestInsecure(server);
          errors += TestPushEvents(server);
          errors += TestBodySigning(server);
          errors += TestBodyEncryption(server);
          errors += TestMessageEncryption(server);
          errors += TestReliable(server);
          errors += TestReliableBA(server);
          errors += TestToken(server);
          errors += TestSubSites(server);
          errors += TestFilter(server);
          errors += TestPatch(server);
          errors += TestCompression(server);
          errors += TestAsynchrone(server);
          errors += TestWebSocket(server);

         // Test the WebServiceServer program generation
         CString contract = "http://interface.marlin.org/testing/";
         errors += TestJsonServer(server,contract,logLevel);
         errors += TestWebServiceServer(server,contract,logLevel);

          // See if we should wait for testing to occur
          if(errors)
          {
            printf("\n"
                   "SERVER (OR PROGRAMMING) IN ERROR STATE!!\n"
                   "%d sites not correctly started\n"
                   "\n",errors);
          }
          else
          {
            printf("\n"
                   "Server running....\n"
                   "Waiting to be called by test clients...\n"
                   "\n");
            // Wait for key to occur
            WaitForKey();
          }

          // Try to stop the WebSocket
//           errors += StopWebSocket();
// 
          // Try to stop the subsites
          errors += StopSubsites(server);

          // Testing the errorlog function
          server->ErrorLog(__FUNCTION__,5,"Not a real error message, but a test to see if it works :-)");

          printf("Stopping the server\n");
          server->StopServer();

          // See if the server is indeed in stopped state
          printf("The server is %s\n",server->GetIsRunning() ? "still running!\n" : "stopped.\n");

          // Remember for a cmd shell
          nRetCode = errors;
        }
        else
        {
          totalErrors = 1;
          printf("HTTPServer in error state in : Error %lu: %s\n"
                 ,server->GetLastError()
                 ,(LPCTSTR)GetLastErrorAsString(GetLastError()));
        }
        CleanupServer(server,logfile);
      }
    }
    printf("\n");
    printf("SUMMARY OF ALL SERVER TESTS\n");
    printf("===========================\n");
    if(totalErrors)
    {
      printf("ERRORS: %d\n",nRetCode += totalErrors);
    }
    else
    {
      printf("ALL OK !!!! YIPEEEE!!!!\n");
    }
    WaitForKey();
    WaitForKey();
  }
  DeleteCriticalSection(&std_stream);

  return nRetCode;
}
Exemplo n.º 9
0
bool isCertificateValidated(const generic_string & fullFilePath, const generic_string & subjectName2check)
{
	bool isOK = false;
	HCERTSTORE hStore = NULL;
	HCRYPTMSG hMsg = NULL;
	PCCERT_CONTEXT pCertContext = NULL;
	BOOL result;
	DWORD dwEncoding, dwContentType, dwFormatType;
	PCMSG_SIGNER_INFO pSignerInfo = NULL;
	DWORD dwSignerInfo;
	CERT_INFO CertInfo;
	LPTSTR szName = NULL;

	generic_string subjectName;

	try {
		// Get message handle and store handle from the signed file.
		result = CryptQueryObject(CERT_QUERY_OBJECT_FILE,
			fullFilePath.c_str(),
			CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
			CERT_QUERY_FORMAT_FLAG_BINARY,
			0,
			&dwEncoding,
			&dwContentType,
			&dwFormatType,
			&hStore,
			&hMsg,
			NULL);

		if (!result)
		{
			generic_string errorMessage = TEXT("Check certificate of ") + fullFilePath + TEXT(" : ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Get signer information size.
		result = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
		if (!result)
		{
			generic_string errorMessage = TEXT("CryptMsgGetParam first call: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Allocate memory for signer information.
		pSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSignerInfo);
		if (!pSignerInfo)
		{
			generic_string errorMessage = TEXT("CryptMsgGetParam memory allocation problem: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Get Signer Information.
		result = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pSignerInfo, &dwSignerInfo);
		if (!result)
		{
			generic_string errorMessage = TEXT("CryptMsgGetParam: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		// Search for the signer certificate in the temporary 
		// certificate store.
		CertInfo.Issuer = pSignerInfo->Issuer;
		CertInfo.SerialNumber = pSignerInfo->SerialNumber;

		pCertContext = CertFindCertificateInStore(hStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, (PVOID)&CertInfo, NULL);
		if (not pCertContext)
		{
			generic_string errorMessage = TEXT("Certificate context: ");
			errorMessage += GetLastErrorAsString(GetLastError());
			throw errorMessage;
		}

		DWORD dwData;

		// Get Subject name size.
		dwData = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
		if (dwData <= 1)
		{
			throw generic_string(TEXT("Certificate checking error: getting data size problem."));
		}

		// Allocate memory for subject name.
		szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
		if (!szName)
		{
			throw generic_string(TEXT("Certificate checking error: memory allocation problem."));
		}

		// Get subject name.
		if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, szName, dwData) <= 1)
		{
			throw generic_string(TEXT("Cannot get certificate info."));
		}

		// check Subject name.
		subjectName = szName;
		if (subjectName != subjectName2check)
		{
			throw generic_string(TEXT("Certificate checking error: the certificate is not matched."));
		}

		isOK = true;
	}
	catch (generic_string s)
	{
		// display error message
		MessageBox(NULL, s.c_str(), TEXT("Certificate checking"), MB_OK);
	}
	catch (...)
	{
		// Unknown error
		generic_string errorMessage = TEXT("Unknown exception occured. ");
		errorMessage += GetLastErrorAsString(GetLastError());
		MessageBox(NULL, errorMessage.c_str(), TEXT("Certificate checking"), MB_OK);
	}

	// Clean up.
	if (pSignerInfo != NULL) LocalFree(pSignerInfo);
	if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);
	if (hStore != NULL) CertCloseStore(hStore, 0);
	if (hMsg != NULL) CryptMsgClose(hMsg);
	if (szName != NULL) LocalFree(szName);

	return isOK;
}
Exemplo n.º 10
0
// Running the service
bool
WebServiceServer::RunService()
{
  // Configure our threadpool
  if(m_pool == nullptr)
  {
    m_pool = new ThreadPool();
    m_poolOwner = true;
  }
  // Setting the correct parameters
  if(m_maxThreads)
  {
    m_pool->TrySetMaximum(m_maxThreads);
  }

  // Starting the logfile
  if(m_log == nullptr)
  {
    m_logOwner = true;
    m_log = new LogAnalysis("Webservice: " + m_name);
    if(!m_logFilename.IsEmpty())
    {
      m_log->SetLogFilename(m_logFilename);
    }
  }
  // Default is logging in file, propagate that setting
  m_log->SetLogLevel(m_logLevel);

  // Start right type of server if not already given.
  if(m_httpServer == nullptr)
  {
    m_httpServer  = new HTTPServerMarlin(m_name);
    m_serverOwner = true;
    m_httpServer->SetWebroot(m_webroot);
  }
  else
  {
    // Use the webroot of the existing server!
    m_webroot = m_httpServer->GetWebroot();
  }
  // Try to set our caching policy
  m_httpServer->SetCachePolicy(m_cachePolicy,m_cacheSeconds);

  // Set our logfile
  m_httpServer->SetLogging(m_log);
  m_httpServer->SetLogLevel(m_logLevel);
  // Use our error reporting facility
  if(m_errorReport)
  {
    m_httpServer->SetErrorReport(m_errorReport);
  }

  // Make sure the server is initialized
  m_httpServer->Initialise();

  // Starting a WSDL 
  StartWsdl();

  // Try to read an external WSDL
  if(!m_externalWsdl.IsEmpty())
  {
    m_generateWsdl = false;
    if(m_wsdl->ReadWSDLFile(m_externalWsdl) == false)
    {
      m_errorMessage.Format("ERROR reading WSDL file: %s\n",m_externalWsdl.GetString());
      m_errorMessage += m_wsdl->GetErrorMessage();
      m_log->AnalysisLog(__FUNCTION__,LogType::LOG_ERROR,false,m_errorMessage);
      return false;
    }
  }

  // Init the WSDL cache for this service
  m_wsdl->SetWebroot(m_webroot);
  m_wsdl->SetTargetNamespace(m_targetNamespace);
  m_wsdl->SetService(m_name,m_url);
  m_wsdl->SetServicePostfix(m_servicePostfix);
  m_wsdl->SetLogAnalysis(m_log);

  // Try to generate the WSDL
  if(m_generateWsdl && m_wsdl->GenerateWSDL() == false)
  {
    m_errorMessage.Format("Cannot start the service. No legal WSDL generated for: %s",m_url.GetString());
    m_log->AnalysisLog(__FUNCTION__, LogType::LOG_ERROR,false,m_errorMessage);
    return false;
  }

  // Analyze the URL
  CrackedURL cracked(m_url);
  if(cracked.Valid() == false)
  {
    m_errorMessage.Format("WebServiceServer has no legal URL to run on: %s",m_url.GetString());
    m_log->AnalysisLog(__FUNCTION__,LogType::LOG_ERROR,false,m_errorMessage);
    return false;
  }
  // Keep the absolute path in separate form
  m_absPath = cracked.m_path;
  if(m_absPath.Right(1) != "/")
  {
    m_absPath += "/";
  }

  // Creating a HTTP site
  m_site = m_httpServer->CreateSite(m_channelType
                                    ,cracked.m_secure
                                    ,cracked.m_port
                                    ,cracked.m_path
                                    ,m_subsite);
  if(m_site == nullptr)
  {
    m_errorMessage.Format("Cannot register an HTTP channel on this machine for URL: %s",m_url.GetString());
    m_log->AnalysisLog(__FUNCTION__, LogType::LOG_ERROR,false,m_errorMessage);
    return false;
  }
  // Setting the service as the payload!!
  // Used in the SiteHandlerSoapWSService
  m_site->SetPayload(this);

  // Read the general settings first
  ReadingWebconfig();

  // Standard text content types
  m_site->AddContentType("",   "text/xml");              // SOAP 1.0 / 1.1
  m_site->AddContentType("xml","application/soap+xml");  // SOAP 1.2
  m_site->SetEncryptionLevel(m_securityLevel);
  m_site->SetEncryptionPassword(m_enc_password);
  m_site->SetAsync(m_asyncMode);
  m_site->SetAuthenticationScheme(m_authentScheme);
  m_site->SetAuthenticationRealm(m_authentRealm);
  m_site->SetAuthenticationDomain(m_authentDomain);
  m_site->SetReliable(m_reliable);
  if(m_reliable)
  {
    m_site->SetReliableLogIn(m_reliableLogin);
  }

  // If already set, pass on the SOAP handler
  // It's always the POST handler!
  if(m_soapHandler)
  {
    m_site->SetHandler(HTTPCommand::http_post,m_soapHandler);
  }
  else
  {
    // If not use the default WSService handler
    m_soapHandler = new SiteHandlerSoapWSService();
    m_site->SetHandler(HTTPCommand::http_post,m_soapHandler);
  }

  // If already set, pass on the GET handler
  if(m_getHandler)
  {
    m_site->SetHandler(HTTPCommand::http_get,m_getHandler);
  }
  else if(m_jsonTranslation)
  {
    // If JSON/SOAP translation: provide a handler for that
    m_getHandler = new SiteHandlerJson2Soap();
    m_site->SetHandler(HTTPCommand::http_get,m_getHandler);
  }
  else if(m_wsdl->GetOperationsCount() > 0)
  {
    // If not, use the default GetWSService handler
    // but only if we generate a WSDL for the users
    m_getHandler = new SiteHandlerGetWSService();
    m_site->SetHandler(HTTPCommand::http_get,m_getHandler);
  }

  // If set, pass on the PUT handler
  if(m_putHandler)
  {
    m_site->SetHandler(HTTPCommand::http_put,m_putHandler);
  }

  // Adding the extra content types to the site
  for(auto& ctype : m_contentTypes)
  {
    m_site->AddContentType(ctype.first,ctype.second.GetContentType());
  }

  // New: Explicit starting the site for HTTP API Version 2.0
  if(m_site->StartSite() == false)
  {
    m_errorMessage.Format("Cannot start HTTPSite for webservice server on: %s",m_url.GetString());
    m_log->AnalysisLog(__FUNCTION__, LogType::LOG_ERROR,false,m_errorMessage);
    return false;
  }

  // Only starting the server if no errors found
  if(m_httpServer->GetLastError() == NO_ERROR)
  {
    // Go run our service!!
    if(m_httpServer->GetIsRunning() == false)
    {
      m_httpServer->Run();
    }
  }
  else
  {
    m_errorMessage.Format("Cannot start HTTPServer. Server in error state. Error %lu: %s"
                          ,m_httpServer->GetLastError()
                          ,GetLastErrorAsString(m_httpServer->GetLastError()).GetString());
    m_log->AnalysisLog(__FUNCTION__, LogType::LOG_ERROR,false,m_errorMessage);
    return false;
  }
  // Now legally running
  return (m_isRunning = true);
}
Exemplo n.º 11
0
int setupDInput()
{
	if (!diAvailable) {
		return FALSE;
	}
	// Create a DirectInput8 instance
	if (di != NULL) {
		return TRUE;
	}
	HRESULT hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&di, NULL);
	if (FAILED(hr)) {
		// If it is not available for any reason, avoid getting back in setupDInput
		diAvailable = false;
		MessageBox(NULL, GetLastErrorAsString().c_str(), "SF5DInput - Direct Input", MB_ICONERROR);
		exit(hr);
	}

	// DI is ready, now create a message-only window
	WNDCLASSEX wndClass = {};
	wndClass.cbSize = sizeof(WNDCLASSEX);
	wndClass.lpfnWndProc = reinterpret_cast<WNDPROC>(messageCallback);
	GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)&wndClass.hInstance, &wndClass.hInstance);
	wndClass.lpszClassName = "SF5DInput";

	if (!RegisterClassEx(&wndClass)) {
		MessageBox(NULL, GetLastErrorAsString().c_str(), "SF5DInput - Registering Window Class", MB_ICONERROR);
		exit(1);
	}

	hWnd = CreateWindowEx(0L, wndClass.lpszClassName, "SF5DInput", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);	
	if (!hWnd) {
		MessageBox(NULL, GetLastErrorAsString().c_str(), "SF5DInput - Create Internal Window", MB_ICONERROR);
		exit(2);
	}

	// Message only window is ready, now we can create a notification filter to register to device notificaitons

	DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;

	ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
	NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
	NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
	// This is GUID_DEVINTERFACE_USB_DEVICE, it scans all usb devices
	NotificationFilter.dbcc_classguid = { 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };

	hDeviceNotify = RegisterDeviceNotification(
		hWnd,                       // events recipient
		&NotificationFilter,        // type of device
		DEVICE_NOTIFY_WINDOW_HANDLE // type of recipient handle
	);

	if (NULL == hDeviceNotify) {
		MessageBox(NULL, GetLastErrorAsString().c_str(), "SF5DInput - Registering Device Notification", MB_ICONERROR);
		exit(1);
	}

	// WOOH we are ready to go!

	// Get all the devices
	refreshDevices();
	return TRUE;
}