Esempio n. 1
0
File: tests.c Progetto: m-b-/cidrc
int
testcidrs(void)
{
	char ip[LenStr], mask[LenStr], cidr[2*LenStr];
	uchar pip[V6], pmask[V6];
	int i, v;

	for (i = 0; cidrs[i].cidr; i++) {
		Z(ip);  Z(mask), Z(cidr);
		Z(pip); Z(pmask);

		/* CIDR to IP mask */
		v = parsecidr(cidrs[i].cidr, pip, pmask);
		if (v != cidrs[i].v) {
			fprintf(stderr, "testcidrs: %d != %d\n", cidrs[i].v, v);
			continue;
		}
		if (v == -1)
			continue;
		if (strcmp(cidrs[i].mask, ipstr(v, pmask, mask)) != 0)
			fprintf(stderr, "testcidrs: %s != %s\n", cidrs[i].mask, mask);
		if (strcmp(cidrs[i].ip, ipstr(v, pip, ip)) != 0)
			fprintf(stderr, "testcidrs: %s != %s\n", cidrs[i].ip, ip);
		if (strcmp(cidrs[i].cidr, cidrstr(v, pip, pmask, cidr)) != 0)
			fprintf(stderr, "testcidrs: %s != %s\n", cidrs[i].cidr, cidr);
	}

	return 0;
}
bool CServerList::AddServer(const CServer* pServer)
{
	if (!IsGoodServerIP(pServer)){ // check for 0-IP, localhost and optionally for LAN addresses
		if (thePrefs.GetLogFilteredIPs())
			AddDebugLogLine(false, _T("Ignored server (IP=%s)"), ipstr(pServer->GetIP()));
		return false;
	}

	if (thePrefs.FilterServerByIP()){
		if (pServer->HasDynIP())
			return false;
		if (theApp.ipfilter->IsFiltered(pServer->GetIP())){
			if (thePrefs.GetLogFilteredIPs())
				AddDebugLogLine(false, _T("Ignored server (IP=%s) - IP filter (%s)"), ipstr(pServer->GetIP()), theApp.ipfilter->GetLastHit());
			return false;
		}
	}

	CServer* test_server = GetServerByAddress(pServer->GetAddress(), pServer->GetPort());
	if (test_server){
		test_server->ResetFailedCount();
		theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(test_server);
		return false;
	}
	list.AddTail(const_cast<CServer*>(pServer));
	return true;
}
Esempio n. 3
0
PingStatus Pinger::PingICMP(uint32 lAddr, uint32 ttl, bool doLog) {
    PingStatus returnValue;

    IN_ADDR stDestAddr;
    char achRepData[sizeof(ICMPECHO) + BUFSIZE];

    // Address is assumed to be ok
    stDestAddr.s_addr = lAddr;
    stIPInfo.Ttl = (u_char)ttl;

    CTimeTick m_time;
	m_time.Tick();
    // Send the ICMP Echo Request and read the Reply
    DWORD dwReplyCount = lpfnIcmpSendEcho(hICMP, 
                                    stDestAddr.s_addr,
                                    0, // databuffer
                                    0, // DataLen, length of databuffer
                                    &stIPInfo, 
                                    achRepData, 
                                    sizeof(achRepData), 
                                    TIMEOUT
                            );
	float usResTime=m_time.Tick();
    if (dwReplyCount != 0) {
        long pingTime = *(u_long *) &(achRepData[8]);

        IN_ADDR stDestAddr;

        stDestAddr.s_addr = *(u_long *)achRepData;

        returnValue.success = true;
        returnValue.status = *(DWORD *) &(achRepData[4]);
		returnValue.delay = (m_time.isPerformanceCounter() && (pingTime <= 20 || pingTime%10 == 0) && (pingTime+10 > usResTime && usResTime+10 > pingTime )? usResTime : pingTime);
        returnValue.destinationAddress = stDestAddr.s_addr;
        returnValue.ttl = (returnValue.status != IP_SUCCESS)?ttl:(*(char *)&(achRepData[20]))&0x00FF;

        if(doLog) {
            theApp.QueueDebugLogLine(false,_T("Reply (ICMP-pinger) from %s: bytes=%d time=%3.2fms (%3.2fms %ldms) TTL=%i"),
                                                        ipstr(stDestAddr),
                                                        *(u_long *) &(achRepData[12]),
                                                        returnValue.delay,
                                                        m_time.isPerformanceCounter() ? usResTime : -1.0f, 
                                                        (u_long)(achRepData[8]),
                                                        returnValue.ttl);
        }
    } else {
        DWORD lastError = GetLastError();
        returnValue.success = false;
        returnValue.error = lastError;
        if(doLog) {
			theApp.QueueDebugLogLine(false,_T("Error from %s: Error=%i"),
				ipstr(stDestAddr),
				returnValue.error);
        }
    }

    return returnValue;
}
Esempio n. 4
0
void
madns_dump(MADNS const *mp, FILE * fp, MADNS_OPTS opts)
{
    QLINK  *lp;
    int     i;
    char    ips[99];

    if (!fp)
        return;
    int     nunused = qleng(mp->unused.next);
    int     nactive = qleng(mp->active.next);

    fprintf(fp, "\n#-- MADNS:%p query_time:%d server_reqs:%d sock:%d"
            " nservs:%d qsize:%d nfree:%d #active:%d #unused:%d\n",
            mp, mp->query_time, mp->server_reqs, mp->sock,
            mp->nservs, mp->qsize, mp->nfree, nactive, nunused);

    if (opts & QUERIES) {
        fprintf(fp, "# SERVERS:\n# ..... ip............. reqs latency\n");
        for (i = 0; i < mp->nservs; ++i)
            fprintf(fp, "# %5d %-15s %4d %.4f\n",
                    i, ipstr(mp->serv[i].ip, ips), mp->serv[i].nreqs,
                    mp->serv[i].latency);

        if (nactive) {
            fprintf(fp, "# QUERIES:\n# ..... ctx....... elapsed.. tid.."
                    " server......... name\n");
            double  now = tick();

            for (lp = mp->active.next; lp != &mp->active; lp = lp->next) {
                QUERY  *qp = link_QUERY(lp);

                fprintf(fp, "# %5d %p %8.4f %5hu %-15s %s\n",
                        (int)(qp - mp->queries), qp->ctx, now - qp->started,
                        qp->tid, qp->server ? ipstr(qp->server->ip, ips) : "",
                        qp->name);
            }
        }
    }

    if (opts & CACHE) {
        fprintf(fp, "# CACHE: limit:%d count:%d\n# ..... hash.... exps."
                " ip............. name\n", mp->limit, mp->count);
        int     now = time(0);
        CACHE_INFO *cip;

        for (i = 0; i < mp->limit; ++i)
            if ((cip = mp->cachev[i]))
                fprintf(fp, "# %5d %08X %5d %-15s %s\n",
                        i, cip->hash, (int)cip->expires - now,
                        ipstr(cip->ip, ips), cip->name);
    }

    putc('\n', fp);
}
Esempio n. 5
0
void ikev2_print_ts(struct traffic_selector *ts)
{
	ipstr_buf b;

	DBG(DBG_CONTROLMORE,
		DBG_log("printing contents struct traffic_selector");
		DBG_log("  ts_type: %s", enum_name(&ikev2_ts_type_names, ts->ts_type));
		DBG_log("  ipprotoid: %d", ts->ipprotoid);
		DBG_log("  startport: %d", ts->startport);
		DBG_log("  endport: %d", ts->endport);
		DBG_log("  ip low: %s", ipstr(&ts->low, &b));
		DBG_log("  ip high: %s", ipstr(&ts->high, &b));
	);
int CClientUDPSocket::SendTo(char* lpBuf,int nBufLen,uint32 dwIP, uint16 nPort){
	// NOTE: *** This function is invoked from a *different* thread!
	uint32 result = CAsyncSocket::SendTo(lpBuf,nBufLen,nPort,ipstr(dwIP));
	if (result == (uint32)SOCKET_ERROR){
		uint32 error = GetLastError();
		if (error == WSAEWOULDBLOCK){
			m_bWouldBlock = true;
			return -1;
		}
		if (thePrefs.GetVerbose())
			DebugLogError(_T("Error: Client UDP socket, failed to send data to %s:%u: %s"), ipstr(dwIP), nPort, GetErrorMessage(error, 1));
	}
	return 0;
}
Esempio n. 7
0
void   *
madns_response(MADNS * mp, in_addr_t * ip)
{
    while (1) {
        char    pkt[DNS_PACKET_LEN];
        INADDR  sa;
        socklen_t salen = sizeof sa;
        RESPONSE resp;
        char    ips[99];

        int     len = recvfrom(mp->sock, pkt, sizeof pkt, 0,
                               (SADDR *) & sa, &salen);
        if (len <= 0)
            break;

        if (!parse_response(pkt, len, &resp))
            continue;

        LOG("resp: ip %s ttl %lu tid %hu name %s\n",
            ipstr(resp.ip, ips), resp.ttl, resp.tid, resp.name);

        QUERY  *qp = &mp->queries[(int)resp.tid % mp->qsize];

        if (qp->ctx && qp->tid == resp.tid && qp->server
            && qp->server->ip == sa.sin_addr.s_addr) {

            if (resp.ip != INADDR_ANY && !strcasecmp(resp.name, qp->name))
                update_cache(mp, &resp);
            return destroy_query(mp, qp, *ip = resp.ip);
        }

        log_packet(__LINE__, pkt, len);
        if (qp->server && qp->server->ip != sa.sin_addr.s_addr)
            LOG("resp.addr=%s tid=%hu ttl=%lu serv=%s\n",
                ipstr(sa.sin_addr.s_addr, pkt), resp.tid, resp.ttl,
                ipstr(qp->server->ip, pkt + 33));
    }

    if (!qempty(&mp->active)) {
        QUERY  *qp = link_QUERY(mp->active.next);

        if (qp->expires <= time(0))
            return destroy_query(mp, qp, *ip = INADDR_ANY);
    }

    return NULL;
}
UINT CSearchList::ProcessSearchAnswer(const uchar* in_packet, uint32 size, bool bOptUTF8,
									  uint32 nServerIP, uint16 nServerPort, bool* pbMoreResultsAvailable)
{
	CSafeMemFile packet(in_packet, size);
	UINT results = packet.ReadUInt32();
	for (UINT i = 0; i < results; i++){
		CSearchFile* toadd = new CSearchFile(&packet, bOptUTF8, m_nCurED2KSearchID);
		toadd->SetClientServerIP(nServerIP);
		toadd->SetClientServerPort(nServerPort);
		if (nServerIP && nServerPort){
			CSearchFile::SServer server(nServerIP, nServerPort);
			server.m_uAvail = toadd->GetIntTagValue(FT_SOURCES);
			toadd->AddServer(server);
		}
		AddToList(toadd, false);
	}
	if (m_MobilMuleSearch)
		theApp.mmserver->SearchFinished(false);
	m_MobilMuleSearch = false;

	if (pbMoreResultsAvailable)
		*pbMoreResultsAvailable = false;
	int iAddData = (int)(packet.GetLength() - packet.GetPosition());
	if (iAddData == 1){
		uint8 ucMore = packet.ReadUInt8();
		if (ucMore == 0x00 || ucMore == 0x01){
			if (pbMoreResultsAvailable)
				*pbMoreResultsAvailable = ucMore!=0;
			if (thePrefs.GetDebugServerTCPLevel() > 0)
				Debug(_T("  Search answer(Server %s:%u): More=%u\n"), ipstr(nServerIP), nServerPort, ucMore);
		}
		else{
			if (thePrefs.GetDebugServerTCPLevel() > 0)
				Debug(_T("*** NOTE: ProcessSearchAnswer(Server %s:%u): ***AddData: 1 byte: 0x%02x\n"), ipstr(nServerIP), nServerPort, ucMore);
		}
	}
	else if (iAddData > 0){
		if (thePrefs.GetDebugServerTCPLevel() > 0){
			Debug(_T("*** NOTE: ProcessSearchAnswer(Server %s:%u): ***AddData: %u bytes\n"), ipstr(nServerIP), nServerPort, iAddData);
			DebugHexDump(in_packet + packet.GetPosition(), iAddData);
		}
	}

	packet.Close();
	return GetED2KResultCount();
}
Esempio n. 9
0
File: utils.c Progetto: m-b-/cidrc
char *
cidrstr(int v, uchar *ip, uchar *mask, char *to)
{
	int n;
	
	n = strlen(ipstr(v, ip, to));
	sprintf(to+n, "/%d", maskcnum(mask));

	return to;
}
Esempio n. 10
0
bool CClientList::AttachToAlreadyKnown(CUpDownClient** client, CClientReqSocket* sender){
	POSITION pos1, pos2;
	CUpDownClient* tocheck = (*client);
	CUpDownClient* found_client = NULL;
	CUpDownClient* found_client2 = NULL;
	for (pos1 = list.GetHeadPosition(); (pos2 = pos1) != NULL; ){
		list.GetNext(pos1);
		CUpDownClient* cur_client =	list.GetAt(pos2);
		if (tocheck->Compare(cur_client,false)){ //matching userhash
			found_client2 = cur_client;
		}
		if (tocheck->Compare(cur_client,true)){	 //matching IP
			found_client = cur_client;
			break;
		}
	}
	if (found_client == NULL)
		found_client = found_client2;

	if (found_client != NULL){
		if (tocheck == found_client){
			//we found the same client instance (client may have sent more than one OP_HELLO). do not delete that client!
			return true;
		}
		if (sender){
			if (found_client->socket){
				if (found_client->socket->IsConnected() 
					&& (found_client->GetIP() != tocheck->GetIP() || found_client->GetUserPort() != tocheck->GetUserPort() ) )
				{
					// if found_client is connected and has the IS_IDENTIFIED, it's safe to say that the other one is a bad guy
					if (found_client->Credits() && found_client->Credits()->GetCurrentIdentState(found_client->GetIP()) == IS_IDENTIFIED){
						if (thePrefs.GetLogBannedClients())
							AddDebugLogLine(false, _T("Clients: %s (%s), Banreason: Userhash invalid"), tocheck->GetUserName(), ipstr(tocheck->GetConnectIP()));
						tocheck->Ban();
						return false;
					}
	
					//IDS_CLIENTCOL Warning: Found matching client, to a currently connected client: %s (%s) and %s (%s)
					if (thePrefs.GetLogBannedClients())
						AddDebugLogLine(true,GetResString(IDS_CLIENTCOL), tocheck->GetUserName(), ipstr(tocheck->GetConnectIP()), found_client->GetUserName(), ipstr(found_client->GetConnectIP()));
					return false;
				}
				found_client->socket->client = 0;
				found_client->socket->Safe_Delete();
			}
			found_client->socket = sender;
			tocheck->socket = 0;
		}
		*client = 0;
		delete tocheck;
		*client = found_client;
		return true;
	}
	return false;
}
Esempio n. 11
0
void CIPFilterDlg::OnLvnGetDispInfoIPFilter(NMHDR *pNMHDR, LRESULT *pResult)
{
	NMLVDISPINFO* pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
	if (pDispInfo->item.mask & LVIF_TEXT) // *have* to check that flag!!
	{
		switch (pDispInfo->item.iSubItem)
		{
			case IPFILTER_COL_START:
				if (pDispInfo->item.cchTextMax > 0){
					_tcsncpy(pDispInfo->item.pszText, ipstr(htonl(m_ppIPFilterItems[pDispInfo->item.iItem]->start)), pDispInfo->item.cchTextMax);
					pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0');
				}
				break;
			case IPFILTER_COL_END:
				if (pDispInfo->item.cchTextMax > 0){
					_tcsncpy(pDispInfo->item.pszText, ipstr(htonl(m_ppIPFilterItems[pDispInfo->item.iItem]->end)), pDispInfo->item.cchTextMax);
					pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0');
				}
				break;
			case IPFILTER_COL_LEVEL:
				if (pDispInfo->item.cchTextMax > 0){
					_tcsncpy(pDispInfo->item.pszText, _itot(m_ppIPFilterItems[pDispInfo->item.iItem]->level, pDispInfo->item.pszText, 10), pDispInfo->item.cchTextMax);
					pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0');
				}
				break;
			case IPFILTER_COL_HITS:
				if (pDispInfo->item.cchTextMax > 0){
					_tcsncpy(pDispInfo->item.pszText, _itot(m_ppIPFilterItems[pDispInfo->item.iItem]->hits, pDispInfo->item.pszText, 10), pDispInfo->item.cchTextMax);
					pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0');
				}
				break;
			case IPFILTER_COL_DESC:
				if (pDispInfo->item.cchTextMax > 0){
					USES_CONVERSION;
					_tcsncpy(pDispInfo->item.pszText, A2T(m_ppIPFilterItems[pDispInfo->item.iItem]->desc), pDispInfo->item.cchTextMax);
					pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0');
				}
				break;
		}
	}
	*pResult = 0;
}
int CEncryptedDatagramSocket::DecryptReceivedServer(BYTE* pbyBufIn, int nBufLen, BYTE** ppbyBufOut, uint32 dwBaseKey, uint32 dbgIP) const{
	int nResult = nBufLen;
	*ppbyBufOut = pbyBufIn;
	
	if (nResult <= CRYPT_HEADER_WITHOUTPADDING || !thePrefs.IsServerCryptLayerUDPEnabled() || dwBaseKey == 0)
		return nResult;
	
	if(pbyBufIn[0] == OP_EDONKEYPROT)
			return nResult; // no encrypted packet (see description on top)

	// might be an encrypted packet, try to decrypt
	uchar achKeyData[7];
	memcpy(achKeyData, &dwBaseKey, 4);
	achKeyData[4] = MAGICVALUE_UDP_SERVERCLIENT;
	memcpy(achKeyData + 5, pbyBufIn + 1, 2); // random key part sent from remote server
	MD5Sum md5(achKeyData, sizeof(achKeyData));
	RC4_Key_Struct keyReceiveKey;
	RC4CreateKey(md5.GetRawHash(), 16, &keyReceiveKey, true);
	
	uint32 dwValue;
	RC4Crypt(pbyBufIn + 3, (uchar*)&dwValue, sizeof(dwValue), &keyReceiveKey);
	if (dwValue == MAGICVALUE_UDP_SYNC_SERVER){
		// yup this is an encrypted packet
		if (thePrefs.GetDebugServerUDPLevel() > 0)
			DEBUG_ONLY( DebugLog(_T("Received obfuscated UDP packet from ServerIP: %s"), ipstr(dbgIP)) );
		uint8 byPadLen;
		RC4Crypt(pbyBufIn + 7, (uchar*)&byPadLen, 1, &keyReceiveKey);
		byPadLen &= 15;
		nResult -= CRYPT_HEADER_WITHOUTPADDING;
		if (nResult <= byPadLen){
			DebugLogError(_T("Invalid obfuscated UDP packet from ServerIP: %s, Paddingsize (%u) larger than received bytes"), ipstr(dbgIP), byPadLen);
			return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk
		}
		if (byPadLen > 0)
			RC4Crypt(NULL, NULL, byPadLen, &keyReceiveKey);
		nResult -= byPadLen;
		*ppbyBufOut = pbyBufIn + (nBufLen - nResult);
		RC4Crypt((uchar*)*ppbyBufOut, (uchar*)*ppbyBufOut, nResult, &keyReceiveKey);
		
		//Xman
		// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
		/*
		theStats.AddDownDataOverheadCrypt(nBufLen - nResult);
		*/
		theApp.pBandWidthControl->AddeMuleInObfuscation(nBufLen - nResult);
		//Xman end
		return nResult; // done
	}
	else{
		DebugLogWarning(_T("Obfuscated packet expected but magicvalue mismatch on UDP packet from ServerIP: %s"), ipstr(dbgIP));
		return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk
	}
}
Esempio n. 13
0
int CEncryptedDatagramSocket::DecryptReceivedClient(BYTE* pbyBufIn, int nBufLen, BYTE** ppbyBufOut, uint32 dwIP) const{
	int nResult = nBufLen;
	*ppbyBufOut = pbyBufIn;
	
	if (nResult <= CRYPT_HEADER_WITHOUTPADDING || !thePrefs.IsClientCryptLayerSupported())
		return nResult;
	
	switch (pbyBufIn[0]){
		case OP_EMULEPROT:
		case OP_KADEMLIAPACKEDPROT:
		case OP_KADEMLIAHEADER:
		case OP_UDPRESERVEDPROT1:
		case OP_UDPRESERVEDPROT2:
		case OP_PACKEDPROT:
			return nResult; // no encrypted packet (see description on top)
	}
	// might be an encrypted packet, try to decrypt
	uchar achKeyData[23];
	md4cpy(achKeyData, thePrefs.GetUserHash());
	achKeyData[20] = MAGICVALUE_UDP;
	memcpy(achKeyData + 16, &dwIP, 4);
	memcpy(achKeyData + 21, pbyBufIn + 1, 2); // random key part sent from remote client
	MD5Sum md5(achKeyData, sizeof(achKeyData));
	RC4_Key_Struct keyReceiveKey;
	RC4CreateKey(md5.GetRawHash(), 16, &keyReceiveKey, true);
	
	uint32 dwValue;
	RC4Crypt(pbyBufIn + 3, (uchar*)&dwValue, sizeof(dwValue), &keyReceiveKey);
	if (dwValue == MAGICVALUE_UDP_SYNC_CLIENT){
		// yup this is an encrypted packet
		DEBUG_ONLY( DebugLog(_T("Received obfuscated UDP packet from clientIP: %s"), ipstr(dwIP)) );
		uint8 byPadLen;
		RC4Crypt(pbyBufIn + 7, (uchar*)&byPadLen, 1, &keyReceiveKey);
		nResult -= CRYPT_HEADER_WITHOUTPADDING;
		if (nResult <= byPadLen){
			DebugLogError(_T("Invalid obfuscated UDP packet from clientIP: %s, Paddingsize (%u) larger than received bytes"), ipstr(dwIP), byPadLen);
			return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk
		}
		if (byPadLen > 0)
			RC4Crypt(NULL, NULL, byPadLen, &keyReceiveKey);
		nResult -= byPadLen;
		*ppbyBufOut = pbyBufIn + (nBufLen - nResult);
		RC4Crypt((uchar*)*ppbyBufOut, (uchar*)*ppbyBufOut, nResult, &keyReceiveKey);
		
		theStats.AddDownDataOverheadCrypt(nBufLen - nResult);
		return nResult; // done
	}
	else{
		DebugLogWarning(_T("Obfuscated packet expected but magicvalue mismatch on UDP packet from clientIP: %s"), ipstr(dwIP));
		return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk
	}
}
Esempio n. 14
0
static void *
destroy_query(MADNS * mp, QUERY * qp, in_addr_t logip)
{
    void   *ret = qp->ctx;
    double  latency = tick() - qp->started;

    qp->server->nreqs--;
    qp->server->latency += (latency - qp->server->latency)
        / mp->server_reqs / 2;
    char    ips[99];

    LOG("%s %s lat %.4f -> server %s %.4f reqs=%d\n", qp->name,
        ipstr(logip, ips + 33), latency, ipstr(qp->server->ip, ips),
        qp->server->latency, qp->server->nreqs);

    free(qp->name);
    qpull(&qp->link);
    memset(qp, 0, sizeof *qp);
    qpush(&mp->unused, &qp->link);
    mp->nfree++;

    return ret;
}
Esempio n. 15
0
bool CUpDownClient::SendPeerCacheFileRequest()
{
	if (GetDownloadState() == DS_ONQUEUE){
		ASSERT( m_ePeerCacheDownState == PCDS_NONE );
		ASSERT( m_pPCDownSocket == NULL );
	}
	else if (GetDownloadState() == DS_DOWNLOADING){
		ASSERT( m_ePeerCacheDownState == PCDS_NONE );
		ASSERT( m_pPCDownSocket == NULL );
	}
	else{
		ASSERT(0);
	}

	if (!SupportPeerCache() || socket == NULL){
		ASSERT(0);
		return false;
	}

	m_uPeerCacheDownloadPushId = GetRandomUInt32();

	CSafeMemFile data(128);
	data.WriteUInt8(PCPCK_VERSION);
	data.WriteUInt8(PCOP_REQ);
	data.WriteUInt8(5);
	CTag tagCacheIP(PCTAG_CACHEIP, theApp.m_pPeerCache->GetCacheIP());
	tagCacheIP.WriteNewEd2kTag(&data);
	CTag tagPushId(PCTAG_PUSHID, m_uPeerCacheDownloadPushId);
	tagPushId.WriteNewEd2kTag(&data);
	CTag tagFileId(PCTAG_FILEID, (uchar*)reqfile->GetFileHash());
	tagFileId.WriteNewEd2kTag(&data);
	CTag tagPublicIP(PCTAG_PUBLICIP, theApp.GetPublicIP());
	tagPublicIP.WriteNewEd2kTag(&data);
	CTag tagCachePort(PCTAG_CACHEPORT, theApp.m_pPeerCache->GetCachePort());
	tagCachePort.WriteNewEd2kTag(&data);

	if (thePrefs.GetDebugClientTCPLevel() > 0){
		DebugSend("OP__PeerCacheQuery", this, reqfile->GetFileHash());
		Debug(_T("  CacheIP=%s  PushId=%u  PublicIP=%s  FileId=%s\n"), ipstr(tagCacheIP.GetInt()), tagPushId.GetInt(), ipstr(tagPublicIP.GetInt()), md4str(tagFileId.GetHash()));
	}

	Packet* pEd2kPacket = new Packet(&data, OP_EMULEPROT, OP_PEERCACHE_QUERY);
	theStats.AddUpDataOverheadFileRequest(pEd2kPacket->size);
	socket->SendPacket(pEd2kPacket);
	SetDownloadState(DS_DOWNLOADING);
	m_dwLastBlockReceived = ::GetTickCount();
	SetPeerCacheDownState(PCDS_WAIT_CLIENT_REPLY);
	return true;
}
Esempio n. 16
0
void CapturePacketThread::PacketHandler(u_char * user,const struct pcap_pkthdr *h,const u_char * p)
{
	//Releaseinfo("PacketHandler input");
    struct tm ltime;
    char timestr[20]={0};
    time_t local_tv_sec;
	char *ipc =(char *)user;
	string ipstr("");
	ipstr = ipc;
	local_tv_sec = h->ts.tv_sec;
    localtime_s(&ltime, &local_tv_sec);
    strftime( timestr, sizeof timestr, "%Y-%m-%d %H:%M:%S", &ltime);
	PROTOCOL_DEFINE::IP_HEADER *ip=(PROTOCOL_DEFINE::IP_HEADER *)(p+14);
	char srcipstr[16]={0};
    char desipstr[16]={0};
    sprintf(srcipstr,"%d.%d.%d.%d",ip->src_addr[0],ip->src_addr[1],ip->src_addr[2],ip->src_addr[3]);
    sprintf(desipstr,"%d.%d.%d.%d",ip->des_addr[0],ip->des_addr[1],ip->des_addr[2],ip->des_addr[3]);
	u_int ipheaderlen=PROTOCOL_DEFINE::GetIPHeaderLength(ip);
	IpPacket *ipobj = new IpPacket();
	string srcip_str = srcipstr;
	string desip_str = desipstr;
    ipobj->set_sip(srcipstr);
    ipobj->set_dip(desipstr);
    ipobj->set_datetime(timestr);
    ipobj->set_length(h->len);
	if(srcip_str == ipstr)
		ipobj->set_flow(0); //0表示上传
	if(desip_str == ipstr)
		ipobj->set_flow(1);//1表示下传
	switch(ip->protocol)
    {
        case TCP:
			{
				TcpPacketHandler(p+14+ipheaderlen,ipobj,h->len-14-ipheaderlen,ipstr);
				
			}
            break;
        case UDP:
			{
				UdpPacketHandler(p+14+ipheaderlen,ipobj,h->len-14-ipheaderlen,ipstr);
				
			}
            break;
		default:
            //Should't be here
			delete ipobj;
			return;
    }
}
Esempio n. 17
0
// Creates an EndPoint from its string representation
// withNetMask = true --> string contains netmask
// withNetMask = false --> string doesnt contain netmask
void EndPoint::fromString(const std::string & epstr) {

  std::string::size_type i = epstr.find(':', 0);
  std::string ipstr(epstr, 0, i);
  std::string::size_type j = epstr.find('|', i);
  std::string portstr(epstr, i+1, j-i-1);
  std::string::size_type k = epstr.find('_', j);
  std::string protostr(epstr, j+1, k-j-1);

  ipAddr.fromString(ipstr);
  portNr = atoi(portstr.c_str());
  protocolID = atoi(protostr.c_str());

  return;
}
Esempio n. 18
0
bool CClientList::DoRequestFirewallCheckUDP(const Kademlia::CContact& contact){
	// first make sure we don't know this IP already from somewhere
	if (FindClientByIP(ntohl(contact.GetIPAddress())) != NULL)
		return false;
	// fine, justcreate the client object, set the state and wait
	// TODO: We don't know the clients usershash, this means we cannot build an obfuscated connection, which 
	// again mean that the whole check won't work on "Require Obfuscation" setting, which is not a huge problem,
	// but certainly not nice. Only somewhat acceptable way to solve this is to use the KadID instead.
	CUpDownClient* pNewClient = new CUpDownClient(0, contact.GetTCPPort(), contact.GetIPAddress(), 0, 0, false );
	pNewClient->SetKadState(KS_QUEUED_FWCHECK_UDP);
	DebugLog(_T("Selected client for UDP Firewallcheck: %s"), ipstr(ntohl(contact.GetIPAddress())));
	AddToKadList(pNewClient);
	AddClient(pNewClient);
	ASSERT( !pNewClient->SupportsDirectUDPCallback() );
	return true;
}
Esempio n. 19
0
/* format a string for the log, with suitable prefixes.
 * A format starting with ~ indicates that this is a reprocessing
 * of the message, so prefixing and quoting is suppressed.
 */
static void fmt_log(char *buf, size_t buf_len, const char *fmt, va_list ap)
{
	bool reproc = *fmt == '~';
	size_t ps;
	struct connection *c = cur_state != NULL ? cur_state->st_connection :
			       cur_connection;

	buf[0] = '\0';
	if (reproc) {
		fmt++; /* ~ at start of format suppresses this prefix */
	} else if (c != NULL) {
		/* start with name of connection */
		char *const be = buf + buf_len;
		char *bp = buf;

		snprintf(bp, be - bp, "\"%s\"", c->name);
		bp += strlen(bp);

		/* if it fits, put in any connection instance information */
		if (be - bp > CONN_INST_BUF) {
			fmt_conn_instance(c, bp);
			bp += strlen(bp);
		}

		if (cur_state != NULL) {
			/* state number */
			snprintf(bp, be - bp, " #%lu", cur_state->st_serialno);
			bp += strlen(bp);
		}
		snprintf(bp, be - bp, ": ");
	} else if (cur_from != NULL) {
		/* peer's IP address */
		ipstr_buf b;

		snprintf(buf, buf_len, "packet from %s:%u: ",
			 ipstr(cur_from, &b),
			 (unsigned)cur_from_port);
	}

	ps = strlen(buf);
	vsnprintf(buf + ps, buf_len - ps, fmt, ap);
	if (!reproc)
		sanitize_string(buf, buf_len);
}
Esempio n. 20
0
void CNatThread::RegisterMe(DWORD sip, WORD sport)
{
	// modified by robert, 2010-07-30 加锁
	CSingleLock locker(&m_Mutex, TRUE);
	
	if(!CGlobalVariable::clientudp) return;
	
	_AddDebugLogLine(false, _T("CNatThread::RegisterMe"));
	
	if(!m_bRegister)
		AddLogLine(false, _T("Registering to NAT traversal server [%s]\n"),ipstr(sip,ntohs(sport)));

	m_dwSvrKeepalive = m_RegisterTime = time(NULL);


	// VC-SearchDream[2007-06-08]: new way statics Begin
	if (m_RegisterTime - m_dwSendStaticsTime > 60 * 10)
	{
		uchar pack[22];
		GetMyUserHash(pack);

		WORD counter1 = m_wTraverseBySvr, counter2 = m_wTraverseBySvr, counter3 = m_wTraverseBySE;

		counter1 = htons(counter1);
		counter2 = htons(counter2);
		counter3 = htons(counter3);

		memcpy(pack+16, &counter1, 2);
		memcpy(pack+18, &counter2, 2);
		memcpy(pack+20, &counter3, 2);

		CNatSocket::SendPacket(sip, sport, OP_NAT_REGISTER, pack, 22);

		m_dwSendStaticsTime = m_RegisterTime;
		m_wTraverseBySvr = m_wTraverseBySE = 0;
	}
	else
	{
		uchar pack[16];
		GetMyUserHash(pack);

		CNatSocket::SendPacket(sip, sport, OP_NAT_REGISTER, pack, 16);
	}
}
Esempio n. 21
0
void CFriend::KadSearchIPByNodeIDResult(Kademlia::EKadClientSearchRes eStatus, uint32_t dwIP, uint16_t nPort){
	if (!theApp.friendlist->IsValid(this))
	{
		ASSERT( false );
		return;
	}
	if (m_FriendConnectState == FCS_KADSEARCHING ){
		if (eStatus == Kademlia::KCSR_SUCCEEDED && GetLinkedClient(true) != NULL){
			DebugLog(_T("Successfully fetched IP (%s) by KadID (%s) for friend %s"), ipstr(dwIP), md4str(m_abyKadID), m_strName.IsEmpty() ? _T("(Unknown)") : m_strName);
			if (GetLinkedClient()->GetIP() != dwIP || GetLinkedClient()->GetUserPort() != nPort){
				// retry to connect with our new found IP
				for (POSITION pos = m_liConnectionReport.GetHeadPosition(); pos != 0; m_liConnectionReport.GetNext(pos)){
					m_liConnectionReport.GetAt(pos)->ReportConnectionProgress(GetLinkedClient(), _T(" ...") + GetResString(IDS_FOUND) + _T("\n"), true);
					m_liConnectionReport.GetAt(pos)->ReportConnectionProgress(m_LinkedClient, _T("*** ") + GetResString(IDS_CONNECTING), false);
				}
				m_FriendConnectState = FCS_CONNECTING;
				m_LinkedClient->SetChatState(MS_CONNECTING);
				if (m_LinkedClient->socket != NULL && m_LinkedClient->socket->IsConnected())
				{
					// we shouldnt get he since we checked for FCS_KADSEARCHING
					ASSERT( false );
					UpdateFriendConnectionState(FCR_ESTABLISHED);
				}
				m_dwLastUsedIP = dwIP;
				m_nLastUsedPort = nPort;
				m_LinkedClient->SetIP(dwIP);
				m_LinkedClient->SetUserPort(nPort);
				m_LinkedClient->TryToConnect(true);
				return;
			}
			else
				DebugLog(_T("KadSearchIPByNodeIDResult: Result IP is the same as known (not working) IP (%s)"), ipstr(dwIP));
		}
		DebugLog(_T("Failed to fetch IP by KadID (%s) for friend %s"), md4str(m_abyKadID), m_strName.IsEmpty() ? _T("(Unknown)") : m_strName);
		// here ends our journey to connect to our friend unsuccessfully
		m_FriendConnectState = FCS_NONE;
		for (POSITION pos = m_liConnectionReport.GetHeadPosition(); pos != 0;)
			m_liConnectionReport.GetNext(pos)->ConnectingResult(GetLinkedClient(), false);
		m_liConnectionReport.RemoveAll();
	}
	else
		ASSERT( false );
}
Esempio n. 22
0
File: tests.c Progetto: m-b-/cidrc
/*
 * parseipv4, parseipv6, parseip,
 * ip4str,    ip6str,    ipstr
 */
int
testips(void)
{
	char  ip[LenStr];
	uchar pip[V6];
	int i, v;

	Z(ip); Z(pip);

	for (i = 0; ips[i].ip; i++) {
		v = parseip(ips[i].ip, pip);
		if (v != ips[i].v)
			fprintf(stderr, "testparse: %d != %d\n", ips[i].v, v);
		else if (v != -1)
		if (strcmp(ips[i].rip, ipstr(v, pip, ip)) != 0)
			fprintf(stderr, "testparse: %s != %s\n",
				ips[i].rip, ip);
	}

	return 0;
}
Esempio n. 23
0
void *UdpServer::processThread(struct sockaddr_in sender,void *ptr, NetworkMessage mid)
{
    switch(mid.getId()){
    case UDPHELLO:
    {
        char* ip = inet_ntoa(sender.sin_addr);
        string ipstr(ip);

        if(!((UdpServer*)ptr)->isOwnAddress(sender))
            ((UdpServer*)ptr)->UdpHelloSignal(ipstr);
    }
    break;
    case VISITORPACKAGE:
    {
        int len;
        socklen_t sendsize = sizeof(sender);
        recvfrom(((UdpServer*)ptr)->getSock(), &len, sizeof(int),0,(struct sockaddr*)&sender, &sendsize);
        char buffer[len];
        recvfrom( ((UdpServer*)ptr)->getSock(), buffer, len,0,(struct sockaddr*)&sender, &sendsize);
        string temp;
        temp.assign(buffer,len);
        VisitorPackage incomingVisitorPackage;
        try{
            incomingVisitorPackage.fromStream(temp);

            if(!((UdpServer*)ptr)->isOwnAddress(sender))
                ((UdpServer*)ptr)->VisitorPackageSignal(incomingVisitorPackage);

        }catch(Server4WinException& e)
        {
           cout << e.what() << endl;
        }


    }
    default: // Do Nothing...
    break;
    }
}
Esempio n. 24
0
void CChatSelector::ProcessMessage(CUpDownClient* sender, const CString& message)
{
	sender->IncMessagesReceived();
	CChatItem* ci = GetItemByClient(sender);

	AddLogLine(true, GetResString(IDS_NEWMSG), sender->GetUserName(), ipstr(sender->GetConnectIP()));
	
	bool isNewChatWindow = false;
	if (!ci)
	{
		if ((UINT)GetItemCount() >= thePrefs.GetMsgSessionsMax())
			return;
		ci = StartSession(sender, false);
		isNewChatWindow = true; 
	}
	if (thePrefs.GetIRCAddTimeStamp())
		AddTimeStamp(ci);
	ci->log->AppendKeyWord(sender->GetUserName(), RECV_SOURCE_MSG_COLOR);
	ci->log->AppendText(_T(": "));
	ci->log->AppendText(message + _T("\n"));
	int iTabItem = GetTabByClient(sender);
	if (GetCurSel() == iTabItem && GetParent()->IsWindowVisible())
	{
		// chat window is already visible
		;
	}
	else if (GetCurSel() != iTabItem)
	{
		// chat window is already visible, but tab is not selected
		ci->notify = true;
	}
	else
	{
		ci->notify = true;
        if (isNewChatWindow || thePrefs.GetNotifierOnEveryChatMsg())
			theApp.emuledlg->ShowNotifier(GetResString(IDS_TBN_NEWCHATMSG) + _T(" ") + CString(sender->GetUserName()) + _T(":'") + message + _T("'\n"), TBN_CHAT);
		isNewChatWindow = false;
	}
}
Esempio n. 25
0
void CGlobalVariable::SetPublicIP(const uint32 dwIP)
{
	if (dwIP != 0){
		ASSERT ( !IsLowID(dwIP));
		ASSERT ( m_pPeerCache );
		if ( GetPublicIP() == 0)
			AddDebugLogLine(DLP_VERYLOW, false, _T("My public IP Address is: %s"),ipstr(dwIP));
		else if (Kademlia::CKademlia::IsConnected() && Kademlia::CKademlia::GetPrefs()->GetIPAddress())
			if(ntohl(Kademlia::CKademlia::GetIPAddress()) != dwIP)
				AddDebugLogLine(DLP_DEFAULT, false,  _T("Public IP Address reported from Kademlia (%s) differs from new found (%s)"),ipstr(ntohl(Kademlia::CKademlia::GetIPAddress())),ipstr(dwIP));
		m_pPeerCache->FoundMyPublicIPAddress(dwIP);	
		
		m_pMyCountry = CGlobalVariable::ip2country->GetCountryFromIP(dwIP);
	}
	else
		AddDebugLogLine(DLP_VERYLOW, false, _T("Deleted public IP"));

	if (dwIP != 0 && dwIP != m_dwPublicIP && CGlobalVariable::serverlist != NULL){
		m_dwPublicIP = dwIP;
		CGlobalVariable::serverlist->CheckForExpiredUDPKeys();
	}
	else
		m_dwPublicIP = dwIP;
}
Esempio n. 26
0
void FilterEndPoint::fromString(const std::string & fepstr, bool withNetmask) {

  if (withNetmask == true) {
    std::string::size_type h = fepstr.find('/', 0);
    std::string ipstr(fepstr, 0, h);
    std::string::size_type i = fepstr.find(':', h);
    std::string netmaskstr(fepstr, h+1, i-h-1);
    std::string::size_type j = fepstr.find('|', i);
    std::string portstr(fepstr, i+1, j-i-1);
    std::string::size_type k = fepstr.find('_', j);
    std::string protostr(fepstr, j+1, k-j-1);

    ipAddr.fromString(ipstr);
    if (atoi(netmaskstr.c_str()) > 0 && atoi(netmaskstr.c_str()) < 32) {
      nmask = atoi(netmaskstr.c_str());
      ipAddr.remanent_mask(nmask);
    }
    else if (atoi(netmaskstr.c_str()) == 0) {
      nmask = 0;
    }
    else if (atoi(netmaskstr.c_str()) < 0 || atoi(netmaskstr.c_str()) > 32) {
      std::cerr << "WARNING:: Invalid Netmask occured in FilterEndPoint::fromString()!\n"
      << "  Netmask may only be a value "
      << "between 0 and 32! Thus, 32 will be assumed for now!\n";
      nmask = 32;
    }
    portNr = atoi(portstr.c_str());
    protocolID = atoi(protostr.c_str());
  }
  else {
    this->EndPoint::fromString(fepstr);
    nmask = 32;
  }

  return;
}
Esempio n. 27
0
bool CClientList::IncomingBuddy(Kademlia::CContact* contact, Kademlia::CUInt128* buddyID )
{
	uint32 nContactIP = ntohl(contact->GetIPAddress());
	//If eMule already knows this client, abort this.. It could cause conflicts.
	//Although the odds of this happening is very small, it could still happen.
	if (FindClientByIP(nContactIP, contact->GetTCPPort()))
		return false;
	else if (IsKadFirewallCheckIP(nContactIP)){ // doing a kad firewall check with this IP, abort 
		DEBUG_ONLY( DebugLogWarning(_T("KAD tcp Firewallcheck / Buddy request collosion for IP %s"), ipstr(nContactIP)) );
		return false;
	}
	else if (theApp.serverconnect->GetLocalIP() == nContactIP && thePrefs.GetPort() == contact->GetTCPPort())
		return false; // don't connect ourself

	//Add client to the lists to be processed.
	CUpDownClient* pNewClient = new CUpDownClient(0, contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, false );
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_INCOMING_BUDDY);
	byte ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(ID); //??
	buddyID->ToByteArray(ID);
	pNewClient->SetBuddyID(ID);
	//MORPH START - Changed by SiRoB, Optimization
	/*
	AddToKadList(pNewClient);
	AddClient(pNewClient);
	*/
	m_KadList.AddTail(pNewClient);
	AddClient(pNewClient, true);
	//MORPH END   - Changed by SiRoB, Optimization
	return true;
}
Esempio n. 28
0
void CClientList::RequestBuddy(Kademlia::CContact* contact, uint8 byConnectOptions)
{
	uint32 nContactIP = ntohl(contact->GetIPAddress());
	// don't connect ourself
	if (theApp.serverconnect->GetLocalIP() == nContactIP && thePrefs.GetPort() == contact->GetTCPPort())
		return;
	CUpDownClient* pNewClient = FindClientByIP(nContactIP, contact->GetTCPPort());
	bool bNewClient = true; //MOPRH - Added by SiRoB,  Fix adding multiple clientKnown with same ip port
	if (!pNewClient)
		pNewClient = new CUpDownClient(0, contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, false );
	else if (pNewClient->GetKadState() != KS_NONE)
		return; // already busy with this client in some way (probably fw stuff), don't mess with it
	else if (IsKadFirewallCheckIP(nContactIP)){ // doing a kad firewall check with this IP, abort 
		DEBUG_ONLY( DebugLogWarning(_T("KAD tcp Firewallcheck / Buddy request collosion for IP %s"), ipstr(nContactIP)) );
		return;
	}
	//MORPH START - Added by SiRoB, Fix adding multiple clientKnown
	else
		bNewClient = false;
	//MORPH END   - Added by SiRoB, Fix adding multiple clientKnown with same ip port
	
	//Add client to the lists to be processed.
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_QUEUED_BUDDY);
	byte ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(ID);
	pNewClient->SetConnectOptions(byConnectOptions, true, false);
	//MORPH START - Added by SiRoB, Optimization
	/*
	AddToKadList(pNewClient);
	//This method checks if this is a dup already.
	AddClient(pNewClient);
	*/
	if (bNewClient) {
		m_KadList.AddTail(pNewClient);
		AddClient(pNewClient, true);
	} else
		AddToKadList(pNewClient);
	//MORPH END   - Changed by SiRoB, Optimization
}
Esempio n. 29
0
void CClientList::TrackBadRequest(const CUpDownClient* upcClient, int nIncreaseCounter){
	CDeletedClient* pResult = NULL;
	if (upcClient->GetIP() == 0){
		ASSERT( false );
		return;
	}
	if (m_trackedClientsList.Lookup(upcClient->GetIP(), pResult)){
		pResult->m_dwInserted = ::GetTickCount();
		pResult->m_cBadRequest += nIncreaseCounter;
		// morph some extra verbose tracking, read http://forum.emule-project.net/index.php?showtopic=136682
		DebugLogError( _T("Client: %s (%s), Increased badrequestcounter to %d"), upcClient->GetUserName(), ipstr(upcClient->GetConnectIP()),pResult->m_cBadRequest);
	}
	else{
		CDeletedClient* ccToAdd = new CDeletedClient(upcClient);
		ccToAdd->m_cBadRequest = nIncreaseCounter;
		// morph some extra verbose tracking, read http://forum.emule-project.net/index.php?showtopic=136682
		// nIncreaseCounter equals ccToAdd->m_cBadRequest here so i will rather use the first
		// anyway, pResult->m_cBadRequest is utterly wrong because pResult is a NULL-pointer here
		DebugLogError( _T("Client: %s (%s), Increased set badrequestcounter to %d"), upcClient->GetUserName(), ipstr(upcClient->GetConnectIP()),nIncreaseCounter);
		m_trackedClientsList.SetAt(upcClient->GetIP(), ccToAdd);
	}
}
int CEncryptedDatagramSocket::DecryptReceivedClient(BYTE* pbyBufIn, int nBufLen, BYTE** ppbyBufOut, uint32 dwIP, uint32* nReceiverVerifyKey, uint32* nSenderVerifyKey) const{
	int nResult = nBufLen;
	*ppbyBufOut = pbyBufIn;
	
	if (nReceiverVerifyKey == NULL || nSenderVerifyKey == NULL){
		ASSERT( false );
		return nResult;
	}
	
	*nReceiverVerifyKey = 0;
	*nSenderVerifyKey = 0;

	if (nResult <= CRYPT_HEADER_WITHOUTPADDING /*|| !thePrefs.IsClientCryptLayerSupported()*/)
		return nResult;	

	switch (pbyBufIn[0]){
		case OP_EMULEPROT:
		case OP_KADEMLIAPACKEDPROT:
		case OP_KADEMLIAHEADER:
		case OP_UDPRESERVEDPROT1:
		case OP_UDPRESERVEDPROT2:
		case OP_PACKEDPROT:
			return nResult; // no encrypted packet (see description on top)
	}

	// might be an encrypted packet, try to decrypt
	RC4_Key_Struct keyReceiveKey;
	uint32 dwValue = 0;
	// check the marker bit which type this packet could be and which key to test first, this is only an indicator since old clients have it set random
	// see the header for marker bits explanation
	byte byCurrentTry = ((pbyBufIn[0] & 0x03) == 3) ? 1 : (pbyBufIn[0] & 0x03); 
	byte byTries;
	if (Kademlia::CKademlia::GetPrefs() == NULL) {
		// if kad never run, no point in checking anything except for ed2k encryption
		byTries = 1;
		byCurrentTry = 1;
	}
	else
		byTries = 3;
	bool bKadRecvKeyUsed = false;
	bool bKad = false;
	do{
		byTries--;
		MD5Sum md5;
		if (byCurrentTry == 0) {
			// kad packet with NodeID as key
			bKad = true;
			bKadRecvKeyUsed = false;
			if (Kademlia::CKademlia::GetPrefs()) {
				uchar achKeyData[18];
				memcpy(achKeyData, Kademlia::CKademlia::GetPrefs()->GetKadID().GetData(), 16);
				memcpy(achKeyData + 16, pbyBufIn + 1, 2); // random key part sent from remote client
				md5.Calculate(achKeyData, sizeof(achKeyData));
			}
		}
		else if (byCurrentTry == 1) {
			// ed2k packet
			bKad = false;
			bKadRecvKeyUsed = false;
			uchar achKeyData[23];
			md4cpy(achKeyData, thePrefs.GetUserHash());
			achKeyData[20] = MAGICVALUE_UDP;
			memcpy(achKeyData + 16, &dwIP, 4);
			memcpy(achKeyData + 21, pbyBufIn + 1, 2); // random key part sent from remote client
			md5.Calculate(achKeyData, sizeof(achKeyData));
		}
		else if (byCurrentTry == 2) {
			// kad packet with ReceiverKey as key
			bKad = true;
			bKadRecvKeyUsed = true;
			if (Kademlia::CKademlia::GetPrefs()) {
				uchar achKeyData[6];
				PokeUInt32(achKeyData, Kademlia::CPrefs::GetUDPVerifyKey(dwIP));
				memcpy(achKeyData + 4, pbyBufIn + 1, 2); // random key part sent from remote client
				md5.Calculate(achKeyData, sizeof(achKeyData));
			}
		}
		else
			ASSERT( false );

		RC4CreateKey(md5.GetRawHash(), 16, &keyReceiveKey, true);
		RC4Crypt(pbyBufIn + 3, (uchar*)&dwValue, sizeof(dwValue), &keyReceiveKey);
		byCurrentTry = (byCurrentTry + 1) % 3;
	} while (dwValue != MAGICVALUE_UDP_SYNC_CLIENT && byTries > 0); // try to decrypt as ed2k as well as kad packet if needed (max 3 rounds)
	
	if (dwValue == MAGICVALUE_UDP_SYNC_CLIENT){
		// yup this is an encrypted packet
		// debugoutput notices
		// the following cases are "allowed" but shouldn't happen given that there is only our implementation yet
		if (bKad && (pbyBufIn[0] & 0x01) != 0)
			DebugLog(_T("Received obfuscated UDP packet from clientIP: %s with wrong key marker bits (kad packet, ed2k bit)"), ipstr(dwIP));
		else if (bKad && !bKadRecvKeyUsed && (pbyBufIn[0] & 0x02) != 0)
			DebugLog(_T("Received obfuscated UDP packet from clientIP: %s with wrong key marker bits (kad packet, nodeid key, recvkey bit)"), ipstr(dwIP));
		else if (bKad && bKadRecvKeyUsed && (pbyBufIn[0] & 0x02) == 0)
			DebugLog(_T("Received obfuscated UDP packet from clientIP: %s with wrong key marker bits (kad packet, recvkey key, nodeid bit)"), ipstr(dwIP));

		uint8 byPadLen;
		RC4Crypt(pbyBufIn + 7, (uchar*)&byPadLen, 1, &keyReceiveKey);
		nResult -= CRYPT_HEADER_WITHOUTPADDING;
		if (nResult <= byPadLen){
			DebugLogError(_T("Invalid obfuscated UDP packet from clientIP: %s, Paddingsize (%u) larger than received bytes"), ipstr(dwIP), byPadLen);
			return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk
		}
		if (byPadLen > 0)
			RC4Crypt(NULL, NULL, byPadLen, &keyReceiveKey);
		nResult -= byPadLen;

		if (bKad){
			if (nResult <= 8){
				DebugLogError(_T("Obfuscated Kad packet with mismatching size (verify keys missing) received from clientIP: %s"), ipstr(dwIP));
				return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk;
			}
			// read the verify keys
			RC4Crypt(pbyBufIn + CRYPT_HEADER_WITHOUTPADDING + byPadLen, (uchar*)nReceiverVerifyKey, 4, &keyReceiveKey);
			RC4Crypt(pbyBufIn + CRYPT_HEADER_WITHOUTPADDING + byPadLen + 4, (uchar*)nSenderVerifyKey, 4, &keyReceiveKey);
			nResult -= 8;
		}
		*ppbyBufOut = pbyBufIn + (nBufLen - nResult);
		RC4Crypt((uchar*)*ppbyBufOut, (uchar*)*ppbyBufOut, nResult, &keyReceiveKey);
		//Xman
		// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
		/*
		theStats.AddDownDataOverheadCrypt(nBufLen - nResult);
		*/
		theApp.pBandWidthControl->AddeMuleInObfuscation(nBufLen - nResult);
		//Xman end
		//DEBUG_ONLY( DebugLog(_T("Received obfuscated UDP packet from clientIP: %s, Key: %s, RKey: %u, SKey: %u"), ipstr(dwIP), bKad ? (bKadRecvKeyUsed ? _T("ReceiverKey") : _T("NodeID")) : _T("UserHash")
		//	, nReceiverVerifyKey != 0 ? *nReceiverVerifyKey : 0, nSenderVerifyKey != 0 ? *nSenderVerifyKey : 0) );
		return nResult; // done
	}
	else{
		DebugLogWarning(_T("Obfuscated packet expected but magicvalue mismatch on UDP packet from clientIP: %s, Possible RecvKey: %u"), ipstr(dwIP), Kademlia::CPrefs::GetUDPVerifyKey(dwIP));
		return nBufLen; // pass through, let the Receivefunction do the errorhandling on this junk
	}
}