2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2011 Merkur ( devs@emule-project.net / http://www.emule-project.net )
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
31 #include "SharedFileList.h" // Needed for CSharedFileList
33 #include <protocol/Protocols.h>
34 #include <protocol/ed2k/Client2Client/TCP.h>
35 #include <protocol/ed2k/ClientSoftware.h>
36 #include <protocol/kad/Client2Client/UDP.h>
37 #include <protocol/kad2/Constants.h>
38 #include <protocol/kad2/Client2Client/TCP.h>
39 #include <protocol/kad2/Client2Client/UDP.h>
41 #include <common/ClientVersion.h>
43 #include <tags/ClientTags.h>
45 #include <zlib.h> // Needed for inflateEnd
47 #include <common/Format.h> // Needed for CFormat
49 #include "SearchList.h" // Needed for CSearchList
50 #include "DownloadQueue.h" // Needed for CDownloadQueue
51 #include "UploadQueue.h" // Needed for CUploadQueue
52 #include "IPFilter.h" // Needed for CIPFilter
53 #include "ServerConnect.h" // Needed for CServerConnect
54 #include "ClientCredits.h" // Needed for CClientCredits
55 #include "ClientCreditsList.h" // Needed for CClientCreditsList
56 #include "Server.h" // Needed for CServer
57 #include "Preferences.h" // Needed for CPreferences
58 #include "MemFile.h" // Needed for CMemFile
59 #include "Packet.h" // Needed for CPacket
60 #include "Friend.h" // Needed for CFriend
61 #include "ClientList.h" // Needed for CClientList
63 #include "amuleDlg.h" // Needed for CamuleDlg
64 #include "CaptchaDialog.h" // Needed for CCaptchaDialog
65 #include "CaptchaGenerator.h"
66 #include "ChatWnd.h" // Needed for CChatWnd
68 #include "amule.h" // Needed for theApp
69 #include "PartFile.h" // Needed for CPartFile
70 #include "ClientTCPSocket.h" // Needed for CClientTCPSocket
71 #include "ListenSocket.h" // Needed for CListenSocket
72 #include "FriendList.h" // Needed for CFriendList
73 #include "Statistics.h" // Needed for theStats
74 #include "ClientUDPSocket.h"
76 #include "DataToText.h" // Needed for GetSoftName()
77 #include "GuiEvents.h" // Needed for Notify_
78 #include "ServerList.h" // For CServerList
80 #include "kademlia/kademlia/Kademlia.h"
81 #include "kademlia/kademlia/Prefs.h"
82 #include "kademlia/kademlia/Search.h"
83 #include "kademlia/kademlia/UDPFirewallTester.h"
84 #include "kademlia/routing/RoutingZone.h"
87 //#define __PACKET_DEBUG__
90 // some client testing variables
91 static wxString crash_name
= wxT("[Invalid User Name]");
92 static wxString empty_name
= wxT("[Empty User Name]");
94 // members of CUpDownClient
95 // which are used by down and uploading functions
98 CUpDownClient::CUpDownClient(CClientTCPSocket
* sender
)
109 CUpDownClient::CUpDownClient(uint16 in_port
, uint32 in_userid
, uint32 in_serverip
, uint16 in_serverport
, CPartFile
* in_reqfile
, bool ed2kID
, bool checkfriend
)
113 m_nUserPort
= in_port
;
115 if(ed2kID
&& !IsLowID(in_userid
)) {
116 SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid
) );
118 SetUserIDHybrid( in_userid
);
121 //If highID and ED2K source, incoming ID and IP are equal..
122 //If highID and Kad source, incoming IP needs swap for the IP
126 m_nConnectIP
= in_userid
;
128 m_nConnectIP
= wxUINT32_SWAP_ALWAYS(in_userid
);
130 // Will be on right endianess now
131 m_FullUserIP
= m_nConnectIP
;
134 m_dwServerIP
= in_serverip
;
135 m_nServerPort
= in_serverport
;
136 SetRequestFile( in_reqfile
);
140 if ((m_Friend
= theApp
->friendlist
->FindFriend(CMD4Hash(), m_dwUserIP
, m_nUserPort
)) != NULL
){
141 m_Friend
->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::CUpDownClient m_Friend->LinkClient")));
143 // avoid that an unwanted client instance keeps a friend slot
144 m_bFriendSlot
= false;
150 void CUpDownClient::Init()
153 #ifdef DEBUG_ZOMBIE_CLIENTS
154 m_linkedDebug
= false;
156 m_bAddNextConnect
= false;
158 m_byChatstate
= MS_NONE
;
159 m_nKadState
= KS_NONE
;
160 m_nChatCaptchaState
= CA_NONE
;
162 m_reqfile
= NULL
; // No file required yet
163 m_nTransferredUp
= 0;
168 bytesReceivedCycle
= 0;
170 m_iFileListRequested
= 0;
171 m_dwLastUpRequest
= 0;
172 m_bEmuleProtocol
= false;
173 m_bCompleteSource
= false;
174 m_bFriendSlot
= false;
175 m_bCommentDirty
= false;
176 m_bReaskPending
= false;
177 m_bUDPPending
= false;
180 m_dwLastAskedTime
= 0;
181 m_nDownloadState
= DS_NONE
;
183 m_nTransferredDown
= 0;
184 m_nUploadState
= US_NONE
;
185 m_dwLastBlockReceived
= 0;
186 m_bUnicodeSupport
= false;
188 m_fSentOutOfPartReqs
= 0;
189 m_nCurQueueSessionPayloadUp
= 0;
190 m_addedPayloadQueueSession
= 0;
192 m_nSumForAvgUpDataRate
= 0;
194 m_nRemoteQueueRank
= 0;
195 m_nOldRemoteQueueRank
= 0;
196 m_dwLastSourceRequest
= 0;
197 m_dwLastSourceAnswer
= 0;
198 m_dwLastAskedForSources
= 0;
200 m_SecureIdentState
= IS_UNAVAILABLE
;
201 m_dwLastSignatureIP
= 0;
203 m_byInfopacketsReceived
= IP_NONE
;
210 m_clientSoft
=SO_UNKNOWN
;
212 m_bRemoteQueueFull
= false;
213 m_HasValidHash
= false;
216 m_fHashsetRequesting
= 0;
217 m_fSharedDirectories
= 0;
218 m_lastPartAsked
= 0xffff;
219 m_nUpCompleteSourcesCount
= 0;
220 m_waitingPosition
= 0;
222 m_lastRefreshedDLDisplay
= 0;
223 m_bHelloAnswerPending
= false;
224 m_fSentCancelTransfer
= 0;
225 m_Aggressiveness
= 0;
226 m_LastFileRequest
= 0;
228 m_clientState
= CS_NEW
;
230 ClearHelloProperties();
232 m_pReqFileAICHHash
= NULL
;
234 m_fAICHRequested
= 0;
235 m_fSupportsLargeFiles
= 0;
236 m_fExtMultiPacket
= 0;
243 m_fNeedOurPublicIP
= false;
244 m_bHashsetRequested
= false;
246 m_lastDownloadingPart
= 0;
248 m_uploadingfile
= NULL
;
250 m_OSInfo_sent
= false;
258 m_nSourceFrom
= SF_NONE
;
261 SetIP(m_socket
->GetPeerInt());
267 m_lastClientSoft
= (uint32
)(-1);
268 m_lastClientVersion
= 0;
270 /* Creation time (for buddies timeout) */
271 m_nCreationTime
= ::GetTickCount();
273 m_MaxBlockRequests
= STANDARD_BLOCKS_REQUEST
; // Safe starting amount
275 m_last_block_start
= 0;
278 SetLastBuddyPingPongTime();
279 m_fRequestsCryptLayer
= 0;
280 m_fSupportsCryptLayer
= 0;
281 m_fRequiresCryptLayer
= 0;
282 m_fSupportsSourceEx2
= 0;
283 m_fSupportsCaptcha
= 0;
284 m_fDirectUDPCallback
= 0;
285 m_dwDirectCallbackTimeout
= 0;
287 m_hasbeenobfuscatinglately
= false;
290 m_cMessagesReceived
= 0;
296 CUpDownClient::~CUpDownClient()
299 if (!connection_reason
.IsEmpty()) {
300 AddDebugLogLineN(logClient
, wxT("Client to check for ") + connection_reason
+ wxT(" was deleted without connection."));
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);
314 // The socket should have been removed in Safe_Delete, but it
315 // doesn't hurt to have an extra check.
317 m_socket
->Safe_Delete();
322 ClearUploadBlockRequests();
323 ClearDownloadBlockRequests();
325 DeleteContents(m_WaitingPackets_list
);
327 // Allow detection of deleted clients that didn't go through Safe_Delete
328 m_clientState
= CS_DYING
;
332 void CUpDownClient::ClearHelloProperties()
337 m_byEmuleVersion
= 0;
338 m_bySourceExchange1Ver
= 0;
339 m_byAcceptCommentVer
= 0;
340 m_byExtendedRequestsVer
= 0;
341 m_byCompatibleClient
= 0;
343 m_bySupportSecIdent
= 0;
344 m_bSupportsPreview
= 0;
345 m_nClientVersion
= 0;
346 m_fSharedDirectories
= 0;
348 m_fOsInfoSupport
= 0;
349 m_fValueBasedTypeTags
= 0;
352 m_fRequestsCryptLayer
= 0;
353 m_fSupportsCryptLayer
= 0;
354 m_fRequiresCryptLayer
= 0;
355 m_fSupportsSourceEx2
= 0;
356 m_fSupportsCaptcha
= 0;
357 m_fDirectUDPCallback
= 0;
360 m_fNoViewSharedFiles
= true; // that's a sensible default to assume until we get the real value
361 m_bUnicodeSupport
= false;
364 bool CUpDownClient::ProcessHelloPacket(const byte
* pachPacket
, uint32 nSize
)
366 const CMemFile
data(pachPacket
,nSize
);
367 uint8 hashsize
= data
.ReadUInt8();
368 if ( 16 != hashsize
) {
370 * Hint: We can not accept other sizes here because:
371 * - the magic number is spread all over the source
372 * - the answer packet lacks the size field
374 throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
376 // eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
377 ClearHelloProperties();
379 return ProcessHelloTypePacket(data
);
382 void CUpDownClient::Safe_Delete()
384 // Because we are delaying the deletion, we might end up trying to delete
385 // it twice, however, this is normal and shouldn't trigger any failures
386 if ( m_clientState
== CS_DYING
) {
390 // If called from background, post an event to process it in main thread
391 if (!wxThread::IsMain()) {
392 CoreNotify_Client_Delete(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete CoreNotify_Client_Delete")));
396 m_clientState
= CS_DYING
;
398 // Make sure client doesn't get deleted until this method is finished
399 CClientRef
ref(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete reflocker")));
401 // Close the socket to avoid any more connections and related events
403 m_socket
->Safe_Delete();
408 // Remove the client from the clientlist if we still have it
409 if ( theApp
->clientlist
) {
410 theApp
->clientlist
->RemoveClient( this );
413 // Doing what RemoveClient used to do. Just to be sure...
414 if (theApp
->uploadqueue
) {
415 theApp
->uploadqueue
->RemoveFromUploadQueue(this);
416 theApp
->uploadqueue
->RemoveFromWaitingQueue(this);
418 if (theApp
->downloadqueue
) {
419 theApp
->downloadqueue
->RemoveSource(this);
422 // For security, remove it from the lists unconditionally.
423 Notify_SharedCtrlRemoveClient(ECID(), (CKnownFile
*)NULL
);
424 Notify_SourceCtrlRemoveSource(ECID(), (CPartFile
*)NULL
);
426 if (IsAICHReqPending()){
427 m_fAICHRequested
= FALSE
;
428 CAICHHashSet::ClientAICHRequestFailed(this);
432 m_Friend
->UnLinkClient(); // this notifies
436 if (m_iRating
>0 || !m_strComment
.IsEmpty()) {
438 m_strComment
.Clear();
440 m_reqfile
->UpdateFileRatingCommentAvail();
444 // Ensure that source-counts gets updated in case
445 // of a source not on the download-queue
446 SetRequestFile( NULL
);
448 SetUploadFileID(NULL
);
450 delete m_pReqFileAICHHash
;
451 m_pReqFileAICHHash
= NULL
;
453 #ifdef DEBUG_ZOMBIE_CLIENTS
455 AddLogLineC(CFormat(wxT("Client %d still linked in %d places: %s")) % ECID() % (m_linked
- 1) % GetLinkedFrom());
456 m_linkedDebug
= true;
462 bool CUpDownClient::ProcessHelloAnswer(const byte
* pachPacket
, uint32 nSize
)
464 const CMemFile
data(pachPacket
,nSize
);
465 bool bIsMule
= ProcessHelloTypePacket(data
);
466 m_bHelloAnswerPending
= false;
470 bool CUpDownClient::ProcessHelloTypePacket(const CMemFile
& data
)
472 uint32 dwEmuleTags
= 0;
474 CMD4Hash hash
= data
.ReadHash();
476 SetUserIDHybrid( data
.ReadUInt32() );
477 uint16 nUserPort
= data
.ReadUInt16(); // hmm clientport is sent twice - why?
478 uint32 tagcount
= data
.ReadUInt32();
479 for (uint32 i
= 0;i
< tagcount
; i
++){
480 CTag
temptag(data
, true);
481 switch(temptag
.GetNameID()){
483 m_Username
= temptag
.GetStr();
487 m_nClientVersion
= temptag
.GetInt();
491 if (temptag
.IsStr()) {
492 m_strModVersion
= temptag
.GetStr();
493 } else if (temptag
.IsInt()) {
494 m_strModVersion
= CFormat(wxT("ModID=%u")) % temptag
.GetInt();
496 m_strModVersion
= wxT("ModID=<Unknown>");
502 nUserPort
= temptag
.GetInt();
505 case CT_EMULE_UDPPORTS
:
508 SetKadPort((temptag
.GetInt() >> 16) & 0xFFFF);
509 m_nUDPPort
= temptag
.GetInt() & 0xFFFF;
511 #ifdef __PACKET_DEBUG__
512 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort
% m_nKadPort
);
516 case CT_EMULE_BUDDYIP
:
518 m_nBuddyIP
= temptag
.GetInt();
519 #ifdef __PACKET_DEBUG__
520 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP
% Uint32toStringIP(m_nBuddyIP
));
524 case CT_EMULE_BUDDYUDP
:
525 // 16 --Reserved for future use--
527 m_nBuddyPort
= (uint16
)temptag
.GetInt();
528 #ifdef __PACKET_DEBUG__
529 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort
);
533 case CT_EMULE_MISCOPTIONS1
: {
534 // 3 AICH Version (0 = not supported)
537 // 4 Data compression version
542 // 1 PeerCache supported
543 // 1 No 'View Shared Files' supported
546 uint32 flags
= temptag
.GetInt();
547 m_fSupportsAICH
= (flags
>> (4*7+1)) & 0x07;
548 m_bUnicodeSupport
= (flags
>> 4*7) & 0x01;
549 m_byUDPVer
= (flags
>> 4*6) & 0x0f;
550 m_byDataCompVer
= (flags
>> 4*5) & 0x0f;
551 m_bySupportSecIdent
= (flags
>> 4*4) & 0x0f;
552 m_bySourceExchange1Ver
= (flags
>> 4*3) & 0x0f;
553 m_byExtendedRequestsVer
= (flags
>> 4*2) & 0x0f;
554 m_byAcceptCommentVer
= (flags
>> 4*1) & 0x0f;
555 m_fNoViewSharedFiles
= (flags
>> 1*2) & 0x01;
556 m_bMultiPacket
= (flags
>> 1*1) & 0x01;
557 m_fSupportsPreview
= (flags
>> 1*0) & 0x01;
559 #ifdef __PACKET_DEBUG__
560 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
561 AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer
);
562 AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer
);
563 AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent
);
564 AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver
);
565 AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer
);
566 AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer
);
567 AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles
);
568 AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket
);
569 AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories
);
570 AddLogLineNS(wxT("That's all."));
576 case CT_EMULE_MISCOPTIONS2
:
578 // 1 Direct UDP Callback supported and available
579 // 1 Supports ChatCaptchas
580 // 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
581 // 1 Requires CryptLayer
582 // 1 Requests CryptLayer
583 // 1 Supports CryptLayer
584 // 1 Reserved (ModBit)
585 // 1 Ext Multipacket (Hash+Size instead of Hash)
586 // 1 Large Files (includes support for 64bit tags)
587 // 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
588 m_fDirectUDPCallback
= (temptag
.GetInt() >> 12) & 0x01;
589 m_fSupportsCaptcha
= (temptag
.GetInt() >> 11) & 0x01;
590 m_fSupportsSourceEx2
= (temptag
.GetInt() >> 10) & 0x01;
591 m_fRequiresCryptLayer
= (temptag
.GetInt() >> 9) & 0x01;
592 m_fRequestsCryptLayer
= (temptag
.GetInt() >> 8) & 0x01;
593 m_fSupportsCryptLayer
= (temptag
.GetInt() >> 7) & 0x01;
595 m_fExtMultiPacket
= (temptag
.GetInt() >> 5) & 0x01;
596 m_fSupportsLargeFiles
= (temptag
.GetInt() >> 4) & 0x01;
597 m_byKadVersion
= (temptag
.GetInt() >> 0) & 0x0f;
600 m_fRequestsCryptLayer
&= m_fSupportsCryptLayer
;
601 m_fRequiresCryptLayer
&= m_fRequestsCryptLayer
;
603 #ifdef __PACKET_DEBUG__
604 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
605 AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback
);
606 AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha
);
607 AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2
);
608 AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer
);
609 AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer
);
610 AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer
);
611 AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket
);
612 AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles
);
613 AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion
);
614 AddLogLineNS(wxT("That's all."));
618 // Special tag for Compat. Clients Misc options.
619 case CT_EMULECOMPAT_OPTIONS
:
620 // 1 Operative System Info
621 // 1 Value-based-type int tags (experimental!)
622 m_fValueBasedTypeTags
= (temptag
.GetInt() >> 1*1) & 0x01;
623 m_fOsInfoSupport
= (temptag
.GetInt() >> 1*0) & 0x01;
626 case CT_EMULE_VERSION
:
627 // 8 Compatible Client ID
628 // 7 Mjr Version (Doesn't really matter..)
629 // 7 Min Version (Only need 0-99)
630 // 3 Upd Version (Only need 0-5)
631 // 7 Bld Version (Only need 0-99)
632 m_byCompatibleClient
= (temptag
.GetInt() >> 24);
633 m_nClientVersion
= temptag
.GetInt() & 0x00ffffff;
634 m_byEmuleVersion
= 0x99;
635 m_fSharedDirectories
= 1;
641 m_nUserPort
= nUserPort
;
642 m_dwServerIP
= data
.ReadUInt32();
643 m_nServerPort
= data
.ReadUInt16();
644 // Hybrid now has an extra uint32.. What is it for?
645 // Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
646 if ( data
.GetLength() - data
.GetPosition() == sizeof(uint32
) ) {
647 uint32 test
= data
.ReadUInt32();
648 /*if (test == 'KDLM') below kdlm is converted to ascii values.
649 This fixes a warning with gcc 3.4.
652 if (test
== 0x4b444c4d) { //if it's == "KDLM"
656 m_fSharedDirectories
= 1;
661 SetIP(m_socket
->GetPeerInt());
663 throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
666 if (thePrefs::AddServersFromClient()) {
667 CServer
* addsrv
= new CServer(m_nServerPort
, Uint32toStringIP(m_dwServerIP
));
668 addsrv
->SetListName(addsrv
->GetAddress());
669 if (!theApp
->AddServer(addsrv
)) {
674 //(a)If this is a highID user, store the ID in the Hybrid format.
675 //(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
676 //(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
677 //because they will send a ID that is the same as their IP..
678 if(!HasLowID() || m_nUserIDHybrid
== 0 || m_nUserIDHybrid
== m_dwUserIP
) {
679 SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP
));
682 // get client credits
683 CClientCredits
* pFoundCredits
= theApp
->clientcredits
->GetCredit(m_UserHash
);
684 if (credits
== NULL
){
685 credits
= pFoundCredits
;
686 if (!theApp
->clientlist
->ComparePriorUserhash(m_dwUserIP
, m_nUserPort
, pFoundCredits
)){
687 AddDebugLogLineN( logClient
, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
690 } else if (credits
!= pFoundCredits
){
691 // userhash change ok, however two hours "waittime" before it can be used
692 credits
= pFoundCredits
;
693 AddDebugLogLineN( logClient
, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
697 if ((m_Friend
= theApp
->friendlist
->FindFriend(m_UserHash
, m_dwUserIP
, m_nUserPort
)) != NULL
){
698 m_Friend
->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::ProcessHelloTypePacket m_Friend->LinkClient")));
700 // avoid that an unwanted client instance keeps a friend slot
701 SetFriendSlot(false);
707 m_byInfopacketsReceived
|= IP_EDONKEYPROTPACK
;
709 // check if at least CT_EMULEVERSION was received, all other tags are optional
710 bool bIsMule
= (dwEmuleTags
& 0x04) == 0x04;
712 m_bEmuleProtocol
= true;
713 m_byInfopacketsReceived
|= IP_EMULEPROTPACK
;
716 if (GetKadPort() && GetKadVersion() > 1) {
717 Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort());
724 bool CUpDownClient::SendHelloPacket()
726 if (m_socket
== NULL
) {
731 // if IP is filtered, don't greet him but disconnect...
732 if (theApp
->ipfilter
->IsFiltered(m_socket
->GetPeerInt())) {
733 if (Disconnected(wxT("IPFilter"))) {
741 data
.WriteUInt8(16); // size of userhash
742 SendHelloTypePacket(&data
);
744 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_HELLO
);
745 theStats::AddUpOverheadOther(packet
->GetPacketSize());
746 SendPacket(packet
,true);
747 m_bHelloAnswerPending
= true;
748 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
752 void CUpDownClient::SendMuleInfoPacket(bool bAnswer
, bool OSInfo
) {
754 if (m_socket
== NULL
){
759 CPacket
* packet
= NULL
;
762 data
.WriteUInt8(CURRENT_VERSION_SHORT
);
766 // Special MuleInfo packet for clients supporting it.
767 // This means aMule >= 2.0.0 and Hydranode
769 // Violently mark it as special Mule Info packet
770 // Sending this makes non-supporting-osinfo clients to refuse to read this
771 // packet. Anyway, this packet should NEVER get to non-supporting clients.
773 data
.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
775 data
.WriteUInt32(1); // One Tag (OS_INFO)
777 CTagString
tag1(ET_OS_INFO
,theApp
->GetOSType());
778 tag1
.WriteTagToFile(&data
);
780 m_OSInfo_sent
= true; // So we don't send it again
784 // Normal MuleInfo packet
786 // Kry - There's no point on upgrading to VBT tags here
787 // as no client supporting it uses mule info packet.
789 data
.WriteUInt8(EMULE_PROTOCOL
);
794 CTagInt32
tag1(ET_COMPRESSION
,1);
795 tag1
.WriteTagToFile(&data
);
796 CTagInt32
tag2(ET_UDPVER
,4);
797 tag2
.WriteTagToFile(&data
);
798 CTagInt32
tag3(ET_UDPPORT
, thePrefs::GetEffectiveUDPPort());
799 tag3
.WriteTagToFile(&data
);
800 CTagInt32
tag4(ET_SOURCEEXCHANGE
,3);
801 tag4
.WriteTagToFile(&data
);
802 CTagInt32
tag5(ET_COMMENTS
,1);
803 tag5
.WriteTagToFile(&data
);
804 CTagInt32
tag6(ET_EXTENDEDREQUEST
,2);
805 tag6
.WriteTagToFile(&data
);
807 uint32 dwTagValue
= (theApp
->CryptoAvailable() ? 3 : 0);
808 // Kry - Needs the preview code from eMule
810 // set 'Preview supported' only if 'View Shared Files' allowed
811 if (thePrefs::CanSeeShares() != vsfaNobody) {
815 CTagInt32
tag7(ET_FEATURES
, dwTagValue
);
816 tag7
.WriteTagToFile(&data
);
818 CTagInt32
tag8(ET_COMPATIBLECLIENT
,SO_AMULE
);
819 tag8
.WriteTagToFile(&data
);
821 // Support for tag ET_MOD_VERSION
822 wxString
mod_name(MOD_VERSION_LONG
);
823 CTagString
tag9(ET_MOD_VERSION
, mod_name
);
824 tag9
.WriteTagToFile(&data
);
829 packet
= new CPacket(data
, OP_EMULEPROT
, (bAnswer
? OP_EMULEINFOANSWER
: OP_EMULEINFO
));
832 theStats::AddUpOverheadOther(packet
->GetPacketSize());
833 SendPacket(packet
,true,true);
838 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
840 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
843 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
849 bool CUpDownClient::ProcessMuleInfoPacket(const byte
* pachPacket
, uint32 nSize
)
851 uint8 protocol_version
;
853 const CMemFile
data(pachPacket
,nSize
);
855 // The version number part of this packet will soon be useless since
856 // it is only able to go to v.99. Why the version is a uint8 and why
857 // it was not done as a tag like the eDonkey hello packet is not known.
858 // Therefore, sooner or later, we are going to have to switch over to
859 // using the eDonkey hello packet to set the version. No sense making
860 // a third value sent for versions.
861 uint8 mule_version
= data
.ReadUInt8();
862 protocol_version
= data
.ReadUInt8();
863 uint32 tagcount
= data
.ReadUInt32();
864 if (protocol_version
== 0xFF) {
865 // OS Info supporting clients sending a recycled Mule info packet
866 for (uint32 i
= 0;i
< tagcount
; i
++){
867 CTag
temptag(data
, true);
868 switch(temptag
.GetNameID()){
870 // Special tag, only supporting clients (aMule/Hydranode)
871 // It was recycled from a mod's tag, so if the other side
872 // is not supporting OS Info, we're seriously fucked up :)
873 m_sClientOSInfo
= temptag
.GetStr();
875 // If we didn't send our OSInfo to this client, just send it
876 if (!m_OSInfo_sent
) {
877 SendMuleInfoPacket(false,true);
884 // Your ad... er... I mean TAG, here
891 // Old eMule sending tags
892 m_byCompatibleClient
= 0;
893 m_byEmuleVersion
= mule_version
;
895 if( m_byEmuleVersion
== 0x2B ) {
896 m_byEmuleVersion
= 0x22;
899 if (!(m_bEmuleProtocol
= (protocol_version
== EMULE_PROTOCOL
))) {
903 for (uint32 i
= 0;i
< tagcount
; i
++){
904 CTag
temptag(data
, false);
905 switch(temptag
.GetNameID()){
907 // Bits 31- 8: 0 - reserved
908 // Bits 7- 0: data compression version
909 m_byDataCompVer
= temptag
.GetInt();
913 // Bits 31-16: 0 - reserved
914 // Bits 15- 0: UDP port
915 m_nUDPPort
= temptag
.GetInt();
919 // Bits 31- 8: 0 - reserved
920 // Bits 7- 0: UDP protocol version
921 m_byUDPVer
= temptag
.GetInt();
924 case ET_SOURCEEXCHANGE
:
925 // Bits 31- 8: 0 - reserved
926 // Bits 7- 0: source exchange protocol version
927 m_bySourceExchange1Ver
= temptag
.GetInt();
931 // Bits 31- 8: 0 - reserved
932 // Bits 7- 0: comments version
933 m_byAcceptCommentVer
= temptag
.GetInt();
936 case ET_EXTENDEDREQUEST
:
937 // Bits 31- 8: 0 - reserved
938 // Bits 7- 0: extended requests version
939 m_byExtendedRequestsVer
= temptag
.GetInt();
942 case ET_COMPATIBLECLIENT
:
943 // Bits 31- 8: 0 - reserved
944 // Bits 7- 0: compatible client ID
945 m_byCompatibleClient
= temptag
.GetInt();
949 // Bits 31- 8: 0 - reserved
951 // Bit 6- 0: secure identification
952 m_bySupportSecIdent
= temptag
.GetInt() & 3;
953 m_bSupportsPreview
= (temptag
.GetInt() & 128) > 0;
958 if (temptag
.IsStr()) {
959 m_strModVersion
= temptag
.GetStr();
960 } else if (temptag
.IsInt()) {
961 m_strModVersion
= CFormat(wxT("ModID=%u")) % temptag
.GetInt();
963 m_strModVersion
= wxT("ModID=<Unknown>");
969 AddDebugLogLineN( logPacketErrors
,
970 CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
971 % temptag
.GetFullInfo()
972 % GetClientFullInfo()
979 if( m_byDataCompVer
== 0 ){
980 m_bySourceExchange1Ver
= 0;
981 m_byExtendedRequestsVer
= 0;
982 m_byAcceptCommentVer
= 0;
986 //implicitly supported options by older clients
987 //in the future do not use version to guess about new features
988 if(m_byEmuleVersion
< 0x25 && m_byEmuleVersion
> 0x22) {
992 if(m_byEmuleVersion
< 0x25 && m_byEmuleVersion
> 0x21) {
993 m_bySourceExchange1Ver
= 1;
996 if(m_byEmuleVersion
== 0x24) {
997 m_byAcceptCommentVer
= 1;
1000 // Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
1001 // the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
1002 // directory which has a trailing backslash.
1003 if(m_byEmuleVersion
>= 0x28 && !m_bIsML
) {// MLdonkey currently does not support shared directories
1004 m_fSharedDirectories
= 1;
1009 m_byInfopacketsReceived
|= IP_EMULEPROTPACK
;
1012 return (protocol_version
== 0xFF); // This was a OS_Info?
1016 void CUpDownClient::SendHelloAnswer()
1018 if (m_socket
== NULL
){
1024 SendHelloTypePacket(&data
);
1025 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_HELLOANSWER
);
1026 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1027 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
1028 SendPacket(packet
,true);
1032 void CUpDownClient::SendHelloTypePacket(CMemFile
* data
)
1034 data
->WriteHash(thePrefs::GetUserHash());
1035 data
->WriteUInt32(theApp
->GetID());
1036 data
->WriteUInt16(thePrefs::GetPort());
1038 uint32 tagcount
= 6;
1040 if( theApp
->clientlist
->GetBuddy() && theApp
->IsFirewalled() ) {
1043 tagcount
++; // eMule misc flags 2 (kad version)
1046 // Kry - This is the tagcount!!! Be sure to update it!!
1047 // Last update: CT_EMULECOMPAT_OPTIONS included
1048 data
->WriteUInt32(tagcount
+ 1);
1050 data
->WriteUInt32(tagcount
); // NO MOD_VERSION
1054 CTagString
tagname(CT_NAME
,thePrefs::GetUserNick());
1055 tagname
.WriteTagToFile(data
, utf8strRaw
);
1057 CTagVarInt
tagversion(CT_VERSION
, EDONKEYVERSION
, GetVBTTags() ? 0 : 32);
1058 tagversion
.WriteTagToFile(data
);
1061 uint32 kadUDPPort
= 0;
1063 if(Kademlia::CKademlia::IsConnected()) {
1064 if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
1065 kadUDPPort
= Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
1067 kadUDPPort
= Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
1071 CTagVarInt
tagUdpPorts(CT_EMULE_UDPPORTS
, (kadUDPPort
<< 16) | ((uint32
)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
1072 tagUdpPorts
.WriteTagToFile(data
);
1074 if( theApp
->clientlist
->GetBuddy() && theApp
->IsFirewalled() ) {
1075 CTagVarInt
tagBuddyIP(CT_EMULE_BUDDYIP
, theApp
->clientlist
->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
1076 tagBuddyIP
.WriteTagToFile(data
);
1078 CTagVarInt
tagBuddyPort(CT_EMULE_BUDDYUDP
,
1080 ((uint32
)theApp
->clientlist
->GetBuddy()->GetUDPPort() )
1081 , GetVBTTags() ? 0 : 32);
1082 tagBuddyPort
.WriteTagToFile(data
);
1086 CTagVarInt
tagMuleVersion(CT_EMULE_VERSION
,
1088 make_full_ed2k_version(VERSION_MJR
, VERSION_MIN
, VERSION_UPDATE
)
1090 , GetVBTTags() ? 0 : 32);
1091 tagMuleVersion
.WriteTagToFile(data
);
1094 // eMule Misc. Options #1
1095 const uint32 uUdpVer
= 4;
1096 const uint32 uDataCompVer
= 1;
1097 const uint32 uSupportSecIdent
= theApp
->CryptoAvailable() ? 3 : 0;
1098 const uint32 uSourceExchangeVer
= 3;
1099 const uint32 uExtendedRequestsVer
= 2;
1100 const uint32 uAcceptCommentVer
= 1;
1101 const uint32 uNoViewSharedFiles
= (thePrefs::CanSeeShares() == vsfaNobody
) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
1102 const uint32 uMultiPacket
= 1;
1103 const uint32 uSupportPreview
= 0; // No network preview at all.
1104 const uint32 uPeerCache
= 0; // No peercache for aMule, baby
1105 const uint32 uUnicodeSupport
= 1;
1106 const uint32 nAICHVer
= 1; // AICH is ENABLED right now.
1108 CTagVarInt
tagMisOptions(CT_EMULE_MISCOPTIONS1
,
1109 (nAICHVer
<< ((4*7)+1)) |
1110 (uUnicodeSupport
<< 4*7) |
1112 (uDataCompVer
<< 4*5) |
1113 (uSupportSecIdent
<< 4*4) |
1114 (uSourceExchangeVer
<< 4*3) |
1115 (uExtendedRequestsVer
<< 4*2) |
1116 (uAcceptCommentVer
<< 4*1) |
1117 (uPeerCache
<< 1*3) |
1118 (uNoViewSharedFiles
<< 1*2) |
1119 (uMultiPacket
<< 1*1) |
1120 (uSupportPreview
<< 1*0)
1121 , GetVBTTags() ? 0 : 32);
1122 tagMisOptions
.WriteTagToFile(data
);
1124 // eMule Misc. Options #2
1125 const uint32 uKadVersion
= KADEMLIA_VERSION
;
1126 const uint32 uSupportLargeFiles
= 1;
1127 const uint32 uExtMultiPacket
= 1;
1128 const uint32 uReserved
= 0; // mod bit
1129 const uint32 uSupportsCryptLayer
= thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
1130 const uint32 uRequestsCryptLayer
= thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
1131 const uint32 uRequiresCryptLayer
= thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
1132 const uint32 uSupportsSourceEx2
= 1;
1134 // captcha for daemon/remotegui not supported for now
1135 const uint32 uSupportsCaptcha
= 0;
1137 const uint32 uSupportsCaptcha
= 1;
1139 // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
1140 const uint32 uDirectUDPCallback
= (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
1141 && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
1143 CTagVarInt
tagMisOptions2(CT_EMULE_MISCOPTIONS2
,
1145 (uDirectUDPCallback
<< 12) |
1146 (uSupportsCaptcha
<< 11) |
1147 (uSupportsSourceEx2
<< 10) |
1148 (uRequiresCryptLayer
<< 9) |
1149 (uRequestsCryptLayer
<< 8) |
1150 (uSupportsCryptLayer
<< 7) |
1152 (uExtMultiPacket
<< 5) |
1153 (uSupportLargeFiles
<< 4) |
1155 , GetVBTTags() ? 0 : 32 );
1156 tagMisOptions2
.WriteTagToFile(data
);
1158 const uint32 nOSInfoSupport
= 1; // We support OS_INFO
1159 const uint32 nValueBasedTypeTags
= 0; // Experimental, disabled
1161 CTagVarInt
tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS
,
1162 (nValueBasedTypeTags
<< 1*1) |
1163 (nOSInfoSupport
<< 1*0)
1164 , GetVBTTags() ? 0 : 32);
1166 tagMisCompatOptions
.WriteTagToFile(data
);
1169 wxString
mod_name(MOD_VERSION_LONG
);
1170 CTagString
tagModName(ET_MOD_VERSION
, mod_name
);
1171 tagModName
.WriteTagToFile(data
);
1176 if (theApp
->IsConnectedED2K()) {
1177 dwIP
= theApp
->serverconnect
->GetCurrentServer()->GetIP();
1178 nPort
= theApp
->serverconnect
->GetCurrentServer()->GetPort();
1180 data
->WriteUInt32(dwIP
);
1181 data
->WriteUInt16(nPort
);
1185 void CUpDownClient::ProcessMuleCommentPacket(const byte
* pachPacket
, uint32 nSize
)
1188 throw CInvalidPacket(wxT("Comment packet for unknown file"));
1191 if (!m_reqfile
->IsPartFile()) {
1192 throw CInvalidPacket(wxT("Comment packet for completed file"));
1195 const CMemFile
data(pachPacket
, nSize
);
1197 uint8 rating
= data
.ReadUInt8();
1199 AddDebugLogLineN( logClient
, wxString(wxT("Invalid Rating for file '")) << m_clientFilename
<< wxT("' received: ") << rating
);
1203 AddDebugLogLineN( logClient
, wxString(wxT("Rating for file '")) << m_clientFilename
<< wxT("' received: ") << m_iRating
);
1206 // The comment is unicoded, with a uin32 len and safe read
1207 // (won't break if string size is < than advertised len)
1208 // Truncated to MAXFILECOMMENTLEN size
1209 m_strComment
= data
.ReadString((GetUnicodeSupport() != utf8strNone
), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN
);
1211 AddDebugLogLineN( logClient
, wxString(wxT("Description for file '")) << m_clientFilename
<< wxT("' received: ") << m_strComment
);
1213 // Update file rating
1214 m_reqfile
->UpdateFileRatingCommentAvail();
1218 void CUpDownClient::ClearDownloadBlockRequests()
1221 std::list
<Requested_Block_Struct
*>::iterator it
= m_DownloadBlocks_list
.begin();
1222 for (; it
!= m_DownloadBlocks_list
.end(); ++it
) {
1223 Requested_Block_Struct
* cur_block
= *it
;
1226 m_reqfile
->RemoveBlockFromList(cur_block
->StartOffset
, cur_block
->EndOffset
);
1232 m_DownloadBlocks_list
.clear();
1236 std::list
<Pending_Block_Struct
*>::iterator it
= m_PendingBlocks_list
.begin();
1237 for (; it
!= m_PendingBlocks_list
.end(); ++it
) {
1238 Pending_Block_Struct
* pending
= *it
;
1241 m_reqfile
->RemoveBlockFromList(pending
->block
->StartOffset
, pending
->block
->EndOffset
);
1244 delete pending
->block
;
1245 // Not always allocated
1246 if (pending
->zStream
){
1247 inflateEnd(pending
->zStream
);
1248 delete pending
->zStream
;
1254 m_PendingBlocks_list
.clear();
1259 bool CUpDownClient::Disconnected(const wxString
& DEBUG_ONLY(strReason
), bool bFromSocket
)
1261 //wxASSERT(theApp->clientlist->IsValidClient(this));
1263 if (HasBeenDeleted()) {
1264 AddDebugLogLineN(logClient
, wxT("Disconnected() called for already deleted client on ip ") + Uint32toStringIP(GetConnectIP()));
1268 // was this a direct callback?
1269 if (m_dwDirectCallbackTimeout
!= 0) {
1270 theApp
->clientlist
->RemoveDirectCallback(this);
1271 m_dwDirectCallbackTimeout
= 0;
1272 theApp
->clientlist
->AddDeadSource(this);
1273 AddDebugLogLineN(logClient
, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP()));
1276 if (GetKadState() == KS_QUEUED_FWCHECK_UDP
|| GetKadState() == KS_CONNECTING_FWCHECK_UDP
) {
1277 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
1278 } else if (GetKadState() == KS_FWCHECK_UDP
) {
1279 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
1280 } else if (GetKadState() == KS_CONNECTED_BUDDY
) {
1281 AddDebugLogLineN(logClient
, wxT("Buddy client disconnected - ") + strReason
);
1284 //If this is a KAD client object, just delete it!
1285 SetKadState(KS_NONE
);
1287 if (GetUploadState() == US_UPLOADING
) {
1289 theApp
->uploadqueue
->RemoveFromUploadQueue(this);
1292 if (GetDownloadState() == DS_DOWNLOADING
) {
1293 SetDownloadState(DS_ONQUEUE
);
1295 // ensure that all possible block requests are removed from the partfile
1296 ClearDownloadBlockRequests();
1298 if (GetDownloadState() == DS_CONNECTED
) {
1299 // successfully connected, but probably didn't respond to our filerequest
1300 theApp
->clientlist
->AddDeadSource(this);
1301 theApp
->downloadqueue
->RemoveSource(this);
1305 // we had still an AICH request pending, handle it
1306 if (IsAICHReqPending()) {
1307 m_fAICHRequested
= FALSE
;
1308 CAICHHashSet::ClientAICHRequestFailed(this);
1311 // The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
1312 // after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
1313 // is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
1314 if (((GetDownloadState() == DS_REQHASHSET
) || m_fHashsetRequesting
) && (m_reqfile
)) {
1315 m_reqfile
->SetHashSetNeeded(true);
1318 SourceItemType source_type
= UNAVAILABLE_SOURCE
;
1319 SourceItemType peer_type
= UNAVAILABLE_SOURCE
;
1321 //check if this client is needed in any way, if not delete it
1322 bool bDelete
= true;
1323 switch (m_nUploadState
) {
1324 case US_ONUPLOADQUEUE
:
1326 peer_type
= AVAILABLE_SOURCE
;
1330 switch (m_nDownloadState
) {
1332 source_type
= A4AF_SOURCE
; // Will be checked.
1333 case DS_TOOMANYCONNS
:
1334 case DS_NONEEDEDPARTS
:
1340 switch (m_nUploadState
) {
1342 case US_WAITCALLBACK
:
1344 theApp
->clientlist
->AddDeadSource(this);
1348 switch (m_nDownloadState
) {
1350 case DS_WAITCALLBACK
:
1353 theApp
->clientlist
->AddDeadSource(this);
1358 // We keep chat partners in any case
1359 if (GetChatState() != MS_NONE
) {
1361 m_pendingMessage
.Clear();
1362 Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString
);
1366 if (!bFromSocket
&& m_socket
) {
1367 wxASSERT (theApp
->listensocket
->IsValidSocket(m_socket
));
1368 m_socket
->Safe_Delete();
1373 if (m_iFileListRequested
) {
1374 AddLogLineC(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
1375 m_iFileListRequested
= 0;
1381 // Remove the friend linkage
1382 m_Friend
->UnLinkClient(); // this notifies
1385 Notify_SharedCtrlRefreshClient(ECID(), peer_type
);
1386 Notify_SourceCtrlUpdateSource(ECID(), source_type
);
1388 m_fHashsetRequesting
= 0;
1389 SetSentCancelTransfer(0);
1390 m_bHelloAnswerPending
= false;
1391 m_fSentOutOfPartReqs
= 0;
1393 AddDebugLogLineN(logClient
, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
1394 % (bDelete
? wxT("Deleted") : wxT("Disconnected"))
1395 % m_nDownloadState
% m_nUploadState
% GetClientFullInfo() % strReason
);
1400 //Returned bool is not if the TryToConnect is successful or not..
1401 //false means the client was deleted!
1402 //true means the client was not deleted!
1403 bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon
)
1406 if (theApp
->listensocket
->TooManySockets() && !bIgnoreMaxCon
) {
1407 if (!(m_socket
&& m_socket
->IsConnected())) {
1408 if(Disconnected(wxT("Too many connections"))) {
1416 // 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)
1417 if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
1418 if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
1427 uint32 uClientIP
= GetIP();
1428 if (uClientIP
== 0 && !HasLowID()) {
1429 uClientIP
= wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid
);
1433 // Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
1434 // we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
1435 if (theApp
->ipfilter
->IsFiltered(uClientIP
)) {
1436 AddDebugLogLineN(logIPFilter
, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP
% Uint32toStringIP(uClientIP
));
1437 if (Disconnected(wxT("IPFilter"))) {
1444 // for safety: check again whether that IP is banned
1445 if (theApp
->clientlist
->IsBannedClient(uClientIP
)) {
1446 AddDebugLogLineN(logClient
, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP
));
1447 if (Disconnected(wxT("Banned IP"))) {
1455 if (GetKadState() == KS_QUEUED_FWCHECK
) {
1456 SetKadState(KS_CONNECTING_FWCHECK
);
1457 } else if (GetKadState() == KS_QUEUED_FWCHECK_UDP
) {
1458 SetKadState(KS_CONNECTING_FWCHECK_UDP
);
1462 if (!theApp
->CanDoCallback(GetServerIP(), GetServerPort())) {
1463 //We cannot do a callback!
1464 if (GetDownloadState() == DS_CONNECTING
) {
1465 SetDownloadState(DS_LOWTOLOWIP
);
1466 } else if (GetDownloadState() == DS_REQHASHSET
) {
1467 SetDownloadState(DS_ONQUEUE
);
1468 m_reqfile
->SetHashSetNeeded(true);
1470 if (GetUploadState() == US_CONNECTING
) {
1471 if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
1479 //We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
1480 //If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
1481 //with the condition that the source is firewalled and we are firewalled, we must
1482 //recheck it before the this check..
1483 if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp
->serverconnect
->IsLocalServer(GetServerIP(), GetServerPort())
1484 && !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
1485 //This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
1486 if( Kademlia::CKademlia::IsConnected() ) {
1487 //We are connect to Kad
1488 if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
1489 //There are too many source lookups already or we are already searching this key.
1490 SetDownloadState(DS_TOOMANYCONNSKAD
);
1497 if (!m_socket
|| !m_socket
->IsConnected()) {
1499 m_socket
->Safe_Delete();
1501 m_socket
= new CClientTCPSocket(this, thePrefs::GetProxyData());
1503 ConnectionEstablished();
1508 if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
1509 if (m_dwDirectCallbackTimeout
!= 0) {
1510 AddDebugLogLineN(logClient
, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP()));
1511 return true; // We're already trying a direct connection to this client
1513 // a direct callback is possible - since no other parties are involved and only one additional packet overhead
1514 // is used we basically handle it like a normal connection try, no restrictions apply
1515 // we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
1516 m_dwDirectCallbackTimeout
= ::GetTickCount() + SEC2MS(45);
1517 theApp
->clientlist
->AddDirectCallbackClient(this);
1518 AddDebugLogLineN(logClient
, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP()));
1521 data
.WriteUInt16(thePrefs::GetPort()); // needs to know our port
1522 data
.WriteHash(thePrefs::GetUserHash()); // and userhash
1523 // our connection settings
1524 data
.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
1525 AddDebugLogLineN(logClientUDP
, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
1526 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_DIRECTCALLBACKREQ
);
1527 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1528 theApp
->clientudp
->SendPacket(packet
, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
1529 } else if (HasLowID()) { // LOWID
1530 if (GetDownloadState() == DS_CONNECTING
) {
1531 SetDownloadState(DS_WAITCALLBACK
);
1533 if (GetUploadState() == US_CONNECTING
) {
1534 if(Disconnected(wxT("LowID and US_CONNECTING"))) {
1541 if (theApp
->serverconnect
->IsLocalServer(m_dwServerIP
,m_nServerPort
)) {
1543 // AFAICS, this id must be reversed to be sent to clients
1544 // But if I reverse it, we do a serve violation ;)
1545 data
.WriteUInt32(m_nUserIDHybrid
);
1546 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_CALLBACKREQUEST
);
1547 theStats::AddUpOverheadServer(packet
->GetPacketSize());
1548 AddDebugLogLineN(logLocalClient
, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
1549 theApp
->serverconnect
->SendPacket(packet
);
1550 SetDownloadState(DS_WAITCALLBACK
);
1552 if (GetUploadState() == US_NONE
&& (!GetRemoteQueueRank() || m_bReaskPending
)) {
1554 if( !HasValidBuddyID() ) {
1555 theApp
->downloadqueue
->RemoveSource(this);
1556 if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
1563 if( !Kademlia::CKademlia::IsConnected() ) {
1564 //We are not connected to Kad and this is a Kad Firewalled source..
1565 theApp
->downloadqueue
->RemoveSource(this);
1566 if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
1573 if( GetDownloadState() == DS_WAITCALLBACK
) {
1574 if( GetBuddyIP() && GetBuddyPort()) {
1576 bio
.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
1577 bio
.WriteUInt128(Kademlia::CUInt128(m_reqfile
->GetFileHash().GetHash()));
1578 bio
.WriteUInt16(thePrefs::GetPort());
1579 CPacket
* packet
= new CPacket(bio
, OP_KADEMLIAHEADER
, KADEMLIA_CALLBACK_REQ
);
1580 // eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
1581 theApp
->clientudp
->SendPacket(packet
, GetBuddyIP(), GetBuddyPort(), false, NULL
, true, 0);
1582 AddDebugLogLineN(logClientKadUDP
, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet
->GetPacketSize() % Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort()));
1583 theStats::AddUpOverheadKad(packet
->GetRealPacketSize());
1584 SetDownloadState(DS_WAITCALLBACKKAD
);
1586 AddLogLineN(_("Searching buddy for lowid connection"));
1587 //Create search to find buddy.
1588 Kademlia::CSearch
*findSource
= new Kademlia::CSearch
;
1589 findSource
->SetSearchTypes(Kademlia::CSearch::FINDSOURCE
);
1590 findSource
->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
1591 findSource
->AddFileID(Kademlia::CUInt128(m_reqfile
->GetFileHash().GetHash()));
1592 if(Kademlia::CSearchManager::StartSearch(findSource
)) {
1594 SetDownloadState(DS_WAITCALLBACKKAD
);
1596 //This should never happen..
1602 if (GetDownloadState() == DS_WAITCALLBACK
) {
1603 m_bReaskPending
= true;
1604 SetDownloadState(DS_ONQUEUE
);
1616 bool CUpDownClient::Connect()
1618 m_hasbeenobfuscatinglately
= false;
1620 if (!m_socket
->IsOk()) {
1621 // Enable or disable crypting based on our and the remote clients preference
1622 if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
1623 m_socket
->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
1625 m_socket
->SetConnectionEncryption(false, NULL
, false);
1627 amuleIPV4Address tmp
;
1628 tmp
.Hostname(GetConnectIP());
1629 tmp
.Service(GetUserPort());
1630 AddDebugLogLineN(logClient
, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
1631 m_socket
->Connect(tmp
, false);
1632 // We should send hello packets AFTER connecting!
1633 // so I moved it to OnConnect
1640 void CUpDownClient::ConnectionEstablished()
1642 /* Kry - First thing, check if this client was just used to retrieve
1643 info. That's some debug thing for myself... check connection_reason
1646 m_hasbeenobfuscatinglately
= (m_socket
&& m_socket
->IsConnected() && m_socket
->IsObfusicating());
1649 if (!connection_reason
.IsEmpty()) {
1650 AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason
% GetClientFullInfo());
1651 connection_reason
.Clear(); // So we don't re-print on destructor.
1657 // Check if we should use this client to retrieve our public IP
1658 // Ignore local ip on GetPublicIP (could be wrong)
1659 if (theApp
->GetPublicIP(true) == 0 && theApp
->IsConnectedED2K()) {
1660 SendPublicIPRequest();
1663 // was this a direct callback?
1664 if (m_dwDirectCallbackTimeout
!= 0){
1665 theApp
->clientlist
->RemoveDirectCallback(this);
1666 m_dwDirectCallbackTimeout
= 0;
1667 AddDebugLogLineN(logClient
, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP()));
1670 switch (GetKadState()) {
1671 case KS_CONNECTING_FWCHECK
:
1672 SetKadState(KS_CONNECTED_FWCHECK
);
1674 case KS_CONNECTING_BUDDY
:
1675 case KS_INCOMING_BUDDY
:
1676 SetKadState(KS_CONNECTED_BUDDY
);
1678 case KS_CONNECTING_FWCHECK_UDP
:
1679 SetKadState(KS_FWCHECK_UDP
);
1680 SendFirewallCheckUDPRequest();
1686 // ok we have a connection, lets see if we want anything from this client
1687 if (GetChatState() == MS_CONNECTING
) {
1688 SetChatState( MS_CHATTING
);
1691 if (GetChatState() == MS_CHATTING
) {
1693 if (!m_pendingMessage
.IsEmpty()) {
1694 result
= SendChatMessage(m_pendingMessage
);
1696 Notify_ChatConnResult(result
,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage
);
1697 m_pendingMessage
.Clear();
1700 switch(GetDownloadState()) {
1702 case DS_WAITCALLBACK
:
1703 case DS_WAITCALLBACKKAD
:
1704 m_bReaskPending
= false;
1705 SetDownloadState(DS_CONNECTED
);
1708 if (m_bReaskPending
){
1709 m_bReaskPending
= false;
1710 if (GetDownloadState() != DS_NONE
&& GetDownloadState() != DS_DOWNLOADING
) {
1711 SetDownloadState(DS_CONNECTED
);
1715 switch(GetUploadState()){
1717 case US_WAITCALLBACK
:
1718 if (theApp
->uploadqueue
->IsDownloading(this)) {
1719 SetUploadState(US_UPLOADING
);
1720 CPacket
* packet
= new CPacket(OP_ACCEPTUPLOADREQ
, 0, OP_EDONKEYPROT
);
1721 theStats::AddUpOverheadFileRequest(packet
->GetPacketSize());
1722 SendPacket(packet
,true);
1723 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
1726 if (m_iFileListRequested
== 1) {
1727 CPacket
* packet
= new CPacket(m_fSharedDirectories
? OP_ASKSHAREDDIRS
: OP_ASKSHAREDFILES
, 0, OP_EDONKEYPROT
);
1728 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1729 SendPacket(packet
,true,true);
1731 if (m_fSharedDirectories
) {
1732 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
1734 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
1739 while (!m_WaitingPackets_list
.empty()) {
1740 CPacket
* packet
= m_WaitingPackets_list
.front();
1741 m_WaitingPackets_list
.pop_front();
1748 int CUpDownClient::GetHashType() const
1750 if ( m_UserHash
[5] == 13 && m_UserHash
[14] == 110 ) {
1754 if ( m_UserHash
[5] == 14 && m_UserHash
[14] == 111 ) {
1758 if ( m_UserHash
[5] == 'M' && m_UserHash
[14] == 'L' ) {
1766 void CUpDownClient::SetSocket(CClientTCPSocket
* socket
)
1769 if (m_socket
== NULL
&& socket
!= NULL
) {
1770 theStats::SocketAssignedToClient();
1771 } else if (m_socket
!= NULL
&& socket
== NULL
) {
1772 theStats::SocketUnassignedFromClient();
1779 void CUpDownClient::ReGetClientSoft()
1781 if (m_Username
.IsEmpty()) {
1782 m_clientSoft
=SO_UNKNOWN
;
1783 m_clientVerString
= m_clientSoftString
= m_clientVersionString
= m_fullClientVerString
= _("Unknown");
1788 int iHashType
= GetHashType();
1789 wxString clientModString
;
1790 if (iHashType
== SO_EMULE
) {
1792 m_clientSoft
= m_byCompatibleClient
;
1793 m_clientSoftString
= GetSoftName(m_clientSoft
);
1795 if(!GetClientModString().IsEmpty() && (m_clientSoft
!= SO_EMULE
)) {
1796 m_clientSoftString
= GetClientModString();
1798 // Isn't xMule annoying?
1799 if ((m_clientSoft
== SO_LXMULE
) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
1800 m_clientSoftString
+= CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion();
1802 if ((m_clientSoft
== SO_EMULE
) &&
1804 wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
1805 || GetUserName().Find(wxT("xmule.")) != -1
1808 // FAKE eMule -a newer xMule faking is ident.
1809 m_clientSoft
= SO_LXMULE
;
1810 if (GetClientModString().IsEmpty() == false) {
1811 m_clientSoftString
= GetClientModString() + _(" (Fake eMule)");
1813 m_clientSoftString
= _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
1816 // Now, what if we don't know this SO_ID?
1817 if (m_clientSoftString
.IsEmpty()) {
1819 m_clientSoft
= SO_MLDONKEY
;
1820 m_clientSoftString
= GetSoftName(m_clientSoft
);
1821 } else if (m_bIsHybrid
) {
1822 m_clientSoft
= SO_EDONKEYHYBRID
;
1823 m_clientSoftString
= GetSoftName(m_clientSoft
);
1824 } else if (m_byCompatibleClient
!= 0) {
1825 m_clientSoft
= SO_COMPAT_UNK
;
1829 (m_byCompatibleClient
!= 0xf0) // Chinese leech mod
1830 && (1==1) // Your ad here
1832 AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient
);
1835 m_clientSoftString
= CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft
) % m_byCompatibleClient
;
1837 // If we step here, it might mean 2 things:
1839 // a Compat Client that has sent no MuleInfo packet yet.
1840 m_clientSoft
= SO_EMULE
;
1841 m_clientSoftString
= wxT("eMule");
1845 if (m_byEmuleVersion
== 0) {
1846 m_nClientVersion
= MAKE_CLIENT_VERSION(0,0,0);
1847 } else if (m_byEmuleVersion
!= 0x99) {
1848 uint32 nClientMinVersion
= (m_byEmuleVersion
>> 4)*10 + (m_byEmuleVersion
& 0x0f);
1849 m_nClientVersion
= MAKE_CLIENT_VERSION(0,nClientMinVersion
,0);
1850 switch (m_clientSoft
) {
1852 m_clientVerString
= CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion
;
1855 m_clientVerString
= wxT("< v0.05");
1858 clientModString
= GetClientModString();
1859 m_clientVerString
= CFormat(wxT("v0.%u")) % nClientMinVersion
;
1863 uint32 nClientMajVersion
= (m_nClientVersion
>> 17) & 0x7f;
1864 uint32 nClientMinVersion
= (m_nClientVersion
>> 10) & 0x7f;
1865 uint32 nClientUpVersion
= (m_nClientVersion
>> 7) & 0x07;
1867 m_nClientVersion
= MAKE_CLIENT_VERSION(nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1869 switch (m_clientSoft
) {
1874 case SO_NEW_MLDONKEY
:
1875 case SO_NEW2_MLDONKEY
:
1876 // Kry - xMule started sending correct version tags on 1.9.1b.
1877 // It only took them 4 months, and being told by me and the
1878 // eMule+ developers, so I think they're slowly getting smarter.
1879 // They are based on our implementation, so we use the same format
1880 // for the version string.
1881 m_clientVerString
= CFormat(wxT("v%u.%u.%u")) % nClientMajVersion
% nClientMinVersion
% nClientUpVersion
;
1884 m_clientVerString
= CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion
-1) % nClientMinVersion
% ('a' + nClientUpVersion
);
1887 m_clientVerString
= CFormat(wxT("v%u")) % nClientMajVersion
;
1888 if(nClientMinVersion
!= 0) {
1889 m_clientVerString
+= CFormat(wxT(".%u")) % nClientMinVersion
;
1891 if(nClientUpVersion
!= 0) {
1892 m_clientVerString
+= CFormat(wxT("%c")) % ('a' + nClientUpVersion
- 1);
1896 clientModString
= GetClientModString();
1897 m_clientVerString
= CFormat(wxT("v%u.%u%c")) % nClientMajVersion
% nClientMinVersion
% ('a' + nClientUpVersion
);
1901 } else if (m_bIsHybrid
) {
1908 m_clientSoft
= SO_EDONKEYHYBRID
;
1909 m_clientSoftString
= GetSoftName(m_clientSoft
);
1911 uint32 nClientMajVersion
;
1912 uint32 nClientMinVersion
;
1913 uint32 nClientUpVersion
;
1914 if (m_nClientVersion
> 100000) {
1915 uint32 uMaj
= m_nClientVersion
/100000;
1916 nClientMajVersion
= uMaj
- 1;
1917 nClientMinVersion
= (m_nClientVersion
- uMaj
*100000) / 100;
1918 nClientUpVersion
= m_nClientVersion
% 100;
1920 else if (m_nClientVersion
> 10000) {
1921 uint32 uMaj
= m_nClientVersion
/10000;
1922 nClientMajVersion
= uMaj
- 1;
1923 nClientMinVersion
= (m_nClientVersion
- uMaj
*10000) / 10;
1924 nClientUpVersion
= m_nClientVersion
% 10;
1926 else if (m_nClientVersion
> 1000) {
1927 uint32 uMaj
= m_nClientVersion
/1000;
1928 nClientMajVersion
= uMaj
- 1;
1929 nClientMinVersion
= m_nClientVersion
- uMaj
*1000;
1930 nClientUpVersion
= 0;
1932 else if (m_nClientVersion
> 100) {
1933 uint32 uMin
= m_nClientVersion
/10;
1934 nClientMajVersion
= 0;
1935 nClientMinVersion
= uMin
;
1936 nClientUpVersion
= m_nClientVersion
- uMin
*10;
1939 nClientMajVersion
= 0;
1940 nClientMinVersion
= m_nClientVersion
;
1941 nClientUpVersion
= 0;
1943 m_nClientVersion
= MAKE_CLIENT_VERSION(nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1944 if (nClientUpVersion
) {
1945 m_clientVerString
= CFormat(wxT("v%u.%u.%u")) % nClientMajVersion
% nClientMinVersion
% nClientUpVersion
;
1947 m_clientVerString
= CFormat(wxT("v%u.%u")) % nClientMajVersion
% nClientMinVersion
;
1949 } else if (m_bIsML
|| (iHashType
== SO_MLDONKEY
)) {
1950 m_clientSoft
= SO_MLDONKEY
;
1951 m_clientSoftString
= GetSoftName(m_clientSoft
);
1952 uint32 nClientMinVersion
= m_nClientVersion
;
1953 m_nClientVersion
= MAKE_CLIENT_VERSION(0, nClientMinVersion
, 0);
1954 m_clientVerString
= CFormat(wxT("v0.%u")) % nClientMinVersion
;
1955 } else if (iHashType
== SO_OLDEMULE
) {
1956 m_clientSoft
= SO_OLDEMULE
;
1957 m_clientSoftString
= GetSoftName(m_clientSoft
);
1958 uint32 nClientMinVersion
= m_nClientVersion
;
1959 m_nClientVersion
= MAKE_CLIENT_VERSION(0, nClientMinVersion
, 0);
1960 m_clientVerString
= CFormat(wxT("v0.%u")) % nClientMinVersion
;
1962 m_clientSoft
= SO_EDONKEY
;
1963 m_clientSoftString
= GetSoftName(m_clientSoft
);
1964 m_nClientVersion
*= 10;
1965 m_clientVerString
= CFormat(wxT("v%u.%u")) % (m_nClientVersion
/ 100000) % ((m_nClientVersion
/ 1000) % 100);
1968 m_clientVersionString
= m_clientVerString
;
1969 if (!clientModString
.IsEmpty()) {
1970 m_clientVerString
+= wxT(" - ") + clientModString
;
1972 m_fullClientVerString
= m_clientSoftString
+ wxT(" ") + m_clientVerString
;
1977 void CUpDownClient::RequestSharedFileList()
1979 if (m_iFileListRequested
== 0) {
1980 AddDebugLogLineN( logClient
, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
1981 m_iFileListRequested
= 1;
1984 AddDebugLogLineN( logClient
, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
1989 void CUpDownClient::ProcessSharedFileList(const byte
* pachPacket
, uint32 nSize
, wxString
& pszDirectory
)
1991 if (m_iFileListRequested
> 0) {
1992 m_iFileListRequested
--;
1993 theApp
->searchlist
->ProcessSharedFileList(pachPacket
, nSize
, this, NULL
, pszDirectory
);
1998 void CUpDownClient::ResetFileStatusInfo()
2003 m_reqfile
->UpdatePartsFrequency( this, false );
2005 m_downPartStatus
.clear();
2007 m_clientFilename
.Clear();
2009 m_bCompleteSource
= false;
2010 m_dwLastAskedTime
= 0;
2012 m_strComment
.Clear();
2014 if (m_pReqFileAICHHash
!= NULL
) {
2015 delete m_pReqFileAICHHash
;
2016 m_pReqFileAICHHash
= NULL
;
2021 wxString
CUpDownClient::GetUploadFileInfo()
2023 // build info text and display it
2025 sRet
= (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
2027 sRet
+= CFormat(_("Requested: %s\n")) % m_reqfile
->GetFileName();
2029 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())
2030 ) % m_reqfile
->statistic
.GetAccepts() % m_reqfile
->statistic
.GetRequests() % CastItoXBytes(m_reqfile
->statistic
.GetTransferred());
2032 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())
2033 ) % m_reqfile
->statistic
.GetAllTimeAccepts() % m_reqfile
->statistic
.GetAllTimeRequests() % CastItoXBytes(m_reqfile
->statistic
.GetAllTimeTransferred());
2035 sRet
+= _("Requested unknown file");
2040 // sends a packet, if needed it will establish a connection before
2041 // options used: ignore max connections, control packet, delete packet
2042 // !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
2043 bool CUpDownClient::SafeSendPacket(CPacket
* packet
)
2045 if (IsConnected()) {
2046 SendPacket(packet
, true);
2049 m_WaitingPackets_list
.push_back(packet
);
2050 return TryToConnect(true);
2054 void CUpDownClient::SendPublicKeyPacket(){
2055 // send our public key to the client who requested it
2056 if (m_socket
== NULL
|| credits
== NULL
|| m_SecureIdentState
!= IS_KEYANDSIGNEEDED
){
2060 if (!theApp
->CryptoAvailable())
2064 data
.WriteUInt8(theApp
->clientcredits
->GetPubKeyLen());
2065 data
.Write(theApp
->clientcredits
->GetPublicKey(), theApp
->clientcredits
->GetPubKeyLen());
2066 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_PUBLICKEY
);
2068 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2069 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
2070 SendPacket(packet
,true,true);
2071 m_SecureIdentState
= IS_SIGNATURENEEDED
;
2075 void CUpDownClient::SendSignaturePacket(){
2076 // signate the public key of this client and send it
2077 if (m_socket
== NULL
|| credits
== NULL
|| m_SecureIdentState
== 0){
2082 if (!theApp
->CryptoAvailable()) {
2085 if (credits
->GetSecIDKeyLen() == 0) {
2086 return; // We don't have his public key yet, will be back here later
2088 // do we have a challenge value received (actually we should if we are in this function)
2089 if (credits
->m_dwCryptRndChallengeFrom
== 0){
2090 AddDebugLogLineN( logClient
, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
2094 // we will use v1 as default, except if only v2 is supported
2096 if ( (m_bySupportSecIdent
&1) == 1 )
2101 uint8 byChaIPKind
= 0;
2102 uint32 ChallengeIP
= 0;
2104 if (::IsLowID(theApp
->GetED2KID())) {
2105 // we cannot do not know for sure our public ip, so use the remote clients one
2106 ChallengeIP
= GetIP();
2107 byChaIPKind
= CRYPT_CIP_REMOTECLIENT
;
2109 ChallengeIP
= theApp
->GetED2KID();
2110 byChaIPKind
= CRYPT_CIP_LOCALCLIENT
;
2114 byte achBuffer
[250];
2116 uint8 siglen
= theApp
->clientcredits
->CreateSignature(credits
, achBuffer
, 250, ChallengeIP
, byChaIPKind
);
2122 data
.WriteUInt8(siglen
);
2123 data
.Write(achBuffer
, siglen
);
2125 data
.WriteUInt8(byChaIPKind
);
2128 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_SIGNATURE
);
2130 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2131 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
2132 SendPacket(packet
,true,true);
2133 m_SecureIdentState
= IS_ALLREQUESTSSEND
;
2137 void CUpDownClient::ProcessPublicKeyPacket(const byte
* pachPacket
, uint32 nSize
)
2139 theApp
->clientlist
->AddTrackClient(this);
2141 if (m_socket
== NULL
|| credits
== NULL
|| pachPacket
[0] != nSize
-1
2142 || nSize
== 0 || nSize
> 250){
2146 if (!theApp
->CryptoAvailable())
2148 // the function will handle everything (mulitple key etc)
2149 if (credits
->SetSecureIdent(pachPacket
+1, pachPacket
[0])){
2150 // if this client wants a signature, now we can send him one
2151 if (m_SecureIdentState
== IS_SIGNATURENEEDED
){
2152 SendSignaturePacket();
2154 else if (m_SecureIdentState
== IS_KEYANDSIGNEEDED
) {
2155 // something is wrong
2156 AddDebugLogLineN( logClient
, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
2159 AddDebugLogLineN( logClient
, wxT("Failed to use new received public key") );
2164 void CUpDownClient::ProcessSignaturePacket(const byte
* pachPacket
, uint32 nSize
)
2166 // here we spread the good guys from the bad ones ;)
2168 if (m_socket
== NULL
|| credits
== NULL
|| nSize
== 0 || nSize
> 250){
2174 if (pachPacket
[0] == nSize
-1)
2176 else if (pachPacket
[0] == nSize
-2 && (m_bySupportSecIdent
& 2) > 0) //v2
2177 byChaIPKind
= pachPacket
[nSize
-1];
2183 if (!theApp
->CryptoAvailable())
2186 // we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
2187 if (m_dwLastSignatureIP
== GetIP()){
2188 AddDebugLogLineN( logClient
, wxT("received multiple signatures from one client") );
2191 // also make sure this client has a public key
2192 if (credits
->GetSecIDKeyLen() == 0){
2193 AddDebugLogLineN( logClient
, wxT("received signature for client without public key") );
2196 // and one more check: did we ask for a signature and sent a challange packet?
2197 if (credits
->m_dwCryptRndChallengeFor
== 0){
2198 AddDebugLogLineN( logClient
, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
2202 // cppcheck-suppress duplicateBranch
2203 if (theApp
->clientcredits
->VerifyIdent(credits
, pachPacket
+1, pachPacket
[0], GetIP(), byChaIPKind
) ) {
2204 // result is saved in function above
2205 AddDebugLogLineN( logClient
, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind
);
2207 AddDebugLogLineN( logClient
, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind
);
2210 m_dwLastSignatureIP
= GetIP();
2213 void CUpDownClient::SendSecIdentStatePacket(){
2214 // check if we need public key and signature
2217 if (theApp
->CryptoAvailable()){
2218 if (credits
->GetSecIDKeyLen() == 0) {
2219 nValue
= IS_KEYANDSIGNEEDED
;
2220 } else if (m_dwLastSignatureIP
!= GetIP()) {
2221 nValue
= IS_SIGNATURENEEDED
;
2225 AddDebugLogLineN( logClient
, wxT("Not sending SecIdentState Packet, because State is Zero") );
2228 // crypt: send random data to sign
2229 uint32 dwRandom
= rand()+1;
2230 credits
->m_dwCryptRndChallengeFor
= dwRandom
;
2233 data
.WriteUInt8(nValue
);
2234 data
.WriteUInt32(dwRandom
);
2235 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_SECIDENTSTATE
);
2237 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2238 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
2239 SendPacket(packet
,true,true);
2246 void CUpDownClient::ProcessSecIdentStatePacket(const byte
* pachPacket
, uint32 nSize
)
2253 wxASSERT( credits
);
2257 CMemFile
data(pachPacket
,nSize
);
2259 switch ( data
.ReadUInt8() ) {
2261 m_SecureIdentState
= IS_UNAVAILABLE
;
2264 m_SecureIdentState
= IS_SIGNATURENEEDED
;
2267 m_SecureIdentState
= IS_KEYANDSIGNEEDED
;
2273 credits
->m_dwCryptRndChallengeFrom
= data
.ReadUInt32();
2277 void CUpDownClient::InfoPacketsReceived()
2279 // indicates that both Information Packets has been received
2280 // needed for actions, which process data from both packets
2281 wxASSERT ( m_byInfopacketsReceived
== IP_BOTH
);
2282 m_byInfopacketsReceived
= IP_NONE
;
2284 if (m_bySupportSecIdent
){
2285 SendSecIdentStatePacket();
2290 bool CUpDownClient::CheckHandshakeFinished() const
2292 if (m_bHelloAnswerPending
) {
2293 // this triggers way too often.. need more time to look at this -> only create a warning
2294 // The reason for this is that 2 clients are connecting to each other at the same time..
2295 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
.Clear();
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
.Clear();
2765 m_strCaptchaPendingMsg
.Clear();
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
);
2838 void CUpDownClient::SendSharedDirectories()
2840 // This list will contain all (unique) folders.
2841 PathList foldersToSend
;
2843 // The shared folders
2844 const unsigned folderCount
= theApp
->glob_prefs
->shareddir_list
.size();
2845 for (unsigned i
= 0; i
< folderCount
; ++i
) {
2846 foldersToSend
.push_back(theApp
->glob_prefs
->shareddir_list
[i
]);
2849 // ... the categories folders ... (category 0 -> incoming)
2850 for (unsigned i
= 0; i
< theApp
->glob_prefs
->GetCatCount(); ++i
) {
2851 foldersToSend
.push_back(theApp
->glob_prefs
->GetCategory(i
)->path
);
2855 foldersToSend
.sort();
2856 foldersToSend
.unique();
2859 CMemFile
tempfile(80);
2860 tempfile
.WriteUInt32(foldersToSend
.size() + 1); // + 1 for the incomplete files
2862 PathList::iterator it
= foldersToSend
.begin();
2863 for (; it
!= foldersToSend
.end(); ++it
) {
2864 // Note: the public shared name contains the 'raw' path, so we can recognize it again.
2865 // the 'raw' path is determined using CPath::GetRaw()
2866 tempfile
.WriteString( theApp
->sharedfiles
->GetPublicSharedDirName(*it
), GetUnicodeSupport() );
2869 // ... and the Magic thing from the eDonkey Hybrids...
2870 tempfile
.WriteString(OP_INCOMPLETE_SHARED_FILES
, GetUnicodeSupport());
2873 CPacket
* replypacket
= new CPacket(tempfile
, OP_EDONKEYPROT
, OP_ASKSHAREDDIRSANS
);
2874 theStats::AddUpOverheadOther(replypacket
->GetPacketSize());
2875 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ASKSHAREDDIRSANS to ") + GetFullIP() );
2876 SendPacket(replypacket
, true, true);
2879 void CUpDownClient::SendSharedFilesOfDirectory(const wxString
& strReqDir
)
2881 CKnownFilePtrList list
;
2883 if (strReqDir
== OP_INCOMPLETE_SHARED_FILES
) {
2884 // get all shared files from download queue
2885 int iQueuedFiles
= theApp
->downloadqueue
->GetFileCount();
2886 for (int i
= 0; i
< iQueuedFiles
; i
++) {
2887 CPartFile
* pFile
= theApp
->downloadqueue
->GetFileByIndex(i
);
2888 if (pFile
== NULL
|| pFile
->GetStatus(true) != PS_READY
) {
2891 list
.push_back(pFile
);
2894 // get all shared files for the requested directory
2895 const CPath
*sharedDir
= theApp
->sharedfiles
->GetDirForPublicSharedDirName(strReqDir
);
2897 theApp
->sharedfiles
->GetSharedFilesByDirectory(sharedDir
->GetRaw(), list
);
2899 AddLogLineC(CFormat(_("User %s (%u) requested sharedfiles-list for not existing directory '%s' -> Ignored")) % GetUserName() % GetUserIDHybrid() % strReqDir
);
2903 CMemFile
tempfile(80);
2904 tempfile
.WriteString(strReqDir
, GetUnicodeSupport());
2905 tempfile
.WriteUInt32(list
.size());
2907 while (!list
.empty()) {
2908 if (!list
.front()->IsLargeFile() || SupportsLargeFiles()) {
2909 list
.front()->CreateOfferedFilePacket(&tempfile
, NULL
, this);
2914 CPacket
* replypacket
= new CPacket(tempfile
, OP_EDONKEYPROT
, OP_ASKSHAREDFILESDIRANS
);
2915 theStats::AddUpOverheadOther(replypacket
->GetPacketSize());
2916 AddDebugLogLineN( logLocalClient
, wxT("Local Client: OP_ASKSHAREDFILESDIRANS to ") + GetFullIP() );
2917 SendPacket(replypacket
, true, true);
2920 void CUpDownClient::SendFirewallCheckUDPRequest()
2922 wxASSERT(GetKadState() == KS_FWCHECK_UDP
);
2924 if (!Kademlia::CKademlia::IsRunning()) {
2925 SetKadState(KS_NONE
);
2927 } else if (GetUploadState() != US_NONE
|| GetDownloadState() != DS_NONE
|| GetChatState() != MS_NONE
|| GetKadVersion() <= 5 || GetKadPort() == 0) {
2928 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
2929 SetKadState(KS_NONE
);
2934 data
.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
2935 data
.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
2936 data
.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
2937 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_FWCHECKUDPREQ
);
2938 theStats::AddUpOverheadKad(packet
->GetPacketSize());
2939 SafeSendPacket(packet
);
2942 void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile
* data
)
2944 if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL
) {
2945 //DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
2949 // first search if we know this IP already, if so the result might be biased and we need tell the requester
2950 bool errorAlreadyKnown
= false;
2951 if (GetUploadState() != US_NONE
|| GetDownloadState() != DS_NONE
|| GetChatState() != MS_NONE
) {
2952 errorAlreadyKnown
= true;
2953 } else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL
) {
2954 errorAlreadyKnown
= true;
2957 uint16_t remoteInternPort
= data
->ReadUInt16();
2958 uint16_t remoteExternPort
= data
->ReadUInt16();
2959 uint32_t senderKey
= data
->ReadUInt32();
2960 if (remoteInternPort
== 0) {
2961 //DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
2964 // if (senderKey == 0)
2965 // DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
2967 CMemFile testPacket1
;
2968 testPacket1
.WriteUInt8(errorAlreadyKnown
? 1 : 0);
2969 testPacket1
.WriteUInt16(remoteInternPort
);
2970 DebugSend(Kad2FirewallUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort
);
2971 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1
, KADEMLIA2_FIREWALLUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort
, Kademlia::CKadUDPKey(senderKey
, theApp
->GetPublicIP(false)), NULL
);
2973 // if the client has a router with PAT (and therefore a different extern port than intern), test this port too
2974 if (remoteExternPort
!= 0 && remoteExternPort
!= remoteInternPort
) {
2975 CMemFile testPacket2
;
2976 testPacket2
.WriteUInt8(errorAlreadyKnown
? 1 : 0);
2977 testPacket2
.WriteUInt16(remoteExternPort
);
2978 DebugSend(Kad2FirewalledUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort
);
2979 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2
, KADEMLIA2_FIREWALLUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort
, Kademlia::CKadUDPKey(senderKey
, theApp
->GetPublicIP(false)), NULL
);
2981 //DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
2984 void CUpDownClient::SetConnectOptions(uint8_t options
, bool encryption
, bool callback
)
2986 SetCryptLayerSupport((options
& 0x01) != 0 && encryption
);
2987 SetCryptLayerRequest((options
& 0x02) != 0 && encryption
);
2988 SetCryptLayerRequires((options
& 0x04) != 0 && encryption
);
2989 SetDirectUDPCallbackSupport((options
& 0x08) != 0 && callback
);
2993 #ifdef DEBUG_ZOMBIE_CLIENTS
2994 void CUpDownClient::Unlink(const wxString
& from
)
2996 std::multiset
<wxString
>::iterator it
= m_linkedFrom
.find(from
);
2997 if (it
!= m_linkedFrom
.end()) {
2998 m_linkedFrom
.erase(it
);
3002 if (m_linkedDebug
) {
3003 AddLogLineN(CFormat(wxT("Last reference to client %d %p unlinked, delete it.")) % ECID() % this);
3011 void CUpDownClient::Unlink()
3021 // File_checked_for_headers