Updated Spanish translation by tHatdUde
[amule.git] / src / ServerList.cpp
blobeebe1adce6e3970b5c0362f5e925b277a0e1b746
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.
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 <wx/wx.h>
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
50 #include "Logger.h"
51 #include "ScopedPtr.h"
52 #include <common/Format.h>
53 #include "IPFilter.h"
54 #include <common/FileFunctions.h> // Needed for UnpackArchive
55 #include <common/TextFile.h> // Needed for CTextFile
57 CServerList::CServerList()
59 m_serverpos = m_servers.end();
60 m_statserverpos = m_servers.end();
61 m_nLastED2KServerLinkCheck = ::GetTickCount();
62 m_initialized = false;
66 bool CServerList::Init()
68 // Load Metfile
69 bool bRes = LoadServerMet(CPath(theApp->ConfigDir + wxT("server.met")));
71 // insert static servers from textfile
72 m_staticServersConfig = theApp->ConfigDir + wxT("staticservers.dat");
73 LoadStaticServers();
75 // Send the auto-update of server.met via HTTPThread requests
76 current_url_index = 0;
77 if ( thePrefs::AutoServerlist()) {
78 AutoUpdate();
81 m_initialized = true;
82 return bRes;
86 bool CServerList::LoadServerMet(const CPath& path)
88 AddLogLineN(CFormat(_("Loading server.met file: %s")) % path);
90 bool merge = !m_servers.empty();
92 if (!path.FileExists()) {
93 AddLogLineN(_("Server.met file not found!"));
94 return false;
97 // Try to unpack the file, might be an archive
98 const wxChar* mets[] = { wxT("server.met"), NULL };
99 // Try to unpack the file, might be an archive
100 if (UnpackArchive(path, mets).second != EFT_Met) {
101 AddLogLineC(CFormat(_("Failed to load server.met file '%s', unknown format encountered.")) % path);
102 return false;
105 CFile servermet(path, CFile::read);
106 if ( !servermet.IsOpened() ){
107 AddLogLineN(_("Failed to open server.met!") );
108 return false;
112 try {
113 Notify_ServerFreeze();
115 byte version = servermet.ReadUInt8();
117 if (version != 0xE0 && version != MET_HEADER) {
118 AddLogLineC(CFormat(_("Server.met file corrupt, found invalid versiontag: 0x%x, size %i")) % version % sizeof(version));
119 Notify_ServerThaw();
120 return false;
123 uint32 fservercount = servermet.ReadUInt32();
125 ServerMet_Struct sbuffer;
126 uint32 iAddCount = 0;
128 for ( uint32 j = 0; j < fservercount; ++j ) {
129 sbuffer.ip = servermet.ReadUInt32();
130 sbuffer.port = servermet.ReadUInt16();
131 sbuffer.tagcount = servermet.ReadUInt32();
133 CServer* newserver = new CServer(&sbuffer);
135 // Load tags
136 for ( uint32 i = 0; i < sbuffer.tagcount; ++i ) {
137 newserver->AddTagFromFile(&servermet);
140 // Server priorities are not in sorted order
141 // High = 1, Low = 2, Normal = 0, so we have to check
142 // in a less logical fashion.
143 int priority = newserver->GetPreferences();
144 if (priority < SRV_PR_MIN || priority > SRV_PR_MAX) {
145 newserver->SetPreference(SRV_PR_NORMAL);
148 // set listname for server
149 if ( newserver->GetListName().IsEmpty() ) {
150 newserver->SetListName(wxT("Server ") +newserver->GetAddress());
154 if ( !theApp->AddServer(newserver) ) {
155 CServer* update = GetServerByAddress(newserver->GetAddress(), newserver->GetPort());
156 if(update) {
157 update->SetListName( newserver->GetListName());
158 if(!newserver->GetDescription().IsEmpty()) {
159 update->SetDescription( newserver->GetDescription());
161 Notify_ServerRefresh(update);
163 delete newserver;
164 } else {
165 ++iAddCount;
170 Notify_ServerThaw();
172 if (!merge) {
173 AddLogLineC(CFormat(wxPLURAL("%i server in server.met found", "%i servers in server.met found", fservercount)) % fservercount);
174 } else {
175 AddLogLineC(CFormat(wxPLURAL("%d server added", "%d servers added", iAddCount)) % iAddCount);
177 } catch (const CInvalidPacket& err) {
178 AddLogLineC(_("Error: the file 'server.met' is corrupted: ") + err.what());
179 Notify_ServerThaw();
180 return false;
181 } catch (const CSafeIOException& err) {
182 AddLogLineC(_("IO error while reading 'server.met': ") + err.what());
183 Notify_ServerThaw();
184 return false;
187 return true;
191 bool CServerList::AddServer(CServer* in_server, bool fromUser)
193 if ( !in_server->GetPort() ) {
194 if ( fromUser ) {
195 AddLogLineC(CFormat( _("Server not added: [%s:%d] does not specify a valid port.") )
196 % in_server->GetAddress()
197 % in_server->GetPort()
201 return false;
202 } else if (
203 !in_server->HasDynIP() &&
205 !IsGoodIP( in_server->GetIP(), thePrefs::FilterLanIPs() ) ||
206 ( // don't test for filtered while ipfilter is still loading,
207 // it will be filtered when filter loading is finished
208 theApp->ipfilter->IsReady()
209 && theApp->ipfilter->IsFiltered(in_server->GetIP(), true))
212 if ( fromUser ) {
213 AddLogLineC(CFormat( _("Server not added: The IP of [%s:%d] is filtered or invalid.") )
214 % in_server->GetAddress()
215 % in_server->GetPort()
219 return false;
222 CServer* test_server = GetServerByAddress(in_server->GetAddress(), in_server->GetPort());
223 // Avoid duplicate (dynIP) servers: If the server which is to be added, is a dynIP-server
224 // but we don't know yet it's DN, we need to search for an already available server with
225 // that IP.
226 if (test_server == NULL && in_server->GetIP() != 0) {
227 test_server = GetServerByIPTCP(in_server->GetIP(), in_server->GetPort());
230 if (test_server) {
231 if ( fromUser ) {
232 AddLogLineC(CFormat( _("Server not added: Server with matching IP:Port [%s:%d] found in list.") )
233 % in_server->GetAddress()
234 % in_server->GetPort()
238 test_server->ResetFailedCount();
239 Notify_ServerRefresh( test_server );
241 return false;
244 theStats::AddServer();
246 m_servers.push_back(in_server);
247 NotifyObservers( EventType( EventType::INSERTED, in_server ) );
249 if ( fromUser ) {
250 AddLogLineC(CFormat( _("Server added: Server at [%s:%d] using the name '%s'.") )
251 % in_server->GetAddress()
252 % in_server->GetPort()
253 % in_server->GetListName()
258 return true;
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;
269 if (!ping_server) {
270 return;
273 while (ping_server->GetLastPingedTime() && (tNow - ping_server->GetLastPingedTime()) < UDPSERVSTATREASKTIME) {
274 ping_server = GetNextStatServer();
275 if (ping_server == test) {
276 return;
280 if (ping_server->GetFailedCount() >= thePrefs::GetDeadserverRetries() && thePrefs::DeadServer() && !ping_server->IsStaticMember()) {
281 RemoveServer(ping_server);
282 return;
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) {
295 dwChallenge++;
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 AddDebugLogLineN(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 AddDebugLogLineN(logServerUDP, wxT("CryptPing failed for server ") + ping_server->GetListName());
319 } else if (thePrefs::IsServerCryptLayerUDPEnabled()) {
320 AddDebugLogLineN(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);
335 } else {
336 wxFAIL;
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);
346 } else {
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) {
356 ++m_serverpos;
358 if (m_statserverpos == it) {
359 ++m_statserverpos;
361 m_servers.erase(it);
362 theStats::DeleteServer();
364 Notify_ServerRemove(in_server);
365 delete 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)
388 failed = 0;
389 user = 0;
390 file = 0;
391 tuser=0;
392 tfile = 0;
393 occ=0;
394 uint32 maxusers=0;
395 uint32 tuserk = 0;
397 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it) {
398 const CServer* const curr = *it;
399 if( curr->GetFailedCount() ) {
400 ++failed;
401 } else {
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();
413 if (maxusers>0) {
414 occ=(float)(tuserk*100)/maxusers;
419 void CServerList::GetUserFileStatus(uint32 &user, uint32 &file)
421 user = 0;
422 file = 0;
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()
435 if (thePrefs::GetNetworkED2K() && IsInitialized()) {
436 SaveServerMet();
438 while ( !m_servers.empty() ) {
439 delete m_servers.back();
440 m_servers.pop_back();
445 void CServerList::LoadStaticServers()
447 if ( !CPath::FileExists(m_staticServersConfig) ) {
448 return;
451 wxFileInputStream stream(m_staticServersConfig);
452 wxTextInputStream f(stream);
454 while ( !stream.Eof() ) {
455 wxString line = f.ReadLine();
457 // Skip comments
458 if (line.IsEmpty() || line.GetChar(0) == '#' || line.GetChar(0) == '/') {
459 continue;
462 wxStringTokenizer tokens( line, wxT(",") );
464 if ( tokens.CountTokens() != 3 ) {
465 continue;
469 // format is host:port,priority,Name
470 wxString addy = tokens.GetNextToken().Strip( wxString::both );
471 wxString prio = tokens.GetNextToken().Strip( wxString::both );
472 wxString name = tokens.GetNextToken().Strip( wxString::both );
474 wxString host = addy.BeforeFirst( wxT(':') );
475 wxString port = addy.AfterFirst( wxT(':') );
478 int priority = StrToLong( prio );
479 if (priority < SRV_PR_MIN || priority > SRV_PR_MAX) {
480 priority = SRV_PR_NORMAL;
484 // We need a valid name for the list
485 if ( name.IsEmpty() ) {
486 name = addy;
490 // create server object and add it to the list
491 CServer* server = new CServer( StrToLong( port ), host );
493 server->SetListName( name );
494 server->SetIsStaticMember( true );
495 server->SetPreference( priority );
498 // Try to add the server to the list
499 if ( !theApp->AddServer( server ) ) {
500 delete server;
501 CServer* existing = GetServerByAddress( host, StrToULong( port ) );
502 if ( existing) {
503 existing->SetListName( name );
504 existing->SetIsStaticMember( true );
505 existing->SetPreference( priority );
507 Notify_ServerRefresh( existing );
513 void CServerList::SaveStaticServers()
515 CTextFile file;
516 if (!file.Open(m_staticServersConfig, CTextFile::write)) {
517 AddLogLineN(CFormat( _("Failed to open '%s'") ) % m_staticServersConfig );
518 return;
521 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it) {
522 const CServer* server = *it;
524 if (server->IsStaticMember()) {
525 file.WriteLine(CFormat(wxT("%s:%u,%u,%s"))
526 % server->GetAddress() % server->GetPort()
527 % server->GetPreferences() % server->GetListName());
531 file.Close();
534 struct ServerPriorityComparator {
535 // Return true iff lhs should strictly appear earlier in the list than rhs.
536 // In this case, we want higher priority servers to appear earlier.
537 bool operator()(const CServer* lhs, const CServer* rhs) {
538 wxASSERT
540 rhs->GetPreferences() == SRV_PR_LOW ||
541 rhs->GetPreferences() == SRV_PR_NORMAL ||
542 rhs->GetPreferences() == SRV_PR_HIGH
544 switch (lhs->GetPreferences()) {
545 case SRV_PR_LOW:
546 return false;
547 case SRV_PR_NORMAL:
548 return rhs->GetPreferences() == SRV_PR_LOW;
549 case SRV_PR_HIGH:
550 return rhs->GetPreferences() != SRV_PR_HIGH;
551 default:
552 wxFAIL;
553 return false;
558 void CServerList::Sort()
560 m_servers.sort(ServerPriorityComparator());
561 // Once the list has been sorted, it doesn't really make sense to continue
562 // traversing the new order from the old position. Plus, there's a bug in
563 // version of libstdc++ before gcc4 such that iterators that were equal to
564 // end() were left dangling.
565 m_serverpos = m_servers.begin();
566 m_statserverpos = m_servers.begin();
570 CServer* CServerList::GetNextServer(bool bOnlyObfuscated)
572 while (bOnlyObfuscated && (m_serverpos != m_servers.end()) && !((*m_serverpos)->SupportsObfuscationTCP() || (*m_serverpos)->SupportsObfuscationUDP())) {
573 wxASSERT(*m_serverpos != NULL);
574 ++m_serverpos;
577 if (m_serverpos == m_servers.end()) {
578 return 0;
579 } else {
580 if (*m_serverpos) {
581 return *m_serverpos++;
582 } else {
583 return 0;
589 CServer* CServerList::GetNextStatServer()
591 if (m_statserverpos == m_servers.end()) {
592 m_statserverpos = m_servers.begin();
595 if (m_statserverpos == m_servers.end()) {
596 return 0;
597 } else {
598 wxASSERT(*m_statserverpos != NULL);
599 return *m_statserverpos++;
604 CServer* CServerList::GetServerByAddress(const wxString& address, uint16 port) const
606 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it) {
607 CServer* const s = *it;
608 if (port == s->GetPort() && s->GetAddress() == address) {
609 return s;
612 return NULL;
616 CServer* CServerList::GetServerByIP(uint32 nIP) const
618 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it){
619 CServer* const s = *it;
620 if (s->GetIP() == nIP)
621 return s;
623 return NULL;
627 CServer* CServerList::GetServerByIPTCP(uint32 nIP, uint16 nPort) const
629 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it){
630 CServer* const s = *it;
631 if (s->GetIP() == nIP && s->GetPort() == nPort)
632 return s;
634 return NULL;
638 CServer* CServerList::GetServerByIPUDP(uint32 nIP, uint16 nUDPPort, bool bObfuscationPorts) const
640 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it){
641 CServer* const s =*it;
642 if (s->GetIP() == nIP
643 && (s->GetPort() == nUDPPort-4
644 || (bObfuscationPorts && s->GetObfuscationPortUDP() == nUDPPort)
645 || s->GetPort() == nUDPPort - 12))
646 return s;
648 return NULL;
652 CServer* CServerList::GetServerByECID(uint32 ecid) const
654 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it){
655 CServer* const s = *it;
656 if (s->ECID() == ecid) {
657 return s;
660 return NULL;
664 void CServerList::SetStaticServer(CServer* server, bool isStatic)
666 server->SetIsStaticMember(isStatic);
667 Notify_ServerRefresh(server);
668 SaveStaticServers();
672 void CServerList::SetServerPrio(CServer* server, uint32 prio)
674 server->SetPreference(prio);
675 Notify_ServerRefresh(server);
679 bool CServerList::SaveServerMet()
681 CPath curservermet = CPath(theApp->ConfigDir + wxT("server.met"));
683 CFile servermet(curservermet, CFile::write_safe);
684 if (!servermet.IsOpened()) {
685 AddLogLineN(_("Failed to save server.met!"));
686 return false;
689 try {
690 servermet.WriteUInt8(0xE0);
691 servermet.WriteUInt32( m_servers.size() );
693 for ( CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it) {
694 const CServer* const server = *it;
696 uint16 tagcount = 12;
697 if (!server->GetListName().IsEmpty()) {
698 ++tagcount;
700 if (!server->GetDynIP().IsEmpty()) {
701 ++tagcount;
703 if (!server->GetDescription().IsEmpty()) {
704 ++tagcount;
706 if (server->GetConnPort() != server->GetPort()) {
707 ++tagcount;
710 // For unicoded name, description, and dynip
711 if ( !server->GetListName().IsEmpty() ) {
712 ++tagcount;
714 if ( !server->GetDynIP().IsEmpty() ) {
715 ++tagcount;
717 if ( !server->GetDescription().IsEmpty() ) {
718 ++tagcount;
720 if (!server->GetVersion().IsEmpty()) {
721 ++tagcount;
724 if (server->GetServerKeyUDP(true)) {
725 ++tagcount;
728 if (server->GetServerKeyUDPIP()) {
729 ++tagcount;
732 if (server->GetObfuscationPortTCP()) {
733 ++tagcount;
736 if (server->GetObfuscationPortUDP()) {
737 ++tagcount;
740 servermet.WriteUInt32(server->GetIP());
741 servermet.WriteUInt16(server->GetPort());
742 servermet.WriteUInt32(tagcount);
744 if ( !server->GetListName().IsEmpty() ) {
745 // This is BOM to keep eMule compatibility
746 CTagString( ST_SERVERNAME, server->GetListName()).WriteTagToFile( &servermet, utf8strOptBOM);
747 CTagString( ST_SERVERNAME, server->GetListName()).WriteTagToFile( &servermet );
750 if ( !server->GetDynIP().IsEmpty() ) {
751 // This is BOM to keep eMule compatibility
752 CTagString( ST_DYNIP, server->GetDynIP()).WriteTagToFile( &servermet, utf8strOptBOM );
753 CTagString( ST_DYNIP, server->GetDynIP()).WriteTagToFile( &servermet );
756 if ( !server->GetDescription().IsEmpty() ) {
757 // This is BOM to keep eMule compatibility
758 CTagString( ST_DESCRIPTION, server->GetDescription()).WriteTagToFile( &servermet, utf8strOptBOM );
759 CTagString( ST_DESCRIPTION, server->GetDescription()).WriteTagToFile( &servermet );
762 if ( server->GetConnPort() != server->GetPort() ) {
763 CTagString( ST_AUXPORTSLIST, server->GetAuxPortsList() ).WriteTagToFile( &servermet );
766 CTagInt32( ST_FAIL, server->GetFailedCount() ).WriteTagToFile( &servermet );
767 CTagInt32( ST_PREFERENCE, server->GetPreferences() ).WriteTagToFile( &servermet );
768 CTagInt32( wxT("users"), server->GetUsers() ).WriteTagToFile( &servermet );
769 CTagInt32( wxT("files"), server->GetFiles() ).WriteTagToFile( &servermet );
770 CTagInt32( ST_PING, server->GetPing() ).WriteTagToFile( &servermet );
771 CTagInt32( ST_LASTPING, server->GetLastPingedTime()).WriteTagToFile( &servermet );
772 CTagInt32( ST_MAXUSERS, server->GetMaxUsers() ).WriteTagToFile( &servermet );
773 CTagInt32( ST_SOFTFILES, server->GetSoftFiles() ).WriteTagToFile( &servermet );
774 CTagInt32( ST_HARDFILES, server->GetHardFiles() ).WriteTagToFile( &servermet );
775 if (!server->GetVersion().IsEmpty()){
776 CTagString( ST_VERSION, server->GetVersion() ).WriteTagToFile( &servermet, utf8strOptBOM );
777 CTagString( ST_VERSION, server->GetVersion() ).WriteTagToFile( &servermet );
779 CTagInt32( ST_UDPFLAGS, server->GetUDPFlags() ).WriteTagToFile( &servermet );
780 CTagInt32( ST_LOWIDUSERS, server->GetLowIDUsers() ).WriteTagToFile( &servermet );
782 if (server->GetServerKeyUDP(true)) {
783 CTagInt32(ST_UDPKEY, server->GetServerKeyUDP(true)).WriteTagToFile( &servermet );
786 if (server->GetServerKeyUDPIP()) {
787 CTagInt32(ST_UDPKEYIP, server->GetServerKeyUDPIP()).WriteTagToFile( &servermet );
790 if (server->GetObfuscationPortTCP()) {
791 CTagInt16(ST_TCPPORTOBFUSCATION, server->GetObfuscationPortTCP()).WriteTagToFile( &servermet );
794 if (server->GetObfuscationPortUDP()) {
795 CTagInt16(ST_UDPPORTOBFUSCATION, server->GetObfuscationPortUDP()).WriteTagToFile( &servermet );
799 // Now server.met.new is ready to be closed and renamed to server.met.
800 // But first rename existing server.met to server.met.bak (replacing old .bak file).
801 const CPath oldservermet = CPath(theApp->ConfigDir + wxT("server.met.bak"));
802 if (curservermet.FileExists()) {
803 CPath::RenameFile(curservermet, oldservermet, true);
806 servermet.Close();
808 } catch (const CIOFailureException& e) {
809 AddLogLineC(wxT("IO failure while writing 'server.met': ") + e.what());
810 return false;
813 return true;
817 void CServerList::RemoveDeadServers()
819 if ( thePrefs::DeadServer() ) {
820 for ( CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ) {
821 CServer* server = *it++;
822 if ( server->GetFailedCount() > thePrefs::GetDeadserverRetries() && !server->IsStaticMember()) {
823 RemoveServer(server);
829 void CServerList::UpdateServerMetFromURL(const wxString& strURL)
831 if (strURL.Find(wxT("://")) == -1) {
832 AddLogLineC(_("Invalid URL"));
833 return;
835 m_URLUpdate = strURL;
836 wxString strTempFilename(theApp->ConfigDir + wxT("server.met.download"));
837 CHTTPDownloadThread *downloader = new CHTTPDownloadThread(strURL, strTempFilename, theApp->ConfigDir + wxT("server.met"), HTTP_ServerMet, false, false);
838 downloader->Create();
839 downloader->Run();
843 void CServerList::DownloadFinished(uint32 result)
845 if(result == HTTP_Success) {
846 const CPath tempFilename = CPath(theApp->ConfigDir + wxT("server.met.download"));
848 // curl succeeded. proceed with server.met loading
849 LoadServerMet(tempFilename);
850 SaveServerMet();
852 // So, file is loaded and merged, and also saved
853 CPath::RemoveFile(tempFilename);
854 AddLogLineN(CFormat(_("Finished downloading the server list from %s")) % m_URLUpdate);
855 } else if (result == HTTP_Skipped) {
856 AddLogLineN(CFormat(_("Skipped download of %s, because requested file is not newer.")) % wxT("server.met"));
857 } else {
858 AddLogLineC(CFormat(_("Failed to download %s from %s")) % wxT("server.met") % m_URLUpdate);
863 void CServerList::AutoUpdate()
866 uint8 url_count = theApp->glob_prefs->adresses_list.GetCount();
868 if (!url_count) {
869 AddLogLineC(_("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"));
870 return;
872 // Do current URL. Callback function will take care of the others.
873 while ( current_url_index < url_count ) {
874 wxString URI = theApp->glob_prefs->adresses_list[current_url_index];
875 // We use wxURL to validate the URI
876 if ( wxURL( URI ).GetError() == wxURL_NOERR ) {
877 // Ok, got a valid URI
878 m_URLUpdate = URI;
879 wxString strTempFilename =
880 theApp->ConfigDir + wxT("server_auto.met");
881 AddLogLineC(CFormat(
882 _("Start downloading server list from %s")) % URI);
883 CHTTPDownloadThread *downloader = new CHTTPDownloadThread(
884 URI, strTempFilename, theApp->ConfigDir + wxT("server.met"), HTTP_ServerMetAuto, false, false);
885 downloader->Create();
886 downloader->Run();
888 return;
889 } else {
890 AddLogLineC(CFormat(
891 _("WARNING: invalid URL specified for auto-updating of servers: %s") ) % URI);
893 current_url_index++;
895 AddLogLineC(_("No valid server.met auto-download url on addresses.dat"));
899 void CServerList::AutoDownloadFinished(uint32 result)
901 if (result == HTTP_Success) {
902 CPath tempFilename = CPath(theApp->ConfigDir + wxT("server_auto.met"));
904 // curl succeeded. proceed with server.met loading
905 LoadServerMet(tempFilename);
906 SaveServerMet();
908 // So, file is loaded and merged, and also saved
909 CPath::RemoveFile(tempFilename);
910 } else {
911 AddLogLineC(CFormat(_("Failed to download the server list from %s") ) % m_URLUpdate);
914 ++current_url_index;
916 if (current_url_index < theApp->glob_prefs->adresses_list.GetCount()) {
917 // Next!
918 AutoUpdate();
923 void CServerList::ObserverAdded( ObserverType* o )
925 CObservableQueue<CServer*>::ObserverAdded( o );
927 EventType::ValueList ilist;
928 ilist.reserve( m_servers.size() );
929 ilist.assign( m_servers.begin(), m_servers.end() );
931 NotifyObservers( EventType( EventType::INITIAL, &ilist ), o );
935 uint32 CServerList::GetAvgFile() const
937 //Since there is no real way to know how many files are in the kad network,
938 //I figure to try to use the ED2K network stats to find how many files the
939 //average user shares..
940 uint32 totaluser = 0;
941 uint32 totalfile = 0;
942 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it){
943 const CServer* const curr = *it;
944 //If this server has reported Users/Files and doesn't limit it's files too much
945 //use this in the calculation..
946 if( curr->GetUsers() && curr->GetFiles() && curr->GetSoftFiles() > 1000 ) {
947 totaluser += curr->GetUsers();
948 totalfile += curr->GetFiles();
951 //If the user count is a little low, don't send back a average..
952 //I added 50 to the count as many servers do not allow a large amount of files to be shared..
953 //Therefore the estimate here will be lower then the actual.
954 //I would love to add a way for the client to send some statistics back so we could see the real
955 //values here..
956 if ( totaluser > 500000 ) {
957 return (totalfile/totaluser)+50;
958 } else {
959 return 0;
964 std::vector<const CServer*> CServerList::CopySnapshot() const
966 std::vector<const CServer*> result;
967 result.reserve(m_servers.size());
968 result.assign(m_servers.begin(), m_servers.end());
969 return result;
973 void CServerList::FilterServers()
975 CInternalList::iterator it = m_servers.begin();
976 while (it != m_servers.end()) {
977 CServer* server = *it++;
979 if (server->HasDynIP()) {
980 continue;
983 if (theApp->ipfilter->IsFiltered(server->GetIP(), true)) {
984 if (server == theApp->serverconnect->GetCurrentServer()) {
985 AddLogLineC(_("Local server is filtered by the IPFilters, reconnecting to a different server!"));
986 theApp->serverconnect->Disconnect();
987 RemoveServer(server);
988 theApp->serverconnect->ConnectToAnyServer();
989 } else {
990 RemoveServer(server);
996 void CServerList::CheckForExpiredUDPKeys() {
998 if (!thePrefs::IsServerCryptLayerUDPEnabled()) {
999 return;
1002 uint32 cKeysTotal = 0;
1003 uint32 cKeysExpired = 0;
1004 uint32 cPingDelayed = 0;
1005 const uint32 dwIP = theApp->GetPublicIP();
1006 const uint32 tNow = ::GetTickCount();
1007 wxASSERT( dwIP != 0 );
1009 for (CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it) {
1010 CServer* pServer = *it;
1011 if (pServer->SupportsObfuscationUDP() && pServer->GetServerKeyUDP(true) != 0 && pServer->GetServerKeyUDPIP() != dwIP){
1012 cKeysTotal++;
1013 cKeysExpired++;
1014 if (tNow - pServer->GetRealLastPingedTime() < UDPSERVSTATMINREASKTIME){
1015 cPingDelayed++;
1016 // next ping: Now + (MinimumDelay - already elapsed time)
1017 pServer->SetLastPingedTime((tNow - (uint32)UDPSERVSTATREASKTIME) + (UDPSERVSTATMINREASKTIME - (tNow - pServer->GetRealLastPingedTime())));
1018 } else {
1019 pServer->SetLastPingedTime(0);
1021 } else if (pServer->SupportsObfuscationUDP() && pServer->GetServerKeyUDP(false) != 0) {
1022 cKeysTotal++;
1026 // File_checked_for_headers