示例#1
0
Error Socket::Disconnect() const {
  if (!socket_) {
    return Error(LNR_EBADF);
  }
  const linear::Addrinfo& peer = GetPeerInfo();
  LINEAR_LOG(LOG_DEBUG, "try to disconnect: %s:%d,%s", peer.addr.c_str(), peer.port, GetTypeString(GetType()).c_str());
  return socket_->Disconnect();
}
示例#2
0
Error Socket::Disconnect() const {
  if (!socket_) {
    return Error(LNR_EBADF);
  }
  const linear::Addrinfo& self = GetSelfInfo();
  const linear::Addrinfo& peer = GetPeerInfo();
  LINEAR_LOG(LOG_DEBUG, "try to disconnect(id = %d): %s:%d x-- %s --- %s:%d",
             GetId(),
             (self.proto == Addrinfo::IPv4) ? self.addr.c_str() : (std::string("[" + self.addr + "]")).c_str(),
             self.port,
             GetTypeString(GetType()).c_str(),
             (peer.proto == Addrinfo::IPv4) ? peer.addr.c_str() : (std::string("[" + peer.addr + "]")).c_str(),
             peer.port);
  return socket_->Disconnect();
}
示例#3
0
int PING::Initialize(CFileLog *a_pclsLog, RESOURCE *a_pRsc, void *a_pclsMain)
{
	RESOURCE_ATTR *pstAttr = NULL;
	PING_VALUE *pstPingData = NULL;	

	if(a_pclsLog == NULL)
		return -1;

	m_pclsLog = a_pclsLog;
	m_pGroupRsc = a_pRsc;
	m_pmapRsc = &(a_pRsc->mapRsc);	
	m_pclsMain = (RSAMain*)a_pclsMain;
    m_pclsEvent = m_pclsMain->GetEvent();

	map<string, RESOURCE_ATTR *>::iterator it;
	for(it = m_pmapRsc->begin(); it != m_pmapRsc->end() ; it++)
	{
		if(it->second != NULL)
		{
			pstAttr = it->second;
		}
		else
		{
			break;
		}
		
		if(pstAttr->pData == NULL)
		{
			//Init Stat Data
			it->second->pData = (void*)new PING_VALUE;
			pstPingData = (PING_VALUE*)it->second->pData;
			GetPeerInfo(pstPingData->vecPeerInfo);
//			pstPingData->vecStringValue.assign(MAX_PING_IDX, "");
		}


		m_pclsLog->INFO("Name : %s, Args : %s", 
			pstAttr->szName, pstAttr->szArgs);

	}	

	return 0;
}
示例#4
0
static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint32_t port,
        const unsigned char *id, uint16_t id_length)
{
    if(NULL == peerAddr
       || NULL == id
       || 0 == port
       || 0 == id_length
       || CA_MAX_ENDPOINT_IDENTITY_LEN < id_length)
    {
        OIC_LOG(ERROR, NET_DTLS_TAG, "CAAddIdToPeerInfoList invalid parameters");
        return CA_STATUS_INVALID_PARAM;
    }

    CASecureEndpoint_t *peer = (CASecureEndpoint_t *)OICCalloc(1, sizeof (CASecureEndpoint_t));
    if (NULL == peer)
    {
        OIC_LOG(ERROR, NET_DTLS_TAG, "peerInfo malloc failed!");
        return CA_MEMORY_ALLOC_FAILED;
    }

    OICStrcpy(peer->endpoint.addr, sizeof(peer->endpoint.addr), peerAddr);
    peer->endpoint.port = port;

    memcpy(peer->identity.id, id, id_length);
    peer->identity.id_length = id_length;

    if (NULL != GetPeerInfo(&peer->endpoint))
    {
        OIC_LOG(ERROR, NET_DTLS_TAG, "CAAddIdToPeerInfoList peer already exist");
        OICFree(peer);
        return CA_STATUS_FAILED;
    }

    bool result = u_arraylist_add(g_caDtlsContext->peerInfoList, (void *)peer);
    if (!result)
    {
        OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_add failed!");
        OICFree(peer);
        return CA_STATUS_FAILED;
    }

    return CA_STATUS_OK;
}
示例#5
0
文件: proxyer.cpp 项目: bymzy/forfun
static void on_accept(int sock,short event,void *arg)
{
    Proxyer* pserver = (Proxyer*) arg;
    int clientsocket = -1;
    int remotesocket = -1;
    Context* newcontext = NULL;
    int err = 0;
    struct sockaddr_in client_addr,remote_addr;
    socklen_t len = sizeof(client_addr);

    do {
        clientsocket = accept(sock,(struct sockaddr *)&client_addr,&len);
        if ( -1 == clientsocket ) {
            std::cerr<<"accept client failed! err: "<<strerror(errno)<<std::endl;
            break;
        }
        std::cout<<"receive connection "<<GetPeerInfo(&client_addr)<<std::endl;
        
        err = SetNonblocking(clientsocket);
        if ( 0 != err ) {
            std::cerr<<"set nonblocking for client socket failed! err: "<<strerror(err)<<std::endl;
            break;
        }

        remotesocket = socket(AF_INET,SOCK_STREAM,0);
        if ( -1 == remotesocket ) {
            std::cerr<<"create remote socket failed!"<<std::endl;
            break;
        }

        memset(&remote_addr,0,sizeof(remote_addr));
        remote_addr.sin_family = AF_INET;
        remote_addr.sin_port = htons(pserver->remote_port);
        remote_addr.sin_addr.s_addr = inet_addr(pserver->remote_addr.c_str());

        err = connect(remotesocket,(struct sockaddr*)&remote_addr,sizeof(remote_addr));
        if ( 0 != err ) {
            if ( EINPROGRESS != err ) {
                err = errno;
                std::cerr<<"connect remote failed! err: "<<strerror(err)<<std::endl;
                break;
            }
            err = CheckConnect(remotesocket);
            if ( 0 != err ) {
                err = errno;
                std::cerr<<"connect remote failed! err: "<<strerror(err)<<std::endl;
                break;
            }
            std::cout<<"connect remote success!"<<std::endl;
        } else {
            std::cout<<"connect remote success!"<<std::endl;
        }

        /**
         * connect remote success,then we need to create a Context
         * */

        newcontext = new Context(pserver,clientsocket,remotesocket);
        if ( NULL == newcontext ) {
            std::cerr<<"Alloc Context failed!"<<std::endl;
            break;
        }

        err = newcontext->Init();
        if ( 0 != err ) {
            std::cerr<<"newcontext init failed!"<<std::endl;
            break;
        }

        /**
         * 将context添加到server的队列中
         * */
        pserver->m_context_list.push_back(newcontext);
    } while(0);

    do{
        if ( 0 != err ) {
            if ( -1 == clientsocket ) {
                 break;
             }
            close(clientsocket);

            if ( -1 == remotesocket ) {
                break;
            }
            close(remotesocket);

            if ( NULL == newcontext ) {
                break;
            }
            delete newcontext;
       }
    } while(0);

}
示例#6
0
//======================================================================================
// MessageHandler()
//
// Handles messages from DirectPlay.
//======================================================================================
HRESULT CDarkPeer::MessageHandler(void* pContext, DWORD messageType, void* pMessage)
{
	switch (messageType)
	{
	case DPN_MSGID_CREATE_PLAYER:
		{
			HandleCreatePlayerMsg((DPNMSG_CREATE_PLAYER*)pMessage);
			break;
		}

      case DPN_MSGID_DESTROY_PLAYER:
		{
			// Translate DPlay8's destroy player message to DPlay4
			PDPNMSG_DESTROY_PLAYER pDestroyPlayer = (PDPNMSG_DESTROY_PLAYER) pMessage;
			DPNID dpnidPlayer = pDestroyPlayer->dpnidPlayer;
			DPMSG_DESTROYPLAYERORGROUP* pDP4DestroyPlayer = new DPMSG_DESTROYPLAYERORGROUP;

			if (dpnidPlayer != m_dpnidLocal && g_pNetMan)
			{
#if (GAME == GAME_THIEF)
#if 1
				DPN_PLAYER_INFO* pPeerInfo = GetPeerInfo(pDestroyPlayer->dpnidPlayer);
				if (pPeerInfo)
				{
					char playerName[kMaxPlayerName];
					WideToAnsi(playerName, pPeerInfo->pwszName, sizeof(playerName));
					const char* str = "%s has left the game.";
					MessageMgr::Get()->AddLineFormat(true, str, playerName);
					ConPrintF(str, playerName);

					SAFE_DELETE_ARRAY(pPeerInfo);
				}
#else
				const char* playerName = Players.NameFromDPNID(pDestroyPlayer->dpnidPlayer);
				const char* msg = "%s has left the game.";
				MessageMgr::Get()->AddLineFormat(true, msg, playerName);
				ConPrintF(msg, playerName);
#endif
#endif
				ZeroMemory(pDP4DestroyPlayer, sizeof(DPMSG_DESTROYPLAYERORGROUP));
				pDP4DestroyPlayer->lpLocalData = m_DP4PlayerData[dpnidPlayer];
				pDP4DestroyPlayer->dpId = dpnidPlayer;
				pDP4DestroyPlayer->dwType = DPSYS_DESTROYPLAYERORGROUP;
				pDP4DestroyPlayer->dwPlayerType = DPPLAYERTYPE_PLAYER;

				// send Thief the destroy player notification in the form it expects from DPlay 4
				NetMessage* pMsg = new NetMessage;
				pMsg->m_pMsgData = (BYTE*)pDP4DestroyPlayer;
				pMsg->m_size = sizeof(DPMSG_DESTROYPLAYERORGROUP);
				pMsg->m_dpnidSender = DPID_SYSMSG;

				m_DarkQueue.Push(pMsg);
				// find the player's index and destroy the player data
			}
			break;
		}

		case DPN_MSGID_INDICATE_CONNECT:
			{
				if (g_Net == STATE_Host)
				{
#ifndef _RELEASE
					if (Client.MissionStarted() && !Cfg.GetBool("AllowJoinsInProgress"))
#else
					if (Client.MissionStarted())
#endif
						return DPNERR_HOSTREJECTEDCONNECTION;
				}
				break;
			}

		case DPN_MSGID_CONNECT_COMPLETE:
			{
				PDPNMSG_CONNECT_COMPLETE pConnComplete = (PDPNMSG_CONNECT_COMPLETE)pMessage;

				if (pConnComplete->hResultCode == DPN_OK)
				{
#if (GAME == GAME_THIEF || GAME == GAME_DROMED)
					m_dpnidLocal = (pConnComplete->dpnidLocal);

					ConPrintF("Connected to session.");
					_SFX_Play_Raw(1, 0, "pickloot.wav");
#endif

					SetEvent(m_ConnectedEvent);
				}
				break;
			}

		case DPN_MSGID_ENUM_HOSTS_RESPONSE:
			{
				m_csEnumResponse.Lock();

				DPNMSG_ENUM_HOSTS_RESPONSE* pResponse = (DPNMSG_ENUM_HOSTS_RESPONSE*)pMessage;

				OnEnumerationResponse(pResponse);

				m_csEnumResponse.Unlock();
				break;
			}

      case DPN_MSGID_RECEIVE:
			{
				PDPNMSG_RECEIVE pRecvData = (PDPNMSG_RECEIVE)pMessage;
				Packet* packet = (Packet*)pRecvData->pReceiveData;

				csReceive.Lock();

				// this may not be a good idea... some original packets are very close to these numbers
				if (packet->type > NewPacketStart && packet->type < NewPacketEnd)
				{
					HandleNewPacket(pRecvData->pReceiveData, pRecvData->dwReceiveDataSize, pRecvData->dpnidSender);
					csReceive.Unlock();
					return DPN_OK;
				}

				NetMessage* pMsg = new NetMessage;

				pMsg->m_pMsgData = pRecvData->pReceiveData;
				pMsg->m_size = pRecvData->dwReceiveDataSize;
				pMsg->m_bufferHandle = pRecvData->hBufferHandle; // Save buffer handle so we can return it to DirectPlay with ReturnBuffer() later
				pMsg->m_dpnidSender = pRecvData->dpnidSender;

				m_DarkQueue.Push(pMsg);

				csReceive.Unlock();

				return DPNSUCCESS_PENDING;
			}

		case DPN_MSGID_TERMINATE_SESSION:
			{
				// Translate DPlay8's terminate session message to DPlay4
				PDPNMSG_TERMINATE_SESSION pTerminateSession = (PDPNMSG_TERMINATE_SESSION)pMessage;
				DPMSG_SESSIONLOST* pDP4SessLost = new DPMSG_SESSIONLOST;
				NetMessage* pMsg = new NetMessage;

				ZeroMemory(pDP4SessLost, sizeof(DPMSG_SESSIONLOST));
				pDP4SessLost->dwType = DPSYS_SESSIONLOST;

				pMsg->m_pMsgData = (BYTE*)pDP4SessLost;
				pMsg->m_size = sizeof(DPMSG_SESSIONLOST);
				pMsg->m_dpnidSender = DPID_SYSMSG;

				m_DarkQueue.Push(pMsg);

#if (GAME == GAME_THIEF || GAME == GAME_DROMED)
				if (pTerminateSession->pvTerminateData)
				{
					SDestroyReason* pMsg = (SDestroyReason*)pTerminateSession->pvTerminateData;

					switch (pMsg->reason)
					{
						case DReason_CrcFailed:
							Client.StartEndGameTimer(EndGameTime, ER_KickedCrc); break;
						default:
						case DReason_Kicked:
							Client.StartEndGameTimer(EndGameTime, ER_Kicked); break;
					}
				}
				else
					Client.StartEndGameTimer(EndGameTime, ER_HostLeft);
#endif
				break;
			}
	}

	return DPN_OK;
}
示例#7
0
//======================================================================================
// HandleCreatePlayerMsg()
//
// Handles create player system message from DPlay.
//======================================================================================
void CDarkPeer::HandleCreatePlayerMsg(DPNMSG_CREATE_PLAYER* pCreatePlayer)
{
	csReceive.Lock(); // Block packet receives while we're handling this

	// Translate DPlay8's create player message to DPlay4
	char playerName[kMaxPlayerName] = "";
	DPMSG_CREATEPLAYERORGROUP* pDP4CreatePlayer = new DPMSG_CREATEPLAYERORGROUP;

	// Retrieve the peer info and set the host and local DPNIDs
	DPN_PLAYER_INFO* pdpPlayerInfo = GetPeerInfo(pCreatePlayer->dpnidPlayer);

	//Log.Print("Connection from DPNID: %08x", pCreatePlayer->dpnidPlayer);

	if (pdpPlayerInfo)
	{
		if (pdpPlayerInfo->dwPlayerFlags == DPNPLAYER_HOST)
		{
			m_dpnidHost = pCreatePlayer->dpnidPlayer;

			if (Debug.IsFlagSet(DEBUG_NET))
				ConPrintF("Set host DPNID to %x.", m_dpnidHost);
		}
		else if (pdpPlayerInfo->dwPlayerFlags == DPNPLAYER_LOCAL)
			m_dpnidLocal = pCreatePlayer->dpnidPlayer;

		char playerName[kMaxPlayerName];
		WideToAnsi(playerName, pdpPlayerInfo->pwszName, kMaxPlayerName);

		// Display the connection message if this isn't the local player
		if (!(pdpPlayerInfo->dwPlayerFlags & DPNPLAYER_LOCAL))
		{
			ConPrintF("%s connected.", playerName);
			MessageMgr::Get()->AddLineFormat(false, "%s connected.", playerName);
		}

		SAFE_DELETE_ARRAY(pdpPlayerInfo);
	}
	else
		ConPrintF("Failed to get peer info for DPNID %x.", pCreatePlayer->dpnidPlayer);

	if (g_pNetMan->AmDefaultHost() && !IsStagingMode())
	{
		if (Client.MissionStarted())
		{
			IPtr<IQuestData> pQuest = _AppGetAggregated(IID_IQuestData);

			CNetMsg_StartMission msg;
			msg.difficulty = pQuest->Get("Difficulty");
			msg.missionID = _GetMissionData()->missNumber;

			Send(pCreatePlayer->dpnidPlayer, (void*)&msg, sizeof(CNetMsg_StartMission), NULL, DPNSEND_GUARANTEED | DPNSEND_NOLOOPBACK);
		}
	}

	if (g_Net == STATE_Client && m_bReceivedExistingPlayers || g_Net == STATE_Host)
	{
		if (pCreatePlayer->pvPlayerContext == this)
		{
			if (Debug.IsFlagSet(DEBUG_NET))
				ConPrintF("Creating local host. (%x)", pCreatePlayer->dpnidPlayer);
			m_dpnidLocal = (pCreatePlayer->dpnidPlayer);

			csReceive.Unlock();
			return;// DPN_OK;
		}

		// send Thief the new player notification in the form it expects from DPlay 4
		ZeroMemory(pDP4CreatePlayer, sizeof(DPMSG_CREATEPLAYERORGROUP));

		pDP4CreatePlayer->dwType = DPSYS_CREATEPLAYERORGROUP;
		pDP4CreatePlayer->dwPlayerType = DPPLAYERTYPE_PLAYER;
		pDP4CreatePlayer->dpId = pCreatePlayer->dpnidPlayer;

		NetMessage* pMsg = new NetMessage;
		pMsg->m_pMsgData = (BYTE*)pDP4CreatePlayer;
		pMsg->m_size = sizeof(DPMSG_CREATEPLAYERORGROUP);
		pMsg->m_dpnidSender = DPID_SYSMSG;

		m_DarkQueue.Push(pMsg);

#ifdef _THIEFBUILD
		_SFX_Play_Raw(1, 0, "pickloot.wav");
#endif

	}			

	csReceive.Unlock();
}