Fix restored columns getting an almost-zero width
[amule.git] / src / BaseClient.cpp
blob65daaf147b49d71aae630074c74c9ffcddb1a13e
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <wx/wx.h>
27 #include <wx/mstream.h>
28 #include <wx/tokenzr.h>
30 #include "updownclient.h" // Needed for CUpDownClient
32 #include <protocol/Protocols.h>
33 #include <protocol/ed2k/Client2Client/TCP.h>
34 #include <protocol/ed2k/ClientSoftware.h>
35 #include <protocol/kad/Client2Client/UDP.h>
36 #include <protocol/kad2/Constants.h>
37 #include <protocol/kad2/Client2Client/TCP.h>
38 #include <protocol/kad2/Client2Client/UDP.h>
40 #include <common/ClientVersion.h>
42 #include <tags/ClientTags.h>
44 #include <zlib.h> // Needed for inflateEnd
46 #include <common/Format.h> // Needed for CFormat
48 #include "SearchList.h" // Needed for CSearchList
49 #include "DownloadQueue.h" // Needed for CDownloadQueue
50 #include "UploadQueue.h" // Needed for CUploadQueue
51 #include "IPFilter.h" // Needed for CIPFilter
52 #include "ServerConnect.h" // Needed for CServerConnect
53 #include "ClientCredits.h" // Needed for CClientCredits
54 #include "ClientCreditsList.h" // Needed for CClientCreditsList
55 #include "Server.h" // Needed for CServer
56 #include "Preferences.h" // Needed for CPreferences
57 #include "MemFile.h" // Needed for CMemFile
58 #include "Packet.h" // Needed for CPacket
59 #include "Friend.h" // Needed for CFriend
60 #include "ClientList.h" // Needed for CClientList
61 #ifndef AMULE_DAEMON
62 #include "amuleDlg.h" // Needed for CamuleDlg
63 #include "CaptchaDialog.h" // Needed for CCaptchaDialog
64 #include "CaptchaGenerator.h"
65 #include "ChatWnd.h" // Needed for CChatWnd
66 #endif
67 #include "amule.h" // Needed for theApp
68 #include "PartFile.h" // Needed for CPartFile
69 #include "ClientTCPSocket.h" // Needed for CClientTCPSocket
70 #include "ListenSocket.h" // Needed for CListenSocket
71 #include "FriendList.h" // Needed for CFriendList
72 #include "Statistics.h" // Needed for theStats
73 #include "ClientUDPSocket.h"
74 #include "Logger.h"
75 #include "DataToText.h" // Needed for GetSoftName()
76 #include "GuiEvents.h" // Needed for Notify_
77 #include "ServerList.h" // For CServerList
79 #include "kademlia/kademlia/Kademlia.h"
80 #include "kademlia/kademlia/Prefs.h"
81 #include "kademlia/kademlia/Search.h"
82 #include "kademlia/kademlia/UDPFirewallTester.h"
83 #include "kademlia/routing/RoutingZone.h"
86 //#define __PACKET_DEBUG__
89 // some client testing variables
90 static wxString crash_name = wxT("[Invalid User Name]");
91 static wxString empty_name = wxT("[Empty User Name]");
93 // members of CUpDownClient
94 // which are used by down and uploading functions
97 CUpDownClient::CUpDownClient(CClientTCPSocket* sender)
99 #ifdef __DEBUG__
100 m_socket = NULL;
101 SetSocket(sender);
102 #else
103 m_socket = sender;
104 #endif
105 Init();
108 CUpDownClient::CUpDownClient(uint16 in_port, uint32 in_userid, uint32 in_serverip, uint16 in_serverport, CPartFile* in_reqfile, bool ed2kID, bool checkfriend)
110 m_socket = NULL;
111 Init();
112 m_nUserPort = in_port;
114 if(ed2kID && !IsLowID(in_userid)) {
115 SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid) );
116 } else {
117 SetUserIDHybrid( in_userid);
120 //If highID and ED2K source, incoming ID and IP are equal..
121 //If highID and Kad source, incoming IP needs swap for the IP
123 if (!HasLowID()) {
124 if (ed2kID) {
125 m_nConnectIP = in_userid;
126 } else {
127 m_nConnectIP = wxUINT32_SWAP_ALWAYS(in_userid);
129 // Will be on right endianess now
130 m_FullUserIP = m_nConnectIP;
133 m_dwServerIP = in_serverip;
134 m_nServerPort = in_serverport;
135 SetRequestFile( in_reqfile );
136 ReGetClientSoft();
138 if (checkfriend) {
139 if ((m_Friend = theApp->friendlist->FindFriend(CMD4Hash(), m_dwUserIP, m_nUserPort)) != NULL){
140 m_Friend->LinkClient(this);
141 } else{
142 // avoid that an unwanted client instance keeps a friend slot
143 m_bFriendSlot = false;
149 void CUpDownClient::Init()
151 m_bAddNextConnect = false;
152 credits = NULL;
153 m_byChatstate = MS_NONE;
154 m_nKadState = KS_NONE;
155 m_nChatCaptchaState = CA_NONE;
156 m_cShowDR = 0;
157 m_reqfile = NULL; // No file required yet
158 m_nTransferredUp = 0;
159 m_cSendblock = 0;
160 m_cAsked = 0;
161 msReceivedPrev = 0;
162 kBpsDown = 0.0;
163 bytesReceivedCycle = 0;
164 m_nServerPort = 0;
165 m_iFileListRequested = 0;
166 m_dwLastUpRequest = 0;
167 m_bEmuleProtocol = false;
168 m_bCompleteSource = false;
169 m_bFriendSlot = false;
170 m_bCommentDirty = false;
171 m_bReaskPending = false;
172 m_bUDPPending = false;
173 m_nUserPort = 0;
174 m_nPartCount = 0;
175 m_dwLastAskedTime = 0;
176 m_nDownloadState = DS_NONE;
177 m_dwUploadTime = 0;
178 m_nTransferredDown = 0;
179 m_nUploadState = US_NONE;
180 m_dwLastBlockReceived = 0;
181 m_bUnicodeSupport = false;
183 m_fSentOutOfPartReqs = 0;
184 m_nCurQueueSessionPayloadUp = 0;
185 m_addedPayloadQueueSession = 0;
186 m_nUpDatarate = 0;
187 m_nSumForAvgUpDataRate = 0;
189 m_nRemoteQueueRank = 0;
190 m_nOldRemoteQueueRank = 0;
191 m_dwLastSourceRequest = 0;
192 m_dwLastSourceAnswer = 0;
193 m_dwLastAskedForSources = 0;
195 m_SecureIdentState = IS_UNAVAILABLE;
196 m_dwLastSignatureIP = 0;
198 m_byInfopacketsReceived = IP_NONE;
200 m_bIsHybrid = false;
201 m_bIsML = false;
202 m_Friend = NULL;
203 m_iRating = 0;
204 m_nCurSessionUp = 0;
205 m_clientSoft=SO_UNKNOWN;
207 m_bRemoteQueueFull = false;
208 m_HasValidHash = false;
209 SetWaitStartTime();
211 m_fHashsetRequesting = 0;
212 m_fSharedDirectories = 0;
213 m_lastPartAsked = 0xffff;
214 m_nUpCompleteSourcesCount= 0;
215 m_waitingPosition = 0;
216 m_score = 0;
217 m_lastRefreshedDLDisplay = 0;
218 m_bHelloAnswerPending = false;
219 m_fSentCancelTransfer = 0;
220 m_Aggressiveness = 0;
221 m_LastFileRequest = 0;
223 m_clientState = CS_NEW;
225 ClearHelloProperties();
227 m_pReqFileAICHHash = NULL;
228 m_fSupportsAICH = 0;
229 m_fAICHRequested = 0;
230 m_fSupportsLargeFiles = 0;
231 m_fExtMultiPacket = 0;
232 m_fIsSpammer = 0;
234 m_dwUserIP = 0;
235 m_nConnectIP = 0;
236 m_dwServerIP = 0;
238 m_fNeedOurPublicIP = false;
239 m_bHashsetRequested = false;
241 m_lastDownloadingPart = 0;
243 m_uploadingfile = NULL;
245 m_OSInfo_sent = false;
247 /* Kad stuff */
248 SetBuddyID(NULL);
249 m_nBuddyIP = 0;
250 m_nBuddyPort = 0;
251 m_nUserIDHybrid = 0;
253 m_nSourceFrom = SF_NONE;
255 if (m_socket) {
256 amuleIPV4Address address;
257 m_socket->GetPeer(address);
258 SetIP(StringIPtoUint32(address.IPAddress()));
259 } else {
260 SetIP(0);
263 /* Statistics */
264 m_lastClientSoft = (uint32)(-1);
265 m_lastClientVersion = 0;
267 /* Creation time (for buddies timeout) */
268 m_nCreationTime = ::GetTickCount();
270 m_MaxBlockRequests = STANDARD_BLOCKS_REQUEST; // Safe starting amount
272 m_last_block_start = 0;
273 m_lastaverage = 0;
275 SetLastBuddyPingPongTime();
276 m_fRequestsCryptLayer = 0;
277 m_fSupportsCryptLayer = 0;
278 m_fRequiresCryptLayer = 0;
279 m_fSupportsSourceEx2 = 0;
280 m_fSupportsCaptcha = 0;
281 m_fDirectUDPCallback = 0;
282 m_dwDirectCallbackTimeout = 0;
284 m_hasbeenobfuscatinglately = false;
286 m_cCaptchasSent = 0;
287 m_cMessagesReceived = 0;
288 m_cMessagesSent = 0;
293 CUpDownClient::~CUpDownClient()
295 #ifdef __DEBUG__
296 if (!connection_reason.IsEmpty()) {
297 AddDebugLogLineN(logClient, wxT("Client to check for ") + connection_reason + wxT(" was deleted without connection."));
299 #endif
301 // For security, remove it from the lists unconditionally.
302 Notify_SharedCtrlRemoveClient((CKnownFile*)NULL, this);
303 Notify_SourceCtrlRemoveSource(this, (CPartFile*)NULL);
305 if (m_lastClientSoft == SO_UNKNOWN) {
306 theStats::RemoveUnknownClient();
307 } else if (m_lastClientSoft != (uint32)(-1)) {
308 theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
311 // Indicate that we are not anymore on stats
312 m_lastClientSoft = (uint32)(-1);
315 if (IsAICHReqPending()){
316 m_fAICHRequested = FALSE;
317 CAICHHashSet::ClientAICHRequestFailed(this);
320 //theApp->clientlist->RemoveClient(this, wxT("Destructing client object"));
322 if (m_Friend) {
323 m_Friend->UnLinkClient();
324 Notify_ChatRefreshFriend(m_Friend, false);
325 m_Friend = NULL;
328 // The socket should have been removed in Safe_Delete, but it
329 // doesn't hurt to have an extra check.
330 if (m_socket) {
331 m_socket->Safe_Delete();
332 // Paranoia
333 SetSocket(NULL);
337 ClearUploadBlockRequests();
338 ClearDownloadBlockRequests();
340 DeleteContents(m_WaitingPackets_list);
342 if (m_iRating>0 || !m_strComment.IsEmpty()) {
343 m_iRating = 0;
344 m_strComment.Clear();
345 if (m_reqfile) {
346 m_reqfile->UpdateFileRatingCommentAvail();
350 // Ensure that source-counts gets updated in case
351 // of a source not on the download-queue
352 SetRequestFile( NULL );
354 SetUploadFileID(NULL);
356 if (m_pReqFileAICHHash != NULL) {
357 delete m_pReqFileAICHHash;
358 m_pReqFileAICHHash = NULL;
362 void CUpDownClient::ClearHelloProperties()
364 m_nUDPPort = 0;
365 m_byUDPVer = 0;
366 m_byDataCompVer = 0;
367 m_byEmuleVersion = 0;
368 m_bySourceExchange1Ver = 0;
369 m_byAcceptCommentVer = 0;
370 m_byExtendedRequestsVer = 0;
371 m_byCompatibleClient = 0;
372 m_nKadPort = 0;
373 m_bySupportSecIdent = 0;
374 m_bSupportsPreview = 0;
375 m_nClientVersion = 0;
376 m_fSharedDirectories = 0;
377 m_bMultiPacket = 0;
378 m_fOsInfoSupport = 0;
379 m_fValueBasedTypeTags = 0;
380 SecIdentSupRec = 0;
381 m_byKadVersion = 0;
382 m_fRequestsCryptLayer = 0;
383 m_fSupportsCryptLayer = 0;
384 m_fRequiresCryptLayer = 0;
385 m_fSupportsSourceEx2 = 0;
386 m_fSupportsCaptcha = 0;
387 m_fDirectUDPCallback = 0;
390 bool CUpDownClient::ProcessHelloPacket(const byte* pachPacket, uint32 nSize)
392 const CMemFile data(pachPacket,nSize);
393 uint8 hashsize = data.ReadUInt8();
394 if ( 16 != hashsize ) {
396 * Hint: We can not accept other sizes here because:
397 * - the magic number is spread all over the source
398 * - the answer packet lacks the size field
400 throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
402 // eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
403 ClearHelloProperties();
405 return ProcessHelloTypePacket(data);
408 void CUpDownClient::Safe_Delete()
410 // Because we are delaying the deletion, we might end up trying to delete
411 // it twice, however, this is normal and shouldn't trigger any failures
412 if ( m_clientState == CS_DYING ) {
413 return;
416 m_clientState = CS_DYING;
418 // Close the socket to avoid any more connections and related events
419 if ( m_socket ) {
420 m_socket->Safe_Delete();
421 // Paranoia
422 SetSocket(NULL);
425 // Schedule the client for deletion if we still have the clientlist
426 if ( theApp->clientlist ) {
427 theApp->clientlist->AddToDeleteQueue( this );
428 } else {
429 delete this;
434 bool CUpDownClient::ProcessHelloAnswer(const byte* pachPacket, uint32 nSize)
436 const CMemFile data(pachPacket,nSize);
437 bool bIsMule = ProcessHelloTypePacket(data);
438 m_bHelloAnswerPending = false;
439 return bIsMule;
442 bool CUpDownClient::ProcessHelloTypePacket(const CMemFile& data)
445 m_bIsHybrid = false;
446 m_bIsML = false;
447 m_fNoViewSharedFiles = 0;
448 m_bUnicodeSupport = false;
449 uint32 dwEmuleTags = 0;
451 CMD4Hash hash = data.ReadHash();
452 SetUserHash( hash );
453 SetUserIDHybrid( data.ReadUInt32() );
454 uint16 nUserPort = data.ReadUInt16(); // hmm clientport is sent twice - why?
455 uint32 tagcount = data.ReadUInt32();
456 for (uint32 i = 0;i < tagcount; i++){
457 CTag temptag(data, true);
458 switch(temptag.GetNameID()){
459 case CT_NAME:
460 m_Username = temptag.GetStr();
461 break;
463 case CT_VERSION:
464 m_nClientVersion = temptag.GetInt();
465 break;
467 case ET_MOD_VERSION:
468 if (temptag.IsStr()) {
469 m_strModVersion = temptag.GetStr();
470 } else if (temptag.IsInt()) {
471 m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
472 } else {
473 m_strModVersion = wxT("ModID=<Unknown>");
476 break;
478 case CT_PORT:
479 nUserPort = temptag.GetInt();
480 break;
482 case CT_EMULE_UDPPORTS:
483 // 16 KAD Port
484 // 16 UDP Port
485 SetKadPort((temptag.GetInt() >> 16) & 0xFFFF);
486 m_nUDPPort = temptag.GetInt() & 0xFFFF;
487 dwEmuleTags |= 1;
488 #ifdef __PACKET_DEBUG__
489 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort % m_nKadPort);
490 #endif
491 break;
493 case CT_EMULE_BUDDYIP:
494 // 32 BUDDY IP
495 m_nBuddyIP = temptag.GetInt();
496 #ifdef __PACKET_DEBUG__
497 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP % Uint32toStringIP(m_nBuddyIP));
498 #endif
499 break;
501 case CT_EMULE_BUDDYUDP:
502 // 16 --Reserved for future use--
503 // 16 BUDDY Port
504 m_nBuddyPort = (uint16)temptag.GetInt();
505 #ifdef __PACKET_DEBUG__
506 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort);
507 #endif
508 break;
510 case CT_EMULE_MISCOPTIONS1: {
511 // 3 AICH Version (0 = not supported)
512 // 1 Unicode
513 // 4 UDP version
514 // 4 Data compression version
515 // 4 Secure Ident
516 // 4 Source Exchange
517 // 4 Ext. Requests
518 // 4 Comments
519 // 1 PeerCache supported
520 // 1 No 'View Shared Files' supported
521 // 1 MultiPacket
522 // 1 Preview
523 uint32 flags = temptag.GetInt();
524 m_fSupportsAICH = (flags >> (4*7+1)) & 0x07;
525 m_bUnicodeSupport = (flags >> 4*7) & 0x01;
526 m_byUDPVer = (flags >> 4*6) & 0x0f;
527 m_byDataCompVer = (flags >> 4*5) & 0x0f;
528 m_bySupportSecIdent = (flags >> 4*4) & 0x0f;
529 m_bySourceExchange1Ver = (flags >> 4*3) & 0x0f;
530 m_byExtendedRequestsVer = (flags >> 4*2) & 0x0f;
531 m_byAcceptCommentVer = (flags >> 4*1) & 0x0f;
532 m_fNoViewSharedFiles = (flags >> 1*2) & 0x01;
533 m_bMultiPacket = (flags >> 1*1) & 0x01;
534 m_fSupportsPreview = (flags >> 1*0) & 0x01;
535 dwEmuleTags |= 2;
536 #ifdef __PACKET_DEBUG__
537 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
538 AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer);
539 AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer);
540 AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent);
541 AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver);
542 AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer);
543 AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer);
544 AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles);
545 AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket);
546 AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories);
547 AddLogLineNS(wxT("That's all."));
548 #endif
549 SecIdentSupRec += 1;
550 break;
553 case CT_EMULE_MISCOPTIONS2:
554 // 19 Reserved
555 // 1 Direct UDP Callback supported and available
556 // 1 Supports ChatCaptchas
557 // 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
558 // 1 Requires CryptLayer
559 // 1 Requests CryptLayer
560 // 1 Supports CryptLayer
561 // 1 Reserved (ModBit)
562 // 1 Ext Multipacket (Hash+Size instead of Hash)
563 // 1 Large Files (includes support for 64bit tags)
564 // 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
565 m_fDirectUDPCallback = (temptag.GetInt() >> 12) & 0x01;
566 m_fSupportsCaptcha = (temptag.GetInt() >> 11) & 0x01;
567 m_fSupportsSourceEx2 = (temptag.GetInt() >> 10) & 0x01;
568 m_fRequiresCryptLayer = (temptag.GetInt() >> 9) & 0x01;
569 m_fRequestsCryptLayer = (temptag.GetInt() >> 8) & 0x01;
570 m_fSupportsCryptLayer = (temptag.GetInt() >> 7) & 0x01;
571 // reserved 1
572 m_fExtMultiPacket = (temptag.GetInt() >> 5) & 0x01;
573 m_fSupportsLargeFiles = (temptag.GetInt() >> 4) & 0x01;
574 m_byKadVersion = (temptag.GetInt() >> 0) & 0x0f;
575 dwEmuleTags |= 8;
577 m_fRequestsCryptLayer &= m_fSupportsCryptLayer;
578 m_fRequiresCryptLayer &= m_fRequestsCryptLayer;
580 #ifdef __PACKET_DEBUG__
581 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
582 AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback);
583 AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha);
584 AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2);
585 AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer);
586 AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer);
587 AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer);
588 AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket);
589 AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles);
590 AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion);
591 AddLogLineNS(wxT("That's all."));
592 #endif
593 break;
595 // Special tag for Compat. Clients Misc options.
596 case CT_EMULECOMPAT_OPTIONS:
597 // 1 Operative System Info
598 // 1 Value-based-type int tags (experimental!)
599 m_fValueBasedTypeTags = (temptag.GetInt() >> 1*1) & 0x01;
600 m_fOsInfoSupport = (temptag.GetInt() >> 1*0) & 0x01;
601 break;
603 case CT_EMULE_VERSION:
604 // 8 Compatible Client ID
605 // 7 Mjr Version (Doesn't really matter..)
606 // 7 Min Version (Only need 0-99)
607 // 3 Upd Version (Only need 0-5)
608 // 7 Bld Version (Only need 0-99)
609 m_byCompatibleClient = (temptag.GetInt() >> 24);
610 m_nClientVersion = temptag.GetInt() & 0x00ffffff;
611 m_byEmuleVersion = 0x99;
612 m_fSharedDirectories = 1;
613 dwEmuleTags |= 4;
614 break;
618 m_nUserPort = nUserPort;
619 m_dwServerIP = data.ReadUInt32();
620 m_nServerPort = data.ReadUInt16();
621 // Hybrid now has an extra uint32.. What is it for?
622 // Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
623 if ( data.GetLength() - data.GetPosition() == sizeof(uint32) ) {
624 uint32 test = data.ReadUInt32();
625 /*if (test == 'KDLM') below kdlm is converted to ascii values.
626 This fixes a warning with gcc 3.4.
627 K=4b D=44 L=4c M=4d
629 if (test == 0x4b444c4d) { //if it's == "KDLM"
630 m_bIsML=true;
631 } else{
632 m_bIsHybrid = true;
633 m_fSharedDirectories = 1;
637 if (m_socket) {
638 amuleIPV4Address address;
639 m_socket->GetPeer(address);
640 SetIP(StringIPtoUint32(address.IPAddress()));
641 } else {
642 throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
645 if (thePrefs::AddServersFromClient()) {
646 CServer* addsrv = new CServer(m_nServerPort, Uint32toStringIP(m_dwServerIP));
647 addsrv->SetListName(addsrv->GetAddress());
648 if (!theApp->AddServer(addsrv)) {
649 delete addsrv;
653 //(a)If this is a highID user, store the ID in the Hybrid format.
654 //(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
655 //(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
656 //because they will send a ID that is the same as their IP..
657 if(!HasLowID() || m_nUserIDHybrid == 0 || m_nUserIDHybrid == m_dwUserIP ) {
658 SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP));
661 // get client credits
662 CClientCredits* pFoundCredits = theApp->clientcredits->GetCredit(m_UserHash);
663 if (credits == NULL){
664 credits = pFoundCredits;
665 if (!theApp->clientlist->ComparePriorUserhash(m_dwUserIP, m_nUserPort, pFoundCredits)){
666 AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
667 Ban();
669 } else if (credits != pFoundCredits){
670 // userhash change ok, however two hours "waittime" before it can be used
671 credits = pFoundCredits;
672 AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
673 Ban();
676 if ((m_Friend = theApp->friendlist->FindFriend(m_UserHash, m_dwUserIP, m_nUserPort)) != NULL){
677 m_Friend->LinkClient(this);
678 } else{
679 // avoid that an unwanted client instance keeps a friend slot
680 SetFriendSlot(false);
684 ReGetClientSoft();
686 m_byInfopacketsReceived |= IP_EDONKEYPROTPACK;
688 // check if at least CT_EMULEVERSION was received, all other tags are optional
689 bool bIsMule = (dwEmuleTags & 0x04) == 0x04;
690 if (bIsMule) {
691 m_bEmuleProtocol = true;
692 m_byInfopacketsReceived |= IP_EMULEPROTPACK;
695 if (GetKadPort() && GetKadVersion() > 1) {
696 Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort());
699 return bIsMule;
703 bool CUpDownClient::SendHelloPacket()
705 if (m_socket == NULL) {
706 wxFAIL;
707 return true;
710 // if IP is filtered, don't greet him but disconnect...
711 amuleIPV4Address address;
712 m_socket->GetPeer(address);
713 if ( theApp->ipfilter->IsFiltered(StringIPtoUint32(address.IPAddress()))) {
714 if (Disconnected(wxT("IPFilter"))) {
715 Safe_Delete();
716 return false;
718 return true;
721 CMemFile data(128);
722 data.WriteUInt8(16); // size of userhash
723 SendHelloTypePacket(&data);
725 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLO);
726 theStats::AddUpOverheadOther(packet->GetPacketSize());
727 SendPacket(packet,true);
728 m_bHelloAnswerPending = true;
729 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
730 return true;
733 void CUpDownClient::SendMuleInfoPacket(bool bAnswer, bool OSInfo) {
735 if (m_socket == NULL){
736 wxFAIL;
737 return;
740 CPacket* packet = NULL;
741 CMemFile data;
743 data.WriteUInt8(CURRENT_VERSION_SHORT);
745 if (OSInfo) {
747 // Special MuleInfo packet for clients supporting it.
748 // This means aMule >= 2.0.0 and Hydranode
750 // Violently mark it as special Mule Info packet
751 // Sending this makes non-supporting-osinfo clients to refuse to read this
752 // packet. Anyway, this packet should NEVER get to non-supporting clients.
754 data.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
756 data.WriteUInt32(1); // One Tag (OS_INFO)
758 CTagString tag1(ET_OS_INFO,theApp->GetOSType());
759 tag1.WriteTagToFile(&data);
761 m_OSInfo_sent = true; // So we don't send it again
763 } else {
765 // Normal MuleInfo packet
767 // Kry - There's no point on upgrading to VBT tags here
768 // as no client supporting it uses mule info packet.
770 data.WriteUInt8(EMULE_PROTOCOL);
772 // Tag number
773 data.WriteUInt32(9);
775 CTagInt32 tag1(ET_COMPRESSION,1);
776 tag1.WriteTagToFile(&data);
777 CTagInt32 tag2(ET_UDPVER,4);
778 tag2.WriteTagToFile(&data);
779 CTagInt32 tag3(ET_UDPPORT, thePrefs::GetEffectiveUDPPort());
780 tag3.WriteTagToFile(&data);
781 CTagInt32 tag4(ET_SOURCEEXCHANGE,3);
782 tag4.WriteTagToFile(&data);
783 CTagInt32 tag5(ET_COMMENTS,1);
784 tag5.WriteTagToFile(&data);
785 CTagInt32 tag6(ET_EXTENDEDREQUEST,2);
786 tag6.WriteTagToFile(&data);
788 uint32 dwTagValue = (theApp->CryptoAvailable() ? 3 : 0);
789 // Kry - Needs the preview code from eMule
791 // set 'Preview supported' only if 'View Shared Files' allowed
792 if (thePrefs::CanSeeShares() != vsfaNobody) {
793 dwTagValue |= 128;
796 CTagInt32 tag7(ET_FEATURES, dwTagValue);
797 tag7.WriteTagToFile(&data);
799 CTagInt32 tag8(ET_COMPATIBLECLIENT,SO_AMULE);
800 tag8.WriteTagToFile(&data);
802 // Support for tag ET_MOD_VERSION
803 wxString mod_name(MOD_VERSION_LONG);
804 CTagString tag9(ET_MOD_VERSION, mod_name);
805 tag9.WriteTagToFile(&data);
806 // Maella end
810 packet = new CPacket(data, OP_EMULEPROT, (bAnswer ? OP_EMULEINFOANSWER : OP_EMULEINFO));
812 if (m_socket) {
813 theStats::AddUpOverheadOther(packet->GetPacketSize());
814 SendPacket(packet,true,true);
816 if (!bAnswer) {
817 if (!OSInfo) {
818 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
819 } else {
820 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
822 } else {
823 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
828 bool CUpDownClient::ProcessMuleInfoPacket(const byte* pachPacket, uint32 nSize)
830 uint8 protocol_version;
832 const CMemFile data(pachPacket,nSize);
834 // The version number part of this packet will soon be useless since
835 // it is only able to go to v.99. Why the version is a uint8 and why
836 // it was not done as a tag like the eDonkey hello packet is not known.
837 // Therefore, sooner or later, we are going to have to switch over to
838 // using the eDonkey hello packet to set the version. No sense making
839 // a third value sent for versions.
840 uint8 mule_version = data.ReadUInt8();
841 protocol_version = data.ReadUInt8();
842 uint32 tagcount = data.ReadUInt32();
843 if (protocol_version == 0xFF) {
844 // OS Info supporting clients sending a recycled Mule info packet
845 for (uint32 i = 0;i < tagcount; i++){
846 CTag temptag(data, true);
847 switch(temptag.GetNameID()){
848 case ET_OS_INFO:
849 // Special tag, only supporting clients (aMule/Hydranode)
850 // It was recycled from a mod's tag, so if the other side
851 // is not supporting OS Info, we're seriously fucked up :)
852 m_sClientOSInfo = temptag.GetStr();
854 // If we didn't send our OSInfo to this client, just send it
855 if (!m_OSInfo_sent) {
856 SendMuleInfoPacket(false,true);
859 UpdateStats();
861 break;
863 // Your ad... er... I mean TAG, here
865 default:
866 break;
869 } else {
870 // Old eMule sending tags
871 m_byCompatibleClient = 0;
872 m_byEmuleVersion = mule_version;
874 if( m_byEmuleVersion == 0x2B ) {
875 m_byEmuleVersion = 0x22;
878 if (!(m_bEmuleProtocol = (protocol_version == EMULE_PROTOCOL))) {
879 return false;
882 for (uint32 i = 0;i < tagcount; i++){
883 CTag temptag(data, false);
884 switch(temptag.GetNameID()){
885 case ET_COMPRESSION:
886 // Bits 31- 8: 0 - reserved
887 // Bits 7- 0: data compression version
888 m_byDataCompVer = temptag.GetInt();
889 break;
891 case ET_UDPPORT:
892 // Bits 31-16: 0 - reserved
893 // Bits 15- 0: UDP port
894 m_nUDPPort = temptag.GetInt();
895 break;
897 case ET_UDPVER:
898 // Bits 31- 8: 0 - reserved
899 // Bits 7- 0: UDP protocol version
900 m_byUDPVer = temptag.GetInt();
901 break;
903 case ET_SOURCEEXCHANGE:
904 // Bits 31- 8: 0 - reserved
905 // Bits 7- 0: source exchange protocol version
906 m_bySourceExchange1Ver = temptag.GetInt();
907 break;
909 case ET_COMMENTS:
910 // Bits 31- 8: 0 - reserved
911 // Bits 7- 0: comments version
912 m_byAcceptCommentVer = temptag.GetInt();
913 break;
915 case ET_EXTENDEDREQUEST:
916 // Bits 31- 8: 0 - reserved
917 // Bits 7- 0: extended requests version
918 m_byExtendedRequestsVer = temptag.GetInt();
919 break;
921 case ET_COMPATIBLECLIENT:
922 // Bits 31- 8: 0 - reserved
923 // Bits 7- 0: compatible client ID
924 m_byCompatibleClient = temptag.GetInt();
925 break;
927 case ET_FEATURES:
928 // Bits 31- 8: 0 - reserved
929 // Bit 7: Preview
930 // Bit 6- 0: secure identification
931 m_bySupportSecIdent = temptag.GetInt() & 3;
932 m_bSupportsPreview = (temptag.GetInt() & 128) > 0;
933 SecIdentSupRec += 2;
934 break;
936 case ET_MOD_VERSION:
937 if (temptag.IsStr()) {
938 m_strModVersion = temptag.GetStr();
939 } else if (temptag.IsInt()) {
940 m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
941 } else {
942 m_strModVersion = wxT("ModID=<Unknown>");
945 break;
947 default:
948 AddDebugLogLineN( logPacketErrors,
949 CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
950 % temptag.GetFullInfo()
951 % GetClientFullInfo()
954 break;
958 if( m_byDataCompVer == 0 ){
959 m_bySourceExchange1Ver = 0;
960 m_byExtendedRequestsVer = 0;
961 m_byAcceptCommentVer = 0;
962 m_nUDPPort = 0;
965 //implicitly supported options by older clients
966 //in the future do not use version to guess about new features
967 if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x22) {
968 m_byUDPVer = 1;
971 if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x21) {
972 m_bySourceExchange1Ver = 1;
975 if(m_byEmuleVersion == 0x24) {
976 m_byAcceptCommentVer = 1;
979 // Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
980 // the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
981 // directory which has a trailing backslash.
982 if(m_byEmuleVersion >= 0x28 && !m_bIsML) {// MLdonkey currently does not support shared directories
983 m_fSharedDirectories = 1;
986 ReGetClientSoft();
988 m_byInfopacketsReceived |= IP_EMULEPROTPACK;
991 return (protocol_version == 0xFF); // This was a OS_Info?
995 void CUpDownClient::SendHelloAnswer()
997 if (m_socket == NULL){
998 wxFAIL;
999 return;
1002 CMemFile data(128);
1003 SendHelloTypePacket(&data);
1004 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLOANSWER);
1005 theStats::AddUpOverheadOther(packet->GetPacketSize());
1006 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
1007 SendPacket(packet,true);
1011 void CUpDownClient::SendHelloTypePacket(CMemFile* data)
1013 data->WriteHash(thePrefs::GetUserHash());
1014 data->WriteUInt32(theApp->GetID());
1015 data->WriteUInt16(thePrefs::GetPort());
1017 uint32 tagcount = 6;
1019 if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
1020 tagcount += 2;
1022 tagcount ++; // eMule misc flags 2 (kad version)
1024 #ifdef __SVN__
1025 // Kry - This is the tagcount!!! Be sure to update it!!
1026 // Last update: CT_EMULECOMPAT_OPTIONS included
1027 data->WriteUInt32(tagcount + 1);
1028 #else
1029 data->WriteUInt32(tagcount); // NO MOD_VERSION
1030 #endif
1033 CTagString tagname(CT_NAME,thePrefs::GetUserNick());
1034 tagname.WriteTagToFile(data, utf8strRaw);
1036 CTagVarInt tagversion(CT_VERSION, EDONKEYVERSION, GetVBTTags() ? 0 : 32);
1037 tagversion.WriteTagToFile(data);
1038 // eMule UDP Ports
1040 uint32 kadUDPPort = 0;
1042 if(Kademlia::CKademlia::IsConnected()) {
1043 if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
1044 kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
1045 } else {
1046 kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
1050 CTagVarInt tagUdpPorts(CT_EMULE_UDPPORTS, (kadUDPPort << 16) | ((uint32)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
1051 tagUdpPorts.WriteTagToFile(data);
1053 if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
1054 CTagVarInt tagBuddyIP(CT_EMULE_BUDDYIP, theApp->clientlist->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
1055 tagBuddyIP.WriteTagToFile(data);
1057 CTagVarInt tagBuddyPort(CT_EMULE_BUDDYUDP,
1058 // ( RESERVED )
1059 ((uint32)theApp->clientlist->GetBuddy()->GetUDPPort() )
1060 , GetVBTTags() ? 0 : 32);
1061 tagBuddyPort.WriteTagToFile(data);
1064 // aMule Version
1065 CTagVarInt tagMuleVersion(CT_EMULE_VERSION,
1066 (SO_AMULE << 24) |
1067 make_full_ed2k_version(VERSION_MJR, VERSION_MIN, VERSION_UPDATE)
1068 // | (RESERVED )
1069 , GetVBTTags() ? 0 : 32);
1070 tagMuleVersion.WriteTagToFile(data);
1073 // eMule Misc. Options #1
1074 const uint32 uUdpVer = 4;
1075 const uint32 uDataCompVer = 1;
1076 const uint32 uSupportSecIdent = theApp->CryptoAvailable() ? 3 : 0;
1077 const uint32 uSourceExchangeVer = 3;
1078 const uint32 uExtendedRequestsVer = 2;
1079 const uint32 uAcceptCommentVer = 1;
1080 const uint32 uNoViewSharedFiles = (thePrefs::CanSeeShares() == vsfaNobody) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
1081 const uint32 uMultiPacket = 1;
1082 const uint32 uSupportPreview = 0; // No network preview at all.
1083 const uint32 uPeerCache = 0; // No peercache for aMule, baby
1084 const uint32 uUnicodeSupport = 1;
1085 const uint32 nAICHVer = 1; // AICH is ENABLED right now.
1087 CTagVarInt tagMisOptions(CT_EMULE_MISCOPTIONS1,
1088 (nAICHVer << ((4*7)+1)) |
1089 (uUnicodeSupport << 4*7) |
1090 (uUdpVer << 4*6) |
1091 (uDataCompVer << 4*5) |
1092 (uSupportSecIdent << 4*4) |
1093 (uSourceExchangeVer << 4*3) |
1094 (uExtendedRequestsVer << 4*2) |
1095 (uAcceptCommentVer << 4*1) |
1096 (uPeerCache << 1*3) |
1097 (uNoViewSharedFiles << 1*2) |
1098 (uMultiPacket << 1*1) |
1099 (uSupportPreview << 1*0)
1100 , GetVBTTags() ? 0 : 32);
1101 tagMisOptions.WriteTagToFile(data);
1103 // eMule Misc. Options #2
1104 const uint32 uKadVersion = KADEMLIA_VERSION;
1105 const uint32 uSupportLargeFiles = 1;
1106 const uint32 uExtMultiPacket = 1;
1107 const uint32 uReserved = 0; // mod bit
1108 const uint32 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
1109 const uint32 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
1110 const uint32 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
1111 const uint32 uSupportsSourceEx2 = 1;
1112 #ifdef AMULE_DAEMON
1113 // captcha for daemon/remotegui not supported for now
1114 const uint32 uSupportsCaptcha = 0;
1115 #else
1116 const uint32 uSupportsCaptcha = 1;
1117 #endif
1118 // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
1119 const uint32 uDirectUDPCallback = (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
1120 && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
1122 CTagVarInt tagMisOptions2(CT_EMULE_MISCOPTIONS2,
1123 // (RESERVED )
1124 (uDirectUDPCallback << 12) |
1125 (uSupportsCaptcha << 11) |
1126 (uSupportsSourceEx2 << 10) |
1127 (uRequiresCryptLayer << 9) |
1128 (uRequestsCryptLayer << 8) |
1129 (uSupportsCryptLayer << 7) |
1130 (uReserved << 6) |
1131 (uExtMultiPacket << 5) |
1132 (uSupportLargeFiles << 4) |
1133 (uKadVersion << 0)
1134 , GetVBTTags() ? 0 : 32 );
1135 tagMisOptions2.WriteTagToFile(data);
1137 const uint32 nOSInfoSupport = 1; // We support OS_INFO
1138 const uint32 nValueBasedTypeTags = 0; // Experimental, disabled
1140 CTagVarInt tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS,
1141 (nValueBasedTypeTags << 1*1) |
1142 (nOSInfoSupport << 1*0)
1143 , GetVBTTags() ? 0 : 32);
1145 tagMisCompatOptions.WriteTagToFile(data);
1147 #ifdef __SVN__
1148 wxString mod_name(MOD_VERSION_LONG);
1149 CTagString tagModName(ET_MOD_VERSION, mod_name);
1150 tagModName.WriteTagToFile(data);
1151 #endif
1153 uint32 dwIP = 0;
1154 uint16 nPort = 0;
1155 if (theApp->IsConnectedED2K()) {
1156 dwIP = theApp->serverconnect->GetCurrentServer()->GetIP();
1157 nPort = theApp->serverconnect->GetCurrentServer()->GetPort();
1159 data->WriteUInt32(dwIP);
1160 data->WriteUInt16(nPort);
1164 void CUpDownClient::ProcessMuleCommentPacket(const byte* pachPacket, uint32 nSize)
1166 if (!m_reqfile) {
1167 throw CInvalidPacket(wxT("Comment packet for unknown file"));
1170 if (!m_reqfile->IsPartFile()) {
1171 throw CInvalidPacket(wxT("Comment packet for completed file"));
1174 const CMemFile data(pachPacket, nSize);
1176 uint8 rating = data.ReadUInt8();
1177 if (rating > 5) {
1178 AddDebugLogLineN( logClient, wxString(wxT("Invalid Rating for file '")) << m_clientFilename << wxT("' received: ") << rating);
1179 m_iRating = 0;
1180 } else {
1181 m_iRating = rating;
1182 AddDebugLogLineN( logClient, wxString(wxT("Rating for file '")) << m_clientFilename << wxT("' received: ") << m_iRating);
1185 // The comment is unicoded, with a uin32 len and safe read
1186 // (won't break if string size is < than advertised len)
1187 // Truncated to MAXFILECOMMENTLEN size
1188 m_strComment = data.ReadString((GetUnicodeSupport() != utf8strNone), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN);
1190 AddDebugLogLineN( logClient, wxString(wxT("Description for file '")) << m_clientFilename << wxT("' received: ") << m_strComment);
1192 // Update file rating
1193 m_reqfile->UpdateFileRatingCommentAvail();
1197 void CUpDownClient::ClearDownloadBlockRequests()
1200 std::list<Requested_Block_Struct*>::iterator it = m_DownloadBlocks_list.begin();
1201 for (; it != m_DownloadBlocks_list.end(); ++it) {
1202 Requested_Block_Struct* cur_block = *it;
1204 if (m_reqfile){
1205 m_reqfile->RemoveBlockFromList(cur_block->StartOffset, cur_block->EndOffset);
1208 delete cur_block;
1211 m_DownloadBlocks_list.clear();
1215 std::list<Pending_Block_Struct*>::iterator it = m_PendingBlocks_list.begin();
1216 for (; it != m_PendingBlocks_list.end(); ++it) {
1217 Pending_Block_Struct* pending = *it;
1219 if (m_reqfile) {
1220 m_reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset);
1223 delete pending->block;
1224 // Not always allocated
1225 if (pending->zStream){
1226 inflateEnd(pending->zStream);
1227 delete pending->zStream;
1230 delete pending;
1233 m_PendingBlocks_list.clear();
1238 bool CUpDownClient::Disconnected(const wxString& strReason, bool bFromSocket)
1240 //wxASSERT(theApp->clientlist->IsValidClient(this));
1242 // was this a direct callback?
1243 if (m_dwDirectCallbackTimeout != 0) {
1244 theApp->clientlist->RemoveDirectCallback(this);
1245 m_dwDirectCallbackTimeout = 0;
1246 theApp->clientlist->AddDeadSource(this);
1247 AddDebugLogLineN(logClient, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP()));
1250 if (GetKadState() == KS_QUEUED_FWCHECK_UDP || GetKadState() == KS_CONNECTING_FWCHECK_UDP) {
1251 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
1252 } else if (GetKadState() == KS_FWCHECK_UDP) {
1253 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
1254 } else if (GetKadState() == KS_CONNECTED_BUDDY) {
1255 AddDebugLogLineN(logClient, wxT("Buddy client disconnected - ") + strReason);
1258 //If this is a KAD client object, just delete it!
1259 SetKadState(KS_NONE);
1261 if (GetUploadState() == US_UPLOADING) {
1262 // sets US_NONE
1263 theApp->uploadqueue->RemoveFromUploadQueue(this);
1266 if (GetDownloadState() == DS_DOWNLOADING) {
1267 SetDownloadState(DS_ONQUEUE);
1268 } else {
1269 // ensure that all possible block requests are removed from the partfile
1270 ClearDownloadBlockRequests();
1272 if (GetDownloadState() == DS_CONNECTED) {
1273 // successfully connected, but probably didn't respond to our filerequest
1274 theApp->clientlist->AddDeadSource(this);
1275 theApp->downloadqueue->RemoveSource(this);
1279 // we had still an AICH request pending, handle it
1280 if (IsAICHReqPending()) {
1281 m_fAICHRequested = FALSE;
1282 CAICHHashSet::ClientAICHRequestFailed(this);
1285 // The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
1286 // after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
1287 // is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
1288 if (((GetDownloadState() == DS_REQHASHSET) || m_fHashsetRequesting) && (m_reqfile)) {
1289 m_reqfile->SetHashSetNeeded(true);
1292 SourceItemType source_type = UNAVAILABLE_SOURCE;
1293 SourceItemType peer_type = UNAVAILABLE_SOURCE;
1295 //check if this client is needed in any way, if not delete it
1296 bool bDelete = true;
1297 switch (m_nUploadState) {
1298 case US_ONUPLOADQUEUE:
1299 bDelete = false;
1300 peer_type = AVAILABLE_SOURCE;
1301 break;
1304 switch (m_nDownloadState) {
1305 case DS_ONQUEUE:
1306 source_type = A4AF_SOURCE; // Will be checked.
1307 case DS_TOOMANYCONNS:
1308 case DS_NONEEDEDPARTS:
1309 case DS_LOWTOLOWIP:
1310 bDelete = false;
1311 break;
1314 switch (m_nUploadState) {
1315 case US_CONNECTING:
1316 case US_WAITCALLBACK:
1317 case US_ERROR:
1318 theApp->clientlist->AddDeadSource(this);
1319 bDelete = true;
1322 switch (m_nDownloadState) {
1323 case DS_CONNECTING:
1324 case DS_WAITCALLBACK:
1325 case DS_ERROR:
1326 case DS_BANNED:
1327 theApp->clientlist->AddDeadSource(this);
1328 bDelete = true;
1332 // We keep chat partners in any case
1333 if (GetChatState() != MS_NONE) {
1334 bDelete = false;
1335 m_pendingMessage.Clear();
1336 Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString);
1339 // Delete socket
1340 if (!bFromSocket && m_socket) {
1341 wxASSERT (theApp->listensocket->IsValidSocket(m_socket));
1342 m_socket->Safe_Delete();
1345 SetSocket(NULL);
1347 if (m_iFileListRequested) {
1348 AddLogLineN(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
1349 m_iFileListRequested = 0;
1353 if (bDelete) {
1354 if (m_Friend) {
1355 // Remove the friend linkage
1356 Notify_ChatRefreshFriend(m_Friend, false);
1358 } else {
1359 Notify_SharedCtrlRefreshClient( this, peer_type);
1360 Notify_SourceCtrlUpdateSource( this, source_type);
1362 m_fHashsetRequesting = 0;
1363 SetSentCancelTransfer(0);
1364 m_bHelloAnswerPending = false;
1365 m_fSentOutOfPartReqs = 0;
1367 AddDebugLogLineN(logClient, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
1368 % (bDelete ? wxT("Deleted") : wxT("Disconnected"))
1369 % m_nDownloadState % m_nUploadState % GetClientFullInfo() % strReason );
1371 return bDelete;
1374 //Returned bool is not if the TryToConnect is successful or not..
1375 //false means the client was deleted!
1376 //true means the client was not deleted!
1377 bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon)
1379 // Kad reviewed
1380 if (theApp->listensocket->TooManySockets() && !bIgnoreMaxCon ) {
1381 if (!(m_socket && m_socket->IsConnected())) {
1382 if(Disconnected(wxT("Too many connections"))) {
1383 Safe_Delete();
1384 return false;
1386 return true;
1390 // 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)
1391 if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
1392 if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
1393 Safe_Delete();
1394 return false;
1395 } else {
1396 return true;
1400 // Ipfilter check
1401 uint32 uClientIP = GetIP();
1402 if (uClientIP == 0 && !HasLowID()) {
1403 uClientIP = wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid);
1406 if (uClientIP) {
1407 // Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
1408 // we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
1409 if (theApp->ipfilter->IsFiltered(uClientIP)) {
1410 AddDebugLogLineN(logIPFilter, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP % Uint32toStringIP(uClientIP));
1411 if (Disconnected(wxT("IPFilter"))) {
1412 Safe_Delete();
1413 return false;
1415 return true;
1418 // for safety: check again whether that IP is banned
1419 if (theApp->clientlist->IsBannedClient(uClientIP)) {
1420 AddDebugLogLineN(logClient, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP));
1421 if (Disconnected(wxT("Banned IP"))) {
1422 Safe_Delete();
1423 return false;
1425 return true;
1429 if (GetKadState() == KS_QUEUED_FWCHECK) {
1430 SetKadState(KS_CONNECTING_FWCHECK);
1431 } else if (GetKadState() == KS_QUEUED_FWCHECK_UDP) {
1432 SetKadState(KS_CONNECTING_FWCHECK_UDP);
1435 if (HasLowID()) {
1436 if (!theApp->CanDoCallback(this)) {
1437 //We cannot do a callback!
1438 if (GetDownloadState() == DS_CONNECTING) {
1439 SetDownloadState(DS_LOWTOLOWIP);
1440 } else if (GetDownloadState() == DS_REQHASHSET) {
1441 SetDownloadState(DS_ONQUEUE);
1442 m_reqfile->SetHashSetNeeded(true);
1444 if (GetUploadState() == US_CONNECTING) {
1445 if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
1446 Safe_Delete();
1447 return false;
1450 return true;
1453 //We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
1454 //If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
1455 //with the condition that the source is firewalled and we are firewalled, we must
1456 //recheck it before the this check..
1457 if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp->serverconnect->IsLocalServer(GetServerIP(), GetServerPort())
1458 && !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
1459 //This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
1460 if( Kademlia::CKademlia::IsConnected() ) {
1461 //We are connect to Kad
1462 if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
1463 //There are too many source lookups already or we are already searching this key.
1464 SetDownloadState(DS_TOOMANYCONNSKAD);
1465 return true;
1471 if (!m_socket || !m_socket->IsConnected()) {
1472 if (m_socket) {
1473 m_socket->Safe_Delete();
1475 m_socket = new CClientTCPSocket(this, thePrefs::GetProxyData());
1476 } else {
1477 ConnectionEstablished();
1478 return true;
1482 if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
1483 if (m_dwDirectCallbackTimeout != 0) {
1484 AddDebugLogLineN(logClient, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP()));
1485 return true; // We're already trying a direct connection to this client
1487 // a direct callback is possible - since no other parties are involved and only one additional packet overhead
1488 // is used we basically handle it like a normal connection try, no restrictions apply
1489 // we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
1490 m_dwDirectCallbackTimeout = ::GetTickCount() + SEC2MS(45);
1491 theApp->clientlist->AddDirectCallbackClient(this);
1492 AddDebugLogLineN(logClient, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP()));
1494 CMemFile data;
1495 data.WriteUInt16(thePrefs::GetPort()); // needs to know our port
1496 data.WriteHash(thePrefs::GetUserHash()); // and userhash
1497 // our connection settings
1498 data.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
1499 AddDebugLogLineN(logClientUDP, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
1500 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_DIRECTCALLBACKREQ);
1501 theStats::AddUpOverheadOther(packet->GetPacketSize());
1502 theApp->clientudp->SendPacket(packet, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
1503 } else if (HasLowID()) { // LOWID
1504 if (GetDownloadState() == DS_CONNECTING) {
1505 SetDownloadState(DS_WAITCALLBACK);
1507 if (GetUploadState() == US_CONNECTING) {
1508 if(Disconnected(wxT("LowID and US_CONNECTING"))) {
1509 Safe_Delete();
1510 return false;
1512 return true;
1515 if (theApp->serverconnect->IsLocalServer(m_dwServerIP,m_nServerPort)) {
1516 CMemFile data;
1517 // AFAICS, this id must be reversed to be sent to clients
1518 // But if I reverse it, we do a serve violation ;)
1519 data.WriteUInt32(m_nUserIDHybrid);
1520 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_CALLBACKREQUEST);
1521 theStats::AddUpOverheadServer(packet->GetPacketSize());
1522 AddDebugLogLineN(logLocalClient, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
1523 theApp->serverconnect->SendPacket(packet);
1524 SetDownloadState(DS_WAITCALLBACK);
1525 } else {
1526 if (GetUploadState() == US_NONE && (!GetRemoteQueueRank() || m_bReaskPending)) {
1528 if( !HasValidBuddyID() ) {
1529 theApp->downloadqueue->RemoveSource(this);
1530 if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
1531 Safe_Delete();
1532 return false;
1534 return true;
1537 if( !Kademlia::CKademlia::IsConnected() ) {
1538 //We are not connected to Kad and this is a Kad Firewalled source..
1539 theApp->downloadqueue->RemoveSource(this);
1540 if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
1541 Safe_Delete();
1542 return false;
1544 return true;
1547 if( GetDownloadState() == DS_WAITCALLBACK ) {
1548 if( GetBuddyIP() && GetBuddyPort()) {
1549 CMemFile bio(34);
1550 bio.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
1551 bio.WriteUInt128(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
1552 bio.WriteUInt16(thePrefs::GetPort());
1553 CPacket* packet = new CPacket(bio, OP_KADEMLIAHEADER, KADEMLIA_CALLBACK_REQ);
1554 // eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
1555 theApp->clientudp->SendPacket(packet, GetBuddyIP(), GetBuddyPort(), false, NULL, true, 0);
1556 AddDebugLogLineN(logClientKadUDP, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet->GetPacketSize() % Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort()));
1557 theStats::AddUpOverheadKad(packet->GetRealPacketSize());
1558 SetDownloadState(DS_WAITCALLBACKKAD);
1559 } else {
1560 AddLogLineN(_("Searching buddy for lowid connection"));
1561 //Create search to find buddy.
1562 Kademlia::CSearch *findSource = new Kademlia::CSearch;
1563 findSource->SetSearchTypes(Kademlia::CSearch::FINDSOURCE);
1564 findSource->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
1565 findSource->AddFileID(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
1566 if(Kademlia::CSearchManager::StartSearch(findSource)) {
1567 //Started lookup..
1568 SetDownloadState(DS_WAITCALLBACKKAD);
1569 } else {
1570 //This should never happen..
1571 wxFAIL;
1575 } else {
1576 if (GetDownloadState() == DS_WAITCALLBACK) {
1577 m_bReaskPending = true;
1578 SetDownloadState(DS_ONQUEUE);
1582 } else { // HIGHID
1583 if (!Connect()) {
1584 return false;
1587 return true;
1590 bool CUpDownClient::Connect()
1592 m_hasbeenobfuscatinglately = false;
1594 if (!m_socket->IsOk()) {
1595 // Enable or disable crypting based on our and the remote clients preference
1596 if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
1597 m_socket->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
1598 } else {
1599 m_socket->SetConnectionEncryption(false, NULL, false);
1601 amuleIPV4Address tmp;
1602 tmp.Hostname(GetConnectIP());
1603 tmp.Service(GetUserPort());
1604 AddDebugLogLineN(logClient, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
1605 m_socket->Connect(tmp, false);
1606 // We should send hello packets AFTER connecting!
1607 // so I moved it to OnConnect
1608 return true;
1609 } else {
1610 return false;
1614 void CUpDownClient::ConnectionEstablished()
1616 /* Kry - First thing, check if this client was just used to retrieve
1617 info. That's some debug thing for myself... check connection_reason
1618 definition */
1620 m_hasbeenobfuscatinglately = (m_socket && m_socket->IsConnected() && m_socket->IsObfusicating());
1622 #ifdef __DEBUG__
1623 if (!connection_reason.IsEmpty()) {
1624 AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason % GetClientFullInfo());
1625 connection_reason.Clear(); // So we don't re-print on destructor.
1626 Safe_Delete();
1627 return;
1629 #endif
1631 // Check if we should use this client to retrieve our public IP
1632 // Ignore local ip on GetPublicIP (could be wrong)
1633 if (theApp->GetPublicIP(true) == 0 && theApp->IsConnectedED2K()) {
1634 SendPublicIPRequest();
1637 // was this a direct callback?
1638 if (m_dwDirectCallbackTimeout != 0){
1639 theApp->clientlist->RemoveDirectCallback(this);
1640 m_dwDirectCallbackTimeout = 0;
1641 AddDebugLogLineN(logClient, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP()));
1644 switch (GetKadState()) {
1645 case KS_CONNECTING_FWCHECK:
1646 SetKadState(KS_CONNECTED_FWCHECK);
1647 break;
1648 case KS_CONNECTING_BUDDY:
1649 case KS_INCOMING_BUDDY:
1650 SetKadState(KS_CONNECTED_BUDDY);
1651 break;
1652 case KS_CONNECTING_FWCHECK_UDP:
1653 SetKadState(KS_FWCHECK_UDP);
1654 SendFirewallCheckUDPRequest();
1655 break;
1656 default:
1657 break;
1660 // ok we have a connection, lets see if we want anything from this client
1661 if (GetChatState() == MS_CONNECTING) {
1662 SetChatState( MS_CHATTING );
1665 if (GetChatState() == MS_CHATTING) {
1666 bool result = true;
1667 if (!m_pendingMessage.IsEmpty()) {
1668 result = SendChatMessage(m_pendingMessage);
1670 Notify_ChatConnResult(result,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage);
1671 m_pendingMessage.Clear();
1674 switch(GetDownloadState()) {
1675 case DS_CONNECTING:
1676 case DS_WAITCALLBACK:
1677 case DS_WAITCALLBACKKAD:
1678 m_bReaskPending = false;
1679 SetDownloadState(DS_CONNECTED);
1680 SendFileRequest();
1682 if (m_bReaskPending){
1683 m_bReaskPending = false;
1684 if (GetDownloadState() != DS_NONE && GetDownloadState() != DS_DOWNLOADING) {
1685 SetDownloadState(DS_CONNECTED);
1686 SendFileRequest();
1689 switch(GetUploadState()){
1690 case US_CONNECTING:
1691 case US_WAITCALLBACK:
1692 if (theApp->uploadqueue->IsDownloading(this)) {
1693 SetUploadState(US_UPLOADING);
1694 CPacket* packet = new CPacket(OP_ACCEPTUPLOADREQ, 0, OP_EDONKEYPROT);
1695 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
1696 SendPacket(packet,true);
1697 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
1700 if (m_iFileListRequested == 1) {
1701 CPacket* packet = new CPacket(m_fSharedDirectories ? OP_ASKSHAREDDIRS : OP_ASKSHAREDFILES, 0, OP_EDONKEYPROT);
1702 theStats::AddUpOverheadOther(packet->GetPacketSize());
1703 SendPacket(packet,true,true);
1704 if (m_fSharedDirectories) {
1705 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
1706 } else {
1707 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
1711 while (!m_WaitingPackets_list.empty()) {
1712 CPacket* packet = m_WaitingPackets_list.front();
1713 m_WaitingPackets_list.pop_front();
1715 SendPacket(packet);
1720 int CUpDownClient::GetHashType() const
1722 if ( m_UserHash[5] == 13 && m_UserHash[14] == 110 ) {
1723 return SO_OLDEMULE;
1726 if ( m_UserHash[5] == 14 && m_UserHash[14] == 111 ) {
1727 return SO_EMULE;
1730 if ( m_UserHash[5] == 'M' && m_UserHash[14] == 'L' ) {
1731 return SO_MLDONKEY;
1734 return SO_UNKNOWN;
1738 void CUpDownClient::SetSocket(CClientTCPSocket* socket)
1740 #if defined(__DEBUG__)
1741 if (m_socket == NULL && socket != NULL) {
1742 theStats::SocketAssignedToClient();
1743 } else if (m_socket != NULL && socket == NULL) {
1744 theStats::SocketUnassignedFromClient();
1746 #endif
1747 m_socket = socket;
1751 void CUpDownClient::ReGetClientSoft()
1753 if (m_Username.IsEmpty()) {
1754 m_clientSoft=SO_UNKNOWN;
1755 m_clientVerString = m_clientSoftString = m_clientVersionString = m_fullClientVerString = _("Unknown");
1756 UpdateStats();
1757 return;
1760 int iHashType = GetHashType();
1761 wxString clientModString;
1762 if (iHashType == SO_EMULE) {
1764 m_clientSoft = m_byCompatibleClient;
1765 m_clientSoftString = GetSoftName(m_clientSoft);
1766 // Special issues:
1767 if(!GetClientModString().IsEmpty() && (m_clientSoft != SO_EMULE)) {
1768 m_clientSoftString = GetClientModString();
1770 // Isn't xMule annoying?
1771 if ((m_clientSoft == SO_LXMULE) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
1772 m_clientSoftString += CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion();
1774 if ((m_clientSoft == SO_EMULE) &&
1776 wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
1777 || GetUserName().Find(wxT("xmule.")) != -1
1780 // FAKE eMule -a newer xMule faking is ident.
1781 m_clientSoft = SO_LXMULE;
1782 if (GetClientModString().IsEmpty() == false) {
1783 m_clientSoftString = GetClientModString() + _(" (Fake eMule)");
1784 } else {
1785 m_clientSoftString = _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
1788 // Now, what if we don't know this SO_ID?
1789 if (m_clientSoftString.IsEmpty()) {
1790 if(m_bIsML) {
1791 m_clientSoft = SO_MLDONKEY;
1792 m_clientSoftString = GetSoftName(m_clientSoft);
1793 } else if (m_bIsHybrid) {
1794 m_clientSoft = SO_EDONKEYHYBRID;
1795 m_clientSoftString = GetSoftName(m_clientSoft);
1796 } else if (m_byCompatibleClient != 0) {
1797 m_clientSoft = SO_COMPAT_UNK;
1798 #ifdef __DEBUG__
1799 if (
1800 // Exceptions:
1801 (m_byCompatibleClient != 0xf0) // Chinese leech mod
1802 && (1==1) // Your ad here
1804 AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient);
1806 #endif
1807 m_clientSoftString = CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft) % m_byCompatibleClient;
1808 } else {
1809 // If we step here, it might mean 2 things:
1810 // a eMule
1811 // a Compat Client that has sent no MuleInfo packet yet.
1812 m_clientSoft = SO_EMULE;
1813 m_clientSoftString = wxT("eMule");
1817 if (m_byEmuleVersion == 0) {
1818 m_nClientVersion = MAKE_CLIENT_VERSION(0,0,0);
1819 } else if (m_byEmuleVersion != 0x99) {
1820 uint32 nClientMinVersion = (m_byEmuleVersion >> 4)*10 + (m_byEmuleVersion & 0x0f);
1821 m_nClientVersion = MAKE_CLIENT_VERSION(0,nClientMinVersion,0);
1822 switch (m_clientSoft) {
1823 case SO_AMULE:
1824 m_clientVerString = CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion;
1825 break;
1826 case SO_LPHANT:
1827 m_clientVerString = wxT("< v0.05");
1828 break;
1829 default:
1830 clientModString = GetClientModString();
1831 m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
1832 break;
1834 } else {
1835 uint32 nClientMajVersion = (m_nClientVersion >> 17) & 0x7f;
1836 uint32 nClientMinVersion = (m_nClientVersion >> 10) & 0x7f;
1837 uint32 nClientUpVersion = (m_nClientVersion >> 7) & 0x07;
1839 m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
1841 switch (m_clientSoft) {
1842 case SO_AMULE:
1843 case SO_LXMULE:
1844 case SO_HYDRANODE:
1845 case SO_MLDONKEY:
1846 case SO_NEW_MLDONKEY:
1847 case SO_NEW2_MLDONKEY:
1848 // Kry - xMule started sending correct version tags on 1.9.1b.
1849 // It only took them 4 months, and being told by me and the
1850 // eMule+ developers, so I think they're slowly getting smarter.
1851 // They are based on our implementation, so we use the same format
1852 // for the version string.
1853 m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
1854 break;
1855 case SO_LPHANT:
1856 m_clientVerString = CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion-1) % nClientMinVersion % ('a' + nClientUpVersion);
1857 break;
1858 case SO_EMULEPLUS:
1859 m_clientVerString = CFormat(wxT("v%u")) % nClientMajVersion;
1860 if(nClientMinVersion != 0) {
1861 m_clientVerString += CFormat(wxT(".%u")) % nClientMinVersion;
1863 if(nClientUpVersion != 0) {
1864 m_clientVerString += CFormat(wxT("%c")) % ('a' + nClientUpVersion - 1);
1866 break;
1867 default:
1868 clientModString = GetClientModString();
1869 m_clientVerString = CFormat(wxT("v%u.%u%c")) % nClientMajVersion % nClientMinVersion % ('a' + nClientUpVersion);
1870 break;
1873 } else if (m_bIsHybrid) {
1874 // seen:
1875 // 105010 50.10
1876 // 10501 50.1
1877 // 1051 51.0
1878 // 501 50.1
1880 m_clientSoft = SO_EDONKEYHYBRID;
1881 m_clientSoftString = GetSoftName(m_clientSoft);
1883 uint32 nClientMajVersion;
1884 uint32 nClientMinVersion;
1885 uint32 nClientUpVersion;
1886 if (m_nClientVersion > 100000) {
1887 uint32 uMaj = m_nClientVersion/100000;
1888 nClientMajVersion = uMaj - 1;
1889 nClientMinVersion = (m_nClientVersion - uMaj*100000) / 100;
1890 nClientUpVersion = m_nClientVersion % 100;
1892 else if (m_nClientVersion > 10000) {
1893 uint32 uMaj = m_nClientVersion/10000;
1894 nClientMajVersion = uMaj - 1;
1895 nClientMinVersion = (m_nClientVersion - uMaj*10000) / 10;
1896 nClientUpVersion = m_nClientVersion % 10;
1898 else if (m_nClientVersion > 1000) {
1899 uint32 uMaj = m_nClientVersion/1000;
1900 nClientMajVersion = uMaj - 1;
1901 nClientMinVersion = m_nClientVersion - uMaj*1000;
1902 nClientUpVersion = 0;
1904 else if (m_nClientVersion > 100) {
1905 uint32 uMin = m_nClientVersion/10;
1906 nClientMajVersion = 0;
1907 nClientMinVersion = uMin;
1908 nClientUpVersion = m_nClientVersion - uMin*10;
1910 else{
1911 nClientMajVersion = 0;
1912 nClientMinVersion = m_nClientVersion;
1913 nClientUpVersion = 0;
1915 m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
1916 if (nClientUpVersion) {
1917 m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
1918 } else {
1919 m_clientVerString = CFormat(wxT("v%u.%u")) % nClientMajVersion % nClientMinVersion;
1921 } else if (m_bIsML || (iHashType == SO_MLDONKEY)) {
1922 m_clientSoft = SO_MLDONKEY;
1923 m_clientSoftString = GetSoftName(m_clientSoft);
1924 uint32 nClientMinVersion = m_nClientVersion;
1925 m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
1926 m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
1927 } else if (iHashType == SO_OLDEMULE) {
1928 m_clientSoft = SO_OLDEMULE;
1929 m_clientSoftString = GetSoftName(m_clientSoft);
1930 uint32 nClientMinVersion = m_nClientVersion;
1931 m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
1932 m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
1933 } else {
1934 m_clientSoft = SO_EDONKEY;
1935 m_clientSoftString = GetSoftName(m_clientSoft);
1936 m_nClientVersion *= 10;
1937 m_clientVerString = CFormat(wxT("v%u.%u")) % (m_nClientVersion / 100000) % ((m_nClientVersion / 1000) % 100);
1940 m_clientVersionString = m_clientVerString;
1941 if (!clientModString.IsEmpty()) {
1942 m_clientVerString += wxT(" - ") + clientModString;
1944 m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString;
1946 UpdateStats();
1949 void CUpDownClient::RequestSharedFileList()
1951 if (m_iFileListRequested == 0) {
1952 AddDebugLogLineN( logClient, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
1953 m_iFileListRequested = 1;
1954 TryToConnect(true);
1955 } else {
1956 AddDebugLogLineN( logClient, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
1961 void CUpDownClient::ProcessSharedFileList(const byte* pachPacket, uint32 nSize, wxString& pszDirectory)
1963 if (m_iFileListRequested > 0) {
1964 m_iFileListRequested--;
1965 theApp->searchlist->ProcessSharedFileList(pachPacket, nSize, this, NULL, pszDirectory);
1970 void CUpDownClient::ResetFileStatusInfo()
1972 m_nPartCount = 0;
1974 if ( m_reqfile ) {
1975 m_reqfile->UpdatePartsFrequency( this, false );
1977 m_downPartStatus.clear();
1979 m_clientFilename.Clear();
1981 m_bCompleteSource = false;
1982 m_dwLastAskedTime = 0;
1983 m_iRating = 0;
1984 m_strComment.Clear();
1986 if (m_pReqFileAICHHash != NULL) {
1987 delete m_pReqFileAICHHash;
1988 m_pReqFileAICHHash = NULL;
1993 wxString CUpDownClient::GetUploadFileInfo()
1995 // build info text and display it
1996 wxString sRet;
1997 sRet = (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
1998 if (m_reqfile) {
1999 sRet += CFormat(_("Requested: %s\n")) % m_reqfile->GetFileName();
2000 sRet += CFormat(
2001 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())
2002 ) % m_reqfile->statistic.GetAccepts() % m_reqfile->statistic.GetRequests() % CastItoXBytes(m_reqfile->statistic.GetTransferred());
2003 sRet += CFormat(
2004 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())
2005 ) % m_reqfile->statistic.GetAllTimeAccepts() % m_reqfile->statistic.GetAllTimeRequests() % CastItoXBytes(m_reqfile->statistic.GetAllTimeTransferred());
2006 } else {
2007 sRet += _("Requested unknown file");
2009 return sRet;
2012 // sends a packet, if needed it will establish a connection before
2013 // options used: ignore max connections, control packet, delete packet
2014 // !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
2015 bool CUpDownClient::SafeSendPacket(CPacket* packet)
2017 if (IsConnected()) {
2018 SendPacket(packet, true);
2019 return true;
2020 } else {
2021 m_WaitingPackets_list.push_back(packet);
2022 return TryToConnect(true);
2026 void CUpDownClient::SendPublicKeyPacket(){
2027 // send our public key to the client who requested it
2028 if (m_socket == NULL || credits == NULL || m_SecureIdentState != IS_KEYANDSIGNEEDED){
2029 wxFAIL;
2030 return;
2032 if (!theApp->CryptoAvailable())
2033 return;
2035 CMemFile data;
2036 data.WriteUInt8(theApp->clientcredits->GetPubKeyLen());
2037 data.Write(theApp->clientcredits->GetPublicKey(), theApp->clientcredits->GetPubKeyLen());
2038 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_PUBLICKEY);
2040 theStats::AddUpOverheadOther(packet->GetPacketSize());
2041 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
2042 SendPacket(packet,true,true);
2043 m_SecureIdentState = IS_SIGNATURENEEDED;
2047 void CUpDownClient::SendSignaturePacket(){
2048 // signate the public key of this client and send it
2049 if (m_socket == NULL || credits == NULL || m_SecureIdentState == 0){
2050 wxFAIL;
2051 return;
2054 if (!theApp->CryptoAvailable()) {
2055 return;
2057 if (credits->GetSecIDKeyLen() == 0) {
2058 return; // We don't have his public key yet, will be back here later
2060 // do we have a challenge value received (actually we should if we are in this function)
2061 if (credits->m_dwCryptRndChallengeFrom == 0){
2062 AddDebugLogLineN( logClient, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
2063 return;
2065 // v2
2066 // we will use v1 as default, except if only v2 is supported
2067 bool bUseV2;
2068 if ( (m_bySupportSecIdent&1) == 1 )
2069 bUseV2 = false;
2070 else
2071 bUseV2 = true;
2073 uint8 byChaIPKind = 0;
2074 uint32 ChallengeIP = 0;
2075 if (bUseV2){
2076 if (::IsLowID(theApp->GetED2KID())) {
2077 // we cannot do not know for sure our public ip, so use the remote clients one
2078 ChallengeIP = GetIP();
2079 byChaIPKind = CRYPT_CIP_REMOTECLIENT;
2080 } else {
2081 ChallengeIP = theApp->GetED2KID();
2082 byChaIPKind = CRYPT_CIP_LOCALCLIENT;
2085 //end v2
2086 byte achBuffer[250];
2088 uint8 siglen = theApp->clientcredits->CreateSignature(credits, achBuffer, 250, ChallengeIP, byChaIPKind );
2089 if (siglen == 0){
2090 wxFAIL;
2091 return;
2093 CMemFile data;
2094 data.WriteUInt8(siglen);
2095 data.Write(achBuffer, siglen);
2096 if (bUseV2) {
2097 data.WriteUInt8(byChaIPKind);
2100 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SIGNATURE);
2102 theStats::AddUpOverheadOther(packet->GetPacketSize());
2103 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
2104 SendPacket(packet,true,true);
2105 m_SecureIdentState = IS_ALLREQUESTSSEND;
2109 void CUpDownClient::ProcessPublicKeyPacket(const byte* pachPacket, uint32 nSize)
2111 theApp->clientlist->AddTrackClient(this);
2113 if (m_socket == NULL || credits == NULL || pachPacket[0] != nSize-1
2114 || nSize == 0 || nSize > 250){
2115 wxFAIL;
2116 return;
2118 if (!theApp->CryptoAvailable())
2119 return;
2120 // the function will handle everything (mulitple key etc)
2121 if (credits->SetSecureIdent(pachPacket+1, pachPacket[0])){
2122 // if this client wants a signature, now we can send him one
2123 if (m_SecureIdentState == IS_SIGNATURENEEDED){
2124 SendSignaturePacket();
2126 else if (m_SecureIdentState == IS_KEYANDSIGNEEDED) {
2127 // something is wrong
2128 AddDebugLogLineN( logClient, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
2130 } else {
2131 AddDebugLogLineN( logClient, wxT("Failed to use new received public key") );
2136 void CUpDownClient::ProcessSignaturePacket(const byte* pachPacket, uint32 nSize)
2138 // here we spread the good guys from the bad ones ;)
2140 if (m_socket == NULL || credits == NULL || nSize == 0 || nSize > 250){
2141 wxFAIL;
2142 return;
2145 uint8 byChaIPKind;
2146 if (pachPacket[0] == nSize-1)
2147 byChaIPKind = 0;
2148 else if (pachPacket[0] == nSize-2 && (m_bySupportSecIdent & 2) > 0) //v2
2149 byChaIPKind = pachPacket[nSize-1];
2150 else{
2151 wxFAIL;
2152 return;
2155 if (!theApp->CryptoAvailable())
2156 return;
2158 // we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
2159 if (m_dwLastSignatureIP == GetIP()){
2160 AddDebugLogLineN( logClient, wxT("received multiple signatures from one client") );
2161 return;
2163 // also make sure this client has a public key
2164 if (credits->GetSecIDKeyLen() == 0){
2165 AddDebugLogLineN( logClient, wxT("received signature for client without public key") );
2166 return;
2168 // and one more check: did we ask for a signature and sent a challange packet?
2169 if (credits->m_dwCryptRndChallengeFor == 0){
2170 AddDebugLogLineN( logClient, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
2171 return;
2174 if (theApp->clientcredits->VerifyIdent(credits, pachPacket+1, pachPacket[0], GetIP(), byChaIPKind ) ) {
2175 // result is saved in function above
2176 AddDebugLogLineN( logClient, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
2177 } else {
2178 AddDebugLogLineN( logClient, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
2181 m_dwLastSignatureIP = GetIP();
2184 void CUpDownClient::SendSecIdentStatePacket(){
2185 // check if we need public key and signature
2186 uint8 nValue = 0;
2187 if (credits){
2188 if (theApp->CryptoAvailable()){
2189 if (credits->GetSecIDKeyLen() == 0) {
2190 nValue = IS_KEYANDSIGNEEDED;
2191 } else if (m_dwLastSignatureIP != GetIP()) {
2192 nValue = IS_SIGNATURENEEDED;
2195 if (nValue == 0){
2196 AddDebugLogLineN( logClient, wxT("Not sending SecIdentState Packet, because State is Zero") );
2197 return;
2199 // crypt: send random data to sign
2200 uint32 dwRandom = rand()+1;
2201 credits->m_dwCryptRndChallengeFor = dwRandom;
2203 CMemFile data;
2204 data.WriteUInt8(nValue);
2205 data.WriteUInt32(dwRandom);
2206 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SECIDENTSTATE);
2208 theStats::AddUpOverheadOther(packet->GetPacketSize());
2209 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
2210 SendPacket(packet,true,true);
2211 } else {
2212 wxFAIL;
2217 void CUpDownClient::ProcessSecIdentStatePacket(const byte* pachPacket, uint32 nSize)
2219 if ( nSize != 5 ) {
2220 return;
2223 if ( !credits ) {
2224 wxASSERT( credits );
2225 return;
2228 CMemFile data(pachPacket,nSize);
2230 switch ( data.ReadUInt8() ) {
2231 case 0:
2232 m_SecureIdentState = IS_UNAVAILABLE;
2233 break;
2234 case 1:
2235 m_SecureIdentState = IS_SIGNATURENEEDED;
2236 break;
2237 case 2:
2238 m_SecureIdentState = IS_KEYANDSIGNEEDED;
2239 break;
2240 default:
2241 return;
2244 credits->m_dwCryptRndChallengeFrom = data.ReadUInt32();
2248 void CUpDownClient::InfoPacketsReceived()
2250 // indicates that both Information Packets has been received
2251 // needed for actions, which process data from both packets
2252 wxASSERT ( m_byInfopacketsReceived == IP_BOTH );
2253 m_byInfopacketsReceived = IP_NONE;
2255 if (m_bySupportSecIdent){
2256 SendSecIdentStatePacket();
2261 bool CUpDownClient::CheckHandshakeFinished() const
2263 if (m_bHelloAnswerPending) {
2264 // this triggers way too often.. need more time to look at this -> only create a warning
2265 // The reason for this is that 2 clients are connecting to each other at the same time..
2266 AddDebugLogLineN( logClient, wxT("Handshake not finished while processing packet.") );
2267 return false;
2270 return true;
2274 wxString CUpDownClient::GetClientFullInfo()
2276 if (m_clientVerString.IsEmpty()) {
2277 ReGetClientSoft();
2280 return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") )
2281 % ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
2282 % GetFullIP()
2283 % GetUserPort()
2284 % m_clientSoftString
2285 % m_clientVerString
2286 % m_strModVersion;
2290 wxString CUpDownClient::GetClientShortInfo()
2292 if (m_clientVerString.IsEmpty()) {
2293 ReGetClientSoft();
2296 return CFormat( wxT("'%s' (%s %s %s)") )
2297 % ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
2298 % m_clientSoftString
2299 % m_clientVerString
2300 % m_strModVersion;
2304 void CUpDownClient::SendPublicIPRequest()
2306 if (IsConnected()){
2307 CPacket* packet = new CPacket(OP_PUBLICIP_REQ,0,OP_EMULEPROT);
2308 theStats::AddUpOverheadOther(packet->GetPacketSize());
2309 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICIP_REQ to ") + GetFullIP());
2310 SendPacket(packet,true);
2311 m_fNeedOurPublicIP = true;
2315 void CUpDownClient::ProcessPublicIPAnswer(const byte* pbyData, uint32 uSize)
2317 if (uSize != 4) {
2318 throw wxString(wxT("Wrong Packet size on Public IP answer"));
2320 uint32 dwIP = PeekUInt32(pbyData);
2321 if (m_fNeedOurPublicIP == true){ // did we?
2322 m_fNeedOurPublicIP = false;
2323 // Ignore local ip on GetPublicIP (could be wrong)
2324 if (theApp->GetPublicIP(true) == 0 && !IsLowID(dwIP) ) {
2325 theApp->SetPublicIP(dwIP);
2331 bool CUpDownClient::IsConnected() const
2333 return m_socket && m_socket->IsConnected();
2336 bool CUpDownClient::SendPacket(CPacket* packet, bool delpacket, bool controlpacket)
2338 if ( m_socket ) {
2339 m_socket->SendPacket(packet, delpacket, controlpacket );
2340 return true;
2341 } else {
2342 AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()"));
2343 return false;
2347 float CUpDownClient::SetDownloadLimit(uint32 reducedownload)
2349 // lfroen: in daemon it actually can happen
2350 wxASSERT( m_socket );
2352 float kBpsClient = CalculateKBpsDown();
2354 if ( m_socket ) {
2356 if (reducedownload) {
2357 // (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD)
2358 // which is how often it is called per second.
2359 uint32 limit = (uint32)(reducedownload * kBpsClient * 1024.0 / 100000.0 * CORE_TIMER_PERIOD);
2361 if(limit<1024 && reducedownload >= 200) {
2362 // If we're going up and this download is < 1kB,
2363 // we want it to go up fast. Can be reduced later,
2364 // and it'll probably be in a more fair way with
2365 // other downloads that are faster.
2366 limit +=1024;
2367 } else if(limit == 0) {
2368 // This download is not transferring yet... make it
2369 // 1024 so we don't fill the TCP stack and lose the
2370 // connection.
2371 limit = 1024;
2374 m_socket->SetDownloadLimit(limit);
2375 } else {
2376 m_socket->DisableDownloadLimit();
2379 } else {
2380 AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient);
2383 return kBpsClient;
2386 void CUpDownClient::SetUserIDHybrid(uint32 nUserID)
2388 theApp->clientlist->UpdateClientID( this, nUserID );
2390 m_nUserIDHybrid = nUserID;
2394 void CUpDownClient::SetIP( uint32 val )
2396 theApp->clientlist->UpdateClientIP( this, val );
2398 m_dwUserIP = val;
2400 m_nConnectIP = val;
2402 m_FullUserIP = val;
2406 void CUpDownClient::SetUserHash(const CMD4Hash& userhash)
2408 theApp->clientlist->UpdateClientHash( this, userhash );
2410 m_UserHash = userhash;
2412 ValidateHash();
2415 EUtf8Str CUpDownClient::GetUnicodeSupport() const
2417 return m_bUnicodeSupport ? utf8strRaw : utf8strNone;
2420 void CUpDownClient::SetSpammer(bool bVal)
2422 if (bVal) {
2423 Ban();
2424 } else if (IsBanned() && m_fIsSpammer) {
2425 UnBan();
2427 m_fIsSpammer = bVal;
2430 uint8 CUpDownClient::GetSecureIdentState()
2432 if (m_SecureIdentState != IS_UNAVAILABLE) {
2433 if (!SecIdentSupRec) {
2434 // This can be caused by a 0.30x based client which sends the old
2435 // style Hello packet, and the mule info packet, but between them they
2436 // send a secure ident state packet (after a hello but before we have
2437 // the SUI capabilities). This is a misbehaving client, and somehow I
2438 // feel like it should be dropped. But then again, it won't harm to use
2439 // this SUI state if they are reporting no SUI (won't be used) and if
2440 // they report using SUI on the mule info packet, it's ok to use it.
2442 AddDebugLogLineN(logClient, wxT("A client sent secure ident state before telling us the SUI capabilities"));
2443 AddDebugLogLineN(logClient, wxT("Client info: ") + GetClientFullInfo());
2444 AddDebugLogLineN(logClient, wxT("This client won't be disconnected, but it should be. :P"));
2448 return m_SecureIdentState;
2452 bool CUpDownClient::SendChatMessage(const wxString& message)
2454 if (GetChatCaptchaState() == CA_CAPTCHARECV) {
2455 m_nChatCaptchaState = CA_SOLUTIONSENT;
2456 } else if (GetChatCaptchaState() == CA_SOLUTIONSENT) {
2457 wxFAIL; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through
2458 } else {
2459 m_nChatCaptchaState = CA_ACCEPTING;
2462 SetSpammer(false);
2463 IncMessagesSent();
2464 // Already connecting?
2465 if (GetChatState() == MS_CONNECTING) {
2466 // Queue all messages till we're able to send them (or discard them)
2467 if (!m_pendingMessage.IsEmpty()) {
2468 m_pendingMessage += wxT("\n");
2469 } else {
2470 // There must be a message to send
2471 // - except if we got disconnected. No need to assert therefore.
2473 m_pendingMessage += message;
2474 return false;
2476 if (IsConnected()) {
2477 // If we are already connected when we send the first message,
2478 // we have to update the chat status.
2479 SetChatState(MS_CHATTING);
2480 CMemFile data;
2481 data.WriteString(message, GetUnicodeSupport());
2482 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_MESSAGE);
2483 theStats::AddUpOverheadOther(packet->GetPacketSize());
2484 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
2485 SendPacket(packet, true, true);
2486 return true;
2487 } else {
2488 m_pendingMessage = message;
2489 SetChatState(MS_CONNECTING);
2490 // True to ignore "Too Many Connections"
2491 TryToConnect(true);
2492 return false;
2496 /* Kad stuff */
2498 void CUpDownClient::SetBuddyID(const byte* pucBuddyID)
2500 if( pucBuddyID == NULL ){
2501 md4clr(m_achBuddyID);
2502 m_bBuddyIDValid = false;
2503 return;
2505 m_bBuddyIDValid = true;
2506 md4cpy(m_achBuddyID, pucBuddyID);
2509 // Kad added by me
2511 bool CUpDownClient::SendBuddyPing() {
2512 SetLastBuddyPingPongTime();
2513 CPacket* buddyPing = new CPacket(OP_BUDDYPING, 0, OP_EMULEPROT);
2514 theStats::AddUpOverheadKad(buddyPing->GetPacketSize());
2515 AddDebugLogLineN(logLocalClient,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
2516 return SafeSendPacket(buddyPing);
2520 /* Statistics */
2522 void CUpDownClient::UpdateStats()
2524 if (m_lastClientSoft != m_clientSoft || m_lastClientVersion != m_nClientVersion || m_lastOSInfo != m_sClientOSInfo) {
2525 if (m_lastClientSoft == SO_UNKNOWN) {
2526 theStats::RemoveUnknownClient();
2527 } else if (m_lastClientSoft != (uint32)(-1)) {
2528 theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
2531 m_lastClientSoft = m_clientSoft;
2532 m_lastClientVersion = m_nClientVersion;
2533 m_lastOSInfo = m_sClientOSInfo;
2535 if (m_clientSoft == SO_UNKNOWN) {
2536 theStats::AddUnknownClient();
2537 } else {
2538 theStats::AddKnownClient(this);
2543 bool CUpDownClient::IsIdentified() const
2545 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED);
2548 bool CUpDownClient::IsBadGuy() const
2550 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDBADGUY);
2553 bool CUpDownClient::SUIFailed() const
2555 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDFAILED);
2558 bool CUpDownClient::SUINeeded() const
2560 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDNEEDED);
2563 bool CUpDownClient::SUINotSupported() const
2565 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE);
2568 uint64 CUpDownClient::GetDownloadedTotal() const
2570 return credits ? credits->GetDownloadedTotal() : 0;
2573 uint64 CUpDownClient::GetUploadedTotal() const
2575 return credits ? credits->GetUploadedTotal() : 0;
2578 double CUpDownClient::GetScoreRatio() const
2580 return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0;
2583 const wxString CUpDownClient::GetServerName() const
2585 wxString ret;
2586 wxString srvaddr = Uint32toStringIP(GetServerIP());
2587 CServer* cserver = theApp->serverlist->GetServerByAddress(
2588 srvaddr, GetServerPort());
2589 if (cserver) {
2590 ret = cserver->GetListName();
2591 } else {
2592 ret = _("Unknown");
2595 return ret;
2598 bool CUpDownClient::ShouldReceiveCryptUDPPackets() const
2600 return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp->GetPublicIP() != 0
2601 && HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) );
2604 #ifdef AMULE_DAEMON
2606 void CUpDownClient::ProcessCaptchaRequest(CMemFile* WXUNUSED(data)) {}
2607 void CUpDownClient::ProcessCaptchaReqRes(uint8 WXUNUSED(nStatus)) {}
2608 void CUpDownClient::ProcessChatMessage(const wxString WXUNUSED(message)) {}
2610 #else
2612 void CUpDownClient::ProcessCaptchaRequest(CMemFile* data)
2614 uint64 id = GUI_ID(GetIP(),GetUserPort());
2615 // received a captcha request, check if we actually accept it (only after sending a message ourself to this client)
2616 if (GetChatCaptchaState() == CA_ACCEPTING && GetChatState() != MS_NONE
2617 && theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
2618 // read tags (for future use)
2619 uint8 nTagCount = data->ReadUInt8();
2620 if (nTagCount) {
2621 AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount);
2622 // and ignore them for now
2623 for (uint32 i = 0; i < nTagCount; i++) {
2624 CTag tag(*data, true);
2628 // sanitize checks - we want a small captcha not a wallpaper
2629 uint32 nSize = (uint32)(data->GetLength() - data->GetPosition());
2631 if ( nSize > 128 && nSize < 4096 ) {
2632 uint64 pos = data->GetPosition();
2633 wxMemoryInputStream memstr(data->GetRawBuffer() + pos, nSize);
2634 wxImage imgCaptcha(memstr, wxBITMAP_TYPE_BMP);
2636 if (imgCaptcha.IsOk() && imgCaptcha.GetHeight() > 10 && imgCaptcha.GetHeight() < 50
2637 && imgCaptcha.GetWidth() > 10 && imgCaptcha.GetWidth() < 150 ) {
2638 m_nChatCaptchaState = CA_CAPTCHARECV;
2639 CCaptchaDialog * dialog = new CCaptchaDialog(theApp->amuledlg, imgCaptcha, id);
2640 dialog->Show();
2642 } else {
2643 AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP());
2645 } else {
2646 AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize % GetFullIP());
2648 } else {
2649 AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP());
2653 void CUpDownClient::ProcessCaptchaReqRes(uint8 nStatus)
2655 uint64 id = GUI_ID(GetIP(),GetUserPort());
2656 if (GetChatCaptchaState() == CA_SOLUTIONSENT && GetChatState() != MS_NONE
2657 && theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
2658 wxASSERT( nStatus < 3 );
2659 m_nChatCaptchaState = CA_NONE;
2660 theApp->amuledlg->m_chatwnd->ShowCaptchaResult(id, nStatus == 0);
2661 } else {
2662 m_nChatCaptchaState = CA_NONE;
2663 AddDebugLogLineN(logClient, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP());
2667 void CUpDownClient::ProcessChatMessage(wxString message)
2669 if (IsMessageFiltered(message)) {
2670 AddLogLineC(CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP());
2671 return;
2674 // advanced spamfilter check
2675 if (thePrefs::IsChatCaptchaEnabled() && !IsFriend()) {
2676 // captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam
2677 // first check if we need to send a captcha request to this client
2678 if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED) {
2679 // we have never sent a message to this client, and no message from him has ever passed our filters
2680 if (GetChatCaptchaState() != CA_CHALLENGESENT) {
2681 // we also aren't currently expecting a captcha response
2682 if (m_fSupportsCaptcha) {
2683 // and he supports captcha, so send him one and store the message (without showing for now)
2684 if (m_cCaptchasSent < 3) { // no more than 3 tries
2685 m_strCaptchaPendingMsg = message;
2686 wxMemoryOutputStream memstr;
2687 memstr.PutC(0); // no tags, for future use
2688 CCaptchaGenerator captcha(4);
2689 if (captcha.WriteCaptchaImage(memstr)){
2690 m_strCaptchaChallenge = captcha.GetCaptchaText();
2691 m_nChatCaptchaState = CA_CHALLENGESENT;
2692 m_cCaptchasSent++;
2693 CMemFile fileAnswer((byte*) memstr.GetOutputStreamBuffer()->GetBufferStart(), memstr.GetLength());
2694 CPacket* packet = new CPacket(fileAnswer, OP_EMULEPROT, OP_CHATCAPTCHAREQ);
2695 theStats::AddUpOverheadOther(packet->GetPacketSize());
2696 AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % m_strCaptchaChallenge % packet->GetPacketSize());
2697 SafeSendPacket(packet);
2698 } else {
2699 wxFAIL;
2702 } else {
2703 // client doesn't support captchas, but we require them, tell him that it's not going to work out
2704 // with an answer message (will not be shown and doesn't count as sent message)
2705 if (m_cCaptchasSent < 1) { // don't send this notifier more than once
2706 m_cCaptchasSent++;
2707 // always sent in english
2708 SendChatMessage(wxT("In order to avoid spam messages, this user requires you to solve a captcha before you can send a message to him. However your client does not supports captchas, so you will not be able to chat with this user."));
2709 AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo());
2710 } else {
2711 AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo());
2714 return;
2715 } else { // (GetChatCaptchaState() == CA_CHALLENGESENT)
2716 // this message must be the answer to the captcha request we sent him, let's verify
2717 wxASSERT( !m_strCaptchaChallenge.IsEmpty() );
2718 if (m_strCaptchaChallenge.CmpNoCase(message.Trim().Right(std::min(message.Length(), m_strCaptchaChallenge.Length()))) == 0) {
2719 // allright
2720 AddDebugLogLineN(logClient, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo());
2721 m_nChatCaptchaState = CA_CAPTCHASOLVED; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved
2722 // replace captchaanswer with withheld message and show it
2723 message = m_strCaptchaPendingMsg;
2724 m_cCaptchasSent = 0;
2725 m_strCaptchaChallenge = wxEmptyString;
2726 CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
2727 byte statusResponse = 0; // status response
2728 packet->CopyToDataBuffer(0, &statusResponse, 1);
2729 theStats::AddUpOverheadOther(packet->GetPacketSize());
2730 SafeSendPacket(packet);
2731 } else { // wrong, cleanup and ignore
2732 AddDebugLogLineN(logClient, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo());
2733 m_nChatCaptchaState = CA_NONE;
2734 m_strCaptchaChallenge = wxEmptyString;
2735 m_strCaptchaPendingMsg = wxEmptyString;
2736 CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
2737 byte statusResponse = (m_cCaptchasSent < 3) ? 1 : 2; // status response
2738 packet->CopyToDataBuffer(0, &statusResponse, 1);
2739 theStats::AddUpOverheadOther(packet->GetPacketSize());
2740 SafeSendPacket(packet);
2741 return; // nothing more todo
2747 if (thePrefs::IsAdvancedSpamfilterEnabled() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P )
2748 bool bIsSpam = false;
2749 if (m_fIsSpammer) {
2750 bIsSpam = true;
2751 } else {
2752 // first fixed criteria: If a client sends me an URL in his first message before I respond to him
2753 // there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P
2754 if (GetMessagesSent() == 0) {
2755 static wxArrayString urlindicators(wxStringTokenize(wxT("http:|www.|.de |.net |.com |.org |.to |.tk |.cc |.fr |ftp:|ed2k:|https:|ftp.|.info|.biz|.uk|.eu|.es|.tv|.cn|.tw|.ws|.nu|.jp"), wxT("|")));
2756 for (size_t pos = urlindicators.GetCount(); pos--;) {
2757 if (message.Find(urlindicators[pos]) != wxNOT_FOUND) {
2758 bIsSpam = true;
2759 break;
2762 // second fixed criteria: he sent me 4 or more messages and I didn't answer him once
2763 if (GetMessagesReceived() > 3) {
2764 bIsSpam = true;
2768 if (bIsSpam) {
2769 AddDebugLogLineN(logClient, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName());
2770 SetSpammer(true);
2771 theApp->amuledlg->m_chatwnd->EndSession(GUI_ID(GetIP(),GetUserPort()));
2772 return;
2777 wxString logMsg = CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP();
2778 if(thePrefs::ShowMessagesInLog()) {
2779 logMsg += wxT(": ") + message;
2781 AddLogLineC(logMsg);
2782 IncMessagesReceived();
2784 Notify_ChatProcessMsg(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message);
2787 bool CUpDownClient::IsMessageFiltered(const wxString& message)
2789 bool filtered = false;
2790 // If we're chatting to the guy, we don't want to filter!
2791 if (GetChatState() != MS_CHATTING) {
2792 if (thePrefs::MsgOnlyFriends() && !IsFriend()) {
2793 filtered = true;
2794 } else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) {
2795 filtered = true;
2796 } else if (thePrefs::MustFilterMessages()) {
2797 filtered = thePrefs::IsMessageFiltered(message);
2800 if (filtered) {
2801 SetSpammer(true);
2803 return filtered;
2806 #endif
2809 void CUpDownClient::SendFirewallCheckUDPRequest()
2811 wxASSERT(GetKadState() == KS_FWCHECK_UDP);
2813 if (!Kademlia::CKademlia::IsRunning()) {
2814 SetKadState(KS_NONE);
2815 return;
2816 } else if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE || GetKadVersion() <= 5 || GetKadPort() == 0) {
2817 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
2818 SetKadState(KS_NONE);
2819 return;
2822 CMemFile data;
2823 data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
2824 data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
2825 data.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
2826 CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_FWCHECKUDPREQ);
2827 theStats::AddUpOverheadKad(packet->GetPacketSize());
2828 SafeSendPacket(packet);
2831 void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile* data)
2833 if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL) {
2834 //DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
2835 return;
2838 // first search if we know this IP already, if so the result might be biased and we need tell the requester
2839 bool errorAlreadyKnown = false;
2840 if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE) {
2841 errorAlreadyKnown = true;
2842 } else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL) {
2843 errorAlreadyKnown = true;
2846 uint16_t remoteInternPort = data->ReadUInt16();
2847 uint16_t remoteExternPort = data->ReadUInt16();
2848 uint32_t senderKey = data->ReadUInt32();
2849 if (remoteInternPort == 0) {
2850 //DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
2851 return;
2853 // if (senderKey == 0)
2854 // DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
2856 CMemFile testPacket1;
2857 testPacket1.WriteUInt8(errorAlreadyKnown ? 1 : 0);
2858 testPacket1.WriteUInt16(remoteInternPort);
2859 DebugSend(Kad2FirewallUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort);
2860 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
2862 // if the client has a router with PAT (and therefore a different extern port than intern), test this port too
2863 if (remoteExternPort != 0 && remoteExternPort != remoteInternPort) {
2864 CMemFile testPacket2;
2865 testPacket2.WriteUInt8(errorAlreadyKnown ? 1 : 0);
2866 testPacket2.WriteUInt16(remoteExternPort);
2867 DebugSend(Kad2FirewalledUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort);
2868 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
2870 //DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
2873 void CUpDownClient::SetConnectOptions(uint8_t options, bool encryption, bool callback)
2875 SetCryptLayerSupport((options & 0x01) != 0 && encryption);
2876 SetCryptLayerRequest((options & 0x02) != 0 && encryption);
2877 SetCryptLayerRequires((options & 0x04) != 0 && encryption);
2878 SetDirectUDPCallbackSupport((options & 0x08) != 0 && callback);
2880 // File_checked_for_headers