2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28 #include "ServerList.h" // Interface declarations.
30 #include <protocol/Protocols.h>
31 #include <protocol/ed2k/Constants.h>
32 #include <common/DataFileVersion.h>
33 #include <tags/ServerTags.h>
35 #include <wx/txtstrm.h>
36 #include <wx/wfstream.h>
37 #include <wx/url.h> // Needed for wxURL
38 #include <wx/tokenzr.h>
40 #include "DownloadQueue.h" // Needed for CDownloadQueue
41 #include "ServerConnect.h" // Needed for CServerConnect
42 #include "Server.h" // Needed for CServer and SRV_PR_*
43 #include "OtherStructs.h" // Needed for ServerMet_Struct
44 #include "CFile.h" // Needed for CFile
45 #include "HTTPDownload.h" // Needed for HTTPThread
46 #include "Preferences.h" // Needed for thePrefs
47 #include "amule.h" // Needed for theApp
48 #include "Statistics.h" // Needed for theStats
49 #include "Packet.h" // Neeed for CPacket
51 #include "ScopedPtr.h"
52 #include <common/Format.h>
54 #include <common/FileFunctions.h> // Needed for UnpackArchive
56 CServerList::CServerList()
58 m_serverpos
= m_servers
.end();
59 m_statserverpos
= m_servers
.end();
60 m_nLastED2KServerLinkCheck
= ::GetTickCount();
64 bool CServerList::Init()
67 bool bRes
= LoadServerMet(CPath(theApp
->ConfigDir
+ wxT("server.met")));
69 // insert static servers from textfile
70 LoadStaticServers(theApp
->ConfigDir
+ wxT("staticservers.dat"));
72 // Send the auto-update of server.met via HTTPThread requests
73 current_url_index
= 0;
74 if ( thePrefs::AutoServerlist()) {
82 bool CServerList::LoadServerMet(const CPath
& path
)
84 AddLogLineM(false, CFormat(_("Loading server.met file: %s")) % path
);
86 bool merge
= !m_servers
.empty();
88 if (!path
.FileExists()) {
89 AddLogLineM(false, _("Server.met file not found!"));
93 // Try to unpack the file, might be an archive
94 const wxChar
* mets
[] = { wxT("server.met"), NULL
};
95 // Try to unpack the file, might be an archive
96 if (UnpackArchive(path
, mets
).second
!= EFT_Met
) {
97 AddLogLineM(true, CFormat(_("Failed to load server.met file '%s', unknown format encountered.")) % path
);
101 CFile
servermet(path
, CFile::read
);
102 if ( !servermet
.IsOpened() ){
103 AddLogLineM( false, _("Failed to open server.met!") );
109 Notify_ServerFreeze();
111 byte version
= servermet
.ReadUInt8();
113 if (version
!= 0xE0 && version
!= MET_HEADER
) {
114 AddLogLineM(true, wxString::Format(_("Server.met file corrupt, found invalid versiontag: 0x%x, size %i"), version
, sizeof(version
)));
119 uint32 fservercount
= servermet
.ReadUInt32();
121 ServerMet_Struct sbuffer
;
122 uint32 iAddCount
= 0;
124 for ( uint32 j
= 0; j
< fservercount
; ++j
) {
125 sbuffer
.ip
= servermet
.ReadUInt32();
126 sbuffer
.port
= servermet
.ReadUInt16();
127 sbuffer
.tagcount
= servermet
.ReadUInt32();
129 CServer
* newserver
= new CServer(&sbuffer
);
132 for ( uint32 i
= 0; i
< sbuffer
.tagcount
; ++i
) {
133 newserver
->AddTagFromFile(&servermet
);
136 // Server priorities are not in sorted order
137 // High = 1, Low = 2, Normal = 0, so we have to check
138 // in a less logical fashion.
139 int priority
= newserver
->GetPreferences();
140 if (priority
< SRV_PR_MIN
|| priority
> SRV_PR_MAX
) {
141 newserver
->SetPreference(SRV_PR_NORMAL
);
144 // set listname for server
145 if ( newserver
->GetListName().IsEmpty() ) {
146 newserver
->SetListName(wxT("Server ") +newserver
->GetAddress());
150 if ( !theApp
->AddServer(newserver
) ) {
151 CServer
* update
= GetServerByAddress(newserver
->GetAddress(), newserver
->GetPort());
153 update
->SetListName( newserver
->GetListName());
154 if(!newserver
->GetDescription().IsEmpty()) {
155 update
->SetDescription( newserver
->GetDescription());
157 Notify_ServerRefresh(update
);
169 AddLogLineM(true, wxString::Format(wxPLURAL("%i server in server.met found", "%i servers in server.met found", fservercount
), fservercount
));
171 AddLogLineM(true, wxString::Format(wxPLURAL("%d server added", "%d servers added", iAddCount
), iAddCount
));
173 } catch (const CInvalidPacket
& err
) {
174 AddLogLineM(true, wxT("Error: the file server.met is corrupted: ") + err
.what());
177 } catch (const CSafeIOException
& err
) {
178 AddLogLineM(true, wxT("IO error while reading 'server.met': ") + err
.what());
187 bool CServerList::AddServer(CServer
* in_server
, bool fromUser
)
189 if ( !in_server
->GetPort() ) {
192 CFormat( _("Server not added: [%s:%d] does not specify a valid port.") )
193 % in_server
->GetAddress()
194 % in_server
->GetPort()
200 !in_server
->HasDynIP() &&
202 !IsGoodIP( in_server
->GetIP(), thePrefs::FilterLanIPs() ) ||
203 ( // don't test for filtered while ipfilter is still loading,
204 // it will be filtered when filter loading is finished
205 theApp
->ipfilter
->IsReady()
206 && theApp
->ipfilter
->IsFiltered(in_server
->GetIP(), true))
211 CFormat( _("Server not added: The IP of [%s:%d] is filtered or invalid.") )
212 % in_server
->GetAddress()
213 % in_server
->GetPort()
220 CServer
* test_server
= GetServerByAddress(in_server
->GetAddress(), in_server
->GetPort());
221 // Avoid duplicate (dynIP) servers: If the server which is to be added, is a dynIP-server
222 // but we don't know yet it's DN, we need to search for an already available server with
224 if (test_server
== NULL
&& in_server
->GetIP() != 0) {
225 test_server
= GetServerByIPTCP(in_server
->GetIP(), in_server
->GetPort());
231 CFormat( _("Server not added: Server with matching IP:Port [%s:%d] found in list.") )
232 % in_server
->GetAddress()
233 % in_server
->GetPort()
237 test_server
->ResetFailedCount();
238 Notify_ServerRefresh( test_server
);
243 theStats::AddServer();
245 m_servers
.push_back(in_server
);
246 NotifyObservers( EventType( EventType::INSERTED
, in_server
) );
250 CFormat( _("Server added: Server at [%s:%d] using the name '%s'.") )
251 % in_server
->GetAddress()
252 % in_server
->GetPort()
253 % in_server
->GetListName()
262 void CServerList::ServerStats()
264 uint32 tNow
= ::GetTickCount();
266 if (theApp
->IsConnectedED2K() && m_servers
.size() > 0) {
267 CServer
* ping_server
= GetNextStatServer();
268 CServer
* test
= ping_server
;
273 while (ping_server
->GetLastPingedTime() && (tNow
- ping_server
->GetLastPingedTime()) < UDPSERVSTATREASKTIME
) {
274 ping_server
= GetNextStatServer();
275 if (ping_server
== test
) {
280 if (ping_server
->GetFailedCount() >= thePrefs::GetDeadserverRetries() && thePrefs::DeadServer() && !ping_server
->IsStaticMember()) {
281 RemoveServer(ping_server
);
285 srand((unsigned)time(NULL
));
286 ping_server
->SetRealLastPingedTime(tNow
); // this is not used to calcualte the next ping, but only to ensure a minimum delay for premature pings
287 if (!ping_server
->GetCryptPingReplyPending() && (!ping_server
->GetLastPingedTime() || (tNow
- ping_server
->GetLastPingedTime()) >= UDPSERVSTATREASKTIME
) && theApp
->GetPublicIP() && thePrefs::IsServerCryptLayerUDPEnabled()) {
288 // We try a obfsucation ping first and wait 20 seconds for an answer
289 // if it doesn't get responsed, we don't count it as error but continue with a normal ping
290 ping_server
->SetCryptPingReplyPending(true);
291 uint32 nPacketLen
= 4 + (uint8
)(rand() % 16); // max padding 16 bytes
292 CScopedArray
<byte
> pRawPacket(nPacketLen
);
293 uint32 dwChallenge
= (rand() << 17) | (rand() << 2) | (rand() & 0x03);
294 if (dwChallenge
== 0) {
298 memcpy(pRawPacket
.get(), &dwChallenge
, sizeof(uint32
));
299 for (uint32 i
= 4; i
< nPacketLen
; i
++) { // fillng up the remaining bytes with random data
300 pRawPacket
[i
] = (uint8
)rand();
303 ping_server
->SetChallenge(dwChallenge
);
304 ping_server
->SetLastPinged(tNow
);
305 ping_server
->SetLastPingedTime((tNow
- (uint32
)UDPSERVSTATREASKTIME
) + 20); // give it 20 seconds to respond
307 AddDebugLogLineM(false, logServerUDP
, CFormat(wxT(">> Sending OP__GlobServStatReq (obfuscated) to server %s:%u")) % ping_server
->GetAddress() % ping_server
->GetPort());
309 CPacket
* packet
= new CPacket(pRawPacket
[1], nPacketLen
- 2, pRawPacket
[0]);
310 packet
->CopyToDataBuffer(0, pRawPacket
.get() + 2, nPacketLen
- 2);
312 theStats::AddUpOverheadServer(packet
->GetPacketSize());
313 theApp
->serverconnect
->SendUDPPacket(packet
, ping_server
, true, true /*raw packet*/, 12 /* Port offset is 12 for obfuscated encryption*/);
314 } else if (ping_server
->GetCryptPingReplyPending() || theApp
->GetPublicIP() == 0 || !thePrefs::IsServerCryptLayerUDPEnabled()){
315 // our obfsucation ping request was not answered, so probably the server doesn'T supports obfuscation
316 // continue with a normal request
317 if (ping_server
->GetCryptPingReplyPending() && thePrefs::IsServerCryptLayerUDPEnabled()) {
318 AddDebugLogLineM(false, logServerUDP
, wxT("CryptPing failed for server ") + ping_server
->GetListName());
319 } else if (thePrefs::IsServerCryptLayerUDPEnabled()) {
320 AddDebugLogLineM(false, logServerUDP
, wxT("CryptPing skipped because our public IP is unknown for server ") + ping_server
->GetListName());
323 ping_server
->SetCryptPingReplyPending(false);
325 CPacket
* packet
= new CPacket(OP_GLOBSERVSTATREQ
, 4, OP_EDONKEYPROT
);
326 uint32 challenge
= 0x55AA0000 + (uint16
)rand();
327 ping_server
->SetChallenge(challenge
);
328 packet
->CopyUInt32ToDataBuffer(challenge
);
329 ping_server
->SetLastPinged(tNow
);
330 ping_server
->SetLastPingedTime(tNow
- (rand() % HR2S(1)));
331 ping_server
->AddFailedCount();
332 Notify_ServerRefresh(ping_server
);
333 theStats::AddUpOverheadServer(packet
->GetPacketSize());
334 theApp
->serverconnect
->SendUDPPacket(packet
, ping_server
, true);
342 void CServerList::RemoveServer(CServer
* in_server
)
344 if (in_server
== theApp
->serverconnect
->GetCurrentServer()) {
345 theApp
->ShowAlert(_("You are connected to the server you are trying to delete. please disconnect first."), _("Info"), wxOK
);
347 CInternalList::iterator it
= std::find(m_servers
.begin(), m_servers
.end(), in_server
);
348 if ( it
!= m_servers
.end() ) {
349 if (theApp
->downloadqueue
->GetUDPServer() == in_server
) {
350 theApp
->downloadqueue
->SetUDPServer( 0 );
353 NotifyObservers( EventType( EventType::REMOVED
, in_server
) );
355 if (m_serverpos
== it
) {
358 if (m_statserverpos
== it
) {
362 theStats::DeleteServer();
364 Notify_ServerRemove(in_server
);
371 void CServerList::RemoveAllServers()
373 NotifyObservers( EventType( EventType::CLEARED
) );
375 theStats::DeleteAllServers();
376 // no connection, safely remove all servers
377 while ( !m_servers
.empty() ) {
378 delete m_servers
.back();
379 m_servers
.pop_back();
381 m_serverpos
= m_servers
.end();
382 m_statserverpos
= m_servers
.end();
386 void CServerList::GetStatus(uint32
&failed
, uint32
&user
, uint32
&file
, uint32
&tuser
, uint32
&tfile
,float &occ
)
397 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
) {
398 const CServer
* const curr
= *it
;
399 if( curr
->GetFailedCount() ) {
402 user
+= curr
->GetUsers();
403 file
+= curr
->GetFiles();
405 tuser
+= curr
->GetUsers();
406 tfile
+= curr
->GetFiles();
408 if (curr
->GetMaxUsers()) {
409 tuserk
+= curr
->GetUsers(); // total users on servers with known maximum
410 maxusers
+=curr
->GetMaxUsers();
414 occ
=(float)(tuserk
*100)/maxusers
;
419 void CServerList::GetUserFileStatus(uint32
&user
, uint32
&file
)
423 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
) {
424 const CServer
* const curr
= *it
;
425 if( !curr
->GetFailedCount() ) {
426 user
+= curr
->GetUsers();
427 file
+= curr
->GetFiles();
433 CServerList::~CServerList()
436 while ( !m_servers
.empty() ) {
437 delete m_servers
.back();
438 m_servers
.pop_back();
443 void CServerList::LoadStaticServers( const wxString
& filename
)
445 if ( !CPath::FileExists( filename
) ) {
449 wxFileInputStream
stream( filename
);
450 wxTextInputStream
f(stream
);
452 while ( !stream
.Eof() ) {
453 wxString line
= f
.ReadLine();
456 if ( line
.GetChar(0) == '#' || line
.GetChar(0) == '/') {
460 wxStringTokenizer
tokens( line
, wxT(",") );
462 if ( tokens
.CountTokens() != 3 ) {
467 // format is host:port,priority,Name
468 wxString addy
= tokens
.GetNextToken().Strip( wxString::both
);
469 wxString prio
= tokens
.GetNextToken().Strip( wxString::both
);
470 wxString name
= tokens
.GetNextToken().Strip( wxString::both
);
472 wxString host
= addy
.BeforeFirst( wxT(':') );
473 wxString port
= addy
.AfterFirst( wxT(':') );
476 int priority
= StrToLong( prio
);
477 if (priority
< SRV_PR_MIN
|| priority
> SRV_PR_MAX
) {
478 priority
= SRV_PR_NORMAL
;
482 // We need a valid name for the list
483 if ( name
.IsEmpty() ) {
488 // create server object and add it to the list
489 CServer
* server
= new CServer( StrToLong( port
), host
);
491 server
->SetListName( name
);
492 server
->SetIsStaticMember( true );
493 server
->SetPreference( priority
);
496 // Try to add the server to the list
497 if ( !theApp
->AddServer( server
) ) {
499 CServer
* existing
= GetServerByAddress( host
, StrToULong( port
) );
501 existing
->SetListName( name
);
502 existing
->SetIsStaticMember( true );
503 existing
->SetPreference( priority
);
505 Notify_ServerRefresh( existing
);
512 struct ServerPriorityComparator
{
513 // Return true iff lhs should strictly appear earlier in the list than rhs.
514 // In this case, we want higher priority servers to appear earlier.
515 bool operator()(const CServer
* lhs
, const CServer
* rhs
) {
518 rhs
->GetPreferences() == SRV_PR_LOW
||
519 rhs
->GetPreferences() == SRV_PR_NORMAL
||
520 rhs
->GetPreferences() == SRV_PR_HIGH
522 switch (lhs
->GetPreferences()) {
526 return rhs
->GetPreferences() == SRV_PR_LOW
;
528 return rhs
->GetPreferences() != SRV_PR_HIGH
;
536 void CServerList::Sort()
538 m_servers
.sort(ServerPriorityComparator());
539 // Once the list has been sorted, it doesn't really make sense to continue
540 // traversing the new order from the old position. Plus, there's a bug in
541 // version of libstdc++ before gcc4 such that iterators that were equal to
542 // end() were left dangling.
543 m_serverpos
= m_servers
.begin();
544 m_statserverpos
= m_servers
.begin();
548 CServer
* CServerList::GetNextServer(bool bOnlyObfuscated
)
550 while (bOnlyObfuscated
&& (m_serverpos
!= m_servers
.end()) && !((*m_serverpos
)->SupportsObfuscationTCP() || (*m_serverpos
)->SupportsObfuscationUDP())) {
551 wxASSERT(*m_serverpos
!= NULL
);
555 if (m_serverpos
== m_servers
.end()) {
559 return *m_serverpos
++;
567 CServer
* CServerList::GetNextStatServer()
569 if (m_statserverpos
== m_servers
.end()) {
570 m_statserverpos
= m_servers
.begin();
573 if (m_statserverpos
== m_servers
.end()) {
576 wxASSERT(*m_statserverpos
!= NULL
);
577 return *m_statserverpos
++;
582 CServer
* CServerList::GetServerByAddress(const wxString
& address
, uint16 port
) const
584 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
) {
585 CServer
* const s
= *it
;
586 if (port
== s
->GetPort() && s
->GetAddress() == address
) {
594 CServer
* CServerList::GetServerByIP(uint32 nIP
) const
596 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
){
597 CServer
* const s
= *it
;
598 if (s
->GetIP() == nIP
)
605 CServer
* CServerList::GetServerByIPTCP(uint32 nIP
, uint16 nPort
) const
607 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
){
608 CServer
* const s
= *it
;
609 if (s
->GetIP() == nIP
&& s
->GetPort() == nPort
)
615 CServer
* CServerList::GetServerByIPUDP(uint32 nIP
, uint16 nUDPPort
, bool bObfuscationPorts
) const
617 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
){
618 CServer
* const s
=*it
;
619 if (s
->GetIP() == nIP
620 && (s
->GetPort() == nUDPPort
-4
621 || (bObfuscationPorts
&& s
->GetObfuscationPortUDP() == nUDPPort
)
622 || s
->GetPort() == nUDPPort
- 12))
628 bool CServerList::SaveServerMet()
630 CPath newservermet
= CPath(theApp
->ConfigDir
+ wxT("server.met.new"));
632 CFile
servermet( newservermet
, CFile::write
);
633 if (!servermet
.IsOpened()) {
634 AddLogLineM(false,_("Failed to save server.met!"));
640 servermet
.WriteUInt8(0xE0);
641 servermet
.WriteUInt32( m_servers
.size() );
643 for ( CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
) {
644 const CServer
* const server
= *it
;
646 uint16 tagcount
= 12;
647 if (!server
->GetListName().IsEmpty()) {
650 if (!server
->GetDynIP().IsEmpty()) {
653 if (!server
->GetDescription().IsEmpty()) {
656 if (server
->GetConnPort() != server
->GetPort()) {
660 // For unicoded name, description, and dynip
661 if ( !server
->GetListName().IsEmpty() ) {
664 if ( !server
->GetDynIP().IsEmpty() ) {
667 if ( !server
->GetDescription().IsEmpty() ) {
670 if (!server
->GetVersion().IsEmpty()) {
674 if (server
->GetServerKeyUDP(true)) {
678 if (server
->GetServerKeyUDPIP()) {
682 if (server
->GetObfuscationPortTCP()) {
686 if (server
->GetObfuscationPortUDP()) {
690 servermet
.WriteUInt32(server
->GetIP());
691 servermet
.WriteUInt16(server
->GetPort());
692 servermet
.WriteUInt32(tagcount
);
694 if ( !server
->GetListName().IsEmpty() ) {
695 // This is BOM to keep eMule compatibility
696 CTagString( ST_SERVERNAME
, server
->GetListName()).WriteTagToFile( &servermet
, utf8strOptBOM
);
697 CTagString( ST_SERVERNAME
, server
->GetListName()).WriteTagToFile( &servermet
);
700 if ( !server
->GetDynIP().IsEmpty() ) {
701 // This is BOM to keep eMule compatibility
702 CTagString( ST_DYNIP
, server
->GetDynIP()).WriteTagToFile( &servermet
, utf8strOptBOM
);
703 CTagString( ST_DYNIP
, server
->GetDynIP()).WriteTagToFile( &servermet
);
706 if ( !server
->GetDescription().IsEmpty() ) {
707 // This is BOM to keep eMule compatibility
708 CTagString( ST_DESCRIPTION
, server
->GetDescription()).WriteTagToFile( &servermet
, utf8strOptBOM
);
709 CTagString( ST_DESCRIPTION
, server
->GetDescription()).WriteTagToFile( &servermet
);
712 if ( server
->GetConnPort() != server
->GetPort() ) {
713 CTagString( ST_AUXPORTSLIST
, server
->GetAuxPortsList() ).WriteTagToFile( &servermet
);
716 CTagInt32( ST_FAIL
, server
->GetFailedCount() ).WriteTagToFile( &servermet
);
717 CTagInt32( ST_PREFERENCE
, server
->GetPreferences() ).WriteTagToFile( &servermet
);
718 CTagInt32( wxT("users"), server
->GetUsers() ).WriteTagToFile( &servermet
);
719 CTagInt32( wxT("files"), server
->GetFiles() ).WriteTagToFile( &servermet
);
720 CTagInt32( ST_PING
, server
->GetPing() ).WriteTagToFile( &servermet
);
721 CTagInt32( ST_LASTPING
, server
->GetLastPingedTime()).WriteTagToFile( &servermet
);
722 CTagInt32( ST_MAXUSERS
, server
->GetMaxUsers() ).WriteTagToFile( &servermet
);
723 CTagInt32( ST_SOFTFILES
, server
->GetSoftFiles() ).WriteTagToFile( &servermet
);
724 CTagInt32( ST_HARDFILES
, server
->GetHardFiles() ).WriteTagToFile( &servermet
);
725 if (!server
->GetVersion().IsEmpty()){
726 CTagString( ST_VERSION
, server
->GetVersion() ).WriteTagToFile( &servermet
, utf8strOptBOM
);
727 CTagString( ST_VERSION
, server
->GetVersion() ).WriteTagToFile( &servermet
);
729 CTagInt32( ST_UDPFLAGS
, server
->GetUDPFlags() ).WriteTagToFile( &servermet
);
730 CTagInt32( ST_LOWIDUSERS
, server
->GetLowIDUsers() ).WriteTagToFile( &servermet
);
732 if (server
->GetServerKeyUDP(true)) {
733 CTagInt32(ST_UDPKEY
, server
->GetServerKeyUDP(true)).WriteTagToFile( &servermet
);;
736 if (server
->GetServerKeyUDPIP()) {
737 CTagInt32(ST_UDPKEYIP
, server
->GetServerKeyUDPIP()).WriteTagToFile( &servermet
);;;
740 if (server
->GetObfuscationPortTCP()) {
741 CTagInt16(ST_TCPPORTOBFUSCATION
, server
->GetObfuscationPortTCP()).WriteTagToFile( &servermet
);;;
744 if (server
->GetObfuscationPortUDP()) {
745 CTagInt16(ST_UDPPORTOBFUSCATION
, server
->GetObfuscationPortUDP()).WriteTagToFile( &servermet
);;;
749 } catch (const CIOFailureException
& e
) {
750 AddLogLineM(true, wxT("IO failure while writing 'server.met': ") + e
.what());
755 const CPath curservermet
= CPath(theApp
->ConfigDir
+ wxT("server.met"));
756 const CPath oldservermet
= CPath(theApp
->ConfigDir
+ wxT("server_met.old"));
758 if (oldservermet
.FileExists()) {
759 CPath::RemoveFile(oldservermet
);
762 if (curservermet
.FileExists()) {
763 CPath::RenameFile(curservermet
, oldservermet
);
766 CPath::RenameFile(newservermet
, curservermet
);
772 void CServerList::RemoveDeadServers()
774 if ( thePrefs::DeadServer() ) {
775 for ( CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ) {
776 CServer
* server
= *it
++;
777 if ( server
->GetFailedCount() > thePrefs::GetDeadserverRetries() && !server
->IsStaticMember()) {
778 RemoveServer(server
);
784 void CServerList::UpdateServerMetFromURL(const wxString
& strURL
)
786 if (strURL
.Find(wxT("://")) == -1) {
787 AddLogLineM(true, _("Invalid URL"));
790 m_URLUpdate
= strURL
;
791 wxString
strTempFilename(theApp
->ConfigDir
+ wxT("server.met.download"));
792 CHTTPDownloadThread
*downloader
= new CHTTPDownloadThread(strURL
, strTempFilename
, theApp
->ConfigDir
+ wxT("server.met"), HTTP_ServerMet
);
793 downloader
->Create();
798 void CServerList::DownloadFinished(uint32 result
)
800 if(result
== HTTP_Success
) {
801 const CPath tempFilename
= CPath(theApp
->ConfigDir
+ wxT("server.met.download"));
803 // curl succeeded. proceed with server.met loading
804 LoadServerMet(tempFilename
);
807 // So, file is loaded and merged, and also saved
808 CPath::RemoveFile(tempFilename
);
809 AddLogLineN(CFormat(_("Finished downloading the server list from %s")) % m_URLUpdate
);
810 } else if (result
== HTTP_Skipped
) {
811 AddLogLineN(CFormat(_("Skipped download of %s, because requested file is not newer.")) % wxT("server.met"));
813 AddLogLineC(CFormat(_("Failed to download %s from %s")) % wxT("server.met") % m_URLUpdate
);
818 void CServerList::AutoUpdate()
821 uint8 url_count
= theApp
->glob_prefs
->adresses_list
.GetCount();
824 AddLogLineM(true, _("No server list address entry in 'addresses.dat' found. Please paste a valid server list address into this file in order to auto-update your server list"));
827 // Do current URL. Callback function will take care of the others.
828 while ( current_url_index
< url_count
) {
829 wxString URI
= theApp
->glob_prefs
->adresses_list
[current_url_index
];
830 // We use wxURL to validate the URI
831 if ( wxURL( URI
).GetError() == wxURL_NOERR
) {
832 // Ok, got a valid URI
834 wxString strTempFilename
=
835 theApp
->ConfigDir
+ wxT("server_auto.met");
836 AddLogLineM(true, CFormat(
837 _("Start downloading server list from %s")) % URI
);
838 CHTTPDownloadThread
*downloader
= new CHTTPDownloadThread(
839 URI
, strTempFilename
, theApp
->ConfigDir
+ wxT("server.met"), HTTP_ServerMetAuto
);
840 downloader
->Create();
845 AddLogLineM(true, CFormat(
846 _("WARNING: invalid URL specified for auto-updating of servers: %s") ) % URI
);
850 AddLogLineM(true, _("No valid server.met auto-download url on addresses.dat"));
854 void CServerList::AutoDownloadFinished(uint32 result
)
856 if (result
== HTTP_Success
) {
857 CPath tempFilename
= CPath(theApp
->ConfigDir
+ wxT("server_auto.met"));
859 // curl succeeded. proceed with server.met loading
860 LoadServerMet(tempFilename
);
863 // So, file is loaded and merged, and also saved
864 CPath::RemoveFile(tempFilename
);
866 AddLogLineM(true, CFormat(_("Failed to download the server list from %s") ) % m_URLUpdate
);
871 if (current_url_index
< theApp
->glob_prefs
->adresses_list
.GetCount()) {
878 void CServerList::ObserverAdded( ObserverType
* o
)
880 CObservableQueue
<CServer
*>::ObserverAdded( o
);
882 EventType::ValueList ilist
;
883 ilist
.reserve( m_servers
.size() );
884 ilist
.assign( m_servers
.begin(), m_servers
.end() );
886 NotifyObservers( EventType( EventType::INITIAL
, &ilist
), o
);
890 uint32
CServerList::GetAvgFile() const
892 //Since there is no real way to know how many files are in the kad network,
893 //I figure to try to use the ED2K network stats to find how many files the
894 //average user shares..
895 uint32 totaluser
= 0;
896 uint32 totalfile
= 0;
897 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
){
898 const CServer
* const curr
= *it
;
899 //If this server has reported Users/Files and doesn't limit it's files too much
900 //use this in the calculation..
901 if( curr
->GetUsers() && curr
->GetFiles() && curr
->GetSoftFiles() > 1000 ) {
902 totaluser
+= curr
->GetUsers();
903 totalfile
+= curr
->GetFiles();
906 //If the user count is a little low, don't send back a average..
907 //I added 50 to the count as many servers do not allow a large amount of files to be shared..
908 //Therefore the estimate here will be lower then the actual.
909 //I would love to add a way for the client to send some statistics back so we could see the real
911 if ( totaluser
> 500000 ) {
912 return (totalfile
/totaluser
)+50;
919 std::vector
<const CServer
*> CServerList::CopySnapshot() const
921 std::vector
<const CServer
*> result
;
922 result
.reserve(m_servers
.size());
923 result
.assign(m_servers
.begin(), m_servers
.end());
928 void CServerList::FilterServers()
930 CInternalList::iterator it
= m_servers
.begin();
931 while (it
!= m_servers
.end()) {
932 CServer
* server
= *it
++;
934 if (server
->HasDynIP()) {
938 if (theApp
->ipfilter
->IsFiltered(server
->GetIP(), true)) {
939 if (server
== theApp
->serverconnect
->GetCurrentServer()) {
940 AddLogLineM(true, _("Local server is filtered by the IPFilters, reconnecting to a different server!"));
941 theApp
->serverconnect
->Disconnect();
942 RemoveServer(server
);
943 theApp
->serverconnect
->ConnectToAnyServer();
945 RemoveServer(server
);
951 void CServerList::CheckForExpiredUDPKeys() {
953 if (!thePrefs::IsServerCryptLayerUDPEnabled()) {
957 uint32 cKeysTotal
= 0;
958 uint32 cKeysExpired
= 0;
959 uint32 cPingDelayed
= 0;
960 const uint32 dwIP
= theApp
->GetPublicIP();
961 const uint32 tNow
= ::GetTickCount();
962 wxASSERT( dwIP
!= 0 );
964 for (CInternalList::const_iterator it
= m_servers
.begin(); it
!= m_servers
.end(); ++it
) {
965 CServer
* pServer
= *it
;
966 if (pServer
->SupportsObfuscationUDP() && pServer
->GetServerKeyUDP(true) != 0 && pServer
->GetServerKeyUDPIP() != dwIP
){
969 if (tNow
- pServer
->GetRealLastPingedTime() < UDPSERVSTATMINREASKTIME
){
971 // next ping: Now + (MinimumDelay - already elapsed time)
972 pServer
->SetLastPingedTime((tNow
- (uint32
)UDPSERVSTATREASKTIME
) + (UDPSERVSTATMINREASKTIME
- (tNow
- pServer
->GetRealLastPingedTime())));
974 pServer
->SetLastPingedTime(0);
976 } else if (pServer
->SupportsObfuscationUDP() && pServer
->GetServerKeyUDP(false) != 0) {
981 // File_checked_for_headers