// Full debug output of all data
void CCorruptionBlackBox::DumpAll()
{
#ifdef __DEBUG__
	AddDebugLogLineN(logPartFile, wxT("CBB Dump Records"));
	std::map<uint16, CRecordList>::iterator it = m_Records.begin();
	for (; it != m_Records.end(); ++it) {
		uint16 block = it->first;
		CRecordList & list = it->second;
		for (CRecordList::iterator it2 = list.begin(); it2 != list.end(); ++it2) {
			AddDebugLogLineN(logPartFile, CFormat(wxT("CBBD %6d %.16s %10d - %10d"))
				% block % Uint32toStringIP(it2->m_dwIP) % it2->m_nStartPos % it2->m_nEndPos);
		}
	}
	if (!m_goodClients.empty()) {
		AddDebugLogLineN(logPartFile, wxT("CBB Dump good Clients"));
		CCBBClientMap::iterator it3 = m_goodClients.begin();
		for (; it3 != m_goodClients.end(); ++it3) {
			AddDebugLogLineN(logPartFile, CFormat(wxT("CBBD %.16s good %10d"))
				% Uint32toStringIP(it3->first) % it3->second.m_downloaded);
		}
	}
	if (!m_badClients.empty()) {
		AddDebugLogLineN(logPartFile, wxT("CBB Dump bad Clients"));
		CCBBClientMap::iterator it3 = m_badClients.begin();
		for (; it3 != m_badClients.end(); ++it3) {
			AddDebugLogLineN(logPartFile, CFormat(wxT("CBBD %.16s bad %10d"))
				% Uint32toStringIP(it3->first) % it3->second.m_downloaded);
		}
	}
#endif
}
void CMUSHclientApp::ShowGlobalOptions (CMUSHclientDoc * pDoc)
  {

  int i;

  for (i = 0; GlobalOptionsTable [i].pName; i++)
    {
    const char * p = (const char *) this +  GlobalOptionsTable [i].iOffset;
    const int Value = * (const long *) p;
    pDoc->Note (CFormat ("%35s = %ld",
                   (LPCTSTR) GlobalOptionsTable [i].pName, 
                   Value));

    };

  for (i = 0; AlphaGlobalOptionsTable [i].pName; i++)
    {
    const char * p = (const char *) this +  AlphaGlobalOptionsTable [i].iOffset;
    CString strValue = * (CString *) p;
    
    pDoc->Note (CFormat ("%35s = %s",
                   (LPCTSTR) AlphaGlobalOptionsTable [i].pName, 
                   (LPCTSTR) strValue));

    };



  } // end of CMUSHclientApp::ShowGlobalOptions 
Beispiel #3
0
bool CDownloadQueue::IsFileExisting( const CMD4Hash& fileid ) const 
{
	if (CKnownFile* file = theApp->sharedfiles->GetFileByID(fileid)) {
		if (file->IsPartFile()) {
			AddLogLineC(CFormat( _("You are already trying to download the file '%s'") ) % file->GetFileName());
		} else {
			// Check if the file exists, since otherwise the user is forced to 
			// manually reload the shares to download a file again.
			CPath fullpath = file->GetFilePath().JoinPaths(file->GetFileName());
			if (!fullpath.FileExists()) {
				// The file is no longer available, unshare it
				theApp->sharedfiles->RemoveFile(file);
				
				return false;
			}
			
			AddLogLineC(CFormat( _("You already have the file '%s'") ) % file->GetFileName());
		}
		
		return true;
	} else if ((file = GetFileByID(fileid))) {
		AddLogLineC(CFormat( _("You are already trying to download the file %s") ) % file->GetFileName());
		return true;
	}
	
	return false;
}
Beispiel #4
0
wxString CStatTreeItemRatio::GetString() const
{
    wxString ret;
    double v1 = m_counter1->GetValue();
    double v2 = m_counter2->GetValue();
    if (v1 > 0 && v2 > 0) {
        if (v2 < v1) {
            ret = CFormat(wxT("%.2f : 1")) % (v1 / v2);
        } else {
            ret = CFormat(wxT("1 : %.2f")) % (v2 / v1);
        }

        if (m_totalfunc1 && m_totalfunc2) {
            double t1 = m_totalfunc1() + v1;
            double t2 = m_totalfunc2() + v2;
            if (t2 < t1) {
                ret += CFormat(wxT(" (%.2f : 1)")) % (t1 / t2);
            } else {
                ret += CFormat(wxT(" (1 : %.2f)")) % (t2 / t1);
            }
        }
    } else {
        ret = _("Not available");
    }
    return ret;
}
Beispiel #5
0
void CServerList::AutoUpdate() 
{
	
	uint8 url_count = theApp->glob_prefs->adresses_list.GetCount();
	
	if (!url_count) {
		AddLogLineC(_("No server list address entry in 'addresses.dat' found. Please paste a valid server list address into this file in order to auto-update your server list"));
		return;
	}
	// Do current URL. Callback function will take care of the others.
	while ( current_url_index < url_count ) {
		wxString URI = theApp->glob_prefs->adresses_list[current_url_index];
		// We use wxURL to validate the URI
		if ( wxURL( URI ).GetError() == wxURL_NOERR ) {
			// Ok, got a valid URI
			m_URLUpdate = URI;
			wxString strTempFilename =
				theApp->ConfigDir + wxT("server_auto.met");
			AddLogLineC(CFormat(
				_("Start downloading server list from %s")) % URI);
			CHTTPDownloadThread *downloader = new CHTTPDownloadThread(
				URI, strTempFilename, theApp->ConfigDir + wxT("server.met"), HTTP_ServerMetAuto, false, false);
			downloader->Create();
			downloader->Run();
		
			return;
		} else {
			AddLogLineC(CFormat(
				_("WARNING: invalid URL specified for auto-updating of servers: %s") ) % URI);
		}
		current_url_index++;
	}
	AddLogLineC(_("No valid server.met auto-download url on addresses.dat"));
}
Beispiel #6
0
void CECTag::DebugPrint(int level, bool print_empty) const
{
	if (m_dataLen || print_empty) {
		wxString space;
		for (int i = level; i--;) space += wxT("  ");
		wxString s1 = CFormat(wxT("%s%s %d = ")) % space % GetDebugNameECTagNames(m_tagName) % m_dataLen;
		wxString s2;
		switch (m_tagName) {
			case EC_TAG_DETAIL_LEVEL:
				s2 = GetDebugNameEC_DETAIL_LEVEL(GetInt()); break;
			case EC_TAG_SEARCH_TYPE:
				s2 = GetDebugNameEC_SEARCH_TYPE(GetInt()); break;
			case EC_TAG_STAT_VALUE_TYPE:
				s2 = GetDebugNameEC_STATTREE_NODE_VALUE_TYPE(GetInt()); break;
			default:
				switch (m_dataType) {
					case EC_TAGTYPE_UINT8:
					case EC_TAGTYPE_UINT16:
					case EC_TAGTYPE_UINT32:
					case EC_TAGTYPE_UINT64:
						s2 = CFormat(wxT("%d")) % GetInt(); break;
					case EC_TAGTYPE_STRING:
						s2 = GetStringData(); break;
					case EC_TAGTYPE_DOUBLE:
						s2 = CFormat(wxT("%.1f")) % GetDoubleData(); break;
					case EC_TAGTYPE_HASH16:
						s2 = GetMD4Data().Encode(); break;
					case EC_TAGTYPE_UINT128:
						// Using any non-inline function from UInt128.h would break linkage
						// of remote apps otherwise not using CUInt128. So just fall through
						// and display the value as a byte-stream. Since the value is sent
						// big-endian on the network, the visual result is correct, except
						// for the intervening spaces...
						//s2 = GetInt128Data().ToHexString(); break;
					case EC_TAGTYPE_CUSTOM:
						if (m_dataLen == 0) {
							s2 = wxT("empty");
						} else {
							// Make a hex dump (limited to maxOutput)
							const uint32 maxOutput = 50;
							for (uint32 i = 0; i < m_dataLen; i++) {
								if (i == maxOutput) {
									s2 += wxT("...");
									break;
								}
								s2 += CFormat(wxT("%02X ")) % (unsigned char) m_tagData[i];
							}
						}
						break;
					default:
						s2 = GetDebugNameECTagTypes(m_dataType);
				}
		}
		DoECLogLine(s1 + s2);
	}
	for (TagList::const_iterator it = m_tagList.begin(); it != m_tagList.end(); ++it) {
		it->DebugPrint(level + 1, true);
	}
}
void CMUSHclientApp::SaveGlobalsToDatabase (void)
  {

  // close and re-open database, in case they somehow lost connection to it

  if (db)
    sqlite3_close(db);

  int db_rc = sqlite3_open(m_PreferencesDatabaseName.c_str (), &db);

  if( db_rc )
    {
    ::AfxMessageBox ((LPCTSTR) CFormat ("Can't open global preferences database at: %s"
         "\r\n(Error was: \"%s\")"
         "\r\nCheck you have write-access to that file.", 
        m_PreferencesDatabaseName.c_str (), 
        sqlite3_errmsg(db)));
    sqlite3_close(db);
    db = NULL;
		return;
    }

  db_rc = db_execute ("BEGIN TRANSACTION", true);

  int i;

  for (i = 0; GlobalOptionsTable [i].pName; i++)
    {
    const char * p = (const char *) this +  GlobalOptionsTable [i].iOffset;
    const int Value = * (const long *) p;


    db_rc = db_execute ((LPCTSTR) CFormat ("UPDATE prefs SET value = %i WHERE name = '%s'",
                        Value, GlobalOptionsTable [i].pName), true);

    if (db_rc != SQLITE_OK)
      break;

    };

  if (db_rc == SQLITE_OK)
    for (i = 0; AlphaGlobalOptionsTable [i].pName; i++)
      {
      const char * p = (const char *) this +  AlphaGlobalOptionsTable [i].iOffset;
      CString strValue = * (CString *) p;
    
      strValue.Replace ("'", "''");  // fix up quotes

      db_rc = db_execute ((LPCTSTR) CFormat ("UPDATE prefs SET value = '%s' WHERE name = '%s'",
                          (LPCTSTR) strValue, AlphaGlobalOptionsTable [i].pName), true);

      if (db_rc != SQLITE_OK)
        break;

      };

  db_execute ("COMMIT", true);

  } // end of CMUSHclientApp::SaveGlobalsToDatabase
void CaMuleExternalConnector::ConnectAndRun(const wxString &ProgName, const wxString& ProgVersion)
{
	if (m_NeedsConfigSave) {
		SaveConfigFile();
		return;
	}

	#ifdef SVNDATE
		Show(CFormat(_("This is %s %s %s\n")) % wxString::FromAscii(m_appname) % wxT(VERSION) % wxT(SVNDATE));
	#else
		Show(CFormat(_("This is %s %s\n")) % wxString::FromAscii(m_appname) % wxT(VERSION));
	#endif

	// HostName, Port and Password
	if ( m_password.IsEmpty() ) {
		m_password = GetPassword(true);
		// MD5 hash for an empty string, according to rfc1321.
		if (m_password.Encode() == wxT("D41D8CD98F00B204E9800998ECF8427E")) {
			m_password.Clear();
		}
	}

	if (!m_password.IsEmpty()) {

		// Create the socket
		Show(_("\nCreating client...\n"));
		m_ECClient = new CRemoteConnect(NULL);
		m_ECClient->SetCapabilities(m_ZLIB, true, false);	// ZLIB, UTF8 numbers, notification

		// ConnectToCore is blocking since m_ECClient was initialized with NULL
		if (!m_ECClient->ConnectToCore(m_host, m_port, wxT("foobar"), m_password.Encode(), ProgName, ProgVersion)) {
			// no connection => close gracefully
			if (!m_ECClient->GetServerReply().IsEmpty()) {
					Show(CFormat(wxT("%s\n")) % m_ECClient->GetServerReply());
			}
			Show(CFormat(_("Connection Failed. Unable to connect to %s:%d\n")) % m_host % m_port);
		} else {
			// Authenticate ourselves
			// ConnectToCore() already authenticated for us.
			//m_ECClient->ConnectionEstablished();
			Show(m_ECClient->GetServerReply()+wxT("\n"));
			if (m_ECClient->IsSocketConnected()) {
				if (m_interactive) {
					ShowGreet();
				}
				Pre_Shell();
				TextShell(ProgName);
				Post_Shell();
				if (m_interactive) {
					Show(CFormat(_("\nOk, exiting %s...\n")) % ProgName);
				}
			}
		}
		m_ECClient->DestroySocket();
	} else {
		Show(_("Cannot connect with an empty password.\nYou must specify a password either in config file\nor on command-line, or enter one when asked.\n\nExiting...\n"));
	}
}
Beispiel #9
0
wxString CStatTreeItemAverageSpeed::GetDisplayString() const
{
    uint64 time = m_timer->GetTimerSeconds();
    if (time) {
        return CFormat(wxGetTranslation(m_label)) % CastItoSpeed((*m_counter)/time);
    } else {
        return CFormat(wxGetTranslation(m_label)) % CastItoSpeed(0);
    }
}
Beispiel #10
0
bool CAICHHashSet::CreatePartRecoveryData(uint64 nPartStartPos, CFileDataIO* fileDataOut, bool bDbgDontLoad)
{
	wxASSERT( m_pOwner );
	if (m_pOwner->IsPartFile() || m_eStatus != AICH_HASHSETCOMPLETE) {
		wxFAIL;
		return false;
	}
	if (m_pHashTree.m_nDataSize <= EMBLOCKSIZE) {
		wxFAIL;
		return false;
	}
	if (!bDbgDontLoad) {
		if (!LoadHashSet()) {
			AddDebugLogLineM(false, logSHAHashSet,
				CFormat(wxT("Created RecoveryData error: failed to load hashset. File: %s")) % m_pOwner->GetFileName());
			SetStatus(AICH_ERROR);
			return false;
		}
	}
	bool bResult;
	uint8 nLevel = 0;
	uint32 nPartSize = min<uint64>(PARTSIZE, m_pOwner->GetFileSize()-nPartStartPos);
	m_pHashTree.FindHash(nPartStartPos, nPartSize,&nLevel);
	uint16 nHashsToWrite = (nLevel-1) + nPartSize/EMBLOCKSIZE + ((nPartSize % EMBLOCKSIZE != 0 )? 1:0);
	const bool bUse32BitIdentifier = m_pOwner->IsLargeFile();

	if (bUse32BitIdentifier) {
		fileDataOut->WriteUInt16(0); // no 16bit hashs to write
	}

	fileDataOut->WriteUInt16(nHashsToWrite);
	uint64 nCheckFilePos = fileDataOut->GetPosition();
	if (m_pHashTree.CreatePartRecoveryData(nPartStartPos, nPartSize, fileDataOut, 0, bUse32BitIdentifier)) {
		if (nHashsToWrite*(HASHSIZE+(bUse32BitIdentifier? 4u:2u)) != fileDataOut->GetPosition() - nCheckFilePos) {
			wxFAIL;
			AddDebugLogLineM( false, logSHAHashSet,
				CFormat(wxT("Created RecoveryData has wrong length. File: %s")) % m_pOwner->GetFileName() );
			bResult = false;
			SetStatus(AICH_ERROR);
		} else {
			bResult = true;
		}
	} else {
		AddDebugLogLineM(false, logSHAHashSet,
			CFormat(wxT("Failed to create RecoveryData for '%s'")) % m_pOwner->GetFileName());
		bResult = false;
		SetStatus(AICH_ERROR);
	}
	if (!bUse32BitIdentifier) {
		fileDataOut->WriteUInt16(0); // no 32bit hashs to write
	}

	if (!bDbgDontLoad) {
		FreeHashSet();
	}
	return bResult;
}
Beispiel #11
0
wxString CStatTreeItemMaxConnLimitReached::GetDisplayString() const
{
	if (m_count) {
		return CFormat(wxGetTranslation(m_label)) %
			(CFormat(wxT("%i : %s %s")) % m_count % m_time.FormatISODate() % m_time.FormatISOTime());
	} else {
		return CFormat(wxGetTranslation(m_label)) % _("Never");
	}
}
Beispiel #12
0
void CChatListDlg::OnEdit() 
{
// iterate through list 
for (int nItem = -1;
      (nItem = m_ctlChatList.GetNextItem(nItem, LVNI_SELECTED)) != -1;)
  {

  long iChatID = m_ctlChatList.GetItemData (nItem);
	  
  CChatSocket * pSock = m_pDoc->GetChatSocket (iChatID);

  if (!pSock)   // must have gone
    continue;

  // edit it here
  CChatDetailsDlg dlg;


  dlg.m_strRemoteUserName   = pSock->m_strRemoteUserName  ;
	dlg.m_strGroup            = pSock->m_strGroup           ;
	dlg.m_strActualIPaddress  = inet_ntoa (pSock->m_ServerAddr.sin_addr);
	dlg.m_strAllegedAddress   = pSock->m_strAllegedAddress  ;
	dlg.m_strAllegedPort      = CFormat ("%d", pSock->m_iAllegedPort);
	dlg.m_strChatID           = CFormat ("%ld", pSock->m_iChatID);
	dlg.m_strRemoteVersion    = pSock->m_strRemoteVersion   ;
	dlg.m_bIncoming           = pSock->m_bIncoming          ;
	dlg.m_bCanSnoop           = pSock->m_bCanSnoop          ;
	dlg.m_bCanSendFiles       = pSock->m_bCanSendFiles      ;
	dlg.m_bPrivate            = pSock->m_bPrivate           ;
	dlg.m_bIgnore             = pSock->m_bIgnore            ;
  dlg.m_bCanSendCommands    = pSock->m_bCanSendCommands   ;

  if (dlg.DoModal () != IDOK)
    continue;

  // check still exists :)
  pSock = m_pDoc->GetChatSocket (iChatID);

  if (!pSock)  
    continue;    // must have gone while we were thinking

  // we do it this way so they get the message about the option changing
  m_pDoc->SetChatOption (iChatID, "group",              dlg.m_strGroup);
  // boolean options
  m_pDoc->SetChatOption (iChatID, "served",             dlg.m_bIncoming ? "1" : "0");
  m_pDoc->SetChatOption (iChatID, "can_snoop",          dlg.m_bCanSnoop ? "1" : "0");
  m_pDoc->SetChatOption (iChatID, "can_send_files",     dlg.m_bCanSendFiles ? "1" : "0");
  m_pDoc->SetChatOption (iChatID, "private",            dlg.m_bPrivate ? "1" : "0");
  m_pDoc->SetChatOption (iChatID, "ignore",             dlg.m_bIgnore ? "1" : "0");
  m_pDoc->SetChatOption (iChatID, "can_send_commands",  dlg.m_bCanSendCommands ? "1" : "0");
  
  } // end of loop
	
}
Beispiel #13
0
void CECTag::DebugPrint(int level, bool print_empty) const
{
	if (m_dataLen || print_empty) {
		wxString space;
		for (int i = level; i--;) space += wxT("  ");
		wxString s1 = CFormat(wxT("%s%s %d = ")) % space % GetDebugNameECTagNames(m_tagName) % m_dataLen;
		wxString s2;
		switch (m_tagName) {
			case EC_TAG_DETAIL_LEVEL:
				s2 = GetDebugNameEC_DETAIL_LEVEL(GetInt()); break;
			case EC_TAG_SEARCH_TYPE:
				s2 = GetDebugNameEC_SEARCH_TYPE(GetInt()); break;
			case EC_TAG_STAT_VALUE_TYPE:
				s2 = GetDebugNameEC_STATTREE_NODE_VALUE_TYPE(GetInt()); break;
			default:
				switch (m_dataType) {
					case EC_TAGTYPE_UINT8:
					case EC_TAGTYPE_UINT16:
					case EC_TAGTYPE_UINT32:
					case EC_TAGTYPE_UINT64:
						s2 = CFormat(wxT("%d")) % GetInt(); break;
					case EC_TAGTYPE_STRING:
						s2 = GetStringData(); break;
					case EC_TAGTYPE_DOUBLE:
						s2 = CFormat(wxT("%.1f")) % GetDoubleData(); break;
					case EC_TAGTYPE_HASH16:
						s2 = GetMD4Data().Encode(); break;
					case EC_TAGTYPE_CUSTOM:
						if (m_dataLen == 0) {
							s2 = wxT("empty");
						} else {
							// Make a hex dump (limited to maxOutput)
							const uint32 maxOutput = 50;
							for (uint32 i = 0; i < m_dataLen; i++) {
								if (i == maxOutput) {
									s2 += wxT("...");
									break;
								}
								s2 += CFormat(wxT("%02X ")) % (unsigned char) m_tagData[i];
							}
						}
						break;
					default:
						s2 = GetDebugNameECTagTypes(m_dataType);
				}
		}
		DoECLogLine(s1 + s2);
	}
	for (TagList::const_iterator it = m_tagList.begin(); it != m_tagList.end(); ++it) {
		it->DebugPrint(level + 1, true);
	}
}
Beispiel #14
0
bool CKnownFileList::Append(CKnownFile *Record, bool afterHashing)
{
	if (Record->GetFileSize() > 0) {
		const CMD4Hash& tkey = Record->GetFileHash();
		CKnownFileMap::iterator it = m_knownFileMap.find(tkey);
		if (it == m_knownFileMap.end()) {
			m_knownFileMap[tkey] = Record;
			return true;
		} else {
			CKnownFile *existing = it->second;
			if (KnownFileMatches(Record, existing->GetFileName(), existing->GetLastChangeDatetime(), existing->GetFileSize())) {
				// The file is already on the list, ignore it.
				AddDebugLogLineN(logKnownFiles, CFormat(wxT("%s is already on the list")) % Record->GetFileName().GetPrintable());
				return false;
			} else if (IsOnDuplicates(Record->GetFileName(), Record->GetLastChangeDatetime(), Record->GetFileSize())) {
				// The file is on the duplicates list, ignore it.
				// Should not happen, at least not after hashing. Or why did it get hashed in the first place then?
				AddDebugLogLineN(logKnownFiles, CFormat(wxT("%s is on the duplicates list")) % Record->GetFileName().GetPrintable());
				return false;
			} else {
				if (afterHashing && existing->GetFileSize() == Record->GetFileSize()) {
					// We just hashed a "new" shared file and find it's already known under a different name or date.
					// Guess what - it was probably renamed or touched.
					// So copy over all properties from the existing known file and just keep name/date.
					time_t newDate = Record->GetLastChangeDatetime();
					CPath newName = Record->GetFileName();
					CMemFile f;
					existing->WriteToFile(&f);
					f.Reset();
					Record->LoadFromFile(&f);
					Record->SetLastChangeDatetime(newDate);
					Record->SetFileName(newName);
				}
				// The file is a duplicated hash. Add THE OLD ONE to the duplicates list.
				// (This is used when reading the known file list where the duplicates are stored in front.)
				m_duplicateFileList.push_back(existing);
				if (theApp->sharedfiles) {
					// Removing the old kad keywords created with the old filename
					theApp->sharedfiles->RemoveKeywords(existing);
				}
				m_knownFileMap[tkey] = Record;
				return true;
			}
		}
	} else {
		AddDebugLogLineN(logGeneral,
			CFormat(wxT("%s is 0-size, not added")) %
			Record->GetFileName());

		return false;
	}
}
// Check all clients that uploaded corrupted data,
// and ban them if they didn't upload enough good data too.
void CCorruptionBlackBox::EvaluateData()
{
	CCBBClientMap::iterator it = m_badClients.begin();
	for (; it != m_badClients.end(); ++it) {
		uint32 ip = it->first;
		uint64 bad = it->second.m_downloaded;
		if (!bad) {
			wxFAIL;		// this should not happen
			continue;
		}
		uint64 good = 0;
		CCBBClientMap::iterator it2 = m_goodClients.find(ip);
		if (it2 != m_goodClients.end()) {
			good = it2->second.m_downloaded;
		}

		int nCorruptPercentage = bad * 100 / (bad + good);

		if (nCorruptPercentage > CBB_BANTHRESHOLD) {
			CUpDownClient* pEvilClient = theApp->clientlist->FindClientByIP(ip);
			wxString clientName;
			if (pEvilClient != NULL) {
				clientName = pEvilClient->GetClientShortInfo();
				AddDebugLogLineN(logPartFile, CFormat(wxT("CorruptionBlackBox(%s): Banning: Found client which sent %d of %d corrupted data, %s"))
					% m_partNumber % bad % (good + bad) % pEvilClient->GetClientFullInfo());
				theApp->clientlist->AddTrackClient(pEvilClient);
				pEvilClient->Ban();  // Identified as sender of corrupt data
				// Stop download right away
				pEvilClient->SetDownloadState(DS_BANNED);
				if (pEvilClient->Disconnected(wxT("Upload of corrupted data"))) {
					pEvilClient->Safe_Delete();
				}
			} else {
				clientName = Uint32toStringIP(ip);
				theApp->clientlist->AddBannedClient(ip);
			}
			AddLogLineN(CFormat(_("Banned client %s for sending %s corrupt data of %s total for the file '%s'"))
				% clientName % CastItoXBytes(bad) % CastItoXBytes(good + bad) % m_fileName);
		} else {
			CUpDownClient* pSuspectClient = theApp->clientlist->FindClientByIP(ip);
			if (pSuspectClient != NULL) {
				AddDebugLogLineN(logPartFile, CFormat(wxT("CorruptionBlackBox(%s): Reporting: Found client which probably sent %d of %d corrupted data, but it is within the acceptable limit, %s"))
					% m_partNumber % bad % (good + bad) % pSuspectClient->GetClientFullInfo());
				theApp->clientlist->AddTrackClient(pSuspectClient);
			} else {
				AddDebugLogLineN(logPartFile, CFormat(wxT("CorruptionBlackBox(%s): Reporting: Found client which probably sent %d of %d corrupted data, but it is within the acceptable limit, %s"))
					% m_partNumber % bad % (good + bad) % Uint32toStringIP(ip));
			}
		}
	}
}
Beispiel #16
0
bool CamuleDlg::Check_and_Init_Skin()
{
	bool ret = true;
	wxString skinFileName(thePrefs::GetSkin());

	if (skinFileName.IsEmpty() || skinFileName.IsSameAs(_("- default -"))) {
		return false;
	}

	wxString userDir(JoinPaths(GetConfigDir(), wxT("skins")) + wxFileName::GetPathSeparator());

	wxStandardPathsBase &spb(wxStandardPaths::Get());
#ifdef __WINDOWS__ 
	wxString dataDir(spb.GetPluginsDir());
#elif defined(__WXMAC__)
		wxString dataDir(spb.GetDataDir());
#else
	wxString dataDir(spb.GetDataDir().BeforeLast(wxT('/')) + wxT("/amule"));
#endif
	wxString systemDir(JoinPaths(dataDir,wxT("skins")) + wxFileName::GetPathSeparator());


	skinFileName.Replace(wxT("User:"******"System:"), systemDir );

	m_skinFileName.Assign(skinFileName);
	if (!m_skinFileName.FileExists()) {
		AddLogLineC(CFormat(
			_("Skin directory '%s' does not exist")) %
			skinFileName );
		ret = false;
	} else if (!m_skinFileName.IsFileReadable()) {
		AddLogLineC(CFormat(
			_("WARNING: Unable to open skin file '%s' for read")) %
			skinFileName);
		ret = false;
	}

	wxFFileInputStream in(m_skinFileName.GetFullPath());
	wxZipInputStream zip(in);
	wxZipEntry *entry;

	while ((entry = zip.GetNextEntry()) != NULL) {
		wxZipEntry*& current = cat[entry->GetInternalName()];
		delete current;
		current = entry;
	}

	return ret;
}
Beispiel #17
0
wxString CStatTreeItemSimple::GetDisplayString() const
{
	switch (m_valuetype) {
		case vtInteger:
			switch (m_displaymode) {
				case dmTime:	return CFormat(wxGetTranslation(m_label)) % CastSecondsToHM(m_intvalue);
				case dmBytes:	return CFormat(wxGetTranslation(m_label)) % CastItoXBytes(m_intvalue);
				default:	return CFormat(wxGetTranslation(m_label)) % m_intvalue;
			}
		case vtFloat:	return CFormat(wxGetTranslation(m_label)) % m_floatvalue;
		case vtString:	return CFormat(wxGetTranslation(m_label)) % m_stringvalue;
		default:	return wxGetTranslation(m_label);
	}
}
// copy the registry prefs into the SQLite database into table 'prefs'
int CMUSHclientApp::PopulateDatabase (void)
  {

  SetRegistryKey ("Gammon Software Solutions");

  int i;
  int db_rc = SQLITE_OK;

  for (i = 0; GlobalOptionsTable [i].pName; i++)
    {
    const char * p = (const char *) this +  GlobalOptionsTable [i].iOffset;
    const int Value = GetProfileInt ("Global prefs",  
                                GlobalOptionsTable [i].pName, 
                                GlobalOptionsTable [i].iDefault);

    db_rc = db_execute ((LPCTSTR) CFormat ("INSERT INTO prefs (name, value) VALUES ('%s', %i)",
                        GlobalOptionsTable [i].pName, Value), true);

    if (db_rc != SQLITE_OK)
      return db_rc;
    };

  for (i = 0; AlphaGlobalOptionsTable [i].pName; i++)
    {
    const char * p = (const char *) this +  AlphaGlobalOptionsTable [i].iOffset;

    // fix up the fixed-pitch font
    if (strcmp (AlphaGlobalOptionsTable [i].pName, "DefaultInputFont") == 0 ||
        strcmp (AlphaGlobalOptionsTable [i].pName, "DefaultOutputFont") == 0 ||
        strcmp (AlphaGlobalOptionsTable [i].pName, "FixedPitchFont") == 0)
       AlphaGlobalOptionsTable [i].sDefault = (LPCTSTR) m_strFixedPitchFont;
    
    CString strValue = GetProfileString ("Global prefs",  
                                AlphaGlobalOptionsTable [i].pName, 
                                AlphaGlobalOptionsTable [i].sDefault);

    strValue.Replace ("'", "''");  // fix up quotes

    db_rc = db_execute ((LPCTSTR) CFormat ("INSERT INTO prefs (name, value) VALUES ('%s', '%s')",
                        AlphaGlobalOptionsTable [i].pName, (LPCTSTR) strValue), true);

    if (db_rc != SQLITE_OK)
      return db_rc;

    };

   return SQLITE_OK;

  }  // end of CMUSHclientApp::PopulateDatabase 
Beispiel #19
0
bool CKnownFileList::Init()
{
	CFile file;

	CPath fullpath = CPath(theApp->ConfigDir + m_filename);
	if (!fullpath.FileExists()) {
		// This is perfectly normal. The file was probably either
		// deleted, or this is the first time running aMule.
		return false;
	}

	if (!file.Open(fullpath)) {
		AddLogLineC(CFormat(_("WARNING: %s cannot be opened.")) % m_filename);
		return false;
	}

	try {
		uint8 version = file.ReadUInt8();
		if ((version != MET_HEADER) && (version != MET_HEADER_WITH_LARGEFILES)) {
			AddLogLineC(_("WARNING: Known file list corrupted, contains invalid header."));
			return false;
		}

		wxMutexLocker sLock(list_mut);
		uint32 RecordsNumber = file.ReadUInt32();
		AddDebugLogLineN(logKnownFiles, CFormat(wxT("Reading %i known files from file format 0x%2.2x."))
			% RecordsNumber % version);
		for (uint32 i = 0; i < RecordsNumber; i++) {
			CScopedPtr<CKnownFile> record;
			if (record->LoadFromFile(&file)) {
				AddDebugLogLineN(logKnownFiles,
					CFormat(wxT("Known file read: %s")) % record->GetFileName());
				Append(record.release());
			} else {
				AddLogLineC(_("Failed to load entry in known file list, file may be corrupt"));
			}
		}
		AddDebugLogLineN(logKnownFiles, wxT("Finished reading known files"));

		return true;
	} catch (const CInvalidPacket& e) {
		AddLogLineC(_("Invalid entry in known file list, file may be corrupt: ") + e.what());
	} catch (const CSafeIOException& e) {
		AddLogLineC(CFormat(_("IO error while reading %s file: %s")) % m_filename % e.what());
	}

	return false;
}
Beispiel #20
0
CString GetTabText (HWND hwnd)
  {
  CString strName;
  char text[256];

  CWnd * pWnd = CWnd::FromHandle  (hwnd);

  ::GetWindowText(hwnd, text, sizeof text);
  strName = text;

  if (pWnd->IsKindOf(RUNTIME_CLASS(CChildFrame)))
    {
    CChildFrame * pWorldFrame = (CChildFrame *) pWnd;
    CMUSHclientDoc * pDoc = pWorldFrame->m_pDoc;
    // custom title?
    if (pDoc->m_strWindowTitle.IsEmpty ())
      strName = pDoc->m_mush_name;
    else
      strName = pDoc->m_strWindowTitle;
    if (pDoc->m_new_lines && !pDoc->m_bDoNotShowOutstandingLines)
      strName += CFormat (" (%i)", pDoc->m_new_lines);
    }
  else if (pWnd->IsKindOf(RUNTIME_CLASS(CTextChildFrame)))
    {
    CTextChildFrame * pNotepadFrame = (CTextChildFrame *) pWnd;
    CTextDocument * pDoc = pNotepadFrame->m_pDoc;
    if (!pDoc->m_strTitle.IsEmpty ())
      strName = pDoc->m_strTitle;
    if (pDoc->IsModified () && !pDoc->m_bReadOnly)
       strName += " *";
    }

  strName.Replace ("&", "&&");
  return strName;
  }
void CCommentDialogLst::UpdateList()
{
	int count = 0;
	ClearList();

	FileRatingList list;
	m_file->GetRatingAndComments(list);
	for (FileRatingList::const_iterator it = list.begin(); it != list.end(); ++it) {
		if (!thePrefs::IsCommentFiltered(it->Comment)) {
			m_list->InsertItem(count, it->UserName);
			m_list->SetItem(count, 1, it->FileName);
			m_list->SetItem(count, 2, (it->Rating != -1) ? GetRateString(it->Rating) : wxString(wxT("on")));
			m_list->SetItem(count, 3, it->Comment);
			m_list->SetItemPtrData(count, reinterpret_cast<wxUIntPtr>(new SFileRating(*it)));
			++count;
		}
	}

	wxString info;
	if (count == 0) {
		info = _("No comments");
	} else {
		info = CFormat(wxPLURAL("%u comment", "%u comments", count)) % count;
	}

	FindWindow(IDC_CMSTATUS)->SetLabel(info);
	FindWindow(IDC_CMSTATUS)->GetParent()->Layout();

	m_file->UpdateFileRatingCommentAvail();
}
// Store a piece of received data (don't know if it's good or bad yet).
// Data is stored in a list for the chunk in belongs to.
void CCorruptionBlackBox::TransferredData(uint64 nStartPos, uint64 nEndPos, uint32 senderIP)
{
	if (nStartPos > nEndPos) {
		wxFAIL;
		return;
	}

	// convert pos to relative block pos
	uint16 nPart = (uint16)(nStartPos / PARTSIZE);
	uint32 nRelStartPos = nStartPos - nPart*PARTSIZE;
	uint32 nRelEndPos = nEndPos - nPart*PARTSIZE;
	if (nRelEndPos >= PARTSIZE) {
		// data crosses the partborder, split it
		// (for the fun of it, this should never happen)
		nRelEndPos = PARTSIZE-1;
		TransferredData((nPart+1)*PARTSIZE, nEndPos, senderIP);
	}
	//
	// Let's keep things simple.
	// We don't request data we already have.
	// We check if received data exceeds block boundaries.
	// -> There should not be much overlap here.
	// So just stuff everything received into the list and only join adjacent blocks.
	//
	CRecordList & list = m_Records[nPart]; // this creates the entry if it doesn't exist yet
	bool merged = false;
	for (CRecordList::iterator it = list.begin(); it != list.end() && !merged; ++it) {
		merged = it->Merge(nRelStartPos, nRelEndPos, senderIP);
	}
	if (!merged) {
		list.push_back(CCBBRecord(nRelStartPos, nRelEndPos, senderIP));
		AddDebugLogLineN(logPartFile, CFormat(wxT("CorruptionBlackBox(%s): transferred: new record for part %d (%d - %d, %s)"))
			% m_partNumber % nPart % nRelStartPos % nRelEndPos % Uint32toStringIP(senderIP));
	}
}
Beispiel #23
0
int CamuleDaemonApp::OnExit()
{
#ifdef AMULED28
	/*
	 * Stop all socket threads before entering
	 * shutdown sequence.
	 */
	delete listensocket;
	listensocket = 0;
	if (clientudp) {
		delete clientudp;
		clientudp = NULL;
	}
#endif

	ShutDown();

#ifndef __WXMSW__
	int ret = sigaction(SIGCHLD, &m_oldSignalChildAction, NULL);
	if (ret == -1) {
		AddDebugLogLineC(logStandard, CFormat(wxT("CamuleDaemonApp::OnRun(): second sigaction() failed: %m.")));
	} else {
		AddDebugLogLineN(logGeneral, wxT("CamuleDaemonApp::OnRun(): Uninstallation of SIGCHLD callback with sigaction() succeeded."));
	}
#endif // __WXMSW__
	
	// lfroen: delete socket threads
	if (ECServerHandler) {
		ECServerHandler = 0;
	}

	delete core_timer;
	
	return CamuleApp::OnExit();
}
Beispiel #24
0
CChatSession* CChatSelector::StartSession(uint64 client_id, const wxString& client_name, bool show)
{
	// Check to see if we've already opened a session for this user
	if ( GetPageByClientID( client_id ) ) {
		if ( show ) {
		  SetSelection( GetTabByClientID( client_id ) );
		}

		return NULL;
	}

	CChatSession* chatsession = new CChatSession(this);

	chatsession->m_client_id = client_id;

	wxString text;
	text = wxT(" *** ") + (CFormat(_("Chat-Session Started: %s (%s:%u) - %s %s"))
			% client_name
			% Uint32toStringIP(IP_FROM_GUI_ID(client_id))
			% PORT_FROM_GUI_ID(client_id)
			% wxDateTime::Now().FormatISODate()
			% wxDateTime::Now().FormatISOTime());

	chatsession->AddText( text, COLOR_RED );
	AddPage(chatsession, client_name, show, 0);

	CUserEvents::ProcessEvent(CUserEvents::NewChatSession, &client_name);

	return chatsession;
}
Beispiel #25
0
void CDownloadQueue::AddDownload(CPartFile* file, bool paused, uint8 category)
{
	wxCHECK_RET(!IsFileExisting(file->GetFileHash()), wxT("Adding duplicate part-file"));

	if (file->GetStatus(true) == PS_ALLOCATING) {
		file->PauseFile();
	} else if (paused && GetFileCount()) {
		file->StopFile();
	}

	{
		wxMutexLocker lock(m_mutex);
		m_filelist.push_back( file );
		DoSortByPriority();
	}

	NotifyObservers( EventType( EventType::INSERTED, file ) );
	if (category < theApp->glob_prefs->GetCatCount()) {
		file->SetCategory(category);
	} else {
		AddDebugLogLineN( logDownloadQueue, wxT("Tried to add download into invalid category.") );
	}
	Notify_DownloadCtrlAddFile( file );
	theApp->searchlist->UpdateSearchFileByHash(file->GetFileHash()); 	// Update file in the search dialog if it's still open
	AddLogLineC(CFormat(_("Downloading %s")) % file->GetFileName() );
}
Beispiel #26
0
void CIP2Country::Update()
{
	AddLogLineN(CFormat(_("Download new GeoIP.dat from %s")) % thePrefs::GetGeoIPUpdateUrl());
	CHTTPDownloadThread *downloader = new CHTTPDownloadThread(thePrefs::GetGeoIPUpdateUrl(), m_DataBasePath + wxT(".download"), m_DataBasePath, HTTP_GeoIP, true, true);
	downloader->Create();
	downloader->Run();
}
void CPartFileConvertDlg::UpdateJobInfo(ConvertInfo& info)
{
	if (s_convertgui) {
		// search jobitem in listctrl
		long itemnr = s_convertgui->m_joblist->FindItem(-1, info.id);
		// if it does not exist, add it
		if (itemnr == -1) {
			itemnr = s_convertgui->m_joblist->InsertItem(s_convertgui->m_joblist->GetItemCount(), info.folder.GetPrintable());
			if (itemnr != -1) {
				s_convertgui->m_joblist->SetItemData(itemnr, info.id);
			}
		}
		// update columns
		if (itemnr != -1) {
			s_convertgui->m_joblist->SetItem(itemnr, 0, info.filename.IsOk() ? info.folder.GetPrintable() : info.filename.GetPrintable() );
			s_convertgui->m_joblist->SetItem(itemnr, 1, GetConversionState(info.state) );
			if (info.size > 0) {
				s_convertgui->m_joblist->SetItem(itemnr, 2, CFormat(_("%s (Disk: %s)")) % CastItoXBytes(info.size) % CastItoXBytes(info.spaceneeded));
			} else {
				s_convertgui->m_joblist->SetItem(itemnr, 2, wxEmptyString);
			}
			s_convertgui->m_joblist->SetItem(itemnr, 3, info.filehash);
		}
	}
}
Beispiel #28
0
/*
 * This function adds a file indicated by filehash to suspended_uploads_list
 */
uint16 CUploadQueue::SuspendUpload( const CMD4Hash& filehash )
{
	AddLogLineM( false, CFormat( _("Suspending upload of file: %s" ) )
				% filehash.Encode() );
	uint16 removed = 0;

	//Append the filehash to the list.
	suspended_uploads_list.push_back(filehash);
	wxString base16hash = filehash.Encode();

	CClientPtrList::iterator it = m_uploadinglist.begin();
	while (it != m_uploadinglist.end()) {
		CUpDownClient *potential = *it++;
		//check if the client is uploading the file we need to suspend
		if(potential->GetUploadFileID() == filehash) {
			//remove the unlucky client from the upload queue and add to the waiting queue
			RemoveFromUploadQueue(potential);

			m_waitinglist.push_back(potential);
			theStats::AddWaitingClient();
			potential->SetUploadState(US_ONUPLOADQUEUE);
			potential->SendRankingInfo();
			Notify_QlistRefreshClient(potential);
			Notify_ShowQueueCount(m_waitinglist.size());
			removed++;
		}
	}
	return removed;
}
Beispiel #29
0
void CIP2Country::DownloadFinished(uint32 result)
{
	if (result == HTTP_Success) {
		Disable();
		// download succeeded. Switch over to new database.
		wxString newDat = m_DataBasePath + wxT(".download");

		// Try to unpack the file, might be an archive
		wxWCharBuffer dataBaseName = m_DataBaseName.wc_str();
		const wxChar* geoip_files[] = {
			dataBaseName,
			NULL
		};

		if (UnpackArchive(CPath(newDat), geoip_files).second == EFT_Error) {
			AddLogLineC(_("Download of GeoIP.dat file failed, aborting update."));
			return;
		}

		if (wxFileExists(m_DataBasePath)) {
			if (!wxRemoveFile(m_DataBasePath)) {
				AddLogLineC(CFormat(_("Failed to remove %s file, aborting update.")) % m_DataBaseName);
				return;
			}
		}

		if (!wxRenameFile(newDat, m_DataBasePath)) {
			AddLogLineC(CFormat(_("Failed to rename %s file, aborting update.")) % m_DataBaseName);
			return;
		}

		Enable();
		if (m_geoip) {
			AddLogLineN(CFormat(_("Successfully updated %s")) % m_DataBaseName);
		} else {
			AddLogLineC(_("Error updating GeoIP.dat"));
		}
	} else if (result == HTTP_Skipped) {
		AddLogLineN(CFormat(_("Skipped download of %s, because requested file is not newer.")) % m_DataBaseName);
	} else {
		AddLogLineC(CFormat(_("Failed to download %s from %s")) % m_DataBaseName % thePrefs::GetGeoIPUpdateUrl());
		// if it failed and there is no database, turn it off
		if (!wxFileExists(m_DataBasePath)) {
			thePrefs::SetGeoIPEnabled(false);
		}
	}
}
Beispiel #30
0
void CKadDlg::UpdateNodeCount(unsigned nodeCount)
{
	wxStaticText* label = CastChild( wxT("nodesListLabel"), wxStaticText );
	wxCHECK_RET(label, wxT("Failed to find kad-nodes label"));

	label->SetLabel(CFormat(_("Nodes (%u)")) % nodeCount);
	label->GetParent()->Layout();
}