Fix language getting reset to system default on saving preferences
[amule.git] / src / DownloadQueue.cpp
blob05a87c34ed76d8fb8843aa663a7d66438c708457
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/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 );
176 uint16 CDownloadQueue::GetFileCount() const
178 wxMutexLocker lock( m_mutex );
180 return m_filelist.size();
184 void CDownloadQueue::CopyFileList(std::vector<CPartFile*>& out_list, bool includeCompleted) const
186 wxMutexLocker lock(m_mutex);
188 out_list.reserve(m_filelist.size() + includeCompleted ? m_completedDownloads.size() : 0);
189 for (FileQueue::const_iterator it = m_filelist.begin(); it != m_filelist.end(); ++it) {
190 out_list.push_back(*it);
192 if (includeCompleted) {
193 for (FileList::const_iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); ++it) {
194 out_list.push_back(*it);
200 CServer* CDownloadQueue::GetUDPServer() const
202 wxMutexLocker lock( m_mutex );
204 return m_udpserver;
208 void CDownloadQueue::SetUDPServer( CServer* server )
210 wxMutexLocker lock( m_mutex );
212 m_udpserver = server;
216 void CDownloadQueue::SaveSourceSeeds()
218 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
219 GetFileByIndex( i )->SaveSourceSeeds();
224 void CDownloadQueue::LoadSourceSeeds()
226 for ( uint16 i = 0; i < GetFileCount(); i++ ) {
227 GetFileByIndex( i )->LoadSourceSeeds();
232 void CDownloadQueue::AddSearchToDownload(CSearchFile* toadd, uint8 category)
234 if ( IsFileExisting(toadd->GetFileHash()) ) {
235 return;
238 if (toadd->GetFileSize() > OLD_MAX_FILE_SIZE) {
239 if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
240 AddLogLineC(_("Filesystem for Temp directory cannot handle large files."));
241 return;
242 } else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
243 AddLogLineC(_("Filesystem for Incoming directory cannot handle large files."));
244 return;
248 CPartFile* newfile = NULL;
249 try {
250 newfile = new CPartFile(toadd);
251 } catch (const CInvalidPacket& WXUNUSED(e)) {
252 AddDebugLogLineC(logDownloadQueue, wxT("Search-result contained invalid tags, could not add"));
255 if ( newfile && newfile->GetStatus() != PS_ERROR ) {
256 AddDownload( newfile, thePrefs::AddNewFilesPaused(), category );
257 // Add any possible sources
258 if (toadd->GetClientID() && toadd->GetClientPort()) {
259 CMemFile sources(1+4+2);
260 sources.WriteUInt8(1);
261 sources.WriteUInt32(toadd->GetClientID());
262 sources.WriteUInt16(toadd->GetClientPort());
263 sources.Reset();
264 newfile->AddSources(sources, toadd->GetClientServerIP(), toadd->GetClientServerPort(), SF_SEARCH_RESULT, false);
266 for (std::list<CSearchFile::ClientStruct>::const_iterator it = toadd->GetClients().begin(); it != toadd->GetClients().end(); ++it) {
267 CMemFile sources(1+4+2);
268 sources.WriteUInt8(1);
269 sources.WriteUInt32(it->m_ip);
270 sources.WriteUInt16(it->m_port);
271 sources.Reset();
272 newfile->AddSources(sources, it->m_serverIP, it->m_serverPort, SF_SEARCH_RESULT, false);
274 } else {
275 delete newfile;
280 struct SFindBestPF
282 void operator()(CPartFile* file) {
283 // Check if we should filter out other categories
284 int alphaorder = 0;
286 if ((m_category != -1) && (file->GetCategory() != m_category)) {
287 return;
288 } else if (file->GetStatus() != PS_PAUSED) {
289 return;
290 } else if (m_alpha && m_result && ((alphaorder = file->GetFileName().GetPrintable().CmpNoCase(m_result->GetFileName().GetPrintable())) > 0)) {
291 return;
294 if (!m_result) {
295 m_result = file;
296 } else {
297 if (m_alpha && (alphaorder < 0)) {
298 m_result = file;
299 } else if (file->GetDownPriority() > m_result->GetDownPriority()) {
300 // Either not alpha ordered, or they have the same alpha ordering (could happen if they have same name)
301 m_result = file;
302 } else {
303 // Lower priority file
308 //! The category to look for, or -1 if any category is good
309 int m_category;
310 //! If any acceptable files are found, this variable store their pointer
311 CPartFile* m_result;
312 //! If we should order alphabetically
313 bool m_alpha;
317 void CDownloadQueue::StartNextFile(CPartFile* oldfile)
319 if ( thePrefs::StartNextFile() ) {
320 SFindBestPF visitor = { -1, NULL, thePrefs::StartNextFileAlpha() };
323 wxMutexLocker lock(m_mutex);
325 if (thePrefs::StartNextFileSame()) {
326 // Get a download in the same category
327 visitor.m_category = oldfile->GetCategory();
329 visitor = std::for_each(m_filelist.begin(), m_filelist.end(), visitor);
332 if (visitor.m_result == NULL) {
333 // Get a download, regardless of category
334 visitor.m_category = -1;
336 visitor = std::for_each(m_filelist.begin(), m_filelist.end(), visitor);
339 // Alpha doesn't need special cases
342 if (visitor.m_result) {
343 visitor.m_result->ResumeFile();
349 void CDownloadQueue::AddDownload(CPartFile* file, bool paused, uint8 category)
351 wxCHECK_RET(!IsFileExisting(file->GetFileHash()), wxT("Adding duplicate part-file"));
353 if (file->GetStatus(true) == PS_ALLOCATING) {
354 file->PauseFile();
355 } else if (paused && GetFileCount()) {
356 file->StopFile();
360 wxMutexLocker lock(m_mutex);
361 m_filelist.push_back( file );
362 DoSortByPriority();
365 NotifyObservers( EventType( EventType::INSERTED, file ) );
366 if (category < theApp->glob_prefs->GetCatCount()) {
367 file->SetCategory(category);
368 } else {
369 AddDebugLogLineN( logDownloadQueue, wxT("Tried to add download into invalid category.") );
371 Notify_DownloadCtrlAddFile( file );
372 theApp->searchlist->UpdateSearchFileByHash(file->GetFileHash()); // Update file in the search dialog if it's still open
373 AddLogLineC(CFormat(_("Downloading %s")) % file->GetFileName() );
377 bool CDownloadQueue::IsFileExisting( const CMD4Hash& fileid ) const
379 if (CKnownFile* file = theApp->sharedfiles->GetFileByID(fileid)) {
380 if (file->IsPartFile()) {
381 AddLogLineC(CFormat( _("You are already trying to download the file '%s'") ) % file->GetFileName());
382 } else {
383 // Check if the file exists, since otherwise the user is forced to
384 // manually reload the shares to download a file again.
385 CPath fullpath = file->GetFilePath().JoinPaths(file->GetFileName());
386 if (!fullpath.FileExists()) {
387 // The file is no longer available, unshare it
388 theApp->sharedfiles->RemoveFile(file);
390 return false;
393 AddLogLineC(CFormat( _("You already have the file '%s'") ) % file->GetFileName());
396 return true;
397 } else if ((file = GetFileByID(fileid))) {
398 AddLogLineC(CFormat( _("You are already trying to download the file %s") ) % file->GetFileName());
399 return true;
402 return false;
405 #define RARITY_FACTOR 4 // < 25%
406 #define NORMALITY_FACTOR 2 // <50%
407 // x > NORMALITY_FACTOR -> High availablity.
409 void CDownloadQueue::Process()
411 // send src requests to local server
412 ProcessLocalRequests();
415 wxMutexLocker lock(m_mutex);
417 uint32 downspeed = 0;
418 if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) {
419 downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1);
420 if (downspeed < 50) {
421 downspeed = 50;
422 } else if (downspeed > 200) {
423 downspeed = 200;
427 m_datarate = 0;
428 m_udcounter++;
429 uint32 cur_datarate = 0;
430 uint32 cur_udcounter = m_udcounter;
432 std::list<int> m_sourcecountlist;
434 bool mustPreventSleep = false;
436 for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
437 CPartFile* file = m_filelist[i];
439 CMutexUnlocker unlocker(m_mutex);
441 uint8 status = file->GetStatus();
442 mustPreventSleep |= !(status == PS_ERROR || status == PS_INSUFFICIENT || status == PS_PAUSED || status == PS_COMPLETE);
444 if (status == PS_READY || status == PS_EMPTY ){
445 cur_datarate += file->Process( downspeed, cur_udcounter );
446 } else {
447 //This will make sure we don't keep old sources to paused and stoped files..
448 file->StopPausedFile();
451 if (!file->IsPaused() && !file->IsStopped()) {
452 m_sourcecountlist.push_back(file->GetSourceCount());
456 if (thePrefs::GetPreventSleepWhileDownloading()) {
457 if ((mustPreventSleep == false) && (theStats::GetSessionSentBytes() < theStats::GetSessionReceivedBytes())) {
458 // I can see right through your clever plan.
459 mustPreventSleep = true;
462 if (mustPreventSleep) {
463 PlatformSpecific::PreventSleepMode();
464 } else {
465 PlatformSpecific::AllowSleepMode();
467 } else {
468 // Just in case the value changes while we're preventing. Calls to this function are totally inexpensive anwyay
469 PlatformSpecific::AllowSleepMode();
473 // Set the source rarity thresholds
474 int nSourceGroups = m_sourcecountlist.size();
475 if (nSourceGroups) {
476 m_sourcecountlist.sort();
477 if (nSourceGroups == 1) {
478 // High anyway.
479 m_rareFileThreshold = m_sourcecountlist.front() + 1;
480 m_commonFileThreshold = m_rareFileThreshold + 1;
481 } else if (nSourceGroups == 2) {
482 // One high, one low (unless they're both 0, then both high)
483 m_rareFileThreshold = (m_sourcecountlist.back() > 0) ? (m_sourcecountlist.back() - 1) : 1;
484 m_commonFileThreshold = m_rareFileThreshold + 1;
485 } else {
486 // More than two, time to do some math.
488 // Lower 25% with the current #define values.
489 int rarecutpoint = (nSourceGroups / RARITY_FACTOR);
490 for (int i = 0; i < rarecutpoint; ++ i) {
491 m_sourcecountlist.pop_front();
493 m_rareFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1;
495 // 50% of the non-rare ones, with the curent #define values.
496 int commoncutpoint = (nSourceGroups - rarecutpoint) / NORMALITY_FACTOR;
497 for (int i = 0; i < commoncutpoint; ++ i) {
498 m_sourcecountlist.pop_front();
500 m_commonFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1;
502 } else {
503 m_rareFileThreshold = RARE_FILE;
504 m_commonFileThreshold = 100;
507 m_datarate += cur_datarate;
509 if (m_udcounter == 5) {
510 if (theApp->serverconnect->IsUDPSocketAvailable()) {
511 if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) {
512 m_lastudpstattime = ::GetTickCount();
514 CMutexUnlocker unlocker(m_mutex);
515 theApp->serverlist->ServerStats();
520 if (m_udcounter == 10) {
521 m_udcounter = 0;
522 if (theApp->serverconnect->IsUDPSocketAvailable()) {
523 if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) {
524 SendNextUDPPacket();
529 if ( (::GetTickCount() - m_lastsorttime) > 10000 ) {
530 DoSortByPriority();
532 // Check if any paused files can be resumed
534 CheckDiskspace(thePrefs::GetTempDir());
538 // Check for new links once per second.
539 if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) {
540 theApp->AddLinksFromFile();
541 m_nLastED2KLinkCheck = ::GetTickCount();
546 CPartFile* CDownloadQueue::GetFileByID(const CMD4Hash& filehash) const
548 wxMutexLocker lock( m_mutex );
550 for ( uint16 i = 0; i < m_filelist.size(); ++i ) {
551 if ( filehash == m_filelist[i]->GetFileHash()) {
552 return m_filelist[ i ];
555 // Check completed too so we can execute remote commands (like change cat) on them
556 for (FileList::const_iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); ++it) {
557 if ( filehash == (*it)->GetFileHash()) {
558 return *it;
562 return NULL;
566 CPartFile* CDownloadQueue::GetFileByIndex(unsigned int index) const
568 wxMutexLocker lock( m_mutex );
570 if ( index < m_filelist.size() ) {
571 return m_filelist[ index ];
574 wxFAIL;
575 return NULL;
579 bool CDownloadQueue::IsPartFile(const CKnownFile* file) const
581 wxMutexLocker lock(m_mutex);
583 for (uint16 i = 0; i < m_filelist.size(); ++i) {
584 if (file == m_filelist[i]) {
585 return true;
589 return false;
593 void CDownloadQueue::OnConnectionState(bool bConnected)
595 wxMutexLocker lock(m_mutex);
597 for (uint16 i = 0; i < m_filelist.size(); ++i) {
598 if ( m_filelist[i]->GetStatus() == PS_READY ||
599 m_filelist[i]->GetStatus() == PS_EMPTY) {
600 m_filelist[i]->SetActive(bConnected);
606 void CDownloadQueue::CheckAndAddSource(CPartFile* sender, CUpDownClient* source)
608 // if we block loopbacks at this point it should prevent us from connecting to ourself
609 if ( source->HasValidHash() ) {
610 if ( source->GetUserHash() == thePrefs::GetUserHash() ) {
611 AddDebugLogLineN( logDownloadQueue, wxT("Tried to add source with matching hash to your own.") );
612 source->Safe_Delete();
613 return;
617 if (sender->IsStopped()) {
618 source->Safe_Delete();
619 return;
622 // Filter sources which are known to be dead/useless
623 if ( theApp->clientlist->IsDeadSource( source ) || sender->IsDeadSource(source) ) {
624 source->Safe_Delete();
625 return;
628 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
629 if ( (source->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source->HasValidHash())) || (thePrefs::IsClientCryptLayerRequired() && (!source->SupportsCryptLayer() || !source->HasValidHash()))) {
630 source->Safe_Delete();
631 return;
634 // Find all clients with the same hash
635 if ( source->HasValidHash() ) {
636 CClientList::SourceList found = theApp->clientlist->GetClientsByHash( source->GetUserHash() );
638 CClientList::SourceList::iterator it = found.begin();
639 for ( ; it != found.end(); it++ ) {
640 CKnownFile* file = (*it)->GetRequestFile();
642 // Only check files on the download-queue
643 if ( file ) {
644 // Is the found source queued for something else?
645 if ( file != sender ) {
646 // Try to add a request for the other file
647 if ( (*it)->AddRequestForAnotherFile(sender)) {
648 // Add it to downloadlistctrl
649 Notify_SourceCtrlAddSource(sender, *it, A4AF_SOURCE);
653 source->Safe_Delete();
654 return;
661 // Our new source is real new but maybe it is already uploading to us?
662 // If yes the known client will be attached to the var "source" and the old
663 // source-client will be deleted. However, if the request file of the known
664 // source is NULL, then we have to treat it almost like a new source and if
665 // it isn't NULL and not "sender", then we shouldn't move it, but rather add
666 // a request for the new file.
667 ESourceFrom nSourceFrom = source->GetSourceFrom();
668 if ( theApp->clientlist->AttachToAlreadyKnown(&source, 0) ) {
669 // Already queued for another file?
670 if ( source->GetRequestFile() ) {
671 // If we're already queued for the right file, then there's nothing to do
672 if ( sender != source->GetRequestFile() ) {
673 // Add the new file to the request list
674 source->AddRequestForAnotherFile( sender );
676 } else {
677 // Source was known, but reqfile NULL.
678 source->SetRequestFile( sender );
679 source->SetSourceFrom(nSourceFrom);
680 sender->AddSource( source );
681 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
682 sender->UpdateFileRatingCommentAvail();
685 Notify_SourceCtrlAddSource(sender, source, UNAVAILABLE_SOURCE);
687 } else {
688 // Unknown client, add it to the clients list
689 source->SetRequestFile( sender );
691 theApp->clientlist->AddClient(source);
693 sender->AddSource( source );
694 if ( source->GetFileRating() || !source->GetFileComment().IsEmpty() ) {
695 sender->UpdateFileRatingCommentAvail();
698 Notify_SourceCtrlAddSource(sender, source, UNAVAILABLE_SOURCE);
703 void CDownloadQueue::CheckAndAddKnownSource(CPartFile* sender,CUpDownClient* source)
705 // Kad reviewed
707 if (sender->IsStopped()) {
708 return;
711 // Filter sources which are known to be dead/useless
712 if ( sender->IsDeadSource(source) ) {
713 return;
716 // "Filter LAN IPs" -- this may be needed here in case we are connected to the internet and are also connected
717 // to a LAN and some client from within the LAN connected to us. Though this situation may be supported in future
718 // by adding that client to the source list and filtering that client's LAN IP when sending sources to
719 // a client within the internet.
721 // "IPfilter" is not needed here, because that "known" client was already IPfiltered when receiving OP_HELLO.
722 if (!source->HasLowID()) {
723 uint32 nClientIP = wxUINT32_SWAP_ALWAYS(source->GetUserIDHybrid());
724 if (!IsGoodIP(nClientIP, thePrefs::FilterLanIPs())) { // check for 0-IP, localhost and LAN addresses
725 AddDebugLogLineN(logIPFilter, wxT("Ignored already known source with IP=%s") + Uint32toStringIP(nClientIP));
726 return;
730 // Filter sources which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
731 if ( (source->RequiresCryptLayer() && (!thePrefs::IsClientCryptLayerSupported() || !source->HasValidHash())) || (thePrefs::IsClientCryptLayerRequired() && (!source->SupportsCryptLayer() || !source->HasValidHash())))
733 source->Safe_Delete();
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, source, 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, source, 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, 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;
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