Upstream tarball 20080414
[amule.git] / src / ServerConnect.cpp
blobfe31710e57a4978d918111c2425ac77a51085bb2
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 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 "ServerConnect.h" // Interface declarations.
28 #include <protocol/Protocols.h>
29 #include <protocol/ed2k/ClientSoftware.h> // Sometimes we reply with TCP packets.
30 #include <tags/ClientTags.h>
31 #include <common/ClientVersion.h>
32 #include <common/EventIDs.h>
34 #include "SearchList.h" // Needed for CSearchList
35 #include "ServerUDPSocket.h" // Needed for CServerUDPSocket
36 #include "SharedFileList.h" // Needed for CSharedFileList
37 #include "Packet.h" // Needed for CTag
38 #include "MemFile.h" // Needed for CMemFile
39 #include "ServerSocket.h" // Needed for CServerSocket
40 #include "ListenSocket.h" // Needed for CListenSocket
41 #include "Server.h" // Needed for CServer
42 #include "amule.h" // Needed for theApp
43 #include "ServerList.h" // Needed for CServerList
44 #include "Preferences.h" // Needed for CPreferences
45 #include "Statistics.h" // Needed for theStats
46 #include "Logger.h"
47 #include "GuiEvents.h" // Needed for Notify_*
48 #include <common/Format.h>
51 //#define DEBUG_CLIENT_PROTOCOL
54 void CServerConnect::TryAnotherConnectionrequest()
56 if ( connectionattemps.size() < (unsigned)(( thePrefs::IsSafeServerConnectEnabled()) ? 1 : 2) ) {
58 CServer* next_server = used_list->GetNextServer(m_bTryObfuscated);
60 if ( thePrefs::AutoConnectStaticOnly() ) {
61 while (next_server && !next_server->IsStaticMember()) {
62 next_server = used_list->GetNextServer(m_bTryObfuscated);
66 if (!next_server) {
67 if ( connectionattemps.empty() ) {
68 if (m_bTryObfuscated && !thePrefs::IsClientCryptLayerRequired()){
69 AddLogLineM(true, _("Failed to connect to all obfuscated servers listed. Making another pass without obfuscation."));
70 // try all servers on the non-obfuscated port next
71 m_bTryObfuscated = false;
72 ConnectToAnyServer( false, true);
73 } else {
74 AddLogLineM(true, _("Failed to connect to all servers listed. Making another pass."));
75 ConnectToAnyServer( false );
78 return;
81 ConnectToServer(next_server, true, !m_bTryObfuscated);
85 void CServerConnect::ConnectToAnyServer(bool prioSort, bool bNoCrypt)
87 if (!thePrefs::GetNetworkED2K()){
88 AddLogLineM(true,_("ED2K network disabled on preferences, not connecting."));
89 return;
92 StopConnectionTry();
93 Disconnect();
94 connecting = true;
95 singleconnecting = false;
96 m_bTryObfuscated = thePrefs::IsServerCryptLayerTCPRequested() && !bNoCrypt;
98 // Barry - Only auto-connect to static server option
99 if (thePrefs::AutoConnectStaticOnly()) {
100 bool anystatic = false;
101 CServer *next_server;
102 used_list->ResetServerPos();
103 while ((next_server = used_list->GetNextServer(false)) != NULL) {
104 if (next_server->IsStaticMember()) {
105 anystatic = true;
106 break;
109 if (!anystatic) {
110 connecting = false;
111 AddLogLineM(true,_("No valid servers to connect in serverlist found"));
112 return;
116 if ( thePrefs::Score() && prioSort ) {
117 used_list->Sort();
120 used_list->ResetServerPos();
122 if (used_list->GetServerCount()==0 ) {
123 connecting = false;
124 AddLogLineM(true,_("No valid servers to connect in serverlist found"));
125 return;
128 theApp->listensocket->Process();
130 TryAnotherConnectionrequest();
134 void CServerConnect::ConnectToServer(CServer* server, bool multiconnect, bool bNoCrypt)
136 if (!thePrefs::GetNetworkED2K()){
137 AddLogLineM(true,_("ED2K network disabled on preferences, not connecting."));
138 return;
141 if (!multiconnect) {
142 StopConnectionTry();
143 Disconnect();
145 connecting = true;
146 singleconnecting = !multiconnect;
148 CServerSocket* newsocket = new CServerSocket(this, thePrefs::GetProxyData());
149 m_lstOpenSockets.push_back(newsocket);
150 newsocket->ConnectToServer(server, bNoCrypt);
152 connectionattemps[GetTickCount()] = newsocket;
156 void CServerConnect::StopConnectionTry()
158 connectionattemps.clear();
159 connecting = false;
160 singleconnecting = false;
162 if (m_idRetryTimer.IsRunning())
164 m_idRetryTimer.Stop();
167 // close all currenty opened sockets except the one which is connected to our current server
168 for(SocketsList::iterator it = m_lstOpenSockets.begin(); it != m_lstOpenSockets.end(); ) {
169 CServerSocket *pSck = *it++;
170 if (pSck == connectedsocket) // don't destroy socket which is connected to server
171 continue;
172 if (pSck->m_bIsDeleting == false) // don't destroy socket if it is going to destroy itself later on
173 DestroySocket(pSck);
177 #define CAPABLE_ZLIB 0x01
178 #define CAPABLE_IP_IN_LOGIN_FRAME 0x02
179 #define CAPABLE_AUXPORT 0x04
180 #define CAPABLE_NEWTAGS 0x08
181 #define CAPABLE_UNICODE 0x10
182 #define CAPABLE_LARGEFILES 0x100
183 #define SRVCAP_SUPPORTCRYPT 0x0200
184 #define SRVCAP_REQUESTCRYPT 0x0400
185 #define SRVCAP_REQUIRECRYPT 0x0800
187 void CServerConnect::ConnectionEstablished(CServerSocket* sender)
189 if (connecting == false)
191 // we are already connected to another server
192 DestroySocket(sender);
193 return;
196 if (sender->GetConnectionState() == CS_WAITFORLOGIN) {
197 AddLogLineM(false, CFormat( _("Connected to %s (%s:%i)") )
198 % sender->cur_server->GetListName()
199 % sender->cur_server->GetFullIP()
200 % sender->cur_server->GetPort() );
202 //send loginpacket
203 CServer* update = theApp->serverlist->GetServerByAddress( sender->cur_server->GetAddress(), sender->cur_server->GetPort() );
204 if (update){
205 update->ResetFailedCount();
206 Notify_ServerRefresh( update );
209 CMemFile data(256);
210 data.WriteHash(thePrefs::GetUserHash());
211 // Why pass an ID, if we are loggin in?
212 data.WriteUInt32(GetClientID());
213 data.WriteUInt16(thePrefs::GetPort());
214 data.WriteUInt32(4); // tagcount
216 // Kry - Server doesn't support VBT tags afaik.
217 // Not to mention we don't know its flags yet
219 CTagString tagname(CT_NAME,thePrefs::GetUserNick());
220 tagname.WriteTagToFile(&data);
222 CTagInt32 tagversion(CT_VERSION,EDONKEYVERSION);
223 tagversion.WriteTagToFile(&data);
225 uint32 dwCryptFlags = 0;
227 if (thePrefs::IsClientCryptLayerSupported()) {
228 dwCryptFlags |= SRVCAP_SUPPORTCRYPT;
231 if (thePrefs::IsClientCryptLayerRequested()) {
232 dwCryptFlags |= SRVCAP_REQUESTCRYPT;
235 if (thePrefs::IsClientCryptLayerRequired()) {
236 dwCryptFlags |= SRVCAP_REQUIRECRYPT;
239 // FLAGS for server connection
240 CTagInt32 tagflags(CT_SERVER_FLAGS, CAPABLE_ZLIB
241 | CAPABLE_AUXPORT
242 | CAPABLE_NEWTAGS
243 | CAPABLE_UNICODE
244 | CAPABLE_LARGEFILES
245 | dwCryptFlags
248 tagflags.WriteTagToFile(&data);
250 // eMule Version (14-Mar-2004: requested by lugdunummaster (need for LowID clients which have no chance
251 // to send an Hello packet to the server during the callback test))
252 CTagInt32 tagMuleVersion(CT_EMULE_VERSION,
253 (SO_AMULE << 24) |
254 make_full_ed2k_version(VERSION_MJR, VERSION_MIN, VERSION_UPDATE)
256 tagMuleVersion.WriteTagToFile(&data);
258 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_LOGINREQUEST);
259 #ifdef DEBUG_CLIENT_PROTOCOL
260 AddLogLineM(true,wxT("Client: OP_LOGINREQUEST"));
261 AddLogLineM(true,wxString(wxT(" Hash : ")) << thePrefs::GetUserHash().Encode());
262 AddLogLineM(true,wxString(wxT(" ClientID : ")) << GetClientID());
263 AddLogLineM(true,wxString(wxT(" Port : ")) << thePrefs::GetPort());
264 AddLogLineM(true,wxString(wxT(" User Nick: ")) << thePrefs::GetUserNick());
265 AddLogLineM(true,wxString(wxT(" Edonkey : ")) << EDONKEYVERSION);
266 #endif
267 theStats::AddUpOverheadServer(packet->GetPacketSize());
268 SendPacket(packet, true, sender);
269 } else if (sender->GetConnectionState() == CS_CONNECTED){
270 theStats::AddReconnect();
271 theStats::GetServerConnectTimer()->ResetTimer();
272 connected = true;
273 AddLogLineM(true, CFormat( _("Connection established on: %s") ) % sender->cur_server->GetListName());
274 connectedsocket = sender;
276 StopConnectionTry();
278 CServer* update = theApp->serverlist->GetServerByAddress(connectedsocket->cur_server->GetAddress(),sender->cur_server->GetPort());
279 if ( update ) {
280 Notify_ServerHighlight(update, true);
283 theApp->sharedfiles->ClearED2KPublishInfo();
285 Notify_ServerRemoveDead();
287 // tecxx 1609 2002 - serverlist update
288 if (thePrefs::AddServersFromServer()) {
289 CPacket* packet = new CPacket(OP_GETSERVERLIST, 0, OP_EDONKEYPROT);
290 theStats::AddUpOverheadServer(packet->GetPacketSize());
291 SendPacket(packet, true);
292 #ifdef DEBUG_CLIENT_PROTOCOL
293 AddLogLineM(true,wxT("Client: OP_GETSERVERLIST"));
294 #endif
298 theApp->ShowConnectionState();
302 bool CServerConnect::SendPacket(CPacket* packet,bool delpacket, CServerSocket* to)
304 if (!to) {
305 if (connected) {
306 connectedsocket->SendPacket(packet, delpacket, true);
307 return true;
308 } else {
309 if ( delpacket ) {
310 delete packet;
313 return false;
315 } else {
316 to->SendPacket(packet, delpacket, true);
317 return true;
322 bool CServerConnect::SendUDPPacket(CPacket* packet, CServer* host, bool delpacket, bool rawpacket, uint16 port_offset)
324 if (connected) {
325 serverudpsocket->SendPacket(packet, host, delpacket, rawpacket, port_offset);
326 } else if (delpacket) {
327 delete packet;
330 return true;
334 void CServerConnect::ConnectionFailed(CServerSocket* sender)
336 if (connecting == false && sender != connectedsocket)
338 // just return, cleanup is done by the socket itself
339 return;
341 //messages
342 CServer* pServer = theApp->serverlist->GetServerByAddress(sender->cur_server->GetAddress(), sender->cur_server->GetPort());
343 switch (sender->GetConnectionState()){
344 case CS_FATALERROR:
345 AddLogLineM(true, _("Fatal Error while trying to connect. Internet connection might be down"));
346 break;
347 case CS_DISCONNECTED:
348 theApp->sharedfiles->ClearED2KPublishInfo();
349 AddLogLineM(false,CFormat( _("Lost connection to %s (%s:%i)") )
350 % sender->cur_server->GetListName()
351 % sender->cur_server->GetFullIP()
352 % sender->cur_server->GetPort() );
354 if (pServer){
355 Notify_ServerHighlight(pServer, false);
357 break;
358 case CS_SERVERDEAD:
359 AddLogLineM(false, CFormat( _("%s (%s:%i) appears to be dead.") )
360 % sender->cur_server->GetListName()
361 % sender->cur_server->GetFullIP()
362 % sender->cur_server->GetPort() );
364 if (pServer) {
365 pServer->AddFailedCount();
366 Notify_ServerRefresh( pServer );
368 break;
369 case CS_ERROR:
370 break;
371 case CS_SERVERFULL:
372 AddLogLineM(false, CFormat( _("%s (%s:%i) appears to be full.") )
373 % sender->cur_server->GetListName()
374 % sender->cur_server->GetFullIP()
375 % sender->cur_server->GetPort() );
377 break;
378 case CS_NOTCONNECTED:;
379 break;
382 // IMPORTANT: mark this socket not to be deleted in StopConnectionTry(),
383 // because it will delete itself after this function!
384 sender->m_bIsDeleting = true;
386 switch (sender->GetConnectionState()) {
387 case CS_FATALERROR:{
388 bool autoretry= !singleconnecting;
389 StopConnectionTry();
390 if ((thePrefs::Reconnect()) && (autoretry) && (!m_idRetryTimer.IsRunning())){
391 AddLogLineM(false, wxString::Format(wxPLURAL("Automatic connection to server will retry in %d second", "Automatic connection to server will retry in %d seconds", CS_RETRYCONNECTTIME), CS_RETRYCONNECTTIME));
392 m_idRetryTimer.Start(1000*CS_RETRYCONNECTTIME);
394 break;
396 case CS_DISCONNECTED:{
397 theApp->sharedfiles->ClearED2KPublishInfo();
398 connected = false;
399 Notify_ServerHighlight(sender->cur_server,false);
400 if (connectedsocket) {
401 connectedsocket->Close();
403 connectedsocket = NULL;
404 theApp->searchlist->StopGlobalSearch();
405 Notify_SearchCancel();
406 theStats::GetServerConnectTimer()->StopTimer();
407 if (thePrefs::Reconnect() && !connecting){
408 ConnectToAnyServer();
411 AddLogLineM( true, _("Connection lost") );
412 break;
414 case CS_ERROR:
415 case CS_NOTCONNECTED:{
416 if (!connecting)
417 break;
418 AddLogLineM(false, CFormat( _("Connecting to %s (%s:%i) failed.") )
419 % sender->info
420 % sender->cur_server->GetFullIP()
421 % sender->cur_server->GetPort() );
423 case CS_SERVERDEAD:
424 case CS_SERVERFULL:{
425 if (!connecting) {
426 break;
428 if (singleconnecting) {
429 if (pServer && sender->IsServerCryptEnabledConnection() && !thePrefs::IsClientCryptLayerRequired()){
430 // try reconnecting without obfuscation
431 ConnectToServer(pServer, false, true);
432 break;
435 StopConnectionTry();
436 break;
439 ServerSocketMap::iterator it = connectionattemps.begin();
440 while ( it != connectionattemps.end() ){
441 if ( it->second == sender ) {
442 connectionattemps.erase( it );
443 break;
445 ++it;
447 TryAnotherConnectionrequest();
450 theApp->ShowConnectionState();
453 void CServerConnect::CheckForTimeout()
455 uint32 dwCurTick = GetTickCount();
457 ServerSocketMap::iterator it = connectionattemps.begin();
458 while ( it != connectionattemps.end() ){
459 if ( !it->second ) {
460 AddLogLineM(false, _("Error: Socket invalid at timeoutcheck"));
461 connectionattemps.erase( it );
462 return;
465 if ( dwCurTick - it->first > CONSERVTIMEOUT) {
466 uint32 key = it->first;
467 CServerSocket* value = it->second;
468 ++it;
469 if (!value->IsSolving()) {
470 AddLogLineM(false, CFormat( _("Connection attempt to %s (%s:%i) timed out.") )
471 % value->info
472 % value->cur_server->GetFullIP()
473 % value->cur_server->GetPort() );
475 connectionattemps.erase( key );
477 TryAnotherConnectionrequest();
478 DestroySocket( value );
480 } else {
481 ++it;
487 bool CServerConnect::Disconnect()
489 if (connected && connectedsocket) {
490 theApp->sharedfiles->ClearED2KPublishInfo();
492 connected = false;
494 CServer* update = theApp->serverlist->GetServerByAddress(
495 connectedsocket->cur_server->GetAddress(),
496 connectedsocket->cur_server->GetPort());
497 Notify_ServerHighlight(update, false);
498 theApp->SetPublicIP(0);
499 DestroySocket(connectedsocket);
500 connectedsocket = NULL;
501 theApp->ShowConnectionState();
502 theStats::GetServerConnectTimer()->StopTimer();
503 return true;
504 } else {
505 return false;
510 CServerConnect::CServerConnect(CServerList* in_serverlist, amuleIPV4Address &address)
511 : m_idRetryTimer(theApp,ID_SERVER_RETRY_TIMER_EVENT)
513 connectedsocket = NULL;
514 used_list = in_serverlist;
515 max_simcons = (thePrefs::IsSafeServerConnectEnabled()) ? 1 : 2;
516 connecting = false;
517 connected = false;
518 clientid = 0;
519 singleconnecting = false;
521 // initalize socket for udp packets
522 serverudpsocket = new CServerUDPSocket(address, thePrefs::GetProxyData());
526 CServerConnect::~CServerConnect()
528 m_idRetryTimer.Stop();
529 // stop all connections
530 StopConnectionTry();
531 // close connected socket, if any
532 DestroySocket(connectedsocket);
533 connectedsocket = NULL;
534 // close udp socket
535 delete serverudpsocket;
539 CServer* CServerConnect::GetCurrentServer()
541 if (IsConnected() && connectedsocket) {
542 return connectedsocket->cur_server;
544 return NULL;
548 void CServerConnect::SetClientID(uint32 newid)
550 clientid = newid;
552 if (!::IsLowID(newid)) {
553 theApp->SetPublicIP(newid);
558 void CServerConnect::DestroySocket(CServerSocket* pSck)
560 if (pSck == NULL) {
561 return;
563 m_lstOpenSockets.remove(pSck);
564 pSck->Destroy();
568 bool CServerConnect::IsLocalServer(uint32 dwIP, uint16 nPort)
570 if (IsConnected()){
571 if (connectedsocket->cur_server->GetIP() == dwIP && connectedsocket->cur_server->GetPort() == nPort)
572 return true;
574 return false;
578 void CServerConnect::KeepConnectionAlive()
580 uint32 dwServerKeepAliveTimeout = thePrefs::GetServerKeepAliveTimeout();
581 if (dwServerKeepAliveTimeout && connected && connectedsocket &&
582 connectedsocket->connectionstate == CS_CONNECTED &&
583 GetTickCount() - connectedsocket->GetLastTransmission() >= dwServerKeepAliveTimeout) {
584 // "Ping" the server if the TCP connection was not used for the specified interval with
585 // an empty publish files packet -> recommended by lugdunummaster himself!
587 CMemFile files(4);
588 files.WriteUInt32(0); //nFiles
590 CPacket* packet = new CPacket(files, OP_EDONKEYPROT, OP_OFFERFILES);
591 #ifdef DEBUG_CLIENT_PROTOCOL
592 AddLogLineM(true,wxT("Client: OP_OFFERFILES"));
593 #endif
594 // compress packet
595 // - this kind of data is highly compressable (N * (1 MD4 and at least 3 string meta data tags and 1 integer meta data tag))
596 // - the min. amount of data needed for one published file is ~100 bytes
597 // - this function is called once when connecting to a server and when a file becomes shareable - so, it's called rarely.
598 // - if the compressed size is still >= the original size, we send the uncompressed packet
599 // therefor we always try to compress the packet
600 theStats::AddUpOverheadServer(packet->GetPacketSize());
601 connectedsocket->SendPacket(packet,true);
603 AddDebugLogLineM(false, logServer, wxT("Refreshing server connection"));
607 // true if the IP is one of a server which we currently try to connect to
608 bool CServerConnect::AwaitingTestFromIP(uint32 dwIP)
610 ServerSocketMap::iterator it = connectionattemps.begin();
612 while (it != connectionattemps.end()) {
613 const CServerSocket* serversocket = it->second;
614 if (serversocket && (serversocket->GetConnectionState() == CS_WAITFORLOGIN) &&
615 (serversocket->GetServerIP() == dwIP)) {
616 return true;
618 ++it;
621 return false;
625 bool CServerConnect::IsConnectedObfuscated() const
627 return connectedsocket != NULL && connectedsocket->IsObfusicating();
631 void CServerConnect::OnServerHostnameResolved(void* socket, uint32 ip)
633 // The socket object might have been deleted while we waited for the hostname
634 // to be resolved, so we check if it's still among the open sockets.
635 SocketsList::iterator it = std::find(m_lstOpenSockets.begin(), m_lstOpenSockets.end(), socket);
636 if (it != m_lstOpenSockets.end()) {
637 (*it)->OnHostnameResolved(ip);
638 } else {
639 printf("Received late result of DNS lookup, discarding.\n");
644 // File_checked_for_headers