Upstream tarball 9445
[amule.git] / src / ExternalConn.cpp
blobb41d7b02a47ddd5ebdc1dd70e0c361b7c8646bc2
1 //
2 // This file is part of the aMule Project.
3 //
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)
7 //
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.
21 //
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
27 #ifdef HAVE_CONFIG_H
28 #include "config.h" // Needed for VERSION
29 #endif
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
50 #include "Logger.h"
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
63 public:
64 CECServerSocket(ECNotifier *notifier);
65 virtual ~CECServerSocket();
67 virtual const CECPacket *OnPacketReceived(const CECPacket *packet);
68 virtual void OnLost();
70 virtual void WriteDoneAndQueueEmpty();
71 private:
72 ECNotifier *m_ec_notifier;
74 const CECPacket *Authenticate(const CECPacket *);
76 enum {
77 CONN_INIT,
78 CONN_SALT_SENT,
79 CONN_ESTABLISHED,
80 CONN_FAILED
81 } m_conn_state;
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 &,
92 CObjTagMap &);
97 CECServerSocket::CECServerSocket(ECNotifier *notifier)
99 CECMuleSocket(true),
100 m_conn_state(CONN_INIT),
101 m_passwd_salt(GetRandomUint64()),
102 m_part_encoder(),
103 m_shared_encoder(),
104 m_obj_tagmap()
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."));
126 CloseSocket();
129 if (m_conn_state != CONN_ESTABLISHED) {
130 reply = Authenticate(packet);
131 if (reply->GetOpCode() == EC_OP_AUTH_FAIL) {
132 // Access denied!
133 AddLogLineM(false, _("Unauthorized access attempt. Connection closed."));
134 m_conn_state = CONN_FAILED;
135 } else {
136 theApp->ECServerHandler->m_ec_notifier->Add_EC_Client(this);
138 } else {
139 reply = ProcessRequest2(
140 packet, m_part_encoder, m_shared_encoder, m_obj_tagmap);
142 return reply;
146 void CECServerSocket::OnLost()
148 AddLogLineM(false,_("External connection closed."));
149 theApp->ECServerHandler->m_ec_notifier->Remove_EC_Client(this);
150 DestroySocket();
153 void CECServerSocket::WriteDoneAndQueueEmpty()
155 if ( HaveNotificationSupport() ) {
156 CECPacket *packet = m_ec_notifier->GetNextPacket(this);
157 if ( packet ) {
158 SendPacket(packet);
160 } else {
161 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
165 //-------------------- ExternalConn --------------------
167 enum
168 { // id for sockets
169 SERVER_ID = 1000
173 BEGIN_EVENT_TABLE(ExternalConn, wxEvtHandler)
174 EVT_SOCKET(SERVER_ID, ExternalConn::OnServerEvent)
175 END_EVENT_TABLE()
178 ExternalConn::ExternalConn(amuleIPV4Address addr, wxString *msg)
180 wxString msgLocal;
181 m_ECServer = NULL;
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!"));
188 return;
191 // Create the socket
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);
204 } else {
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);
210 } else {
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()
220 KillAllSockets();
221 delete m_ECServer;
222 delete m_ec_notifier;
226 void ExternalConn::AddSocket(CECServerSocket *s)
228 wxASSERT(s);
229 socket_list.insert(s);
233 void ExternalConn::RemoveSocket(CECServerSocket *s)
235 wxASSERT(s);
236 socket_list.erase(s);
240 void ExternalConn::KillAllSockets()
242 AddDebugLogLineM(false, logGeneral,
243 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
244 socket_list.size());
245 SocketSet::iterator it = socket_list.begin();
246 while (it != socket_list.end()) {
247 CECServerSocket *s = *(it++);
248 s->Close();
249 s->Destroy();
250 delete s;
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"));
264 } else {
265 delete sock;
266 AddLogLineM(false, _("ERROR: couldn't accept a new external connection"));
272 // Authentication
274 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
276 CECPacket *response;
278 if (request == NULL) {
279 response = new CECPacket(EC_OP_AUTH_FAIL);
280 return response;
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);
298 #ifdef EC_VERSION_ID
299 // For SVN versions, both client and server must use SVNDATE, and they must be the same
300 CMD4Hash vhash;
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.")));
307 #else
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")));
312 #endif
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;
319 } else {
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)));
323 } else {
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);
329 CMD4Hash passh;
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.")));
335 } else {
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)));
344 } else {
345 if (passwd) {
346 AddLogLineM(false, wxT("EC Auth failed: (") + passwd->GetMD4Data().Encode() + wxT(" != ") + passh.Encode() + wxT(")."));
347 } else {
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.")));
355 } else {
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()));
367 return response;
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
377 int entries = 0;
378 wxString line;
379 while (entries < 200 && LoggerAccess.GetString(line)) {
380 tag.AddTag(CECTag(EC_TAG_STRING, line));
381 entries++;
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()) {
393 case EC_DETAIL_FULL:
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);
398 case EC_DETAIL_WEB:
399 case EC_DETAIL_CMD:
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()));
406 // User/Filecounts
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()));
415 // Kad stats
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()));
424 uint32 BuddyIP = 0;
425 uint16 BuddyPort = 0;
426 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
427 if (Buddy) {
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:
436 break;
439 return response;
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())) ) {
459 continue;
462 CEC_SharedFile_Tag filetag(cur_file, detail_level);
463 CKnownFile_Encoder &enc = encoders[cur_file];
464 if ( detail_level != EC_DETAIL_UPDATE ) {
465 enc.ResetEncoder();
467 enc.Encode(&filetag);
468 response->AddTag(filetag);
470 return response;
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);
496 return response;
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())) ) {
517 continue;
519 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level);
521 response->AddTag(cli_tag);
524 return response;
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);
542 return response;
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())) ) {
564 continue;
567 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level);
568 response->AddTag(cli_tag);
571 return response;
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);
590 return response;
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);
609 return response;
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()) ) {
627 continue;
630 CEC_PartFile_Tag filetag(cur_file, detail_level, detail);
632 CPartFile_Encoder &enc = encoders[cur_file];
633 if ( detail_level != EC_DETAIL_UPDATE ) {
634 enc.ResetEncoder();
636 enc.Encode(&filetag);
638 response->AddTag(filetag);
640 return response;
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 );
657 if ( !pfile ) {
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()));
661 //return response;
662 break;
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);
675 break;
676 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
677 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
678 break;
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);
689 break;
690 case EC_OP_PARTFILE_PAUSE:
691 pfile->PauseFile();
692 break;
693 case EC_OP_PARTFILE_RESUME:
694 pfile->ResumeFile();
695 pfile->SavePartFile();
696 break;
697 case EC_OP_PARTFILE_STOP:
698 pfile->StopFile();
699 break;
700 case EC_OP_PARTFILE_PRIO_SET: {
701 uint8 prio = hashtag->GetTagByIndexSafe(0)->GetInt();
702 if ( prio == PR_AUTO ) {
703 pfile->SetAutoDownPriority(1);
704 } else {
705 pfile->SetAutoDownPriority(0);
706 pfile->SetDownPriority(prio);
709 break;
710 case EC_OP_PARTFILE_DELETE:
711 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
712 theApp->downloadqueue->StartNextFile(pfile);
714 pfile->Delete();
715 break;
717 case EC_OP_PARTFILE_SET_CAT:
718 pfile->SetCategory(hashtag->GetTagByIndexSafe(0)->GetInt());
719 break;
721 default:
722 response = new CECPacket(EC_OP_FAILED);
723 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
724 break;
727 if (!response) {
728 response = new CECPacket(EC_OP_NOOP);
730 return response;
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);
751 } else {
752 response = new CECPacket(EC_OP_FAILED);
753 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
754 delete toadd;
757 return response;
760 CECPacket *Get_EC_Response_Server(const CECPacket *request)
762 CECPacket *response = NULL;
763 const CECTag *srv_tag = request->GetTagByIndex(0);
764 CServer *srv = 0;
765 if ( srv_tag ) {
766 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
767 // server tag passed, but server not found
768 if ( !srv ) {
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()));
772 return response;
775 switch (request->GetOpCode()) {
776 case EC_OP_SERVER_DISCONNECT:
777 theApp->serverconnect->Disconnect();
778 response = new CECPacket(EC_OP_NOOP);
779 break;
780 case EC_OP_SERVER_REMOVE:
781 if ( srv ) {
782 theApp->serverlist->RemoveServer(srv);
783 response = new CECPacket(EC_OP_NOOP);
784 } else {
785 response = new CECPacket(EC_OP_FAILED);
786 response->AddTag(CECTag(EC_TAG_STRING,
787 wxTRANSLATE("need to define server to be removed")));
789 break;
790 case EC_OP_SERVER_CONNECT:
791 if (thePrefs::GetNetworkED2K()) {
792 if ( srv ) {
793 theApp->serverconnect->ConnectToServer(srv);
794 response = new CECPacket(EC_OP_NOOP);
795 } else {
796 theApp->serverconnect->ConnectToAnyServer();
797 response = new CECPacket(EC_OP_NOOP);
799 } else {
800 response = new CECPacket(EC_OP_FAILED);
801 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
803 break;
805 if (!response) {
806 response = new CECPacket(EC_OP_FAILED);
807 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
809 return response;
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()) ) {
826 continue;
828 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
830 return response;
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));
844 return response;
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);
856 return response;
859 CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
861 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
862 theApp->searchlist->StopGlobalSearch();
863 return reply;
866 CECPacket *Get_EC_Response_Search(const CECPacket *request)
868 wxString response;
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;
887 case EC_SEARCH_KAD:
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()) {
895 response = error;
896 } else {
897 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
899 break;
901 case EC_SEARCH_WEB:
902 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
903 break;
906 CECPacket *reply = new CECPacket(EC_OP_FAILED);
907 // error or search in progress
908 reply->AddTag(CECTag(EC_TAG_STRING, response));
910 return reply;
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);
921 if ( !cur_file ) {
922 continue;
924 if (prio == PR_AUTO) {
925 cur_file->SetAutoUpPriority(1);
926 cur_file->UpdateAutoUpPriority();
927 } else {
928 cur_file->SetAutoUpPriority(0);
929 cur_file->SetUpPriority(prio);
933 return response;
936 CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
938 CECPacket *response;
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);
946 if ( addrtag ) {
947 uint32 ip = addrtag->GetIPv4Data().IP();
948 uint16 port = addrtag->GetIPv4Data().m_port;
949 Kademlia::CKademlia::Bootstrap(ip, port, true);
951 } else {
952 response = new CECPacket(EC_OP_FAILED);
953 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
956 return response;
959 // init with some default size
960 CPartFile_Encoder::GapBuffer CPartFile_Encoder::m_gap_buffer(128);
962 // encoder side
963 CPartFile_Encoder::CPartFile_Encoder(CPartFile *file) :
964 m_enc_data(file->GetPartCount(), file->GetGapList().size() * 2)
966 m_file = file;
969 // decoder side
970 CPartFile_Encoder::CPartFile_Encoder(int size): m_enc_data(size, 0)
972 m_file = 0;
975 CPartFile_Encoder::~CPartFile_Encoder()
979 // stl side :)
980 CPartFile_Encoder::CPartFile_Encoder()
982 m_file = 0;
985 CPartFile_Encoder::CPartFile_Encoder(const CPartFile_Encoder &obj) : m_enc_data(obj.m_enc_data)
987 m_file = obj.m_file;
990 CPartFile_Encoder &CPartFile_Encoder::operator=(const CPartFile_Encoder &obj)
992 m_file = obj.m_file;
993 m_enc_data = obj.m_enc_data;
994 return *this;
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);
1018 int part_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]));
1054 // encoder side
1055 CKnownFile_Encoder::CKnownFile_Encoder(CKnownFile *file) :
1056 m_enc_data(file->GetPartCount(), true)
1058 m_file = file;
1061 CKnownFile_Encoder::CKnownFile_Encoder()
1063 m_file = 0;
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;
1079 return *this;
1082 void CKnownFile_Encoder::Encode(CECTag *parent)
1084 int part_enc_size;
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()) {
1095 case EC_DETAIL_WEB:
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();
1103 uint32 *graphData;
1104 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1105 if (numPoints) {
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));
1110 } else {
1111 response = new CECPacket(EC_OP_FAILED);
1112 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1114 break;
1116 case EC_DETAIL_INC_UPDATE:
1117 case EC_DETAIL_UPDATE:
1118 case EC_DETAIL_CMD:
1119 // No graphs
1120 response = new CECPacket(EC_OP_FAILED);
1121 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1122 break;
1124 if (!response) {
1125 response = new CECPacket(EC_OP_FAILED);
1126 // Unknown reason
1129 return response;
1132 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request,
1133 CPartFile_Encoder_Map &enc_part_map, CKnownFile_Encoder_Map &enc_shared_map, CObjTagMap &objmap)
1136 if ( !request ) {
1137 return 0;
1140 CECPacket *response = NULL;
1142 switch (request->GetOpCode()) {
1144 // Misc commands
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
1152 wxCloseEvent evt;
1153 evt.SetCanVeto(false);
1154 theApp->ShutDown(evt);
1156 #else
1157 theApp->ExitMainLoop();
1158 #endif
1159 } else {
1160 response = new CECPacket(EC_OP_FAILED);
1161 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1163 break;
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);
1172 } else {
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.")));
1178 break;
1180 // Status requests
1182 case EC_OP_STAT_REQ:
1183 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1184 break;
1185 case EC_OP_GET_CONNSTATE:
1186 if (!response) {
1187 response = new CECPacket(EC_OP_MISC_DATA);
1189 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1190 break;
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);
1197 } else {
1198 response = Get_EC_Response_GetSharedFiles(request, enc_shared_map);
1200 break;
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);
1204 } else {
1205 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map);
1207 break;
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);
1212 } else {
1213 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map, true);
1215 break;
1216 case EC_OP_GET_ULOAD_QUEUE:
1217 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1218 response = Get_EC_Response_GetUpQueue(objmap);
1219 } else {
1220 response = Get_EC_Response_GetUpQueue(request);
1222 break;
1223 case EC_OP_GET_WAIT_QUEUE:
1224 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1225 response = Get_EC_Response_GetWaitQueue(objmap);
1226 } else {
1227 response = Get_EC_Response_GetWaitQueue(request);
1229 break;
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);
1244 break;
1245 case EC_OP_SHAREDFILES_RELOAD:
1246 theApp->sharedfiles->Reload();
1247 response = new CECPacket(EC_OP_NOOP);
1248 break;
1249 case EC_OP_SHARED_SET_PRIO:
1250 response = Get_EC_Response_Set_SharedFile_Prio(request);
1251 break;
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();
1256 if (!file) {
1257 file = theApp->downloadqueue->GetFileByID(fileHash);
1259 if (!file) {
1260 response = new CECPacket(EC_OP_FAILED);
1261 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1262 break;
1264 if (newName.IsEmpty()) {
1265 response = new CECPacket(EC_OP_FAILED);
1266 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1267 break;
1270 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1271 response = new CECPacket(EC_OP_NOOP);
1272 } else {
1273 response = new CECPacket(EC_OP_FAILED);
1274 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1277 break;
1282 // Server commands
1284 case EC_OP_SERVER_ADD:
1285 response = Get_EC_Response_Server_Add(request);
1286 break;
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);
1291 break;
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();
1296 for (
1297 std::vector<const CServer*>::const_iterator it = servers.begin();
1298 it != servers.end();
1299 ++it
1301 response->AddTag(CEC_Server_Tag(*it, detail_level));
1304 break;
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);
1314 break;
1317 // IPFilter
1319 case EC_OP_IPFILTER_RELOAD:
1320 theApp->ipfilter->Reload();
1321 response = new CECPacket(EC_OP_NOOP);
1322 break;
1324 // Search
1326 case EC_OP_SEARCH_START:
1327 response = Get_EC_Response_Search(request);
1328 break;
1330 case EC_OP_SEARCH_STOP:
1331 response = Get_EC_Response_Search_Stop(request);
1332 break;
1334 case EC_OP_SEARCH_RESULTS:
1335 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1336 response = Get_EC_Response_Search_Results(objmap);
1337 } else {
1338 response = Get_EC_Response_Search_Results(request);
1340 break;
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()));
1346 break;
1348 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1349 response = Get_EC_Response_Search_Results_Download(request);
1350 break;
1352 // Preferences
1354 case EC_OP_GET_PREFERENCES:
1355 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1356 break;
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()) {
1370 theApp->StopKad();
1372 response = new CECPacket(EC_OP_NOOP);
1373 break;
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);
1381 break;
1382 case EC_OP_UPDATE_CATEGORY:
1383 if ( request->GetTagCount() == 1 ) {
1384 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetTagByIndex(0);
1385 tag->Apply();
1386 Notify_CategoryUpdate(tag->GetInt());
1388 response = new CECPacket(EC_OP_NOOP);
1389 break;
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);
1396 break;
1399 // Logging
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);
1404 break;
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);
1408 break;
1409 case EC_OP_GET_LOG:
1410 response = new CECPacket(EC_OP_LOG);
1411 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1412 break;
1413 case EC_OP_GET_DEBUGLOG:
1414 response = new CECPacket(EC_OP_DEBUGLOG);
1415 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1416 break;
1417 case EC_OP_RESET_LOG:
1418 theApp->GetLog(true);
1419 response = new CECPacket(EC_OP_NOOP);
1420 break;
1421 case EC_OP_RESET_DEBUGLOG:
1422 theApp->GetDebugLog(true);
1423 response = new CECPacket(EC_OP_NOOP);
1424 break;
1425 case EC_OP_GET_LAST_LOG_ENTRY:
1427 wxString tmp = theApp->GetLog(false);
1428 if (tmp.Last() == '\n') {
1429 tmp.RemoveLast();
1431 response = new CECPacket(EC_OP_LOG);
1432 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1434 break;
1435 case EC_OP_GET_SERVERINFO:
1436 response = new CECPacket(EC_OP_SERVERINFO);
1437 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1438 break;
1439 case EC_OP_CLEAR_SERVERINFO:
1440 theApp->GetServerLog(true);
1441 response = new CECPacket(EC_OP_NOOP);
1442 break;
1444 // Statistics
1446 case EC_OP_GET_STATSGRAPHS:
1447 response = GetStatsGraphs(request);
1448 break;
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());
1453 if (tree) {
1454 response->AddTag(*tree);
1455 delete 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()));
1461 break;
1465 // Kad
1467 case EC_OP_KAD_START:
1468 response = Get_EC_Response_Kad_Connect(request);
1469 break;
1470 case EC_OP_KAD_STOP:
1471 theApp->StopKad();
1472 response = new CECPacket(EC_OP_NOOP);
1473 break;
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);
1483 break;
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);
1489 break;
1492 // Networks
1494 case EC_OP_CONNECT:
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.")));
1499 } else {
1500 theApp->serverconnect->ConnectToAnyServer();
1501 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1504 if (thePrefs::GetNetworkKademlia()) {
1505 if (!response) {
1506 response = new CECPacket(EC_OP_STRINGS);
1508 if (theApp->IsConnectedKad()) {
1509 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1510 } else {
1511 theApp->StartKad();
1512 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1515 if (!response) {
1516 response = new CECPacket(EC_OP_FAILED);
1517 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1519 break;
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()) {
1528 theApp->StopKad();
1529 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1531 } else {
1532 response = new CECPacket(EC_OP_NOOP);
1534 break;
1536 default:
1537 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1538 wxFAIL;
1539 response = new CECPacket(EC_OP_FAILED);
1540 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1541 break;
1543 return response;
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() ) {
1565 return 1;
1566 } else {
1567 return 0;
1571 uint32 ECStatusMsgSource::GetKadStatus()
1573 if ( theApp->IsConnectedKad() ) {
1574 return 1;
1575 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1576 return 2;
1577 } else if ( Kademlia::CKademlia::IsRunning() ) {
1578 return 3;
1580 return 0;
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));
1595 return response;
1597 return 0;
1601 * Downloading files
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);
1658 } else {
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;
1665 return packet;
1668 return 0;
1672 * Notification about search status
1674 ECSearchMsgSource::ECSearchMsgSource()
1678 CECPacket *ECSearchMsgSource::GetNextPacket()
1680 return 0;
1684 * Notification about uploading clients
1686 CECPacket *ECClientMsgSource::GetNextPacket()
1688 return 0;
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 ) {
1706 break;
1709 return packet;
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 ) {
1721 return 0;
1723 CECPacket *packet = GetNextPacket(notifier_array);
1724 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1725 return packet;
1726 } else {
1727 return 0;
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);
1807 if ( packet ) {
1808 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
1809 sock->SendPacket(packet);
1815 // File_checked_for_headers