Recognize additional file types (gagar)
[amule.git] / src / ExternalConn.cpp
blobf919b3dfa4f16f59b2528dba35722da630811a88
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 // This is not an actual INC_UPDATE.
565 // amulegui only sets the detail level of the stats package to EC_DETAIL_INC_UPDATE
566 // so that the included conn state tag is created the way it is needed here.
567 case EC_DETAIL_INC_UPDATE:
568 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
569 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
570 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
571 AddLoggerTag(response, LoggerAccess);
572 // Needed only for the remote tray icon context menu
573 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SENT_BYTES, theStats::GetTotalSentBytes()));
574 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_RECEIVED_BYTES, theStats::GetTotalReceivedBytes()));
575 response->AddTag(CECTag(EC_TAG_STATS_SHARED_FILE_COUNT, theStats::GetSharedFileCount()));
576 case EC_DETAIL_WEB:
577 case EC_DETAIL_CMD:
578 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
579 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
580 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
581 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
582 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
583 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
584 // User/Filecounts
586 uint32 totaluser = 0, totalfile = 0;
587 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
588 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
589 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
590 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
591 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
593 // Kad stats
594 if (Kademlia::CKademlia::IsConnected()) {
595 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
596 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
597 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
598 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
599 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
600 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
601 response->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE, Kademlia::CKademlia::IsRunningInLANMode()));
602 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
603 uint32 BuddyIP = 0;
604 uint16 BuddyPort = 0;
605 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
606 if (Buddy) {
607 BuddyIP = Buddy->GetIP();
608 BuddyPort = Buddy->GetUDPPort();
610 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
611 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
613 case EC_DETAIL_UPDATE:
614 break;
617 return response;
620 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CFileEncoderMap &encoders)
622 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
624 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
626 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
628 // request can contain list of queried items
629 CTagSet<uint32, EC_TAG_KNOWNFILE> queryitems(request);
631 encoders.UpdateEncoders();
633 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
634 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
636 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->ECID())) ) {
637 continue;
640 CEC_SharedFile_Tag filetag(cur_file, detail_level);
641 CKnownFile_Encoder *enc = encoders[cur_file->ECID()];
642 if ( detail_level != EC_DETAIL_UPDATE ) {
643 enc->ResetEncoder();
645 enc->Encode(&filetag);
646 response->AddTag(filetag);
648 return response;
651 static CECPacket *Get_EC_Response_GetUpdate(CFileEncoderMap &encoders, CObjTagMap &tagmap)
653 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
655 encoders.UpdateEncoders();
656 for (CFileEncoderMap::iterator it = encoders.begin(); it != encoders.end(); ++it) {
657 const CKnownFile *cur_file = it->second->GetFile();
658 CValueMap &valuemap = tagmap.GetValueMap(cur_file->ECID());
659 // Completed cleared Partfiles are still stored as CPartfile,
660 // but encoded as KnownFile, so we have to check the encoder type
661 // instead of the file type.
662 if (it->second->IsPartFile_Encoder()) {
663 CEC_PartFile_Tag filetag((const CPartFile*) cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
664 // Add information if partfile is shared
665 filetag.AddTag(EC_TAG_PARTFILE_SHARED, it->second->IsShared(), &valuemap);
667 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
668 enc->Encode(&filetag);
669 response->AddTag(filetag);
670 } else {
671 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
672 CKnownFile_Encoder * enc = encoders[cur_file->ECID()];
673 enc->Encode(&filetag);
674 response->AddTag(filetag);
678 // Add clients
679 CECEmptyTag clients(EC_TAG_CLIENT);
680 const CClientList::IDMap& clientList = theApp->clientlist->GetClientList();
681 bool onlyTransmittingClients = thePrefs::IsTransmitOnlyUploadingClients();
682 for (CClientList::IDMap::const_iterator it = clientList.begin(); it != clientList.end(); it++) {
683 const CUpDownClient* cur_client = it->second.GetClient();
684 if (onlyTransmittingClients && !cur_client->IsDownloading()) {
685 // For poor CPU cores only transmit uploading clients. This will save a lot of CPU.
686 // Set ExternalConnect/TransmitOnlyUploadingClients to 1 for it.
687 continue;
689 CValueMap &valuemap = tagmap.GetValueMap(cur_client->ECID());
690 clients.AddTag(CEC_UpDownClient_Tag(cur_client, EC_DETAIL_INC_UPDATE, &valuemap));
692 response->AddTag(clients);
694 // Add servers
695 CECEmptyTag servers(EC_TAG_SERVER);
696 std::vector<const CServer*> serverlist = theApp->serverlist->CopySnapshot();
697 uint32 nrServers = serverlist.size();
698 for (uint32 i = 0; i < nrServers; i++) {
699 const CServer* cur_server = serverlist[i];
700 CValueMap &valuemap = tagmap.GetValueMap(cur_server->ECID());
701 servers.AddTag(CEC_Server_Tag(cur_server, &valuemap));
703 response->AddTag(servers);
705 // Add friends
706 CECEmptyTag friends(EC_TAG_FRIEND);
707 for (CFriendList::const_iterator it = theApp->friendlist->begin(); it != theApp->friendlist->end(); it++) {
708 const CFriend* cur_friend = *it;
709 CValueMap &valuemap = tagmap.GetValueMap(cur_friend->ECID());
710 friends.AddTag(CEC_Friend_Tag(cur_friend, &valuemap));
712 response->AddTag(friends);
714 return response;
717 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
719 CECPacket *response = new CECPacket(op);
721 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
724 // request can contain list of queried items
725 // (not for incremental update of course)
726 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
728 const CClientRefList& clients = theApp->uploadqueue->GetUploadingList();
729 CClientRefList::const_iterator it = clients.begin();
730 for (; it != clients.end(); ++it) {
731 CUpDownClient* cur_client = it->GetClient();
733 if (!cur_client) { // shouldn't happen
734 continue;
736 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
737 continue;
739 CValueMap *valuemap = NULL;
740 if (detail_level == EC_DETAIL_INC_UPDATE) {
741 valuemap = &tagmap.GetValueMap(cur_client->ECID());
743 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
745 response->AddTag(cli_tag);
748 return response;
752 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
754 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
756 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
758 // request can contain list of queried items
759 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
761 encoders.UpdateEncoders();
763 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
764 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
766 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
767 continue;
770 CEC_PartFile_Tag filetag(cur_file, detail_level);
772 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
773 if ( detail_level != EC_DETAIL_UPDATE ) {
774 enc->ResetEncoder();
776 enc->Encode(&filetag);
778 response->AddTag(filetag);
780 return response;
784 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
786 CECPacket *response = NULL;
788 // request can contain multiple files.
789 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); it1++) {
790 const CECTag &hashtag = *it1;
792 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
794 CMD4Hash hash = hashtag.GetMD4Data();
795 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
797 if ( !pfile ) {
798 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
799 response = new CECPacket(EC_OP_FAILED);
800 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
801 //return response;
802 break;
804 switch (request->GetOpCode()) {
805 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
806 CoreNotify_PartFile_Swap_A4AF(pfile);
807 break;
808 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
809 CoreNotify_PartFile_Swap_A4AF_Auto(pfile);
810 break;
811 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
812 CoreNotify_PartFile_Swap_A4AF_Others(pfile);
813 break;
814 case EC_OP_PARTFILE_PAUSE:
815 pfile->PauseFile();
816 break;
817 case EC_OP_PARTFILE_RESUME:
818 pfile->ResumeFile();
819 pfile->SavePartFile();
820 break;
821 case EC_OP_PARTFILE_STOP:
822 pfile->StopFile();
823 break;
824 case EC_OP_PARTFILE_PRIO_SET: {
825 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
826 if ( prio == PR_AUTO ) {
827 pfile->SetAutoDownPriority(1);
828 } else {
829 pfile->SetAutoDownPriority(0);
830 pfile->SetDownPriority(prio);
833 break;
834 case EC_OP_PARTFILE_DELETE:
835 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
836 theApp->downloadqueue->StartNextFile(pfile);
838 pfile->Delete();
839 break;
841 case EC_OP_PARTFILE_SET_CAT:
842 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
843 break;
845 default:
846 response = new CECPacket(EC_OP_FAILED);
847 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
848 break;
851 if (!response) {
852 response = new CECPacket(EC_OP_NOOP);
854 return response;
857 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
859 CECPacket *response = NULL;
861 wxString full_addr = request->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS)->GetStringData();
862 wxString name = request->GetTagByNameSafe(EC_TAG_SERVER_NAME)->GetStringData();
864 wxString s_ip = full_addr.Left(full_addr.Find(':'));
865 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
867 long port = StrToULong(s_port);
868 CServer* toadd = new CServer(port, s_ip);
869 toadd->SetListName(name.IsEmpty() ? full_addr : name);
871 if ( theApp->AddServer(toadd, true) ) {
872 response = new CECPacket(EC_OP_NOOP);
873 } else {
874 response = new CECPacket(EC_OP_FAILED);
875 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
876 delete toadd;
879 return response;
882 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
884 CECPacket *response = NULL;
885 const CECTag *srv_tag = request->GetTagByName(EC_TAG_SERVER);
886 CServer *srv = 0;
887 if ( srv_tag ) {
888 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
889 // server tag passed, but server not found
890 if ( !srv ) {
891 response = new CECPacket(EC_OP_FAILED);
892 response->AddTag(CECTag(EC_TAG_STRING,
893 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
894 return response;
897 switch (request->GetOpCode()) {
898 case EC_OP_SERVER_DISCONNECT:
899 theApp->serverconnect->Disconnect();
900 response = new CECPacket(EC_OP_NOOP);
901 break;
902 case EC_OP_SERVER_REMOVE:
903 if ( srv ) {
904 theApp->serverlist->RemoveServer(srv);
905 response = new CECPacket(EC_OP_NOOP);
906 } else {
907 response = new CECPacket(EC_OP_FAILED);
908 response->AddTag(CECTag(EC_TAG_STRING,
909 wxTRANSLATE("need to define server to be removed")));
911 break;
912 case EC_OP_SERVER_CONNECT:
913 if (thePrefs::GetNetworkED2K()) {
914 if ( srv ) {
915 theApp->serverconnect->ConnectToServer(srv);
916 response = new CECPacket(EC_OP_NOOP);
917 } else {
918 theApp->serverconnect->ConnectToAnyServer();
919 response = new CECPacket(EC_OP_NOOP);
921 } else {
922 response = new CECPacket(EC_OP_FAILED);
923 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
925 break;
927 if (!response) {
928 response = new CECPacket(EC_OP_FAILED);
929 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
931 return response;
935 static CECPacket *Get_EC_Response_Friend(const CECPacket *request)
937 CECPacket *response = NULL;
938 const CECTag *tag = request->GetTagByName(EC_TAG_FRIEND_ADD);
939 if (tag) {
940 const CECTag *subtag = tag->GetTagByName(EC_TAG_CLIENT);
941 if (subtag) {
942 CUpDownClient * client = theApp->clientlist->FindClientByECID(subtag->GetInt());
943 if (client) {
944 theApp->friendlist->AddFriend(CCLIENTREF(client, wxT("Get_EC_Response_Friend theApp->friendlist->AddFriend")));
945 response = new CECPacket(EC_OP_NOOP);
947 } else {
948 const CECTag *hashtag = tag->GetTagByName(EC_TAG_FRIEND_HASH);
949 const CECTag *iptag = tag->GetTagByName(EC_TAG_FRIEND_IP);
950 const CECTag *porttag = tag->GetTagByName(EC_TAG_FRIEND_PORT);
951 const CECTag *nametag = tag->GetTagByName(EC_TAG_FRIEND_NAME);
952 if (hashtag && iptag && porttag && nametag) {
953 theApp->friendlist->AddFriend(hashtag->GetMD4Data(), iptag->GetInt(), porttag->GetInt(), nametag->GetStringData());
954 response = new CECPacket(EC_OP_NOOP);
957 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_REMOVE))) {
958 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
959 if (subtag) {
960 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
961 if (Friend) {
962 theApp->friendlist->RemoveFriend(Friend);
963 response = new CECPacket(EC_OP_NOOP);
966 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_FRIENDSLOT))) {
967 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
968 if (subtag) {
969 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
970 if (Friend) {
971 theApp->friendlist->SetFriendSlot(Friend, tag->GetInt() != 0);
972 response = new CECPacket(EC_OP_NOOP);
975 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_SHARED))) {
976 response = new CECPacket(EC_OP_FAILED);
977 response->AddTag(CECTag(EC_TAG_STRING, wxT("Request shared files list not implemented yet.")));
978 #if 0
979 // This works fine - but there is no way atm to transfer the results to amulegui, so disable it for now.
981 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
982 if (subtag) {
983 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
984 if (Friend) {
985 theApp->friendlist->RequestSharedFileList(Friend);
986 response = new CECPacket(EC_OP_NOOP);
988 } else if ((subtag = tag->GetTagByName(EC_TAG_CLIENT))) {
989 CUpDownClient * client = theApp->clientlist->FindClientByECID(subtag->GetInt());
990 if (client) {
991 client->RequestSharedFileList();
992 response = new CECPacket(EC_OP_NOOP);
995 #endif
998 if (!response) {
999 response = new CECPacket(EC_OP_FAILED);
1000 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
1002 return response;
1006 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
1008 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1010 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1012 // request can contain list of queried items
1013 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
1015 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
1016 CSearchResultList::const_iterator it = list.begin();
1017 while (it != list.end()) {
1018 CSearchFile* sf = *it++;
1019 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
1020 continue;
1022 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
1024 return response;
1027 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
1029 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1031 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
1032 CSearchResultList::const_iterator it = list.begin();
1033 while (it != list.end()) {
1034 CSearchFile* sf = *it++;
1035 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
1036 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
1037 // Add the children
1038 if (sf->HasChildren()) {
1039 const CSearchResultList& children = sf->GetChildren();
1040 for (size_t i = 0; i < children.size(); ++i) {
1041 CSearchFile* sfc = children.at(i);
1042 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
1043 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
1047 return response;
1050 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
1052 CECPacket *response = new CECPacket(EC_OP_STRINGS);
1053 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1054 const CECTag &tag = *it;
1055 CMD4Hash hash = tag.GetMD4Data();
1056 uint8 category = tag.GetFirstTagSafe()->GetInt();
1057 theApp->searchlist->AddFileToDownloadByHash(hash, category);
1059 return response;
1062 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
1064 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
1065 theApp->searchlist->StopSearch();
1066 return reply;
1069 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
1071 wxString response;
1073 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetFirstTagSafe();
1074 theApp->searchlist->RemoveResults(0xffffffff);
1076 CSearchList::CSearchParams params;
1077 params.searchString = search_request->SearchText();
1078 params.typeText = search_request->SearchFileType();
1079 params.extension = search_request->SearchExt();
1080 params.minSize = search_request->MinSize();
1081 params.maxSize = search_request->MaxSize();
1082 params.availability = search_request->Avail();
1085 EC_SEARCH_TYPE search_type = search_request->SearchType();
1086 SearchType core_search_type = LocalSearch;
1087 uint32 op = EC_OP_FAILED;
1088 switch (search_type) {
1089 case EC_SEARCH_GLOBAL:
1090 core_search_type = GlobalSearch;
1091 case EC_SEARCH_KAD:
1092 if (core_search_type != GlobalSearch) { // Not a global search obviously
1093 core_search_type = KadSearch;
1095 case EC_SEARCH_LOCAL: {
1096 uint32 search_id = 0xffffffff;
1097 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
1098 if (!error.IsEmpty()) {
1099 response = error;
1100 } else {
1101 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
1102 op = EC_OP_STRINGS;
1104 break;
1106 case EC_SEARCH_WEB:
1107 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
1108 break;
1111 CECPacket *reply = new CECPacket(op);
1112 // error or search in progress
1113 reply->AddTag(CECTag(EC_TAG_STRING, response));
1115 return reply;
1118 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1120 CECPacket *response = new CECPacket(EC_OP_NOOP);
1121 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1122 const CECTag &tag = *it;
1123 CMD4Hash hash = tag.GetMD4Data();
1124 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1125 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1126 if ( !cur_file ) {
1127 continue;
1129 if (prio == PR_AUTO) {
1130 cur_file->SetAutoUpPriority(1);
1131 cur_file->UpdateAutoUpPriority();
1132 } else {
1133 cur_file->SetAutoUpPriority(0);
1134 cur_file->SetUpPriority(prio);
1136 Notify_SharedFilesUpdateItem(cur_file);
1139 return response;
1142 void CPartFile_Encoder::Encode(CECTag *parent)
1145 // Source part frequencies
1147 CKnownFile_Encoder::Encode(parent);
1150 // Gaps
1152 const CGapList& gaplist = m_PartFile()->GetGapList();
1153 const size_t gap_list_size = gaplist.size();
1154 ArrayOfUInts64 gaps;
1155 gaps.reserve(gap_list_size * 2);
1157 for (CGapList::const_iterator curr_pos = gaplist.begin();
1158 curr_pos != gaplist.end(); ++curr_pos) {
1159 gaps.push_back(curr_pos.start());
1160 gaps.push_back(curr_pos.end());
1163 int gap_enc_size = 0;
1164 bool changed;
1165 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1166 if (changed) {
1167 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1169 delete[] gap_enc_data;
1172 // Requested blocks
1174 ArrayOfUInts64 req_buffer;
1175 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1176 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1178 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1179 Requested_Block_Struct* block = *curr_pos2;
1180 req_buffer.push_back(block->StartOffset);
1181 req_buffer.push_back(block->EndOffset);
1183 int req_enc_size = 0;
1184 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1185 if (changed) {
1186 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1188 delete[] req_enc_data;
1191 // Source names
1193 // First count occurrence of all source names
1195 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1196 typedef std::map<wxString, int> strIntMap;
1197 strIntMap nameMap;
1198 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1199 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1200 const CClientRef &cur_src = *it;
1201 if (cur_src.GetRequestFile() != m_file || cur_src.GetClientFilename().Length() == 0) {
1202 continue;
1204 const wxString &name = cur_src.GetClientFilename();
1205 strIntMap::iterator itm = nameMap.find(name);
1206 if (itm == nameMap.end()) {
1207 nameMap[name] = 1;
1208 } else {
1209 itm->second++;
1213 // Go through our last list
1215 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1216 SourcenameItemMap::iterator it2 = it1++;
1217 strIntMap::iterator itm = nameMap.find(it2->second.name);
1218 if (itm == nameMap.end()) {
1219 // name doesn't exist anymore, tell client to forget it
1220 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1221 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1222 sourceNames.AddTag(tag);
1223 // and forget it
1224 m_sourcenameItemMap.erase(it2);
1225 } else {
1226 // update count if it changed
1227 if (it2->second.count != itm->second) {
1228 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1229 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1230 sourceNames.AddTag(tag);
1231 it2->second.count = itm->second;
1233 // remove it from nameMap so that only new names are left there
1234 nameMap.erase(itm);
1238 // Add new names
1240 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1241 int id = ++m_sourcenameID;
1242 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1243 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1244 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1245 sourceNames.AddTag(tag);
1246 // remember it
1247 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1249 if (sourceNames.HasChildTags()) {
1250 parent->AddTag(sourceNames);
1255 void CPartFile_Encoder::ResetEncoder()
1257 CKnownFile_Encoder::ResetEncoder();
1258 m_gap_status.ResetEncoder();
1259 m_req_status.ResetEncoder();
1262 void CKnownFile_Encoder::Encode(CECTag *parent)
1265 // Source part frequencies
1267 // Reference to the availability list
1268 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1269 ((CPartFile*)m_file)->m_SrcpartFrequency :
1270 m_file->m_AvailPartFrequency;
1271 // Don't add tag if available parts aren't populated yet.
1272 if (!list.empty()) {
1273 int part_enc_size;
1274 bool changed;
1275 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1276 if (changed) {
1277 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1279 delete[] part_enc_data;
1283 static CECPacket *GetStatsGraphs(const CECPacket *request)
1285 CECPacket *response = NULL;
1287 switch (request->GetDetailLevel()) {
1288 case EC_DETAIL_WEB:
1289 case EC_DETAIL_FULL: {
1290 double dTimestamp = 0.0;
1291 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1292 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1294 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1295 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1296 uint32 *graphData;
1297 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1298 if (numPoints) {
1299 response = new CECPacket(EC_OP_STATSGRAPHS);
1300 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1301 delete [] graphData;
1302 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1303 } else {
1304 response = new CECPacket(EC_OP_FAILED);
1305 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1307 break;
1309 case EC_DETAIL_INC_UPDATE:
1310 case EC_DETAIL_UPDATE:
1311 case EC_DETAIL_CMD:
1312 // No graphs
1313 response = new CECPacket(EC_OP_FAILED);
1314 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1315 break;
1317 if (!response) {
1318 response = new CECPacket(EC_OP_FAILED);
1319 // Unknown reason
1322 return response;
1325 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1328 if ( !request ) {
1329 return 0;
1332 CECPacket *response = NULL;
1334 switch (request->GetOpCode()) {
1336 // Misc commands
1338 case EC_OP_SHUTDOWN:
1339 if (!theApp->IsOnShutDown()) {
1340 response = new CECPacket(EC_OP_NOOP);
1341 AddLogLineC(_("External Connection: shutdown requested"));
1342 #ifndef AMULE_DAEMON
1344 wxCloseEvent evt;
1345 evt.SetCanVeto(false);
1346 theApp->ShutDown(evt);
1348 #else
1349 theApp->ExitMainLoop();
1350 #endif
1351 } else {
1352 response = new CECPacket(EC_OP_FAILED);
1353 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1355 break;
1356 case EC_OP_ADD_LINK:
1357 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1358 const CECTag &tag = *it;
1359 wxString link = tag.GetStringData();
1360 int category = 0;
1361 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1362 if (cattag) {
1363 category = cattag->GetInt();
1365 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link);
1366 if ( theApp->downloadqueue->AddLink(link, category) ) {
1367 response = new CECPacket(EC_OP_NOOP);
1368 } else {
1369 // Error messages are printed by the add function.
1370 response = new CECPacket(EC_OP_FAILED);
1371 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1374 break;
1376 // Status requests
1378 case EC_OP_STAT_REQ:
1379 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1380 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1381 break;
1382 case EC_OP_GET_CONNSTATE:
1383 response = new CECPacket(EC_OP_MISC_DATA);
1384 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1385 break;
1389 case EC_OP_GET_SHARED_FILES:
1390 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1391 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1393 break;
1394 case EC_OP_GET_DLOAD_QUEUE:
1395 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1396 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1398 break;
1400 // This will evolve into an update-all for inc tags
1402 case EC_OP_GET_UPDATE:
1403 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1404 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1406 break;
1407 case EC_OP_GET_ULOAD_QUEUE:
1408 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1409 break;
1410 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1411 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1412 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1413 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1414 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1415 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1416 case EC_OP_PARTFILE_PAUSE:
1417 case EC_OP_PARTFILE_RESUME:
1418 case EC_OP_PARTFILE_STOP:
1419 case EC_OP_PARTFILE_PRIO_SET:
1420 case EC_OP_PARTFILE_DELETE:
1421 case EC_OP_PARTFILE_SET_CAT:
1422 response = Get_EC_Response_PartFile_Cmd(request);
1423 break;
1424 case EC_OP_SHAREDFILES_RELOAD:
1425 theApp->sharedfiles->Reload();
1426 response = new CECPacket(EC_OP_NOOP);
1427 break;
1428 case EC_OP_SHARED_SET_PRIO:
1429 response = Get_EC_Response_Set_SharedFile_Prio(request);
1430 break;
1431 case EC_OP_RENAME_FILE: {
1432 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1433 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1434 // search first in downloadqueue - it might be in known files as well
1435 CKnownFile* file = theApp->downloadqueue->GetFileByID(fileHash);
1436 if (!file) {
1437 file = theApp->knownfiles->FindKnownFileByID(fileHash);
1439 if (!file) {
1440 response = new CECPacket(EC_OP_FAILED);
1441 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1442 break;
1444 if (newName.IsEmpty()) {
1445 response = new CECPacket(EC_OP_FAILED);
1446 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1447 break;
1450 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1451 response = new CECPacket(EC_OP_NOOP);
1452 } else {
1453 response = new CECPacket(EC_OP_FAILED);
1454 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1457 break;
1459 case EC_OP_CLEAR_COMPLETED: {
1460 ListOfUInts32 toClear;
1461 for (CECTag::const_iterator it = request->begin(); it != request->end(); it++) {
1462 if (it->GetTagName() == EC_TAG_ECID) {
1463 toClear.push_back(it->GetInt());
1466 theApp->downloadqueue->ClearCompleted(toClear);
1467 response = new CECPacket(EC_OP_NOOP);
1468 break;
1470 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE: {
1471 theApp->sharedfiles->Reload();
1472 uint32 idClient = request->GetTagByNameSafe(EC_TAG_CLIENT)->GetInt();
1473 CUpDownClient * client = theApp->clientlist->FindClientByECID(idClient);
1474 CMD4Hash idFile = request->GetTagByNameSafe(EC_TAG_PARTFILE)->GetMD4Data();
1475 CPartFile * file = theApp->downloadqueue->GetFileByID(idFile);
1476 if (client && file) {
1477 client->SwapToAnotherFile( true, false, false, file);
1479 response = new CECPacket(EC_OP_NOOP);
1480 break;
1482 case EC_OP_SHARED_FILE_SET_COMMENT: {
1483 CMD4Hash hash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1484 CKnownFile * file = theApp->sharedfiles->GetFileByID(hash);
1485 if (file) {
1486 wxString newComment = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT)->GetStringData();
1487 uint8 newRating = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING)->GetInt();
1488 CoreNotify_KnownFile_Comment_Set(file, newComment, newRating);
1490 response = new CECPacket(EC_OP_NOOP);
1491 break;
1495 // Server commands
1497 case EC_OP_SERVER_ADD:
1498 response = Get_EC_Response_Server_Add(request);
1499 break;
1500 case EC_OP_SERVER_DISCONNECT:
1501 case EC_OP_SERVER_CONNECT:
1502 case EC_OP_SERVER_REMOVE:
1503 response = Get_EC_Response_Server(request);
1504 break;
1505 case EC_OP_GET_SERVER_LIST: {
1506 response = new CECPacket(EC_OP_SERVER_LIST);
1507 if (!thePrefs::GetNetworkED2K()) {
1508 // Kad only: just send an empty list
1509 break;
1511 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1512 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1513 for (
1514 std::vector<const CServer*>::const_iterator it = servers.begin();
1515 it != servers.end();
1516 ++it
1518 response->AddTag(CEC_Server_Tag(*it, detail_level));
1521 break;
1522 case EC_OP_SERVER_UPDATE_FROM_URL: {
1523 wxString url = request->GetFirstTagSafe()->GetStringData();
1525 // Save the new url, and update the UI (if not amuled).
1526 Notify_ServersURLChanged(url);
1527 thePrefs::SetEd2kServersUrl(url);
1529 theApp->serverlist->UpdateServerMetFromURL(url);
1530 response = new CECPacket(EC_OP_NOOP);
1531 break;
1533 case EC_OP_SERVER_SET_STATIC_PRIO: {
1534 uint32 ecid = request->GetTagByNameSafe(EC_TAG_SERVER)->GetInt();
1535 CServer * server = theApp->serverlist->GetServerByECID(ecid);
1536 if (server) {
1537 const CECTag * staticTag = request->GetTagByName(EC_TAG_SERVER_STATIC);
1538 if (staticTag) {
1539 theApp->serverlist->SetStaticServer(server, staticTag->GetInt() > 0);
1541 const CECTag * prioTag = request->GetTagByName(EC_TAG_SERVER_PRIO);
1542 if (prioTag) {
1543 theApp->serverlist->SetServerPrio(server, prioTag->GetInt());
1546 response = new CECPacket(EC_OP_NOOP);
1547 break;
1550 // Friends
1552 case EC_OP_FRIEND:
1553 response = Get_EC_Response_Friend(request);
1554 break;
1557 // IPFilter
1559 case EC_OP_IPFILTER_RELOAD:
1560 NotifyAlways_IPFilter_Reload();
1561 response = new CECPacket(EC_OP_NOOP);
1562 break;
1564 case EC_OP_IPFILTER_UPDATE: {
1565 wxString url = request->GetFirstTagSafe()->GetStringData();
1566 if (url.IsEmpty()) {
1567 url = thePrefs::IPFilterURL();
1569 NotifyAlways_IPFilter_Update(url);
1570 response = new CECPacket(EC_OP_NOOP);
1571 break;
1574 // Search
1576 case EC_OP_SEARCH_START:
1577 response = Get_EC_Response_Search(request);
1578 break;
1580 case EC_OP_SEARCH_STOP:
1581 response = Get_EC_Response_Search_Stop(request);
1582 break;
1584 case EC_OP_SEARCH_RESULTS:
1585 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1586 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1587 } else {
1588 response = Get_EC_Response_Search_Results(request);
1590 break;
1592 case EC_OP_SEARCH_PROGRESS:
1593 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1594 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1595 theApp->searchlist->GetSearchProgress()));
1596 break;
1598 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1599 response = Get_EC_Response_Search_Results_Download(request);
1600 break;
1602 // Preferences
1604 case EC_OP_GET_PREFERENCES:
1605 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1606 break;
1607 case EC_OP_SET_PREFERENCES:
1608 ((CEC_Prefs_Packet *)request)->Apply();
1609 theApp->glob_prefs->Save();
1610 if (thePrefs::IsFilteringClients()) {
1611 theApp->clientlist->FilterQueues();
1613 if (thePrefs::IsFilteringServers()) {
1614 theApp->serverlist->FilterServers();
1616 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1617 theApp->DisconnectED2K();
1619 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1620 theApp->StopKad();
1622 response = new CECPacket(EC_OP_NOOP);
1623 break;
1625 case EC_OP_CREATE_CATEGORY:
1626 if ( request->GetTagCount() == 1 ) {
1627 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1628 if (tag->Create()) {
1629 response = new CECPacket(EC_OP_NOOP);
1630 } else {
1631 response = new CECPacket(EC_OP_FAILED);
1632 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1633 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1635 Notify_CategoryAdded();
1636 } else {
1637 response = new CECPacket(EC_OP_NOOP);
1639 break;
1640 case EC_OP_UPDATE_CATEGORY:
1641 if ( request->GetTagCount() == 1 ) {
1642 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1643 if (tag->Apply()) {
1644 response = new CECPacket(EC_OP_NOOP);
1645 } else {
1646 response = new CECPacket(EC_OP_FAILED);
1647 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1648 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1650 Notify_CategoryUpdate(tag->GetInt());
1651 } else {
1652 response = new CECPacket(EC_OP_NOOP);
1654 break;
1655 case EC_OP_DELETE_CATEGORY:
1656 if ( request->GetTagCount() == 1 ) {
1657 uint32 cat = request->GetFirstTagSafe()->GetInt();
1658 // this noes not only update the gui, but actually deletes the cat
1659 Notify_CategoryDelete(cat);
1661 response = new CECPacket(EC_OP_NOOP);
1662 break;
1665 // Logging
1667 case EC_OP_ADDLOGLINE:
1668 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1669 AddLogLineC(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1670 } else {
1671 AddLogLineN(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1673 response = new CECPacket(EC_OP_NOOP);
1674 break;
1675 case EC_OP_ADDDEBUGLOGLINE:
1676 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1677 AddDebugLogLineC(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1678 } else {
1679 AddDebugLogLineN(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1681 response = new CECPacket(EC_OP_NOOP);
1682 break;
1683 case EC_OP_GET_LOG:
1684 response = new CECPacket(EC_OP_LOG);
1685 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1686 break;
1687 case EC_OP_GET_DEBUGLOG:
1688 response = new CECPacket(EC_OP_DEBUGLOG);
1689 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1690 break;
1691 case EC_OP_RESET_LOG:
1692 theApp->GetLog(true);
1693 response = new CECPacket(EC_OP_NOOP);
1694 break;
1695 case EC_OP_RESET_DEBUGLOG:
1696 theApp->GetDebugLog(true);
1697 response = new CECPacket(EC_OP_NOOP);
1698 break;
1699 case EC_OP_GET_LAST_LOG_ENTRY:
1701 wxString tmp = theApp->GetLog(false);
1702 if (tmp.Last() == '\n') {
1703 tmp.RemoveLast();
1705 response = new CECPacket(EC_OP_LOG);
1706 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1708 break;
1709 case EC_OP_GET_SERVERINFO:
1710 response = new CECPacket(EC_OP_SERVERINFO);
1711 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1712 break;
1713 case EC_OP_CLEAR_SERVERINFO:
1714 theApp->GetServerLog(true);
1715 response = new CECPacket(EC_OP_NOOP);
1716 break;
1718 // Statistics
1720 case EC_OP_GET_STATSGRAPHS:
1721 response = GetStatsGraphs(request);
1722 break;
1723 case EC_OP_GET_STATSTREE: {
1724 theApp->m_statistics->UpdateStatsTree();
1725 response = new CECPacket(EC_OP_STATSTREE);
1726 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1727 if (tree) {
1728 response->AddTag(*tree);
1729 delete tree;
1731 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1732 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1733 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1735 break;
1739 // Kad
1741 case EC_OP_KAD_START:
1742 if (thePrefs::GetNetworkKademlia()) {
1743 response = new CECPacket(EC_OP_NOOP);
1744 if ( !Kademlia::CKademlia::IsRunning() ) {
1745 Kademlia::CKademlia::Start();
1746 theApp->ShowConnectionState();
1748 } else {
1749 response = new CECPacket(EC_OP_FAILED);
1750 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1752 break;
1753 case EC_OP_KAD_STOP:
1754 theApp->StopKad();
1755 theApp->ShowConnectionState();
1756 response = new CECPacket(EC_OP_NOOP);
1757 break;
1758 case EC_OP_KAD_UPDATE_FROM_URL: {
1759 wxString url = request->GetFirstTagSafe()->GetStringData();
1761 // Save the new url, and update the UI (if not amuled).
1762 Notify_NodesURLChanged(url);
1763 thePrefs::SetKadNodesUrl(url);
1765 theApp->UpdateNotesDat(url);
1766 response = new CECPacket(EC_OP_NOOP);
1767 break;
1769 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1770 if (thePrefs::GetNetworkKademlia()) {
1771 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1772 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1773 theApp->ShowConnectionState();
1774 response = new CECPacket(EC_OP_NOOP);
1775 } else {
1776 response = new CECPacket(EC_OP_FAILED);
1777 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1779 break;
1782 // Networks
1783 // These requests are currently used only in the text client
1785 case EC_OP_CONNECT:
1786 if (thePrefs::GetNetworkED2K()) {
1787 response = new CECPacket(EC_OP_STRINGS);
1788 if (theApp->IsConnectedED2K()) {
1789 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1790 } else {
1791 theApp->serverconnect->ConnectToAnyServer();
1792 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1795 if (thePrefs::GetNetworkKademlia()) {
1796 if (!response) {
1797 response = new CECPacket(EC_OP_STRINGS);
1799 if (theApp->IsConnectedKad()) {
1800 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1801 } else {
1802 theApp->StartKad();
1803 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1806 if (response) {
1807 theApp->ShowConnectionState();
1808 } else {
1809 response = new CECPacket(EC_OP_FAILED);
1810 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1812 break;
1813 case EC_OP_DISCONNECT:
1814 if (theApp->IsConnected()) {
1815 response = new CECPacket(EC_OP_STRINGS);
1816 if (theApp->IsConnectedED2K()) {
1817 theApp->serverconnect->Disconnect();
1818 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1820 if (theApp->IsConnectedKad()) {
1821 theApp->StopKad();
1822 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1824 theApp->ShowConnectionState();
1825 } else {
1826 response = new CECPacket(EC_OP_NOOP);
1828 break;
1830 if (!response) {
1831 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request->GetOpCode());
1832 wxFAIL;
1833 response = new CECPacket(EC_OP_FAILED);
1834 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1836 return response;
1840 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1844 * Core general status
1846 ECStatusMsgSource::ECStatusMsgSource()
1848 m_last_ed2k_status_sent = 0xffffffff;
1849 m_last_kad_status_sent = 0xffffffff;
1850 m_server = (void *)0xffffffff;
1853 uint32 ECStatusMsgSource::GetEd2kStatus()
1855 if ( theApp->IsConnectedED2K() ) {
1856 return theApp->GetED2KID();
1857 } else if ( theApp->serverconnect->IsConnecting() ) {
1858 return 1;
1859 } else {
1860 return 0;
1864 uint32 ECStatusMsgSource::GetKadStatus()
1866 if ( theApp->IsConnectedKad() ) {
1867 return 1;
1868 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1869 return 2;
1870 } else if ( Kademlia::CKademlia::IsRunning() ) {
1871 return 3;
1873 return 0;
1876 CECPacket *ECStatusMsgSource::GetNextPacket()
1878 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1879 (m_last_kad_status_sent != GetKadStatus()) ||
1880 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1882 m_last_ed2k_status_sent = GetEd2kStatus();
1883 m_last_kad_status_sent = GetKadStatus();
1884 m_server = theApp->serverconnect->GetCurrentServer();
1886 CECPacket *response = new CECPacket(EC_OP_STATS);
1887 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1888 return response;
1890 return 0;
1894 * Downloading files
1896 ECPartFileMsgSource::ECPartFileMsgSource()
1898 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1899 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1900 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1901 m_dirty_status[cur_file->GetFileHash()] = status;
1905 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1907 CMD4Hash filehash = file->GetFileHash();
1908 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1909 m_dirty_status[filehash].m_dirty = true;;
1913 void ECPartFileMsgSource::SetNew(CPartFile *file)
1915 CMD4Hash filehash = file->GetFileHash();
1916 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1917 PARTFILE_STATUS status = { true, false, false, false, true, file };
1918 m_dirty_status[filehash] = status;
1921 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1923 CMD4Hash filehash = file->GetFileHash();
1924 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1926 m_dirty_status[filehash].m_finished = true;
1929 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1931 CMD4Hash filehash = file->GetFileHash();
1932 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1934 m_dirty_status[filehash].m_removed = true;
1937 CECPacket *ECPartFileMsgSource::GetNextPacket()
1939 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1940 it != m_dirty_status.end(); it++) {
1941 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1942 CMD4Hash filehash = it->first;
1944 CPartFile *partfile = it->second.m_file;
1946 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1947 if ( it->second.m_removed ) {
1948 CECTag tag(EC_TAG_PARTFILE, filehash);
1949 packet->AddTag(tag);
1950 m_dirty_status.erase(it);
1951 } else {
1952 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1953 packet->AddTag(tag);
1955 m_dirty_status[filehash].m_new = false;
1956 m_dirty_status[filehash].m_dirty = false;
1958 return packet;
1961 return 0;
1965 * Shared files - similar to downloading
1967 ECKnownFileMsgSource::ECKnownFileMsgSource()
1969 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1970 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1971 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1972 m_dirty_status[cur_file->GetFileHash()] = status;
1976 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1978 CMD4Hash filehash = file->GetFileHash();
1979 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1980 m_dirty_status[filehash].m_dirty = true;;
1984 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1986 CMD4Hash filehash = file->GetFileHash();
1987 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1988 KNOWNFILE_STATUS status = { true, false, false, true, file };
1989 m_dirty_status[filehash] = status;
1992 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1994 CMD4Hash filehash = file->GetFileHash();
1995 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1997 m_dirty_status[filehash].m_removed = true;
2000 CECPacket *ECKnownFileMsgSource::GetNextPacket()
2002 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
2003 it != m_dirty_status.end(); it++) {
2004 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
2005 CMD4Hash filehash = it->first;
2007 CKnownFile *partfile = it->second.m_file;
2009 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
2010 if ( it->second.m_removed ) {
2011 CECTag tag(EC_TAG_PARTFILE, filehash);
2012 packet->AddTag(tag);
2013 m_dirty_status.erase(it);
2014 } else {
2015 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
2016 packet->AddTag(tag);
2018 m_dirty_status[filehash].m_new = false;
2019 m_dirty_status[filehash].m_dirty = false;
2021 return packet;
2024 return 0;
2028 * Notification about search status
2030 ECSearchMsgSource::ECSearchMsgSource()
2034 CECPacket *ECSearchMsgSource::GetNextPacket()
2036 if ( m_dirty_status.empty() ) {
2037 return 0;
2040 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
2041 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
2042 it != m_dirty_status.end(); it++) {
2044 if ( it->second.m_new ) {
2045 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
2046 it->second.m_new = false;
2047 } else if ( it->second.m_dirty ) {
2048 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
2053 return response;
2056 void ECSearchMsgSource::FlushStatus()
2058 m_dirty_status.clear();
2061 void ECSearchMsgSource::SetDirty(CSearchFile *file)
2063 if ( m_dirty_status.count(file->GetFileHash()) ) {
2064 m_dirty_status[file->GetFileHash()].m_dirty = true;
2065 } else {
2066 m_dirty_status[file->GetFileHash()].m_new = true;
2067 m_dirty_status[file->GetFileHash()].m_dirty = true;
2068 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
2069 m_dirty_status[file->GetFileHash()].m_file = file;
2073 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
2075 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
2079 * Notification about uploading clients
2081 CECPacket *ECClientMsgSource::GetNextPacket()
2083 return 0;
2087 // Notification iface per-client
2089 ECNotifier::ECNotifier()
2093 ECNotifier::~ECNotifier()
2095 while (m_msg_source.begin() != m_msg_source.end())
2096 Remove_EC_Client(m_msg_source.begin()->first);
2099 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
2101 CECPacket *packet = 0;
2103 // priority 0 is highest
2105 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2106 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
2107 break;
2110 return packet;
2113 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
2116 // OnOutput is called for a first time before
2117 // socket is registered
2119 if ( m_msg_source.count(sock) ) {
2120 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2121 if ( !notifier_array ) {
2122 return 0;
2124 CECPacket *packet = GetNextPacket(notifier_array);
2125 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
2126 return packet;
2127 } else {
2128 return 0;
2133 // Interface to notification macros
2135 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
2137 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2138 i != m_msg_source.end(); i++) {
2139 CECServerSocket *sock = i->first;
2140 if ( sock->HaveNotificationSupport() ) {
2141 ECUpdateMsgSource **notifier_array = i->second;
2142 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
2145 NextPacketToSocket();
2148 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
2150 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2151 i != m_msg_source.end(); i++) {
2152 ECUpdateMsgSource **notifier_array = i->second;
2153 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
2155 NextPacketToSocket();
2158 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
2160 // per-partfile source list is not supported (yet), and IMHO quite useless
2163 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
2165 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2166 i != m_msg_source.end(); i++) {
2167 ECUpdateMsgSource **notifier_array = i->second;
2168 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
2170 NextPacketToSocket();
2173 void ECNotifier::DownloadFile_AddSource(CPartFile *)
2175 // per-partfile source list is not supported (yet), and IMHO quite useless
2178 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
2180 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2181 i != m_msg_source.end(); i++) {
2182 ECUpdateMsgSource **notifier_array = i->second;
2183 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
2185 NextPacketToSocket();
2188 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
2190 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2191 i != m_msg_source.end(); i++) {
2192 ECUpdateMsgSource **notifier_array = i->second;
2193 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
2195 NextPacketToSocket();
2198 void ECNotifier::SharedFile_RemoveAllFiles()
2200 // need to figure out what to do here
2203 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2205 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2206 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2207 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2208 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2209 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2210 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2212 m_msg_source[sock] = notifier_array;
2215 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2217 if (m_msg_source.count(sock)) {
2218 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2220 m_msg_source.erase(sock);
2222 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2223 delete notifier_array[i];
2225 delete [] notifier_array;
2229 void ECNotifier::NextPacketToSocket()
2231 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2232 i != m_msg_source.end(); i++) {
2233 CECServerSocket *sock = i->first;
2234 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2235 ECUpdateMsgSource **notifier_array = i->second;
2236 CECPacket *packet = GetNextPacket(notifier_array);
2237 if ( packet ) {
2238 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2239 sock->SendPacket(packet);
2245 // File_checked_for_headers