bool CAICHSyncThread::ConvertToKnown2ToKnown264(CSafeFile* pTargetFile){ // converting known2.met to known2_64.met to support large files // changing hashcount from uint16 to uint32 // there still exists a lock on known2_64.met and it should be not opened at this point CString oldfullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); oldfullpath.Append(OLD_KNOWN2_MET_FILENAME); CString newfullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); newfullpath.Append(KNOWN2_MET_FILENAME); if (PathFileExists(newfullpath) || !PathFileExists(oldfullpath)){ // only continue if the old file doe and the new file does not exists return false; } CSafeFile oldfile; CFileException fexp; if (!oldfile.Open(oldfullpath,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyNone, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") OLD_KNOWN2_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 -> known2.met also doesn't exists, so nothing to convert return false; } if (!pTargetFile->Open(newfullpath,CFile::modeCreate|CFile::modeReadWrite|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyNone, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") KNOWN2_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; } theApp.QueueLogLine(false, GetResString(IDS_CONVERTINGKNOWN2MET), OLD_KNOWN2_MET_FILENAME, KNOWN2_MET_FILENAME); try { pTargetFile->WriteUInt8(KNOWN2_MET_VERSION); uint32 nHashCount; while (oldfile.GetPosition() < oldfile.GetLength()){ CAICHHash aichHash(&oldfile); nHashCount = oldfile.ReadUInt16(); if (oldfile.GetPosition() + nHashCount*CAICHHash::GetHashSize() > oldfile.GetLength()){ AfxThrowFileException(CFileException::endOfFile, 0, oldfile.GetFileName()); } BYTE* buffer = new BYTE[nHashCount*CAICHHash::GetHashSize()]; oldfile.Read(buffer, nHashCount*CAICHHash::GetHashSize()); pTargetFile->Write(aichHash.GetRawHash(), CAICHHash::GetHashSize()); pTargetFile->WriteUInt32(nHashCount); pTargetFile->Write(buffer, nHashCount*CAICHHash::GetHashSize()); delete[] buffer; } pTargetFile->Flush(); oldfile.Close(); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile){ LogError(LOG_STATUSBAR,GetResString(IDS_ERR_MET_BAD), OLD_KNOWN2_MET_FILENAME); ASSERT( false ); } else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer); } error->Delete(); theApp.QueueLogLine(false, GetResString(IDS_CONVERTINGKNOWN2FAILED)); pTargetFile->Close(); return false; } theApp.QueueLogLine(false, GetResString(IDS_CONVERTINGKNOWN2DONE)); // FIXME LARGE FILES (uncomment) //DeleteFile(oldfullpath); pTargetFile->SeekToBegin(); return true; }
int CAICHSyncThread::Run() { //MORPH START SLUGFILLER: SafeHash CReadWriteLock lock(&theApp.m_threadlock); if (!lock.ReadLock(0)) return 0; // MORPH END SLUGFILLER: SafeHash if ( !theApp.emuledlg->IsRunning() ) return 0; // we need to keep a lock on this file while the thread is running CSingleLock lockKnown2Met(&CAICHRecoveryHashSet::m_mutKnown2File); lockKnown2Met.Lock(); CSafeFile file; bool bJustCreated = ConvertToKnown2ToKnown264(&file); // we collect all masterhashs which we find in the known2.met and store them in a list CList<CAICHHash> liKnown2Hashs; CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR); fullpath.Append(KNOWN2_MET_FILENAME); CFileException fexp; uint32 nLastVerifiedPos = 0; if (!bJustCreated && !file.Open(fullpath,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyNone, &fexp)){ if (fexp.m_cause != CFileException::fileNotFound){ CString strError(_T("Failed to load ") KNOWN2_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; } try { if (file.GetLength() >= 1){ uint8 header = file.ReadUInt8(); if (header != KNOWN2_MET_VERSION){ AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName()); } //setvbuf(file.m_pStream, NULL, _IOFBF, 16384); uint32 nExistingSize = (UINT)file.GetLength(); uint32 nHashCount; while (file.GetPosition() < nExistingSize){ liKnown2Hashs.AddTail(CAICHHash(&file)); nHashCount = file.ReadUInt32(); if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){ AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName()); } // skip the rest of this hashset file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current); nLastVerifiedPos = (UINT)file.GetPosition(); } } else file.WriteUInt8(KNOWN2_MET_VERSION); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile){ LogError(LOG_STATUSBAR,GetResString(IDS_ERR_MET_BAD), KNOWN2_MET_FILENAME); // truncate the file to the size to the last verified valid pos try{ file.SetLength(nLastVerifiedPos); if (file.GetLength() == 0){ file.SeekToBegin(); file.WriteUInt8(KNOWN2_MET_VERSION); } } catch(CFileException* error2){ error2->Delete(); } } else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer); } error->Delete(); return false; } // now we check that all files which are in the sharedfilelist have a corresponding hash in out list // those who don'T are added to the hashinglist CList<CAICHHash> liUsedHashs; CSingleLock sharelock(&theApp.sharedfiles->m_mutWriteList); sharelock.Lock(); bool bDbgMsgCreatingPartHashs = true; for (int i = 0; i < theApp.sharedfiles->GetCount(); i++){ CKnownFile* pCurFile = theApp.sharedfiles->GetFileByIndex(i); if (pCurFile != NULL && !pCurFile->IsPartFile() ) { if (theApp.emuledlg==NULL || !theApp.emuledlg->IsRunning()) // in case of shutdown while still hashing return 0; if (pCurFile->GetFileIdentifier().HasAICHHash()){ bool bFound = false; for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;) { CAICHHash current_hash = liKnown2Hashs.GetNext(pos); if (current_hash == pCurFile->GetFileIdentifier().GetAICHHash()){ bFound = true; liUsedHashs.AddTail(current_hash); pCurFile->SetAICHRecoverHashSetAvailable(true); // Has the file the proper AICH Parthashset? If not probably upgrading, create it if (!pCurFile->GetFileIdentifier().HasExpectedAICHHashCount()) { if (bDbgMsgCreatingPartHashs) { bDbgMsgCreatingPartHashs = false; DebugLogWarning(_T("Missing AICH Part Hashsets for known files - maybe upgrading from earlier version. Creating them out of full AICH Recovery Hashsets, shouldn't take too long")); } CAICHRecoveryHashSet tempHashSet(pCurFile, pCurFile->GetFileSize()); tempHashSet.SetMasterHash(pCurFile->GetFileIdentifier().GetAICHHash(), AICH_HASHSETCOMPLETE); if (!tempHashSet.LoadHashSet()) { ASSERT( false ); DebugLogError(_T("Failed to load full AICH Recovery Hashset - known2.met might be corrupt. Unable to create AICH Part Hashset - %s"), pCurFile->GetFileName()); } else { if (!pCurFile->GetFileIdentifier().SetAICHHashSet(tempHashSet)) { DebugLogError(_T("Failed to create AICH Part Hashset out of full AICH Recovery Hashset - %s"), pCurFile->GetFileName()); ASSERT( false ); } ASSERT(pCurFile->GetFileIdentifier().HasExpectedAICHHashCount()); } } //theApp.QueueDebugLogLine(false, _T("%s - %s"), current_hash.GetString(), pCurFile->GetFileName()); /*#ifdef _DEBUG // in debugmode we load and verify all hashsets CAICHRecoveryHashSet* pTempHashSet = new CAICHRecoveryHashSet(pCurFile); pTempHashSet->SetFileSize(pCurFile->GetFileSize()); pTempHashSet->SetMasterHash(pCurFile->GetFileIdentifier().GetAICHHash(), AICH_HASHSETCOMPLETE) ASSERT( pTempHashSet->LoadHashSet() ); delete pTempHashSet; #endif*/ break; } } if (bFound) // hashset is available, everything fine with this file continue; } pCurFile->SetAICHRecoverHashSetAvailable(false); m_liToHash.AddTail(pCurFile); } } sharelock.Unlock(); // removed all unused AICH hashsets from known2.met if (liUsedHashs.GetCount() != liKnown2Hashs.GetCount() && // EastShare START - Added by TAHO, .met file control /* (!thePrefs.IsRememberingDownloadedFiles() || thePrefs.DoPartiallyPurgeOldKnownFiles())) */ (!thePrefs.IsRememberingDownloadedFiles() || thePrefs.DoPartiallyPurgeOldKnownFiles() || thePrefs.DoCompletlyPurgeOldKnownFiles() || thePrefs.DoRemoveAichImmediatly() ) ) // EastShare END - Added by TAHO, .met file control { file.SeekToBegin(); try { uint8 header = file.ReadUInt8(); if (header != KNOWN2_MET_VERSION){ AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName()); } uint32 nExistingSize = (UINT)file.GetLength(); uint32 nHashCount; ULONGLONG posWritePos = file.GetPosition(); ULONGLONG posReadPos = file.GetPosition(); uint32 nPurgeCount = 0; uint32 nPurgeBecauseOld = 0; while (file.GetPosition() < nExistingSize){ CAICHHash aichHash(&file); nHashCount = file.ReadUInt32(); if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){ AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName()); } if (!thePrefs.IsRememberingDownloadedFiles() && liUsedHashs.Find(aichHash) == NULL) { // unused hashset skip the rest of this hashset file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current); nPurgeCount++; } else if (thePrefs.IsRememberingDownloadedFiles() && theApp.knownfiles->ShouldPurgeAICHHashset(aichHash)) { // EastShare START - Added by TAHO, .met file control /* ASSERT( thePrefs.DoPartiallyPurgeOldKnownFiles() ); */ ASSERT( thePrefs.DoPartiallyPurgeOldKnownFiles() || thePrefs.DoRemoveAichImmediatly()); // EastShare END - Added by TAHO, .met file control // also unused (purged) hashset skip the rest of this hashset file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current); nPurgeCount++; nPurgeBecauseOld++; } else if(nPurgeCount == 0){ // used Hashset, but it does not need to be moved as nothing changed yet file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current); posWritePos = file.GetPosition(); CAICHRecoveryHashSet::AddStoredAICHHash(aichHash); } else{ // used Hashset, move position in file BYTE* buffer = new BYTE[nHashCount*CAICHHash::GetHashSize()]; file.Read(buffer, nHashCount*CAICHHash::GetHashSize()); posReadPos = file.GetPosition(); file.Seek(posWritePos, CFile::begin); file.Write(aichHash.GetRawHash(), CAICHHash::GetHashSize()); file.WriteUInt32(nHashCount); file.Write(buffer, nHashCount*CAICHHash::GetHashSize()); delete[] buffer; posWritePos = file.GetPosition(); file.Seek(posReadPos, CFile::begin); CAICHRecoveryHashSet::AddStoredAICHHash(aichHash); } } posReadPos = file.GetPosition(); file.SetLength(posWritePos); theApp.QueueDebugLogLine(false, _T("Cleaned up known2.met, removed %u hashsets and purged %u hashsets of old known files (%s)") , nPurgeCount - nPurgeBecauseOld, nPurgeBecauseOld, CastItoXBytes(posReadPos-posWritePos)); file.Flush(); file.Close(); } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile){ // we just parsed this files some ms ago, should never happen here ASSERT( false ); } else{ TCHAR buffer[MAX_CFEXP_ERRORMSG]; error->GetErrorMessage(buffer, ARRSIZE(buffer)); LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer); } error->Delete(); return false; } } else { // remember (/index) all hashs which are stored in the file for faster checking lateron for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;) { CAICHRecoveryHashSet::AddStoredAICHHash(liKnown2Hashs.GetNext(pos)); } } lockKnown2Met.Unlock(); // warn the user if he just upgraded if (thePrefs.IsFirstStart() && !m_liToHash.IsEmpty() && !bJustCreated){ LogWarning(GetResString(IDS_AICH_WARNUSER)); } if (!m_liToHash.IsEmpty()){ theApp.QueueLogLine(true, GetResString(IDS_AICH_SYNCTOTAL), m_liToHash.GetCount() ); theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(m_liToHash.GetCount()); // let first all normal hashing be done before starting out synchashing CSingleLock sLock1(&theApp.hashing_mut); // only one filehash at a time while (theApp.sharedfiles->GetHashingCount() != 0){ Sleep(100); if (!CemuleDlg::IsRunning()) return 0; } sLock1.Lock(); uint32 cDone = 0; for (POSITION pos = m_liToHash.GetHeadPosition();pos != 0; cDone++) { if (!CemuleDlg::IsRunning()){ // in case of shutdown while still hashing return 0; } theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(m_liToHash.GetCount()-cDone); if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL) theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount(); CKnownFile* pCurFile = m_liToHash.GetNext(pos); // just to be sure that the file hasnt been deleted lately if (!(theApp.knownfiles->IsKnownFile(pCurFile) && theApp.sharedfiles->GetFileByID(pCurFile->GetFileHash())) ) continue; theApp.QueueLogLine(false, GetResString(IDS_AICH_CALCFILE), pCurFile->GetFileName()); if(!pCurFile->CreateAICHHashSetOnly()) theApp.QueueDebugLogLine(false, _T("Failed to create AICH Hashset while sync. for file %s"), pCurFile->GetFileName()); } theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(0); if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL) theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount(); sLock1.Unlock(); } theApp.QueueDebugLogLine(false, _T("AICHSyncThread finished")); return 0; }
BOOL CTextFile::ReadTextFile( CString& filename, CString& contents ) /* ============================================================ Function : CTextFile::ReadTextFile Description : Will read the contents of the file filename into contents. If filename is empty, the standard file dialog will be displayed, and - if OK is selected - filename will contain the selected filename on return. Return : BOOL - TRUE if OK. GetErrorMessage will contain errors. Parameters : CString& filename - file to read from CString& contents - will be filled with the contents of the file ============================================================*/ { contents = _T( "" ); // Error handling ClearError(); CStdioFile file; CFileException feError; BOOL result = TRUE; if( filename.IsEmpty() ) result = GetFilename( FALSE, filename ); if( result ) { // Reading the file if( file.Open( filename, CFile::modeRead, &feError ) ) { CString line; while( file.ReadString( line ) ) contents += line + m_eol; file.Close(); } else { // Setting error message TCHAR errBuff[256]; feError.GetErrorMessage( errBuff, 256 ); m_error = errBuff; result = FALSE; } } return result; }
BOOL CTextFile::WriteTextFile( CString& filename, const CStringArray& contents ) /* ============================================================ Function : CTextFile::WriteTextFile Description : Writes contents to filename. Will create the file if it doesn't already exist, overwrite it otherwise. If filename is empty, the standard file dialog will be displayed, and - if OK is selected - filename will contain the selected filename on return. Return : BOOL - TRUE if OK. GetErrorMessage will return errors Parameters : CString& filename - file to write to conste CStringArray& contents - contents to write ============================================================*/ { // Error handling ClearError(); CStdioFile file; CFileException feError; BOOL result = TRUE; if( filename.IsEmpty() ) result = GetFilename( TRUE, filename ); if( result ) { // Write file if( file.Open( filename, CFile::modeWrite | CFile::modeCreate, &feError ) ) { int max = contents.GetSize(); for( int t = 0 ; t < max ; t++ ) file.WriteString( contents[ t ] + m_eol ); file.Close(); } else { // Set error message TCHAR errBuff[256]; feError.GetErrorMessage( errBuff, 256 ); m_error = errBuff; result = FALSE; } } return result; }
/** * \brief Get Check Sum * \param[in] omStrConfigFileName reference to File name * \param[out] pucCheckSum Returns computed check sum * \param[out] pucCheckSumInFile : Returns the chechsum in file * \return TRUE for success and FALSE for failure * * This method computes the checksum for a given bytes * in a file. The file is opened and checksum is computed * for all bytes except the last byte. */ BOOL CComputeCheckSum::bGetCheckSum(CString& omStrConfigFileName, UCHAR* pucCheckSum, UCHAR* pucCheckSumInFile) { CStdioFile omStdiofile; CFileException omException ; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bReturn = FALSE; BOOL bFileOpen = FALSE; CString omStrErrorMessage = ""; char acErrorMsg[defSIZE_OF_ERROR_BUFFER]; // Open the configration file. TRY { bFileOpen = omStdiofile.Open(omStrConfigFileName, CFile::modeRead | CFile::typeBinary, &omException); if(bFileOpen!=FALSE) { UCHAR* pucBuff = NULL; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); if( dwSize > 0) { pucBuff = static_cast<UCHAR*> (new UCHAR[dwSize]); if(pucBuff!=NULL) { // Read the whole file and put the content to pucBuff; dwRead = omStdiofile.Read(pucBuff,dwSize); // Compute the checksum bReturn = bComputeCheckSum(pucBuff,dwSize - 1, pucCheckSum); // Get the check sum stored in file ( Last byte ) *pucCheckSumInFile = pucBuff[dwSize-1]; delete [] pucBuff; pucBuff = NULL; } } omStdiofile.Close(); bReturn = TRUE; } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // configuration file open error notification //AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,nZERO); MessageBox(NULL,acErrorMsg, defPROJECT_NAME,MB_OK|MB_ICONERROR|MB_TOPMOST); } } CATCH_ALL(pomE) { if(pomE != NULL ) { // Get the exception error message pomE->GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); //Display the error //AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,nZERO); MessageBox(NULL,acErrorMsg, defPROJECT_NAME,MB_OK|MB_ICONERROR|MB_TOPMOST); } } END_CATCH_ALL return bReturn; }
//##ModelId=474D307E0041 long CFileRecieve::RecieveFileData(ULONG lFileSize, CString csFileName) { CString csFile = CGetSetOptions::GetPath(PATH_REMOTE_FILES); CreateDirectory(csFile, NULL); csFile += m_csRecievingFromIP + "\\"; CreateDirectory(csFile, NULL); nsPath::CPath path(csFileName); csFile += path.GetName(); CFile File; CFileException ex; if(File.Open(csFile, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary, &ex) == FALSE) { TCHAR szError[200]; ex.GetErrorMessage(szError, 200); LogSendRecieveInfo(StrF(_T("Error opening file in RequestCopiedFiles, error: %s"), szError)); return FALSE; } ULONG lBytesRead = 0; long lBytesNeeded = 0; int nPercent = 0; int nPrevPercent = 0; char *pBuffer = new char[CHUNK_WRITE_SIZE]; if(pBuffer == NULL) { LogSendRecieveInfo("Error creating buffer in RequestCopiedFiles"); return FALSE; } BOOL bRet = FALSE; while(true) { lBytesNeeded = CHUNK_WRITE_SIZE; if(lFileSize - lBytesRead < CHUNK_WRITE_SIZE) lBytesNeeded = lFileSize - lBytesRead; if(m_Sock.RecieveExactSize(pBuffer, lBytesNeeded) == FALSE) { break; } File.Write(pBuffer, lBytesNeeded); lBytesRead += lBytesNeeded; if(lBytesRead >= lFileSize) { m_pProgress->SetSingleFilePos(100); bRet = TRUE; break; } if(lBytesNeeded > 0) { nPercent = (int)((lBytesRead / (double)lFileSize) * 100); if((nPercent - nPrevPercent) > 5) { m_pProgress->SetSingleFilePos(nPercent); m_pProgress->PumpMessages(); if(m_pProgress->Cancelled()) { bRet = USER_CANCELED; break; } nPrevPercent = nPercent; } } } File.Close(); if(bRet) { m_RecievedFiles.Add(csFile); } delete []pBuffer; pBuffer = NULL; return bRet; }
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.GetConfigDir()); 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); servermet.WriteUInt32(nextserver->GetIP()); servermet.WriteUInt16(nextserver->GetPort()); uint32 uTagCount = 0; ULONG uTagCountFilePos = (ULONG)servermet.GetPosition(); servermet.WriteUInt32(uTagCount); if (!nextserver->GetListName().IsEmpty()){ if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetListName(), ST_SERVERNAME)) uTagCount++; CTag servername(ST_SERVERNAME, nextserver->GetListName()); servername.WriteTagToFile(&servermet); uTagCount++; } if (!nextserver->GetDynIP().IsEmpty()){ if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetDynIP(), ST_DYNIP)) uTagCount++; CTag serverdynip(ST_DYNIP, nextserver->GetDynIP()); serverdynip.WriteTagToFile(&servermet); uTagCount++; } if (!nextserver->GetDescription().IsEmpty()){ if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetDescription(), ST_DESCRIPTION)) uTagCount++; CTag serverdesc(ST_DESCRIPTION, nextserver->GetDescription()); serverdesc.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetFailedCount()){ CTag serverfail(ST_FAIL, nextserver->GetFailedCount()); serverfail.WriteTagToFile(&servermet); uTagCount++; } if (nextserver->GetPreferences() != SRV_PR_NORMAL){ CTag serverpref(ST_PREFERENCE, nextserver->GetPreferences()); 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); 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++; } 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.GetConfigDir()); CString oldservermet(thePrefs.GetConfigDir()); 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; }
/******************************************************************************* Function Name : bWriteDBHeader Input(s) : - Output : TRUE/FALSE Functionality : Creates a "Unions.h" file and adds union defintions to it. Member of : CMsgSignal Friend of : - Author(s) : Amarnath Shastry Date Created : 15.02.2002 Modifications : Amitesh Bharti, 12.03.2003 changes made to create unions.h structures as per CRH0002 Modifications : Raja N 12.02.2004 Modified to include Sign check for signals and moved some hardcoded strings to Hashdefines.h Modifications : Raja N 18.05.2004 Added two more members in the union to give word and long access of the data array Modifications : Raja N 18.05.2004 Added two more members in the union to give word and long access of the data array Modifications : Anish 21.12.2006 Added code to have header name as header file name in ifndef condition at the begining of *_UNIONS.h file *******************************************************************************/ CString Cluster::bWriteDBHeader(CString omStrActiveDataBase, ETYPE_BUS eBus) { BOOL bRetVal = TRUE; CString omStrPath = EMPTY_STRING; //Add header for ifndef condition CString omStrHeaderString = EMPTY_STRING; CString omStrHeaderFileName = defHEADER_FILE_NAME; char acErrorMsg[defSIZE_OF_ERROR_BUFFER]; CFileException omException ; CStdioFile omHeaderFile; omStrHeaderFileName = omStrActiveDataBase.Left( omStrActiveDataBase.ReverseFind('.') ); omStrHeaderString = omStrHeaderFileName; omStrHeaderFileName += defHEADER_FILE_NAME; TRY { // Open HeaderFile bRetVal = omHeaderFile.Open( omStrHeaderFileName, CFile::modeCreate|CFile::modeWrite|CFile::typeText,&omException); if (bRetVal == FALSE) { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // union.h file open error notification // AfxMessageBox and MessageBox does not work here. So the API // call for MessageBox is used. if (m_bAutoServerMode == FALSE) { ::MessageBox(NULL,acErrorMsg,("BUSMASTER") ,MB_ICONERROR|MB_OK); } } else { int nIndex = omStrHeaderString.ReverseFind(defCHAR_PATH_SEPRATER); int nLength = omStrHeaderString.GetLength(); omStrHeaderString = omStrHeaderString.Right(nLength - nIndex -1); omStrHeaderString.MakeUpper(); CString omStrTemp; omStrTemp.Format(H_FILE_HEADER_START,omStrHeaderString,omStrHeaderString); // Add Header "Help information" omHeaderFile.WriteString(defHELP_INFO_IN_UNIONS); // Add Header "ifndef..." omHeaderFile.WriteString(omStrTemp); // Add Pragma Pack omStrTemp.Format(H_FILE_HEADER_PRAGMA_PACK,omStrHeaderString,omStrHeaderString); omHeaderFile.WriteString(omStrTemp); CString omStrDLC = STR_EMPTY; UINT aunSigStartBit[defMAX_SIGNALS] ; UINT aunLength[defMAX_SIGNALS] ; CStringArray omStrArraySigName; omStrArraySigName.RemoveAll(); BOOL bReturn = FALSE; UINT unSigCount = 0; CString omStrcommandLine = STR_EMPTY; CString omStrSigName = STR_EMPTY; CString omStrdelimiter = STR_EMPTY; list<FRAME_STRUCT> ouFrameList; GetFrames(ouFrameList ); for ( list<FRAME_STRUCT>::iterator unMsgIndex = ouFrameList.begin(); unMsgIndex != ouFrameList.end(); unMsgIndex++) { // Get all signal names. // signal name will be the variable name // of the union of length specified in DB unSigCount = 0; list<SIGNAL_STRUCT> sigList; unMsgIndex->GetSignalList(sigList); //sSIGNALS* pSg = m_psMessages[unMsgIndex].m_psSignals; list<SIGNAL_STRUCT>::iterator itrSig = sigList.begin(); while(itrSig != sigList.end()) { //UINT nSize = omStrArraySigName.GetSize(); /*aunSigStartBit[unSigCount] = (itrSig->m_unStartByte - 1 ) * defBITS_IN_BYTE;*/ aunSigStartBit[unSigCount] = itrSig->m_unStartbit; unSigCount++; //pSg = pSg->m_psNextSignalList; itrSig++; } // Check if there is no signal add one signal declaration // with no name occuppying whole message length. if(sigList.size() > 0 ) { bReturn = bSortSignalStartBitAscend(aunSigStartBit, sigList.size()); if(bReturn == TRUE ) { switch (eBus) { case LIN: // TODO: LIN { bReturn = bFormSigNameAndLength(aunLength, aunSigStartBit, omStrArraySigName, unMsgIndex); } break; default: //This is a general routine which contructs //structure based on message length and its signal length { /* bReturn = bFormSigNameAndLengthJ1939(aunSigStartBit, omStrArraySigName, unMsgIndex);*/ } break; } } } else { CString omFormatString; // If message length is more then four byte // define two signal with no name. UINT unTempLen = unMsgIndex->m_nLength; while (unTempLen > defUINT_SIZE) { omFormatString.Format(defUNION_FORMAT_STRING, defUNSIGNED_INT, STR_EMPTY, defUINT_LENGTH); omStrArraySigName.Add(omFormatString); unSigCount++; unTempLen -= defUINT_SIZE; } UINT unLength = unMsgIndex->m_nLength * defBITS_IN_BYTE - ( unSigCount * defUINT_LENGTH ); omFormatString.Format(defUNION_FORMAT_STRING, defUNSIGNED_INTEGER, STR_EMPTY, unLength); omStrArraySigName.Add(omFormatString); unSigCount = 0; bReturn = TRUE; } // INT nIndex = 0; if(bReturn == TRUE ) { bInsertBusSpecStructures(omHeaderFile, omStrcommandLine, omStrArraySigName, unMsgIndex, LIN); } } // add "#endif.." //omHeaderFile.WriteString(H_FILE_HEADER_END); omStrPath = omStrHeaderFileName; // Close opened file omHeaderFile.Close(); } } CATCH_ALL(pomE) { if(pomE != NULL ) { pomE->GetErrorMessage(acErrorMsg ,sizeof(acErrorMsg) ); bRetVal = FALSE; pomE->Delete(); // union.h file open error notification if (m_bAutoServerMode == FALSE) { ::MessageBox(NULL,acErrorMsg,("BUSMASTER") ,MB_ICONERROR|MB_OK); } } // Close opened file omHeaderFile.Close(); } END_CATCH_ALL return omStrPath; }
// Does: Saves The Picture That Is Stored In The IPicture Object As a Bitmap // ~~~~ (Converts From Any Known Picture Type To a Bitmap / Icon File) // // InPut: sFilePathName - Path And FileName Target To Save // ~~~~~ // // OutPut: TRUE If Succeeded... // ~~~~~~ //----------------------------------------------------------------------------- BOOL CPicture_Ex::SaveAsBitmap(CString sFilePathName) //============================================================================= { BOOL bResult = FALSE; ILockBytes *Buffer = 0; IStorage *pStorage = 0; IStream *FileStream = 0; BYTE *BufferBytes; STATSTG BytesStatistics; DWORD OutData; long OutStream; CFile BitmapFile; CFileException e; double SkipFloat = 0; DWORD ByteSkip = 0; _ULARGE_INTEGER RealData; CreateILockBytesOnHGlobal(NULL, TRUE, &Buffer); // Create ILockBytes Buffer HRESULT hr = ::StgCreateDocfileOnILockBytes(Buffer, STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage); hr = pStorage->CreateStream(L"PICTURE", STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, 0, &FileStream); m_pPict->SaveAsFile(FileStream, TRUE, &OutStream); // Copy Data Stream FileStream->Release(); pStorage->Release(); Buffer->Flush(); // Get Statistics For Final Size Of Byte Array Buffer->Stat(&BytesStatistics, STATFLAG_NONAME); // Cut UnNeeded Data Coming From SaveAsFile() (Leave Only "Pure" Picture Data) SkipFloat = (double(OutStream) / 512); // Must Be In a 512 Blocks... if(SkipFloat > DWORD(SkipFloat)) ByteSkip = (DWORD)SkipFloat + 1; else ByteSkip = (DWORD)SkipFloat; ByteSkip = ByteSkip * 512; // Must Be In a 512 Blocks... // Find Difference Between The Two Values ByteSkip = (DWORD)(BytesStatistics.cbSize.QuadPart - ByteSkip); // Allocate Only The "Pure" Picture Data RealData.LowPart = 0; RealData.HighPart = 0; RealData.QuadPart = ByteSkip; BufferBytes = (BYTE*)malloc(OutStream); if(BufferBytes == NULL) { Buffer->Release(); HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd; MessageBoxEx(hWnd, "Can not allocate enough memory\t", "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH); } Buffer->ReadAt(RealData, BufferBytes, OutStream, &OutData); if(BitmapFile.Open(sFilePathName, CFile::typeBinary | CFile::modeCreate | CFile::modeWrite, &e)) { BitmapFile.Write(BufferBytes, OutData); BitmapFile.Close(); bResult = TRUE; } else // Write File Failed... { TCHAR szCause[255]; e.GetErrorMessage(szCause, 255, NULL); HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd; MessageBoxEx(hWnd, szCause, "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH); bResult = FALSE; } Buffer->Release(); free(BufferBytes); return(bResult); }
// 文件接收回调函数 // return 0 之前,可能没释放内存 pData DWORD WINAPI CXRecvDlg::ProcRecvFile(LPVOID lParam) { CXRecvDlg *pDlg = (CXRecvDlg*)lParam; // LPXTCP_RecvData pData = (LPXTCP_RecvData)lParam; pDlg->m_sockListen = socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == pDlg->m_sockListen) { // 其他错误处理 CString str; str.Format("%d", WSAGetLastError()); ::MessageBox(NULL, str, "Error", MB_OK); return 0; } // end if (INVALID_SOCKET == sock) sockaddr_in sin; sin.sin_addr.s_addr = inet_addr(pDlg->m_xFileInfo.szUIP); sin.sin_family = AF_INET; sin.sin_port = htons(pDlg->m_xFileInfo.dwPort); int len = sizeof(sin); CFile file; CFileException e; file.Open(pDlg->m_xFileInfo.szFullName, CFile::modeWrite|CFile::modeCreate|CFile::shareExclusive, &e); if (e.m_cause != 0) { char *str = new char[1024]; e.GetErrorMessage(str, 1024, NULL); ::MessageBox(NULL, str, "Error", MB_OK); return 0; } int ret = connect(pDlg->m_sockListen, (PSOCKADDR)&sin, len); if (SOCKET_ERROR == ret) { int error = WSAGetLastError(); CString str; str.Format("connect failed:%d", error); ::MessageBox(NULL, str, "Error", MB_OK); return 0; } // 1 接收文件信息 XTCP_FileInfo xInfo; ret = recv(pDlg->m_sockListen, (char*)&xInfo, sizeof(XTCP_FileInfo), 0); if (ret == SOCKET_ERROR ) { CString err; err.Format("接收文件信息 recv failed:%d", WSAGetLastError()); ::MessageBox(NULL, err, "Error", MB_OK); return 0; } int nTotal = 0; char szBuf[1024]; pDlg->m_dwFileLength = xInfo.nFileLength; pDlg->m_bRunning = TRUE; while ((nTotal < xInfo.nFileLength) && pDlg->m_bRunning) { ret = recv(pDlg->m_sockListen, szBuf, 1024, 0); if (SOCKET_ERROR == ret) { CString str; str.Format("%d", WSAGetLastError()); AfxMessageBox(str); break; } if (ret == 0) { pDlg->PostMessage(WM_DEST_CANCEL, 0, 0); break; } file.Write(szBuf, ret); nTotal += ret; pDlg->m_dwRecvLength = nTotal; } if (! pDlg->m_bRunning) { pDlg->PostMessage(WM_RECV_CANCEL); } closesocket(pDlg->m_sockListen); file.Close(); // 3 通知主窗口文件发送成功 // Sleep(2000); return 0; }
void CClientCreditsList::LoadList( bool bFromBakFile ) { CString strFileName; if( bFromBakFile ) strFileName.Format(_T("%s") CLIENTS_MET_FILENAME _T(".bak"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); else strFileName = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + 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); } if(!bFromBakFile) LoadList(true); 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; } BOOL bCreateBackup = TRUE; CString strBakFileName; if(!bFromBakFile) { // everything is ok, lets see if the backup exist... strBakFileName.Format(_T("%s") CLIENTS_MET_FILENAME _T(".bak"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR)); ASSERT(strBakFileName.Right(8).CollateNoCase(_T(".bak.bak"))); DWORD dwBakFileSize = 0; 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 } else { bCreateBackup = FALSE; } UINT count = file.ReadUInt32(); if( count>2000000 ) //[VC-Huby-20080520]: client.met data error ! { file.Close(); if(!bFromBakFile) LoadList(true); return; } m_mapClients.InitHashTable(count+5000); // TODO: should be prime number... and 20% larger if (bCreateBackup) { file.Close(); // close the file before copying DWORD dwFileAttrbute = GetFileAttributes(strBakFileName); dwFileAttrbute &= (~FILE_ATTRIBUTE_READONLY); dwFileAttrbute &= (~FILE_ATTRIBUTE_HIDDEN); SetFileAttributes(strBakFileName,dwFileAttrbute); if (!::CopyFile(strFileName, strBakFileName, FALSE)) LogError(GetResString(IDS_ERR_MAKEBAKCREDITFILE)); else { SetFileAttributes(strBakFileName, FILE_ATTRIBUTE_HIDDEN); } // 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(5, CFile::begin); //set filepointer behind file version+count byte } 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; } //ADDED by fengwen on 2006/12/11 <begin> : 格式出错,删除文件。直接退出函数。 if (newcstruct->nKeySize > MAXPUBKEYSIZE) { file.Close(); OnCorruptedFile(file.GetFilePath()); if(!bFromBakFile) LoadList(true); return; } //ADDED by fengwen on 2006/12/11 <end> : 格式出错,删除文件。直接退出函数。 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(); } }
BOOL CBuildProgram::bCreateMakeFile(CString& omStrMakeFileTemplateName, CString& omStrMakeFileName ) { CStdioFile omStdiofile; CFileException omException ; CString omStrFile = ""; BOOL bReturn = FALSE; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bFileOpen = FALSE; CString omStrErrorMessage = ""; char acErrorMsg[defSIZE_OF_ERROR_BUFFER]; // Open the make file template. TRY { bFileOpen = omStdiofile.Open(omStrMakeFileTemplateName, CFile::modeRead | CFile::typeText, &omException); if(bFileOpen!=FALSE) { CHAR *pcBuff = NULL; CString omTemp = ""; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); pcBuff = (CHAR*) new char[dwSize]; if(pcBuff!=NULL) { // Read the whole file and put the content to pcBuff; dwRead = omStdiofile.Read(pcBuff,dwSize); // Add end of string; *(pcBuff+dwRead) = '\0'; // copy the content to CString object; omStrFile = pcBuff; // Delete the buffer and initialise it to NULL delete [] pcBuff; pcBuff = NULL; char acStrShortPath[1000] ; // Convert long name to short name for GCC compiler dwConvertShortPathName(omStrMakeFileTemplateName,acStrShortPath); omTemp = acStrShortPath; INT nIndex = 0; // Get the path of make file temptate in temp object nIndex = omTemp.ReverseFind('\\'); if(nIndex>=0) { omTemp = omTemp.Left(nIndex); // Replace all occurrence of "<INSTALLDIR>" string with template path omStrFile.Replace(_T("<INSTALLDIR>"),omTemp); } // Replace all occurence of <SRCDIR> and <FILENAME> with source // directory and file name respectively. // Convert long name to short name for GCC compiler dwConvertShortPathName(m_omStrSourceFilename,acStrShortPath); omTemp = acStrShortPath; // ReverseFind() returns a zero based index of last matched // charactor. nIndex = omTemp.ReverseFind('\\'); if(nIndex>=0) { omTemp = omTemp.Left(nIndex); omStrFile.Replace(_T("<SRCDIR>"),omTemp); omTemp = acStrShortPath; // Right() takes zero based index and so -1 omTemp = omTemp.Right(omTemp.GetLength() - nIndex -1); omTemp = omTemp.Left(omTemp.ReverseFind('.')); //omTemp.Replace(".c",""); omStrFile.Replace(_T("<FILENAME>"),omTemp); bReturn = TRUE; } } omStdiofile.Close(); } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // make file template open error notification // AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); m_omStrArray.Add(acErrorMsg); bAddString(m_omStrArray); } if(bReturn == TRUE) { bFileOpen = omStdiofile.Open( omStrMakeFileName, CFile::modeCreate | CFile::modeWrite, &omException); if(bFileOpen!=FALSE) { //AfxMessageBox(omStrFile); omStdiofile.WriteString(omStrFile); omStdiofile.Close(); } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); //AfxMessageBox(acErrorMsg , // MB_ICONERROR| MB_SYSTEMMODAL|MB_OK, // 0); m_omStrArray.Add(acErrorMsg); bAddString(m_omStrArray); bReturn = FALSE; } } } CATCH_ALL(pomE) { if(pomE != NULL ) { // Get the exception error message pomE->GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); omStrErrorMessage = acErrorMsg; //Display the error //AfxMessageBox(omStrErrorMessage , // MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); m_omStrArray.Add(acErrorMsg); bAddString(m_omStrArray); pomE->Delete(); } bReturn = FALSE; } END_CATCH_ALL return bReturn; }
// CCloneDetectorGUIApp initialization void CCloneDetectorGUIApp::readFragFromFile(const CString &infile, CString &fragStr) { fragStr = ""; /* FILE *fStream; errno_t err; char *f = ( char *)(LPCTSTR)infile; strcpy(f,(const char *)(LPCTSTR)infile); fStream = fopen("C:\\Users\\benfung\\AppData\\Local\\Temp\\temFrag.ext", "r"); if(fStream != NULL) { fseek(fStream,0,SEEK_END); int size = ftell(fStream); fseek(fStream,0, SEEK_SET); //char * buffer = (char*) malloc(size); fread(fragStr.GetBuffer(size),1,size,fStream); fragStr.ReleaseBuffer(size); fclose(fStream); } else { CString err; err.Format(_T("Error open framgment file %s"),f); AfxMessageBox(err); } */ CFile file; CFileException ex; if( !file.Open((LPCTSTR)infile,CFile::modeRead | CFile::shareDenyWrite, &ex)) { TCHAR szError[1024]; ex.GetErrorMessage(szError, 1024); TRACE1("Couldn't open source file: %s\n", szError); return; } else { file.SeekToBegin(); bool done = false; while(!done) { char buf[1025] = {0}; UINT nRead = file.Read(buf,1024); if( nRead < 1024) { done = true; }; buf[nRead] = '\0'; fragStr += CString(buf); } /* UINT nBytes = (UINT)file.GetLength(); int nChars = nBytes / sizeof(TCHAR); nBytes = file.Read(fragStr.GetBuffer(nChars), nBytes); fragStr.ReleaseBuffer(nChars); */ } file.Close(); }
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 CComputeCheckSum::setCheckSum(CString& omStrConfigFileName, UCHAR* pucCheckSum) { CStdioFile omStdiofile; CFileException omException ; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bReturn = FALSE; BOOL bFileOpen = FALSE; CString omStrStrErrorMessage = ""; char acErrorMsg[defSIZE_OF_ERROR_BUFFER]; // Open the configration file template. TRY { bFileOpen = omStdiofile.Open(omStrConfigFileName, CFile::modeReadWrite| CFile::typeBinary, &omException); if(bFileOpen!=FALSE) { UCHAR* pucBuff = NULL; UCHAR ucCheckSum = 0; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); pucBuff = static_cast<UCHAR*> (new UCHAR[dwSize]); if(pucBuff!=NULL) { // Read the whole file and put the content to pucBuff; dwRead = omStdiofile.Read(pucBuff,dwSize); // compute the checksum bReturn = computeCheckSum(pucBuff,dwSize, &ucCheckSum); if(bReturn == TRUE) { // Seek to the last byte to store checksum omStdiofile.Seek(dwSize,CFile::begin); // Write one byte checksum omStdiofile.Write(&ucCheckSum,1); // return the checksum if(pucCheckSum!= NULL ) { *pucCheckSum = ucCheckSum; } else { bReturn = FALSE; } } delete [] pucBuff; pucBuff = NULL; } omStdiofile.Close(); } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // configuration file open error notification MessageBox(NULL, acErrorMsg, defPROJECT_NAME, MB_OK | MB_ICONERROR | MB_SYSTEMMODAL); //AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); } } CATCH_ALL(pomE) { if(pomE != NULL ) { // Get the exception error message pomE->GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); //Display the error MessageBox(NULL, acErrorMsg, defPROJECT_NAME, MB_OK | MB_ICONERROR | MB_SYSTEMMODAL); //AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); pomE->Delete(); } } END_CATCH_ALL return bReturn; }
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()){ CString listname; listname.Format(_T("Server %s"), newserver->GetAddress()); newserver->SetListName(listname); } if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(newserver, 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; }