Add EC for the Remote GUI's tray icon right-click menu data
[amule.git] / src / ExternalConn.cpp
blob081ed4d4607492da9c040cb599034dcba25be58f
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2011 Kry ( elkry@sourceforge.net / http://www.amule.org )
5 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Copyright (c) 2008-2011 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 "ClientList.h"
48 #include "Preferences.h" // Needed for CPreferences
49 #include "Logger.h"
50 #include "GuiEvents.h" // Needed for Notify_* macros
51 #include "Statistics.h" // Needed for theStats
52 #include "KnownFileList.h" // Needed for CKnownFileList
53 #include "Friend.h"
54 #include "FriendList.h"
55 #include "RandomFunctions.h"
56 #include "kademlia/kademlia/Kademlia.h"
57 #include "kademlia/kademlia/UDPFirewallTester.h"
60 //-------------------- File_Encoder --------------------
64 * Encode 'obtained parts' info to be sent to remote gui
66 class CKnownFile_Encoder {
67 // number of sources for each part for progress bar colouring
68 RLE_Data m_enc_data;
69 protected:
70 const CKnownFile *m_file;
71 public:
72 CKnownFile_Encoder(const CKnownFile *file = 0) { m_file = file; }
74 virtual ~CKnownFile_Encoder() {}
76 virtual void Encode(CECTag *parent_tag);
78 virtual void ResetEncoder()
80 m_enc_data.ResetEncoder();
83 virtual void SetShared() { }
84 virtual bool IsShared() { return true; }
85 virtual bool IsPartFile_Encoder() { return false; }
86 const CKnownFile * GetFile() { return m_file; }
89 /*!
90 * PartStatus strings and gap lists are quite long - RLE encoding will help.
92 * Instead of sending each time full part-status string, send
93 * RLE encoded difference from previous one.
95 * PartFileEncoderData class is used for decode only,
96 * while CPartFile_Encoder is used for encode only.
98 class CPartFile_Encoder : public CKnownFile_Encoder {
99 // blocks requested for download
100 RLE_Data m_req_status;
101 // gap list
102 RLE_Data m_gap_status;
103 // source names
104 SourcenameItemMap m_sourcenameItemMap;
105 // counter for unique source name ids
106 int m_sourcenameID;
107 // not all part files are shared (only when at least one part is complete)
108 bool m_shared;
110 // cast inherited member to CPartFile
111 CPartFile * m_PartFile() { wxASSERT(m_file->IsCPartFile()); return (CPartFile *)m_file; }
112 public:
113 // encoder side
114 CPartFile_Encoder(const CPartFile *file = 0) : CKnownFile_Encoder(file)
116 m_sourcenameID = 0;
117 m_shared = false;
120 virtual ~CPartFile_Encoder() {}
122 // encode - take data from m_file
123 virtual void Encode(CECTag *parent_tag);
125 // Encoder may reset history if full info requested
126 virtual void ResetEncoder();
128 virtual void SetShared() { m_shared = true; }
129 virtual bool IsShared() { return m_shared; }
130 virtual bool IsPartFile_Encoder() { return true; }
133 class CFileEncoderMap : public std::map<uint32, CKnownFile_Encoder*> {
134 typedef std::set<uint32> IDSet;
135 public:
136 ~CFileEncoderMap();
137 void UpdateEncoders();
140 CFileEncoderMap::~CFileEncoderMap()
142 // DeleteContents() causes infinite recursion here!
143 for (iterator it = begin(); it != end(); it++) {
144 delete it->second;
148 // Check if encoder contains files that are no longer used
149 // or if we have new files without encoder yet.
150 void CFileEncoderMap::UpdateEncoders()
152 IDSet curr_files, dead_files;
153 // Downloads
154 std::vector<CPartFile*> downloads;
155 theApp->downloadqueue->CopyFileList(downloads, true);
156 for (uint32 i = downloads.size(); i--;) {
157 uint32 id = downloads[i]->ECID();
158 curr_files.insert(id);
159 if (!count(id)) {
160 (*this)[id] = new CPartFile_Encoder(downloads[i]);
163 // Shares
164 std::vector<CKnownFile*> shares;
165 theApp->sharedfiles->CopyFileList(shares);
166 for (uint32 i = shares.size(); i--;) {
167 uint32 id = shares[i]->ECID();
168 // Check if it is already there.
169 // The curr_files.count(id) is enough, the IsCPartFile() is just a speedup.
170 if (shares[i]->IsCPartFile() && curr_files.count(id)) {
171 (*this)[id]->SetShared();
172 continue;
174 curr_files.insert(id);
175 if (!count(id)) {
176 (*this)[id] = new CKnownFile_Encoder(shares[i]);
179 // Check for removed files, and store them in a set for deletion.
180 // (std::map documentation is unclear if a construct like
181 // iterator to_del = it++; erase(to_del) ;
182 // works or invalidates it too.)
183 for (iterator it = begin(); it != end(); it++) {
184 if (!curr_files.count(it->first)) {
185 dead_files.insert(it->first);
188 // then delete them
189 for (IDSet::iterator it = dead_files.begin(); it != dead_files.end(); it++) {
190 iterator it2 = find(*it);
191 delete it2->second;
192 erase(it2);
197 //-------------------- CECServerSocket --------------------
199 class CECServerSocket : public CECMuleSocket
201 public:
202 CECServerSocket(ECNotifier *notifier);
203 virtual ~CECServerSocket();
205 virtual const CECPacket *OnPacketReceived(const CECPacket *packet, uint32 trueSize);
206 virtual void OnLost();
208 virtual void WriteDoneAndQueueEmpty();
210 void ResetLog() { m_LoggerAccess.Reset(); }
211 private:
212 ECNotifier *m_ec_notifier;
214 const CECPacket *Authenticate(const CECPacket *);
216 enum {
217 CONN_INIT,
218 CONN_SALT_SENT,
219 CONN_ESTABLISHED,
220 CONN_FAILED
221 } m_conn_state;
223 uint64_t m_passwd_salt;
224 CLoggerAccess m_LoggerAccess;
225 CFileEncoderMap m_FileEncoder;
226 CObjTagMap m_obj_tagmap;
227 CECPacket *ProcessRequest2(const CECPacket *request);
229 virtual bool IsAuthorized() { return m_conn_state == CONN_ESTABLISHED; }
233 CECServerSocket::CECServerSocket(ECNotifier *notifier)
235 CECMuleSocket(true),
236 m_conn_state(CONN_INIT),
237 m_passwd_salt(GetRandomUint64())
239 wxASSERT(theApp->ECServerHandler);
240 theApp->ECServerHandler->AddSocket(this);
241 m_ec_notifier = notifier;
245 CECServerSocket::~CECServerSocket()
247 wxASSERT(theApp->ECServerHandler);
248 theApp->ECServerHandler->RemoveSocket(this);
252 const CECPacket *CECServerSocket::OnPacketReceived(const CECPacket *packet, uint32 trueSize)
254 packet->DebugPrint(true, trueSize);
256 const CECPacket *reply = NULL;
258 if (m_conn_state == CONN_FAILED) {
259 // Client didn't close the socket when authentication failed.
260 AddLogLineN(_("Client sent packet after authentication failed."));
261 CloseSocket();
264 if (m_conn_state != CONN_ESTABLISHED) {
265 // This is called twice:
266 // 1) send salt
267 // 2) verify password
268 reply = Authenticate(packet);
269 } else {
270 reply = ProcessRequest2(packet);
272 return reply;
276 void CECServerSocket::OnLost()
278 AddLogLineN(_("External connection closed."));
279 theApp->ECServerHandler->m_ec_notifier->Remove_EC_Client(this);
280 DestroySocket();
283 void CECServerSocket::WriteDoneAndQueueEmpty()
285 if ( HaveNotificationSupport() && (m_conn_state == CONN_ESTABLISHED) ) {
286 CECPacket *packet = m_ec_notifier->GetNextPacket(this);
287 if ( packet ) {
288 SendPacket(packet);
290 } else {
291 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
295 //-------------------- ExternalConn --------------------
297 enum
298 { // id for sockets
299 SERVER_ID = 1000
303 BEGIN_EVENT_TABLE(ExternalConn, wxEvtHandler)
304 EVT_SOCKET(SERVER_ID, ExternalConn::OnServerEvent)
305 END_EVENT_TABLE()
308 ExternalConn::ExternalConn(amuleIPV4Address addr, wxString *msg)
310 wxString msgLocal;
311 m_ECServer = NULL;
312 // Are we allowed to accept External Connections?
313 if ( thePrefs::AcceptExternalConnections() ) {
314 // We must have a valid password, otherwise we will not allow EC connections
315 if (thePrefs::ECPassword().IsEmpty()) {
316 *msg += wxT("External connections disabled due to empty password!\n");
317 AddLogLineC(_("External connections disabled due to empty password!"));
318 return;
321 // Create the socket
322 m_ECServer = new wxSocketServer(addr, wxSOCKET_REUSEADDR);
323 m_ECServer->SetEventHandler(*this, SERVER_ID);
324 m_ECServer->SetNotify(wxSOCKET_CONNECTION_FLAG);
325 m_ECServer->Notify(true);
327 int port = addr.Service();
328 wxString ip = addr.IPAddress();
329 if (m_ECServer->Ok()) {
330 msgLocal = CFormat(wxT("*** TCP socket (ECServer) listening on %s:%d")) % ip % port;
331 *msg += msgLocal + wxT("\n");
332 AddLogLineN(msgLocal);
333 } else {
334 msgLocal = CFormat(wxT("Could not listen for external connections at %s:%d!")) % ip % port;
335 *msg += msgLocal + wxT("\n");
336 AddLogLineN(msgLocal);
338 } else {
339 *msg += wxT("External connections disabled in config file\n");
340 AddLogLineN(_("External connections disabled in config file"));
342 m_ec_notifier = new ECNotifier();
346 ExternalConn::~ExternalConn()
348 KillAllSockets();
349 delete m_ECServer;
350 delete m_ec_notifier;
354 void ExternalConn::AddSocket(CECServerSocket *s)
356 wxASSERT(s);
357 socket_list.insert(s);
361 void ExternalConn::RemoveSocket(CECServerSocket *s)
363 wxASSERT(s);
364 socket_list.erase(s);
368 void ExternalConn::KillAllSockets()
370 AddDebugLogLineN(logGeneral,
371 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
372 socket_list.size());
373 SocketSet::iterator it = socket_list.begin();
374 while (it != socket_list.end()) {
375 CECServerSocket *s = *(it++);
376 s->Close();
377 s->Destroy();
382 void ExternalConn::ResetAllLogs()
384 SocketSet::iterator it = socket_list.begin();
385 while (it != socket_list.end()) {
386 CECServerSocket *s = *(it++);
387 s->ResetLog();
392 void ExternalConn::OnServerEvent(wxSocketEvent& WXUNUSED(event))
394 CECServerSocket *sock = new CECServerSocket(m_ec_notifier);
395 // Accept new connection if there is one in the pending
396 // connections queue, else exit. We use Accept(FALSE) for
397 // non-blocking accept (although if we got here, there
398 // should ALWAYS be a pending connection).
399 if ( m_ECServer->AcceptWith(*sock, false) ) {
400 AddLogLineN(_("New external connection accepted"));
401 } else {
402 delete sock;
403 AddLogLineN(_("ERROR: couldn't accept a new external connection"));
409 // Authentication
411 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
413 CECPacket *response;
415 if (request == NULL) {
416 return new CECPacket(EC_OP_AUTH_FAIL);
419 // Password must be specified if we are to allow remote connections
420 if ( thePrefs::ECPassword().IsEmpty() ) {
421 AddLogLineC(_("External connection refused due to empty password in preferences!"));
423 return new CECPacket(EC_OP_AUTH_FAIL);
426 if ((m_conn_state == CONN_INIT) && (request->GetOpCode() == EC_OP_AUTH_REQ) ) {
427 const CECTag *clientName = request->GetTagByName(EC_TAG_CLIENT_NAME);
428 const CECTag *clientVersion = request->GetTagByName(EC_TAG_CLIENT_VERSION);
430 AddLogLineN(CFormat( _("Connecting client: %s %s") )
431 % ( clientName ? clientName->GetStringData() : wxString(_("Unknown")) )
432 % ( clientVersion ? clientVersion->GetStringData() : wxString(_("Unknown version")) ) );
433 const CECTag *protocol = request->GetTagByName(EC_TAG_PROTOCOL_VERSION);
434 #ifdef EC_VERSION_ID
435 // For SVN versions, both client and server must use SVNDATE, and they must be the same
436 CMD4Hash vhash;
437 if (!vhash.Decode(wxT(EC_VERSION_ID))) {
438 response = new CECPacket(EC_OP_AUTH_FAIL);
439 response->AddTag(CECTag(EC_TAG_STRING, wxT("Fatal error, version hash is not a valid MD4-hash.")));
440 } else if (!request->GetTagByName(EC_TAG_VERSION_ID) || request->GetTagByNameSafe(EC_TAG_VERSION_ID)->GetMD4Data() != vhash) {
441 response = new CECPacket(EC_OP_AUTH_FAIL);
442 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
443 #else
444 // For release versions, we don't want to allow connections from any arbitrary SVN client.
445 if (request->GetTagByName(EC_TAG_VERSION_ID)) {
446 response = new CECPacket(EC_OP_AUTH_FAIL);
447 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("You cannot connect to a release version from an arbitrary development snapshot! *sigh* possible crash prevented")));
448 #endif
449 } else if (protocol != NULL) {
450 uint16 proto_version = protocol->GetInt();
451 if (proto_version == EC_CURRENT_PROTOCOL_VERSION) {
452 response = new CECPacket(EC_OP_AUTH_SALT);
453 response->AddTag(CECTag(EC_TAG_PASSWD_SALT, m_passwd_salt));
454 m_conn_state = CONN_SALT_SENT;
456 // So far ok, check capabilities of client
458 bool canZLIB = false, canUTF8numbers = false;
459 if (request->GetTagByName(EC_TAG_CAN_ZLIB)) {
460 canZLIB = true;
461 m_my_flags |= EC_FLAG_ZLIB;
463 if (request->GetTagByName(EC_TAG_CAN_UTF8_NUMBERS)) {
464 canUTF8numbers = true;
465 m_my_flags |= EC_FLAG_UTF8_NUMBERS;
467 m_haveNotificationSupport = request->GetTagByName(EC_TAG_CAN_NOTIFY) != NULL;
468 AddDebugLogLineN(logEC, CFormat(wxT("Client capabilities: ZLIB: %s UTF8 numbers: %s Push notification: %s") )
469 % (canZLIB ? wxT("yes") : wxT("no"))
470 % (canUTF8numbers ? wxT("yes") : wxT("no"))
471 % (m_haveNotificationSupport ? wxT("yes") : wxT("no")));
472 } else {
473 response = new CECPacket(EC_OP_AUTH_FAIL);
474 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid protocol version.")
475 + CFormat(wxT("( %#.4x != %#.4x )")) % proto_version % (uint16_t)EC_CURRENT_PROTOCOL_VERSION));
477 } else {
478 response = new CECPacket(EC_OP_AUTH_FAIL);
479 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Missing protocol version tag.")));
481 } else if ((m_conn_state == CONN_SALT_SENT) && (request->GetOpCode() == EC_OP_AUTH_PASSWD)) {
482 const CECTag *passwd = request->GetTagByName(EC_TAG_PASSWD_HASH);
483 CMD4Hash passh;
485 if (!passh.Decode(thePrefs::ECPassword())) {
486 wxString err = wxTRANSLATE("Authentication failed: invalid hash specified as EC password.");
487 AddLogLineN(wxString(wxGetTranslation(err))
488 + wxT(" ") + thePrefs::ECPassword());
489 response = new CECPacket(EC_OP_AUTH_FAIL);
490 response->AddTag(CECTag(EC_TAG_STRING, err));
491 } else {
492 wxString saltHash = MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt).GetHash();
493 wxString saltStr = CFormat(wxT("%lX")) % m_passwd_salt;
495 passh.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash).GetHash());
497 if (passwd && passwd->GetMD4Data() == passh) {
498 response = new CECPacket(EC_OP_AUTH_OK);
499 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
500 } else {
501 wxString err;
502 if (passwd) {
503 err = wxTRANSLATE("Authentication failed: wrong password.");
504 } else {
505 err = wxTRANSLATE("Authentication failed: missing password.");
508 response = new CECPacket(EC_OP_AUTH_FAIL);
509 response->AddTag(CECTag(EC_TAG_STRING, err));
510 AddLogLineN(wxGetTranslation(err));
513 } else {
514 response = new CECPacket(EC_OP_AUTH_FAIL);
515 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid request, please authenticate first.")));
518 if (response->GetOpCode() == EC_OP_AUTH_OK) {
519 m_conn_state = CONN_ESTABLISHED;
520 AddLogLineN(_("Access granted."));
521 // Establish notification handler if client supports it
522 if (HaveNotificationSupport()) {
523 theApp->ECServerHandler->m_ec_notifier->Add_EC_Client(this);
525 } else if (response->GetOpCode() == EC_OP_AUTH_FAIL) {
526 // Log message sent to client
527 if (response->GetFirstTagSafe()->IsString()) {
528 AddLogLineN(CFormat(_("Sent error message \"%s\" to client.")) % wxGetTranslation(response->GetFirstTagSafe()->GetStringData()));
530 // Access denied!
531 amuleIPV4Address address;
532 GetPeer(address);
533 AddLogLineN(CFormat(_("Unauthorized access attempt from %s. Connection closed.")) % address.IPAddress() );
534 m_conn_state = CONN_FAILED;
537 return response;
540 // Make a Logger tag (if there are any logging messages) and add it to the response
541 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
543 if (LoggerAccess.HasString()) {
544 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
545 // Tag structure is fix: tag carries nothing, inside are the strings
546 // maximum of 200 log lines per message
547 int entries = 0;
548 wxString line;
549 while (entries < 200 && LoggerAccess.GetString(line)) {
550 tag.AddTag(CECTag(EC_TAG_STRING, line));
551 entries++;
553 response->AddTag(tag);
554 //printf("send Log tag %d %d\n", FirstEntry, entries);
558 static CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
560 CECPacket *response = new CECPacket(EC_OP_STATS);
562 switch (request->GetDetailLevel()) {
563 case EC_DETAIL_FULL:
564 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
565 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
566 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
567 AddLoggerTag(response, LoggerAccess);
568 // Needed only for the remote tray icon context menu
569 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SENT_BYTES, theStats::GetTotalSentBytes()));
570 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_RECEIVED_BYTES, theStats::GetTotalReceivedBytes()));
571 response->AddTag(CECTag(EC_TAG_STATS_SHARED_FILE_COUNT, theStats::GetSharedFileCount()));
572 case EC_DETAIL_WEB:
573 case EC_DETAIL_CMD:
574 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
575 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
576 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
577 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
578 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
579 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
580 // User/Filecounts
582 uint32 totaluser = 0, totalfile = 0;
583 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
584 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
585 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
586 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
587 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
589 // Kad stats
590 if (Kademlia::CKademlia::IsConnected()) {
591 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
592 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
593 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
594 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
595 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
596 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
597 response->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE, Kademlia::CKademlia::IsRunningInLANMode()));
598 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
599 uint32 BuddyIP = 0;
600 uint16 BuddyPort = 0;
601 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
602 if (Buddy) {
603 BuddyIP = Buddy->GetIP();
604 BuddyPort = Buddy->GetUDPPort();
606 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
607 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
609 case EC_DETAIL_UPDATE:
610 case EC_DETAIL_INC_UPDATE:
611 break;
614 return response;
617 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CFileEncoderMap &encoders)
619 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
621 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
623 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
625 // request can contain list of queried items
626 CTagSet<uint32, EC_TAG_KNOWNFILE> queryitems(request);
628 encoders.UpdateEncoders();
630 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
631 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
633 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->ECID())) ) {
634 continue;
637 CEC_SharedFile_Tag filetag(cur_file, detail_level);
638 CKnownFile_Encoder *enc = encoders[cur_file->ECID()];
639 if ( detail_level != EC_DETAIL_UPDATE ) {
640 enc->ResetEncoder();
642 enc->Encode(&filetag);
643 response->AddTag(filetag);
645 return response;
648 static CECPacket *Get_EC_Response_GetUpdate(CFileEncoderMap &encoders, CObjTagMap &tagmap)
650 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
652 encoders.UpdateEncoders();
653 for (CFileEncoderMap::iterator it = encoders.begin(); it != encoders.end(); ++it) {
654 const CKnownFile *cur_file = it->second->GetFile();
655 CValueMap &valuemap = tagmap.GetValueMap(cur_file->ECID());
656 // Completed cleared Partfiles are still stored as CPartfile,
657 // but encoded as KnownFile, so we have to check the encoder type
658 // instead of the file type.
659 if (it->second->IsPartFile_Encoder()) {
660 CEC_PartFile_Tag filetag((const CPartFile*) cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
661 // Add information if partfile is shared
662 filetag.AddTag(EC_TAG_PARTFILE_SHARED, it->second->IsShared(), &valuemap);
664 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
665 enc->Encode(&filetag);
666 response->AddTag(filetag);
667 } else {
668 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
669 CKnownFile_Encoder * enc = encoders[cur_file->ECID()];
670 enc->Encode(&filetag);
671 response->AddTag(filetag);
675 // Add clients
676 CECEmptyTag clients(EC_TAG_CLIENT);
677 const CClientList::IDMap& clientList = theApp->clientlist->GetClientList();
678 bool onlyTransmittingClients = thePrefs::IsTransmitOnlyUploadingClients();
679 for (CClientList::IDMap::const_iterator it = clientList.begin(); it != clientList.end(); it++) {
680 const CUpDownClient* cur_client = it->second.GetClient();
681 if (onlyTransmittingClients && !cur_client->IsDownloading()) {
682 // For poor CPU cores only transmit uploading clients. This will save a lot of CPU.
683 // Set ExternalConnect/TransmitOnlyUploadingClients to 1 for it.
684 continue;
686 CValueMap &valuemap = tagmap.GetValueMap(cur_client->ECID());
687 clients.AddTag(CEC_UpDownClient_Tag(cur_client, EC_DETAIL_INC_UPDATE, &valuemap));
689 response->AddTag(clients);
691 // Add servers
692 CECEmptyTag servers(EC_TAG_SERVER);
693 std::vector<const CServer*> serverlist = theApp->serverlist->CopySnapshot();
694 uint32 nrServers = serverlist.size();
695 for (uint32 i = 0; i < nrServers; i++) {
696 const CServer* cur_server = serverlist[i];
697 CValueMap &valuemap = tagmap.GetValueMap(cur_server->ECID());
698 servers.AddTag(CEC_Server_Tag(cur_server, &valuemap));
700 response->AddTag(servers);
702 // Add friends
703 CECEmptyTag friends(EC_TAG_FRIEND);
704 for (CFriendList::const_iterator it = theApp->friendlist->begin(); it != theApp->friendlist->end(); it++) {
705 const CFriend* cur_friend = *it;
706 CValueMap &valuemap = tagmap.GetValueMap(cur_friend->ECID());
707 friends.AddTag(CEC_Friend_Tag(cur_friend, &valuemap));
709 response->AddTag(friends);
711 return response;
714 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
716 CECPacket *response = new CECPacket(op);
718 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
721 // request can contain list of queried items
722 // (not for incremental update of course)
723 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
725 const CClientRefList& clients = theApp->uploadqueue->GetUploadingList();
726 CClientRefList::const_iterator it = clients.begin();
727 for (; it != clients.end(); ++it) {
728 CUpDownClient* cur_client = it->GetClient();
730 if (!cur_client) { // shouldn't happen
731 continue;
733 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
734 continue;
736 CValueMap *valuemap = NULL;
737 if (detail_level == EC_DETAIL_INC_UPDATE) {
738 valuemap = &tagmap.GetValueMap(cur_client->ECID());
740 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
742 response->AddTag(cli_tag);
745 return response;
749 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
751 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
753 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
755 // request can contain list of queried items
756 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
758 encoders.UpdateEncoders();
760 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
761 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
763 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
764 continue;
767 CEC_PartFile_Tag filetag(cur_file, detail_level);
769 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
770 if ( detail_level != EC_DETAIL_UPDATE ) {
771 enc->ResetEncoder();
773 enc->Encode(&filetag);
775 response->AddTag(filetag);
777 return response;
781 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
783 CECPacket *response = NULL;
785 // request can contain multiple files.
786 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); it1++) {
787 const CECTag &hashtag = *it1;
789 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
791 CMD4Hash hash = hashtag.GetMD4Data();
792 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
794 if ( !pfile ) {
795 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
796 response = new CECPacket(EC_OP_FAILED);
797 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
798 //return response;
799 break;
801 switch (request->GetOpCode()) {
802 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
803 CoreNotify_PartFile_Swap_A4AF(pfile);
804 break;
805 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
806 CoreNotify_PartFile_Swap_A4AF_Auto(pfile);
807 break;
808 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
809 CoreNotify_PartFile_Swap_A4AF_Others(pfile);
810 break;
811 case EC_OP_PARTFILE_PAUSE:
812 pfile->PauseFile();
813 break;
814 case EC_OP_PARTFILE_RESUME:
815 pfile->ResumeFile();
816 pfile->SavePartFile();
817 break;
818 case EC_OP_PARTFILE_STOP:
819 pfile->StopFile();
820 break;
821 case EC_OP_PARTFILE_PRIO_SET: {
822 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
823 if ( prio == PR_AUTO ) {
824 pfile->SetAutoDownPriority(1);
825 } else {
826 pfile->SetAutoDownPriority(0);
827 pfile->SetDownPriority(prio);
830 break;
831 case EC_OP_PARTFILE_DELETE:
832 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
833 theApp->downloadqueue->StartNextFile(pfile);
835 pfile->Delete();
836 break;
838 case EC_OP_PARTFILE_SET_CAT:
839 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
840 break;
842 default:
843 response = new CECPacket(EC_OP_FAILED);
844 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
845 break;
848 if (!response) {
849 response = new CECPacket(EC_OP_NOOP);
851 return response;
854 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
856 CECPacket *response = NULL;
858 wxString full_addr = request->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS)->GetStringData();
859 wxString name = request->GetTagByNameSafe(EC_TAG_SERVER_NAME)->GetStringData();
861 wxString s_ip = full_addr.Left(full_addr.Find(':'));
862 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
864 long port = StrToULong(s_port);
865 CServer* toadd = new CServer(port, s_ip);
866 toadd->SetListName(name.IsEmpty() ? full_addr : name);
868 if ( theApp->AddServer(toadd, true) ) {
869 response = new CECPacket(EC_OP_NOOP);
870 } else {
871 response = new CECPacket(EC_OP_FAILED);
872 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
873 delete toadd;
876 return response;
879 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
881 CECPacket *response = NULL;
882 const CECTag *srv_tag = request->GetTagByName(EC_TAG_SERVER);
883 CServer *srv = 0;
884 if ( srv_tag ) {
885 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
886 // server tag passed, but server not found
887 if ( !srv ) {
888 response = new CECPacket(EC_OP_FAILED);
889 response->AddTag(CECTag(EC_TAG_STRING,
890 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
891 return response;
894 switch (request->GetOpCode()) {
895 case EC_OP_SERVER_DISCONNECT:
896 theApp->serverconnect->Disconnect();
897 response = new CECPacket(EC_OP_NOOP);
898 break;
899 case EC_OP_SERVER_REMOVE:
900 if ( srv ) {
901 theApp->serverlist->RemoveServer(srv);
902 response = new CECPacket(EC_OP_NOOP);
903 } else {
904 response = new CECPacket(EC_OP_FAILED);
905 response->AddTag(CECTag(EC_TAG_STRING,
906 wxTRANSLATE("need to define server to be removed")));
908 break;
909 case EC_OP_SERVER_CONNECT:
910 if (thePrefs::GetNetworkED2K()) {
911 if ( srv ) {
912 theApp->serverconnect->ConnectToServer(srv);
913 response = new CECPacket(EC_OP_NOOP);
914 } else {
915 theApp->serverconnect->ConnectToAnyServer();
916 response = new CECPacket(EC_OP_NOOP);
918 } else {
919 response = new CECPacket(EC_OP_FAILED);
920 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
922 break;
924 if (!response) {
925 response = new CECPacket(EC_OP_FAILED);
926 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
928 return response;
932 static CECPacket *Get_EC_Response_Friend(const CECPacket *request)
934 CECPacket *response = NULL;
935 const CECTag *tag = request->GetTagByName(EC_TAG_FRIEND_ADD);
936 if (tag) {
937 const CECTag *subtag = tag->GetTagByName(EC_TAG_CLIENT);
938 if (subtag) {
939 CUpDownClient * client = theApp->clientlist->FindClientByECID(subtag->GetInt());
940 if (client) {
941 theApp->friendlist->AddFriend(CCLIENTREF(client, wxT("Get_EC_Response_Friend theApp->friendlist->AddFriend")));
942 response = new CECPacket(EC_OP_NOOP);
944 } else {
945 const CECTag *hashtag = tag->GetTagByName(EC_TAG_FRIEND_HASH);
946 const CECTag *iptag = tag->GetTagByName(EC_TAG_FRIEND_IP);
947 const CECTag *porttag = tag->GetTagByName(EC_TAG_FRIEND_PORT);
948 const CECTag *nametag = tag->GetTagByName(EC_TAG_FRIEND_NAME);
949 if (hashtag && iptag && porttag && nametag) {
950 theApp->friendlist->AddFriend(hashtag->GetMD4Data(), iptag->GetInt(), porttag->GetInt(), nametag->GetStringData());
951 response = new CECPacket(EC_OP_NOOP);
954 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_REMOVE))) {
955 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
956 if (subtag) {
957 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
958 if (Friend) {
959 theApp->friendlist->RemoveFriend(Friend);
960 response = new CECPacket(EC_OP_NOOP);
963 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_FRIENDSLOT))) {
964 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
965 if (subtag) {
966 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
967 if (Friend) {
968 theApp->friendlist->SetFriendSlot(Friend, tag->GetInt() != 0);
969 response = new CECPacket(EC_OP_NOOP);
972 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_SHARED))) {
973 response = new CECPacket(EC_OP_FAILED);
974 response->AddTag(CECTag(EC_TAG_STRING, wxT("Request shared files list not implemented yet.")));
975 #if 0
976 // This works fine - but there is no way atm to transfer the results to amulegui, so disable it for now.
978 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
979 if (subtag) {
980 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
981 if (Friend) {
982 theApp->friendlist->RequestSharedFileList(Friend);
983 response = new CECPacket(EC_OP_NOOP);
985 } else if ((subtag = tag->GetTagByName(EC_TAG_CLIENT))) {
986 CUpDownClient * client = theApp->clientlist->FindClientByECID(subtag->GetInt());
987 if (client) {
988 client->RequestSharedFileList();
989 response = new CECPacket(EC_OP_NOOP);
992 #endif
995 if (!response) {
996 response = new CECPacket(EC_OP_FAILED);
997 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
999 return response;
1003 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
1005 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1007 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1009 // request can contain list of queried items
1010 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
1012 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
1013 CSearchResultList::const_iterator it = list.begin();
1014 while (it != list.end()) {
1015 CSearchFile* sf = *it++;
1016 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
1017 continue;
1019 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
1021 return response;
1024 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
1026 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1028 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
1029 CSearchResultList::const_iterator it = list.begin();
1030 while (it != list.end()) {
1031 CSearchFile* sf = *it++;
1032 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
1033 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
1034 // Add the children
1035 if (sf->HasChildren()) {
1036 const CSearchResultList& children = sf->GetChildren();
1037 for (size_t i = 0; i < children.size(); ++i) {
1038 CSearchFile* sfc = children.at(i);
1039 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
1040 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
1044 return response;
1047 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
1049 CECPacket *response = new CECPacket(EC_OP_STRINGS);
1050 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1051 const CECTag &tag = *it;
1052 CMD4Hash hash = tag.GetMD4Data();
1053 uint8 category = tag.GetFirstTagSafe()->GetInt();
1054 theApp->searchlist->AddFileToDownloadByHash(hash, category);
1056 return response;
1059 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
1061 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
1062 theApp->searchlist->StopSearch();
1063 return reply;
1066 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
1068 wxString response;
1070 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetFirstTagSafe();
1071 theApp->searchlist->RemoveResults(0xffffffff);
1073 CSearchList::CSearchParams params;
1074 params.searchString = search_request->SearchText();
1075 params.typeText = search_request->SearchFileType();
1076 params.extension = search_request->SearchExt();
1077 params.minSize = search_request->MinSize();
1078 params.maxSize = search_request->MaxSize();
1079 params.availability = search_request->Avail();
1082 EC_SEARCH_TYPE search_type = search_request->SearchType();
1083 SearchType core_search_type = LocalSearch;
1084 uint32 op = EC_OP_FAILED;
1085 switch (search_type) {
1086 case EC_SEARCH_GLOBAL:
1087 core_search_type = GlobalSearch;
1088 case EC_SEARCH_KAD:
1089 if (core_search_type != GlobalSearch) { // Not a global search obviously
1090 core_search_type = KadSearch;
1092 case EC_SEARCH_LOCAL: {
1093 uint32 search_id = 0xffffffff;
1094 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
1095 if (!error.IsEmpty()) {
1096 response = error;
1097 } else {
1098 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
1099 op = EC_OP_STRINGS;
1101 break;
1103 case EC_SEARCH_WEB:
1104 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
1105 break;
1108 CECPacket *reply = new CECPacket(op);
1109 // error or search in progress
1110 reply->AddTag(CECTag(EC_TAG_STRING, response));
1112 return reply;
1115 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1117 CECPacket *response = new CECPacket(EC_OP_NOOP);
1118 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1119 const CECTag &tag = *it;
1120 CMD4Hash hash = tag.GetMD4Data();
1121 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1122 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1123 if ( !cur_file ) {
1124 continue;
1126 if (prio == PR_AUTO) {
1127 cur_file->SetAutoUpPriority(1);
1128 cur_file->UpdateAutoUpPriority();
1129 } else {
1130 cur_file->SetAutoUpPriority(0);
1131 cur_file->SetUpPriority(prio);
1133 Notify_SharedFilesUpdateItem(cur_file);
1136 return response;
1139 void CPartFile_Encoder::Encode(CECTag *parent)
1142 // Source part frequencies
1144 CKnownFile_Encoder::Encode(parent);
1147 // Gaps
1149 const CGapList& gaplist = m_PartFile()->GetGapList();
1150 const size_t gap_list_size = gaplist.size();
1151 ArrayOfUInts64 gaps;
1152 gaps.reserve(gap_list_size * 2);
1154 for (CGapList::const_iterator curr_pos = gaplist.begin();
1155 curr_pos != gaplist.end(); ++curr_pos) {
1156 gaps.push_back(curr_pos.start());
1157 gaps.push_back(curr_pos.end());
1160 int gap_enc_size = 0;
1161 bool changed;
1162 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1163 if (changed) {
1164 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1166 delete[] gap_enc_data;
1169 // Requested blocks
1171 ArrayOfUInts64 req_buffer;
1172 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1173 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1175 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1176 Requested_Block_Struct* block = *curr_pos2;
1177 req_buffer.push_back(block->StartOffset);
1178 req_buffer.push_back(block->EndOffset);
1180 int req_enc_size = 0;
1181 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1182 if (changed) {
1183 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1185 delete[] req_enc_data;
1188 // Source names
1190 // First count occurrence of all source names
1192 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1193 typedef std::map<wxString, int> strIntMap;
1194 strIntMap nameMap;
1195 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1196 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1197 const CClientRef &cur_src = *it;
1198 if (cur_src.GetRequestFile() != m_file || cur_src.GetClientFilename().Length() == 0) {
1199 continue;
1201 const wxString &name = cur_src.GetClientFilename();
1202 strIntMap::iterator itm = nameMap.find(name);
1203 if (itm == nameMap.end()) {
1204 nameMap[name] = 1;
1205 } else {
1206 itm->second++;
1210 // Go through our last list
1212 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1213 SourcenameItemMap::iterator it2 = it1++;
1214 strIntMap::iterator itm = nameMap.find(it2->second.name);
1215 if (itm == nameMap.end()) {
1216 // name doesn't exist anymore, tell client to forget it
1217 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1218 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1219 sourceNames.AddTag(tag);
1220 // and forget it
1221 m_sourcenameItemMap.erase(it2);
1222 } else {
1223 // update count if it changed
1224 if (it2->second.count != itm->second) {
1225 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1226 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1227 sourceNames.AddTag(tag);
1228 it2->second.count = itm->second;
1230 // remove it from nameMap so that only new names are left there
1231 nameMap.erase(itm);
1235 // Add new names
1237 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1238 int id = ++m_sourcenameID;
1239 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1240 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1241 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1242 sourceNames.AddTag(tag);
1243 // remember it
1244 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1246 if (sourceNames.HasChildTags()) {
1247 parent->AddTag(sourceNames);
1252 void CPartFile_Encoder::ResetEncoder()
1254 CKnownFile_Encoder::ResetEncoder();
1255 m_gap_status.ResetEncoder();
1256 m_req_status.ResetEncoder();
1259 void CKnownFile_Encoder::Encode(CECTag *parent)
1262 // Source part frequencies
1264 // Reference to the availability list
1265 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1266 ((CPartFile*)m_file)->m_SrcpartFrequency :
1267 m_file->m_AvailPartFrequency;
1268 // Don't add tag if available parts aren't populated yet.
1269 if (!list.empty()) {
1270 int part_enc_size;
1271 bool changed;
1272 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1273 if (changed) {
1274 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1276 delete[] part_enc_data;
1280 static CECPacket *GetStatsGraphs(const CECPacket *request)
1282 CECPacket *response = NULL;
1284 switch (request->GetDetailLevel()) {
1285 case EC_DETAIL_WEB:
1286 case EC_DETAIL_FULL: {
1287 double dTimestamp = 0.0;
1288 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1289 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1291 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1292 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1293 uint32 *graphData;
1294 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1295 if (numPoints) {
1296 response = new CECPacket(EC_OP_STATSGRAPHS);
1297 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1298 delete [] graphData;
1299 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1300 } else {
1301 response = new CECPacket(EC_OP_FAILED);
1302 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1304 break;
1306 case EC_DETAIL_INC_UPDATE:
1307 case EC_DETAIL_UPDATE:
1308 case EC_DETAIL_CMD:
1309 // No graphs
1310 response = new CECPacket(EC_OP_FAILED);
1311 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1312 break;
1314 if (!response) {
1315 response = new CECPacket(EC_OP_FAILED);
1316 // Unknown reason
1319 return response;
1322 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1325 if ( !request ) {
1326 return 0;
1329 CECPacket *response = NULL;
1331 switch (request->GetOpCode()) {
1333 // Misc commands
1335 case EC_OP_SHUTDOWN:
1336 if (!theApp->IsOnShutDown()) {
1337 response = new CECPacket(EC_OP_NOOP);
1338 AddLogLineC(_("External Connection: shutdown requested"));
1339 #ifndef AMULE_DAEMON
1341 wxCloseEvent evt;
1342 evt.SetCanVeto(false);
1343 theApp->ShutDown(evt);
1345 #else
1346 theApp->ExitMainLoop();
1347 #endif
1348 } else {
1349 response = new CECPacket(EC_OP_FAILED);
1350 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1352 break;
1353 case EC_OP_ADD_LINK:
1354 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1355 const CECTag &tag = *it;
1356 wxString link = tag.GetStringData();
1357 int category = 0;
1358 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1359 if (cattag) {
1360 category = cattag->GetInt();
1362 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link);
1363 if ( theApp->downloadqueue->AddLink(link, category) ) {
1364 response = new CECPacket(EC_OP_NOOP);
1365 } else {
1366 // Error messages are printed by the add function.
1367 response = new CECPacket(EC_OP_FAILED);
1368 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1371 break;
1373 // Status requests
1375 case EC_OP_STAT_REQ:
1376 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1377 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1378 break;
1379 case EC_OP_GET_CONNSTATE:
1380 response = new CECPacket(EC_OP_MISC_DATA);
1381 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1382 break;
1386 case EC_OP_GET_SHARED_FILES:
1387 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1388 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1390 break;
1391 case EC_OP_GET_DLOAD_QUEUE:
1392 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1393 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1395 break;
1397 // This will evolve into an update-all for inc tags
1399 case EC_OP_GET_UPDATE:
1400 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1401 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1403 break;
1404 case EC_OP_GET_ULOAD_QUEUE:
1405 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1406 break;
1407 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1408 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1409 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1410 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1411 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1412 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1413 case EC_OP_PARTFILE_PAUSE:
1414 case EC_OP_PARTFILE_RESUME:
1415 case EC_OP_PARTFILE_STOP:
1416 case EC_OP_PARTFILE_PRIO_SET:
1417 case EC_OP_PARTFILE_DELETE:
1418 case EC_OP_PARTFILE_SET_CAT:
1419 response = Get_EC_Response_PartFile_Cmd(request);
1420 break;
1421 case EC_OP_SHAREDFILES_RELOAD:
1422 theApp->sharedfiles->Reload();
1423 response = new CECPacket(EC_OP_NOOP);
1424 break;
1425 case EC_OP_SHARED_SET_PRIO:
1426 response = Get_EC_Response_Set_SharedFile_Prio(request);
1427 break;
1428 case EC_OP_RENAME_FILE: {
1429 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1430 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1431 // search first in downloadqueue - it might be in known files as well
1432 CKnownFile* file = theApp->downloadqueue->GetFileByID(fileHash);
1433 if (!file) {
1434 file = theApp->knownfiles->FindKnownFileByID(fileHash);
1436 if (!file) {
1437 response = new CECPacket(EC_OP_FAILED);
1438 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1439 break;
1441 if (newName.IsEmpty()) {
1442 response = new CECPacket(EC_OP_FAILED);
1443 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1444 break;
1447 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1448 response = new CECPacket(EC_OP_NOOP);
1449 } else {
1450 response = new CECPacket(EC_OP_FAILED);
1451 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1454 break;
1456 case EC_OP_CLEAR_COMPLETED: {
1457 ListOfUInts32 toClear;
1458 for (CECTag::const_iterator it = request->begin(); it != request->end(); it++) {
1459 if (it->GetTagName() == EC_TAG_ECID) {
1460 toClear.push_back(it->GetInt());
1463 theApp->downloadqueue->ClearCompleted(toClear);
1464 response = new CECPacket(EC_OP_NOOP);
1465 break;
1467 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE: {
1468 theApp->sharedfiles->Reload();
1469 uint32 idClient = request->GetTagByNameSafe(EC_TAG_CLIENT)->GetInt();
1470 CUpDownClient * client = theApp->clientlist->FindClientByECID(idClient);
1471 CMD4Hash idFile = request->GetTagByNameSafe(EC_TAG_PARTFILE)->GetMD4Data();
1472 CPartFile * file = theApp->downloadqueue->GetFileByID(idFile);
1473 if (client && file) {
1474 client->SwapToAnotherFile( true, false, false, file);
1476 response = new CECPacket(EC_OP_NOOP);
1477 break;
1479 case EC_OP_SHARED_FILE_SET_COMMENT: {
1480 CMD4Hash hash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1481 CKnownFile * file = theApp->sharedfiles->GetFileByID(hash);
1482 if (file) {
1483 wxString newComment = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT)->GetStringData();
1484 uint8 newRating = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING)->GetInt();
1485 CoreNotify_KnownFile_Comment_Set(file, newComment, newRating);
1487 response = new CECPacket(EC_OP_NOOP);
1488 break;
1492 // Server commands
1494 case EC_OP_SERVER_ADD:
1495 response = Get_EC_Response_Server_Add(request);
1496 break;
1497 case EC_OP_SERVER_DISCONNECT:
1498 case EC_OP_SERVER_CONNECT:
1499 case EC_OP_SERVER_REMOVE:
1500 response = Get_EC_Response_Server(request);
1501 break;
1502 case EC_OP_GET_SERVER_LIST: {
1503 response = new CECPacket(EC_OP_SERVER_LIST);
1504 if (!thePrefs::GetNetworkED2K()) {
1505 // Kad only: just send an empty list
1506 break;
1508 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1509 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1510 for (
1511 std::vector<const CServer*>::const_iterator it = servers.begin();
1512 it != servers.end();
1513 ++it
1515 response->AddTag(CEC_Server_Tag(*it, detail_level));
1518 break;
1519 case EC_OP_SERVER_UPDATE_FROM_URL: {
1520 wxString url = request->GetFirstTagSafe()->GetStringData();
1522 // Save the new url, and update the UI (if not amuled).
1523 Notify_ServersURLChanged(url);
1524 thePrefs::SetEd2kServersUrl(url);
1526 theApp->serverlist->UpdateServerMetFromURL(url);
1527 response = new CECPacket(EC_OP_NOOP);
1528 break;
1530 case EC_OP_SERVER_SET_STATIC_PRIO: {
1531 uint32 ecid = request->GetTagByNameSafe(EC_TAG_SERVER)->GetInt();
1532 CServer * server = theApp->serverlist->GetServerByECID(ecid);
1533 if (server) {
1534 const CECTag * staticTag = request->GetTagByName(EC_TAG_SERVER_STATIC);
1535 if (staticTag) {
1536 theApp->serverlist->SetStaticServer(server, staticTag->GetInt() > 0);
1538 const CECTag * prioTag = request->GetTagByName(EC_TAG_SERVER_PRIO);
1539 if (prioTag) {
1540 theApp->serverlist->SetServerPrio(server, prioTag->GetInt());
1543 response = new CECPacket(EC_OP_NOOP);
1544 break;
1547 // Friends
1549 case EC_OP_FRIEND:
1550 response = Get_EC_Response_Friend(request);
1551 break;
1554 // IPFilter
1556 case EC_OP_IPFILTER_RELOAD:
1557 NotifyAlways_IPFilter_Reload();
1558 response = new CECPacket(EC_OP_NOOP);
1559 break;
1561 case EC_OP_IPFILTER_UPDATE: {
1562 wxString url = request->GetFirstTagSafe()->GetStringData();
1563 if (url.IsEmpty()) {
1564 url = thePrefs::IPFilterURL();
1566 NotifyAlways_IPFilter_Update(url);
1567 response = new CECPacket(EC_OP_NOOP);
1568 break;
1571 // Search
1573 case EC_OP_SEARCH_START:
1574 response = Get_EC_Response_Search(request);
1575 break;
1577 case EC_OP_SEARCH_STOP:
1578 response = Get_EC_Response_Search_Stop(request);
1579 break;
1581 case EC_OP_SEARCH_RESULTS:
1582 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1583 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1584 } else {
1585 response = Get_EC_Response_Search_Results(request);
1587 break;
1589 case EC_OP_SEARCH_PROGRESS:
1590 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1591 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1592 theApp->searchlist->GetSearchProgress()));
1593 break;
1595 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1596 response = Get_EC_Response_Search_Results_Download(request);
1597 break;
1599 // Preferences
1601 case EC_OP_GET_PREFERENCES:
1602 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1603 break;
1604 case EC_OP_SET_PREFERENCES:
1605 ((CEC_Prefs_Packet *)request)->Apply();
1606 theApp->glob_prefs->Save();
1607 if (thePrefs::IsFilteringClients()) {
1608 theApp->clientlist->FilterQueues();
1610 if (thePrefs::IsFilteringServers()) {
1611 theApp->serverlist->FilterServers();
1613 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1614 theApp->DisconnectED2K();
1616 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1617 theApp->StopKad();
1619 response = new CECPacket(EC_OP_NOOP);
1620 break;
1622 case EC_OP_CREATE_CATEGORY:
1623 if ( request->GetTagCount() == 1 ) {
1624 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1625 if (tag->Create()) {
1626 response = new CECPacket(EC_OP_NOOP);
1627 } else {
1628 response = new CECPacket(EC_OP_FAILED);
1629 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1630 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1632 Notify_CategoryAdded();
1633 } else {
1634 response = new CECPacket(EC_OP_NOOP);
1636 break;
1637 case EC_OP_UPDATE_CATEGORY:
1638 if ( request->GetTagCount() == 1 ) {
1639 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1640 if (tag->Apply()) {
1641 response = new CECPacket(EC_OP_NOOP);
1642 } else {
1643 response = new CECPacket(EC_OP_FAILED);
1644 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1645 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1647 Notify_CategoryUpdate(tag->GetInt());
1648 } else {
1649 response = new CECPacket(EC_OP_NOOP);
1651 break;
1652 case EC_OP_DELETE_CATEGORY:
1653 if ( request->GetTagCount() == 1 ) {
1654 uint32 cat = request->GetFirstTagSafe()->GetInt();
1655 // this noes not only update the gui, but actually deletes the cat
1656 Notify_CategoryDelete(cat);
1658 response = new CECPacket(EC_OP_NOOP);
1659 break;
1662 // Logging
1664 case EC_OP_ADDLOGLINE:
1665 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1666 AddLogLineC(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1667 } else {
1668 AddLogLineN(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1670 response = new CECPacket(EC_OP_NOOP);
1671 break;
1672 case EC_OP_ADDDEBUGLOGLINE:
1673 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1674 AddDebugLogLineC(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1675 } else {
1676 AddDebugLogLineN(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1678 response = new CECPacket(EC_OP_NOOP);
1679 break;
1680 case EC_OP_GET_LOG:
1681 response = new CECPacket(EC_OP_LOG);
1682 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1683 break;
1684 case EC_OP_GET_DEBUGLOG:
1685 response = new CECPacket(EC_OP_DEBUGLOG);
1686 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1687 break;
1688 case EC_OP_RESET_LOG:
1689 theApp->GetLog(true);
1690 response = new CECPacket(EC_OP_NOOP);
1691 break;
1692 case EC_OP_RESET_DEBUGLOG:
1693 theApp->GetDebugLog(true);
1694 response = new CECPacket(EC_OP_NOOP);
1695 break;
1696 case EC_OP_GET_LAST_LOG_ENTRY:
1698 wxString tmp = theApp->GetLog(false);
1699 if (tmp.Last() == '\n') {
1700 tmp.RemoveLast();
1702 response = new CECPacket(EC_OP_LOG);
1703 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1705 break;
1706 case EC_OP_GET_SERVERINFO:
1707 response = new CECPacket(EC_OP_SERVERINFO);
1708 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1709 break;
1710 case EC_OP_CLEAR_SERVERINFO:
1711 theApp->GetServerLog(true);
1712 response = new CECPacket(EC_OP_NOOP);
1713 break;
1715 // Statistics
1717 case EC_OP_GET_STATSGRAPHS:
1718 response = GetStatsGraphs(request);
1719 break;
1720 case EC_OP_GET_STATSTREE: {
1721 theApp->m_statistics->UpdateStatsTree();
1722 response = new CECPacket(EC_OP_STATSTREE);
1723 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1724 if (tree) {
1725 response->AddTag(*tree);
1726 delete tree;
1728 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1729 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1730 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1732 break;
1736 // Kad
1738 case EC_OP_KAD_START:
1739 if (thePrefs::GetNetworkKademlia()) {
1740 response = new CECPacket(EC_OP_NOOP);
1741 if ( !Kademlia::CKademlia::IsRunning() ) {
1742 Kademlia::CKademlia::Start();
1743 theApp->ShowConnectionState();
1745 } else {
1746 response = new CECPacket(EC_OP_FAILED);
1747 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1749 break;
1750 case EC_OP_KAD_STOP:
1751 theApp->StopKad();
1752 theApp->ShowConnectionState();
1753 response = new CECPacket(EC_OP_NOOP);
1754 break;
1755 case EC_OP_KAD_UPDATE_FROM_URL: {
1756 wxString url = request->GetFirstTagSafe()->GetStringData();
1758 // Save the new url, and update the UI (if not amuled).
1759 Notify_NodesURLChanged(url);
1760 thePrefs::SetKadNodesUrl(url);
1762 theApp->UpdateNotesDat(url);
1763 response = new CECPacket(EC_OP_NOOP);
1764 break;
1766 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1767 if (thePrefs::GetNetworkKademlia()) {
1768 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1769 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1770 theApp->ShowConnectionState();
1771 response = new CECPacket(EC_OP_NOOP);
1772 } else {
1773 response = new CECPacket(EC_OP_FAILED);
1774 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1776 break;
1779 // Networks
1780 // These requests are currently used only in the text client
1782 case EC_OP_CONNECT:
1783 if (thePrefs::GetNetworkED2K()) {
1784 response = new CECPacket(EC_OP_STRINGS);
1785 if (theApp->IsConnectedED2K()) {
1786 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1787 } else {
1788 theApp->serverconnect->ConnectToAnyServer();
1789 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1792 if (thePrefs::GetNetworkKademlia()) {
1793 if (!response) {
1794 response = new CECPacket(EC_OP_STRINGS);
1796 if (theApp->IsConnectedKad()) {
1797 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1798 } else {
1799 theApp->StartKad();
1800 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1803 if (response) {
1804 theApp->ShowConnectionState();
1805 } else {
1806 response = new CECPacket(EC_OP_FAILED);
1807 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1809 break;
1810 case EC_OP_DISCONNECT:
1811 if (theApp->IsConnected()) {
1812 response = new CECPacket(EC_OP_STRINGS);
1813 if (theApp->IsConnectedED2K()) {
1814 theApp->serverconnect->Disconnect();
1815 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1817 if (theApp->IsConnectedKad()) {
1818 theApp->StopKad();
1819 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1821 theApp->ShowConnectionState();
1822 } else {
1823 response = new CECPacket(EC_OP_NOOP);
1825 break;
1827 if (!response) {
1828 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request->GetOpCode());
1829 wxFAIL;
1830 response = new CECPacket(EC_OP_FAILED);
1831 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1833 return response;
1837 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1841 * Core general status
1843 ECStatusMsgSource::ECStatusMsgSource()
1845 m_last_ed2k_status_sent = 0xffffffff;
1846 m_last_kad_status_sent = 0xffffffff;
1847 m_server = (void *)0xffffffff;
1850 uint32 ECStatusMsgSource::GetEd2kStatus()
1852 if ( theApp->IsConnectedED2K() ) {
1853 return theApp->GetED2KID();
1854 } else if ( theApp->serverconnect->IsConnecting() ) {
1855 return 1;
1856 } else {
1857 return 0;
1861 uint32 ECStatusMsgSource::GetKadStatus()
1863 if ( theApp->IsConnectedKad() ) {
1864 return 1;
1865 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1866 return 2;
1867 } else if ( Kademlia::CKademlia::IsRunning() ) {
1868 return 3;
1870 return 0;
1873 CECPacket *ECStatusMsgSource::GetNextPacket()
1875 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1876 (m_last_kad_status_sent != GetKadStatus()) ||
1877 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1879 m_last_ed2k_status_sent = GetEd2kStatus();
1880 m_last_kad_status_sent = GetKadStatus();
1881 m_server = theApp->serverconnect->GetCurrentServer();
1883 CECPacket *response = new CECPacket(EC_OP_STATS);
1884 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1885 return response;
1887 return 0;
1891 * Downloading files
1893 ECPartFileMsgSource::ECPartFileMsgSource()
1895 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1896 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1897 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1898 m_dirty_status[cur_file->GetFileHash()] = status;
1902 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1904 CMD4Hash filehash = file->GetFileHash();
1905 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1906 m_dirty_status[filehash].m_dirty = true;;
1910 void ECPartFileMsgSource::SetNew(CPartFile *file)
1912 CMD4Hash filehash = file->GetFileHash();
1913 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1914 PARTFILE_STATUS status = { true, false, false, false, true, file };
1915 m_dirty_status[filehash] = status;
1918 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1920 CMD4Hash filehash = file->GetFileHash();
1921 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1923 m_dirty_status[filehash].m_finished = true;
1926 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1928 CMD4Hash filehash = file->GetFileHash();
1929 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1931 m_dirty_status[filehash].m_removed = true;
1934 CECPacket *ECPartFileMsgSource::GetNextPacket()
1936 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1937 it != m_dirty_status.end(); it++) {
1938 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1939 CMD4Hash filehash = it->first;
1941 CPartFile *partfile = it->second.m_file;
1943 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1944 if ( it->second.m_removed ) {
1945 CECTag tag(EC_TAG_PARTFILE, filehash);
1946 packet->AddTag(tag);
1947 m_dirty_status.erase(it);
1948 } else {
1949 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1950 packet->AddTag(tag);
1952 m_dirty_status[filehash].m_new = false;
1953 m_dirty_status[filehash].m_dirty = false;
1955 return packet;
1958 return 0;
1962 * Shared files - similar to downloading
1964 ECKnownFileMsgSource::ECKnownFileMsgSource()
1966 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1967 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1968 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1969 m_dirty_status[cur_file->GetFileHash()] = status;
1973 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1975 CMD4Hash filehash = file->GetFileHash();
1976 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1977 m_dirty_status[filehash].m_dirty = true;;
1981 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1983 CMD4Hash filehash = file->GetFileHash();
1984 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1985 KNOWNFILE_STATUS status = { true, false, false, true, file };
1986 m_dirty_status[filehash] = status;
1989 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1991 CMD4Hash filehash = file->GetFileHash();
1992 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1994 m_dirty_status[filehash].m_removed = true;
1997 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1999 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
2000 it != m_dirty_status.end(); it++) {
2001 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
2002 CMD4Hash filehash = it->first;
2004 CKnownFile *partfile = it->second.m_file;
2006 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
2007 if ( it->second.m_removed ) {
2008 CECTag tag(EC_TAG_PARTFILE, filehash);
2009 packet->AddTag(tag);
2010 m_dirty_status.erase(it);
2011 } else {
2012 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
2013 packet->AddTag(tag);
2015 m_dirty_status[filehash].m_new = false;
2016 m_dirty_status[filehash].m_dirty = false;
2018 return packet;
2021 return 0;
2025 * Notification about search status
2027 ECSearchMsgSource::ECSearchMsgSource()
2031 CECPacket *ECSearchMsgSource::GetNextPacket()
2033 if ( m_dirty_status.empty() ) {
2034 return 0;
2037 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
2038 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
2039 it != m_dirty_status.end(); it++) {
2041 if ( it->second.m_new ) {
2042 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
2043 it->second.m_new = false;
2044 } else if ( it->second.m_dirty ) {
2045 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
2050 return response;
2053 void ECSearchMsgSource::FlushStatus()
2055 m_dirty_status.clear();
2058 void ECSearchMsgSource::SetDirty(CSearchFile *file)
2060 if ( m_dirty_status.count(file->GetFileHash()) ) {
2061 m_dirty_status[file->GetFileHash()].m_dirty = true;
2062 } else {
2063 m_dirty_status[file->GetFileHash()].m_new = true;
2064 m_dirty_status[file->GetFileHash()].m_dirty = true;
2065 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
2066 m_dirty_status[file->GetFileHash()].m_file = file;
2070 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
2072 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
2076 * Notification about uploading clients
2078 CECPacket *ECClientMsgSource::GetNextPacket()
2080 return 0;
2084 // Notification iface per-client
2086 ECNotifier::ECNotifier()
2090 ECNotifier::~ECNotifier()
2092 while (m_msg_source.begin() != m_msg_source.end())
2093 Remove_EC_Client(m_msg_source.begin()->first);
2096 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
2098 CECPacket *packet = 0;
2100 // priority 0 is highest
2102 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2103 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
2104 break;
2107 return packet;
2110 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
2113 // OnOutput is called for a first time before
2114 // socket is registered
2116 if ( m_msg_source.count(sock) ) {
2117 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2118 if ( !notifier_array ) {
2119 return 0;
2121 CECPacket *packet = GetNextPacket(notifier_array);
2122 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
2123 return packet;
2124 } else {
2125 return 0;
2130 // Interface to notification macros
2132 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
2134 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2135 i != m_msg_source.end(); i++) {
2136 CECServerSocket *sock = i->first;
2137 if ( sock->HaveNotificationSupport() ) {
2138 ECUpdateMsgSource **notifier_array = i->second;
2139 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
2142 NextPacketToSocket();
2145 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
2147 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2148 i != m_msg_source.end(); i++) {
2149 ECUpdateMsgSource **notifier_array = i->second;
2150 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
2152 NextPacketToSocket();
2155 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
2157 // per-partfile source list is not supported (yet), and IMHO quite useless
2160 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
2162 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2163 i != m_msg_source.end(); i++) {
2164 ECUpdateMsgSource **notifier_array = i->second;
2165 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
2167 NextPacketToSocket();
2170 void ECNotifier::DownloadFile_AddSource(CPartFile *)
2172 // per-partfile source list is not supported (yet), and IMHO quite useless
2175 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
2177 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2178 i != m_msg_source.end(); i++) {
2179 ECUpdateMsgSource **notifier_array = i->second;
2180 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
2182 NextPacketToSocket();
2185 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
2187 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2188 i != m_msg_source.end(); i++) {
2189 ECUpdateMsgSource **notifier_array = i->second;
2190 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
2192 NextPacketToSocket();
2195 void ECNotifier::SharedFile_RemoveAllFiles()
2197 // need to figure out what to do here
2200 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2202 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2203 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2204 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2205 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2206 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2207 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2209 m_msg_source[sock] = notifier_array;
2212 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2214 if (m_msg_source.count(sock)) {
2215 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2217 m_msg_source.erase(sock);
2219 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2220 delete notifier_array[i];
2222 delete [] notifier_array;
2226 void ECNotifier::NextPacketToSocket()
2228 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2229 i != m_msg_source.end(); i++) {
2230 CECServerSocket *sock = i->first;
2231 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2232 ECUpdateMsgSource **notifier_array = i->second;
2233 CECPacket *packet = GetNextPacket(notifier_array);
2234 if ( packet ) {
2235 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2236 sock->SendPacket(packet);
2242 // File_checked_for_headers