2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 Kry ( elkry@sourceforge.net / http://www.amule.org )
5 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Copyright (c) 2008 Froenchenko Leonid (lfroen@gmail.com)
8 // Any parts of this program derived from the xMule, lMule or eMule project,
9 // or contributed by third-party developers are copyrighted by their
10 // respective authors.
12 // This program is free software; you can redistribute it and/or modify
13 // it under the terms of the GNU General Public License as published by
14 // the Free Software Foundation; either version 2 of the License, or
15 // (at your option) any later version.
17 // This program is distributed in the hope that it will be useful,
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 // GNU General Public License for more details.
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28 #include "config.h" // Needed for VERSION
31 #include <ec/cpp/ECMuleSocket.h> // Needed for CECSocket
33 #include <common/Format.h> // Needed for CFormat
35 #include <common/ClientVersion.h>
36 #include <common/MD5Sum.h>
38 #include "ExternalConn.h" // Interface declarations
39 #include "updownclient.h" // Needed for CUpDownClient
40 #include "Server.h" // Needed for CServer
41 #include "ServerList.h" // Needed for CServerList
42 #include "PartFile.h" // Needed for CPartFile
43 #include "ServerConnect.h" // Needed for CServerConnect
44 #include "UploadQueue.h" // Needed for CUploadQueue
45 #include "amule.h" // Needed for theApp
46 #include "SearchList.h" // Needed for GetSearchResults
47 #include "IPFilter.h" // Needed for CIPFilter
48 #include "ClientList.h"
49 #include "Preferences.h" // Needed for CPreferences
51 #include "GuiEvents.h" // Needed for Notify_* macros
52 #include "Statistics.h" // Needed for theStats
53 #include "KnownFileList.h" // Needed for CKnownFileList
54 #include "RandomFunctions.h"
55 #include "kademlia/kademlia/Kademlia.h"
56 #include "kademlia/kademlia/UDPFirewallTester.h"
59 //-------------------- CECServerSocket --------------------
61 class CECServerSocket
: public CECMuleSocket
64 CECServerSocket(ECNotifier
*notifier
);
65 virtual ~CECServerSocket();
67 virtual const CECPacket
*OnPacketReceived(const CECPacket
*packet
);
68 virtual void OnLost();
70 virtual void WriteDoneAndQueueEmpty();
72 ECNotifier
*m_ec_notifier
;
74 const CECPacket
*Authenticate(const CECPacket
*);
83 uint64_t m_passwd_salt
;
84 CLoggerAccess m_LoggerAccess
;
85 CPartFile_Encoder_Map m_part_encoder
;
86 CKnownFile_Encoder_Map m_shared_encoder
;
87 CObjTagMap m_obj_tagmap
;
88 CECPacket
*ProcessRequest2(
89 const CECPacket
*request
,
90 CPartFile_Encoder_Map
&,
91 CKnownFile_Encoder_Map
&,
97 CECServerSocket::CECServerSocket(ECNotifier
*notifier
)
100 m_conn_state(CONN_INIT
),
101 m_passwd_salt(GetRandomUint64()),
106 wxASSERT(theApp
->ECServerHandler
);
107 theApp
->ECServerHandler
->AddSocket(this);
108 m_ec_notifier
= notifier
;
112 CECServerSocket::~CECServerSocket()
114 wxASSERT(theApp
->ECServerHandler
);
115 theApp
->ECServerHandler
->RemoveSocket(this);
119 const CECPacket
*CECServerSocket::OnPacketReceived(const CECPacket
*packet
)
121 const CECPacket
*reply
= NULL
;
123 if (m_conn_state
== CONN_FAILED
) {
124 // Client didn't close the socket when authentication failed.
125 AddLogLineM(false, _("Client sent packet after authentication failed."));
129 if (m_conn_state
!= CONN_ESTABLISHED
) {
130 reply
= Authenticate(packet
);
131 if (reply
->GetOpCode() == EC_OP_AUTH_FAIL
) {
133 AddLogLineM(false, _("Unauthorized access attempt. Connection closed."));
134 m_conn_state
= CONN_FAILED
;
136 theApp
->ECServerHandler
->m_ec_notifier
->Add_EC_Client(this);
139 reply
= ProcessRequest2(
140 packet
, m_part_encoder
, m_shared_encoder
, m_obj_tagmap
);
146 void CECServerSocket::OnLost()
148 AddLogLineM(false,_("External connection closed."));
149 theApp
->ECServerHandler
->m_ec_notifier
->Remove_EC_Client(this);
153 void CECServerSocket::WriteDoneAndQueueEmpty()
155 if ( HaveNotificationSupport() ) {
156 CECPacket
*packet
= m_ec_notifier
->GetNextPacket(this);
161 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
165 //-------------------- ExternalConn --------------------
173 BEGIN_EVENT_TABLE(ExternalConn
, wxEvtHandler
)
174 EVT_SOCKET(SERVER_ID
, ExternalConn::OnServerEvent
)
178 ExternalConn::ExternalConn(amuleIPV4Address addr
, wxString
*msg
)
182 // Are we allowed to accept External Connections?
183 if ( thePrefs::AcceptExternalConnections() ) {
184 // We must have a valid password, otherwise we will not allow EC connections
185 if (thePrefs::ECPassword().IsEmpty()) {
186 *msg
+= wxT("External connections disabled due to empty password!\n");
187 AddLogLineM(true, _("External connections disabled due to empty password!"));
192 m_ECServer
= new wxSocketServer(addr
, wxSOCKET_REUSEADDR
);
193 m_ECServer
->SetEventHandler(*this, SERVER_ID
);
194 m_ECServer
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
195 m_ECServer
->Notify(true);
197 int port
= addr
.Service();
198 wxString ip
= addr
.IPAddress();
199 if (m_ECServer
->Ok()) {
200 msgLocal
= wxT("*** TCP socket (ECServer) listening on ") + ip
+
201 wxString::Format(wxT(":%d"), port
);
202 *msg
+= msgLocal
+ wxT("\n");
203 AddLogLineM(false, msgLocal
);
205 msgLocal
= wxT("Could not listen for external connections at ") + ip
+
206 wxString::Format(wxT(":%d!"), port
);
207 *msg
+= msgLocal
+ wxT("\n");
208 AddLogLineM(false, msgLocal
);
211 *msg
+= wxT("External connections disabled in config file\n");
212 AddLogLineM(false,_("External connections disabled in config file"));
214 m_ec_notifier
= new ECNotifier();
218 ExternalConn::~ExternalConn()
222 delete m_ec_notifier
;
226 void ExternalConn::AddSocket(CECServerSocket
*s
)
229 socket_list
.insert(s
);
233 void ExternalConn::RemoveSocket(CECServerSocket
*s
)
236 socket_list
.erase(s
);
240 void ExternalConn::KillAllSockets()
242 AddDebugLogLineM(false, logGeneral
,
243 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
245 SocketSet::iterator it
= socket_list
.begin();
246 while (it
!= socket_list
.end()) {
247 CECServerSocket
*s
= *(it
++);
255 void ExternalConn::OnServerEvent(wxSocketEvent
& WXUNUSED(event
))
257 CECServerSocket
*sock
= new CECServerSocket(m_ec_notifier
);
258 // Accept new connection if there is one in the pending
259 // connections queue, else exit. We use Accept(FALSE) for
260 // non-blocking accept (although if we got here, there
261 // should ALWAYS be a pending connection).
262 if ( m_ECServer
->AcceptWith(*sock
, false) ) {
263 AddLogLineM(false, _("New external connection accepted"));
266 AddLogLineM(false, _("ERROR: couldn't accept a new external connection"));
274 const CECPacket
*CECServerSocket::Authenticate(const CECPacket
*request
)
278 if (request
== NULL
) {
279 response
= new CECPacket(EC_OP_AUTH_FAIL
);
283 // Password must be specified if we are to allow remote connections
284 if ( thePrefs::ECPassword().IsEmpty() ) {
285 AddLogLineM(true, _("External connection refused due to empty password in preferences!"));
287 return new CECPacket(EC_OP_AUTH_FAIL
);
290 if ((m_conn_state
== CONN_INIT
) && (request
->GetOpCode() == EC_OP_AUTH_REQ
) ) {
291 const CECTag
*clientName
= request
->GetTagByName(EC_TAG_CLIENT_NAME
);
292 const CECTag
*clientVersion
= request
->GetTagByName(EC_TAG_CLIENT_VERSION
);
294 AddLogLineM(false, CFormat( _("Connecting client: %s %s") )
295 % ( clientName
? clientName
->GetStringData() : wxString(_("Unknown")) )
296 % ( clientVersion
? clientVersion
->GetStringData() : wxString(_("Unknown version")) ) );
297 const CECTag
*protocol
= request
->GetTagByName(EC_TAG_PROTOCOL_VERSION
);
299 // For SVN versions, both client and server must use SVNDATE, and they must be the same
301 if (!vhash
.Decode(wxT(EC_VERSION_ID
))) {
302 response
= new CECPacket(EC_OP_AUTH_FAIL
);
303 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Fatal error, version hash is not a valid MD4-hash.")));
304 } else if (!request
->GetTagByName(EC_TAG_VERSION_ID
) || request
->GetTagByNameSafe(EC_TAG_VERSION_ID
)->GetMD4Data() != vhash
) {
305 response
= new CECPacket(EC_OP_AUTH_FAIL
);
306 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
308 // For release versions, we don't want to allow connections from any arbitrary SVN client.
309 if (request
->GetTagByName(EC_TAG_VERSION_ID
)) {
310 response
= new CECPacket(EC_OP_AUTH_FAIL
);
311 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("You cannot connect to a release version from an arbitrary SVN version! *sigh* possible crash prevented")));
313 } else if (protocol
!= NULL
) {
314 uint16 proto_version
= protocol
->GetInt();
315 if (proto_version
== EC_CURRENT_PROTOCOL_VERSION
) {
316 response
= new CECPacket(EC_OP_AUTH_SALT
);
317 response
->AddTag(CECTag(EC_TAG_PASSWD_SALT
, m_passwd_salt
));
318 m_conn_state
= CONN_SALT_SENT
;
320 response
= new CECPacket(EC_OP_AUTH_FAIL
);
321 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid protocol version.") + wxString::Format(wxT("( %i != %i )"),proto_version
,EC_CURRENT_PROTOCOL_VERSION
)));
324 response
= new CECPacket(EC_OP_AUTH_FAIL
);
325 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Missing protocol version tag.")));
327 } else if ((m_conn_state
== CONN_SALT_SENT
) && (request
->GetOpCode() == EC_OP_AUTH_PASSWD
)) {
328 const CECTag
*passwd
= request
->GetTagByName(EC_TAG_PASSWD_HASH
);
331 if (!passh
.Decode(thePrefs::ECPassword())) {
332 AddLogLineM(false, wxT("EC Auth failed, invalid hash specificed as EC password: ") + thePrefs::ECPassword());
333 response
= new CECPacket(EC_OP_AUTH_FAIL
);
334 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Authentication failed, invalid hash specified as EC password.")));
336 wxString saltHash
= MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt
).GetHash();
337 wxString saltStr
= CFormat(wxT("%lX")) % m_passwd_salt
;
339 passh
.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash
).GetHash());
341 if (passwd
&& passwd
->GetMD4Data() == passh
) {
342 response
= new CECPacket(EC_OP_AUTH_OK
);
343 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
346 AddLogLineM(false, wxT("EC Auth failed: (") + passwd
->GetMD4Data().Encode() + wxT(" != ") + passh
.Encode() + wxT(")."));
348 AddLogLineM(false, wxT("EC Auth failed. Password tag missing."));
351 response
= new CECPacket(EC_OP_AUTH_FAIL
);
352 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Authentication failed.")));
356 response
= new CECPacket(EC_OP_AUTH_FAIL
);
357 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid request, please authenticate first.")));
360 if (response
->GetOpCode() == EC_OP_AUTH_OK
) {
361 m_conn_state
= CONN_ESTABLISHED
;
362 AddLogLineM(false, _("Access granted."));
363 } else if (response
->GetTagByIndex(0)->IsString()) {
364 AddLogLineM(false, wxGetTranslation(response
->GetTagByIndex(0)->GetStringData()));
370 // Make a Logger tag (if there are any logging messages) and add it to the response
371 static void AddLoggerTag(CECPacket
*response
, CLoggerAccess
&LoggerAccess
)
373 if (LoggerAccess
.HasString()) {
374 CECEmptyTag
tag(EC_TAG_STATS_LOGGER_MESSAGE
);
375 // Tag structure is fix: tag carries nothing, inside are the strings
376 // maximum of 200 log lines per message
379 while (entries
< 200 && LoggerAccess
.GetString(line
)) {
380 tag
.AddTag(CECTag(EC_TAG_STRING
, line
));
383 response
->AddTag(tag
);
384 //printf("send Log tag %d %d\n", FirstEntry, entries);
388 CECPacket
*Get_EC_Response_StatRequest(const CECPacket
*request
, CLoggerAccess
&LoggerAccess
)
390 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
392 switch (request
->GetDetailLevel()) {
394 response
->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD
, (uint32
)theStats::GetUpOverheadRate()));
395 response
->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD
, (uint32
)theStats::GetDownOverheadRate()));
396 response
->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT
, /*(uint32)*/theStats::GetBannedCount()));
397 AddLoggerTag(response
, LoggerAccess
);
400 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED
, (uint32
)theStats::GetUploadRate()));
401 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED
, (uint32
)(theStats::GetDownloadRate())));
402 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxUpload()*1024.0)));
403 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxDownload()*1024.0)));
404 response
->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN
, /*(uint32)*/theStats::GetWaitingUserCount()));
405 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT
, /*(uint32)*/theStats::GetFoundSources()));
408 uint32 totaluser
= 0, totalfile
= 0;
409 theApp
->serverlist
->GetUserFileStatus( totaluser
, totalfile
);
410 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS
, totaluser
));
411 response
->AddTag(CECTag(EC_TAG_STATS_KAD_USERS
, Kademlia::CKademlia::GetKademliaUsers()));
412 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES
, totalfile
));
413 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FILES
, Kademlia::CKademlia::GetKademliaFiles()));
416 if (Kademlia::CKademlia::IsConnected()) {
417 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP
, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
418 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource
));
419 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS
, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword
));
420 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes
));
421 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD
, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad
));
422 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS
, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
423 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS
, theApp
->clientlist
->GetBuddyStatus()));
425 uint16 BuddyPort
= 0;
426 CUpDownClient
* Buddy
= theApp
->clientlist
->GetBuddy();
428 BuddyIP
= Buddy
->GetIP();
429 BuddyPort
= Buddy
->GetUDPPort();
431 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP
, BuddyIP
));
432 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT
, BuddyPort
));
434 case EC_DETAIL_UPDATE
:
435 case EC_DETAIL_INC_UPDATE
:
442 CECPacket
*Get_EC_Response_GetSharedFiles(const CECPacket
*request
, CKnownFile_Encoder_Map
&encoders
)
444 wxASSERT(request
->GetOpCode() == EC_OP_GET_SHARED_FILES
);
446 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
448 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
450 // request can contain list of queried items
451 CTagSet
<CMD4Hash
, EC_TAG_KNOWNFILE
> queryitems(request
);
453 encoders
.UpdateEncoders(theApp
->sharedfiles
);
455 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
456 CKnownFile
*cur_file
= (CKnownFile
*)theApp
->sharedfiles
->GetFileByIndex(i
);
458 if ( !cur_file
|| (!queryitems
.empty() && !queryitems
.count(cur_file
->GetFileHash())) ) {
462 CEC_SharedFile_Tag
filetag(cur_file
, detail_level
);
463 CKnownFile_Encoder
&enc
= encoders
[cur_file
];
464 if ( detail_level
!= EC_DETAIL_UPDATE
) {
467 enc
.Encode(&filetag
);
468 response
->AddTag(filetag
);
473 CECPacket
*Get_EC_Response_GetSharedFiles(CKnownFile_Encoder_Map
&encoders
, CObjTagMap
&tagmap
)
475 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
477 encoders
.UpdateEncoders(theApp
->sharedfiles
);
478 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
479 CKnownFile
*cur_file
= (CKnownFile
*)theApp
->sharedfiles
->GetFileByIndex(i
);
482 // Hashes of tags are maintained on "per-object" basis. So, in this mode only
483 // same kind of objects can go into particular query type.
484 // Particulary here it means that files from download queue (aka partfiles)
485 // will not ne shown as shared files. Remote gui can do combine them if wishes
487 if ( !cur_file
|| cur_file
->IsPartFile() ) continue;
489 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
);
490 CEC_SharedFile_Tag
filetag(cur_file
, valuemap
);
491 CKnownFile_Encoder
&enc
= encoders
[cur_file
];
492 enc
.Encode(&filetag
);
494 response
->AddTag(filetag
);
499 CECPacket
*Get_EC_Response_GetWaitQueue(const CECPacket
*request
)
501 wxASSERT(request
->GetOpCode() == EC_OP_GET_WAIT_QUEUE
);
503 CECPacket
*response
= new CECPacket(EC_OP_WAIT_QUEUE
);
505 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
508 // request can contain list of queried items
509 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
511 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetWaitingList();
512 CClientPtrList::const_iterator it
= uploading
.begin();
513 for (; it
!= uploading
.end(); ++it
) {
514 CUpDownClient
* cur_client
= *it
;
516 if ( !cur_client
|| (!queryitems
.empty() && !queryitems
.count(cur_client
->GetUserIDHybrid())) ) {
519 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
);
521 response
->AddTag(cli_tag
);
527 CECPacket
*Get_EC_Response_GetWaitQueue(CObjTagMap
&tagmap
)
529 CECPacket
*response
= new CECPacket(EC_OP_WAIT_QUEUE
);
531 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetWaitingList();
532 CClientPtrList::const_iterator it
= uploading
.begin();
533 for (; it
!= uploading
.end(); ++it
) {
534 CUpDownClient
* cur_client
= *it
;
536 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
);
537 CEC_UpDownClient_Tag
cli_tag(cur_client
, valuemap
);
539 response
->AddTag(cli_tag
);
545 CECPacket
*Get_EC_Response_GetUpQueue(const CECPacket
*request
)
547 wxASSERT(request
->GetOpCode() == EC_OP_GET_ULOAD_QUEUE
);
549 CECPacket
*response
= new CECPacket(EC_OP_ULOAD_QUEUE
);
551 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
554 // request can contain list of queried items
555 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
558 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetUploadingList();
559 CClientPtrList::const_iterator it
= uploading
.begin();
560 for (; it
!= uploading
.end(); ++it
) {
561 CUpDownClient
* cur_client
= *it
;
563 if ( !cur_client
|| (!queryitems
.empty() && !queryitems
.count(cur_client
->GetUserIDHybrid())) ) {
567 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
);
568 response
->AddTag(cli_tag
);
575 CECPacket
*Get_EC_Response_GetUpQueue(CObjTagMap
&tagmap
)
577 CECPacket
*response
= new CECPacket(EC_OP_ULOAD_QUEUE
);
579 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetUploadingList();
580 CClientPtrList::const_iterator it
= uploading
.begin();
581 for (; it
!= uploading
.end(); ++it
) {
582 CUpDownClient
* cur_client
= *it
;
584 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
);
585 CEC_UpDownClient_Tag
cli_tag(cur_client
, valuemap
);
587 response
->AddTag(cli_tag
);
594 CECPacket
*Get_EC_Response_GetDownloadQueue(CPartFile_Encoder_Map
&encoders
, CObjTagMap
&tagmap
)
596 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
598 encoders
.UpdateEncoders(theApp
->downloadqueue
);
599 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
600 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
602 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
);
603 CEC_PartFile_Tag
filetag(cur_file
, valuemap
);
604 CPartFile_Encoder
&enc
= encoders
[cur_file
];
605 enc
.Encode(&filetag
);
607 response
->AddTag(filetag
);
612 CECPacket
*Get_EC_Response_GetDownloadQueue(const CECPacket
*request
, CPartFile_Encoder_Map
&encoders
, bool detail
= false)
614 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
616 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
618 // request can contain list of queried items
619 CTagSet
<CMD4Hash
, EC_TAG_PARTFILE
> queryitems(request
);
621 encoders
.UpdateEncoders(theApp
->downloadqueue
);
623 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
624 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
626 if ( !queryitems
.empty() && !queryitems
.count(cur_file
->GetFileHash()) ) {
630 CEC_PartFile_Tag
filetag(cur_file
, detail_level
, detail
);
632 CPartFile_Encoder
&enc
= encoders
[cur_file
];
633 if ( detail_level
!= EC_DETAIL_UPDATE
) {
636 enc
.Encode(&filetag
);
638 response
->AddTag(filetag
);
644 CECPacket
*Get_EC_Response_PartFile_Cmd(const CECPacket
*request
)
646 CECPacket
*response
= NULL
;
648 // request can contain multiple files.
649 for (unsigned int i
= 0; i
< request
->GetTagCount(); ++i
) {
650 const CECTag
*hashtag
= request
->GetTagByIndex(i
);
652 wxASSERT(hashtag
->GetTagName() == EC_TAG_PARTFILE
);
654 CMD4Hash hash
= hashtag
->GetMD4Data();
655 CPartFile
*pfile
= theApp
->downloadqueue
->GetFileByID( hash
);
658 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash
.Encode());
659 response
= new CECPacket(EC_OP_FAILED
);
660 response
->AddTag(CECTag(EC_TAG_STRING
, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash
.Encode()));
664 switch (request
->GetOpCode()) {
665 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
666 if ((pfile
->GetStatus(false) == PS_READY
) ||
667 (pfile
->GetStatus(false) == PS_EMPTY
)) {
668 CPartFile::SourceSet::const_iterator it
= pfile
->GetA4AFList().begin();
669 while ( it
!= pfile
->GetA4AFList().end() ) {
670 CUpDownClient
*cur_source
= *it
++;
672 cur_source
->SwapToAnotherFile(true, false, false, pfile
);
676 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
677 pfile
->SetA4AFAuto(!pfile
->IsA4AFAuto());
679 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
680 if ((pfile
->GetStatus(false) == PS_READY
) ||
681 (pfile
->GetStatus(false) == PS_EMPTY
)) {
682 CPartFile::SourceSet::const_iterator it
= pfile
->GetSourceList().begin();
683 while ( it
!= pfile
->GetSourceList().end() ) {
684 CUpDownClient
* cur_source
= *it
++;
686 cur_source
->SwapToAnotherFile(false, false, false, NULL
);
690 case EC_OP_PARTFILE_PAUSE
:
693 case EC_OP_PARTFILE_RESUME
:
695 pfile
->SavePartFile();
697 case EC_OP_PARTFILE_STOP
:
700 case EC_OP_PARTFILE_PRIO_SET
: {
701 uint8 prio
= hashtag
->GetTagByIndexSafe(0)->GetInt();
702 if ( prio
== PR_AUTO
) {
703 pfile
->SetAutoDownPriority(1);
705 pfile
->SetAutoDownPriority(0);
706 pfile
->SetDownPriority(prio
);
710 case EC_OP_PARTFILE_DELETE
:
711 if ( thePrefs::StartNextFile() && (pfile
->GetStatus() != PS_PAUSED
) ) {
712 theApp
->downloadqueue
->StartNextFile(pfile
);
717 case EC_OP_PARTFILE_SET_CAT
:
718 pfile
->SetCategory(hashtag
->GetTagByIndexSafe(0)->GetInt());
722 response
= new CECPacket(EC_OP_FAILED
);
723 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
728 response
= new CECPacket(EC_OP_NOOP
);
733 CECPacket
*Get_EC_Response_Server_Add(const CECPacket
*request
)
735 CECPacket
*response
= NULL
;
737 const CECTag
*srv_tag
= request
->GetTagByIndex(0);
739 wxString full_addr
= srv_tag
->GetTagByName(EC_TAG_SERVER_ADDRESS
)->GetStringData();
740 wxString name
= srv_tag
->GetTagByName(EC_TAG_SERVER_NAME
)->GetStringData();
742 wxString s_ip
= full_addr
.Left(full_addr
.Find(':'));
743 wxString s_port
= full_addr
.Mid(full_addr
.Find(':') + 1);
745 long port
= StrToULong(s_port
);
746 CServer
* toadd
= new CServer(port
, s_ip
);
747 toadd
->SetListName(name
.IsEmpty() ? full_addr
: name
);
749 if ( theApp
->AddServer(toadd
, true) ) {
750 response
= new CECPacket(EC_OP_NOOP
);
752 response
= new CECPacket(EC_OP_FAILED
);
753 response
->AddTag(CECTag(EC_TAG_STRING
, _("Server not added")));
760 CECPacket
*Get_EC_Response_Server(const CECPacket
*request
)
762 CECPacket
*response
= NULL
;
763 const CECTag
*srv_tag
= request
->GetTagByIndex(0);
766 srv
= theApp
->serverlist
->GetServerByIPTCP(srv_tag
->GetIPv4Data().IP(), srv_tag
->GetIPv4Data().m_port
);
767 // server tag passed, but server not found
769 response
= new CECPacket(EC_OP_FAILED
);
770 response
->AddTag(CECTag(EC_TAG_STRING
,
771 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag
->GetIPv4Data().StringIP()));
775 switch (request
->GetOpCode()) {
776 case EC_OP_SERVER_DISCONNECT
:
777 theApp
->serverconnect
->Disconnect();
778 response
= new CECPacket(EC_OP_NOOP
);
780 case EC_OP_SERVER_REMOVE
:
782 theApp
->serverlist
->RemoveServer(srv
);
783 response
= new CECPacket(EC_OP_NOOP
);
785 response
= new CECPacket(EC_OP_FAILED
);
786 response
->AddTag(CECTag(EC_TAG_STRING
,
787 wxTRANSLATE("need to define server to be removed")));
790 case EC_OP_SERVER_CONNECT
:
791 if (thePrefs::GetNetworkED2K()) {
793 theApp
->serverconnect
->ConnectToServer(srv
);
794 response
= new CECPacket(EC_OP_NOOP
);
796 theApp
->serverconnect
->ConnectToAnyServer();
797 response
= new CECPacket(EC_OP_NOOP
);
800 response
= new CECPacket(EC_OP_FAILED
);
801 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("eD2k is disabled in preferences.")));
806 response
= new CECPacket(EC_OP_FAILED
);
807 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
812 CECPacket
*Get_EC_Response_Search_Results(const CECPacket
*request
)
814 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
816 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
818 // request can contain list of queried items
819 CTagSet
<CMD4Hash
, EC_TAG_SEARCHFILE
> queryitems(request
);
821 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
822 CSearchResultList::const_iterator it
= list
.begin();
823 while (it
!= list
.end()) {
824 CSearchFile
* sf
= *it
++;
825 if ( !queryitems
.empty() && !queryitems
.count(sf
->GetFileHash()) ) {
828 response
->AddTag(CEC_SearchFile_Tag(sf
, detail_level
));
833 CECPacket
*Get_EC_Response_Search_Results(CObjTagMap
&tagmap
)
835 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
837 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
838 CSearchResultList::const_iterator it
= list
.begin();
839 while (it
!= list
.end()) {
840 CSearchFile
* sf
= *it
++;
841 CValueMap
&valuemap
= tagmap
.GetValueMap(sf
);
842 response
->AddTag(CEC_SearchFile_Tag(sf
, valuemap
));
847 CECPacket
*Get_EC_Response_Search_Results_Download(const CECPacket
*request
)
849 CECPacket
*response
= new CECPacket(EC_OP_STRINGS
);
850 for (unsigned int i
= 0;i
< request
->GetTagCount();i
++) {
851 const CECTag
*tag
= request
->GetTagByIndex(i
);
852 CMD4Hash hash
= tag
->GetMD4Data();
853 uint8 category
= tag
->GetTagByIndexSafe(0)->GetInt();
854 theApp
->searchlist
->AddFileToDownloadByHash(hash
, category
);
859 CECPacket
*Get_EC_Response_Search_Stop(const CECPacket
*WXUNUSED(request
))
861 CECPacket
*reply
= new CECPacket(EC_OP_MISC_DATA
);
862 theApp
->searchlist
->StopGlobalSearch();
866 CECPacket
*Get_EC_Response_Search(const CECPacket
*request
)
870 CEC_Search_Tag
*search_request
= (CEC_Search_Tag
*)request
->GetTagByIndex(0);
871 theApp
->searchlist
->RemoveResults(0xffffffff);
873 CSearchList::CSearchParams params
;
874 params
.searchString
= search_request
->SearchText();
875 params
.typeText
= search_request
->SearchFileType();
876 params
.extension
= search_request
->SearchExt();
877 params
.minSize
= search_request
->MinSize();
878 params
.maxSize
= search_request
->MaxSize();
879 params
.availability
= search_request
->Avail();
882 EC_SEARCH_TYPE search_type
= search_request
->SearchType();
883 SearchType core_search_type
= LocalSearch
;
884 switch (search_type
) {
885 case EC_SEARCH_GLOBAL
:
886 core_search_type
= GlobalSearch
;
888 if (core_search_type
!= GlobalSearch
) { // Not a global search obviously
889 core_search_type
= KadSearch
;
891 case EC_SEARCH_LOCAL
: {
892 uint32 search_id
= 0xffffffff;
893 wxString error
= theApp
->searchlist
->StartNewSearch(&search_id
, core_search_type
, params
);
894 if (!error
.IsEmpty()) {
897 response
= wxTRANSLATE("Search in progress. Refetch results in a moment!");
902 response
= wxTRANSLATE("WebSearch from remote interface makes no sense.");
906 CECPacket
*reply
= new CECPacket(EC_OP_FAILED
);
907 // error or search in progress
908 reply
->AddTag(CECTag(EC_TAG_STRING
, response
));
913 CECPacket
*Get_EC_Response_Set_SharedFile_Prio(const CECPacket
*request
)
915 CECPacket
*response
= new CECPacket(EC_OP_NOOP
);
916 for (unsigned int i
= 0;i
< request
->GetTagCount();i
++) {
917 const CECTag
*tag
= request
->GetTagByIndex(i
);
918 CMD4Hash hash
= tag
->GetMD4Data();
919 uint8 prio
= tag
->GetTagByIndexSafe(0)->GetInt();
920 CKnownFile
* cur_file
= theApp
->sharedfiles
->GetFileByID(hash
);
924 if (prio
== PR_AUTO
) {
925 cur_file
->SetAutoUpPriority(1);
926 cur_file
->UpdateAutoUpPriority();
928 cur_file
->SetAutoUpPriority(0);
929 cur_file
->SetUpPriority(prio
);
936 CECPacket
*Get_EC_Response_Kad_Connect(const CECPacket
*request
)
939 if (thePrefs::GetNetworkKademlia()) {
940 response
= new CECPacket(EC_OP_NOOP
);
941 if ( !Kademlia::CKademlia::IsRunning() ) {
942 Kademlia::CKademlia::Start();
943 theApp
->ShowConnectionState();
945 const CECTag
*addrtag
= request
->GetTagByIndex(0);
947 uint32 ip
= addrtag
->GetIPv4Data().IP();
948 uint16 port
= addrtag
->GetIPv4Data().m_port
;
949 Kademlia::CKademlia::Bootstrap(ip
, port
, true);
952 response
= new CECPacket(EC_OP_FAILED
);
953 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
959 // init with some default size
960 CPartFile_Encoder::GapBuffer
CPartFile_Encoder::m_gap_buffer(128);
963 CPartFile_Encoder::CPartFile_Encoder(CPartFile
*file
) :
964 m_enc_data(file
->GetPartCount(), file
->GetGapList().size() * 2)
970 CPartFile_Encoder::CPartFile_Encoder(int size
): m_enc_data(size
, 0)
975 CPartFile_Encoder::~CPartFile_Encoder()
980 CPartFile_Encoder::CPartFile_Encoder()
985 CPartFile_Encoder::CPartFile_Encoder(const CPartFile_Encoder
&obj
) : m_enc_data(obj
.m_enc_data
)
990 CPartFile_Encoder
&CPartFile_Encoder::operator=(const CPartFile_Encoder
&obj
)
993 m_enc_data
= obj
.m_enc_data
;
997 void CPartFile_Encoder::Encode(CECTag
*parent
)
999 const CGapList
& gaplist
= m_file
->GetNewGapList();
1000 const size_t gap_list_size
= gaplist
.size();
1002 if ( m_gap_buffer
.size() < gap_list_size
* 2 ) {
1003 m_gap_buffer
.clear();
1004 m_gap_buffer
.resize(gap_list_size
* 2);
1007 GapBuffer::iterator it
= m_gap_buffer
.begin();
1009 for (CGapList::const_iterator curr_pos
= gaplist
.begin(); curr_pos
!= gaplist
.end(); ++curr_pos
) {
1010 *it
++ = ENDIAN_HTONLL(curr_pos
.start());
1011 *it
++ = ENDIAN_HTONLL(curr_pos
.end());
1014 m_enc_data
.m_gap_status
.Realloc(gap_list_size
*2*sizeof(uint64
));
1015 int gap_enc_size
= 0;
1016 const unsigned char *gap_enc_data
= m_enc_data
.m_gap_status
.Encode((unsigned char *)&m_gap_buffer
[0], gap_enc_size
);
1019 const unsigned char *part_enc_data
= m_enc_data
.m_part_status
.Encode(m_file
->m_SrcpartFrequency
, part_enc_size
);
1022 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
1025 // Put data inside of tag in following order:
1026 // [num_of_gaps] [gap_enc_data]
1028 unsigned char *tagdata
;
1029 CECTag
etag(EC_TAG_PARTFILE_GAP_STATUS
,
1030 sizeof(uint32
) + gap_enc_size
, (void **)&tagdata
);
1032 // real number of gaps - so remote size can realloc
1033 RawPokeUInt32( tagdata
, ENDIAN_HTONL( gap_list_size
) );
1034 tagdata
+= sizeof(uint32
);
1035 memcpy(tagdata
, gap_enc_data
, gap_enc_size
);
1037 parent
->AddTag(etag
);
1039 it
= m_gap_buffer
.begin();
1041 const CPartFile::CReqBlockPtrList
& requestedblocks
= m_file
->GetRequestedBlockList();
1042 CPartFile::CReqBlockPtrList::const_iterator curr_pos2
= requestedblocks
.begin();
1044 wxASSERT(m_gap_buffer
.size() >= requestedblocks
.size() * 2);
1045 for ( ; curr_pos2
!= requestedblocks
.end(); ++curr_pos2
) {
1046 Requested_Block_Struct
* block
= *curr_pos2
;
1047 *it
++ = ENDIAN_HTONLL(block
->StartOffset
);
1048 *it
++ = ENDIAN_HTONLL(block
->EndOffset
);
1050 parent
->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS
,
1051 requestedblocks
.size() * 2 * sizeof(uint64
), (void *)&m_gap_buffer
[0]));
1055 CKnownFile_Encoder::CKnownFile_Encoder(CKnownFile
*file
) :
1056 m_enc_data(file
->GetPartCount(), true)
1061 CKnownFile_Encoder::CKnownFile_Encoder()
1066 CKnownFile_Encoder::~CKnownFile_Encoder()
1070 CKnownFile_Encoder::CKnownFile_Encoder(const CKnownFile_Encoder
&obj
) : m_enc_data(obj
.m_enc_data
)
1072 m_file
= obj
.m_file
;
1075 CKnownFile_Encoder
&CKnownFile_Encoder::operator=(const CKnownFile_Encoder
&obj
)
1077 m_file
= obj
.m_file
;
1078 m_enc_data
= obj
.m_enc_data
;
1082 void CKnownFile_Encoder::Encode(CECTag
*parent
)
1085 const unsigned char *part_enc_data
= m_enc_data
.Encode(m_file
->m_AvailPartFrequency
, part_enc_size
);
1087 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
1090 CECPacket
*GetStatsGraphs(const CECPacket
*request
)
1092 CECPacket
*response
= NULL
;
1094 switch (request
->GetDetailLevel()) {
1096 case EC_DETAIL_FULL
: {
1097 double dTimestamp
= 0.0;
1098 if (request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
) != NULL
) {
1099 dTimestamp
= request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
)->GetDoubleData();
1101 uint16 nScale
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE
)->GetInt();
1102 uint16 nMaxPoints
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH
)->GetInt();
1104 unsigned int numPoints
= theApp
->m_statistics
->GetHistoryForWeb(nMaxPoints
, (double)nScale
, &dTimestamp
, &graphData
);
1106 response
= new CECPacket(EC_OP_STATSGRAPHS
);
1107 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA
, 4 * numPoints
* sizeof(uint32
), graphData
));
1108 delete [] graphData
;
1109 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST
, dTimestamp
));
1111 response
= new CECPacket(EC_OP_FAILED
);
1112 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("No points for graph.")));
1116 case EC_DETAIL_INC_UPDATE
:
1117 case EC_DETAIL_UPDATE
:
1120 response
= new CECPacket(EC_OP_FAILED
);
1121 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Your client is not configured for this detail level.")));
1125 response
= new CECPacket(EC_OP_FAILED
);
1132 CECPacket
*CECServerSocket::ProcessRequest2(const CECPacket
*request
,
1133 CPartFile_Encoder_Map
&enc_part_map
, CKnownFile_Encoder_Map
&enc_shared_map
, CObjTagMap
&objmap
)
1140 CECPacket
*response
= NULL
;
1142 switch (request
->GetOpCode()) {
1146 case EC_OP_SHUTDOWN
:
1147 if (!theApp
->IsOnShutDown()) {
1148 response
= new CECPacket(EC_OP_NOOP
);
1149 AddLogLineM(true, _("External Connection: shutdown requested"));
1150 #ifndef AMULE_DAEMON
1153 evt
.SetCanVeto(false);
1154 theApp
->ShutDown(evt
);
1157 theApp
->ExitMainLoop();
1160 response
= new CECPacket(EC_OP_FAILED
);
1161 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already shutting down.")));
1164 case EC_OP_ADD_LINK
:
1165 for(unsigned int i
= 0; i
< request
->GetTagCount();i
++) {
1166 const CECTag
*tag
= request
->GetTagByIndex(i
);
1167 wxString link
= tag
->GetStringData();
1168 int category
= tag
->GetTagByIndexSafe(0)->GetInt();
1169 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link
);
1170 if ( theApp
->downloadqueue
->AddLink(link
, category
) ) {
1171 response
= new CECPacket(EC_OP_NOOP
);
1173 // Error messages are printed by the add function.
1174 response
= new CECPacket(EC_OP_FAILED
);
1175 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid link or already on list.")));
1182 case EC_OP_STAT_REQ
:
1183 response
= Get_EC_Response_StatRequest(request
, m_LoggerAccess
);
1185 case EC_OP_GET_CONNSTATE
:
1187 response
= new CECPacket(EC_OP_MISC_DATA
);
1189 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1194 case EC_OP_GET_SHARED_FILES
:
1195 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1196 response
= Get_EC_Response_GetSharedFiles(enc_shared_map
, objmap
);
1198 response
= Get_EC_Response_GetSharedFiles(request
, enc_shared_map
);
1201 case EC_OP_GET_DLOAD_QUEUE
:
1202 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1203 response
= Get_EC_Response_GetDownloadQueue(enc_part_map
, objmap
);
1205 response
= Get_EC_Response_GetDownloadQueue(request
, enc_part_map
);
1208 // transmit source names and comments only if file detail dialog is open
1209 case EC_OP_GET_DLOAD_QUEUE_DETAIL
:
1210 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1211 response
= Get_EC_Response_GetDownloadQueue(enc_part_map
, objmap
);
1213 response
= Get_EC_Response_GetDownloadQueue(request
, enc_part_map
, true);
1216 case EC_OP_GET_ULOAD_QUEUE
:
1217 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1218 response
= Get_EC_Response_GetUpQueue(objmap
);
1220 response
= Get_EC_Response_GetUpQueue(request
);
1223 case EC_OP_GET_WAIT_QUEUE
:
1224 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1225 response
= Get_EC_Response_GetWaitQueue(objmap
);
1227 response
= Get_EC_Response_GetWaitQueue(request
);
1230 case EC_OP_PARTFILE_REMOVE_NO_NEEDED
:
1231 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE
:
1232 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE
:
1233 case EC_OP_PARTFILE_CLEANUP_SOURCES
:
1234 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
1235 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
1236 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
1237 case EC_OP_PARTFILE_PAUSE
:
1238 case EC_OP_PARTFILE_RESUME
:
1239 case EC_OP_PARTFILE_STOP
:
1240 case EC_OP_PARTFILE_PRIO_SET
:
1241 case EC_OP_PARTFILE_DELETE
:
1242 case EC_OP_PARTFILE_SET_CAT
:
1243 response
= Get_EC_Response_PartFile_Cmd(request
);
1245 case EC_OP_SHAREDFILES_RELOAD
:
1246 theApp
->sharedfiles
->Reload();
1247 response
= new CECPacket(EC_OP_NOOP
);
1249 case EC_OP_SHARED_SET_PRIO
:
1250 response
= Get_EC_Response_Set_SharedFile_Prio(request
);
1252 case EC_OP_RENAME_FILE
: {
1253 CMD4Hash fileHash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1254 CKnownFile
* file
= theApp
->knownfiles
->FindKnownFileByID(fileHash
);
1255 wxString newName
= request
->GetTagByNameSafe(EC_TAG_PARTFILE_NAME
)->GetStringData();
1257 file
= theApp
->downloadqueue
->GetFileByID(fileHash
);
1260 response
= new CECPacket(EC_OP_FAILED
);
1261 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("File not found.")));
1264 if (newName
.IsEmpty()) {
1265 response
= new CECPacket(EC_OP_FAILED
);
1266 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid file name.")));
1270 if (theApp
->sharedfiles
->RenameFile(file
, CPath(newName
))) {
1271 response
= new CECPacket(EC_OP_NOOP
);
1273 response
= new CECPacket(EC_OP_FAILED
);
1274 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Unable to rename file.")));
1284 case EC_OP_SERVER_ADD
:
1285 response
= Get_EC_Response_Server_Add(request
);
1287 case EC_OP_SERVER_DISCONNECT
:
1288 case EC_OP_SERVER_CONNECT
:
1289 case EC_OP_SERVER_REMOVE
:
1290 response
= Get_EC_Response_Server(request
);
1292 case EC_OP_GET_SERVER_LIST
: {
1293 response
= new CECPacket(EC_OP_SERVER_LIST
);
1294 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1295 std::vector
<const CServer
*> servers
= theApp
->serverlist
->CopySnapshot();
1297 std::vector
<const CServer
*>::const_iterator it
= servers
.begin();
1298 it
!= servers
.end();
1301 response
->AddTag(CEC_Server_Tag(*it
, detail_level
));
1305 case EC_OP_SERVER_UPDATE_FROM_URL
: {
1306 wxString url
= request
->GetTagByIndexSafe(0)->GetStringData();
1308 // Save the new url, and update the UI (if not amuled).
1309 Notify_ServersURLChanged(url
);
1310 thePrefs::SetEd2kServersUrl(url
);
1312 theApp
->serverlist
->UpdateServerMetFromURL(url
);
1313 response
= new CECPacket(EC_OP_NOOP
);
1319 case EC_OP_IPFILTER_RELOAD
:
1320 theApp
->ipfilter
->Reload();
1321 response
= new CECPacket(EC_OP_NOOP
);
1326 case EC_OP_SEARCH_START
:
1327 response
= Get_EC_Response_Search(request
);
1330 case EC_OP_SEARCH_STOP
:
1331 response
= Get_EC_Response_Search_Stop(request
);
1334 case EC_OP_SEARCH_RESULTS
:
1335 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1336 response
= Get_EC_Response_Search_Results(objmap
);
1338 response
= Get_EC_Response_Search_Results(request
);
1342 case EC_OP_SEARCH_PROGRESS
:
1343 response
= new CECPacket(EC_OP_SEARCH_PROGRESS
);
1344 response
->AddTag(CECTag(EC_TAG_SEARCH_STATUS
,
1345 theApp
->searchlist
->GetSearchProgress()));
1348 case EC_OP_DOWNLOAD_SEARCH_RESULT
:
1349 response
= Get_EC_Response_Search_Results_Download(request
);
1354 case EC_OP_GET_PREFERENCES
:
1355 response
= new CEC_Prefs_Packet(request
->GetTagByNameSafe(EC_TAG_SELECT_PREFS
)->GetInt(), request
->GetDetailLevel());
1357 case EC_OP_SET_PREFERENCES
:
1358 ((CEC_Prefs_Packet
*)request
)->Apply();
1359 theApp
->glob_prefs
->Save();
1360 if (thePrefs::IsFilteringClients()) {
1361 theApp
->clientlist
->FilterQueues();
1363 if (thePrefs::IsFilteringServers()) {
1364 theApp
->serverlist
->FilterServers();
1366 if (!thePrefs::GetNetworkED2K() && theApp
->IsConnectedED2K()) {
1367 theApp
->DisconnectED2K();
1369 if (!thePrefs::GetNetworkKademlia() && theApp
->IsConnectedKad()) {
1372 response
= new CECPacket(EC_OP_NOOP
);
1375 case EC_OP_CREATE_CATEGORY
:
1376 if ( request
->GetTagCount() == 1 ) {
1377 ((CEC_Category_Tag
*)request
->GetTagByIndex(0))->Create();
1378 Notify_CategoryAdded();
1380 response
= new CECPacket(EC_OP_NOOP
);
1382 case EC_OP_UPDATE_CATEGORY
:
1383 if ( request
->GetTagCount() == 1 ) {
1384 CEC_Category_Tag
*tag
= (CEC_Category_Tag
*)request
->GetTagByIndex(0);
1386 Notify_CategoryUpdate(tag
->GetInt());
1388 response
= new CECPacket(EC_OP_NOOP
);
1390 case EC_OP_DELETE_CATEGORY
:
1391 if ( request
->GetTagCount() == 1 ) {
1392 uint32 cat
= request
->GetTagByIndex(0)->GetInt();
1393 Notify_CategoryDelete(cat
);
1395 response
= new CECPacket(EC_OP_NOOP
);
1401 case EC_OP_ADDLOGLINE
:
1402 AddLogLineM( (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
), request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData() );
1403 response
= new CECPacket(EC_OP_NOOP
);
1405 case EC_OP_ADDDEBUGLOGLINE
:
1406 AddDebugLogLineM( (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
), logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData() );
1407 response
= new CECPacket(EC_OP_NOOP
);
1410 response
= new CECPacket(EC_OP_LOG
);
1411 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetLog(false)));
1413 case EC_OP_GET_DEBUGLOG
:
1414 response
= new CECPacket(EC_OP_DEBUGLOG
);
1415 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetDebugLog(false)));
1417 case EC_OP_RESET_LOG
:
1418 theApp
->GetLog(true);
1419 response
= new CECPacket(EC_OP_NOOP
);
1421 case EC_OP_RESET_DEBUGLOG
:
1422 theApp
->GetDebugLog(true);
1423 response
= new CECPacket(EC_OP_NOOP
);
1425 case EC_OP_GET_LAST_LOG_ENTRY
:
1427 wxString tmp
= theApp
->GetLog(false);
1428 if (tmp
.Last() == '\n') {
1431 response
= new CECPacket(EC_OP_LOG
);
1432 response
->AddTag(CECTag(EC_TAG_STRING
, tmp
.AfterLast('\n')));
1435 case EC_OP_GET_SERVERINFO
:
1436 response
= new CECPacket(EC_OP_SERVERINFO
);
1437 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetServerLog(false)));
1439 case EC_OP_CLEAR_SERVERINFO
:
1440 theApp
->GetServerLog(true);
1441 response
= new CECPacket(EC_OP_NOOP
);
1446 case EC_OP_GET_STATSGRAPHS
:
1447 response
= GetStatsGraphs(request
);
1449 case EC_OP_GET_STATSTREE
: {
1450 theApp
->m_statistics
->UpdateStatsTree();
1451 response
= new CECPacket(EC_OP_STATSTREE
);
1452 CECTag
* tree
= theStats::GetECStatTree(request
->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING
)->GetInt());
1454 response
->AddTag(*tree
);
1457 if (request
->GetDetailLevel() == EC_DETAIL_WEB
) {
1458 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
1459 response
->AddTag(CECTag(EC_TAG_USER_NICK
, thePrefs::GetUserNick()));
1467 case EC_OP_KAD_START
:
1468 response
= Get_EC_Response_Kad_Connect(request
);
1470 case EC_OP_KAD_STOP
:
1472 response
= new CECPacket(EC_OP_NOOP
);
1474 case EC_OP_KAD_UPDATE_FROM_URL
: {
1475 wxString url
= request
->GetTagByIndexSafe(0)->GetStringData();
1477 // Save the new url, and update the UI (if not amuled).
1478 Notify_NodesURLChanged(url
);
1479 thePrefs::SetKadNodesUrl(url
);
1481 theApp
->UpdateNotesDat(url
);
1482 response
= new CECPacket(EC_OP_NOOP
);
1485 case EC_OP_KAD_BOOTSTRAP_FROM_IP
:
1486 theApp
->BootstrapKad(request
->GetTagByIndexSafe(0)->GetInt(),
1487 request
->GetTagByIndexSafe(1)->GetInt());
1488 response
= new CECPacket(EC_OP_NOOP
);
1495 if (thePrefs::GetNetworkED2K()) {
1496 response
= new CECPacket(EC_OP_STRINGS
);
1497 if (theApp
->IsConnectedED2K()) {
1498 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to eD2k.")));
1500 theApp
->serverconnect
->ConnectToAnyServer();
1501 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to eD2k...")));
1504 if (thePrefs::GetNetworkKademlia()) {
1506 response
= new CECPacket(EC_OP_STRINGS
);
1508 if (theApp
->IsConnectedKad()) {
1509 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to Kad.")));
1512 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to Kad...")));
1516 response
= new CECPacket(EC_OP_FAILED
);
1517 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("All networks are disabled.")));
1520 case EC_OP_DISCONNECT
:
1521 if (theApp
->IsConnected()) {
1522 response
= new CECPacket(EC_OP_STRINGS
);
1523 if (theApp
->IsConnectedED2K()) {
1524 theApp
->serverconnect
->Disconnect();
1525 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from eD2k.")));
1527 if (theApp
->IsConnectedKad()) {
1529 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from Kad.")));
1532 response
= new CECPacket(EC_OP_NOOP
);
1537 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request
->GetOpCode()));
1539 response
= new CECPacket(EC_OP_FAILED
);
1540 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1547 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1551 * Core general status
1553 ECStatusMsgSource::ECStatusMsgSource()
1555 m_last_ed2k_status_sent
= 0xffffffff;
1556 m_last_kad_status_sent
= 0xffffffff;
1557 m_server
= (void *)0xffffffff;
1560 uint32
ECStatusMsgSource::GetEd2kStatus()
1562 if ( theApp
->IsConnectedED2K() ) {
1563 return theApp
->GetED2KID();
1564 } else if ( theApp
->serverconnect
->IsConnecting() ) {
1571 uint32
ECStatusMsgSource::GetKadStatus()
1573 if ( theApp
->IsConnectedKad() ) {
1575 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1577 } else if ( Kademlia::CKademlia::IsRunning() ) {
1583 CECPacket
*ECStatusMsgSource::GetNextPacket()
1585 if ( (m_last_ed2k_status_sent
!= GetEd2kStatus()) ||
1586 (m_last_kad_status_sent
!= GetKadStatus()) ||
1587 (m_server
!= theApp
->serverconnect
->GetCurrentServer()) ) {
1589 m_last_ed2k_status_sent
= GetEd2kStatus();
1590 m_last_kad_status_sent
= GetKadStatus();
1591 m_server
= theApp
->serverconnect
->GetCurrentServer();
1593 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
1594 response
->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE
));
1603 ECPartFileMsgSource::ECPartFileMsgSource()
1605 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
1606 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
1607 PARTFILE_STATUS status
= { true, false, false, false, true, cur_file
};
1608 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1612 void ECPartFileMsgSource::SetDirty(CPartFile
*file
)
1614 CMD4Hash filehash
= file
->GetFileHash();
1615 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1616 m_dirty_status
[filehash
].m_dirty
= true;;
1620 void ECPartFileMsgSource::SetNew(CPartFile
*file
)
1622 CMD4Hash filehash
= file
->GetFileHash();
1623 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1624 PARTFILE_STATUS status
= { true, false, false, false, true, file
};
1625 m_dirty_status
[filehash
] = status
;
1628 void ECPartFileMsgSource::SetCompleted(CPartFile
*file
)
1630 CMD4Hash filehash
= file
->GetFileHash();
1631 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1633 m_dirty_status
[filehash
].m_finished
= true;
1636 void ECPartFileMsgSource::SetRemoved(CPartFile
*file
)
1638 CMD4Hash filehash
= file
->GetFileHash();
1639 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1641 m_dirty_status
[filehash
].m_removed
= true;
1644 CECPacket
*ECPartFileMsgSource::GetNextPacket()
1646 for(std::map
<CMD4Hash
, PARTFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
1647 it
!= m_dirty_status
.end(); it
++) {
1648 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
1649 CMD4Hash filehash
= it
->first
;
1651 CPartFile
*partfile
= it
->second
.m_file
;
1653 CECPacket
*packet
= new CECPacket(EC_OP_DLOAD_QUEUE
);
1654 if ( it
->second
.m_removed
) {
1655 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
1656 packet
->AddTag(tag
);
1657 m_dirty_status
.erase(it
);
1659 CEC_PartFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
1660 packet
->AddTag(tag
);
1662 m_dirty_status
[filehash
].m_new
= false;
1663 m_dirty_status
[filehash
].m_dirty
= false;
1672 * Notification about search status
1674 ECSearchMsgSource::ECSearchMsgSource()
1678 CECPacket
*ECSearchMsgSource::GetNextPacket()
1684 * Notification about uploading clients
1686 CECPacket
*ECClientMsgSource::GetNextPacket()
1692 // Notification iface per-client
1694 ECNotifier::ECNotifier()
1698 CECPacket
*ECNotifier::GetNextPacket(ECUpdateMsgSource
*msg_source_array
[])
1700 CECPacket
*packet
= 0;
1702 // priority 0 is highest
1704 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
1705 if ( (packet
= msg_source_array
[i
]->GetNextPacket()) != 0 ) {
1712 CECPacket
*ECNotifier::GetNextPacket(CECServerSocket
*sock
)
1715 // OnOutput is called for a first time before
1716 // socket is registered
1718 if ( m_msg_source
.count(sock
) ) {
1719 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
1720 if ( !notifier_array
) {
1723 CECPacket
*packet
= GetNextPacket(notifier_array
);
1724 printf("[EC] next update packet; opcode=%x\n",packet
? packet
->GetOpCode() : 0xff);
1732 // Interface to notification macros
1734 void ECNotifier::DownloadFile_SetDirty(CPartFile
*file
)
1736 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1737 i
!= m_msg_source
.end(); i
++) {
1738 CECServerSocket
*sock
= i
->first
;
1739 if ( sock
->HaveNotificationSupport() ) {
1740 ECUpdateMsgSource
**notifier_array
= i
->second
;
1741 ((ECPartFileMsgSource
*)notifier_array
[EC_PARTFILE
])->SetDirty(file
);
1744 NextPacketToSocket();
1747 void ECNotifier::DownloadFile_RemoveFile(CPartFile
*file
)
1749 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1750 i
!= m_msg_source
.end(); i
++) {
1751 ECUpdateMsgSource
**notifier_array
= i
->second
;
1752 ((ECPartFileMsgSource
*)notifier_array
[EC_PARTFILE
])->SetRemoved(file
);
1754 NextPacketToSocket();
1757 void ECNotifier::DownloadFile_RemoveSource(CPartFile
*)
1759 // per-partfile source list is not supported (yet), and IMHO quite useless
1762 void ECNotifier::DownloadFile_AddFile(CPartFile
*file
)
1764 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1765 i
!= m_msg_source
.end(); i
++) {
1766 ECUpdateMsgSource
**notifier_array
= i
->second
;
1767 ((ECPartFileMsgSource
*)notifier_array
[EC_PARTFILE
])->SetNew(file
);
1769 NextPacketToSocket();
1772 void ECNotifier::DownloadFile_AddSource(CPartFile
*)
1774 // per-partfile source list is not supported (yet), and IMHO quite useless
1777 void ECNotifier::Add_EC_Client(CECServerSocket
*sock
)
1779 ECUpdateMsgSource
**notifier_array
= new ECUpdateMsgSource
*[EC_STATUS_LAST_PRIO
];
1780 notifier_array
[EC_STATUS
] = new ECStatusMsgSource();
1781 notifier_array
[EC_SEARCH
] = new ECSearchMsgSource();
1782 notifier_array
[EC_PARTFILE
] = new ECPartFileMsgSource();
1783 notifier_array
[EC_CLIENT
] = new ECClientMsgSource();
1785 m_msg_source
[sock
] = notifier_array
;
1788 void ECNotifier::Remove_EC_Client(CECServerSocket
*sock
)
1790 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
1791 m_msg_source
.erase(sock
);
1793 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
1794 delete notifier_array
[i
];
1796 delete [] notifier_array
;
1799 void ECNotifier::NextPacketToSocket()
1801 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1802 i
!= m_msg_source
.end(); i
++) {
1803 CECServerSocket
*sock
= i
->first
;
1804 if ( sock
->HaveNotificationSupport() && !sock
->DataPending() ) {
1805 ECUpdateMsgSource
**notifier_array
= i
->second
;
1806 CECPacket
*packet
= GetNextPacket(notifier_array
);
1808 printf("[EC] sending update packet; opcode=%x\n",packet
->GetOpCode());
1809 sock
->SendPacket(packet
);
1815 // File_checked_for_headers