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(this);
142 // avoid that an unwanted client instance keeps a friend slot
143 m_bFriendSlot
= false;
149 void CUpDownClient::Init()
151 m_bAddNextConnect
= false;
153 m_byChatstate
= MS_NONE
;
154 m_nKadState
= KS_NONE
;
155 m_nChatCaptchaState
= CA_NONE
;
157 m_reqfile
= NULL
; // No file required yet
158 m_nTransferredUp
= 0;
163 bytesReceivedCycle
= 0;
165 m_iFileListRequested
= 0;
166 m_dwLastUpRequest
= 0;
167 m_bEmuleProtocol
= false;
168 m_bCompleteSource
= false;
169 m_bFriendSlot
= false;
170 m_bCommentDirty
= false;
171 m_bReaskPending
= false;
172 m_bUDPPending
= false;
175 m_dwLastAskedTime
= 0;
176 m_nDownloadState
= DS_NONE
;
178 m_nTransferredDown
= 0;
179 m_nUploadState
= US_NONE
;
180 m_dwLastBlockReceived
= 0;
181 m_bUnicodeSupport
= false;
183 m_fSentOutOfPartReqs
= 0;
184 m_nCurQueueSessionPayloadUp
= 0;
185 m_addedPayloadQueueSession
= 0;
187 m_nSumForAvgUpDataRate
= 0;
189 m_nRemoteQueueRank
= 0;
190 m_nOldRemoteQueueRank
= 0;
191 m_dwLastSourceRequest
= 0;
192 m_dwLastSourceAnswer
= 0;
193 m_dwLastAskedForSources
= 0;
195 m_SecureIdentState
= IS_UNAVAILABLE
;
196 m_dwLastSignatureIP
= 0;
198 m_byInfopacketsReceived
= IP_NONE
;
205 m_clientSoft
=SO_UNKNOWN
;
207 m_bRemoteQueueFull
= false;
208 m_HasValidHash
= false;
211 m_fHashsetRequesting
= 0;
212 m_fSharedDirectories
= 0;
213 m_lastPartAsked
= 0xffff;
214 m_nUpCompleteSourcesCount
= 0;
215 m_lastRefreshedDLDisplay
= 0;
216 m_bHelloAnswerPending
= false;
217 m_fSentCancelTransfer
= 0;
218 m_Aggressiveness
= 0;
219 m_LastFileRequest
= 0;
221 m_clientState
= CS_NEW
;
223 ClearHelloProperties();
225 m_pReqFileAICHHash
= NULL
;
227 m_fAICHRequested
= 0;
228 m_fSupportsLargeFiles
= 0;
229 m_fExtMultiPacket
= 0;
236 m_fNeedOurPublicIP
= false;
237 m_bHashsetRequested
= false;
239 m_nLastBlockOffset
= 0;
241 m_uploadingfile
= NULL
;
243 m_OSInfo_sent
= false;
251 m_nSourceFrom
= SF_NONE
;
254 amuleIPV4Address address
;
255 m_socket
->GetPeer(address
);
256 SetIP(StringIPtoUint32(address
.IPAddress()));
262 m_lastClientSoft
= (uint32
)(-1);
263 m_lastClientVersion
= 0;
265 /* Creation time (for buddies timeout) */
266 m_nCreationTime
= ::GetTickCount();
268 m_MaxBlockRequests
= STANDARD_BLOCKS_REQUEST
; // Safe starting amount
270 m_last_block_start
= 0;
273 SetLastBuddyPingPongTime();
274 m_fRequestsCryptLayer
= 0;
275 m_fSupportsCryptLayer
= 0;
276 m_fRequiresCryptLayer
= 0;
277 m_fSupportsSourceEx2
= 0;
278 m_fSupportsCaptcha
= 0;
279 m_fDirectUDPCallback
= 0;
280 m_dwDirectCallbackTimeout
= 0;
282 m_hasbeenobfuscatinglately
= false;
285 m_cMessagesReceived
= 0;
291 CUpDownClient::~CUpDownClient()
294 if (!connection_reason
.IsEmpty()) {
295 AddDebugLogLineN(logClient
, wxT("Client to check for ") + connection_reason
+ wxT(" was deleted without connection."));
299 // For security, remove it from the lists unconditionally.
300 Notify_SharedCtrlRemoveClient((CKnownFile
*)NULL
, this);
301 Notify_SourceCtrlRemoveSource(this, (CPartFile
*)NULL
);
303 if (m_lastClientSoft
== SO_UNKNOWN
) {
304 theStats::RemoveUnknownClient();
305 } else if (m_lastClientSoft
!= (uint32
)(-1)) {
306 theStats::RemoveKnownClient(m_lastClientSoft
, m_lastClientVersion
, m_lastOSInfo
);
309 // Indicate that we are not anymore on stats
310 m_lastClientSoft
= (uint32
)(-1);
313 if (IsAICHReqPending()){
314 m_fAICHRequested
= FALSE
;
315 CAICHHashSet::ClientAICHRequestFailed(this);
318 //theApp->clientlist->RemoveClient(this, wxT("Destructing client object"));
321 m_Friend
->UnLinkClient();
322 Notify_ChatRefreshFriend(m_Friend
, false);
326 // The socket should have been removed in Safe_Delete, but it
327 // doesn't hurt to have an extra check.
329 m_socket
->Safe_Delete();
335 ClearUploadBlockRequests();
336 ClearDownloadBlockRequests();
338 DeleteContents(m_WaitingPackets_list
);
340 if (m_iRating
>0 || !m_strComment
.IsEmpty()) {
342 m_strComment
.Clear();
344 m_reqfile
->UpdateFileRatingCommentAvail();
348 // Ensure that source-counts gets updated in case
349 // of a source not on the download-queue
350 SetRequestFile( NULL
);
352 SetUploadFileID(NULL
);
354 if (m_pReqFileAICHHash
!= NULL
) {
355 delete m_pReqFileAICHHash
;
356 m_pReqFileAICHHash
= NULL
;
360 void CUpDownClient::ClearHelloProperties()
365 m_byEmuleVersion
= 0;
366 m_bySourceExchange1Ver
= 0;
367 m_byAcceptCommentVer
= 0;
368 m_byExtendedRequestsVer
= 0;
369 m_byCompatibleClient
= 0;
371 m_bySupportSecIdent
= 0;
372 m_bSupportsPreview
= 0;
373 m_nClientVersion
= 0;
374 m_fSharedDirectories
= 0;
376 m_fOsInfoSupport
= 0;
377 m_fValueBasedTypeTags
= 0;
380 m_fRequestsCryptLayer
= 0;
381 m_fSupportsCryptLayer
= 0;
382 m_fRequiresCryptLayer
= 0;
383 m_fSupportsSourceEx2
= 0;
384 m_fSupportsCaptcha
= 0;
385 m_fDirectUDPCallback
= 0;
388 bool CUpDownClient::ProcessHelloPacket(const byte
* pachPacket
, uint32 nSize
)
390 const CMemFile
data(pachPacket
,nSize
);
391 uint8 hashsize
= data
.ReadUInt8();
392 if ( 16 != hashsize
) {
394 * Hint: We can not accept other sizes here because:
395 * - the magic number is spread all over the source
396 * - the answer packet lacks the size field
398 throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
400 // eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
401 ClearHelloProperties();
403 return ProcessHelloTypePacket(data
);
406 void CUpDownClient::Safe_Delete()
408 // Because we are delaying the deletion, we might end up trying to delete
409 // it twice, however, this is normal and shouldn't trigger any failures
410 if ( m_clientState
== CS_DYING
) {
414 m_clientState
= CS_DYING
;
416 // Close the socket to avoid any more connections and related events
418 m_socket
->Safe_Delete();
423 // Schedule the client for deletion if we still have the clientlist
424 if ( theApp
->clientlist
) {
425 theApp
->clientlist
->AddToDeleteQueue( this );
432 bool CUpDownClient::ProcessHelloAnswer(const byte
* pachPacket
, uint32 nSize
)
434 const CMemFile
data(pachPacket
,nSize
);
435 bool bIsMule
= ProcessHelloTypePacket(data
);
436 m_bHelloAnswerPending
= false;
440 bool CUpDownClient::ProcessHelloTypePacket(const CMemFile
& data
)
445 m_fNoViewSharedFiles
= 0;
446 m_bUnicodeSupport
= false;
447 uint32 dwEmuleTags
= 0;
449 CMD4Hash hash
= data
.ReadHash();
451 SetUserIDHybrid( data
.ReadUInt32() );
452 uint16 nUserPort
= data
.ReadUInt16(); // hmm clientport is sent twice - why?
453 uint32 tagcount
= data
.ReadUInt32();
454 for (uint32 i
= 0;i
< tagcount
; i
++){
455 CTag
temptag(data
, true);
456 switch(temptag
.GetNameID()){
458 m_Username
= temptag
.GetStr();
462 m_nClientVersion
= temptag
.GetInt();
466 if (temptag
.IsStr()) {
467 m_strModVersion
= temptag
.GetStr();
468 } else if (temptag
.IsInt()) {
469 m_strModVersion
= CFormat(wxT("ModID=%u")) % temptag
.GetInt();
471 m_strModVersion
= wxT("ModID=<Unknown>");
477 nUserPort
= temptag
.GetInt();
480 case CT_EMULE_UDPPORTS
:
483 SetKadPort((temptag
.GetInt() >> 16) & 0xFFFF);
484 m_nUDPPort
= temptag
.GetInt() & 0xFFFF;
486 #ifdef __PACKET_DEBUG__
487 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort
% m_nKadPort
);
491 case CT_EMULE_BUDDYIP
:
493 m_nBuddyIP
= temptag
.GetInt();
494 #ifdef __PACKET_DEBUG__
495 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP
% Uint32toStringIP(m_nBuddyIP
));
499 case CT_EMULE_BUDDYUDP
:
500 // 16 --Reserved for future use--
502 m_nBuddyPort
= (uint16
)temptag
.GetInt();
503 #ifdef __PACKET_DEBUG__
504 AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort
);
508 case CT_EMULE_MISCOPTIONS1
: {
509 // 3 AICH Version (0 = not supported)
512 // 4 Data compression version
517 // 1 PeerCache supported
518 // 1 No 'View Shared Files' supported
521 uint32 flags
= temptag
.GetInt();
522 m_fSupportsAICH
= (flags
>> (4*7+1)) & 0x07;
523 m_bUnicodeSupport
= (flags
>> 4*7) & 0x01;
524 m_byUDPVer
= (flags
>> 4*6) & 0x0f;
525 m_byDataCompVer
= (flags
>> 4*5) & 0x0f;
526 m_bySupportSecIdent
= (flags
>> 4*4) & 0x0f;
527 m_bySourceExchange1Ver
= (flags
>> 4*3) & 0x0f;
528 m_byExtendedRequestsVer
= (flags
>> 4*2) & 0x0f;
529 m_byAcceptCommentVer
= (flags
>> 4*1) & 0x0f;
530 m_fNoViewSharedFiles
= (flags
>> 1*2) & 0x01;
531 m_bMultiPacket
= (flags
>> 1*1) & 0x01;
532 m_fSupportsPreview
= (flags
>> 1*0) & 0x01;
534 #ifdef __PACKET_DEBUG__
535 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
536 AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer
);
537 AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer
);
538 AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent
);
539 AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver
);
540 AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer
);
541 AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer
);
542 AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles
);
543 AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket
);
544 AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories
);
545 AddLogLineNS(wxT("That's all."));
551 case CT_EMULE_MISCOPTIONS2
:
553 // 1 Direct UDP Callback supported and available
554 // 1 Supports ChatCaptchas
555 // 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
556 // 1 Requires CryptLayer
557 // 1 Requests CryptLayer
558 // 1 Supports CryptLayer
559 // 1 Reserved (ModBit)
560 // 1 Ext Multipacket (Hash+Size instead of Hash)
561 // 1 Large Files (includes support for 64bit tags)
562 // 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
563 m_fDirectUDPCallback
= (temptag
.GetInt() >> 12) & 0x01;
564 m_fSupportsCaptcha
= (temptag
.GetInt() >> 11) & 0x01;
565 m_fSupportsSourceEx2
= (temptag
.GetInt() >> 10) & 0x01;
566 m_fRequiresCryptLayer
= (temptag
.GetInt() >> 9) & 0x01;
567 m_fRequestsCryptLayer
= (temptag
.GetInt() >> 8) & 0x01;
568 m_fSupportsCryptLayer
= (temptag
.GetInt() >> 7) & 0x01;
570 m_fExtMultiPacket
= (temptag
.GetInt() >> 5) & 0x01;
571 m_fSupportsLargeFiles
= (temptag
.GetInt() >> 4) & 0x01;
572 m_byKadVersion
= (temptag
.GetInt() >> 0) & 0x0f;
575 m_fRequestsCryptLayer
&= m_fSupportsCryptLayer
;
576 m_fRequiresCryptLayer
&= m_fRequestsCryptLayer
;
578 #ifdef __PACKET_DEBUG__
579 AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
580 AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback
);
581 AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha
);
582 AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2
);
583 AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer
);
584 AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer
);
585 AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer
);
586 AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket
);
587 AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles
);
588 AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion
);
589 AddLogLineNS(wxT("That's all."));
593 // Special tag for Compat. Clients Misc options.
594 case CT_EMULECOMPAT_OPTIONS
:
595 // 1 Operative System Info
596 // 1 Value-based-type int tags (experimental!)
597 m_fValueBasedTypeTags
= (temptag
.GetInt() >> 1*1) & 0x01;
598 m_fOsInfoSupport
= (temptag
.GetInt() >> 1*0) & 0x01;
601 case CT_EMULE_VERSION
:
602 // 8 Compatible Client ID
603 // 7 Mjr Version (Doesn't really matter..)
604 // 7 Min Version (Only need 0-99)
605 // 3 Upd Version (Only need 0-5)
606 // 7 Bld Version (Only need 0-99)
607 m_byCompatibleClient
= (temptag
.GetInt() >> 24);
608 m_nClientVersion
= temptag
.GetInt() & 0x00ffffff;
609 m_byEmuleVersion
= 0x99;
610 m_fSharedDirectories
= 1;
616 m_nUserPort
= nUserPort
;
617 m_dwServerIP
= data
.ReadUInt32();
618 m_nServerPort
= data
.ReadUInt16();
619 // Hybrid now has an extra uint32.. What is it for?
620 // Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
621 if ( data
.GetLength() - data
.GetPosition() == sizeof(uint32
) ) {
622 uint32 test
= data
.ReadUInt32();
623 /*if (test == 'KDLM') below kdlm is converted to ascii values.
624 This fixes a warning with gcc 3.4.
627 if (test
== 0x4b444c4d) { //if it's == "KDLM"
631 m_fSharedDirectories
= 1;
636 amuleIPV4Address address
;
637 m_socket
->GetPeer(address
);
638 SetIP(StringIPtoUint32(address
.IPAddress()));
640 throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
643 if (thePrefs::AddServersFromClient()) {
644 CServer
* addsrv
= new CServer(m_nServerPort
, Uint32toStringIP(m_dwServerIP
));
645 addsrv
->SetListName(addsrv
->GetAddress());
646 if (!theApp
->AddServer(addsrv
)) {
651 //(a)If this is a highID user, store the ID in the Hybrid format.
652 //(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
653 //(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
654 //because they will send a ID that is the same as their IP..
655 if(!HasLowID() || m_nUserIDHybrid
== 0 || m_nUserIDHybrid
== m_dwUserIP
) {
656 SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP
));
659 // get client credits
660 CClientCredits
* pFoundCredits
= theApp
->clientcredits
->GetCredit(m_UserHash
);
661 if (credits
== NULL
){
662 credits
= pFoundCredits
;
663 if (!theApp
->clientlist
->ComparePriorUserhash(m_dwUserIP
, m_nUserPort
, pFoundCredits
)){
664 AddDebugLogLineM( false, logClient
, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
667 } else if (credits
!= pFoundCredits
){
668 // userhash change ok, however two hours "waittime" before it can be used
669 credits
= pFoundCredits
;
670 AddDebugLogLineM( false, logClient
, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
674 if ((m_Friend
= theApp
->friendlist
->FindFriend(m_UserHash
, m_dwUserIP
, m_nUserPort
)) != NULL
){
675 m_Friend
->LinkClient(this);
677 // avoid that an unwanted client instance keeps a friend slot
678 SetFriendSlot(false);
684 m_byInfopacketsReceived
|= IP_EDONKEYPROTPACK
;
686 // check if at least CT_EMULEVERSION was received, all other tags are optional
687 bool bIsMule
= (dwEmuleTags
& 0x04) == 0x04;
689 m_bEmuleProtocol
= true;
690 m_byInfopacketsReceived
|= IP_EMULEPROTPACK
;
694 Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort(), GetKadVersion() > 1);
701 bool CUpDownClient::SendHelloPacket()
703 if (m_socket
== NULL
) {
708 // if IP is filtered, don't greet him but disconnect...
709 amuleIPV4Address address
;
710 m_socket
->GetPeer(address
);
711 if ( theApp
->ipfilter
->IsFiltered(StringIPtoUint32(address
.IPAddress()))) {
712 if (Disconnected(wxT("IPFilter"))) {
720 data
.WriteUInt8(16); // size of userhash
721 SendHelloTypePacket(&data
);
723 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_HELLO
);
724 theStats::AddUpOverheadOther(packet
->GetPacketSize());
725 SendPacket(packet
,true);
726 m_bHelloAnswerPending
= true;
727 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
731 void CUpDownClient::SendMuleInfoPacket(bool bAnswer
, bool OSInfo
) {
733 if (m_socket
== NULL
){
738 CPacket
* packet
= NULL
;
741 data
.WriteUInt8(CURRENT_VERSION_SHORT
);
745 // Special MuleInfo packet for clients supporting it.
746 // This means aMule >= 2.0.0 and Hydranode
748 // Violently mark it as special Mule Info packet
749 // Sending this makes non-supporting-osinfo clients to refuse to read this
750 // packet. Anyway, this packet should NEVER get to non-supporting clients.
752 data
.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
754 data
.WriteUInt32(1); // One Tag (OS_INFO)
756 CTagString
tag1(ET_OS_INFO
,theApp
->GetOSType());
757 tag1
.WriteTagToFile(&data
);
759 m_OSInfo_sent
= true; // So we don't send it again
763 // Normal MuleInfo packet
765 // Kry - There's no point on upgrading to VBT tags here
766 // as no client supporting it uses mule info packet.
768 data
.WriteUInt8(EMULE_PROTOCOL
);
773 CTagInt32
tag1(ET_COMPRESSION
,1);
774 tag1
.WriteTagToFile(&data
);
775 CTagInt32
tag2(ET_UDPVER
,4);
776 tag2
.WriteTagToFile(&data
);
777 CTagInt32
tag3(ET_UDPPORT
, thePrefs::GetEffectiveUDPPort());
778 tag3
.WriteTagToFile(&data
);
779 CTagInt32
tag4(ET_SOURCEEXCHANGE
,3);
780 tag4
.WriteTagToFile(&data
);
781 CTagInt32
tag5(ET_COMMENTS
,1);
782 tag5
.WriteTagToFile(&data
);
783 CTagInt32
tag6(ET_EXTENDEDREQUEST
,2);
784 tag6
.WriteTagToFile(&data
);
786 uint32 dwTagValue
= (theApp
->CryptoAvailable() ? 3 : 0);
787 // Kry - Needs the preview code from eMule
789 // set 'Preview supported' only if 'View Shared Files' allowed
790 if (thePrefs::CanSeeShares() != vsfaNobody) {
794 CTagInt32
tag7(ET_FEATURES
, dwTagValue
);
795 tag7
.WriteTagToFile(&data
);
797 CTagInt32
tag8(ET_COMPATIBLECLIENT
,SO_AMULE
);
798 tag8
.WriteTagToFile(&data
);
800 // Support for tag ET_MOD_VERSION
801 wxString
mod_name(MOD_VERSION_LONG
);
802 CTagString
tag9(ET_MOD_VERSION
, mod_name
);
803 tag9
.WriteTagToFile(&data
);
808 packet
= new CPacket(data
, OP_EMULEPROT
, (bAnswer
? OP_EMULEINFOANSWER
: OP_EMULEINFO
));
811 theStats::AddUpOverheadOther(packet
->GetPacketSize());
812 SendPacket(packet
,true,true);
816 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
818 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
821 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
826 bool CUpDownClient::ProcessMuleInfoPacket(const byte
* pachPacket
, uint32 nSize
)
828 uint8 protocol_version
;
830 const CMemFile
data(pachPacket
,nSize
);
832 // The version number part of this packet will soon be useless since
833 // it is only able to go to v.99. Why the version is a uint8 and why
834 // it was not done as a tag like the eDonkey hello packet is not known.
835 // Therefore, sooner or later, we are going to have to switch over to
836 // using the eDonkey hello packet to set the version. No sense making
837 // a third value sent for versions.
838 uint8 mule_version
= data
.ReadUInt8();
839 protocol_version
= data
.ReadUInt8();
840 uint32 tagcount
= data
.ReadUInt32();
841 if (protocol_version
== 0xFF) {
842 // OS Info supporting clients sending a recycled Mule info packet
843 for (uint32 i
= 0;i
< tagcount
; i
++){
844 CTag
temptag(data
, true);
845 switch(temptag
.GetNameID()){
847 // Special tag, only supporting clients (aMule/Hydranode)
848 // It was recycled from a mod's tag, so if the other side
849 // is not supporting OS Info, we're seriously fucked up :)
850 m_sClientOSInfo
= temptag
.GetStr();
852 // If we didn't send our OSInfo to this client, just send it
853 if (!m_OSInfo_sent
) {
854 SendMuleInfoPacket(false,true);
861 // Your ad... er... I mean TAG, here
868 // Old eMule sending tags
869 m_byCompatibleClient
= 0;
870 m_byEmuleVersion
= mule_version
;
872 if( m_byEmuleVersion
== 0x2B ) {
873 m_byEmuleVersion
= 0x22;
876 if (!(m_bEmuleProtocol
= (protocol_version
== EMULE_PROTOCOL
))) {
880 for (uint32 i
= 0;i
< tagcount
; i
++){
881 CTag
temptag(data
, false);
882 switch(temptag
.GetNameID()){
884 // Bits 31- 8: 0 - reserved
885 // Bits 7- 0: data compression version
886 m_byDataCompVer
= temptag
.GetInt();
890 // Bits 31-16: 0 - reserved
891 // Bits 15- 0: UDP port
892 m_nUDPPort
= temptag
.GetInt();
896 // Bits 31- 8: 0 - reserved
897 // Bits 7- 0: UDP protocol version
898 m_byUDPVer
= temptag
.GetInt();
901 case ET_SOURCEEXCHANGE
:
902 // Bits 31- 8: 0 - reserved
903 // Bits 7- 0: source exchange protocol version
904 m_bySourceExchange1Ver
= temptag
.GetInt();
908 // Bits 31- 8: 0 - reserved
909 // Bits 7- 0: comments version
910 m_byAcceptCommentVer
= temptag
.GetInt();
913 case ET_EXTENDEDREQUEST
:
914 // Bits 31- 8: 0 - reserved
915 // Bits 7- 0: extended requests version
916 m_byExtendedRequestsVer
= temptag
.GetInt();
919 case ET_COMPATIBLECLIENT
:
920 // Bits 31- 8: 0 - reserved
921 // Bits 7- 0: compatible client ID
922 m_byCompatibleClient
= temptag
.GetInt();
926 // Bits 31- 8: 0 - reserved
928 // Bit 6- 0: secure identification
929 m_bySupportSecIdent
= temptag
.GetInt() & 3;
930 m_bSupportsPreview
= (temptag
.GetInt() & 128) > 0;
935 if (temptag
.IsStr()) {
936 m_strModVersion
= temptag
.GetStr();
937 } else if (temptag
.IsInt()) {
938 m_strModVersion
= CFormat(wxT("ModID=%u")) % temptag
.GetInt();
940 m_strModVersion
= wxT("ModID=<Unknown>");
946 AddDebugLogLineM( false, logPacketErrors
,
947 CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
948 % temptag
.GetFullInfo()
949 % GetClientFullInfo()
956 if( m_byDataCompVer
== 0 ){
957 m_bySourceExchange1Ver
= 0;
958 m_byExtendedRequestsVer
= 0;
959 m_byAcceptCommentVer
= 0;
963 //implicitly supported options by older clients
964 //in the future do not use version to guess about new features
965 if(m_byEmuleVersion
< 0x25 && m_byEmuleVersion
> 0x22) {
969 if(m_byEmuleVersion
< 0x25 && m_byEmuleVersion
> 0x21) {
970 m_bySourceExchange1Ver
= 1;
973 if(m_byEmuleVersion
== 0x24) {
974 m_byAcceptCommentVer
= 1;
977 // Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
978 // the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
979 // directory which has a trailing backslash.
980 if(m_byEmuleVersion
>= 0x28 && !m_bIsML
) {// MLdonkey currently does not support shared directories
981 m_fSharedDirectories
= 1;
986 m_byInfopacketsReceived
|= IP_EMULEPROTPACK
;
989 return (protocol_version
== 0xFF); // This was a OS_Info?
993 void CUpDownClient::SendHelloAnswer()
995 if (m_socket
== NULL
){
1001 SendHelloTypePacket(&data
);
1002 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_HELLOANSWER
);
1003 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1004 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
1005 SendPacket(packet
,true);
1009 void CUpDownClient::SendHelloTypePacket(CMemFile
* data
)
1011 data
->WriteHash(thePrefs::GetUserHash());
1012 data
->WriteUInt32(theApp
->GetID());
1013 data
->WriteUInt16(thePrefs::GetPort());
1015 uint32 tagcount
= 6;
1017 if( theApp
->clientlist
->GetBuddy() && theApp
->IsFirewalled() ) {
1020 tagcount
++; // eMule misc flags 2 (kad version)
1023 // Kry - This is the tagcount!!! Be sure to update it!!
1024 // Last update: CT_EMULECOMPAT_OPTIONS included
1025 data
->WriteUInt32(tagcount
+ 1);
1027 data
->WriteUInt32(tagcount
); // NO MOD_VERSION
1031 CTagString
tagname(CT_NAME
,thePrefs::GetUserNick());
1032 tagname
.WriteTagToFile(data
, utf8strRaw
);
1034 CTagVarInt
tagversion(CT_VERSION
, EDONKEYVERSION
, GetVBTTags() ? 0 : 32);
1035 tagversion
.WriteTagToFile(data
);
1038 uint32 kadUDPPort
= 0;
1040 if(Kademlia::CKademlia::IsConnected()) {
1041 if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
1042 kadUDPPort
= Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
1044 kadUDPPort
= Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
1048 CTagVarInt
tagUdpPorts(CT_EMULE_UDPPORTS
, (kadUDPPort
<< 16) | ((uint32
)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
1049 tagUdpPorts
.WriteTagToFile(data
);
1051 if( theApp
->clientlist
->GetBuddy() && theApp
->IsFirewalled() ) {
1052 CTagVarInt
tagBuddyIP(CT_EMULE_BUDDYIP
, theApp
->clientlist
->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
1053 tagBuddyIP
.WriteTagToFile(data
);
1055 CTagVarInt
tagBuddyPort(CT_EMULE_BUDDYUDP
,
1057 ((uint32
)theApp
->clientlist
->GetBuddy()->GetUDPPort() )
1058 , GetVBTTags() ? 0 : 32);
1059 tagBuddyPort
.WriteTagToFile(data
);
1063 CTagVarInt
tagMuleVersion(CT_EMULE_VERSION
,
1065 make_full_ed2k_version(VERSION_MJR
, VERSION_MIN
, VERSION_UPDATE
)
1067 , GetVBTTags() ? 0 : 32);
1068 tagMuleVersion
.WriteTagToFile(data
);
1071 // eMule Misc. Options #1
1072 const uint32 uUdpVer
= 4;
1073 const uint32 uDataCompVer
= 1;
1074 const uint32 uSupportSecIdent
= theApp
->CryptoAvailable() ? 3 : 0;
1075 const uint32 uSourceExchangeVer
= 3;
1076 const uint32 uExtendedRequestsVer
= 2;
1077 const uint32 uAcceptCommentVer
= 1;
1078 const uint32 uNoViewSharedFiles
= (thePrefs::CanSeeShares() == vsfaNobody
) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
1079 const uint32 uMultiPacket
= 1;
1080 const uint32 uSupportPreview
= 0; // No network preview at all.
1081 const uint32 uPeerCache
= 0; // No peercache for aMule, baby
1082 const uint32 uUnicodeSupport
= 1;
1083 const uint32 nAICHVer
= 1; // AICH is ENABLED right now.
1085 CTagVarInt
tagMisOptions(CT_EMULE_MISCOPTIONS1
,
1086 (nAICHVer
<< ((4*7)+1)) |
1087 (uUnicodeSupport
<< 4*7) |
1089 (uDataCompVer
<< 4*5) |
1090 (uSupportSecIdent
<< 4*4) |
1091 (uSourceExchangeVer
<< 4*3) |
1092 (uExtendedRequestsVer
<< 4*2) |
1093 (uAcceptCommentVer
<< 4*1) |
1094 (uPeerCache
<< 1*3) |
1095 (uNoViewSharedFiles
<< 1*2) |
1096 (uMultiPacket
<< 1*1) |
1097 (uSupportPreview
<< 1*0)
1098 , GetVBTTags() ? 0 : 32);
1099 tagMisOptions
.WriteTagToFile(data
);
1101 // eMule Misc. Options #2
1102 const uint32 uKadVersion
= KADEMLIA_VERSION
;
1103 const uint32 uSupportLargeFiles
= 1;
1104 const uint32 uExtMultiPacket
= 1;
1105 const uint32 uReserved
= 0; // mod bit
1106 const uint32 uSupportsCryptLayer
= thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
1107 const uint32 uRequestsCryptLayer
= thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
1108 const uint32 uRequiresCryptLayer
= thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
1109 const uint32 uSupportsSourceEx2
= 1;
1111 // captcha for daemon/remotegui not supported for now
1112 const uint32 uSupportsCaptcha
= 0;
1114 const uint32 uSupportsCaptcha
= 1;
1116 // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
1117 const uint32 uDirectUDPCallback
= (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
1118 && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
1120 CTagVarInt
tagMisOptions2(CT_EMULE_MISCOPTIONS2
,
1122 (uDirectUDPCallback
<< 12) |
1123 (uSupportsCaptcha
<< 11) |
1124 (uSupportsSourceEx2
<< 10) |
1125 (uRequiresCryptLayer
<< 9) |
1126 (uRequestsCryptLayer
<< 8) |
1127 (uSupportsCryptLayer
<< 7) |
1129 (uExtMultiPacket
<< 5) |
1130 (uSupportLargeFiles
<< 4) |
1132 , GetVBTTags() ? 0 : 32 );
1133 tagMisOptions2
.WriteTagToFile(data
);
1135 const uint32 nOSInfoSupport
= 1; // We support OS_INFO
1136 const uint32 nValueBasedTypeTags
= 0; // Experimental, disabled
1138 CTagVarInt
tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS
,
1139 (nValueBasedTypeTags
<< 1*1) |
1140 (nOSInfoSupport
<< 1*0)
1141 , GetVBTTags() ? 0 : 32);
1143 tagMisCompatOptions
.WriteTagToFile(data
);
1146 wxString
mod_name(MOD_VERSION_LONG
);
1147 CTagString
tagModName(ET_MOD_VERSION
, mod_name
);
1148 tagModName
.WriteTagToFile(data
);
1153 if (theApp
->IsConnectedED2K()) {
1154 dwIP
= theApp
->serverconnect
->GetCurrentServer()->GetIP();
1155 nPort
= theApp
->serverconnect
->GetCurrentServer()->GetPort();
1157 data
->WriteUInt32(dwIP
);
1158 data
->WriteUInt16(nPort
);
1162 void CUpDownClient::ProcessMuleCommentPacket(const byte
* pachPacket
, uint32 nSize
)
1165 throw CInvalidPacket(wxT("Comment packet for unknown file"));
1168 if (!m_reqfile
->IsPartFile()) {
1169 throw CInvalidPacket(wxT("Comment packet for completed file"));
1172 const CMemFile
data(pachPacket
, nSize
);
1174 uint8 rating
= data
.ReadUInt8();
1176 AddDebugLogLineM( false, logClient
, wxString(wxT("Invalid Rating for file '")) << m_clientFilename
<< wxT("' received: ") << rating
);
1180 AddDebugLogLineM( false, logClient
, wxString(wxT("Rating for file '")) << m_clientFilename
<< wxT("' received: ") << m_iRating
);
1183 // The comment is unicoded, with a uin32 len and safe read
1184 // (won't break if string size is < than advertised len)
1185 // Truncated to MAXFILECOMMENTLEN size
1186 m_strComment
= data
.ReadString((GetUnicodeSupport() != utf8strNone
), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN
);
1188 AddDebugLogLineM( false, logClient
, wxString(wxT("Description for file '")) << m_clientFilename
<< wxT("' received: ") << m_strComment
);
1190 // Update file rating
1191 m_reqfile
->UpdateFileRatingCommentAvail();
1195 void CUpDownClient::ClearDownloadBlockRequests()
1198 std::list
<Requested_Block_Struct
*>::iterator it
= m_DownloadBlocks_list
.begin();
1199 for (; it
!= m_DownloadBlocks_list
.end(); ++it
) {
1200 Requested_Block_Struct
* cur_block
= *it
;
1203 m_reqfile
->RemoveBlockFromList(cur_block
->StartOffset
, cur_block
->EndOffset
);
1209 m_DownloadBlocks_list
.clear();
1213 std::list
<Pending_Block_Struct
*>::iterator it
= m_PendingBlocks_list
.begin();
1214 for (; it
!= m_PendingBlocks_list
.end(); ++it
) {
1215 Pending_Block_Struct
* pending
= *it
;
1218 m_reqfile
->RemoveBlockFromList(pending
->block
->StartOffset
, pending
->block
->EndOffset
);
1221 delete pending
->block
;
1222 // Not always allocated
1223 if (pending
->zStream
){
1224 inflateEnd(pending
->zStream
);
1225 delete pending
->zStream
;
1231 m_PendingBlocks_list
.clear();
1236 bool CUpDownClient::Disconnected(const wxString
& strReason
, bool bFromSocket
)
1238 //wxASSERT(theApp->clientlist->IsValidClient(this));
1240 // was this a direct callback?
1241 if (m_dwDirectCallbackTimeout
!= 0) {
1242 theApp
->clientlist
->RemoveDirectCallback(this);
1243 m_dwDirectCallbackTimeout
= 0;
1244 theApp
->clientlist
->AddDeadSource(this);
1245 AddDebugLogLineM(false, logClient
, wxT("Direct callback failed to client ") + GetUserHash().Encode() + wxT(" on ip ") + GetFullIP());
1248 if (GetKadState() == KS_QUEUED_FWCHECK_UDP
|| GetKadState() == KS_CONNECTING_FWCHECK_UDP
) {
1249 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
1250 } else if (GetKadState() == KS_FWCHECK_UDP
) {
1251 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
1252 // } else if (GetKadState() == KS_CONNECTED_BUDDY) {
1253 // AddDebugLogLineM(false, logClient, wxT("Buddy client disconnected - ") + strReason);
1256 //If this is a KAD client object, just delete it!
1257 SetKadState(KS_NONE
);
1259 if (GetUploadState() == US_UPLOADING
) {
1261 theApp
->uploadqueue
->RemoveFromUploadQueue(this);
1264 if (GetDownloadState() == DS_DOWNLOADING
) {
1265 SetDownloadState(DS_ONQUEUE
);
1267 // ensure that all possible block requests are removed from the partfile
1268 ClearDownloadBlockRequests();
1270 if (GetDownloadState() == DS_CONNECTED
) {
1271 // successfully connected, but probably didn't respond to our filerequest
1272 theApp
->clientlist
->AddDeadSource(this);
1276 // we had still an AICH request pending, handle it
1277 if (IsAICHReqPending()) {
1278 m_fAICHRequested
= FALSE
;
1279 CAICHHashSet::ClientAICHRequestFailed(this);
1282 // The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
1283 // after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
1284 // is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
1285 if (((GetDownloadState() == DS_REQHASHSET
) || m_fHashsetRequesting
) && (m_reqfile
)) {
1286 m_reqfile
->SetHashSetNeeded(true);
1289 SourceItemType source_type
= UNAVAILABLE_SOURCE
;
1290 SourceItemType peer_type
= UNAVAILABLE_SOURCE
;
1292 //check if this client is needed in any way, if not delete it
1293 bool bDelete
= true;
1294 switch (m_nUploadState
) {
1295 case US_ONUPLOADQUEUE
:
1297 peer_type
= AVAILABLE_SOURCE
;
1301 switch (m_nDownloadState
) {
1303 source_type
= A4AF_SOURCE
; // Will be checked.
1304 case DS_TOOMANYCONNS
:
1305 case DS_NONEEDEDPARTS
:
1311 switch (m_nUploadState
) {
1313 case US_WAITCALLBACK
:
1315 theApp
->clientlist
->AddDeadSource(this);
1319 switch (m_nDownloadState
) {
1321 case DS_WAITCALLBACK
:
1324 theApp
->clientlist
->AddDeadSource(this);
1329 // We keep chat partners in any case
1330 if (GetChatState() != MS_NONE
) {
1332 m_pendingMessage
.Clear();
1333 Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString
);
1337 if (!bFromSocket
&& m_socket
) {
1338 wxASSERT (theApp
->listensocket
->IsValidSocket(m_socket
));
1339 m_socket
->Safe_Delete();
1344 if (m_iFileListRequested
) {
1345 AddLogLineM( false, CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
1346 m_iFileListRequested
= 0;
1352 // Remove the friend linkage
1353 Notify_ChatRefreshFriend(m_Friend
, false);
1356 Notify_SharedCtrlRefreshClient( this, peer_type
);
1357 Notify_SourceCtrlUpdateSource( this, source_type
);
1359 m_fHashsetRequesting
= 0;
1360 SetSentCancelTransfer(0);
1361 m_bHelloAnswerPending
= false;
1362 m_fSentOutOfPartReqs
= 0;
1364 AddDebugLogLineN(logClient
, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
1365 % (bDelete
? wxT("Deleted") : wxT("Disconnected"))
1366 % m_nDownloadState
% m_nUploadState
% GetClientFullInfo() % strReason
);
1371 //Returned bool is not if the TryToConnect is successful or not..
1372 //false means the client was deleted!
1373 //true means the client was not deleted!
1374 bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon
)
1377 if (theApp
->listensocket
->TooManySockets() && !bIgnoreMaxCon
) {
1378 if (!(m_socket
&& m_socket
->IsConnected())) {
1379 if(Disconnected(wxT("Too many connections"))) {
1387 // 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)
1388 if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
1389 if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
1398 uint32 uClientIP
= GetIP();
1399 if (uClientIP
== 0 && !HasLowID()) {
1400 uClientIP
= wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid
);
1404 // Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
1405 // we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
1406 if (theApp
->ipfilter
->IsFiltered(uClientIP
)) {
1407 AddDebugLogLineM(false, logIPFilter
, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP
% Uint32toStringIP(uClientIP
));
1408 if (Disconnected(wxT("IPFilter"))) {
1415 // for safety: check again whether that IP is banned
1416 if (theApp
->clientlist
->IsBannedClient(uClientIP
)) {
1417 AddDebugLogLineM(false, logClient
, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP
));
1418 if (Disconnected(wxT("Banned IP"))) {
1426 if (GetKadState() == KS_QUEUED_FWCHECK
) {
1427 SetKadState(KS_CONNECTING_FWCHECK
);
1428 } else if (GetKadState() == KS_QUEUED_FWCHECK_UDP
) {
1429 SetKadState(KS_CONNECTING_FWCHECK_UDP
);
1433 if (!theApp
->CanDoCallback(this)) {
1434 //We cannot do a callback!
1435 if (GetDownloadState() == DS_CONNECTING
) {
1436 SetDownloadState(DS_LOWTOLOWIP
);
1437 } else if (GetDownloadState() == DS_REQHASHSET
) {
1438 SetDownloadState(DS_ONQUEUE
);
1439 m_reqfile
->SetHashSetNeeded(true);
1441 if (GetUploadState() == US_CONNECTING
) {
1442 if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
1450 //We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
1451 //If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
1452 //with the condition that the source is firewalled and we are firewalled, we must
1453 //recheck it before the this check..
1454 if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp
->serverconnect
->IsLocalServer(GetServerIP(), GetServerPort())
1455 && !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
1456 //This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
1457 if( Kademlia::CKademlia::IsConnected() ) {
1458 //We are connect to Kad
1459 if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
1460 //There are too many source lookups already or we are already searching this key.
1461 SetDownloadState(DS_TOOMANYCONNSKAD
);
1468 if (!m_socket
|| !m_socket
->IsConnected()) {
1470 m_socket
->Safe_Delete();
1472 m_socket
= new CClientTCPSocket(this, thePrefs::GetProxyData());
1474 ConnectionEstablished();
1479 if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
1480 if (m_dwDirectCallbackTimeout
!= 0) {
1481 AddDebugLogLineM(false, logClient
, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client ") + GetUserHash().Encode());
1482 return true; // We're already trying a direct connection to this client
1484 // a direct callback is possible - since no other parties are involved and only one additional packet overhead
1485 // is used we basically handle it like a normal connection try, no restrictions apply
1486 // we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
1487 m_dwDirectCallbackTimeout
= ::GetTickCount() + SEC2MS(45);
1488 theApp
->clientlist
->AddDirectCallbackClient(this);
1490 AddDebugLogLineM(false, logClient
, wxString::Format(wxT("Direct Callback on port %u to client "), GetKadPort()) + GetUserHash().Encode());
1493 data
.WriteUInt16(thePrefs::GetPort()); // needs to know our port
1494 data
.WriteHash(thePrefs::GetUserHash()); // and userhash
1495 // our connection settings
1496 data
.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
1497 AddDebugLogLineM(false, logClientUDP
, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
1498 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_DIRECTCALLBACKREQ
);
1499 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1500 theApp
->clientudp
->SendPacket(packet
, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
1501 } else if (HasLowID()) { // LOWID
1502 if (GetDownloadState() == DS_CONNECTING
) {
1503 SetDownloadState(DS_WAITCALLBACK
);
1505 if (GetUploadState() == US_CONNECTING
) {
1506 if(Disconnected(wxT("LowID and US_CONNECTING"))) {
1513 if (theApp
->serverconnect
->IsLocalServer(m_dwServerIP
,m_nServerPort
)) {
1515 // AFAICS, this id must be reversed to be sent to clients
1516 // But if I reverse it, we do a serve violation ;)
1517 data
.WriteUInt32(m_nUserIDHybrid
);
1518 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_CALLBACKREQUEST
);
1519 theStats::AddUpOverheadServer(packet
->GetPacketSize());
1520 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
1521 theApp
->serverconnect
->SendPacket(packet
);
1522 SetDownloadState(DS_WAITCALLBACK
);
1524 if (GetUploadState() == US_NONE
&& (!GetRemoteQueueRank() || m_bReaskPending
)) {
1526 if( !HasValidBuddyID() ) {
1527 theApp
->downloadqueue
->RemoveSource(this);
1528 if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
1535 if( !Kademlia::CKademlia::IsConnected() ) {
1536 //We are not connected to Kad and this is a Kad Firewalled source..
1537 theApp
->downloadqueue
->RemoveSource(this);
1538 if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
1545 if( GetDownloadState() == DS_WAITCALLBACK
) {
1546 if( GetBuddyIP() && GetBuddyPort()) {
1548 bio
.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
1549 bio
.WriteUInt128(Kademlia::CUInt128(m_reqfile
->GetFileHash().GetHash()));
1550 bio
.WriteUInt16(thePrefs::GetPort());
1551 CPacket
* packet
= new CPacket(bio
, OP_KADEMLIAHEADER
, KADEMLIA_CALLBACK_REQ
);
1552 // eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
1553 theApp
->clientudp
->SendPacket(packet
, GetBuddyIP(), GetBuddyPort(), false, NULL
, true, 0);
1554 AddDebugLogLineM(false, logClientKadUDP
, wxString::Format(wxT("KadCallbackReq (size=%i) to "),packet
->GetPacketSize()) + Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort()));
1555 theStats::AddUpOverheadKad(packet
->GetRealPacketSize());
1556 SetDownloadState(DS_WAITCALLBACKKAD
);
1558 AddLogLineN(_("Searching buddy for lowid connection"));
1559 //Create search to find buddy.
1560 Kademlia::CSearch
*findSource
= new Kademlia::CSearch
;
1561 findSource
->SetSearchTypes(Kademlia::CSearch::FINDSOURCE
);
1562 findSource
->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
1563 findSource
->AddFileID(Kademlia::CUInt128(m_reqfile
->GetFileHash().GetHash()));
1564 if(Kademlia::CSearchManager::StartSearch(findSource
)) {
1566 SetDownloadState(DS_WAITCALLBACKKAD
);
1568 //This should never happen..
1574 if (GetDownloadState() == DS_WAITCALLBACK
) {
1575 m_bReaskPending
= true;
1576 SetDownloadState(DS_ONQUEUE
);
1588 bool CUpDownClient::Connect()
1590 m_hasbeenobfuscatinglately
= false;
1592 if (!m_socket
->IsOk()) {
1593 // Enable or disable crypting based on our and the remote clients preference
1594 if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
1595 m_socket
->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
1597 m_socket
->SetConnectionEncryption(false, NULL
, false);
1599 amuleIPV4Address tmp
;
1600 tmp
.Hostname(GetConnectIP());
1601 tmp
.Service(GetUserPort());
1602 AddDebugLogLineM(false, logClient
, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
1603 m_socket
->Connect(tmp
, false);
1604 // We should send hello packets AFTER connecting!
1605 // so I moved it to OnConnect
1612 void CUpDownClient::ConnectionEstablished()
1614 /* Kry - First thing, check if this client was just used to retrieve
1615 info. That's some debug thing for myself... check connection_reason
1618 m_hasbeenobfuscatinglately
= (m_socket
&& m_socket
->IsConnected() && m_socket
->IsObfusicating());
1621 if (!connection_reason
.IsEmpty()) {
1622 AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason
% GetClientFullInfo());
1623 connection_reason
.Clear(); // So we don't re-print on destructor.
1629 // Check if we should use this client to retrieve our public IP
1630 // Ignore local ip on GetPublicIP (could be wrong)
1631 if (theApp
->GetPublicIP(true) == 0 && theApp
->IsConnectedED2K()) {
1632 SendPublicIPRequest();
1635 // was this a direct callback?
1636 if (m_dwDirectCallbackTimeout
!= 0){
1637 theApp
->clientlist
->RemoveDirectCallback(this);
1638 m_dwDirectCallbackTimeout
= 0;
1640 AddDebugLogLineM(false, logClient
, wxT("Direct Callback succeeded, connection established to ") + GetUserHash().Encode());
1643 switch (GetKadState()) {
1644 case KS_CONNECTING_FWCHECK
:
1645 SetKadState(KS_CONNECTED_FWCHECK
);
1647 case KS_CONNECTING_BUDDY
:
1648 case KS_INCOMING_BUDDY
:
1649 SetKadState(KS_CONNECTED_BUDDY
);
1651 case KS_CONNECTING_FWCHECK_UDP
:
1652 SetKadState(KS_FWCHECK_UDP
);
1653 SendFirewallCheckUDPRequest();
1659 // ok we have a connection, lets see if we want anything from this client
1660 if (GetChatState() == MS_CONNECTING
) {
1661 SetChatState( MS_CHATTING
);
1664 if (GetChatState() == MS_CHATTING
) {
1666 if (!m_pendingMessage
.IsEmpty()) {
1667 result
= SendChatMessage(m_pendingMessage
);
1669 Notify_ChatConnResult(result
,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage
);
1670 m_pendingMessage
.Clear();
1673 switch(GetDownloadState()) {
1675 case DS_WAITCALLBACK
:
1676 case DS_WAITCALLBACKKAD
:
1677 m_bReaskPending
= false;
1678 SetDownloadState(DS_CONNECTED
);
1681 if (m_bReaskPending
){
1682 m_bReaskPending
= false;
1683 if (GetDownloadState() != DS_NONE
&& GetDownloadState() != DS_DOWNLOADING
) {
1684 SetDownloadState(DS_CONNECTED
);
1688 switch(GetUploadState()){
1690 case US_WAITCALLBACK
:
1691 if (theApp
->uploadqueue
->IsDownloading(this)) {
1692 SetUploadState(US_UPLOADING
);
1693 CPacket
* packet
= new CPacket(OP_ACCEPTUPLOADREQ
, 0, OP_EDONKEYPROT
);
1694 theStats::AddUpOverheadFileRequest(packet
->GetPacketSize());
1695 SendPacket(packet
,true);
1696 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
1699 if (m_iFileListRequested
== 1) {
1700 CPacket
* packet
= new CPacket(m_fSharedDirectories
? OP_ASKSHAREDDIRS
: OP_ASKSHAREDFILES
, 0, OP_EDONKEYPROT
);
1701 theStats::AddUpOverheadOther(packet
->GetPacketSize());
1702 SendPacket(packet
,true,true);
1703 if (m_fSharedDirectories
) {
1704 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
1706 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
1710 while (!m_WaitingPackets_list
.empty()) {
1711 CPacket
* packet
= m_WaitingPackets_list
.front();
1712 m_WaitingPackets_list
.pop_front();
1719 int CUpDownClient::GetHashType() const
1721 if ( m_UserHash
[5] == 13 && m_UserHash
[14] == 110 ) {
1725 if ( m_UserHash
[5] == 14 && m_UserHash
[14] == 111 ) {
1729 if ( m_UserHash
[5] == 'M' && m_UserHash
[14] == 'L' ) {
1737 void CUpDownClient::SetSocket(CClientTCPSocket
* socket
)
1739 #if defined(__DEBUG__)
1740 if (m_socket
== NULL
&& socket
!= NULL
) {
1741 theStats::SocketAssignedToClient();
1742 } else if (m_socket
!= NULL
&& socket
== NULL
) {
1743 theStats::SocketUnassignedFromClient();
1750 void CUpDownClient::ReGetClientSoft()
1752 if (m_Username
.IsEmpty()) {
1753 m_clientSoft
=SO_UNKNOWN
;
1754 m_clientVerString
= m_clientSoftString
= m_clientVersionString
= m_fullClientVerString
= _("Unknown");
1759 int iHashType
= GetHashType();
1760 wxString clientModString
;
1761 if (iHashType
== SO_EMULE
) {
1763 m_clientSoft
= m_byCompatibleClient
;
1764 m_clientSoftString
= GetSoftName(m_clientSoft
);
1766 if(!GetClientModString().IsEmpty() && (m_clientSoft
!= SO_EMULE
)) {
1767 m_clientSoftString
= GetClientModString();
1769 // Isn't xMule annoying?
1770 if ((m_clientSoft
== SO_LXMULE
) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
1771 m_clientSoftString
+= wxString::Format(_(" (Fake eMule version %#x)"),GetMuleVersion());
1773 if ((m_clientSoft
== SO_EMULE
) &&
1775 wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
1776 || GetUserName().Find(wxT("xmule.")) != -1
1779 // FAKE eMule -a newer xMule faking is ident.
1780 m_clientSoft
= SO_LXMULE
;
1781 if (GetClientModString().IsEmpty() == false) {
1782 m_clientSoftString
= GetClientModString() + _(" (Fake eMule)");
1784 m_clientSoftString
= _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
1787 // Now, what if we don't know this SO_ID?
1788 if (m_clientSoftString
.IsEmpty()) {
1790 m_clientSoft
= SO_MLDONKEY
;
1791 m_clientSoftString
= GetSoftName(m_clientSoft
);
1792 } else if (m_bIsHybrid
) {
1793 m_clientSoft
= SO_EDONKEYHYBRID
;
1794 m_clientSoftString
= GetSoftName(m_clientSoft
);
1795 } else if (m_byCompatibleClient
!= 0) {
1796 m_clientSoft
= SO_COMPAT_UNK
;
1800 (m_byCompatibleClient
!= 0xf0) // Chinese leech mod
1801 && (1==1) // Your ad here
1803 AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient
);
1806 m_clientSoftString
= GetSoftName(m_clientSoft
) + wxString::Format(wxT("(%#x)"),m_byCompatibleClient
);
1808 // If we step here, it might mean 2 things:
1810 // a Compat Client that has sent no MuleInfo packet yet.
1811 m_clientSoft
= SO_EMULE
;
1812 m_clientSoftString
= wxT("eMule");
1816 if (m_byEmuleVersion
== 0) {
1817 m_nClientVersion
= MAKE_CLIENT_VERSION(0,0,0);
1818 } else if (m_byEmuleVersion
!= 0x99) {
1819 uint32 nClientMinVersion
= (m_byEmuleVersion
>> 4)*10 + (m_byEmuleVersion
& 0x0f);
1820 m_nClientVersion
= MAKE_CLIENT_VERSION(0,nClientMinVersion
,0);
1821 switch (m_clientSoft
) {
1823 m_clientVerString
= wxString::Format(_("1.x (based on eMule v0.%u)"), nClientMinVersion
);
1826 m_clientVerString
= wxT("< v0.05");
1829 clientModString
= GetClientModString();
1830 m_clientVerString
= wxString::Format(wxT("v0.%u"), nClientMinVersion
);
1834 uint32 nClientMajVersion
= (m_nClientVersion
>> 17) & 0x7f;
1835 uint32 nClientMinVersion
= (m_nClientVersion
>> 10) & 0x7f;
1836 uint32 nClientUpVersion
= (m_nClientVersion
>> 7) & 0x07;
1838 m_nClientVersion
= MAKE_CLIENT_VERSION(nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1840 switch (m_clientSoft
) {
1844 // Kry - xMule started sending correct version tags on 1.9.1b.
1845 // It only took them 4 months, and being told by me and the
1846 // eMule+ developers, so I think they're slowly getting smarter.
1847 // They are based on our implementation, so we use the same format
1848 // for the version string.
1849 m_clientVerString
= wxString::Format(wxT("v%u.%u.%u"), nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1852 m_clientVerString
= wxString::Format(wxT(" v%u.%.2u%c"), nClientMajVersion
-1, nClientMinVersion
, 'a' + nClientUpVersion
);
1855 m_clientVerString
= wxString::Format(wxT("v%u"), nClientMajVersion
);
1856 if(nClientMinVersion
!= 0) {
1857 m_clientVerString
+= wxString::Format(wxT(".%u"), nClientMinVersion
);
1859 if(nClientUpVersion
!= 0) {
1860 m_clientVerString
+= wxString::Format(wxT("%c"), 'a' + nClientUpVersion
- 1);
1864 clientModString
= GetClientModString();
1865 m_clientVerString
= wxString::Format(wxT("v%u.%u%c"), nClientMajVersion
, nClientMinVersion
, 'a' + nClientUpVersion
);
1869 } else if (m_bIsHybrid
) {
1876 m_clientSoft
= SO_EDONKEYHYBRID
;
1877 m_clientSoftString
= GetSoftName(m_clientSoft
);
1879 uint32 nClientMajVersion
;
1880 uint32 nClientMinVersion
;
1881 uint32 nClientUpVersion
;
1882 if (m_nClientVersion
> 100000) {
1883 uint32 uMaj
= m_nClientVersion
/100000;
1884 nClientMajVersion
= uMaj
- 1;
1885 nClientMinVersion
= (m_nClientVersion
- uMaj
*100000) / 100;
1886 nClientUpVersion
= m_nClientVersion
% 100;
1888 else if (m_nClientVersion
> 10000) {
1889 uint32 uMaj
= m_nClientVersion
/10000;
1890 nClientMajVersion
= uMaj
- 1;
1891 nClientMinVersion
= (m_nClientVersion
- uMaj
*10000) / 10;
1892 nClientUpVersion
= m_nClientVersion
% 10;
1894 else if (m_nClientVersion
> 1000) {
1895 uint32 uMaj
= m_nClientVersion
/1000;
1896 nClientMajVersion
= uMaj
- 1;
1897 nClientMinVersion
= m_nClientVersion
- uMaj
*1000;
1898 nClientUpVersion
= 0;
1900 else if (m_nClientVersion
> 100) {
1901 uint32 uMin
= m_nClientVersion
/10;
1902 nClientMajVersion
= 0;
1903 nClientMinVersion
= uMin
;
1904 nClientUpVersion
= m_nClientVersion
- uMin
*10;
1907 nClientMajVersion
= 0;
1908 nClientMinVersion
= m_nClientVersion
;
1909 nClientUpVersion
= 0;
1911 m_nClientVersion
= MAKE_CLIENT_VERSION(nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1912 if (nClientUpVersion
) {
1913 m_clientVerString
= wxString::Format(wxT("v%u.%u.%u"), nClientMajVersion
, nClientMinVersion
, nClientUpVersion
);
1915 m_clientVerString
= wxString::Format(wxT("v%u.%u"), nClientMajVersion
, nClientMinVersion
);
1917 } else if (m_bIsML
|| (iHashType
== SO_MLDONKEY
)) {
1918 m_clientSoft
= SO_MLDONKEY
;
1919 m_clientSoftString
= GetSoftName(m_clientSoft
);
1920 uint32 nClientMinVersion
= m_nClientVersion
;
1921 m_nClientVersion
= MAKE_CLIENT_VERSION(0, nClientMinVersion
, 0);
1922 m_clientVerString
= wxString::Format(wxT("v0.%u"), nClientMinVersion
);
1923 } else if (iHashType
== SO_OLDEMULE
) {
1924 m_clientSoft
= SO_OLDEMULE
;
1925 m_clientSoftString
= GetSoftName(m_clientSoft
);
1926 uint32 nClientMinVersion
= m_nClientVersion
;
1927 m_nClientVersion
= MAKE_CLIENT_VERSION(0, nClientMinVersion
, 0);
1928 m_clientVerString
= wxString::Format(wxT("v0.%u"), nClientMinVersion
);
1930 m_clientSoft
= SO_EDONKEY
;
1931 m_clientSoftString
= GetSoftName(m_clientSoft
);
1932 m_nClientVersion
*= 10;
1933 m_clientVerString
= wxString::Format(wxT("v%u.%u"), m_nClientVersion
/ 100000, (m_nClientVersion
/ 1000) % 100);
1936 m_clientVersionString
= m_clientVerString
;
1937 if (!clientModString
.IsEmpty()) {
1938 m_clientVerString
+= wxT(" - ") + clientModString
;
1940 m_fullClientVerString
= m_clientSoftString
+ wxT(" ") + m_clientVerString
;
1945 void CUpDownClient::RequestSharedFileList()
1947 if (m_iFileListRequested
== 0) {
1948 AddDebugLogLineM( false, logClient
, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
1949 m_iFileListRequested
= 1;
1952 AddDebugLogLineM( false, logClient
, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
1957 void CUpDownClient::ProcessSharedFileList(const byte
* pachPacket
, uint32 nSize
, wxString
& pszDirectory
)
1959 if (m_iFileListRequested
> 0) {
1960 m_iFileListRequested
--;
1961 theApp
->searchlist
->ProcessSharedFileList(pachPacket
, nSize
, this, NULL
, pszDirectory
);
1966 void CUpDownClient::ResetFileStatusInfo()
1971 m_reqfile
->UpdatePartsFrequency( this, false );
1973 m_downPartStatus
.clear();
1975 m_clientFilename
.Clear();
1977 m_bCompleteSource
= false;
1978 m_dwLastAskedTime
= 0;
1980 m_strComment
.Clear();
1982 if (m_pReqFileAICHHash
!= NULL
) {
1983 delete m_pReqFileAICHHash
;
1984 m_pReqFileAICHHash
= NULL
;
1989 wxString
CUpDownClient::GetUploadFileInfo()
1991 // build info text and display it
1993 sRet
= (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
1995 sRet
+= CFormat(_("Requested: %s\n")) % m_reqfile
->GetFileName();
1997 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())
1998 ) % m_reqfile
->statistic
.GetAccepts() % m_reqfile
->statistic
.GetRequests() % CastItoXBytes(m_reqfile
->statistic
.GetTransferred());
2000 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())
2001 ) % m_reqfile
->statistic
.GetAllTimeAccepts() % m_reqfile
->statistic
.GetAllTimeRequests() % CastItoXBytes(m_reqfile
->statistic
.GetAllTimeTransferred());
2003 sRet
+= _("Requested unknown file");
2008 // sends a packet, if needed it will establish a connection before
2009 // options used: ignore max connections, control packet, delete packet
2010 // !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
2011 bool CUpDownClient::SafeSendPacket(CPacket
* packet
)
2013 if (IsConnected()) {
2014 SendPacket(packet
, true);
2017 m_WaitingPackets_list
.push_back(packet
);
2018 return TryToConnect(true);
2022 void CUpDownClient::SendPublicKeyPacket(){
2023 // send our public key to the client who requested it
2024 if (m_socket
== NULL
|| credits
== NULL
|| m_SecureIdentState
!= IS_KEYANDSIGNEEDED
){
2028 if (!theApp
->CryptoAvailable())
2032 data
.WriteUInt8(theApp
->clientcredits
->GetPubKeyLen());
2033 data
.Write(theApp
->clientcredits
->GetPublicKey(), theApp
->clientcredits
->GetPubKeyLen());
2034 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_PUBLICKEY
);
2036 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2037 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
2038 SendPacket(packet
,true,true);
2039 m_SecureIdentState
= IS_SIGNATURENEEDED
;
2043 void CUpDownClient::SendSignaturePacket(){
2044 // signate the public key of this client and send it
2045 if (m_socket
== NULL
|| credits
== NULL
|| m_SecureIdentState
== 0){
2050 if (!theApp
->CryptoAvailable()) {
2053 if (credits
->GetSecIDKeyLen() == 0) {
2054 return; // We don't have his public key yet, will be back here later
2056 // do we have a challenge value received (actually we should if we are in this function)
2057 if (credits
->m_dwCryptRndChallengeFrom
== 0){
2058 AddDebugLogLineM( false, logClient
, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
2062 // we will use v1 as default, except if only v2 is supported
2064 if ( (m_bySupportSecIdent
&1) == 1 )
2069 uint8 byChaIPKind
= 0;
2070 uint32 ChallengeIP
= 0;
2072 if (::IsLowID(theApp
->GetED2KID())) {
2073 // we cannot do not know for sure our public ip, so use the remote clients one
2074 ChallengeIP
= GetIP();
2075 byChaIPKind
= CRYPT_CIP_REMOTECLIENT
;
2077 ChallengeIP
= theApp
->GetED2KID();
2078 byChaIPKind
= CRYPT_CIP_LOCALCLIENT
;
2082 byte achBuffer
[250];
2084 uint8 siglen
= theApp
->clientcredits
->CreateSignature(credits
, achBuffer
, 250, ChallengeIP
, byChaIPKind
);
2090 data
.WriteUInt8(siglen
);
2091 data
.Write(achBuffer
, siglen
);
2093 data
.WriteUInt8(byChaIPKind
);
2096 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_SIGNATURE
);
2098 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2099 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
2100 SendPacket(packet
,true,true);
2101 m_SecureIdentState
= IS_ALLREQUESTSSEND
;
2105 void CUpDownClient::ProcessPublicKeyPacket(const byte
* pachPacket
, uint32 nSize
)
2107 theApp
->clientlist
->AddTrackClient(this);
2109 if (m_socket
== NULL
|| credits
== NULL
|| pachPacket
[0] != nSize
-1
2110 || nSize
== 0 || nSize
> 250){
2114 if (!theApp
->CryptoAvailable())
2116 // the function will handle everything (mulitple key etc)
2117 if (credits
->SetSecureIdent(pachPacket
+1, pachPacket
[0])){
2118 // if this client wants a signature, now we can send him one
2119 if (m_SecureIdentState
== IS_SIGNATURENEEDED
){
2120 SendSignaturePacket();
2122 else if(m_SecureIdentState
== IS_KEYANDSIGNEEDED
){
2123 // something is wrong
2124 AddDebugLogLineM( false, logClient
, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
2127 AddDebugLogLineM( false, logClient
, wxT("Failed to use new received public key") );
2132 void CUpDownClient::ProcessSignaturePacket(const byte
* pachPacket
, uint32 nSize
)
2134 // here we spread the good guys from the bad ones ;)
2136 if (m_socket
== NULL
|| credits
== NULL
|| nSize
== 0 || nSize
> 250){
2142 if (pachPacket
[0] == nSize
-1)
2144 else if (pachPacket
[0] == nSize
-2 && (m_bySupportSecIdent
& 2) > 0) //v2
2145 byChaIPKind
= pachPacket
[nSize
-1];
2151 if (!theApp
->CryptoAvailable())
2154 // we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
2155 if (m_dwLastSignatureIP
== GetIP()){
2156 AddDebugLogLineM( false, logClient
, wxT("received multiple signatures from one client") );
2159 // also make sure this client has a public key
2160 if (credits
->GetSecIDKeyLen() == 0){
2161 AddDebugLogLineM( false, logClient
, wxT("received signature for client without public key") );
2164 // and one more check: did we ask for a signature and sent a challange packet?
2165 if (credits
->m_dwCryptRndChallengeFor
== 0){
2166 AddDebugLogLineM( false, logClient
, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
2170 if (theApp
->clientcredits
->VerifyIdent(credits
, pachPacket
+1, pachPacket
[0], GetIP(), byChaIPKind
) ){
2171 // result is saved in function above
2172 AddDebugLogLineM( false, logClient
, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind
);
2174 AddDebugLogLineM( false, logClient
, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind
);
2177 m_dwLastSignatureIP
= GetIP();
2180 void CUpDownClient::SendSecIdentStatePacket(){
2181 // check if we need public key and signature
2184 if (theApp
->CryptoAvailable()){
2185 if (credits
->GetSecIDKeyLen() == 0) {
2186 nValue
= IS_KEYANDSIGNEEDED
;
2187 } else if (m_dwLastSignatureIP
!= GetIP()) {
2188 nValue
= IS_SIGNATURENEEDED
;
2192 AddDebugLogLineM( false, logClient
, wxT("Not sending SecIdentState Packet, because State is Zero") );
2195 // crypt: send random data to sign
2196 uint32 dwRandom
= rand()+1;
2197 credits
->m_dwCryptRndChallengeFor
= dwRandom
;
2200 data
.WriteUInt8(nValue
);
2201 data
.WriteUInt32(dwRandom
);
2202 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_SECIDENTSTATE
);
2204 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2205 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
2206 SendPacket(packet
,true,true);
2213 void CUpDownClient::ProcessSecIdentStatePacket(const byte
* pachPacket
, uint32 nSize
)
2220 wxASSERT( credits
);
2224 CMemFile
data(pachPacket
,nSize
);
2226 switch ( data
.ReadUInt8() ) {
2228 m_SecureIdentState
= IS_UNAVAILABLE
;
2231 m_SecureIdentState
= IS_SIGNATURENEEDED
;
2234 m_SecureIdentState
= IS_KEYANDSIGNEEDED
;
2240 credits
->m_dwCryptRndChallengeFrom
= data
.ReadUInt32();
2244 void CUpDownClient::InfoPacketsReceived()
2246 // indicates that both Information Packets has been received
2247 // needed for actions, which process data from both packets
2248 wxASSERT ( m_byInfopacketsReceived
== IP_BOTH
);
2249 m_byInfopacketsReceived
= IP_NONE
;
2251 if (m_bySupportSecIdent
){
2252 SendSecIdentStatePacket();
2257 bool CUpDownClient::CheckHandshakeFinished() const
2259 if (m_bHelloAnswerPending
) {
2260 // this triggers way too often.. need more time to look at this -> only create a warning
2261 // The reason for this is that 2 clients are connecting to each other at the same time..
2262 AddDebugLogLineM( false, logClient
, wxT("Handshake not finished while processing packet.") );
2270 wxString
CUpDownClient::GetClientFullInfo()
2272 if (m_clientVerString
.IsEmpty()) {
2276 return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") )
2277 % ( m_Username
.IsEmpty() ? wxString(_("Unknown")) : m_Username
)
2280 % m_clientSoftString
2286 wxString
CUpDownClient::GetClientShortInfo()
2288 if (m_clientVerString
.IsEmpty()) {
2292 return CFormat( wxT("'%s' (%s %s %s)") )
2293 % ( m_Username
.IsEmpty() ? wxString(_("Unknown")) : m_Username
)
2294 % m_clientSoftString
2300 void CUpDownClient::SendPublicIPRequest()
2303 CPacket
* packet
= new CPacket(OP_PUBLICIP_REQ
,0,OP_EMULEPROT
);
2304 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2305 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_PUBLICIP_REQ to") + GetFullIP());
2306 SendPacket(packet
,true);
2307 m_fNeedOurPublicIP
= true;
2311 void CUpDownClient::ProcessPublicIPAnswer(const byte
* pbyData
, uint32 uSize
)
2314 throw wxString(wxT("Wrong Packet size on Public IP answer"));
2316 uint32 dwIP
= PeekUInt32(pbyData
);
2317 if (m_fNeedOurPublicIP
== true){ // did we?
2318 m_fNeedOurPublicIP
= false;
2319 // Ignore local ip on GetPublicIP (could be wrong)
2320 if (theApp
->GetPublicIP(true) == 0 && !IsLowID(dwIP
) ) {
2321 theApp
->SetPublicIP(dwIP
);
2327 bool CUpDownClient::IsConnected() const
2329 return m_socket
&& m_socket
->IsConnected();
2332 bool CUpDownClient::SendPacket(CPacket
* packet
, bool delpacket
, bool controlpacket
)
2335 m_socket
->SendPacket(packet
, delpacket
, controlpacket
);
2338 AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()"));
2343 float CUpDownClient::SetDownloadLimit(uint32 reducedownload
)
2345 // lfroen: in daemon it actually can happen
2346 wxASSERT( m_socket
);
2348 float kBpsClient
= CalculateKBpsDown();
2352 if (reducedownload
) {
2353 // (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD)
2354 // which is how often it is called per second.
2355 uint32 limit
= (uint32
)(reducedownload
* kBpsClient
* 1024.0 / 100000.0 * CORE_TIMER_PERIOD
);
2357 if(limit
<1024 && reducedownload
>= 200) {
2358 // If we're going up and this download is < 1kB,
2359 // we want it to go up fast. Can be reduced later,
2360 // and it'll probably be in a more fair way with
2361 // other downloads that are faster.
2363 } else if(limit
== 0) {
2364 // This download is not transferring yet... make it
2365 // 1024 so we don't fill the TCP stack and lose the
2370 m_socket
->SetDownloadLimit(limit
);
2372 m_socket
->DisableDownloadLimit();
2376 AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient
);
2382 void CUpDownClient::SetUserIDHybrid(uint32 nUserID
)
2384 theApp
->clientlist
->UpdateClientID( this, nUserID
);
2386 m_nUserIDHybrid
= nUserID
;
2390 void CUpDownClient::SetIP( uint32 val
)
2392 theApp
->clientlist
->UpdateClientIP( this, val
);
2402 void CUpDownClient::SetUserHash(const CMD4Hash
& userhash
)
2404 theApp
->clientlist
->UpdateClientHash( this, userhash
);
2406 m_UserHash
= userhash
;
2411 EUtf8Str
CUpDownClient::GetUnicodeSupport() const
2413 return m_bUnicodeSupport
? utf8strRaw
: utf8strNone
;
2416 void CUpDownClient::SetSpammer(bool bVal
)
2420 } else if (IsBanned() && m_fIsSpammer
) {
2423 m_fIsSpammer
= bVal
;
2426 uint8
CUpDownClient::GetSecureIdentState()
2428 if (m_SecureIdentState
!= IS_UNAVAILABLE
) {
2429 if (!SecIdentSupRec
) {
2430 // This can be caused by a 0.30x based client which sends the old
2431 // style Hello packet, and the mule info packet, but between them they
2432 // send a secure ident state packet (after a hello but before we have
2433 // the SUI capabilities). This is a misbehaving client, and somehow I
2434 // feel like it should be dropped. But then again, it won't harm to use
2435 // this SUI state if they are reporting no SUI (won't be used) and if
2436 // they report using SUI on the mule info packet, it's ok to use it.
2438 AddDebugLogLineM(false, logClient
, wxT("A client sent secure ident state before telling us the SUI capabilities"));
2439 AddDebugLogLineM(false, logClient
, wxT("Client info: ") + GetClientFullInfo());
2440 AddDebugLogLineM(false, logClient
, wxT("This client won't be disconnected, but it should be. :P"));
2444 return m_SecureIdentState
;
2448 bool CUpDownClient::SendChatMessage(const wxString
& message
)
2450 if (GetChatCaptchaState() == CA_CAPTCHARECV
) {
2451 m_nChatCaptchaState
= CA_SOLUTIONSENT
;
2452 } else if (GetChatCaptchaState() == CA_SOLUTIONSENT
) {
2453 wxFAIL
; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through
2455 m_nChatCaptchaState
= CA_ACCEPTING
;
2460 // Already connecting?
2461 if (GetChatState() == MS_CONNECTING
) {
2462 // Queue all messages till we're able to send them (or discard them)
2463 if (!m_pendingMessage
.IsEmpty()) {
2464 m_pendingMessage
+= wxT("\n");
2466 // There must be a message to send
2467 // - except if we got disconnected. No need to assert therefore.
2469 m_pendingMessage
+= message
;
2472 if (IsConnected()) {
2473 // If we are already connected when we send the first message,
2474 // we have to update the chat status.
2475 SetChatState(MS_CHATTING
);
2477 data
.WriteString(message
, GetUnicodeSupport());
2478 CPacket
* packet
= new CPacket(data
, OP_EDONKEYPROT
, OP_MESSAGE
);
2479 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2480 AddDebugLogLineM( false, logLocalClient
, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
2481 SendPacket(packet
, true, true);
2484 m_pendingMessage
= message
;
2485 SetChatState(MS_CONNECTING
);
2486 // True to ignore "Too Many Connections"
2494 void CUpDownClient::SetBuddyID(const byte
* pucBuddyID
)
2496 if( pucBuddyID
== NULL
){
2497 md4clr(m_achBuddyID
);
2498 m_bBuddyIDValid
= false;
2501 m_bBuddyIDValid
= true;
2502 md4cpy(m_achBuddyID
, pucBuddyID
);
2507 bool CUpDownClient::SendBuddyPing() {
2508 SetLastBuddyPingPongTime();
2509 CPacket
* buddyPing
= new CPacket(OP_BUDDYPING
, 0, OP_EMULEPROT
);
2510 theStats::AddUpOverheadKad(buddyPing
->GetPacketSize());
2511 AddDebugLogLineM(false, logLocalClient
,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
2512 return SafeSendPacket(buddyPing
);
2518 void CUpDownClient::UpdateStats()
2520 if (m_lastClientSoft
!= m_clientSoft
|| m_lastClientVersion
!= m_nClientVersion
|| m_lastOSInfo
!= m_sClientOSInfo
) {
2521 if (m_lastClientSoft
== SO_UNKNOWN
) {
2522 theStats::RemoveUnknownClient();
2523 } else if (m_lastClientSoft
!= (uint32
)(-1)) {
2524 theStats::RemoveKnownClient(m_lastClientSoft
, m_lastClientVersion
, m_lastOSInfo
);
2527 m_lastClientSoft
= m_clientSoft
;
2528 m_lastClientVersion
= m_nClientVersion
;
2529 m_lastOSInfo
= m_sClientOSInfo
;
2531 if (m_clientSoft
== SO_UNKNOWN
) {
2532 theStats::AddUnknownClient();
2534 theStats::AddKnownClient(this);
2539 bool CUpDownClient::IsIdentified() const
2541 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED
);
2544 bool CUpDownClient::IsBadGuy() const
2546 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDBADGUY
);
2549 bool CUpDownClient::SUIFailed() const
2551 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDFAILED
);
2554 bool CUpDownClient::SUINeeded() const
2556 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_IDNEEDED
);
2559 bool CUpDownClient::SUINotSupported() const
2561 return (credits
&& credits
->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE
);
2564 uint64
CUpDownClient::GetDownloadedTotal() const
2566 return credits
? credits
->GetDownloadedTotal() : 0;
2569 uint64
CUpDownClient::GetUploadedTotal() const
2571 return credits
? credits
->GetUploadedTotal() : 0;
2574 double CUpDownClient::GetScoreRatio() const
2576 return credits
? credits
->GetScoreRatio(GetIP(), theApp
->CryptoAvailable()) : 0;
2579 const wxString
CUpDownClient::GetServerName() const
2582 wxString srvaddr
= Uint32toStringIP(GetServerIP());
2583 CServer
* cserver
= theApp
->serverlist
->GetServerByAddress(
2584 srvaddr
, GetServerPort());
2586 ret
= cserver
->GetListName();
2594 bool CUpDownClient::ShouldReceiveCryptUDPPackets() const
2596 return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp
->GetPublicIP() != 0
2597 && HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) );
2602 void CUpDownClient::ProcessCaptchaRequest(CMemFile
* WXUNUSED(data
)) {}
2603 void CUpDownClient::ProcessCaptchaReqRes(uint8
WXUNUSED(nStatus
)) {}
2604 void CUpDownClient::ProcessChatMessage(const wxString
WXUNUSED(message
)) {}
2608 void CUpDownClient::ProcessCaptchaRequest(CMemFile
* data
)
2610 uint64 id
= GUI_ID(GetIP(),GetUserPort());
2611 // received a captcha request, check if we actually accept it (only after sending a message ourself to this client)
2612 if (GetChatCaptchaState() == CA_ACCEPTING
&& GetChatState() != MS_NONE
2613 && theApp
->amuledlg
->m_chatwnd
->IsIdValid(id
)) {
2614 // read tags (for future use)
2615 uint8 nTagCount
= data
->ReadUInt8();
2617 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount
);
2618 // and ignore them for now
2619 for (uint32 i
= 0; i
< nTagCount
; i
++) {
2620 CTag
tag(*data
, true);
2624 // sanitize checks - we want a small captcha not a wallpaper
2625 uint32 nSize
= (uint32
)(data
->GetLength() - data
->GetPosition());
2627 if ( nSize
> 128 && nSize
< 4096 ) {
2628 uint64 pos
= data
->GetPosition();
2629 wxMemoryInputStream
memstr(data
->GetRawBuffer() + pos
, nSize
);
2630 wxImage
imgCaptcha(memstr
, wxBITMAP_TYPE_BMP
);
2632 if (imgCaptcha
.IsOk() && imgCaptcha
.GetHeight() > 10 && imgCaptcha
.GetHeight() < 50
2633 && imgCaptcha
.GetWidth() > 10 && imgCaptcha
.GetWidth() < 150 ) {
2634 m_nChatCaptchaState
= CA_CAPTCHARECV
;
2635 CCaptchaDialog
* dialog
= new CCaptchaDialog(theApp
->amuledlg
, imgCaptcha
, id
);
2639 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP());
2642 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize
% GetFullIP());
2645 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP());
2649 void CUpDownClient::ProcessCaptchaReqRes(uint8 nStatus
)
2651 uint64 id
= GUI_ID(GetIP(),GetUserPort());
2652 if (GetChatCaptchaState() == CA_SOLUTIONSENT
&& GetChatState() != MS_NONE
2653 && theApp
->amuledlg
->m_chatwnd
->IsIdValid(id
)) {
2654 wxASSERT( nStatus
< 3 );
2655 m_nChatCaptchaState
= CA_NONE
;
2656 theApp
->amuledlg
->m_chatwnd
->ShowCaptchaResult(id
, nStatus
== 0);
2658 m_nChatCaptchaState
= CA_NONE
;
2659 AddDebugLogLineN(logClient
, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP());
2663 void CUpDownClient::ProcessChatMessage(wxString message
)
2665 if (IsMessageFiltered(message
)) {
2666 AddLogLineM( true, CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP());
2670 // advanced spamfilter check
2671 if (thePrefs::IsChatCaptchaEnabled() && !IsFriend()) {
2672 // captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam
2673 // first check if we need to send a captcha request to this client
2674 if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED
) {
2675 // we have never sent a message to this client, and no message from him has ever passed our filters
2676 if (GetChatCaptchaState() != CA_CHALLENGESENT
) {
2677 // we also aren't currently expecting a captcha response
2678 if (m_fSupportsCaptcha
) {
2679 // and he supports captcha, so send him one and store the message (without showing for now)
2680 if (m_cCaptchasSent
< 3) { // no more than 3 tries
2681 m_strCaptchaPendingMsg
= message
;
2682 wxMemoryOutputStream memstr
;
2683 memstr
.PutC(0); // no tags, for future use
2684 CCaptchaGenerator
captcha(4);
2685 if (captcha
.WriteCaptchaImage(memstr
)){
2686 m_strCaptchaChallenge
= captcha
.GetCaptchaText();
2687 m_nChatCaptchaState
= CA_CHALLENGESENT
;
2689 CMemFile
fileAnswer((byte
*) memstr
.GetOutputStreamBuffer()->GetBufferStart(), memstr
.GetLength());
2690 CPacket
* packet
= new CPacket(fileAnswer
, OP_EMULEPROT
, OP_CHATCAPTCHAREQ
);
2691 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2692 AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % m_strCaptchaChallenge
% packet
->GetPacketSize());
2693 SafeSendPacket(packet
);
2699 // client doesn't support captchas, but we require them, tell him that it's not going to work out
2700 // with an answer message (will not be shown and doesn't count as sent message)
2701 if (m_cCaptchasSent
< 1) { // don't send this notifier more than once
2703 // always sent in english
2704 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."));
2705 AddDebugLogLineN(logClient
, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo());
2707 AddDebugLogLineN(logClient
, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo());
2711 } else { // (GetChatCaptchaState() == CA_CHALLENGESENT)
2712 // this message must be the answer to the captcha request we sent him, let's verify
2713 wxASSERT( !m_strCaptchaChallenge
.IsEmpty() );
2714 if (m_strCaptchaChallenge
.CmpNoCase(message
.Trim().Right(std::min(message
.Length(), m_strCaptchaChallenge
.Length()))) == 0) {
2716 AddDebugLogLineN(logClient
, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo());
2717 m_nChatCaptchaState
= CA_CAPTCHASOLVED
; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved
2718 // replace captchaanswer with withheld message and show it
2719 message
= m_strCaptchaPendingMsg
;
2720 m_cCaptchasSent
= 0;
2721 m_strCaptchaChallenge
= wxEmptyString
;
2722 CPacket
* packet
= new CPacket(OP_CHATCAPTCHARES
, 1, OP_EMULEPROT
, false);
2723 byte statusResponse
= 0; // status response
2724 packet
->CopyToDataBuffer(0, &statusResponse
, 1);
2725 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2726 SafeSendPacket(packet
);
2727 } else { // wrong, cleanup and ignore
2728 AddDebugLogLineN(logClient
, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo());
2729 m_nChatCaptchaState
= CA_NONE
;
2730 m_strCaptchaChallenge
= wxEmptyString
;
2731 m_strCaptchaPendingMsg
= wxEmptyString
;
2732 CPacket
* packet
= new CPacket(OP_CHATCAPTCHARES
, 1, OP_EMULEPROT
, false);
2733 byte statusResponse
= (m_cCaptchasSent
< 3) ? 1 : 2; // status response
2734 packet
->CopyToDataBuffer(0, &statusResponse
, 1);
2735 theStats::AddUpOverheadOther(packet
->GetPacketSize());
2736 SafeSendPacket(packet
);
2737 return; // nothing more todo
2743 if (thePrefs::IsAdvancedSpamfilterEnabled() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P )
2744 bool bIsSpam
= false;
2748 // first fixed criteria: If a client sends me an URL in his first message before I respond to him
2749 // there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P
2750 if (GetMessagesSent() == 0) {
2751 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("|")));
2752 for (size_t pos
= urlindicators
.GetCount(); pos
--;) {
2753 if (message
.Find(urlindicators
[pos
]) != wxNOT_FOUND
) {
2758 // second fixed criteria: he sent me 4 or more messages and I didn't answer him once
2759 if (GetMessagesReceived() > 3) {
2765 AddDebugLogLineN(logClient
, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName());
2767 theApp
->amuledlg
->m_chatwnd
->EndSession(GUI_ID(GetIP(),GetUserPort()));
2773 wxString logMsg
= CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP();
2774 if(thePrefs::ShowMessagesInLog()) {
2775 logMsg
+= wxT(": ") + message
;
2777 AddLogLineM(true, logMsg
);
2778 IncMessagesReceived();
2780 Notify_ChatProcessMsg(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message
);
2783 bool CUpDownClient::IsMessageFiltered(const wxString
& message
)
2785 bool filtered
= false;
2786 // If we're chatting to the guy, we don't want to filter!
2787 if (GetChatState() != MS_CHATTING
) {
2788 if (thePrefs::MsgOnlyFriends() && !IsFriend()) {
2790 } else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) {
2792 } else if (thePrefs::MustFilterMessages()) {
2793 filtered
= thePrefs::IsMessageFiltered(message
);
2805 void CUpDownClient::SendFirewallCheckUDPRequest()
2807 wxASSERT(GetKadState() == KS_FWCHECK_UDP
);
2809 if (!Kademlia::CKademlia::IsRunning()) {
2810 SetKadState(KS_NONE
);
2812 } else if (GetUploadState() != US_NONE
|| GetDownloadState() != DS_NONE
|| GetChatState() != MS_NONE
|| GetKadVersion() <= 5 || GetKadPort() == 0) {
2813 Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
2814 SetKadState(KS_NONE
);
2819 data
.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
2820 data
.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
2821 data
.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
2822 CPacket
* packet
= new CPacket(data
, OP_EMULEPROT
, OP_FWCHECKUDPREQ
);
2823 theStats::AddUpOverheadKad(packet
->GetPacketSize());
2824 SafeSendPacket(packet
);
2827 void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile
* data
)
2829 if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL
) {
2830 //DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
2834 // first search if we know this IP already, if so the result might be biased and we need tell the requester
2835 bool errorAlreadyKnown
= false;
2836 if (GetUploadState() != US_NONE
|| GetDownloadState() != DS_NONE
|| GetChatState() != MS_NONE
) {
2837 errorAlreadyKnown
= true;
2838 } else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL
) {
2839 errorAlreadyKnown
= true;
2842 uint16_t remoteInternPort
= data
->ReadUInt16();
2843 uint16_t remoteExternPort
= data
->ReadUInt16();
2844 uint32_t senderKey
= data
->ReadUInt32();
2845 if (remoteInternPort
== 0) {
2846 //DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
2849 // if (senderKey == 0)
2850 // DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
2852 CMemFile testPacket1
;
2853 testPacket1
.WriteUInt8(errorAlreadyKnown
? 1 : 0);
2854 testPacket1
.WriteUInt16(remoteInternPort
);
2855 DebugSend(Kad2FirewallUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort
);
2856 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1
, KADEMLIA2_FIREWALLUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort
, Kademlia::CKadUDPKey(senderKey
, theApp
->GetPublicIP(false)), NULL
);
2858 // if the client has a router with PAT (and therefore a different extern port than intern), test this port too
2859 if (remoteExternPort
!= 0 && remoteExternPort
!= remoteInternPort
) {
2860 CMemFile testPacket2
;
2861 testPacket2
.WriteUInt8(errorAlreadyKnown
? 1 : 0);
2862 testPacket2
.WriteUInt16(remoteExternPort
);
2863 DebugSend(Kad2FirewalledUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort
);
2864 Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2
, KADEMLIA2_FIREWALLUDP
, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort
, Kademlia::CKadUDPKey(senderKey
, theApp
->GetPublicIP(false)), NULL
);
2866 //DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
2869 void CUpDownClient::SetConnectOptions(uint8_t options
, bool encryption
, bool callback
)
2871 SetCryptLayerSupport((options
& 0x01) != 0 && encryption
);
2872 SetCryptLayerRequest((options
& 0x02) != 0 && encryption
);
2873 SetCryptLayerRequires((options
& 0x04) != 0 && encryption
);
2874 SetDirectUDPCallbackSupport((options
& 0x08) != 0 && callback
);
2876 // File_checked_for_headers