void CQueueListCtrl::OnGetDispInfo(NMHDR *pNMHDR, LRESULT *pResult) { NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR); if (g_App.m_pMDlg->IsRunning()) { // Although we have an owner drawn listview control we store the text for the primary item in the listview, to be // capable of quick searching those items via the keyboard. Because our listview items may change their contents, // we do this via a text callback function. The listview control will send us the LVN_DISPINFO notification if // it needs to know the contents of the primary item. // // But, the listview control sends this notification all the time, even if we do not search for an item. At least // this notification is only sent for the visible items and not for all items in the list. Though, because this // function is invoked *very* often, no *NOT* put any time consuming code here in. if ((pDispInfo->item.mask & LVIF_TEXT) != 0) { // Check for own search request, the rest of the flood comes from list control // and isn't used as list is drawn by us if (pDispInfo->item.cchTextMax == ML_SEARCH_SZ) { CUpDownClient *pClient = reinterpret_cast<CUpDownClient*>(pDispInfo->item.lParam); if (pClient != NULL) { switch (pDispInfo->item.iSubItem) { case QLCOL_USERNAME: _tcsncpy(pDispInfo->item.pszText, pClient->GetUserName(), pDispInfo->item.cchTextMax); pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0'); break; case QLCOL_COUNTRY: _tcsncpy(pDispInfo->item.pszText, pClient->GetCountryName(), pDispInfo->item.cchTextMax); pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0'); break; case QLCOL_FILENAME: { CKnownFile *pKnownFile = g_App.m_pSharedFilesList->GetFileByID(pClient->m_reqFileHash); if (pKnownFile != NULL) { _tcsncpy(pDispInfo->item.pszText, pKnownFile->GetFileName(), pDispInfo->item.cchTextMax); pDispInfo->item.pszText[pDispInfo->item.cchTextMax - 1] = _T('\0'); break; } } default: pDispInfo->item.pszText[0] = _T('\0'); break; } } } else if (pDispInfo->item.cchTextMax != 0) pDispInfo->item.pszText[0] = _T('\0'); } } *pResult = 0; }
void CMMServer::ProcessPreviewRequest(CMMData* data, CMMSocket* sender){ uint8 byFileType = data->ReadByte(); uint8 byFileIndex = data->ReadByte(); uint16 nDisplayWidth = data->ReadShort(); uint8 nNumber = data->ReadByte(); CKnownFile* knownfile = NULL; bool bError = false; if (byFileType == MMT_PARTFILFE){ if (byFileIndex >= m_SentFileList.GetSize() || !theApp.downloadqueue->IsPartFile(m_SentFileList[byFileIndex])) { bError = true; } else knownfile = m_SentFileList[byFileIndex]; } else if (byFileType == MMT_FINISHEDFILE){ if (byFileIndex >= m_SentFinishedList.GetSize() || !theApp.knownfiles->IsKnownFile(m_SentFinishedList[byFileIndex])) { bError = true; } else knownfile = m_SentFinishedList[byFileIndex]; } if (!bError){ if (h_timer != 0) bError = true; else{ h_timer = SetTimer(0,0,20000,CommandTimer); if (!h_timer){ bError = true; } else{ if (nDisplayWidth > 140) nDisplayWidth = 140; m_byPendingCommand = MMT_PREVIEW; m_pPendingCommandSocket = sender; if (!knownfile->GrabImage(1,(nNumber+1)*50.0,true,nDisplayWidth,this)) PreviewFinished(NULL,0); } } } if (bError){ CMMPacket* packet = new CMMPacket(MMP_GENERALERROR); sender->SendPacket(packet); ASSERT ( false ); return; } }
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; } }
bool CUploadQueue::CheckForTimeOver(CUpDownClient* client){ //If we have nobody in the queue, do NOT remove the current uploads.. //This will save some bandwidth and some unneeded swapping from upload/queue/upload.. if ( waitinglist.IsEmpty() || client->GetFriendSlot() ) return false; if(client->HasCollectionUploadSlot()){ CKnownFile* pDownloadingFile = theApp.sharedfiles->GetFileByID(client->requpfileid); if(pDownloadingFile == NULL) return true; if (CCollection::HasCollectionExtention(pDownloadingFile->GetFileName()) && pDownloadingFile->GetFileSize() < (uint64)MAXPRIORITYCOLL_SIZE) return false; else{ if (thePrefs.GetLogUlDlEvents()) AddDebugLogLine(DLP_HIGH, false, _T("%s: Upload session ended - client with Collection Slot tried to request blocks from another file"), client->GetUserName()); return true; } } if (!thePrefs.TransferFullChunks()){ if( client->GetUpStartTimeDelay() > SESSIONMAXTIME){ // Try to keep the clients from downloading for ever if (thePrefs.GetLogUlDlEvents()) AddDebugLogLine(DLP_LOW, false, _T("%s: Upload session ended due to max time %s."), client->GetUserName(), CastSecondsToHM(SESSIONMAXTIME/1000)); return true; } // Cache current client score const uint32 score = client->GetScore(true, true); // Check if another client has a bigger score if (score < GetMaxClientScore() && m_dwRemovedClientByScore < GetTickCount()) { if (thePrefs.GetLogUlDlEvents()) AddDebugLogLine(DLP_VERYLOW, false, _T("%s: Upload session ended due to score."), client->GetUserName()); //Set timer to prevent to many uploadslot getting kick do to score. //Upload slots are delayed by a min of 1 sec and the maxscore is reset every 5 sec. //So, I choose 6 secs to make sure the maxscore it updated before doing this again. m_dwRemovedClientByScore = GetTickCount()+SEC2MS(6); return true; } } else{ // Allow the client to download a specified amount per session if( client->GetQueueSessionPayloadUp() > SESSIONMAXTRANS ){ if (thePrefs.GetLogUlDlEvents()) AddDebugLogLine(DLP_DEFAULT, false, _T("%s: Upload session ended due to max transferred amount. %s"), client->GetUserName(), CastItoXBytes(SESSIONMAXTRANS, false, false)); return true; } } return false; }
BOOL CUpdateInfo::DeleteUpdate(CString hash) { uchar UpdateHash[16]; CPartFile* pPartFile; if(!strmd4(hash,UpdateHash)) { return FALSE; } CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(UpdateHash); try { //共享列表中是否有 if(file) { if(file->IsPartFile()) { //共享列表有,但未下载完,移除 pPartFile = DYNAMIC_DOWNCAST(CPartFile,file); if( pPartFile ) { pPartFile->DeleteFile(); } } else { //共享列表有,已经下载完成未安装,移除 DeleteFile(file->GetFilePath()); theApp.emuledlg->sharedfileswnd->sharedfilesctrl.RemoveFile(file); CGlobalVariable::sharedfiles->RemoveFile(file); } } if ((pPartFile = CGlobalVariable::downloadqueue->GetFileByID(UpdateHash)) != NULL) { //共享列表没有,但未下载完,移除 pPartFile->DeleteFile(); } } catch (CException* e) { e->Delete(); return FALSE; } return FALSE; }
bool CUploadQueue::RemoveFromUploadQueue(CUpDownClient* client, LPCTSTR pszReason, bool updatewindow, bool earlyabort){ bool result = false; uint32 slotCounter = 1; for (POSITION pos = uploadinglist.GetHeadPosition();pos != 0;){ POSITION curPos = pos; CUpDownClient* curClient = uploadinglist.GetNext(pos); if (client == curClient){ if (updatewindow) theApp.emuledlg->transferwnd->uploadlistctrl.RemoveClient(client); if (thePrefs.GetLogUlDlEvents()) AddDebugLogLine(DLP_DEFAULT, true,_T("Removing client from upload list: %s Client: %s Transferred: %s SessionUp: %s QueueSessionPayload: %s In buffer: %s Req blocks: %i File: %s"), pszReason==NULL ? _T("") : pszReason, client->DbgGetClientInfo(), CastSecondsToHM( client->GetUpStartTimeDelay()/1000), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false), CastItoXBytes(client->GetPayloadInBuffer()), client->GetNumberOfRequestedBlocksInQueue(), (theApp.sharedfiles->GetFileByID(client->GetUploadFileID())?theApp.sharedfiles->GetFileByID(client->GetUploadFileID())->GetFileName():_T(""))); client->m_bAddNextConnect = false; uploadinglist.RemoveAt(curPos); bool removed = theApp.uploadBandwidthThrottler->RemoveFromStandardList(client->socket); bool pcRemoved = theApp.uploadBandwidthThrottler->RemoveFromStandardList((CClientReqSocket*)client->m_pPCUpSocket); (void)removed; (void)pcRemoved; //if(thePrefs.GetLogUlDlEvents() && !(removed || pcRemoved)) { // AddDebugLogLine(false, _T("UploadQueue: Didn't find socket to delete. Adress: 0x%x"), client->socket); //} if(client->GetSessionUp() > 0) { ++successfullupcount; totaluploadtime += client->GetUpStartTimeDelay()/1000; } else if(earlyabort == false) ++failedupcount; CKnownFile* requestedFile = theApp.sharedfiles->GetFileByID(client->GetUploadFileID()); if(requestedFile != NULL) { requestedFile->UpdatePartsInfo(); } theApp.clientlist->AddTrackClient(client); // Keep track of this client client->SetUploadState(US_NONE); client->ClearUploadBlockRequests(); client->SetCollectionUploadSlot(false); m_iHighestNumberOfFullyActivatedSlotsSinceLastCall = 0; result = true; } else { curClient->SetSlotNumber(slotCounter); slotCounter++; } } return result; }
void CSharedFilesCtrl::OnRename( wxCommandEvent& WXUNUSED(event) ) { int item = GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED ); if ( item != -1 ) { CKnownFile* file = (CKnownFile*)GetItemData(item); wxString strNewName = ::wxGetTextFromUser( _("Enter new name for this file:"), _("File rename"), file->GetFileName().GetPrintable()); CPath newName = CPath(strNewName); if (newName.IsOk() && (newName != file->GetFileName())) { theApp->sharedfiles->RenameFile(file, newName); } } }
void CSharedFilesCtrl::OnAddCollection( wxCommandEvent& WXUNUSED(evt) ) { int item = GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED ); if (item != -1) { CKnownFile *file = reinterpret_cast<CKnownFile*>(GetItemData(item)); wxString CollectionFile = file->GetFilePath().JoinPaths(file->GetFileName()).GetRaw(); CMuleCollection my_collection; if (my_collection.Open( (std::string)CollectionFile.mb_str() )) { //#warning This is probably not working on Unicode for (size_t e = 0; e < my_collection.size(); ++e) { theApp->downloadqueue->AddLink(wxString(my_collection[e].c_str(), wxConvUTF8)); } } } }
BOOL CCommentDialog::OnApply() { if (!m_bDataChanged) { CString strComment; GetDlgItem(IDC_CMT_TEXT)->GetWindowText(strComment); int iRating = m_ratebox.GetCurSel(); for (int i = 0; i < m_paFiles->GetSize(); i++) { CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*m_paFiles)[i]); if (!strComment.IsEmpty() || !m_bMergedComment) file->SetFileComment(strComment); if (iRating != -1) file->SetFileRating(iRating); } } return CResizablePage::OnApply(); }
void CUploadListCtrl::OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMLVGETINFOTIP>(pNMHDR); if (pGetInfoTip->iSubItem == 0) { LVHITTESTINFO hti = {0}; ::GetCursorPos(&hti.pt); ScreenToClient(&hti.pt); if (SubItemHitTest(&hti) == -1 || hti.iItem != pGetInfoTip->iItem || hti.iSubItem != 0){ // don' show the default label tip for the main item, if the mouse is not over the main item if ((pGetInfoTip->dwFlags & LVGIT_UNFOLDED) == 0 && pGetInfoTip->cchTextMax > 0 && pGetInfoTip->pszText[0] != '\0') pGetInfoTip->pszText[0] = '\0'; return; } const CUpDownClient* client = (CUpDownClient*)GetItemData(pGetInfoTip->iItem); if (client && pGetInfoTip->pszText && pGetInfoTip->cchTextMax > 0) { CString info; CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID()); // build info text and display it info.Format(GetResString(IDS_USERINFO), client->GetUserName()); if (file) { info += GetResString(IDS_SF_REQUESTED) + _T(" ") + CString(file->GetFileName()) + _T("\n"); CString stat; stat.Format(GetResString(IDS_FILESTATS_SESSION)+GetResString(IDS_FILESTATS_TOTAL), file->statistic.GetAccepts(), file->statistic.GetRequests(), CastItoXBytes(file->statistic.GetTransferred(), false, false), file->statistic.GetAllTimeAccepts(), file->statistic.GetAllTimeRequests(), CastItoXBytes(file->statistic.GetAllTimeTransferred(), false, false) ); info += stat; } else { info += GetResString(IDS_REQ_UNKNOWNFILE); } _tcsncpy(pGetInfoTip->pszText, info, pGetInfoTip->cchTextMax); pGetInfoTip->pszText[pGetInfoTip->cchTextMax-1] = _T('\0'); } } *pResult = 0; }
BOOL CCommentDialog::OnSetActive() { if (!CResizablePage::OnSetActive()) return FALSE; if (m_bDataChanged) { int iRating = -1; m_bMergedComment = false; CString strComment; for (int i = 0; i < m_paFiles->GetSize(); i++) { CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*m_paFiles)[i]); if (i == 0) { strComment = file->GetFileComment(); iRating = file->GetFileRating(); } else { if (!m_bMergedComment && strComment.Compare(file->GetFileComment()) != 0) { strComment.Empty(); m_bMergedComment = true; } if (iRating != -1 && (UINT)iRating != file->GetFileRating()) iRating = -1; } } m_bSelf = true; SetDlgItemText(IDC_CMT_TEXT, strComment); ((CEdit*)GetDlgItem(IDC_CMT_TEXT))->SetLimitText(MAXFILECOMMENTLEN); m_ratebox.SetCurSel(iRating); m_bSelf = false; m_bDataChanged = false; RefreshData(); } return TRUE; }
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; }
BOOL CCommentDialog::OnApply() { if (m_bEnabled && !m_bDataChanged) { CString strComment; GetDlgItem(IDC_CMT_TEXT)->GetWindowText(strComment); int iRating = m_ratebox.GetCurSel(); for (int i = 0; i < m_paFiles->GetSize(); i++) { if (!(*m_paFiles)[i]->IsKindOf(RUNTIME_CLASS(CKnownFile))) continue; CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*m_paFiles)[i]); if (theApp.sharedfiles->GetFileByID(file->GetFileHash()) == NULL) continue; if (!strComment.IsEmpty() || !m_bMergedComment) file->SetFileComment(strComment); if (iRating != -1) file->SetFileRating(iRating); } } return CResizablePage::OnApply(); }
BOOL CED2kLinkDlg::OnSetActive() { if (!CResizablePage::OnSetActive()) return FALSE; if (m_bDataChanged) { //hashsetlink - check if at least one file has a hasset BOOL bShowHashset = FALSE; BOOL bShowAICH = FALSE; BOOL bShowHTML = FALSE; for (int i = 0; i != m_paFiles->GetSize(); i++){ if (!(*m_paFiles)[i]->IsKindOf(RUNTIME_CLASS(CKnownFile))) continue; bShowHTML = TRUE; CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*m_paFiles)[i]); if (file->GetFileIdentifier().GetAvailableMD4PartHashCount() > 0 && file->GetFileIdentifier().HasExpectedMD4HashCount()) { bShowHashset = TRUE; } if (file->GetFileIdentifier().HasAICHHash()) { bShowAICH = TRUE; } if (bShowHashset && bShowAICH) break; } GetDlgItem(IDC_LD_HASHSETCHE)->EnableWindow(bShowHashset); if (!bShowHashset) ((CButton*)GetDlgItem(IDC_LD_HASHSETCHE))->SetCheck(BST_UNCHECKED); GetDlgItem(IDC_LD_HTMLCHE)->EnableWindow(bShowHTML); UpdateLink(); m_bDataChanged = false; } return TRUE; }
void CED2kLinkDlg::UpdateLink() { CString strLinks; CString strBuffer; const bool bHashset = ((CButton*)GetDlgItem(IDC_LD_HASHSETCHE))->GetCheck() == BST_CHECKED; const bool bHTML = ((CButton*)GetDlgItem(IDC_LD_HTMLCHE))->GetCheck() == BST_CHECKED; const bool bSource = ((CButton*)GetDlgItem(IDC_LD_SOURCECHE))->GetCheck() == BST_CHECKED && theApp.IsConnected() && theApp.GetPublicIP() != 0 && !theApp.IsFirewalled(); const bool bHostname = ((CButton*)GetDlgItem(IDC_LD_HOSTNAMECHE))->GetCheck() == BST_CHECKED && theApp.IsConnected() && !theApp.IsFirewalled() && !thePrefs.GetYourHostname().IsEmpty() && thePrefs.GetYourHostname().Find(_T('.')) != -1; for (int i = 0; i != m_paFiles->GetSize(); i++) { if (!(*m_paFiles)[i]->IsKindOf(RUNTIME_CLASS(CKnownFile))) continue; if (!strLinks.IsEmpty()) strLinks += _T("\r\n\r\n"); CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*m_paFiles)[i]); strLinks += file->GetED2kLink(bHashset, bHTML, bHostname, bSource, theApp.GetPublicIP()); } m_ctrlLinkEdit.SetWindowText(strLinks); }
BOOL CCommentDialog::OnSetActive() { if (!CResizablePage::OnSetActive()) return FALSE; if (m_bDataChanged) { bool bContainsSharedKnownFile = false;; int iRating = -1; m_bMergedComment = false; CString strComment; for (int i = 0; i < m_paFiles->GetSize(); i++) { if (!(*m_paFiles)[i]->IsKindOf(RUNTIME_CLASS(CKnownFile))) continue; CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*m_paFiles)[i]); // we actually could show, add and even search for comments on kad for known but not shared files, // but we don't publish coments entered by the user if the file is not shared (which might be changed at some point) // so make sure we don't let him think he can comment and disable the dialog for such files if (theApp.sharedfiles->GetFileByID(file->GetFileHash()) == NULL) continue; bContainsSharedKnownFile = true; if (i == 0) { strComment = file->GetFileComment(); iRating = file->GetFileRating(); } else { if (!m_bMergedComment && strComment.Compare(file->GetFileComment()) != 0) { strComment.Empty(); m_bMergedComment = true; } if (iRating != -1 && (UINT)iRating != file->GetFileRating()) iRating = -1; } } m_bSelf = true; SetDlgItemText(IDC_CMT_TEXT, strComment); ((CEdit*)GetDlgItem(IDC_CMT_TEXT))->SetLimitText(MAXFILECOMMENTLEN); m_ratebox.SetCurSel(iRating); m_bSelf = false; EnableDialog(bContainsSharedKnownFile); m_bDataChanged = false; RefreshData(); } return TRUE; }
void CQueueListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { if( !theApp.emuledlg->IsRunning() ) return; if (!lpDrawItemStruct->itemData) return; CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC); BOOL bCtrlFocused = ((GetFocus() == this ) || (GetStyle() & LVS_SHOWSELALWAYS)); if (lpDrawItemStruct->itemState & ODS_SELECTED) { if(bCtrlFocused) odc->SetBkColor(m_crHighlight); else odc->SetBkColor(m_crNoHighlight); } else odc->SetBkColor(GetBkColor()); const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData; CMemDC dc(odc, &lpDrawItemStruct->rcItem); CFont* pOldFont = dc.SelectObject(GetFont()); CRect cur_rec(lpDrawItemStruct->rcItem); COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText); int iOldBkMode; if (m_crWindowTextBk == CLR_NONE) { DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0); iOldBkMode = dc.SetBkMode(TRANSPARENT); } else iOldBkMode = OPAQUE; CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID()); CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl(); int iCount = pHeaderCtrl->GetItemCount(); cur_rec.right = cur_rec.left - 8; cur_rec.left += 4; CString Sbuffer; for(int iCurrent = 0; iCurrent < iCount; iCurrent++) { int iColumn = pHeaderCtrl->OrderToIndex(iCurrent); if( !IsColumnHidden(iColumn) ) { cur_rec.right += GetColumnWidth(iColumn); switch(iColumn) { case 0: { uint8 image; if (client->IsFriend()) image = 4; else if (client->GetClientSoft() == SO_EDONKEYHYBRID) { //==> Xman CreditSystem [shadow2004] if (client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) image = 8; else image = 7; } else if (client->GetClientSoft() == SO_MLDONKEY) { if (client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) image = 6; else image = 5; } else if (client->GetClientSoft() == SO_SHAREAZA) { if(client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) image = 10; else image = 9; } else if (client->GetClientSoft() == SO_AMULE) { if(client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) image = 12; else image = 11; } else if (client->GetClientSoft() == SO_LPHANT) { if(client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) image = 14; else image = 13; } else if (client->ExtProtocolAvailable()) { if(client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) //==>Modversion [shadow2004] #ifdef MODVERSION image = (client->IsNextEMF())?16:3; #else //Modversion image = 3; #endif //Modversion //<==Modversion [shadow2004] else //==>Modversion [shadow2004] #ifdef MODVERSION image = (client->IsNextEMF())?16:1; #else //Modversion image = 1; #endif //Modversion //<==Modversion [shadow2004] } else { if (client->credits->GetScoreRatio(client/*->GetIP()*/) > 1) //==> Xman CreditSystem [shadow2004] image = 2; else image = 0; } POINT point = {cur_rec.left, cur_rec.top+1}; imagelist.Draw(dc,image, point, ILD_NORMAL | ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED) ? INDEXTOOVERLAYMASK(1) : 0)); Sbuffer = client->GetUserName(); cur_rec.left +=20; dc.DrawText(Sbuffer,Sbuffer.GetLength(),&cur_rec,DLC_DT_TEXT); cur_rec.left -=20; break; } case 1: if(file) Sbuffer = file->GetFileName(); else Sbuffer = _T("?"); break; case 2: if(file) { switch (file->GetUpPriority()) { case PR_VERYLOW : { Sbuffer = GetResString(IDS_PRIOVERYLOW); break; } case PR_LOW : { if( file->IsAutoUpPriority() ) Sbuffer = GetResString(IDS_PRIOAUTOLOW); else Sbuffer = GetResString(IDS_PRIOLOW); break; } case PR_NORMAL : { if( file->IsAutoUpPriority() ) Sbuffer = GetResString(IDS_PRIOAUTONORMAL); else Sbuffer = GetResString(IDS_PRIONORMAL); break; } case PR_HIGH : { if( file->IsAutoUpPriority() ) Sbuffer = GetResString(IDS_PRIOAUTOHIGH); else Sbuffer = GetResString(IDS_PRIOHIGH); break; } case PR_VERYHIGH : { Sbuffer = GetResString(IDS_PRIORELEASE); break; } default: Sbuffer.Empty(); } } else Sbuffer = _T("?"); break; case 3: Sbuffer.Format(_T("%i"),client->GetScore(false,false,true)); break; case 4: if (client->HasLowID()) { if (client->m_bAddNextConnect) Sbuffer.Format(_T("%i ****"),client->GetScore(false)); else Sbuffer.Format(_T("%i LowID"),client->GetScore(false)); } else Sbuffer.Format(_T("%i"),client->GetScore(false)); break; case 5: Sbuffer.Format(_T("%i"),client->GetAskedCount()); break; case 6: Sbuffer = CastSecondsToHM((::GetTickCount() - client->GetLastUpRequest())/1000); break; case 7: Sbuffer = CastSecondsToHM((::GetTickCount() - client->GetWaitStartTime())/1000); break; case 8: if(client->IsBanned()) Sbuffer = GetResString(IDS_YES); else Sbuffer = GetResString(IDS_NO); break; case 9: if( client->GetUpPartCount()) { cur_rec.bottom--; cur_rec.top++; client->DrawUpStatusBar(dc,&cur_rec,false); cur_rec.bottom++; cur_rec.top--; } break; //==>Modversion [shadow2004] #ifdef MODVERSION case 10: Sbuffer = client->GetClientSoftVer(); break; #endif //Modversion //<==Modversion [shadow2004] }
int CAICHSyncThread::Run() { if ( !theApp.emuledlg->IsRunning() ) return 0; // we need to keep a lock on this file while the thread is running CSingleLock lockKnown2Met(&CAICHHashSet::m_mutKnown2File); lockKnown2Met.Lock(); // we collect all masterhashs which we find in the known2.met and store them in a list CList<CAICHHash> liKnown2Hashs; CString fullpath=thePrefs.GetConfigDir(); fullpath.Append(KNOWN2_MET_FILENAME); CSafeFile file; CFileException fexp; uint32 nLastVerifiedPos = 0; if (!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 { //setvbuf(file.m_pStream, NULL, _IOFBF, 16384); uint32 nExistingSize = (UINT)file.GetLength(); uint16 nHashCount; while (file.GetPosition() < nExistingSize){ liKnown2Hashs.AddTail(CAICHHash(&file)); nHashCount = file.ReadUInt16(); 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(); } } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile){ LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_BAD)); // truncate the file to the size to the last verified valid pos try{ file.SetLength(nLastVerifiedPos); } 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 how don'T are added to the hashinglist CList<CAICHHash> liUsedHashs; CSingleLock sharelock(&theApp.sharedfiles->m_mutWriteList); sharelock.Lock(); for (uint32 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->GetAICHHashset()->GetStatus() == AICH_HASHSETCOMPLETE){ bool bFound = false; for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;) { CAICHHash current_hash = liKnown2Hashs.GetNext(pos); if (current_hash == pCurFile->GetAICHHashset()->GetMasterHash()){ bFound = true; liUsedHashs.AddTail(current_hash); //theApp.QueueDebugLogLine(false, _T("%s - %s"), current_hash.GetString(), pCurFile->GetFileName()); #ifdef _DEBUG // in debugmode we load and verify all hashsets ASSERT( pCurFile->GetAICHHashset()->LoadHashSet() ); // pCurFile->GetAICHHashset()->DbgTest(); pCurFile->GetAICHHashset()->FreeHashSet(); #endif break; } } if (bFound) // hashset is available, everything fine with this file continue; } pCurFile->GetAICHHashset()->SetStatus(AICH_ERROR); m_liToHash.AddTail(pCurFile); } } sharelock.Unlock(); // removed all unused AICH hashsets from known2.met if (!thePrefs.IsRememberingDownloadedFiles() && liUsedHashs.GetCount() != liKnown2Hashs.GetCount()){ file.SeekToBegin(); try { uint32 nExistingSize = (UINT)file.GetLength(); uint16 nHashCount; ULONGLONG posWritePos = 0; ULONGLONG posReadPos = 0; uint32 nPurgeCount = 0; while (file.GetPosition() < nExistingSize){ CAICHHash aichHash(&file); nHashCount = file.ReadUInt16(); if (file.GetPosition() + nHashCount*CAICHHash::GetHashSize() > nExistingSize){ AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName()); } if (liUsedHashs.Find(aichHash) == NULL){ // unused hashset skip the rest of this hashset file.Seek(nHashCount*CAICHHash::GetHashSize(), CFile::current); nPurgeCount++; } 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(); } 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.WriteUInt16(nHashCount); file.Write(buffer, nHashCount*CAICHHash::GetHashSize()); delete[] buffer; posWritePos = file.GetPosition(); file.Seek(posReadPos, CFile::begin); } } posReadPos = file.GetPosition(); file.SetLength(posWritePos); theApp.QueueDebugLogLine(false, _T("Cleaned up known2.met, removed %u hashsets (%s)"), nPurgeCount, 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; } } lockKnown2Met.Unlock(); // warn the user if he just upgraded if (thePrefs.IsFirstStart() && !m_liToHash.IsEmpty()){ 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); } sLock1.Lock(); uint32 cDone = 0; for (POSITION pos = m_liToHash.GetHeadPosition();pos != 0; cDone++) { if (theApp.emuledlg==NULL || !theApp.emuledlg->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; }
/** * Add a client to the waiting queue for uploads. * * @param client address of the client that should be added to the waiting queue * * @param bIgnoreTimelimit don't check time limit to possibly ban the client. */ void CUploadQueue::AddClientToQueue(CUpDownClient* client, bool bIgnoreTimelimit) { //This is to keep users from abusing the limits we put on lowID callbacks. //1)Check if we are connected to any network and that we are a lowID. //(Although this check shouldn't matter as they wouldn't have found us.. // But, maybe I'm missing something, so it's best to check as a precaution.) //2)Check if the user is connected to Kad. We do allow all Kad Callbacks. //3)Check if the user is in our download list or a friend.. //We give these users a special pass as they are helping us.. //4)Are we connected to a server? If we are, is the user on the same server? //TCP lowID callbacks are also allowed.. //5)If the queue is very short, allow anyone in as we want to make sure //our upload is always used. if (theApp.IsConnected() && theApp.IsFirewalled() && !client->GetKadPort() && client->GetDownloadState() == DS_NONE && !client->IsFriend() && theApp.serverconnect && !theApp.serverconnect->IsLocalServer(client->GetServerIP(),client->GetServerPort()) && GetWaitingUserCount() > 50) return; client->AddAskedCount(); client->SetLastUpRequest(); if (!bIgnoreTimelimit) client->AddRequestCount(client->GetUploadFileID()); if (client->IsBanned()) return; uint16 cSameIP = 0; // check for double POSITION pos1, pos2; for (pos1 = waitinglist.GetHeadPosition();( pos2 = pos1 ) != NULL;) { waitinglist.GetNext(pos1); CUpDownClient* cur_client= waitinglist.GetAt(pos2); if (cur_client == client) { if (client->m_bAddNextConnect && AcceptNewClient(client->m_bAddNextConnect)) { //Special care is given to lowID clients that missed their upload slot //due to the saving bandwidth on callbacks. if(thePrefs.GetLogUlDlEvents()) AddDebugLogLine(true, _T("Adding ****lowid when reconnecting. Client: %s"), client->DbgGetClientInfo()); client->m_bAddNextConnect = false; RemoveFromWaitingQueue(client, true); // statistic values // TODO: Maybe we should change this to count each request for a file only once and ignore reasks CKnownFile* reqfile = theApp.sharedfiles->GetFileByID((uchar*)client->GetUploadFileID()); if (reqfile) reqfile->statistic.AddRequest(); AddUpNextClient(_T("Adding ****lowid when reconnecting."), client); return; } client->SendRankingInfo(); theApp.emuledlg->transferwnd->queuelistctrl.RefreshClient(client); return; } else if ( client->Compare(cur_client) ) { theApp.clientlist->AddTrackClient(client); // in any case keep track of this client // another client with same ip:port or hash // this happens only in rare cases, because same userhash / ip:ports are assigned to the right client on connecting in most cases if (cur_client->credits != NULL && cur_client->credits->GetCurrentIdentState(cur_client->GetIP()) == IS_IDENTIFIED) { //cur_client has a valid secure hash, don't remove him if (thePrefs.GetVerbose()) AddDebugLogLine(false, GetResString(IDS_SAMEUSERHASH), client->GetUserName(), cur_client->GetUserName(), client->GetUserName()); return; } if (client->credits != NULL && client->credits->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED) { //client has a valid secure hash, add him remove other one if (thePrefs.GetVerbose()) AddDebugLogLine(false, GetResString(IDS_SAMEUSERHASH), client->GetUserName(), cur_client->GetUserName(), cur_client->GetUserName()); RemoveFromWaitingQueue(pos2,true); if (!cur_client->socket) { if(cur_client->Disconnected(_T("AddClientToQueue - same userhash 1"))) delete cur_client; } } else { // remove both since we do not know who the bad one is if (thePrefs.GetVerbose()) AddDebugLogLine(false, GetResString(IDS_SAMEUSERHASH), client->GetUserName() ,cur_client->GetUserName(), _T("Both")); RemoveFromWaitingQueue(pos2,true); if (!cur_client->socket) { if(cur_client->Disconnected(_T("AddClientToQueue - same userhash 2"))) delete cur_client; } return; } } else if (client->GetIP() == cur_client->GetIP()) { // same IP, different port, different userhash cSameIP++; } } if (cSameIP >= 3) { // do not accept more than 3 clients from the same IP if (thePrefs.GetVerbose()) DEBUG_ONLY( AddDebugLogLine(false,_T("%s's (%s) request to enter the queue was rejected, because of too many clients with the same IP"), client->GetUserName(), ipstr(client->GetConnectIP())) ); return; } else if (theApp.clientlist->GetClientsFromIP(client->GetIP()) >= 3) { if (thePrefs.GetVerbose()) DEBUG_ONLY( AddDebugLogLine(false,_T("%s's (%s) request to enter the queue was rejected, because of too many clients with the same IP (found in TrackedClientsList)"), client->GetUserName(), ipstr(client->GetConnectIP())) ); return; } // done // statistic values // TODO: Maybe we should change this to count each request for a file only once and ignore reasks CKnownFile* reqfile = theApp.sharedfiles->GetFileByID((uchar*)client->GetUploadFileID()); if (reqfile) reqfile->statistic.AddRequest(); // emule collection will bypass the queue if (reqfile != NULL && CCollection::HasCollectionExtention(reqfile->GetFileName()) && reqfile->GetFileSize() < (uint64)MAXPRIORITYCOLL_SIZE && !client->IsDownloading() && client->socket != NULL && client->socket->IsConnected()) { client->SetCollectionUploadSlot(true); RemoveFromWaitingQueue(client, true); AddUpNextClient(_T("Collection Priority Slot"), client); return; } else client->SetCollectionUploadSlot(false); // cap the list // the queue limit in prefs is only a soft limit. Hard limit is 25% higher, to let in powershare clients and other // high ranking clients after soft limit has been reached uint32 softQueueLimit = thePrefs.GetQueueSize(); uint32 hardQueueLimit = thePrefs.GetQueueSize() + max(thePrefs.GetQueueSize()/4, 200); // if soft queue limit has been reached, only let in high ranking clients if ((uint32)waitinglist.GetCount() >= hardQueueLimit || (uint32)waitinglist.GetCount() >= softQueueLimit && // soft queue limit is reached (client->IsFriend() && client->GetFriendSlot()) == false && // client is not a friend with friend slot client->GetCombinedFilePrioAndCredit() < GetAverageCombinedFilePrioAndCredit()) { // and client has lower credits/wants lower prio file than average client in queue // then block client from getting on queue return; } if (client->IsDownloading()) { // he's already downloading and wants probably only another file if (thePrefs.GetDebugClientTCPLevel() > 0) DebugSend("OP__AcceptUploadReq", client); Packet* packet = new Packet(OP_ACCEPTUPLOADREQ,0); theStats.AddUpDataOverheadFileRequest(packet->size); client->SendPacket(packet, true); return; } if (waitinglist.IsEmpty() && ForceNewClient(true)) { AddUpNextClient(_T("Direct add with empty queue."), client); } else { waitinglist.AddTail(client); client->SetUploadState(US_ONUPLOADQUEUE); theApp.emuledlg->transferwnd->queuelistctrl.AddClient(client,true); theApp.emuledlg->transferwnd->ShowQueueCount(waitinglist.GetCount()); client->SendRankingInfo(); } }
BOOL CUpdateInfo::ClearUpdateHistory(const uchar * hashkey)//清除历史升级任务 { for (int i = 0; i < CGlobalVariable::sharedfiles->GetCount(); i++) { CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByIndex(i); CPartFile* pPartFile; try { //共享列表中是否有 if(file) { if ( IsUpdateTask( file->GetFilePath() ) && file->GetFileHash() != hashkey ) { if(file->IsPartFile()) { //共享列表有,但未下载完,移除 pPartFile = DYNAMIC_DOWNCAST(CPartFile,file); if( pPartFile ) { pPartFile->DeleteFile(); } } else { //共享列表有,已经下载完成未安装,移除 DeleteFile(file->GetFilePath()); theApp.emuledlg->sharedfileswnd->sharedfilesctrl.RemoveFile(file); CGlobalVariable::sharedfiles->RemoveFile(file); CGlobalVariable::filemgr.RemoveFileItem(file); } } else continue; } } catch (CException* e) { e->Delete(); //return FALSE; } } for (int i = 0; i < CGlobalVariable::downloadqueue->GetFileCount(); i++) { CPartFile* pFile = CGlobalVariable::downloadqueue->GetFileByIndex(i); try { if (pFile) { if ( IsUpdateTask( pFile->GetFilePath() ) && pFile->GetFileHash() != hashkey ) { //共享列表没有,但未下载完,移除 pFile->DeleteFile(); } } } catch (CException* e) { e->Delete(); //return FALSE; } } return TRUE; }
void CUploadListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { if (!theApp.emuledlg->IsRunning()) return; if (!lpDrawItemStruct->itemData) return; CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC); BOOL bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS)); if (lpDrawItemStruct->itemState & ODS_SELECTED) { if (bCtrlFocused) odc->SetBkColor(m_crHighlight); else odc->SetBkColor(m_crNoHighlight); } else odc->SetBkColor(GetBkColor()); const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData; CMemDC dc(odc, &lpDrawItemStruct->rcItem); CFont* pOldFont = dc.SelectObject(GetFont()); CRect cur_rec(lpDrawItemStruct->rcItem); COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText); if (client->GetSlotNumber() > theApp.uploadqueue->GetActiveUploadsCount()) { dc.SetTextColor(::GetSysColor(COLOR_GRAYTEXT)); } int iOldBkMode; if (m_crWindowTextBk == CLR_NONE){ DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0); iOldBkMode = dc.SetBkMode(TRANSPARENT); } else iOldBkMode = OPAQUE; CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID()); CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl(); int iCount = pHeaderCtrl->GetItemCount(); cur_rec.right = cur_rec.left - 8; cur_rec.left += 4; CString Sbuffer; for (int iCurrent = 0; iCurrent < iCount; iCurrent++) { int iColumn = pHeaderCtrl->OrderToIndex(iCurrent); if (!IsColumnHidden(iColumn)) { cur_rec.right += GetColumnWidth(iColumn); switch (iColumn) { case 0:{ uint8 image; if (client->IsFriend()) image = 4; else if (client->GetClientSoft() == SO_EDONKEYHYBRID){ if (client->credits->GetScoreRatio(client->GetIP()) > 1) image = 8; else image = 7; } else if (client->GetClientSoft() == SO_MLDONKEY){ if (client->credits->GetScoreRatio(client->GetIP()) > 1) image = 6; else image = 5; } else if (client->GetClientSoft() == SO_SHAREAZA){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 10; else image = 9; } else if (client->GetClientSoft() == SO_AMULE){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 12; else image = 11; } else if (client->GetClientSoft() == SO_LPHANT){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 14; else image = 13; } else if (client->ExtProtocolAvailable()){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 3; else image = 1; } else{ if (client->credits->GetScoreRatio(client->GetIP()) > 1) image = 2; else image = 0; } POINT point = {cur_rec.left, cur_rec.top+1}; imagelist.Draw(dc,image, point, ILD_NORMAL | ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED) ? INDEXTOOVERLAYMASK(1) : 0)); Sbuffer = client->GetUserName(); cur_rec.left += 20; dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT); cur_rec.left -= 20; break; } case 1: if (file) Sbuffer = file->GetFileName(); else Sbuffer = _T("?"); break; case 2: Sbuffer = CastItoXBytes(client->GetDatarate(), false, true); break; case 3: // NOTE: If you change (add/remove) anything which is displayed here, update also the sorting part.. if (thePrefs.m_bExtControls) Sbuffer.Format( _T("%s (%s)"), CastItoXBytes(client->GetSessionUp(), false, false), CastItoXBytes(client->GetQueueSessionPayloadUp(), false, false)); else Sbuffer = CastItoXBytes(client->GetSessionUp(), false, false); break; case 4: if (client->HasLowID()) Sbuffer.Format(_T("%s (%s)"), CastSecondsToHM(client->GetWaitTime()/1000), GetResString(IDS_IDLOW)); else Sbuffer = CastSecondsToHM(client->GetWaitTime()/1000); break; case 5: Sbuffer = CastSecondsToHM(client->GetUpStartTimeDelay()/1000); break; case 6: Sbuffer = client->GetUploadStateDisplayString(); break; case 7: cur_rec.bottom--; cur_rec.top++; client->DrawUpStatusBar(dc, &cur_rec, false, thePrefs.UseFlatBar()); cur_rec.bottom++; cur_rec.top--; break; } if (iColumn != 7 && iColumn != 0) dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT); cur_rec.left += GetColumnWidth(iColumn); } } //draw rectangle around selected item(s) if (lpDrawItemStruct->itemState & ODS_SELECTED) { RECT outline_rec = lpDrawItemStruct->rcItem; outline_rec.top--; outline_rec.bottom++; dc.FrameRect(&outline_rec, &CBrush(GetBkColor())); outline_rec.top++; outline_rec.bottom--; outline_rec.left++; outline_rec.right--; if (bCtrlFocused) dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine)); else dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine)); } if (m_crWindowTextBk == CLR_NONE) dc.SetBkMode(iOldBkMode); dc.SelectObject(pOldFont); dc.SetTextColor(crOldTextColor); }
void CQueueListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { if (!theApp.emuledlg->IsRunning()) return; if (!lpDrawItemStruct->itemData) return; CDC* odc = CDC::FromHandle(lpDrawItemStruct->hDC); BOOL bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS)); if (lpDrawItemStruct->itemState & ODS_SELECTED) { if (bCtrlFocused) odc->SetBkColor(m_crHighlight); else odc->SetBkColor(m_crNoHighlight); } else odc->SetBkColor(GetBkColor()); const CUpDownClient* client = (CUpDownClient*)lpDrawItemStruct->itemData; CMemDC dc(odc, &lpDrawItemStruct->rcItem); CFont* pOldFont = dc.SelectObject(GetFont()); CRect cur_rec(lpDrawItemStruct->rcItem); COLORREF crOldTextColor = dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText); int iOldBkMode; if (m_crWindowTextBk == CLR_NONE){ DefWindowProc(WM_ERASEBKGND, (WPARAM)(HDC)dc, 0); iOldBkMode = dc.SetBkMode(TRANSPARENT); } else iOldBkMode = OPAQUE; CKnownFile* file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID()); CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl(); int iCount = pHeaderCtrl->GetItemCount(); cur_rec.right = cur_rec.left - 8; cur_rec.left += 4; CString Sbuffer; for(int iCurrent = 0; iCurrent < iCount; iCurrent++){ int iColumn = pHeaderCtrl->OrderToIndex(iCurrent); if( !IsColumnHidden(iColumn) ){ cur_rec.right += GetColumnWidth(iColumn); switch(iColumn){ case 0:{ uint8 image; if (client->IsFriend()) image = 4; else if (client->GetClientSoft() == SO_EDONKEYHYBRID){ if (client->credits->GetScoreRatio(client->GetIP()) > 1) image = 8; else image = 7; } else if (client->GetClientSoft() == SO_MLDONKEY){ if (client->credits->GetScoreRatio(client->GetIP()) > 1) image = 6; else image = 5; } else if (client->GetClientSoft() == SO_SHAREAZA){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 10; else image = 9; } else if (client->GetClientSoft() == SO_AMULE){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 12; else image = 11; } else if (client->GetClientSoft() == SO_LPHANT){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 14; else image = 13; } else if (client->ExtProtocolAvailable()){ if(client->credits->GetScoreRatio(client->GetIP()) > 1) image = 3; else image = 1; } else{ if (client->credits->GetScoreRatio(client->GetIP()) > 1) image = 2; else image = 0; } uint32 nOverlayImage = 0; if ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED)) nOverlayImage |= 1; if (client->IsObfuscatedConnectionEstablished()) nOverlayImage |= 2; int iIconPosY = (cur_rec.Height() > 16) ? ((cur_rec.Height() - 16) / 2) : 1; POINT point = {cur_rec.left, cur_rec.top + iIconPosY}; imagelist.Draw(dc,image, point, ILD_NORMAL | INDEXTOOVERLAYMASK(nOverlayImage)); Sbuffer = client->GetUserName(); cur_rec.left += 20; dc.DrawText(Sbuffer, Sbuffer.GetLength(), &cur_rec, DLC_DT_TEXT); cur_rec.left -= 20; break; } case 1: if(file) Sbuffer = file->GetFileName(); else Sbuffer = _T("?"); break; case 2: if(file){ switch (file->GetUpPriority()) { case PR_VERYLOW : { Sbuffer = GetResString(IDS_PRIOVERYLOW); break; } case PR_LOW : { if( file->IsAutoUpPriority() ) Sbuffer = GetResString(IDS_PRIOAUTOLOW); else Sbuffer = GetResString(IDS_PRIOLOW); break; } case PR_NORMAL : { if( file->IsAutoUpPriority() ) Sbuffer = GetResString(IDS_PRIOAUTONORMAL); else Sbuffer = GetResString(IDS_PRIONORMAL); break; } case PR_HIGH : { if( file->IsAutoUpPriority() ) Sbuffer = GetResString(IDS_PRIOAUTOHIGH); else Sbuffer = GetResString(IDS_PRIOHIGH); break; } case PR_VERYHIGH : { Sbuffer = GetResString(IDS_PRIORELEASE); break; } default: Sbuffer.Empty(); } } else Sbuffer = _T("?"); break; case 3: Sbuffer.Format(_T("%i"),client->GetScore(false,false,true)); break; case 4: if (client->HasLowID()){ if (client->m_bAddNextConnect) Sbuffer.Format(_T("%i ****"),client->GetScore(false)); else Sbuffer.Format(_T("%i (%s)"),client->GetScore(false), GetResString(IDS_IDLOW)); } else Sbuffer.Format(_T("%i"),client->GetScore(false)); break; case 5: Sbuffer.Format(_T("%i"),client->GetAskedCount()); break; case 6: Sbuffer = CastSecondsToHM((::GetTickCount() - client->GetLastUpRequest())/1000); break; case 7: Sbuffer = CastSecondsToHM((::GetTickCount() - client->GetWaitStartTime())/1000); break; case 8: if(client->IsBanned()) Sbuffer = GetResString(IDS_YES); else Sbuffer = GetResString(IDS_NO); break; case 9: if( client->GetUpPartCount()){ cur_rec.bottom--; cur_rec.top++; client->DrawUpStatusBar(dc,&cur_rec,false,thePrefs.UseFlatBar()); cur_rec.bottom++; cur_rec.top--; } break; } if( iColumn != 9 && iColumn != 0) dc.DrawText(Sbuffer,Sbuffer.GetLength(),&cur_rec,DLC_DT_TEXT); cur_rec.left += GetColumnWidth(iColumn); } } // draw rectangle around selected item(s) if (lpDrawItemStruct->itemState & ODS_SELECTED) { RECT outline_rec = lpDrawItemStruct->rcItem; outline_rec.top--; outline_rec.bottom++; dc.FrameRect(&outline_rec, &CBrush(GetBkColor())); outline_rec.top++; outline_rec.bottom--; outline_rec.left++; outline_rec.right--; if(bCtrlFocused) dc.FrameRect(&outline_rec, &CBrush(m_crFocusLine)); else dc.FrameRect(&outline_rec, &CBrush(m_crNoFocusLine)); } if (m_crWindowTextBk == CLR_NONE) dc.SetBkMode(iOldBkMode); dc.SelectObject(pOldFont); dc.SetTextColor(crOldTextColor); }
bool CUpDownClient::ProcessPeerCacheQuery(const uchar* packet, UINT size) { const bool bDebug = (thePrefs.GetDebugClientTCPLevel() > 0); if (bDebug) DebugRecv("OP_PeerCacheQuery", this); if (socket == NULL){ ASSERT(0); return false; } CSafeMemFile dataRecv(packet, size); uint8 uPCVersion = dataRecv.ReadUInt8(); if (uPCVersion != PCPCK_VERSION){ if (bDebug) Debug(_T(" ***Invalid packet version: 0x%02x\n"), uPCVersion); ASSERT(0); return false; } uint8 uPCOpcode = dataRecv.ReadUInt8(); if (uPCOpcode != PCOP_REQ){ if (bDebug) Debug(_T(" ***Invalid packet opcode: 0x%02x\n"), uPCOpcode); ASSERT(0); return false; } uint32 uCacheIP = 0; uint16 uCachePort = 0; uint32 uPushId = 0; uchar aucFileHash[16]; uint32 uRemoteIP = 0; md4clr(aucFileHash); CString strInfo; UINT uTags = dataRecv.ReadUInt8(); while (uTags--) { CTag tag(&dataRecv, GetUnicodeSupport()!=utf8strNone); if (tag.GetNameID() == PCTAG_CACHEIP && tag.IsInt()) { uCacheIP = tag.GetInt(); if (bDebug) strInfo.AppendFormat(_T(" CacheIP=%s"), ipstr(uCacheIP)); } else if (tag.GetNameID() == PCTAG_CACHEPORT && tag.IsInt()) { uCachePort = (uint16)tag.GetInt(); if (bDebug) strInfo.AppendFormat(_T(" CachePort=%u"), uCachePort); } else if (tag.GetNameID() == PCTAG_PUSHID && tag.IsInt()) { uPushId = tag.GetInt(); if (bDebug) strInfo.AppendFormat(_T(" PushId=%u"), uPushId); } else if (tag.GetNameID() == PCTAG_FILEID && tag.IsHash() && tag.GetHash() != NULL) { md4cpy(aucFileHash, tag.GetHash()); if (bDebug) strInfo.AppendFormat(_T(" FileId=%s"), md4str(aucFileHash)); } else if (tag.GetNameID() == PCTAG_PUBLICIP && tag.IsInt()) { uRemoteIP = tag.GetInt(); if (bDebug) strInfo.AppendFormat(_T(" PublicIP=%s"), ipstr(uRemoteIP)); } else { if (bDebug) strInfo.AppendFormat(_T(" ***UnkTag: %s"), tag.GetFullInfo()); ASSERT(0); } } if (bDebug) { if (dataRecv.GetPosition() < dataRecv.GetLength()) strInfo.AppendFormat(_T(" ***AddData: %u bytes"), (UINT)(dataRecv.GetLength() - dataRecv.GetPosition())); Debug(_T("%s\n"), strInfo); } if (uCacheIP == 0 || uCachePort == 0 || uPushId == 0 || isnulmd4(aucFileHash)){ if (thePrefs.GetVerbose()) AddDebugLogLine(false, _T("Invalid PeerCacheQuery; %s"), DbgGetClientInfo()); return false; } CKnownFile* pUploadFile = theApp.sharedfiles->GetFileByID(aucFileHash); if (pUploadFile == NULL){ if (thePrefs.GetVerbose()) AddDebugLogLine(false, _T("PeerCacheQuery reqfile does not match ed2k reqfile; %s"), DbgGetClientInfo()); return false; } if (m_pPCUpSocket != NULL) { SetPeerCacheUpState(PCUS_NONE); m_pPCUpSocket->Safe_Delete(); ASSERT( m_pPCUpSocket == NULL ); } m_pPCUpSocket = new CPeerCacheUpSocket(this); m_pPCUpSocket->SetTimeOut(GetPeerCacheSocketUploadTimeout()); m_pPCUpSocket->Create(); SOCKADDR_IN sockAddr = {0}; sockAddr.sin_family = AF_INET; sockAddr.sin_port = htons(uCachePort); sockAddr.sin_addr.S_un.S_addr = uCacheIP; //Try to always tell the socket to WaitForOnConnect before you call Connect. m_pPCUpSocket->WaitForOnConnect(); m_pPCUpSocket->Connect((SOCKADDR*)&sockAddr, sizeof sockAddr); CStringA strPCRequest; strPCRequest.AppendFormat("GIVE %u\r\n", uPushId); if (thePrefs.GetDebugClientTCPLevel() > 0){ DebugSend("PeerCache-GIVE", this, pUploadFile->GetFileHash()); Debug(_T(" %hs\n"), strPCRequest); } CRawPacket* pHttpPacket = new CRawPacket(strPCRequest); theStats.AddUpDataOverheadFileRequest(pHttpPacket->size); m_pPCUpSocket->SendPacket(pHttpPacket); m_pPCUpSocket->SetHttpState(HttpStateRecvExpected); m_bPeerCacheUpHit = false; SetPeerCacheUpState(PCUS_WAIT_CACHE_REPLY); //theApp.uploadBandwidthThrottler->AddToStandardList(0, m_pPCUpSocket); CSafeMemFile dataSend(128); dataSend.WriteUInt8(PCPCK_VERSION); dataSend.WriteUInt8(PCOP_RES); dataSend.WriteUInt8(3); CTag tagPushId(PCTAG_PUSHID, uPushId); tagPushId.WriteNewEd2kTag(&dataSend); CTag tagPublicIP(PCTAG_PUBLICIP, theApp.GetPublicIP()); tagPublicIP.WriteNewEd2kTag(&dataSend); CTag tagFileId(PCTAG_FILEID, (BYTE*)aucFileHash); tagFileId.WriteNewEd2kTag(&dataSend); if (thePrefs.GetDebugClientTCPLevel() > 0){ DebugSend("OP__PeerCacheAnswer", this, aucFileHash); Debug(_T(" PushId=%u PublicIP=%s FileId=%s\n"), tagPushId.GetInt(), ipstr(tagPublicIP.GetInt()), md4str(tagFileId.GetHash())); } Packet* pEd2kPacket = new Packet(&dataSend, OP_EMULEPROT, OP_PEERCACHE_ANSWER); theStats.AddUpDataOverheadFileRequest(pEd2kPacket->size); socket->SendPacket(pEd2kPacket); return true; }
UINT CUpDownClient::ProcessPeerCacheUpHttpRequest(const CStringAArray& astrHeaders) { ASSERT( m_ePeerCacheUpState == PCUS_WAIT_CACHE_REPLY ); if (astrHeaders.GetCount() == 0) return HTTP_STATUS_BAD_REQUEST; const CStringA& rstrHdr = astrHeaders.GetAt(0); char szUrl[1024]; UINT uHttpMajVer, uHttpMinVer; if (sscanf(rstrHdr, "GET %1023s HTTP/%u.%u", szUrl, &uHttpMajVer, &uHttpMinVer) != 3){ DebugHttpHeaders(astrHeaders); return HTTP_STATUS_BAD_REQUEST; } if (uHttpMajVer != 1 || (uHttpMinVer != 0 && uHttpMinVer != 1)){ DebugHttpHeaders(astrHeaders); return HTTP_STATUS_BAD_REQUEST; } char szFileHash[33]; if (sscanf(szUrl, "/.ed2khash=%32s", szFileHash) != 1){ DebugHttpHeaders(astrHeaders); return HTTP_STATUS_BAD_REQUEST; } uchar aucUploadFileID[16]; if (!strmd4(szFileHash, aucUploadFileID)){ DebugHttpHeaders(astrHeaders); return HTTP_STATUS_BAD_REQUEST; } CKnownFile* pUploadFile = theApp.sharedfiles->GetFileByID(aucUploadFileID); if (pUploadFile == NULL){ DebugHttpHeaders(astrHeaders); return HTTP_STATUS_NOT_FOUND; } bool bValidRange = false; uint64 ui64RangeStart = 0; uint64 ui64RangeEnd = 0; DWORD dwPushID = 0; for (int i = 1; i < astrHeaders.GetCount(); i++) { const CStringA& rstrHdr = astrHeaders.GetAt(i); if (strnicmp(rstrHdr, "Range:", 6) == 0) { int iParams; if ( (iParams = sscanf((LPCSTR)rstrHdr+6," bytes = %I64u - %I64u", &ui64RangeStart, &ui64RangeEnd)) != 2 && (iParams = sscanf((LPCSTR)rstrHdr+6," bytes = %I64u -", &ui64RangeStart)) != 1){ DebugHttpHeaders(astrHeaders); TRACE("*** Unexpected HTTP %hs\n", rstrHdr); return HTTP_STATUS_BAD_REQUEST; } if (iParams == 1) ui64RangeEnd = pUploadFile->GetFileSize() - (uint64)1; if (ui64RangeEnd < ui64RangeStart){ DebugHttpHeaders(astrHeaders); TRACE("*** Unexpected HTTP %hs\n", rstrHdr); return HTTP_STATUS_INV_RANGE; } bValidRange = true; } else if (strnicmp(rstrHdr, "X-ED2K-PushId:", 14) == 0) { if (sscanf((LPCSTR)rstrHdr+14, "%u", &dwPushID) != 1){ DebugHttpHeaders(astrHeaders); TRACE("*** Unexpected HTTP %hs\n", rstrHdr); return HTTP_STATUS_BAD_REQUEST; } } } if (!bValidRange){ DebugHttpHeaders(astrHeaders); return HTTP_STATUS_LENGTH_REQUIRED; } m_uPeerCacheUploadPushId = dwPushID; //PC-TODO: Where does this flag need to be cleared again? // When client is removed from uploading list? // When client is allowed to send more block requests? // everything is setup for uploading with PeerCache. SetPeerCacheUpState(PCUS_UPLOADING); Requested_Block_Struct* reqblock = new Requested_Block_Struct; reqblock->StartOffset = ui64RangeStart; reqblock->EndOffset = ui64RangeEnd + 1; md4cpy(reqblock->FileID, aucUploadFileID); reqblock->transferred = 0; AddReqBlock(reqblock); return HTTP_STATUS_OK; }
int CAICHSyncThread::Run() { if ( !theApp.emuledlg->IsRunning() ) return 0; // we collect all masterhashs which we find in the known2.met and store them in a list CList<CAICHHash> liKnown2Hashs; CString fullpath=thePrefs.GetConfigDir(); fullpath.Append(KNOWN2_MET_FILENAME); CSafeFile file; CFileException fexp; uint32 nLastVerifiedPos = 0; if (!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 { //setvbuf(file.m_pStream, NULL, _IOFBF, 16384); uint32 nExistingSize = file.GetLength(); uint16 nHashCount; while (file.GetPosition() < nExistingSize){ liKnown2Hashs.AddTail(CAICHHash(&file)); nHashCount = file.ReadUInt16(); if (file.GetPosition() + nHashCount*HASHSIZE > nExistingSize){ AfxThrowFileException(CFileException::endOfFile, 0, file.GetFileName()); } // skip the rest of this hashset file.Seek(nHashCount*HASHSIZE, CFile::current); nLastVerifiedPos = file.GetPosition(); } } catch(CFileException* error){ if (error->m_cause == CFileException::endOfFile){ LogError(LOG_STATUSBAR,GetResString(IDS_ERR_SERVERMET_BAD)); // truncate the file to the size to the last verified valid pos try{ file.SetLength(nLastVerifiedPos); } 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; } file.Close(); // now we check that all files which are in the sharedfilelist have a corresponding hash in out list // those how don'T are added to the hashinglist for (uint32 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->GetAICHHashset()->GetStatus() == AICH_HASHSETCOMPLETE){ bool bFound = false; for (POSITION pos = liKnown2Hashs.GetHeadPosition();pos != 0;) { if (liKnown2Hashs.GetNext(pos) == pCurFile->GetAICHHashset()->GetMasterHash()){ bFound = true; #ifdef _DEBUG // in debugmode we load and verify all hashsets ASSERT( pCurFile->GetAICHHashset()->LoadHashSet() ); // pCurFile->GetAICHHashset()->DbgTest(); pCurFile->GetAICHHashset()->FreeHashSet(); #endif break; } } if (bFound) // hashset is available, everything fine with this file continue; } pCurFile->GetAICHHashset()->SetStatus(AICH_ERROR); m_liToHash.AddTail(pCurFile); } } // warn the user if he just upgraded if (thePrefs.IsFirstStart() && !m_liToHash.IsEmpty()){ LogWarning(GetResString(IDS_AICH_WARNUSER)); } if (!m_liToHash.IsEmpty()){ AddLogLine(true, GetResString(IDS_AICH_SYNCTOTAL), m_liToHash.GetCount() ); // I18n: ThreadSafeLog 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); } sLock1.Lock(); uint32 cDone = 0; for (POSITION pos = m_liToHash.GetHeadPosition();pos != 0; cDone++) { if (theApp.emuledlg==NULL || !theApp.emuledlg->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; AddLogLine(false, GetResString(IDS_AICH_CALCFILE), pCurFile->GetFileName()); // I18n: ThreadSafeLog if(!pCurFile->CreateAICHHashSetOnly()) // [TPT] - WebCache if(thePrefs.GetLogICHEvents()) //JP log ICH events AddDebugLogLine(false, _T("Failed to create AICH Hashset while sync. for file %s"), pCurFile->GetFileName()); // I18n: ThreadSafeLog } theApp.emuledlg->sharedfileswnd->sharedfilesctrl.SetAICHHashing(0); if (theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd != NULL) theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount(); sLock1.Unlock(); } // [TPT] - WebCache if(thePrefs.GetLogICHEvents()) //JP log ICH events AddDebugLogLine(false, _T("AICHSyncThread finished")); // I18n: ThreadSafeLog return 0; }
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(); } } }
void CCollectionCreateDialog::OnBnClickedOk() { //Some users have noted that the collection can at times //save a collection with a invalid name... OnEnKillFocusCollectionName(); CString sFileName; m_CollectionNameEdit.GetWindowText(sFileName); if (!sFileName.IsEmpty()) { m_pCollection->m_sCollectionAuthorName.Empty(); m_pCollection->SetCollectionAuthorKey(NULL, 0); m_pCollection->m_sCollectionName = sFileName; m_pCollection->m_bTextFormat = (m_CollectionCreateFormatCheck.GetCheck() == BST_CHECKED); CString sFilePath; sFilePath.Format(_T("%s\\%s.emulecollection"), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR), m_pCollection->m_sCollectionName); using namespace CryptoPP; RSASSA_PKCS1v15_SHA_Signer* pSignkey = NULL; if (m_CollectionCreateSignNameKeyCheck.GetCheck()) { bool bCreateNewKey = false; HANDLE hKeyFile = ::CreateFile(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hKeyFile != INVALID_HANDLE_VALUE) { if (::GetFileSize(hKeyFile, NULL) == 0) bCreateNewKey = true; ::CloseHandle(hKeyFile); } else bCreateNewKey = true; if (bCreateNewKey) { try { AutoSeededRandomPool rng; InvertibleRSAFunction privkey; privkey.Initialize(rng, 1024); Base64Encoder privkeysink(new FileSink(CStringA(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat")))); privkey.DEREncode(privkeysink); privkeysink.MessageEnd(); } catch(...) { ASSERT(0); } } try { FileSource filesource(CStringA(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat")), true,new Base64Decoder); pSignkey = new RSASSA_PKCS1v15_SHA_Signer(filesource); RSASSA_PKCS1v15_SHA_Verifier pubkey(*pSignkey); byte abyMyPublicKey[1000]; ArraySink asink(abyMyPublicKey, 1000); pubkey.DEREncode(asink); int nLen = asink.TotalPutLength(); asink.MessageEnd(); m_pCollection->SetCollectionAuthorKey(abyMyPublicKey, nLen); } catch(...) { ASSERT(0); } m_pCollection->m_sCollectionAuthorName = thePrefs.GetUserNick(); } if (!PathFileExists(sFilePath)) { m_pCollection->WriteToFileAddShared(pSignkey); } else { if (AfxMessageBox(GetResString(IDS_COLL_REPLACEEXISTING), MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO) == IDNO) return; bool bDeleteSuccessful = ShellDeleteFile(sFilePath); if (bDeleteSuccessful) { CKnownFile* pKnownFile = theApp.knownfiles->FindKnownFileByPath(sFilePath); if (pKnownFile) { theApp.sharedfiles->RemoveFile(pKnownFile, true); if (pKnownFile->IsKindOf(RUNTIME_CLASS(CPartFile))) theApp.emuledlg->transferwnd->GetDownloadList()->ClearCompleted(static_cast<CPartFile*>(pKnownFile)); } m_pCollection->WriteToFileAddShared(pSignkey); } else { AfxMessageBox(GetResString(IDS_COLL_ERR_DELETING),MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO); } } delete pSignkey; pSignkey = NULL; OnOK(); } }
bool CKnownFileList::SafeAddKFile(CKnownFile* toadd) { bool bRemovedDuplicateSharedFile = false; CCKey key(toadd->GetFileHash()); CKnownFile* pFileInMap; if (m_Files_map.Lookup(key, pFileInMap)) { TRACE(_T("%hs: Already in known list: %s %I64u \"%s\"\n"), __FUNCTION__, md4str(pFileInMap->GetFileHash()), pFileInMap->GetFileSize(), pFileInMap->GetFileName()); TRACE(_T("%hs: Old entry replaced with: %s %I64u \"%s\"\n"), __FUNCTION__, md4str(toadd->GetFileHash()), toadd->GetFileSize(), toadd->GetFileName()); // if we hash files which are already in known file list and add them later (when the hashing thread is finished), // we can not delete any already available entry from known files list. that entry can already be used by the // shared file list -> crash. m_Files_map.RemoveKey(CCKey(pFileInMap->GetFileHash())); m_mapKnownFilesByAICH.RemoveKey(pFileInMap->GetAICHHashset()->GetMasterHash()); //This can happen in a couple situations.. //File was renamed outside of eMule.. //A user decided to redownload a file he has downloaded and unshared.. //RemovingKeyWords I believe is not thread safe if I'm looking at this right. //Not sure of a good solution yet.. if (theApp.sharedfiles) { #if 0 // This may crash the client because of dangling ptr in shared files ctrl. // This may happen if a file is re-shared which is also currently downloaded. // After the file was downloaded (again) there is a dangl. ptr in shared files // ctrl. // Actually that's also wrong in some cases: Keywords are not always removed // because the wrong ptr is used to search for in keyword publish list. theApp.sharedfiles->RemoveKeywords(pFileInMap); #else // This solves the problem with dangl. ptr in shared files ctrl, // but creates a new bug. It may lead to unshared files! Even // worse it may lead to files which are 'shared' in GUI but // which are though not shared 'logically'. // // To reduce the harm, remove the file from shared files list, // only if really needed. Right now this 'harm' applies for files // which are re-shared and then completed (again) because they were // also in download queue (they were added there when the already // available file was not in shared file list). if (theApp.sharedfiles->IsFilePtrInList(pFileInMap)) bRemovedDuplicateSharedFile = theApp.sharedfiles->RemoveFile(pFileInMap); #endif ASSERT( !theApp.sharedfiles->IsFilePtrInList(pFileInMap) ); } //Double check to make sure this is the same file as it's possible that a two files have the same hash. //Maybe in the furture we can change the client to not just use Hash as a key throughout the entire client.. ASSERT( toadd->GetFileSize() == pFileInMap->GetFileSize() ); ASSERT( toadd != pFileInMap ); if (toadd->GetFileSize() == pFileInMap->GetFileSize()) toadd->statistic.MergeFileStats(&pFileInMap->statistic); ASSERT( theApp.sharedfiles==NULL || !theApp.sharedfiles->IsFilePtrInList(pFileInMap) ); ASSERT( theApp.downloadqueue==NULL || !theApp.downloadqueue->IsPartFile(pFileInMap) ); // Quick fix: If we downloaded already downloaded files again and if those files all had the same file names // and were renamed during file completion, we have a pending ptr in transfer window. if (theApp.emuledlg && theApp.emuledlg->transferwnd && theApp.emuledlg->transferwnd->downloadlistctrl.m_hWnd) theApp.emuledlg->transferwnd->downloadlistctrl.RemoveFile((CPartFile*)pFileInMap); delete pFileInMap; } m_Files_map.SetAt(key, toadd); if (bRemovedDuplicateSharedFile) { theApp.sharedfiles->SafeAddKFile(toadd); } if (toadd->GetAICHHashset()->HasValidMasterHash()) m_mapKnownFilesByAICH.SetAt(toadd->GetAICHHashset()->GetMasterHash(), toadd); return true; }
void CSharedFilesCtrl::OnRightClick(wxListEvent& event) { long item_hit = CheckSelection(event); if ( (m_menu == NULL) && (item_hit != -1)) { m_menu = new wxMenu(_("Shared Files")); wxMenu* prioMenu = new wxMenu(); prioMenu->AppendCheckItem(MP_PRIOVERYLOW, _("Very low")); prioMenu->AppendCheckItem(MP_PRIOLOW, _("Low")); prioMenu->AppendCheckItem(MP_PRIONORMAL, _("Normal")); prioMenu->AppendCheckItem(MP_PRIOHIGH, _("High")); prioMenu->AppendCheckItem(MP_PRIOVERYHIGH, _("Very High")); prioMenu->AppendCheckItem(MP_POWERSHARE, _("Release")); prioMenu->AppendCheckItem(MP_PRIOAUTO, _("Auto")); m_menu->Append(0,_("Priority"),prioMenu); m_menu->AppendSeparator(); CKnownFile* file = (CKnownFile*)GetItemData(item_hit); if (file->GetFileComment().IsEmpty() && !file->GetFileRating()) { m_menu->Append(MP_CMT, _("Add Comment/Rating")); } else { m_menu->Append(MP_CMT, _("Edit Comment/Rating")); } m_menu->AppendSeparator(); m_menu->Append(MP_RENAME, _("Rename")); m_menu->AppendSeparator(); if (file->GetFileName().GetExt() == wxT("emulecollection")) { m_menu->Append( MP_ADDCOLLECTION, _("Add files in collection to transfer list")); m_menu->AppendSeparator(); } m_menu->Append(MP_GETMAGNETLINK,_("Copy magnet &URI to clipboard")); m_menu->Append(MP_GETED2KLINK,_("Copy eD2k &link to clipboard")); m_menu->Append(MP_GETSOURCEED2KLINK,_("Copy eD2k link to clipboard (&Source)")); m_menu->Append(MP_GETCRYPTSOURCEDED2KLINK,_("Copy eD2k link to clipboard (Source) (&With Crypt options)")); m_menu->Append(MP_GETHOSTNAMESOURCEED2KLINK,_("Copy eD2k link to clipboard (&Hostname)")); m_menu->Append(MP_GETHOSTNAMECRYPTSOURCEED2KLINK,_("Copy eD2k link to clipboard (Hostname) (With &Crypt options)")); m_menu->Append(MP_GETAICHED2KLINK,_("Copy eD2k link to clipboard (&AICH info)")); m_menu->Append(MP_WS,_("Copy feedback to clipboard")); m_menu->Enable(MP_GETAICHED2KLINK, file->HasProperAICHHashSet()); m_menu->Enable(MP_GETHOSTNAMESOURCEED2KLINK, !thePrefs::GetYourHostname().IsEmpty()); m_menu->Enable(MP_GETHOSTNAMECRYPTSOURCEED2KLINK, !thePrefs::GetYourHostname().IsEmpty()); int priority = file->IsAutoUpPriority() ? PR_AUTO : file->GetUpPriority(); prioMenu->Check(MP_PRIOVERYLOW, priority == PR_VERYLOW); prioMenu->Check(MP_PRIOLOW, priority == PR_LOW); prioMenu->Check(MP_PRIONORMAL, priority == PR_NORMAL); prioMenu->Check(MP_PRIOHIGH, priority == PR_HIGH); prioMenu->Check(MP_PRIOVERYHIGH,priority == PR_VERYHIGH); prioMenu->Check(MP_POWERSHARE, priority == PR_POWERSHARE); prioMenu->Check(MP_PRIOAUTO, priority == PR_AUTO); PopupMenu( m_menu, event.GetPoint() ); delete m_menu; m_menu = NULL; } }
void CSharedFilesCtrl::OnDrawItem( int item, wxDC* dc, const wxRect& rect, const wxRect& rectHL, bool highlighted ) { CKnownFile *file = (CKnownFile*)GetItemData(item); wxASSERT( file ); if ( highlighted ) { CMuleColour newcol(GetFocus() ? wxSYS_COLOUR_HIGHLIGHT : wxSYS_COLOUR_BTNSHADOW); dc->SetBackground(newcol.Blend(125).GetBrush()); dc->SetTextForeground( CMuleColour(wxSYS_COLOUR_HIGHLIGHTTEXT)); // The second blending goes over the first one. dc->SetPen(newcol.Blend(65).GetPen()); } else { dc->SetBackground( CMuleColour(wxSYS_COLOUR_LISTBOX).GetBrush() ); dc->SetTextForeground(CMuleColour(wxSYS_COLOUR_WINDOWTEXT)); dc->SetPen(*wxTRANSPARENT_PEN); } dc->SetBrush(dc->GetBackground()); dc->DrawRectangle(rectHL); dc->SetPen(*wxTRANSPARENT_PEN); // Offset based on the height of the fonts const int textVOffset = ( rect.GetHeight() - dc->GetCharHeight() ) / 2; // Empty space to each side of a column const int SPARE_PIXELS_HORZ = 4; // The leftmost position of the current column int columnLeft = 0; for ( int i = 0; i < GetColumnCount(); ++i ) { const int columnWidth = GetColumnWidth(i); if (columnWidth > 2*SPARE_PIXELS_HORZ) { wxRect columnRect( columnLeft + SPARE_PIXELS_HORZ, rect.y, columnWidth - 2 * SPARE_PIXELS_HORZ, rect.height); wxDCClipper clipper(*dc, columnRect); wxString textBuffer; switch ( i ) { case ID_SHARED_COL_NAME: textBuffer = file->GetFileName().GetPrintable(); if (file->GetFileRating() || file->GetFileComment().Length()) { int image = Client_CommentOnly_Smiley; if (file->GetFileRating()) { image = Client_InvalidRating_Smiley + file->GetFileRating() - 1; } wxASSERT(image >= Client_InvalidRating_Smiley); wxASSERT(image <= Client_CommentOnly_Smiley); int imgWidth = 16; theApp->amuledlg->m_imagelist.Draw(image, *dc, columnRect.x, columnRect.y + 1, wxIMAGELIST_DRAW_TRANSPARENT); // Move the text to the right columnRect.x += (imgWidth + 4); } break; case ID_SHARED_COL_SIZE: textBuffer = CastItoXBytes(file->GetFileSize()); break; case ID_SHARED_COL_TYPE: textBuffer = GetFiletypeByName(file->GetFileName()); break; case ID_SHARED_COL_PRIO: textBuffer = PriorityToStr(file->GetUpPriority(), file->IsAutoUpPriority()); break; case ID_SHARED_COL_ID: textBuffer = file->GetFileHash().Encode(); break; case ID_SHARED_COL_REQ: textBuffer = CFormat(wxT("%u (%u)")) % file->statistic.GetRequests() % file->statistic.GetAllTimeRequests(); break; case ID_SHARED_COL_AREQ: textBuffer = CFormat(wxT("%u (%u)")) % file->statistic.GetAccepts() % file->statistic.GetAllTimeAccepts(); break; case ID_SHARED_COL_TRA: textBuffer = CastItoXBytes(file->statistic.GetTransferred()) + wxT(" (") + CastItoXBytes(file->statistic.GetAllTimeTransferred()) + wxT(")"); break; case ID_SHARED_COL_RTIO: textBuffer = CFormat(wxT("%.2f")) % ((double)file->statistic.GetAllTimeTransferred() / file->GetFileSize()); break; case ID_SHARED_COL_PART: if ( file->GetPartCount() ) { wxRect barRect(columnRect.x, columnRect. y + 1, columnRect.width, columnRect.height - 2); DrawAvailabilityBar(file, dc, barRect); } break; case ID_SHARED_COL_CMPL: if ( file->m_nCompleteSourcesCountLo == 0 ) { if ( file->m_nCompleteSourcesCountHi ) { textBuffer = CFormat(wxT("< %u")) % file->m_nCompleteSourcesCountHi; } else { textBuffer = wxT("0"); } } else if (file->m_nCompleteSourcesCountLo == file->m_nCompleteSourcesCountHi) { textBuffer = CFormat(wxT("%u")) % file->m_nCompleteSourcesCountLo; } else { textBuffer = CFormat(wxT("%u - %u")) % file->m_nCompleteSourcesCountLo % file->m_nCompleteSourcesCountHi; } break; case ID_SHARED_COL_PATH: if ( file->IsPartFile() ) { textBuffer = _("[PartFile]"); } else { textBuffer = file->GetFilePath().GetPrintable(); } } if (!textBuffer.IsEmpty()) { dc->DrawText(textBuffer, columnRect.x, columnRect.y + textVOffset); } } // Move to the next column columnLeft += columnWidth; } }