void CRoutingZone::DbgWriteBootstrapFile() { DebugLogWarning(_T("Writing special bootstrap nodes.dat - not intended for normal use")); try { // Write a saved contact list. CUInt128 uID; CSafeBufferedFile file; CFileException fexp; if (file.Open(m_sFilename, CFile::modeWrite | CFile::modeCreate | CFile::typeBinary|CFile::shareDenyWrite, &fexp)) { setvbuf(file.m_pStream, NULL, _IOFBF, 32768); // The bootstrap method gets a very nice sample of contacts to save. ContactMap mapContacts; CUInt128 uRandom(CUInt128((ULONG)0), 0); CUInt128 uDistance = uRandom; uDistance.Xor(uMe); GetClosestTo(2, uRandom, uDistance, 1200, &mapContacts, false, false); // filter out Kad1 nodes for (ContactMap::iterator itContactMap = mapContacts.begin(); itContactMap != mapContacts.end(); ) { ContactMap::iterator itCurContactMap = itContactMap; ++itContactMap; CContact* pContact = itCurContactMap->second; if (pContact->GetVersion() <= 1) mapContacts.erase(itCurContactMap); } // Start file with 0 to prevent older clients from reading it. file.WriteUInt32(0); // Now tag it with a version which happens to be 2 (1 till 0.48a). file.WriteUInt32(3); file.WriteUInt32(1); // if we would use version >=3, this would mean that this is not a normal nodes.dat file.WriteUInt32((uint32_t)mapContacts.size()); for (ContactMap::const_iterator itContactMap = mapContacts.begin(); itContactMap != mapContacts.end(); ++itContactMap) { CContact* pContact = itContactMap->second; pContact->GetClientID(&uID); file.WriteUInt128(&uID); file.WriteUInt32(pContact->GetIPAddress()); file.WriteUInt16(pContact->GetUDPPort()); file.WriteUInt16(pContact->GetTCPPort()); file.WriteUInt8(pContact->GetVersion()); } file.Close(); AddDebugLogLine( false, _T("Wrote %ld contact to bootstrap file."), mapContacts.size()); } else DebugLogError(_T("Unable to store Kad file: %s"), m_sFilename); } catch (CFileException* e) { e->Delete(); AddDebugLogLine(false, _T("CFileException in CRoutingZone::writeFile")); } }
void CPrefs::WriteFile() { try { CSafeBufferedFile file; CFileException fexp; if (file.Open(m_sFilename, CFile::modeWrite | CFile::modeCreate | CFile::typeBinary | CFile::shareDenyWrite, &fexp)) { setvbuf(file.m_pStream, NULL, _IOFBF, 16384); file.WriteUInt32(m_uIP); file.WriteUInt16(0); //This is no longer used. file.WriteUInt128(&m_uClientID); file.WriteUInt8(0); //This is to tell older clients there are no tags.. file.Close(); } } catch (CException *ex) { ASSERT(0); ex->Delete(); } catch (...) { TRACE("Exception in CPrefs::writeFile\n"); } }
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; }
void CPrefs::ReadFile() { try { CSafeBufferedFile file; CFileException fexp; if (file.Open(m_sFilename, CFile::modeRead | CFile::osSequentialScan | CFile::typeBinary | CFile::shareDenyWrite, &fexp)) { setvbuf(file.m_pStream, NULL, _IOFBF, 16384); m_uIP = file.ReadUInt32(); file.ReadUInt16(); file.ReadUInt128(&m_uClientID); // get rid of invalid kad IDs which may have been stored by older versions if (m_uClientID == 0) m_uClientID.SetValueRandom(); file.Close(); } } catch (CException *ex) { ASSERT(0); ex->Delete(); } catch (...) { TRACE("Exception in CPrefs::readFile\n"); } }
bool CFriendList::AddEmfriendsMetToList(const CString& strFile) { CSafeBufferedFile file; CFileException fexp; if ( !file.Open(strFile, CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary, &fexp) ) { if ( fexp.m_cause != CFileException::fileNotFound ) { CString strError(GetResString(IDS_ERR_READEMFRIENDS)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if ( fexp.GetErrorMessage(szError,MAX_CFEXP_ERRORMSG) ) { strError += _T(" - "); strError += szError; } AddLogLine(true, _T("%s"), strError); } return false; } try { uint8 header = file.ReadUInt8(); if ( header != MET_HEADER ) { file.Close(); return false; } UINT nRecordsNumber = file.ReadUInt32(); for (UINT i = 0; i < nRecordsNumber; i++) { CFriend* Record = new CFriend(); Record->LoadFromFile(&file); if ( !IsAlreadyFriend(Record->m_abyUserhash) ) m_listFriends.AddTail(Record); } file.Close(); } catch ( CFileException* error ) { if ( error->m_cause == CFileException::endOfFile ) AddLogLine(true,GetResString(IDS_ERR_EMFRIENDSINVALID)); else { TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, MAX_CFEXP_ERRORMSG); AddLogLine(true, GetResString(IDS_ERR_READEMFRIENDS), buffer); } error->Delete(); return false; } return true; }// MORPH END - Added by Commander, Friendlinks [emulEspaña]
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(); } }
bool CFriendList::LoadList(){ CString strFileName = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + EMFRIENDS_MET_FILENAME; CSafeBufferedFile file; CFileException fexp; if (!file.Open(strFileName, CFile::modeRead | CFile::osSequentialScan | CFile::typeBinary | CFile::shareDenyWrite, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(GetResString(IDS_ERR_READEMFRIENDS)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } LogError(LOG_STATUSBAR, _T("%s"), strError); } return false; } try { uint8 header = file.ReadUInt8(); if (header != MET_HEADER){ file.Close(); return false; } UINT nRecordsNumber = file.ReadUInt32(); for (UINT i = 0; i < nRecordsNumber; i++) { CFriend* Record = new CFriend(); Record->LoadFromFile(&file); m_listFriends.AddTail(Record); } file.Close(); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile) LogError(LOG_STATUSBAR,GetResString(IDS_ERR_EMFRIENDSINVALID)); else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR,GetResString(IDS_ERR_READEMFRIENDS),buffer); } error->Delete(); return false; } return true; }
void CClientCreditsList::LoadList() { CString strFileName = thePrefs.GetConfigDir() + CLIENTS_MET_FILENAME; const int iOpenFlags = CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite; CSafeBufferedFile file; CFileException fexp; if (!file.Open(strFileName, iOpenFlags, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(GetResString(IDS_ERR_LOADCREDITFILE)); 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{ uint8 version = file.ReadUInt8(); if (version != CREDITFILE_VERSION && version != CREDITFILE_VERSION_29){ LogWarning(GetResString(IDS_ERR_CREDITFILEOLD)); file.Close(); return; } // everything is ok, lets see if the backup exist... CString strBakFileName; strBakFileName.Format(_T("%s") CLIENTS_MET_FILENAME _T(".bak"), thePrefs.GetConfigDir()); DWORD dwBakFileSize = 0; BOOL bCreateBackup = TRUE; HANDLE hBakFile = ::CreateFile(strBakFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hBakFile != INVALID_HANDLE_VALUE) { // Ok, the backup exist, get the size dwBakFileSize = ::GetFileSize(hBakFile, NULL); //debug if (dwBakFileSize > (DWORD)file.GetLength()) { // the size of the backup was larger then the org. file, something is wrong here, don't overwrite old backup.. bCreateBackup = FALSE; } //else: backup is smaller or the same size as org. file, proceed with copying of file ::CloseHandle(hBakFile); } //else: the backup doesn't exist, create it if (bCreateBackup) { file.Close(); // close the file before copying if (!::CopyFile(strFileName, strBakFileName, FALSE)) LogError(GetResString(IDS_ERR_MAKEBAKCREDITFILE)); // reopen file CFileException fexp; if (!file.Open(strFileName, iOpenFlags, &fexp)){ CString strError(GetResString(IDS_ERR_LOADCREDITFILE)); 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); file.Seek(1, CFile::begin); //set filepointer behind file version byte } UINT count = file.ReadUInt32(); m_mapClients.InitHashTable(count+5000); // TODO: should be prime number... and 20% larger const uint32 dwExpired = time(NULL) - 12960000; // today - 150 day uint32 cDeleted = 0; for (UINT i = 0; i < count; i++){ CreditStruct* newcstruct = new CreditStruct; MEMSET(newcstruct, 0, sizeof(CreditStruct)); if (version == CREDITFILE_VERSION_29) file.Read(newcstruct, sizeof(CreditStruct_29a)); else file.Read(newcstruct, sizeof(CreditStruct)); if (newcstruct->nLastSeen < dwExpired){ cDeleted++; delete newcstruct; continue; } CClientCredits* newcredits = new CClientCredits(newcstruct); m_mapClients.SetAt(CCKey(newcredits->GetKey()), newcredits); } file.Close(); if (cDeleted>0) AddLogLine(false, GetResString(IDS_CREDITFILELOADED) + GetResString(IDS_CREDITSEXPIRED), count-cDeleted,cDeleted); else AddLogLine(false, GetResString(IDS_CREDITFILELOADED), count); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile) LogError(LOG_STATUSBAR, GetResString(IDS_CREDITFILECORRUPT)); else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR, GetResString(IDS_ERR_CREDITFILEREAD), buffer); } error->Delete(); } }
void CKnownFileList::Save() { if (thePrefs.GetLogFileSaving()) AddDebugLogLine(false, _T("Saving known files list file \"%s\""), KNOWN_MET_FILENAME); m_nLastSaved = ::GetTickCount(); CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath += KNOWN_MET_FILENAME; CSafeBufferedFile file; CFileException fexp; if (!file.Open(fullpath, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ CString strError(_T("Failed to save ") 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); } else{ setvbuf(file.m_pStream, NULL, _IOFBF, 16384); try{ file.WriteUInt8(0); // we will write the version tag later depending if any large files are on the list UINT nRecordsNumber = 0; bool bContainsAnyLargeFiles = false; file.WriteUInt32(nRecordsNumber); POSITION pos = m_Files_map.GetStartPosition(); while( pos != NULL ) { CKnownFile* pFile; CCKey key; m_Files_map.GetNextAssoc( pos, key, pFile ); if (!thePrefs.IsRememberingDownloadedFiles() && !theApp.sharedfiles->IsFilePtrInList(pFile)){ continue; } else{ pFile->WriteToFile(&file); nRecordsNumber++; if (pFile->IsLargeFile()) bContainsAnyLargeFiles = true; } } file.SeekToBegin(); file.WriteUInt8(bContainsAnyLargeFiles ? MET_HEADER_I64TAGS : MET_HEADER); file.WriteUInt32(nRecordsNumber); 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 ") KNOWN_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(); } } if (thePrefs.GetLogFileSaving()) AddDebugLogLine(false, _T("Saving known files list file \"%s\""), CANCELLED_MET_FILENAME); fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath += CANCELLED_MET_FILENAME; if (!file.Open(fullpath, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ CString strError(_T("Failed to save ") CANCELLED_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); } else{ setvbuf(file.m_pStream, NULL, _IOFBF, 16384); try{ file.WriteUInt8(CANCELLED_HEADER); file.WriteUInt8(CANCELLED_VERSION); file.WriteUInt32(m_dwCancelledFilesSeed); if (!thePrefs.IsRememberingCancelledFiles()){ file.WriteUInt32(0); } else{ UINT nRecordsNumber = m_mapCancelledFiles.GetCount(); file.WriteUInt32(nRecordsNumber); POSITION pos = m_mapCancelledFiles.GetStartPosition(); while( pos != NULL ) { int dwDummy; CSKey key; m_mapCancelledFiles.GetNextAssoc( pos, key, dwDummy ); file.WriteHash16(key.m_key); file.WriteUInt8(0); } } 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 ") CANCELLED_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(); } } }
bool CKnownFileList::LoadCancelledFiles(){ // cancelled.met Format: <Header 1 = CANCELLED_HEADER><Version 1 = CANCELLED_VERSION><Seed 4><Count 4>[<HashHash 16><TagCount 1>[Tags TagCount] Count] if (!thePrefs.IsRememberingCancelledFiles()) return true; CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath.Append(CANCELLED_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 ") CANCELLED_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); uchar ucHash[16]; try { bool bOldVersion = false; uint8 header = file.ReadUInt8(); if (header != CANCELLED_HEADER){ if (header == CANCELLED_HEADER_OLD){ bOldVersion = true; DebugLog(_T("Deprecated version of cancelled.met found, converting to new version")); } else{ file.Close(); return false; } } uint8 byVersion = 0; if (!bOldVersion){ byVersion = file.ReadUInt8(); if (byVersion > CANCELLED_VERSION){ file.Close(); return false; } m_dwCancelledFilesSeed = file.ReadUInt32(); } if (m_dwCancelledFilesSeed == 0) { ASSERT( bOldVersion || file.GetLength() <= 10 ); m_dwCancelledFilesSeed = (GetRandomUInt32() % 0xFFFFFFFE) + 1; } UINT RecordsNumber = file.ReadUInt32(); for (UINT i = 0; i < RecordsNumber; i++) { file.ReadHash16(ucHash); uint8 nCount = file.ReadUInt8(); // for compatibility with future versions which may add more data than just the hash for (UINT j = 0; j < nCount; j++) { CTag tag(&file, false); } if (bOldVersion){ // convert old real hash to new hashash uchar pachSeedHash[20]; PokeUInt32(pachSeedHash, m_dwCancelledFilesSeed); md4cpy(pachSeedHash + 4, ucHash); MD5Sum md5(pachSeedHash, sizeof(pachSeedHash)); md4cpy(ucHash, md5.GetRawHash()); } m_mapCancelledFiles.SetAt(CSKey(ucHash), 1); } file.Close(); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile) LogError(LOG_STATUSBAR, GetResString(IDS_ERR_CONFIGCORRUPT), CANCELLED_MET_FILENAME); else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR, GetResString(IDS_ERR_FAILEDTOLOAD), CANCELLED_MET_FILENAME, buffer); } error->Delete(); return false; } return true; }
bool CServerList::SaveServermetToFile() { if (thePrefs.GetLogFileSaving()) AddDebugLogLine(false, _T("Saving servers list file \"%s\""), SERVER_MET_FILENAME); m_nLastSaved = ::GetTickCount(); CString newservermet(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); newservermet += SERVER_MET_FILENAME _T(".new"); CSafeBufferedFile servermet; CFileException fexp; if (!servermet.Open(newservermet, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ CString strError(GetResString(IDS_ERR_SAVESERVERMET)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } LogError(LOG_STATUSBAR, _T("%s"), strError); return false; } setvbuf(servermet.m_pStream, NULL, _IOFBF, 16384); try{ servermet.WriteUInt8(0xE0); UINT fservercount = list.GetCount(); servermet.WriteUInt32(fservercount); for (UINT j = 0; j < fservercount; j++) { const CServer* nextserver = GetServerAt(j); // don't write potential out-dated IPs of dynIP-servers servermet.WriteUInt32(nextserver->HasDynIP() ? 0 : nextserver->GetIP()); servermet.WriteUInt16(nextserver->GetPort()); UINT uTagCount = 0; ULONG uTagCountFilePos = (ULONG)servermet.GetPosition(); servermet.WriteUInt32(uTagCount); if (!nextserver->GetListName().IsEmpty()){ CTag servername(ST_SERVERNAME, nextserver->GetListName()); servername.WriteTagToFile(&servermet, utf8strOptBOM); uTagCount++; } if (!nextserver->GetDynIP().IsEmpty()){ CTag serverdynip(ST_DYNIP, nextserver->GetDynIP()); serverdynip.WriteTagToFile(&servermet, utf8strOptBOM); uTagCount++; } if (!nextserver->GetDescription().IsEmpty()){ CTag serverdesc(ST_DESCRIPTION, nextserver->GetDescription()); serverdesc.WriteTagToFile(&servermet, utf8strOptBOM); uTagCount++; } if (nextserver->GetFailedCount()){ CTag serverfail(ST_FAIL, nextserver->GetFailedCount()); serverfail.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetPreference() != SRV_PR_NORMAL){ CTag serverpref(ST_PREFERENCE, nextserver->GetPreference()); serverpref.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetUsers()){ CTag serveruser("users", nextserver->GetUsers()); serveruser.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetFiles()){ CTag serverfiles("files", nextserver->GetFiles()); serverfiles.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetPing()){ CTag serverping(ST_PING, nextserver->GetPing()); serverping.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetLastPingedTime()){ CTag serverlastp(ST_LASTPING, nextserver->GetLastPingedTime()); serverlastp.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetMaxUsers()){ CTag servermaxusers(ST_MAXUSERS, nextserver->GetMaxUsers()); servermaxusers.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetSoftFiles()){ CTag softfiles(ST_SOFTFILES, nextserver->GetSoftFiles()); softfiles.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetHardFiles()){ CTag hardfiles(ST_HARDFILES, nextserver->GetHardFiles()); hardfiles.WriteTagToFile(&servermet); uTagCount++; } if (!nextserver->GetVersion().IsEmpty()){ // as long as we don't receive an integer version tag from the local server (TCP) we store it as string CTag version(ST_VERSION, nextserver->GetVersion()); version.WriteTagToFile(&servermet, utf8strOptBOM); uTagCount++; } if (nextserver->GetUDPFlags()){ CTag tagUDPFlags(ST_UDPFLAGS, nextserver->GetUDPFlags()); tagUDPFlags.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetLowIDUsers()){ CTag tagLowIDUsers(ST_LOWIDUSERS, nextserver->GetLowIDUsers()); tagLowIDUsers.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetServerKeyUDP(true)){ CTag tagServerKeyUDP(ST_UDPKEY, nextserver->GetServerKeyUDP(true)); tagServerKeyUDP.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetServerKeyUDPIP()){ CTag tagServerKeyUDPIP(ST_UDPKEYIP, nextserver->GetServerKeyUDPIP()); tagServerKeyUDPIP.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetObfuscationPortTCP()){ CTag tagObfuscationPortTCP(ST_TCPPORTOBFUSCATION, nextserver->GetObfuscationPortTCP()); tagObfuscationPortTCP.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetObfuscationPortUDP()){ CTag tagObfuscationPortUDP(ST_UDPPORTOBFUSCATION, nextserver->GetObfuscationPortUDP()); tagObfuscationPortUDP.WriteTagToFile(&servermet); uTagCount++; } servermet.Seek(uTagCountFilePos, CFile::begin); servermet.WriteUInt32(uTagCount); servermet.SeekToEnd(); } if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning())){ servermet.Flush(); // flush file stream buffers to disk buffers if (_commit(_fileno(servermet.m_pStream)) != 0) // commit disk buffers to disk AfxThrowFileException(CFileException::hardIO, GetLastError(), servermet.GetFileName()); } servermet.Close(); CString curservermet(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); CString oldservermet(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); curservermet += SERVER_MET_FILENAME; oldservermet += _T("server_met.old"); if (_taccess(oldservermet, 0) == 0) CFile::Remove(oldservermet); if (_taccess(curservermet, 0) == 0) CFile::Rename(curservermet,oldservermet); CFile::Rename(newservermet,curservermet); } catch(CFileException* error) { CString strError(GetResString(IDS_ERR_SAVESERVERMET2)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (error->GetErrorMessage(szError, ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } LogError(LOG_STATUSBAR, _T("%s"), strError); error->Delete(); return false; } return true; }
bool CServerList::AddServerMetToList(const CString& strFile, bool bMerge) { if (!bMerge) { theApp.emuledlg->serverwnd->serverlistctrl.DeleteAllItems(); RemoveAllServers(); } CSafeBufferedFile servermet; CFileException fexp; if (!servermet.Open(strFile ,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){ if (!bMerge){ CString strError(GetResString(IDS_ERR_LOADSERVERMET)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (fexp.GetErrorMessage(szError,ARRSIZE(szError))){ strError += _T(" - "); strError += szError; } LogError(LOG_STATUSBAR, _T("%s"), strError); } return false; } setvbuf(servermet.m_pStream, NULL, _IOFBF, 16384); try{ version = servermet.ReadUInt8(); if (version != 0xE0 && version != MET_HEADER){ servermet.Close(); LogError(LOG_STATUSBAR,GetResString(IDS_ERR_BADSERVERMETVERSION), version); return false; } theApp.emuledlg->serverwnd->serverlistctrl.Hide(); theApp.emuledlg->serverwnd->serverlistctrl.SetRedraw(FALSE); UINT fservercount = servermet.ReadUInt32(); ServerMet_Struct sbuffer; UINT iAddCount = 0; for (UINT j = 0; j < fservercount; j++) { // get server servermet.Read(&sbuffer, sizeof(ServerMet_Struct)); CServer* newserver = new CServer(&sbuffer); // add tags for (UINT i = 0; i < sbuffer.tagcount; i++) newserver->AddTagFromFile(&servermet); if (bMerge) { // If we are merging a (downloaded) server list into our list, ignore the priority of the // server -- some server list providers are doing a poor job with this and offering lists // with dead servers set to 'High'.. newserver->SetPreference(SRV_PR_NORMAL); } // set listname for server if (newserver->GetListName().IsEmpty()) newserver->SetListName(newserver->GetAddress()); if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(newserver, true, true)) { CServer* update = theApp.serverlist->GetServerByAddress(newserver->GetAddress(), newserver->GetPort()); if (update) { update->SetListName(newserver->GetListName()); update->SetDescription(newserver->GetDescription()); theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(update); } delete newserver; } else iAddCount++; } if (!bMerge) AddLogLine(true,GetResString(IDS_SERVERSFOUND), fservercount); else AddLogLine(true,GetResString(IDS_SERVERSADDED), iAddCount, fservercount - iAddCount); servermet.Close(); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile){ LogError(LOG_STATUSBAR, GetResString(IDS_ERR_BADSERVERLIST)); } else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR, GetResString(IDS_ERR_FILEERROR_SERVERMET),buffer); } error->Delete(); } theApp.emuledlg->serverwnd->serverlistctrl.SetRedraw(TRUE); theApp.emuledlg->serverwnd->serverlistctrl.Visable(); return true; }
void CRoutingZone::WriteFile() { // don't overwrite a bootstrap nodes.dat with an empty one, if we didn't finished probing if (!CKademlia::s_liBootstapList.IsEmpty() && GetNumContacts() == 0){ DebugLogWarning(_T("Skipped storing nodes.dat, because we have an unfinished bootstrap of the nodes.dat version and no contacts in our routing table")); return; } try { // Write a saved contact list. CUInt128 uID; CSafeBufferedFile file; CFileException fexp; if (file.Open(m_sFilename, CFile::modeWrite | CFile::modeCreate | CFile::typeBinary|CFile::shareDenyWrite, &fexp)) { setvbuf(file.m_pStream, NULL, _IOFBF, 32768); // The bootstrap method gets a very nice sample of contacts to save. ContactList listContacts; GetBootstrapContacts(&listContacts, 200); // Start file with 0 to prevent older clients from reading it. file.WriteUInt32(0); // Now tag it with a version which happens to be 2 (1 till 0.48a). file.WriteUInt32(2); // file.WriteUInt32(0) // if we would use version >=3, this would mean that this is a normal nodes.dat file.WriteUInt32((uint32_t)listContacts.size()); for (ContactList::const_iterator itContactList = listContacts.begin(); itContactList != listContacts.end(); ++itContactList) { CContact* pContact = *itContactList; pContact->GetClientID(&uID); file.WriteUInt128(&uID); file.WriteUInt32(pContact->GetIPAddress()); file.WriteUInt16(pContact->GetUDPPort()); file.WriteUInt16(pContact->GetTCPPort()); file.WriteUInt8(pContact->GetVersion()); pContact->GetUDPKey().StoreToFile(file); file.WriteUInt8(pContact->IsIpVerified() ? 1 : 0); } file.Close(); AddDebugLogLine( false, _T("Wrote %ld contact%s to file."), listContacts.size(), ((listContacts.size() == 1) ? _T("") : _T("s"))); } else DebugLogError(_T("Unable to store Kad file: %s"), m_sFilename); } catch (CFileException* e) { e->Delete(); AddDebugLogLine(false, _T("CFileException in CRoutingZone::writeFile")); } }
void CRoutingZone::ReadFile(CString strSpecialNodesdate) { if (m_pSuperZone != NULL || (m_sFilename.IsEmpty() && strSpecialNodesdate.IsEmpty())){ ASSERT( false ); return; } bool bDoHaveVerifiedContacts = false; // Read in the saved contact list. try { CSafeBufferedFile file; CFileException fexp; if (file.Open(strSpecialNodesdate.IsEmpty() ? m_sFilename : strSpecialNodesdate, CFile::modeRead | CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)) { setvbuf(file.m_pStream, NULL, _IOFBF, 32768); // Get how many contacts in the saved list. // NOTE: Older clients put the number of contacts here.. // Newer clients always have 0 here to prevent older clients from reading it. uint32_t uNumContacts = file.ReadUInt32(); uint32_t uVersion = 0; if (uNumContacts == 0) { if (file.GetLength() >= 8){ uVersion = file.ReadUInt32(); if (uVersion == 3){ uint32_t nBoostrapEdition = file.ReadUInt32(); if (nBoostrapEdition == 1){ // this is a special bootstrap-only nodes.dat, handle it in a seperate reading function ReadBootstrapNodesDat(file); file.Close(); return; } } if(uVersion >= 1 && uVersion <= 3) // those version we know, others we ignore uNumContacts = file.ReadUInt32(); } else AddDebugLogLine( false, GetResString(IDS_ERR_KADCONTACTS)); } if (uNumContacts != 0 && uNumContacts * 25 <= (file.GetLength() - file.GetPosition())) { // Hide contact list in the GUI theApp.emuledlg->kademliawnd->HideContacts(); uint32_t uValidContacts = 0; CUInt128 uID; while ( uNumContacts ) { file.ReadUInt128(&uID); uint32_t uIP = file.ReadUInt32(); uint16_t uUDPPort = file.ReadUInt16(); uint16_t uTCPPort = file.ReadUInt16(); byte byType = 0; uint8_t uContactVersion = 0; if(uVersion >= 1) uContactVersion = file.ReadUInt8(); else byType = file.ReadUInt8(); CKadUDPKey kadUDPKey; bool bVerified = false; if(uVersion >= 2){ kadUDPKey.ReadFromFile(file); bVerified = file.ReadUInt8() != 0; if (bVerified) bDoHaveVerifiedContacts = true; } // IP Appears valid if( byType < 4) { uint32_t uhostIP = ntohl(uIP); if (::IsGoodIPPort(uhostIP, uUDPPort)) { if (::theApp.ipfilter->IsFiltered(uhostIP)) { if (::thePrefs.GetLogFilteredIPs()) AddDebugLogLine(false, _T("Ignored kad contact (IP=%s:%u)--read known.dat -- - IP filter (%s)") , ipstr(uhostIP), uUDPPort, ::theApp.ipfilter->GetLastHit()); } else if (uUDPPort == 53 && uContactVersion <= KADEMLIA_VERSION5_48a) /*No DNS Port without encryption*/ { if (::thePrefs.GetLogFilteredIPs()) AddDebugLogLine(false, _T("Ignored kad contact (IP=%s:%u)--read known.dat") , ipstr(uhostIP), uUDPPort); } else { // This was not a dead contact, Inc counter if add was successful if (AddUnfiltered(uID, uIP, uUDPPort, uTCPPort, uContactVersion, kadUDPKey, bVerified, false, true, false)) uValidContacts++; } } } uNumContacts--; } AddLogLine( false, GetResString(IDS_KADCONTACTSREAD), uValidContacts); if (!bDoHaveVerifiedContacts){ DebugLogWarning(_T("No verified contacts found in nodes.dat - might be an old file version. Setting all contacts verified for this time to speed up Kad bootstrapping")); SetAllContactsVerified(); } } file.Close(); } else DebugLogWarning(_T("Unable to read Kad file: %s"), m_sFilename); } catch (CFileException* e) { e->Delete(); DebugLogError(_T("CFileException in CRoutingZone::readFile")); } // Show contact list in GUI theApp.emuledlg->kademliawnd->ShowContacts(); }