Upstream tarball 20080512
[amule.git] / src / BaseClient.cpp
blob92f979c84b49df71debf10fd75d2ef6818f6429b
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 <wx/wx.h>
28 #include "updownclient.h" // Needed for CUpDownClient
30 #include <protocol/Protocols.h>
31 #include <protocol/ed2k/Client2Client/TCP.h>
32 #include <protocol/ed2k/ClientSoftware.h>
33 #include <protocol/kad/Client2Client/UDP.h>
34 #include <protocol/kad2/Constants.h>
35 #include <protocol/kad2/Client2Client/TCP.h>
36 #include <protocol/kad2/Client2Client/UDP.h>
38 #include <common/ClientVersion.h>
40 #include <tags/ClientTags.h>
42 #include <zlib.h> // Needed for inflateEnd
44 #include <common/Format.h> // Needed for CFormat
46 #include "SearchList.h" // Needed for CSearchList
47 #include "DownloadQueue.h" // Needed for CDownloadQueue
48 #include "UploadQueue.h" // Needed for CUploadQueue
49 #include "IPFilter.h" // Needed for CIPFilter
50 #include "ServerConnect.h" // Needed for CServerConnect
51 #include "ClientCredits.h" // Needed for CClientCredits
52 #include "ClientCreditsList.h" // Needed for CClientCreditsList
53 #include "Server.h" // Needed for CServer
54 #include "Preferences.h" // Needed for CPreferences
55 #include "MemFile.h" // Needed for CMemFile
56 #include "Packet.h" // Needed for CPacket
57 #include "Friend.h" // Needed for CFriend
58 #include "ClientList.h" // Needed for CClientList
59 #include "amule.h" // Needed for theApp
60 #include "PartFile.h" // Needed for CPartFile
61 #include "ClientTCPSocket.h" // Needed for CClientTCPSocket
62 #include "ListenSocket.h" // Needed for CListenSocket
63 #include "FriendList.h" // Needed for CFriendList
64 #include "Statistics.h" // Needed for theStats
65 #include "ClientUDPSocket.h"
66 #include "Logger.h"
67 #include "DataToText.h" // Needed for GetSoftName()
68 #include "GuiEvents.h" // Needed for Notify_
69 #include "ServerList.h" // For CServerList
71 #include "kademlia/kademlia/Kademlia.h"
72 #include "kademlia/kademlia/Prefs.h"
73 #include "kademlia/kademlia/Search.h"
74 #include "kademlia/kademlia/UDPFirewallTester.h"
75 #include "kademlia/routing/RoutingZone.h"
78 //#define __PACKET_DEBUG__
81 // some client testing variables
82 static wxString crash_name = wxT("[Invalid User Name]");
83 static wxString empty_name = wxT("[Empty User Name]");
85 // members of CUpDownClient
86 // which are used by down and uploading functions
89 CUpDownClient::CUpDownClient(CClientTCPSocket* sender)
91 #ifdef __DEBUG__
92 m_socket = NULL;
93 SetSocket(sender);
94 #else
95 m_socket = sender;
96 #endif
97 Init();
100 CUpDownClient::CUpDownClient(uint16 in_port, uint32 in_userid, uint32 in_serverip, uint16 in_serverport, CPartFile* in_reqfile, bool ed2kID, bool checkfriend)
102 m_socket = NULL;
103 Init();
104 m_nUserPort = in_port;
106 if(ed2kID && !IsLowID(in_userid)) {
107 SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid) );
108 } else {
109 SetUserIDHybrid( in_userid);
112 //If highID and ED2K source, incoming ID and IP are equal..
113 //If highID and Kad source, incoming IP needs swap for the IP
115 if (!HasLowID()) {
116 if (ed2kID) {
117 m_nConnectIP = in_userid;
118 } else {
119 m_nConnectIP = wxUINT32_SWAP_ALWAYS(in_userid);
121 // Will be on right endianess now
122 m_FullUserIP = Uint32toStringIP(m_nConnectIP);
125 m_dwServerIP = in_serverip;
126 m_nServerPort = in_serverport;
127 SetRequestFile( in_reqfile );
128 ReGetClientSoft();
130 if (checkfriend) {
131 if ((m_Friend = theApp->friendlist->FindFriend(CMD4Hash(), m_dwUserIP, m_nUserPort)) != NULL){
132 m_Friend->LinkClient(this);
133 } else{
134 // avoid that an unwanted client instance keeps a friend slot
135 m_bFriendSlot = false;
141 void CUpDownClient::Init()
143 m_bAddNextConnect = false;
144 credits = NULL;
145 m_byChatstate = MS_NONE;
146 m_nKadState = KS_NONE;
147 m_cShowDR = 0;
148 m_reqfile = NULL; // No file required yet
149 m_nTransferredUp = 0;
150 m_cSendblock = 0;
151 m_cAsked = 0;
152 msReceivedPrev = 0;
153 kBpsDown = 0.0;
154 fDownAvgFilter = 1.0;
155 bytesReceivedCycle = 0;
156 m_nServerPort = 0;
157 m_iFileListRequested = 0;
158 m_dwLastUpRequest = 0;
159 m_bEmuleProtocol = false;
160 m_bCompleteSource = false;
161 m_bFriendSlot = false;
162 m_bCommentDirty = false;
163 m_bReaskPending = false;
164 m_bUDPPending = false;
165 m_nUserPort = 0;
166 m_nPartCount = 0;
167 m_dwLastAskedTime = 0;
168 m_nDownloadState = DS_NONE;
169 m_dwUploadTime = 0;
170 m_nTransferredDown = 0;
171 m_nUploadState = US_NONE;
172 m_dwLastBlockReceived = 0;
173 m_bUnicodeSupport = false;
175 m_fSentOutOfPartReqs = 0;
176 m_nCurQueueSessionPayloadUp = 0;
177 m_addedPayloadQueueSession = 0;
178 m_nUpDatarate = 0;
179 m_nSumForAvgUpDataRate = 0;
181 m_nRemoteQueueRank = 0;
182 m_nOldRemoteQueueRank = 0;
183 m_dwLastSourceRequest = 0;
184 m_dwLastSourceAnswer = 0;
185 m_dwLastAskedForSources = 0;
187 m_SecureIdentState = IS_UNAVAILABLE;
188 m_dwLastSignatureIP = 0;
190 m_byInfopacketsReceived = IP_NONE;
192 m_bIsHybrid = false;
193 m_bIsML = false;
194 m_Friend = NULL;
195 m_iRating = 0;
196 m_nCurSessionUp = 0;
197 m_clientSoft=SO_UNKNOWN;
199 m_bRemoteQueueFull = false;
200 m_HasValidHash = false;
201 SetWaitStartTime();
203 m_fHashsetRequesting = 0;
204 m_fSharedDirectories = 0;
205 m_lastPartAsked = 0xffff;
206 m_nUpCompleteSourcesCount= 0;
207 m_lastRefreshedDLDisplay = 0;
208 m_bHelloAnswerPending = false;
209 m_fSentCancelTransfer = 0;
210 m_Aggressiveness = 0;
211 m_LastFileRequest = 0;
213 m_clientState = CS_NEW;
215 ClearHelloProperties();
217 m_pReqFileAICHHash = NULL;
218 m_fSupportsAICH = 0;
219 m_fAICHRequested = 0;
220 m_fSupportsLargeFiles = 0;
221 m_fExtMultiPacket = 0;
223 m_dwUserIP = 0;
224 m_nConnectIP = 0;
225 m_dwServerIP = 0;
227 m_fNeedOurPublicIP = false;
228 m_bHashsetRequested = false;
230 m_nLastBlockOffset = 0;
232 m_uploadingfile = NULL;
234 m_OSInfo_sent = false;
236 /* Kad stuff */
237 SetBuddyID(NULL);
238 m_nBuddyIP = 0;
239 m_nBuddyPort = 0;
240 m_nUserIDHybrid = 0;
242 m_nSourceFrom = SF_NONE;
244 if (m_socket) {
245 amuleIPV4Address address;
246 m_socket->GetPeer(address);
247 m_FullUserIP = address.IPAddress();
248 SetIP(StringIPtoUint32(m_FullUserIP));
249 } else {
250 SetIP(0);
253 /* Statistics */
254 m_lastClientSoft = (uint32)(-1);
255 m_lastClientVersion = 0;
257 /* Creation time (for buddies timeout) */
258 m_nCreationTime = ::GetTickCount();
260 m_MaxBlockRequests = STANDARD_BLOCKS_REQUEST; // Safe starting amount
262 m_last_block_start = 0;
263 m_lastaverage = 0;
265 SetLastBuddyPingPongTime();
266 m_fRequestsCryptLayer = 0;
267 m_fSupportsCryptLayer = 0;
268 m_fRequiresCryptLayer = 0;
269 m_fSupportsSourceEx2 = 0;
270 m_fDirectUDPCallback = 0;
271 m_dwDirectCallbackTimeout = 0;
273 m_hasbeenobfuscatinglately = false;
277 CUpDownClient::~CUpDownClient()
279 #ifdef __DEBUG__
280 if (!connection_reason.IsEmpty()) {
281 printf("Client to check for %s was deleted without connection.\n",(const char*)unicode2char(connection_reason));
283 #endif
285 if (m_lastClientSoft == SO_UNKNOWN) {
286 theStats::RemoveUnknownClient();
287 } else if (m_lastClientSoft != (uint32)(-1)) {
288 theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
291 // Indicate that we are not anymore on stats
292 m_lastClientSoft = (uint32)(-1);
295 if (IsAICHReqPending()){
296 m_fAICHRequested = FALSE;
297 CAICHHashSet::ClientAICHRequestFailed(this);
300 //theApp->clientlist->RemoveClient(this, wxT("Destructing client object"));
302 if (m_Friend) {
303 m_Friend->UnLinkClient();
304 Notify_ChatRefreshFriend(m_Friend->GetIP(), m_Friend->GetPort(), wxEmptyString);
305 m_Friend = NULL;
308 // The socket should have been removed in Safe_Delete, but it
309 // doesn't hurt to have an extra check.
310 if (m_socket) {
311 m_socket->Safe_Delete();
312 // Paranoia
313 SetSocket(NULL);
317 ClearUploadBlockRequests();
318 ClearDownloadBlockRequests();
320 DeleteContents(m_WaitingPackets_list);
322 if (m_iRating>0 || !m_strComment.IsEmpty()) {
323 m_iRating = 0;
324 m_strComment.Clear();
325 if (m_reqfile) {
326 m_reqfile->UpdateFileRatingCommentAvail();
330 // Ensure that source-counts gets updated in case
331 // of a source not on the download-queue
332 SetRequestFile( NULL );
334 SetUploadFileID(NULL);
336 if (m_pReqFileAICHHash != NULL) {
337 delete m_pReqFileAICHHash;
338 m_pReqFileAICHHash = NULL;
342 void CUpDownClient::ClearHelloProperties()
344 m_nUDPPort = 0;
345 m_byUDPVer = 0;
346 m_byDataCompVer = 0;
347 m_byEmuleVersion = 0;
348 m_bySourceExchange1Ver = 0;
349 m_byAcceptCommentVer = 0;
350 m_byExtendedRequestsVer = 0;
351 m_byCompatibleClient = 0;
352 m_nKadPort = 0;
353 m_bySupportSecIdent = 0;
354 m_bSupportsPreview = 0;
355 m_nClientVersion = 0;
356 m_fSharedDirectories = 0;
357 m_bMultiPacket = 0;
358 m_fOsInfoSupport = 0;
359 m_fValueBasedTypeTags = 0;
360 SecIdentSupRec = 0;
361 m_byKadVersion = 0;
362 m_fRequestsCryptLayer = 0;
363 m_fSupportsCryptLayer = 0;
364 m_fRequiresCryptLayer = 0;
365 m_fSupportsSourceEx2 = 0;
366 m_fDirectUDPCallback = 0;
369 bool CUpDownClient::ProcessHelloPacket(const byte* pachPacket, uint32 nSize)
371 const CMemFile data(pachPacket,nSize);
372 uint8 hashsize = data.ReadUInt8();
373 if ( 16 != hashsize ) {
375 * Hint: We can not accept other sizes here because:
376 * - the magic number is spread all over the source
377 * - the answer packet lacks the size field
379 throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
381 // eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
382 ClearHelloProperties();
384 return ProcessHelloTypePacket(data);
387 void CUpDownClient::Safe_Delete()
389 // Because we are delaying the deletion, we might end up trying to delete
390 // it twice, however, this is normal and shouldn't trigger any failures
391 if ( m_clientState == CS_DYING ) {
392 return;
395 m_clientState = CS_DYING;
397 // Close the socket to avoid any more connections and related events
398 if ( m_socket ) {
399 m_socket->Safe_Delete();
400 // Paranoia
401 SetSocket(NULL);
404 // Schedule the client for deletion if we still have the clientlist
405 if ( theApp->clientlist ) {
406 theApp->clientlist->AddToDeleteQueue( this );
407 } else {
408 delete this;
413 bool CUpDownClient::ProcessHelloAnswer(const byte* pachPacket, uint32 nSize)
415 const CMemFile data(pachPacket,nSize);
416 bool bIsMule = ProcessHelloTypePacket(data);
417 m_bHelloAnswerPending = false;
418 return bIsMule;
421 bool CUpDownClient::ProcessHelloTypePacket(const CMemFile& data)
424 m_bIsHybrid = false;
425 m_bIsML = false;
426 m_fNoViewSharedFiles = 0;
427 m_bUnicodeSupport = false;
428 uint32 dwEmuleTags = 0;
430 CMD4Hash hash = data.ReadHash();
431 SetUserHash( hash );
432 SetUserIDHybrid( data.ReadUInt32() );
433 uint16 nUserPort = data.ReadUInt16(); // hmm clientport is sent twice - why?
434 uint32 tagcount = data.ReadUInt32();
435 for (uint32 i = 0;i < tagcount; i++){
436 CTag temptag(data, true);
437 switch(temptag.GetNameID()){
438 case CT_NAME:
439 m_Username = temptag.GetStr();
440 break;
442 case CT_VERSION:
443 m_nClientVersion = temptag.GetInt();
444 break;
446 case ET_MOD_VERSION:
447 if (temptag.IsStr()) {
448 m_strModVersion = temptag.GetStr();
449 } else if (temptag.IsInt()) {
450 m_strModVersion = wxString::Format(wxT("ModID=%u"), temptag.GetInt());
451 } else {
452 m_strModVersion = wxT("ModID=<Unknown>");
455 break;
457 case CT_PORT:
458 nUserPort = temptag.GetInt();
459 break;
461 case CT_EMULE_UDPPORTS:
462 // 16 KAD Port
463 // 16 UDP Port
464 SetKadPort((temptag.GetInt() >> 16) & 0xFFFF);
465 m_nUDPPort = temptag.GetInt() & 0xFFFF;
466 dwEmuleTags |= 1;
467 #ifdef __PACKET_DEBUG__
468 printf("Hello type packet processing with eMule ports UDP=%i KAD=%i\n",m_nUDPPort,m_nKadPort);
469 #endif
470 break;
472 case CT_EMULE_BUDDYIP:
473 // 32 BUDDY IP
474 m_nBuddyIP = temptag.GetInt();
475 #ifdef __PACKET_DEBUG__
476 printf("Hello type packet processing with eMule BuddyIP=%u (%s)\n",m_nBuddyIP, (const char*)unicode2char(Uint32toStringIP(m_nBuddyIP)));
477 #endif
478 break;
480 case CT_EMULE_BUDDYUDP:
481 // 16 --Reserved for future use--
482 // 16 BUDDY Port
483 m_nBuddyPort = (uint16)temptag.GetInt();
484 #ifdef __PACKET_DEBUG__
485 printf("Hello type packet processing with eMule BuddyPort=%u\n",m_nBuddyPort);
486 #endif
487 break;
489 case CT_EMULE_MISCOPTIONS1: {
490 // 3 AICH Version (0 = not supported)
491 // 1 Unicode
492 // 4 UDP version
493 // 4 Data compression version
494 // 4 Secure Ident
495 // 4 Source Exchange
496 // 4 Ext. Requests
497 // 4 Comments
498 // 1 PeerCache supported
499 // 1 No 'View Shared Files' supported
500 // 1 MultiPacket
501 // 1 Preview
502 uint32 flags = temptag.GetInt();
503 m_fSupportsAICH = (flags >> (4*7+1)) & 0x07;
504 m_bUnicodeSupport = (flags >> 4*7) & 0x01;
505 m_byUDPVer = (flags >> 4*6) & 0x0f;
506 m_byDataCompVer = (flags >> 4*5) & 0x0f;
507 m_bySupportSecIdent = (flags >> 4*4) & 0x0f;
508 m_bySourceExchange1Ver = (flags >> 4*3) & 0x0f;
509 m_byExtendedRequestsVer = (flags >> 4*2) & 0x0f;
510 m_byAcceptCommentVer = (flags >> 4*1) & 0x0f;
511 m_fNoViewSharedFiles = (flags >> 1*2) & 0x01;
512 m_bMultiPacket = (flags >> 1*1) & 0x01;
513 m_fSupportsPreview = (flags >> 1*0) & 0x01;
514 dwEmuleTags |= 2;
515 #ifdef __PACKET_DEBUG__
516 printf("Hello type packet processing with eMule Misc Options:\n");
517 printf("m_byUDPVer = %i\n",m_byUDPVer);
518 printf("m_byDataCompVer = %i\n",m_byDataCompVer);
519 printf("m_bySupportSecIdent = %i\n",m_bySupportSecIdent);
520 printf("m_bySourceExchangeVer = %i\n",m_bySourceExchange1Ver);
521 printf("m_byExtendedRequestsVer = %i\n",m_byExtendedRequestsVer);
522 printf("m_byAcceptCommentVer = %i\n",m_byAcceptCommentVer);
523 printf("m_fNoViewSharedFiles = %i\n",m_fNoViewSharedFiles);
524 printf("m_bMultiPacket = %i\n",m_bMultiPacket);
525 printf("m_fSupportsPreview = %i\n",m_fSharedDirectories);
526 printf("That's all.\n");
527 #endif
528 SecIdentSupRec += 1;
529 break;
532 case CT_EMULE_MISCOPTIONS2:
533 // 19 Reserved
534 // 1 Direct UDP Callback supported and available
535 // 1 Supports ChatCaptchas
536 // 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
537 // 1 Requires CryptLayer
538 // 1 Requests CryptLayer
539 // 1 Supports CryptLayer
540 // 1 Reserved (ModBit)
541 // 1 Ext Multipacket (Hash+Size instead of Hash)
542 // 1 Large Files (includes support for 64bit tags)
543 // 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
544 m_fDirectUDPCallback = (temptag.GetInt() >> 12) & 0x01;
545 // 1 captcha support
546 m_fSupportsSourceEx2 = (temptag.GetInt() >> 10) & 0x01;
547 m_fRequiresCryptLayer = (temptag.GetInt() >> 9) & 0x01;
548 m_fRequestsCryptLayer = (temptag.GetInt() >> 8) & 0x01;
549 m_fSupportsCryptLayer = (temptag.GetInt() >> 7) & 0x01;
550 // reserved 1
551 m_fExtMultiPacket = (temptag.GetInt() >> 5) & 0x01;
552 m_fSupportsLargeFiles = (temptag.GetInt() >> 4) & 0x01;
553 m_byKadVersion = (temptag.GetInt() >> 0) & 0x0f;
554 dwEmuleTags |= 8;
556 m_fRequestsCryptLayer &= m_fSupportsCryptLayer;
557 m_fRequiresCryptLayer &= m_fRequestsCryptLayer;
559 #ifdef __PACKET_DEBUG__
560 printf("Hello type packet processing with eMule Misc Options 2:\n");
561 printf(" m_fDirectUDPCallback = %i\n", m_fDirectUDPCallback);
562 printf(" m_fSupportsSourceEx2 = %i\n", m_fSupportsSourceEx2);
563 printf(" m_fRequiresCryptLayer = %i\n", m_fRequiresCryptLayer);
564 printf(" m_fRequestsCryptLayer = %i\n", m_fRequestsCryptLayer);
565 printf(" m_fSupportsCryptLayer = %i\n", m_fSupportsCryptLayer);
566 printf(" m_fExtMultiPacket = %i\n", m_fExtMultiPacket);
567 printf(" m_fSupportsLargeFiles = %i\n", m_fSupportsLargeFiles);
568 printf(" KadVersion = %u\n", m_byKadVersion);
569 printf("That's all.\n");
570 #endif
571 break;
573 // Special tag for Compat. Clients Misc options.
574 case CT_EMULECOMPAT_OPTIONS:
575 // 1 Operative System Info
576 // 1 Value-based-type int tags (experimental!)
577 m_fValueBasedTypeTags = (temptag.GetInt() >> 1*1) & 0x01;
578 m_fOsInfoSupport = (temptag.GetInt() >> 1*0) & 0x01;
579 break;
581 case CT_EMULE_VERSION:
582 // 8 Compatible Client ID
583 // 7 Mjr Version (Doesn't really matter..)
584 // 7 Min Version (Only need 0-99)
585 // 3 Upd Version (Only need 0-5)
586 // 7 Bld Version (Only need 0-99)
587 m_byCompatibleClient = (temptag.GetInt() >> 24);
588 m_nClientVersion = temptag.GetInt() & 0x00ffffff;
589 m_byEmuleVersion = 0x99;
590 m_fSharedDirectories = 1;
591 dwEmuleTags |= 4;
592 break;
596 m_nUserPort = nUserPort;
597 m_dwServerIP = data.ReadUInt32();
598 m_nServerPort = data.ReadUInt16();
599 // Hybrid now has an extra uint32.. What is it for?
600 // Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
601 if ( data.GetLength() - data.GetPosition() == sizeof(uint32) ) {
602 uint32 test = data.ReadUInt32();
603 /*if (test == 'KDLM') below kdlm is converted to ascii values.
604 This fixes a warning with gcc 3.4.
605 K=4b D=44 L=4c M=4d
607 if (test == 0x4b444c4d) { //if it's == "KDLM"
608 m_bIsML=true;
609 } else{
610 m_bIsHybrid = true;
611 m_fSharedDirectories = 1;
615 if (m_socket) {
616 amuleIPV4Address address;
617 m_socket->GetPeer(address);
618 m_FullUserIP = address.IPAddress();
619 SetIP(StringIPtoUint32(m_FullUserIP));
620 } else {
621 throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
624 if (thePrefs::AddServersFromClient()) {
625 CServer* addsrv = new CServer(m_nServerPort, Uint32toStringIP(m_dwServerIP));
626 addsrv->SetListName(addsrv->GetAddress());
627 if (!theApp->AddServer(addsrv)) {
628 delete addsrv;
632 //(a)If this is a highID user, store the ID in the Hybrid format.
633 //(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
634 //(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
635 //because they will send a ID that is the same as their IP..
636 if(!HasLowID() || m_nUserIDHybrid == 0 || m_nUserIDHybrid == m_dwUserIP ) {
637 SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP));
640 // get client credits
641 CClientCredits* pFoundCredits = theApp->clientcredits->GetCredit(m_UserHash);
642 if (credits == NULL){
643 credits = pFoundCredits;
644 if (!theApp->clientlist->ComparePriorUserhash(m_dwUserIP, m_nUserPort, pFoundCredits)){
645 AddDebugLogLineM( false, logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
646 Ban();
648 } else if (credits != pFoundCredits){
649 // userhash change ok, however two hours "waittime" before it can be used
650 credits = pFoundCredits;
651 AddDebugLogLineM( false, logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
652 Ban();
655 if ((m_Friend = theApp->friendlist->FindFriend(m_UserHash, m_dwUserIP, m_nUserPort)) != NULL){
656 m_Friend->LinkClient(this);
657 } else{
658 // avoid that an unwanted client instance keeps a friend slot
659 SetFriendSlot(false);
663 ReGetClientSoft();
665 m_byInfopacketsReceived |= IP_EDONKEYPROTPACK;
667 // check if at least CT_EMULEVERSION was received, all other tags are optional
668 bool bIsMule = (dwEmuleTags & 0x04) == 0x04;
669 if (bIsMule) {
670 m_bEmuleProtocol = true;
671 m_byInfopacketsReceived |= IP_EMULEPROTPACK;
674 if( GetKadPort() ) {
675 Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort(), GetKadVersion() > 1);
678 return bIsMule;
682 bool CUpDownClient::SendHelloPacket() {
684 if (m_socket == NULL){
685 wxASSERT(0);
686 return true;
689 // if IP is filtered, dont greet him but disconnect...
690 amuleIPV4Address address;
691 m_socket->GetPeer(address);
692 if ( theApp->ipfilter->IsFiltered(StringIPtoUint32(address.IPAddress()))) {
693 if (Disconnected(wxT("IPFilter"))) {
694 Safe_Delete();
695 return false;
697 return true;
700 CMemFile data(128);
701 data.WriteUInt8(16); // size of userhash
702 SendHelloTypePacket(&data);
704 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLO);
705 theStats::AddUpOverheadOther(packet->GetPacketSize());
706 SendPacket(packet,true);
707 m_bHelloAnswerPending = true;
708 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
709 return true;
712 void CUpDownClient::SendMuleInfoPacket(bool bAnswer, bool OSInfo) {
714 if (m_socket == NULL){
715 wxASSERT(0);
716 return;
719 CPacket* packet = NULL;
720 CMemFile data;
722 data.WriteUInt8(CURRENT_VERSION_SHORT);
724 if (OSInfo) {
726 // Special MuleInfo packet for clients supporting it.
727 // This means aMule >= 2.0.0 and Hydranode
729 // Violently mark it as special Mule Info packet
730 // Sending this makes non-supporting-osinfo clients to refuse to read this
731 // packet. Anyway, this packet should NEVER get to non-supporting clients.
733 data.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
735 data.WriteUInt32(1); // One Tag (OS_INFO)
737 CTagString tag1(ET_OS_INFO,theApp->GetOSType());
738 tag1.WriteTagToFile(&data);
740 m_OSInfo_sent = true; // So we don't send it again
742 } else {
744 // Normal MuleInfo packet
746 // Kry - There's no point on upgrading to VBT tags here
747 // as no client supporting it uses mule info packet.
749 data.WriteUInt8(EMULE_PROTOCOL);
751 // Tag number
752 data.WriteUInt32(9);
754 CTagInt32 tag1(ET_COMPRESSION,1);
755 tag1.WriteTagToFile(&data);
756 CTagInt32 tag2(ET_UDPVER,4);
757 tag2.WriteTagToFile(&data);
758 CTagInt32 tag3(ET_UDPPORT, thePrefs::GetEffectiveUDPPort());
759 tag3.WriteTagToFile(&data);
760 CTagInt32 tag4(ET_SOURCEEXCHANGE,3);
761 tag4.WriteTagToFile(&data);
762 CTagInt32 tag5(ET_COMMENTS,1);
763 tag5.WriteTagToFile(&data);
764 CTagInt32 tag6(ET_EXTENDEDREQUEST,2);
765 tag6.WriteTagToFile(&data);
767 uint32 dwTagValue = (theApp->CryptoAvailable() ? 3 : 0);
768 // Kry - Needs the preview code from eMule
770 // set 'Preview supported' only if 'View Shared Files' allowed
771 if (thePrefs::CanSeeShares() != vsfaNobody) {
772 dwTagValue |= 128;
775 CTagInt32 tag7(ET_FEATURES, dwTagValue);
776 tag7.WriteTagToFile(&data);
778 CTagInt32 tag8(ET_COMPATIBLECLIENT,SO_AMULE);
779 tag8.WriteTagToFile(&data);
781 // Support for tag ET_MOD_VERSION
782 wxString mod_name(MOD_VERSION_LONG);
783 CTagString tag9(ET_MOD_VERSION, mod_name);
784 tag9.WriteTagToFile(&data);
785 // Maella end
789 packet = new CPacket(data, OP_EMULEPROT, (bAnswer ? OP_EMULEINFOANSWER : OP_EMULEINFO));
791 if (m_socket) {
792 theStats::AddUpOverheadOther(packet->GetPacketSize());
793 SendPacket(packet,true,true);
795 if (!bAnswer) {
796 if (!OSInfo) {
797 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
798 } else {
799 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
801 } else {
802 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
807 bool CUpDownClient::ProcessMuleInfoPacket(const byte* pachPacket, uint32 nSize)
809 uint8 protocol_version;
811 const CMemFile data(pachPacket,nSize);
813 // The version number part of this packet will soon be useless since
814 // it is only able to go to v.99. Why the version is a uint8 and why
815 // it was not done as a tag like the eDonkey hello packet is not known.
816 // Therefore, sooner or later, we are going to have to switch over to
817 // using the eDonkey hello packet to set the version. No sense making
818 // a third value sent for versions.
819 uint8 mule_version = data.ReadUInt8();
820 protocol_version = data.ReadUInt8();
821 uint32 tagcount = data.ReadUInt32();
822 if (protocol_version == 0xFF) {
823 // OS Info supporting clients sending a recycled Mule info packet
824 for (uint32 i = 0;i < tagcount; i++){
825 CTag temptag(data, true);
826 switch(temptag.GetNameID()){
827 case ET_OS_INFO:
828 // Special tag, only supporting clients (aMule/Hydranode)
829 // It was recycled from a mod's tag, so if the other side
830 // is not supporting OS Info, we're seriously fucked up :)
831 m_sClientOSInfo = temptag.GetStr();
833 // If we didn't send our OSInfo to this client, just send it
834 if (!m_OSInfo_sent) {
835 SendMuleInfoPacket(false,true);
838 UpdateStats();
840 break;
842 // Your ad... er... I mean TAG, here
844 default:
845 break;
848 } else {
849 // Old eMule sending tags
850 m_byCompatibleClient = 0;
851 m_byEmuleVersion = mule_version;
853 if( m_byEmuleVersion == 0x2B ) {
854 m_byEmuleVersion = 0x22;
857 if (!(m_bEmuleProtocol = (protocol_version == EMULE_PROTOCOL))) {
858 return false;
861 for (uint32 i = 0;i < tagcount; i++){
862 CTag temptag(data, false);
863 switch(temptag.GetNameID()){
864 case ET_COMPRESSION:
865 // Bits 31- 8: 0 - reserved
866 // Bits 7- 0: data compression version
867 m_byDataCompVer = temptag.GetInt();
868 break;
870 case ET_UDPPORT:
871 // Bits 31-16: 0 - reserved
872 // Bits 15- 0: UDP port
873 m_nUDPPort = temptag.GetInt();
874 break;
876 case ET_UDPVER:
877 // Bits 31- 8: 0 - reserved
878 // Bits 7- 0: UDP protocol version
879 m_byUDPVer = temptag.GetInt();
880 break;
882 case ET_SOURCEEXCHANGE:
883 // Bits 31- 8: 0 - reserved
884 // Bits 7- 0: source exchange protocol version
885 m_bySourceExchange1Ver = temptag.GetInt();
886 break;
888 case ET_COMMENTS:
889 // Bits 31- 8: 0 - reserved
890 // Bits 7- 0: comments version
891 m_byAcceptCommentVer = temptag.GetInt();
892 break;
894 case ET_EXTENDEDREQUEST:
895 // Bits 31- 8: 0 - reserved
896 // Bits 7- 0: extended requests version
897 m_byExtendedRequestsVer = temptag.GetInt();
898 break;
900 case ET_COMPATIBLECLIENT:
901 // Bits 31- 8: 0 - reserved
902 // Bits 7- 0: compatible client ID
903 m_byCompatibleClient = temptag.GetInt();
904 break;
906 case ET_FEATURES:
907 // Bits 31- 8: 0 - reserved
908 // Bit 7: Preview
909 // Bit 6- 0: secure identification
910 m_bySupportSecIdent = temptag.GetInt() & 3;
911 m_bSupportsPreview = (temptag.GetInt() & 128) > 0;
912 SecIdentSupRec += 2;
913 break;
915 case ET_MOD_VERSION:
916 if (temptag.IsStr()) {
917 m_strModVersion = temptag.GetStr();
918 } else if (temptag.IsInt()) {
919 m_strModVersion = wxString::Format(wxT("ModID=%u"), temptag.GetInt());
920 } else {
921 m_strModVersion = wxT("ModID=<Unknown>");
924 break;
926 default:
927 AddDebugLogLineM( false, logPacketErrors,
928 CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
929 % temptag.GetFullInfo()
930 % GetClientFullInfo()
933 break;
937 if( m_byDataCompVer == 0 ){
938 m_bySourceExchange1Ver = 0;
939 m_byExtendedRequestsVer = 0;
940 m_byAcceptCommentVer = 0;
941 m_nUDPPort = 0;
944 //implicitly supported options by older clients
945 //in the future do not use version to guess about new features
946 if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x22) {
947 m_byUDPVer = 1;
950 if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x21) {
951 m_bySourceExchange1Ver = 1;
954 if(m_byEmuleVersion == 0x24) {
955 m_byAcceptCommentVer = 1;
958 // Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
959 // the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
960 // directory which has a trailing backslash.
961 if(m_byEmuleVersion >= 0x28 && !m_bIsML) {// MLdonkey currently does not support shared directories
962 m_fSharedDirectories = 1;
965 ReGetClientSoft();
967 m_byInfopacketsReceived |= IP_EMULEPROTPACK;
970 return (protocol_version == 0xFF); // This was a OS_Info?
974 void CUpDownClient::SendHelloAnswer()
976 if (m_socket == NULL){
977 wxASSERT(0);
978 return;
981 CMemFile data(128);
982 SendHelloTypePacket(&data);
983 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLOANSWER);
984 theStats::AddUpOverheadOther(packet->GetPacketSize());
985 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
986 SendPacket(packet,true);
990 void CUpDownClient::SendHelloTypePacket(CMemFile* data)
992 data->WriteHash(thePrefs::GetUserHash());
993 data->WriteUInt32(theApp->GetID());
994 data->WriteUInt16(thePrefs::GetPort());
996 uint32 tagcount = 6;
998 if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
999 tagcount += 2;
1001 tagcount ++; // eMule misc flags 2 (kad version)
1003 #ifdef __SVN__
1004 // Kry - This is the tagcount!!! Be sure to update it!!
1005 // Last update: CT_EMULECOMPAT_OPTIONS included
1006 data->WriteUInt32(tagcount + 1);
1007 #else
1008 data->WriteUInt32(tagcount); // NO MOD_VERSION
1009 #endif
1012 CTagString tagname(CT_NAME,thePrefs::GetUserNick());
1013 tagname.WriteTagToFile(data, utf8strRaw);
1015 CTagVarInt tagversion(CT_VERSION, EDONKEYVERSION, GetVBTTags() ? 0 : 32);
1016 tagversion.WriteTagToFile(data);
1017 // eMule UDP Ports
1019 uint32 kadUDPPort = 0;
1021 if(Kademlia::CKademlia::IsConnected()) {
1022 if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
1023 kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
1024 } else {
1025 kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
1029 CTagVarInt tagUdpPorts(CT_EMULE_UDPPORTS, (kadUDPPort << 16) | ((uint32)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
1030 tagUdpPorts.WriteTagToFile(data);
1032 if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
1033 CTagVarInt tagBuddyIP(CT_EMULE_BUDDYIP, theApp->clientlist->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
1034 tagBuddyIP.WriteTagToFile(data);
1036 CTagVarInt tagBuddyPort(CT_EMULE_BUDDYUDP,
1037 // ( RESERVED )
1038 ((uint32)theApp->clientlist->GetBuddy()->GetUDPPort() )
1039 , GetVBTTags() ? 0 : 32);
1040 tagBuddyPort.WriteTagToFile(data);
1043 // aMule Version
1044 CTagVarInt tagMuleVersion(CT_EMULE_VERSION,
1045 (SO_AMULE << 24) |
1046 make_full_ed2k_version(VERSION_MJR, VERSION_MIN, VERSION_UPDATE)
1047 // | (RESERVED )
1048 , GetVBTTags() ? 0 : 32);
1049 tagMuleVersion.WriteTagToFile(data);
1052 // eMule Misc. Options #1
1053 const uint32 uUdpVer = 4;
1054 const uint32 uDataCompVer = 1;
1055 const uint32 uSupportSecIdent = theApp->CryptoAvailable() ? 3 : 0;
1056 const uint32 uSourceExchangeVer = 3;
1057 const uint32 uExtendedRequestsVer = 2;
1058 const uint32 uAcceptCommentVer = 1;
1059 const uint32 uNoViewSharedFiles = (thePrefs::CanSeeShares() == vsfaNobody) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
1060 const uint32 uMultiPacket = 1;
1061 const uint32 uSupportPreview = 0; // No network preview at all.
1062 const uint32 uPeerCache = 0; // No peercache for aMule, baby
1063 const uint32 uUnicodeSupport = 1;
1064 const uint32 nAICHVer = 1; // AICH is ENABLED right now.
1066 CTagVarInt tagMisOptions(CT_EMULE_MISCOPTIONS1,
1067 (nAICHVer << ((4*7)+1)) |
1068 (uUnicodeSupport << 4*7) |
1069 (uUdpVer << 4*6) |
1070 (uDataCompVer << 4*5) |
1071 (uSupportSecIdent << 4*4) |
1072 (uSourceExchangeVer << 4*3) |
1073 (uExtendedRequestsVer << 4*2) |
1074 (uAcceptCommentVer << 4*1) |
1075 (uPeerCache << 1*3) |
1076 (uNoViewSharedFiles << 1*2) |
1077 (uMultiPacket << 1*1) |
1078 (uSupportPreview << 1*0)
1079 , GetVBTTags() ? 0 : 32);
1080 tagMisOptions.WriteTagToFile(data);
1082 // eMule Misc. Options #2
1083 const uint32 uKadVersion = KADEMLIA_VERSION;
1084 const uint32 uSupportLargeFiles = 1;
1085 const uint32 uExtMultiPacket = 1;
1086 const uint32 uReserved = 0; // mod bit
1087 const uint32 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
1088 const uint32 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
1089 const uint32 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
1090 const uint32 uSupportsSourceEx2 = 1;
1091 // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
1092 const uint32 uDirectUDPCallback = (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
1093 && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
1095 CTagVarInt tagMisOptions2(CT_EMULE_MISCOPTIONS2,
1096 // (RESERVED )
1097 (uDirectUDPCallback << 12) |
1098 // (uSupportsCaptcha << 11) | // No captcha support in aMule
1099 (uSupportsSourceEx2 << 10) |
1100 (uRequiresCryptLayer << 9) |
1101 (uRequestsCryptLayer << 8) |
1102 (uSupportsCryptLayer << 7) |
1103 (uReserved << 6) |
1104 (uExtMultiPacket << 5) |
1105 (uSupportLargeFiles << 4) |
1106 (uKadVersion << 0)
1107 , GetVBTTags() ? 0 : 32 );
1108 tagMisOptions2.WriteTagToFile(data);
1110 const uint32 nOSInfoSupport = 1; // We support OS_INFO
1111 const uint32 nValueBasedTypeTags = 0; // Experimental, disabled
1113 CTagVarInt tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS,
1114 (nValueBasedTypeTags << 1*1) |
1115 (nOSInfoSupport << 1*0)
1116 , GetVBTTags() ? 0 : 32);
1118 tagMisCompatOptions.WriteTagToFile(data);
1120 #ifdef __SVN__
1121 wxString mod_name(MOD_VERSION_LONG);
1122 CTagString tagModName(ET_MOD_VERSION, mod_name);
1123 tagModName.WriteTagToFile(data);
1124 #endif
1126 uint32 dwIP = 0;
1127 uint16 nPort = 0;
1128 if (theApp->IsConnectedED2K()) {
1129 dwIP = theApp->serverconnect->GetCurrentServer()->GetIP();
1130 nPort = theApp->serverconnect->GetCurrentServer()->GetPort();
1132 data->WriteUInt32(dwIP);
1133 data->WriteUInt16(nPort);
1137 void CUpDownClient::ProcessMuleCommentPacket(const byte* pachPacket, uint32 nSize)
1139 if (!m_reqfile) {
1140 throw CInvalidPacket(wxT("Comment packet for unknown file"));
1143 if (!m_reqfile->IsPartFile()) {
1144 throw CInvalidPacket(wxT("Comment packet for completed file"));
1147 const CMemFile data(pachPacket, nSize);
1149 uint8 rating = data.ReadUInt8();
1150 if (rating > 5) {
1151 AddDebugLogLineM( false, logClient, wxString(wxT("Invalid Rating for file '")) << m_clientFilename << wxT("' received: ") << rating);
1152 m_iRating = 0;
1153 } else {
1154 m_iRating = rating;
1155 AddDebugLogLineM( false, logClient, wxString(wxT("Rating for file '")) << m_clientFilename << wxT("' received: ") << m_iRating);
1158 // The comment is unicoded, with a uin32 len and safe read
1159 // (won't break if string size is < than advertised len)
1160 // Truncated to MAXFILECOMMENTLEN size
1161 m_strComment = data.ReadString((GetUnicodeSupport() != utf8strNone), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN);
1163 AddDebugLogLineM( false, logClient, wxString(wxT("Description for file '")) << m_clientFilename << wxT("' received: ") << m_strComment);
1165 // Update file rating
1166 m_reqfile->UpdateFileRatingCommentAvail();
1170 void CUpDownClient::ClearDownloadBlockRequests()
1173 std::list<Requested_Block_Struct*>::iterator it = m_DownloadBlocks_list.begin();
1174 for (; it != m_DownloadBlocks_list.end(); ++it) {
1175 Requested_Block_Struct* cur_block = *it;
1177 if (m_reqfile){
1178 m_reqfile->RemoveBlockFromList(cur_block->StartOffset, cur_block->EndOffset);
1181 delete cur_block;
1184 m_DownloadBlocks_list.clear();
1188 std::list<Pending_Block_Struct*>::iterator it = m_PendingBlocks_list.begin();
1189 for (; it != m_PendingBlocks_list.end(); ++it) {
1190 Pending_Block_Struct* pending = *it;
1192 if (m_reqfile) {
1193 m_reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset);
1196 delete pending->block;
1197 // Not always allocated
1198 if (pending->zStream){
1199 inflateEnd(pending->zStream);
1200 delete pending->zStream;
1203 delete pending;
1206 m_PendingBlocks_list.clear();
1211 bool CUpDownClient::Disconnected(const wxString& strReason, bool bFromSocket)
1213 //wxASSERT(theApp->clientlist->IsValidClient(this));
1215 // was this a direct callback?
1216 if (m_dwDirectCallbackTimeout != 0) {
1217 theApp->clientlist->RemoveDirectCallback(this);
1218 m_dwDirectCallbackTimeout = 0;
1219 AddDebugLogLineM(false, logClient, wxT("Direct callback failed to client ") + GetUserHash().Encode());
1222 if (GetKadState() == KS_QUEUED_FWCHECK_UDP || GetKadState() == KS_CONNECTING_FWCHECK_UDP) {
1223 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
1224 } else if (GetKadState() == KS_FWCHECK_UDP) {
1225 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
1226 // } else if (GetKadState() == KS_CONNECTED_BUDDY) {
1227 // AddDebugLogLineM(false, logClient, wxT("Buddy client disconnected - ") + strReason);
1230 //If this is a KAD client object, just delete it!
1231 SetKadState(KS_NONE);
1233 if (GetUploadState() == US_UPLOADING) {
1234 theApp->uploadqueue->RemoveFromUploadQueue(this);
1237 if (GetDownloadState() == DS_DOWNLOADING) {
1238 SetDownloadState(DS_ONQUEUE);
1239 } else{
1240 // ensure that all possible block requests are removed from the partfile
1241 ClearDownloadBlockRequests();
1243 if ( GetDownloadState() == DS_CONNECTED ){
1244 theApp->clientlist->AddDeadSource(this);
1245 theApp->downloadqueue->RemoveSource(this);
1249 // we had still an AICH request pending, handle it
1250 if (IsAICHReqPending()){
1251 m_fAICHRequested = FALSE;
1252 CAICHHashSet::ClientAICHRequestFailed(this);
1255 // The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
1256 // after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
1257 // is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
1258 if (((GetDownloadState() == DS_REQHASHSET) || m_fHashsetRequesting) && (m_reqfile)) {
1259 m_reqfile->SetHashSetNeeded(true);
1262 //check if this client is needed in any way, if not delete it
1263 bool bDelete = true;
1264 switch(m_nUploadState){
1265 case US_ONUPLOADQUEUE:
1266 bDelete = false;
1267 break;
1269 switch(m_nDownloadState){
1270 case DS_ONQUEUE:
1271 case DS_TOOMANYCONNS:
1272 case DS_NONEEDEDPARTS:
1273 case DS_LOWTOLOWIP:
1274 bDelete = false;
1277 switch(m_nUploadState){
1278 case US_CONNECTING:
1279 case US_WAITCALLBACK:
1280 case US_ERROR:
1281 theApp->clientlist->AddDeadSource(this);
1282 bDelete = true;
1284 switch(m_nDownloadState){
1285 case DS_CONNECTING:
1286 case DS_WAITCALLBACK:
1287 case DS_ERROR:
1288 theApp->clientlist->AddDeadSource(this);
1289 bDelete = true;
1293 if (GetChatState() != MS_NONE){
1294 bDelete = false;
1295 m_pendingMessage.Clear();
1296 Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString);
1299 if (!bFromSocket && m_socket){
1300 wxASSERT (theApp->listensocket->IsValidSocket(m_socket));
1301 m_socket->Safe_Delete();
1304 SetSocket(NULL);
1306 if (m_iFileListRequested){
1307 AddLogLineM( false, CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
1308 m_iFileListRequested = 0;
1311 Notify_ClientCtrlRefreshClient( this );
1313 if (bDelete) {
1314 if (m_Friend) {
1315 // Remove the friend linkage
1316 Notify_ChatRefreshFriend(m_Friend->GetIP(), m_Friend->GetPort(), wxEmptyString);
1318 AddDebugLogLineM( false, logClient, wxString() <<
1319 wxT("--- Deleted client \"") << GetClientFullInfo() <<
1320 wxT("\"; Reason was ") << strReason );
1321 } else {
1322 AddDebugLogLineM( false, logClient, wxString() <<
1323 wxT("--- Disconnected client \"") << GetClientFullInfo() <<
1324 wxT("\"; Reason was ") << strReason );
1325 m_fHashsetRequesting = 0;
1326 SetSentCancelTransfer(0);
1327 m_bHelloAnswerPending = false;
1328 m_fSentOutOfPartReqs = 0;
1331 return bDelete;
1334 //Returned bool is not if the TryToConnect is successful or not..
1335 //false means the client was deleted!
1336 //true means the client was not deleted!
1337 bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon)
1339 // Kad reviewed
1340 if (theApp->listensocket->TooManySockets() && !bIgnoreMaxCon ) {
1341 if (!(m_socket && m_socket->IsConnected())) {
1342 if(Disconnected(wxT("Too many connections"))) {
1343 Safe_Delete();
1344 return false;
1346 return true;
1350 // Do not try to connect to source which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
1351 if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
1352 if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
1353 Safe_Delete();
1354 return false;
1355 } else {
1356 return true;
1360 // Ipfilter check
1361 uint32 uClientIP = GetIP();
1362 if (uClientIP == 0 && !HasLowID()) {
1363 uClientIP = wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid);
1366 if (uClientIP) {
1367 // Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
1368 // we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
1369 if (theApp->ipfilter->IsFiltered(uClientIP)) {
1370 AddDebugLogLineM(false, logIPFilter, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP % Uint32toStringIP(uClientIP));
1371 if (Disconnected(wxT("IPFilter"))) {
1372 Safe_Delete();
1373 return false;
1374 } else {
1375 return true;
1379 // for safety: check again whether that IP is banned
1380 if (theApp->clientlist->IsBannedClient(uClientIP)) {
1381 AddDebugLogLineM(false, logClient, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP));
1382 if (Disconnected(wxT("Banned IP"))) {
1383 Safe_Delete();
1384 return false;
1386 return true;
1390 if (GetKadState() == KS_QUEUED_FWCHECK) {
1391 SetKadState(KS_CONNECTING_FWCHECK);
1392 } else if (GetKadState() == KS_QUEUED_FWCHECK_UDP) {
1393 SetKadState(KS_CONNECTING_FWCHECK_UDP);
1396 if ( HasLowID() ) {
1397 if (!theApp->DoCallback(this)) {
1398 //We cannot do a callback!
1399 if (GetDownloadState() == DS_CONNECTING) {
1400 SetDownloadState(DS_LOWTOLOWIP);
1401 } else if (GetDownloadState() == DS_REQHASHSET) {
1402 SetDownloadState(DS_ONQUEUE);
1403 m_reqfile->SetHashSetNeeded(true);
1405 if (GetUploadState() == US_CONNECTING) {
1406 if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
1407 Safe_Delete();
1408 return false;
1411 return true;
1414 //We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
1415 //If ANYTHING changes with the "if(!theApp->DoCallback(this))" above that will let you fall through
1416 //with the condition that the source is firewalled and we are firewalled, we must
1417 //recheck it before the this check..
1418 if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp->serverconnect->IsLocalServer(GetServerIP(), GetServerPort())
1419 && !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
1420 //This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
1421 if( Kademlia::CKademlia::IsConnected() ) {
1422 //We are connect to Kad
1423 if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
1424 //There are too many source lookups already or we are already searching this key.
1425 SetDownloadState(DS_TOOMANYCONNSKAD);
1426 return true;
1432 if (!m_socket || !m_socket->IsConnected()) {
1433 if (m_socket) {
1434 m_socket->Safe_Delete();
1436 m_socket = new CClientTCPSocket(this, thePrefs::GetProxyData());
1437 } else {
1438 ConnectionEstablished();
1439 return true;
1443 if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
1444 // a direct callback is possible - since no other parties are involved and only one additional packet overhead
1445 // is used we basically handle it like a normal connection try, no restrictions apply
1446 // we already check above with !theApp->DoCallback(this) if any callback is possible at all
1447 m_dwDirectCallbackTimeout = ::GetTickCount() + SEC2MS(45);
1448 theApp->clientlist->AddDirectCallbackClient(this);
1449 // TODO LOGREMOVE
1450 AddDebugLogLineM(false, logClient, wxString::Format(wxT("Direct Callback on port %u to client "), GetKadPort()) + GetUserHash().Encode());
1452 CMemFile data;
1453 data.WriteUInt16(thePrefs::GetPort()); // needs to know our port
1454 data.WriteHash(thePrefs::GetUserHash()); // and userhash
1455 // our connection settings
1456 data.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
1457 AddDebugLogLineM(false, logClientUDP, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
1458 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_DIRECTCALLBACKREQ);
1459 theStats::AddUpOverheadOther(packet->GetPacketSize());
1460 theApp->clientudp->SendPacket(packet, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
1461 } else if (HasLowID()) { // LOWID
1462 if (GetDownloadState() == DS_CONNECTING) {
1463 SetDownloadState(DS_WAITCALLBACK);
1465 if (GetUploadState() == US_CONNECTING) {
1466 if(Disconnected(wxT("LowID and US_CONNECTING"))) {
1467 Safe_Delete();
1468 return false;
1470 return true;
1473 if (theApp->serverconnect->IsLocalServer(m_dwServerIP,m_nServerPort)) {
1474 CMemFile data;
1475 // AFAICS, this id must be reversed to be sent to clients
1476 // But if I reverse it, we do a serve violation ;)
1477 data.WriteUInt32(m_nUserIDHybrid);
1478 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_CALLBACKREQUEST);
1479 theStats::AddUpOverheadServer(packet->GetPacketSize());
1480 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
1481 theApp->serverconnect->SendPacket(packet);
1482 SetDownloadState(DS_WAITCALLBACK);
1483 } else {
1484 if (GetUploadState() == US_NONE && (!GetRemoteQueueRank() || m_bReaskPending)) {
1486 if( !HasValidBuddyID() ) {
1487 theApp->downloadqueue->RemoveSource(this);
1488 if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
1489 Safe_Delete();
1490 return false;
1492 return true;
1495 if( !Kademlia::CKademlia::IsConnected() ) {
1496 //We are not connected to Kad and this is a Kad Firewalled source..
1497 theApp->downloadqueue->RemoveSource(this);
1498 if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
1499 Safe_Delete();
1500 return false;
1502 return true;
1505 if( GetDownloadState() == DS_WAITCALLBACK ) {
1506 if( GetBuddyIP() && GetBuddyPort()) {
1507 CMemFile bio(34);
1508 bio.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
1509 bio.WriteUInt128(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
1510 bio.WriteUInt16(thePrefs::GetPort());
1511 CPacket* packet = new CPacket(bio, OP_KADEMLIAHEADER, KADEMLIA_CALLBACK_REQ);
1512 // eMule FIXME: We dont know which kadversion the buddy has, so we need to send unencrypted
1513 theApp->clientudp->SendPacket(packet, GetBuddyIP(), GetBuddyPort(), false, NULL, true, 0);
1514 AddDebugLogLineM(false,logLocalClient, wxString::Format(wxT("KADEMLIA_CALLBACK_REQ (%i) to"),packet->GetPacketSize()) + GetFullIP());
1515 theStats::AddUpOverheadKad(packet->GetRealPacketSize());
1516 SetDownloadState(DS_WAITCALLBACKKAD);
1517 } else {
1518 printf("Searching buddy for lowid connection\n");
1519 //Create search to find buddy.
1520 Kademlia::CSearch *findSource = new Kademlia::CSearch;
1521 findSource->SetSearchTypes(Kademlia::CSearch::FINDSOURCE);
1522 findSource->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
1523 findSource->AddFileID(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
1524 if(Kademlia::CSearchManager::StartSearch(findSource)) {
1525 //Started lookup..
1526 SetDownloadState(DS_WAITCALLBACKKAD);
1527 } else {
1528 //This should never happen..
1529 wxASSERT(0);
1533 } else {
1534 if (GetDownloadState() == DS_WAITCALLBACK) {
1535 m_bReaskPending = true;
1536 SetDownloadState(DS_ONQUEUE);
1540 } else { // HIGHID
1541 if (!Connect()) {
1542 return false;
1545 return true;
1548 bool CUpDownClient::Connect()
1550 m_hasbeenobfuscatinglately = false;
1552 if (!m_socket->IsOk()) {
1553 // Enable or disable crypting based on our and the remote clients preference
1554 if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
1555 // printf("Set connection encryption for socket\n");
1556 //DebugLog(_T("Enabling CryptLayer on outgoing connection to client %s"), DbgGetClientInfo()); // to be removed later
1557 m_socket->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
1558 } else {
1559 m_socket->SetConnectionEncryption(false, NULL, false);
1561 amuleIPV4Address tmp;
1562 tmp.Hostname(GetConnectIP());
1563 tmp.Service(GetUserPort());
1564 AddDebugLogLineM(false, logClient, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
1565 m_socket->Connect(tmp, false);
1566 // We should send hello packets AFTER connecting!
1567 // so I moved it to OnConnect
1568 return true;
1569 } else {
1570 return false;
1574 void CUpDownClient::ConnectionEstablished()
1577 /* Kry - First thing, check if this client was just used to retrieve
1578 info. That's some debug thing for myself... check connection_reason
1579 definition */
1581 m_hasbeenobfuscatinglately = (m_socket && m_socket->IsConnected() && m_socket->IsObfusicating());
1583 #ifdef __DEBUG__
1584 if (!connection_reason.IsEmpty()) {
1585 printf("Got client info checking for %s: %s\nDisconnecting and deleting.\n",(const char*)unicode2char(connection_reason),(const char*)unicode2char(GetClientFullInfo()));
1586 connection_reason.Clear(); // So we don't re-printf on destructor.
1587 Safe_Delete();
1588 return;
1590 #endif
1592 // Check if we should use this client to retrieve our public IP
1593 // Ignore local ip on GetPublicIP (could be wrong)
1594 if (theApp->GetPublicIP(true) == 0 && theApp->IsConnectedED2K()) {
1595 SendPublicIPRequest();
1598 // was this a direct callback?
1599 if (m_dwDirectCallbackTimeout != 0){
1600 theApp->clientlist->RemoveDirectCallback(this);
1601 m_dwDirectCallbackTimeout = 0;
1602 // TODO LOGREMOVE
1603 AddDebugLogLineM(false, logClient, wxT("Direct Callback succeeded, connection established to ") + GetUserHash().Encode());
1606 switch (GetKadState()) {
1607 case KS_CONNECTING_FWCHECK:
1608 SetKadState(KS_CONNECTED_FWCHECK);
1609 break;
1610 case KS_CONNECTING_BUDDY:
1611 case KS_INCOMING_BUDDY:
1612 SetKadState(KS_CONNECTED_BUDDY);
1613 break;
1614 case KS_CONNECTING_FWCHECK_UDP:
1615 SetKadState(KS_FWCHECK_UDP);
1616 SendFirewallCheckUDPRequest();
1617 break;
1618 default:
1619 break;
1622 // ok we have a connection, lets see if we want anything from this client
1623 if (GetChatState() == MS_CONNECTING) {
1624 SetChatState( MS_CHATTING );
1627 if (GetChatState() == MS_CHATTING) {
1628 bool result = true;
1629 if (!m_pendingMessage.IsEmpty()) {
1630 result = SendMessage(m_pendingMessage);
1632 Notify_ChatConnResult(result,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage);
1633 m_pendingMessage.Clear();
1636 switch(GetDownloadState()) {
1637 case DS_CONNECTING:
1638 case DS_WAITCALLBACK:
1639 case DS_WAITCALLBACKKAD:
1640 m_bReaskPending = false;
1641 SetDownloadState(DS_CONNECTED);
1642 SendFileRequest();
1644 if (m_bReaskPending){
1645 m_bReaskPending = false;
1646 if (GetDownloadState() != DS_NONE && GetDownloadState() != DS_DOWNLOADING) {
1647 SetDownloadState(DS_CONNECTED);
1648 SendFileRequest();
1651 switch(GetUploadState()){
1652 case US_CONNECTING:
1653 case US_WAITCALLBACK:
1654 if (theApp->uploadqueue->IsDownloading(this)) {
1655 SetUploadState(US_UPLOADING);
1656 CPacket* packet = new CPacket(OP_ACCEPTUPLOADREQ, 0, OP_EDONKEYPROT);
1657 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
1658 SendPacket(packet,true);
1659 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
1662 if (m_iFileListRequested == 1) {
1663 CPacket* packet = new CPacket(m_fSharedDirectories ? OP_ASKSHAREDDIRS : OP_ASKSHAREDFILES, 0, OP_EDONKEYPROT);
1664 theStats::AddUpOverheadOther(packet->GetPacketSize());
1665 SendPacket(packet,true,true);
1666 if (m_fSharedDirectories) {
1667 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
1668 } else {
1669 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
1673 while (!m_WaitingPackets_list.empty()) {
1674 CPacket* packet = m_WaitingPackets_list.front();
1675 m_WaitingPackets_list.pop_front();
1677 SendPacket(packet);
1682 int CUpDownClient::GetHashType() const
1684 if ( m_UserHash[5] == 13 && m_UserHash[14] == 110 ) {
1685 return SO_OLDEMULE;
1688 if ( m_UserHash[5] == 14 && m_UserHash[14] == 111 ) {
1689 return SO_EMULE;
1692 if ( m_UserHash[5] == 'M' && m_UserHash[14] == 'L' ) {
1693 return SO_MLDONKEY;
1696 return SO_UNKNOWN;
1700 void CUpDownClient::SetSocket(CClientTCPSocket* socket)
1702 #if defined(__DEBUG__) && !defined(EC_REMOTE)
1703 if (m_socket == NULL && socket != NULL) {
1704 theStats::SocketAssignedToClient();
1705 } else if (m_socket != NULL && socket == NULL) {
1706 theStats::SocketUnassignedFromClient();
1708 #endif
1709 m_socket = socket;
1713 void CUpDownClient::ReGetClientSoft()
1715 if (m_Username.IsEmpty()) {
1716 m_clientSoft=SO_UNKNOWN;
1717 m_clientVerString = m_clientSoftString = m_clientVersionString = m_fullClientVerString = _("Unknown");
1718 UpdateStats();
1719 return;
1722 int iHashType = GetHashType();
1723 wxString clientModString;
1724 if (iHashType == SO_EMULE) {
1726 m_clientSoft = m_byCompatibleClient;
1727 m_clientSoftString = GetSoftName(m_clientSoft);
1728 // Special issues:
1729 if(!GetClientModString().IsEmpty() && (m_clientSoft != SO_EMULE)) {
1730 m_clientSoftString = GetClientModString();
1732 // Isn't xMule annoying?
1733 if ((m_clientSoft == SO_LXMULE) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
1734 m_clientSoftString += wxString::Format(_(" (Fake eMule version %#x)"),GetMuleVersion());
1736 if ((m_clientSoft == SO_EMULE) &&
1738 wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
1739 || GetUserName().Find(wxT("xmule.")) != -1
1742 // FAKE eMule -a newer xMule faking is ident.
1743 m_clientSoft = SO_LXMULE;
1744 if (GetClientModString().IsEmpty() == false) {
1745 m_clientSoftString = GetClientModString() + _(" (Fake eMule)");
1746 } else {
1747 m_clientSoftString = _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
1750 // Now, what if we don't know this SO_ID?
1751 if (m_clientSoftString.IsEmpty()) {
1752 if(m_bIsML) {
1753 m_clientSoft = SO_MLDONKEY;
1754 m_clientSoftString = GetSoftName(m_clientSoft);
1755 } else if (m_bIsHybrid) {
1756 m_clientSoft = SO_EDONKEYHYBRID;
1757 m_clientSoftString = GetSoftName(m_clientSoft);
1758 } else if (m_byCompatibleClient != 0) {
1759 m_clientSoft = SO_COMPAT_UNK;
1760 #ifdef __DEBUG__
1761 if (
1762 // Exceptions:
1763 (m_byCompatibleClient != 0xf0) // Chinese leech mod
1764 && (1==1) // Your ad here
1766 printf("Compatible client found with ET_COMPATIBLECLIENT of %#x\n",m_byCompatibleClient);
1768 #endif
1769 m_clientSoftString = GetSoftName(m_clientSoft) + wxString::Format(wxT("(%#x)"),m_byCompatibleClient);
1770 } else {
1771 // If we step here, it might mean 2 things:
1772 // a eMule
1773 // a Compat Client that has sent no MuleInfo packet yet.
1774 m_clientSoft = SO_EMULE;
1775 m_clientSoftString = wxT("eMule");
1779 if (m_byEmuleVersion == 0) {
1780 m_nClientVersion = MAKE_CLIENT_VERSION(0,0,0);
1781 } else if (m_byEmuleVersion != 0x99) {
1782 uint32 nClientMinVersion = (m_byEmuleVersion >> 4)*10 + (m_byEmuleVersion & 0x0f);
1783 m_nClientVersion = MAKE_CLIENT_VERSION(0,nClientMinVersion,0);
1784 switch (m_clientSoft) {
1785 case SO_AMULE:
1786 m_clientVerString = wxString::Format(_("1.x (based on eMule v0.%u)"), nClientMinVersion);
1787 break;
1788 case SO_LPHANT:
1789 m_clientVerString = wxT("< v0.05");
1790 break;
1791 default:
1792 clientModString = GetClientModString();
1793 m_clientVerString = wxString::Format(wxT("v0.%u"), nClientMinVersion);
1794 break;
1796 } else {
1797 uint32 nClientMajVersion = (m_nClientVersion >> 17) & 0x7f;
1798 uint32 nClientMinVersion = (m_nClientVersion >> 10) & 0x7f;
1799 uint32 nClientUpVersion = (m_nClientVersion >> 7) & 0x07;
1801 m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
1803 switch (m_clientSoft) {
1804 case SO_AMULE:
1805 case SO_LXMULE:
1806 case SO_HYDRANODE:
1807 // Kry - xMule started sending correct version tags on 1.9.1b.
1808 // It only took them 4 months, and being told by me and the
1809 // eMule+ developers, so I think they're slowly getting smarter.
1810 // They are based on our implementation, so we use the same format
1811 // for the version string.
1812 m_clientVerString = wxString::Format(wxT("v%u.%u.%u"), nClientMajVersion, nClientMinVersion, nClientUpVersion);
1813 break;
1814 case SO_LPHANT:
1815 m_clientVerString = wxString::Format(wxT(" v%u.%.2u%c"), nClientMajVersion-1, nClientMinVersion, 'a' + nClientUpVersion);
1816 break;
1817 case SO_EMULEPLUS:
1818 m_clientVerString = wxString::Format(wxT("v%u"), nClientMajVersion);
1819 if(nClientMinVersion != 0) {
1820 m_clientVerString += wxString::Format(wxT(".%u"), nClientMinVersion);
1822 if(nClientUpVersion != 0) {
1823 m_clientVerString += wxString::Format(wxT("%c"), 'a' + nClientUpVersion - 1);
1825 break;
1826 default:
1827 clientModString = GetClientModString();
1828 m_clientVerString = wxString::Format(wxT("v%u.%u%c"), nClientMajVersion, nClientMinVersion, 'a' + nClientUpVersion);
1829 break;
1832 } else if (m_bIsHybrid) {
1833 // seen:
1834 // 105010 50.10
1835 // 10501 50.1
1836 // 1051 51.0
1837 // 501 50.1
1839 m_clientSoft = SO_EDONKEYHYBRID;
1840 m_clientSoftString = GetSoftName(m_clientSoft);
1842 uint32 nClientMajVersion;
1843 uint32 nClientMinVersion;
1844 uint32 nClientUpVersion;
1845 if (m_nClientVersion > 100000) {
1846 uint32 uMaj = m_nClientVersion/100000;
1847 nClientMajVersion = uMaj - 1;
1848 nClientMinVersion = (m_nClientVersion - uMaj*100000) / 100;
1849 nClientUpVersion = m_nClientVersion % 100;
1851 else if (m_nClientVersion > 10000) {
1852 uint32 uMaj = m_nClientVersion/10000;
1853 nClientMajVersion = uMaj - 1;
1854 nClientMinVersion = (m_nClientVersion - uMaj*10000) / 10;
1855 nClientUpVersion = m_nClientVersion % 10;
1857 else if (m_nClientVersion > 1000) {
1858 uint32 uMaj = m_nClientVersion/1000;
1859 nClientMajVersion = uMaj - 1;
1860 nClientMinVersion = m_nClientVersion - uMaj*1000;
1861 nClientUpVersion = 0;
1863 else if (m_nClientVersion > 100) {
1864 uint32 uMin = m_nClientVersion/10;
1865 nClientMajVersion = 0;
1866 nClientMinVersion = uMin;
1867 nClientUpVersion = m_nClientVersion - uMin*10;
1869 else{
1870 nClientMajVersion = 0;
1871 nClientMinVersion = m_nClientVersion;
1872 nClientUpVersion = 0;
1874 m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
1875 if (nClientUpVersion) {
1876 m_clientVerString = wxString::Format(wxT("v%u.%u.%u"), nClientMajVersion, nClientMinVersion, nClientUpVersion);
1877 } else {
1878 m_clientVerString = wxString::Format(wxT("v%u.%u"), nClientMajVersion, nClientMinVersion);
1880 } else if (m_bIsML || (iHashType == SO_MLDONKEY)) {
1881 m_clientSoft = SO_MLDONKEY;
1882 m_clientSoftString = GetSoftName(m_clientSoft);
1883 uint32 nClientMinVersion = m_nClientVersion;
1884 m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
1885 m_clientVerString = wxString::Format(wxT("v0.%u"), nClientMinVersion);
1886 } else if (iHashType == SO_OLDEMULE) {
1887 m_clientSoft = SO_OLDEMULE;
1888 m_clientSoftString = GetSoftName(m_clientSoft);
1889 uint32 nClientMinVersion = m_nClientVersion;
1890 m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
1891 m_clientVerString = wxString::Format(wxT("v0.%u"), nClientMinVersion);
1892 } else {
1893 m_clientSoft = SO_EDONKEY;
1894 m_clientSoftString = GetSoftName(m_clientSoft);
1895 m_nClientVersion *= 10;
1896 m_clientVerString = wxString::Format(wxT("v%u.%u"), m_nClientVersion / 100000, (m_nClientVersion / 1000) % 100);
1899 m_clientVersionString = m_clientVerString;
1900 if (!clientModString.IsEmpty()) {
1901 m_clientVerString += wxT(" - ") + clientModString;
1903 m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString;
1905 UpdateStats();
1908 void CUpDownClient::RequestSharedFileList()
1910 if (m_iFileListRequested == 0) {
1911 AddDebugLogLineM( false, logClient, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
1912 m_iFileListRequested = 1;
1913 TryToConnect(true);
1914 } else {
1915 AddDebugLogLineM( false, logClient, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
1920 void CUpDownClient::ProcessSharedFileList(const byte* pachPacket, uint32 nSize, wxString& pszDirectory)
1922 if (m_iFileListRequested > 0) {
1923 m_iFileListRequested--;
1924 theApp->searchlist->ProcessSharedFileList(pachPacket, nSize, this, NULL, pszDirectory);
1929 void CUpDownClient::ResetFileStatusInfo()
1931 m_nPartCount = 0;
1933 if ( m_reqfile ) {
1934 m_reqfile->UpdatePartsFrequency( this, false );
1936 m_downPartStatus.clear();
1938 m_clientFilename.Clear();
1940 m_bCompleteSource = false;
1941 m_dwLastAskedTime = 0;
1942 m_iRating = 0;
1943 m_strComment.Clear();
1945 if (m_pReqFileAICHHash != NULL) {
1946 delete m_pReqFileAICHHash;
1947 m_pReqFileAICHHash = NULL;
1952 wxString CUpDownClient::GetUploadFileInfo()
1954 // build info text and display it
1955 wxString sRet;
1956 sRet = (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
1957 if (m_reqfile) {
1958 sRet += CFormat(_("Requested: %s\n")) % m_reqfile->GetFileName();
1959 sRet += CFormat(
1960 wxPLURAL("Filestats for this session: Accepted %d of %d request, %s transferred\n", "Filestats for this session: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetRequests())
1961 ) % m_reqfile->statistic.GetAccepts() % m_reqfile->statistic.GetRequests() % CastItoXBytes(m_reqfile->statistic.GetTransferred());
1962 sRet += CFormat(
1963 wxPLURAL("Filestats for all sessions: Accepted %d of %d request, %s transferred\n", "Filestats for all sessions: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetAllTimeRequests())
1964 ) % m_reqfile->statistic.GetAllTimeAccepts() % m_reqfile->statistic.GetAllTimeRequests() % CastItoXBytes(m_reqfile->statistic.GetAllTimeTransferred());
1965 } else {
1966 sRet += _("Requested unknown file");
1968 return sRet;
1971 // sends a packet, if needed it will establish a connection before
1972 // options used: ignore max connections, control packet, delete packet
1973 // !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
1974 bool CUpDownClient::SafeSendPacket(CPacket* packet)
1976 if (IsConnected()) {
1977 SendPacket(packet, true);
1978 return true;
1979 } else {
1980 m_WaitingPackets_list.push_back(packet);
1981 return TryToConnect(true);
1985 void CUpDownClient::SendPublicKeyPacket(){
1986 // send our public key to the client who requested it
1987 if (m_socket == NULL || credits == NULL || m_SecureIdentState != IS_KEYANDSIGNEEDED){
1988 wxASSERT ( false );
1989 return;
1991 if (!theApp->CryptoAvailable())
1992 return;
1994 CMemFile data;
1995 data.WriteUInt8(theApp->clientcredits->GetPubKeyLen());
1996 data.Write(theApp->clientcredits->GetPublicKey(), theApp->clientcredits->GetPubKeyLen());
1997 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_PUBLICKEY);
1999 theStats::AddUpOverheadOther(packet->GetPacketSize());
2000 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
2001 SendPacket(packet,true,true);
2002 m_SecureIdentState = IS_SIGNATURENEEDED;
2006 void CUpDownClient::SendSignaturePacket(){
2007 // signate the public key of this client and send it
2008 if (m_socket == NULL || credits == NULL || m_SecureIdentState == 0){
2009 wxASSERT ( false );
2010 return;
2013 if (!theApp->CryptoAvailable()) {
2014 return;
2016 if (credits->GetSecIDKeyLen() == 0) {
2017 return; // We don't have his public key yet, will be back here later
2019 // do we have a challenge value received (actually we should if we are in this function)
2020 if (credits->m_dwCryptRndChallengeFrom == 0){
2021 AddDebugLogLineM( false, logClient, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
2022 return;
2024 // v2
2025 // we will use v1 as default, except if only v2 is supported
2026 bool bUseV2;
2027 if ( (m_bySupportSecIdent&1) == 1 )
2028 bUseV2 = false;
2029 else
2030 bUseV2 = true;
2032 uint8 byChaIPKind = 0;
2033 uint32 ChallengeIP = 0;
2034 if (bUseV2){
2035 if (::IsLowID(theApp->GetED2KID())) {
2036 // we cannot do not know for sure our public ip, so use the remote clients one
2037 ChallengeIP = GetIP();
2038 byChaIPKind = CRYPT_CIP_REMOTECLIENT;
2039 } else {
2040 ChallengeIP = theApp->GetED2KID();
2041 byChaIPKind = CRYPT_CIP_LOCALCLIENT;
2044 //end v2
2045 byte achBuffer[250];
2047 uint8 siglen = theApp->clientcredits->CreateSignature(credits, achBuffer, 250, ChallengeIP, byChaIPKind );
2048 if (siglen == 0){
2049 wxASSERT ( false );
2050 return;
2052 CMemFile data;
2053 data.WriteUInt8(siglen);
2054 data.Write(achBuffer, siglen);
2055 if (bUseV2) {
2056 data.WriteUInt8(byChaIPKind);
2059 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SIGNATURE);
2061 theStats::AddUpOverheadOther(packet->GetPacketSize());
2062 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
2063 SendPacket(packet,true,true);
2064 m_SecureIdentState = IS_ALLREQUESTSSEND;
2068 void CUpDownClient::ProcessPublicKeyPacket(const byte* pachPacket, uint32 nSize)
2070 theApp->clientlist->AddTrackClient(this);
2072 if (m_socket == NULL || credits == NULL || pachPacket[0] != nSize-1
2073 || nSize == 0 || nSize > 250){
2074 wxASSERT ( false );
2075 return;
2077 if (!theApp->CryptoAvailable())
2078 return;
2079 // the function will handle everything (mulitple key etc)
2080 if (credits->SetSecureIdent(pachPacket+1, pachPacket[0])){
2081 // if this client wants a signature, now we can send him one
2082 if (m_SecureIdentState == IS_SIGNATURENEEDED){
2083 SendSignaturePacket();
2085 else if(m_SecureIdentState == IS_KEYANDSIGNEEDED){
2086 // something is wrong
2087 AddDebugLogLineM( false, logClient, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
2089 } else{
2090 AddDebugLogLineM( false, logClient, wxT("Failed to use new received public key") );
2095 void CUpDownClient::ProcessSignaturePacket(const byte* pachPacket, uint32 nSize)
2097 // here we spread the good guys from the bad ones ;)
2099 if (m_socket == NULL || credits == NULL || nSize == 0 || nSize > 250){
2100 wxASSERT ( false );
2101 return;
2104 uint8 byChaIPKind;
2105 if (pachPacket[0] == nSize-1)
2106 byChaIPKind = 0;
2107 else if (pachPacket[0] == nSize-2 && (m_bySupportSecIdent & 2) > 0) //v2
2108 byChaIPKind = pachPacket[nSize-1];
2109 else{
2110 wxASSERT ( false );
2111 return;
2114 if (!theApp->CryptoAvailable())
2115 return;
2117 // we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
2118 if (m_dwLastSignatureIP == GetIP()){
2119 AddDebugLogLineM( false, logClient, wxT("received multiple signatures from one client") );
2120 return;
2122 // also make sure this client has a public key
2123 if (credits->GetSecIDKeyLen() == 0){
2124 AddDebugLogLineM( false, logClient, wxT("received signature for client without public key") );
2125 return;
2127 // and one more check: did we ask for a signature and sent a challange packet?
2128 if (credits->m_dwCryptRndChallengeFor == 0){
2129 AddDebugLogLineM( false, logClient, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
2130 return;
2133 if (theApp->clientcredits->VerifyIdent(credits, pachPacket+1, pachPacket[0], GetIP(), byChaIPKind ) ){
2134 // result is saved in function above
2135 AddDebugLogLineM( false, logClient, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
2136 } else {
2137 AddDebugLogLineM( false, logClient, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
2140 m_dwLastSignatureIP = GetIP();
2143 void CUpDownClient::SendSecIdentStatePacket(){
2144 // check if we need public key and signature
2145 uint8 nValue = 0;
2146 if (credits){
2147 if (theApp->CryptoAvailable()){
2148 if (credits->GetSecIDKeyLen() == 0) {
2149 nValue = IS_KEYANDSIGNEEDED;
2150 } else if (m_dwLastSignatureIP != GetIP()) {
2151 nValue = IS_SIGNATURENEEDED;
2154 if (nValue == 0){
2155 AddDebugLogLineM( false, logClient, wxT("Not sending SecIdentState Packet, because State is Zero") );
2156 return;
2158 // crypt: send random data to sign
2159 uint32 dwRandom = rand()+1;
2160 credits->m_dwCryptRndChallengeFor = dwRandom;
2162 CMemFile data;
2163 data.WriteUInt8(nValue);
2164 data.WriteUInt32(dwRandom);
2165 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SECIDENTSTATE);
2167 theStats::AddUpOverheadOther(packet->GetPacketSize());
2168 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
2169 SendPacket(packet,true,true);
2170 } else {
2171 wxASSERT ( false );
2176 void CUpDownClient::ProcessSecIdentStatePacket(const byte* pachPacket, uint32 nSize)
2178 if ( nSize != 5 ) {
2179 return;
2182 if ( !credits ) {
2183 wxASSERT( credits );
2184 return;
2187 CMemFile data(pachPacket,nSize);
2189 switch ( data.ReadUInt8() ) {
2190 case 0:
2191 m_SecureIdentState = IS_UNAVAILABLE;
2192 break;
2193 case 1:
2194 m_SecureIdentState = IS_SIGNATURENEEDED;
2195 break;
2196 case 2:
2197 m_SecureIdentState = IS_KEYANDSIGNEEDED;
2198 break;
2199 default:
2200 return;
2203 credits->m_dwCryptRndChallengeFrom = data.ReadUInt32();
2207 void CUpDownClient::InfoPacketsReceived()
2209 // indicates that both Information Packets has been received
2210 // needed for actions, which process data from both packets
2211 wxASSERT ( m_byInfopacketsReceived == IP_BOTH );
2212 m_byInfopacketsReceived = IP_NONE;
2214 if (m_bySupportSecIdent){
2215 SendSecIdentStatePacket();
2220 bool CUpDownClient::CheckHandshakeFinished(uint32 WXUNUSED(protocol), uint32 WXUNUSED(opcode)) const
2222 if (m_bHelloAnswerPending){
2223 // this triggers way too often.. need more time to look at this -> only create a warning
2224 AddDebugLogLineM( false, logClient, wxT("Handshake not finished while processing packet.") );
2225 return false;
2228 return true;
2232 wxString CUpDownClient::GetClientFullInfo() {
2234 if (m_clientVerString.IsEmpty()) {
2235 ReGetClientSoft();
2238 return CFormat( _("Client %s on IP:Port %s:%d using %s %s %s") )
2239 % ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
2240 % GetFullIP()
2241 % GetUserPort()
2242 % m_clientSoftString
2243 % m_clientVerString
2244 % m_strModVersion;
2249 void CUpDownClient::SendPublicIPRequest(){
2250 if (IsConnected()){
2251 CPacket* packet = new CPacket(OP_PUBLICIP_REQ,0,OP_EMULEPROT);
2252 theStats::AddUpOverheadOther(packet->GetPacketSize());
2253 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_PUBLICIP_REQ to") + GetFullIP());
2254 SendPacket(packet,true);
2255 m_fNeedOurPublicIP = true;
2259 void CUpDownClient::ProcessPublicIPAnswer(const byte* pbyData, uint32 uSize){
2260 if (uSize != 4) {
2261 throw wxString(wxT("Wrong Packet size on Public IP answer"));
2263 uint32 dwIP = PeekUInt32(pbyData);
2264 if (m_fNeedOurPublicIP == true){ // did we?
2265 m_fNeedOurPublicIP = false;
2266 // Ignore local ip on GetPublicIP (could be wrong)
2267 if (theApp->GetPublicIP(true) == 0 && !IsLowID(dwIP) ) {
2268 theApp->SetPublicIP(dwIP);
2274 bool CUpDownClient::IsConnected() const
2276 return m_socket && m_socket->IsConnected();
2279 bool CUpDownClient::SendPacket(CPacket* packet, bool delpacket, bool controlpacket)
2281 if ( m_socket ) {
2282 m_socket->SendPacket(packet, delpacket, controlpacket );
2283 return true;
2284 } else {
2285 printf("CAUGHT DEAD SOCKET IN SENDPACKET()\n");
2286 return false;
2290 float CUpDownClient::SetDownloadLimit(uint32 reducedownload)
2293 // lfroen: in daemon it actually can happen
2294 wxASSERT( m_socket );
2296 float kBpsClient = CalculateKBpsDown();
2298 if ( m_socket ) {
2300 if (reducedownload) {
2301 // (% to reduce * current speed) / 100 and THEN, / 10 because this
2302 // gets called 10 times per second.
2303 uint32 limit = (uint32)(((float)reducedownload*(kBpsClient*1024.0))/1000);
2305 if(limit<1024 && reducedownload >= 200) {
2306 // If we're going up and this download is < 1kB,
2307 // we want it to go up fast. Can be reduced later,
2308 // and it'll probably be in a more fair way with
2309 // other downloads that are faster.
2310 limit +=1024;
2311 } else if(limit == 0) {
2312 // This download is not transferring yet... make it
2313 // 1024 so we don't fill the TCP stack and lose the
2314 // connection.
2315 limit = 1024;
2318 m_socket->SetDownloadLimit(limit);
2319 } else {
2320 m_socket->DisableDownloadLimit();
2323 } else {
2324 printf("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f\n", kBpsClient);
2327 return kBpsClient;
2331 void CUpDownClient::SetUserIDHybrid(uint32 nUserID)
2333 theApp->clientlist->UpdateClientID( this, nUserID );
2335 m_nUserIDHybrid = nUserID;
2339 void CUpDownClient::SetIP( uint32 val )
2341 theApp->clientlist->UpdateClientIP( this, val );
2343 m_dwUserIP = val;
2345 m_nConnectIP = val;
2349 void CUpDownClient::SetUserHash(const CMD4Hash& userhash)
2351 theApp->clientlist->UpdateClientHash( this, userhash );
2353 m_UserHash = userhash;
2355 ValidateHash();
2358 EUtf8Str CUpDownClient::GetUnicodeSupport() const
2360 return m_bUnicodeSupport ? utf8strRaw : utf8strNone;
2364 uint8 CUpDownClient::GetSecureIdentState() {
2365 if (m_SecureIdentState != IS_UNAVAILABLE) {
2366 if (!SecIdentSupRec) {
2367 // This can be caused by a 0.30x based client which sends the old
2368 // style Hello packet, and the mule info packet, but between them they
2369 // send a secure ident state packet (after a hello but before we have
2370 // the SUI capabilities). This is a misbehaving client, and somehow I
2371 // Feel like ti should be dropped. But then again, it won't harm to use
2372 // this SUI state if they are reporting no SUI (won't be used) and if
2373 // they report using SUI on the mule info packet, it's ok to use it.
2375 AddDebugLogLineM(false, logClient, wxT("A client sent secure ident state before telling us the SUI capabilities"));
2376 AddDebugLogLineM(false, logClient, wxT("Client info: ") + GetClientFullInfo());
2377 AddDebugLogLineM(false, logClient, wxT("This client won't be disconnected, but it should be. :P"));
2381 return m_SecureIdentState;
2385 bool CUpDownClient::SendMessage(const wxString& message)
2387 // Already connecting?
2388 if (GetChatState() == MS_CONNECTING) {
2389 // Queue all messages till we're able to send them (or discard them)
2390 if (!m_pendingMessage.IsEmpty()) {
2391 m_pendingMessage += wxT("\n");
2392 } else {
2393 // There must be a message to send
2394 wxASSERT(0);
2396 m_pendingMessage += message;
2397 return false;
2399 if (IsConnected()) {
2400 CMemFile data;
2401 data.WriteString(message, GetUnicodeSupport());
2402 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_MESSAGE);
2403 theStats::AddUpOverheadOther(packet->GetPacketSize());
2404 AddDebugLogLineM( false, logLocalClient, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
2405 SendPacket(packet, true, true);
2406 return true;
2407 } else {
2408 m_pendingMessage = message;
2409 SetChatState(MS_CONNECTING);
2410 // True to ignore "Too Many Connections"
2411 TryToConnect(true);
2412 return false;
2416 /* Kad stuff */
2418 void CUpDownClient::SetBuddyID(const byte* pucBuddyID)
2420 if( pucBuddyID == NULL ){
2421 md4clr(m_achBuddyID);
2422 m_bBuddyIDValid = false;
2423 return;
2425 m_bBuddyIDValid = true;
2426 md4cpy(m_achBuddyID, pucBuddyID);
2429 // Kad added by me
2431 bool CUpDownClient::SendBuddyPing() {
2432 SetLastBuddyPingPongTime();
2433 CPacket* buddyPing = new CPacket(OP_BUDDYPING, 0, OP_EMULEPROT);
2434 theStats::AddUpOverheadKad(buddyPing->GetPacketSize());
2435 AddDebugLogLineM(false, logLocalClient,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
2436 return SafeSendPacket(buddyPing);
2440 /* Statistics */
2442 void CUpDownClient::UpdateStats()
2444 if (m_lastClientSoft != m_clientSoft || m_lastClientVersion != m_nClientVersion || m_lastOSInfo != m_sClientOSInfo) {
2445 if (m_lastClientSoft == SO_UNKNOWN) {
2446 theStats::RemoveUnknownClient();
2447 } else if (m_lastClientSoft != (uint32)(-1)) {
2448 theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
2451 m_lastClientSoft = m_clientSoft;
2452 m_lastClientVersion = m_nClientVersion;
2453 m_lastOSInfo = m_sClientOSInfo;
2455 if (m_clientSoft == SO_UNKNOWN) {
2456 theStats::AddUnknownClient();
2457 } else {
2458 theStats::AddKnownClient(this);
2463 bool CUpDownClient::IsIdentified() const
2465 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED);
2468 bool CUpDownClient::IsBadGuy() const
2470 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDBADGUY);
2473 bool CUpDownClient::SUIFailed() const
2475 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDFAILED);
2478 bool CUpDownClient::SUINeeded() const
2480 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDNEEDED);
2483 bool CUpDownClient::SUINotSupported() const
2485 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE);
2488 uint64 CUpDownClient::GetDownloadedTotal() const
2490 return credits ? credits->GetDownloadedTotal() : 0;
2493 uint64 CUpDownClient::GetUploadedTotal() const
2495 return credits ? credits->GetUploadedTotal() : 0;
2498 double CUpDownClient::GetScoreRatio() const {
2499 return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0;
2502 const wxString CUpDownClient::GetServerName() const
2504 wxString ret;
2505 wxString srvaddr = Uint32toStringIP(GetServerIP());
2506 CServer* cserver = theApp->serverlist->GetServerByAddress(
2507 srvaddr, GetServerPort());
2508 if (cserver) {
2509 ret = cserver->GetListName();
2510 } else {
2511 ret = _("Unknown");
2514 return ret;
2517 bool CUpDownClient::ShouldReceiveCryptUDPPackets() const {
2518 return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp->GetPublicIP() != 0
2519 && HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) );
2522 void CUpDownClient::SendFirewallCheckUDPRequest()
2524 wxASSERT(GetKadState() == KS_FWCHECK_UDP);
2526 if (!Kademlia::CKademlia::IsRunning()) {
2527 SetKadState(KS_NONE);
2528 return;
2529 } else if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE || GetKadVersion() <= 5 || GetKadPort() == 0) {
2530 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
2531 SetKadState(KS_NONE);
2532 return;
2535 wxASSERT(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0);
2536 CMemFile data;
2537 data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
2538 data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
2539 data.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
2540 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_FWCHECKUDPREQ);
2541 theStats::AddUpOverheadKad(packet->GetPacketSize());
2542 SafeSendPacket(packet);
2545 void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile* data)
2547 if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL) {
2548 //DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), DbgGetClientInfo());
2549 return;
2552 // first search if we know this IP already, if so the result might be biased and we need tell the requester
2553 bool errorAlreadyKnown = false;
2554 if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE) {
2555 errorAlreadyKnown = true;
2556 } else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL) {
2557 errorAlreadyKnown = true;
2560 uint16_t remoteInternPort = data->ReadUInt16();
2561 uint16_t remoteExternPort = data->ReadUInt16();
2562 uint32_t senderKey = data->ReadUInt32();
2563 if (remoteInternPort == 0) {
2564 //DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), DbgGetClientInfo());
2565 return;
2567 // if (senderKey == 0)
2568 // DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), DbgGetClientInfo());
2570 CMemFile testPacket1;
2571 testPacket1.WriteUInt8(errorAlreadyKnown ? 1 : 0);
2572 testPacket1.WriteUInt16(remoteInternPort);
2573 DebugSend(Kad2FirewallUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort);
2574 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
2576 // if the client has a router with PAT (and therefore a different extern port than intern), test this port too
2577 if (remoteExternPort != 0 && remoteExternPort != remoteInternPort) {
2578 CMemFile testPacket2;
2579 testPacket2.WriteUInt8(errorAlreadyKnown ? 1 : 0);
2580 testPacket2.WriteUInt16(remoteExternPort);
2581 DebugSend(Kad2FirewalledUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort);
2582 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
2584 //DebugLog(_T("Answered UDP Firewallcheck request (%s)"), DbgGetClientInfo());
2587 void CUpDownClient::SetConnectOptions(uint8_t options, bool encryption, bool callback)
2589 SetCryptLayerSupport((options & 0x01) != 0 && encryption);
2590 SetCryptLayerRequest((options & 0x02) != 0 && encryption);
2591 SetCryptLayerRequires((options & 0x04) != 0 && encryption);
2592 SetDirectUDPCallbackSupport((options & 0x08) != 0 && callback);
2594 // File_checked_for_headers