2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
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
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
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"
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
)
108 CUpDownClient::CUpDownClient(uint16 in_port
, uint32 in_userid
, uint32 in_serverip
, uint16 in_serverport
, CPartFile
* in_reqfile
, bool ed2kID
, bool checkfriend
)
112 m_nUserPort
= in_port
;
114 if(ed2kID
&& !IsLowID(in_userid
)) {
115 SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid
) );
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
125 m_nConnectIP
= in_userid
;
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
);
139 if ((m_Friend
= theApp
->friendlist
->FindFriend(CMD4Hash(), m_dwUserIP
, m_nUserPort
)) != NULL
){
140 m_Friend
->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::CUpDownClient m_Friend->LinkClient")));
142 // avoid that an unwanted client instance keeps a friend slot
143 m_bFriendSlot
= false;
149 void CUpDownClient::Init()
152 #ifdef DEBUG_ZOMBIE_CLIENTS
153 m_linkedDebug
= false;
155 m_bAddNextConnect
= false;
157 m_byChatstate
= MS_NONE
;
158 m_nKadState
= KS_NONE
;
159 m_nChatCaptchaState
= CA_NONE
;
161 m_reqfile
= NULL
; // No file required yet
162 m_nTransferredUp
= 0;
167 bytesReceivedCycle
= 0;
169 m_iFileListRequested
= 0;
170 m_dwLastUpRequest
= 0;
171 m_bEmuleProtocol
= false;
172 m_bCompleteSource
= false;
173 m_bFriendSlot
= false;
174 m_bCommentDirty
= false;
175 m_bReaskPending
= false;
176 m_bUDPPending
= false;
179 m_dwLastAskedTime
= 0;
180 m_nDownloadState
= DS_NONE
;
182 m_nTransferredDown
= 0;
183 m_nUploadState
= US_NONE
;
184 m_dwLastBlockReceived
= 0;
185 m_bUnicodeSupport
= false;
187 m_fSentOutOfPartReqs
= 0;
188 m_nCurQueueSessionPayloadUp
= 0;
189 m_addedPayloadQueueSession
= 0;
191 m_nSumForAvgUpDataRate
= 0;
193 m_nRemoteQueueRank
= 0;
194 m_nOldRemoteQueueRank
= 0;
195 m_dwLastSourceRequest
= 0;
196 m_dwLastSourceAnswer
= 0;
197 m_dwLastAskedForSources
= 0;
199 m_SecureIdentState
= IS_UNAVAILABLE
;
200 m_dwLastSignatureIP
= 0;
202 m_byInfopacketsReceived
= IP_NONE
;
209 m_clientSoft
=SO_UNKNOWN
;
211 m_bRemoteQueueFull
= false;
212 m_HasValidHash
= false;
215 m_fHashsetRequesting
= 0;
216 m_fSharedDirectories
= 0;
217 m_lastPartAsked
= 0xffff;
218 m_nUpCompleteSourcesCount
= 0;
219 m_waitingPosition
= 0;
221 m_lastRefreshedDLDisplay
= 0;
222 m_bHelloAnswerPending
= false;
223 m_fSentCancelTransfer
= 0;
224 m_Aggressiveness
= 0;
225 m_LastFileRequest
= 0;
227 m_clientState
= CS_NEW
;
229 ClearHelloProperties();
231 m_pReqFileAICHHash
= NULL
;
233 m_fAICHRequested
= 0;
234 m_fSupportsLargeFiles
= 0;
235 m_fExtMultiPacket
= 0;
242 m_fNeedOurPublicIP
= false;
243 m_bHashsetRequested
= false;
245 m_lastDownloadingPart
= 0;
247 m_uploadingfile
= NULL
;
249 m_OSInfo_sent
= false;
257 m_nSourceFrom
= SF_NONE
;
260 amuleIPV4Address address
;
261 m_socket
->GetPeer(address
);
262 SetIP(StringIPtoUint32(address
.IPAddress()));
268 m_lastClientSoft
= (uint32
)(-1);
269 m_lastClientVersion
= 0;
271 /* Creation time (for buddies timeout) */
272 m_nCreationTime
= ::GetTickCount();
274 m_MaxBlockRequests
= STANDARD_BLOCKS_REQUEST
; // Safe starting amount
276 m_last_block_start
= 0;
279 SetLastBuddyPingPongTime();
280 m_fRequestsCryptLayer
= 0;
281 m_fSupportsCryptLayer
= 0;
282 m_fRequiresCryptLayer
= 0;
283 m_fSupportsSourceEx2
= 0;
284 m_fSupportsCaptcha
= 0;
285 m_fDirectUDPCallback
= 0;
286 m_dwDirectCallbackTimeout
= 0;
288 m_hasbeenobfuscatinglately
= false;
291 m_cMessagesReceived
= 0;
297 CUpDownClient::~CUpDownClient()
300 if (!connection_reason
.IsEmpty()) {
301 AddDebugLogLineN(logClient
, wxT("Client to check for ") + connection_reason
+ wxT(" was deleted without connection."));
306 if (m_lastClientSoft
== SO_UNKNOWN
) {
307 theStats::RemoveUnknownClient();
308 } else if (m_lastClientSoft
!= (uint32
)(-1)) {
309 theStats::RemoveKnownClient(m_lastClientSoft
, m_lastClientVersion
, m_lastOSInfo
);
312 // Indicate that we are not anymore on stats
313 m_lastClientSoft
= (uint32
)(-1);
315 // The socket should have been removed in Safe_Delete, but it
316 // doesn't hurt to have an extra check.
318 m_socket
->Safe_Delete();
323 ClearUploadBlockRequests();
324 ClearDownloadBlockRequests();
326 DeleteContents(m_WaitingPackets_list
);
328 // Allow detection of deleted clients that didn't go through Safe_Delete
329 m_clientState
= CS_DYING
;
333 void CUpDownClient::ClearHelloProperties()
338 m_byEmuleVersion
= 0;
339 m_bySourceExchange1Ver
= 0;
340 m_byAcceptCommentVer
= 0;
341 m_byExtendedRequestsVer
= 0;
342 m_byCompatibleClient
= 0;
344 m_bySupportSecIdent
= 0;
345 m_bSupportsPreview
= 0;
346 m_nClientVersion
= 0;
347 m_fSharedDirectories
= 0;
349 m_fOsInfoSupport
= 0;
350 m_fValueBasedTypeTags
= 0;
353 m_fRequestsCryptLayer
= 0;
354 m_fSupportsCryptLayer
= 0;
355 m_fRequiresCryptLayer
= 0;
356 m_fSupportsSourceEx2
= 0;
357 m_fSupportsCaptcha
= 0;
358 m_fDirectUDPCallback
= 0;
361 bool CUpDownClient::ProcessHelloPacket(const byte
* pachPacket
, uint32 nSize
)
363 const CMemFile
data(pachPacket
,nSize
);
364 uint8 hashsize
= data
.ReadUInt8();
365 if ( 16 != hashsize
) {
367 * Hint: We can not accept other sizes here because:
368 * - the magic number is spread all over the source
369 * - the answer packet lacks the size field
371 throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
373 // eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
374 ClearHelloProperties();
376 return ProcessHelloTypePacket(data
);
379 void CUpDownClient::Safe_Delete()
381 // Because we are delaying the deletion, we might end up trying to delete
382 // it twice, however, this is normal and shouldn't trigger any failures
383 if ( m_clientState
== CS_DYING
) {
387 // If called from background, post an event to process it in main thread
388 if (!wxThread::IsMain()) {
389 CoreNotify_Client_Delete(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete CoreNotify_Client_Delete")));
393 m_clientState
= CS_DYING
;
395 // Make sure client doesn't get deleted until this method is finished
396 CClientRef
ref(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete reflocker")));
398 // Close the socket to avoid any more connections and related events
400 m_socket
->Safe_Delete();
405 // Remove the client from the clientlist if we still have it
406 if ( theApp
->clientlist
) {
407 theApp
->clientlist
->RemoveClient( this );
410 // Doing what RemoveClient used to do. Just to be sure...
411 if (theApp
->uploadqueue
) {
412 theApp
->uploadqueue
->RemoveFromUploadQueue(this);
413 theApp
->uploadqueue
->RemoveFromWaitingQueue(this);
415 if (theApp
->downloadqueue
) {
416 theApp
->downloadqueue
->RemoveSource(this);
419 // For security, remove it from the lists unconditionally.
420 Notify_SharedCtrlRemoveClient(ECID(), (CKnownFile
*)NULL
);
421 Notify_SourceCtrlRemoveSource(ECID(), (CPartFile
*)NULL
);
423 if (IsAICHReqPending()){
424 m_fAICHRequested
= FALSE
;
425 CAICHHashSet::ClientAICHRequestFailed(this);
429 m_Friend
->UnLinkClient(); // this notifies
433 if (m_iRating
>0 || !m_strComment
.IsEmpty()) {
435 m_strComment
.Clear();
437 m_reqfile
->UpdateFileRatingCommentAvail();
441 // Ensure that source-counts gets updated in case
442 // of a source not on the download-queue
443 SetRequestFile( NULL
);
445 SetUploadFileID(NULL
);
447 delete m_pReqFileAICHHash
;
448 m_pReqFileAICHHash
= NULL
;
450 #ifdef DEBUG_ZOMBIE_CLIENTS
452 AddLogLineC(CFormat(wxT("Client %d still linked in %d places: %s")) % ECID() % (m_linked
- 1) % GetLinkedFrom());
453 m_linkedDebug
= true;
459 bool CUpDownClient::ProcessHelloAnswer(const byte
* pachPacket
, uint32 nSize
)
461 const CMemFile
data(pachPacket
,nSize
);
462 bool bIsMule
= ProcessHelloTypePacket(data
);
463 m_bHelloAnswerPending
= false;
467 bool CUpDownClient::ProcessHelloTypePacket(const CMemFile
& data
)
472 m_fNoViewSharedFiles
= 0;
473 m_bUnicodeSupport
= false;
474 uint32 dwEmuleTags
= 0;
476 CMD4Hash hash
= data
.ReadHash();
478 SetUserIDHybrid( data
.ReadUInt32() );
479 uint16 nUserPort
= data
.ReadUInt16(); // hmm clientport is sent twice - why?
480 uint32 tagcount
= data
.ReadUInt32();
481 for (uint32 i
= 0;i
< tagcount
; i
++){
482 CTag
temptag(data
, true);
483 switch(temptag
.GetNameID()){
485 m_Username
= temptag
.GetStr();
489 m_nClientVersion
= temptag
.GetInt();
493 if (temptag
.IsStr()) {
494 m_strModVersion
= temptag
.GetStr();
495 } else if (temptag
.IsInt()) {
496 m_strModVersion
= CFormat(wxT("ModID=%u")) % temptag
.GetInt();
498 m_strModVersion
= wxT("ModID=<Unknown>");
504 nUserPort
= temptag
.GetInt();
507 case CT_EMULE_UDPPORTS
:
510 SetKadPort((temptag
.GetInt() >> 16) & 0xFFFF);
511 m_nUDPPort
= temptag
.GetInt() & 0xFFFF;
513 #ifdef __PACKET_DEBUG__
514 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort
% m_nKadPort
);
518 case CT_EMULE_BUDDYIP
:
520 m_nBuddyIP
= temptag
.GetInt();
521 #ifdef __PACKET_DEBUG__
522 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP
% Uint32toStringIP(m_nBuddyIP
));
526 case CT_EMULE_BUDDYUDP
:
527 // 16 --Reserved for future use--
529 m_nBuddyPort
= (uint16
)temptag
.GetInt();
530 #ifdef __PACKET_DEBUG__
531 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort
);
535 case CT_EMULE_MISCOPTIONS1
: {
536 // 3 AICH Version (0 = not supported)
539 // 4 Data compression version
544 // 1 PeerCache supported
545 // 1 No 'View Shared Files' supported
548 uint32 flags
= temptag
.GetInt();
549 m_fSupportsAICH
= (flags
>> (4*7+1)) & 0x07;
550 m_bUnicodeSupport
= (flags
>> 4*7) & 0x01;
551 m_byUDPVer
= (flags
>> 4*6) & 0x0f;
552 m_byDataCompVer
= (flags
>> 4*5) & 0x0f;
553 m_bySupportSecIdent
= (flags
>> 4*4) & 0x0f;
554 m_bySourceExchange1Ver
= (flags
>> 4*3) & 0x0f;
555 m_byExtendedRequestsVer
= (flags
>> 4*2) & 0x0f;
556 m_byAcceptCommentVer
= (flags
>> 4*1) & 0x0f;
557 m_fNoViewSharedFiles
= (flags
>> 1*2) & 0x01;
558 m_bMultiPacket
= (flags
>> 1*1) & 0x01;
559 m_fSupportsPreview
= (flags
>> 1*0) & 0x01;
561 #ifdef __PACKET_DEBUG__
562 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
563 AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer
);
564 AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer
);
565 AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent
);
566 AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver
);
567 AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer
);
568 AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer
);
569 AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles
);
570 AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket
);
571 AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories
);
572 AddLogLineNS(wxT("That's all."));
578 case CT_EMULE_MISCOPTIONS2
:
580 // 1 Direct UDP Callback supported and available
581 // 1 Supports ChatCaptchas
582 // 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
583 // 1 Requires CryptLayer
584 // 1 Requests CryptLayer
585 // 1 Supports CryptLayer
586 // 1 Reserved (ModBit)
587 // 1 Ext Multipacket (Hash+Size instead of Hash)
588 // 1 Large Files (includes support for 64bit tags)
589 // 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
590 m_fDirectUDPCallback
= (temptag
.GetInt() >> 12) & 0x01;
591 m_fSupportsCaptcha
= (temptag
.GetInt() >> 11) & 0x01;
592 m_fSupportsSourceEx2
= (temptag
.GetInt() >> 10) & 0x01;
593 m_fRequiresCryptLayer
= (temptag
.GetInt() >> 9) & 0x01;
594 m_fRequestsCryptLayer
= (temptag
.GetInt() >> 8) & 0x01;
595 m_fSupportsCryptLayer
= (temptag
.GetInt() >> 7) & 0x01;
597 m_fExtMultiPacket
= (temptag
.GetInt() >> 5) & 0x01;
598 m_fSupportsLargeFiles
= (temptag
.GetInt() >> 4) & 0x01;
599 m_byKadVersion
= (temptag
.GetInt() >> 0) & 0x0f;
602 m_fRequestsCryptLayer
&= m_fSupportsCryptLayer
;
603 m_fRequiresCryptLayer
&= m_fRequestsCryptLayer
;
605 #ifdef __PACKET_DEBUG__
606 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
607 AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback
);
608 AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha
);
609 AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2
);
610 AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer
);
611 AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer
);
612 AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer
);
613 AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket
);
614 AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles
);
615 AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion
);
616 AddLogLineNS(wxT("That's all."));
620 // Special tag for Compat. Clients Misc options.
621 case CT_EMULECOMPAT_OPTIONS
:
622 // 1 Operative System Info
623 // 1 Value-based-type int tags (experimental!)
624 m_fValueBasedTypeTags
= (temptag
.GetInt() >> 1*1) & 0x01;
625 m_fOsInfoSupport
= (temptag
.GetInt() >> 1*0) & 0x01;
628 case CT_EMULE_VERSION
:
629 // 8 Compatible Client ID
630 // 7 Mjr Version (Doesn't really matter..)
631 // 7 Min Version (Only need 0-99)
632 // 3 Upd Version (Only need 0-5)
633 // 7 Bld Version (Only need 0-99)
634 m_byCompatibleClient
= (temptag
.GetInt() >> 24);
635 m_nClientVersion
= temptag
.GetInt() & 0x00ffffff;
636 m_byEmuleVersion
= 0x99;
637 m_fSharedDirectories
= 1;
643 m_nUserPort
= nUserPort
;
644 m_dwServerIP
= data
.ReadUInt32();
645 m_nServerPort
= data
.ReadUInt16();
646 // Hybrid now has an extra uint32.. What is it for?
647 // Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
648 if ( data
.GetLength() - data
.GetPosition() == sizeof(uint32
) ) {
649 uint32 test
= data
.ReadUInt32();
650 /*if (test == 'KDLM') below kdlm is converted to ascii values.
651 This fixes a warning with gcc 3.4.
654 if (test
== 0x4b444c4d) { //if it's == "KDLM"
658 m_fSharedDirectories
= 1;
663 amuleIPV4Address address
;
664 m_socket
->GetPeer(address
);
665 SetIP(StringIPtoUint32(address
.IPAddress()));
667 throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
670 if (thePrefs::AddServersFromClient()) {
671 CServer
* addsrv
= new CServer(m_nServerPort
, Uint32toStringIP(m_dwServerIP
));
672 addsrv
->SetListName(addsrv
->GetAddress());
673 if (!theApp
->AddServer(addsrv
)) {
678 //(a)If this is a highID user, store the ID in the Hybrid format.
679 //(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
680 //(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
681 //because they will send a ID that is the same as their IP..
682 if(!HasLowID() || m_nUserIDHybrid
== 0 || m_nUserIDHybrid
== m_dwUserIP
) {
683 SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP
));
686 // get client credits
687 CClientCredits
* pFoundCredits
= theApp
->clientcredits
->GetCredit(m_UserHash
);
688 if (credits
== NULL
){
689 credits
= pFoundCredits
;
690 if (!theApp
->clientlist
->ComparePriorUserhash(m_dwUserIP
, m_nUserPort
, pFoundCredits
)){
691 AddDebugLogLineN( logClient
, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
694 } else if (credits
!= pFoundCredits
){
695 // userhash change ok, however two hours "waittime" before it can be used
696 credits
= pFoundCredits
;
697 AddDebugLogLineN( logClient
, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
701 if ((m_Friend
= theApp
->friendlist
->FindFriend(m_UserHash
, m_dwUserIP
, m_nUserPort
)) != NULL
){
702 m_Friend
->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::ProcessHelloTypePacket m_Friend->LinkClient")));
704 // avoid that an unwanted client instance keeps a friend slot
705 SetFriendSlot(false);
711 m_byInfopacketsReceived
|= IP_EDONKEYPROTPACK
;
713 // check if at least CT_EMULEVERSION was received, all other tags are optional
714 bool bIsMule
= (dwEmuleTags
& 0x04) == 0x04;
716 m_bEmuleProtocol
= true;
717 m_byInfopacketsReceived
|= IP_EMULEPROTPACK
;
720 if (GetKadPort() && GetKadVersion() > 1) {
721 Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort());
728 bool CUpDownClient::SendHelloPacket()
730 if (m_socket
== NULL
) {
735 // if IP is filtered, don't greet him but disconnect...
736 amuleIPV4Address address
;
737 m_socket
->GetPeer(address
);
738 if ( theApp
->ipfilter
->IsFiltered(StringIPtoUint32(address
.IPAddress()))) {
739 if (Disconnected(wxT("IPFilter"))) {
747 data
.WriteUInt8(16); // size of userhash
748 SendHelloTypePacket(&data
);
750 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_HELLO
);
751 theStats::AddUpOverheadOther(packet
->GetPacketSize());
752 SendPacket(packet
,true);
753 m_bHelloAnswerPending
= true;
754 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
758 void CUpDownClient::SendMuleInfoPacket(bool bAnswer
, bool OSInfo
) {
760 if (m_socket
== NULL
){
765 CPacket
* packet
= NULL
;
768 data
.WriteUInt8(CURRENT_VERSION_SHORT
);
772 // Special MuleInfo packet for clients supporting it.
773 // This means aMule >= 2.0.0 and Hydranode
775 // Violently mark it as special Mule Info packet
776 // Sending this makes non-supporting-osinfo clients to refuse to read this
777 // packet. Anyway, this packet should NEVER get to non-supporting clients.
779 data
.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
781 data
.WriteUInt32(1); // One Tag (OS_INFO)
783 CTagString
tag1(ET_OS_INFO
,theApp
->GetOSType());
784 tag1
.WriteTagToFile(&data
);
786 m_OSInfo_sent
= true; // So we don't send it again
790 // Normal MuleInfo packet
792 // Kry - There's no point on upgrading to VBT tags here
793 // as no client supporting it uses mule info packet.
795 data
.WriteUInt8(EMULE_PROTOCOL
);
800 CTagInt32
tag1(ET_COMPRESSION
,1);
801 tag1
.WriteTagToFile(&data
);
802 CTagInt32
tag2(ET_UDPVER
,4);
803 tag2
.WriteTagToFile(&data
);
804 CTagInt32
tag3(ET_UDPPORT
, thePrefs::GetEffectiveUDPPort());
805 tag3
.WriteTagToFile(&data
);
806 CTagInt32
tag4(ET_SOURCEEXCHANGE
,3);
807 tag4
.WriteTagToFile(&data
);
808 CTagInt32
tag5(ET_COMMENTS
,1);
809 tag5
.WriteTagToFile(&data
);
810 CTagInt32
tag6(ET_EXTENDEDREQUEST
,2);
811 tag6
.WriteTagToFile(&data
);
813 uint32 dwTagValue
= (theApp
->CryptoAvailable() ? 3 : 0);
814 // Kry - Needs the preview code from eMule
816 // set 'Preview supported' only if 'View Shared Files' allowed
817 if (thePrefs::CanSeeShares() != vsfaNobody) {
821 CTagInt32
tag7(ET_FEATURES
, dwTagValue
);
822 tag7
.WriteTagToFile(&data
);
824 CTagInt32
tag8(ET_COMPATIBLECLIENT
,SO_AMULE
);
825 tag8
.WriteTagToFile(&data
);
827 // Support for tag ET_MOD_VERSION
828 wxString
mod_name(MOD_VERSION_LONG
);
829 CTagString
tag9(ET_MOD_VERSION
, mod_name
);
830 tag9
.WriteTagToFile(&data
);
835 packet
= new CPacket(data
, OP_EMULEPROT
, (bAnswer
? OP_EMULEINFOANSWER
: OP_EMULEINFO
));
838 theStats::AddUpOverheadOther(packet
->GetPacketSize());
839 SendPacket(packet
,true,true);
843 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
845 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
848 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
853 bool CUpDownClient::ProcessMuleInfoPacket(const byte
* pachPacket
, uint32 nSize
)
855 uint8 protocol_version
;
857 const CMemFile
data(pachPacket
,nSize
);
859 // The version number part of this packet will soon be useless since
860 // it is only able to go to v.99. Why the version is a uint8 and why
861 // it was not done as a tag like the eDonkey hello packet is not known.
862 // Therefore, sooner or later, we are going to have to switch over to
863 // using the eDonkey hello packet to set the version. No sense making
864 // a third value sent for versions.
865 uint8 mule_version
= data
.ReadUInt8();
866 protocol_version
= data
.ReadUInt8();
867 uint32 tagcount
= data
.ReadUInt32();
868 if (protocol_version
== 0xFF) {
869 // OS Info supporting clients sending a recycled Mule info packet
870 for (uint32 i
= 0;i
< tagcount
; i
++){
871 CTag
temptag(data
, true);
872 switch(temptag
.GetNameID()){
874 // Special tag, only supporting clients (aMule/Hydranode)
875 // It was recycled from a mod's tag, so if the other side
876 // is not supporting OS Info, we're seriously fucked up :)
877 m_sClientOSInfo
= temptag
.GetStr();
879 // If we didn't send our OSInfo to this client, just send it
880 if (!m_OSInfo_sent
) {
881 SendMuleInfoPacket(false,true);
888 // Your ad... er... I mean TAG, here
895 // Old eMule sending tags
896 m_byCompatibleClient
= 0;
897 m_byEmuleVersion
= mule_version
;
899 if( m_byEmuleVersion
== 0x2B ) {
900 m_byEmuleVersion
= 0x22;
903 if (!(m_bEmuleProtocol
= (protocol_version
== EMULE_PROTOCOL
))) {
907 for (uint32 i
= 0;i
< tagcount
; i
++){
908 CTag
temptag(data
, false);
909 switch(temptag
.GetNameID()){
911 // Bits 31- 8: 0 - reserved
912 // Bits 7- 0: data compression version
913 m_byDataCompVer
= temptag
.GetInt();
917 // Bits 31-16: 0 - reserved
918 // Bits 15- 0: UDP port
919 m_nUDPPort
= temptag
.GetInt();
923 // Bits 31- 8: 0 - reserved
924 // Bits 7- 0: UDP protocol version
925 m_byUDPVer
= temptag
.GetInt();
928 case ET_SOURCEEXCHANGE
:
929 // Bits 31- 8: 0 - reserved
930 // Bits 7- 0: source exchange protocol version
931 m_bySourceExchange1Ver
= temptag
.GetInt();
935 // Bits 31- 8: 0 - reserved
936 // Bits 7- 0: comments version
937 m_byAcceptCommentVer
= temptag
.GetInt();
940 case ET_EXTENDEDREQUEST
:
941 // Bits 31- 8: 0 - reserved
942 // Bits 7- 0: extended requests version
943 m_byExtendedRequestsVer
= temptag
.GetInt();
946 case ET_COMPATIBLECLIENT
:
947 // Bits 31- 8: 0 - reserved
948 // Bits 7- 0: compatible client ID
949 m_byCompatibleClient
= temptag
.GetInt();
953 // Bits 31- 8: 0 - reserved
955 // Bit 6- 0: secure identification
956 m_bySupportSecIdent
= temptag
.GetInt() & 3;
957 m_bSupportsPreview
= (temptag
.GetInt() & 128) > 0;
962 if (temptag
.IsStr()) {
963 m_strModVersion
= temptag
.GetStr();
964 } else if (temptag
.IsInt()) {
965 m_strModVersion
= CFormat(wxT("ModID=%u")) % temptag
.GetInt();
967 m_strModVersion
= wxT("ModID=<Unknown>");
973 AddDebugLogLineN( logPacketErrors
,
974 CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
975 % temptag
.GetFullInfo()
976 % GetClientFullInfo()
983 if( m_byDataCompVer
== 0 ){
984 m_bySourceExchange1Ver
= 0;
985 m_byExtendedRequestsVer
= 0;
986 m_byAcceptCommentVer
= 0;
990 //implicitly supported options by older clients
991 //in the future do not use version to guess about new features
992 if(m_byEmuleVersion
< 0x25 && m_byEmuleVersion
> 0x22) {
996 if(m_byEmuleVersion
< 0x25 && m_byEmuleVersion
> 0x21) {
997 m_bySourceExchange1Ver
= 1;
1000 if(m_byEmuleVersion
== 0x24) {
1001 m_byAcceptCommentVer
= 1;
1004 // Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
1005 // the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
1006 // directory which has a trailing backslash.
1007 if(m_byEmuleVersion
>= 0x28 && !m_bIsML
) {// MLdonkey currently does not support shared directories
1008 m_fSharedDirectories
= 1;
1013 m_byInfopacketsReceived
|= IP_EMULEPROTPACK
;
1016 return (protocol_version
== 0xFF); // This was a OS_Info?
1020 void CUpDownClient::SendHelloAnswer()
1022 if (m_socket
== NULL
){
1028 SendHelloTypePacket(&data
);
1029 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_HELLOANSWER
);
1030 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1031 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
1032 SendPacket(packet
,true);
1036 void CUpDownClient::SendHelloTypePacket(CMemFile
* data
)
1038 data
->WriteHash(thePrefs::GetUserHash());
1039 data
->WriteUInt32(theApp
->GetID());
1040 data
->WriteUInt16(thePrefs::GetPort());
1042 uint32 tagcount
= 6;
1044 if( theApp
->clientlist
->GetBuddy() && theApp
->IsFirewalled() ) {
1047 tagcount
++; // eMule misc flags 2 (kad version)
1050 // Kry - This is the tagcount!!! Be sure to update it!!
1051 // Last update: CT_EMULECOMPAT_OPTIONS included
1052 data
->WriteUInt32(tagcount
+ 1);
1054 data
->WriteUInt32(tagcount
); // NO MOD_VERSION
1058 CTagString
tagname(CT_NAME
,thePrefs::GetUserNick());
1059 tagname
.WriteTagToFile(data
, utf8strRaw
);
1061 CTagVarInt
tagversion(CT_VERSION
, EDONKEYVERSION
, GetVBTTags() ? 0 : 32);
1062 tagversion
.WriteTagToFile(data
);
1065 uint32 kadUDPPort
= 0;
1067 if(Kademlia::CKademlia::IsConnected()) {
1068 if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
1069 kadUDPPort
= Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
1071 kadUDPPort
= Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
1075 CTagVarInt
tagUdpPorts(CT_EMULE_UDPPORTS
, (kadUDPPort
<< 16) | ((uint32
)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
1076 tagUdpPorts
.WriteTagToFile(data
);
1078 if( theApp
->clientlist
->GetBuddy() && theApp
->IsFirewalled() ) {
1079 CTagVarInt
tagBuddyIP(CT_EMULE_BUDDYIP
, theApp
->clientlist
->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
1080 tagBuddyIP
.WriteTagToFile(data
);
1082 CTagVarInt
tagBuddyPort(CT_EMULE_BUDDYUDP
,
1084 ((uint32
)theApp
->clientlist
->GetBuddy()->GetUDPPort() )
1085 , GetVBTTags() ? 0 : 32);
1086 tagBuddyPort
.WriteTagToFile(data
);
1090 CTagVarInt
tagMuleVersion(CT_EMULE_VERSION
,
1092 make_full_ed2k_version(VERSION_MJR
, VERSION_MIN
, VERSION_UPDATE
)
1094 , GetVBTTags() ? 0 : 32);
1095 tagMuleVersion
.WriteTagToFile(data
);
1098 // eMule Misc. Options #1
1099 const uint32 uUdpVer
= 4;
1100 const uint32 uDataCompVer
= 1;
1101 const uint32 uSupportSecIdent
= theApp
->CryptoAvailable() ? 3 : 0;
1102 const uint32 uSourceExchangeVer
= 3;
1103 const uint32 uExtendedRequestsVer
= 2;
1104 const uint32 uAcceptCommentVer
= 1;
1105 const uint32 uNoViewSharedFiles
= (thePrefs::CanSeeShares() == vsfaNobody
) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
1106 const uint32 uMultiPacket
= 1;
1107 const uint32 uSupportPreview
= 0; // No network preview at all.
1108 const uint32 uPeerCache
= 0; // No peercache for aMule, baby
1109 const uint32 uUnicodeSupport
= 1;
1110 const uint32 nAICHVer
= 1; // AICH is ENABLED right now.
1112 CTagVarInt
tagMisOptions(CT_EMULE_MISCOPTIONS1
,
1113 (nAICHVer
<< ((4*7)+1)) |
1114 (uUnicodeSupport
<< 4*7) |
1116 (uDataCompVer
<< 4*5) |
1117 (uSupportSecIdent
<< 4*4) |
1118 (uSourceExchangeVer
<< 4*3) |
1119 (uExtendedRequestsVer
<< 4*2) |
1120 (uAcceptCommentVer
<< 4*1) |
1121 (uPeerCache
<< 1*3) |
1122 (uNoViewSharedFiles
<< 1*2) |
1123 (uMultiPacket
<< 1*1) |
1124 (uSupportPreview
<< 1*0)
1125 , GetVBTTags() ? 0 : 32);
1126 tagMisOptions
.WriteTagToFile(data
);
1128 // eMule Misc. Options #2
1129 const uint32 uKadVersion
= KADEMLIA_VERSION
;
1130 const uint32 uSupportLargeFiles
= 1;
1131 const uint32 uExtMultiPacket
= 1;
1132 const uint32 uReserved
= 0; // mod bit
1133 const uint32 uSupportsCryptLayer
= thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
1134 const uint32 uRequestsCryptLayer
= thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
1135 const uint32 uRequiresCryptLayer
= thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
1136 const uint32 uSupportsSourceEx2
= 1;
1138 // captcha for daemon/remotegui not supported for now
1139 const uint32 uSupportsCaptcha
= 0;
1141 const uint32 uSupportsCaptcha
= 1;
1143 // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
1144 const uint32 uDirectUDPCallback
= (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
1145 && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
1147 CTagVarInt
tagMisOptions2(CT_EMULE_MISCOPTIONS2
,
1149 (uDirectUDPCallback
<< 12) |
1150 (uSupportsCaptcha
<< 11) |
1151 (uSupportsSourceEx2
<< 10) |
1152 (uRequiresCryptLayer
<< 9) |
1153 (uRequestsCryptLayer
<< 8) |
1154 (uSupportsCryptLayer
<< 7) |
1156 (uExtMultiPacket
<< 5) |
1157 (uSupportLargeFiles
<< 4) |
1159 , GetVBTTags() ? 0 : 32 );
1160 tagMisOptions2
.WriteTagToFile(data
);
1162 const uint32 nOSInfoSupport
= 1; // We support OS_INFO
1163 const uint32 nValueBasedTypeTags
= 0; // Experimental, disabled
1165 CTagVarInt
tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS
,
1166 (nValueBasedTypeTags
<< 1*1) |
1167 (nOSInfoSupport
<< 1*0)
1168 , GetVBTTags() ? 0 : 32);
1170 tagMisCompatOptions
.WriteTagToFile(data
);
1173 wxString
mod_name(MOD_VERSION_LONG
);
1174 CTagString
tagModName(ET_MOD_VERSION
, mod_name
);
1175 tagModName
.WriteTagToFile(data
);
1180 if (theApp
->IsConnectedED2K()) {
1181 dwIP
= theApp
->serverconnect
->GetCurrentServer()->GetIP();
1182 nPort
= theApp
->serverconnect
->GetCurrentServer()->GetPort();
1184 data
->WriteUInt32(dwIP
);
1185 data
->WriteUInt16(nPort
);
1189 void CUpDownClient::ProcessMuleCommentPacket(const byte
* pachPacket
, uint32 nSize
)
1192 throw CInvalidPacket(wxT("Comment packet for unknown file"));
1195 if (!m_reqfile
->IsPartFile()) {
1196 throw CInvalidPacket(wxT("Comment packet for completed file"));
1199 const CMemFile
data(pachPacket
, nSize
);
1201 uint8 rating
= data
.ReadUInt8();
1203 AddDebugLogLineN( logClient
, wxString(wxT("Invalid Rating for file '")) << m_clientFilename
<< wxT("' received: ") << rating
);
1207 AddDebugLogLineN( logClient
, wxString(wxT("Rating for file '")) << m_clientFilename
<< wxT("' received: ") << m_iRating
);
1210 // The comment is unicoded, with a uin32 len and safe read
1211 // (won't break if string size is < than advertised len)
1212 // Truncated to MAXFILECOMMENTLEN size
1213 m_strComment
= data
.ReadString((GetUnicodeSupport() != utf8strNone
), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN
);
1215 AddDebugLogLineN( logClient
, wxString(wxT("Description for file '")) << m_clientFilename
<< wxT("' received: ") << m_strComment
);
1217 // Update file rating
1218 m_reqfile
->UpdateFileRatingCommentAvail();
1222 void CUpDownClient::ClearDownloadBlockRequests()
1225 std::list
<Requested_Block_Struct
*>::iterator it
= m_DownloadBlocks_list
.begin();
1226 for (; it
!= m_DownloadBlocks_list
.end(); ++it
) {
1227 Requested_Block_Struct
* cur_block
= *it
;
1230 m_reqfile
->RemoveBlockFromList(cur_block
->StartOffset
, cur_block
->EndOffset
);
1236 m_DownloadBlocks_list
.clear();
1240 std::list
<Pending_Block_Struct
*>::iterator it
= m_PendingBlocks_list
.begin();
1241 for (; it
!= m_PendingBlocks_list
.end(); ++it
) {
1242 Pending_Block_Struct
* pending
= *it
;
1245 m_reqfile
->RemoveBlockFromList(pending
->block
->StartOffset
, pending
->block
->EndOffset
);
1248 delete pending
->block
;
1249 // Not always allocated
1250 if (pending
->zStream
){
1251 inflateEnd(pending
->zStream
);
1252 delete pending
->zStream
;
1258 m_PendingBlocks_list
.clear();
1263 bool CUpDownClient::Disconnected(const wxString
& strReason
, bool bFromSocket
)
1265 //wxASSERT(theApp->clientlist->IsValidClient(this));
1267 if (HasBeenDeleted()) {
1268 AddDebugLogLineN(logClient
, wxT("Disconnected() called for already deleted client on ip ") + Uint32toStringIP(GetConnectIP()));
1272 // was this a direct callback?
1273 if (m_dwDirectCallbackTimeout
!= 0) {
1274 theApp
->clientlist
->RemoveDirectCallback(this);
1275 m_dwDirectCallbackTimeout
= 0;
1276 theApp
->clientlist
->AddDeadSource(this);
1277 AddDebugLogLineN(logClient
, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP()));
1280 if (GetKadState() == KS_QUEUED_FWCHECK_UDP
|| GetKadState() == KS_CONNECTING_FWCHECK_UDP
) {
1281 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
1282 } else if (GetKadState() == KS_FWCHECK_UDP
) {
1283 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
1284 } else if (GetKadState() == KS_CONNECTED_BUDDY
) {
1285 AddDebugLogLineN(logClient
, wxT("Buddy client disconnected - ") + strReason
);
1288 //If this is a KAD client object, just delete it!
1289 SetKadState(KS_NONE
);
1291 if (GetUploadState() == US_UPLOADING
) {
1293 theApp
->uploadqueue
->RemoveFromUploadQueue(this);
1296 if (GetDownloadState() == DS_DOWNLOADING
) {
1297 SetDownloadState(DS_ONQUEUE
);
1299 // ensure that all possible block requests are removed from the partfile
1300 ClearDownloadBlockRequests();
1302 if (GetDownloadState() == DS_CONNECTED
) {
1303 // successfully connected, but probably didn't respond to our filerequest
1304 theApp
->clientlist
->AddDeadSource(this);
1305 theApp
->downloadqueue
->RemoveSource(this);
1309 // we had still an AICH request pending, handle it
1310 if (IsAICHReqPending()) {
1311 m_fAICHRequested
= FALSE
;
1312 CAICHHashSet::ClientAICHRequestFailed(this);
1315 // The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
1316 // after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
1317 // is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
1318 if (((GetDownloadState() == DS_REQHASHSET
) || m_fHashsetRequesting
) && (m_reqfile
)) {
1319 m_reqfile
->SetHashSetNeeded(true);
1322 SourceItemType source_type
= UNAVAILABLE_SOURCE
;
1323 SourceItemType peer_type
= UNAVAILABLE_SOURCE
;
1325 //check if this client is needed in any way, if not delete it
1326 bool bDelete
= true;
1327 switch (m_nUploadState
) {
1328 case US_ONUPLOADQUEUE
:
1330 peer_type
= AVAILABLE_SOURCE
;
1334 switch (m_nDownloadState
) {
1336 source_type
= A4AF_SOURCE
; // Will be checked.
1337 case DS_TOOMANYCONNS
:
1338 case DS_NONEEDEDPARTS
:
1344 switch (m_nUploadState
) {
1346 case US_WAITCALLBACK
:
1348 theApp
->clientlist
->AddDeadSource(this);
1352 switch (m_nDownloadState
) {
1354 case DS_WAITCALLBACK
:
1357 theApp
->clientlist
->AddDeadSource(this);
1362 // We keep chat partners in any case
1363 if (GetChatState() != MS_NONE
) {
1365 m_pendingMessage
.Clear();
1366 Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString
);
1370 if (!bFromSocket
&& m_socket
) {
1371 wxASSERT (theApp
->listensocket
->IsValidSocket(m_socket
));
1372 m_socket
->Safe_Delete();
1377 if (m_iFileListRequested
) {
1378 AddLogLineN(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
1379 m_iFileListRequested
= 0;
1385 // Remove the friend linkage
1386 m_Friend
->UnLinkClient(); // this notifies
1389 Notify_SharedCtrlRefreshClient(ECID(), peer_type
);
1390 Notify_SourceCtrlUpdateSource(ECID(), source_type
);
1392 m_fHashsetRequesting
= 0;
1393 SetSentCancelTransfer(0);
1394 m_bHelloAnswerPending
= false;
1395 m_fSentOutOfPartReqs
= 0;
1397 AddDebugLogLineN(logClient
, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
1398 % (bDelete
? wxT("Deleted") : wxT("Disconnected"))
1399 % m_nDownloadState
% m_nUploadState
% GetClientFullInfo() % strReason
);
1404 //Returned bool is not if the TryToConnect is successful or not..
1405 //false means the client was deleted!
1406 //true means the client was not deleted!
1407 bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon
)
1410 if (theApp
->listensocket
->TooManySockets() && !bIgnoreMaxCon
) {
1411 if (!(m_socket
&& m_socket
->IsConnected())) {
1412 if(Disconnected(wxT("Too many connections"))) {
1420 // 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)
1421 if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
1422 if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
1431 uint32 uClientIP
= GetIP();
1432 if (uClientIP
== 0 && !HasLowID()) {
1433 uClientIP
= wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid
);
1437 // Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
1438 // we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
1439 if (theApp
->ipfilter
->IsFiltered(uClientIP
)) {
1440 AddDebugLogLineN(logIPFilter
, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP
% Uint32toStringIP(uClientIP
));
1441 if (Disconnected(wxT("IPFilter"))) {
1448 // for safety: check again whether that IP is banned
1449 if (theApp
->clientlist
->IsBannedClient(uClientIP
)) {
1450 AddDebugLogLineN(logClient
, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP
));
1451 if (Disconnected(wxT("Banned IP"))) {
1459 if (GetKadState() == KS_QUEUED_FWCHECK
) {
1460 SetKadState(KS_CONNECTING_FWCHECK
);
1461 } else if (GetKadState() == KS_QUEUED_FWCHECK_UDP
) {
1462 SetKadState(KS_CONNECTING_FWCHECK_UDP
);
1466 if (!theApp
->CanDoCallback(GetServerIP(), GetServerPort())) {
1467 //We cannot do a callback!
1468 if (GetDownloadState() == DS_CONNECTING
) {
1469 SetDownloadState(DS_LOWTOLOWIP
);
1470 } else if (GetDownloadState() == DS_REQHASHSET
) {
1471 SetDownloadState(DS_ONQUEUE
);
1472 m_reqfile
->SetHashSetNeeded(true);
1474 if (GetUploadState() == US_CONNECTING
) {
1475 if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
1483 //We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
1484 //If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
1485 //with the condition that the source is firewalled and we are firewalled, we must
1486 //recheck it before the this check..
1487 if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp
->serverconnect
->IsLocalServer(GetServerIP(), GetServerPort())
1488 && !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
1489 //This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
1490 if( Kademlia::CKademlia::IsConnected() ) {
1491 //We are connect to Kad
1492 if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
1493 //There are too many source lookups already or we are already searching this key.
1494 SetDownloadState(DS_TOOMANYCONNSKAD
);
1501 if (!m_socket
|| !m_socket
->IsConnected()) {
1503 m_socket
->Safe_Delete();
1505 m_socket
= new CClientTCPSocket(this, thePrefs::GetProxyData());
1507 ConnectionEstablished();
1512 if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
1513 if (m_dwDirectCallbackTimeout
!= 0) {
1514 AddDebugLogLineN(logClient
, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP()));
1515 return true; // We're already trying a direct connection to this client
1517 // a direct callback is possible - since no other parties are involved and only one additional packet overhead
1518 // is used we basically handle it like a normal connection try, no restrictions apply
1519 // we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
1520 m_dwDirectCallbackTimeout
= ::GetTickCount() + SEC2MS(45);
1521 theApp
->clientlist
->AddDirectCallbackClient(this);
1522 AddDebugLogLineN(logClient
, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP()));
1525 data
.WriteUInt16(thePrefs::GetPort()); // needs to know our port
1526 data
.WriteHash(thePrefs::GetUserHash()); // and userhash
1527 // our connection settings
1528 data
.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
1529 AddDebugLogLineN(logClientUDP
, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
1530 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_DIRECTCALLBACKREQ
);
1531 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1532 theApp
->clientudp
->SendPacket(packet
, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
1533 } else if (HasLowID()) { // LOWID
1534 if (GetDownloadState() == DS_CONNECTING
) {
1535 SetDownloadState(DS_WAITCALLBACK
);
1537 if (GetUploadState() == US_CONNECTING
) {
1538 if(Disconnected(wxT("LowID and US_CONNECTING"))) {
1545 if (theApp
->serverconnect
->IsLocalServer(m_dwServerIP
,m_nServerPort
)) {
1547 // AFAICS, this id must be reversed to be sent to clients
1548 // But if I reverse it, we do a serve violation ;)
1549 data
.WriteUInt32(m_nUserIDHybrid
);
1550 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_CALLBACKREQUEST
);
1551 theStats::AddUpOverheadServer(packet
->GetPacketSize());
1552 AddDebugLogLineN(logLocalClient
, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
1553 theApp
->serverconnect
->SendPacket(packet
);
1554 SetDownloadState(DS_WAITCALLBACK
);
1556 if (GetUploadState() == US_NONE
&& (!GetRemoteQueueRank() || m_bReaskPending
)) {
1558 if( !HasValidBuddyID() ) {
1559 theApp
->downloadqueue
->RemoveSource(this);
1560 if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
1567 if( !Kademlia::CKademlia::IsConnected() ) {
1568 //We are not connected to Kad and this is a Kad Firewalled source..
1569 theApp
->downloadqueue
->RemoveSource(this);
1570 if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
1577 if( GetDownloadState() == DS_WAITCALLBACK
) {
1578 if( GetBuddyIP() && GetBuddyPort()) {
1580 bio
.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
1581 bio
.WriteUInt128(Kademlia::CUInt128(m_reqfile
->GetFileHash().GetHash()));
1582 bio
.WriteUInt16(thePrefs::GetPort());
1583 CPacket
* packet
= new CPacket(bio
, OP_KADEMLIAHEADER
, KADEMLIA_CALLBACK_REQ
);
1584 // eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
1585 theApp
->clientudp
->SendPacket(packet
, GetBuddyIP(), GetBuddyPort(), false, NULL
, true, 0);
1586 AddDebugLogLineN(logClientKadUDP
, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet
->GetPacketSize() % Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort()));
1587 theStats::AddUpOverheadKad(packet
->GetRealPacketSize());
1588 SetDownloadState(DS_WAITCALLBACKKAD
);
1590 AddLogLineN(_("Searching buddy for lowid connection"));
1591 //Create search to find buddy.
1592 Kademlia::CSearch
*findSource
= new Kademlia::CSearch
;
1593 findSource
->SetSearchTypes(Kademlia::CSearch::FINDSOURCE
);
1594 findSource
->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
1595 findSource
->AddFileID(Kademlia::CUInt128(m_reqfile
->GetFileHash().GetHash()));
1596 if(Kademlia::CSearchManager::StartSearch(findSource
)) {
1598 SetDownloadState(DS_WAITCALLBACKKAD
);
1600 //This should never happen..
1606 if (GetDownloadState() == DS_WAITCALLBACK
) {
1607 m_bReaskPending
= true;
1608 SetDownloadState(DS_ONQUEUE
);
1620 bool CUpDownClient::Connect()
1622 m_hasbeenobfuscatinglately
= false;
1624 if (!m_socket
->IsOk()) {
1625 // Enable or disable crypting based on our and the remote clients preference
1626 if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
1627 m_socket
->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
1629 m_socket
->SetConnectionEncryption(false, NULL
, false);
1631 amuleIPV4Address tmp
;
1632 tmp
.Hostname(GetConnectIP());
1633 tmp
.Service(GetUserPort());
1634 AddDebugLogLineN(logClient
, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
1635 m_socket
->Connect(tmp
, false);
1636 // We should send hello packets AFTER connecting!
1637 // so I moved it to OnConnect
1644 void CUpDownClient::ConnectionEstablished()
1646 /* Kry - First thing, check if this client was just used to retrieve
1647 info. That's some debug thing for myself... check connection_reason
1650 m_hasbeenobfuscatinglately
= (m_socket
&& m_socket
->IsConnected() && m_socket
->IsObfusicating());
1653 if (!connection_reason
.IsEmpty()) {
1654 AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason
% GetClientFullInfo());
1655 connection_reason
.Clear(); // So we don't re-print on destructor.
1661 // Check if we should use this client to retrieve our public IP
1662 // Ignore local ip on GetPublicIP (could be wrong)
1663 if (theApp
->GetPublicIP(true) == 0 && theApp
->IsConnectedED2K()) {
1664 SendPublicIPRequest();
1667 // was this a direct callback?
1668 if (m_dwDirectCallbackTimeout
!= 0){
1669 theApp
->clientlist
->RemoveDirectCallback(this);
1670 m_dwDirectCallbackTimeout
= 0;
1671 AddDebugLogLineN(logClient
, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP()));
1674 switch (GetKadState()) {
1675 case KS_CONNECTING_FWCHECK
:
1676 SetKadState(KS_CONNECTED_FWCHECK
);
1678 case KS_CONNECTING_BUDDY
:
1679 case KS_INCOMING_BUDDY
:
1680 SetKadState(KS_CONNECTED_BUDDY
);
1682 case KS_CONNECTING_FWCHECK_UDP
:
1683 SetKadState(KS_FWCHECK_UDP
);
1684 SendFirewallCheckUDPRequest();
1690 // ok we have a connection, lets see if we want anything from this client
1691 if (GetChatState() == MS_CONNECTING
) {
1692 SetChatState( MS_CHATTING
);
1695 if (GetChatState() == MS_CHATTING
) {
1697 if (!m_pendingMessage
.IsEmpty()) {
1698 result
= SendChatMessage(m_pendingMessage
);
1700 Notify_ChatConnResult(result
,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage
);
1701 m_pendingMessage
.Clear();
1704 switch(GetDownloadState()) {
1706 case DS_WAITCALLBACK
:
1707 case DS_WAITCALLBACKKAD
:
1708 m_bReaskPending
= false;
1709 SetDownloadState(DS_CONNECTED
);
1712 if (m_bReaskPending
){
1713 m_bReaskPending
= false;
1714 if (GetDownloadState() != DS_NONE
&& GetDownloadState() != DS_DOWNLOADING
) {
1715 SetDownloadState(DS_CONNECTED
);
1719 switch(GetUploadState()){
1721 case US_WAITCALLBACK
:
1722 if (theApp
->uploadqueue
->IsDownloading(this)) {
1723 SetUploadState(US_UPLOADING
);
1724 CPacket
* packet
= new CPacket(OP_ACCEPTUPLOADREQ
, 0, OP_EDONKEYPROT
);
1725 theStats::AddUpOverheadFileRequest(packet
->GetPacketSize());
1726 SendPacket(packet
,true);
1727 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
1730 if (m_iFileListRequested
== 1) {
1731 CPacket
* packet
= new CPacket(m_fSharedDirectories
? OP_ASKSHAREDDIRS
: OP_ASKSHAREDFILES
, 0, OP_EDONKEYPROT
);
1732 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1733 SendPacket(packet
,true,true);
1734 if (m_fSharedDirectories
) {
1735 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
1737 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
1741 while (!m_WaitingPackets_list
.empty()) {
1742 CPacket
* packet
= m_WaitingPackets_list
.front();
1743 m_WaitingPackets_list
.pop_front();
1750 int CUpDownClient::GetHashType() const
1752 if ( m_UserHash
[5] == 13 && m_UserHash
[14] == 110 ) {
1756 if ( m_UserHash
[5] == 14 && m_UserHash
[14] == 111 ) {
1760 if ( m_UserHash
[5] == 'M' && m_UserHash
[14] == 'L' ) {
1768 void CUpDownClient::SetSocket(CClientTCPSocket
* socket
)
1770 #if defined(__DEBUG__)
1771 if (m_socket
== NULL
&& socket
!= NULL
) {
1772 theStats::SocketAssignedToClient();
1773 } else if (m_socket
!= NULL
&& socket
== NULL
) {
1774 theStats::SocketUnassignedFromClient();
1781 void CUpDownClient::ReGetClientSoft()
1783 if (m_Username
.IsEmpty()) {
1784 m_clientSoft
=SO_UNKNOWN
;
1785 m_clientVerString
= m_clientSoftString
= m_clientVersionString
= m_fullClientVerString
= _("Unknown");
1790 int iHashType
= GetHashType();
1791 wxString clientModString
;
1792 if (iHashType
== SO_EMULE
) {
1794 m_clientSoft
= m_byCompatibleClient
;
1795 m_clientSoftString
= GetSoftName(m_clientSoft
);
1797 if(!GetClientModString().IsEmpty() && (m_clientSoft
!= SO_EMULE
)) {
1798 m_clientSoftString
= GetClientModString();
1800 // Isn't xMule annoying?
1801 if ((m_clientSoft
== SO_LXMULE
) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
1802 m_clientSoftString
+= CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion();
1804 if ((m_clientSoft
== SO_EMULE
) &&
1806 wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
1807 || GetUserName().Find(wxT("xmule.")) != -1
1810 // FAKE eMule -a newer xMule faking is ident.
1811 m_clientSoft
= SO_LXMULE
;
1812 if (GetClientModString().IsEmpty() == false) {
1813 m_clientSoftString
= GetClientModString() + _(" (Fake eMule)");
1815 m_clientSoftString
= _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
1818 // Now, what if we don't know this SO_ID?
1819 if (m_clientSoftString
.IsEmpty()) {
1821 m_clientSoft
= SO_MLDONKEY
;
1822 m_clientSoftString
= GetSoftName(m_clientSoft
);
1823 } else if (m_bIsHybrid
) {
1824 m_clientSoft
= SO_EDONKEYHYBRID
;
1825 m_clientSoftString
= GetSoftName(m_clientSoft
);
1826 } else if (m_byCompatibleClient
!= 0) {
1827 m_clientSoft
= SO_COMPAT_UNK
;
1831 (m_byCompatibleClient
!= 0xf0) // Chinese leech mod
1832 && (1==1) // Your ad here
1834 AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient
);
1837 m_clientSoftString
= CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft
) % m_byCompatibleClient
;
1839 // If we step here, it might mean 2 things:
1841 // a Compat Client that has sent no MuleInfo packet yet.
1842 m_clientSoft
= SO_EMULE
;
1843 m_clientSoftString
= wxT("eMule");
1847 if (m_byEmuleVersion
== 0) {
1848 m_nClientVersion
= MAKE_CLIENT_VERSION(0,0,0);
1849 } else if (m_byEmuleVersion
!= 0x99) {
1850 uint32 nClientMinVersion
= (m_byEmuleVersion
>> 4)*10 + (m_byEmuleVersion
& 0x0f);
1851 m_nClientVersion
= MAKE_CLIENT_VERSION(0,nClientMinVersion
,0);
1852 switch (m_clientSoft
) {
1854 m_clientVerString
= CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion
;
1857 m_clientVerString
= wxT("< v0.05");
1860 clientModString
= GetClientModString();
1861 m_clientVerString
= CFormat(wxT("v0.%u")) % nClientMinVersion
;
1865 uint32 nClientMajVersion
= (m_nClientVersion
>> 17) & 0x7f;
1866 uint32 nClientMinVersion
= (m_nClientVersion
>> 10) & 0x7f;
1867 uint32 nClientUpVersion
= (m_nClientVersion
>> 7) & 0x07;
1869 m_nClientVersion
= MAKE_CLIENT_VERSION(nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1871 switch (m_clientSoft
) {
1876 case SO_NEW_MLDONKEY
:
1877 case SO_NEW2_MLDONKEY
:
1878 // Kry - xMule started sending correct version tags on 1.9.1b.
1879 // It only took them 4 months, and being told by me and the
1880 // eMule+ developers, so I think they're slowly getting smarter.
1881 // They are based on our implementation, so we use the same format
1882 // for the version string.
1883 m_clientVerString
= CFormat(wxT("v%u.%u.%u")) % nClientMajVersion
% nClientMinVersion
% nClientUpVersion
;
1886 m_clientVerString
= CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion
-1) % nClientMinVersion
% ('a' + nClientUpVersion
);
1889 m_clientVerString
= CFormat(wxT("v%u")) % nClientMajVersion
;
1890 if(nClientMinVersion
!= 0) {
1891 m_clientVerString
+= CFormat(wxT(".%u")) % nClientMinVersion
;
1893 if(nClientUpVersion
!= 0) {
1894 m_clientVerString
+= CFormat(wxT("%c")) % ('a' + nClientUpVersion
- 1);
1898 clientModString
= GetClientModString();
1899 m_clientVerString
= CFormat(wxT("v%u.%u%c")) % nClientMajVersion
% nClientMinVersion
% ('a' + nClientUpVersion
);
1903 } else if (m_bIsHybrid
) {
1910 m_clientSoft
= SO_EDONKEYHYBRID
;
1911 m_clientSoftString
= GetSoftName(m_clientSoft
);
1913 uint32 nClientMajVersion
;
1914 uint32 nClientMinVersion
;
1915 uint32 nClientUpVersion
;
1916 if (m_nClientVersion
> 100000) {
1917 uint32 uMaj
= m_nClientVersion
/100000;
1918 nClientMajVersion
= uMaj
- 1;
1919 nClientMinVersion
= (m_nClientVersion
- uMaj
*100000) / 100;
1920 nClientUpVersion
= m_nClientVersion
% 100;
1922 else if (m_nClientVersion
> 10000) {
1923 uint32 uMaj
= m_nClientVersion
/10000;
1924 nClientMajVersion
= uMaj
- 1;
1925 nClientMinVersion
= (m_nClientVersion
- uMaj
*10000) / 10;
1926 nClientUpVersion
= m_nClientVersion
% 10;
1928 else if (m_nClientVersion
> 1000) {
1929 uint32 uMaj
= m_nClientVersion
/1000;
1930 nClientMajVersion
= uMaj
- 1;
1931 nClientMinVersion
= m_nClientVersion
- uMaj
*1000;
1932 nClientUpVersion
= 0;
1934 else if (m_nClientVersion
> 100) {
1935 uint32 uMin
= m_nClientVersion
/10;
1936 nClientMajVersion
= 0;
1937 nClientMinVersion
= uMin
;
1938 nClientUpVersion
= m_nClientVersion
- uMin
*10;
1941 nClientMajVersion
= 0;
1942 nClientMinVersion
= m_nClientVersion
;
1943 nClientUpVersion
= 0;
1945 m_nClientVersion
= MAKE_CLIENT_VERSION(nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1946 if (nClientUpVersion
) {
1947 m_clientVerString
= CFormat(wxT("v%u.%u.%u")) % nClientMajVersion
% nClientMinVersion
% nClientUpVersion
;
1949 m_clientVerString
= CFormat(wxT("v%u.%u")) % nClientMajVersion
% nClientMinVersion
;
1951 } else if (m_bIsML
|| (iHashType
== SO_MLDONKEY
)) {
1952 m_clientSoft
= SO_MLDONKEY
;
1953 m_clientSoftString
= GetSoftName(m_clientSoft
);
1954 uint32 nClientMinVersion
= m_nClientVersion
;
1955 m_nClientVersion
= MAKE_CLIENT_VERSION(0, nClientMinVersion
, 0);
1956 m_clientVerString
= CFormat(wxT("v0.%u")) % nClientMinVersion
;
1957 } else if (iHashType
== SO_OLDEMULE
) {
1958 m_clientSoft
= SO_OLDEMULE
;
1959 m_clientSoftString
= GetSoftName(m_clientSoft
);
1960 uint32 nClientMinVersion
= m_nClientVersion
;
1961 m_nClientVersion
= MAKE_CLIENT_VERSION(0, nClientMinVersion
, 0);
1962 m_clientVerString
= CFormat(wxT("v0.%u")) % nClientMinVersion
;
1964 m_clientSoft
= SO_EDONKEY
;
1965 m_clientSoftString
= GetSoftName(m_clientSoft
);
1966 m_nClientVersion
*= 10;
1967 m_clientVerString
= CFormat(wxT("v%u.%u")) % (m_nClientVersion
/ 100000) % ((m_nClientVersion
/ 1000) % 100);
1970 m_clientVersionString
= m_clientVerString
;
1971 if (!clientModString
.IsEmpty()) {
1972 m_clientVerString
+= wxT(" - ") + clientModString
;
1974 m_fullClientVerString
= m_clientSoftString
+ wxT(" ") + m_clientVerString
;
1979 void CUpDownClient::RequestSharedFileList()
1981 if (m_iFileListRequested
== 0) {
1982 AddDebugLogLineN( logClient
, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
1983 m_iFileListRequested
= 1;
1986 AddDebugLogLineN( logClient
, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
1991 void CUpDownClient::ProcessSharedFileList(const byte
* pachPacket
, uint32 nSize
, wxString
& pszDirectory
)
1993 if (m_iFileListRequested
> 0) {
1994 m_iFileListRequested
--;
1995 theApp
->searchlist
->ProcessSharedFileList(pachPacket
, nSize
, this, NULL
, pszDirectory
);
2000 void CUpDownClient::ResetFileStatusInfo()
2005 m_reqfile
->UpdatePartsFrequency( this, false );
2007 m_downPartStatus
.clear();
2009 m_clientFilename
.Clear();
2011 m_bCompleteSource
= false;
2012 m_dwLastAskedTime
= 0;
2014 m_strComment
.Clear();
2016 if (m_pReqFileAICHHash
!= NULL
) {
2017 delete m_pReqFileAICHHash
;
2018 m_pReqFileAICHHash
= NULL
;
2023 wxString
CUpDownClient::GetUploadFileInfo()
2025 // build info text and display it
2027 sRet
= (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
2029 sRet
+= CFormat(_("Requested: %s\n")) % m_reqfile
->GetFileName();
2031 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())
2032 ) % m_reqfile
->statistic
.GetAccepts() % m_reqfile
->statistic
.GetRequests() % CastItoXBytes(m_reqfile
->statistic
.GetTransferred());
2034 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())
2035 ) % m_reqfile
->statistic
.GetAllTimeAccepts() % m_reqfile
->statistic
.GetAllTimeRequests() % CastItoXBytes(m_reqfile
->statistic
.GetAllTimeTransferred());
2037 sRet
+= _("Requested unknown file");
2042 // sends a packet, if needed it will establish a connection before
2043 // options used: ignore max connections, control packet, delete packet
2044 // !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
2045 bool CUpDownClient::SafeSendPacket(CPacket
* packet
)
2047 if (IsConnected()) {
2048 SendPacket(packet
, true);
2051 m_WaitingPackets_list
.push_back(packet
);
2052 return TryToConnect(true);
2056 void CUpDownClient::SendPublicKeyPacket(){
2057 // send our public key to the client who requested it
2058 if (m_socket
== NULL
|| credits
== NULL
|| m_SecureIdentState
!= IS_KEYANDSIGNEEDED
){
2062 if (!theApp
->CryptoAvailable())
2066 data
.WriteUInt8(theApp
->clientcredits
->GetPubKeyLen());
2067 data
.Write(theApp
->clientcredits
->GetPublicKey(), theApp
->clientcredits
->GetPubKeyLen());
2068 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_PUBLICKEY
);
2070 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2071 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
2072 SendPacket(packet
,true,true);
2073 m_SecureIdentState
= IS_SIGNATURENEEDED
;
2077 void CUpDownClient::SendSignaturePacket(){
2078 // signate the public key of this client and send it
2079 if (m_socket
== NULL
|| credits
== NULL
|| m_SecureIdentState
== 0){
2084 if (!theApp
->CryptoAvailable()) {
2087 if (credits
->GetSecIDKeyLen() == 0) {
2088 return; // We don't have his public key yet, will be back here later
2090 // do we have a challenge value received (actually we should if we are in this function)
2091 if (credits
->m_dwCryptRndChallengeFrom
== 0){
2092 AddDebugLogLineN( logClient
, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
2096 // we will use v1 as default, except if only v2 is supported
2098 if ( (m_bySupportSecIdent
&1) == 1 )
2103 uint8 byChaIPKind
= 0;
2104 uint32 ChallengeIP
= 0;
2106 if (::IsLowID(theApp
->GetED2KID())) {
2107 // we cannot do not know for sure our public ip, so use the remote clients one
2108 ChallengeIP
= GetIP();
2109 byChaIPKind
= CRYPT_CIP_REMOTECLIENT
;
2111 ChallengeIP
= theApp
->GetED2KID();
2112 byChaIPKind
= CRYPT_CIP_LOCALCLIENT
;
2116 byte achBuffer
[250];
2118 uint8 siglen
= theApp
->clientcredits
->CreateSignature(credits
, achBuffer
, 250, ChallengeIP
, byChaIPKind
);
2124 data
.WriteUInt8(siglen
);
2125 data
.Write(achBuffer
, siglen
);
2127 data
.WriteUInt8(byChaIPKind
);
2130 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_SIGNATURE
);
2132 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2133 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
2134 SendPacket(packet
,true,true);
2135 m_SecureIdentState
= IS_ALLREQUESTSSEND
;
2139 void CUpDownClient::ProcessPublicKeyPacket(const byte
* pachPacket
, uint32 nSize
)
2141 theApp
->clientlist
->AddTrackClient(this);
2143 if (m_socket
== NULL
|| credits
== NULL
|| pachPacket
[0] != nSize
-1
2144 || nSize
== 0 || nSize
> 250){
2148 if (!theApp
->CryptoAvailable())
2150 // the function will handle everything (mulitple key etc)
2151 if (credits
->SetSecureIdent(pachPacket
+1, pachPacket
[0])){
2152 // if this client wants a signature, now we can send him one
2153 if (m_SecureIdentState
== IS_SIGNATURENEEDED
){
2154 SendSignaturePacket();
2156 else if (m_SecureIdentState
== IS_KEYANDSIGNEEDED
) {
2157 // something is wrong
2158 AddDebugLogLineN( logClient
, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
2161 AddDebugLogLineN( logClient
, wxT("Failed to use new received public key") );
2166 void CUpDownClient::ProcessSignaturePacket(const byte
* pachPacket
, uint32 nSize
)
2168 // here we spread the good guys from the bad ones ;)
2170 if (m_socket
== NULL
|| credits
== NULL
|| nSize
== 0 || nSize
> 250){
2176 if (pachPacket
[0] == nSize
-1)
2178 else if (pachPacket
[0] == nSize
-2 && (m_bySupportSecIdent
& 2) > 0) //v2
2179 byChaIPKind
= pachPacket
[nSize
-1];
2185 if (!theApp
->CryptoAvailable())
2188 // we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
2189 if (m_dwLastSignatureIP
== GetIP()){
2190 AddDebugLogLineN( logClient
, wxT("received multiple signatures from one client") );
2193 // also make sure this client has a public key
2194 if (credits
->GetSecIDKeyLen() == 0){
2195 AddDebugLogLineN( logClient
, wxT("received signature for client without public key") );
2198 // and one more check: did we ask for a signature and sent a challange packet?
2199 if (credits
->m_dwCryptRndChallengeFor
== 0){
2200 AddDebugLogLineN( logClient
, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
2204 if (theApp
->clientcredits
->VerifyIdent(credits
, pachPacket
+1, pachPacket
[0], GetIP(), byChaIPKind
) ) {
2205 // result is saved in function above
2206 AddDebugLogLineN( logClient
, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind
);
2208 AddDebugLogLineN( logClient
, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind
);
2211 m_dwLastSignatureIP
= GetIP();
2214 void CUpDownClient::SendSecIdentStatePacket(){
2215 // check if we need public key and signature
2218 if (theApp
->CryptoAvailable()){
2219 if (credits
->GetSecIDKeyLen() == 0) {
2220 nValue
= IS_KEYANDSIGNEEDED
;
2221 } else if (m_dwLastSignatureIP
!= GetIP()) {
2222 nValue
= IS_SIGNATURENEEDED
;
2226 AddDebugLogLineN( logClient
, wxT("Not sending SecIdentState Packet, because State is Zero") );
2229 // crypt: send random data to sign
2230 uint32 dwRandom
= rand()+1;
2231 credits
->m_dwCryptRndChallengeFor
= dwRandom
;
2234 data
.WriteUInt8(nValue
);
2235 data
.WriteUInt32(dwRandom
);
2236 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_SECIDENTSTATE
);
2238 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2239 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
2240 SendPacket(packet
,true,true);
2247 void CUpDownClient::ProcessSecIdentStatePacket(const byte
* pachPacket
, uint32 nSize
)
2254 wxASSERT( credits
);
2258 CMemFile
data(pachPacket
,nSize
);
2260 switch ( data
.ReadUInt8() ) {
2262 m_SecureIdentState
= IS_UNAVAILABLE
;
2265 m_SecureIdentState
= IS_SIGNATURENEEDED
;
2268 m_SecureIdentState
= IS_KEYANDSIGNEEDED
;
2274 credits
->m_dwCryptRndChallengeFrom
= data
.ReadUInt32();
2278 void CUpDownClient::InfoPacketsReceived()
2280 // indicates that both Information Packets has been received
2281 // needed for actions, which process data from both packets
2282 wxASSERT ( m_byInfopacketsReceived
== IP_BOTH
);
2283 m_byInfopacketsReceived
= IP_NONE
;
2285 if (m_bySupportSecIdent
){
2286 SendSecIdentStatePacket();
2291 bool CUpDownClient::CheckHandshakeFinished() const
2293 if (m_bHelloAnswerPending
) {
2294 // this triggers way too often.. need more time to look at this -> only create a warning
2295 // The reason for this is that 2 clients are connecting to each other at the same time..
2296 AddDebugLogLineN( logClient
, wxT("Handshake not finished while processing packet.") );
2304 wxString
CUpDownClient::GetClientFullInfo()
2306 if (m_clientVerString
.IsEmpty()) {
2310 return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") )
2311 % ( m_Username
.IsEmpty() ? wxString(_("Unknown")) : m_Username
)
2314 % m_clientSoftString
2320 wxString
CUpDownClient::GetClientShortInfo()
2322 if (m_clientVerString
.IsEmpty()) {
2326 return CFormat( wxT("'%s' (%s %s %s)") )
2327 % ( m_Username
.IsEmpty() ? wxString(_("Unknown")) : m_Username
)
2328 % m_clientSoftString
2334 void CUpDownClient::SendPublicIPRequest()
2337 CPacket
* packet
= new CPacket(OP_PUBLICIP_REQ
,0,OP_EMULEPROT
);
2338 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2339 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_PUBLICIP_REQ to ") + GetFullIP());
2340 SendPacket(packet
,true);
2341 m_fNeedOurPublicIP
= true;
2345 void CUpDownClient::ProcessPublicIPAnswer(const byte
* pbyData
, uint32 uSize
)
2348 throw wxString(wxT("Wrong Packet size on Public IP answer"));
2350 uint32 dwIP
= PeekUInt32(pbyData
);
2351 if (m_fNeedOurPublicIP
== true){ // did we?
2352 m_fNeedOurPublicIP
= false;
2353 // Ignore local ip on GetPublicIP (could be wrong)
2354 if (theApp
->GetPublicIP(true) == 0 && !IsLowID(dwIP
) ) {
2355 theApp
->SetPublicIP(dwIP
);
2361 bool CUpDownClient::IsConnected() const
2363 return m_socket
&& m_socket
->IsConnected();
2366 bool CUpDownClient::SendPacket(CPacket
* packet
, bool delpacket
, bool controlpacket
)
2369 m_socket
->SendPacket(packet
, delpacket
, controlpacket
);
2372 AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()"));
2377 float CUpDownClient::SetDownloadLimit(uint32 reducedownload
)
2379 // lfroen: in daemon it actually can happen
2380 wxASSERT( m_socket
);
2382 float kBpsClient
= CalculateKBpsDown();
2386 if (reducedownload
) {
2387 // (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD)
2388 // which is how often it is called per second.
2389 uint32 limit
= (uint32
)(reducedownload
* kBpsClient
* 1024.0 / 100000.0 * CORE_TIMER_PERIOD
);
2391 if(limit
<1024 && reducedownload
>= 200) {
2392 // If we're going up and this download is < 1kB,
2393 // we want it to go up fast. Can be reduced later,
2394 // and it'll probably be in a more fair way with
2395 // other downloads that are faster.
2397 } else if(limit
== 0) {
2398 // This download is not transferring yet... make it
2399 // 1024 so we don't fill the TCP stack and lose the
2404 m_socket
->SetDownloadLimit(limit
);
2406 m_socket
->DisableDownloadLimit();
2410 AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient
);
2416 void CUpDownClient::SetUserIDHybrid(uint32 nUserID
)
2418 theApp
->clientlist
->UpdateClientID( this, nUserID
);
2420 m_nUserIDHybrid
= nUserID
;
2424 void CUpDownClient::SetIP( uint32 val
)
2426 theApp
->clientlist
->UpdateClientIP( this, val
);
2436 void CUpDownClient::SetUserHash(const CMD4Hash
& userhash
)
2438 theApp
->clientlist
->UpdateClientHash( this, userhash
);
2440 m_UserHash
= userhash
;
2445 EUtf8Str
CUpDownClient::GetUnicodeSupport() const
2447 return m_bUnicodeSupport
? utf8strRaw
: utf8strNone
;
2450 void CUpDownClient::SetSpammer(bool bVal
)
2454 } else if (IsBanned() && m_fIsSpammer
) {
2457 m_fIsSpammer
= bVal
;
2460 uint8
CUpDownClient::GetSecureIdentState()
2462 if (m_SecureIdentState
!= IS_UNAVAILABLE
) {
2463 if (!SecIdentSupRec
) {
2464 // This can be caused by a 0.30x based client which sends the old
2465 // style Hello packet, and the mule info packet, but between them they
2466 // send a secure ident state packet (after a hello but before we have
2467 // the SUI capabilities). This is a misbehaving client, and somehow I
2468 // feel like it should be dropped. But then again, it won't harm to use
2469 // this SUI state if they are reporting no SUI (won't be used) and if
2470 // they report using SUI on the mule info packet, it's ok to use it.
2472 AddDebugLogLineN(logClient
, wxT("A client sent secure ident state before telling us the SUI capabilities"));
2473 AddDebugLogLineN(logClient
, wxT("Client info: ") + GetClientFullInfo());
2474 AddDebugLogLineN(logClient
, wxT("This client won't be disconnected, but it should be. :P"));
2478 return m_SecureIdentState
;
2482 bool CUpDownClient::SendChatMessage(const wxString
& message
)
2484 if (GetChatCaptchaState() == CA_CAPTCHARECV
) {
2485 m_nChatCaptchaState
= CA_SOLUTIONSENT
;
2486 } else if (GetChatCaptchaState() == CA_SOLUTIONSENT
) {
2487 wxFAIL
; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through
2489 m_nChatCaptchaState
= CA_ACCEPTING
;
2494 // Already connecting?
2495 if (GetChatState() == MS_CONNECTING
) {
2496 // Queue all messages till we're able to send them (or discard them)
2497 if (!m_pendingMessage
.IsEmpty()) {
2498 m_pendingMessage
+= wxT("\n");
2500 // There must be a message to send
2501 // - except if we got disconnected. No need to assert therefore.
2503 m_pendingMessage
+= message
;
2506 if (IsConnected()) {
2507 // If we are already connected when we send the first message,
2508 // we have to update the chat status.
2509 SetChatState(MS_CHATTING
);
2511 data
.WriteString(message
, GetUnicodeSupport());
2512 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_MESSAGE
);
2513 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2514 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
2515 SendPacket(packet
, true, true);
2518 m_pendingMessage
= message
;
2519 SetChatState(MS_CONNECTING
);
2520 // True to ignore "Too Many Connections"
2528 void CUpDownClient::SetBuddyID(const byte
* pucBuddyID
)
2530 if( pucBuddyID
== NULL
){
2531 md4clr(m_achBuddyID
);
2532 m_bBuddyIDValid
= false;
2535 m_bBuddyIDValid
= true;
2536 md4cpy(m_achBuddyID
, pucBuddyID
);
2541 bool CUpDownClient::SendBuddyPing() {
2542 SetLastBuddyPingPongTime();
2543 CPacket
* buddyPing
= new CPacket(OP_BUDDYPING
, 0, OP_EMULEPROT
);
2544 theStats::AddUpOverheadKad(buddyPing
->GetPacketSize());
2545 AddDebugLogLineN(logLocalClient
,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
2546 return SafeSendPacket(buddyPing
);
2552 void CUpDownClient::UpdateStats()
2554 if (m_lastClientSoft
!= m_clientSoft
|| m_lastClientVersion
!= m_nClientVersion
|| m_lastOSInfo
!= m_sClientOSInfo
) {
2555 if (m_lastClientSoft
== SO_UNKNOWN
) {
2556 theStats::RemoveUnknownClient();
2557 } else if (m_lastClientSoft
!= (uint32
)(-1)) {
2558 theStats::RemoveKnownClient(m_lastClientSoft
, m_lastClientVersion
, m_lastOSInfo
);
2561 m_lastClientSoft
= m_clientSoft
;
2562 m_lastClientVersion
= m_nClientVersion
;
2563 m_lastOSInfo
= m_sClientOSInfo
;
2565 if (m_clientSoft
== SO_UNKNOWN
) {
2566 theStats::AddUnknownClient();
2568 theStats::AddKnownClient(this);
2573 bool CUpDownClient::IsIdentified() const
2575 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED
);
2578 bool CUpDownClient::IsBadGuy() const
2580 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDBADGUY
);
2583 bool CUpDownClient::SUIFailed() const
2585 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDFAILED
);
2588 bool CUpDownClient::SUINeeded() const
2590 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDNEEDED
);
2593 bool CUpDownClient::SUINotSupported() const
2595 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE
);
2598 uint64
CUpDownClient::GetDownloadedTotal() const
2600 return credits
? credits
->GetDownloadedTotal() : 0;
2603 uint64
CUpDownClient::GetUploadedTotal() const
2605 return credits
? credits
->GetUploadedTotal() : 0;
2608 double CUpDownClient::GetScoreRatio() const
2610 return credits
? credits
->GetScoreRatio(GetIP(), theApp
->CryptoAvailable()) : 0;
2613 const wxString
CUpDownClient::GetServerName() const
2616 wxString srvaddr
= Uint32toStringIP(GetServerIP());
2617 CServer
* cserver
= theApp
->serverlist
->GetServerByAddress(
2618 srvaddr
, GetServerPort());
2620 ret
= cserver
->GetListName();
2628 bool CUpDownClient::ShouldReceiveCryptUDPPackets() const
2630 return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp
->GetPublicIP() != 0
2631 && HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) );
2636 void CUpDownClient::ProcessCaptchaRequest(CMemFile
* WXUNUSED(data
)) {}
2637 void CUpDownClient::ProcessCaptchaReqRes(uint8
WXUNUSED(nStatus
)) {}
2638 void CUpDownClient::ProcessChatMessage(const wxString
WXUNUSED(message
)) {}
2642 void CUpDownClient::ProcessCaptchaRequest(CMemFile
* data
)
2644 uint64 id
= GUI_ID(GetIP(),GetUserPort());
2645 // received a captcha request, check if we actually accept it (only after sending a message ourself to this client)
2646 if (GetChatCaptchaState() == CA_ACCEPTING
&& GetChatState() != MS_NONE
2647 && theApp
->amuledlg
->m_chatwnd
->IsIdValid(id
)) {
2648 // read tags (for future use)
2649 uint8 nTagCount
= data
->ReadUInt8();
2651 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount
);
2652 // and ignore them for now
2653 for (uint32 i
= 0; i
< nTagCount
; i
++) {
2654 CTag
tag(*data
, true);
2658 // sanitize checks - we want a small captcha not a wallpaper
2659 uint32 nSize
= (uint32
)(data
->GetLength() - data
->GetPosition());
2661 if ( nSize
> 128 && nSize
< 4096 ) {
2662 uint64 pos
= data
->GetPosition();
2663 wxMemoryInputStream
memstr(data
->GetRawBuffer() + pos
, nSize
);
2664 wxImage
imgCaptcha(memstr
, wxBITMAP_TYPE_BMP
);
2666 if (imgCaptcha
.IsOk() && imgCaptcha
.GetHeight() > 10 && imgCaptcha
.GetHeight() < 50
2667 && imgCaptcha
.GetWidth() > 10 && imgCaptcha
.GetWidth() < 150 ) {
2668 m_nChatCaptchaState
= CA_CAPTCHARECV
;
2669 CCaptchaDialog
* dialog
= new CCaptchaDialog(theApp
->amuledlg
, imgCaptcha
, id
);
2673 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP());
2676 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize
% GetFullIP());
2679 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP());
2683 void CUpDownClient::ProcessCaptchaReqRes(uint8 nStatus
)
2685 uint64 id
= GUI_ID(GetIP(),GetUserPort());
2686 if (GetChatCaptchaState() == CA_SOLUTIONSENT
&& GetChatState() != MS_NONE
2687 && theApp
->amuledlg
->m_chatwnd
->IsIdValid(id
)) {
2688 wxASSERT( nStatus
< 3 );
2689 m_nChatCaptchaState
= CA_NONE
;
2690 theApp
->amuledlg
->m_chatwnd
->ShowCaptchaResult(id
, nStatus
== 0);
2692 m_nChatCaptchaState
= CA_NONE
;
2693 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP());
2697 void CUpDownClient::ProcessChatMessage(wxString message
)
2699 if (IsMessageFiltered(message
)) {
2700 AddLogLineC(CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP());
2704 // advanced spamfilter check
2705 if (thePrefs::IsChatCaptchaEnabled() && !IsFriend()) {
2706 // captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam
2707 // first check if we need to send a captcha request to this client
2708 if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED
) {
2709 // we have never sent a message to this client, and no message from him has ever passed our filters
2710 if (GetChatCaptchaState() != CA_CHALLENGESENT
) {
2711 // we also aren't currently expecting a captcha response
2712 if (m_fSupportsCaptcha
) {
2713 // and he supports captcha, so send him one and store the message (without showing for now)
2714 if (m_cCaptchasSent
< 3) { // no more than 3 tries
2715 m_strCaptchaPendingMsg
= message
;
2716 wxMemoryOutputStream memstr
;
2717 memstr
.PutC(0); // no tags, for future use
2718 CCaptchaGenerator
captcha(4);
2719 if (captcha
.WriteCaptchaImage(memstr
)){
2720 m_strCaptchaChallenge
= captcha
.GetCaptchaText();
2721 m_nChatCaptchaState
= CA_CHALLENGESENT
;
2723 CMemFile
fileAnswer((byte
*) memstr
.GetOutputStreamBuffer()->GetBufferStart(), memstr
.GetLength());
2724 CPacket
* packet
= new CPacket(fileAnswer
, OP_EMULEPROT
, OP_CHATCAPTCHAREQ
);
2725 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2726 AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % m_strCaptchaChallenge
% packet
->GetPacketSize());
2727 SafeSendPacket(packet
);
2733 // client doesn't support captchas, but we require them, tell him that it's not going to work out
2734 // with an answer message (will not be shown and doesn't count as sent message)
2735 if (m_cCaptchasSent
< 1) { // don't send this notifier more than once
2737 // always sent in english
2738 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."));
2739 AddDebugLogLineN(logClient
, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo());
2741 AddDebugLogLineN(logClient
, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo());
2745 } else { // (GetChatCaptchaState() == CA_CHALLENGESENT)
2746 // this message must be the answer to the captcha request we sent him, let's verify
2747 wxASSERT( !m_strCaptchaChallenge
.IsEmpty() );
2748 if (m_strCaptchaChallenge
.CmpNoCase(message
.Trim().Right(std::min(message
.Length(), m_strCaptchaChallenge
.Length()))) == 0) {
2750 AddDebugLogLineN(logClient
, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo());
2751 m_nChatCaptchaState
= CA_CAPTCHASOLVED
; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved
2752 // replace captchaanswer with withheld message and show it
2753 message
= m_strCaptchaPendingMsg
;
2754 m_cCaptchasSent
= 0;
2755 m_strCaptchaChallenge
= wxEmptyString
;
2756 CPacket
* packet
= new CPacket(OP_CHATCAPTCHARES
, 1, OP_EMULEPROT
, false);
2757 byte statusResponse
= 0; // status response
2758 packet
->CopyToDataBuffer(0, &statusResponse
, 1);
2759 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2760 SafeSendPacket(packet
);
2761 } else { // wrong, cleanup and ignore
2762 AddDebugLogLineN(logClient
, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo());
2763 m_nChatCaptchaState
= CA_NONE
;
2764 m_strCaptchaChallenge
= wxEmptyString
;
2765 m_strCaptchaPendingMsg
= wxEmptyString
;
2766 CPacket
* packet
= new CPacket(OP_CHATCAPTCHARES
, 1, OP_EMULEPROT
, false);
2767 byte statusResponse
= (m_cCaptchasSent
< 3) ? 1 : 2; // status response
2768 packet
->CopyToDataBuffer(0, &statusResponse
, 1);
2769 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2770 SafeSendPacket(packet
);
2771 return; // nothing more todo
2777 if (thePrefs::IsAdvancedSpamfilterEnabled() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P )
2778 bool bIsSpam
= false;
2782 // first fixed criteria: If a client sends me an URL in his first message before I respond to him
2783 // there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P
2784 if (GetMessagesSent() == 0) {
2785 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("|")));
2786 for (size_t pos
= urlindicators
.GetCount(); pos
--;) {
2787 if (message
.Find(urlindicators
[pos
]) != wxNOT_FOUND
) {
2792 // second fixed criteria: he sent me 4 or more messages and I didn't answer him once
2793 if (GetMessagesReceived() > 3) {
2799 AddDebugLogLineN(logClient
, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName());
2801 theApp
->amuledlg
->m_chatwnd
->EndSession(GUI_ID(GetIP(),GetUserPort()));
2807 wxString logMsg
= CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP();
2808 if(thePrefs::ShowMessagesInLog()) {
2809 logMsg
+= wxT(": ") + message
;
2811 AddLogLineC(logMsg
);
2812 IncMessagesReceived();
2814 Notify_ChatProcessMsg(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message
);
2817 bool CUpDownClient::IsMessageFiltered(const wxString
& message
)
2819 bool filtered
= false;
2820 // If we're chatting to the guy, we don't want to filter!
2821 if (GetChatState() != MS_CHATTING
) {
2822 if (thePrefs::MsgOnlyFriends() && !IsFriend()) {
2824 } else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) {
2826 } else if (thePrefs::MustFilterMessages()) {
2827 filtered
= thePrefs::IsMessageFiltered(message
);
2839 void CUpDownClient::SendFirewallCheckUDPRequest()
2841 wxASSERT(GetKadState() == KS_FWCHECK_UDP
);
2843 if (!Kademlia::CKademlia::IsRunning()) {
2844 SetKadState(KS_NONE
);
2846 } else if (GetUploadState() != US_NONE
|| GetDownloadState() != DS_NONE
|| GetChatState() != MS_NONE
|| GetKadVersion() <= 5 || GetKadPort() == 0) {
2847 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
2848 SetKadState(KS_NONE
);
2853 data
.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
2854 data
.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
2855 data
.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
2856 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_FWCHECKUDPREQ
);
2857 theStats::AddUpOverheadKad(packet
->GetPacketSize());
2858 SafeSendPacket(packet
);
2861 void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile
* data
)
2863 if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL
) {
2864 //DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
2868 // first search if we know this IP already, if so the result might be biased and we need tell the requester
2869 bool errorAlreadyKnown
= false;
2870 if (GetUploadState() != US_NONE
|| GetDownloadState() != DS_NONE
|| GetChatState() != MS_NONE
) {
2871 errorAlreadyKnown
= true;
2872 } else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL
) {
2873 errorAlreadyKnown
= true;
2876 uint16_t remoteInternPort
= data
->ReadUInt16();
2877 uint16_t remoteExternPort
= data
->ReadUInt16();
2878 uint32_t senderKey
= data
->ReadUInt32();
2879 if (remoteInternPort
== 0) {
2880 //DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
2883 // if (senderKey == 0)
2884 // DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
2886 CMemFile testPacket1
;
2887 testPacket1
.WriteUInt8(errorAlreadyKnown
? 1 : 0);
2888 testPacket1
.WriteUInt16(remoteInternPort
);
2889 DebugSend(Kad2FirewallUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort
);
2890 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1
, KADEMLIA2_FIREWALLUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort
, Kademlia::CKadUDPKey(senderKey
, theApp
->GetPublicIP(false)), NULL
);
2892 // if the client has a router with PAT (and therefore a different extern port than intern), test this port too
2893 if (remoteExternPort
!= 0 && remoteExternPort
!= remoteInternPort
) {
2894 CMemFile testPacket2
;
2895 testPacket2
.WriteUInt8(errorAlreadyKnown
? 1 : 0);
2896 testPacket2
.WriteUInt16(remoteExternPort
);
2897 DebugSend(Kad2FirewalledUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort
);
2898 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2
, KADEMLIA2_FIREWALLUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort
, Kademlia::CKadUDPKey(senderKey
, theApp
->GetPublicIP(false)), NULL
);
2900 //DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
2903 void CUpDownClient::SetConnectOptions(uint8_t options
, bool encryption
, bool callback
)
2905 SetCryptLayerSupport((options
& 0x01) != 0 && encryption
);
2906 SetCryptLayerRequest((options
& 0x02) != 0 && encryption
);
2907 SetCryptLayerRequires((options
& 0x04) != 0 && encryption
);
2908 SetDirectUDPCallbackSupport((options
& 0x08) != 0 && callback
);
2912 #ifdef DEBUG_ZOMBIE_CLIENTS
2913 void CUpDownClient::Unlink(const wxString
& from
)
2915 std::multiset
<wxString
>::iterator it
= m_linkedFrom
.find(from
);
2916 if (it
!= m_linkedFrom
.end()) {
2917 m_linkedFrom
.erase(it
);
2921 if (m_linkedDebug
) {
2922 AddLogLineN(CFormat(wxT("Last reference to client %d %p unlinked, delete it.")) % ECID() % this);
2930 void CUpDownClient::Unlink()
2940 // File_checked_for_headers