Fix compilation with wxWidgets 2.8.12
[amule.git] / src / ClientTCPSocket.cpp
blob73e5d21cd9812dfa282aaaae9248c5033f242f09
1 //
2 // This file is part of the aMule Project.
3 //
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 )//
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
8 // respective authors.
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "ClientTCPSocket.h" // Interface declarations
27 #include <protocol/Protocols.h>
28 #include <protocol/ed2k/Client2Client/TCP.h>
29 #include <protocol/ed2k/Client2Client/UDP.h> // Sometimes we reply with UDP packets.
30 #include <protocol/ed2k/ClientSoftware.h>
31 #include <protocol/kad2/Client2Client/TCP.h>
32 #include <common/EventIDs.h>
34 #include "Preferences.h" // Needed for thePrefs
35 #include "Packet.h" // Needed for CPacket
36 #include "Statistics.h" // Needed for theStats
37 #include "Logger.h" // Neeed for logRemoteClient
38 #include "updownclient.h" // Needed for CUpDownClient
39 #include <common/Format.h> // Needed for CFormat
40 #include "amule.h" // Needed for theApp
41 #include "SharedFileList.h" // Needed for CSharedFileList
42 #include "ClientList.h" // Needed for CClientList
43 #include "UploadQueue.h" // Needed for CUploadQueue
44 #include "ClientUDPSocket.h" // Needed for CClientUDPSocket
45 #include "PartFile.h" // Needed for CPartFile
46 #include "MemFile.h" // Needed for CMemFile
47 #include "kademlia/kademlia/Kademlia.h" // Needed for CKademlia::Kademlia
48 #include "kademlia/kademlia/Prefs.h" // Needed for CKademlia::CPrefs
49 #include "DownloadQueue.h" // Needed for CDownloadQueue
50 #include "Server.h" // Needed for CServer
51 #include "ServerList.h" // Needed for CServerList
52 #include "IPFilter.h" // Needed for CIPFilter
53 #include "ListenSocket.h" // Needed for CListenSocket
54 #include "GuiEvents.h" // Needed for Notify_*
57 //#define __PACKET_RECV_DUMP__
59 #ifndef ASIO_SOCKETS
61 //------------------------------------------------------------------------------
62 // CClientTCPSocketHandler
63 //------------------------------------------------------------------------------
65 class CClientTCPSocketHandler: public wxEvtHandler
67 public:
68 CClientTCPSocketHandler() {};
70 private:
71 void ClientTCPSocketHandler(wxSocketEvent& event);
72 DECLARE_EVENT_TABLE()
75 BEGIN_EVENT_TABLE(CClientTCPSocketHandler, wxEvtHandler)
76 EVT_SOCKET(ID_CLIENTTCPSOCKET_EVENT, CClientTCPSocketHandler::ClientTCPSocketHandler)
77 END_EVENT_TABLE()
79 void CClientTCPSocketHandler::ClientTCPSocketHandler(wxSocketEvent& event)
81 wxSocketBase* baseSocket = event.GetSocket();
82 // wxASSERT(baseSocket); // Rather want a log message right now. Enough other wx problems. >:(
83 if (!baseSocket) { // WTF?
84 AddDebugLogLineN(logClient, wxT("received bad wxSocketEvent"));
85 return;
88 CClientTCPSocket *socket = dynamic_cast<CClientTCPSocket *>(baseSocket);
89 wxASSERT(socket);
90 if (!socket) {
91 return;
94 if (socket->IsDestroying()) {
95 return;
98 switch(event.GetSocketEvent()) {
99 case wxSOCKET_LOST:
100 socket->OnError(0xFEFF /* SOCKET_LOST is not an error */);
101 break;
102 case wxSOCKET_INPUT:
103 socket->OnReceive(0);
104 break;
105 case wxSOCKET_OUTPUT:
106 socket->OnSend(0);
107 break;
108 case wxSOCKET_CONNECTION:
109 // connection stablished, nothing to do about it?
110 socket->OnConnect(socket->LastError());
111 break;
112 default:
113 // Nothing should arrive here...
114 wxFAIL;
115 break;
120 // There can be only one. :)
122 static CClientTCPSocketHandler g_clientReqSocketHandler;
124 #endif /* !ASIO_SOCKETS */
127 //------------------------------------------------------------------------------
128 // CClientTCPSocket
129 //------------------------------------------------------------------------------
131 CClientTCPSocket::CClientTCPSocket(CUpDownClient* in_client, const CProxyData *ProxyData)
132 : CEMSocket(ProxyData)
134 SetClient(in_client);
135 if (in_client) {
136 m_remoteip = wxUINT32_SWAP_ALWAYS(in_client->GetUserIDHybrid());
137 } else {
138 m_remoteip = 0;
141 ResetTimeOutTimer();
143 #ifndef ASIO_SOCKETS
144 SetEventHandler(g_clientReqSocketHandler, ID_CLIENTTCPSOCKET_EVENT);
145 SetNotify(
146 wxSOCKET_CONNECTION_FLAG |
147 wxSOCKET_INPUT_FLAG |
148 wxSOCKET_OUTPUT_FLAG |
149 wxSOCKET_LOST_FLAG);
150 #endif
151 Notify(true);
153 theApp->listensocket->AddSocket(this);
154 theApp->listensocket->AddConnection();
157 CClientTCPSocket::~CClientTCPSocket()
159 #ifndef ASIO_SOCKETS
160 // remove event handler
161 SetNotify(0);
162 Notify(false);
163 #endif
165 if (m_client) {
166 m_client->SetSocket( NULL );
168 m_client = NULL;
170 if (theApp->listensocket && !theApp->listensocket->OnShutdown()) {
171 theApp->listensocket->RemoveSocket(this);
175 bool CClientTCPSocket::InitNetworkData()
177 wxASSERT(!m_remoteip);
178 wxASSERT(!m_client);
179 m_remoteip = GetPeerInt();
181 MULE_CHECK(m_remoteip, false);
183 if (theApp->ipfilter->IsFiltered(m_remoteip)) {
184 AddDebugLogLineN(logClient, wxT("Denied connection from ") + GetPeer() + wxT("(Filtered IP)"));
185 return false;
186 } else if (theApp->clientlist->IsBannedClient(m_remoteip)) {
187 AddDebugLogLineN(logClient, wxT("Denied connection from ") + GetPeer() + wxT("(Banned IP)"));
188 return false;
189 } else {
190 AddDebugLogLineN(logClient, wxT("Accepted connection from ") + GetPeer());
191 return true;
195 void CClientTCPSocket::ResetTimeOutTimer()
197 timeout_timer = ::GetTickCount();
201 bool CClientTCPSocket::CheckTimeOut()
203 // 0.42x
204 uint32 uTimeout = GetTimeOut();
205 if (m_client) {
207 if (m_client->GetKadState() == KS_CONNECTED_BUDDY) {
208 //We originally ignored the timeout here for buddies.
209 //This was a stupid idea on my part. There is now a ping/pong system
210 //for buddies. This ping/pong system now prevents timeouts.
211 //This release will allow lowID clients with KadVersion 0 to remain connected.
212 //But a soon future version needs to allow these older clients to time out to prevent dead connections from continuing.
213 //JOHNTODO: Don't forget to remove backward support in a future release.
214 if ( m_client->GetKadVersion() == 0 ) {
215 return false;
218 uTimeout += MIN2MS(15);
221 if (m_client->GetChatState() != MS_NONE) {
222 uTimeout += CONNECTION_TIMEOUT;
226 if (::GetTickCount() - timeout_timer > uTimeout){
227 timeout_timer = ::GetTickCount();
228 Disconnect(wxT("Timeout"));
229 return true;
232 return false;
236 void CClientTCPSocket::SetClient(CUpDownClient* pClient)
238 m_client = pClient;
239 if (m_client) {
240 m_client->SetSocket( this );
245 void CClientTCPSocket::OnClose(int nErrorCode)
247 // 0.42x
248 wxASSERT(theApp->listensocket->IsValidSocket(this));
249 CEMSocket::OnClose(nErrorCode);
250 if (nErrorCode) {
251 Disconnect(CFormat(wxT("Closed: %u")) % nErrorCode);
252 } else {
253 Disconnect(wxT("Close"));
258 void CClientTCPSocket::Disconnect(const wxString& strReason)
260 byConnected = ES_DISCONNECTED;
261 if (m_client) {
262 if (m_client->Disconnected(strReason, true)) {
263 // Somehow, Safe_Delete() is beeing called by Disconnected(),
264 // or any other function that sets m_client to NULL,
265 // so we must check m_client first.
266 if (m_client) {
267 m_client->SetSocket( NULL );
268 m_client->Safe_Delete();
271 m_client = NULL;
274 Safe_Delete();
278 void CClientTCPSocket::Safe_Delete()
280 // More paranoia - make sure client is unlinked in any case
281 if (m_client) {
282 m_client->SetSocket( NULL );
283 m_client = NULL;
286 // Destroy may be called several times
287 byConnected = ES_DISCONNECTED;
288 Destroy();
292 void CClientTCPSocket::Safe_Delete_Client()
294 if (m_client) {
295 m_client->Safe_Delete();
296 m_client = NULL;
301 bool CClientTCPSocket::ProcessPacket(const byte* buffer, uint32 size, uint8 opcode)
303 #ifdef __PACKET_RECV_DUMP__
304 //printf("Rec: OPCODE %x \n",opcode);
305 DumpMem(buffer, size);
306 #endif
307 if (!m_client && opcode != OP_HELLO) {
308 throw wxString(wxT("Asks for something without saying hello"));
309 } else if (m_client && opcode != OP_HELLO && opcode != OP_HELLOANSWER) {
310 m_client->CheckHandshakeFinished();
313 switch(opcode) {
314 case OP_HELLOANSWER: { // 0.43b
315 AddDebugLogLineN(logRemoteClient, wxT("Remote Client: OP_HELLOANSWER from ") + m_client->GetFullIP());
316 theStats::AddDownOverheadOther(size);
317 m_client->ProcessHelloAnswer(buffer, size);
319 // start secure identification, if
320 // - we have received OP_EMULEINFO and OP_HELLOANSWER (old eMule)
321 // - we have received eMule-OP_HELLOANSWER (new eMule)
322 if (m_client->GetInfoPacketsReceived() == IP_BOTH) {
323 m_client->InfoPacketsReceived();
326 // Socket might die because of sending in InfoPacketsReceived, so check
327 if (m_client) {
328 m_client->ConnectionEstablished();
331 // Socket might die on ConnectionEstablished somehow. Check it.
332 if (m_client) {
333 Notify_SharedCtrlRefreshClient( m_client->ECID() , AVAILABLE_SOURCE);
336 break;
338 case OP_HELLO: { // 0.43b
340 theStats::AddDownOverheadOther(size);
341 bool bNewClient = !m_client;
342 if (bNewClient) {
343 // create new client to save standart informations
344 m_client = new CUpDownClient(this);
347 // Do not move up!
348 AddDebugLogLineN(logRemoteClient, wxT("Remote Client: OP_HELLO from ") + m_client->GetFullIP() );
350 bool bIsMuleHello = false;
352 try{
353 bIsMuleHello = m_client->ProcessHelloPacket(buffer, size);
354 } catch(...) {
355 if (bNewClient && m_client) {
356 // Don't let CUpDownClient::Disconnected be processed for a client which is not in the list of clients.
357 m_client->Safe_Delete();
358 m_client = NULL;
360 throw;
363 if (thePrefs::ParanoidFilter() && !IsLowID(m_client->GetUserIDHybrid()) && (GetRemoteIP() != wxUINT32_SWAP_ALWAYS(m_client->GetUserIDHybrid()))) {
364 wxString reason = wxT("Client claims a different IP from the one we received the hello packet from: ");
365 reason += Uint32toStringIP(wxUINT32_SWAP_ALWAYS(m_client->GetUserIDHybrid())) + wxT(" / ") + Uint32toStringIP(GetRemoteIP());
366 AddDebugLogLineN(logClient, reason);
367 if (bNewClient) {
368 m_client->Safe_Delete();
369 m_client = NULL;
371 Disconnect(wxT("Paranoid disconecting: ") + reason);
372 return false;
375 // if IP is filtered, dont reply but disconnect...
376 if (theApp->ipfilter->IsFiltered(m_client->GetIP())) {
377 if (bNewClient) {
378 m_client->Safe_Delete();
379 m_client = NULL;
381 Disconnect(wxT("IPFilter"));
382 return false;
385 wxASSERT(m_client);
387 // now we check if we know this client already. if yes this socket will
388 // be attached to the known client, the new client will be deleted
389 // and the var. "client" will point to the known client.
390 // if not we keep our new-constructed client ;)
391 if (theApp->clientlist->AttachToAlreadyKnown(&m_client,this)) {
392 // update the old client informations
393 bIsMuleHello = m_client->ProcessHelloPacket(buffer, size);
394 } else {
395 theApp->clientlist->AddClient(m_client);
396 m_client->SetCommentDirty();
398 Notify_SharedCtrlRefreshClient( m_client->ECID(), AVAILABLE_SOURCE );
399 // send a response packet with standart informations
400 if ((m_client->GetHashType() == SO_EMULE) && !bIsMuleHello) {
401 m_client->SendMuleInfoPacket(false);
404 // Client might die from Sending in SendMuleInfoPacket, so check
405 if ( m_client ) {
406 m_client->SendHelloAnswer();
409 // Kry - If the other side supports it, send OS_INFO
410 // Client might die from Sending in SendHelloAnswer, so check
411 if (m_client && m_client->GetOSInfoSupport()) {
412 m_client->SendMuleInfoPacket(false,true); // Send the OS Info tag on the recycled Mule Info
415 // Client might die from Sending in SendMuleInfoPacket, so check
416 if ( m_client ) {
417 m_client->ConnectionEstablished();
420 // start secure identification, if
421 // - we have received eMule-OP_HELLO (new eMule)
422 if (m_client && m_client->GetInfoPacketsReceived() == IP_BOTH) {
423 m_client->InfoPacketsReceived();
426 break;
428 case OP_REQUESTFILENAME: { // 0.43b
429 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REQUESTFILENAME from ") + m_client->GetFullIP() );
431 theStats::AddDownOverheadFileRequest(size);
432 // IP banned, no answer for this request
433 if (m_client->IsBanned()) {
434 break;
436 if (size >= 16) {
437 if (!m_client->GetWaitStartTime()) {
438 m_client->SetWaitStartTime();
440 CMemFile data_in(buffer, size);
441 CMD4Hash reqfilehash = data_in.ReadHash();
442 CKnownFile *reqfile = theApp->sharedfiles->GetFileByID(reqfilehash);
443 if ( reqfile == NULL ) {
444 reqfile = theApp->downloadqueue->GetFileByID(reqfilehash);
445 if ( !( reqfile != NULL && reqfile->GetFileSize() > PARTSIZE ) ) {
446 break;
449 // if we are downloading this file, this could be a new source
450 // no passive adding of files with only one part
451 if (reqfile->IsPartFile() && reqfile->GetFileSize() > PARTSIZE) {
452 if (thePrefs::GetMaxSourcePerFile() > static_cast<CPartFile*>(reqfile)->GetSourceCount()) {
453 theApp->downloadqueue->CheckAndAddKnownSource(static_cast<CPartFile*>(reqfile), m_client);
457 // check to see if this is a new file they are asking for
458 if (m_client->GetUploadFileID() != reqfilehash) {
459 m_client->SetCommentDirty();
462 m_client->SetUploadFileID(reqfile);
463 m_client->ProcessExtendedInfo(&data_in, reqfile);
465 // send filename etc
466 CMemFile data_out(128);
467 data_out.WriteHash(reqfile->GetFileHash());
469 // Since it's for somebody else to see, we need to send the prettified
470 // filename, rather than the (possibly) mangled actual filename.
471 data_out.WriteString(reqfile->GetFileName().GetPrintable(), m_client->GetUnicodeSupport());
473 CPacket* packet = new CPacket(data_out, OP_EDONKEYPROT, OP_REQFILENAMEANSWER);
474 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
475 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_REQFILENAMEANSWER to ") + m_client->GetFullIP() );
476 SendPacket(packet,true);
478 // SendPacket might kill the socket, so check
479 if (m_client)
480 m_client->SendCommentInfo(reqfile);
482 break;
484 throw wxString(wxT("Invalid OP_REQUESTFILENAME packet size"));
485 break;
487 case OP_SETREQFILEID: { // 0.43b EXCEPT track of bad clients
488 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_SETREQFILEID from ") + m_client->GetFullIP() );
490 theStats::AddDownOverheadFileRequest(size);
492 if (m_client->IsBanned()) {
493 break;
496 // DbT:FileRequest
497 if (size == 16) {
498 if (!m_client->GetWaitStartTime()) {
499 m_client->SetWaitStartTime();
502 const CMD4Hash fileID(buffer);
503 CKnownFile *reqfile = theApp->sharedfiles->GetFileByID(fileID);
504 if ( reqfile == NULL ) {
505 reqfile = theApp->downloadqueue->GetFileByID(fileID);
506 if ( !( reqfile != NULL && reqfile->GetFileSize() > PARTSIZE ) ) {
507 CPacket* replypacket = new CPacket(OP_FILEREQANSNOFIL, 16, OP_EDONKEYPROT);
508 replypacket->Copy16ToDataBuffer(fileID.GetHash());
509 theStats::AddUpOverheadFileRequest(replypacket->GetPacketSize());
510 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_FILERE to ") + m_client->GetFullIP() );
511 SendPacket(replypacket, true);
512 break;
516 // check to see if this is a new file they are asking for
517 if (m_client->GetUploadFileID() != fileID) {
518 m_client->SetCommentDirty();
521 m_client->SetUploadFileID(reqfile);
522 // send filestatus
523 CMemFile data(16+16);
524 data.WriteHash(reqfile->GetFileHash());
525 if (reqfile->IsPartFile()) {
526 static_cast<CPartFile*>(reqfile)->WritePartStatus(&data);
527 } else {
528 data.WriteUInt16(0);
530 CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_FILESTATUS);
531 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
532 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_FILESTATUS to ") + m_client->GetFullIP() );
533 SendPacket(packet, true);
534 break;
536 throw wxString(wxT("Invalid OP_FILEREQUEST packet size"));
537 break;
538 // DbT:End
541 case OP_FILEREQANSNOFIL: { // 0.43b protocol, lacks ZZ's download manager on swap
542 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_FILEREQANSNOFIL from ") + m_client->GetFullIP() );
544 theStats::AddDownOverheadFileRequest(size);
545 if (size == 16) {
546 // if that client does not have my file maybe has another different
547 CPartFile* reqfile = theApp->downloadqueue->GetFileByID(CMD4Hash(buffer));
548 if ( reqfile) {
549 reqfile->AddDeadSource( m_client );
550 } else {
551 break;
554 // we try to swap to another file ignoring no needed parts files
555 switch (m_client->GetDownloadState()) {
556 case DS_CONNECTED:
557 case DS_ONQUEUE:
558 case DS_NONEEDEDPARTS:
559 if (!m_client->SwapToAnotherFile(true, true, true, NULL)) {
560 theApp->downloadqueue->RemoveSource(m_client);
562 break;
564 break;
566 throw wxString(wxT("Invalid OP_FILEREQUEST packet size"));
567 break;
570 case OP_REQFILENAMEANSWER: { // 0.43b except check for bad clients
571 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REQFILENAMEANSWER from ") + m_client->GetFullIP() );
573 theStats::AddDownOverheadFileRequest(size);
574 CMemFile data(buffer, size);
575 CMD4Hash hash = data.ReadHash();
576 const CPartFile* file = theApp->downloadqueue->GetFileByID(hash);
577 m_client->ProcessFileInfo(&data, file);
578 break;
581 case OP_FILESTATUS: { // 0.43b except check for bad clients
582 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_FILESTATUS from ") + m_client->GetFullIP() );
584 theStats::AddDownOverheadFileRequest(size);
585 CMemFile data(buffer, size);
586 CMD4Hash hash = data.ReadHash();
587 const CPartFile* file = theApp->downloadqueue->GetFileByID(hash);
588 m_client->ProcessFileStatus(false, &data, file);
589 break;
592 case OP_STARTUPLOADREQ: {
593 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_STARTUPLOADREQ from ") + m_client->GetFullIP() );
595 theStats::AddDownOverheadFileRequest(size);
597 if (!m_client->CheckHandshakeFinished()) {
598 break;
601 m_client->CheckForAggressive();
602 if ( m_client->IsBanned() ) {
603 break;
606 if (size == 16) {
607 const CMD4Hash fileID(buffer);
608 CKnownFile* reqfile = theApp->sharedfiles->GetFileByID(fileID);
609 if (reqfile) {
610 if (m_client->GetUploadFileID() != fileID) {
611 m_client->SetCommentDirty();
613 m_client->SetUploadFileID(reqfile);
614 m_client->SendCommentInfo(reqfile);
616 // Socket might die because of SendCommentInfo, so check
617 if (m_client)
618 theApp->uploadqueue->AddClientToQueue(m_client);
621 break;
624 case OP_QUEUERANK: { // 0.43b
625 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_QUEUERANK from ") + m_client->GetFullIP() );
627 theStats::AddDownOverheadFileRequest(size);
628 CMemFile data(buffer, size);
629 uint32 rank = data.ReadUInt32();
631 m_client->SetRemoteQueueRank(rank);
632 break;
635 case OP_ACCEPTUPLOADREQ: { // 0.42e (xcept khaos stats)
636 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ACCEPTUPLOADREQ from ") + m_client->GetFullIP() );
638 theStats::AddDownOverheadFileRequest(size);
639 if (m_client->GetRequestFile() && !m_client->GetRequestFile()->IsStopped() && (m_client->GetRequestFile()->GetStatus()==PS_READY || m_client->GetRequestFile()->GetStatus()==PS_EMPTY)) {
640 if (m_client->GetDownloadState() == DS_ONQUEUE ) {
641 m_client->SetDownloadState(DS_DOWNLOADING);
642 m_client->SetLastPartAsked(0xffff); // Reset current downloaded Chunk // Maella -Enhanced Chunk Selection- (based on jicxicmic)
643 m_client->SendBlockRequests();
645 } else {
646 if (!m_client->GetSentCancelTransfer()) {
647 CPacket* packet = new CPacket(OP_CANCELTRANSFER, 0, OP_EDONKEYPROT);
648 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
649 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_CANCELTRANSFER to ") + m_client->GetFullIP() );
650 m_client->SendPacket(packet,true,true);
652 // SendPacket can cause the socket to die, so check
653 if (m_client)
654 m_client->SetSentCancelTransfer(1);
657 if (m_client)
658 m_client->SetDownloadState((m_client->GetRequestFile()==NULL || m_client->GetRequestFile()->IsStopped()) ? DS_NONE : DS_ONQUEUE);
660 break;
663 case OP_REQUESTPARTS: { // 0.43b
664 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REQUESTPARTS from ") + m_client->GetFullIP() );
666 theStats::AddDownOverheadFileRequest(size);
668 m_client->ProcessRequestPartsPacket(buffer, size, false);
670 break;
673 case OP_CANCELTRANSFER: { // 0.43b
674 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_CANCELTRANSFER from ") + m_client->GetFullIP() );
676 theStats::AddDownOverheadFileRequest(size);
677 theApp->uploadqueue->RemoveFromUploadQueue(m_client);
678 AddDebugLogLineN( logClient, m_client->GetUserName() + wxT(": Upload session ended due canceled transfer."));
679 break;
682 case OP_END_OF_DOWNLOAD: { // 0.43b except check for bad clients
683 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_END_OF_DOWNLOAD from ") + m_client->GetFullIP() );
685 theStats::AddDownOverheadFileRequest(size);
686 if (size>=16 && m_client->GetUploadFileID() == CMD4Hash(buffer)) {
687 theApp->uploadqueue->RemoveFromUploadQueue(m_client);
688 AddDebugLogLineN( logClient, m_client->GetUserName() + wxT(": Upload session ended due ended transfer."));
690 break;
693 case OP_HASHSETREQUEST: { // 0.43b except check for bad clients
694 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_HASHSETREQUEST from ") + m_client->GetFullIP() );
697 theStats::AddDownOverheadFileRequest(size);
698 if (size != 16) {
699 throw wxString(wxT("Invalid OP_HASHSETREQUEST packet size"));
701 m_client->SendHashsetPacket(CMD4Hash(buffer));
702 break;
705 case OP_HASHSETANSWER: { // 0.43b
706 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_HASHSETANSWER from ") + m_client->GetFullIP() );
708 theStats::AddDownOverheadFileRequest(size);
709 m_client->ProcessHashSet(buffer, size);
710 break;
713 case OP_SENDINGPART: { // 0.47a
714 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_SENDINGPART from ") + m_client->GetFullIP() );
716 if ( m_client->GetRequestFile() &&
717 !m_client->GetRequestFile()->IsStopped() &&
718 (m_client->GetRequestFile()->GetStatus() == PS_READY || m_client->GetRequestFile()->GetStatus()==PS_EMPTY)) {
720 m_client->ProcessBlockPacket(buffer, size, false, false);
722 if ( m_client &&
723 ( m_client->GetRequestFile()->IsStopped() ||
724 m_client->GetRequestFile()->GetStatus() == PS_PAUSED ||
725 m_client->GetRequestFile()->GetStatus() == PS_ERROR) ) {
726 if (!m_client->GetSentCancelTransfer()) {
727 CPacket* packet = new CPacket(OP_CANCELTRANSFER, 0, OP_EDONKEYPROT);
728 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
729 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_CANCELTRANSFER to ") + m_client->GetFullIP() );
730 m_client->SendPacket(packet,true,true);
732 // Socket might die because of SendPacket, so check
733 if (m_client)
734 m_client->SetSentCancelTransfer(1);
737 if (m_client)
738 m_client->SetDownloadState(m_client->GetRequestFile()->IsStopped() ? DS_NONE : DS_ONQUEUE);
740 } else {
741 if (!m_client->GetSentCancelTransfer()) {
742 CPacket* packet = new CPacket(OP_CANCELTRANSFER, 0, OP_EDONKEYPROT);
743 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
744 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_CANCELTRANSFER to ") + m_client->GetFullIP() );
745 m_client->SendPacket(packet,true,true);
747 // Socket might die because of SendPacket, so check
748 m_client->SetSentCancelTransfer(1);
750 m_client->SetDownloadState((m_client->GetRequestFile()==NULL || m_client->GetRequestFile()->IsStopped()) ? DS_NONE : DS_ONQUEUE);
752 break;
755 case OP_OUTOFPARTREQS: { // 0.43b
756 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_OUTOFPARTREQS from ") + m_client->GetFullIP() );
758 theStats::AddDownOverheadFileRequest(size);
759 if (m_client->GetDownloadState() == DS_DOWNLOADING) {
760 m_client->SetDownloadState(DS_ONQUEUE);
762 break;
765 case OP_CHANGE_CLIENT_ID: { // Kad reviewed
766 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_CHANGE_CLIENT_ID from ") + m_client->GetFullIP() );
768 theStats::AddDownOverheadOther(size);
769 CMemFile data(buffer, size);
770 uint32 nNewUserID = data.ReadUInt32();
771 uint32 nNewServerIP = data.ReadUInt32();
773 if (IsLowID(nNewUserID)) { // client changed server and gots a LowID
774 CServer* pNewServer = theApp->serverlist->GetServerByIP(nNewServerIP);
775 if (pNewServer != NULL){
776 m_client->SetUserIDHybrid(nNewUserID); // update UserID only if we know the server
777 m_client->SetServerIP(nNewServerIP);
778 m_client->SetServerPort(pNewServer->GetPort());
780 } else if (nNewUserID == m_client->GetIP()) { // client changed server and gots a HighID(IP)
781 m_client->SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(nNewUserID));
782 CServer* pNewServer = theApp->serverlist->GetServerByIP(nNewServerIP);
783 if (pNewServer != NULL){
784 m_client->SetServerIP(nNewServerIP);
785 m_client->SetServerPort(pNewServer->GetPort());
789 break;
792 case OP_CHANGE_SLOT:{ // 0.43b
793 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_CHANGE_SLOT from ") + m_client->GetFullIP() );
795 // sometimes sent by Hybrid
796 theStats::AddDownOverheadOther(size);
797 break;
800 case OP_MESSAGE: { // 0.43b
801 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MESSAGE from ") + m_client->GetFullIP() );
803 theStats::AddDownOverheadOther(size);
805 if (size < 2) {
806 throw wxString(wxT("invalid message packet"));
808 CMemFile message_file(buffer, size);
809 uint16 length = message_file.ReadUInt16();
810 if (length + 2u != size) {
811 throw wxString(wxT("invalid message packet"));
814 // limit message length
815 static const uint16 MAX_CLIENT_MSG_LEN = 450;
817 if (length > MAX_CLIENT_MSG_LEN) {
818 AddDebugLogLineN(logRemoteClient, CFormat(wxT("Message from '%s' (IP:%s) exceeds limit by %u chars, truncated."))
819 % m_client->GetUserName() % m_client->GetFullIP() % (length - MAX_CLIENT_MSG_LEN));
820 length = MAX_CLIENT_MSG_LEN;
823 wxString message = message_file.ReadOnlyString((m_client->GetUnicodeSupport() != utf8strNone), length);
824 m_client->ProcessChatMessage(message);
826 break;
829 case OP_ASKSHAREDFILES: { // 0.43b (well, er, it does the same, but in our own way)
830 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDFILES from ") + m_client->GetFullIP() );
832 // client wants to know what we have in share, let's see if we allow him to know that
833 theStats::AddDownOverheadOther(size);
834 // IP banned, no answer for this request
835 if (m_client->IsBanned()) {
836 break;
839 if (thePrefs::CanSeeShares() == vsfaEverybody || (thePrefs::CanSeeShares() == vsfaFriends && m_client->IsFriend())) {
840 AddLogLineC(CFormat( _("User %s (%u) requested your sharedfiles-list -> Accepted"))
841 % m_client->GetUserName()
842 % m_client->GetUserIDHybrid() );
844 std::vector<CKnownFile*> list;
845 theApp->sharedfiles->CopyFileList(list);
847 CMemFile tempfile(80);
848 tempfile.WriteUInt32(list.size());
849 for (unsigned i = 0; i < list.size(); ++i) {
850 if (!list[i]->IsLargeFile() || m_client->SupportsLargeFiles()) {
851 list[i]->CreateOfferedFilePacket(&tempfile, NULL, m_client);
855 // create a packet and send it
856 CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDFILESANSWER);
857 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILESANSWER to ") + m_client->GetFullIP() );
858 theStats::AddUpOverheadOther(replypacket->GetPacketSize());
859 SendPacket(replypacket, true, true);
860 } else {
861 AddLogLineC(CFormat( _("User %s (%u) requested your sharedfiles-list -> Denied"))
862 % m_client->GetUserName()
863 % m_client->GetUserIDHybrid() );
865 CPacket* replypacket = new CPacket(OP_ASKSHAREDDENIEDANS, 0, OP_EDONKEYPROT);
866 theStats::AddUpOverheadOther(replypacket->GetPacketSize());
867 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDENIEDANS to ") + m_client->GetFullIP() );
868 SendPacket(replypacket, true, true);
871 break;
874 case OP_ASKSHAREDFILESANSWER: { // 0.43b
875 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDFILESANSWER from ") + m_client->GetFullIP() );
877 theStats::AddDownOverheadOther(size);
878 wxString EmptyStr;
879 m_client->ProcessSharedFileList(buffer, size, EmptyStr);
880 break;
883 case OP_ASKSHAREDDIRS: { // 0.43b
884 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDDIRS from ") + m_client->GetFullIP() );
886 theStats::AddDownOverheadOther(size);
887 wxASSERT( size == 0 );
888 // IP banned, no answer for this request
889 if (m_client->IsBanned()) {
890 break;
892 if ((thePrefs::CanSeeShares()==vsfaEverybody) || ((thePrefs::CanSeeShares()==vsfaFriends) && m_client->IsFriend())) {
893 AddLogLineC(CFormat( _("User %s (%u) requested your shareddirectories-list -> Accepted") )
894 % m_client->GetUserName()
895 % m_client->GetUserIDHybrid() );
896 // send the list of shared directories
897 m_client->SendSharedDirectories();
898 } else {
899 AddLogLineC(CFormat( _("User %s (%u) requested your shareddirectories-list -> Denied") )
900 % m_client->GetUserName()
901 % m_client->GetUserIDHybrid() );
903 CPacket* replypacket = new CPacket(OP_ASKSHAREDDENIEDANS, 0, OP_EDONKEYPROT);
904 theStats::AddUpOverheadOther(replypacket->GetPacketSize());
905 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDENIEDANS to ") + m_client->GetFullIP() );
906 SendPacket(replypacket, true, true);
909 break;
912 case OP_ASKSHAREDFILESDIR: { // 0.43b
913 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDFILESDIR from ") + m_client->GetFullIP() );
915 theStats::AddDownOverheadOther(size);
916 // IP banned, no answer for this request
917 if (m_client->IsBanned()) {
918 break;
920 CMemFile data(buffer, size);
922 wxString strReqDir = data.ReadString((m_client->GetUnicodeSupport() != utf8strNone));
923 if (thePrefs::CanSeeShares()==vsfaEverybody || (thePrefs::CanSeeShares()==vsfaFriends && m_client->IsFriend())) {
924 AddLogLineC(CFormat(_("User %s (%u) requested your sharedfiles-list for directory '%s' -> accepted")) % m_client->GetUserName() % m_client->GetUserIDHybrid() % strReqDir);
925 wxASSERT( data.GetPosition() == data.GetLength() );
926 // send the list of shared files for the requested directory
927 m_client->SendSharedFilesOfDirectory(strReqDir);
928 } else {
929 AddLogLineC(CFormat(_("User %s (%u) requested your sharedfiles-list for directory '%s' -> denied")) % m_client->GetUserName() % m_client->GetUserIDHybrid() % strReqDir);
931 CPacket* replypacket = new CPacket(OP_ASKSHAREDDENIEDANS, 0, OP_EDONKEYPROT);
932 theStats::AddUpOverheadOther(replypacket->GetPacketSize());
933 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDENIEDANS to ") + m_client->GetFullIP() );
934 SendPacket(replypacket, true, true);
936 break;
939 case OP_ASKSHAREDDIRSANS:{ // 0.43b
940 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDDIRSANS from ") + m_client->GetFullIP() );
942 theStats::AddDownOverheadOther(size);
943 if (m_client->GetFileListRequested() == 1){
944 CMemFile data(buffer, size);
945 uint32 uDirs = data.ReadUInt32();
946 for (uint32 i = 0; i < uDirs; i++){
947 wxString strDir = data.ReadString((m_client->GetUnicodeSupport() != utf8strNone));
948 AddLogLineC(CFormat( _("User %s (%u) shares directory '%s'") )
949 % m_client->GetUserName()
950 % m_client->GetUserIDHybrid()
951 % strDir );
953 CMemFile tempfile(80);
954 tempfile.WriteString(strDir, m_client->GetUnicodeSupport());
955 CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDFILESDIR);
956 theStats::AddUpOverheadOther(replypacket->GetPacketSize());
957 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILESDIR to ") + m_client->GetFullIP() );
958 SendPacket(replypacket, true, true);
960 wxASSERT( data.GetPosition() == data.GetLength() );
961 m_client->SetFileListRequested(uDirs);
962 } else {
963 AddLogLineC(CFormat( _("User %s (%u) sent unrequested shared dirs.") )
964 % m_client->GetUserName()
965 % m_client->GetUserIDHybrid() );
967 break;
970 case OP_ASKSHAREDFILESDIRANS: { // 0.43b
971 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDFILESDIRANS from ") + m_client->GetFullIP() );
973 theStats::AddDownOverheadOther(size);
974 CMemFile data(buffer, size);
975 wxString strDir = data.ReadString((m_client->GetUnicodeSupport() != utf8strNone));
977 if (m_client->GetFileListRequested() > 0){
978 AddLogLineC(CFormat( _("User %s (%u) sent sharedfiles-list for directory '%s'") )
979 % m_client->GetUserName()
980 % m_client->GetUserIDHybrid()
981 % strDir );
983 m_client->ProcessSharedFileList(buffer + data.GetPosition(), size - data.GetPosition(), strDir);
984 if (m_client->GetFileListRequested() == 0) {
985 AddLogLineC(CFormat( _("User %s (%u) finished sending sharedfiles-list") )
986 % m_client->GetUserName()
987 % m_client->GetUserIDHybrid() );
989 } else {
990 AddLogLineC(CFormat( _("User %s (%u) sent unwanted sharedfiles-list") )
991 % m_client->GetUserName()
992 % m_client->GetUserIDHybrid() );
994 break;
997 case OP_ASKSHAREDDENIEDANS:
998 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ASKSHAREDDENIEDANS from ") + m_client->GetFullIP() );
1000 theStats::AddDownOverheadOther(size);
1001 wxASSERT( size == 0 );
1002 AddLogLineC(CFormat( _("User %s (%u) denied access to shared directories/files list") )
1003 % m_client->GetUserName()
1004 % m_client->GetUserIDHybrid() );
1006 m_client->SetFileListRequested(0);
1007 break;
1009 default:
1010 theStats::AddDownOverheadOther(size);
1011 AddDebugLogLineN(logRemoteClient, CFormat(wxT("Edonkey packet: unknown opcode: %i %x from %s")) % opcode % opcode % m_client->GetFullIP());
1012 return false;
1015 return true;
1019 bool CClientTCPSocket::ProcessExtPacket(const byte* buffer, uint32 size, uint8 opcode)
1021 #ifdef __PACKET_RECV_DUMP__
1022 //printf("Rec: OPCODE %x \n",opcode);
1023 DumpMem(buffer,size);
1024 #endif
1026 // 0.42e - except the catchs on mem exception and file exception
1027 if (!m_client) {
1028 throw wxString(wxT("Unknown clients sends extended protocol packet"));
1031 if (!client->CheckHandshakeFinished()) {
1032 // Here comes an extended packet without finishing the handshake.
1033 // IMHO, we should disconnect the client.
1034 throw wxString(wxT("Client send extended packet before finishing handshake"));
1037 switch(opcode) {
1038 case OP_MULTIPACKET_EXT:
1039 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKET_EXT from ") + m_client->GetFullIP());
1040 case OP_MULTIPACKET: {
1041 if (opcode == OP_MULTIPACKET) AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKET from ") + m_client->GetFullIP() );
1043 theStats::AddDownOverheadFileRequest(size);
1045 if (m_client->IsBanned()) {
1046 break;
1049 if (!m_client->CheckHandshakeFinished()) {
1050 // Here comes an extended packet without finishing the handshake.
1051 // IMHO, we should disconnect the client.
1052 throw wxString(wxT("Client send OP_MULTIPACKET before finishing handshake"));
1055 CMemFile data_in(buffer, size);
1056 CMD4Hash reqfilehash = data_in.ReadHash();
1057 uint64 nSize = (opcode == OP_MULTIPACKET_EXT) ? data_in.ReadUInt64() : 0;
1059 bool file_not_found = false;
1060 CKnownFile* reqfile = theApp->sharedfiles->GetFileByID(reqfilehash);
1061 if ( reqfile == NULL ){
1062 reqfile = theApp->downloadqueue->GetFileByID(reqfilehash);
1063 if ( !( reqfile != NULL && reqfile->GetFileSize() > PARTSIZE ) ) {
1064 AddDebugLogLineN(logRemoteClient, wxT("Remote client asked for a non-shared file"));
1065 file_not_found = true;
1069 if (!file_not_found && reqfile->IsLargeFile() && !m_client->SupportsLargeFiles()) {
1070 AddDebugLogLineN(logRemoteClient, wxT("Remote client asked for a large file but doesn't support them"));
1071 file_not_found = true;
1074 if (!file_not_found && nSize && (reqfile->GetFileSize() != nSize)) {
1075 AddDebugLogLineN(logRemoteClient, wxT("Remote client asked for a file but specified wrong size"));
1076 file_not_found = true;
1079 if (file_not_found) {
1080 CPacket* replypacket = new CPacket(OP_FILEREQANSNOFIL, 16, OP_EDONKEYPROT);
1081 replypacket->Copy16ToDataBuffer(reqfilehash.GetHash());
1082 theStats::AddUpOverheadFileRequest(replypacket->GetPacketSize());
1083 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_FILEREQANSNOFIL to ") + m_client->GetFullIP() );
1084 SendPacket(replypacket, true);
1085 break;
1088 if (!m_client->GetWaitStartTime()) {
1089 m_client->SetWaitStartTime();
1091 // if we are downloading this file, this could be a new source
1092 // no passive adding of files with only one part
1093 if (reqfile->IsPartFile() && reqfile->GetFileSize() > PARTSIZE) {
1094 if (thePrefs::GetMaxSourcePerFile() > static_cast<CPartFile*>(reqfile)->GetSourceCount()) {
1095 theApp->downloadqueue->CheckAndAddKnownSource(static_cast<CPartFile*>(reqfile), m_client);
1098 // check to see if this is a new file they are asking for
1099 if (m_client->GetUploadFileID() != reqfilehash) {
1100 m_client->SetCommentDirty();
1102 m_client->SetUploadFileID(reqfile);
1103 CMemFile data_out(128);
1104 data_out.WriteHash(reqfile->GetFileHash());
1105 while(data_in.GetLength()-data_in.GetPosition()) {
1106 if (!m_client) {
1107 throw wxString(wxT("Client suddenly disconnected"));
1109 uint8 opcode_in = data_in.ReadUInt8();
1110 switch(opcode_in) {
1111 case OP_REQUESTFILENAME: {
1112 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKET has OP_REQUESTFILENAME") );
1113 m_client->ProcessExtendedInfo(&data_in, reqfile);
1114 data_out.WriteUInt8(OP_REQFILENAMEANSWER);
1116 // Since it's for somebody else to see, we need to send the prettified
1117 // filename, rather than the (possibly) mangled actual filename
1118 data_out.WriteString(reqfile->GetFileName().GetPrintable(), m_client->GetUnicodeSupport());
1119 break;
1121 case OP_AICHFILEHASHREQ: {
1122 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKET has OP_AICHFILEHASHANS") );
1123 if (m_client->IsSupportingAICH() && reqfile->GetAICHHashset()->GetStatus() == AICH_HASHSETCOMPLETE
1124 && reqfile->GetAICHHashset()->HasValidMasterHash())
1126 data_out.WriteUInt8(OP_AICHFILEHASHANS);
1127 reqfile->GetAICHHashset()->GetMasterHash().Write(&data_out);
1129 break;
1131 case OP_SETREQFILEID: {
1132 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKET has OP_SETREQFILEID") );
1133 data_out.WriteUInt8(OP_FILESTATUS);
1134 if (reqfile->IsPartFile()) {
1135 static_cast<CPartFile*>(reqfile)->WritePartStatus(&data_out);
1136 } else {
1137 data_out.WriteUInt16(0);
1139 break;
1141 //We still send the source packet separately..
1142 //We could send it within this packet.. If agreeded, I will fix it..
1143 case OP_REQUESTSOURCES2:
1144 case OP_REQUESTSOURCES: {
1145 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKET has OP_REQUESTSOURCES(2)") );
1146 uint8 byRequestedVersion = 0;
1147 uint16 byRequestedOptions = 0;
1148 if (opcode_in == OP_REQUESTSOURCES2){ // SX2 requests contains additional data
1149 byRequestedVersion = data_in.ReadUInt8();
1150 byRequestedOptions = data_in.ReadUInt16();
1153 //Although this shouldn't happen, it's a just in case to any Mods that mess with version numbers.
1155 if (byRequestedVersion > 0 || m_client->GetSourceExchange1Version() > 1) {
1156 uint32 dwTimePassed = ::GetTickCount() - m_client->GetLastSrcReqTime() + CONNECTION_LATENCY;
1157 bool bNeverAskedBefore = m_client->GetLastSrcReqTime() == 0;
1159 //if not complete and file is rare
1160 ( reqfile->IsPartFile()
1161 && (bNeverAskedBefore || dwTimePassed > SOURCECLIENTREASKS)
1162 && static_cast<CPartFile*>(reqfile)->GetSourceCount() <= RARE_FILE
1163 ) ||
1164 //OR if file is not rare or if file is complete
1165 ( (bNeverAskedBefore || dwTimePassed > SOURCECLIENTREASKS * MINCOMMONPENALTY) )
1168 m_client->SetLastSrcReqTime();
1169 CPacket* tosend = reqfile->CreateSrcInfoPacket(m_client, byRequestedVersion, byRequestedOptions);
1170 if(tosend) {
1171 theStats::AddUpOverheadSourceExchange(tosend->GetPacketSize());
1172 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ANSWERSOURCES to ") + m_client->GetFullIP() );
1173 SendPacket(tosend, true);
1177 break;
1182 if( data_out.GetLength() > 16 ) {
1183 CPacket* reply = new CPacket(data_out, OP_EMULEPROT, OP_MULTIPACKETANSWER);
1184 theStats::AddUpOverheadFileRequest(reply->GetPacketSize());
1185 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_MULTIPACKETANSWER to ") + m_client->GetFullIP() );
1186 SendPacket(reply, true);
1188 break;
1191 case OP_MULTIPACKETANSWER: { // 0.43b
1192 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_MULTIPACKETANSWER from ") + m_client->GetFullIP() );
1194 theStats::AddDownOverheadFileRequest(size);
1196 if (m_client->IsBanned()) {
1197 break;
1200 if (m_client->GetKadPort() && m_client->GetKadVersion() > 1) {
1201 Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(m_client->GetIP()), m_client->GetKadPort());
1204 if (!m_client->CheckHandshakeFinished()) {
1205 // Here comes an extended packet without finishing the handshake.
1206 // IMHO, we should disconnect the client.
1207 throw wxString(wxT("Client send OP_MULTIPACKETANSWER before finishing handshake"));
1210 CMemFile data_in(buffer, size);
1211 CMD4Hash reqfilehash = data_in.ReadHash();
1212 const CPartFile *reqfile = theApp->downloadqueue->GetFileByID(reqfilehash);
1213 //Make sure we are downloading this file.
1214 if ( !reqfile ) {
1215 throw wxString(wxT(" Wrong File ID: (OP_MULTIPACKETANSWER; reqfile==NULL)"));
1217 if ( !m_client->GetRequestFile() ) {
1219 throw wxString(wxT(" Wrong File ID: OP_MULTIPACKETANSWER; client->reqfile==NULL)"));
1221 if (reqfile != m_client->GetRequestFile()) {
1222 throw wxString(wxT(" Wrong File ID: OP_MULTIPACKETANSWER; reqfile!=client->reqfile)"));
1224 while (data_in.GetLength()-data_in.GetPosition()) {
1225 // Some of the cases down there can actually send a packet and lose the client
1226 if (!m_client) {
1227 throw wxString(wxT("Client suddenly disconnected"));
1229 uint8 opcode_in = data_in.ReadUInt8();
1230 switch(opcode_in) {
1231 case OP_REQFILENAMEANSWER: {
1232 if (!m_client) {
1233 throw wxString(wxT("Client suddenly disconnected"));
1234 } else {
1235 m_client->ProcessFileInfo(&data_in, reqfile);
1237 break;
1239 case OP_FILESTATUS: {
1240 if (!m_client) {
1241 throw wxString(wxT("Client suddenly disconnected"));
1242 } else {
1243 m_client->ProcessFileStatus(false, &data_in, reqfile);
1245 break;
1247 case OP_AICHFILEHASHANS: {
1248 if (!m_client) {
1249 throw wxString(wxT("Client suddenly disconnected"));
1250 } else {
1251 m_client->ProcessAICHFileHash(&data_in, reqfile);
1253 break;
1258 break;
1261 case OP_EMULEINFO: { // 0.43b
1262 theStats::AddDownOverheadOther(size);
1264 if (!m_client->ProcessMuleInfoPacket(buffer, size)) {
1265 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_EMULEINFO from ") + m_client->GetFullIP() );
1267 // If it's not a OS Info packet, is an old client
1268 // start secure identification, if
1269 // - we have received eD2K and eMule info (old eMule)
1270 if (m_client->GetInfoPacketsReceived() == IP_BOTH) {
1271 m_client->InfoPacketsReceived();
1273 m_client->SendMuleInfoPacket(true);
1274 } else {
1275 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_EMULEINFO is an OS_INFO") );
1277 break;
1279 case OP_EMULEINFOANSWER: { // 0.43b
1280 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_EMULEINFOANSWER from ") + m_client->GetFullIP() );
1281 theStats::AddDownOverheadOther(size);
1283 m_client->ProcessMuleInfoPacket(buffer, size);
1284 // start secure identification, if
1285 // - we have received eD2K and eMule info (old eMule)
1287 if (m_client->GetInfoPacketsReceived() == IP_BOTH) {
1288 m_client->InfoPacketsReceived();
1291 break;
1294 case OP_SECIDENTSTATE:{ // 0.43b
1295 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_SECIDENTSTATE from ") + m_client->GetFullIP() );
1297 if (!m_client->CheckHandshakeFinished()) {
1298 // Here comes an extended packet without finishing the handshake.
1299 // IMHO, we should disconnect the client.
1300 throw wxString(wxT("Client send OP_SECIDENTSTATE before finishing handshake"));
1302 m_client->ProcessSecIdentStatePacket(buffer, size);
1303 // ProcessSecIdentStatePacket() might cause the socket to die, so check
1304 if (m_client) {
1305 int SecureIdentState = m_client->GetSecureIdentState();
1306 if (SecureIdentState == IS_SIGNATURENEEDED) {
1307 m_client->SendSignaturePacket();
1308 } else if (SecureIdentState == IS_KEYANDSIGNEEDED) {
1309 m_client->SendPublicKeyPacket();
1310 // SendPublicKeyPacket() might cause the socket to die, so check
1311 if ( m_client ) {
1312 m_client->SendSignaturePacket();
1316 break;
1319 case OP_PUBLICKEY: { // 0.43b
1320 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_PUBLICKEY from ") + m_client->GetFullIP() );
1322 if (m_client->IsBanned() ){
1323 break;
1326 if (!m_client->CheckHandshakeFinished()) {
1327 // Here comes an extended packet without finishing the handshake.
1328 // IMHO, we should disconnect the client.
1329 throw wxString(wxT("Client send OP_PUBLICKEY before finishing handshake"));
1332 m_client->ProcessPublicKeyPacket(buffer, size);
1333 break;
1335 case OP_SIGNATURE:{ // 0.43b
1336 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_SIGNATURE from ") + m_client->GetFullIP() );
1338 if (!m_client->CheckHandshakeFinished()) {
1339 // Here comes an extended packet without finishing the handshake.
1340 // IMHO, we should disconnect the client.
1341 throw wxString(wxT("Client send OP_COMPRESSEDPART before finishing handshake"));
1344 m_client->ProcessSignaturePacket(buffer, size);
1345 break;
1347 case OP_SENDINGPART_I64:
1348 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_SENDINGPART_I64 from ") + m_client->GetFullIP() );
1349 case OP_COMPRESSEDPART_I64:
1350 if (opcode == OP_COMPRESSEDPART_I64) AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_COMPRESSEDPART_I64 from ") + m_client->GetFullIP() );
1351 case OP_COMPRESSEDPART: { // 0.47a
1352 if (opcode == OP_COMPRESSEDPART) AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_COMPRESSEDPART from ") + m_client->GetFullIP() );
1354 if (!m_client->CheckHandshakeFinished()) {
1355 // Here comes an extended packet without finishing the handshake.
1356 // IMHO, we should disconnect the client.
1357 throw wxString(wxT("Client send OP_COMPRESSEDPART before finishing handshake"));
1360 if (m_client->GetRequestFile() && !m_client->GetRequestFile()->IsStopped() && (m_client->GetRequestFile()->GetStatus()==PS_READY || m_client->GetRequestFile()->GetStatus()==PS_EMPTY)) {
1362 m_client->ProcessBlockPacket(buffer, size, (opcode != OP_SENDINGPART_I64), (opcode == OP_COMPRESSEDPART_I64) || (opcode == OP_SENDINGPART_I64));
1364 if (m_client && (
1365 m_client->GetRequestFile()->IsStopped() ||
1366 m_client->GetRequestFile()->GetStatus() == PS_PAUSED ||
1367 m_client->GetRequestFile()->GetStatus() == PS_ERROR)) {
1368 if (!m_client->GetSentCancelTransfer()) {
1369 CPacket* packet = new CPacket(OP_CANCELTRANSFER, 0, OP_EDONKEYPROT);
1370 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
1371 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_CANCELTRANSFER to ") + m_client->GetFullIP() );
1372 m_client->SendPacket(packet,true,true);
1374 if (m_client) {
1375 m_client->SetSentCancelTransfer(1);
1379 if ( m_client ) {
1380 m_client->SetDownloadState(m_client->GetRequestFile()->IsStopped() ? DS_NONE : DS_ONQUEUE);
1383 } else {
1384 if (!m_client->GetSentCancelTransfer()) {
1385 CPacket* packet = new CPacket(OP_CANCELTRANSFER, 0, OP_EDONKEYPROT);
1386 theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
1387 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_CANCELTRANSFER to ") + m_client->GetFullIP() );
1388 m_client->SendPacket(packet,true,true);
1390 if ( m_client ) {
1391 m_client->SetSentCancelTransfer(1);
1395 if ( m_client ) {
1396 m_client->SetDownloadState((m_client->GetRequestFile()==NULL || m_client->GetRequestFile()->IsStopped()) ? DS_NONE : DS_ONQUEUE);
1399 break;
1401 case OP_REQUESTPARTS_I64: {
1402 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REQUESTPARTS_I64 from ") + m_client->GetFullIP() );
1404 theStats::AddDownOverheadFileRequest(size);
1406 m_client->ProcessRequestPartsPacket(buffer, size, true);
1408 break;
1410 case OP_QUEUERANKING: { // 0.43b
1411 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_QUEUERANKING from ") + m_client->GetFullIP() );
1413 theStats::AddDownOverheadOther(size);
1415 if (!m_client->CheckHandshakeFinished()) {
1416 // Here comes an extended packet without finishing the handshake.
1417 // IMHO, we should disconnect the client.
1418 throw wxString(wxT("Client send OP_QUEUERANKING before finishing handshake"));
1421 if (size != 12) {
1422 throw wxString(wxT("Invalid size (OP_QUEUERANKING)"));
1425 uint16 newrank = PeekUInt16(buffer);
1426 m_client->SetRemoteQueueFull(false);
1427 m_client->SetRemoteQueueRank(newrank);
1428 break;
1430 case OP_REQUESTSOURCES2:
1431 case OP_REQUESTSOURCES:{
1432 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REQUESTSOURCES from ") + m_client->GetFullIP() );
1434 theStats::AddDownOverheadSourceExchange(size);
1436 if (!m_client->CheckHandshakeFinished()) {
1437 // Here comes an extended packet without finishing the handshake.
1438 // IMHO, we should disconnect the client.
1439 throw wxString(wxT("Client send OP_REQUESTSOURCES before finishing handshake"));
1442 uint8 byRequestedVersion = 0;
1443 uint16 byRequestedOptions = 0;
1444 CMemFile data_in(buffer, size);
1445 if (opcode == OP_REQUESTSOURCES2){ // SX2 requests contains additional data
1446 byRequestedVersion = data_in.ReadUInt8();
1447 byRequestedOptions = data_in.ReadUInt16();
1450 if (byRequestedVersion > 0 || m_client->GetSourceExchange1Version() >= 1) {
1451 if(size != 16) {
1452 throw wxString(wxT("Invalid size (OP_QUEUERANKING)"));
1454 //first check shared file list, then download list
1455 const CMD4Hash fileID(buffer);
1456 CKnownFile* file = theApp->sharedfiles->GetFileByID(fileID);
1457 if(!file) {
1458 file = theApp->downloadqueue->GetFileByID(fileID);
1460 if(file) {
1461 // There are some clients which do not follow the correct protocol procedure of sending
1462 // the sequence OP_REQUESTFILENAME, OP_SETREQFILEID, OP_REQUESTSOURCES. If those clients
1463 // are doing this, they will not get the optimal set of sources which we could offer if
1464 // they would follow the above noted protocol sequence. They better do it the right way
1465 // or they will get just a random set of sources because we do not know their download
1466 // part status which may get cleared with the call of 'SetUploadFileID'.
1467 m_client->SetUploadFileID(file);
1469 uint32 dwTimePassed = ::GetTickCount() - m_client->GetLastSrcReqTime() + CONNECTION_LATENCY;
1470 bool bNeverAskedBefore = m_client->GetLastSrcReqTime() == 0;
1472 //if not complete and file is rare, allow once every 40 minutes
1473 ( file->IsPartFile() &&
1474 static_cast<CPartFile*>(file)->GetSourceCount() <= RARE_FILE &&
1475 (bNeverAskedBefore || dwTimePassed > SOURCECLIENTREASKS)
1476 ) ||
1477 //OR if file is not rare or if file is complete, allow every 90 minutes
1478 ( (bNeverAskedBefore || dwTimePassed > SOURCECLIENTREASKS * MINCOMMONPENALTY) )
1481 m_client->SetLastSrcReqTime();
1482 CPacket* tosend = file->CreateSrcInfoPacket(m_client, byRequestedVersion, byRequestedOptions);
1483 if(tosend) {
1484 theStats::AddUpOverheadSourceExchange(tosend->GetPacketSize());
1485 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ANSWERSOURCES to ") + m_client->GetFullIP() );
1486 SendPacket(tosend, true, true);
1491 break;
1493 case OP_ANSWERSOURCES: {
1494 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_ANSWERSOURCES from ") + m_client->GetFullIP() );
1496 theStats::AddDownOverheadSourceExchange(size);
1498 if (!m_client->CheckHandshakeFinished()) {
1499 // Here comes an extended packet without finishing the handshake.
1500 // IMHO, we should disconnect the client.
1501 throw wxString(wxT("Client send OP_ANSWERSOURCES before finishing handshake"));
1504 CMemFile data(buffer, size);
1505 CMD4Hash hash = data.ReadHash();
1506 CKnownFile* file = theApp->downloadqueue->GetFileByID(hash);
1507 if(file){
1508 if (file->IsPartFile()){
1509 //set the client's answer time
1510 m_client->SetLastSrcAnswerTime();
1511 //and set the file's last answer time
1512 static_cast<CPartFile*>(file)->SetLastAnsweredTime();
1513 static_cast<CPartFile*>(file)->AddClientSources(&data, SF_SOURCE_EXCHANGE, m_client->GetSourceExchange1Version(), false, m_client);
1516 break;
1518 case OP_ANSWERSOURCES2: {
1519 //printf("Received OP_ANSWERSOURCES2\n");
1520 theStats::AddDownOverheadSourceExchange(size);
1522 if (!m_client->CheckHandshakeFinished()) {
1523 // Here comes an extended packet without finishing the handshake.
1524 // IMHO, we should disconnect the client.
1525 throw wxString(wxT("Client send OP_ANSWERSOURCES2 before finishing handshake"));
1528 CMemFile data(buffer, size);
1529 uint8 byVersion = data.ReadUInt8();
1530 CMD4Hash hash = data.ReadHash();
1531 CKnownFile* file = theApp->downloadqueue->GetFileByID(hash);
1532 if (file){
1533 if (file->IsPartFile()){
1534 //set the client's answer time
1535 m_client->SetLastSrcAnswerTime();
1536 //and set the file's last answer time
1537 static_cast<CPartFile*>(file)->SetLastAnsweredTime();
1538 static_cast<CPartFile*>(file)->AddClientSources(&data, SF_SOURCE_EXCHANGE, byVersion, true, m_client);
1541 break;
1543 case OP_FILEDESC: { // 0.43b
1544 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_FILEDESC from ") + m_client->GetFullIP() );
1546 theStats::AddDownOverheadFileRequest(size);
1548 if (!m_client->CheckHandshakeFinished()) {
1549 // Here comes an extended packet without finishing the handshake.
1550 // IMHO, we should disconnect the client.
1551 throw wxString(wxT("Client send OP_FILEDESC before finishing handshake"));
1554 m_client->ProcessMuleCommentPacket(buffer, size);
1555 break;
1558 // Unsupported
1559 case OP_REQUESTPREVIEW: {
1560 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REQUESTPREVIEW from ") + m_client->GetFullIP() );
1561 break;
1563 // Unsupported
1564 case OP_PREVIEWANSWER: {
1565 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_PREVIEWANSWER from ") + m_client->GetFullIP() );
1566 break;
1569 case OP_PUBLICIP_ANSWER: {
1570 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_PUBLICIP_ANSWER from ") + m_client->GetFullIP() );
1571 theStats::AddDownOverheadOther(size);
1572 m_client->ProcessPublicIPAnswer(buffer, size);
1573 break;
1575 case OP_PUBLICIP_REQ: {
1576 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_PUBLICIP_REQ from ") + m_client->GetFullIP() );
1577 theStats::AddDownOverheadOther(size);
1578 CPacket* pPacket = new CPacket(OP_PUBLICIP_ANSWER, 4, OP_EMULEPROT);
1579 pPacket->CopyUInt32ToDataBuffer(m_client->GetIP());
1580 theStats::AddUpOverheadOther(pPacket->GetPacketSize());
1581 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICIP_ANSWER to") + m_client->GetFullIP());
1582 SendPacket(pPacket);
1583 break;
1585 case OP_AICHANSWER: {
1586 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_AICHANSWER from ") + m_client->GetFullIP() );
1587 theStats::AddDownOverheadOther(size);
1588 m_client->ProcessAICHAnswer(buffer, size);
1589 break;
1591 case OP_AICHREQUEST: {
1592 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_AICHREQUEST from ") + m_client->GetFullIP() );
1593 theStats::AddDownOverheadOther(size);
1594 m_client->ProcessAICHRequest(buffer, size);
1595 break;
1597 case OP_AICHFILEHASHANS: {
1598 // those should not be received normally, since we should only get those in MULTIPACKET
1599 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_AICHFILEHASHANS from ") + m_client->GetFullIP() );
1600 theStats::AddDownOverheadOther(size);
1601 CMemFile data(buffer, size);
1602 m_client->ProcessAICHFileHash(&data, NULL);
1603 break;
1605 case OP_AICHFILEHASHREQ: {
1606 // those should not be received normally, since we should only get those in MULTIPACKET
1607 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_AICHFILEHASHREQ from ") + m_client->GetFullIP() );
1608 CMemFile data(buffer, size);
1609 CMD4Hash hash = data.ReadHash();
1610 CKnownFile* pPartFile = theApp->sharedfiles->GetFileByID(hash);
1611 if (pPartFile == NULL){
1612 break;
1615 if (m_client->IsSupportingAICH() && pPartFile->GetAICHHashset()->GetStatus() == AICH_HASHSETCOMPLETE
1616 && pPartFile->GetAICHHashset()->HasValidMasterHash()) {
1617 CMemFile data_out;
1618 data_out.WriteHash(hash);
1619 pPartFile->GetAICHHashset()->GetMasterHash().Write(&data_out);
1620 CPacket* packet = new CPacket(data_out, OP_EMULEPROT, OP_AICHFILEHASHANS);
1621 theStats::AddUpOverheadOther(packet->GetPacketSize());
1622 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_AICHFILEHASHANS to") + m_client->GetFullIP());
1623 SendPacket(packet);
1625 break;
1627 case OP_CALLBACK: {
1628 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_CALLBACK from ") + m_client->GetFullIP() );
1629 theStats::AddDownOverheadFileRequest(size);
1630 if(!Kademlia::CKademlia::IsRunning()) {
1631 break;
1633 CMemFile data(buffer, size);
1634 CUInt128 check = data.ReadUInt128();
1635 check ^= Kademlia::CUInt128(true);
1636 if (check != Kademlia::CKademlia::GetPrefs()->GetKadID()) {
1637 break;
1639 CUInt128 fileid = data.ReadUInt128();
1640 byte fileid2[16];
1641 fileid.ToByteArray(fileid2);
1642 const CMD4Hash fileHash(fileid2);
1643 if (theApp->sharedfiles->GetFileByID(fileHash) == NULL) {
1644 if (theApp->downloadqueue->GetFileByID(fileHash) == NULL) {
1645 break;
1649 uint32 ip = data.ReadUInt32();
1650 uint16 tcp = data.ReadUInt16();
1651 CUpDownClient* callback;
1652 callback = theApp->clientlist->FindClientByIP(wxUINT32_SWAP_ALWAYS(ip), tcp);
1653 if( callback == NULL ) {
1654 //#warning Do we actually have to check friend status here?
1655 callback = new CUpDownClient(tcp,ip,0,0,NULL,false, false);
1656 theApp->clientlist->AddClient(callback);
1658 callback->TryToConnect(true);
1659 break;
1662 case OP_BUDDYPING: {
1663 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_BUDDYPING from ") + m_client->GetFullIP() );
1664 theStats::AddDownOverheadKad(size);
1666 CUpDownClient* buddy = theApp->clientlist->GetBuddy();
1667 if( buddy != m_client || m_client->GetKadVersion() == 0 || !m_client->AllowIncomeingBuddyPingPong() ) {
1668 //This ping was not from our buddy or wrong version or packet sent to fast. Ignore
1669 break;
1672 m_client->SetLastBuddyPingPongTime();
1673 CPacket* replypacket = new CPacket(OP_BUDDYPONG, 0, OP_EMULEPROT);
1674 theStats::AddUpOverheadKad(replypacket->GetPacketSize());
1675 AddDebugLogLineN(logLocalClient,wxT("Local Client: OP_BUDDYPONG to ") + m_client->GetFullIP());
1676 SendPacket(replypacket);
1677 break;
1679 case OP_BUDDYPONG: {
1680 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_BUDDYPONG from ") + m_client->GetFullIP() );
1681 theStats::AddDownOverheadKad(size);
1683 CUpDownClient* buddy = theApp->clientlist->GetBuddy();
1684 if( buddy != m_client || m_client->GetKadVersion() == 0 ) {
1685 //This pong was not from our buddy or wrong version. Ignore
1686 break;
1688 m_client->SetLastBuddyPingPongTime();
1689 //All this is for is to reset our socket timeout.
1690 break;
1692 case OP_REASKCALLBACKTCP: {
1693 theStats::AddDownOverheadFileRequest(size);
1694 CUpDownClient* buddy = theApp->clientlist->GetBuddy();
1695 if (buddy != m_client) {
1696 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REASKCALLBACKTCP from ") + m_client->GetFullIP() + wxT(" which is not our buddy!") );
1697 //This callback was not from our buddy.. Ignore.
1698 break;
1700 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: OP_REASKCALLBACKTCP from ") + m_client->GetFullIP() );
1701 CMemFile data_in(buffer, size);
1702 uint32 destip = data_in.ReadUInt32();
1703 uint16 destport = data_in.ReadUInt16();
1704 CMD4Hash hash = data_in.ReadHash();
1705 CKnownFile* reqfile = theApp->sharedfiles->GetFileByID(hash);
1707 bool bSenderMultipleIpUnknown = false;
1708 CUpDownClient* sender = theApp->uploadqueue->GetWaitingClientByIP_UDP(destip, destport, true, &bSenderMultipleIpUnknown);
1709 if (!reqfile) {
1710 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_FILENOTFOUND to ") + m_client->GetFullIP() );
1711 CPacket* response = new CPacket(OP_FILENOTFOUND,0,OP_EMULEPROT);
1712 theStats::AddUpOverheadFileRequest(response->GetPacketSize());
1713 if (sender) {
1714 theApp->clientudp->SendPacket(response, destip, destport, sender->ShouldReceiveCryptUDPPackets(), sender->GetUserHash().GetHash(), false, 0);
1715 } else {
1716 theApp->clientudp->SendPacket(response, destip, destport, false, NULL, false, 0);
1718 break;
1721 if (sender) {
1722 //Make sure we are still thinking about the same file
1723 if (hash == sender->GetUploadFileID()) {
1724 sender->AddAskedCount();
1725 sender->SetLastUpRequest();
1726 //I messed up when I first added extended info to UDP
1727 //I should have originally used the entire ProcessExtenedInfo the first time.
1728 //So now I am forced to check UDPVersion to see if we are sending all the extended info.
1729 //For now on, we should not have to change anything here if we change
1730 //anything to the extended info data as this will be taken care of in ProcessExtendedInfo()
1731 //Update extended info.
1732 if (sender->GetUDPVersion() > 3) {
1733 sender->ProcessExtendedInfo(&data_in, reqfile);
1734 } else if (sender->GetUDPVersion() > 2) {
1735 //Update our complete source counts.
1736 uint16 nCompleteCountLast= sender->GetUpCompleteSourcesCount();
1737 uint16 nCompleteCountNew = data_in.ReadUInt16();
1738 sender->SetUpCompleteSourcesCount(nCompleteCountNew);
1739 if (nCompleteCountLast != nCompleteCountNew) {
1740 reqfile->UpdatePartsInfo();
1744 CMemFile data_out(128);
1745 if(sender->GetUDPVersion() > 3) {
1746 if (reqfile->IsPartFile()) {
1747 static_cast<CPartFile*>(reqfile)->WritePartStatus(&data_out);
1748 } else {
1749 data_out.WriteUInt16(0);
1753 data_out.WriteUInt16(sender->GetUploadQueueWaitingPosition());
1754 CPacket* response = new CPacket(data_out, OP_EMULEPROT, OP_REASKACK);
1755 theStats::AddUpOverheadFileRequest(response->GetPacketSize());
1756 AddDebugLogLineN( logLocalClient, wxT("Local Client UDP: OP_REASKACK to ") + m_client->GetFullIP() );
1757 theApp->clientudp->SendPacket(response, destip, destport, sender->ShouldReceiveCryptUDPPackets(), sender->GetUserHash().GetHash(), false, 0);
1758 } else {
1759 AddDebugLogLineN(logListenSocket, wxT("Client UDP socket; OP_REASKCALLBACKTCP; reqfile does not match"));
1761 } else {
1762 if (!bSenderMultipleIpUnknown){
1763 if ((theStats::GetWaitingUserCount() + 50) > thePrefs::GetQueueSize()) {
1764 AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_QUEUEFULL to ") + m_client->GetFullIP() );
1765 CPacket* response = new CPacket(OP_QUEUEFULL,0,OP_EMULEPROT);
1766 theStats::AddUpOverheadFileRequest(response->GetPacketSize());
1767 theApp->clientudp->SendPacket(response, destip, destport, false, NULL, false, 0);
1769 } else {
1770 AddDebugLogLineN(logRemoteClient, CFormat(wxT("OP_REASKCALLBACKTCP Packet received - multiple clients with the same IP but different UDP port found. Possible UDP Portmapping problem, enforcing TCP connection. IP: %s, Port: %u")) % Uint32toStringIP(destip) % destport);
1773 break;
1775 case OP_CHATCAPTCHAREQ:
1777 AddDebugLogLineN(logRemoteClient, wxT("Remote Client: OP_CHATCAPTCHAREQ from ") + m_client->GetFullIP());
1778 theStats::AddDownOverheadOther(size);
1779 CMemFile data_in(buffer, size);
1780 m_client->ProcessCaptchaRequest(&data_in);
1781 break;
1783 case OP_CHATCAPTCHARES:
1785 AddDebugLogLineN(logRemoteClient, wxT("Remote Client: OP_CHATCAPTCHARES from ") + m_client->GetFullIP());
1786 theStats::AddDownOverheadOther(size);
1787 if (size) {
1788 m_client->ProcessCaptchaReqRes(buffer[0]);
1790 break;
1792 case OP_FWCHECKUDPREQ: { // Support required for Kadversion >= 6
1793 AddDebugLogLineN(logRemoteClient, wxT("Remote Client: OP_FWCHECKUDPREQ from ") + m_client->GetFullIP());
1794 theStats::AddDownOverheadOther(size);
1795 CMemFile data_in(buffer, size);
1796 m_client->ProcessFirewallCheckUDPRequest(&data_in);
1797 break;
1799 case OP_KAD_FWTCPCHECK_ACK: { // Support required for Kadversion >= 7
1800 AddDebugLogLineN(logRemoteClient, wxT("Remote Client: OP_KAD_FWTCPCHECK_ACK from ") + m_client->GetFullIP());
1801 if (theApp->clientlist->IsKadFirewallCheckIP(m_client->GetIP())) {
1802 if (Kademlia::CKademlia::IsRunning()) {
1803 Kademlia::CKademlia::GetPrefs()->IncFirewalled();
1805 } else {
1806 AddDebugLogLineN(logListenSocket, wxT("Received unrequested OP_KAD_FWTCPCHECK_ACK packet from ") + m_client->GetFullIP());
1808 break;
1810 default:
1811 theStats::AddDownOverheadOther(size);
1812 AddDebugLogLineN(logRemoteClient, CFormat(wxT("eMule packet : unknown opcode: %i %x from %s")) % opcode % opcode % m_client->GetFullIP());
1813 break;
1816 return true;
1819 bool CClientTCPSocket::ProcessED2Kv2Packet(const byte* buffer, uint32 size, uint8 opcode)
1821 #ifdef __PACKET_RECV_DUMP__
1822 //printf("Rec: OPCODE %x ED2Kv2\n",opcode);
1823 DumpMem(buffer,size);
1824 #endif
1826 if (!m_client) {
1827 throw wxString(wxT("Unknown clients sends extended ED2Kv2 protocol packet"));
1830 CMemFile data(buffer, size);
1831 try {
1832 switch(opcode) {
1833 case OP_QUEUERANK: {
1834 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: ED2Kv2 OP_QUEUERANK from ") + m_client->GetFullIP() );
1836 uint8 numtags = data.ReadUInt8();
1837 wxASSERT(numtags == 1);
1838 if(numtags){} // prevent GCC warning
1840 m_client->SetRemoteQueueRank(data.GetIntTagValue());
1842 theStats::AddDownOverheadFileRequest(size);
1843 break;
1846 case OP_REQUESTPARTS: {
1847 AddDebugLogLineN( logRemoteClient, wxT("Remote Client: ED2Kv2 OP_REQUESTPARTS from ") + m_client->GetFullIP() );
1849 m_client->ProcessRequestPartsPacketv2(data);
1851 theStats::AddDownOverheadFileRequest(size);
1852 break;
1855 default:
1856 theStats::AddDownOverheadOther(size);
1857 AddDebugLogLineN(logRemoteClient, CFormat(wxT("ED2Kv2 packet : unknown opcode: %i %x from %s")) % opcode % opcode % m_client->GetFullIP());
1859 } catch (...) {
1860 AddDebugLogLineN(logRemoteClient, CFormat(wxT("ED2Kv2 packet is corrupt at pos %i! opcode: %i %x from %s")) % data.GetPosition() % opcode % opcode % m_client->GetFullIP());
1861 throw;
1864 return true;
1867 void CClientTCPSocket::OnConnect(int nErrorCode)
1869 if (nErrorCode) {
1870 OnError(nErrorCode);
1871 } else if (!m_client) {
1872 // and now? Disconnect? not?
1873 AddDebugLogLineN( logClient, wxT("Couldn't send hello packet (Client deleted!)") );
1874 } else if (!m_client->SendHelloPacket()) {
1875 // and now? Disconnect? not?
1876 AddDebugLogLineN( logClient, wxT("Couldn't send hello packet (Client deleted by SendHelloPacket!)") );
1877 } else {
1878 ResetTimeOutTimer();
1883 void CClientTCPSocket::OnSend(int nErrorCode)
1885 ResetTimeOutTimer();
1886 CEMSocket::OnSend(nErrorCode);
1890 void CClientTCPSocket::OnReceive(int nErrorCode)
1892 ResetTimeOutTimer();
1893 // We might have updated ipfilter
1894 wxASSERT(m_remoteip);
1896 if (theApp->ipfilter->IsFiltered(m_remoteip)) {
1897 if (m_client) {
1898 m_client->Safe_Delete();
1900 Safe_Delete();
1901 AddDebugLogLineN( logIPFilter, wxT("A connected client was dropped by IPFilter on new packet received"));
1902 } else {
1903 CEMSocket::OnReceive(nErrorCode);
1908 void CClientTCPSocket::OnError(int nErrorCode)
1910 //printf("* Called OnError for %p\n",this);
1911 // 0.42e + Kry changes for handling of socket lost events
1912 wxString strError;
1914 if ((nErrorCode == 0) || (nErrorCode == 7) || (nErrorCode == 0xFEFF)) {
1915 if (m_client) {
1916 if (!m_client->GetUserName().IsEmpty()) {
1917 strError = wxT("Client '") + m_client->GetUserName() + wxT("'");
1918 } else {
1919 strError = wxT("An unnamed client");
1921 strError += wxT(" (IP:") + m_client->GetFullIP() + wxT(") ");
1922 } else {
1923 strError = wxT("A client ");
1925 if (nErrorCode == 0) {
1926 strError += wxT("closed connection.");
1927 } else if (nErrorCode == 0xFEFF) {
1928 strError += wxT(" caused a wxSOCKET_LOST event.");
1929 } else {
1930 strError += wxT("caused a socket blocking error.");
1932 } else {
1933 if (theLogger.IsEnabled(logClient) && nErrorCode != 107) {
1934 // 0 -> No Error / Disconect
1935 // 107 -> Transport endpoint is not connected
1936 if (m_client) {
1937 if (!m_client->GetUserName().IsEmpty()) {
1938 strError = CFormat(wxT("OnError: Client '%s' (IP:%s) caused an error: %u. Disconnecting client!"))
1939 % m_client->GetUserName() % m_client->GetFullIP() % nErrorCode;
1940 } else {
1941 strError = CFormat(wxT("OnError: Unknown client (IP:%s) caused an error: %u. Disconnecting client!"))
1942 % m_client->GetFullIP() % nErrorCode;
1944 } else {
1945 strError = CFormat(wxT("OnError: A client caused an error or did something bad (error %u). Disconnecting client !"))
1946 % nErrorCode;
1948 } else {
1949 strError = wxT("Error 107 (Transport endpoint is not connected)");
1953 Disconnect(strError);
1957 bool CClientTCPSocket::PacketReceived(CPacket* packet)
1959 // 0.42e
1960 bool bResult = false;
1961 uint32 uRawSize = packet->GetPacketSize();
1963 AddDebugLogLineN( logRemoteClient,
1964 CFormat(wxT("Packet with protocol %x, opcode %x, size %u received from %s"))
1965 % packet->GetProtocol()
1966 % packet->GetOpCode()
1967 % packet->GetPacketSize()
1968 % ( m_client ? m_client->GetFullIP() : wxT("Unknown Client") )
1971 wxString exception;
1973 try {
1974 bool process = true;
1976 if ((packet->GetProtocol() == OP_PACKEDPROT) ||
1977 (packet->GetProtocol() == OP_ED2KV2PACKEDPROT)) {
1979 if (!packet->UnPackPacket()) {
1980 AddDebugLogLineN(logZLib, wxT("Failed to decompress client TCP packet."));
1981 bResult = false;
1982 process = false;
1983 } else {
1984 AddDebugLogLineN(logRemoteClient, CFormat(wxT("Packet unpacked, new protocol %x, opcode %x, size %u"))
1985 % packet->GetProtocol() % packet->GetOpCode() % packet->GetPacketSize());
1989 if (process) {
1990 switch (packet->GetProtocol()) {
1991 case OP_EDONKEYPROT:
1992 bResult = ProcessPacket(packet->GetDataBuffer(),uRawSize,packet->GetOpCode());
1993 break;
1994 case OP_EMULEPROT:
1995 bResult = ProcessExtPacket(packet->GetDataBuffer(), packet->GetPacketSize(), packet->GetOpCode());
1996 break;
1997 case OP_ED2KV2HEADER:
1998 bResult = ProcessED2Kv2Packet(packet->GetDataBuffer(), packet->GetPacketSize(), packet->GetOpCode());
1999 break;
2000 case OP_ED2KV2PACKEDPROT:
2001 case OP_PACKEDPROT:
2002 // Packed inside packed?
2003 wxFAIL;
2004 break;
2005 default: {
2006 theStats::AddDownOverheadOther(uRawSize);
2007 if (m_client) {
2008 m_client->SetDownloadState(DS_ERROR);
2010 Disconnect(wxT("Unknown protocol"));
2011 bResult = false;
2015 } catch (const CEOFException& err) {
2016 exception = wxT("EOF exception: ") + err.what();
2017 } catch (const CInvalidPacket& err) {
2018 exception = wxT("InvalidPacket exception: ") + err.what();
2019 } catch (const wxString& error) {
2020 exception = wxT("error: ") + (error.IsEmpty() ? wxString(wxT("Unknown error")) : error);
2023 if (!exception.IsEmpty()) {
2024 AddDebugLogLineN( logPacketErrors,
2025 CFormat(wxT("Caught %s\nOn packet with protocol %x, opcode %x, size %u\tClientData: %s\n"))
2026 % exception
2027 % packet->GetProtocol()
2028 % packet->GetOpCode()
2029 % packet->GetPacketSize()
2030 % ( m_client ? m_client->GetClientFullInfo() : wxT("Unknown") )
2033 if (m_client) {
2034 m_client->SetDownloadState(DS_ERROR);
2037 AddDebugLogLineN( logClient,
2038 CFormat( wxT("Client '%s' (IP: %s) caused an error (%s). Disconnecting client!" ) )
2039 % ( m_client ? m_client->GetUserName() : wxString(wxT("Unknown")) )
2040 % ( m_client ? m_client->GetFullIP() : wxString(wxT("Unknown")) )
2041 % exception
2044 Disconnect(wxT("Caught exception on CClientTCPSocket::ProcessPacket\n"));
2047 return bResult;
2051 SocketSentBytes CClientTCPSocket::SendControlData(uint32 maxNumberOfBytesToSend, uint32 overchargeMaxBytesToSend)
2053 SocketSentBytes returnStatus = CEMSocket::SendControlData(maxNumberOfBytesToSend, overchargeMaxBytesToSend);
2055 if(returnStatus.success && (returnStatus.sentBytesControlPackets > 0 || returnStatus.sentBytesStandardPackets > 0)) {
2056 ResetTimeOutTimer();
2059 return returnStatus;
2063 SocketSentBytes CClientTCPSocket::SendFileAndControlData(uint32 maxNumberOfBytesToSend, uint32 overchargeMaxBytesToSend)
2065 SocketSentBytes returnStatus = CEMSocket::SendFileAndControlData(maxNumberOfBytesToSend, overchargeMaxBytesToSend);
2067 if(returnStatus.success && (returnStatus.sentBytesControlPackets > 0 || returnStatus.sentBytesStandardPackets > 0)) {
2068 ResetTimeOutTimer();
2071 return returnStatus;
2075 void CClientTCPSocket::SendPacket(CPacket* packet, bool delpacket, bool controlpacket, uint32 actualPayloadSize)
2077 ResetTimeOutTimer();
2078 CEMSocket::SendPacket(packet,delpacket,controlpacket, actualPayloadSize);
2080 // File_checked_for_headers