コード例 #1
0
void CUDTSocketListner::Process()
{
	for(;;) // repeat untill all pending connections are accepted
	{
		/*timeval tv;
		tv.tv_sec = 0;
		tv.tv_usec = 0;
		UDT::UDSET readfds;
		UD_ZERO(&readfds);
		UD_SET(m_Server, &readfds);
		int res	= UDT::select(0, &readfds, NULL, NULL, &tv);
		if (!((res != UDT::ERROR) && (UD_ISSET(m_Server, &readfds))))
			break;*/
		
		sockaddr_in6 sa; // sockaddr_in is smaller
		int sa_len = sizeof(sa); 
		UDTSOCKET Client = UDT::accept(m_Server, (sockaddr*)&sa, &sa_len);
		if (UDT::INVALID_SOCK == Client)
		{
			LogLine(LOG_ERROR, L"accept: %S", UDT::getlasterror().getErrorMessage());
			break;
		}
		else if(Client == NULL)
			break;
		
		ConfigSocket(Client);

		uint64_t SendKey = 0;
		int KeySize = sizeof(SendKey);
		UDT::getsockopt(Client, 0, UDT_SENDKEY, &SendKey, &KeySize);

		CSafeAddress Address((sockaddr*)&sa, sa_len, sa_len == sizeof(sockaddr_in) ? CSafeAddress::eUDT_IP4 : CSafeAddress::eUDT_IP6);
		Address.SetPassKey(SendKey);
		GetParent<CSmartSocket>()->AddSessions(Address, new CUDTSocketSession(this, Client, Address));
	}

	const uint64 Size = 0xFFFF;
	char Buffer[Size];
	for(;;) // repeat untill all data is read
	{
		sockaddr_in6 sa; // sockaddr_in is smaller
		int sa_len = sizeof(sa); 
		uint64_t RecvKey = 0;
		int Recived = UDT::recvfrom(m_Server, Buffer, Size, (sockaddr*)&sa, &sa_len, &RecvKey);
		if (UDT::ERROR == Recived)
		{
			LogLine(LOG_ERROR, L"recvfrom: %S", UDT::getlasterror().getErrorMessage());
			break;
		}
		else if(Recived == 0)
			break; // nothing more to be recived
		CBuffer Packet(Buffer, Recived, true);

		CSafeAddress Address((sockaddr*)&sa, sa_len, sa_len == sizeof(sockaddr_in) ? CSafeAddress::eUDT_IP4 : CSafeAddress::eUDT_IP6);
		Address.SetPassKey(RecvKey);
		ReceiveFrom(Packet, Address);
	}
}
コード例 #2
0
ファイル: NetEndpoint.cpp プロジェクト: looncraz/haiku
int32
BNetEndpoint::ReceiveFrom(BNetBuffer& buffer, size_t length,
	BNetAddress& address, int flags)
{
	BNetBuffer chunk(length);
	ssize_t bytesReceived = ReceiveFrom(chunk.Data(), length, address, flags);
	if (bytesReceived > 0)
		buffer.AppendData(chunk.Data(), bytesReceived);
	return bytesReceived;
}
コード例 #3
0
void CUdpSocket::OnReceive(int nErrorCode) 
{
	CString sIP, sMsg;
	UINT nPort;
	char buf[100];
	ZeroMemory(buf, 100);
	ReceiveFrom(buf, 100, sIP, nPort);
	sMsg.Format(_T("%s (%d):%s"), sIP, nPort, buf);
	AfxMessageBox(sMsg);

	CAsyncSocket::OnReceive(nErrorCode);
}
コード例 #4
0
ファイル: netsock.cpp プロジェクト: EISALab/AMGAgroundwater
int CSocket::ReceiveFrom(void* lpBuf, int nBufLen, string& rSocketAddress, UINT& rSocketPort, int nFlags)
{
	SOCKADDR_IN sockAddr;
	memset(&sockAddr, 0, sizeof(sockAddr));

	int nResult = ReceiveFrom(lpBuf, nBufLen, &sockAddr, nFlags);
	if(nResult != SOCKET_ERROR)
	{
		rSocketPort = ntohs(sockAddr.sin_port);
		rSocketAddress = inet_ntoa(sockAddr.sin_addr);
	}
	return nResult;
}
コード例 #5
0
ファイル: MySocket.cpp プロジェクト: alex159s/test
void CMySocket::OnReceive(int nErrorCode)
{
	char buf[256];
	CString ip;
	UINT port;
	ReceiveFrom(buf,256,ip,port);
	CMFCSockDlg* p = (CMFCSockDlg*)m_CWnd;

	CStringA as = buf;
	p->m_RecordList.AddString( CA2W(as) );

	CAsyncSocket::OnReceive(nErrorCode);
}
コード例 #6
0
void CSocketInterfaceDataRev::OnReceive(int nErrorCode)
{
	// TODO: 在此添加专用代码和/或调用基类
	int iCount = ReceiveFrom(m_oFrameInterface.m_pFrameData, 65536, m_strIPSource, m_uiPortSource);
	if(iCount > 0)
	{
		// 帧字节数
		m_iFrameSize = iCount;
		// 解析帧头
		m_oFrameInterface.ParseFrameHead();
		// 处理内部网络命令帧
		CMainFrame* pMainFrame = NULL;
		pMainFrame = (CMainFrame*)AfxGetMainWnd();		
		pMainFrame->OnProcInterFaceCommand(&m_oFrameInterface);
	}

	CSocket::OnReceive(nErrorCode);
}
コード例 #7
0
ファイル: UdpMessager.cpp プロジェクト: bocai/Gobang
void CUdpMessager::OnReceive(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	
	MsgStruct msgStruct;

	memset(&msgStruct, 0, sizeof(msgStruct));

/* (1) */
// 	SOCKADDR_IN romoteAddr;
// 	
// 	memset(&romoteAddr, 0, sizeof(romoteAddr));
// 	romoteAddr.sin_port = htons(5050);
// 	romoteAddr.sin_family = AF_INET;
// 	romoteAddr.sin_addr.S_un.S_addr = inet_addr(ipStr);
// 
// 	int len = sizeof(romoteAddr);
 
// 	if (ReceiveFrom(buf, sizeof(buf), (SOCKADDR *)&romoteAddr, &len) <= 0)
// 	{
// 		AfxMessageBox("接收数据出错!");
// 		
// 	}
// 	else {
// 		buf[len] = '\0';
// 		AfxMessageBox(buf);
// 	}

	/* (2) */
	CString ipString;
	UINT port = 0;
	ReceiveFrom(&msgStruct, sizeof(msgStruct), ipString, port);

	if (NULL != PparentWnd)
	{
		((CGobangDlg *)PparentWnd)->handleNetMsg(&msgStruct, sizeof(msgStruct), ipString, port);
	}
// 		CString msg;
// 		msg.Format("接收:%s:%d %s", ipStr,port, buf);
// 		AfxMessageBox(msg);
	

	CSocket::OnReceive(nErrorCode);
}
コード例 #8
0
void CMulticastSocket::OnReceive(int nErrorCode)
{
	int nError = ReceiveFrom (m_strBuffer, 32000, m_strSendersIP, m_nSendersPort);
	if(nError == SOCKET_ERROR)
		AfxMessageBox("Error receiving data from the host group");
	else
	{
		if (!bForceNoLoopback || (bForceNoLoopback && !(m_strSendersIP == m_strLocalIP && m_nSendersPort == m_nLocalPort)))
		{
			// 1. If loopbackback is not to be forced then interface handles the loopback itself
			// 2. If you have to loopback and SOCKOPT LOOPBACK fails, no problem, interfaces loopback by default
			// 3. If you have to stop loopback and SOCKOPT LOOPBACK fails, ignore messages coming from your own sending socket

			// TODO : Add your code for here. The packet received is in m_strBuffer
		}
	}

	CAsyncSocket::OnReceive(nErrorCode); 
}
コード例 #9
0
ファイル: ClientSocket.cpp プロジェクト: bugou/test
void CClientSocket::OnReceive(int nErrorCode) 
{
	char buff[DataBufLength];
	int nRead;
	CString sIP;
	UINT nPort;
	
	nRead = ReceiveFrom(buff,DataBufLength,sIP,nPort);
	
	if (nRead != SOCKET_ERROR && nRead != 0 )
	{	
		if(StrNSame(buff,m_szResponseMsg,nRead-4,m_szrLength))
		{				
			DWORD Index=*((DWORD*)(buff+nRead-4));				
			if(Index<=CheckBufLength)
			{		
				m_arBuf[Index]=1;				
				return;
			}
		}		
		
		CData* pData=new CData;
		
		StrNCopy(pData->szBuf,buff,nRead);			
		pData->num=nRead;
		pData->nPort=nPort;
		pData->tarIP=inet_addr(sIP);
		
		if(pData->LoadFromBuf())
		{			
			StrNCopy(m_szResponseMsg+m_szrLength,(char*)&pData->This,sizeof(DWORD));
			SendTo(m_szResponseMsg,m_szrLength+sizeof(DWORD),nPort,sIP);
			if(pData->wIndex>=0&&pData->wIndex<RecvWndNumber&&m_apRecvWnd[pData->wIndex]!=NULL)
			{
				m_apRecvWnd[pData->wIndex]->PostMessage(WM_RECIEVE_MSG,(WPARAM)pData,0);
			}
			TRACE2("Recv a Data index: %d This: %d\n",pData->index,pData->This);
		}
	}	
}
コード例 #10
0
ファイル: netsock.cpp プロジェクト: EISALab/AMGAgroundwater
int CSocket::ReceiveFrom(void* lpBuf, int nBufLen, SOCKADDR_IN* lpSockInAddr, int nFlags)
{
	socklen_t nSockAddrLen = sizeof(SOCKADDR_IN);
	return ReceiveFrom( lpBuf, nBufLen, (SOCKADDR*)lpSockInAddr, &nSockAddrLen, nFlags );
}
コード例 #11
0
ファイル: GnuLocal.cpp プロジェクト: johnpark82/fish_client
void CGnuLocal::OnReceive(int nErrorCode) 
{
	byte buffer[1024];

	CString Host, LocalHost, NetworkPing, NetworkPong;
	CString LanName, IRCAddr, InfoURL;

	UINT    Port, LocalPort, Leaves = 0;

	int buffLength = ReceiveFrom(buffer, 1024, Host, Port);

	GetSockName(LocalHost, LocalPort);

	// Handle Errors
	if(!buffLength || buffLength == SOCKET_ERROR)
		return;
	
	CString strBuffer((char*) buffer, 128);

	NetworkPing =  theApp.m_spGD->ModeNetwork;
	NetworkPing += _T(" PING\r\n");

	NetworkPong =  theApp.m_spGD->ModeNetwork;
	NetworkPong += _T(" PONG\r\n");


	// Handle Ping over LAN
	if(strBuffer.Find(NetworkPing) == 0)
	{
		if(Host == LocalHost)
		{
			return;
		}

		// Send back pong only if not a leaf
		if(!m_pComm->m_LeafModeActive)
		{
			NetworkPong += _T("Port: ") + DWrdtoStr(m_pComm->m_CurrentPort) + _T("\r\n");

			if(theApp.m_spGD->m_NetworkModel == NETWORK_PRIVATE)
			{
				// LAN header
				if(theApp.m_spGD->m_Lan)
					NetworkPong += _T("LAN: ") + theApp.m_spGD->m_LanName + _T("\r\n");

				// IRC header
				if(theApp.m_spGD->m_InternalIRC)
					NetworkPong += _T("IRC: ") + theApp.m_spGD->m_InternalIRCAddr + _T("\r\n");
			}

			// Leaves header
			if(m_pComm->m_NodeCapability == CLIENT_ULTRAPEER)
			{
				int Leaves = m_pComm->CountLeafConnects();

				if(Leaves)
					NetworkPong += _T("Leaves: ") + DWrdtoStr(Leaves) + _T("\r\n");
			}


			NetworkPong += _T("\r\n");

			int pos = strBuffer.Find(_T("\r\nPort: "));
			if(pos != -1)
			{
				pos += 2;
				_stscanf((TCHAR*)buffer + pos, _T("Port: %d\r\n"), &Port);
			}
			
			SendTo(NetworkPong, NetworkPong.GetLength(), UDP_PORT, Host);
		}
	}

	// Extract Data from ping/pong
	if(strBuffer.Find(NetworkPing) == 0 || strBuffer.Find(NetworkPong) == 0)
	{
		int pos, backpos;

		pos = strBuffer.Find(_T("\r\nPort: "));
		if(pos != -1)
		{
			pos += 2;
			_stscanf((TCHAR*)buffer + pos, _T("Port: %d\r\n"), &Port);
		}

		pos = strBuffer.Find(_T("\r\nLAN: "));
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find(_T("\r\n"), pos);
			LanName = strBuffer.Mid(pos + 5, backpos - pos - 5);
		}

		pos = strBuffer.Find(_T("\r\nIRC: "));
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find(_T("\r\n"), pos);
			IRCAddr = strBuffer.Mid(pos + 5, backpos - pos - 5);
		}

		pos = strBuffer.Find(_T("\r\nInfoURL: "));
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find(_T("\r\n"), pos);
			InfoURL = strBuffer.Mid(pos + 9, backpos - pos - 9);
		}

		pos = strBuffer.Find(_T("\r\nLeaves: "));
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find(_T("\r\n"), pos);
			Leaves  = _ttoi( strBuffer.Mid(pos + 8, backpos - pos - 8) );
		}
	}

	
	// Handle Pong over LAN
	if(strBuffer.Find(NetworkPong) == 0)
	{
		CString Extra;

		if(Leaves)
			Extra = _T(" with ") + DWrdtoStr(Leaves) + _T(" leaves");
	}

	for(int i = 0; i < m_HostList.size(); i++)
		if( m_HostList[i].Host == Host && m_HostList[i].Port == Port)
			return;


	LanNode LocalNode;
	LocalNode.Host		= Host;
	LocalNode.Port		= Port;
	LocalNode.Name		= LanName;
	LocalNode.IRCserver = IRCAddr;
	LocalNode.InfoPage	= InfoURL;
	LocalNode.Leaves	= Leaves;
	m_HostList.push_back(LocalNode);

	CAsyncSocket::OnReceive(nErrorCode);
}
コード例 #12
0
void CUTPSocketListner::Recv(const byte* Buffer, size_t uSize, const struct sockaddr* sa, socklen_t sa_len)
{
	byte* pBuffer = (byte*)Buffer;
	size_t uPos = 0;

	if(uSize < 8)
		return;

	uint32 Rand;
	memcpy(&Rand, pBuffer, sizeof(uint32));						uPos += 4;

	CryptoPP::Weak1::MD5 md5;
	md5.Update((byte*)&Rand, sizeof(uint32));
	md5.Update((byte*)&m_RecvKey, sizeof(uint64));
	byte Hash[16];
	md5.Final(Hash);

//#ifdef _DEBUG
//	LogLine(LOG_INFO | LOG_DEBUG, L"Recv from %s PassKey %I64u -> %s", 
//		CSafeAddress(sa, sa_len, sa_len == sizeof(sockaddr_in) ? CSafeAddress::eUTP_IP4 : CSafeAddress::eUTP_IP6).ToString().c_str(),
//		m_RecvKey, ToHex(Hash, 16).c_str());
//#endif

	CryptoPP::Weak::ARC4::Encryption RC4;
	RC4.SetKey(Hash, 16);
	RC4.DiscardBytes(256);

	RC4.ProcessData(pBuffer + 4, pBuffer + 4, 4);
	UHdr Hdr;
	memcpy(&Hdr.Bits, pBuffer + uPos, 4);						uPos += 4;

	if(Hdr.Fields.Discard)
		RC4.DiscardBytes(Hdr.Fields.Discard * 256);

	RC4.ProcessData(pBuffer + uPos, pBuffer + uPos, uSize - uPos);

	uint64 PassKey = 0;
	if(Hdr.Fields.HasKey)
	{
		if(uSize - uPos < 8)
			return;
		memcpy(&PassKey, pBuffer + uPos, sizeof(uint64));		uPos += 8;
	}

	if(uSize - uPos < Hdr.Fields.PadLen)
		return;
	uSize -= Hdr.Fields.PadLen;
	
	if(Hdr.Fields.Reserved != 0) // if we want to use the reserverd bits we must set the magic value
	{
		if(memcmp(pBuffer + uSize, NEO_MAGIC, 4) != 0)
			return;
	}

	TKeyMap::iterator I = m_SendKeys.find((struct sockaddr*)sa);
	if(I == m_SendKeys.end())
	{
		if(PassKey == 0)
			return; // drop this packet as wen cant answer it

		SPassKey* pSendKey = new SPassKey((struct sockaddr*)sa);
		I = m_SendKeys.insert(TKeyMap::value_type(pSendKey->sa, pSendKey)).first;
	}
	if(PassKey != 0)
		I->second->PassKey = PassKey;
	//I->second->bAck = true; // if we got a packet it means that the other site knows out passkey and those we dont have to send it
	I->second->LastActivity = GetCurTick();


	switch(Hdr.Fields.Type)
	{
	case 0:
		{
			CBuffer Packet(pBuffer + uPos, uSize - uPos, true);
			CSafeAddress Address((sockaddr*)sa, sa_len, sa_len == sizeof(sockaddr_in) ? CSafeAddress::eUTP_IP4 : CSafeAddress::eUTP_IP6);
			Address.SetPassKey(I->second->PassKey);
			ReceiveFrom(Packet, Address);
			break;
		}
	case 1:
		// Lookup the right UTP socket that can handle this message
		UTP_IsIncomingUTP(&got_incoming_connection, &send_to, this, pBuffer + uPos, uSize - uPos, (const struct sockaddr*)sa, sa_len, &utp_overhead_2);
		break;
	case 15:
		{
			if(m_RecvKey < I->second->PassKey) // we have to decide who does the Sync, we do that in a trivial way
				Send(NULL, 0, sa, sa_len, 15);
			else
			{
				CSafeAddress Address(sa, sa_len, sa_len == sizeof(sockaddr_in) ? CSafeAddress::eUTP_IP4 : CSafeAddress::eUTP_IP6);
				Address.SetPassKey(I->second->PassKey);
				CSmartSocket* pSocket = GetParent<CSmartSocket>();
				CUTPSocketSession* pSession = pSocket->NewChannel(Address)->Cast<CUTPSocketSession>();
				if(pSession && !pSession->IsValid())
					pSession->Connect(sa, sa_len);
			}
			break;
		}
	}
}
コード例 #13
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));
		}
	}
}
コード例 #14
0
ファイル: GnuLocal.cpp プロジェクト: swax/GnucDNA
void CGnuLocal::OnReceive(int nErrorCode) 
{
	byte buffer[1024];

	CString Host, LocalHost, NetworkPing, NetworkPong;
	CString LanName, IRCAddr, InfoURL;

	UINT    Port, LocalPort, Leaves = 0;

	int buffLength = ReceiveFrom(buffer, 1024, Host, Port);

	GetSockName(LocalHost, LocalPort);

	// Handle Errors
	if(!buffLength || buffLength == SOCKET_ERROR)
		return;
	
	CString strBuffer((char*) buffer, 128);

	NetworkPing =  m_pComm->m_NetworkName;
	NetworkPing += " PING\r\n";

	NetworkPong =  m_pComm->m_NetworkName;
	NetworkPong += " PONG\r\n";


	// Handle Ping over LAN
	if(strBuffer.Find(NetworkPing) == 0)
	{
		if(Host == LocalHost)
		{
			m_pCore->LogError("UDP: Ping received from localhost");
			//return;
		}

		// Send back pong only if not a leaf
		NetworkPong += "Port: " + NumtoStr(m_pNet->m_CurrentPort) + "\r\n";

		if(m_pPrefs->m_LanMode)
		{
			NetworkPong += "LAN: " + m_pPrefs->m_LanName + "\r\n";

			CString RandCache = m_pComm->m_pCache->GetRandWebCache(true);
		
			if(!RandCache.IsEmpty())
				NetworkPing += "WebCache: " + RandCache + "\r\n";
		}

		// Leaves header
		if(m_pComm->m_GnuClientMode ==GNU_ULTRAPEER)
		{
			int Leaves = m_pComm->CountLeafConnects();

			if(Leaves)
				NetworkPong += "Leaves: " + NumtoStr(Leaves) + "\r\n";
		}


		NetworkPong += "\r\n";

		int pos = strBuffer.Find("\r\nPort: ");
		if(pos != -1)
		{
			pos += 2;
			sscanf((char*)buffer + pos, "Port: %d\r\n", &Port);
		}
		
		SendTo(NetworkPong, NetworkPong.GetLength(), UDP_PORT, Host);
		m_pCore->LogError("UDP: Pong Sent to " + Host + ":" + NumtoStr(Port));
	
	}

	// Extract Data from ping/pong
	if(strBuffer.Find(NetworkPing) == 0 || strBuffer.Find(NetworkPong) == 0)
	{
		int pos, backpos;

		pos = strBuffer.Find("\r\nPort: ");
		if(pos != -1)
		{
			pos += 2;
			sscanf((char*)buffer + pos, "Port: %d\r\n", &Port);
		}

		pos = strBuffer.Find("\r\nLAN: ");
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find("\r\n", pos);
			LanName = strBuffer.Mid(pos + 5, backpos - pos - 5);
		}

		pos = strBuffer.Find("\r\nWebCache: ");
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find("\r\n", pos);
			CString NewWebCache = strBuffer.Mid(pos + 10, backpos - pos - 10);

			m_pComm->m_pCache->WebCacheAddCache(NewWebCache);
		}

		pos = strBuffer.Find("\r\nIRC: ");
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find("\r\n", pos);
			IRCAddr = strBuffer.Mid(pos + 5, backpos - pos - 5);
		}

		pos = strBuffer.Find("\r\nInfoURL: ");
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find("\r\n", pos);
			InfoURL = strBuffer.Mid(pos + 9, backpos - pos - 9);
		}

		pos = strBuffer.Find("\r\nLeaves: ");
		if(pos != -1)
		{
			pos += 2;
			backpos = strBuffer.Find("\r\n", pos);
			Leaves  = atoi( strBuffer.Mid(pos + 8, backpos - pos - 8) );
		}
	}

	
	// Handle Pong over LAN
	if(strBuffer.Find(NetworkPong) == 0)
	{
		CString Extra;

		if(Leaves)
			Extra = " with " + NumtoStr(Leaves) + " leaves";

		m_pCore->LogError("UDP: Pong Received from " + Host + ":" + NumtoStr(Port) + Extra);
	}


	std::map<int, LanNode>::iterator itNode;
	for(itNode = m_LanNodeIDMap.begin(); itNode != m_LanNodeIDMap.end(); itNode++)
		if( itNode->second.Host == Host && itNode->second.Port == Port)
			return;


	LanNode LocalNode;
	LocalNode.Host		= Host;
	LocalNode.Port		= Port;
	LocalNode.Name		= LanName;
	LocalNode.IRCserver = IRCAddr;
	LocalNode.InfoPage	= InfoURL;
	LocalNode.Leaves	= Leaves;

	int LanNodeID = m_NextLanID++;
	m_LanNodeIDMap[LanNodeID] = LocalNode;


	// If we're not in lan mode, just add to cache
	if(!m_pPrefs->m_LanMode)
	{
		Node PermNode;
		PermNode.Host = Host;
		PermNode.Port = Port;
		
		if(PermNode.Host != LocalHost)
			m_pComm->m_pCache->m_GnuPerm.push_back(PermNode);
	}


	CAsyncSocket::OnReceive(nErrorCode);
}
コード例 #15
0
// We receive message from other application
//
void CConnexionSocket::OnReceive(int nErrorCode) 
{
	CString IP;
	UINT	Port;

	DWORD DataToRead;
	if( IOCtl( FIONREAD, &DataToRead )!=0 )
	{
		// Read data in the buffer
		if( m_BufferReceive )
		{
			char* BufferTemp = (char*) malloc( m_BufferReceiveSize+DataToRead );
			memcpy( BufferTemp, m_BufferReceive, m_BufferReceiveSize );
			free( m_BufferReceive );
			m_BufferReceive = BufferTemp;
		}
		else
		{
			m_BufferReceive = (char*) malloc( DataToRead );
			m_BufferReceiveSize = 0;
		}

		ReceiveFrom( &m_BufferReceive[m_BufferReceiveSize], DataToRead, IP, Port );
		m_BufferReceiveSize += DataToRead;

		// If we have the type and len of the message
		while( m_BufferReceiveSize>=sizeof(short)+sizeof(int) )
		{
			// Verify that the message is complete
			int Len;
			memcpy( &Len, &m_BufferReceive[sizeof(short)], sizeof(Len) );
			short Id;
			memcpy( &Id, m_BufferReceive, sizeof(Id) );

			//CString Str;
			//Str.Format( _T("Recu message. Taille attendu : %i / Taille recue : %i"), Len+6, m_BufferReceiveSize );
			//AfxMessageBox( Str );

			if( m_BufferReceiveSize>=(int) (Len+sizeof(short)+sizeof(int)) )
			{
				// Save the message in a file for debug
				{
					//CString Str, Str2;
					//Str.Format( _T("Message %i (len=%i) : "), (int) Id, Len );
					//for( int i=0; i<(int) (Len+sizeof(short)+sizeof(int)); i++ )
					//{
					//	Str2.Format( _T("%02x "), m_BufferReceive[i] );
					//	Str += Str2;
					//}
					//Str += _T("\n");
					//CStdioFile f(_T("c:\\tracelima.txt"), CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite | CFile::typeText | CFile::shareDenyWrite );
					//f.SeekToEnd();
					//f.WriteString(Str);				
					//f.Close();
				}
				ReadAMessage( IP, Port );
			}
			else
				break;
		}
	}

	// Call the base class
	CSocket::OnReceive(nErrorCode);
}
コード例 #16
0
void CWin32Socket::ServiceL(TWin32Message& aMessage)
	{
	switch (aMessage.OppCode())
		{
		case EConnect:
			{
			Connect(aMessage);
			break;
			}
		case ECancelConnect:
			{
			if (iConnectMessage)
				{
				Complete(iConnectMessage, KErrCancel);
				}
			break;
			}
		case ESend:
			{
			Send(aMessage);
			break;
			}
		case ECancelSend:
			{
			if (iSendMessage)
				{
				Complete(iSendMessage, KErrCancel);
				}
			break;
			}
		case ESendTo:
			{
			SendTo(aMessage);
			break;
			}
		case ECancelSendTo:
			{
			if (iSendMessage)
				{
				Complete(iSendMessage, KErrCancel);
				}
			break;
			}
		case EReceive:
			{
			Receive(aMessage);
			break;
			}
		case ECancelReceive:
			{
			if (iReceiveMessage)
				{
				Complete(iReceiveMessage, KErrCancel);
				}
			break;
			}
		case EReceiveFrom:
			{
			ReceiveFrom(aMessage);
			break;
			}
		case ECancelReceiveFrom:
			{
			if (iReceiveMessage)
				{
				Complete(iReceiveMessage, KErrCancel);
				}
			break;
			}
		case EGetSocketName:
			{
			GetSocketName(aMessage);
			break;
			}
		case EBind:
			{
			Bind(aMessage);
			break;
			}
		case EGetPeerName:
			{
			GetPeerName(aMessage);
			break;
			}
		case EListen:
			{
			Listen(aMessage);
			break;
			}
		case EAccept:
			{
			Accept(aMessage);
			break;
			}
		case ECancelAccept:
			{
			if (iAcceptMessage)
				{
				Complete(iAcceptMessage, KErrCancel);
				}
			break;
			}
		case EGetOption:
			{
			GetOption(aMessage);
			break;
			}
		case ESetOption:
			{
			SetOption(aMessage);
			break;
			}
		default:
			{
			__ASSERT_DEBUG(EFalse, Panic(EWinSockPrtInvalidSocketOppCode));
			}
		}
	}