Upstream tarball 9401
[amule.git] / src / DownloadQueue.cpp
blobaaf59d7260d893f443d256717e5628ef5e04a7cf
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "DownloadQueue.h" // Interface declarations
28 #include <protocol/Protocols.h>
29 #include <protocol/kad/Constants.h>
30 #include <common/Macros.h>
31 #include <common/MenuIDs.h>
32 #include <common/Constants.h>
34 #include <wx/textfile.h> // Needed for wxTextFile
35 #include <wx/utils.h>
37 #include "Server.h" // Needed for CServer
38 #include "Packet.h" // Needed for CPacket
39 #include "MemFile.h" // Needed for CMemFile
40 #include "ClientList.h" // Needed for CClientList
41 #include "updownclient.h" // Needed for CUpDownClient
42 #include "ServerList.h" // Needed for CServerList
43 #include "ServerConnect.h" // Needed for CServerConnect
44 #include "ED2KLink.h" // Needed for CED2KFileLink
45 #include "SearchList.h" // Needed for CSearchFile
46 #include "SharedFileList.h" // Needed for CSharedFileList
47 #include "PartFile.h" // Needed for CPartFile
48 #include "Preferences.h" // Needed for thePrefs
49 #include "amule.h" // Needed for theApp
50 #include "AsyncDNS.h" // Needed for CAsyncDNS
51 #include "Statistics.h" // Needed for theStats
52 #include "Logger.h"
53 #include <common/Format.h> // Needed for CFormat
54 #include "IPFilter.h"
55 #include <common/FileFunctions.h> // Needed for CDirIterator
56 #include "FileLock.h" // Needed for CFileLock
57 #include "GuiEvents.h" // Needed for Notify_*
58 #include "UserEvents.h"
59 #include "MagnetURI.h" // Needed for CMagnetED2KConverter
60 #include "ScopedPtr.h" // Needed for CScopedPtr
61 #include "PlatformSpecific.h" // Needed for CanFSHandleLargeFiles
63 #include "kademlia/kademlia/Kademlia.h"
65 #include <string> // Do_not_auto_remove (mingw-gcc-3.4.5)
68 // Max. file IDs per UDP packet
69 // ----------------------------
70 // 576 - 30 bytes of header (28 for UDP, 2 for "E3 9A" edonkey proto) = 546 bytes
71 // 546 / 16 = 34
74 #define MAX_FILES_PER_UDP_PACKET 31 // 2+16*31 = 498 ... is still less than 512 bytes!!
75 #define MAX_REQUESTS_PER_SERVER 35
78 CDownloadQueue::CDownloadQueue()
79 // Needs to be recursive that that is can own an observer assigned to itself
80 : m_mutex( wxMUTEX_RECURSIVE )
82 m_datarate = 0;
83 m_udpserver = 0;
84 m_lastsorttime = 0;
85 m_lastudpsearchtime = 0;
86 m_lastudpstattime = 0;
87 m_udcounter = 0;
88 m_nLastED2KLinkCheck = 0;
89 m_dwNextTCPSrcReq = 0;
90 m_cRequestsSentToServer = 0;
91 m_lastDiskCheck = 0;
92 SetLastKademliaFileRequest();
96 CDownloadQueue::~CDownloadQueue()
98 if ( !m_filelist.empty() ) {
99 for ( unsigned int i = 0; i < m_filelist.size(); i++ ) {
100 AddLogLineNS(CFormat(_("Saving PartFile %u of %u")) % (i + 1) % m_filelist.size());
101 delete m_filelist[i];
103 AddLogLineNS(_("All PartFiles Saved."));
108 void CDownloadQueue::LoadMetFiles(const CPath& path)
110 AddLogLineNS(CFormat(_("Loading temp files from %s.")) % path.GetPrintable());
112 std::vector<CPath> files;
114 // Locate part-files to be loaded
115 CDirIterator TempDir(path);
116 CPath fileName = TempDir.GetFirstFile(CDirIterator::File, wxT("*.part.met"));
117 while (fileName.IsOk()) {
118 files.push_back(path.JoinPaths(fileName));
120 fileName = TempDir.GetNextFile();
123 // Loading in order makes it easier to figure which
124 // file is broken in case of crashes, or the like.
125 std::sort(files.begin(), files.end());
127 // Load part-files
128 for ( size_t i = 0; i < files.size(); i++ ) {
129 AddLogLineNS(CFormat(_("Loading PartFile %u of %u")) % (i + 1) % files.size());
130 fileName = files[i].GetFullName();
131 CPartFile *toadd = new CPartFile();
132 bool result = toadd->LoadPartFile(path, fileName) != 0;
133 if (!result) {
134 // Try from backup
135 result = toadd->LoadPartFile(path, fileName, true) != 0;
137 if (result && !IsFileExisting(toadd->GetFileHash())) {
139 wxMutexLocker lock(m_mutex);
140 m_filelist.push_back(toadd);
142 NotifyObservers(EventType(EventType::INSERTED, toadd));
143 Notify_DownloadCtrlAddFile(toadd);
144 } else {
145 wxString msg;
146 if (result) {
147 msg << CFormat(wxT("WARNING: Duplicate partfile with hash '%s' found, skipping: %s"))
148 % toadd->GetFileHash().Encode() % fileName;
149 } else {
150 // If result is false, then reading of both the primary and the backup .met failed
151 AddLogLineM(false,
152 _("ERROR: Failed to load backup file. Search http://forum.amule.org for .part.met recovery solutions."));
153 msg << CFormat(wxT("ERROR: Failed to load PartFile '%s'")) % fileName;
155 AddLogLineCS(msg);
157 // Delete the partfile object in the end.
158 delete toadd;
161 AddLogLineNS(_("All PartFiles Loaded."));
163 if ( GetFileCount() == 0 ) {
164 AddLogLineM(false, _("No part files found"));
165 } else {
166 AddLogLineM(false, wxString::Format(wxPLURAL("Found %u part file", "Found %u part files", GetFileCount()), GetFileCount()) );
168 DoSortByPriority();
169 CheckDiskspace( path );
174 uint16 CDownloadQueue::GetFileCount() const
176 wxMutexLocker lock( m_mutex );
178 return m_filelist.size();
182 CServer* CDownloadQueue::GetUDPServer() const
184 wxMutexLocker lock( m_mutex );
186 return m_udpserver;
190 void CDownloadQueue::SetUDPServer( CServer* server )
192 wxMutexLocker lock( m_mutex );
194 m_udpserver = server;
198 void CDownloadQueue::SaveSourceSeeds()
200 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
201 GetFileByIndex( i )->SaveSourceSeeds();
206 void CDownloadQueue::LoadSourceSeeds()
208 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
209 GetFileByIndex( i )->LoadSourceSeeds();
214 void CDownloadQueue::AddSearchToDownload(CSearchFile* toadd, uint8 category)
216 if ( IsFileExisting(toadd->GetFileHash()) ) {
217 return;
220 if (toadd->GetFileSize() > OLD_MAX_FILE_SIZE) {
221 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
222 AddLogLineM(true, _("Filesystem for Temp directory cannot handle large files."));
223 return;
224 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
225 AddLogLineM(true, _("Filesystem for Incoming directory cannot handle large files."));
226 return;
230 CPartFile* newfile = NULL;
231 try {
232 newfile = new CPartFile(toadd);
233 } catch (const CInvalidPacket& WXUNUSED(e)) {
234 AddDebugLogLineM(true, logDownloadQueue, wxT("Search-result contained invalid tags, could not add"));
237 if ( newfile && newfile->GetStatus() != PS_ERROR ) {
238 AddDownload( newfile, thePrefs::AddNewFilesPaused(), category );
239 // Add any possible sources
240 if (toadd->GetClientID() && toadd->GetClientPort()) {
241 CMemFile sources(1+4+2);
242 sources.WriteUInt8(1);
243 sources.WriteUInt32(toadd->GetClientID());
244 sources.WriteUInt16(toadd->GetClientPort());
245 sources.Reset();
246 newfile->AddSources(sources, toadd->GetClientServerIP(), toadd->GetClientServerPort(), SF_SEARCH_RESULT, false);
248 for (std::list<CSearchFile::ClientStruct>::const_iterator it = toadd->GetClients().begin(); it != toadd->GetClients().end(); ++it) {
249 CMemFile sources(1+4+2);
250 sources.WriteUInt8(1);
251 sources.WriteUInt32(it->m_ip);
252 sources.WriteUInt16(it->m_port);
253 sources.Reset();
254 newfile->AddSources(sources, it->m_serverIP, it->m_serverPort, SF_SEARCH_RESULT, false);
256 } else {
257 delete newfile;
262 struct SFindBestPF
264 void operator()(CPartFile* file) {
265 // Check if we should filter out other categories
266 if ((m_category != -1) && (file->GetCategory() != m_category)) {
267 return;
268 } else if (file->GetStatus() != PS_PAUSED) {
269 return;
272 if (!m_result || (file->GetDownPriority() > m_result->GetDownPriority())) {
273 m_result = file;
277 //! The category to look for, or -1 if any category is good
278 int m_category;
279 //! If any acceptable files are found, this variable store their pointer
280 CPartFile* m_result;
284 void CDownloadQueue::StartNextFile(CPartFile* oldfile)
286 if ( thePrefs::StartNextFile() ) {
287 SFindBestPF visitor = { -1, NULL };
290 wxMutexLocker lock(m_mutex);
292 if (thePrefs::StartNextFileSame()) {
293 // Get a download in the same category
294 visitor.m_category = oldfile->GetCategory();
296 visitor = std::for_each(m_filelist.begin(), m_filelist.end(), visitor);
299 if (visitor.m_result == NULL) {
300 // Get a download, regardless of category
301 visitor.m_category = -1;
303 visitor = std::for_each(m_filelist.begin(), m_filelist.end(), visitor);
307 if (visitor.m_result) {
308 visitor.m_result->ResumeFile();
314 void CDownloadQueue::AddDownload(CPartFile* file, bool paused, uint8 category)
316 wxCHECK_RET(!IsFileExisting(file->GetFileHash()), wxT("Adding duplicate part-file"));
318 if (file->GetStatus(true) == PS_ALLOCATING) {
319 file->PauseFile();
320 } else if (paused && GetFileCount()) {
321 file->StopFile();
325 wxMutexLocker lock(m_mutex);
326 m_filelist.push_back( file );
327 DoSortByPriority();
330 NotifyObservers( EventType( EventType::INSERTED, file ) );
332 file->SetCategory(category);
333 Notify_DownloadCtrlAddFile( file );
334 AddLogLineM(true, CFormat(_("Downloading %s")) % file->GetFileName() );
338 bool CDownloadQueue::IsFileExisting( const CMD4Hash& fileid ) const
340 if (CKnownFile* file = theApp->sharedfiles->GetFileByID(fileid)) {
341 if (file->IsPartFile()) {
342 AddLogLineM(true, CFormat( _("You are already trying to download the file '%s'") ) % file->GetFileName());
343 } else {
344 // Check if the file exists, since otherwise the user is forced to
345 // manually reload the shares to download a file again.
346 CPath fullpath = file->GetFilePath().JoinPaths(file->GetFileName());
347 if (!fullpath.FileExists()) {
348 // The file is no longer available, unshare it
349 theApp->sharedfiles->RemoveFile(file);
351 return false;
354 AddLogLineM(true, CFormat( _("You already have the file '%s'") ) % file->GetFileName());
357 return true;
358 } else if ((file = GetFileByID(fileid))) {
359 AddLogLineM(true, CFormat( _("You are already trying to download the file %s") ) % file->GetFileName());
360 return true;
363 return false;
367 void CDownloadQueue::Process()
369 // send src requests to local server
370 ProcessLocalRequests();
373 wxMutexLocker lock(m_mutex);
375 uint32 downspeed = 0;
376 if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) {
377 downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1);
378 if (downspeed < 50) {
379 downspeed = 50;
380 } else if (downspeed > 200) {
381 downspeed = 200;
385 m_datarate = 0;
386 m_udcounter++;
387 uint32 cur_datarate = 0;
388 uint32 cur_udcounter = m_udcounter;
390 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
391 CPartFile* file = m_filelist[i];
393 CMutexUnlocker unlocker(m_mutex);
395 if ( file->GetStatus() == PS_READY || file->GetStatus() == PS_EMPTY ){
396 cur_datarate += file->Process( downspeed, cur_udcounter );
397 } else {
398 //This will make sure we don't keep old sources to paused and stoped files..
399 file->StopPausedFile();
403 m_datarate += cur_datarate;
406 if (m_udcounter == 5) {
407 if (theApp->serverconnect->IsUDPSocketAvailable()) {
408 if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) {
409 m_lastudpstattime = ::GetTickCount();
411 CMutexUnlocker unlocker(m_mutex);
412 theApp->serverlist->ServerStats();
417 if (m_udcounter == 10) {
418 m_udcounter = 0;
419 if (theApp->serverconnect->IsUDPSocketAvailable()) {
420 if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) {
421 SendNextUDPPacket();
426 if ( (::GetTickCount() - m_lastsorttime) > 10000 ) {
429 DoSortByPriority();
431 // Check if any paused files can be resumed
433 CheckDiskspace(thePrefs::GetTempDir());
437 // Check for new links once per second.
438 if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) {
439 AddLinksFromFile();
440 m_nLastED2KLinkCheck = ::GetTickCount();
445 CPartFile* CDownloadQueue::GetFileByID(const CMD4Hash& filehash) const
447 wxMutexLocker lock( m_mutex );
449 for ( uint16 i = 0; i < m_filelist.size(); ++i ) {
450 if ( filehash == m_filelist[i]->GetFileHash()) {
451 return m_filelist[ i ];
455 return NULL;
459 CPartFile* CDownloadQueue::GetFileByIndex(unsigned int index) const
461 wxMutexLocker lock( m_mutex );
463 if ( index < m_filelist.size() ) {
464 return m_filelist[ index ];
467 wxASSERT( false );
468 return NULL;
472 bool CDownloadQueue::IsPartFile(const CKnownFile* file) const
474 wxMutexLocker lock(m_mutex);
476 for (uint16 i = 0; i < m_filelist.size(); ++i) {
477 if (file == m_filelist[i]) {
478 return true;
482 return false;
486 void CDownloadQueue::OnConnectionState(bool bConnected)
488 wxMutexLocker lock(m_mutex);
490 for (uint16 i = 0; i < m_filelist.size(); ++i) {
491 if ( m_filelist[i]->GetStatus() == PS_READY ||
492 m_filelist[i]->GetStatus() == PS_EMPTY) {
493 m_filelist[i]->SetActive(bConnected);
499 void CDownloadQueue::CheckAndAddSource(CPartFile* sender, CUpDownClient* source)
501 // if we block loopbacks at this point it should prevent us from connecting to ourself
502 if ( source->HasValidHash() ) {
503 if ( source->GetUserHash() == thePrefs::GetUserHash() ) {
504 AddDebugLogLineM( false, logDownloadQueue, wxT("Tried to add source with matching hash to your own.") );
505 source->Safe_Delete();
506 return;
510 if (sender->IsStopped()) {
511 source->Safe_Delete();
512 return;
515 // Filter sources which are known to be dead/useless
516 if ( theApp->clientlist->IsDeadSource( source ) || sender->IsDeadSource(source) ) {
517 source->Safe_Delete();
518 return;
521 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
522 if ( (source->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source->HasValidHash())) || (thePrefs::IsClientCryptLayerRequired() && (!source->SupportsCryptLayer() || !source->HasValidHash()))) {
523 source->Safe_Delete();
524 return;
527 // Find all clients with the same hash
528 if ( source->HasValidHash() ) {
529 CClientList::SourceList found = theApp->clientlist->GetClientsByHash( source->GetUserHash() );
531 CClientList::SourceList::iterator it = found.begin();
532 for ( ; it != found.end(); it++ ) {
533 CKnownFile* file = (*it)->GetRequestFile();
535 // Only check files on the download-queue
536 if ( file ) {
537 // Is the found source queued for something else?
538 if ( file != sender ) {
539 // Try to add a request for the other file
540 if ( (*it)->AddRequestForAnotherFile(sender)) {
541 // Add it to downloadlistctrl
542 Notify_DownloadCtrlAddSource(sender, *it, A4AF_SOURCE);
546 source->Safe_Delete();
547 return;
554 // Our new source is real new but maybe it is already uploading to us?
555 // If yes the known client will be attached to the var "source" and the old
556 // source-client will be deleted. However, if the request file of the known
557 // source is NULL, then we have to treat it almost like a new source and if
558 // it isn't NULL and not "sender", then we shouldn't move it, but rather add
559 // a request for the new file.
560 ESourceFrom nSourceFrom = source->GetSourceFrom();
561 if ( theApp->clientlist->AttachToAlreadyKnown(&source, 0) ) {
562 // Already queued for another file?
563 if ( source->GetRequestFile() ) {
564 // If we're already queued for the right file, then there's nothing to do
565 if ( sender != source->GetRequestFile() ) {
566 // Add the new file to the request list
567 source->AddRequestForAnotherFile( sender );
569 } else {
570 // Source was known, but reqfile NULL.
571 source->SetRequestFile( sender );
572 if (source->GetSourceFrom() != nSourceFrom) {
573 if (source->GetSourceFrom() != SF_NONE) {
574 theStats::RemoveSourceOrigin(source->GetSourceFrom());
575 theStats::RemoveFoundSource();
577 source->SetSourceFrom(nSourceFrom);
579 sender->AddSource( source );
580 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
581 sender->UpdateFileRatingCommentAvail();
584 Notify_DownloadCtrlAddSource(sender, source, UNAVAILABLE_SOURCE);
586 } else {
587 // Unknown client, add it to the clients list
588 source->SetRequestFile( sender );
590 theApp->clientlist->AddClient(source);
592 sender->AddSource( source );
593 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
594 sender->UpdateFileRatingCommentAvail();
597 Notify_DownloadCtrlAddSource(sender, source, UNAVAILABLE_SOURCE);
602 void CDownloadQueue::CheckAndAddKnownSource(CPartFile* sender,CUpDownClient* source)
604 // Kad reviewed
606 if (sender->IsStopped()) {
607 return;
610 // Filter sources which are known to be dead/useless
611 if ( sender->IsDeadSource(source) ) {
612 return;
615 // "Filter LAN IPs" -- this may be needed here in case we are connected to the internet and are also connected
616 // to a LAN and some client from within the LAN connected to us. Though this situation may be supported in future
617 // by adding that client to the source list and filtering that client's LAN IP when sending sources to
618 // a client within the internet.
620 // "IPfilter" is not needed here, because that "known" client was already IPfiltered when receiving OP_HELLO.
621 if (!source->HasLowID()) {
622 uint32 nClientIP = wxUINT32_SWAP_ALWAYS(source->GetUserIDHybrid());
623 if (!IsGoodIP(nClientIP, thePrefs::FilterLanIPs())) { // check for 0-IP, localhost and LAN addresses
624 AddDebugLogLineM(false, logIPFilter, wxT("Ignored already known source with IP=%s") + Uint32toStringIP(nClientIP));
625 return;
629 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
630 if ( (source->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source->HasValidHash())) || (thePrefs::IsClientCryptLayerRequired() && (!source->SupportsCryptLayer() || !source->HasValidHash())))
632 source->Safe_Delete();
633 return;
636 CPartFile* file = source->GetRequestFile();
638 // Check if the file is already queued for something else
639 if ( file ) {
640 if ( file != sender ) {
641 if ( source->AddRequestForAnotherFile( sender ) ) {
642 Notify_DownloadCtrlAddSource( sender, source, A4AF_SOURCE );
645 } else {
646 source->SetRequestFile( sender );
648 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
649 sender->UpdateFileRatingCommentAvail();
652 source->SetSourceFrom(SF_PASSIVE);
653 sender->AddSource( source );
654 Notify_DownloadCtrlAddSource( sender, source, UNAVAILABLE_SOURCE);
659 bool CDownloadQueue::RemoveSource(CUpDownClient* toremove, bool WXUNUSED(updatewindow), bool bDoStatsUpdate)
661 bool removed = false;
662 toremove->DeleteAllFileRequests();
664 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
665 CPartFile* cur_file = GetFileByIndex( i );
667 // Remove from source-list
668 if ( cur_file->DelSource( toremove ) ) {
669 cur_file->RemoveDownloadingSource(toremove);
670 removed = true;
671 if ( bDoStatsUpdate ) {
672 cur_file->UpdatePartsInfo();
676 // Remove from A4AF-list
677 cur_file->RemoveA4AFSource( toremove );
681 if ( !toremove->GetFileComment().IsEmpty() || toremove->GetFileRating()>0) {
682 toremove->GetRequestFile()->UpdateFileRatingCommentAvail();
685 toremove->SetRequestFile( NULL );
686 toremove->SetDownloadState(DS_NONE);
688 // Remove from downloadlist widget
689 Notify_DownloadCtrlRemoveSource(toremove, (CPartFile*)NULL);
690 toremove->ResetFileStatusInfo();
692 return removed;
696 void CDownloadQueue::RemoveFile(CPartFile* file)
698 RemoveLocalServerRequest( file );
700 NotifyObservers( EventType( EventType::REMOVED, file ) );
702 wxMutexLocker lock( m_mutex );
704 EraseValue( m_filelist, file );
708 CUpDownClient* CDownloadQueue::GetDownloadClientByIP_UDP(uint32 dwIP, uint16 nUDPPort) const
710 wxMutexLocker lock( m_mutex );
712 for ( unsigned int i = 0; i < m_filelist.size(); i++ ) {
713 const CPartFile::SourceSet& set = m_filelist[i]->GetSourceList();
715 for ( CPartFile::SourceSet::const_iterator it = set.begin(); it != set.end(); it++ ) {
716 if ( (*it)->GetIP() == dwIP && (*it)->GetUDPPort() == nUDPPort ) {
717 return *it;
721 return NULL;
726 * Checks if the specified server is the one we are connected to.
728 bool IsConnectedServer(const CServer* server)
730 if (server && theApp->serverconnect->GetCurrentServer()) {
731 wxString srvAddr = theApp->serverconnect->GetCurrentServer()->GetAddress();
732 uint16 srvPort = theApp->serverconnect->GetCurrentServer()->GetPort();
734 return server->GetAddress() == srvAddr && server->GetPort() == srvPort;
737 return false;
741 bool CDownloadQueue::SendNextUDPPacket()
743 if ( m_filelist.empty() || !theApp->serverconnect->IsUDPSocketAvailable() || !theApp->IsConnectedED2K()) {
744 return false;
747 // Start monitoring the server and the files list
748 if ( !m_queueServers.IsActive() ) {
749 AddObserver( &m_queueFiles );
751 theApp->serverlist->AddObserver( &m_queueServers );
755 bool packetSent = false;
756 while ( !packetSent ) {
757 // Get max files ids per packet for current server
758 int filesAllowed = GetMaxFilesPerUDPServerPacket();
760 if (filesAllowed < 1 || !m_udpserver || IsConnectedServer(m_udpserver)) {
761 // Select the next server to ask, must not be the connected server
762 do {
763 m_udpserver = m_queueServers.GetNext();
764 } while (IsConnectedServer(m_udpserver));
766 m_cRequestsSentToServer = 0;
767 filesAllowed = GetMaxFilesPerUDPServerPacket();
771 // Check if we have asked all servers, in which case we are done
772 if (m_udpserver == NULL) {
773 DoStopUDPRequests();
775 return false;
778 // Memoryfile containing the hash of every file to request
779 // 28bytes allocation because 16b + 4b + 8b is the worse case scenario.
780 CMemFile hashlist( 28 );
782 CPartFile* file = m_queueFiles.GetNext();
784 while ( file && filesAllowed ) {
785 uint8 status = file->GetStatus();
787 if ( ( status == PS_READY || status == PS_EMPTY ) && file->GetSourceCount() < thePrefs::GetMaxSourcePerFileUDP() ) {
788 if (file->IsLargeFile() && !m_udpserver->SupportsLargeFilesUDP()) {
789 AddDebugLogLineM(false, logDownloadQueue, wxT("UDP Request for sources on a large file ignored: server doesn't support it"));
790 } else {
791 ++m_cRequestsSentToServer;
792 hashlist.WriteHash( file->GetFileHash() );
793 // See the notes on TCP packet
794 if ( m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2 ) {
795 if (file->IsLargeFile()) {
796 wxASSERT(m_udpserver->SupportsLargeFilesUDP());
797 hashlist.WriteUInt32( 0 );
798 hashlist.WriteUInt64( file->GetFileSize() );
799 } else {
800 hashlist.WriteUInt32( file->GetFileSize() );
803 --filesAllowed;
807 // Avoid skipping a file if we can't send any more currently
808 if ( filesAllowed ) {
809 file = m_queueFiles.GetNext();
813 // See if we have anything to send
814 if ( hashlist.GetLength() ) {
815 packetSent = SendGlobGetSourcesUDPPacket(hashlist);
818 // Check if we've covered every file
819 if ( file == NULL ) {
820 // Reset the list of asked files so that the loop will start over
821 m_queueFiles.Reset();
823 // Unset the server so that the next server will be used
824 m_udpserver = NULL;
828 return true;
832 void CDownloadQueue::StopUDPRequests()
834 wxMutexLocker lock( m_mutex );
836 DoStopUDPRequests();
840 void CDownloadQueue::DoStopUDPRequests()
842 // No need to observe when we wont be using the results
843 theApp->serverlist->RemoveObserver( &m_queueServers );
844 RemoveObserver( &m_queueFiles );
846 m_udpserver = 0;
847 m_lastudpsearchtime = ::GetTickCount();
851 // Comparison function needed by sort. Returns true if file1 preceeds file2
852 bool ComparePartFiles(const CPartFile* file1, const CPartFile* file2) {
853 if (file1->GetDownPriority() != file2->GetDownPriority()) {
854 // To place high-priority files before low priority files we have to
855 // invert this test, since PR_LOW is lower than PR_HIGH, and since
856 // placing a PR_LOW file before a PR_HIGH file would mean that
857 // the PR_LOW file gets sources before the PR_HIGH file ...
858 return (file1->GetDownPriority() > file2->GetDownPriority());
859 } else {
860 int sourcesA = file1->GetSourceCount();
861 int sourcesB = file2->GetSourceCount();
863 int notSourcesA = file1->GetNotCurrentSourcesCount();
864 int notSourcesB = file2->GetNotCurrentSourcesCount();
866 int cmp = CmpAny( sourcesA - notSourcesA, sourcesB - notSourcesB );
868 if ( cmp == 0 ) {
869 cmp = CmpAny( notSourcesA, notSourcesB );
872 return cmp < 0;
877 void CDownloadQueue::DoSortByPriority()
879 m_lastsorttime = ::GetTickCount();
880 sort( m_filelist.begin(), m_filelist.end(), ComparePartFiles );
884 void CDownloadQueue::ResetLocalServerRequests()
886 wxMutexLocker lock( m_mutex );
888 m_dwNextTCPSrcReq = 0;
889 m_localServerReqQueue.clear();
891 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
892 m_filelist[i]->SetLocalSrcRequestQueued(false);
897 void CDownloadQueue::RemoveLocalServerRequest( CPartFile* file )
899 wxMutexLocker lock( m_mutex );
901 EraseValue( m_localServerReqQueue, file );
903 file->SetLocalSrcRequestQueued(false);
907 void CDownloadQueue::ProcessLocalRequests()
909 wxMutexLocker lock( m_mutex );
911 bool bServerSupportsLargeFiles = theApp->serverconnect
912 && theApp->serverconnect->GetCurrentServer()
913 && theApp->serverconnect->GetCurrentServer()->SupportsLargeFilesTCP();
915 if ( (!m_localServerReqQueue.empty()) && (m_dwNextTCPSrcReq < ::GetTickCount()) ) {
916 CMemFile dataTcpFrame(22);
917 const int iMaxFilesPerTcpFrame = 15;
918 int iFiles = 0;
919 while (!m_localServerReqQueue.empty() && iFiles < iMaxFilesPerTcpFrame) {
920 // find the file with the longest waitingtime
921 uint32 dwBestWaitTime = 0xFFFFFFFF;
923 std::list<CPartFile*>::iterator posNextRequest = m_localServerReqQueue.end();
924 std::list<CPartFile*>::iterator it = m_localServerReqQueue.begin();
925 while( it != m_localServerReqQueue.end() ) {
926 CPartFile* cur_file = (*it);
927 if (cur_file->GetStatus() == PS_READY || cur_file->GetStatus() == PS_EMPTY) {
928 uint8 nPriority = cur_file->GetDownPriority();
929 if (nPriority > PR_HIGH) {
930 wxASSERT(0);
931 nPriority = PR_HIGH;
934 if (cur_file->GetLastSearchTime() + (PR_HIGH-nPriority) < dwBestWaitTime ){
935 dwBestWaitTime = cur_file->GetLastSearchTime() + (PR_HIGH - nPriority);
936 posNextRequest = it;
939 it++;
940 } else {
941 it = m_localServerReqQueue.erase(it);
942 cur_file->SetLocalSrcRequestQueued(false);
943 AddDebugLogLineM( false, logDownloadQueue,
944 CFormat(wxT("Local server source request for file '%s' not sent because of status '%s'"))
945 % cur_file->GetFileName() % cur_file->getPartfileStatus());
949 if (posNextRequest != m_localServerReqQueue.end()) {
950 CPartFile* cur_file = (*posNextRequest);
951 cur_file->SetLocalSrcRequestQueued(false);
952 cur_file->SetLastSearchTime(::GetTickCount());
953 m_localServerReqQueue.erase(posNextRequest);
954 iFiles++;
956 if (!bServerSupportsLargeFiles && cur_file->IsLargeFile()) {
957 AddDebugLogLineM(false, logDownloadQueue, wxT("TCP Request for sources on a large file ignored: server doesn't support it"));
958 } else {
959 AddDebugLogLineM(false, logDownloadQueue,
960 CFormat(wxT("Creating local sources request packet for '%s'")) % cur_file->GetFileName());
961 // create request packet
962 CMemFile data(16 + (cur_file->IsLargeFile() ? 8 : 4));
963 data.WriteHash(cur_file->GetFileHash());
964 // Kry - lugdunum extended protocol on 17.3 to handle filesize properly.
965 // There is no need to check anything, old server ignore the extra 4 bytes.
966 // As of 17.9, servers accept a 0 32-bits size and then a 64bits size
967 if (cur_file->IsLargeFile()) {
968 wxASSERT(bServerSupportsLargeFiles);
969 data.WriteUInt32(0);
970 data.WriteUInt64(cur_file->GetFileSize());
971 } else {
972 data.WriteUInt32(cur_file->GetFileSize());
974 uint8 byOpcode = 0;
975 if (thePrefs::IsClientCryptLayerSupported() && theApp->serverconnect->GetCurrentServer() != NULL && theApp->serverconnect->GetCurrentServer()->SupportsGetSourcesObfuscation()) {
976 byOpcode = OP_GETSOURCES_OBFU;
977 } else {
978 byOpcode = OP_GETSOURCES;
980 CPacket packet(data, OP_EDONKEYPROT, byOpcode);
981 dataTcpFrame.Write(packet.GetPacket(), packet.GetRealPacketSize());
986 int iSize = dataTcpFrame.GetLength();
987 if (iSize > 0) {
988 // create one 'packet' which contains all buffered OP_GETSOURCES ED2K packets to be sent with one TCP frame
989 // server credits: (16+4)*regularfiles + (16+4+8)*largefiles +1
990 CScopedPtr<CPacket> packet(new CPacket(new byte[iSize], dataTcpFrame.GetLength(), true, false));
991 dataTcpFrame.Seek(0, wxFromStart);
992 dataTcpFrame.Read(packet->GetPacket(), iSize);
993 uint32 size = packet->GetPacketSize();
994 theApp->serverconnect->SendPacket(packet.release(), true); // Deletes `packet'.
995 AddDebugLogLineM(false, logDownloadQueue, wxT("Sent local sources request packet."));
996 theStats::AddUpOverheadServer(size);
999 // next TCP frame with up to 15 source requests is allowed to be sent in..
1000 m_dwNextTCPSrcReq = ::GetTickCount() + SEC2MS(iMaxFilesPerTcpFrame*(16+4));
1006 void CDownloadQueue::SendLocalSrcRequest(CPartFile* sender)
1008 wxMutexLocker lock( m_mutex );
1010 m_localServerReqQueue.push_back(sender);
1014 void CDownloadQueue::AddLinksFromFile()
1016 const wxString fullPath = theApp->ConfigDir + wxT("ED2KLinks");
1017 if (!wxFile::Exists(fullPath)) {
1018 return;
1021 // Attempt to lock the ED2KLinks file.
1022 CFileLock lock((const char*)unicode2char(fullPath));
1024 wxTextFile file(fullPath);
1025 if ( file.Open() ) {
1026 for ( unsigned int i = 0; i < file.GetLineCount(); i++ ) {
1027 wxString line = file.GetLine( i ).Strip( wxString::both );
1029 if ( !line.IsEmpty() ) {
1030 // Special case! used by a secondary running mule to raise this one.
1031 if ( line == wxT("RAISE_DIALOG") ) {
1032 Notify_ShowGUI();
1033 continue;
1036 AddLink( line );
1040 file.Close();
1041 } else {
1042 AddLogLineNS(_("Failed to open ED2KLinks file."));
1045 // Delete the file.
1046 wxRemoveFile(theApp->ConfigDir + wxT("ED2KLinks"));
1050 void CDownloadQueue::ResetCatParts(uint8 cat)
1052 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
1053 CPartFile* file = GetFileByIndex( i );
1055 if ( file->GetCategory() == cat ) {
1056 // Reset the category
1057 file->SetCategory( 0 );
1058 } else if ( file->GetCategory() > cat ) {
1059 // Set to the new position of the original category
1060 file->SetCategory( file->GetCategory() - 1 );
1066 void CDownloadQueue::SetCatPrio(uint8 cat, uint8 newprio)
1068 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
1069 CPartFile* file = GetFileByIndex( i );
1071 if ( !cat || file->GetCategory() == cat ) {
1072 if ( newprio == PR_AUTO ) {
1073 file->SetAutoDownPriority(true);
1074 } else {
1075 file->SetAutoDownPriority(false);
1076 file->SetDownPriority(newprio);
1083 void CDownloadQueue::SetCatStatus(uint8 cat, int newstatus)
1085 std::list<CPartFile*> files;
1088 wxMutexLocker lock(m_mutex);
1090 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1091 if ( m_filelist[i]->CheckShowItemInGivenCat(cat) ) {
1092 files.push_back( m_filelist[i] );
1097 std::list<CPartFile*>::iterator it = files.begin();
1099 for ( ; it != files.end(); it++ ) {
1100 switch ( newstatus ) {
1101 case MP_CANCEL: (*it)->Delete(); break;
1102 case MP_PAUSE: (*it)->PauseFile(); break;
1103 case MP_STOP: (*it)->StopFile(); break;
1104 case MP_RESUME: (*it)->ResumeFile(); break;
1110 uint16 CDownloadQueue::GetDownloadingFileCount() const
1112 wxMutexLocker lock( m_mutex );
1114 uint16 count = 0;
1115 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1116 uint8 status = m_filelist[i]->GetStatus();
1117 if ( status == PS_READY || status == PS_EMPTY ) {
1118 count++;
1122 return count;
1126 uint16 CDownloadQueue::GetPausedFileCount() const
1128 wxMutexLocker lock( m_mutex );
1130 uint16 count = 0;
1131 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1132 if ( m_filelist[i]->GetStatus() == PS_PAUSED ) {
1133 count++;
1137 return count;
1141 void CDownloadQueue::CheckDiskspace( const CPath& path )
1143 if ( ::GetTickCount() - m_lastDiskCheck < DISKSPACERECHECKTIME ) {
1144 return;
1147 m_lastDiskCheck = ::GetTickCount();
1149 uint64 min = 0;
1150 // Check if the user has set an explicit limit
1151 if ( thePrefs::IsCheckDiskspaceEnabled() ) {
1152 min = thePrefs::GetMinFreeDiskSpace();
1155 // The very least acceptable diskspace is a single PART
1156 if ( min < PARTSIZE ) {
1157 min = PARTSIZE;
1160 uint64 free = CPath::GetFreeSpaceAt(path);
1161 if (free == static_cast<uint64>(wxInvalidOffset)) {
1162 return;
1163 } else if (free < min) {
1164 CUserEvents::ProcessEvent(
1165 CUserEvents::OutOfDiskSpace,
1166 wxT("Temporary partition"));
1169 for (unsigned int i = 0; i < m_filelist.size(); ++i) {
1170 CPartFile* file = m_filelist[i];
1172 switch ( file->GetStatus() ) {
1173 case PS_ERROR:
1174 case PS_COMPLETING:
1175 case PS_COMPLETE:
1176 continue;
1179 if ( free >= min && file->GetInsufficient() ) {
1180 // We'll try to resume files if there is enough free space
1181 if ( free - file->GetNeededSpace() > min ) {
1182 file->ResumeFile();
1184 } else if ( free < min && !file->IsPaused() ) {
1185 // No space left, stop the files.
1186 file->PauseFile( true );
1192 int CDownloadQueue::GetMaxFilesPerUDPServerPacket() const
1194 if ( m_udpserver ) {
1195 if ( m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES ) {
1196 // get max. file ids per packet
1197 if ( m_cRequestsSentToServer < MAX_REQUESTS_PER_SERVER ) {
1198 return std::min(
1199 MAX_FILES_PER_UDP_PACKET,
1200 MAX_REQUESTS_PER_SERVER - m_cRequestsSentToServer
1203 } else if ( m_cRequestsSentToServer < MAX_REQUESTS_PER_SERVER ) {
1204 return 1;
1208 return 0;
1212 bool CDownloadQueue::SendGlobGetSourcesUDPPacket(CMemFile& data)
1214 if (!m_udpserver) {
1215 return false;
1218 CPacket packet(data, OP_EDONKEYPROT, ((m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2) ? OP_GLOBGETSOURCES2 : OP_GLOBGETSOURCES));
1220 theStats::AddUpOverheadServer(packet.GetPacketSize());
1221 theApp->serverconnect->SendUDPPacket(&packet,m_udpserver,false);
1223 return true;
1227 void CDownloadQueue::AddToResolve(const CMD4Hash& fileid, const wxString& pszHostname, uint16 port, const wxString& hash, uint8 cryptoptions)
1229 // double checking
1230 if ( !GetFileByID(fileid) ) {
1231 return;
1234 wxMutexLocker lock( m_mutex );
1236 Hostname_Entry entry = { fileid, pszHostname, port, hash, cryptoptions };
1237 m_toresolve.push_front(entry);
1239 // Check if there are other DNS lookups on queue
1240 if (m_toresolve.size() == 1) {
1241 // Check if it is a simple dot address
1242 uint32 ip = StringIPtoUint32(pszHostname);
1244 if (ip) {
1245 OnHostnameResolved(ip);
1246 } else {
1247 CAsyncDNS* dns = new CAsyncDNS(pszHostname, DNS_SOURCE, theApp);
1249 if ((dns->Create() != wxTHREAD_NO_ERROR) || (dns->Run() != wxTHREAD_NO_ERROR)) {
1250 dns->Delete();
1251 m_toresolve.pop_front();
1258 void CDownloadQueue::OnHostnameResolved(uint32 ip)
1260 wxMutexLocker lock( m_mutex );
1262 wxASSERT( m_toresolve.size() );
1264 Hostname_Entry resolved = m_toresolve.front();
1265 m_toresolve.pop_front();
1267 if ( ip ) {
1268 CPartFile* file = GetFileByID( resolved.fileid );
1269 if ( file ) {
1270 CMemFile sources(1+4+2);
1271 sources.WriteUInt8(1); // No. Sources
1272 sources.WriteUInt32(ip);
1273 sources.WriteUInt16(resolved.port);
1274 sources.WriteUInt8(resolved.cryptoptions);
1275 if (resolved.cryptoptions & 0x80) {
1276 wxASSERT(!resolved.hash.IsEmpty());
1277 CMD4Hash sourcehash;
1278 sourcehash.Decode(resolved.hash);
1279 sources.WriteHash(sourcehash);
1281 sources.Seek(0,wxFromStart);
1283 file->AddSources(sources, 0, 0, SF_LINK, true);
1287 while (m_toresolve.size()) {
1288 Hostname_Entry entry = m_toresolve.front();
1290 // Check if it is a simple dot address
1291 uint32 tmpIP = StringIPtoUint32(entry.strHostname);
1293 if (tmpIP) {
1294 OnHostnameResolved(tmpIP);
1295 } else {
1296 CAsyncDNS* dns = new CAsyncDNS(entry.strHostname, DNS_SOURCE, theApp);
1298 if ((dns->Create() != wxTHREAD_NO_ERROR) || (dns->Run() != wxTHREAD_NO_ERROR)) {
1299 dns->Delete();
1300 m_toresolve.pop_front();
1301 } else {
1302 break;
1309 bool CDownloadQueue::AddLink( const wxString& link, int category )
1311 wxString uri(link);
1313 if (link.compare(0, 7, wxT("magnet:")) == 0) {
1314 uri = CMagnetED2KConverter(link);
1315 if (uri.empty()) {
1316 AddLogLineM(true, CFormat(_("Cannot convert magnet link to eD2k: %s")) % link);
1317 return false;
1321 if (uri.compare(0, 7, wxT("ed2k://")) == 0) {
1322 return AddED2KLink(uri, category);
1323 } else {
1324 AddLogLineM(true, CFormat(_("Unknown protocol of link: %s")) % link);
1325 return false;
1330 bool CDownloadQueue::AddED2KLink( const wxString& link, int category )
1332 wxASSERT( !link.IsEmpty() );
1333 wxString URI = link;
1335 // Need the links to end with /, otherwise CreateLinkFromUrl crashes us.
1336 if ( URI.Last() != wxT('/') ) {
1337 URI += wxT("/");
1340 try {
1341 CScopedPtr<CED2KLink> uri(CED2KLink::CreateLinkFromUrl(URI));
1343 return AddED2KLink( uri.get(), category );
1344 } catch ( const wxString& err ) {
1345 AddLogLineM( true, CFormat( _("Invalid eD2k link! ERROR: %s")) % err);
1348 return false;
1352 bool CDownloadQueue::AddED2KLink( const CED2KLink* link, int category )
1354 switch ( link->GetKind() ) {
1355 case CED2KLink::kFile:
1356 return AddED2KLink( dynamic_cast<const CED2KFileLink*>( link ), category );
1358 case CED2KLink::kServer:
1359 return AddED2KLink( dynamic_cast<const CED2KServerLink*>( link ) );
1361 case CED2KLink::kServerList:
1362 return AddED2KLink( dynamic_cast<const CED2KServerListLink*>( link ) );
1364 default:
1365 return false;
1371 bool CDownloadQueue::AddED2KLink( const CED2KFileLink* link, int category )
1373 CPartFile* file = NULL;
1374 if (IsFileExisting(link->GetHashKey())) {
1375 // Must be a shared file if we are to add hashes or sources
1376 if ((file = GetFileByID(link->GetHashKey())) == NULL) {
1377 return false;
1379 } else {
1380 if (link->GetSize() > OLD_MAX_FILE_SIZE) {
1381 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
1382 AddLogLineM(true, _("Filesystem for Temp directory cannot handle large files."));
1383 return false;
1384 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
1385 AddLogLineM(true, _("Filesystem for Incoming directory cannot handle large files."));
1386 return false;
1390 file = new CPartFile(link);
1392 if (file->GetStatus() == PS_ERROR) {
1393 delete file;
1394 return false;
1397 AddDownload(file, thePrefs::AddNewFilesPaused(), category);
1400 if (link->HasValidAICHHash()) {
1401 CAICHHashSet* hashset = file->GetAICHHashset();
1403 if (!hashset->HasValidMasterHash() || (hashset->GetMasterHash() != link->GetAICHHash())) {
1404 hashset->SetMasterHash(link->GetAICHHash(), AICH_VERIFIED);
1405 hashset->FreeHashSet();
1409 const CED2KFileLink::CED2KLinkSourceList& list = link->m_sources;
1410 CED2KFileLink::CED2KLinkSourceList::const_iterator it = list.begin();
1411 for (; it != list.end(); ++it) {
1412 AddToResolve(link->GetHashKey(), it->addr, it->port, it->hash, it->cryptoptions);
1415 return true;
1419 bool CDownloadQueue::AddED2KLink( const CED2KServerLink* link )
1421 CServer *server = new CServer( link->GetPort(), Uint32toStringIP( link->GetIP() ) );
1423 server->SetListName( Uint32toStringIP( link->GetIP() ) );
1425 theApp->serverlist->AddServer(server);
1427 Notify_ServerAdd(server);
1429 return true;
1433 bool CDownloadQueue::AddED2KLink( const CED2KServerListLink* link )
1435 theApp->serverlist->UpdateServerMetFromURL( link->GetAddress() );
1437 return true;
1441 void CDownloadQueue::ObserverAdded( ObserverType* o )
1443 CObservableQueue<CPartFile*>::ObserverAdded( o );
1445 EventType::ValueList list;
1448 wxMutexLocker lock(m_mutex);
1449 list.reserve( m_filelist.size() );
1450 list.insert( list.begin(), m_filelist.begin(), m_filelist.end() );
1453 NotifyObservers( EventType( EventType::INITIAL, &list ), o );
1456 void CDownloadQueue::KademliaSearchFile(uint32_t searchID, const Kademlia::CUInt128* pcontactID, const Kademlia::CUInt128* pbuddyID, uint8_t type, uint32_t ip, uint16_t tcp, uint16_t udp, uint32_t buddyip, uint16_t buddyport, uint8_t byCryptOptions)
1458 AddDebugLogLineM(false, logKadSearch, wxString::Format(wxT("Search result sources (type %i)"),type));
1460 //Safety measure to make sure we are looking for these sources
1461 CPartFile* temp = GetFileByKadFileSearchID(searchID);
1462 if( !temp ) {
1463 AddDebugLogLineM(false, logKadSearch, wxT("This is not the file we're looking for..."));
1464 return;
1467 //Do we need more sources?
1468 if(!(!temp->IsStopped() && thePrefs::GetMaxSourcePerFile() > temp->GetSourceCount())) {
1469 AddDebugLogLineM(false, logKadSearch, wxT("No more sources needed for this file"));
1470 return;
1473 uint32_t ED2KID = wxUINT32_SWAP_ALWAYS(ip);
1475 if (theApp->ipfilter->IsFiltered(ED2KID)) {
1476 AddDebugLogLineM(false, logKadSearch, wxT("Source ip got filtered"));
1477 AddDebugLogLineM(false, logIPFilter, CFormat(wxT("IPfiltered source IP=%s received from Kademlia")) % Uint32toStringIP(ED2KID));
1478 return;
1481 if( (ip == Kademlia::CKademlia::GetIPAddress() || ED2KID == theApp->GetED2KID()) && tcp == thePrefs::GetPort()) {
1482 AddDebugLogLineM(false, logKadSearch, wxT("Trying to add myself as source, ignore"));
1483 return;
1486 CUpDownClient* ctemp = NULL;
1487 switch (type) {
1488 case 4:
1489 case 1: {
1490 // NonFirewalled users
1491 if(!tcp) {
1492 AddDebugLogLineM(false, logKadSearch, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, no tcp port received")) % Uint32toStringIP(ip));
1493 return;
1495 if (!IsGoodIP(ED2KID,thePrefs::FilterLanIPs())) {
1496 AddDebugLogLineM(false, logKadSearch, CFormat(wxT("%s got filtered")) % Uint32toStringIP(ED2KID));
1497 AddDebugLogLineM(false, logIPFilter, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, filtered")) % Uint32toStringIP(ED2KID));
1498 return;
1500 ctemp = new CUpDownClient(tcp, ip, 0, 0, temp, false, true);
1501 ctemp->SetSourceFrom(SF_KADEMLIA);
1502 // not actually sent or needed for HighID sources
1503 //ctemp->SetServerIP(serverip);
1504 //ctemp->SetServerPort(serverport);
1505 ctemp->SetKadPort(udp);
1506 byte cID[16];
1507 pcontactID->ToByteArray(cID);
1508 ctemp->SetUserHash(CMD4Hash(cID));
1509 break;
1511 case 2: {
1512 // Don't use this type... Some clients will process it wrong..
1513 break;
1515 case 5:
1516 case 3: {
1517 // This will be a firewalled client connected to Kad only.
1518 // We set the clientID to 1 as a Kad user only has 1 buddy.
1519 ctemp = new CUpDownClient(tcp, 1, 0, 0, temp, false, true);
1520 // The only reason we set the real IP is for when we get a callback
1521 // from this firewalled source, the compare method will match them.
1522 ctemp->SetSourceFrom(SF_KADEMLIA);
1523 ctemp->SetKadPort(udp);
1524 byte cID[16];
1525 pcontactID->ToByteArray(cID);
1526 ctemp->SetUserHash(CMD4Hash(cID));
1527 pbuddyID->ToByteArray(cID);
1528 ctemp->SetBuddyID(cID);
1529 ctemp->SetBuddyIP(buddyip);
1530 ctemp->SetBuddyPort(buddyport);
1531 break;
1533 case 6: {
1534 // firewalled source which supports direct UDP callback
1535 // if we are firewalled ourself, the source is useless to us
1536 if (theApp->IsFirewalled()) {
1537 break;
1540 if ((byCryptOptions & 0x08) == 0){
1541 AddDebugLogLineM(false, logKadSearch, CFormat(wxT("Received Kad source type 6 (direct callback) which has the direct callback flag not set (%s)")) % Uint32toStringIP(ED2KID));
1542 break;
1545 ctemp = new CUpDownClient(tcp, 1, 0, 0, temp, false, true);
1546 ctemp->SetSourceFrom(SF_KADEMLIA);
1547 ctemp->SetKadPort(udp);
1548 ctemp->SetIP(ED2KID); // need to set the IP address, which cannot be used for TCP but for UDP
1549 byte cID[16];
1550 pcontactID->ToByteArray(cID);
1551 ctemp->SetUserHash(CMD4Hash(cID));
1555 if (ctemp) {
1556 // add encryption settings
1557 ctemp->SetConnectOptions(byCryptOptions);
1559 AddDebugLogLineM(false, logKadSearch, CFormat(wxT("Happily adding a source (%s) type %d")) % Uint32_16toStringIP_Port(ED2KID, ctemp->GetUserPort()) % type);
1560 CheckAndAddSource(temp, ctemp);
1564 CPartFile* CDownloadQueue::GetFileByKadFileSearchID(uint32 id) const
1566 wxMutexLocker lock( m_mutex );
1568 for ( uint16 i = 0; i < m_filelist.size(); ++i ) {
1569 if ( id == m_filelist[i]->GetKadFileSearchID()) {
1570 return m_filelist[ i ];
1574 return NULL;
1577 bool CDownloadQueue::DoKademliaFileRequest()
1579 return ((::GetTickCount() - lastkademliafilerequest) > KADEMLIAASKTIME);
1581 // File_checked_for_headers