コード例 #1
0
ファイル: UploadQueue.cpp プロジェクト: machado2/emule
bool CUploadQueue::CheckForTimeOver(CUpDownClient* client){
	//If we have nobody in the queue, do NOT remove the current uploads..
	//This will save some bandwidth and some unneeded swapping from upload/queue/upload..
	if ( waitinglist.IsEmpty() || client->GetFriendSlot() )
		return false;
	
	if(client->HasCollectionUploadSlot()){
		CKnownFile* pDownloadingFile = theApp.sharedfiles->GetFileByID(client->requpfileid);
		if(pDownloadingFile == NULL)
			return true;
		if (CCollection::HasCollectionExtention(pDownloadingFile->GetFileName()) && pDownloadingFile->GetFileSize() < MAXPRIORITYCOLL_SIZE)
			return false;
		else{
			if (thePrefs.GetLogUlDlEvents())
				AddDebugLogLine(DLP_HIGH, false, _T("%s: Upload session ended - client with Collection Slot tried to request blocks from another file"), client->GetUserName());
			return true;
		}
	}
	
	if (!thePrefs.TransferFullChunks()){
	    if( client->GetUpStartTimeDelay() > SESSIONMAXTIME){ // Try to keep the clients from downloading for ever
		    if (thePrefs.GetLogUlDlEvents())
			    AddDebugLogLine(DLP_LOW, false, _T("%s: Upload session ended due to max time %s."), client->GetUserName(), CastSecondsToHM(SESSIONMAXTIME/1000));
		    return true;
	    }

		// Cache current client score
		const uint32 score = client->GetScore(true, true);

		// Check if another client has a bigger score
		if (score < GetMaxClientScore() && m_dwRemovedClientByScore < GetTickCount()) {
			if (thePrefs.GetLogUlDlEvents())
				AddDebugLogLine(DLP_VERYLOW, false, _T("%s: Upload session ended due to score."), client->GetUserName());
			//Set timer to prevent to many uploadslot getting kick do to score.
			//Upload slots are delayed by a min of 1 sec and the maxscore is reset every 5 sec.
			//So, I choose 6 secs to make sure the maxscore it updated before doing this again.
			m_dwRemovedClientByScore = GetTickCount()+SEC2MS(6);
			return true;
		}
	}
	else{
		// Allow the client to download a specified amount per session
		if( client->GetQueueSessionPayloadUp() > SESSIONMAXTRANS ){
			if (thePrefs.GetLogUlDlEvents())
				AddDebugLogLine(DLP_DEFAULT, false, _T("%s: Upload session ended due to max transferred amount. %s"), client->GetUserName(), CastItoXBytes(SESSIONMAXTRANS, false, false));
			return true;
		}
	}
	return false;
}
コード例 #2
0
void CSendGetUrlReqSocket::DataReceived(const BYTE* pucData, UINT uSize)
{
	if (thePrefs.GetVerbose())
	{
		CString		strUrlPath(GetUrlPath());
		strUrlPath.Replace(_T("%"), _T("%%"));

		CStringA	straRecv((char *)pucData, uSize);
		AddDebugLogLine(false, _T("取%s时,返回结果:"), strUrlPath);
		AddDebugLogLine(false, CString(straRecv));
	}

	CHttpClientReqSocket::DataReceived(pucData, uSize);
}
コード例 #3
0
ファイル: PPgLogs.cpp プロジェクト: rusingineer/EmulePlus
BOOL CPPgLogs::OnApply()
{
	if(m_bModified)
	{
		UpdateData(TRUE);

		m_pPrefs->SetLogToFile(writeLogToFile);
		if (m_pPrefs->GetVerbose() != (bool)debugLog)
		{
			m_pPrefs->SetVerbose(debugLog);
			g_App.m_pMDlg->m_wndServer.ToggleDebugWindow();
			if(debugLog)
				AddDebugLogLine(_T("Debug log is active"));
		}
		m_pPrefs->SetCMNotLog(cmNotLog);
		m_pPrefs->SetLogUploadToFile(uploadLog);
		m_pPrefs->SetLogDownloadToFile(downloadLog);
		m_pPrefs->SetAutoSourcesLogEnabled(autoSourcesLogEnabled);
		m_pPrefs->SetClientTransferLogEnabled(clientTransferLogEnabled);

		SetModified(FALSE);
	}

	return CPropertyPage::OnApply();
}
コード例 #4
0
ファイル: ClientList.cpp プロジェクト: rusingineer/emulemorph
void CClientList::CleanUpClientList(){
	// we remove clients which are not needed any more by time
	// this check is also done on CUpDownClient::Disconnected, however it will not catch all
	// cases (if a client changes the state without beeing connected
	//
	// Adding this check directly to every point where any state changes would be more effective,
	// is however not compatible with the current code, because there are points where a client has
	// no state for some code lines and the code is also not prepared that a client object gets
	// invalid while working with it (aka setting a new state)
	// so this way is just the easy and safe one to go (as long as emule is basically single threaded)
	const uint32 cur_tick = ::GetTickCount();
	if (m_dwLastClientCleanUp + CLIENTLIST_CLEANUP_TIME < cur_tick ){
		m_dwLastClientCleanUp = cur_tick;
		POSITION pos1, pos2;
		uint32 cDeleted = 0;
		for (pos1 = list.GetHeadPosition();( pos2 = pos1 ) != NULL;){
			list.GetNext(pos1);
			CUpDownClient* pCurClient =	list.GetAt(pos2);
			if ((pCurClient->GetUploadState() == US_NONE || pCurClient->GetUploadState() == US_BANNED && !pCurClient->IsBanned())
				&& pCurClient->GetDownloadState() == DS_NONE
				&& pCurClient->GetChatState() == MS_NONE
				&& pCurClient->GetKadState() == KS_NONE
				&& pCurClient->socket == NULL)
			{
				cDeleted++;
				delete pCurClient;
			}
		}
		DEBUG_ONLY(AddDebugLogLine(false,_T("Cleaned ClientList, removed %i not used known clients"), cDeleted));
	}
}
コード例 #5
0
ファイル: KnownFileList.cpp プロジェクト: dalinhuang/dmibox
bool CKnownFileList::LoadKnownFiles()
{
	CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR);
	fullpath.Append(KNOWN_MET_FILENAME);
	CSafeBufferedFile file;
	CFileException fexp;
	if (!file.Open(fullpath,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){
		if (fexp.m_cause != CFileException::fileNotFound){
			CString strError(_T("Failed to load ") KNOWN_MET_FILENAME _T(" file"));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(LOG_STATUSBAR, _T("%s"), strError);
		}
		return false;
	}
	setvbuf(file.m_pStream, NULL, _IOFBF, 16384);

	CKnownFile* pRecord = NULL;
	try {
		uint8 header = file.ReadUInt8();
		if (header != MET_HEADER && header != MET_HEADER_I64TAGS){
			file.Close();
			LogError(LOG_STATUSBAR, GetResString(IDS_ERR_SERVERMET_BAD));
			return false;
		}
		AddDebugLogLine(false, _T("Known.met file version is %u (%s support 64bit tags)"), header, (header == MET_HEADER) ? _T("doesn't") : _T("does")); 

		UINT RecordsNumber = file.ReadUInt32();
		for (UINT i = 0; i < RecordsNumber; i++) {
			pRecord = new CKnownFile();
			if (!pRecord->LoadFromFile(&file)){
				TRACE(_T("*** Failed to load entry %u (name=%s  hash=%s  size=%I64u  parthashs=%u expected parthashs=%u) from known.met\n"), i, 
					pRecord->GetFileName(), md4str(pRecord->GetFileHash()), pRecord->GetFileSize(), pRecord->GetHashCount(), pRecord->GetED2KPartHashCount());
				delete pRecord;
				pRecord = NULL;
				continue;
			}
			SafeAddKFile(pRecord);
			pRecord = NULL;
		}
		file.Close();
	}
	catch(CFileException* error){
		if (error->m_cause == CFileException::endOfFile)
			LogError(LOG_STATUSBAR, GetResString(IDS_ERR_SERVERMET_BAD));
		else{
			TCHAR buffer[MAX_CFEXP_ERRORMSG];
			error->GetErrorMessage(buffer, ARRSIZE(buffer));
			LogError(LOG_STATUSBAR, GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer);
		}
		error->Delete();
		delete pRecord;
		return false;
	}

	return true;
}
コード例 #6
0
ファイル: UploadQueue.cpp プロジェクト: dalinhuang/dmibox
CUploadQueue::CUploadQueue()
{
	VERIFY( (h_timer = SetTimer(0,0,100,UploadTimer)) != NULL );
	if (thePrefs.GetVerbose() && !h_timer)
		AddDebugLogLine(true,_T("Failed to create 'upload queue' timer - %s"),GetErrorMessage(GetLastError()));
	datarate = 0;
	counter=0;
	successfullupcount = 0;
	failedupcount = 0;
	totaluploadtime = 0;
	m_nLastStartUpload = 0;
	statsave=0;
	// -khaos--+++>
	iupdateconnstats=0;
	// <-----khaos-
	m_dwRemovedClientByScore = ::GetTickCount();
    m_iHighestNumberOfFullyActivatedSlotsSinceLastCall = 0;
    m_MaxActiveClients = 0;
    m_MaxActiveClientsShortTime = 0;

    m_lastCalculatedDataRateTick = 0;
    m_avarage_dr_sum = 0;
    friendDatarate = 0;

    m_dwLastResortedUploadSlots = 0;
}
コード例 #7
0
void CSendGetUrlReqSocket::OnConnect(int nErrorCode)
{
	if (0 != nErrorCode)
	{
		if (thePrefs.GetVerbose())
		{
			CString		strUrlPath(GetUrlPath());
			CString		strServer(GetServer());

			strUrlPath.Replace(_T("%"), _T("%%"));
			AddDebugLogLine(false, _T("将要取%s,但连接%s返回失败。"), strUrlPath, strServer);
		}

		return;
	}

	CStringA strHttpRequest;
	strHttpRequest.AppendFormat("%s %s HTTP/1.0\r\n", m_bIsPost ? "POST" : "GET", GetUrlPath());
	strHttpRequest.AppendFormat("Host: %s\r\n", GetServer());
	strHttpRequest.AppendFormat("Accept: */*\r\n");
	if(m_bIsPost)
	{
		strHttpRequest.AppendFormat("Accept-Encoding: none\r\n");
		strHttpRequest.AppendFormat("Content-Type: application/x-www-form-urlencoded\r\n");
		strHttpRequest.AppendFormat("Content-Length: %d\r\n", m_strPost.GetLength());
	}
	//strHttpRequest.AppendFormat("Connection: Keep-Alive\r\n");
	strHttpRequest.Append("\r\n");
	if(m_bIsPost)
	{
		strHttpRequest.Append(m_strPost);
	}

	if (thePrefs.GetVerbose())
	{
		CString		strRequest(strHttpRequest);
		strRequest.Replace(_T("%"), _T("%%"));

		AddDebugLogLine(false, _T("与服务器 %s 连接成功,准备发送:"), CString(GetServer()));
		AddDebugLogLine(false, strRequest);
	}


	CRawPacket* pHttpPacket = new CRawPacket(strHttpRequest);
	SendPacket(pHttpPacket);
	SetHttpState(HttpStateRecvExpected);
}
コード例 #8
0
void CDeadSourceList::CleanUp(){
	m_dwLastCleanUp = ::GetTickCount();
	if (thePrefs.GetLogFilteredIPs())
		AddDebugLogLine(DLP_VERYLOW, false, _T("Cleaning up DeadSourceList (%s), %i clients on List..."),  m_bGlobalList ? _T("Global") : _T("Local"), m_mapDeadSources.GetCount());
	POSITION pos = m_mapDeadSources.GetStartPosition();
	CDeadSource dsKey;
	uint32 dwExpTime;
	uint32 dwTick = ::GetTickCount();
	while (pos != NULL){
		m_mapDeadSources.GetNextAssoc( pos, dsKey, dwExpTime );
		if (dwExpTime < dwTick){
			m_mapDeadSources.RemoveKey(dsKey);
		}
	}
	if (thePrefs.GetLogFilteredIPs())
		AddDebugLogLine(DLP_VERYLOW, false, _T("...done, %i clients left on list"), m_mapDeadSources.GetCount());
}
コード例 #9
0
ファイル: SecRunAsUser.cpp プロジェクト: dalinhuang/dmibox
bool CSecRunAsUser::LoadAPI(){
	if (m_hADVAPI32_DLL == 0)
		m_hADVAPI32_DLL = LoadLibrary(_T("Advapi32.dll"));
	if (m_hACTIVEDS_DLL == 0)
		m_hACTIVEDS_DLL = LoadLibrary(_T("ActiveDS"));

    if (m_hADVAPI32_DLL == 0) {
        AddDebugLogLine(false,_T("Failed to load Advapi32.dll!"));
        return false;
    }
    if (m_hACTIVEDS_DLL == 0) {
        AddDebugLogLine(false,_T("Failed to load ActiveDS.dll!"));
        return false;
    }

	bool bSucceeded = true;
	bSucceeded = bSucceeded && (CreateProcessWithLogonW = (TCreateProcessWithLogonW) GetProcAddress(m_hADVAPI32_DLL,"CreateProcessWithLogonW")) != NULL;
	bSucceeded = bSucceeded && (GetNamedSecurityInfo = (TGetNamedSecurityInfo)GetProcAddress(m_hADVAPI32_DLL,_TWINAPI("GetNamedSecurityInfo"))) != NULL;
	bSucceeded = bSucceeded && (SetNamedSecurityInfo = (TSetNamedSecurityInfo)GetProcAddress(m_hADVAPI32_DLL,_TWINAPI("SetNamedSecurityInfo"))) != NULL;
	bSucceeded = bSucceeded && (AddAccessAllowedAceEx = (TAddAccessAllowedAceEx)GetProcAddress(m_hADVAPI32_DLL,"AddAccessAllowedAceEx")) != NULL;	
	// Probably these functions do not need to bel loaded dynamically, but just to be sure
	bSucceeded = bSucceeded && (LookupAccountName = (TLookupAccountName)GetProcAddress(m_hADVAPI32_DLL,_TWINAPI("LookupAccountName"))) != NULL;
	bSucceeded = bSucceeded && (GetAclInformation = (TGetAclInformation)GetProcAddress(m_hADVAPI32_DLL,"GetAclInformation")) != NULL;
	bSucceeded = bSucceeded && (InitializeAcl = (TInitializeAcl)GetProcAddress(m_hADVAPI32_DLL,"InitializeAcl")) != NULL;
	bSucceeded = bSucceeded && (GetAce = (TGetAce)GetProcAddress(m_hADVAPI32_DLL,"GetAce")) != NULL;
	bSucceeded = bSucceeded && (AddAce = (TAddAce)GetProcAddress(m_hADVAPI32_DLL,"AddAce")) != NULL;
	bSucceeded = bSucceeded && (EqualSid = (TEqualSid)GetProcAddress(m_hADVAPI32_DLL,"EqualSid")) != NULL;
	bSucceeded = bSucceeded && (GetLengthSid = (TGetLengthSid)GetProcAddress(m_hADVAPI32_DLL,"GetLengthSid")) != NULL;
	// for SecureShellExecute
	bSucceeded = bSucceeded && (OpenProcessToken = (TOpenProcessToken)GetProcAddress(m_hADVAPI32_DLL,"OpenProcessToken")) != NULL;
	bSucceeded = bSucceeded && (GetTokenInformation = (TGetTokenInformation)GetProcAddress(m_hADVAPI32_DLL,"GetTokenInformation")) != NULL;
	bSucceeded = bSucceeded && (CreateRestrictedToken = (TCreateRestrictedToken)GetProcAddress(m_hADVAPI32_DLL,"CreateRestrictedToken")) != NULL;
	bSucceeded = bSucceeded && (CreateProcessAsUser = (TCreateProcessAsUser)GetProcAddress(m_hADVAPI32_DLL,_TWINAPI("CreateProcessAsUser"))) != NULL;

	// activeDS.dll
	bSucceeded = bSucceeded && (ADsGetObject = (TADsGetObject)GetProcAddress(m_hACTIVEDS_DLL,"ADsGetObject")) != NULL;
	bSucceeded = bSucceeded && (ADsBuildEnumerator = (TADsBuildEnumerator)GetProcAddress(m_hACTIVEDS_DLL,"ADsBuildEnumerator")) != NULL;
	bSucceeded = bSucceeded && (ADsEnumerateNext = (TADsEnumerateNext)GetProcAddress(m_hACTIVEDS_DLL,"ADsEnumerateNext")) != NULL;
	
	if (!bSucceeded){
		AddDebugLogLine(false,_T("Failed to load all functions from Advapi32.dll!"));
		FreeAPI();
		return false;
	}
	return true;
}
コード例 #10
0
CQueueListCtrl::CQueueListCtrl()
    : CListCtrlItemWalk(this)
{
    // Barry - Refresh the queue every 10 secs
    VERIFY( (m_hTimer = ::SetTimer(NULL, NULL, 10000, QueueUpdateTimer)) != NULL );
    if (thePrefs.GetVerbose() && !m_hTimer)
        AddDebugLogLine(true,_T("Failed to create 'queue list control' timer - %s"),GetErrorMessage(GetLastError()));
}
コード例 #11
0
ファイル: IrcSocket.cpp プロジェクト: machado2/emule
void CIrcSocket::OnClose(int nErrorCode)
{
	if (nErrorCode){
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("IRC socket: Failed to close - %s"), GetErrorMessage(nErrorCode, 1));
		return;
	}
	m_pIrcMain->Disconnect();
}
コード例 #12
0
void CTimerOp_UrlClientRetry::TimerOp(WPARAM wParam, LPARAM /*lParam*/)
{
	CHttpClient	*pUrlClient = (CHttpClient*) wParam;

	if (NULL != pUrlClient && !IsBadWritePtr(pUrlClient, sizeof(CHttpClient)) )
	{
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Retry to connect <%s>"), pUrlClient->GetUserName());

		pUrlClient->TryToConnect(true);
	}
}
コード例 #13
0
bool CServerList::AddServer(const CServer* pServer, bool bAddTail)
{
	if (!IsGoodServerIP(pServer)){ // check for 0-IP, localhost and optionally for LAN addresses
		if (thePrefs.GetLogFilteredIPs())
			AddDebugLogLine(false, _T("IPFilter(AddServer): Filtered server \"%s\" (IP=%s) - Invalid IP or LAN address."), pServer->GetListName(), ipstr(pServer->GetIP()));
		return false;
	}

	if (thePrefs.GetFilterServerByIP()){
		// IP-Filter: We don't need to reject dynIP-servers here. After the DN was
		// resolved, the IP will get filtered and the server will get removed. This applies
		// for TCP-connections as well as for outgoing UDP-packets because for both protocols
		// we resolve the DN and filter the received IP.
		//if (pServer->HasDynIP())
		//	return false;
		if (theApp.ipfilter->IsFiltered(pServer->GetIP())){
			if (thePrefs.GetLogFilteredIPs())
				AddDebugLogLine(false, _T("IPFilter(AddServer): Filtered server \"%s\" (IP=%s) - IP filter (%s)"), pServer->GetListName(), ipstr(pServer->GetIP()), theApp.ipfilter->GetLastHit());
			return false;
		}
	}

	CServer* pFoundServer = GetServerByAddress(pServer->GetAddress(), pServer->GetPort());
	// Avoid duplicate (dynIP) servers: If the server which is to be added, is a dynIP-server
	// but we don't know yet it's DN, we need to search for an already available server with
	// that IP.
	if (pFoundServer == NULL && pServer->GetIP() != 0)
		pFoundServer = GetServerByIPTCP(pServer->GetIP(), pServer->GetPort());
	if (pFoundServer){
		pFoundServer->ResetFailedCount();
		theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pFoundServer);
		return false;
	}
	if (bAddTail)
		list.AddTail(const_cast<CServer*>(pServer));
	else
		list.AddHead(const_cast<CServer*>(pServer));
	return true;
}
コード例 #14
0
ファイル: Loggable.cpp プロジェクト: BackupTheBerlios/nextemf
void CLoggable::TagToDebugLogLine(LPCTSTR info, LPCTSTR tag, uint32 size, uint8 opcode) const
{
	CString buffer;
	buffer.Format(_T("%s: %02x, size=%u"), info, opcode, size);
	buffer += _T(", data=[");
	uint32 maxsize = 100;
	for(uint32 i = 0; i < size && i < maxsize; i++){		
		buffer.AppendFormat(_T("%02x"), (uint8)tag[i]);
		buffer += _T(" ");
	}
	buffer += ((size < maxsize) ? _T("]") : _T("..]"));
	AddDebugLogLine(false, buffer); 
}
コード例 #15
0
ファイル: Loggable.cpp プロジェクト: BackupTheBerlios/nextemf
// DbT:Logging
void CLoggable::PacketToDebugLogLine(LPCTSTR info, char * packet, uint32 size, uint8 opcode, EDebugLogPriority dlpPriority) const
{
	CString buffer; 
	buffer.Format(_T("%s: %02x, size=%u"), info, opcode, size);
	buffer += _T(", data=[");
	uint32 maxsize = 100;
	for(uint32 i = 0; i < size && i < maxsize; i++){		
		buffer.AppendFormat(_T("%02x"), (uint8)packet[i]);
		buffer += _T(" ");
	}
	buffer += ((size < maxsize) ? _T("]") : _T("..]"));
	AddDebugLogLine(dlpPriority, false, buffer); 
}
コード例 #16
0
void CSendGetUrlReqSocket::OnConnect(int nErrorCode)
{
	if (0 != nErrorCode)
	{
		if (thePrefs.GetVerbose())
		{
			CString		strUrlPath(GetUrlPath());
			CString		strServer(GetServer());

			strUrlPath.Replace(_T("%"), _T("%%"));
			AddDebugLogLine(false, _T("将要取%s,但连接%s返回失败。"), strUrlPath, strServer);
		}

		return;
	}

	CStringA strHttpRequest;
	strHttpRequest.AppendFormat("GET %s HTTP/1.0\r\n", GetUrlPath());
	strHttpRequest.AppendFormat("Host: %s\r\n", GetServer());
	strHttpRequest.AppendFormat("Accept: */*\r\n");
	//strHttpRequest.AppendFormat("Connection: Keep-Alive\r\n");
	strHttpRequest.AppendFormat("\r\n");

	if (thePrefs.GetVerbose())
	{
		CString		strRequest(strHttpRequest);
		strRequest.Replace(_T("%"), _T("%%"));

		AddDebugLogLine(false, _T("与服务器 %s 连接成功,准备发送:"), CString(GetServer()));
		AddDebugLogLine(false, strRequest);
	}


	CRawPacket* pHttpPacket = new CRawPacket(strHttpRequest);
	SendPacket(pHttpPacket);
	SetHttpState(HttpStateRecvExpected);
}
コード例 #17
0
bool CUrlSrcGetFromSvrSocket::ProcessHttpResponse_Start()
{
	int iMajorVer, iMinorVer;
	int iResponseCode;
	char szResponsePhrase[1024];
	sscanf(m_astrHttpHeaders[0], "HTTP/%d.%d %d %s", &iMajorVer, &iMinorVer, &iResponseCode, szResponsePhrase);

	if (thePrefs.GetVerbose())
		AddDebugLogLine(false, _T("Receive UrlSources from server (http response code = %d)"), iResponseCode);

	if (200 != iResponseCode)
		return false;

	return true;
}
コード例 #18
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;
}
コード例 #19
0
void CIrcSocket::OnReceive(int iErrorCode)
{
	if (iErrorCode)
	{
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("IRC socket: Failed to read - %s"), GetErrorMessage(iErrorCode, 1));
		return;
	}

	int iLength;
	char cBuffer[1024];
	try
	{
		do
		{
			iLength = Receive(cBuffer, sizeof(cBuffer)-1);
			if (iLength < 0)
			{
				if (thePrefs.GetVerbose())
					AddDebugLogLine(false, _T("IRC socket: Failed to read - %s"), GetErrorMessage(GetLastError(), 1));
				return;
			}
			if (iLength > 0)
			{
				cBuffer[iLength] = '\0';
				theStats.AddDownDataOverheadOther(iLength);
				m_pIrcMain->PreParseMessage(cBuffer);
			}
		}
		while( iLength > 1022 );
	}
	catch(...)
	{
		AddDebugLogLine(false, _T("IRC socket: Exception in OnReceive."), GetErrorMessage(iErrorCode, 1));
	}
}
コード例 #20
0
ファイル: UploadQueue.cpp プロジェクト: dalinhuang/dmibox
bool CUploadQueue::RemoveFromUploadQueue(CUpDownClient* client, LPCTSTR pszReason, bool updatewindow, bool earlyabort){
    bool result = false;
    uint32 slotCounter = 1;
	for (POSITION pos = uploadinglist.GetHeadPosition();pos != 0;){
        POSITION curPos = pos;
        CUpDownClient* curClient = uploadinglist.GetNext(pos);
		if (client == curClient){
			if (updatewindow)
				theApp.emuledlg->transferwnd->uploadlistctrl.RemoveClient(client);

			if (thePrefs.GetLogUlDlEvents())
                AddDebugLogLine(DLP_DEFAULT, true,_T("Removing client from upload list: %s Client: %s Transferred: %s SessionUp: %s QueueSessionPayload: %s In buffer: %s Req blocks: %i File: %s"), pszReason==NULL ? _T("") : pszReason, client->DbgGetClientInfo(), CastSecondsToHM( client->GetUpStartTimeDelay()/1000), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false), CastItoXBytes(client->GetPayloadInBuffer()), client->GetNumberOfRequestedBlocksInQueue(), (theApp.sharedfiles->GetFileByID(client->GetUploadFileID())?theApp.sharedfiles->GetFileByID(client->GetUploadFileID())->GetFileName():_T("")));
            client->m_bAddNextConnect = false;
			uploadinglist.RemoveAt(curPos);

            bool removed = theApp.uploadBandwidthThrottler->RemoveFromStandardList(client->socket);
            bool pcRemoved = theApp.uploadBandwidthThrottler->RemoveFromStandardList((CClientReqSocket*)client->m_pPCUpSocket);
			(void)removed;
			(void)pcRemoved;
            //if(thePrefs.GetLogUlDlEvents() && !(removed || pcRemoved)) {
            //    AddDebugLogLine(false, _T("UploadQueue: Didn't find socket to delete. Adress: 0x%x"), client->socket);
            //}

			if(client->GetSessionUp() > 0) {
				++successfullupcount;
				totaluploadtime += client->GetUpStartTimeDelay()/1000;
            } else if(earlyabort == false)
				++failedupcount;

            CKnownFile* requestedFile = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
            if(requestedFile != NULL) {
                requestedFile->UpdatePartsInfo();
            }
			theApp.clientlist->AddTrackClient(client); // Keep track of this client
			client->SetUploadState(US_NONE);
			client->ClearUploadBlockRequests();
			client->SetCollectionUploadSlot(false);

            m_iHighestNumberOfFullyActivatedSlotsSinceLastCall = 0;

			result = true;
        } else {
            curClient->SetSlotNumber(slotCounter);
            slotCounter++;
        }
	}
	return result;
}
コード例 #21
0
void CServerListCtrl::RemoveAllFilteredServers()
{
	if (!thePrefs.GetFilterServerByIP())
		return;
	ShowWindow(SW_HIDE);
	for (POSITION pos = theApp.serverlist->list.GetHeadPosition(); pos != NULL; theApp.serverlist->list.GetNext(pos))
	{
		const CServer* cur_server = theApp.serverlist->list.GetAt(pos);
		if (theApp.ipfilter->IsFiltered(cur_server->GetIP()))
		{
			if (thePrefs.GetLogFilteredIPs())
				AddDebugLogLine(false, _T("Filtered server \"%s\" (IP=%s) - IP filter (%s)"), cur_server->GetListName(), ipstr(cur_server->GetIP()), theApp.ipfilter->GetLastHit());
			RemoveServer(cur_server);
			pos = theApp.serverlist->list.GetHeadPosition();
		}
	}
	ShowWindow(SW_SHOW);
}
コード例 #22
0
ファイル: IPFilter.cpp プロジェクト: brolee/EMule-GIFC
bool CIPFilter::IsFiltered(uint32 ip, UINT level) /*const*/
{
	if (m_iplist.GetCount() == 0 || ip == 0)
		return false;
	
	ip = htonl(ip);

	// to speed things up we use a binary search
	//	*)	the IP filter list must be sorted by IP range start addresses
	//	*)	the IP filter list is not allowed to contain overlapping IP ranges (see also the IP range merging code when
	//		loading the list)
	//	*)	the filter 'level' is ignored during the binary search and is evaluated only for the found element
	//
	// TODO: this can still be improved even more:
	//	*)	use a pre assembled list of IP ranges which contains only the IP ranges for the currently used filter level
	//	*)	use a dumb plain array for storing the IP range structures. this will give more cach hits when processing
	//		the list. but(!) this would require to also use a dumb SIPFilter structure (don't use data items with ctors).
	//		otherwise the creation of the array would be rather slow.

	// ==> IP Filter White List [Stulle] - Stulle
	if(m_iplist_White.GetCount() > 0)
	{
		SIPFilter** ppFound_White = (SIPFilter**)bsearch(&ip, m_iplist_White.GetData(), m_iplist_White.GetCount(), sizeof(m_iplist_White[0]), CmpSIPFilterByAddr);
		if (ppFound_White && (*ppFound_White)->level < level)
		{
			(*ppFound_White)->hits++;
			if(thePrefs.GetVerbose() && thePrefs.GetLogFilteredIPs())
				AddDebugLogLine(false, _T("Prevented filtering IP %s in range: %s - %s Description: %s Hits: %u"),ipstr_rev(ip),ipstr_rev((*ppFound_White)->start),ipstr_rev((*ppFound_White)->end),CString((*ppFound_White)->desc),(*ppFound_White)->hits);
			return false;
		}
	}
	// <== IP Filter White List [Stulle] - Stulle

	SIPFilter** ppFound = (SIPFilter**)bsearch(&ip, m_iplist.GetData(), m_iplist.GetCount(), sizeof(m_iplist[0]), CmpSIPFilterByAddr);
	if (ppFound && (*ppFound)->level < level)
	{
		(*ppFound)->hits++;
		m_pLastHit = *ppFound;
		return true;
	}

	return false;
}
コード例 #23
0
void CFriendList::SaveList(){
	if (thePrefs.GetLogFileSaving())
		AddDebugLogLine(false, _T("Saving friends list file \"%s\""), EMFRIENDS_MET_FILENAME);
	m_nLastSaved = ::GetTickCount();

	CString strFileName = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + EMFRIENDS_MET_FILENAME;
	CSafeBufferedFile file;
	CFileException fexp;
	if (!file.Open(strFileName, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary | CFile::shareDenyWrite, &fexp)){
		CString strError(_T("Failed to save ") EMFRIENDS_MET_FILENAME _T(" file"));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		return;
	}
	setvbuf(file.m_pStream, NULL, _IOFBF, 16384);
	
	try{
		file.WriteUInt8(MET_HEADER);
		file.WriteUInt32(m_listFriends.GetCount());
		for (POSITION pos = m_listFriends.GetHeadPosition();pos != 0;)
			m_listFriends.GetNext(pos)->WriteToFile(&file);
		if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning())){
			file.Flush(); // flush file stream buffers to disk buffers
			if (_commit(_fileno(file.m_pStream)) != 0) // commit disk buffers to disk
				AfxThrowFileException(CFileException::hardIO, GetLastError(), file.GetFileName());
		}
		file.Close();
	}
	catch(CFileException* error){
		CString strError(_T("Failed to save ") EMFRIENDS_MET_FILENAME _T(" file"));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (error->GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		error->Delete();
	}
}
コード例 #24
0
ファイル: sockets.cpp プロジェクト: HackLinux/eMule-Mirror
void CServerConnect::KeepConnectionAlive()
{
	DWORD dwServerKeepAliveTimeout = thePrefs.GetServerKeepAliveTimeout();
	if (dwServerKeepAliveTimeout && connected && connectedsocket && connectedsocket->connectionstate == CS_CONNECTED &&
		GetTickCount() - connectedsocket->GetLastTransmission() >= dwServerKeepAliveTimeout)
	{
		// "Ping" the server if the TCP connection was not used for the specified interval with 
		// an empty publish files packet -> recommended by lugdunummaster himself!
		CSafeMemFile files(4);
		files.WriteUInt32(0); // nr. of files
		Packet* packet = new Packet(&files);
		packet->opcode = OP_OFFERFILES;
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Refreshing server connection"));
		if (thePrefs.GetDebugServerTCPLevel() > 0)
			Debug(_T(">>> Sending OP__OfferFiles(KeepAlive) to server\n"));
		theStats.AddUpDataOverheadServer(packet->size);
		connectedsocket->SendPacket(packet,true);
	}
}
コード例 #25
0
ファイル: PeerCacheClient.cpp プロジェクト: axxapp/winxgui
void CUpDownClient::OnPeerCacheDownSocketClosed(int nErrorCode)
{
	if (nErrorCode)
		return;
	
	// restart PC download if cache just closed the connection without obvious reason
	if (GetDownloadState() == DS_DOWNLOADING 
		&& m_ePeerCacheDownState == PCDS_DOWNLOADING
		&& !m_PendingBlocks_list.IsEmpty())
	{
		if (thePrefs.GetVerbose())
			AddDebugLogLine(DLP_HIGH, false, _T("PeerCache: Socket closed unexpedtedly, trying to reestablish connection"));
		theApp.m_pPeerCache->DownloadAttemptFailed();
		TRACE("+++ Restarting PeerCache download - socket closed\n");
		ASSERT( m_pPCDownSocket == NULL );
		SetPeerCacheDownState(PCDS_NONE);
		ClearDownloadBlockRequests();
		SendPeerCacheFileRequest();
	}
}
コード例 #26
0
void CHttpClientReqSocket::OnConnect(int nErrorCode)
{
	if (NULL != GetClient())
	{
		if (WSAENETUNREACH == nErrorCode || WSAETIMEDOUT == nErrorCode)
		{
			if (thePrefs.GetVerbose())
			{
				AddDebugLogLine(false, _T("Connect <%s> failed. ErrorCode = %d. Retry later."),
								GetClient()->GetUserName(), nErrorCode);
			}
			
			return;
		}
	}

	CClientReqSocket::OnConnect(nErrorCode);

	if (GetClient())
		GetClient()->OnSocketConnected(nErrorCode);
}
コード例 #27
0
ファイル: ServerSocket.cpp プロジェクト: brolee/EMule-GIFC
BOOL CServerSocket::OnHostNameResolved(const SOCKADDR_IN *pSockAddr)
{
	// If we are connecting to a dynIP-server by DN, we will get this callback after the
	// DNS query finished.
	//
	if (cur_server->HasDynIP())
	{
		// Update the IP of this dynIP-server
		//
		cur_server->SetIP(pSockAddr->sin_addr.S_un.S_addr);
		CServer* pServer = theApp.serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort());
		if (pServer) {
			pServer->SetIP(pSockAddr->sin_addr.S_un.S_addr);
			// If we already have entries in the server list (dynIP-servers without a DN)
			// with the same IP as this dynIP-server, remove the duplicates.
			theApp.serverlist->RemoveDuplicatesByIP(pServer);
		}
		DEBUG_ONLY( DebugLog(_T("Resolved DN for server '%s': IP=%s"), cur_server->GetAddress(), ipstr(cur_server->GetIP())) );

		// As this is a dynIP-server, we need to check the IP against the IP-filter
		// and eventually disconnect and delete that server.
		//
		if (thePrefs.GetFilterServerByIP() && theApp.ipfilter->IsFiltered(cur_server->GetIP())) {
			if (thePrefs.GetLogFilteredIPs())
				AddDebugLogLine(false, _T("IPFilter(TCP/DNSResolve): Filtered server \"%s\" (IP=%s) - IP filter (%s)"), pServer ? pServer->GetAddress() : cur_server->GetAddress(), ipstr(cur_server->GetIP()), theApp.ipfilter->GetLastHit());
			if (pServer)
				theApp.emuledlg->serverwnd->serverlistctrl.RemoveServer(pServer);
			m_bIsDeleting = true;
			SetConnectionState(CS_ERROR);
			serverconnect->DestroySocket(this);
			return FALSE;	// Do *NOT* connect to this server
		}
		//zz_fly :: support dynamic ip servers :: DolphinX :: Start
		if (pServer)
			pServer->ResetIP2Country(); //EastShare - added by AndCycle, IP to Country
		//zz_fly :: End
	}
	return TRUE; // Connect to this server
}
コード例 #28
0
void CDeadSourceList::AddDeadSource(const CUpDownClient* pToAdd){
	if (thePrefs.GetLogFilteredIPs())
		AddDebugLogLine(DLP_VERYLOW, false, _T("Added source to bad source list (%s) - file %s : %s")
		, m_bGlobalList? _T("Global"):_T("Local"), (pToAdd->GetRequestFile() != NULL)? pToAdd->GetRequestFile()->GetFileName() : _T("???"), pToAdd->DbgGetClientInfo() );

	if(!pToAdd->HasLowID())
		m_mapDeadSources.SetAt(CDeadSource(pToAdd->GetUserIDHybrid(), pToAdd->GetUserPort(), pToAdd->GetServerIP(), pToAdd->GetKadPort()), BLOCKTIME );
	else{
		bool bDbgCheck = false;
		if(pToAdd->GetServerIP() != 0){
			bDbgCheck = true;
			m_mapDeadSources.SetAt(CDeadSource(pToAdd->GetUserIDHybrid(), pToAdd->GetUserPort(), pToAdd->GetServerIP(), 0), BLOCKTIMEFW);
		}
		if (pToAdd->HasValidBuddyID()){
			bDbgCheck = true;
			m_mapDeadSources.SetAt(CDeadSource(pToAdd->GetUserHash()), BLOCKTIMEFW);
		}
		ASSERT( bDbgCheck );
	}
	if (::GetTickCount() - m_dwLastCleanUp  > CLEANUPTIME)
		CleanUp();
}
コード例 #29
0
ファイル: IPFilter.cpp プロジェクト: brolee/EMule-GIFC
//Xman dynamic IP-Filters
void CIPFilter::Process()
{
	if(m_iplist.GetCount()==0)
		return;
	if(theApp.ipdlgisopen)
		return; //don't process if user is working on ipfilter
	uint32 lasttick=::GetTickCount();
	static uint32 m_lastcleanup;
	if(lasttick - m_lastcleanup > (1000 * 60 * 60)) //every hour
	{
		m_lastcleanup=lasttick;
		int countall=0;
		int countdel=0;
		for (int i=0;i<m_iplist.GetCount();)
		{
			SIPFilter* search = m_iplist[i];
			if(search->timestamp>0 && ((lasttick - search->timestamp) >=  (1000 * 60 * 60 * 12))) //12 hours
			{
				countdel++;
				//Xman Code Fix: deleting the description-String can throw an exception
				try 
				{
					delete m_iplist[i];
				}
				catch(...)
				{
					//nothing
				}
				m_iplist.RemoveAt(i);
			}
			else
			{
				countall++;
				i++;
			}
		}
		AddDebugLogLine(false,_T("%u temporary IPFilters deleted, %u left"),countdel, countall)	;
	}
}
コード例 #30
0
ファイル: PeerCacheClient.cpp プロジェクト: axxapp/winxgui
bool CUpDownClient::OnPeerCacheDownSocketTimeout()
{
	// restart PC download if cache just stalls
	if (GetDownloadState() == DS_DOWNLOADING 
		&& m_ePeerCacheDownState == PCDS_DOWNLOADING
		&& !m_PendingBlocks_list.IsEmpty())
	{
		if (thePrefs.GetVerbose())
			AddDebugLogLine(DLP_HIGH, false, _T("PeerCache Error: Socket TimeOut, trying to reestablish connection"));
		theApp.m_pPeerCache->DownloadAttemptFailed();
		TRACE("+++ Restarting PeerCache download - socket timeout\n");
		if (m_pPCDownSocket)
		{
			m_pPCDownSocket->Safe_Delete();
			ASSERT( m_pPCDownSocket == NULL );
		}
		SetPeerCacheDownState(PCDS_NONE);
		ClearDownloadBlockRequests();
		return SendPeerCacheFileRequest();
	}
	return false;
}