2 // This file is part of the aMule Project.
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 )
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
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.
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>
36 #include "Server.h" // Needed for CServer
37 #include "Packet.h" // Needed for CPacket
38 #include "MemFile.h" // Needed for CMemFile
39 #include "ClientList.h" // Needed for CClientList
40 #include "updownclient.h" // Needed for CUpDownClient
41 #include "ServerList.h" // Needed for CServerList
42 #include "ServerConnect.h" // Needed for CServerConnect
43 #include "ED2KLink.h" // Needed for CED2KFileLink
44 #include "SearchList.h" // Needed for CSearchFile
45 #include "SharedFileList.h" // Needed for CSharedFileList
46 #include "PartFile.h" // Needed for CPartFile
47 #include "Preferences.h" // Needed for thePrefs
48 #include "amule.h" // Needed for theApp
49 #include "AsyncDNS.h" // Needed for CAsyncDNS
50 #include "Statistics.h" // Needed for theStats
52 #include <common/Format.h> // Needed for CFormat
54 #include <common/FileFunctions.h> // Needed for CDirIterator
55 #include "GuiEvents.h" // Needed for Notify_*
56 #include "UserEvents.h"
57 #include "MagnetURI.h" // Needed for CMagnetED2KConverter
58 #include "ScopedPtr.h" // Needed for CScopedPtr
59 #include "PlatformSpecific.h" // Needed for CanFSHandleLargeFiles
61 #include "kademlia/kademlia/Kademlia.h"
63 #include <string> // Do_not_auto_remove (mingw-gcc-3.4.5)
66 // Max. file IDs per UDP packet
67 // ----------------------------
68 // 576 - 30 bytes of header (28 for UDP, 2 for "E3 9A" edonkey proto) = 546 bytes
72 #define MAX_FILES_PER_UDP_PACKET 31 // 2+16*31 = 498 ... is still less than 512 bytes!!
73 #define MAX_REQUESTS_PER_SERVER 35
76 CDownloadQueue::CDownloadQueue()
77 // Needs to be recursive that that is can own an observer assigned to itself
78 : m_mutex( wxMUTEX_RECURSIVE
)
83 m_lastudpsearchtime
= 0;
84 m_lastudpstattime
= 0;
86 m_nLastED2KLinkCheck
= 0;
87 m_dwNextTCPSrcReq
= 0;
88 m_cRequestsSentToServer
= 0;
90 SetLastKademliaFileRequest();
94 CDownloadQueue::~CDownloadQueue()
96 if ( !m_filelist
.empty() ) {
97 for ( unsigned int i
= 0; i
< m_filelist
.size(); i
++ ) {
98 AddLogLineNS(CFormat(_("Saving PartFile %u of %u")) % (i
+ 1) % m_filelist
.size());
101 AddLogLineNS(_("All PartFiles Saved."));
106 void CDownloadQueue::LoadMetFiles(const CPath
& path
)
108 AddLogLineNS(CFormat(_("Loading temp files from %s.")) % path
.GetPrintable());
110 std::vector
<CPath
> files
;
112 // Locate part-files to be loaded
113 CDirIterator
TempDir(path
);
114 CPath fileName
= TempDir
.GetFirstFile(CDirIterator::File
, wxT("*.part.met"));
115 while (fileName
.IsOk()) {
116 files
.push_back(path
.JoinPaths(fileName
));
118 fileName
= TempDir
.GetNextFile();
121 // Loading in order makes it easier to figure which
122 // file is broken in case of crashes, or the like.
123 std::sort(files
.begin(), files
.end());
126 for ( size_t i
= 0; i
< files
.size(); i
++ ) {
127 AddLogLineNS(CFormat(_("Loading PartFile %u of %u")) % (i
+ 1) % files
.size());
128 fileName
= files
[i
].GetFullName();
129 CPartFile
*toadd
= new CPartFile();
130 bool result
= toadd
->LoadPartFile(path
, fileName
) != 0;
133 result
= toadd
->LoadPartFile(path
, fileName
, true) != 0;
135 if (result
&& !IsFileExisting(toadd
->GetFileHash())) {
137 wxMutexLocker
lock(m_mutex
);
138 m_filelist
.push_back(toadd
);
140 NotifyObservers(EventType(EventType::INSERTED
, toadd
));
141 Notify_DownloadCtrlAddFile(toadd
);
145 msg
<< CFormat(wxT("WARNING: Duplicate partfile with hash '%s' found, skipping: %s"))
146 % toadd
->GetFileHash().Encode() % fileName
;
148 // If result is false, then reading of both the primary and the backup .met failed
150 _("ERROR: Failed to load backup file. Search http://forum.amule.org for .part.met recovery solutions."));
151 msg
<< CFormat(wxT("ERROR: Failed to load PartFile '%s'")) % fileName
;
155 // Delete the partfile object in the end.
159 AddLogLineNS(_("All PartFiles Loaded."));
161 if ( GetFileCount() == 0 ) {
162 AddLogLineM(false, _("No part files found"));
164 AddLogLineM(false, wxString::Format(wxPLURAL("Found %u part file", "Found %u part files", GetFileCount()), GetFileCount()) );
167 CheckDiskspace( path
);
172 uint16
CDownloadQueue::GetFileCount() const
174 wxMutexLocker
lock( m_mutex
);
176 return m_filelist
.size();
180 void CDownloadQueue::CopyFileList(std::vector
<CPartFile
*>& out_list
) const
182 wxMutexLocker
lock(m_mutex
);
184 out_list
.reserve(m_filelist
.size());
185 for (FileQueue::const_iterator it
= m_filelist
.begin(); it
!= m_filelist
.end(); ++it
) {
186 out_list
.push_back(*it
);
191 CServer
* CDownloadQueue::GetUDPServer() const
193 wxMutexLocker
lock( m_mutex
);
199 void CDownloadQueue::SetUDPServer( CServer
* server
)
201 wxMutexLocker
lock( m_mutex
);
203 m_udpserver
= server
;
207 void CDownloadQueue::SaveSourceSeeds()
209 for ( uint16 i
= 0; i
< GetFileCount(); i
++ ) {
210 GetFileByIndex( i
)->SaveSourceSeeds();
215 void CDownloadQueue::LoadSourceSeeds()
217 for ( uint16 i
= 0; i
< GetFileCount(); i
++ ) {
218 GetFileByIndex( i
)->LoadSourceSeeds();
223 void CDownloadQueue::AddSearchToDownload(CSearchFile
* toadd
, uint8 category
)
225 if ( IsFileExisting(toadd
->GetFileHash()) ) {
229 if (toadd
->GetFileSize() > OLD_MAX_FILE_SIZE
) {
230 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
231 AddLogLineM(true, _("Filesystem for Temp directory cannot handle large files."));
233 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp
->glob_prefs
->GetCatPath(category
))) {
234 AddLogLineM(true, _("Filesystem for Incoming directory cannot handle large files."));
239 CPartFile
* newfile
= NULL
;
241 newfile
= new CPartFile(toadd
);
242 } catch (const CInvalidPacket
& WXUNUSED(e
)) {
243 AddDebugLogLineM(true, logDownloadQueue
, wxT("Search-result contained invalid tags, could not add"));
246 if ( newfile
&& newfile
->GetStatus() != PS_ERROR
) {
247 AddDownload( newfile
, thePrefs::AddNewFilesPaused(), category
);
248 // Add any possible sources
249 if (toadd
->GetClientID() && toadd
->GetClientPort()) {
250 CMemFile
sources(1+4+2);
251 sources
.WriteUInt8(1);
252 sources
.WriteUInt32(toadd
->GetClientID());
253 sources
.WriteUInt16(toadd
->GetClientPort());
255 newfile
->AddSources(sources
, toadd
->GetClientServerIP(), toadd
->GetClientServerPort(), SF_SEARCH_RESULT
, false);
257 for (std::list
<CSearchFile::ClientStruct
>::const_iterator it
= toadd
->GetClients().begin(); it
!= toadd
->GetClients().end(); ++it
) {
258 CMemFile
sources(1+4+2);
259 sources
.WriteUInt8(1);
260 sources
.WriteUInt32(it
->m_ip
);
261 sources
.WriteUInt16(it
->m_port
);
263 newfile
->AddSources(sources
, it
->m_serverIP
, it
->m_serverPort
, SF_SEARCH_RESULT
, false);
273 void operator()(CPartFile
* file
) {
274 // Check if we should filter out other categories
275 if ((m_category
!= -1) && (file
->GetCategory() != m_category
)) {
277 } else if (file
->GetStatus() != PS_PAUSED
) {
281 if (!m_result
|| (file
->GetDownPriority() > m_result
->GetDownPriority())) {
286 //! The category to look for, or -1 if any category is good
288 //! If any acceptable files are found, this variable store their pointer
293 void CDownloadQueue::StartNextFile(CPartFile
* oldfile
)
295 if ( thePrefs::StartNextFile() ) {
296 SFindBestPF visitor
= { -1, NULL
};
299 wxMutexLocker
lock(m_mutex
);
301 if (thePrefs::StartNextFileSame()) {
302 // Get a download in the same category
303 visitor
.m_category
= oldfile
->GetCategory();
305 visitor
= std::for_each(m_filelist
.begin(), m_filelist
.end(), visitor
);
308 if (visitor
.m_result
== NULL
) {
309 // Get a download, regardless of category
310 visitor
.m_category
= -1;
312 visitor
= std::for_each(m_filelist
.begin(), m_filelist
.end(), visitor
);
316 if (visitor
.m_result
) {
317 visitor
.m_result
->ResumeFile();
323 void CDownloadQueue::AddDownload(CPartFile
* file
, bool paused
, uint8 category
)
325 wxCHECK_RET(!IsFileExisting(file
->GetFileHash()), wxT("Adding duplicate part-file"));
327 if (file
->GetStatus(true) == PS_ALLOCATING
) {
329 } else if (paused
&& GetFileCount()) {
334 wxMutexLocker
lock(m_mutex
);
335 m_filelist
.push_back( file
);
339 NotifyObservers( EventType( EventType::INSERTED
, file
) );
340 if (category
< theApp
->glob_prefs
->GetCatCount()) {
341 file
->SetCategory(category
);
343 AddDebugLogLineM( false, logDownloadQueue
, wxT("Tried to add download into invalid category.") );
345 Notify_DownloadCtrlAddFile( file
);
346 theApp
->searchlist
->UpdateSearchFileByHash(file
->GetFileHash()); // Update file in the search dialog if it's still open
347 AddLogLineM(true, CFormat(_("Downloading %s")) % file
->GetFileName() );
351 bool CDownloadQueue::IsFileExisting( const CMD4Hash
& fileid
) const
353 if (CKnownFile
* file
= theApp
->sharedfiles
->GetFileByID(fileid
)) {
354 if (file
->IsPartFile()) {
355 AddLogLineM(true, CFormat( _("You are already trying to download the file '%s'") ) % file
->GetFileName());
357 // Check if the file exists, since otherwise the user is forced to
358 // manually reload the shares to download a file again.
359 CPath fullpath
= file
->GetFilePath().JoinPaths(file
->GetFileName());
360 if (!fullpath
.FileExists()) {
361 // The file is no longer available, unshare it
362 theApp
->sharedfiles
->RemoveFile(file
);
367 AddLogLineM(true, CFormat( _("You already have the file '%s'") ) % file
->GetFileName());
371 } else if ((file
= GetFileByID(fileid
))) {
372 AddLogLineM(true, CFormat( _("You are already trying to download the file %s") ) % file
->GetFileName());
380 void CDownloadQueue::Process()
382 // send src requests to local server
383 ProcessLocalRequests();
386 wxMutexLocker
lock(m_mutex
);
388 uint32 downspeed
= 0;
389 if (thePrefs::GetMaxDownload() != UNLIMITED
&& m_datarate
> 1500) {
390 downspeed
= (((uint32
)thePrefs::GetMaxDownload())*1024*100)/(m_datarate
+1);
391 if (downspeed
< 50) {
393 } else if (downspeed
> 200) {
400 uint32 cur_datarate
= 0;
401 uint32 cur_udcounter
= m_udcounter
;
403 for ( uint16 i
= 0; i
< m_filelist
.size(); i
++ ) {
404 CPartFile
* file
= m_filelist
[i
];
406 CMutexUnlocker
unlocker(m_mutex
);
408 if ( file
->GetStatus() == PS_READY
|| file
->GetStatus() == PS_EMPTY
){
409 cur_datarate
+= file
->Process( downspeed
, cur_udcounter
);
411 //This will make sure we don't keep old sources to paused and stoped files..
412 file
->StopPausedFile();
416 m_datarate
+= cur_datarate
;
419 if (m_udcounter
== 5) {
420 if (theApp
->serverconnect
->IsUDPSocketAvailable()) {
421 if( (::GetTickCount() - m_lastudpstattime
) > UDPSERVERSTATTIME
) {
422 m_lastudpstattime
= ::GetTickCount();
424 CMutexUnlocker
unlocker(m_mutex
);
425 theApp
->serverlist
->ServerStats();
430 if (m_udcounter
== 10) {
432 if (theApp
->serverconnect
->IsUDPSocketAvailable()) {
433 if ( (::GetTickCount() - m_lastudpsearchtime
) > UDPSERVERREASKTIME
) {
439 if ( (::GetTickCount() - m_lastsorttime
) > 10000 ) {
444 // Check if any paused files can be resumed
446 CheckDiskspace(thePrefs::GetTempDir());
450 // Check for new links once per second.
451 if ((::GetTickCount() - m_nLastED2KLinkCheck
) >= 1000) {
452 theApp
->AddLinksFromFile();
453 m_nLastED2KLinkCheck
= ::GetTickCount();
458 CPartFile
* CDownloadQueue::GetFileByID(const CMD4Hash
& filehash
) const
460 wxMutexLocker
lock( m_mutex
);
462 for ( uint16 i
= 0; i
< m_filelist
.size(); ++i
) {
463 if ( filehash
== m_filelist
[i
]->GetFileHash()) {
464 return m_filelist
[ i
];
472 CPartFile
* CDownloadQueue::GetFileByIndex(unsigned int index
) const
474 wxMutexLocker
lock( m_mutex
);
476 if ( index
< m_filelist
.size() ) {
477 return m_filelist
[ index
];
485 bool CDownloadQueue::IsPartFile(const CKnownFile
* file
) const
487 wxMutexLocker
lock(m_mutex
);
489 for (uint16 i
= 0; i
< m_filelist
.size(); ++i
) {
490 if (file
== m_filelist
[i
]) {
499 void CDownloadQueue::OnConnectionState(bool bConnected
)
501 wxMutexLocker
lock(m_mutex
);
503 for (uint16 i
= 0; i
< m_filelist
.size(); ++i
) {
504 if ( m_filelist
[i
]->GetStatus() == PS_READY
||
505 m_filelist
[i
]->GetStatus() == PS_EMPTY
) {
506 m_filelist
[i
]->SetActive(bConnected
);
512 void CDownloadQueue::CheckAndAddSource(CPartFile
* sender
, CUpDownClient
* source
)
514 // if we block loopbacks at this point it should prevent us from connecting to ourself
515 if ( source
->HasValidHash() ) {
516 if ( source
->GetUserHash() == thePrefs::GetUserHash() ) {
517 AddDebugLogLineM( false, logDownloadQueue
, wxT("Tried to add source with matching hash to your own.") );
518 source
->Safe_Delete();
523 if (sender
->IsStopped()) {
524 source
->Safe_Delete();
528 // Filter sources which are known to be dead/useless
529 if ( theApp
->clientlist
->IsDeadSource( source
) || sender
->IsDeadSource(source
) ) {
530 source
->Safe_Delete();
534 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
535 if ( (source
->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source
->HasValidHash())) || (thePrefs::IsClientCryptLayerRequired() && (!source
->SupportsCryptLayer() || !source
->HasValidHash()))) {
536 source
->Safe_Delete();
540 // Find all clients with the same hash
541 if ( source
->HasValidHash() ) {
542 CClientList::SourceList found
= theApp
->clientlist
->GetClientsByHash( source
->GetUserHash() );
544 CClientList::SourceList::iterator it
= found
.begin();
545 for ( ; it
!= found
.end(); it
++ ) {
546 CKnownFile
* file
= (*it
)->GetRequestFile();
548 // Only check files on the download-queue
550 // Is the found source queued for something else?
551 if ( file
!= sender
) {
552 // Try to add a request for the other file
553 if ( (*it
)->AddRequestForAnotherFile(sender
)) {
554 // Add it to downloadlistctrl
555 Notify_SourceCtrlAddSource(sender
, *it
, A4AF_SOURCE
);
559 source
->Safe_Delete();
567 // Our new source is real new but maybe it is already uploading to us?
568 // If yes the known client will be attached to the var "source" and the old
569 // source-client will be deleted. However, if the request file of the known
570 // source is NULL, then we have to treat it almost like a new source and if
571 // it isn't NULL and not "sender", then we shouldn't move it, but rather add
572 // a request for the new file.
573 ESourceFrom nSourceFrom
= source
->GetSourceFrom();
574 if ( theApp
->clientlist
->AttachToAlreadyKnown(&source
, 0) ) {
575 // Already queued for another file?
576 if ( source
->GetRequestFile() ) {
577 // If we're already queued for the right file, then there's nothing to do
578 if ( sender
!= source
->GetRequestFile() ) {
579 // Add the new file to the request list
580 source
->AddRequestForAnotherFile( sender
);
583 // Source was known, but reqfile NULL.
584 source
->SetRequestFile( sender
);
585 source
->SetSourceFrom(nSourceFrom
);
586 sender
->AddSource( source
);
587 if ( source
->GetFileRating() || !source
->GetFileComment().IsEmpty() ) {
588 sender
->UpdateFileRatingCommentAvail();
591 Notify_SourceCtrlAddSource(sender
, source
, UNAVAILABLE_SOURCE
);
594 // Unknown client, add it to the clients list
595 source
->SetRequestFile( sender
);
597 theApp
->clientlist
->AddClient(source
);
599 sender
->AddSource( source
);
600 if ( source
->GetFileRating() || !source
->GetFileComment().IsEmpty() ) {
601 sender
->UpdateFileRatingCommentAvail();
604 Notify_SourceCtrlAddSource(sender
, source
, UNAVAILABLE_SOURCE
);
609 void CDownloadQueue::CheckAndAddKnownSource(CPartFile
* sender
,CUpDownClient
* source
)
613 if (sender
->IsStopped()) {
617 // Filter sources which are known to be dead/useless
618 if ( sender
->IsDeadSource(source
) ) {
622 // "Filter LAN IPs" -- this may be needed here in case we are connected to the internet and are also connected
623 // to a LAN and some client from within the LAN connected to us. Though this situation may be supported in future
624 // by adding that client to the source list and filtering that client's LAN IP when sending sources to
625 // a client within the internet.
627 // "IPfilter" is not needed here, because that "known" client was already IPfiltered when receiving OP_HELLO.
628 if (!source
->HasLowID()) {
629 uint32 nClientIP
= wxUINT32_SWAP_ALWAYS(source
->GetUserIDHybrid());
630 if (!IsGoodIP(nClientIP
, thePrefs::FilterLanIPs())) { // check for 0-IP, localhost and LAN addresses
631 AddDebugLogLineM(false, logIPFilter
, wxT("Ignored already known source with IP=%s") + Uint32toStringIP(nClientIP
));
636 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
637 if ( (source
->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source
->HasValidHash())) || (thePrefs::IsClientCryptLayerRequired() && (!source
->SupportsCryptLayer() || !source
->HasValidHash())))
639 source
->Safe_Delete();
643 CPartFile
* file
= source
->GetRequestFile();
645 // Check if the file is already queued for something else
647 if ( file
!= sender
) {
648 if ( source
->AddRequestForAnotherFile( sender
) ) {
649 Notify_SourceCtrlAddSource( sender
, source
, A4AF_SOURCE
);
653 source
->SetRequestFile( sender
);
655 if ( source
->GetFileRating() || !source
->GetFileComment().IsEmpty() ) {
656 sender
->UpdateFileRatingCommentAvail();
659 source
->SetSourceFrom(SF_PASSIVE
);
660 sender
->AddSource( source
);
661 Notify_SourceCtrlAddSource( sender
, source
, UNAVAILABLE_SOURCE
);
666 bool CDownloadQueue::RemoveSource(CUpDownClient
* toremove
, bool WXUNUSED(updatewindow
), bool bDoStatsUpdate
)
668 bool removed
= false;
669 toremove
->DeleteAllFileRequests();
671 for ( uint16 i
= 0; i
< GetFileCount(); i
++ ) {
672 CPartFile
* cur_file
= GetFileByIndex( i
);
674 // Remove from source-list
675 if ( cur_file
->DelSource( toremove
) ) {
677 // Remove from sourcelist widget
678 Notify_SourceCtrlRemoveSource(toremove
, cur_file
);
680 cur_file
->RemoveDownloadingSource(toremove
);
682 if ( bDoStatsUpdate
) {
683 cur_file
->UpdatePartsInfo();
687 // Remove from A4AF-list
688 cur_file
->RemoveA4AFSource( toremove
);
692 if ( !toremove
->GetFileComment().IsEmpty() || toremove
->GetFileRating()>0) {
693 toremove
->GetRequestFile()->UpdateFileRatingCommentAvail();
696 toremove
->SetRequestFile( NULL
);
697 toremove
->SetDownloadState(DS_NONE
);
698 toremove
->ResetFileStatusInfo();
704 void CDownloadQueue::RemoveFile(CPartFile
* file
)
706 RemoveLocalServerRequest( file
);
708 NotifyObservers( EventType( EventType::REMOVED
, file
) );
710 wxMutexLocker
lock( m_mutex
);
712 EraseValue( m_filelist
, file
);
716 CUpDownClient
* CDownloadQueue::GetDownloadClientByIP_UDP(uint32 dwIP
, uint16 nUDPPort
) const
718 wxMutexLocker
lock( m_mutex
);
720 for ( unsigned int i
= 0; i
< m_filelist
.size(); i
++ ) {
721 const CKnownFile::SourceSet
& set
= m_filelist
[i
]->GetSourceList();
723 for ( CKnownFile::SourceSet::const_iterator it
= set
.begin(); it
!= set
.end(); it
++ ) {
724 if ( (*it
)->GetIP() == dwIP
&& (*it
)->GetUDPPort() == nUDPPort
) {
734 * Checks if the specified server is the one we are connected to.
736 bool IsConnectedServer(const CServer
* server
)
738 if (server
&& theApp
->serverconnect
->GetCurrentServer()) {
739 wxString srvAddr
= theApp
->serverconnect
->GetCurrentServer()->GetAddress();
740 uint16 srvPort
= theApp
->serverconnect
->GetCurrentServer()->GetPort();
742 return server
->GetAddress() == srvAddr
&& server
->GetPort() == srvPort
;
749 bool CDownloadQueue::SendNextUDPPacket()
751 if ( m_filelist
.empty() || !theApp
->serverconnect
->IsUDPSocketAvailable() || !theApp
->IsConnectedED2K()) {
755 // Start monitoring the server and the files list
756 if ( !m_queueServers
.IsActive() ) {
757 AddObserver( &m_queueFiles
);
759 theApp
->serverlist
->AddObserver( &m_queueServers
);
763 bool packetSent
= false;
764 while ( !packetSent
) {
765 // Get max files ids per packet for current server
766 int filesAllowed
= GetMaxFilesPerUDPServerPacket();
768 if (filesAllowed
< 1 || !m_udpserver
|| IsConnectedServer(m_udpserver
)) {
769 // Select the next server to ask, must not be the connected server
771 m_udpserver
= m_queueServers
.GetNext();
772 } while (IsConnectedServer(m_udpserver
));
774 m_cRequestsSentToServer
= 0;
775 filesAllowed
= GetMaxFilesPerUDPServerPacket();
779 // Check if we have asked all servers, in which case we are done
780 if (m_udpserver
== NULL
) {
786 // Memoryfile containing the hash of every file to request
787 // 28bytes allocation because 16b + 4b + 8b is the worse case scenario.
788 CMemFile
hashlist( 28 );
790 CPartFile
* file
= m_queueFiles
.GetNext();
792 while ( file
&& filesAllowed
) {
793 uint8 status
= file
->GetStatus();
795 if ( ( status
== PS_READY
|| status
== PS_EMPTY
) && file
->GetSourceCount() < thePrefs::GetMaxSourcePerFileUDP() ) {
796 if (file
->IsLargeFile() && !m_udpserver
->SupportsLargeFilesUDP()) {
797 AddDebugLogLineM(false, logDownloadQueue
, wxT("UDP Request for sources on a large file ignored: server doesn't support it"));
799 ++m_cRequestsSentToServer
;
800 hashlist
.WriteHash( file
->GetFileHash() );
801 // See the notes on TCP packet
802 if ( m_udpserver
->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2
) {
803 if (file
->IsLargeFile()) {
804 wxASSERT(m_udpserver
->SupportsLargeFilesUDP());
805 hashlist
.WriteUInt32( 0 );
806 hashlist
.WriteUInt64( file
->GetFileSize() );
808 hashlist
.WriteUInt32( file
->GetFileSize() );
815 // Avoid skipping a file if we can't send any more currently
816 if ( filesAllowed
) {
817 file
= m_queueFiles
.GetNext();
821 // See if we have anything to send
822 if ( hashlist
.GetLength() ) {
823 packetSent
= SendGlobGetSourcesUDPPacket(hashlist
);
826 // Check if we've covered every file
827 if ( file
== NULL
) {
828 // Reset the list of asked files so that the loop will start over
829 m_queueFiles
.Reset();
831 // Unset the server so that the next server will be used
840 void CDownloadQueue::StopUDPRequests()
842 wxMutexLocker
lock( m_mutex
);
848 void CDownloadQueue::DoStopUDPRequests()
850 // No need to observe when we wont be using the results
851 theApp
->serverlist
->RemoveObserver( &m_queueServers
);
852 RemoveObserver( &m_queueFiles
);
855 m_lastudpsearchtime
= ::GetTickCount();
859 // Comparison function needed by sort. Returns true if file1 preceeds file2
860 bool ComparePartFiles(const CPartFile
* file1
, const CPartFile
* file2
) {
861 if (file1
->GetDownPriority() != file2
->GetDownPriority()) {
862 // To place high-priority files before low priority files we have to
863 // invert this test, since PR_LOW is lower than PR_HIGH, and since
864 // placing a PR_LOW file before a PR_HIGH file would mean that
865 // the PR_LOW file gets sources before the PR_HIGH file ...
866 return (file1
->GetDownPriority() > file2
->GetDownPriority());
868 int sourcesA
= file1
->GetSourceCount();
869 int sourcesB
= file2
->GetSourceCount();
871 int notSourcesA
= file1
->GetNotCurrentSourcesCount();
872 int notSourcesB
= file2
->GetNotCurrentSourcesCount();
874 int cmp
= CmpAny( sourcesA
- notSourcesA
, sourcesB
- notSourcesB
);
877 cmp
= CmpAny( notSourcesA
, notSourcesB
);
885 void CDownloadQueue::DoSortByPriority()
887 m_lastsorttime
= ::GetTickCount();
888 sort( m_filelist
.begin(), m_filelist
.end(), ComparePartFiles
);
892 void CDownloadQueue::ResetLocalServerRequests()
894 wxMutexLocker
lock( m_mutex
);
896 m_dwNextTCPSrcReq
= 0;
897 m_localServerReqQueue
.clear();
899 for ( uint16 i
= 0; i
< m_filelist
.size(); i
++ ) {
900 m_filelist
[i
]->SetLocalSrcRequestQueued(false);
905 void CDownloadQueue::RemoveLocalServerRequest( CPartFile
* file
)
907 wxMutexLocker
lock( m_mutex
);
909 EraseValue( m_localServerReqQueue
, file
);
911 file
->SetLocalSrcRequestQueued(false);
915 void CDownloadQueue::ProcessLocalRequests()
917 wxMutexLocker
lock( m_mutex
);
919 bool bServerSupportsLargeFiles
= theApp
->serverconnect
920 && theApp
->serverconnect
->GetCurrentServer()
921 && theApp
->serverconnect
->GetCurrentServer()->SupportsLargeFilesTCP();
923 if ( (!m_localServerReqQueue
.empty()) && (m_dwNextTCPSrcReq
< ::GetTickCount()) ) {
924 CMemFile
dataTcpFrame(22);
925 const int iMaxFilesPerTcpFrame
= 15;
927 while (!m_localServerReqQueue
.empty() && iFiles
< iMaxFilesPerTcpFrame
) {
928 // find the file with the longest waitingtime
929 uint32 dwBestWaitTime
= 0xFFFFFFFF;
931 std::list
<CPartFile
*>::iterator posNextRequest
= m_localServerReqQueue
.end();
932 std::list
<CPartFile
*>::iterator it
= m_localServerReqQueue
.begin();
933 while( it
!= m_localServerReqQueue
.end() ) {
934 CPartFile
* cur_file
= (*it
);
935 if (cur_file
->GetStatus() == PS_READY
|| cur_file
->GetStatus() == PS_EMPTY
) {
936 uint8 nPriority
= cur_file
->GetDownPriority();
937 if (nPriority
> PR_HIGH
) {
942 if (cur_file
->GetLastSearchTime() + (PR_HIGH
-nPriority
) < dwBestWaitTime
){
943 dwBestWaitTime
= cur_file
->GetLastSearchTime() + (PR_HIGH
- nPriority
);
949 it
= m_localServerReqQueue
.erase(it
);
950 cur_file
->SetLocalSrcRequestQueued(false);
951 AddDebugLogLineM( false, logDownloadQueue
,
952 CFormat(wxT("Local server source request for file '%s' not sent because of status '%s'"))
953 % cur_file
->GetFileName() % cur_file
->getPartfileStatus());
957 if (posNextRequest
!= m_localServerReqQueue
.end()) {
958 CPartFile
* cur_file
= (*posNextRequest
);
959 cur_file
->SetLocalSrcRequestQueued(false);
960 cur_file
->SetLastSearchTime(::GetTickCount());
961 m_localServerReqQueue
.erase(posNextRequest
);
964 if (!bServerSupportsLargeFiles
&& cur_file
->IsLargeFile()) {
965 AddDebugLogLineM(false, logDownloadQueue
, wxT("TCP Request for sources on a large file ignored: server doesn't support it"));
967 AddDebugLogLineM(false, logDownloadQueue
,
968 CFormat(wxT("Creating local sources request packet for '%s'")) % cur_file
->GetFileName());
969 // create request packet
970 CMemFile
data(16 + (cur_file
->IsLargeFile() ? 8 : 4));
971 data
.WriteHash(cur_file
->GetFileHash());
972 // Kry - lugdunum extended protocol on 17.3 to handle filesize properly.
973 // There is no need to check anything, old server ignore the extra 4 bytes.
974 // As of 17.9, servers accept a 0 32-bits size and then a 64bits size
975 if (cur_file
->IsLargeFile()) {
976 wxASSERT(bServerSupportsLargeFiles
);
978 data
.WriteUInt64(cur_file
->GetFileSize());
980 data
.WriteUInt32(cur_file
->GetFileSize());
983 if (thePrefs::IsClientCryptLayerSupported() && theApp
->serverconnect
->GetCurrentServer() != NULL
&& theApp
->serverconnect
->GetCurrentServer()->SupportsGetSourcesObfuscation()) {
984 byOpcode
= OP_GETSOURCES_OBFU
;
986 byOpcode
= OP_GETSOURCES
;
988 CPacket
packet(data
, OP_EDONKEYPROT
, byOpcode
);
989 dataTcpFrame
.Write(packet
.GetPacket(), packet
.GetRealPacketSize());
994 int iSize
= dataTcpFrame
.GetLength();
996 // create one 'packet' which contains all buffered OP_GETSOURCES ED2K packets to be sent with one TCP frame
997 // server credits: (16+4)*regularfiles + (16+4+8)*largefiles +1
998 CScopedPtr
<CPacket
> packet(new CPacket(new byte
[iSize
], dataTcpFrame
.GetLength(), true, false));
999 dataTcpFrame
.Seek(0, wxFromStart
);
1000 dataTcpFrame
.Read(packet
->GetPacket(), iSize
);
1001 uint32 size
= packet
->GetPacketSize();
1002 theApp
->serverconnect
->SendPacket(packet
.release(), true); // Deletes `packet'.
1003 AddDebugLogLineM(false, logDownloadQueue
, wxT("Sent local sources request packet."));
1004 theStats::AddUpOverheadServer(size
);
1007 // next TCP frame with up to 15 source requests is allowed to be sent in..
1008 m_dwNextTCPSrcReq
= ::GetTickCount() + SEC2MS(iMaxFilesPerTcpFrame
*(16+4));
1014 void CDownloadQueue::SendLocalSrcRequest(CPartFile
* sender
)
1016 wxMutexLocker
lock( m_mutex
);
1018 m_localServerReqQueue
.push_back(sender
);
1022 void CDownloadQueue::ResetCatParts(uint8 cat
)
1024 for ( uint16 i
= 0; i
< GetFileCount(); i
++ ) {
1025 CPartFile
* file
= GetFileByIndex( i
);
1027 if ( file
->GetCategory() == cat
) {
1028 // Reset the category
1029 file
->SetCategory( 0 );
1030 } else if ( file
->GetCategory() > cat
) {
1031 // Set to the new position of the original category
1032 file
->SetCategory( file
->GetCategory() - 1 );
1038 void CDownloadQueue::SetCatPrio(uint8 cat
, uint8 newprio
)
1040 for ( uint16 i
= 0; i
< GetFileCount(); i
++ ) {
1041 CPartFile
* file
= GetFileByIndex( i
);
1043 if ( !cat
|| file
->GetCategory() == cat
) {
1044 if ( newprio
== PR_AUTO
) {
1045 file
->SetAutoDownPriority(true);
1047 file
->SetAutoDownPriority(false);
1048 file
->SetDownPriority(newprio
);
1055 void CDownloadQueue::SetCatStatus(uint8 cat
, int newstatus
)
1057 std::list
<CPartFile
*> files
;
1060 wxMutexLocker
lock(m_mutex
);
1062 for ( uint16 i
= 0; i
< m_filelist
.size(); i
++ ) {
1063 if ( m_filelist
[i
]->CheckShowItemInGivenCat(cat
) ) {
1064 files
.push_back( m_filelist
[i
] );
1069 std::list
<CPartFile
*>::iterator it
= files
.begin();
1071 for ( ; it
!= files
.end(); it
++ ) {
1072 switch ( newstatus
) {
1073 case MP_CANCEL
: (*it
)->Delete(); break;
1074 case MP_PAUSE
: (*it
)->PauseFile(); break;
1075 case MP_STOP
: (*it
)->StopFile(); break;
1076 case MP_RESUME
: (*it
)->ResumeFile(); break;
1082 uint16
CDownloadQueue::GetDownloadingFileCount() const
1084 wxMutexLocker
lock( m_mutex
);
1087 for ( uint16 i
= 0; i
< m_filelist
.size(); i
++ ) {
1088 uint8 status
= m_filelist
[i
]->GetStatus();
1089 if ( status
== PS_READY
|| status
== PS_EMPTY
) {
1098 uint16
CDownloadQueue::GetPausedFileCount() const
1100 wxMutexLocker
lock( m_mutex
);
1103 for ( uint16 i
= 0; i
< m_filelist
.size(); i
++ ) {
1104 if ( m_filelist
[i
]->GetStatus() == PS_PAUSED
) {
1113 void CDownloadQueue::CheckDiskspace( const CPath
& path
)
1115 if ( ::GetTickCount() - m_lastDiskCheck
< DISKSPACERECHECKTIME
) {
1119 m_lastDiskCheck
= ::GetTickCount();
1122 // Check if the user has set an explicit limit
1123 if ( thePrefs::IsCheckDiskspaceEnabled() ) {
1124 min
= thePrefs::GetMinFreeDiskSpace();
1127 // The very least acceptable diskspace is a single PART
1128 if ( min
< PARTSIZE
) {
1132 uint64 free
= CPath::GetFreeSpaceAt(path
);
1133 if (free
== static_cast<uint64
>(wxInvalidOffset
)) {
1135 } else if (free
< min
) {
1136 CUserEvents::ProcessEvent(
1137 CUserEvents::OutOfDiskSpace
,
1138 wxT("Temporary partition"));
1141 for (unsigned int i
= 0; i
< m_filelist
.size(); ++i
) {
1142 CPartFile
* file
= m_filelist
[i
];
1144 switch ( file
->GetStatus() ) {
1151 if ( free
>= min
&& file
->GetInsufficient() ) {
1152 // We'll try to resume files if there is enough free space
1153 if ( free
- file
->GetNeededSpace() > min
) {
1156 } else if ( free
< min
&& !file
->IsPaused() ) {
1157 // No space left, stop the files.
1158 file
->PauseFile( true );
1164 int CDownloadQueue::GetMaxFilesPerUDPServerPacket() const
1166 if ( m_udpserver
) {
1167 if ( m_udpserver
->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES
) {
1168 // get max. file ids per packet
1169 if ( m_cRequestsSentToServer
< MAX_REQUESTS_PER_SERVER
) {
1171 MAX_FILES_PER_UDP_PACKET
,
1172 MAX_REQUESTS_PER_SERVER
- m_cRequestsSentToServer
1175 } else if ( m_cRequestsSentToServer
< MAX_REQUESTS_PER_SERVER
) {
1184 bool CDownloadQueue::SendGlobGetSourcesUDPPacket(CMemFile
& data
)
1190 CPacket
packet(data
, OP_EDONKEYPROT
, ((m_udpserver
->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2
) ? OP_GLOBGETSOURCES2
: OP_GLOBGETSOURCES
));
1192 theStats::AddUpOverheadServer(packet
.GetPacketSize());
1193 theApp
->serverconnect
->SendUDPPacket(&packet
,m_udpserver
,false);
1199 void CDownloadQueue::AddToResolve(const CMD4Hash
& fileid
, const wxString
& pszHostname
, uint16 port
, const wxString
& hash
, uint8 cryptoptions
)
1202 if ( !GetFileByID(fileid
) ) {
1206 wxMutexLocker
lock( m_mutex
);
1208 Hostname_Entry entry
= { fileid
, pszHostname
, port
, hash
, cryptoptions
};
1209 m_toresolve
.push_front(entry
);
1211 // Check if there are other DNS lookups on queue
1212 if (m_toresolve
.size() == 1) {
1213 // Check if it is a simple dot address
1214 uint32 ip
= StringIPtoUint32(pszHostname
);
1217 OnHostnameResolved(ip
);
1219 CAsyncDNS
* dns
= new CAsyncDNS(pszHostname
, DNS_SOURCE
, theApp
);
1221 if ((dns
->Create() != wxTHREAD_NO_ERROR
) || (dns
->Run() != wxTHREAD_NO_ERROR
)) {
1223 m_toresolve
.pop_front();
1230 void CDownloadQueue::OnHostnameResolved(uint32 ip
)
1232 wxMutexLocker
lock( m_mutex
);
1234 wxASSERT( m_toresolve
.size() );
1236 Hostname_Entry resolved
= m_toresolve
.front();
1237 m_toresolve
.pop_front();
1240 CPartFile
* file
= GetFileByID( resolved
.fileid
);
1242 CMemFile
sources(1+4+2);
1243 sources
.WriteUInt8(1); // No. Sources
1244 sources
.WriteUInt32(ip
);
1245 sources
.WriteUInt16(resolved
.port
);
1246 sources
.WriteUInt8(resolved
.cryptoptions
);
1247 if (resolved
.cryptoptions
& 0x80) {
1248 wxASSERT(!resolved
.hash
.IsEmpty());
1249 CMD4Hash sourcehash
;
1250 sourcehash
.Decode(resolved
.hash
);
1251 sources
.WriteHash(sourcehash
);
1253 sources
.Seek(0,wxFromStart
);
1255 file
->AddSources(sources
, 0, 0, SF_LINK
, true);
1259 while (m_toresolve
.size()) {
1260 Hostname_Entry entry
= m_toresolve
.front();
1262 // Check if it is a simple dot address
1263 uint32 tmpIP
= StringIPtoUint32(entry
.strHostname
);
1266 OnHostnameResolved(tmpIP
);
1268 CAsyncDNS
* dns
= new CAsyncDNS(entry
.strHostname
, DNS_SOURCE
, theApp
);
1270 if ((dns
->Create() != wxTHREAD_NO_ERROR
) || (dns
->Run() != wxTHREAD_NO_ERROR
)) {
1272 m_toresolve
.pop_front();
1281 bool CDownloadQueue::AddLink( const wxString
& link
, uint8 category
)
1285 if (link
.compare(0, 7, wxT("magnet:")) == 0) {
1286 uri
= CMagnetED2KConverter(link
);
1288 AddLogLineM(true, CFormat(_("Cannot convert magnet link to eD2k: %s")) % link
);
1293 if (uri
.compare(0, 7, wxT("ed2k://")) == 0) {
1294 return AddED2KLink(uri
, category
);
1296 AddLogLineM(true, CFormat(_("Unknown protocol of link: %s")) % link
);
1302 bool CDownloadQueue::AddED2KLink( const wxString
& link
, uint8 category
)
1304 wxASSERT( !link
.IsEmpty() );
1305 wxString URI
= link
;
1307 // Need the links to end with /, otherwise CreateLinkFromUrl crashes us.
1308 if ( URI
.Last() != wxT('/') ) {
1313 CScopedPtr
<CED2KLink
> uri(CED2KLink::CreateLinkFromUrl(URI
));
1315 return AddED2KLink( uri
.get(), category
);
1316 } catch ( const wxString
& err
) {
1317 AddLogLineM( true, CFormat( _("Invalid eD2k link! ERROR: %s")) % err
);
1324 bool CDownloadQueue::AddED2KLink( const CED2KLink
* link
, uint8 category
)
1326 switch ( link
->GetKind() ) {
1327 case CED2KLink::kFile
:
1328 return AddED2KLink( dynamic_cast<const CED2KFileLink
*>( link
), category
);
1330 case CED2KLink::kServer
:
1331 return AddED2KLink( dynamic_cast<const CED2KServerLink
*>( link
) );
1333 case CED2KLink::kServerList
:
1334 return AddED2KLink( dynamic_cast<const CED2KServerListLink
*>( link
) );
1343 bool CDownloadQueue::AddED2KLink( const CED2KFileLink
* link
, uint8 category
)
1345 CPartFile
* file
= NULL
;
1346 if (IsFileExisting(link
->GetHashKey())) {
1347 // Must be a shared file if we are to add hashes or sources
1348 if ((file
= GetFileByID(link
->GetHashKey())) == NULL
) {
1352 if (link
->GetSize() > OLD_MAX_FILE_SIZE
) {
1353 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
1354 AddLogLineM(true, _("Filesystem for Temp directory cannot handle large files."));
1356 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp
->glob_prefs
->GetCatPath(category
))) {
1357 AddLogLineM(true, _("Filesystem for Incoming directory cannot handle large files."));
1362 file
= new CPartFile(link
);
1364 if (file
->GetStatus() == PS_ERROR
) {
1369 AddDownload(file
, thePrefs::AddNewFilesPaused(), category
);
1372 if (link
->HasValidAICHHash()) {
1373 CAICHHashSet
* hashset
= file
->GetAICHHashset();
1375 if (!hashset
->HasValidMasterHash() || (hashset
->GetMasterHash() != link
->GetAICHHash())) {
1376 hashset
->SetMasterHash(link
->GetAICHHash(), AICH_VERIFIED
);
1377 hashset
->FreeHashSet();
1381 const CED2KFileLink::CED2KLinkSourceList
& list
= link
->m_sources
;
1382 CED2KFileLink::CED2KLinkSourceList::const_iterator it
= list
.begin();
1383 for (; it
!= list
.end(); ++it
) {
1384 AddToResolve(link
->GetHashKey(), it
->addr
, it
->port
, it
->hash
, it
->cryptoptions
);
1391 bool CDownloadQueue::AddED2KLink( const CED2KServerLink
* link
)
1393 CServer
*server
= new CServer( link
->GetPort(), Uint32toStringIP( link
->GetIP() ) );
1395 server
->SetListName( Uint32toStringIP( link
->GetIP() ) );
1397 theApp
->serverlist
->AddServer(server
);
1399 Notify_ServerAdd(server
);
1405 bool CDownloadQueue::AddED2KLink( const CED2KServerListLink
* link
)
1407 theApp
->serverlist
->UpdateServerMetFromURL( link
->GetAddress() );
1413 void CDownloadQueue::ObserverAdded( ObserverType
* o
)
1415 CObservableQueue
<CPartFile
*>::ObserverAdded( o
);
1417 EventType::ValueList list
;
1420 wxMutexLocker
lock(m_mutex
);
1421 list
.reserve( m_filelist
.size() );
1422 list
.insert( list
.begin(), m_filelist
.begin(), m_filelist
.end() );
1425 NotifyObservers( EventType( EventType::INITIAL
, &list
), o
);
1428 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
)
1430 AddDebugLogLineM(false, logKadSearch
, wxString::Format(wxT("Search result sources (type %i)"),type
));
1432 //Safety measure to make sure we are looking for these sources
1433 CPartFile
* temp
= GetFileByKadFileSearchID(searchID
);
1435 AddDebugLogLineM(false, logKadSearch
, wxT("This is not the file we're looking for..."));
1439 //Do we need more sources?
1440 if(!(!temp
->IsStopped() && thePrefs::GetMaxSourcePerFile() > temp
->GetSourceCount())) {
1441 AddDebugLogLineM(false, logKadSearch
, wxT("No more sources needed for this file"));
1445 uint32_t ED2KID
= wxUINT32_SWAP_ALWAYS(ip
);
1447 if (theApp
->ipfilter
->IsFiltered(ED2KID
)) {
1448 AddDebugLogLineM(false, logKadSearch
, wxT("Source ip got filtered"));
1449 AddDebugLogLineM(false, logIPFilter
, CFormat(wxT("IPfiltered source IP=%s received from Kademlia")) % Uint32toStringIP(ED2KID
));
1453 if( (ip
== Kademlia::CKademlia::GetIPAddress() || ED2KID
== theApp
->GetED2KID()) && tcp
== thePrefs::GetPort()) {
1454 AddDebugLogLineM(false, logKadSearch
, wxT("Trying to add myself as source, ignore"));
1458 CUpDownClient
* ctemp
= NULL
;
1462 // NonFirewalled users
1464 AddDebugLogLineM(false, logKadSearch
, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, no tcp port received")) % Uint32toStringIP(ip
));
1467 if (!IsGoodIP(ED2KID
,thePrefs::FilterLanIPs())) {
1468 AddDebugLogLineM(false, logKadSearch
, CFormat(wxT("%s got filtered")) % Uint32toStringIP(ED2KID
));
1469 AddDebugLogLineM(false, logIPFilter
, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, filtered")) % Uint32toStringIP(ED2KID
));
1472 ctemp
= new CUpDownClient(tcp
, ip
, 0, 0, temp
, false, true);
1473 ctemp
->SetSourceFrom(SF_KADEMLIA
);
1474 // not actually sent or needed for HighID sources
1475 //ctemp->SetServerIP(serverip);
1476 //ctemp->SetServerPort(serverport);
1477 ctemp
->SetKadPort(udp
);
1479 pcontactID
->ToByteArray(cID
);
1480 ctemp
->SetUserHash(CMD4Hash(cID
));
1484 // Don't use this type... Some clients will process it wrong..
1489 // This will be a firewalled client connected to Kad only.
1490 // We set the clientID to 1 as a Kad user only has 1 buddy.
1491 ctemp
= new CUpDownClient(tcp
, 1, 0, 0, temp
, false, true);
1492 // The only reason we set the real IP is for when we get a callback
1493 // from this firewalled source, the compare method will match them.
1494 ctemp
->SetSourceFrom(SF_KADEMLIA
);
1495 ctemp
->SetKadPort(udp
);
1497 pcontactID
->ToByteArray(cID
);
1498 ctemp
->SetUserHash(CMD4Hash(cID
));
1499 pbuddyID
->ToByteArray(cID
);
1500 ctemp
->SetBuddyID(cID
);
1501 ctemp
->SetBuddyIP(buddyip
);
1502 ctemp
->SetBuddyPort(buddyport
);
1506 // firewalled source which supports direct UDP callback
1507 // if we are firewalled ourself, the source is useless to us
1508 if (theApp
->IsFirewalled()) {
1512 if ((byCryptOptions
& 0x08) == 0){
1513 AddDebugLogLineM(false, logKadSearch
, CFormat(wxT("Received Kad source type 6 (direct callback) which has the direct callback flag not set (%s)")) % Uint32toStringIP(ED2KID
));
1517 ctemp
= new CUpDownClient(tcp
, 1, 0, 0, temp
, false, true);
1518 ctemp
->SetSourceFrom(SF_KADEMLIA
);
1519 ctemp
->SetKadPort(udp
);
1520 ctemp
->SetIP(ED2KID
); // need to set the IP address, which cannot be used for TCP but for UDP
1522 pcontactID
->ToByteArray(cID
);
1523 ctemp
->SetUserHash(CMD4Hash(cID
));
1528 // add encryption settings
1529 ctemp
->SetConnectOptions(byCryptOptions
);
1531 AddDebugLogLineM(false, logKadSearch
, CFormat(wxT("Happily adding a source (%s) type %d")) % Uint32_16toStringIP_Port(ED2KID
, ctemp
->GetUserPort()) % type
);
1532 CheckAndAddSource(temp
, ctemp
);
1536 CPartFile
* CDownloadQueue::GetFileByKadFileSearchID(uint32 id
) const
1538 wxMutexLocker
lock( m_mutex
);
1540 for ( uint16 i
= 0; i
< m_filelist
.size(); ++i
) {
1541 if ( id
== m_filelist
[i
]->GetKadFileSearchID()) {
1542 return m_filelist
[ i
];
1549 bool CDownloadQueue::DoKademliaFileRequest()
1551 return ((::GetTickCount() - lastkademliafilerequest
) > KADEMLIAASKTIME
);
1553 // File_checked_for_headers