Esempio n. 1
0
void CRemoteConsole :: readPendingDatagrams()
{
	while (m_UDPSocket->hasPendingDatagrams()) {
		QByteArray datagram;
		datagram.resize(m_UDPSocket->pendingDatagramSize());
		QHostAddress sender;
		quint16 senderPort;
		
		m_UDPSocket->readDatagram(datagram.data(), datagram.size(),
								&sender, &senderPort);
		ProcessPacket( datagram, sender, senderPort );
		// echo
		m_UDPSocket->writeDatagram(datagram.data(), sender, senderPort);
	}
}
Esempio n. 2
0
void NetClient::ProcessIn( void )
{
	SDL_mutexP( Lock );
	
	// Process the entire incoming packet buffer.
	while( ! InBuffer.empty() )
	{
		Packet *packet = InBuffer.front();
		ProcessPacket( packet );
		delete packet;
		InBuffer.pop();
	}
	
	SDL_mutexV( Lock );
}
Esempio n. 3
0
int main()
{
    int saddr_size , data_size;
    struct sockaddr saddr;
    fptr=fopen("sniffer.csv","w");
    if(fptr==NULL)
    {
      printf("Error!");
      exit(1);
    }

    fprintf(fptr,"TCP,UDP,ICMP,ARP,DHCP,Total\n");
    unsigned char *buffer = (unsigned char *) malloc(65536); //Its Big!

    logfile=fopen("snifferlog.txt","w");
    if(logfile==NULL)
    {
        printf("Unable to create log.txt file.");
    }
    printf("Starting...\n");

    int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;

    if(sock_raw < 0)
    {
        //Print the error with proper message
        perror("Socket Error");
        return 1;
    }

    while(1)
    {
        saddr_size = sizeof saddr;
        //Receive a packet
        data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , (socklen_t*)&saddr_size);
        if(data_size <0 )
        {
            printf("Recvfrom error , failed to get packets\n");
            return 1;
        }
        //Now process the packet
        ProcessPacket(buffer , data_size);
    }
    fclose(fptr);
    close(sock_raw);
    printf("Finished");
    return 0;
}
Esempio n. 4
0
void Server::Run()
{
	Logger::Print("Server is now online and listening to incoming traffic");
	m_IsRunning = true;
	int nextAvailableID = 0;
	ENetEvent event;

	while (m_IsRunning)
	{
		while (enet_host_service(m_ENetHost, &event, 1000) > 0)
		{
			switch (event.type)
			{
			case ENET_EVENT_TYPE_CONNECT:
			{
				Client* c = new Client(this, event.peer, nextAvailableID);
				m_Clients.insert(std::pair<int, Client*>(nextAvailableID, c));
				nextAvailableID++;
				event.peer->data = c;
				Logger::Print("A new client connected from %x:%u assigned with id %d", event.peer->address.host, event.peer->address.port, m_Clients.size() - 1);
				break;
			}
			case ENET_EVENT_TYPE_RECEIVE:
			{
				ProcessPacket(event.packet, event.peer);
				enet_packet_destroy(event.packet);
				break;
			}
			case ENET_EVENT_TYPE_DISCONNECT:
			{
				m_ClientsMutex.lock();
				Client* c = m_Clients[event.data];
				event.peer->data = NULL;
				int playerID = c->GetPlayerID();
				m_Clients.erase(playerID);
				//delete c; //Delete the client after removed it reference from all other places
				//BroadcastPacket(std::make_shared<PacketPlayerDisconnected>(playerID), nullptr);
				Logger::Print("Client %d has disconnected", playerID);
				m_ClientsMutex.unlock();
				break;
			}
			}
		}
	}

	m_IsRunning = false;
}
Esempio n. 5
0
File: kate.c Progetto: CityFire/vlc
/****************************************************************************
 * DecodeBlock: the whole thing
 ****************************************************************************
 * This function must be fed with kate packets.
 ****************************************************************************/
static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
{
    decoder_sys_t *p_sys = p_dec->p_sys;
    block_t *p_block;
    kate_packet kp;

    if( !pp_block || !*pp_block )
        return NULL;

    p_block = *pp_block;
    *pp_block = NULL;

    if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
    {
#ifdef HAVE_TIGER
        if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY)
        {
            /* Hmm, should we wait before flushing the renderer ? I think not, but not certain... */
            vlc_mutex_lock( &p_sys->lock );
            tiger_renderer_seek( p_sys->p_tr, 0 );
            vlc_mutex_unlock( &p_sys->lock );
        }
#endif
        if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
        {
            p_sys->i_max_stop = VLC_TS_INVALID;
            block_Release( p_block );
            return NULL;
        }
    }

    /* Block to Kate packet */
    kate_packet_wrap(&kp, p_block->i_buffer, p_block->p_buffer);

    if( !p_sys->b_has_headers )
    {
        if( ProcessHeaders( p_dec ) )
        {
            block_Release( *pp_block );
            return NULL;
        }
        p_sys->b_has_headers = true;
    }

    return ProcessPacket( p_dec, &kp, pp_block );
}
Esempio n. 6
0
void SocketHandler::OnRead()
{
    char *curChar = new char;
    while(m_socket->read(curChar, 1) > (qint64)0)
    {
        if(*curChar != 0x00)
        {
            if(*curChar != '\n' && *curChar != '\r')
                m_packet += *curChar;
        }
        else // Fin d'un packet détectée
        {
            ProcessPacket(m_packet);
            m_packet = "";
        }
    }
}
Esempio n. 7
0
void NetworkManager::ProcessQueuedPackets()
{
	//look at the front packet...
	while( !mPacketQueue.empty() )
	{
		ReceivedPacket& nextPacket = mPacketQueue.front();
		if( Timing::sInstance.GetTimef() > nextPacket.GetReceivedTime() )
		{
			ProcessPacket( nextPacket.GetPacketBuffer(), nextPacket.GetFromPlayer() );
			mPacketQueue.pop();
		}
		else
		{
			break;
		}
	
	}

}
Esempio n. 8
0
void Server::ReadPacket()
{
	DWORD iobyte, ioflag = 0;

	int ret = WSARecv(sock, &WSA_recv_buf, 1, &iobyte, &ioflag, NULL, NULL);
	if (ret != 0)
	{
		int err_code = WSAGetLastError();
		cout << "Recv Error : " << err_code << endl;
	}
	cout << "recv" << endl;
	BYTE *ptr = reinterpret_cast<BYTE*>(Recv_buf);

	while (0 != iobyte)
	{
		if (in_packet_size == 0)
		{
			in_packet_size = ptr[0];
		}

		if (iobyte + save_packet_size >= in_packet_size)
		{
			memcpy(Complete_buf + save_packet_size,
				ptr,
				in_packet_size - save_packet_size);

			ProcessPacket(Complete_buf);

			ptr += in_packet_size - save_packet_size;
			iobyte -= in_packet_size - save_packet_size;
			in_packet_size = 0;
			save_packet_size = 0;
		}
		else
		{
			memcpy(Complete_buf + save_packet_size, ptr, iobyte);
			save_packet_size += iobyte;
			iobyte = 0;
		}

	}
}
Esempio n. 9
0
/****************************************************************************
 * DecodeBlock: the whole thing
 ****************************************************************************
 * This function must be fed with ogg packets.
 ****************************************************************************/
static block_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
{
    decoder_sys_t *p_sys = p_dec->p_sys;
    ogg_packet oggpacket;

    if( !pp_block ) return NULL;

    if( *pp_block )
    {
        /* Block to Ogg packet */
        oggpacket.packet = (*pp_block)->p_buffer;
        oggpacket.bytes = (*pp_block)->i_buffer;
    }
    else
    {
        if( p_sys->b_packetizer ) return NULL;

        /* Block to Ogg packet */
        oggpacket.packet = NULL;
        oggpacket.bytes = 0;
    }

    oggpacket.granulepos = -1;
    oggpacket.b_o_s = 0;
    oggpacket.e_o_s = 0;
    oggpacket.packetno = 0;

    /* Check for headers */
    if( !p_sys->b_has_headers )
    {
        if( ProcessHeaders( p_dec ) )
        {
            if( *pp_block )
                block_Release( *pp_block );
            return NULL;
        }
        p_sys->b_has_headers = true;
    }

    return ProcessPacket( p_dec, &oggpacket, pp_block );
}
Esempio n. 10
0
//-----------------------------------------------------------------------------------------------
//Private Methods
//-----------------------------------------------------------------------------------------------
void Server::ReceiveMessagesFromClientsIfAny()
{
	Network& theNetwork = Network::GetInstance();

	int bytesReceived = 0;
	CS6Packet receivedPacket;

	do 
	{
		bytesReceived = 0;
		ZeroMemory( &receivedPacket, sizeof( receivedPacket ) );

		bytesReceived = theNetwork.ReceiveUDPMessage( ( char* )&receivedPacket, sizeof( receivedPacket ), m_listenConnectionID );

		if( bytesReceived == sizeof( CS6Packet ) )
		{
			ProcessPacket( receivedPacket );
		}
	} 
	while ( bytesReceived > 0 );
}
Esempio n. 11
0
void StartSniffing(SOCKET sniffer)
{
	BYTE *Buffer = new BYTE[65536]; //Its Big!
	int  mangobyte;
	
	if (Buffer == NULL)
	{
		printf("malloc() failed.\n");
		return;
	}

	do
	{
		mangobyte = recvfrom(sniffer,(char*)Buffer,65536,0,0,0); //Eat as much as u can
		if(mangobyte > 0)	ProcessPacket(Buffer, mangobyte);
		else printf( "recvfrom() failed.\n");
	} 
	while (mangobyte > 0);

	delete [] Buffer;
}
Esempio n. 12
0
bool CServerSocket::PacketReceived(Packet* packet)
{
#ifndef _DEBUG
	try {
#endif
		theStats.AddDownDataOverheadServer(packet->size);
		if (packet->prot == OP_PACKEDPROT)
		{
			uint32 uComprSize = packet->size;
			if (!packet->UnPackPacket(250000)){
				if (thePrefs.GetVerbose())
					DebugLogError(_T("Failed to decompress server TCP packet: protocol=0x%02x  opcode=0x%02x  size=%u"), packet ? packet->prot : 0, packet ? packet->opcode : 0, packet ? packet->size : 0);
				return true;
			}
			packet->prot = OP_EDONKEYPROT;
			if (thePrefs.GetDebugServerTCPLevel() > 1)
				Debug(_T("Received compressed server TCP packet; opcode=0x%02x  size=%u  uncompr size=%u\n"), packet->opcode, uComprSize, packet->size);
		}

		if (packet->prot == OP_EDONKEYPROT)
		{
			ProcessPacket((const BYTE*)packet->pBuffer, packet->size, packet->opcode);
		}
		else
		{
			if (thePrefs.GetVerbose())
				DebugLogWarning(_T("Received server TCP packet with unknown protocol: protocol=0x%02x  opcode=0x%02x  size=%u"), packet ? packet->prot : 0, packet ? packet->opcode : 0, packet ? packet->size : 0);
		}
#ifndef _DEBUG
	}
	catch(...)
	{
		if (thePrefs.GetVerbose())
			DebugLogError(_T("Error: Unhandled exception while processing server TCP packet: protocol=0x%02x  opcode=0x%02x  size=%u"), packet ? packet->prot : 0, packet ? packet->opcode : 0, packet ? packet->size : 0);
		ASSERT(0);
		return false;
	}
#endif
	return true;
}
Esempio n. 13
0
int main()
{
    int saddr_size , data_size;
    struct sockaddr saddr;
         
    unsigned char *buffer = (unsigned char *) malloc(65536); //Its Big!
     
    logfile=fopen("log.txt","w");
    if(logfile==NULL) 
    {
        printf("Unable to create log.txt file.");
    }
    printf("Starting...\n");
     
    int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
    //setsockopt(sock_raw , SOL_SOCKET , SO_BINDTODEVICE , "eth0" , strlen("eth0")+ 1 );
     
    if(sock_raw < 0)
    {
        //Print the error with proper message
        perror("Socket Error");
        return 1;
    }
    while(1)
    {
        saddr_size = sizeof saddr;
        //Receive a packet
        data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , (socklen_t*)&saddr_size);
        if(data_size <0 )
        {
            printf("Recvfrom error , failed to get packets\n");
            return 1;
        }
        //Now process the packet
        ProcessPacket(buffer , data_size);
    }
    close(sock_raw);
    printf("Finished");
    return 0;
}
void AReplayPlayer::SeekToIncident(EPlaybackDirection NewDirection) {
	Direction = NewDirection;
	Paused = true;

	msgpack_object* obj = NULL;
	while (true) {
		if (Direction == EPlaybackDirection::PD_Forward) {
			obj = NextPacket();
		}
		else{
			obj = PrevPacket();
		}

		if (!obj) {
			Paused = true;
			Time = CurrentTime;
			Stats->SetTimePaused(CurrentTime - StartTime);
			return;
		}
		if (!(obj->type == MSGPACK_OBJECT_ARRAY)) {
			continue;
		}
		check(obj->type == MSGPACK_OBJECT_ARRAY);

		ProcessPacket(obj);

		msgpack_object* p = obj->via.array.ptr;
		const uint8 Type = p[1].via.u64;
		Time = CurrentTime;

		if (Type == VEHICLES_CRASHED) {
			break;
		}
	}

	Stats->SetTimePaused(CurrentTime - StartTime);

	UpdateActors();

}
Esempio n. 15
0
/****************************************************************************
 * DecodeBlock: the whole thing
 ****************************************************************************
 * This function must be fed with ogg packets.
 ****************************************************************************/
static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
{
    decoder_sys_t *p_sys = p_dec->p_sys;
    block_t *p_block;
    ogg_packet oggpacket;

    if( !pp_block || !*pp_block ) return NULL;

    p_block = *pp_block;

    /* Block to Ogg packet */
    oggpacket.packet = p_block->p_buffer;
    oggpacket.bytes = p_block->i_buffer;
    oggpacket.granulepos = p_block->i_dts;
    oggpacket.b_o_s = 0;
    oggpacket.e_o_s = 0;
    oggpacket.packetno = 0;

    /* Check for headers */
    if( !p_sys->b_has_headers )
    {
        if( ProcessHeaders( p_dec ) )
        {
            block_Release( p_block );
            return NULL;
        }
        p_sys->b_has_headers = true;
    }

    /* If we haven't seen a single keyframe yet, set to preroll,
     * otherwise we'll get display artifacts.  (This is impossible
     * in the general case, but can happen if e.g. we play a network stream
     * using a timed URL, such that the server doesn't start the video with a
     * keyframe). */
    if( !p_sys->b_decoded_first_keyframe )
        p_block->i_flags |= BLOCK_FLAG_PREROLL; /* Wait until we've decoded the first keyframe */

    return ProcessPacket( p_dec, &oggpacket, pp_block );
}
Esempio n. 16
0
bool WorldSocket::ProcessIncomingData()
{
    while (read_buffer_->length() > 0)
    {
        if (!received_header_)
        {
            if (!ReadPacketHeader())
                return true;

            if (!ValidatePacketHeader())
                return false;
        }

        if (!ReadPacketContent())
            return true;

        if (!ProcessPacket(packet_))
            return false;
    }

    return true;
}
Esempio n. 17
0
void EQStream::Process(const unsigned char *buffer, const uint32 length)
{
static unsigned char newbuffer[2048];
uint32 newlength=0;
	if (EQProtocolPacket::ValidateCRC(buffer,length,Key)) {
		if (compressed) {
			newlength=EQProtocolPacket::Decompress(buffer,length,newbuffer,2048);
		} else {
			memcpy(newbuffer,buffer,length);
			newlength=length;
			if (encoded)
				EQProtocolPacket::ChatDecode(newbuffer,newlength-2,Key);
		}
		if (buffer[1]!=0x01 && buffer[1]!=0x02 && buffer[1]!=0x1d)
			newlength-=2;
		EQProtocolPacket *p = MakeProtocolPacket(newbuffer,newlength);
		ProcessPacket(p);
		delete p;
		ProcessQueue();
	} else {
		Log.Out(Logs::Detail, Logs::Netcode, _L "Incoming packet failed checksum" __L);
	}
}
int ToshibaReceiveByte( unsigned char byte )
{
    if( strlen(toshiba_state.response) > 0 )
    {
        memset( toshiba_state.response, 0, sizeof(toshiba_state.response) );
    }

    if( byte == 0x0d )
    {
        /* Finished packet */
        if( PACKET_DEBUG ) { PrintHex( "= Incoming: ", (const unsigned char *)toshiba_state.packet, strlen(toshiba_state.packet) ); }
        ProcessPacket( toshiba_state.packet, toshiba_state.response );
        memset( toshiba_state.packet, 0, sizeof(toshiba_state.packet) );
        return 1;
    }
    else
    {
        /* Add to received data */
        toshiba_state.packet[strlen(toshiba_state.packet)] = byte;
    }

    return 0;
}
Esempio n. 19
0
int main()
{
	int saddr_size , data_size;
	struct sockaddr saddr;
	struct in_addr in;
	
	unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big!
	
	logfile=fopen("log.txt","w");
	if(logfile==NULL) printf("Unable to create file.");
	//Create a raw socket that shall sniff
	sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_IP);
	//sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
	//sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_RAW);
	if(sock_raw < 0)
	{
		printf("Socket Error\n");
		return 1;
	}
	while(1)
	{
		saddr_size = sizeof saddr;
		//Receive a packet
		data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , &saddr_size);
		if(data_size <0 )
		{
			printf("Recvfrom error , failed to get packets\n");
			return 1;
		}
		printf("Starting...\n");
		//Now process the packet
		ProcessPacket(buffer , data_size);
	}
	close(sock_raw);
	printf("Finished");
	return 0;
}
Esempio n. 20
0
void MainWindow::readDatagrams()
{
    packet p;

    int randomValue = qrand() % ((100 + 1) - 0) + 0;


    if (socket->hasPendingDatagrams())
    {

        if (randomValue >= bit_error_rate)
        {
            socket->readDatagram((char*)&p, sizeof(p));
            ProcessPacket(p);
        }
        else
        {
            socket->readDatagram((char*)&p, sizeof(p));
            AppendToLog("Dropping packet: ");
            PrintPacketInfo(p);

        }
    }
}
Esempio n. 21
0
void WorkerThreadFunc(void)
{
	DWORD ioSize, key;
	OverlapEx *overlap;
	BOOL result;
	Client *clientData = nullptr;

	while (true)
	{
		result = GetQueuedCompletionStatus(ghIOCP, &ioSize, reinterpret_cast<PULONG_PTR>(&key), reinterpret_cast<LPOVERLAPPED*>(&overlap), INFINITE);

		if (false == result || 0 == ioSize)
		{
			if (false == result)
				DisplayErrMsg("WorkerThread :: GetQueuedCompletionStatus Fail !!", GetLastError());

			if (WSAENOTSOCK == GetLastError() || ERROR_NETNAME_DELETED == GetLastError() || 0 == ioSize)
			{
				gClientInfoSet->Search(key, &clientData);
				clientData->isConnect = false;
				closesocket(clientData->socket);

				// ToDo : 10054 error 처리
				// 각 플레이어에게 플레이어 접속 종료 알림
				Packet::Disconnect packet;
				packet.size = sizeof(Packet::Disconnect);
				packet.type = PacketType::Disconnect;
				packet.id = key;

				BroadcastingExceptIndex(key, reinterpret_cast<unsigned char*>(&packet));
				gClientInfoSet->Remove(key);

				std::string debugText = "WorkerThread :: Disconnect " + std::to_string(key) + " client. :(";
				DisplayDebugText(debugText);
			}
			continue;
		}
		if (OP_RECV == overlap->operation)
		{
			gClientInfoSet->Search(key, &clientData);
			
			unsigned char *buf_ptr = overlap->buffer;
			int remained = ioSize;
			while (0 < remained)
			{
				if (0 == clientData->recvOverlap.packetSize)
					clientData->recvOverlap.packetSize = buf_ptr[0];
				int required = clientData->recvOverlap.packetSize - clientData->previousDataSize;
				// 패킷을 완성 시킬 수 있는가? 없는가?
				if (remained >= required)
				{
					// 완성을 시킬 수 있는 상황이면
					// 패킷을 어떠한 공간에다가 고이 모셔와야 한다.
					// 그래서 패킷을 완성시키는 저장공간이 별도로 있어야한다. 
					// 데이터가 패킷단위로 오는 것이 아니기 때문에 패킷단위로 처리하고 남은데이터는 그 별도의 공간에 저장해야
					// 다음의 온 데이터가 온전하지 못한 채로 오게되면 별도의 공간에 집어넣고 하나의 패킷으로 마저 만들어 주어야 한다.
					memcpy(clientData->packetBuf + clientData->previousDataSize, buf_ptr, required);
					// +하는 이유는 지난번에 받은 데이터 이후에 저장을 해야하기 때문에 그 시작위치로 옮겨줌.
					ProcessPacket(key, clientData->packetBuf);
					// Packet 처리
					remained -= required;
					// 날아 있는 것은 필요한 것을 제외하고
					buf_ptr += required;
					// ???
					clientData->recvOverlap.packetSize = 0;
				}
				else
				{
					// 패킷을 완성 시킬 수 없는 크기이다.
					memcpy(clientData->packetBuf + clientData->previousDataSize, buf_ptr, remained);
					// buf_ptr의 모든 것을 packet에 저장한다.
					clientData->previousDataSize += remained;
					// 이전의 데이터가 남아있는 사이즈만큼 늘어났다.
					remained = 0;
					// 현재 recv의 남아있는 size는 이미 저장을 해두었으므로 초기화
				}
			}
			DWORD flags = 0;
			WSARecv(clientData->socket,
				&clientData->recvOverlap.wsaBuf,
				1, NULL, &flags,
				reinterpret_cast<LPWSAOVERLAPPED>(&clientData->recvOverlap),
				NULL);
		}
		else if (OP_SEND == overlap->operation)
		{
			// ioSize하고 실제 보낸 크기 비교 후 소켓 접속 끊기
			BYTE packetType = overlap->buffer[1];
			BYTE packetSize = overlap->buffer[0];

			if (BeCompeletedSendPacket(packetType, packetSize))
				delete overlap;
			else
			{
				std::string debugText = "WorkerThread :: " + std::to_string(key) + " client don't send " + std::to_string(packetType) + "No. packet";
				DisplayDebugText(debugText);
			}
		}
		else
		{
			DisplayDebugText("WorkerThread :: Unknown Event on worker_thread");
			continue;
		}
	}
	return;
}
Esempio n. 22
0
/**
 @brief 
*/
void XEWinConnectionInServer::Process( void )
{
	XPROF_OBJ_AUTO();
	// XWinSocketSvr::Process()에서 커넥션별로 락걸어서 들어오고 있음.
// 	XLOCK_OBJ;
	// 소켓이 끊어졌으면 더이상 돌필요 없다.
// 	if( m_Socket == 0 )		// 
// 		return;
	// 쌓인 패킷 다 뽑아낼때까지 락걸어두자 패킷 계속오면 계속 못빠져나올수도...
	if( !GetbDestroy() ) {
		// 만약 커넥션 프로세스도 멀티스레드에서 돌아가면 이거 전체를 락걸어야 한다.
		// 자동연결해제 옵션이 있으면 허트비트 처리
		if( GetbAutoDisconnect() ) {
			XPROF_OBJ("ProcessHeartBeat");
			ProcessHeartBeat();
		}
		//////////////////////////////////////////////////////////////////////////
		{
			XPROF_OBJ( "PumpPacket" );
			XENetworkConnection::xtError err = XENetworkConnection::xERR_NOERROR;
			XPacket p( true );
			// 		while( PumpPacket( &p ) )	{
			// 패킷 한번만 뽑고 넘어감.
			auto bPump = PumpPacket( &p, &err );
			if( bPump ) {
				XPROF_OBJ( "ProcessPacket" );
#ifdef _XCRYPT_PACKET
				BOOL bOk = FALSE;
				if( m_pSocketSvr->GetbEncryption() ) {
					bOk = p.DoDecrypto( m_pSocketSvr );
				}
#endif
				DWORD idPacket;
				p >> idPacket;
				ID idKey;
				p >> idKey;
				// 예약된 패킷 처리
				if( idPacket == XE::xXEPK_RESPONSE_HB )	{
#ifdef _DEBUG
					//			CONSOLE("recv heart beat");
#endif
					// 응답이 왔으므로 다시 대기상태로...
					m_timerHeartBeat.Off();
					m_modeHeartBeat = xHB_READY;
				}
				else {
					p._SetidPacket( idPacket );
					BOOL result = ProcessPacket( idPacket, idKey, p );
					if( result == FALSE ) {		// virtual call
						// 패킷 처리에 실패함. 접속 끊어야 함.
						// 일단 커넥션만 끊음.
						DoDisconnect();
						//					break;
					}
				}
				p.Clear();
			} else {
				if( err != XENetworkConnection::xERR_NOERROR ) {
					CONSOLE( "%s:PumpPacket실패:ip=%s", __TFUNC__, m_szIP );
				}
			}
		}
	} // bDestroy
Esempio n. 23
0
void CClientUDPSocket::OnReceive(int nErrorCode)
{
	if (nErrorCode)
	{
		if (thePrefs.GetVerbose())
			DebugLogError(_T("Error: Client UDP socket, error on receive event: %s"), GetErrorMessage(nErrorCode, 1));
	}

	BYTE buffer[5000];
	SOCKADDR_IN sockAddr = {0};
	int iSockAddrLen = sizeof sockAddr;
	int length = ReceiveFrom(buffer, sizeof buffer, (SOCKADDR*)&sockAddr, &iSockAddrLen);
	if (length >= 1 && !(theApp.ipfilter->IsFiltered(sockAddr.sin_addr.S_un.S_addr) || theApp.clientlist->IsBannedClient(sockAddr.sin_addr.S_un.S_addr)))
    {
		CString strError;
		try
		{
			switch (buffer[0])
			{
				case OP_EMULEPROT:
				{
					if (length >= 2)
						ProcessPacket(buffer+2, length-2, buffer[1], sockAddr.sin_addr.S_un.S_addr, ntohs(sockAddr.sin_port));
					else
						throw CString(_T("eMule packet too short"));
					break;
				}
				case OP_KADEMLIAPACKEDPROT:
				{
					theStats.AddDownDataOverheadKad(length);
					if (length >= 2)
					{
						uint32 nNewSize = length*10+300;
						byte* unpack = new byte[nNewSize];
						uLongf unpackedsize = nNewSize-2;
						int iZLibResult = uncompress(unpack+2, &unpackedsize, buffer+2, length-2);
						if (iZLibResult == Z_OK)
						{
							unpack[0] = OP_KADEMLIAHEADER;
							unpack[1] = buffer[1];
							try
							{
								Kademlia::CKademlia::processPacket(unpack, unpackedsize+2, ntohl(sockAddr.sin_addr.S_un.S_addr), ntohs(sockAddr.sin_port));
							}
							catch(...)
							{
								delete[] unpack;
								throw;
							}
						}
						else
						{
							delete[] unpack;
							CString strError;
							strError.Format(_T("Failed to uncompress Kad packet: zip error: %d (%hs)"), iZLibResult, zError(iZLibResult));
							throw strError;
						}
						delete[] unpack;
					}
					else
						throw CString(_T("Kad packet (compressed) too short"));
					break;
				}
				case OP_KADEMLIAHEADER:
				{
					theStats.AddDownDataOverheadKad(length);
					if (length >= 2)
						Kademlia::CKademlia::processPacket(buffer, length, ntohl(sockAddr.sin_addr.S_un.S_addr), ntohs(sockAddr.sin_port));
					else
						throw CString(_T("Kad packet too short"));
					break;
				}
				default:
				{
					CString strError;
					strError.Format(_T("Unknown protocol 0x%02x"), buffer[0]);
					throw strError;
				}
			}
		}
		catch(CFileException* error)
		{
			error->Delete();
			strError = _T("Invalid packet received");
		}
		catch(CMemoryException* error)
		{
			error->Delete();
			strError = _T("Memory exception");
		}
		catch(CString error)
		{
			strError = error;
		}
		catch(Kademlia::CIOException* error)
		{
			error->Delete();
			strError = _T("Invalid packet received");
		}
		catch(CException* error)
		{
			error->Delete();
			strError = _T("General packet error");
		}
		catch(...)
		{
			strError = _T("Unknown exception");
			ASSERT(0);
		}

		if (thePrefs.GetVerbose() && !strError.IsEmpty())
		{
			CString strClientInfo;
			CUpDownClient* client;
			if (buffer[0] == OP_EMULEPROT)
				client = theApp.clientlist->FindClientByIP_UDP(sockAddr.sin_addr.S_un.S_addr, ntohs(sockAddr.sin_port));
			else
				client = theApp.clientlist->FindClientByIP_KadPort(sockAddr.sin_addr.S_un.S_addr, ntohs(sockAddr.sin_port));
			if (client)
				strClientInfo = client->DbgGetClientInfo();
			else
				strClientInfo.Format(_T("%s:%u"), ipstr(sockAddr.sin_addr), ntohs(sockAddr.sin_port));

			DebugLogWarning(_T("Client UDP socket: prot=0x%02x  opcode=0x%02x  size=%u  %s: %s"), buffer[0], buffer[1], length, strError, strClientInfo);
		}
    }
	else if (length == SOCKET_ERROR)
	{
		DWORD dwError = WSAGetLastError();
		if (dwError == WSAECONNRESET)
		{
			// Depending on local and remote OS and depending on used local (remote?) router we may receive
			// WSAECONNRESET errors. According some KB articles, this is a special way of winsock to report 
			// that a sent UDP packet was not received by the remote host because it was not listening on 
			// the specified port -> no eMule running there.
			//
			// TODO: So, actually we should do something with this information and drop the related Kad node 
			// or eMule client...
			;
		}
		if (thePrefs.GetVerbose() && dwError != WSAECONNRESET)
		{
			CString strClientInfo;
			if (iSockAddrLen > 0 && sockAddr.sin_addr.S_un.S_addr != 0 && sockAddr.sin_addr.S_un.S_addr != INADDR_NONE)
				strClientInfo.Format(_T(" from %s:%u"), ipstr(sockAddr.sin_addr), ntohs(sockAddr.sin_port));
			DebugLogError(_T("Error: Client UDP socket, failed to receive data%s: %s"), strClientInfo, GetErrorMessage(dwError, 1));
		}
	}
}
Esempio n. 24
0
int main(int argc,char *argv[])
{

	//FILE *fp;
	//char file[15];
	//strcpy(file,argv[1]);
	//strcat(file,".txt");

	//fp=fopen(file,"wt");

	//*stdout = *fp;

	//memset( &player,'-1' ,sizeof(player) );
	player.iUid = -1;

	for(int i = 0 ; i < MAX_USERS_CLI ; ++i )
	{
		players[i].iUid = -1;
		players[i].bOnline = false;
	}

	//----------------------for RWP--------------------------
	srand( (unsigned)time( NULL ) );
	player.iState = 0;
	//-------------------------------------------------------

	Initial();
	strcpy ( player.sUserName,argv[1]);
	int show = ( atoi(argv[3]) );

	WSADATA wsaData;
	if( SOCKET_ERROR == WSAStartup( WINSOCK_VERSION, &wsaData ) || wsaData.wVersion != WINSOCK_VERSION )
		return false;

	//------------------for user login to gs request zone ip----------------
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in addr;
	ZeroMemory( &addr, sizeof(addr) );

	addr.sin_family = AF_INET;
	addr.sin_port   = htons(atoi(gs_port));
	addr.sin_addr.S_un.S_addr   = inet_addr(gs_ip);

	connect( sockfd, (struct sockaddr *)&addr , sizeof(struct sockaddr));

	UserLogInToGS ultg;
	strcpy ( ultg.sUserName,player.sUserName);
	strcpy ( ultg.sPass,argv[2]);

	SendTCPPacket( sockfd, (char *)&ultg , sizeof(ultg) );

	char buf[MAX_PACKET_SIZE];
	ZeroMemory( &buf, sizeof(buf) );

	RecvTCPPacket( sockfd, (char *)&buf );

	int try_num = 0;
	while(try_num < 3)
	{
		MessageHeader * tMh = (MessageHeader*)buf;

		if(tMh->MsgID == MSG_USERREJECT)
		{
			UserReject *urm = (UserReject *)buf;
			switch(urm->rWhy)
			{
			case 	R_NOTEXIST:
				{
					printf("Wrong username!!!\n");
				}break;
			case	R_FULL:
				{
					printf("zone server FULL!!!\n");
				}break;
			case	R_WRONGPASS:
				{
					printf("Pass wrong!!!\n");
				}break;
			}

			printf("Retry ? (username pass)\n");
			scanf("%s %s\n",&ultg.sUserName,&ultg.sPass );

			SendTCPPacket( sockfd, (char *)&ultg , sizeof(ultg) );
		}else
		{
			UserZoneInfo *uzi = (UserZoneInfo *)buf;
			player.iUid = uzi->iUid;
			player.iZid = uzi->iZid;
			strcpy ( player.sIP, uzi->sZip );
			strcpy ( player.sPort , uzi->sZport );		

			printf("uid = %d get zone info ip %s,port %s\n",player.iUid,player.sIP,player.sPort);
			break;
		}

		ZeroMemory( &buf, sizeof(buf) );
		++try_num;
		RecvTCPPacket(sockfd, (char *)&buf);
	}
	closesocket(sockfd);

	//---------------get zone info and go to login mx and zone---------------
	printf("Manual control ? (y/n)\n (W,S,A,D direction,Q exit)\n");
	scanf("%c",&con);

	if(show)
	{
		if( NULL == CreateThread( NULL, 0, glut_Thread, player.sUserName, 0, NULL ))
			return -1;
	}

	if( SOCKET_ERROR == (sMXSocket = socket( AF_INET, SOCK_STREAM, 0 )))
	{
		printf("Socket Error !!!!\n");
		return false;
	}

	if( ConnectToMX( ) )
	{	
		fLastUpdate = 0.0f;

		int nready;
		struct timeval timeout;

		FD_ZERO(&rset);
		FD_ZERO(&temprset);
		FD_SET( sMXSocket, &rset);
		int maxfdp1 = sMXSocket + 1;

		//int time1 = GetTickCount();

		//int time2;

		//int attack_t = 50;

		while(true)
		{
			/*
			time2 = GetTickCount();

			if( ((time2 - time1)>1) && player.iUid == 1 && attack_t != 0 )
			{
				UserComToMX ucm;
				ucm.iUid_S = player.iUid;
				ucm.iUid_D = 10;
				ucm.cCom = C_ATTACK;
				ucm.iTime = time2;
				printf("attack uid=10!!\n");
				SendTCPPacket( sMXSocket, (char*)&ucm, sizeof(ucm) );
				--attack_t;
				time1 = time2;
			}
			*/
			if(con == 'n')
				UpdatePlayer();
			FD_ZERO(&temprset);
			temprset = rset;
			timeout.tv_sec = 0;
			timeout.tv_usec = 5000;

			if ( (nready = select(maxfdp1, &temprset, NULL, NULL, &timeout)) < 0)
			{
				break;

			}else if( nready == 0)
			{
				if(con == 'n')
					UpdatePlayer();
				continue;
			}

			if (FD_ISSET(sMXSocket, &temprset))
			{
				char buffer[MAX_PACKET_SIZE];
				ZeroMemory( buffer, sizeof(buffer) );
				RecvTCPPacket( sMXSocket , (char *)&buffer );

				ProcessPacket( (char *)&buffer );
			}
		}

	}

	closesocket( sMXSocket );
	WSACleanup();
	//fclose( fp );

	return 0;
}
Esempio n. 25
0
void SocketHandler::OnRead()
{
    ProcessPacket();
}
Esempio n. 26
0
bool CClientThread::RecvMessage(void)
{
	_i32 rc;
	timeval lon;
	lon.tv_usec=0;
	lon.tv_sec=60;
	rc=clientpipe->isReadable(lon.tv_sec*1000)?1:0;
	if(clientpipe->hasError())
		rc=-1;
	if( rc==0 )
	{
		if(state==CS_NONE)
		{
			Log("1 min Timeout deleting Buffers ("+nconvert((NBUFFERS*READSIZE)/1024 )+" KB) and waiting 1h more...", LL_DEBUG);
			delete bufmgr;
			bufmgr=NULL;
			lon.tv_sec=3600;
			int n=0;
			while(stopped==false && rc==0 && n<60)
			{
				rc=clientpipe->isReadable(lon.tv_sec*1000);
				if(clientpipe->hasError())
					rc=-1;
				++n;
			}
		}
	}
	
	if( rc<1)
	{
		Log("Select Error/Timeout in RecvMessage", LL_DEBUG);

		return false;
	}
	else
	{
		rc=(_i32)clientpipe->Read(buffer, BUFFERSIZE, lon.tv_sec*1000);


		if(rc<1)
		{
			Log("Recv Error in RecvMessage", LL_DEBUG);
			return false;
		}
		else
		{
			Log("Received data...");
			stack.AddData(buffer, rc);				
		}

		size_t packetsize;
		char* packet;
		while( (packet=stack.getPacket(&packetsize)) != NULL )
		{
			Log("Received a Packet.", LL_DEBUG);
			CRData data(packet, packetsize);

			bool b=ProcessPacket( &data );
			delete[] packet;

			if( b==false )
				return false;
		}
	}
	return true;
}
Esempio n. 27
0
void EQStream::ProcessPacket(EQProtocolPacket *p)
{
uint32 processed=0,subpacket_length=0;
	if (p == NULL)
		return;
	// Raw Application packet
	if (p->opcode > 0xff) {
		p->opcode = htons(p->opcode);  //byte order is backwards in the protocol packet
		EQRawApplicationPacket *ap=MakeApplicationPacket(p);
		if (ap)
			InboundQueuePush(ap);
		return;
	}

	if (!Session && p->opcode!=OP_SessionRequest && p->opcode!=OP_SessionResponse) {
		_log(NET__DEBUG, _L "Session not initialized, packet ignored" __L);
		_raw(NET__DEBUG, 0xFFFF, p);
		return;
	}

	switch (p->opcode) {
		case OP_Combined: {
			processed=0;
			while(processed < p->size) {
				subpacket_length=*(p->pBuffer+processed);
				EQProtocolPacket *subp=MakeProtocolPacket(p->pBuffer+processed+1,subpacket_length);
				_log(NET__NET_CREATE, _L "Extracting combined packet of length %d" __L, subpacket_length);
				_raw(NET__NET_CREATE_HEX, 0xFFFF, subp);
				subp->copyInfo(p);
				ProcessPacket(subp);
				delete subp;
				processed+=subpacket_length+1;
			}
		}
		break;
		
		case OP_AppCombined: {
			processed=0;
			while(processed<p->size) {
				EQRawApplicationPacket *ap=NULL;
				if ((subpacket_length=(unsigned char)*(p->pBuffer+processed))!=0xff) {
					_log(NET__NET_CREATE, _L "Extracting combined app packet of length %d, short len" __L, subpacket_length);
					ap=MakeApplicationPacket(p->pBuffer+processed+1,subpacket_length);
					processed+=subpacket_length+1;
				} else {
					subpacket_length=ntohs(*(uint16 *)(p->pBuffer+processed+1));
					_log(NET__NET_CREATE, _L "Extracting combined app packet of length %d, short len" __L, subpacket_length);
					ap=MakeApplicationPacket(p->pBuffer+processed+3,subpacket_length);
					processed+=subpacket_length+3;
				}
				if (ap) {
					ap->copyInfo(p);
					InboundQueuePush(ap);
				}
			}
		}
		break;
		
		case OP_Packet: {
			if(!p->pBuffer || (p->Size() < 4))
			{
				_log(NET__ERROR, _L "Received OP_Packet that was of malformed size" __L);
				break;
			}
			uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
			SeqOrder check=CompareSequence(NextInSeq,seq);
			if (check == SeqFuture) {
					_log(NET__DEBUG, _L "Future OP_Packet: Expecting Seq=%d, but got Seq=%d" __L, NextInSeq, seq);
					_raw(NET__DEBUG, seq, p);

					PacketQueue[seq]=p->Copy();
					_log(NET__APP_TRACE, _L "OP_Packet Queue size=%d" __L, PacketQueue.size());

				//SendOutOfOrderAck(seq);

			} else if (check == SeqPast) {
				_log(NET__DEBUG, _L "Duplicate OP_Packet: Expecting Seq=%d, but got Seq=%d" __L, NextInSeq, seq);
				_raw(NET__DEBUG, seq, p);
				SendOutOfOrderAck(seq);  //we already got this packet but it was out of order
			} else {
				// In case we did queue one before as well.
				EQProtocolPacket *qp=RemoveQueue(seq);
				if (qp) {
					_log(NET__NET_TRACE, "OP_Packet: Removing older queued packet with sequence %d", seq);
					delete qp;
				}

				SetNextAckToSend(seq);
				NextInSeq++;
				// Check for an embedded OP_AppCombinded (protocol level 0x19)
				if (*(p->pBuffer+2)==0x00 && *(p->pBuffer+3)==0x19) {
					EQProtocolPacket *subp=MakeProtocolPacket(p->pBuffer+2,p->size-2);
					_log(NET__NET_CREATE, _L "seq %d, Extracting combined packet of length %d" __L, seq, subp->size);
					_raw(NET__NET_CREATE_HEX, seq, subp);
					subp->copyInfo(p);
					ProcessPacket(subp);
					delete subp;
				} else {
					EQRawApplicationPacket *ap=MakeApplicationPacket(p->pBuffer+2,p->size-2);
					if (ap) {
						ap->copyInfo(p);
						InboundQueuePush(ap);
					}
				}
			}
		}
		break;
		
		case OP_Fragment: {
			if(!p->pBuffer || (p->Size() < 4))
			{
				_log(NET__ERROR, _L "Received OP_Fragment that was of malformed size" __L);
				break;
			}
			uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
			SeqOrder check=CompareSequence(NextInSeq,seq);
			if (check == SeqFuture) {
				_log(NET__DEBUG, _L "Future OP_Fragment: Expecting Seq=%d, but got Seq=%d" __L, NextInSeq, seq);
				_raw(NET__DEBUG, seq, p);

				PacketQueue[seq]=p->Copy();
				_log(NET__APP_TRACE, _L "OP_Fragment Queue size=%d" __L, PacketQueue.size());

				//SendOutOfOrderAck(seq);

			} else if (check == SeqPast) {
				_log(NET__DEBUG, _L "Duplicate OP_Fragment: Expecting Seq=%d, but got Seq=%d" __L, NextInSeq, seq);
				_raw(NET__DEBUG, seq, p);
				SendOutOfOrderAck(seq);
			} else {
				// In case we did queue one before as well.
				EQProtocolPacket *qp=RemoveQueue(seq);
				if (qp) {
					_log(NET__NET_TRACE, "OP_Fragment: Removing older queued packet with sequence %d", seq);
					delete qp;
				}
				SetNextAckToSend(seq);
				NextInSeq++;
				if (oversize_buffer) {
					memcpy(oversize_buffer+oversize_offset,p->pBuffer+2,p->size-2);
					oversize_offset+=p->size-2;
					_log(NET__NET_TRACE, _L "Fragment of oversized of length %d, seq %d: now at %d/%d" __L, p->size-2, seq, oversize_offset, oversize_length);
					if (oversize_offset==oversize_length) {
						if (*(p->pBuffer+2)==0x00 && *(p->pBuffer+3)==0x19) {
							EQProtocolPacket *subp=MakeProtocolPacket(oversize_buffer,oversize_offset);
							_log(NET__NET_CREATE, _L "seq %d, Extracting combined oversize packet of length %d" __L, seq, subp->size);
							//_raw(NET__NET_CREATE_HEX, subp);
							subp->copyInfo(p);
							ProcessPacket(subp);
							delete subp;
						} else {
							EQRawApplicationPacket *ap=MakeApplicationPacket(oversize_buffer,oversize_offset);
							_log(NET__NET_CREATE, _L "seq %d, completed combined oversize packet of length %d" __L, seq, ap->size);
							if (ap) {
								ap->copyInfo(p);
								InboundQueuePush(ap);
							}
						}
						delete[] oversize_buffer;
						oversize_buffer=NULL;
						oversize_offset=0;
					}
				} else {
					oversize_length=ntohl(*(uint32 *)(p->pBuffer+2));
					oversize_buffer=new unsigned char[oversize_length];
					memcpy(oversize_buffer,p->pBuffer+6,p->size-6);
					oversize_offset=p->size-6;
					_log(NET__NET_TRACE, _L "First fragment of oversized of seq %d: now at %d/%d" __L, seq, oversize_offset, oversize_length);
				}
			}
		}
		break;
		case OP_KeepAlive: {
#ifndef COLLECTOR
			NonSequencedPush(new EQProtocolPacket(p->opcode,p->pBuffer,p->size));
			_log(NET__NET_TRACE, _L "Received and queued reply to keep alive" __L);
#endif
		}
		break;
		case OP_Ack: {
			if(!p->pBuffer || (p->Size() < 4))
			{
				_log(NET__ERROR, _L "Received OP_Ack that was of malformed size" __L);
				break;
			}
#ifndef COLLECTOR
			uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
			AckPackets(seq);
#ifdef RETRANSMITS
			retransmittimer = Timer::GetCurrentTime();
#endif
#endif
		}
		break;
		case OP_SessionRequest: {
			if(p->Size() < sizeof(SessionRequest))
			{
				_log(NET__ERROR, _L "Received OP_SessionRequest that was of malformed size" __L);
				break;
			}
#ifndef COLLECTOR
			if (GetState()==ESTABLISHED) {
				_log(NET__ERROR, _L "Received OP_SessionRequest in ESTABLISHED state (%d)" __L, GetState());
				
				/*RemoveData();
				init(); 
				State=UNESTABLISHED;*/ 
				_SendDisconnect();
				SetState(CLOSED);
				break;
			}
#endif
			//cout << "Got OP_SessionRequest" << endl;
			init();
			OutboundQueueClear();
			SessionRequest *Request=(SessionRequest *)p->pBuffer;
			Session=ntohl(Request->Session);
			SetMaxLen(ntohl(Request->MaxLength));
			_log(NET__NET_TRACE, _L "Received OP_SessionRequest: session %lu, maxlen %d" __L, (unsigned long)Session, MaxLen);
			SetState(ESTABLISHED);
#ifndef COLLECTOR
			Key=0x11223344;
			SendSessionResponse();
#endif
		}
		break;
		case OP_SessionResponse: {
			if(p->Size() < sizeof(SessionResponse))
			{
				_log(NET__ERROR, _L "Received OP_SessionResponse that was of malformed size" __L);
				break;
			}

			init();
			OutboundQueueClear();
			SessionResponse *Response=(SessionResponse *)p->pBuffer;
			SetMaxLen(ntohl(Response->MaxLength));
			Key=ntohl(Response->Key);
			NextInSeq=0;
			SetState(ESTABLISHED);
			if (!Session)
				Session=ntohl(Response->Session);
			compressed=(Response->Format&FLAG_COMPRESSED);
			encoded=(Response->Format&FLAG_ENCODED);

			_log(NET__NET_TRACE, _L "Received OP_SessionResponse: session %lu, maxlen %d, key %lu, compressed? %s, encoded? %s" __L, (unsigned long)Session, MaxLen, (unsigned long)Key, compressed?"yes":"no", encoded?"yes":"no");
			
			// Kinda kludgy, but trie for now
			if (StreamType==UnknownStream) {
				if (compressed) {
					if (remote_port==9000 || (remote_port==0 && p->src_port==9000)) {
						SetStreamType(WorldStream);
					} else {
						SetStreamType(ZoneStream);
					}
				} else if (encoded) {
					SetStreamType(ChatOrMailStream);
				} else {
					SetStreamType(LoginStream);
				}
			}
		}
		break;
		case OP_SessionDisconnect: {
			//NextInSeq=0;
			EQStreamState state = GetState();
			if(state == ESTABLISHED) {
				//client initiated disconnect?
				_log(NET__NET_TRACE, _L "Received unsolicited OP_SessionDisconnect. Treating like a client-initiated disconnect." __L);
				_SendDisconnect();
				SetState(CLOSED);
			} else if(state == CLOSING) {
				//we were waiting for this anyways, ignore pending messages, send the reply and be closed.
				_log(NET__NET_TRACE, _L "Received OP_SessionDisconnect when we have a pending close, they beat us to it. Were happy though." __L);
				_SendDisconnect();
				SetState(CLOSED);
			} else {
				//we are expecting this (or have already gotten it, but dont care either way)
				_log(NET__NET_TRACE, _L "Received expected OP_SessionDisconnect. Moving to closed state." __L);
				SetState(CLOSED);
			}
		}
		break;
		case OP_OutOfOrderAck: {
			if(!p->pBuffer || (p->Size() < 4))
			{
				_log(NET__ERROR, _L "Received OP_OutOfOrderAck that was of malformed size" __L);
				break;
			}
#ifndef COLLECTOR
			uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
			MOutboundQueue.lock();
			
if(uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
	_log(NET__ERROR, _L "Pre-OOA Invalid Sequenced queue: BS %d + SQ %d != NOS %d" __L, SequencedBase, SequencedQueue.size(), NextOutSeq);
}
if(NextSequencedSend > SequencedQueue.size()) {
	_log(NET__ERROR, _L "Pre-OOA Next Send Sequence is beyond the end of the queue NSS %d > SQ %d" __L, NextSequencedSend, SequencedQueue.size());
}
			//if the packet they got out of order is between our last acked packet and the last sent packet, then its valid.
			if (CompareSequence(SequencedBase,seq) != SeqPast && CompareSequence(NextOutSeq,seq) == SeqPast) {
				_log(NET__NET_TRACE, _L "Received OP_OutOfOrderAck for sequence %d, starting retransmit at the start of our unacked buffer (seq %d, was %d)." __L,
					seq, SequencedBase, SequencedBase+NextSequencedSend);
#ifdef RETRANSMITS
                        	if (!RuleB(EQStream, RetransmitAckedPackets)) {
#endif
					uint16 sqsize = SequencedQueue.size();
					uint16 index = seq - SequencedBase;
					_log(NET__NET_TRACE, _L "         OP_OutOfOrderAck marking packet acked in queue (queue index = %d, queue size = %d)." __L, index, sqsize);
					if (index < sqsize) {
						deque<EQProtocolPacket *>::iterator sitr;
						sitr = SequencedQueue.begin();
						sitr += index;
						(*sitr)->acked = true;
					}
#ifdef RETRANSMITS
				}
                        	if (RuleR(EQStream, RetransmitTimeoutMult)) { // only choose new behavior if multiplier is set
					retransmittimer = Timer::GetCurrentTime();
				}
#endif
				NextSequencedSend = 0;
			} else {
				_log(NET__NET_TRACE, _L "Received OP_OutOfOrderAck for out-of-window %d. Window (%d->%d)." __L, seq, SequencedBase, NextOutSeq);
			}
if(uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
	_log(NET__ERROR, _L "Post-OOA Invalid Sequenced queue: BS %d + SQ %d != NOS %d" __L, SequencedBase, SequencedQueue.size(), NextOutSeq);
}
if(NextSequencedSend > SequencedQueue.size()) {
	_log(NET__ERROR, _L "Post-OOA Next Send Sequence is beyond the end of the queue NSS %d > SQ %d" __L, NextSequencedSend, SequencedQueue.size());
}
			MOutboundQueue.unlock();
#endif
		}
		break;
		case OP_SessionStatRequest: {
			if(p->Size() < sizeof(SessionStats))
			{
				_log(NET__ERROR, _L "Received OP_SessionStatRequest that was of malformed size" __L);
				break;
			}
#ifndef COLLECTOR
			SessionStats *Stats=(SessionStats *)p->pBuffer;
			_log(NET__NET_TRACE, _L "Received Stats: %lu packets received, %lu packets sent, Deltas: local %lu, (%lu <- %lu -> %lu) remote %lu" __L, 
				(unsigned long)ntohl(Stats->packets_received), (unsigned long)ntohl(Stats->packets_sent), (unsigned long)ntohl(Stats->last_local_delta), 
				(unsigned long)ntohl(Stats->low_delta), (unsigned long)ntohl(Stats->average_delta), 
				(unsigned long)ntohl(Stats->high_delta), (unsigned long)ntohl(Stats->last_remote_delta));
			uint64 x=Stats->packets_received;
			Stats->packets_received=Stats->packets_sent;
			Stats->packets_sent=x;
			NonSequencedPush(new EQProtocolPacket(OP_SessionStatResponse,p->pBuffer,p->size));
			AdjustRates(ntohl(Stats->average_delta));
#ifdef RETRANSMITS
			if (RuleR(EQStream, RetransmitTimeoutMult) && ntohl(Stats->average_delta)) {
				//recalculate retransmittimeout using the larger of the last rtt or average rtt, which is multiplied by the rule value
				if((ntohl(Stats->last_local_delta) + ntohl(Stats->last_remote_delta)) > (ntohl(Stats->average_delta) * 2)) {
					retransmittimeout = (ntohl(Stats->last_local_delta) + ntohl(Stats->last_remote_delta)) * RuleR(EQStream, RetransmitTimeoutMult);
				} else {
					retransmittimeout = ntohl(Stats->average_delta) * 2 * RuleR(EQStream, RetransmitTimeoutMult);
				}
				if(retransmittimeout > RuleI(EQStream, RetransmitTimeoutMax))
					retransmittimeout = RuleI(EQStream, RetransmitTimeoutMax);
				_log(NET__NET_TRACE, _L "Retransmit timeout recalculated to %dms" __L, retransmittimeout);
			}
#endif
#endif
		}
		break;
		case OP_SessionStatResponse: {
			_log(NET__NET_TRACE, _L "Received OP_SessionStatResponse. Ignoring." __L);
		}
		break;
		case OP_OutOfSession: {
			_log(NET__NET_TRACE, _L "Received OP_OutOfSession. Ignoring." __L);
		}
		break;
		default:
			EQRawApplicationPacket *ap = MakeApplicationPacket(p);
			if (ap)
				InboundQueuePush(ap);
			break;
	}
}
Esempio n. 28
0
void *Arrival(void* arg){
    
    
    int i =0;
    double prev_itime = 0 ;
    double inter_a_time = 0.0;
    Packet_desc *p = NULL;
    
    //Init the list
    My402ListInit(&Q1_node);
    
    
    //create packet
    while(i != num) {
        
        p = (Packet_desc*)malloc(sizeof(Packet_desc));
        
        if(fp != NULL){
            ReadFile(p);
        }
        else{
            p->int_time = 1/lamda*THOUSAND ; // interarrival time
            p->tokens = P;
            p->ser_time = 1/mu*THOUSAND; // service time
        }
        p->name_ID = ++i;
        
        
        usleep(p->int_time*THOUSAND);
        
        inter_a_time = GetMTimeOfDay()- prev_itime;
        
        prev_itime = GetMTimeOfDay() ;
        
        total_i_a_time += inter_a_time;
        
        pthread_mutex_lock(&lock);
        
        if(p->tokens > B){
            
            fprintf(stdout, "%012.3lfms: p%d arrives, needs %d tokens, inter-arrival time = %.3fms, dropped\n",GetMTimeOfDay(),p->name_ID,p->tokens, inter_a_time);
            packets_drop++;
            total_packets_prod++;
            free(p);
            
            pthread_mutex_unlock(&lock);
            
            continue;
        }
        
        fprintf(stdout, "%012.3lfms: p%d arrives, needs %d tokens, inter-arrival time = %.3fms\n",GetMTimeOfDay() ,p->name_ID,p->tokens,inter_a_time);
        
        total_packets_prod++;
        
        pthread_mutex_unlock(&lock);
        
        pthread_mutex_lock(&lock);
        
        packet_arrived++;
        
        //critical section
        
        EnquePacket(p);
        
        ProcessPacket();
        
        pthread_mutex_unlock(&lock);
    }
    
    if(filename){
        fclose(fp);
    }
    
    return 0;
}
Esempio n. 29
0
int main()
{
	u_int i, res, inum;
	u_char errbuf[PCAP_ERRBUF_SIZE], buffer[100];
	u_char *pkt_data;
	time_t seconds;
	struct tm tbreak;
	pcap_if_t *alldevs, *d;
	pcap_t *fp;
	struct pcap_pkthdr *header;

	fopen_s(&logfile, "log.txt", "w");

	if (logfile == NULL)
	{
		printf("Unable to create file.");
	}

	/* The user didn't provide a packet source: Retrieve the local device list */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs_ex: %s\n", errbuf);
		return -1;
	}

	i = 0;
	/* Print the list */
	for (d = alldevs; d; d = d->next)
	{
		printf("%d. %s\n    ", ++i, d->name);

		if (d->description)
		{
			printf(" (%s)\n", d->description);
		}
		else
		{
			printf(" (No description available)\n");
		}
	}

	if (i == 0)
	{
		fprintf(stderr, "No interfaces found! Exiting.\n");
		return -1;
	}

	printf("Enter the interface number you would like to sniff : ");
	scanf_s("%d", &inum);


	/* Jump to the selected adapter */
	for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);

	/* Open the device */
	if ((fp = pcap_open(d->name,
		100 /*snaplen*/,
		PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
		20 /*read timeout*/,
		NULL /* remote authentication */,
		errbuf)
		) == NULL)
	{
		fprintf(stderr, "\nError opening adapter\n");
		return -1;
	}

	//read packets in a loop :)
	while ((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0)
	{
		if (res == 0)
		{
			// Timeout elapsed
			continue;
		}
		seconds = header->ts.tv_sec;
		localtime_s(&tbreak, &seconds);
		strftime(buffer, 80, "%d-%b-%Y %I:%M:%S %p", &tbreak);
		//print pkt timestamp and pkt len
		//fprintf(logfile , "\nNext Packet : %ld:%ld (Packet Length : %ld bytes) " , header->ts.tv_sec, header->ts.tv_usec, header->len);
		fprintf(logfile, "\nNext Packet : %s.%ld (Packet Length : %ld bytes) ", buffer, header->ts.tv_usec, header->len);
		ProcessPacket(pkt_data, header->caplen);
	}

	if (res == -1)
	{
		fprintf(stderr, "Error reading the packets: %s\n", pcap_geterr(fp));
		return -1;
	}

	return 0;
}
Esempio n. 30
0
void Session::Worker()
{
    sLog->StaticOut("Network worker thread running");
    sApp->ThreadStatus.sessionworker = true;

    char* buf = new char[BUFFER_LEN];
    int result, error;
    SOCK res;
    Player* pClient = NULL;
    Player* pNew = new Player;
    pNew->m_addrLen = sizeof(pNew->m_sockInfo);
    std::list<Player*>::iterator itr;

    while(1)
    {
        res = accept(m_socket, (sockaddr*)&pNew->m_sockInfo, &pNew->m_addrLen);
        error = LASTERROR();

        if (res == INVALID_SOCKET && error == SOCKETWOULDBLOCK)
        {
            // zadne prichozi spojeni
        }
        else if (res == INVALID_SOCKET && error != SOCKETWOULDBLOCK)
        {
            sLog->ErrorOut("Socket error: %i", error);
        }
        else
        {
            pNew->m_socket = res;
            pNew->m_addrLen = sizeof(pNew->m_sockInfo);

            sLog->DebugOut("Accepting connection from %s",inet_ntoa((in_addr)pNew->m_sockInfo.sin_addr));

            clientList.push_back(pNew);
            sLog->NetworkDebugOut(pNew,"Inserted into client list");

            pNew = new Player;
            pNew->m_addrLen = sizeof(pNew->m_sockInfo);
        }

        if (clientList.empty())
        {
            // Wait for longer period, no need to check for socket traffic so often if nobody's connected
            boost::this_thread::sleep(boost::posix_time::milliseconds(100));
            continue;
        }

        for (itr = clientList.begin(); itr != clientList.end();)
        {
            pClient = (*itr); // Who wants ugly star in brackets?!
            if (pClient)
            {
                memset(buf,0,BUFFER_LEN);
                result = recv(pClient->m_socket, buf, BUFFER_LEN, 0);
                error = LASTERROR();

                if (result > 0)
                {
                    sLog->NetworkDebugOut(pClient,"Received data, size: %u",result);
                    SmartPacket* parsed = BuildPacket(buf,result);
                    if (parsed)
                    {
                        sLog->NetworkDebugOut(pClient,"Opcode 0x%.2X, size %u", parsed->GetOpcode(), parsed->GetSize());
                        ProcessPacket(parsed, pClient);

                        int32 totalparsed = parsed->GetSize()+8;
                        while (totalparsed < result)
                        {
                            parsed = BuildPacket(buf+totalparsed, result-totalparsed);
                            if (parsed)
                            {
                                sLog->NetworkDebugOut(pClient,"Parsed additional %u bytes",parsed->GetSize());
                                sLog->NetworkDebugOut(pClient,"Opcode 0x%.2X, size %u", parsed->GetOpcode(), parsed->GetSize());
                                ProcessPacket(parsed, pClient);
                                totalparsed += parsed->GetSize()+8;
                            }
                            else
                                break;
                        }
                    }
                }
                else if (result == 0 || error == SOCKETCONNRESET)
                {
                    sLog->NetworkDebugOut(pClient,"Client disconnected");
                    sInstanceManager->RemovePlayerFromInstances(pClient);
                    itr = clientList.erase(itr);
                    continue;
                }
                else
                {
                    if (error != SOCKETWOULDBLOCK && error != 0)
                    {
                        //error
                        sLog->NetworkOut(pClient,"Unhandled socket error: %u",error);
                    }
                }
            }
            ++itr;
        }

        // Some waiting time, could be changed if needed, but thread have to wait since select() is not present
        // technically, this counts as "yield" on Windows
        boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    }
}