Example #1
0
BOOL COcsSystrayDlg::IsServiceRunning( CString &csStatusText)
{
    SERVICE_STATUS ss;
	SC_HANDLE hSCM, hService;

	// open the service control manager
    hSCM = OpenSCManager( NULL, SERVICES_ACTIVE_DATABASE, GENERIC_READ);
    if(!hSCM)
 	{
		csStatusText.Format( IDS_FAILED_CONNECT_SERVICE, _T( "Service Control Manager"), LookupError( GetLastError()));
		return FALSE;
	}
    // open the service
    hService = OpenService( hSCM, OCS_SERVICE_SECTION, GENERIC_READ);
    if(!hService)
	{
		csStatusText.Format( IDS_FAILED_CONNECT_SERVICE, OCS_SERVICE_SECTION, LookupError( GetLastError()));
		CloseServiceHandle( hSCM);
		return FALSE;
	}
    // Get the current status
    memset( &ss, 0, sizeof( ss));
    if (!QueryServiceStatus( hService, &ss))
	{
		csStatusText.Format( IDS_FAILED_CONNECT_SERVICE, OCS_SERVICE_SECTION, LookupError( GetLastError()));
		CloseServiceHandle( hService);
		CloseServiceHandle( hSCM);
		return FALSE;
	}
    // close the service handle
    CloseServiceHandle( hService);
    // close the service control manager handle
    CloseServiceHandle( hSCM);
    // See what we got
	switch (ss.dwCurrentState) 
	{
    case SERVICE_START_PENDING:
    case SERVICE_CONTINUE_PENDING:
		csStatusText.Format( IDS_SERVICE_STARTING, OCS_SERVICE_SECTION);
        break;
    case SERVICE_RUNNING:
		csStatusText.Format( IDS_SERVICE_STARTED, OCS_SERVICE_SECTION);
        break;
    case SERVICE_STOP_PENDING:
    case SERVICE_PAUSE_PENDING:
		csStatusText.Format( IDS_SERVICE_STOPPING, OCS_SERVICE_SECTION);
        break;
    case SERVICE_STOPPED:
    case SERVICE_PAUSED:
		csStatusText.Format( IDS_SERVICE_STOPPED, OCS_SERVICE_SECTION);
        break;
	default:
 		csStatusText.Format( IDS_FAILED_CONNECT_SERVICE, OCS_SERVICE_SECTION, LookupError( GetLastError()));
		break;
   }
	return TRUE;
}
DWORD CExecCommand::realCreateProcess(LPCTSTR lpstrCommand, LPCTSTR lpstrPath, BOOL bCapture)
{
	PROCESS_INFORMATION piProcInfo;
	STARTUPINFO		siStartInfo;
	CString			csComspec,
					csCommand;
	static DWORD	dwProcessID = 0;

	ASSERT( lpstrCommand);

	if (m_bComspec)
	{
		// Find COMSPEC environnement variable to start process
		if (!csComspec.GetEnvironmentVariable( _T( "COMSPEC")))
		{
			/*
			* Oh gag, we're on Win9x or using COMMAND.COM. Not supported
			*/
			m_csOutput.Format( "Get COMSPEC Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
			return 0;
		}
		csCommand.Format( _T( "\"%s\" /c %s"), csComspec, lpstrCommand);
	}
	else
		// Do not use COMSPEC to start process => full path for command must be provided
		csCommand = lpstrCommand;

	ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
	siStartInfo.cb = sizeof(STARTUPINFO);
	if (bCapture)
	{
		// Capture stdin/stdout/stderr
		siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
		siStartInfo.hStdInput = m_hChildStdinRd;
		siStartInfo.hStdOutput = m_hChildStdoutWr;
		siStartInfo.hStdError = m_hChildStdoutWr;
	}
	else
		// No capture
		siStartInfo.dwFlags = STARTF_USESHOWWINDOW;
	siStartInfo.wShowWindow = SW_HIDE;

	if (!CreateProcess( NULL, csCommand.GetBuffer(), NULL, NULL, TRUE,
					0, //CREATE_NEW_CONSOLE,
					NULL, lpstrPath, &siStartInfo, &piProcInfo)) 
	{
		m_csOutput.Format( "CreateProcess Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
		return 0;
	}
	// Close the handles now so anyone waiting is woken.
	CloseHandle( piProcInfo.hThread);
	// Return process handle
	m_hProcessHandle = piProcInfo.hProcess;
	dwProcessID = piProcInfo.dwProcessId;
	return dwProcessID;
}
BOOL  CExecCommand::wait( BOOL bCapture)
{
	int		nResult = -1;
	DWORD	dwExitCode,
			dwTime = 0;
	char	bBuffer[1024];
	int		nLength;
	struct _stat fsOut;

	m_csOutput = "";

	// If capturing stdout/stderr enabled, and timeout is not reached
	while (bCapture && (dwTime < m_dwTimeout))
	{
		// Each 200 millisecond, store stdout and stderr
		dwTime += 200;
		if (WaitForSingleObject( m_hProcessHandle, 200) == WAIT_FAILED)
		{
			m_csOutput.Format( "WaitForSingleObject Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
			m_nExitValue = -1;
			return -1; 
		}
		// Read console output
		if ((_fstat( m_fdStdOut, &fsOut) == 0 ) && (fsOut.st_size > 0))
		{
			// There is something to read
			nLength = _read( m_fdStdOut, bBuffer, 1023);
			bBuffer[nLength] = 0;
			m_csOutput.AppendFormat( "%s", bBuffer);
		}
		// Check if process still active
		if (!GetExitCodeProcess( m_hProcessHandle, &dwExitCode) || (dwExitCode != STILL_ACTIVE))
		{
			// Process not active, exit loop
			break;
		}
	}  
	// Wait for process ending (not capturing output or error capturing output)
	if (GetExitCodeProcess( m_hProcessHandle, &dwExitCode)) 
	{
		nResult = dwExitCode;
	} 
	else 
	{
		m_csOutput.Format( "GetExitCode Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
		nResult = -1;
	}
	m_nExitValue = nResult;
	return (nResult >= 0);
}
Example #4
0
/*
 *----------------------------------------------------------------------
 *
 * Tcl_MacOSError --
 *
 *	This procedure is typically called after MacOS ToolBox calls return
 *	errors.  It stores machine-readable information about the error in
 *	$errorCode and returns an information string for the caller's use.
 *	It's a bit like Tcl_PosixError().
 *
 *  To get the most bang for your buck, install FindErrorLib.
 *    
 * Results:
 *	The return value is a human-readable string describing the error.
 *
 * Side effects:
 *	The global variable $errorCode is reset to:
 *	
 *		 {theErrorName theErrorNumber theErrorDescription}
 *		 
 *  or at least as much as is available.
 *
 *----------------------------------------------------------------------
 */
char *
Tcl_MacOSError(Tcl_Interp  *interp,			/* to assign global error code */
			   OSStatus    err)				/* error code to interpret */
{
	char        theErrorNumber[132];        /* text representation of 'err' */
	char		theErrorName[132];          /* from FindErrorLib */
	char 		theErrorDescription[132];   /* from FindErrorLib */
	static char	theErrorString[132];		/* static for return */
	
	theErrorDescription[0] = 0;  // (bd 2003-10-10)
	
//  FindErrorLib exists only for PPC
#if USE_FIND_ERROR_LIB
	/* Try to use FindErrorLib to interpret result */
	if ((((long) GetFindErrorLibDataInfo) != kUnresolvedCFragSymbolAddress)
	&&  (LookupError(err, theErrorName, theErrorDescription))) {
		/* error was found by FindErrorLib */
		if (strlen(theErrorDescription) > 0) {
			strcpy(theErrorString, theErrorDescription);
		} else {
			/* 
			 * No description was found in database.
			 * Make as much of an error string as we can.
			 */
			snprintf(theErrorString, 132, "OSErr %d, %s", err, theErrorName);
		} 
	} else 
#endif
	{
	
		/* 
		 * FindErrorLib is not installed or error wasn't found in database.
		 * Make a generic error string.
		 */
		strcpy(theErrorName, "OSErr");
		snprintf(theErrorString, 132, "OSErr %ld", (long)err);
	}
		
	/* string representation of the number */
	snprintf(theErrorNumber, 132, "%ld", (long)err);

	if (interp) {
		/* Set up Tcl error code with all info */
		Tcl_SetErrorCode(interp, 
						 theErrorName, 
						 theErrorNumber, 
						 theErrorDescription, 
						 (char *) NULL);		
	}
	
	/* Return the error description for output in the Tcl result */
    return theErrorString;
}
	CodecStatus_t   Codec_MmeVideoRmv_c::CheckCodecReturnParameters(CodecBaseDecodeContext_t * Context)
	{
		MME_Command_t*                              MMECommand              = (MME_Command_t*)(&Context->MMECommand);
		MME_CommandStatus_t*                        CmdStatus               = (MME_CommandStatus_t*)(&MMECommand->CmdStatus);
		RV89Dec_TransformStatusAdditionalInfo_t*    AdditionalInfo_p        = (RV89Dec_TransformStatusAdditionalInfo_t*)CmdStatus->AdditionalInfo_p;
		if (AdditionalInfo_p != NULL)
		{
			if (AdditionalInfo_p->ErrorCode != RV89DEC_NO_ERROR)
				CODEC_TRACE("%s - %s  %x \n", __FUNCTION__, LookupError(AdditionalInfo_p->ErrorCode), AdditionalInfo_p->ErrorCode);
		}
		return CodecNoError;
	}
Example #6
0
BOOL COcsSystrayDlg::ServiceSendMessage( DWORD dwMsg)
{
    SERVICE_STATUS ss;
	SC_HANDLE hSCM, hService;
	CString csMessage;

	// open the service control manager
    hSCM = OpenSCManager( NULL, SERVICES_ACTIVE_DATABASE, GENERIC_READ);
    if(!hSCM)
 	{
		csMessage.Format( IDS_FAILED_CONNECT_SERVICE, _T( "Service Control Manager"), LookupError( GetLastError()));
		AfxMessageBox( csMessage, MB_ICONSTOP|MB_OK);
		return FALSE;
	}
    // open the service
    hService = OpenService( hSCM, OCS_SERVICE_SECTION, GENERIC_READ|SERVICE_USER_DEFINED_CONTROL);
    if(!hService)
	{
		csMessage.Format( IDS_FAILED_CONNECT_SERVICE, OCS_SERVICE_SECTION, LookupError( GetLastError()));
		AfxMessageBox( csMessage, MB_ICONSTOP|MB_OK);
		CloseServiceHandle( hSCM);
		return FALSE;
	}
    // Send the service control message
    memset( &ss, 0, sizeof( ss));
    if (!ControlService( hService, dwMsg, &ss))
	{
		csMessage.Format( IDS_FAILED_SEND_MESSAGE, OCS_SERVICE_SECTION, LookupError( GetLastError()));
		AfxMessageBox( csMessage, MB_ICONSTOP|MB_OK);
		CloseServiceHandle( hService);
		CloseServiceHandle( hSCM);
		return FALSE;
	}
    // close the service handle
    CloseServiceHandle( hService);
    // close the service control manager handle
    CloseServiceHandle( hSCM);
	return TRUE;
}
BOOL CCapDownload::retrievePackages()
{
	CString					csCertFile,
		csId,
		csValue;
	COptDownloadPackage		*pOptDownloadPackage;
	CMapStringToStringArray	*pMapArray = NULL;
	CMapStringToString		*pMap = NULL;
	INT_PTR					nPack = 0;

	/***
	*
	* Environnement checking
	*
	***/

	// Working directory
	if (directoryCreate(getDownloadFolder()) == FALSE)
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot create working directory (%s)"), LookupError(GetLastError()));
		return FALSE;
	}
	// Open package history file, create it if needed
	CFilePackageHistory cFileHistory;
	if (!cFileHistory.Open(getPackageHistoryFilename(), FALSE, TRUE))
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot create history file <%>"), getPackageHistoryFilename());
		return FALSE;
	}
	if (!m_pPrologResp->isDownloadRequired())
	{
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => No package available for download"));
		return FALSE;
	}
	// Trying to create suspend Download tool
	if (!suspendDownload())
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot suspend Download and Setup Tool using <%s> file"), OCS_DOWNLOAD_SUSPEND);
		return FALSE;
	}
	// Trying to get exclusive access to download
	if (!lockDownload())
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot lock directory <%s>"), getDownloadFolder());
		resumeDownload();
		return FALSE;
	}
	// Get generic download parameters and write them for using with download tool
	pMapArray = m_pPrologResp->getDownloadParameters();
	if ((pMapArray == NULL) || pMapArray->IsEmpty())
	{
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => No download parameter available"));
		unlockDownload();
		resumeDownload();
		return FALSE;
	}
	// There is only one record for download parameters
	pMap = pMapArray->GetAt(0);
	pMap->Lookup(_T("FRAG_LATENCY"), m_csDownloadFragLatency);
	pMap->Lookup(_T("CYCLE_LATENCY"), m_csDownloadCycleLatency);
	pMap->Lookup(_T("PERIOD_LATENCY"), m_csDownloadPeriodLatency);
	pMap->Lookup(_T("PERIOD_LENGTH"), m_csDownloadPeriodLength);
	pMap->Lookup(_T("TIMEOUT"), m_csDownloadTimeout);
	pMap->Lookup(_T("EXECUTION_TIMEOUT"), m_csCommandTimeout);
	if (m_csCommandTimeout.IsEmpty())
		m_csCommandTimeout = COMMAND_TIMEOUT_DEFAULT;
	pMap->Lookup(_T("ON"), m_csDownloadOn);
	writeConfig();
	delete pMapArray;
	pMapArray = NULL;

	// Now get each package information
	pMapArray = m_pPrologResp->getDownloadPackages();
	for (nPack = 0; (pMapArray != NULL) && (nPack<pMapArray->GetCount()); nPack++)
	{
		if (((pMap = pMapArray->GetAt(nPack)) == NULL) || pMap->IsEmpty())
			continue;
		csId.Empty();
		pMap->Lookup(_T("ID"), csId);
		// Try to find if package was not previously downloaded, parsing package history file
		CString csHistBuf;
		BOOL	bAlreadySetup = FALSE;
		cFileHistory.SeekToBegin();
		while (cFileHistory.ReadPackage(csHistBuf))
		{
			if (csHistBuf.Find(csId) != -1)
			{
				// Package ID found in history
				bAlreadySetup = TRUE;
				break;
			}
		}
		pOptDownloadPackage = new COptDownloadPackage(this);
		pOptDownloadPackage->setId(csId);
		// If CERT_PATH or CERT_FILE option is provided
		csValue.Empty();
		pMap->Lookup(_T("CERT_PATH"), csValue);
		pOptDownloadPackage->setCertPath(csValue);
		csValue.Empty();
		pMap->Lookup(_T("CERT_FILE"), csValue);
		pOptDownloadPackage->setCertFile(csValue);
		// Set URL where to download INFO metadata
		csValue.Empty();
		pMap->Lookup(_T("INFO_LOC"), csValue);
		pOptDownloadPackage->setInfoLocation(csValue);
		// Set URL where to download fragment
		csValue.Empty();
		pMap->Lookup(_T("PACK_LOC"), csValue);
		pOptDownloadPackage->setPackLocation(csValue);
		// Set if we have to force package setup, even if already installed
		csValue.Empty();
		pMap->Lookup(_T("FORCE"), csValue);
		pOptDownloadPackage->setForce(csValue);
		// Set if we have to schedule package setup at specified date
		csValue.Empty();
		pMap->Lookup(_T("SCHEDULE"), csValue);
		pOptDownloadPackage->setSchedule(csValue);
		// Set post execution command if package action succeeded
		csValue.Empty();
		pMap->Lookup(_T("POSTCMD"), csValue);
		pOptDownloadPackage->setPostCmd(csValue);
		if (bAlreadySetup && !pOptDownloadPackage->isForced())
		{
			// Package ID found in history, do not download
			m_pLogger->log(LOG_PRIORITY_NOTICE, _T("DOWNLOAD => Will not download package <%s>, already in the package history"), csId);
			sendMessage(csId, SUCCESS_ALREADY_SETUP);
			// Delete already download directory if needed 
			pOptDownloadPackage->clean();
			delete pOptDownloadPackage;
		}
		else
		{
			// Package not already downloaded, or setup forced, put it in the download queue
			if (pOptDownloadPackage->isForced())
				m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package <%s> forced, ignoring package history check"), csId);
			m_tPackages.Add(pOptDownloadPackage);
		}
	}
	cFileHistory.Close();
	delete pMapArray;
	// Cleaning file history for duplicates
	switch (CFilePackageHistory::CleanDuplicates(getPackageHistoryFilename()))
	{
	case 1:
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package history file successfully cleaned for duplicate IDs"));
		break;
	case 2:
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package history file cleaning not required"));
		break;
	default:
		m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Failed to clean Package history file for duplicate IDs"));
		break;
	}

	// Now, prepare directories and download instructions for download tool
	for (nPack = 0; nPack<m_tPackages.GetSize(); nPack++)
	{
		pOptDownloadPackage = (COptDownloadPackage*)(m_tPackages[nPack]);
		// Check if package is not expired
		if (pOptDownloadPackage->isExpired(m_csDownloadTimeout))
		{
			ULONG ulNow = time(NULL);
			m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Package <%s> timed out (now:%lu, since:%lu, Timeout:%s)"), pOptDownloadPackage->getId(), ulNow, (ULONG)pOptDownloadPackage->getTimeStamp(), m_csDownloadTimeout);
			if (sendMessage(pOptDownloadPackage->getId(), ERR_TIMEOUT))
				// Server successfully notified => remove package
				if (!pOptDownloadPackage->clean())
					m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Failed to remove timed out package <%s>"), pOptDownloadPackage->getId());
		}
		else
		{
			// Check if package not already added to download queue
			if (pOptDownloadPackage->makeDirectory() && !fileExists(pOptDownloadPackage->getLocalMetadataFilename()))
			{
				// Download metadata from deployment server
				if (pOptDownloadPackage->downloadInfoFile())
					m_pLogger->log(LOG_PRIORITY_NOTICE, _T("DOWNLOAD => Package <%s> added to download queue"), pOptDownloadPackage->getId());
				else
					// Error dowloading metadata => remove package directory to avoid error message into download tool
					pOptDownloadPackage->clean();
			}
			else
				m_pLogger->log(LOG_PRIORITY_DEBUG, _T("DOWNLOAD => Package <%s> already in download queue, keeping on package"), pOptDownloadPackage->getId());
		}
	}
	// Now, allow Download tool
	unlockDownload();
	resumeDownload();
	return TRUE;
}
BOOL COptDownloadPackage::makeDirectory()
{
	if (!directoryCreate(m_csLocalPackLoc))
	{
		m_pLogger->log(LOG_PRIORITY_ERROR, _T("DOWNLOAD => Cannot create package <%s> directory (%s)"), m_csId, LookupError(GetLastError()));
		return FALSE;
	}
	return TRUE;
}
Example #9
0
BOOL CComProvider::load(LPCTSTR lpstrProvider)
{
    CLog *pLogger = getOcsLogger();

    try
    {
        CFileVersion fileVer;

        unload();

        pLogger->log( LOG_PRIORITY_DEBUG,  _T( "COM PROVIDER => Loading Communication Provider <%s>"), lpstrProvider);
        if ((m_hComProvider = LoadLibrary( lpstrProvider)) == NULL)
        {
            pLogger->log( LOG_PRIORITY_WARNING,  _T( "COM PROVIDER => Unable to load library <%s>, %s"), lpstrProvider, LookupError( GetLastError()));
            return FALSE;
        }
        if ((m_pNewServerConfig = (NEW_SERVER_CONFIG_OBJECT)GetProcAddress( m_hComProvider, "newServerConfig")) == NULL)
        {
            pLogger->log( LOG_PRIORITY_WARNING,  _T( "COM PROVIDER => No newServerConfig hook for Communication Provider <%s>, %s"), lpstrProvider, LookupError( GetLastError()));
            FreeLibrary( m_hComProvider);
            return FALSE;
        }
        if ((m_pDeleteServerConfig = (DELETE_SERVER_CONFIG_OBJECT)GetProcAddress( m_hComProvider, "deleteServerConfig")) == NULL)
        {
            pLogger->log( LOG_PRIORITY_WARNING,  _T( "COM PROVIDER => No deleteServerConfig hook for Communication Provider <%s>, %s"), lpstrProvider, LookupError( GetLastError()));
            FreeLibrary( m_hComProvider);
            return FALSE;
        }
        if ((m_pNewServerConnexion = (NEW_SERVER_OBJECT)GetProcAddress( m_hComProvider, "newServerConnexion")) == NULL)
        {
            pLogger->log( LOG_PRIORITY_WARNING,  _T( "COM PROVIDER => No newServerConnexion hook for Communication Provider <%s>, %s"), lpstrProvider, LookupError( GetLastError()));
            FreeLibrary( m_hComProvider);
            return FALSE;
        }
        if ((m_pDeleteServerConnexion = (DELETE_SERVER_OBJECT)GetProcAddress( m_hComProvider, "deleteServerConnexion")) == NULL)
        {
            pLogger->log( LOG_PRIORITY_WARNING,  _T( "COM PROVIDER => No deleteServerConnexion hook for Communication Provider <%s>, %s"), lpstrProvider, LookupError( GetLastError()));
            FreeLibrary( m_hComProvider);
            return FALSE;
        }
        // Open application file to get version from file
        if (fileVer.Open( lpstrProvider))
        {
            m_csName = fileVer.GetFileDescription();
            m_csVersion = fileVer.GetFixedFileVersion();
            fileVer.Close();
        }
        else
        {
            m_csName = _T( "N/A");
            m_csVersion = _T( "N/A");
        }
        return TRUE;
    }
    catch (CException *pEx)
    {
        pLogger->log( LOG_PRIORITY_WARNING,  _T( "COM PROVIDER => Error while loading provider DLL <%s>, %s"), lpstrProvider, LookupError( pEx));
        pEx->Delete();
        return FALSE;
    }
}
Example #10
0
int CPlugins::Load( LPCTSTR lpstrPath)
{
	CString	csPath;
	int		nPlugin = 0,
			nCount = 0;
	BOOL	bFoundPlugins = FALSE,
			bValidPlugin;

	try
	{
		CFileFind			cFinder;

		// plugin struct array initialization
		for (int i=0; i<MAX_PLUGINS; i++ )
		{
			m_plugin[i].hDll		= NULL;
			m_plugin[i].pInventory	= NULL;
			m_plugin[i].pPrologResp	= NULL;
			m_plugin[i].pPrologWrite= NULL;
			m_plugin[i].pStart		= NULL;
			m_plugin[i].pEnd		= NULL;
			m_plugin[i].pClean		= NULL;
		}
		if ((lpstrPath == NULL) || (_tcslen( lpstrPath) == 0))
			// Use standard install path
			csPath.Format( _T( "%s\\plugins"), getInstallFolder());
		else
			// Use provided path to search for plugins
			csPath = lpstrPath;
		// Search for DLL into path
		m_pLogger->log( LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => Searching for Plug-in DLL(s) in folder <%s>"), csPath);
		csPath +=  _T( "\\*.dll");
		bFoundPlugins = cFinder.FindFile( csPath);
		while (bFoundPlugins)
		{
			bValidPlugin = FALSE;
			// One DLL found, try to load it
			bFoundPlugins = cFinder.FindNextFile();
			m_pLogger->log(LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => Trying to validate DLL <%s> as a Plug-in"), cFinder.GetFileName());
			if( (m_plugin[nPlugin].hDll = LoadLibrary( cFinder.GetFilePath())) == NULL )
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => Failed loading Plug-in DLL <%s>, %s"), cFinder.GetFileName(), LookupError( GetLastError()));
				continue;
			}
			// Get name
			m_plugin[nPlugin].csName = cFinder.GetFileTitle();
			// Try to load each API entry
			if( (m_plugin[nPlugin].pEnd = (HOOK_END)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_END_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No End hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pStart = (HOOK_START)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_START_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Start hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pClean = (HOOK_CLEAN)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_CLEAN_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Clean hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pInventory = (HOOK_INVENTORY)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_INVENTORY_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Inventory hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pPrologWrite = (HOOK_PROLOG_WRITE)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_PROLOGWRITE_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Prolog Read hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if( (m_plugin[nPlugin].pPrologResp = (HOOK_PROLOG_RESP)GetProcAddress( m_plugin[nPlugin].hDll, "OCS_CALL_PROLOGRESP_EXPORTED")) == NULL)
			{
				m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => No Prolog response hook for Plug-in <%s>, %s"), cFinder.GetFileTitle(), LookupError( GetLastError()));
			}
			else
				// Hook available, so valid plugin
				bValidPlugin = TRUE;
			if (bValidPlugin)
			{
				// At least one hook available and plugin valid
				m_pLogger->log( LOG_PRIORITY_NOTICE,  _T( "DLL PLUGIN => Plug-in <%s> loaded"), m_plugin[nPlugin].csName);
				// Store and increase plugin number
				nPlugin++;
			}
			else
			{
				// Do not store DLL as a plugin
				m_pLogger->log(LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => DLL <%s> is not a valid Plug-in"), cFinder.GetFileName());
				FreeLibrary( m_plugin[nPlugin].hDll );
			}
			nCount++;
		}
		cFinder.Close();
		m_pLogger->log(LOG_PRIORITY_DEBUG,  _T( "DLL PLUGIN => %d DLL Plug-in(s) succesfully loaded on %d DLL(s) found"), nPlugin, nCount);
		return nPlugin;
	}
	catch (CException *pEx)
	{
		m_pLogger->log( LOG_PRIORITY_WARNING,  _T( "DLL PLUGIN => Error while parsing Plug-in directory <%s>"), LookupError( pEx));
		pEx->Delete();
		return -1;
	}
}
BOOL CInventoryRequest::initInventory()
{
	CString csStateFile;

	if (m_bNotify)
		// Notify IP information changes
		setQuery( _T( "NOTIFY"), _T( "IP"));
	else
	{
		setQuery( _T( "INVENTORY"));

		/****	
		*
		* Package history inventory section
		*
		****/
		m_pLogger->log( LOG_PRIORITY_DEBUG, _T( "INVENTORY => Loading Download history"));
		if (!loadDownloadHistory())
		{
			m_pLogger->log( LOG_PRIORITY_DEBUG, _T("INVENTORY => Failed opening Download Package history file <%s>"), LookupError( GetLastError()));
		}
	}
	/******************/

	if( m_pDeviceid->getOldDeviceID() != _T("") )
		m_cmXml.AddChildElem( _T("OLD_DEVICEID"),m_pDeviceid->getOldDeviceID());
			
	/****	
	*
	* Get the Device netbios Name
	*
	****/

	m_pTheDB	= new CXMLInteract(&m_cmXml);
	m_pState	= new COCSInventoryState;
	m_pPluginState	= new COCSInventoryState;
	m_pSysInfo	= new CSysInfo( getAgentConfig()->isDebugRequired() >= OCS_DEBUG_MODE_TRACE, getDataFolder());

	m_Device.SetDeviceName( m_pDeviceid->getComputerName());
	// Get DeviceId from ocsinventoryFront
	m_Device.SetDeviceID( m_pDeviceid->getDeviceID() );

	/*****
	 *
	 *	Main inventory function
	 *
	 ****/
	// Get Device info
	if (!runInventory())
		return FALSE;

	// Read last inventory state from XML file
	m_pLogger->log( LOG_PRIORITY_DEBUG, _T( "INVENTORY => Reading last inventory state"));
	csStateFile.Format( _T("%s\\%s"), getDataFolder(), OCS_LAST_STATE_FILE);
	if (!m_pState->ReadFromFile( csStateFile, OCS_STATE_STANDARD_SECTION))
		m_pLogger->log( LOG_PRIORITY_WARNING, _T( "INVENTORY => Failed to load/parse inventory state from file <%s>"), csStateFile);
	if (!m_pPluginState->ReadFromFile( csStateFile, OCS_STATE_PLUGIN_SECTION))
		m_pLogger->log( LOG_PRIORITY_WARNING, _T( "INVENTORY => Failed to load/parse plugin state from file <%s>"), csStateFile);
	return TRUE;
}
Example #12
0
UINT CPackage::executePostCmd( UINT uCommandTimeOut)
{
	CLog *pLog = getOcsLogger();
	CExecCommand cmProcess;
	CString csBuffer;
	HANDLE hToken; 
	TOKEN_PRIVILEGES tkp; 

	// check if there is post command to execute
	if (m_csPostCmd.IsEmpty())
	{
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => No post execution command provided for package <%s>"), m_csID);
		return TRUE;
	}
	// Check if post command is REBOOT
	if (m_csPostCmd == OCS_DOWNLOAD_POST_CMD_REBOOT)
	{
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Executing post execution command <%s> for package <%s>"), m_csPostCmd, m_csID);
		// Request ability to restart computer
		if (!OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) 
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to request Reboot privilege for package <%s>: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		if (!LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid)) 
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to request Reboot privilege for package <%s>: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		tkp.PrivilegeCount = 1; 
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 
		if (!AdjustTokenPrivileges( hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0))
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to request Reboot privilege for package <%s>: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		// Initiate a planned restart to perform application installation.
		if (!InitiateSystemShutdownEx( NULL, _T( "OCS Inventory NG must REBOOT your system after package setup"), 
										uCommandTimeOut, TRUE, TRUE,
										SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION | SHTDN_REASON_FLAG_PLANNED))
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to initiate System Reboot after package <%s> execution: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		return TRUE;
	}
	// Check if post command is SHUTDOWN
	if (m_csPostCmd == OCS_DOWNLOAD_POST_CMD_SHUTDOWN)
	{
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Executing post execution command <%s> for package <%s>"), m_csPostCmd, m_csID);
		// Request ability to shutdown computer
		if (!OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) 
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to request Shutdown privilege for package <%s>: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		if (!LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid)) 
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to request Shutdown privilege for package <%s>: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		tkp.PrivilegeCount = 1; 
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 
		if (!AdjustTokenPrivileges( hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0))
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to request Shutdown privilege for package <%s>: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		// Initiate a planned shutdown to perform application installation.
		if (!InitiateSystemShutdownEx( NULL, _T( "OCS Inventory NG must SHUTDOWN your system after package setup"),
										uCommandTimeOut, TRUE, FALSE,
										SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION | SHTDN_REASON_FLAG_PLANNED))
		{
			pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Unable to initiate System Shutdown after package <%s> execution: %s"), m_csID, LookupError( GetLastError()));
			return FALSE;
		}
		return TRUE;
	}
	// Execute default post command
	pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Executing post execution command <%s> for package <%s>"), m_csPostCmd, m_csID);
	// Set command time out in milliseconds
	cmProcess.setTimeout( uCommandTimeOut * 60 * 1000);
	// Execute command and wait only for main process to terminate
	switch (cmProcess.execWait( m_csPostCmd, m_csPath))
	{
	case EXEC_ERROR_START_COMMAND:
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to execute post execution command <%s> for package <%s> (%s)"), m_csPostCmd, m_csID, cmProcess.getOutput());
		setDone( ERR_EXECUTE);
		return FALSE;
	case EXEC_ERROR_WAIT_COMMAND:
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Failed to get post execution command <%s> result code for package <%s> (%s)"), m_csPostCmd, m_csID, cmProcess.getOutput());
		csBuffer = ERR_EXECUTE_NO_EXIT_CODE;
		return FALSE;
	case EXEC_ERROR_TIMEOUT_COMMAND:
		pLog->log( LOG_PRIORITY_WARNING, _T( "PACKAGE => Post execution command <%s> execution reached timeout (%s)"), m_csPostCmd, cmProcess.getOutput());
		csBuffer = ERR_EXECUTE_TIMEOUT;
		return FALSE;
	default:
		pLog->log( LOG_PRIORITY_DEBUG, _T( "PACKAGE => Package <%s> post execution command successfully executed. Command exit code is <%d>"), m_csID, cmProcess.getExitValue());
		if (cmProcess.getExitValue() != 0)
			// Command result code is not a success
			csBuffer.Format( _T( "%s%d"), ERR_EXIT_CODE, cmProcess.getExitValue());
		else
			csBuffer = CODE_SUCCESS;
		break;
	}
	return TRUE;
}
int CExecCommand::execWaitForAllChilds( LPCTSTR lpstrCommand, LPCTSTR lpstrPath)
{
	CObArray		myProcessList;
	CProcessProps	*pProcess;
	DWORD			dwExitCode,
					dwProcessID,
					dwTime = 0;

	try
	{
		ASSERT( lpstrCommand);

		// Start process
		initialize();
		if ((dwProcessID = realCreateProcess( lpstrCommand, lpstrPath)) == 0) 
		{
			closeHandles();
			return EXEC_ERROR_START_COMMAND;
		}
		// We need high priority on OS to follow thread/process created by main command
		SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS);
		// Store first process
		pProcess = new CProcessProps();
		pProcess->set( dwProcessID, GetCurrentProcessId(), lpstrCommand);
		myProcessList.Add( pProcess);
		// While there is running processes or timeout not reached
		while ((myProcessList.GetCount() > 0) && (dwTime < m_dwTimeout))
		{
			// Parse memory processes for new childs process or terminated processes
			if (!parseRunningProcesses( &myProcessList))
			{
				SetPriorityClass( GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
				m_csOutput.Format( "Parse running processes Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
				freeProcessList( &myProcessList);
				closeHandles();
				return EXEC_ERROR_WAIT_COMMAND;
			}
			Sleep( EXEC_WAIT_CHECK_LATENCY);
			dwTime += EXEC_WAIT_CHECK_LATENCY;
		}
		freeProcessList( &myProcessList);
		// Now return to normal prioity
		SetPriorityClass( GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
		// Get exit code
		if (GetExitCodeProcess( m_hProcessHandle, &dwExitCode)) 
		{
			m_nExitValue = dwExitCode;
		}
		else
		{
			m_nExitValue = -1;
			m_csOutput.Format( "GetExitCode Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
			closeHandles();
			return EXEC_ERROR_WAIT_COMMAND;
		}
		closeHandles();
		return EXEC_SUCCESSFULL;
	}
	catch (CException *pEx)
	{
		pEx->Delete();
		closeHandles();
		m_csOutput = "Unhandled exception Error";
		return EXEC_ERROR_START_COMMAND;
	}
}
BOOL CExecCommand::startProcessCapture(LPCTSTR lpstrCommand, LPCTSTR lpstrPath)
{
	SECURITY_ATTRIBUTES saAttr;

	ASSERT( lpstrCommand);
	initialize();

	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = NULL;

	////////////////////////////////////////////////////////////////
	// Capture stdin
	if (!CreatePipe(&m_hChildStdinRd, &m_hChildStdinWr, &saAttr, 0))
	{
		m_csOutput.Format( "CreatePipe Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
		return FALSE;
	}
	/* Create new output read handle and the input write handle. Set
	* the inheritance properties to FALSE. Otherwise, the child inherits
	* these handles; resulting in non-closeable handles to the pipes
	* being created. */
	if (!DuplicateHandle( GetCurrentProcess(), m_hChildStdinWr, GetCurrentProcess(), &m_hChildStdinWrDup, 0,
		 FALSE, DUPLICATE_SAME_ACCESS))
	{
		m_csOutput.Format( "DuplicateHandle Error");
		return FALSE;
	}

	// Close the inheritable version of ChildStdin that we're using.
	CloseHandle( m_hChildStdinWr);
	m_hChildStdinWr = NULL;

	////////////////////////////////////////////////////////////////
	// Capture stdout and stderr
	if (!CreatePipe(&m_hChildStdoutRd, &m_hChildStdoutWr, &saAttr, 0))
	{
		m_csOutput.Format( "CreatePipe Error: %s", GetAnsiFromUnicode( LookupError( GetLastError())));
		return FALSE;
	}
	if (!DuplicateHandle( GetCurrentProcess(), m_hChildStdoutRd, GetCurrentProcess(), &m_hChildStdoutRdDup, 0,
		 FALSE, DUPLICATE_SAME_ACCESS))
	{
		m_csOutput.Format( "DuplicateHandle Error");
		return FALSE;
	}

	// Close the inheritable version of ChildStdout that we're using.
	CloseHandle( m_hChildStdoutRd);
	m_hChildStdoutRd = NULL;

	// Associates a C run-time file descriptor with an existing operating-system file handle
	// It's easier to use for the console
	if ((m_fdStdOut = _open_osfhandle(TO_INTPTR(m_hChildStdoutRdDup), _O_RDONLY|_O_TEXT)) == -1)
	{
		m_csOutput.Format( "_open_osfhandle Error");
		return FALSE;
	}

	if (realCreateProcess( lpstrCommand, lpstrPath, TRUE) == 0)
	{
		// m_csOuput already conatins error description
		return FALSE;
	}

	return TRUE;
}
Example #15
0
BOOL COcsNotifyUserApp::InitInstance()
{
    HANDLE hMutexOneInstance = NULL;

    try
    {
        // InitCommonControlsEx() is required on Windows XP if an application
        // manifest specifies use of ComCtl32.dll version 6 or later to enable
        // visual styles.  Otherwise, any window creation will fail.
        INITCOMMONCONTROLSEX InitCtrls;
        InitCtrls.dwSize = sizeof(InitCtrls);
        // Set this to include all the common control classes you want to use
        // in your application.
        InitCtrls.dwICC = ICC_WIN95_CLASSES;
        InitCommonControlsEx(&InitCtrls);

        if (!CWinApp::InitInstance())
            return FALSE; // terminates the application

        // Logger
        CTime	cStartTime;		// Start time of the inventory check
        cStartTime = CTime::GetCurrentTime();
        m_pLogger			= getOcsLogger();
        m_pLogger->setApplication( AfxGetAppName());

        /*****
        *
        * Parse command line
        *
        ****/
        if (!parseCommandLine())
            return FALSE;

        m_pLogger->log( LOG_PRIORITY_DEBUG, _T( "=============================================================================="));
        m_pLogger->log( LOG_PRIORITY_DEBUG, _T( "Starting OCS Inventory NG User Notification Tool on %s."), cStartTime.Format( _T( "%#c")));

        /*****
         *
         *	Checks wether another instance of ocsinventory.exe is
         *	already running.
         *
         ****/

        hMutexOneInstance = ::CreateMutex( NULL, TRUE, _T("OCSNOTIFYUSER-088FA840-B10D-11D3-BC36-006067709674"));
        if ( GetLastError() == ERROR_ALREADY_EXISTS )
        {
            m_nExitCode = OCS_NOTIFY_APP_ALREADY_RUNNING_ERROR;
            m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => already running"));
            return FALSE; // terminates the application
        }

        /*****
         *
         *	Gets Download version
         *
         ****/
        CString csMessage = getVersion();
        if (csMessage == _T( ""))
        {
            m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => Failed to retrieve Notification Tool version from file. Version 0.0.0.1 assumed"));
            csMessage=_T( "0.0.0.1");
        }
        m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => Running OCS Inventory NG Notification Tool Version %s"), csMessage);
        m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => Using OCS Inventory NG FrameWork Version %s"), getFrameworkVersion());

        /*****
         *
         *	Main initinstance block
         *
         ****/
        AfxEnableControlContainer();

        switch (m_uNotifcation)
        {
        case NOTIFY_TYPE_PREINSTALL:
            // Display preinstallation dialogbox
            if (!displayPreinstallDialogBox())
                m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => failed to display preinstall DialogBox"));
            break;
        case NOTIFY_TYPE_POSTINSTALL:
            // Display postinstallation dialogbox
            if (!displayPostinstallDialogBox())
                m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => failed to display postinstall DialogBox"));
            break;
        case NOTIFY_TYPE_MSGBOX:
            // Display standard messagebox
            if (!displayMessageBox())
                m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => failed to display standard MessageBox!"));
            break;
        case NOTIFY_TYPE_ASKTAG:
            // Display standard messagebox
            if (!askTagDialogBox())
                m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => failed to display AskTag DialogBox!"));
            break;
        default:
            m_pLogger->log( LOG_PRIORITY_DEBUG, _T("Notification Tool => wrong notification type!"));
            break;
        }
    }
    catch( CException *pEx)
    {
        m_pLogger->log( LOG_PRIORITY_DEBUG, _T( "Notification Tool => %s"), LookupError( pEx));
        pEx->Delete();
    }

    /*****
     *
     *	Releasing mutex and terminate
     *
     ****/
    if (hMutexOneInstance != NULL)
    {
        ::ReleaseMutex( hMutexOneInstance);
    }
    // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
}