Example #1
0
MyServer::~MyServer()
{
    Disconnect();
}
Example #2
0
void ConsoleSocket::OnRead()
{
    uint32 readlen = (uint32)readBuffer.GetSize();
    uint32 len;
    char* p;
    if ((readlen + m_pBufferPos) >= m_pBufferLen)
    {
        Disconnect();
        return;
    }

    readBuffer.Read((uint8*)&m_pBuffer[m_pBufferPos], readlen);
    m_pBufferPos += readlen;

    // let's look for any newline bytes.
    p = strchr(m_pBuffer, '\n');
    while (p != NULL)
    {
        // windows is stupid. :P
        len = (uint32)((p + 1) - m_pBuffer);
        if (*(p - 1) == '\r')
            *(p - 1) = '\0';

        *p = '\0';

        // handle the command
        if (*m_pBuffer != '\0')
        {
            switch (m_state)
            {
                case STATE_USER:
                    m_username = string(m_pBuffer);
                    m_pConsole->Write("password: "******"\r\nAttempting to authenticate. Please wait.\r\n");
                    m_state = STATE_WAITING;

                    m_requestNo = ConsoleAuthMgr::getSingleton().GenerateRequestId();
                    ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, this);

                    TestConsoleLogin(m_username, m_password, m_requestNo);
                    break;

                case STATE_LOGGED:
                    if (!strnicmp(m_pBuffer, "quit", 4))
                    {
                        Disconnect();
                        break;
                    }

                    HandleConsoleInput(m_pConsole, m_pBuffer);
                    break;
            }
        }

        // move the bytes back
        if (len == m_pBufferPos)
        {
            m_pBuffer[0] = '\0';
            m_pBufferPos = 0;
        }
        else
        {
            memcpy(m_pBuffer, &m_pBuffer[len], m_pBufferPos - len);
            m_pBufferPos -= len;
        }

        p = strchr(m_pBuffer, '\n');
    }
}
// ---------------------------------------------------------
// CT_LbsClientPosTp178::CloseTest
// Always called after the test, even if the test leaves
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CT_LbsClientPosTp178::CloseTest()
{
    ClosePositioner();
    Disconnect();
}
Example #4
0
//-----------------------------------------------------------------------------
// Name: empty()
// Desc: 
//-----------------------------------------------------------------------------
void CArmyWar::ReadPackets(void)
{
	char data[1400];
	struct sockaddr address;

	clientData *clList;

	int type;
	int ind;
	int local;
	int ret;

	char name[50];

	DreamMessage mes;
	mes.Init(data, sizeof(data));

	while(ret = networkClient->GetPacket(mes.data, &address))
	{
		mes.SetSize(ret);
		mes.BeginReading();

		type = mes.ReadByte();

		switch(type)
		{
		case DREAMSOCK_MES_ADDCLIENT:
			local	= mes.ReadByte();
			ind		= mes.ReadByte();
			strcpy(name, mes.ReadString());

			AddClient(local, ind, name);
			break;

		case DREAMSOCK_MES_REMOVECLIENT:
			ind = mes.ReadByte();

			LogString("Got removeclient %d message", ind);

			RemoveClient(ind);

			break;

		case USER_MES_FRAME:
			// Skip sequences
			mes.ReadShort();
			mes.ReadShort();

			for(clList = clientList; clList != NULL; clList = clList->next)
			{
//				LogString("Reading DELTAFRAME for client %d", clList->index);
				ReadDeltaMoveCommand(&mes, clList);
			}

			break;

		case USER_MES_NONDELTAFRAME:
			// Skip sequences
			mes.ReadShort();
			mes.ReadShort();

			clList = clientList;

			for(clList = clientList; clList != NULL; clList = clList->next)
			{
				LogString("Reading NONDELTAFRAME for client %d", clList->index);
				ReadMoveCommand(&mes, clList);
			}

			break;

		case USER_MES_SERVEREXIT:
			MessageBox(NULL, "Server disconnected", "Info", MB_OK);
			Disconnect();
			break;

		}
	}
}
void CUser::SelectCharacter(Packet & pkt)
{
	Packet result(WIZ_SEL_CHAR);
	uint8 bResult, bInit;

	if (isBanned())
	{
		Disconnect();
		return;
	}

	pkt >> bResult >> bInit;
	result << bResult;

	if (bResult == 0 || !GetZoneID()) 
		goto fail_return;

	m_pMap = g_pMain->GetZoneByID(GetZoneID());
	if (GetMap() == nullptr)
		goto fail_return;

	if (g_pMain->m_nServerNo != GetMap()->m_nServerNo)
	{
		_ZONE_SERVERINFO *pInfo = g_pMain->m_ServerArray.GetData(GetMap()->m_nServerNo);
		if (pInfo == nullptr) 
			goto fail_return;

		SendServerChange(pInfo->strServerIP, bInit);
		return;
	}

	if (g_pMain->m_byBattleOpen == NO_BATTLE && GetFame() == COMMAND_CAPTAIN)
		m_bFame = CHIEF;

	// Disallow players from relogging in the opposite nation's home zone when an invasion's not running.
	if (((GetZoneID() != GetNation() && GetZoneID() <= ZONE_ELMORAD && !g_pMain->m_byBattleOpen)
		// also disallow players from logging back into war zones that aren't currently active...
			|| (GetMap()->isWarZone() && (GetZoneID() - ZONE_BATTLE_BASE) != g_pMain->m_byBattleZone)
			// Chaos, bdw and juraid montuain
			|| isInTempleEventZone()
			// Ronark Land, Ardream, RLB, Bifrost, Krowaz Dominion.
			|| (g_pMain->m_byBattleOpen && (GetZoneID() == ZONE_RONARK_LAND 
			|| GetZoneID() == ZONE_ARDREAM 
			|| GetZoneID() == ZONE_RONARK_LAND_BASE
			|| GetZoneID() == ZONE_BIFROST
			|| GetZoneID() == ZONE_KROWAZ_DOMINION)) && !isGM()))
	{
		NativeZoneReturn();
		Disconnect();
		return;
	}

	SetLogInInfoToDB(bInit);

	result << GetZoneID() << GetSPosX() << GetSPosZ() << GetSPosY() << g_pMain->m_byOldVictory;
	m_bSelectedCharacter = true;
	Send(&result);

	SetUserAbility(false);

	if (GetLevel() > MAX_LEVEL) 
	{
		Disconnect();
		return;
	}

	m_iMaxExp = g_pMain->GetExpByLevel(GetLevel());
	SetRegion(GetNewRegionX(), GetNewRegionZ());

	if (GetClanID() == -1)
	{
		SetClanID(0);
		m_bFame = 0;
		return;
	}
	else if (GetClanID() != 0
		&& GetZoneID() > 2)
	{
		result.Initialize(WIZ_KNIGHTS_PROCESS);
		result << uint8(KNIGHTS_LIST_REQ) << GetClanID();
		g_pMain->AddDatabaseRequest(result, this);
	}
	return;

fail_return:
	Send(&result);
}
// ---------------------------------------------------------
// CT_LbsClientPosTp261::StartL
//
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CT_LbsClientPosTp261::StartL()
    {
    _LIT(KService1, "Service1");
    _LIT(KService2, "Service2");
    _LIT(KService3, "Service3");

    _LIT(KContact1, "Contact1");
    _LIT(KContact2, "Contact2");
    _LIT(KContact3, "Contact3");

    CRequestor* serviceId1 = 
		CRequestor::NewL(CRequestor::ERequestorService, CRequestor::EFormatApplication, 
                    KService1);

    CRequestor* serviceId2 = 
        CRequestor::NewL(CRequestor::ERequestorService, CRequestor::EFormatApplication, 
                    KService2);

    CRequestor* serviceId3 = 
        CRequestor::NewL(CRequestor::ERequestorService, CRequestor::EFormatApplication, 
                    KService3);

    CRequestor* contactId1 = 
        CRequestor::NewL(CRequestor::ERequestorContact, CRequestor::EFormatTelephone, 
                    KContact1);

    CRequestor* contactId2 = 
        CRequestor::NewL(CRequestor::ERequestorContact, CRequestor::EFormatUrl, 
                    KContact2);

    CRequestor* contactId3 = 
        CRequestor::NewL(CRequestor::ERequestorContact, CRequestor::EFormatMail, 
                    KContact3);

    RRequestorStack stack = RRequestorStack();
    CleanupStack::PushL(TCleanupItem(CleanOp ,&stack));

    CleanupStack::PushL(serviceId1);
    CleanupStack::PushL(serviceId2);
    CleanupStack::PushL(serviceId3);
    CleanupStack::PushL(contactId1);
    CleanupStack::PushL(contactId2);
    CleanupStack::PushL(contactId3);
    
    ConnectL();
    OpenPositioner();
    
    stack.Append(serviceId1);
    stack.Append(contactId1);
    stack.Append(contactId2);
    stack.Append(serviceId2);
    stack.Append(contactId3);
    stack.Append(serviceId3);

    CleanupStack::Pop(contactId3);
    CleanupStack::Pop(contactId2);
    CleanupStack::Pop(contactId1);
    CleanupStack::Pop(serviceId3);
    CleanupStack::Pop(serviceId2);
    CleanupStack::Pop(serviceId1);

    TInt err = iPositioner.SetRequestor(stack);
    if (err != KErrNone)
    	{
    	_LIT(KErrorAndLeave, "Problems setting requestorstack");
    	LogErrorAndLeaveL(KErrorAndLeave);
    	}
    	
    const TInt KPosBufFlatExpandSize = 100;
    
    //ExternalizeL
    CBufFlat* bufFlat = CBufFlat::NewL(KPosBufFlatExpandSize);
    CleanupStack::PushL(bufFlat);
    
    RBufWriteStream stream(*bufFlat);
    CleanupClosePushL(stream);        
    stack.ExternalizeL(stream);
    
    TPtr8 dataPtr((TUint8*)NULL, 0);
    dataPtr.Set(bufFlat->Ptr(0));    

    CleanupStack::PopAndDestroy(&stream);                

    HBufC8* tempBuf = HBufC8::NewLC(bufFlat->Size());
    TPtr8 ptr = tempBuf->Des();
    ptr = dataPtr;
    
    //Internalize
    bufFlat->InsertL(0, ptr);
    
    RBufReadStream rstream(*bufFlat);
    CleanupClosePushL(rstream);
    
    RRequestorStack stack2 = RRequestorStack();
    CleanupStack::PushL(TCleanupItem(CleanOp ,&stack2));

    stack2.InternalizeL(rstream);
    
    // Verify the requestor stack
    VerifyRequestorStackL(stack2);
    _LIT(KResult, "The RequestorStack is correct after Externalize/Internalize");
    INFO_PRINTF1(KResult);

    CleanupStack::PopAndDestroy(1); // CleanupOp stack2

    CleanupStack::PopAndDestroy(&rstream);
    CleanupStack::PopAndDestroy(tempBuf);
    CleanupStack::PopAndDestroy(bufFlat);
    CleanupStack::PopAndDestroy(1); // CleanupOp stack1

    ClosePositioner();
    Disconnect();
    }
Example #7
0
///////////////////////////////////////////////////////////////////////////////
// Destruktor
MySQL::~MySQL(void)
{
    Disconnect();
}
Example #8
0
wxNumericTextCtrl::~wxNumericTextCtrl() {
    Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( wxNumericTextCtrl::onTextChanged ), NULL, this );
}
// ---------------------------------------------------------
// CDownloadMgrSession::DispatchMessageL
// ---------------------------------------------------------
//
void CDownloadMgrSession::DispatchMessageL( const RMessage2& aMessage )
	{
    CLOG_ENTERFN( "CDownloadMgrSession::DispatchMessageL" )
    CLOG_WRITE_FORMAT( "Message function: %d", aMessage.Function() )
    // Set this false in case of the asyncron requests!!!
    iComplete = ETrue;
    SetCurrentMessage( aMessage );
    
    // Fixed for Bug id - JJUN-78WCJ3 (DownloadMgrServer crashes under IPC attack)
    //This check will make sure that before start of any download, InitializeL() should
    // be called so that all the member variables will be initialized.
    if(aMessage.Function() != EHttpDownloadMgrInitialize && iClientAppInstance == NULL)
        {
        User::Leave(KErrGeneral);
        }
        
    // check for session-relative requests
	switch( aMessage.Function() )
		{
        case EHttpDownloadMgrInitialize:
            {
            InitializeL();
            return;
            }
	    case EHttpDownloadMgrCreateDownload:
            {
		    NewDownloadL();
            return;
            }
        case EHttpDownloadMgrAttach:
            {
            DownloadMgrAttachL();
            return;
            }
        case EHttpDownloadAttach:
            {
            DownloadAttachL();
            return;
            }
		case EHttpDownloadAttachToDownload:
		    {
		    AttachToDownloadL();
		    return;
		    }
        case EHttpDownloadMgrPauseAll:
            {
            PauseAllL();
            return;
            }
        case EHttpDownloadMgrStartAllL:
            {
            StartAllL();
            return;
            }
        case EHttpDownloadMgrResetAll:
            {
            ResetAll();
            return;
            }
        case EHttpDownloadMgrDeleteAll:
            {
            DeleteAll();
            return;
            }
        case EHttpDownloadMgrDisconnect:
            {
            Disconnect();
            return;
            }
        case EHttpDownloadMgrGetIntAttribute:
            {
            GetIntAttributeL();
            return;
            }
        case EHttpDownloadMgrGetBoolAttribute:
            {
            GetBoolAttributeL();
            return;
            }
        case EHttpDownloadMgrGetStringAttribute:
            {
            GetStringAttributeL();
            return;
            }
        case EHttpDownloadMgrGetString8Attribute:
            {
            GetString8AttributeL();
            return;
            }
        case EHttpDownloadMgrSetIntAttribute:
            {
            SetIntAttributeL();
            return;
            }
        case EHttpDownloadMgrSetBoolAttribute:
            {
            SetBoolAttributeL();
            return;
            }
        case EHttpDownloadMgrSetStringAttribute:
            {
            SetStringAttributeL();
            return;
            }
        case EHttpDownloadMgrSetString8Attribute:
            {
            SetString8AttributeL();
            return;
            }
        case EHttpDownloadMgrSessionEventSubscription:
            {
            InitSessionEvent( aMessage );
            // Send event from the queue
            TUint dummy( 0 );
            Event( NULL, (THttpDownloadState)dummy, (THttpProgressState)dummy, dummy );
            // This is an asyncron request will be completed later!
            SetComplete( EFalse );
            return;
            }
        case EHttpDownloadMgrSessionEventCancel:
            {
            CancelMovedEvent();
            return;
            }
		}
	// ok, it must be subsession relative
	CDownloadSubSession* download = DownloadFromHandle( aMessage.Int3() );
    __ASSERT_DEBUG( download, PanicClient( EBadSubsessionHandle ) );

    TRAPD( err, download->DispatchMessageL( aMessage ) );

    if( err )
        {
        download->OnError( err );
        User::Leave( err );
        }
	}
Example #10
0
CDatagrams::~CDatagrams()
{
	Disconnect();
}
void
JabberProtocol::OnTag(XMLEntity *entity)
{
	char buffer[4096]; // general buffer space
	static int seen_streams = 0;

	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "iq"))
	{
		
		// handle roster retrival
		if (entity->Child("query") && entity->Child("query")->Attribute("xmlns") &&
			!strcasecmp(entity->Child("query")->Attribute("xmlns"),"jabber:iq:roster"))
		{
			ParseRosterList(entity);
			return;
		}
		
		// handle session retrival
		if (entity->Attribute("id") && entity->Attribute("type") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Attribute("id"), "sess_1"))
		{
			release_sem(logged);
		
			mainWindow->Lock();
			mainWindow->PostMessage(JAB_LOGGED_IN);
			mainWindow->Unlock();
			
			return;
		}
		
		// handle binding retrival
		if (entity->Attribute("id") && entity->Attribute("type") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Attribute("id"), "bind_0"))
		{
			jid = BString(entity->Child("bind")->Child("jid")->Data());

			fprintf(stderr, "JID: %s.\n", jid.String());

			Session();
			
			return;
		}
		
		if (entity->Attribute("type") && entity->Child("query") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			entity->Child("query", "xmlns", "jabber:iq:register"))
		{
			Authorize();
			
			return;
		}
		
		if (entity->Attribute("type") && entity->Attribute("id") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Attribute("id"), "request_room_info"))
		{
			BMessage msg(JAB_PREFERENCES_DATAFORM);
			msg.AddPointer("XMLEntity", entity);
			MessageRepeater::Instance()->PostMessage(&msg);
			
			return;
		}
		
		if (entity->Attribute("type") && entity->Attribute("id") &&
			!strcasecmp(entity->Attribute("type"), "error"))
		{
			if (!strcasecmp(entity->Attribute("id"), "storage_request"))
			{
				_storage_supported = false;
				return;
			}
			else if (!strcasecmp(entity->Attribute("id"), "save_conferences"))
			{
				_storage_supported = false;
				sprintf(buffer, "Storage XEP-0049 is not supported on server. Cannot save conferences.\n\nNext time will try save to roster.");
				ModalAlertFactory::Alert(buffer, "Pity", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
				return;
			}
			else if (!strcasecmp(entity->Attribute("id"), "request_room_info"))
			{
				
				if (entity->Child("error") &&
					entity->Child("error")->Child("text") &&
					entity->Child("error")->Attribute("code"))
					sprintf(buffer, "Error %s:\n\n%s", entity->Child("error")->Attribute("code"),
							entity->Child("error")->Child("text")->Data());
				else
					sprintf(buffer, "Error %s", entity->Child("error")->Attribute("code"));
			
				ModalAlertFactory::Alert(buffer, "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
			
				return;
			}
				
			if (entity->Child("error") &&
				entity->Child("error")->Child("text") &&
				entity->Child("error")->Attribute("code"))
				sprintf(buffer, "Error %s:\n\n%s", entity->Child("error")->Attribute("code"),
					entity->Child("error")->Child("text")->Data());
			else
				sprintf(buffer, "Error %s", entity->Child("error")->Attribute("code"));
			
			ModalAlertFactory::Alert(buffer, "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
			
			Disconnect();
			
			return;
			
		}
		
		if (entity->Attribute("id") && entity->Child("query") && entity->Child("query")->Attribute("xmlns") &&
			entity->Attribute("type") &&
			!strcasecmp(entity->Attribute("id"), "storage_request") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Child("query")->Attribute("xmlns"), "jabber:iq:private"))
		{
			if (entity->Child("query")->Child("storage"))
				ParseStorage(entity->Child("query")->Child("storage"));
				
			return;
		}
		
		if (entity->Attribute("type") && !strcasecmp(entity->Attribute("type"), "get"))
		{
			BString iq_from;
			BString iq_id;   
			
			if (entity->Attribute("from")) {
				iq_from = BString(entity->Attribute("from"));
			}
			
			if (entity->Attribute("id")) {
				iq_id = BString(entity->Attribute("id"));
			}
			
			// handle version request
			XMLEntity *query = entity->Child("query");
			if (query && query->Attribute("xmlns")) {
				if (!strcasecmp(query->Attribute("xmlns"), "jabber:iq:version")) {
					ProcessVersionRequest(iq_id, iq_from);
				}
			}
			
			// handle version request
			query = entity->Child("ping");
			if (query && query->Attribute("xmlns")) {
				if (!strcasecmp(query->Attribute("xmlns"), "urn:xmpp:ping"))
				{
					Pong(iq_id, iq_from);
				}
			}
			
			return;
		}
		
		fprintf(stderr, "Unknown IQ message.\n");
		return;
	}
	
	// handle authorization success
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "success"))
	{
		InitSession();
		
		return;
		
	}
	
	// handle presence messages
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "presence"))
	{
		ProcessPresence(entity);
		
		return;
	}
	
	// handle stream error
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "stream:error")) {
		sprintf(buffer, "An stream error has occurred.");
		ModalAlertFactory::Alert(buffer, "Sorry", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
		
		Disconnect();
		
		return;
	}
	
	// handle stream error
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "stream:features"))
	{
		mainWindow->Lock();
		int wantRegister = mainWindow->_login_new_account->Value();
		mainWindow->Unlock();
		
		if (wantRegister == B_CONTROL_ON)
		{
			if (entity->Child("register"))
			{
				mainWindow->Lock();
				mainWindow->_login_new_account->SetValue(B_CONTROL_OFF);
				mainWindow->Unlock();
				
				SendUserRegistration(user, pass, "haiku");
			} else
			{
				sprintf(buffer, "Registration not supported on this server.");
				ModalAlertFactory::Alert(buffer, "Sorry", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
				
				Disconnect();
			}
		}
		else if (entity->Child("mechanisms"))
			Authorize();
		else if (entity->Child("bind"))
			Bind();
		else if (entity->Child("session"))
			Session();
			
		return;
		
	}
	
	// handle failures
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "failure")) {
		if (entity->Child("not-authorized") != NULL)
			sprintf(buffer, "Not authorized failure.");
		else if (entity->Child("invalid-mechanism") != NULL)
			sprintf(buffer, "Invalid mechanism failure.");
		else if (entity->Child("invalid-authzid") != NULL)
			sprintf(buffer, "Invalid authorization Id.");
		else
			sprintf(buffer, "An failure occured.");
			
		ModalAlertFactory::Alert(buffer, "Sorry", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
		
		Disconnect();
		
		return;
	}
	
	// handle disconnection
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "stream:stream"))
	{
		++seen_streams;
		if (seen_streams % 2 == 1)
			Disconnect();
			
		return;
	}
	
	// handle incoming messages
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "message"))
	{
		//TalkManager::Instance()->Lock();
		TalkManager::Instance()->ProcessMessageData(entity);
		//TalkManager::Instance()->Unlock();
		
		return;
	}
	
	//delete entity;
}
Example #12
0
bool NetPlayClient::Connect()
{
    // send connect message
    sf::Packet spac;
    spac << NETPLAY_VERSION;
    spac << netplay_dolphin_ver;
    spac << m_player_name;
    Send(spac);
    enet_host_flush(m_client);
    sf::Packet rpac;
    // TODO: make this not hang
    ENetEvent netEvent;
    if (enet_host_service(m_client, &netEvent, 5000) > 0 && netEvent.type == ENET_EVENT_TYPE_RECEIVE)
    {
        rpac.append(netEvent.packet->data, netEvent.packet->dataLength);
    }
    else
    {
        return false;
    }

    MessageId error;
    rpac >> error;

    // got error message
    if (error)
    {
        switch (error)
        {
        case CON_ERR_SERVER_FULL:
            PanicAlertT("The server is full!");
            break;
        case CON_ERR_VERSION_MISMATCH:
            PanicAlertT("The server and client's NetPlay versions are incompatible!");
            break;
        case CON_ERR_GAME_RUNNING:
            PanicAlertT("The server responded: the game is currently running!");
            break;
        default:
            PanicAlertT("The server sent an unknown error message!");
            break;
        }

        Disconnect();
        return false;
    }
    else
    {
        rpac >> m_pid;

        Player player;
        player.name = m_player_name;
        player.pid = m_pid;
        player.revision = netplay_dolphin_ver;

        // add self to player list
        m_players[m_pid] = player;
        m_local_player = &m_players[m_pid];

        m_dialog->Update();

        is_connected = true;

        return true;
    }
}
Example #13
0
void AutocloseMessageBox::EndModal( int retCode )
{
	Disconnect( delay_timerID, wxEVT_TIMER, wxTimerEventHandler( AutocloseMessageBox::OnUnlock) );
	m_delay_timer.Stop();
	TimedMessageBox::EndModal( retCode );
}
// VPN Azure client main thread
void AcMainThread(THREAD *thread, void *param)
{
	AZURE_CLIENT *ac = (AZURE_CLIENT *)param;
	UINT last_ip_revision = INFINITE;
	UINT64 last_reconnect_tick = 0;
	UINT64 next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
	UINT num_reconnect_retry = 0;
	UINT64 next_ddns_retry_tick = 0;
	bool last_connect_ok = false;
	// Validate arguments
	if (ac == NULL || thread == NULL)
	{
		return;
	}

	while (ac->Halt == false)
	{
		UINT64 now = Tick64();
		bool connect_was_ok = false;
		// Wait for enabling VPN Azure function
		if (ac->IsEnabled)
		{
			// VPN Azure is enabled
			DDNS_CLIENT_STATUS st;
			bool connect_now = false;
			bool azure_ip_changed = false;

			Lock(ac->Lock);
			{
				Copy(&st, &ac->DDnsStatus, sizeof(DDNS_CLIENT_STATUS));

				if (StrCmpi(st.CurrentAzureIp, ac->DDnsStatusCopy.CurrentAzureIp) != 0)
				{
					if (IsEmptyStr(st.CurrentAzureIp) == false)
					{
						// Destination IP address is changed
						connect_now = true;
						num_reconnect_retry = 0;
					}
				}

				if (StrCmpi(st.CurrentHostName, ac->DDnsStatusCopy.CurrentHostName) != 0)
				{
					// DDNS host name is changed
					connect_now = true;
					num_reconnect_retry = 0;
				}

				Copy(&ac->DDnsStatusCopy, &st, sizeof(DDNS_CLIENT_STATUS));
			}
			Unlock(ac->Lock);

			if (last_ip_revision != ac->IpStatusRevision)
			{
				last_ip_revision = ac->IpStatusRevision;

				connect_now = true;

				num_reconnect_retry = 0;
			}

			if (last_reconnect_tick == 0 || (now >= (last_reconnect_tick + next_reconnect_interval)))
			{
				UINT r;

				last_reconnect_tick = now;
				num_reconnect_retry++;
				next_reconnect_interval = (UINT64)num_reconnect_retry * AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
				next_reconnect_interval = MIN(next_reconnect_interval, AZURE_CONNECT_MAX_RETRY_INTERVAL);

				r = (UINT)next_reconnect_interval;

				r = GenRandInterval(r / 2, r);

				next_reconnect_interval = r;

				connect_now = true;
			}

			if (IsEmptyStr(st.CurrentAzureIp) == false && IsEmptyStr(st.CurrentHostName) == false)
			{
				if (connect_now)
				{
					SOCK *s;
					char *host = NULL;
					UINT port = AZURE_SERVER_PORT;

					Debug("VPN Azure: Connecting to %s...\n", st.CurrentAzureIp);

					if (ParseHostPort(st.CurrentAzureIp, &host, &port, AZURE_SERVER_PORT))
					{
						if (st.InternetSetting.ProxyType == PROXY_DIRECT)
						{
							s = ConnectEx2(host, port, 0, (bool *)&ac->Halt);
						}
						else
						{
							s = WpcSockConnect2(host, port, &st.InternetSetting, NULL, AZURE_VIA_PROXY_TIMEOUT);
						}

						if (s != NULL)
						{
							PACK *p;
							UINT64 established_tick = 0;

							Debug("VPN Azure: Connected.\n");

							SetTimeout(s, AZURE_PROTOCOL_CONTROL_TIMEOUT_DEFAULT);

							Lock(ac->Lock);
							{
								ac->CurrentSock = s;
								ac->IsConnected = true;
								StrCpy(ac->ConnectingAzureIp, sizeof(ac->ConnectingAzureIp), st.CurrentAzureIp);
							}
							Unlock(ac->Lock);

							SendAll(s, AZURE_PROTOCOL_CONTROL_SIGNATURE, StrLen(AZURE_PROTOCOL_CONTROL_SIGNATURE), false);

							// Receive parameter
							p = RecvPackWithHash(s);
							if (p != NULL)
							{
								UCHAR c;
								AZURE_PARAM param;
								bool hostname_changed = false;

								Zero(&param, sizeof(param));

								param.ControlKeepAlive = PackGetInt(p, "ControlKeepAlive");
								param.ControlTimeout = PackGetInt(p, "ControlTimeout");
								param.DataTimeout = PackGetInt(p, "DataTimeout");
								param.SslTimeout = PackGetInt(p, "SslTimeout");

								FreePack(p);

								param.ControlKeepAlive = MAKESURE(param.ControlKeepAlive, 1000, AZURE_SERVER_MAX_KEEPALIVE);
								param.ControlTimeout = MAKESURE(param.ControlTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);
								param.DataTimeout = MAKESURE(param.DataTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);
								param.SslTimeout = MAKESURE(param.SslTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);

								Lock(ac->Lock);
								{
									Copy(&ac->AzureParam, &param, sizeof(AZURE_PARAM));
								}
								Unlock(ac->Lock);

								SetTimeout(s, param.ControlTimeout);

								// Send parameter
								p = NewPack();
								PackAddStr(p, "CurrentHostName", st.CurrentHostName);
								PackAddStr(p, "CurrentAzureIp", st.CurrentAzureIp);
								PackAddInt64(p, "CurrentAzureTimestamp", st.CurrentAzureTimestamp);
								PackAddStr(p, "CurrentAzureSignature", st.CurrentAzureSignature);

								Lock(ac->Lock);
								{
									if (StrCmpi(st.CurrentHostName, ac->DDnsStatus.CurrentHostName) != 0)
									{
										hostname_changed = true;
									}
								}
								Unlock(ac->Lock);

								if (hostname_changed == false)
								{
									if (SendPackWithHash(s, p))
									{
										// Receive result
										if (RecvAll(s, &c, 1, false))
										{
											if (c && ac->Halt == false)
											{
												connect_was_ok = true;

												established_tick = Tick64();

												AcWaitForRequest(ac, s, &param);
											}
										}
									}
								}

								FreePack(p);
							}
							else
							{
								WHERE;
							}

							Debug("VPN Azure: Disconnected.\n");

							Lock(ac->Lock);
							{
								ac->IsConnected = false;
								ac->CurrentSock = NULL;
								ClearStr(ac->ConnectingAzureIp, sizeof(ac->ConnectingAzureIp));
							}
							Unlock(ac->Lock);

							if (established_tick != 0)
							{
								if ((established_tick + (UINT64)AZURE_CONNECT_MAX_RETRY_INTERVAL) <= Tick64())
								{
									// If the connected time exceeds the AZURE_CONNECT_MAX_RETRY_INTERVAL, reset the retry counter.
									last_reconnect_tick = 0;
									num_reconnect_retry = 0;
									next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
								}
							}

							Disconnect(s);
							ReleaseSock(s);
						}
						else
						{
							Debug("VPN Azure: Error: Connect Failed.\n");
						}

						Free(host);
					}
				}
			}
		}
		else
		{
			last_reconnect_tick = 0;
			num_reconnect_retry = 0;
			next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
		}

		if (ac->Halt)
		{
			break;
		}

		if (connect_was_ok)
		{
			// If connection goes out after connected, increment connection success count to urge DDNS client query
			next_ddns_retry_tick = Tick64() + MIN((UINT64)DDNS_VPN_AZURE_CONNECT_ERROR_DDNS_RETRY_TIME_DIFF * (UINT64)(num_reconnect_retry + 1), (UINT64)DDNS_VPN_AZURE_CONNECT_ERROR_DDNS_RETRY_TIME_DIFF_MAX);
		}

		if ((next_ddns_retry_tick != 0) && (Tick64() >= next_ddns_retry_tick))
		{
			next_ddns_retry_tick = 0;

			ac->DDnsTriggerInt++;
		}

		Wait(ac->Event, rand() % 1000);
	}
}
Example #15
0
// Listener thread
void ElListenerProc(THREAD *thread, void *param)
{
	TCP_ACCEPTED_PARAM *data = (TCP_ACCEPTED_PARAM *)param;
	EL *e;
	SOCK *s;
	UCHAR rand[SHA1_SIZE];
	UCHAR pass1[SHA1_SIZE], pass2[SHA1_SIZE];
	// Validate arguments
	if (data == NULL || thread == NULL)
	{
		return;
	}

	e = (EL *)data->r->ThreadParam;
	s = data->s;
	AddRef(s->ref);
	SetTimeout(s, 5000);
	LockList(e->AdminThreadList);
	{
		AddRef(thread->ref);
		AddRef(s->ref);
		Insert(e->AdminThreadList, thread);
		Insert(e->AdminSockList, s);
	}
	UnlockList(e->AdminThreadList);
	NoticeThreadInit(thread);

	// Submit a challenge
	Rand(rand, sizeof(rand));
	SendAll(s, rand, sizeof(rand), false);

	// Receive a response
	SecurePassword(pass1, e->HashedPassword, rand);
	Zero(pass2, sizeof(pass2));
	RecvAll(s, pass2, sizeof(pass2), false);

	if (Cmp(pass1, pass2, SHA1_SIZE) != 0)
	{
		// Password incorrect
		bool code = false;
		code = Endian32(code);
		SendAll(s, &code, sizeof(code), false);
	}
	else
	{
		// Password match
		bool code = true;
		RPC *r;

		code = Endian32(code);
		SendAll(s, &code, sizeof(code), false);

		SetTimeout(s, INFINITE);

		// Start operation as a RPC server
		r = StartRpcServer(s, ElRpcServer, e);
		RpcServer(r);
		RpcFree(r);
	}

	Disconnect(s);
	ReleaseSock(s);

	LockList(e->AdminThreadList);
	{
		if (Delete(e->AdminThreadList, thread))
		{
			ReleaseThread(thread);
		}
		if (Delete(e->AdminSockList, s))
		{
			ReleaseSock(s);
		}
	}
	UnlockList(e->AdminThreadList);
}
void EDA_DRAW_PANEL_GAL::StopDrawing()
{
    m_pendingRefresh = true;
    m_refreshTimer.Stop();
    Disconnect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), NULL, this );
}
Example #17
0
ClientInfo::~ClientInfo()
{
	Disconnect();
	m_thread.join();
	Cli::writeDebugMsg("Client Destructed");
}
Example #18
0
/**************************************************************************//**
 * @brief
 *   The main command line loop. Placed in Ram so that it can still run after
 *   a destructive write operation.
 *   NOTE: __ramfunc is a IAR specific instruction to put code into RAM.
 *   This allows the bootloader to survive a destructive upload.
 *****************************************************************************/
static void commandlineLoop( void )
{
  uint8_t  c;

  /* The main command loop */
  while (1)
  {
    /* Retrieve new character */
    c = BOOTLDIO_rxByte();
    /* Echo */
    if (c != 0)
    {
      BOOTLDIO_txByte( c );
    }

    switch (c)
    {
    /* Bootloader version command */
    case 'i':
      /* Print version */
      BOOTLDIO_printString("\r\n\r\n" BOOTLOADER_VERSION_STRING );
      /* Print the chip ID */
      BOOTLDIO_printHex(DEVINFO->UNIQUEH);
      BOOTLDIO_printHex(DEVINFO->UNIQUEL);
      BOOTLDIO_printString("\r\n");
      break;

    /* Upload command */
    case 'u':
      BOOTLDIO_printString( readyString );
      XMODEM_download( BOOTLOADER_SIZE, flashSize );
      break;

    /* Destructive upload command */
    case 'd':
      BOOTLDIO_printString( readyString );
      XMODEM_download( 0, flashSize );
      break;

    /* Write to user page */
    case 't':
      BOOTLDIO_printString( readyString );
      XMODEM_download( USER_PAGE_START, USER_PAGE_END );
      break;

    /* Write to lock bits */
    case 'p':
      BOOTLDIO_printString( readyString );
      XMODEM_download( LOCK_PAGE_START, LOCK_PAGE_END );
      break;

    /* Boot into new program */
    case 'b':
      Disconnect( 5000, 2000 );
      BOOT_boot();
      break;

    /* Debug lock */
    case 'l':
#if defined( BL_DEBUG )
      /* We check if there is a debug session active in DHCSR. If there is we
       * abort the locking. This is because we wish to make sure that the debug
       * lock functionality works without a debugger attatched. */
      if ((CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) != 0x0)
      {
        USB_PUTS( "\r\n\r\n **** WARNING: DEBUG SESSION ACTIVE. NOT LOCKING!  **** \r\n\r\n" );
        BOOTLDIO_printString( "Debug active.\r\n" );
      }
      else
      {
        USB_PUTS( "Starting debug lock sequence.\r\n" );
#endif
        FLASH_writeWord( DEBUG_LOCK_WORD, 0x0 );
        if ( *(volatile uint32_t*)DEBUG_LOCK_WORD == 0x0 )
        {
          BOOTLDIO_printString( okString );
        }
        else
        {
          BOOTLDIO_printString( failString );
        }
#if defined( BL_DEBUG )
        USB_PRINTF( "Debug lock word: 0x%x \r\n", *((uint32_t *) DEBUG_LOCK_WORD) );
      }
#endif
      break;

    /* Verify content by calculating CRC of entire flash */
    case 'v':
      verify( 0, flashSize );
      break;

    /* Verify content by calculating CRC of application area */
    case 'c':
      verify( BOOTLOADER_SIZE, flashSize );
      break;

    /* Verify content by calculating CRC of user page.*/
    case 'n':
      verify( USER_PAGE_START, USER_PAGE_END );
      break;

    /* Verify content by calculating CRC of lock page */
    case 'm':
      verify( LOCK_PAGE_START, LOCK_PAGE_END );
      break;

    /* Reset command */
    case 'r':
      Disconnect( 5000, 2000 );

      /* Write to the Application Interrupt/Reset Command Register to reset
       * the EFM32. See section 9.3.7 in the reference manual. */
      SCB->AIRCR = 0x05FA0004;
      break;

    /* Unknown command */
    case 0:
      /* Timeout waiting for RX - avoid printing the unknown string. */
      break;

    default:
      BOOTLDIO_printString( unknownString );
    }
  }
}
Example #19
0
// OnReceive
//------------------------------------------------------------------------------
/*virtual*/ void Client::OnReceive( const ConnectionInfo * connection, void * data, uint32_t size, bool & keepMemory )
{
	keepMemory = true; // we'll take care of freeing the memory

	MutexHolder mh( m_ServerListMutex );

	ServerState * ss = (ServerState *)connection->GetUserData();
	ASSERT( ss );

	// are we expecting a msg, or the payload for a msg?
	void * payload = nullptr;
	size_t payloadSize = 0;
	if ( ss->m_CurrentMessage == nullptr )
	{
		// message
		ss->m_CurrentMessage = reinterpret_cast< const Protocol::IMessage * >( data );
		if ( ss->m_CurrentMessage->HasPayload() )
		{
			return;
		}
	}
	else
	{
		// payload
		ASSERT( ss->m_CurrentMessage->HasPayload() );
		payload = data;
		payloadSize = size;
	}

	// determine message type
	const Protocol::IMessage * imsg = ss->m_CurrentMessage;
	Protocol::MessageType messageType = imsg->GetType();

	PROTOCOL_DEBUG( "Server -> Client : %u (%s)\n", messageType, GetProtocolMessageDebugName( messageType ) );

	switch ( messageType )
	{
		case Protocol::MSG_REQUEST_JOB:
		{
			const Protocol::MsgRequestJob * msg = static_cast< const Protocol::MsgRequestJob * >( imsg );
			Process( connection, msg ); 
			break;
		}
		case Protocol::MSG_JOB_RESULT:
		{
			const Protocol::MsgJobResult * msg = static_cast< const Protocol::MsgJobResult * >( imsg );
			Process( connection, msg, payload, payloadSize ); 
			break;
		}
		case Protocol::MSG_REQUEST_MANIFEST:
		{
			const Protocol::MsgRequestManifest * msg = static_cast< const Protocol::MsgRequestManifest * >( imsg );
			Process( connection, msg ); 
			break;
		}
		case Protocol::MSG_REQUEST_FILE:
		{
			const Protocol::MsgRequestFile * msg = static_cast< const Protocol::MsgRequestFile * >( imsg );
			Process( connection, msg ); 
			break;
		}
		case Protocol::MSG_SERVER_STATUS:
		{
			const Protocol::MsgServerStatus * msg = static_cast< const Protocol::MsgServerStatus * >( imsg );
			Process( connection, msg ); 
			break;
		}
		default:
		{
			// unknown message type
			ASSERT( false ); // this indicates a protocol bug
			Disconnect( connection );
			break;
		}
	}

	// free everything
	FREE( (void *)( ss->m_CurrentMessage ) );
	FREE( payload );
	ss->m_CurrentMessage = nullptr;
}
Example #20
0
/**************************************************************************//**
 * The main entry point.
 *****************************************************************************/
int main(void)
{
  int msElapsed, i;

  /* Set new vector table pointer */
  SCB->VTOR = 0x20000000;

  /* Enable peripheral clocks. */
  CMU->HFPERCLKDIV = CMU_HFPERCLKDIV_HFPERCLKEN;
  CMU->HFPERCLKEN0 = CMU_HFPERCLKEN0_GPIO | BOOTLOADER_USART_CLOCK |
                     AUTOBAUD_TIMER_CLOCK ;

  /* Enable DMA interface */
  CMU->HFCORECLKEN0 = CMU_HFCORECLKEN0_DMA;

#if defined( BL_DEBUG )
  RETARGET_SerialInit();        /* Setup debug serialport etc. */
  USB_PUTS( "EFM32 USB/USART0 bootloader\r\n" );
#endif

  /* Calculate CRC16 for the bootloader itself and the Device Information page. */
  /* This is used for production testing and can safely be omitted in */
  /* your own code. */
  bootloaderCRC  = CRC_calc((void *) 0x0, (void *) BOOTLOADER_SIZE);
  bootloaderCRC |= CRC_calc((void *) 0x0FE081B2, (void *) 0x0FE08200) << 16;

  StartRTC();

#if !defined( SIMULATE_SWDCLK_PIN_HI )
  while ( SWDCLK_PIN_IS_LO() )
  {
    USB_PUTS( "SWDCLK is low\r\n" );

    if ( BOOT_checkFirmwareIsValid() )
    {
      USB_PUTS( "Booting application\r\n  " );
      BOOT_boot();
    }
    else
    {
      USB_PUTS( "No valid application, resetting EFM32... \r\n" );

      /* Go to EM2 and wait for RTC wakeup. */
      EMU_EnterEM2( false );
    }
  }
#endif

  NVIC_DisableIRQ( RTC_IRQn );

  /* Try to start HFXO. */

  CMU_OscillatorEnable( cmuOsc_HFXO, true, false );

  /* Wait approx. 1 second to see if HFXO starts. */
  i = 1500000;
  while ( i && !( CMU->STATUS & CMU_STATUS_HFXORDY ) )
  {
    i--;
  }

  USBTIMER_Init();

  if ( i == 0 )
  {
    CMU_HFRCOBandSet( cmuHFRCOBand_28MHz );
  }
  else
  {
    CMU_ClockSelectSet( cmuClock_HF, cmuSelect_HFXO );
    USBD_Init( &initstruct );       /* Start USB CDC functionality  */
  }

  AUTOBAUD_start();                 /* Start autobaud               */

  /* Wait 30 seconds for USART or USB connection */
  msElapsed = 0;
  while ( msElapsed < 30000 )
  {
    if ( AUTOBAUD_completed() )
      break;

    if ( CDC_Configured )
    {
      BOOTLDIO_setMode( CDC_Configured );
      break;
    }

    USBTIMER_DelayMs( 100 );
    msElapsed += 100;
  }
  AUTOBAUD_stop();

  if ( msElapsed >= 30000 )
  {
    USB_PUTS( "USART0/USB timeout, resetting EFM32...\r\n  " );
    Disconnect( 0, 2000 );
    SCB->AIRCR = 0x05FA0004;        /* Reset EFM32. */
  }

  /* Print a message to show that we are in bootloader mode */
  BOOTLDIO_printString("\r\n\r\n" BOOTLOADER_VERSION_STRING );

  /* Print the chip ID. This is useful for production tracking */
  BOOTLDIO_printHex(DEVINFO->UNIQUEH);
  BOOTLDIO_printHex(DEVINFO->UNIQUEL);
  BOOTLDIO_printString("\r\n");

  /* Figure out correct flash geometry. */
  FLASH_CalcPageSize();
  /* Initialize flash for writing */
  FLASH_init();

  /* Start executing command line */
  commandlineLoop();
}
Example #21
0
CPullPin::~CPullPin() {
    Disconnect();
}
Example #22
0
CRmqCli::~CRmqCli()
{
	Disconnect();
}
void SyncSocketConnection::Shutdown()
{
	Disconnect();
	m_bInitialized = FALSE;
}
nsXULCommandDispatcher::~nsXULCommandDispatcher()
{
  Disconnect();
}
void CUser::RecvLoginInfo(Packet & pkt)
{
	int8 bResult = pkt.read<uint8>();
	if (bResult < 0)
		Disconnect();
}
void CustomVirtListCtrl<T,L>::StopTimer()
{
	m_periodic_sort_timer.Stop();
	Disconnect( m_periodic_sort_timer_id, wxTimerEvent().GetEventType(),   wxTimerEventHandler( ThisType::OnPeriodicSort ) );
}
// ---------------------------------------------------------
// CT_LbsClientPosTp178::TestTimeout
//
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CT_LbsClientPosTp178::TestTimeoutL()
    {
    _LIT(KSTART, "TestTimeout()");
    _LIT(KEND, "TestTimeout() passed");
    _LIT(KTIME, "Request took %d us");
    
    // Setup verification stuff
    INFO_PRINTF1(KSTART);
    
    //TPrivDlgDiagnostics tmpdiag;
    TTime requestStartTime;
    TTime requestStopTime;
    TTimeIntervalMicroSeconds durationMicro;
    
    TBuf<100> buf;
    
	_LIT(KService, "SAAA");
    TPositionUpdateOptions updateOptions;
    
    TTimeIntervalMicroSeconds longInterval(7000000);
    ConnectL();
    SetupPsyL(iUidTestPsy3);

    OpenPositionerByName(iUidTestPsy3);    
    updateOptions.SetUpdateTimeOut(longInterval);
    
    // Access protected member (iPositioner) here
    iPositioner.SetUpdateOptions(updateOptions);
    
    _LIT(KONE, "Perform first request, should NOT time out");
    INFO_PRINTF1(KONE);
    
    requestStartTime.UniversalTime();
    //Make one request to verify psy
    PerformRequestL(KService, CRequestor::ERequestorService, CRequestor::EFormatApplication);
    
    CheckRequestResultL(KErrNone);
    requestStopTime.UniversalTime();

    durationMicro = requestStopTime.MicroSecondsFrom(requestStartTime);
    TInt duration = durationMicro.Int64();
    
    buf.Format(KTIME, duration);
    INFO_PRINTF1(buf);
    
    ClosePositioner();
    
    OpenPositionerByName(iUidTestPsy3);
    // ECancelButton means that the Automatised class should wait for a cancel call
    // before returning result
    
    updateOptions.SetUpdateTimeOut(longInterval);
    
    // Access protected (iPositioner) member here
    iPositioner.SetUpdateOptions(updateOptions);
    
    _LIT(KTWO, "Perform second request, should not time out");
    INFO_PRINTF1(KTWO);
    
    //Make one request to verify psy
    TPositionInfo info = TPositionInfo();
    requestStartTime.UniversalTime();
    TInt err = PerformSyncRequest(KService, &info);
    requestStopTime.UniversalTime();
    
    if (err != KErrNone)
    {
        _LIT(KError, "Wrong result from iStatus, should be KErrNone, was %d");
        TBuf<100> buf;
        buf.Format(KError, err);
        LogErrorAndLeaveL(buf);
    }
    
    durationMicro = requestStopTime.MicroSecondsFrom(requestStartTime); 
    duration = durationMicro.Int64();
    
    buf.Format(KTIME, duration);
    INFO_PRINTF1(buf);
    
    ClosePositioner();
    Disconnect();

    INFO_PRINTF1(KEND);
}
void CUser::SelectCharacter(Packet & pkt)
{
	Packet result(WIZ_SEL_CHAR);
	uint8 bResult, bInit;

	if (isBanned())
	{
		Disconnect();
		return;
	}

	pkt >> bResult >> bInit;
	result << bResult;

	if (bResult == 0 || !GetZoneID()) 
		goto fail_return;

	m_pMap = g_pMain->GetZoneByID(GetZoneID());
	if (GetMap() == NULL)
		goto fail_return;

	// Temporarily convert the old quest storage format to the new one.
	// This won't be necessary when Aujard's out of the picture.
	m_questMap.clear();
	for (int i = 0, index = 0; i < m_pUserData->m_sQuestCount; i++)
	{
		uint16	sQuestID	= GetShort(m_pUserData->m_bstrQuest, index);
		uint8	bQuestState	= GetByte(m_pUserData->m_bstrQuest, index);

		m_questMap.insert(std::make_pair(sQuestID, bQuestState));
	}

	if (g_pMain->m_nServerNo != GetMap()->m_nServerNo)
	{
		_ZONE_SERVERINFO *pInfo = g_pMain->m_ServerArray.GetData(GetMap()->m_nServerNo);
		if (pInfo == NULL) 
			goto fail_return;

		SendServerChange(pInfo->strServerIP, bInit);
		return;
	}

	if (g_pMain->m_byBattleOpen == NO_BATTLE && getFame() == COMMAND_CAPTAIN)
		m_pUserData->m_bFame = CHIEF;

	if ((GetZoneID() != GetNation() && GetZoneID() < 3 && !g_pMain->m_byBattleOpen)
		|| (GetZoneID() == ZONE_BATTLE && (g_pMain->m_byBattleOpen != NATION_BATTLE))
		|| (GetZoneID() == ZONE_SNOW_BATTLE && (g_pMain->m_byBattleOpen != SNOW_BATTLE))
		|| (GetZoneID() == ZONE_FRONTIER && g_pMain->m_byBattleOpen))
	{
		NativeZoneReturn();
		Disconnect();
		return;
	}

	SetLogInInfoToDB(bInit);

	result << GetZoneID() << GetSPosX() << GetSPosZ() << GetSPosY() << g_pMain->m_byOldVictory;
	m_bSelectedCharacter = true;
	Send(&result);

	SetSlotItemValue();
	SetUserAbility(false);

	if (GetLevel() > MAX_LEVEL) 
	{
		Disconnect();
		return;
	}

	m_iMaxExp = g_pMain->GetExpByLevel(GetLevel());
	SetRegion(GetNewRegionX(), GetNewRegionZ());

	if (m_pUserData->m_bKnights == -1)
	{
		m_pUserData->m_bKnights = m_pUserData->m_bFame = 0;
		return;
	}
	else if (m_pUserData->m_bKnights != 0)
	{
		CKnights* pKnights = g_pMain->GetClanPtr( m_pUserData->m_bKnights );
		if (pKnights != NULL)
		{
			g_pMain->m_KnightsManager.SetKnightsUser( m_pUserData->m_bKnights, m_pUserData->m_id );
		}
		else if (GetZoneID() > 2)
		{
			result.Initialize(WIZ_KNIGHTS_PROCESS);
			result << uint8(KNIGHTS_LIST_REQ) << m_pUserData->m_bKnights;
			g_pMain->m_LoggerSendQueue.PutData(&result, GetSocketID());
		}
	}
	return;

fail_return:
	Send(&result);
}
// ---------------------------------------------------------
// CT_LbsClientPosTp178::StartL
//
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CT_LbsClientPosTp178::StartL()
    {
    _LIT(KServiceAccept, "SAAA");
    
    SetupPsyL(iUidTestPsy3);
    
    RPositioner positioner;
    TPositionInfo info = TPositionInfo();
    
    ConnectL();
    
    User::LeaveIfError(positioner.Open(iPosServer,iUidTestPsy3));
    CleanupClosePushL(positioner);
    
    TInt Err = positioner.SetRequestor(CRequestor::ERequestorService,
        CRequestor::EFormatApplication, KServiceAccept);
    
    TPositionUpdateOptions updateOptionsLong, updateOptionsShort;
    
    TTimeIntervalMicroSeconds longInterval(7000000);
    
    updateOptionsLong.SetUpdateTimeOut(longInterval);
    Err = positioner.SetUpdateOptions(updateOptionsLong);
    
    TTimeIntervalMicroSeconds shortInterval(2000000);
    updateOptionsShort.SetUpdateTimeOut(shortInterval);
    
    TPositionUpdateOptions theUpdateOptions;
    Err = positioner.GetUpdateOptions(theUpdateOptions);
    
    if (theUpdateOptions.UpdateTimeOut() != updateOptionsLong.UpdateTimeOut() ||
        updateOptionsLong.UpdateTimeOut() != longInterval)
    {
        _LIT(KUpdateOptions, "The update option was not set correctly");
        LogErrorAndLeaveL(KUpdateOptions);
    }
    
    _LIT(KDelayMsg, "The successfull requests was completed within %d microsecs.");
    _LIT(KCancelMsg, "The canceled requests was completed within %d microsecs.");
    
    TRequestStatus status;
    
    for (TInt i = 0; i < 10; i++) // makes 10 test inorder to get some statistic
    {         
        
        positioner.SetUpdateOptions(updateOptionsLong);
        TTime requestStartTime;
        
        requestStartTime.UniversalTime();
        positioner.NotifyPositionUpdate(info, status);
        User::WaitForRequest(status);
        TTime requestStopTime;
        requestStopTime.UniversalTime();
        
        TTimeIntervalMicroSeconds durationMicro = requestStopTime.MicroSecondsFrom(requestStartTime);
        
        TInt duration = durationMicro.Int64();
        
        TBuf<100> timeMsg;
        timeMsg.Format(KDelayMsg, duration);
        INFO_PRINTF1(timeMsg);
        
        //check error status
        if (status != KErrNone)
        {
            _LIT(KErrPositionRequest, "error code returned from NotifyPositionUpdate, error code = %d");
            TBuf<100> buf;
            buf.Format(KErrPositionRequest, status.Int());
            LogErrorAndLeaveL(buf);
        }
        
        
        TTimeIntervalMicroSeconds shortInterval(2000000);
        updateOptionsShort.SetUpdateTimeOut(shortInterval);
        
        positioner.SetUpdateOptions(updateOptionsShort);
        
        requestStartTime.UniversalTime();
        positioner.NotifyPositionUpdate(info, status);
        User::WaitForRequest(status);
        requestStopTime.UniversalTime();
        
        durationMicro = requestStopTime.MicroSecondsFrom(requestStartTime);
        
        duration = durationMicro.Int64();
        
#ifdef __WINS__
        TTimeIntervalMicroSeconds winsFail(100000);
        durationMicro = TTimeIntervalMicroSeconds(durationMicro.Int64()+winsFail.Int64());
#endif
        
        timeMsg.Format(KCancelMsg, duration);
        INFO_PRINTF1(timeMsg);
        
        
        if (status != KErrTimedOut)
        {
            _LIT(KErrPositionRequest, "Request did not returned KErrTimedOut, status code = %d.");
            TBuf<100> buf;
            buf.Format(KErrPositionRequest, status.Int());
            LogErrorAndLeaveL(buf);
        }

        //Check that the request was not aborted before the Interval
        //Remove this condition if a lot of data is needed in test log.
        if (durationMicro < shortInterval)
        {
            _LIT(KErrInterval, " The request was aborted before the set timed out ");
            LogErrorAndLeaveL(KErrInterval);
        }
        
        
    } // end for loop
    CleanupStack::PopAndDestroy(1); //positioner
    Disconnect();

    // Do timeout test
    TestTimeoutL();

    // Do cancel test
    TestCancelL();

    // ESLI-5QRA7U just check that it is not possible to set a timeout that is less than
    // the update interval
    TestOptionL();
    }
Example #30
0
void MyFrame::OnDisconnect(wxCommandEvent& WXUNUSED(event))
{
    Disconnect();
}