Fixed some build warnings in release mode
[amule.git] / src / DownloadQueue.cpp
blobd094c96cab5304abaf18e8218d8f4160c505e9b0
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2011 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/utils.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
51 #include "Logger.h"
52 #include <common/Format.h> // Needed for CFormat
53 #include "IPFilter.h"
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
69 // 546 / 16 = 34
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 )
80 m_datarate = 0;
81 m_udpserver = 0;
82 m_lastsorttime = 0;
83 m_lastudpsearchtime = 0;
84 m_lastudpstattime = 0;
85 m_udcounter = 0;
86 m_nLastED2KLinkCheck = 0;
87 m_dwNextTCPSrcReq = 0;
88 m_cRequestsSentToServer = 0;
89 m_lastDiskCheck = 0;
91 // Static thresholds until dynamic kicks in.
92 m_rareFileThreshold = RARE_FILE;
93 m_commonFileThreshold = 100;
95 SetLastKademliaFileRequest();
99 CDownloadQueue::~CDownloadQueue()
101 if ( !m_filelist.empty() ) {
102 for ( unsigned int i = 0; i < m_filelist.size(); i++ ) {
103 AddLogLineNS(CFormat(_("Saving PartFile %u of %u")) % (i + 1) % m_filelist.size());
104 delete m_filelist[i];
106 AddLogLineNS(_("All PartFiles Saved."));
111 void CDownloadQueue::LoadMetFiles(const CPath& path)
113 AddLogLineNS(CFormat(_("Loading temp files from %s.")) % path.GetPrintable());
115 std::vector<CPath> files;
117 // Locate part-files to be loaded
118 CDirIterator TempDir(path);
119 CPath fileName = TempDir.GetFirstFile(CDirIterator::File, wxT("*.part.met"));
120 while (fileName.IsOk()) {
121 files.push_back(path.JoinPaths(fileName));
123 fileName = TempDir.GetNextFile();
126 // Loading in order makes it easier to figure which
127 // file is broken in case of crashes, or the like.
128 std::sort(files.begin(), files.end());
130 // Load part-files
131 for ( size_t i = 0; i < files.size(); i++ ) {
132 AddLogLineNS(CFormat(_("Loading PartFile %u of %u")) % (i + 1) % files.size());
133 fileName = files[i].GetFullName();
134 CPartFile *toadd = new CPartFile();
135 bool result = toadd->LoadPartFile(path, fileName) != 0;
136 if (!result) {
137 // Try from backup
138 result = toadd->LoadPartFile(path, fileName, true) != 0;
140 if (result && !IsFileExisting(toadd->GetFileHash())) {
142 wxMutexLocker lock(m_mutex);
143 m_filelist.push_back(toadd);
145 NotifyObservers(EventType(EventType::INSERTED, toadd));
146 Notify_DownloadCtrlAddFile(toadd);
147 } else {
148 wxString msg;
149 if (result) {
150 msg << CFormat(wxT("WARNING: Duplicate partfile with hash '%s' found, skipping: %s"))
151 % toadd->GetFileHash().Encode() % fileName;
152 } else {
153 // If result is false, then reading of both the primary and the backup .met failed
154 AddLogLineN(_("ERROR: Failed to load backup file. Search http://forum.amule.org for .part.met recovery solutions."));
155 msg << CFormat(wxT("ERROR: Failed to load PartFile '%s'")) % fileName;
157 AddLogLineCS(msg);
159 // Delete the partfile object in the end.
160 delete toadd;
163 AddLogLineNS(_("All PartFiles Loaded."));
165 if ( GetFileCount() == 0 ) {
166 AddLogLineN(_("No part files found"));
167 } else {
168 AddLogLineN(CFormat(wxPLURAL("Found %u part file", "Found %u part files", GetFileCount())) % GetFileCount());
170 DoSortByPriority();
171 CheckDiskspace( path );
172 Notify_ShowUpdateCatTabTitles();
177 uint16 CDownloadQueue::GetFileCount() const
179 wxMutexLocker lock( m_mutex );
181 return m_filelist.size();
185 void CDownloadQueue::CopyFileList(std::vector<CPartFile*>& out_list, bool includeCompleted) const
187 wxMutexLocker lock(m_mutex);
189 out_list.reserve(m_filelist.size() + includeCompleted ? m_completedDownloads.size() : 0);
190 for (FileQueue::const_iterator it = m_filelist.begin(); it != m_filelist.end(); ++it) {
191 out_list.push_back(*it);
193 if (includeCompleted) {
194 for (FileList::const_iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); ++it) {
195 out_list.push_back(*it);
201 CServer* CDownloadQueue::GetUDPServer() const
203 wxMutexLocker lock( m_mutex );
205 return m_udpserver;
209 void CDownloadQueue::SetUDPServer( CServer* server )
211 wxMutexLocker lock( m_mutex );
213 m_udpserver = server;
217 void CDownloadQueue::SaveSourceSeeds()
219 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
220 GetFileByIndex( i )->SaveSourceSeeds();
225 void CDownloadQueue::LoadSourceSeeds()
227 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
228 GetFileByIndex( i )->LoadSourceSeeds();
233 void CDownloadQueue::AddSearchToDownload(CSearchFile* toadd, uint8 category)
235 if ( IsFileExisting(toadd->GetFileHash()) ) {
236 return;
239 if (toadd->GetFileSize() > OLD_MAX_FILE_SIZE) {
240 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
241 AddLogLineC(_("Filesystem for Temp directory cannot handle large files."));
242 return;
243 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
244 AddLogLineC(_("Filesystem for Incoming directory cannot handle large files."));
245 return;
249 CPartFile* newfile = NULL;
250 try {
251 newfile = new CPartFile(toadd);
252 } catch (const CInvalidPacket& WXUNUSED(e)) {
253 AddDebugLogLineC(logDownloadQueue, wxT("Search-result contained invalid tags, could not add"));
256 if ( newfile && newfile->GetStatus() != PS_ERROR ) {
257 AddDownload( newfile, thePrefs::AddNewFilesPaused(), category );
258 // Add any possible sources
259 if (toadd->GetClientID() && toadd->GetClientPort()) {
260 CMemFile sources(1+4+2);
261 sources.WriteUInt8(1);
262 sources.WriteUInt32(toadd->GetClientID());
263 sources.WriteUInt16(toadd->GetClientPort());
264 sources.Reset();
265 newfile->AddSources(sources, toadd->GetClientServerIP(), toadd->GetClientServerPort(), SF_SEARCH_RESULT, false);
267 for (std::list<CSearchFile::ClientStruct>::const_iterator it = toadd->GetClients().begin(); it != toadd->GetClients().end(); ++it) {
268 CMemFile sources(1+4+2);
269 sources.WriteUInt8(1);
270 sources.WriteUInt32(it->m_ip);
271 sources.WriteUInt16(it->m_port);
272 sources.Reset();
273 newfile->AddSources(sources, it->m_serverIP, it->m_serverPort, SF_SEARCH_RESULT, false);
275 } else {
276 delete newfile;
281 struct SFindBestPF
283 void operator()(CPartFile* file) {
284 // Check if we should filter out other categories
285 int alphaorder = 0;
287 if ((m_category != -1) && (file->GetCategory() != m_category)) {
288 return;
289 } else if (file->GetStatus() != PS_PAUSED) {
290 return;
291 } else if (m_alpha && m_result && ((alphaorder = file->GetFileName().GetPrintable().CmpNoCase(m_result->GetFileName().GetPrintable())) > 0)) {
292 return;
295 if (!m_result) {
296 m_result = file;
297 } else {
298 if (m_alpha && (alphaorder < 0)) {
299 m_result = file;
300 } else if (file->GetDownPriority() > m_result->GetDownPriority()) {
301 // Either not alpha ordered, or they have the same alpha ordering (could happen if they have same name)
302 m_result = file;
303 } else {
304 // Lower priority file
309 //! The category to look for, or -1 if any category is good
310 int m_category;
311 //! If any acceptable files are found, this variable store their pointer
312 CPartFile* m_result;
313 //! If we should order alphabetically
314 bool m_alpha;
318 void CDownloadQueue::StartNextFile(CPartFile* oldfile)
320 if ( thePrefs::StartNextFile() ) {
321 SFindBestPF visitor = { -1, NULL, thePrefs::StartNextFileAlpha() };
324 wxMutexLocker lock(m_mutex);
326 if (thePrefs::StartNextFileSame()) {
327 // Get a download in the same category
328 visitor.m_category = oldfile->GetCategory();
330 visitor = std::for_each(m_filelist.begin(), m_filelist.end(), visitor);
333 if (visitor.m_result == NULL) {
334 // Get a download, regardless of category
335 visitor.m_category = -1;
337 visitor = std::for_each(m_filelist.begin(), m_filelist.end(), visitor);
340 // Alpha doesn't need special cases
343 if (visitor.m_result) {
344 visitor.m_result->ResumeFile();
350 void CDownloadQueue::AddDownload(CPartFile* file, bool paused, uint8 category)
352 wxCHECK_RET(!IsFileExisting(file->GetFileHash()), wxT("Adding duplicate part-file"));
354 if (file->GetStatus(true) == PS_ALLOCATING) {
355 file->PauseFile();
356 } else if (paused && GetFileCount()) {
357 file->StopFile();
361 wxMutexLocker lock(m_mutex);
362 m_filelist.push_back( file );
363 DoSortByPriority();
366 NotifyObservers( EventType( EventType::INSERTED, file ) );
367 if (category < theApp->glob_prefs->GetCatCount()) {
368 file->SetCategory(category);
369 } else {
370 AddDebugLogLineN( logDownloadQueue, wxT("Tried to add download into invalid category.") );
372 Notify_DownloadCtrlAddFile( file );
373 theApp->searchlist->UpdateSearchFileByHash(file->GetFileHash()); // Update file in the search dialog if it's still open
374 AddLogLineC(CFormat(_("Downloading %s")) % file->GetFileName() );
378 bool CDownloadQueue::IsFileExisting( const CMD4Hash& fileid ) const
380 if (CKnownFile* file = theApp->sharedfiles->GetFileByID(fileid)) {
381 if (file->IsPartFile()) {
382 AddLogLineC(CFormat( _("You are already trying to download the file '%s'") ) % file->GetFileName());
383 } else {
384 // Check if the file exists, since otherwise the user is forced to
385 // manually reload the shares to download a file again.
386 CPath fullpath = file->GetFilePath().JoinPaths(file->GetFileName());
387 if (!fullpath.FileExists()) {
388 // The file is no longer available, unshare it
389 theApp->sharedfiles->RemoveFile(file);
391 return false;
394 AddLogLineC(CFormat( _("You already have the file '%s'") ) % file->GetFileName());
397 return true;
398 } else if ((file = GetFileByID(fileid))) {
399 AddLogLineC(CFormat( _("You are already trying to download the file %s") ) % file->GetFileName());
400 return true;
403 return false;
406 #define RARITY_FACTOR 4 // < 25%
407 #define NORMALITY_FACTOR 2 // <50%
408 // x > NORMALITY_FACTOR -> High availablity.
410 void CDownloadQueue::Process()
412 // send src requests to local server
413 ProcessLocalRequests();
416 wxMutexLocker lock(m_mutex);
418 uint32 downspeed = 0;
419 if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) {
420 downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1);
421 if (downspeed < 50) {
422 downspeed = 50;
423 } else if (downspeed > 200) {
424 downspeed = 200;
428 m_datarate = 0;
429 m_udcounter++;
430 uint32 cur_datarate = 0;
431 uint32 cur_udcounter = m_udcounter;
433 std::list<int> m_sourcecountlist;
435 bool mustPreventSleep = false;
437 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
438 CPartFile* file = m_filelist[i];
440 CMutexUnlocker unlocker(m_mutex);
442 uint8 status = file->GetStatus();
443 mustPreventSleep |= !(status == PS_ERROR || status == PS_INSUFFICIENT || status == PS_PAUSED || status == PS_COMPLETE);
445 if (status == PS_READY || status == PS_EMPTY ){
446 cur_datarate += file->Process( downspeed, cur_udcounter );
447 } else {
448 //This will make sure we don't keep old sources to paused and stoped files..
449 file->StopPausedFile();
452 if (!file->IsPaused() && !file->IsStopped()) {
453 m_sourcecountlist.push_back(file->GetSourceCount());
457 if (thePrefs::GetPreventSleepWhileDownloading()) {
458 if ((mustPreventSleep == false) && (theStats::GetSessionSentBytes() < theStats::GetSessionReceivedBytes())) {
459 // I can see right through your clever plan.
460 mustPreventSleep = true;
463 if (mustPreventSleep) {
464 PlatformSpecific::PreventSleepMode();
465 } else {
466 PlatformSpecific::AllowSleepMode();
468 } else {
469 // Just in case the value changes while we're preventing. Calls to this function are totally inexpensive anwyay
470 PlatformSpecific::AllowSleepMode();
474 // Set the source rarity thresholds
475 int nSourceGroups = m_sourcecountlist.size();
476 if (nSourceGroups) {
477 m_sourcecountlist.sort();
478 if (nSourceGroups == 1) {
479 // High anyway.
480 m_rareFileThreshold = m_sourcecountlist.front() + 1;
481 m_commonFileThreshold = m_rareFileThreshold + 1;
482 } else if (nSourceGroups == 2) {
483 // One high, one low (unless they're both 0, then both high)
484 m_rareFileThreshold = (m_sourcecountlist.back() > 0) ? (m_sourcecountlist.back() - 1) : 1;
485 m_commonFileThreshold = m_rareFileThreshold + 1;
486 } else {
487 // More than two, time to do some math.
489 // Lower 25% with the current #define values.
490 int rarecutpoint = (nSourceGroups / RARITY_FACTOR);
491 for (int i = 0; i < rarecutpoint; ++ i) {
492 m_sourcecountlist.pop_front();
494 m_rareFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1;
496 // 50% of the non-rare ones, with the curent #define values.
497 int commoncutpoint = (nSourceGroups - rarecutpoint) / NORMALITY_FACTOR;
498 for (int i = 0; i < commoncutpoint; ++ i) {
499 m_sourcecountlist.pop_front();
501 m_commonFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1;
503 } else {
504 m_rareFileThreshold = RARE_FILE;
505 m_commonFileThreshold = 100;
508 m_datarate += cur_datarate;
510 if (m_udcounter == 5) {
511 if (theApp->serverconnect->IsUDPSocketAvailable()) {
512 if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) {
513 m_lastudpstattime = ::GetTickCount();
515 CMutexUnlocker unlocker(m_mutex);
516 theApp->serverlist->ServerStats();
521 if (m_udcounter == 10) {
522 m_udcounter = 0;
523 if (theApp->serverconnect->IsUDPSocketAvailable()) {
524 if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) {
525 SendNextUDPPacket();
530 if ( (::GetTickCount() - m_lastsorttime) > 10000 ) {
531 DoSortByPriority();
533 // Check if any paused files can be resumed
535 CheckDiskspace(thePrefs::GetTempDir());
539 // Check for new links once per second.
540 if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) {
541 theApp->AddLinksFromFile();
542 m_nLastED2KLinkCheck = ::GetTickCount();
547 CPartFile* CDownloadQueue::GetFileByID(const CMD4Hash& filehash) const
549 wxMutexLocker lock( m_mutex );
551 for ( uint16 i = 0; i < m_filelist.size(); ++i ) {
552 if ( filehash == m_filelist[i]->GetFileHash()) {
553 return m_filelist[ i ];
556 // Check completed too so we can execute remote commands (like change cat) on them
557 for (FileList::const_iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); ++it) {
558 if ( filehash == (*it)->GetFileHash()) {
559 return *it;
563 return NULL;
567 CPartFile* CDownloadQueue::GetFileByIndex(unsigned int index) const
569 wxMutexLocker lock( m_mutex );
571 if ( index < m_filelist.size() ) {
572 return m_filelist[ index ];
575 wxFAIL;
576 return NULL;
580 bool CDownloadQueue::IsPartFile(const CKnownFile* file) const
582 wxMutexLocker lock(m_mutex);
584 for (uint16 i = 0; i < m_filelist.size(); ++i) {
585 if (file == m_filelist[i]) {
586 return true;
590 return false;
594 void CDownloadQueue::OnConnectionState(bool bConnected)
596 wxMutexLocker lock(m_mutex);
598 for (uint16 i = 0; i < m_filelist.size(); ++i) {
599 if ( m_filelist[i]->GetStatus() == PS_READY ||
600 m_filelist[i]->GetStatus() == PS_EMPTY) {
601 m_filelist[i]->SetActive(bConnected);
607 void CDownloadQueue::CheckAndAddSource(CPartFile* sender, CUpDownClient* source)
609 // if we block loopbacks at this point it should prevent us from connecting to ourself
610 if ( source->HasValidHash() ) {
611 if ( source->GetUserHash() == thePrefs::GetUserHash() ) {
612 AddDebugLogLineN( logDownloadQueue, wxT("Tried to add source with matching hash to your own.") );
613 source->Safe_Delete();
614 return;
618 if (sender->IsStopped()) {
619 source->Safe_Delete();
620 return;
623 // Filter sources which are known to be dead/useless
624 if ( theApp->clientlist->IsDeadSource( source ) || sender->IsDeadSource(source) ) {
625 source->Safe_Delete();
626 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()))) {
631 source->Safe_Delete();
632 return;
635 // Find all clients with the same hash
636 if ( source->HasValidHash() ) {
637 CClientList::SourceList found = theApp->clientlist->GetClientsByHash( source->GetUserHash() );
639 CClientList::SourceList::iterator it = found.begin();
640 for ( ; it != found.end(); it++ ) {
641 CKnownFile* file = it->GetRequestFile();
643 // Only check files on the download-queue
644 if ( file ) {
645 // Is the found source queued for something else?
646 if ( file != sender ) {
647 // Try to add a request for the other file
648 if ( it->GetClient()->AddRequestForAnotherFile(sender)) {
649 // Add it to downloadlistctrl
650 Notify_SourceCtrlAddSource(sender, *it, A4AF_SOURCE);
654 source->Safe_Delete();
655 return;
662 // Our new source is real new but maybe it is already uploading to us?
663 // If yes the known client will be attached to the var "source" and the old
664 // source-client will be deleted. However, if the request file of the known
665 // source is NULL, then we have to treat it almost like a new source and if
666 // it isn't NULL and not "sender", then we shouldn't move it, but rather add
667 // a request for the new file.
668 ESourceFrom nSourceFrom = source->GetSourceFrom();
669 if ( theApp->clientlist->AttachToAlreadyKnown(&source, 0) ) {
670 // Already queued for another file?
671 if ( source->GetRequestFile() ) {
672 // If we're already queued for the right file, then there's nothing to do
673 if ( sender != source->GetRequestFile() ) {
674 // Add the new file to the request list
675 source->AddRequestForAnotherFile( sender );
677 } else {
678 // Source was known, but reqfile NULL.
679 source->SetRequestFile( sender );
680 source->SetSourceFrom(nSourceFrom);
681 sender->AddSource( source );
682 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
683 sender->UpdateFileRatingCommentAvail();
686 Notify_SourceCtrlAddSource(sender, CCLIENTREF(source, wxT("CDownloadQueue::CheckAndAddSource Notify_SourceCtrlAddSource 1")), UNAVAILABLE_SOURCE);
688 } else {
689 // Unknown client, add it to the clients list
690 source->SetRequestFile( sender );
692 theApp->clientlist->AddClient(source);
694 sender->AddSource( source );
695 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
696 sender->UpdateFileRatingCommentAvail();
699 Notify_SourceCtrlAddSource(sender, CCLIENTREF(source, wxT("CDownloadQueue::CheckAndAddSource Notify_SourceCtrlAddSource 2")), UNAVAILABLE_SOURCE);
704 void CDownloadQueue::CheckAndAddKnownSource(CPartFile* sender,CUpDownClient* source)
706 // Kad reviewed
708 if (sender->IsStopped()) {
709 return;
712 // Filter sources which are known to be dead/useless
713 if ( sender->IsDeadSource(source) ) {
714 return;
717 // "Filter LAN IPs" -- this may be needed here in case we are connected to the internet and are also connected
718 // to a LAN and some client from within the LAN connected to us. Though this situation may be supported in future
719 // by adding that client to the source list and filtering that client's LAN IP when sending sources to
720 // a client within the internet.
722 // "IPfilter" is not needed here, because that "known" client was already IPfiltered when receiving OP_HELLO.
723 if (!source->HasLowID()) {
724 uint32 nClientIP = wxUINT32_SWAP_ALWAYS(source->GetUserIDHybrid());
725 if (!IsGoodIP(nClientIP, thePrefs::FilterLanIPs())) { // check for 0-IP, localhost and LAN addresses
726 AddDebugLogLineN(logIPFilter, wxT("Ignored already known source with IP=%s") + Uint32toStringIP(nClientIP));
727 return;
731 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
732 if ( (source->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source->HasValidHash()))
733 || (thePrefs::IsClientCryptLayerRequired() && (!source->SupportsCryptLayer() || !source->HasValidHash()))) {
734 return;
737 CPartFile* file = source->GetRequestFile();
739 // Check if the file is already queued for something else
740 if ( file ) {
741 if ( file != sender ) {
742 if ( source->AddRequestForAnotherFile( sender ) ) {
743 Notify_SourceCtrlAddSource( sender, CCLIENTREF(source, wxT("CDownloadQueue::CheckAndAddKnownSource Notify_SourceCtrlAddSource 1")), A4AF_SOURCE );
746 } else {
747 source->SetRequestFile( sender );
749 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
750 sender->UpdateFileRatingCommentAvail();
753 source->SetSourceFrom(SF_PASSIVE);
754 sender->AddSource( source );
755 Notify_SourceCtrlAddSource( sender, CCLIENTREF(source, wxT("CDownloadQueue::CheckAndAddKnownSource Notify_SourceCtrlAddSource 2")), UNAVAILABLE_SOURCE);
760 bool CDownloadQueue::RemoveSource(CUpDownClient* toremove, bool WXUNUSED(updatewindow), bool bDoStatsUpdate)
762 bool removed = false;
763 toremove->DeleteAllFileRequests();
765 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
766 CPartFile* cur_file = GetFileByIndex( i );
768 // Remove from source-list
769 if ( cur_file->DelSource( toremove ) ) {
771 // Remove from sourcelist widget
772 Notify_SourceCtrlRemoveSource(toremove->ECID(), cur_file);
774 cur_file->RemoveDownloadingSource(toremove);
775 removed = true;
776 if ( bDoStatsUpdate ) {
777 cur_file->UpdatePartsInfo();
781 // Remove from A4AF-list
782 cur_file->RemoveA4AFSource( toremove );
786 if ( !toremove->GetFileComment().IsEmpty() || toremove->GetFileRating()>0) {
787 toremove->GetRequestFile()->UpdateFileRatingCommentAvail();
790 toremove->SetRequestFile( NULL );
791 toremove->SetDownloadState(DS_NONE);
792 toremove->ResetFileStatusInfo();
794 return removed;
798 void CDownloadQueue::RemoveFile(CPartFile* file, bool keepAsCompleted)
800 RemoveLocalServerRequest( file );
802 NotifyObservers( EventType( EventType::REMOVED, file ) );
804 wxMutexLocker lock( m_mutex );
806 EraseValue( m_filelist, file );
808 if (keepAsCompleted) {
809 m_completedDownloads.push_back(file);
814 void CDownloadQueue::ClearCompleted(const ListOfUInts32 & ecids)
816 for (ListOfUInts32::const_iterator it1 = ecids.begin(); it1 != ecids.end(); it1++) {
817 uint32 ecid = *it1;
818 for (FileList::iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); it++) {
819 CPartFile * file = *it;
820 if (file->ECID() == ecid) {
821 m_completedDownloads.erase(it);
822 // get a new EC ID so it is resent and cleared in remote gui
823 file->RenewECID();
824 Notify_DownloadCtrlRemoveFile(file);
825 break;
832 CUpDownClient* CDownloadQueue::GetDownloadClientByIP_UDP(uint32 dwIP, uint16 nUDPPort) const
834 wxMutexLocker lock( m_mutex );
836 for ( unsigned int i = 0; i < m_filelist.size(); i++ ) {
837 const CKnownFile::SourceSet& set = m_filelist[i]->GetSourceList();
839 for ( CKnownFile::SourceSet::const_iterator it = set.begin(); it != set.end(); it++ ) {
840 if ( it->GetIP() == dwIP && it->GetUDPPort() == nUDPPort ) {
841 return it->GetClient();
845 return NULL;
850 * Checks if the specified server is the one we are connected to.
852 bool IsConnectedServer(const CServer* server)
854 if (server && theApp->serverconnect->GetCurrentServer()) {
855 wxString srvAddr = theApp->serverconnect->GetCurrentServer()->GetAddress();
856 uint16 srvPort = theApp->serverconnect->GetCurrentServer()->GetPort();
858 return server->GetAddress() == srvAddr && server->GetPort() == srvPort;
861 return false;
865 bool CDownloadQueue::SendNextUDPPacket()
867 if ( m_filelist.empty() || !theApp->serverconnect->IsUDPSocketAvailable() || !theApp->IsConnectedED2K()) {
868 return false;
871 // Start monitoring the server and the files list
872 if ( !m_queueServers.IsActive() ) {
873 AddObserver( &m_queueFiles );
875 theApp->serverlist->AddObserver( &m_queueServers );
879 bool packetSent = false;
880 while ( !packetSent ) {
881 // Get max files ids per packet for current server
882 int filesAllowed = GetMaxFilesPerUDPServerPacket();
884 if (filesAllowed < 1 || !m_udpserver || IsConnectedServer(m_udpserver)) {
885 // Select the next server to ask, must not be the connected server
886 do {
887 m_udpserver = m_queueServers.GetNext();
888 } while (IsConnectedServer(m_udpserver));
890 m_cRequestsSentToServer = 0;
891 filesAllowed = GetMaxFilesPerUDPServerPacket();
895 // Check if we have asked all servers, in which case we are done
896 if (m_udpserver == NULL) {
897 DoStopUDPRequests();
899 return false;
902 // Memoryfile containing the hash of every file to request
903 // 28bytes allocation because 16b + 4b + 8b is the worse case scenario.
904 CMemFile hashlist( 28 );
906 CPartFile* file = m_queueFiles.GetNext();
908 while ( file && filesAllowed ) {
909 uint8 status = file->GetStatus();
911 if ( ( status == PS_READY || status == PS_EMPTY ) && file->GetSourceCount() < thePrefs::GetMaxSourcePerFileUDP() ) {
912 if (file->IsLargeFile() && !m_udpserver->SupportsLargeFilesUDP()) {
913 AddDebugLogLineN(logDownloadQueue, wxT("UDP Request for sources on a large file ignored: server doesn't support it"));
914 } else {
915 ++m_cRequestsSentToServer;
916 hashlist.WriteHash( file->GetFileHash() );
917 // See the notes on TCP packet
918 if ( m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2 ) {
919 if (file->IsLargeFile()) {
920 wxASSERT(m_udpserver->SupportsLargeFilesUDP());
921 hashlist.WriteUInt32( 0 );
922 hashlist.WriteUInt64( file->GetFileSize() );
923 } else {
924 hashlist.WriteUInt32( file->GetFileSize() );
927 --filesAllowed;
931 // Avoid skipping a file if we can't send any more currently
932 if ( filesAllowed ) {
933 file = m_queueFiles.GetNext();
937 // See if we have anything to send
938 if ( hashlist.GetLength() ) {
939 packetSent = SendGlobGetSourcesUDPPacket(hashlist);
942 // Check if we've covered every file
943 if ( file == NULL ) {
944 // Reset the list of asked files so that the loop will start over
945 m_queueFiles.Reset();
947 // Unset the server so that the next server will be used
948 m_udpserver = NULL;
952 return true;
956 void CDownloadQueue::StopUDPRequests()
958 wxMutexLocker lock( m_mutex );
960 DoStopUDPRequests();
964 void CDownloadQueue::DoStopUDPRequests()
966 // No need to observe when we wont be using the results
967 theApp->serverlist->RemoveObserver( &m_queueServers );
968 RemoveObserver( &m_queueFiles );
970 m_udpserver = 0;
971 m_lastudpsearchtime = ::GetTickCount();
975 // Comparison function needed by sort. Returns true if file1 preceeds file2
976 bool ComparePartFiles(const CPartFile* file1, const CPartFile* file2) {
977 if (file1->GetDownPriority() != file2->GetDownPriority()) {
978 // To place high-priority files before low priority files we have to
979 // invert this test, since PR_LOW is lower than PR_HIGH, and since
980 // placing a PR_LOW file before a PR_HIGH file would mean that
981 // the PR_LOW file gets sources before the PR_HIGH file ...
982 return (file1->GetDownPriority() > file2->GetDownPriority());
983 } else {
984 int sourcesA = file1->GetSourceCount();
985 int sourcesB = file2->GetSourceCount();
987 int notSourcesA = file1->GetNotCurrentSourcesCount();
988 int notSourcesB = file2->GetNotCurrentSourcesCount();
990 int cmp = CmpAny( sourcesA - notSourcesA, sourcesB - notSourcesB );
992 if ( cmp == 0 ) {
993 cmp = CmpAny( notSourcesA, notSourcesB );
996 return cmp < 0;
1001 void CDownloadQueue::DoSortByPriority()
1003 m_lastsorttime = ::GetTickCount();
1004 sort( m_filelist.begin(), m_filelist.end(), ComparePartFiles );
1008 void CDownloadQueue::ResetLocalServerRequests()
1010 wxMutexLocker lock( m_mutex );
1012 m_dwNextTCPSrcReq = 0;
1013 m_localServerReqQueue.clear();
1015 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1016 m_filelist[i]->SetLocalSrcRequestQueued(false);
1021 void CDownloadQueue::RemoveLocalServerRequest( CPartFile* file )
1023 wxMutexLocker lock( m_mutex );
1025 EraseValue( m_localServerReqQueue, file );
1027 file->SetLocalSrcRequestQueued(false);
1031 void CDownloadQueue::ProcessLocalRequests()
1033 wxMutexLocker lock( m_mutex );
1035 bool bServerSupportsLargeFiles = theApp->serverconnect
1036 && theApp->serverconnect->GetCurrentServer()
1037 && theApp->serverconnect->GetCurrentServer()->SupportsLargeFilesTCP();
1039 if ( (!m_localServerReqQueue.empty()) && (m_dwNextTCPSrcReq < ::GetTickCount()) ) {
1040 CMemFile dataTcpFrame(22);
1041 const int iMaxFilesPerTcpFrame = 15;
1042 int iFiles = 0;
1043 while (!m_localServerReqQueue.empty() && iFiles < iMaxFilesPerTcpFrame) {
1044 // find the file with the longest waitingtime
1045 uint32 dwBestWaitTime = 0xFFFFFFFF;
1047 std::list<CPartFile*>::iterator posNextRequest = m_localServerReqQueue.end();
1048 std::list<CPartFile*>::iterator it = m_localServerReqQueue.begin();
1049 while( it != m_localServerReqQueue.end() ) {
1050 CPartFile* cur_file = (*it);
1051 if (cur_file->GetStatus() == PS_READY || cur_file->GetStatus() == PS_EMPTY) {
1052 uint8 nPriority = cur_file->GetDownPriority();
1053 if (nPriority > PR_HIGH) {
1054 wxFAIL;
1055 nPriority = PR_HIGH;
1058 if (cur_file->GetLastSearchTime() + (PR_HIGH-nPriority) < dwBestWaitTime ){
1059 dwBestWaitTime = cur_file->GetLastSearchTime() + (PR_HIGH - nPriority);
1060 posNextRequest = it;
1063 it++;
1064 } else {
1065 it = m_localServerReqQueue.erase(it);
1066 cur_file->SetLocalSrcRequestQueued(false);
1067 AddDebugLogLineN(logDownloadQueue,
1068 CFormat(wxT("Local server source request for file '%s' not sent because of status '%s'"))
1069 % cur_file->GetFileName() % cur_file->getPartfileStatus());
1073 if (posNextRequest != m_localServerReqQueue.end()) {
1074 CPartFile* cur_file = (*posNextRequest);
1075 cur_file->SetLocalSrcRequestQueued(false);
1076 cur_file->SetLastSearchTime(::GetTickCount());
1077 m_localServerReqQueue.erase(posNextRequest);
1078 iFiles++;
1080 if (!bServerSupportsLargeFiles && cur_file->IsLargeFile()) {
1081 AddDebugLogLineN(logDownloadQueue, wxT("TCP Request for sources on a large file ignored: server doesn't support it"));
1082 } else {
1083 AddDebugLogLineN(logDownloadQueue,
1084 CFormat(wxT("Creating local sources request packet for '%s'")) % cur_file->GetFileName());
1085 // create request packet
1086 CMemFile data(16 + (cur_file->IsLargeFile() ? 8 : 4));
1087 data.WriteHash(cur_file->GetFileHash());
1088 // Kry - lugdunum extended protocol on 17.3 to handle filesize properly.
1089 // There is no need to check anything, old server ignore the extra 4 bytes.
1090 // As of 17.9, servers accept a 0 32-bits size and then a 64bits size
1091 if (cur_file->IsLargeFile()) {
1092 wxASSERT(bServerSupportsLargeFiles);
1093 data.WriteUInt32(0);
1094 data.WriteUInt64(cur_file->GetFileSize());
1095 } else {
1096 data.WriteUInt32(cur_file->GetFileSize());
1098 uint8 byOpcode = 0;
1099 if (thePrefs::IsClientCryptLayerSupported() && theApp->serverconnect->GetCurrentServer() != NULL && theApp->serverconnect->GetCurrentServer()->SupportsGetSourcesObfuscation()) {
1100 byOpcode = OP_GETSOURCES_OBFU;
1101 } else {
1102 byOpcode = OP_GETSOURCES;
1104 CPacket packet(data, OP_EDONKEYPROT, byOpcode);
1105 dataTcpFrame.Write(packet.GetPacket(), packet.GetRealPacketSize());
1110 int iSize = dataTcpFrame.GetLength();
1111 if (iSize > 0) {
1112 // create one 'packet' which contains all buffered OP_GETSOURCES ED2K packets to be sent with one TCP frame
1113 // server credits: (16+4)*regularfiles + (16+4+8)*largefiles +1
1114 CScopedPtr<CPacket> packet(new CPacket(new byte[iSize], dataTcpFrame.GetLength(), true, false));
1115 dataTcpFrame.Seek(0, wxFromStart);
1116 dataTcpFrame.Read(packet->GetPacket(), iSize);
1117 uint32 size = packet->GetPacketSize();
1118 theApp->serverconnect->SendPacket(packet.release(), true); // Deletes `packet'.
1119 AddDebugLogLineN(logDownloadQueue, wxT("Sent local sources request packet."));
1120 theStats::AddUpOverheadServer(size);
1123 // next TCP frame with up to 15 source requests is allowed to be sent in..
1124 m_dwNextTCPSrcReq = ::GetTickCount() + SEC2MS(iMaxFilesPerTcpFrame*(16+4));
1130 void CDownloadQueue::SendLocalSrcRequest(CPartFile* sender)
1132 wxMutexLocker lock( m_mutex );
1134 m_localServerReqQueue.push_back(sender);
1138 void CDownloadQueue::ResetCatParts(uint8 cat)
1140 for (FileQueue::iterator it = m_filelist.begin(); it != m_filelist.end(); it++) {
1141 CPartFile* file = *it;
1142 file->RemoveCategory(cat);
1144 for (FileList::iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); it++) {
1145 CPartFile* file = *it;
1146 file->RemoveCategory(cat);
1151 void CDownloadQueue::SetCatPrio(uint8 cat, uint8 newprio)
1153 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
1154 CPartFile* file = GetFileByIndex( i );
1156 if ( !cat || file->GetCategory() == cat ) {
1157 if ( newprio == PR_AUTO ) {
1158 file->SetAutoDownPriority(true);
1159 } else {
1160 file->SetAutoDownPriority(false);
1161 file->SetDownPriority(newprio);
1168 void CDownloadQueue::SetCatStatus(uint8 cat, int newstatus)
1170 std::list<CPartFile*> files;
1173 wxMutexLocker lock(m_mutex);
1175 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1176 if ( m_filelist[i]->CheckShowItemInGivenCat(cat) ) {
1177 files.push_back( m_filelist[i] );
1182 std::list<CPartFile*>::iterator it = files.begin();
1184 for ( ; it != files.end(); it++ ) {
1185 switch ( newstatus ) {
1186 case MP_CANCEL: (*it)->Delete(); break;
1187 case MP_PAUSE: (*it)->PauseFile(); break;
1188 case MP_STOP: (*it)->StopFile(); break;
1189 case MP_RESUME: (*it)->ResumeFile(); break;
1195 uint16 CDownloadQueue::GetDownloadingFileCount() const
1197 wxMutexLocker lock( m_mutex );
1199 uint16 count = 0;
1200 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1201 uint8 status = m_filelist[i]->GetStatus();
1202 if ( status == PS_READY || status == PS_EMPTY ) {
1203 count++;
1207 return count;
1211 uint16 CDownloadQueue::GetPausedFileCount() const
1213 wxMutexLocker lock( m_mutex );
1215 uint16 count = 0;
1216 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
1217 if ( m_filelist[i]->GetStatus() == PS_PAUSED ) {
1218 count++;
1222 return count;
1226 void CDownloadQueue::CheckDiskspace( const CPath& path )
1228 if ( ::GetTickCount() - m_lastDiskCheck < DISKSPACERECHECKTIME ) {
1229 return;
1232 m_lastDiskCheck = ::GetTickCount();
1234 uint64 min = 0;
1235 // Check if the user has set an explicit limit
1236 if ( thePrefs::IsCheckDiskspaceEnabled() ) {
1237 min = thePrefs::GetMinFreeDiskSpace();
1240 // The very least acceptable diskspace is a single PART
1241 if ( min < PARTSIZE ) {
1242 min = PARTSIZE;
1245 uint64 free = CPath::GetFreeSpaceAt(path);
1246 if (free == static_cast<uint64>(wxInvalidOffset)) {
1247 return;
1248 } else if (free < min) {
1249 CUserEvents::ProcessEvent(
1250 CUserEvents::OutOfDiskSpace,
1251 wxT("Temporary partition"));
1254 for (unsigned int i = 0; i < m_filelist.size(); ++i) {
1255 CPartFile* file = m_filelist[i];
1257 switch ( file->GetStatus() ) {
1258 case PS_ERROR:
1259 case PS_COMPLETING:
1260 case PS_COMPLETE:
1261 continue;
1264 if ( free >= min && file->GetInsufficient() ) {
1265 // We'll try to resume files if there is enough free space
1266 if ( free - file->GetNeededSpace() > min ) {
1267 file->ResumeFile();
1269 } else if ( free < min && !file->IsPaused() ) {
1270 // No space left, stop the files.
1271 file->PauseFile( true );
1277 int CDownloadQueue::GetMaxFilesPerUDPServerPacket() const
1279 if ( m_udpserver ) {
1280 if ( m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES ) {
1281 // get max. file ids per packet
1282 if ( m_cRequestsSentToServer < MAX_REQUESTS_PER_SERVER ) {
1283 return std::min(
1284 MAX_FILES_PER_UDP_PACKET,
1285 MAX_REQUESTS_PER_SERVER - m_cRequestsSentToServer
1288 } else if ( m_cRequestsSentToServer < MAX_REQUESTS_PER_SERVER ) {
1289 return 1;
1293 return 0;
1297 bool CDownloadQueue::SendGlobGetSourcesUDPPacket(CMemFile& data)
1299 if (!m_udpserver) {
1300 return false;
1303 CPacket packet(data, OP_EDONKEYPROT, ((m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2) ? OP_GLOBGETSOURCES2 : OP_GLOBGETSOURCES));
1305 theStats::AddUpOverheadServer(packet.GetPacketSize());
1306 theApp->serverconnect->SendUDPPacket(&packet,m_udpserver,false);
1308 return true;
1312 void CDownloadQueue::AddToResolve(const CMD4Hash& fileid, const wxString& pszHostname, uint16 port, const wxString& hash, uint8 cryptoptions)
1314 // double checking
1315 if ( !GetFileByID(fileid) ) {
1316 return;
1319 wxMutexLocker lock( m_mutex );
1321 Hostname_Entry entry = { fileid, pszHostname, port, hash, cryptoptions };
1322 m_toresolve.push_front(entry);
1324 // Check if there are other DNS lookups on queue
1325 if (m_toresolve.size() == 1) {
1326 // Check if it is a simple dot address
1327 uint32 ip = StringIPtoUint32(pszHostname);
1329 if (ip) {
1330 OnHostnameResolved(ip);
1331 } else {
1332 CAsyncDNS* dns = new CAsyncDNS(pszHostname, DNS_SOURCE, theApp);
1334 if ((dns->Create() != wxTHREAD_NO_ERROR) || (dns->Run() != wxTHREAD_NO_ERROR)) {
1335 dns->Delete();
1336 m_toresolve.pop_front();
1343 void CDownloadQueue::OnHostnameResolved(uint32 ip)
1345 wxMutexLocker lock( m_mutex );
1347 wxASSERT( m_toresolve.size() );
1349 Hostname_Entry resolved = m_toresolve.front();
1350 m_toresolve.pop_front();
1352 if ( ip ) {
1353 CPartFile* file = GetFileByID( resolved.fileid );
1354 if ( file ) {
1355 CMemFile sources(1+4+2);
1356 sources.WriteUInt8(1); // No. Sources
1357 sources.WriteUInt32(ip);
1358 sources.WriteUInt16(resolved.port);
1359 sources.WriteUInt8(resolved.cryptoptions);
1360 if (resolved.cryptoptions & 0x80) {
1361 wxASSERT(!resolved.hash.IsEmpty());
1362 CMD4Hash sourcehash;
1363 sourcehash.Decode(resolved.hash);
1364 sources.WriteHash(sourcehash);
1366 sources.Seek(0,wxFromStart);
1368 file->AddSources(sources, 0, 0, SF_LINK, true);
1372 while (m_toresolve.size()) {
1373 Hostname_Entry entry = m_toresolve.front();
1375 // Check if it is a simple dot address
1376 uint32 tmpIP = StringIPtoUint32(entry.strHostname);
1378 if (tmpIP) {
1379 OnHostnameResolved(tmpIP);
1380 } else {
1381 CAsyncDNS* dns = new CAsyncDNS(entry.strHostname, DNS_SOURCE, theApp);
1383 if ((dns->Create() != wxTHREAD_NO_ERROR) || (dns->Run() != wxTHREAD_NO_ERROR)) {
1384 dns->Delete();
1385 m_toresolve.pop_front();
1386 } else {
1387 break;
1394 bool CDownloadQueue::AddLink( const wxString& link, uint8 category )
1396 wxString uri(link);
1398 if (link.compare(0, 7, wxT("magnet:")) == 0) {
1399 uri = CMagnetED2KConverter(link);
1400 if (uri.empty()) {
1401 AddLogLineC(CFormat(_("Cannot convert magnet link to eD2k: %s")) % link);
1402 return false;
1406 if (uri.compare(0, 7, wxT("ed2k://")) == 0) {
1407 return AddED2KLink(uri, category);
1408 } else {
1409 AddLogLineC(CFormat(_("Unknown protocol of link: %s")) % link);
1410 return false;
1415 bool CDownloadQueue::AddED2KLink( const wxString& link, uint8 category )
1417 wxASSERT( !link.IsEmpty() );
1418 wxString URI = link;
1420 // Need the links to end with /, otherwise CreateLinkFromUrl crashes us.
1421 if ( URI.Last() != wxT('/') ) {
1422 URI += wxT("/");
1425 try {
1426 CScopedPtr<CED2KLink> uri(CED2KLink::CreateLinkFromUrl(URI));
1428 return AddED2KLink( uri.get(), category );
1429 } catch ( const wxString& err ) {
1430 AddLogLineC(CFormat( _("Invalid eD2k link! ERROR: %s")) % err);
1433 return false;
1437 bool CDownloadQueue::AddED2KLink( const CED2KLink* link, uint8 category )
1439 switch ( link->GetKind() ) {
1440 case CED2KLink::kFile:
1441 return AddED2KLink( dynamic_cast<const CED2KFileLink*>( link ), category );
1443 case CED2KLink::kServer:
1444 return AddED2KLink( dynamic_cast<const CED2KServerLink*>( link ) );
1446 case CED2KLink::kServerList:
1447 return AddED2KLink( dynamic_cast<const CED2KServerListLink*>( link ) );
1449 default:
1450 return false;
1456 bool CDownloadQueue::AddED2KLink( const CED2KFileLink* link, uint8 category )
1458 CPartFile* file = NULL;
1459 if (IsFileExisting(link->GetHashKey())) {
1460 // Must be a shared file if we are to add hashes or sources
1461 if ((file = GetFileByID(link->GetHashKey())) == NULL) {
1462 return false;
1464 } else {
1465 if (link->GetSize() > OLD_MAX_FILE_SIZE) {
1466 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
1467 AddLogLineC(_("Filesystem for Temp directory cannot handle large files."));
1468 return false;
1469 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
1470 AddLogLineC(_("Filesystem for Incoming directory cannot handle large files."));
1471 return false;
1475 file = new CPartFile(link);
1477 if (file->GetStatus() == PS_ERROR) {
1478 delete file;
1479 return false;
1482 AddDownload(file, thePrefs::AddNewFilesPaused(), category);
1485 if (link->HasValidAICHHash()) {
1486 CAICHHashSet* hashset = file->GetAICHHashset();
1488 if (!hashset->HasValidMasterHash() || (hashset->GetMasterHash() != link->GetAICHHash())) {
1489 hashset->SetMasterHash(link->GetAICHHash(), AICH_VERIFIED);
1490 hashset->FreeHashSet();
1494 const CED2KFileLink::CED2KLinkSourceList& list = link->m_sources;
1495 CED2KFileLink::CED2KLinkSourceList::const_iterator it = list.begin();
1496 for (; it != list.end(); ++it) {
1497 AddToResolve(link->GetHashKey(), it->addr, it->port, it->hash, it->cryptoptions);
1500 return true;
1504 bool CDownloadQueue::AddED2KLink( const CED2KServerLink* link )
1506 CServer *server = new CServer( link->GetPort(), Uint32toStringIP( link->GetIP() ) );
1508 server->SetListName( Uint32toStringIP( link->GetIP() ) );
1510 theApp->serverlist->AddServer(server);
1512 Notify_ServerAdd(server);
1514 return true;
1518 bool CDownloadQueue::AddED2KLink( const CED2KServerListLink* link )
1520 theApp->serverlist->UpdateServerMetFromURL( link->GetAddress() );
1522 return true;
1526 void CDownloadQueue::ObserverAdded( ObserverType* o )
1528 CObservableQueue<CPartFile*>::ObserverAdded( o );
1530 EventType::ValueList list;
1533 wxMutexLocker lock(m_mutex);
1534 list.reserve( m_filelist.size() );
1535 list.insert( list.begin(), m_filelist.begin(), m_filelist.end() );
1538 NotifyObservers( EventType( EventType::INITIAL, &list ), o );
1541 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)
1543 AddDebugLogLineN(logKadSearch, CFormat(wxT("Search result sources (type %i)")) % type);
1545 //Safety measure to make sure we are looking for these sources
1546 CPartFile* temp = GetFileByKadFileSearchID(searchID);
1547 if( !temp ) {
1548 AddDebugLogLineN(logKadSearch, wxT("This is not the file we're looking for..."));
1549 return;
1552 //Do we need more sources?
1553 if(!(!temp->IsStopped() && thePrefs::GetMaxSourcePerFile() > temp->GetSourceCount())) {
1554 AddDebugLogLineN(logKadSearch, wxT("No more sources needed for this file"));
1555 return;
1558 uint32_t ED2KID = wxUINT32_SWAP_ALWAYS(ip);
1560 if (theApp->ipfilter->IsFiltered(ED2KID)) {
1561 AddDebugLogLineN(logKadSearch, wxT("Source ip got filtered"));
1562 AddDebugLogLineN(logIPFilter, CFormat(wxT("IPfiltered source IP=%s received from Kademlia")) % Uint32toStringIP(ED2KID));
1563 return;
1566 if( (ip == Kademlia::CKademlia::GetIPAddress() || ED2KID == theApp->GetED2KID()) && tcp == thePrefs::GetPort()) {
1567 AddDebugLogLineN(logKadSearch, wxT("Trying to add myself as source, ignore"));
1568 return;
1571 CUpDownClient* ctemp = NULL;
1572 switch (type) {
1573 case 4:
1574 case 1: {
1575 // NonFirewalled users
1576 if(!tcp) {
1577 AddDebugLogLineN(logKadSearch, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, no tcp port received")) % Uint32toStringIP(ip));
1578 return;
1580 if (!IsGoodIP(ED2KID,thePrefs::FilterLanIPs())) {
1581 AddDebugLogLineN(logKadSearch, CFormat(wxT("%s got filtered")) % Uint32toStringIP(ED2KID));
1582 AddDebugLogLineN(logIPFilter, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, filtered")) % Uint32toStringIP(ED2KID));
1583 return;
1585 ctemp = new CUpDownClient(tcp, ip, 0, 0, temp, false, true);
1586 ctemp->SetSourceFrom(SF_KADEMLIA);
1587 // not actually sent or needed for HighID sources
1588 //ctemp->SetServerIP(serverip);
1589 //ctemp->SetServerPort(serverport);
1590 ctemp->SetKadPort(udp);
1591 byte cID[16];
1592 pcontactID->ToByteArray(cID);
1593 ctemp->SetUserHash(CMD4Hash(cID));
1594 break;
1596 case 2: {
1597 // Don't use this type... Some clients will process it wrong..
1598 break;
1600 case 5:
1601 case 3: {
1602 // This will be a firewalled client connected to Kad only.
1603 // We set the clientID to 1 as a Kad user only has 1 buddy.
1604 ctemp = new CUpDownClient(tcp, 1, 0, 0, temp, false, true);
1605 // The only reason we set the real IP is for when we get a callback
1606 // from this firewalled source, the compare method will match them.
1607 ctemp->SetSourceFrom(SF_KADEMLIA);
1608 ctemp->SetKadPort(udp);
1609 byte cID[16];
1610 pcontactID->ToByteArray(cID);
1611 ctemp->SetUserHash(CMD4Hash(cID));
1612 pbuddyID->ToByteArray(cID);
1613 ctemp->SetBuddyID(cID);
1614 ctemp->SetBuddyIP(buddyip);
1615 ctemp->SetBuddyPort(buddyport);
1616 break;
1618 case 6: {
1619 // firewalled source which supports direct UDP callback
1620 // if we are firewalled ourself, the source is useless to us
1621 if (theApp->IsFirewalled()) {
1622 break;
1625 if ((byCryptOptions & 0x08) == 0){
1626 AddDebugLogLineN(logKadSearch, CFormat(wxT("Received Kad source type 6 (direct callback) which has the direct callback flag not set (%s)")) % Uint32toStringIP(ED2KID));
1627 break;
1630 ctemp = new CUpDownClient(tcp, 1, 0, 0, temp, false, true);
1631 ctemp->SetSourceFrom(SF_KADEMLIA);
1632 ctemp->SetKadPort(udp);
1633 ctemp->SetIP(ED2KID); // need to set the IP address, which cannot be used for TCP but for UDP
1634 byte cID[16];
1635 pcontactID->ToByteArray(cID);
1636 ctemp->SetUserHash(CMD4Hash(cID));
1640 if (ctemp) {
1641 // add encryption settings
1642 ctemp->SetConnectOptions(byCryptOptions);
1644 AddDebugLogLineN(logKadSearch, CFormat(wxT("Happily adding a source (%s) type %d")) % Uint32_16toStringIP_Port(ED2KID, ctemp->GetUserPort()) % type);
1645 CheckAndAddSource(temp, ctemp);
1649 CPartFile* CDownloadQueue::GetFileByKadFileSearchID(uint32 id) const
1651 wxMutexLocker lock( m_mutex );
1653 for ( uint16 i = 0; i < m_filelist.size(); ++i ) {
1654 if ( id == m_filelist[i]->GetKadFileSearchID()) {
1655 return m_filelist[ i ];
1659 return NULL;
1662 bool CDownloadQueue::DoKademliaFileRequest()
1664 return ((::GetTickCount() - lastkademliafilerequest) > KADEMLIAASKTIME);
1666 // File_checked_for_headers