void Debug::Print(const char* text, bool timestamp)
{
	StartSession();

	if (vaultmplog == NULL)
		return;

	if (timestamp)
	{
		char buf[32];
		GetTimeFormat(buf, sizeof(buf), false);
		fprintf(this->vaultmplog, "[%s] ", buf);
	}

	/*
	char* lpMsgBuf;

	if( FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), ( LPTSTR ) &lpMsgBuf, 0, NULL ) )
	{
		fprintf( this->vaultmplog, "[error: %s(0x%x)] ", lpMsgBuf, GetLastError() );
	}
	*/

	fwrite(text, sizeof(char), strlen(text), this->vaultmplog);
	fputc((int) '\n', this->vaultmplog);

	EndSession();
}
void UCreateSessionCallbackProxyAdvanced::OnCreateCompleted(FName SessionName, bool bWasSuccessful)
{
	FOnlineSubsystemBPCallHelperAdvanced Helper(TEXT("CreateSessionCallback"), GEngine->GetWorldFromContextObject(WorldContextObject));
	//Helper.QueryIDFromPlayerController(PlayerControllerWeakPtr.Get());

	if (Helper.OnlineSub != nullptr)
	{
		auto Sessions = Helper.OnlineSub->GetSessionInterface();
		if (Sessions.IsValid())
		{
			Sessions->ClearOnCreateSessionCompleteDelegate_Handle(CreateCompleteDelegateHandle);
			
			if (bWasSuccessful)
			{
				StartCompleteDelegateHandle = Sessions->AddOnStartSessionCompleteDelegate_Handle(StartCompleteDelegate);
				Sessions->StartSession(GameSessionName);

				// OnStartCompleted will get called, nothing more to do now
				return;
			}
		}
	}

	if (!bWasSuccessful)
	{
		OnFailure.Broadcast();
	}
}
Example #3
0
File: weather.c Project: YeLee/code
int main(const int argc, const char* argv[])
{
	ArgInfo arg = {0};
	if ((argc != 2) && (argc != 4)) {
		usage(argv[0]);
		return 2;
	}

	if (!InitProc(&arg, argc, argv + 1)) {
		fprintf(stderr, "Error! Can't Initialization.\n");
		return 1;
	}

	if (argc == 4) {
		printf("%s %s %s的城市代码是:%s\n",
				argv[1], argv[2], argv[3], arg.citycode);
		return 0;
	}

	if (!StartSession(&arg)) {
		fprintf(stderr, "Error! Can't Start Session.\n");
		return 1;
	}

	//Do something
	printf("%s", arg.output);

	EndSession(&arg);
	CleanupProc(&arg, argc);
	return 0;
}
Example #4
0
static void
ChooseSessionFailSafeXtProc(Widget w, XtPointer client_data, 
			    XtPointer callData)
{
    /*
     * Pop down choice of sessions, and start the fail safe session.
     */

    CheckDeleteCancel ();
    CheckBreakLockCancel ();

    XtPopdown (chooseSessionPopup);

    if (session_name)
	XtFree (session_name);

    session_name = XtNewString (FAILSAFE_SESSION_NAME);

    FreeSessionNames (sessionNameCount,
	sessionNamesShort, sessionNamesLong, sessionsLocked);


    /*
     * We don't need to check return value of StartSession in this case,
     * because we are using the default session, and StartSession will
     * not try to lock the session at this time.  It will try to lock
     * it as soon as the user gives the session a name.
     */

    StartSession (session_name,
	True /* Use ~/.xsmstartup if found, else system.xsm */);
}
Example #5
0
void CGameStateRecorder::Enable(bool bEnable, bool bRecording)
{
	m_bRecording = bRecording;
	m_bEnable = bEnable;
	//m_mode = mode;
	if(!bEnable)
		m_mode = GPM_Disabled;

	if(m_bEnable && bRecording)
	{
		gEnv->pGame->GetIGameFramework()->GetIGameplayRecorder()->RegisterListener(this);

		//CActor *pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
		//if(pActor && !pActor->GetSpectatorMode() && pActor->IsPlayer() && ((CPlayer*)pActor)->GetNanoSuit())
			//((CPlayer*)pActor)->GetNanoSuit()->AddListener(this);

	}
	else
	{
		gEnv->pGame->GetIGameFramework()->GetIGameplayRecorder()->UnregisterListener(this);

		//CActor *pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
		//if(pActor && !pActor->GetSpectatorMode() && pActor->IsPlayer() && ((CPlayer*)pActor)->GetNanoSuit())
			//((CPlayer*)pActor)->GetNanoSuit()->RemoveListener(this);
	}
	
	if(m_bEnable)
		StartSession();
}
Example #6
0
void CHexeEngine::MsgRun (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgRun
//
//	Hexe.run {code}

	{
	StartSession(Msg, new CRunSession);
	}
Example #7
0
void CCryptosaurEngine::MsgCheckPasswordSHA1 (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgCheckPasswordSHA1
//
//	Cryptosaur.login_SHA1 {username} {challenge} {response}

	{
	StartSession(Msg, new CUserInfoSession(this, NULL_STR, Msg.dPayload.GetElement(0)));
	}
Example #8
0
void CCryptosaurEngine::MsgLoginUser (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgLoginUser
//
//	Cryptosaur.loginUser {username} {authDesc}

	{
	StartSession(Msg, new CUserInfoSession(this, (pSecurityCtx ? pSecurityCtx->GetSandbox() : NULL_STR), Msg.dPayload.GetElement(0)));
	}
Example #9
0
void CCryptosaurEngine::MsgHasRights (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgHasRights
//
//	Cryptosaur.hasRights {username} {rights}

	{
	StartSession(Msg, new CUserInfoSession(this, (pSecurityCtx ? pSecurityCtx->GetSandbox() : NULL_STR), Msg.dPayload.GetElement(0), Msg.dPayload));
	}
bool SessionManager::StartSessionByCustomIdentify(
		ILiveChatClient* livechat,
		IRequest* request,
		const string& customIdentify
		) {
	char identify[1024];
	sprintf(identify, "%s_%s", CUSTOM_TYPE, customIdentify.c_str());

	return StartSession(livechat, request, identify);
}
bool SessionManager::StartSessionBySeq(
		ILiveChatClient* livechat,
		IRequest* request,
		int seq
		) {

	char identify[1024];
	sprintf(identify, "%s_%d", SEQ_TYPE, seq);

	return StartSession(livechat, request, identify);
}
Example #12
0
EXPORT_C TInt RLayoutManager::Connect()
    {
    const TVersion KMinServerVersion(1, 0, 0);
    _LIT(KLayoutServerFilename, "LayoutMgr");
    const TUid KServerUid3 =
        {
            LAYOUTMGR_UID
        }
        ;	//This was KServerUid2 before
    const TUidType serverUid(KNullUid, KNullUid, KServerUid3);
    const TUint KDefaultMessageSlots = 3;

    return StartSession(KLayoutServerName, KMinServerVersion,
                        KLayoutServerFilename, serverUid, KDefaultMessageSlots);
    }
/*
-------------------------------------------------------------------------------

    Class: -

    Method: E32Main

    Description: 

    Parameters: None

    Return Values: TInt: Symbian error code

    Errors/Exceptions: None

    Status: Draft

-------------------------------------------------------------------------------
*/
GLDEF_C TInt E32Main()
    {
    _LIT( KProcessMsgStart, "New process starting" );
    RDebug::Print( KProcessMsgStart );


    // This starts a new session that get capabilites that is used in 
    // BCDRMCAFCAPS_exe.mmp file.
    TInt r = StartSession();

    _LIT( KProcessMsgEnd, "New process ends" );
    RDebug::Print( KProcessMsgEnd );

    return r;

    }
Example #14
0
//--------------------------------------------------------------------------------------------------
void ecallApp_StartSession
(
    uint32_t  paxCount ///< [IN] number of passengers
)
{
    int32_t  hMinAccuracy = 0;
    int32_t  dirMinAccuracy = 0;

    LoadECallSettings(&hMinAccuracy, &dirMinAccuracy);

    LE_DEBUG("Start eCall session with %d passengers, hMinAccuracy.%d, dirMinAccuracy.%d",
                paxCount,
                hMinAccuracy,
                dirMinAccuracy);

    StartSession(paxCount, hMinAccuracy, dirMinAccuracy);
}
Example #15
0
static void
ChooseSessionLoadXtProc(Widget w, XtPointer client_data, XtPointer callData)
{
    XawListReturnStruct *current;

    CheckDeleteCancel ();
    CheckBreakLockCancel ();

    current = XawListShowCurrent (chooseSessionListWidget);

    if (!current || !current->string || *(current->string) == '\0')
    {
	if (current)
	    XtFree ((char *) current);
#ifdef XKB
	XkbStdBell(XtDisplay(topLevel),XtWindow(topLevel),0,XkbBI_BadValue);
#else
	XBell (XtDisplay (topLevel), 0);
#endif
	return;
    }

    /*
     * Pop down choice of sessions and start the specified session.
     */

    XtPopdown (chooseSessionPopup);

    if (session_name)
	XtFree (session_name);

    session_name = XtNewString (current->string);

    XtFree ((char *) current);

    FreeSessionNames (sessionNameCount,
	sessionNamesShort, sessionNamesLong, sessionsLocked);


    /*
     * Start the session, looking for .XSM-<session name> startup file.
     */

    if (!StartSession (session_name, False))
	UnableToLockSession (session_name);
}
void Debug::PrintSystem()
{
	StartSession();

	FILE* systeminfo = popen("systeminfo", "r");

	if (systeminfo == NULL)
		return;

	char buf[2048];

	while (fgets(buf, sizeof(buf), systeminfo) != NULL)
		fwrite(buf, sizeof(char), strlen(buf), this->vaultmplog);

	pclose(systeminfo);

	EndSession();
}
Example #17
0
bool CChatSelector::ProcessMessage(uint64 sender_id, const wxString& message)
{
	CChatSession* session = GetPageByClientID(sender_id);

	// Try to get the name (core sent it?)
	int separator = message.Find(wxT("|"));
	wxString client_name;
	wxString client_message;
	if (separator != -1) {
		client_name = message.Left(separator);
		client_message = message.Mid(separator+1);
	} else {
		// No need to define client_name. If needed, will be build on tab creation.
		client_message = message;
	}

	bool newtab = !session;

	if ( !session ) {
		// This must be a mesage from a client that is not already chatting
		if (client_name.IsEmpty()) {
			// Core did not send us the name.
			// This must NOT happen.
			// Build a client name based on the ID
			uint32 ip = IP_FROM_GUI_ID(sender_id);
			client_name = CFormat(wxT("IP: %s Port: %u")) % Uint32toStringIP(ip) % PORT_FROM_GUI_ID(sender_id);
		}

		session = StartSession( sender_id, client_name, true );
	}

	// Other client connected after disconnection or a new session
	if ( !session->m_active ) {
		session->m_active = true;

		session->AddText( _("*** Connected to Client ***"), COLOR_RED );
	}

	// Page text is client name
	session->AddText( GetPageText(GetTabByClientID(sender_id)), COLOR_BLUE, false );
	session->AddText( wxT(": ") + client_message, COLOR_BLACK );

	return newtab;
}
Example #18
0
void CHyperionEngine::MsgResizeImage (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgResizeImage
//
//	Hyperion.resizeImage filePath newSize [options]

	{
	//	Get parameters

	CString sFilePath = Msg.dPayload.GetElement(0);
	if (sFilePath.IsEmpty())
		{
		SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, ERR_BAD_PARAMS, Msg);
		return;
		}
		
	DWORD dwSize = (DWORD)Msg.dPayload.GetElement(1);
	if (dwSize == 0)
		{
		SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, ERR_BAD_PARAMS, Msg);
		return;
		}

	//	Generate an ID for the generated file.

	CString sID = strPattern("%s#size=%d", sFilePath, dwSize);

	//	If we have it in the cache, then we're done.

	CDatum dData;
	if (m_Cache.FindEntry(sID, &dData))
		{
		SendMessageReply(MSG_AEON_FILE_DOWNLOAD_DESC, dData, Msg);
		return;
		}

	//	Otherwise, we need to resize the file. Start a session to get the 
	//	original file bits.

	StartSession(Msg, new CResizeImageSession(*this, sFilePath, dwSize, sID, pSecurityCtx));
	}
Example #19
0
bool CChatSelector::SendMessage( const wxString& message, const wxString& client_name, uint64 to_id )
{
	// Dont let the user send empty messages
	// This is also a user-fix for people who mash the enter-key ...
	if ( message.IsEmpty() ) {
		return false;
	}

	if (to_id) {
		// Checks if there's a page with this client, and selects it or creates it
		StartSession(to_id, client_name, true);
	}

	int usedtab = GetSelection();
	// Workaround for a problem with wxNotebook, where an invalid selection is returned
	if (usedtab >= (int)GetPageCount()) {
		usedtab = GetPageCount() - 1;
	}
	if (usedtab == -1) {
		return false;
	}

	CChatSession* ci = (CChatSession*)GetPage( usedtab );

	ci->m_active = true;

	//#warning EC needed here.

	#ifndef CLIENT_GUI
	if (theApp->clientlist->SendChatMessage(ci->m_client_id, message)) {
		ci->AddText( thePrefs::GetUserNick(), COLOR_GREEN, false );
		ci->AddText( wxT(": ") + message, COLOR_BLACK );
	} else {
		ci->AddText( _("*** Connecting to Client ***"), COLOR_RED );
	}
	#endif

	return true;
}
Example #20
0
void CChatSelector::ProcessMessage(CUpDownClient* sender, const CString& message)
{
	sender->IncMessagesReceived();
	CChatItem* ci = GetItemByClient(sender);

	AddLogLine(true, GetResString(IDS_NEWMSG), sender->GetUserName(), ipstr(sender->GetConnectIP()));
	
	bool isNewChatWindow = false;
	if (!ci)
	{
		if ((UINT)GetItemCount() >= thePrefs.GetMsgSessionsMax())
			return;
		ci = StartSession(sender, false);
		isNewChatWindow = true; 
	}
	if (thePrefs.GetIRCAddTimeStamp())
		AddTimeStamp(ci);
	ci->log->AppendKeyWord(sender->GetUserName(), RECV_SOURCE_MSG_COLOR);
	ci->log->AppendText(_T(": "));
	ci->log->AppendText(message + _T("\n"));
	int iTabItem = GetTabByClient(sender);
	if (GetCurSel() == iTabItem && GetParent()->IsWindowVisible())
	{
		// chat window is already visible
		;
	}
	else if (GetCurSel() != iTabItem)
	{
		// chat window is already visible, but tab is not selected
		ci->notify = true;
	}
	else
	{
		ci->notify = true;
        if (isNewChatWindow || thePrefs.GetNotifierOnEveryChatMsg())
			theApp.emuledlg->ShowNotifier(GetResString(IDS_TBN_NEWCHATMSG) + _T(" ") + CString(sender->GetUserName()) + _T(":'") + message + _T("'\n"), TBN_CHAT);
		isNewChatWindow = false;
	}
}
Example #21
0
void CChatSelector::ProcessMessage(CUpDownClient* pSender, const CString &strIncomingMessage)
{
	CString	strMessage = strIncomingMessage;
	int		iCurPos = 0;

	strMessage.MakeLower();

//	Ban spammers
	if ( g_App.m_pPrefs->IsCounterMeasures() &&
		( strMessage.Find(_T("di-emule")) >= 0
		|| strMessage.Find(_T("emule fx")) >= 0
		|| strMessage.Find(_T("zambor")) >= 0
		|| strMessage.Find(_T("fastest emule ever")) >= 0
		|| strMessage.Find(_T("robot from riaa")) >= 0
		|| strMessage.Find(_T("ketamine")) >= 0
		|| strMessage.Find(_T("http://www.chez.com/theworld/")) >= 0
		|| strMessage.Find(_T("http://fullspeed.to/mison")) >= 0 ) )
	{
		AddDebugLogLine(RGB_LOG_DIMMED_TXT _T("Anti-leechermods: Client %s has been banned because of spamming"), pSender->GetClientNameWithSoftware());
		pSender->Ban(BAN_CLIENT_SPAMMING);
		return;
	}

	CString	strResToken, strFilter = g_App.m_pPrefs->GetMessageFilter();

	strFilter.MakeLower();
	for (;;)
	{
		strResToken = strFilter.Tokenize(_T("|"), iCurPos);
		if (strResToken.IsEmpty())
			break;
		if (strMessage.Find(strResToken) >= 0)
		{
			AddDebugLogLine(RGB_LOG_DIMMED_TXT _T("Filtered message '%s' from client %s"), strIncomingMessage, pSender->GetClientNameWithSoftware());
			return;
		}
	}

	CChatItem	*pChatItem = GetItemByClient(pSender);
	bool		bIsNewChatWindow = false;

	if (pChatItem == NULL)
	{
		if (GetItemCount() >= 50)
		{
			AddDebugLogLine(RGB_LOG_WARNING_TXT _T("Instant Messaging: Messages limit reached"));
			return;
		}

		if (g_App.m_pPrefs->GetAcceptMessagesFrom() == 4) //no messages
			return;

		if ((g_App.m_pPrefs->GetAcceptMessagesFrom() == 2) && !pSender->IsFriend()) //only friends
			return;

		if ((g_App.m_pPrefs->GetAcceptMessagesFrom() == 3) && !pSender->IsFriend()) //log non friends
		{
			AddLogLine(false, GetResString(IDS_IM_MSGFROMCHAT) + _T(" %s: %s"), pSender->GetUserName(), strIncomingMessage);
			pSender->SetChatState(MS_NONE);
			return;
		}

		pChatItem = StartSession(pSender);
		if (pChatItem == NULL)
			return;
		bIsNewChatWindow = true;
	}
	COleDateTime	timelog(COleDateTime::GetCurrentTime());

	strMessage.Format(_T("%s (%s): "), pSender->GetUserName(), timelog.Format(_T("%c")));
	pChatItem->m_pLog->AppendText(strMessage, RGB(50, 200, 250));
	pChatItem->m_pLog->AppendText(strIncomingMessage + _T('\n'));

	if (g_App.m_pPrefs->GetAwayState())
	{
		if ((::GetTickCount() - pChatItem->m_pClient->GetAwayMessageResendCount()) > 3000)
		{ //send again only if 3 secs from last away message
			SendAwayMessage(pChatItem);
			pChatItem->m_pClient->SetAwayMessageResendCount(::GetTickCount());
		}
	}

	if ((iCurPos = GetTabByClient(pSender)) != GetCurSel())
		SetItemState(iCurPos, TCIS_HIGHLIGHTED, TCIS_HIGHLIGHTED);
	if (!g_App.m_pPrefs->GetAwayState())
	{
		BOOL	bVisible = ::IsWindowVisible(::GetParent(m_hWnd));

	//	Show statusbar indicator if Messages window isn't active or our application isn't topmost one
		if (!bVisible || (g_App.m_pMDlg->m_hWnd != ::GetForegroundWindow()))
		{
			pChatItem->m_bNotify = true;
		//	Send Notification is required
			if ( ( g_App.m_pPrefs->GetUseChatNotifier() &&
				(bIsNewChatWindow || g_App.m_pPrefs->GetNotifierPopsEveryChatMsg()) ) )
			{
				strMessage.Format(_T("%s %s:'%s'\n"), GetResString(IDS_TBN_NEWCHATMSG), pSender->GetUserName(), strIncomingMessage);
				g_App.m_pMDlg->SendMail(strMessage, true, g_App.m_pPrefs->IsSMTPInfoEnabled());
				g_App.m_pMDlg->ShowNotifier(strMessage, TBN_CHAT, false, true);
			}
		}
	}
}
Example #22
0
extern int main(int argc, char **argv) {
  GOptionContext *goctx;
  char *command;
  GLProtocol *ctx;

  setlocale(LC_CTYPE, "ja_JP.UTF-8");

  AUTHURI = NULL;
  RPCURI = NULL;
  RESTURI = NULL;
  SESSIONID = NULL;
  RPCID = 0;
  USER = NULL;
  PASS = NULL;
#ifdef USE_SSL
  CERTFILE = NULL;
  KEYFILE = NULL;
  KEYPASS = NULL;
  CAFILE = NULL;
#endif

  goctx = g_option_context_new("");
  g_option_context_add_main_entries(goctx, entries, NULL);
  g_option_context_parse(goctx, &argc, &argv, NULL);

  if (argc < 2) {
    PrintArgError();
    exit(1);
  }

  command = argv[1];

  InitTempDir();
  ctx = InitProtocol(AUTHURI, USER, PASS);
  if (RPCURI != NULL) {
    GLP_SetRPCURI(ctx, RPCURI);
  }
  if (RESTURI != NULL) {
    GLP_SetRESTURI(ctx, RESTURI);
  }
  if (SESSIONID != NULL) {
    GLP_SetSessionID(ctx, SESSIONID);
  }
  if (RPCID != 0) {
    GLP_SetRPCID(ctx, RPCID);
  }
#ifdef USE_SSL
  if (CERTFILE != NULL && KEYFILE != NULL && KEYPASS != NULL &&
      CAFILE != NULL) {
    GLP_SetSSL(ctx, CERTFILE, KEYFILE, KEYPASS, CAFILE);
  }
#endif

  if (!strcmp(command, "start_session")) {
    StartSession(ctx);
  } else if (!strcmp(command, "get_window")) {
    GetWindow(ctx);
  } else if (!strcmp(command, "send_event")) {
    if (argc < 3) {
      fprintf(stderr, "start_session need param.json\n");
      exit(1);
    }
    SendEvent(ctx, argv[2]);
  } else if (!strcmp(command, "end_session")) {
    EndSession(ctx);
  } else if (!strcmp(command, "list_downloads")) {
    ListDownloads(ctx);
  } else if (!strcmp(command, "get_message")) {
    GetMessage(ctx);
  } else {
    PrintArgError();
    exit(1);
  }
  FinalProtocol(ctx);
  return 0;
}
Example #23
0
File: Game.cpp Project: Sumez/Minos
Game::Game(GraphicsAdapter* graphics, AudioAdapter* audio, InputHandler* input) {
	_graphics = graphics;
	_audio = audio;
	_input = input;

	_mainMenu = new MainMenu(graphics, audio, input);
	_mainMenu->Add(new MenuItem("Begin game", [this]() -> void { _activeMenus.push_back(_gameTypeMenu); 	}));

	_mainMenu->Add(new MenuItem("Configuration", [this]() -> void {
		_activeMenus.push_back(_configMenu);
	}));
	_mainMenu->Add(new MenuItem("Replays", [this]() -> void {
		_activeMenus.push_back(_replayMenu);
	}));
	_mainMenu->Add(new MenuItem("Exit", [this]() -> void { Exiting = true; }));

	_gameTypeMenu = new Menu(_graphics, _audio, _input);
	_gameTypeMenu->Add(new MenuItem("Master", [this]() -> void { StartSession(Settings::Master); }));
	_gameTypeMenu->Add(new MenuItem("Old School", [this]() -> void { StartSession(Settings::OldSchool); }));
	_gameTypeMenu->Add(new MenuItem("Death", [this]() -> void { StartSession(Settings::Death); }));
	_gameTypeMenu->Add(new MenuItem("Back", [this]() -> void { CloseMenu(); }));
	
	_configMenu = new Menu(_graphics, _audio, _input);
	_configMenu->Add(new MenuItem("Controls", [this]() -> void {
		_activeMenus.push_back(_keyConfigMenu);
	}));
	_configMenu->Add(new MenuItem("Back", [this]() -> void { CloseMenu(); }));

	_replayMenu = new Menu(_graphics, _audio, _input);
	// TODO: Move to separate file, and only init when menu is displayed
	_replays = Replay::GetReplays(); // TODO: static list of replay or Delete replays when refreshing
	int replaySize = _replays.size();
	for (int i = 0; i < replaySize; i++) {
		ReplayHeader* replayHeader = &_replays[i];
		_replayMenu->Add(new MenuItem("A replay", [=]() -> void {
			if (LoadedState != Loaded) return;
			Replay* replay = new Replay(replayHeader->Filename); // TODO: Delete replay when done playing
			auto* newSession = new Session(_graphics, _audio, _input);
			newSession->Init(Settings::Master, replay); //TODO: Get settings from replay
			_activeSessions.push_back(newSession);
			while (_activeMenus.size()) _activeMenus.erase(_activeMenus.begin());
		}));
	}
	_replayMenu->Add(new MenuItem("Back", [this]() -> void { CloseMenu(); }));

	_keyConfigMenu = new ControlConfigMenu(_graphics, _audio, _input);
	_keyConfigMenu->Style = Menu::Small;
	_keyConfigMenu->Add(new MenuItem("Back", [this]() -> void { CloseMenu(); }));

	_ingameMenu = new Menu(_graphics, _audio, _input);
	_ingameMenu->Add(new MenuItem("Resume game", [this]() -> void {
		CloseMenu();
	}));
	_ingameMenu->Add(new MenuItem("Configuration", [this]() -> void {
		_activeMenus.push_back(_keyConfigMenu);
	}));
	_ingameMenu->Add(new MenuItem("Quit game", [this]() -> void {
		CloseMenu();
		_activeMenus.push_back(_mainMenu);
		delete _activeSessions[_activeSessions.size() - 1];
		_activeSessions.pop_back();
	}));

	_activeMenus.push_back(_mainMenu);
}
void ArpRemoteTerminal::MessageReceived(BMessage *message)
{
	ArpD(cdb << ADH << "ArpRemoteTerminal::MessageReceived: " << *message << endl);
	switch( message->what ) {
	
		case TERM_XFER_TEXT_MSG: {
#if 1
			const ichar* txt = NULL;
			long len=0;
			int32 idx=0;
			while( message->FindData("text", B_ASCII_TYPE, idx,
									 (const void**)&txt, &len) == B_NO_ERROR ) {
				if( txt && len > 0 ) {
					Emulator().EmulateToTTY(txt,len);
				}
				idx++;
			}
			message->SendReply(B_NO_REPLY);
#else
			int32 recpos = 0;
			BMessage* curmsg = Window()->DetachCurrentMessage();
			BMessageQueue* queue = Window()->MessageQueue();
			while( curmsg ) {
				ichar* txt = NULL;
				long len=0;
				int32 idx=0;
				while( curmsg->FindData("text", B_ASCII_TYPE, idx,
									  &txt, &len) == B_NO_ERROR ) {
					if( txt ) {
						if( recpos + len > sizeof(receiveBuffer) ) {
							if( recpos > 0 ) {
								Emulator().EmulateToTTY(&receiveBuffer[0],recpos);
								recpos = 0;
							}
						}
						if( len > sizeof(receiveBuffer) ) {
							Emulator().EmulateToTTY(txt,len);
						} else {
							memcpy(&receiveBuffer[recpos],txt,len);
							recpos += len;
						}
					}
					idx++;
				}
				delete curmsg;
				curmsg = NULL;
				if( queue ) {
					curmsg = queue->FindMessage((int32)0);
					if( curmsg &&
						curmsg->what == TERM_XFER_TEXT_MSG ) {
						curmsg = queue->NextMessage();
					} else curmsg = NULL;
				}
			}
			if( recpos > 0 ) {
				Emulator().EmulateToTTY(&receiveBuffer[0],recpos);
			}
			return;
#endif
		} break;
		
		case TERM_RESET_MSG: {
			bool hard = false;
			if( message->FindBool("hard", &hard) != B_OK ) hard = false;
			Emulator().Reset(hard);
			TermClean();
			// HACK: The emulator often changes the terminal's mode
			// flags after calling its reset, leaving any active
			// settings view with incorrect settings.  Until we can
			// do better at tracking state changes, for this situation
			// send another update to the settings view.
			if( HaveWatchers() ) {
				BMessage config;
				if( GetConfiguration(&config) == B_NO_ERROR ) {
					ArpD(cdb << ADH << "Reporting change: " << config << endl);
					ReportChange(&config);
				}
			}
		} break;
		
		case TERM_START_SESSION_MSG: {
			StartSession();
			TermClean();
			Owner().SendMessage(message);
		} break;
		
		case TERM_END_SESSION_MSG: {
			EndSession();
			TermClean();
			Owner().SendMessage(message);
		} break;
		
		case TERM_REQUEST_STATUS_MSG: {
			int32 rows,cols;
			TermGetSize(&rows,&cols);
			SendSizeMsg(rows,cols);
			SendEmulatorsMsg();
		} break;
		
		case TERM_WINDOW_SIZE_MSG: {
			int32 rows,cols;
			TermGetFixedSize(&rows,&cols);
			message->FindInt32("rows",&rows);
			message->FindInt32("columns",&cols);
			TermSetFixedSize(rows,cols);
		} break;
		
		case TERM_SELECT_EMULATION_MSG: {
			BMenuItem* item = NULL;
			if( message->FindPointer("source",(void**)&item) ) item = NULL;
			BMenu* menu = NULL;
			if( item ) menu = item->Menu();
			int32 num=0;
			type_code type;
			if( !message->GetInfo("name",&type,&num) ) {
				for( int i=0; i<num; i++ ) {
					const char* str;
					if( !message->FindString("name",i,&str) ) {
						delete SetEmulator(str);
						if( !IsDefaultEmulator() ) {
							if( menu ) CheckEmulationMenu(menu);
							return;
						}
					}
				}
			}
			if( menu ) CheckEmulationMenu(menu);
		} break;
		
		case ARP_PUT_CONFIGURATION_MSG: {
			BMessage config;
			if( message->FindMessage("settings",&config) == B_NO_ERROR ) {
				PutConfiguration(&config);
			} else {
				inherited::MessageReceived(message);
			}
		} break;
		
		case TERM_ADD_WATCHER_MSG: {
			BMessenger w;
			if( message->FindMessenger("watch",&w) == B_NO_ERROR ) {
				AddWatcher(w);
				BMessage config;
				if( GetConfiguration(&config) == B_NO_ERROR ) {
					ReportChange(&config, &w);
				}
			} else {
				inherited::MessageReceived(message);
			}
		} break;
		
		case TERM_REM_WATCHER_MSG: {
			BMessenger w;
			if( message->FindMessenger("watch",&w) == B_NO_ERROR ) {
				RemWatcher(w);
			} else {
				inherited::MessageReceived(message);
			}
		} break;
		
		default:
			inherited::MessageReceived(message);
	}
}
Example #25
0
File: xsm.c Project: aosm/X11
/*
 * Main program
 */
int
main(int argc, char *argv[])
{
    char	*p;
    char 	errormsg[256];
    static	char environment_name[] = "SESSION_MANAGER";
    int		success, found_command_line_name, i;

    Argc = argc;
    Argv = argv;

    for (i = 1; i < argc; i++)
    {
	if (argv[i][0] == '-')
	{
	    switch (argv[i][1])
	    {
	    case 'd':					/* -display */
		if (++i >= argc) goto usage;
		cmd_line_display = (char *) XtNewString (argv[i]);
		continue;

	    case 's':					/* -session */
		if (++i >= argc) goto usage;
		session_name = XtNewString (argv[i]);
		continue;

	    case 'v':					/* -verbose */
		verbose = 1;
		continue;
	    }
	}

    usage:
	fprintf (stderr,
	 "usage: xsm [-display display] [-session session_name] [-verbose]\n");
	exit (1);
    }

    topLevel = XtVaAppInitialize (&appContext, "XSm", NULL, 0,
	&argc, argv, NULL,
	XtNmappedWhenManaged, False,
	XtNwindowRole, "xsm main window",
	NULL);
	
    wmStateAtom = XInternAtom (
	XtDisplay (topLevel), "WM_STATE", False);
    wmDeleteAtom = XInternAtom (
	XtDisplay (topLevel), "WM_DELETE_WINDOW", False);

    register_signals (appContext);


    /*
     * Install an IO error handler.  For an explanation,
     * see the comments for InstallIOErrorHandler().
     */

    InstallIOErrorHandler ();


    /*
     * Init SM lib
     */

    if (!SmsInitialize ("SAMPLE-SM", "1.0",
	NewClientProc, NULL,
	HostBasedAuthProc, 256, errormsg))
    {
	fprintf (stderr, "%s\n", errormsg);
	exit (1);
    }

    if (!IceListenForConnections (&numTransports, &listenObjs,
	256, errormsg))
    {
	fprintf (stderr, "%s\n", errormsg);
	exit (1);
    }

    atexit(CloseListeners);

    if (!SetAuthentication (numTransports, listenObjs, &authDataEntries))
    {
	fprintf (stderr, "Could not set authorization\n");
	exit (1);
    }

    InitWatchProcs (appContext);

    for (i = 0; i < numTransports; i++)
    {
	XtAppAddInput (appContext,
	    IceGetListenConnectionNumber (listenObjs[i]),
	    (XtPointer) XtInputReadMask,
	    NewConnectionXtProc, (XtPointer) listenObjs[i]);
    }

    /* the sizeof includes the \0, so we don't need to count the '=' */
    networkIds = IceComposeNetworkIdList (numTransports, listenObjs);
    p = (char *) XtMalloc((sizeof environment_name) + strlen(networkIds) + 1);
    if(!p) nomem();
    sprintf(p, "%s=%s", environment_name, networkIds);
    putenv(p);

    if (cmd_line_display)
    {
	/*
	 * If a display was passed on the command line, set the DISPLAY
	 * environment in this process so all applications started by
	 * the session manager will run on the specified display.
	 */

	p = (char *) XtMalloc(8 + strlen(cmd_line_display) + 1);
	sprintf(p, "DISPLAY=%s", cmd_line_display);
	putenv(p);
    }

    if (verbose)
	printf ("setenv %s %s\n", environment_name, networkIds);

    create_choose_session_popup ();
    create_main_window ();
    create_client_info_popup ();
    create_save_popup ();
    create_log_popup ();


    /*
     * Initalize all lists
     */

    RunningList = ListInit();
    if(!RunningList) nomem();

    PendingList = ListInit();
    if(!PendingList) nomem();

    RestartAnywayList = ListInit();
    if(!RestartAnywayList) nomem();

    RestartImmedList = ListInit();
    if(!RestartImmedList) nomem();

    WaitForSaveDoneList = ListInit();
    if (!WaitForSaveDoneList) nomem();

    InitialSaveList = ListInit();
    if (!InitialSaveList) nomem();

    FailedSaveList = ListInit();
    if (!FailedSaveList) nomem();

    WaitForInteractList = ListInit();
    if (!WaitForInteractList) nomem();

    WaitForPhase2List = ListInit();
    if (!WaitForPhase2List) nomem();


    /*
     * Get list of session names.  If a session name was found on the
     * command line, and it is in the list of session names we got, then
     * use that session name.  If there were no session names found, then
     * use the default session name.  Otherwise, present a list of session
     * names for the user to choose from.
     */

    success = GetSessionNames (&sessionNameCount,
	&sessionNamesShort, &sessionNamesLong, &sessionsLocked);

    found_command_line_name = 0;
    if (success && session_name)
    {
	for (i = 0; i < sessionNameCount; i++)
	    if (strcmp (session_name, sessionNamesShort[i]) == 0)
	    {
		found_command_line_name = 1;

		if (sessionsLocked[i])
		{
		    fprintf (stderr, "Session '%s' is locked\n", session_name);
		    exit (1);
		}

		break;
	    }
    }

    if (!success || found_command_line_name)
    {
	FreeSessionNames (sessionNameCount,
	    sessionNamesShort, sessionNamesLong, sessionsLocked);

	if (!found_command_line_name)
	    session_name = XtNewString (DEFAULT_SESSION_NAME);

    	if (!StartSession (session_name, !found_command_line_name))
	    UnableToLockSession (session_name);
    }
    else
    {
	ChooseSession ();
    }
    

    /*
     * Main loop
     */

    XtAppMainLoop (appContext);
    exit(0);
}
Example #26
0
void CExarchEngine::MsgAddModule (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgAddModule
//
//	Exarch.addModule [{machineName}] {filePath} [{debug}]

	{
	CSmartLock Lock(m_cs);
	CString sError;

	//	Must be admin service

	if (!ValidateSandboxAdmin(Msg, pSecurityCtx))
		return;

	//	Get parameters

	bool bHasMachineName = (Msg.dPayload.GetCount() >= 2 && !strEndsWith(strToLower(Msg.dPayload.GetElement(0)), STR_EXE_SUFFIX));
	int iArg = 0;
	CString sMachineName = (bHasMachineName ? Msg.dPayload.GetElement(iArg++) : NULL_STR);
	CString sModuleFilePath = Msg.dPayload.GetElement(iArg++);
	CDatum dDebug = Msg.dPayload.GetElement(iArg++);

	//	If we have a machine name, try to parse it in case the user gave us
	//	a partial name.

	if (bHasMachineName)
		{
		if (!ParseMachineName(sMachineName, &sMachineName))
			{
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, strPattern("Unknown machine: %s", sMachineName), Msg);
			return;
			}
		}

	//	If this is not for our machine, then we need to send a message to the
	//	other machine.

	if (!sMachineName.IsEmpty()
			&& !strEqualsNoCase(GetMachineName(), sMachineName))
		{
		CString sAddress = GenerateMachineAddress(sMachineName, ADDRESS_EXARCH_COMMAND);
		if (sAddress.IsEmpty())
			{
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, strPattern("Unable to generate address for: %s", sMachineName), Msg);
			return;
			}

		StartSession(Msg, new CAddModuleSession(this, sAddress, sModuleFilePath));
		}

	//	Otherwise, we add a local module

	else
		{
		//	Add the module

		CString sModuleName;
		if (!AddModule(sModuleFilePath, strEqualsNoCase(dDebug, FIELD_DEBUG), &sModuleName, &sError))
			{
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, sError, Msg);
			return;
			}

		//	Add it to our list of modules

		CComplexArray *pModuleList = new CComplexArray(m_dMachineConfig.GetElement(FIELD_MODULES));
		pModuleList->Append(CDatum(sModuleName));

		CComplexStruct *pConfig = new CComplexStruct(m_dMachineConfig);
		pConfig->SetElement(FIELD_MODULES, CDatum(pModuleList));
		m_dMachineConfig = CDatum(pConfig);

		//	Save it

		WriteConfig();

		//	Done

		SendMessageReply(MSG_OK, CDatum(), Msg);
		}
	}
Example #27
0
void CChatSelector::ProcessMessage(CUpDownClient* sender, const CString& message)
{
	sender->IncMessagesReceived();

	CString strMessage(message);
	strMessage.MakeLower();
	CString resToken;
	int curPos = 0;
	resToken = thePrefs.GetMessageFilter().Tokenize(_T("|"), curPos);
	while (!resToken.IsEmpty())
	{
		resToken.Trim();
		if (strMessage.Find(resToken.MakeLower()) > -1)
			return;
		resToken = thePrefs.GetMessageFilter().Tokenize(_T("|"), curPos);
	}

	CChatItem* ci = GetItemByClient(sender);

	// advanced spamfilter check
	if (IsSpam(strMessage, sender))
	{
		if (!sender->IsSpammer()){
			if (thePrefs.GetVerbose())
				AddDebugLogLine(false, _T("'%s' has been marked as spammer"), sender->GetUserName());
		}
		sender->SetSpammer(true);
		if (ci)
			EndSession(sender);
		return;
	}

	bool isNewChatWindow = false;
	if (!ci)
	{
		if (GetItemCount() >= thePrefs.GetMsgSessionsMax())
			return;
		ci = StartSession(sender, false);
		isNewChatWindow = true; 
	}
//==>timestamp in chatwindow [shadow2004]
	if (thePrefs.GetIRCAddTimestamp())
		AddTimeStamp(ci);
//<==timestamp in chatwindow [shadow2004]
	ci->log->AppendKeyWord(sender->GetUserName(), RGB(50,200,250));
	ci->log->AppendText(_T(": "));
	ci->log->AppendText(message + _T("\n"));
	int iTabItem = GetTabByClient(sender);
	if (GetCurSel() == iTabItem && GetParent()->IsWindowVisible())
	{
		// chat window is already visible
		;
	}
	else if (GetCurSel() != iTabItem)
	{
		// chat window is already visible, but tab is not selected
		ci->notify = true;
	}
	else
	{
		ci->notify = true;
        if (isNewChatWindow || thePrefs.GetNotifierPopsEveryChatMsg())
			theApp.emuledlg->ShowNotifier(GetResString(IDS_TBN_NEWCHATMSG) + _T(" ") + CString(sender->GetUserName()) + _T(":'") + message + _T("'\n"), TBN_CHAT);
		isNewChatWindow = false;
	}
}
Example #28
0
int
main(int argc, char **argv, char **envp)
{
	struct Session session;
	time_t	t1, t2;

	int tmp = 0;

	if(RegisterHandlers() == -1)
	{
		fprintf(stderr, "[!] Cannot register signal handlers, aborting\n");
		goto cleanup;
	}
	
	InitSession(&session, envp, argv);

	if(ParseArguments(argc, argv, &session) == -1)
	{
		PrintHelp(argv[0]);
		goto cleanup;
	}

	if(OpenLogFile(&session) == -1)
	{
		fprintf(stderr, "[!] Cannot open %s for logging, aborting\n",
			session.logfilename);

		goto cleanup;
	}

	if(PrepareArgv(&session) == -1)
	{
		fprintf(stderr, "[!] Cannot parse arguments\n");
		goto cleanup;
	}
	
	if(InitFuzzingStrings(&session) == -1)
	{
		fprintf(stderr, "[!] Error initializing fuzzing variables\n");
		goto cleanup;
	}

	switch(session.mode)
	{
		/* Smart mode read the file structure from a file */ 
		case MODE_SMART:
		{
			fprintf(stdout, "[%%] Reading headers structure from %s\n",
			session.headers);

			session.headercount = Extract_DataFields(&session);
			break;
		}
		/* ASCII mode read a file and tries to get the right file structure =) */
		case MODE_ASCII:
		{
			fprintf(stdout, "[%%] Reading ASCII structure from %s\n",
				session.input);
			
			session.headercount = Extract_ASCII_Structure(&session);
			break;
		}
	}

	if((session.mode == MODE_ASCII) || (session.mode == MODE_SMART))
	{
		if(!session.headercount)
		{
			fprintf(stderr, "[!] Error loading Offsets from input file\n");
			goto cleanup;
		}

		session.range.low   = 0;
		session.range.high  = session.headercount;
		
		fprintf(stdout, "[%%] Loaded %d fields in headers\n",
			session.headercount);
	}

	tmp = CountFuzzingStrings(&session);
	
	fprintf(stdout, "[%%] Loaded %d fuzzing variables\n", tmp);
	fprintf(stdout, "[%%] Fuzzing from %d to %d\n",	session.range.low,
		session.range.high);
	
	if(session.mode == MODE_BRUTE)
	{
		session.byte = session.range.low;
		tmp         *= session.range.high - session.range.low + 1;
	}
	else
	{
		session.curfield = session.d;
		session.byte     = session.curfield->offset;
		tmp             *= session.headercount;
	}

	PrintLogHeader(&session);

	fprintf(stdout, "[%%] Number of files to be generated %d\n", tmp);
	fprintf(stdout, "[%%] Proceding with fuzzing\n");

	time(&t1);
	StartSession(&session);
	time(&t2);

	fprintf(stdout, "[%%] Time elapsed %f\n", difftime(t2, t1));
	fprintf(stdout, "[%%] Number of succesful executions %d\n", session.exec);
	fprintf(stdout, "[%%] Skipped executions due to fuzzing string size %d\n", session.skipped);
	fprintf(stdout, "[%%] Number of \"bugs\" found: %d\n", session.bugs);
	
	/* Cleanup Resources */
	cleanup:
	{
		FreeFuzzingList(session.f);
		FreeMaps(session.maps);
		CloseLogFile(&session);
	}
	
	return 0;
}
Example #29
0
// Deal with input/output from/to the client (if any)
void Webserver::Spin()
{
	if (webserverActive)
	{
		uint32_t ip;
		size_t length;
		uint32_t fragment;
		const char* request = network->GetRequest(ip, length, fragment);
		if (request != nullptr)
		{
			if (reprap.Debug(moduleWebserver))
			{
				platform->MessageF(HOST_MESSAGE, "Request: %s fragment %u\n", request, fragment);
			}

			uint32_t fragNum = fragment & ~lastFragmentFlag;
			if (fragNum == 0)
			{
				HttpSession *session = StartSession(ip);
				if (session == nullptr)
				{
					network->SendReply(ip, 400, "Too many sessions");
				}
				else
				{
					// First fragment, so parse the request
					ResetState();
					const char *error = nullptr;
					bool finished = false;
					while (!finished && length != 0)
					{
						finished = CharFromClient(*request++, error);
						--length;
					}

					if (!finished)
					{
						error = "Incomplete command";
					}

					if (error != nullptr)
					{
						network->SendReply(ip, 400, error);
					}
					else
					{
						ProcessFirstFragment(*session, clientMessage, (fragment & lastFragmentFlag) != 0);
					}
				}
			}
			else
			{
				HttpSession *session = FindSession(ip);
				if (session != nullptr)
				{
					ProcessUploadFragment(*session, request, length, fragment);
				}
				else
				{
					// Discard the message
					network->DiscardMessage();
					platform->MessageF(DEBUG_MESSAGE, "session not found, fragment=%u\n", fragment);
				}
			}
		}
	}
	CheckSessions();
	platform->ClassReport(longWait);
}
Example #30
0
nsresult ProbeManager::StartSession()
{
  return StartSession(mAllProbes);
}