📄 peercachefinder.cpp
字号:
//this file is part of eMule
//Copyright (C)2004 Merkur ( devs@emule-project.net / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
// notes to myself, remove before release :)
#include "StdAfx.h"
#include <windns.h>
#include "peercachefinder.h"
#include "emule.h"
#include "emuledlg.h"
#include "otherfunctions.h"
#include "Preferences.h"
#include "md5sum.h"
#include "version.h"
#include <crypto51/rsa.h>
#include <crypto51/integer.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define PCBASELOCATION "edcache.p2p."
#define RETRYDAYS 2
#define SIGNATURELENGTH 256
static char _acDNSBuffer[MAXGETHOSTSTRUCT];
static const uint16 anPeerCachPorts[3] = {4662, 1214, 80};
static const uchar achVerify_Key[256] = {
0xCE, 0x9A, 0x90, 0x08, 0x47, 0xE7, 0x1E, 0x15, 0x94, 0xFD, 0x65, 0xC7, 0x82, 0xF9, 0xB2,
0xB7, 0xB7, 0x6A, 0xF2, 0x4A, 0x31, 0x08, 0xFC, 0x36, 0x6C, 0xB1, 0xD9, 0x3F, 0x3B, 0x94, 0x6B,
0xC4, 0x55, 0x39, 0xAF, 0x53, 0x4D, 0x78, 0xE7, 0x1A, 0xE9, 0x83, 0x34, 0x1D, 0x6C, 0xE3, 0xEF,
0xAD, 0x56, 0x88, 0x0D, 0x38, 0x94, 0x86, 0x0F, 0x81, 0x7C, 0x9C, 0x21, 0xCF, 0x49, 0xDA, 0xE8,
0x13, 0x38, 0x30, 0x88, 0xBD, 0x6A, 0xCE, 0x66, 0x4C, 0xB0, 0x36, 0x3E,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CPeerCacheFinder::CPeerCacheFinder()
{
m_dwPCIP = 0;
m_PCStatus = PCS_NOINIT;
m_PCLUState = LUS_NONE;
m_posCurrentLookUp = 0;
m_dwMyIP = 0;
m_bValdited = false;
m_bNotReValdited = false;
m_bNotReSearched = false;
m_nDownloadAttempts = 0;
m_nFailedDownloads = 0;
m_nPCPort = 0;
}
CPeerCacheFinder::~CPeerCacheFinder(void)
{
}
void CPeerCacheFinder::Save(){
if (m_PCStatus > 10){ // permanent errorrange
if (!m_bNotReSearched){
thePrefs.SetPeerCacheLastSearch(mktime(CTime::GetCurrentTime().GetLocalTm()));
thePrefs.SetPeerCacheWasFound(false);
thePrefs.SetPeerCachePort(0);
}
}
else if (m_PCStatus == PCS_READY){
if (!m_bNotReValdited){
thePrefs.SetPeerCacheLastSearch(mktime(CTime::GetCurrentTime().GetLocalTm()));
}
thePrefs.SetPeerCachePort(m_nPCPort);
thePrefs.SetPeerCacheWasFound(true);
}
}
void CPeerCacheFinder::Init(uint32 dwLastSearch, bool bLastSearchSuccess, bool bEnabled, uint16 nPort){
if (!bEnabled){
m_PCStatus = PCS_DISABLED;
}
else{
if (bLastSearchSuccess){ // sanitycheck
bool bOK = false;
for (int i = 0; i != ARRSIZE(anPeerCachPorts); i++){
if(anPeerCachPorts[i] == nPort)
bOK = true;
}
if (!bOK){
dwLastSearch = 0;
bLastSearchSuccess = false;
DEBUG_ONLY(theApp.QueueDebugLogLine(false, _T("Sanitycheck for PeerCache-Port '%u' failed"), nPort));
}
else
m_nPCPort = nPort;
}
if (dwLastSearch != 0){
CTime last(dwLastSearch);
time_t tLast=safe_mktime(last.GetLocalTm());
time_t tNow=safe_mktime(CTime::GetCurrentTime().GetLocalTm());
if ( (difftime(tNow,tLast) / 86400) < RETRYDAYS ){
if (!bLastSearchSuccess){
// no retry to find the cache
m_PCStatus = PCS_NOTFOUND;
m_bNotReSearched = true;
DEBUG_ONLY(theApp.QueueDebugLogLine(false, _T("PeerCache: Not starting a search - last failed search is too near")));
return;
}
else{
// no need to revaldite the cache yet
m_bValdited = true;
m_bNotReValdited = true;
DEBUG_ONLY(theApp.QueueDebugLogLine(false, _T("PeerCache: CacheIdent still valid, not trying to revaldite this time")));
}
}
else
m_bNotReValdited = false;
}
m_bNotReSearched = false;
SearchForPC();
}
}
void CPeerCacheFinder::FoundMyPublicIPAddress(uint32 dwIP){
m_dwMyIP = dwIP;
if (m_PCStatus == PCS_OWNIPUNKNOWN){
m_PCStatus = PCS_DOINGLOOKUPS;
SearchForPC();
}
}
void CPeerCacheFinder::SearchForPC(){
switch(m_PCStatus){
case PCS_NOINIT:
m_PCStatus = PCS_DOINGLOOKUPS;
case PCS_DOINGLOOKUPS:
switch(m_PCLUState){
case LUS_NONE:
// ok lets start, base pos first
m_PCLUState = LUS_BASEPCLOCATION;
DoLookUp(PCBASELOCATION);
break;
case LUS_BASEPCLOCATION:
// so the first lookup failed, now we need our hostname
if (m_dwMyIP == 0){
// we have to wait until we now our IP for a reverse lookup
m_PCStatus = PCS_OWNIPUNKNOWN;
break;
}
m_PCLUState = LUS_MYHOSTNAME;
DoReverseLookUp(m_dwMyIP);
break;
case LUS_MYHOSTNAME:
// we should have found the hostname and now start to contruct sublocations to lookup
m_PCLUState = LUS_EXTPCLOCATION;
m_posCurrentLookUp = 0;
case LUS_EXTPCLOCATION:
ASSERT ( !m_strMyHostname.IsEmpty() );
// build string
m_posCurrentLookUp = m_strMyHostname.Find('.',m_posCurrentLookUp+1);
if (m_posCurrentLookUp == -1 || m_posCurrentLookUp+1 >= m_strMyHostname.GetLength() || m_strMyHostname.Find('.',m_posCurrentLookUp+1) == (-1) ){
// failed:
m_PCLUState = LUS_NONE;
m_PCStatus = PCS_NOTFOUND;
}
else{
DoLookUp(PCBASELOCATION + CStringA(m_strMyHostname.Mid(m_posCurrentLookUp+1)));
}
break;
case LUS_FINISHED:
if (m_dwMyIP == 0){
// we have to wait until we now our IP for a reverse lookup
m_PCStatus = PCS_OWNIPUNKNOWN;
break;
}
if (!m_bValdited){
m_PCStatus = PCS_VALDITING;
ValditeDescriptorFile();
}
else{
DEBUG_ONLY(theApp.QueueLogLine(false, GetResString(IDS_PEERCACHE_ENABLED)));
m_PCStatus = PCS_READY;
}
break;
}
break;
}
}
LRESULT CPeerCacheFinder::OnPeerCacheCheckResponse(WPARAM wParam, LPARAM lParam){
if (m_PCLUState == LUS_MYHOSTNAME){
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)_acDNSBuffer;
m_strMyHostname = pHost->h_name;
if (!m_strMyHostname.IsEmpty()){
DEBUG_ONLY(AddDebugLogLine(false, _T("PeerCache: Found my Hostname: %s, continue search"), m_strMyHostname));
SearchForPC();
return 0;
}
}
}
m_PCStatus = PCS_NOTFOUND;
DEBUG_ONLY(AddDebugLogLine(false, _T("DNS Reverse Lookup for own IP failed, aborting PC search")));
}
else{
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)_acDNSBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
m_dwPCIP = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
DEBUG_ONLY(AddDebugLogLine(false, _T("Found PeerCache IP: %s"), ipstr(m_dwPCIP) ));
m_PCLUState = LUS_FINISHED;
SearchForPC();
return 0;
}
}
}
// no luck, continue search
DEBUG_ONLY(AddDebugLogLine(false, _T("DNS Lookup for PC, state %i, failed - PC not found yet"), m_PCLUState));
SearchForPC();
}
return 0;
}
void CPeerCacheFinder::DoLookUp(CStringA strHostname){
if (WSAAsyncGetHostByName(theApp.emuledlg->m_hWnd, WM_PEERCHACHE_RESPONSE, strHostname, _acDNSBuffer, sizeof(_acDNSBuffer)) == 0){
DEBUG_ONLY(AddDebugLogLine(false, _T("DNS Lookup for PC, state %i, failed (DoLookUP) - PC not found yet"), m_PCLUState));
}
}
bool CPeerCacheFinder::IsCacheAvailable() const {
if(m_nDownloadAttempts > 20 && m_nFailedDownloads > 0){
if ( (float)(m_nDownloadAttempts/m_nFailedDownloads) < (float)2)
return false;
}
return m_PCStatus == PCS_READY && theApp.GetPublicIP() != 0 && m_nPCPort != 0;
}
CString ReverseDnsLookup(DWORD dwIP)
{
CString strHostName;
HMODULE hLib = LoadLibrary(_T("dnsapi.dll"));
if (hLib)
{
DNS_STATUS (WINAPI *pfnDnsQueryConfig)(DNS_CONFIG_TYPE Config, DWORD Flag, PWSTR pwsAdapterName, PVOID pReserved, PVOID pBuffer, PDWORD pBufferLength);
DNS_STATUS (WINAPI *pfnDnsQuery)(PCTSTR pszName, WORD wType, DWORD Options, PIP4_ARRAY aipServers, PDNS_RECORD* ppQueryResults, PVOID* pReserved);
VOID (WINAPI *pfnDnsRecordListFree)(PDNS_RECORD pRecordList, DNS_FREE_TYPE FreeType);
(FARPROC&)pfnDnsQueryConfig = GetProcAddress(hLib, "DnsQueryConfig");
(FARPROC&)pfnDnsQuery = GetProcAddress(hLib, _TWINAPI("DnsQuery_"));
(FARPROC&)pfnDnsRecordListFree = GetProcAddress(hLib, "DnsRecordListFree");
if (pfnDnsQueryConfig && pfnDnsQuery && pfnDnsRecordListFree)
{
// WinXP: We explicitly need to pass the DNS servers to be used to DnsQuery,
// otherwise that function will never query a DNS server for the *local* host name.
IP4_ARRAY* pDnsServers = NULL;
BYTE aucBuff[16384];
memset(aucBuff, 0, sizeof aucBuff);
DWORD dwSize = sizeof aucBuff;
DNS_STATUS nDnsState = (*pfnDnsQueryConfig)(DnsConfigDnsServerList, FALSE, NULL, NULL, aucBuff, &dwSize);
if (nDnsState == 0)
{
if (dwSize >= 4)
{
DWORD dwDnsServers = ((DWORD*)aucBuff)[0];
if (dwDnsServers >= 1 && dwSize == sizeof(DWORD) + dwDnsServers*sizeof(DWORD))
{
UINT uArrSize = sizeof(IP4_ARRAY) + sizeof(IP4_ADDRESS)*dwDnsServers;
pDnsServers = (IP4_ARRAY*)new BYTE[uArrSize];
memset(pDnsServers, 0, uArrSize);
pDnsServers->AddrCount = dwDnsServers;
for (UINT s = 0; s < dwDnsServers; s++)
pDnsServers->AddrArray[s] = ((DWORD*)aucBuff)[1+s];
}
}
}
else{
if (thePrefs.GetVerbose())
DEBUG_ONLY(theApp.QueueDebugLogLine(false, _T("ReverseDNS: Failed to get list of DNS servers - %s"), GetErrorMessage(nDnsState, 1)));
}
CString strDnsQuery;
strDnsQuery.Format(_T("%u.%u.%u.%u.IN-ADDR.ARPA"), (dwIP >> 24) & 0xFF, (dwIP >> 16) & 0xFF, (dwIP >> 8) & 0xFF, (dwIP >> 0) & 0xFF);
// This is a *blocking* call!
PDNS_RECORD pDnsRecords = NULL;
nDnsState = (*pfnDnsQuery)(strDnsQuery, DNS_TYPE_PTR, DNS_QUERY_BYPASS_CACHE, pDnsServers, &pDnsRecords, NULL);
if (nDnsState == 0)
{
if (AtlIsValidAddress(pDnsRecords, sizeof(*pDnsRecords) - sizeof(pDnsRecords->Data) + sizeof(pDnsRecords->Data.PTR), FALSE))
{
if (AtlIsValidAddress(pDnsRecords->Data.PTR.pNameHost, sizeof(TCHAR), FALSE))
strHostName = pDnsRecords->Data.PTR.pNameHost;
(*pfnDnsRecordListFree)(pDnsRecords, DnsFreeRecordListDeep);
}
}
else{
if (thePrefs.GetVerbose())
DEBUG_ONLY(theApp.QueueDebugLogLine(false, _T("ReverseDNS: Failed to resolve address \"%s\" - %s"), strDnsQuery, GetErrorMessage(nDnsState, 1)));
}
delete[] (BYTE*)pDnsServers;
}
FreeLibrary(hLib);
}
return strHostName;
}
void CPeerCacheFinder::DoReverseLookUp(uint32 dwIP){
CPCReverseDnsThread* pThread = (CPCReverseDnsThread*)AfxBeginThread(RUNTIME_CLASS(CPCReverseDnsThread), THREAD_PRIORITY_BELOW_NORMAL, 0, CREATE_SUSPENDED);
pThread->m_dwIP = dwIP;
pThread->m_hwndAsyncResult = theApp.emuledlg->m_hWnd;
pThread->ResumeThread();
}
void CPeerCacheFinder::ValditeDescriptorFile(){
CPCValditeThread* pValditeThread = (CPCValditeThread*) AfxBeginThread(RUNTIME_CLASS(CPCValditeThread), THREAD_PRIORITY_BELOW_NORMAL,0, CREATE_SUSPENDED);
pValditeThread->SetValues(this, m_dwPCIP, m_dwMyIP);
pValditeThread->ResumeThread();
}
void CPeerCacheFinder::AddBannedVersion(CClientVersionInfo cviVersion){
// Thread safe, due to logic this is not really needed at this time
// (because noone will access the list while the ValditeThread is running),
// but better to be on the safe side in case the code changes
CSingleLock lock(&m_SettingsMutex, TRUE);
liBannedVersions.Add(cviVersion);
}
void CPeerCacheFinder::AddAllowedVersion(CClientVersionInfo cviVersion){
CSingleLock lock(&m_SettingsMutex, TRUE);
liAllowedVersions.Add(cviVersion);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -