Don't allow autoconf 2.70, it's known to fail
[amule.git] / src / ExternalConn.cpp
blobb65b5e29c68b220cd0246d3e9f2a2628763e2b97
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.
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"
58 #include "Statistics.h"
61 //-------------------- File_Encoder --------------------
65 * Encode 'obtained parts' info to be sent to remote gui
67 class CKnownFile_Encoder {
68 // number of sources for each part for progress bar colouring
69 RLE_Data m_enc_data;
70 protected:
71 const CKnownFile *m_file;
72 public:
73 CKnownFile_Encoder(const CKnownFile *file = 0) { m_file = file; }
75 virtual ~CKnownFile_Encoder() {}
77 virtual void Encode(CECTag *parent_tag);
79 virtual void ResetEncoder()
81 m_enc_data.ResetEncoder();
84 virtual void SetShared() { }
85 virtual bool IsShared() { return true; }
86 virtual bool IsPartFile_Encoder() { return false; }
87 const CKnownFile * GetFile() { return m_file; }
90 /*!
91 * PartStatus strings and gap lists are quite long - RLE encoding will help.
93 * Instead of sending each time full part-status string, send
94 * RLE encoded difference from previous one.
96 * PartFileEncoderData class is used for decode only,
97 * while CPartFile_Encoder is used for encode only.
99 class CPartFile_Encoder : public CKnownFile_Encoder {
100 // blocks requested for download
101 RLE_Data m_req_status;
102 // gap list
103 RLE_Data m_gap_status;
104 // source names
105 SourcenameItemMap m_sourcenameItemMap;
106 // counter for unique source name ids
107 int m_sourcenameID;
108 // not all part files are shared (only when at least one part is complete)
109 bool m_shared;
111 // cast inherited member to CPartFile
112 const CPartFile * m_PartFile() { wxCHECK(m_file->IsCPartFile(), NULL); return static_cast<const CPartFile *>(m_file); }
113 public:
114 // encoder side
115 CPartFile_Encoder(const CPartFile *file = 0) : CKnownFile_Encoder(file)
117 m_sourcenameID = 0;
118 m_shared = false;
121 virtual ~CPartFile_Encoder() {}
123 // encode - take data from m_file
124 virtual void Encode(CECTag *parent_tag);
126 // Encoder may reset history if full info requested
127 virtual void ResetEncoder();
129 virtual void SetShared() { m_shared = true; }
130 virtual bool IsShared() { return m_shared; }
131 virtual bool IsPartFile_Encoder() { return true; }
134 class CFileEncoderMap : public std::map<uint32, CKnownFile_Encoder*> {
135 typedef std::set<uint32> IDSet;
136 public:
137 ~CFileEncoderMap();
138 void UpdateEncoders();
141 CFileEncoderMap::~CFileEncoderMap()
143 // DeleteContents() causes infinite recursion here!
144 for (iterator it = begin(); it != end(); ++it) {
145 delete it->second;
149 // Check if encoder contains files that are no longer used
150 // or if we have new files without encoder yet.
151 void CFileEncoderMap::UpdateEncoders()
153 IDSet curr_files, dead_files;
154 // Downloads
155 std::vector<CPartFile*> downloads;
156 theApp->downloadqueue->CopyFileList(downloads, true);
157 for (uint32 i = downloads.size(); i--;) {
158 uint32 id = downloads[i]->ECID();
159 curr_files.insert(id);
160 if (!count(id)) {
161 (*this)[id] = new CPartFile_Encoder(downloads[i]);
164 // Shares
165 std::vector<CKnownFile*> shares;
166 theApp->sharedfiles->CopyFileList(shares);
167 for (uint32 i = shares.size(); i--;) {
168 uint32 id = shares[i]->ECID();
169 // Check if it is already there.
170 // The curr_files.count(id) is enough, the IsCPartFile() is just a speedup.
171 if (shares[i]->IsCPartFile() && curr_files.count(id)) {
172 (*this)[id]->SetShared();
173 continue;
175 curr_files.insert(id);
176 if (!count(id)) {
177 (*this)[id] = new CKnownFile_Encoder(shares[i]);
180 // Check for removed files, and store them in a set for deletion.
181 // (std::map documentation is unclear if a construct like
182 // iterator to_del = it++; erase(to_del) ;
183 // works or invalidates it too.)
184 for (iterator it = begin(); it != end(); ++it) {
185 if (!curr_files.count(it->first)) {
186 dead_files.insert(it->first);
189 // then delete them
190 for (IDSet::iterator it = dead_files.begin(); it != dead_files.end(); ++it) {
191 iterator it2 = find(*it);
192 delete it2->second;
193 erase(it2);
198 //-------------------- CECServerSocket --------------------
200 class CECServerSocket : public CECMuleSocket
202 public:
203 CECServerSocket(ECNotifier *notifier);
204 virtual ~CECServerSocket();
206 virtual const CECPacket *OnPacketReceived(const CECPacket *packet, uint32 trueSize);
207 virtual void OnLost();
209 virtual void WriteDoneAndQueueEmpty();
211 void ResetLog() { m_LoggerAccess.Reset(); }
212 private:
213 ECNotifier *m_ec_notifier;
215 const CECPacket *Authenticate(const CECPacket *);
217 enum {
218 CONN_INIT,
219 CONN_SALT_SENT,
220 CONN_ESTABLISHED,
221 CONN_FAILED
222 } m_conn_state;
224 uint64_t m_passwd_salt;
225 CLoggerAccess m_LoggerAccess;
226 CFileEncoderMap m_FileEncoder;
227 CObjTagMap m_obj_tagmap;
228 CECPacket *ProcessRequest2(const CECPacket *request);
230 virtual bool IsAuthorized() { return m_conn_state == CONN_ESTABLISHED; }
234 CECServerSocket::CECServerSocket(ECNotifier *notifier)
236 CECMuleSocket(true),
237 m_conn_state(CONN_INIT),
238 m_passwd_salt(GetRandomUint64())
240 wxASSERT(theApp->ECServerHandler);
241 theApp->ECServerHandler->AddSocket(this);
242 m_ec_notifier = notifier;
246 CECServerSocket::~CECServerSocket()
248 wxASSERT(theApp->ECServerHandler);
249 theApp->ECServerHandler->RemoveSocket(this);
253 const CECPacket *CECServerSocket::OnPacketReceived(const CECPacket *packet, uint32 trueSize)
255 packet->DebugPrint(true, trueSize);
257 const CECPacket *reply = NULL;
259 if (m_conn_state == CONN_FAILED) {
260 // Client didn't close the socket when authentication failed.
261 AddLogLineN(_("Client sent packet after authentication failed."));
262 CloseSocket();
265 if (m_conn_state != CONN_ESTABLISHED) {
266 // This is called twice:
267 // 1) send salt
268 // 2) verify password
269 reply = Authenticate(packet);
270 } else {
271 reply = ProcessRequest2(packet);
273 return reply;
277 void CECServerSocket::OnLost()
279 AddLogLineN(_("External connection closed."));
280 theApp->ECServerHandler->m_ec_notifier->Remove_EC_Client(this);
281 DestroySocket();
284 void CECServerSocket::WriteDoneAndQueueEmpty()
286 if ( HaveNotificationSupport() && (m_conn_state == CONN_ESTABLISHED) ) {
287 CECPacket *packet = m_ec_notifier->GetNextPacket(this);
288 if ( packet ) {
289 SendPacket(packet);
291 } else {
292 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
296 //-------------------- ExternalConn --------------------
298 #ifndef ASIO_SOCKETS
299 enum
300 { // id for sockets
301 SERVER_ID = 1000
305 BEGIN_EVENT_TABLE(ExternalConn, wxEvtHandler)
306 EVT_SOCKET(SERVER_ID, ExternalConn::OnServerEvent)
307 END_EVENT_TABLE()
308 #endif
311 ExternalConn::ExternalConn(amuleIPV4Address addr, wxString *msg)
313 wxString msgLocal;
314 m_ECServer = NULL;
315 // Are we allowed to accept External Connections?
316 if ( thePrefs::AcceptExternalConnections() ) {
317 // We must have a valid password, otherwise we will not allow EC connections
318 if (thePrefs::ECPassword().IsEmpty()) {
319 *msg += wxT("External connections disabled due to empty password!\n");
320 AddLogLineC(_("External connections disabled due to empty password!"));
321 return;
324 // Create the socket
325 m_ECServer = new CExternalConnListener(addr, MULE_SOCKET_REUSEADDR, this);
326 #ifndef ASIO_SOCKETS
327 m_ECServer->SetEventHandler(*this, SERVER_ID);
328 m_ECServer->SetNotify(wxSOCKET_CONNECTION_FLAG);
329 #endif
330 m_ECServer->Notify(true);
332 int port = addr.Service();
333 wxString ip = addr.IPAddress();
334 if (m_ECServer->IsOk()) {
335 msgLocal = CFormat(wxT("*** TCP socket (ECServer) listening on %s:%d")) % ip % port;
336 *msg += msgLocal + wxT("\n");
337 AddLogLineN(msgLocal);
338 } else {
339 msgLocal = CFormat(wxT("Could not listen for external connections at %s:%d!")) % ip % port;
340 *msg += msgLocal + wxT("\n");
341 AddLogLineN(msgLocal);
343 } else {
344 *msg += wxT("External connections disabled in config file\n");
345 AddLogLineN(_("External connections disabled in config file"));
347 m_ec_notifier = new ECNotifier();
351 ExternalConn::~ExternalConn()
353 KillAllSockets();
354 delete m_ECServer;
355 delete m_ec_notifier;
359 void ExternalConn::AddSocket(CECServerSocket *s)
361 wxASSERT(s);
362 socket_list.insert(s);
366 void ExternalConn::RemoveSocket(CECServerSocket *s)
368 wxASSERT(s);
369 socket_list.erase(s);
373 void ExternalConn::KillAllSockets()
375 AddDebugLogLineN(logGeneral,
376 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
377 socket_list.size());
378 SocketSet::iterator it = socket_list.begin();
379 while (it != socket_list.end()) {
380 CECServerSocket *s = *(it++);
381 s->Close();
382 s->Destroy();
384 socket_list.clear();
388 void ExternalConn::ResetAllLogs()
390 SocketSet::iterator it = socket_list.begin();
391 while (it != socket_list.end()) {
392 CECServerSocket *s = *(it++);
393 s->ResetLog();
398 #ifndef ASIO_SOCKETS
399 void ExternalConn::OnServerEvent(wxSocketEvent& WXUNUSED(event))
401 m_ECServer->OnAccept();
403 #endif
406 void CExternalConnListener::OnAccept()
408 CECServerSocket *sock = new CECServerSocket(m_conn->m_ec_notifier);
409 // Accept new connection if there is one in the pending
410 // connections queue, else exit. We use Accept(FALSE) for
411 // non-blocking accept (although if we got here, there
412 // should ALWAYS be a pending connection).
413 if (AcceptWith(*sock, false)) {
414 AddLogLineN(_("New external connection accepted"));
415 } else {
416 delete sock;
417 AddLogLineN(_("ERROR: couldn't accept a new external connection"));
423 // Authentication
425 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
427 CECPacket *response;
429 if (request == NULL) {
430 return new CECPacket(EC_OP_AUTH_FAIL);
433 // Password must be specified if we are to allow remote connections
434 if ( thePrefs::ECPassword().IsEmpty() ) {
435 AddLogLineC(_("External connection refused due to empty password in preferences!"));
437 return new CECPacket(EC_OP_AUTH_FAIL);
440 if ((m_conn_state == CONN_INIT) && (request->GetOpCode() == EC_OP_AUTH_REQ) ) {
441 // cppcheck-suppress unreadVariable
442 const CECTag *clientName = request->GetTagByName(EC_TAG_CLIENT_NAME);
443 // cppcheck-suppress unreadVariable
444 const CECTag *clientVersion = request->GetTagByName(EC_TAG_CLIENT_VERSION);
446 AddLogLineN(CFormat( _("Connecting client: %s %s") )
447 % ( clientName ? clientName->GetStringData() : wxString(_("Unknown")) )
448 % ( clientVersion ? clientVersion->GetStringData() : wxString(_("Unknown version")) ) );
449 const CECTag *protocol = request->GetTagByName(EC_TAG_PROTOCOL_VERSION);
450 #ifdef EC_VERSION_ID
451 // For SVN versions, both client and server must use SVNDATE, and they must be the same
452 CMD4Hash vhash;
453 if (!vhash.Decode(wxT(EC_VERSION_ID))) {
454 response = new CECPacket(EC_OP_AUTH_FAIL);
455 response->AddTag(CECTag(EC_TAG_STRING, wxT("Fatal error, version hash is not a valid MD4-hash.")));
456 } else if (!request->GetTagByName(EC_TAG_VERSION_ID) || request->GetTagByNameSafe(EC_TAG_VERSION_ID)->GetMD4Data() != vhash) {
457 response = new CECPacket(EC_OP_AUTH_FAIL);
458 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
459 #else
460 // For release versions, we don't want to allow connections from any arbitrary SVN client.
461 if (request->GetTagByName(EC_TAG_VERSION_ID)) {
462 response = new CECPacket(EC_OP_AUTH_FAIL);
463 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("You cannot connect to a release version from an arbitrary development snapshot! *sigh* possible crash prevented")));
464 #endif
465 } else if (protocol != NULL) {
466 uint16 proto_version = protocol->GetInt();
467 if (proto_version == EC_CURRENT_PROTOCOL_VERSION) {
468 response = new CECPacket(EC_OP_AUTH_SALT);
469 response->AddTag(CECTag(EC_TAG_PASSWD_SALT, m_passwd_salt));
470 m_conn_state = CONN_SALT_SENT;
472 // So far ok, check capabilities of client
474 if (request->GetTagByName(EC_TAG_CAN_ZLIB)) {
475 m_my_flags |= EC_FLAG_ZLIB;
477 if (request->GetTagByName(EC_TAG_CAN_UTF8_NUMBERS)) {
478 m_my_flags |= EC_FLAG_UTF8_NUMBERS;
480 m_haveNotificationSupport = request->GetTagByName(EC_TAG_CAN_NOTIFY) != NULL;
481 AddDebugLogLineN(logEC, CFormat(wxT("Client capabilities: ZLIB: %s UTF8 numbers: %s Push notification: %s") )
482 % ((m_my_flags & EC_FLAG_ZLIB) ? wxT("yes") : wxT("no"))
483 % ((m_my_flags & EC_FLAG_UTF8_NUMBERS) ? wxT("yes") : wxT("no"))
484 % (m_haveNotificationSupport ? wxT("yes") : wxT("no")));
485 } else {
486 response = new CECPacket(EC_OP_AUTH_FAIL);
487 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid protocol version.")
488 + CFormat(wxT("( %#.4x != %#.4x )")) % proto_version % (uint16_t)EC_CURRENT_PROTOCOL_VERSION));
490 } else {
491 response = new CECPacket(EC_OP_AUTH_FAIL);
492 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Missing protocol version tag.")));
494 } else if ((m_conn_state == CONN_SALT_SENT) && (request->GetOpCode() == EC_OP_AUTH_PASSWD)) {
495 const CECTag *passwd = request->GetTagByName(EC_TAG_PASSWD_HASH);
496 CMD4Hash passh;
498 if (!passh.Decode(thePrefs::ECPassword())) {
499 wxString err = wxTRANSLATE("Authentication failed: invalid hash specified as EC password.");
500 AddLogLineN(wxString(wxGetTranslation(err))
501 + wxT(" ") + thePrefs::ECPassword());
502 response = new CECPacket(EC_OP_AUTH_FAIL);
503 response->AddTag(CECTag(EC_TAG_STRING, err));
504 } else {
505 wxString saltHash = MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt).GetHash();
506 wxString saltStr = CFormat(wxT("%lX")) % m_passwd_salt;
508 passh.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash).GetHash());
510 if (passwd && passwd->GetMD4Data() == passh) {
511 response = new CECPacket(EC_OP_AUTH_OK);
512 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
513 } else {
514 wxString err;
515 if (passwd) {
516 err = wxTRANSLATE("Authentication failed: wrong password.");
517 } else {
518 err = wxTRANSLATE("Authentication failed: missing password.");
521 response = new CECPacket(EC_OP_AUTH_FAIL);
522 response->AddTag(CECTag(EC_TAG_STRING, err));
523 AddLogLineN(wxGetTranslation(err));
526 } else {
527 response = new CECPacket(EC_OP_AUTH_FAIL);
528 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid request, please authenticate first.")));
531 if (response->GetOpCode() == EC_OP_AUTH_OK) {
532 m_conn_state = CONN_ESTABLISHED;
533 AddLogLineN(_("Access granted."));
534 // Establish notification handler if client supports it
535 if (HaveNotificationSupport()) {
536 theApp->ECServerHandler->m_ec_notifier->Add_EC_Client(this);
538 } else if (response->GetOpCode() == EC_OP_AUTH_FAIL) {
539 // Log message sent to client
540 if (response->GetFirstTagSafe()->IsString()) {
541 AddLogLineN(CFormat(_("Sent error message \"%s\" to client.")) % wxGetTranslation(response->GetFirstTagSafe()->GetStringData()));
543 // Access denied!
544 AddLogLineN(CFormat(_("Unauthorized access attempt from %s. Connection closed.")) % GetPeer() );
545 m_conn_state = CONN_FAILED;
548 return response;
551 // Make a Logger tag (if there are any logging messages) and add it to the response
552 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
554 if (LoggerAccess.HasString()) {
555 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
556 // Tag structure is fix: tag carries nothing, inside are the strings
557 // maximum of 200 log lines per message
558 int entries = 0;
559 wxString line;
560 while (entries < 200 && LoggerAccess.GetString(line)) {
561 tag.AddTag(CECTag(EC_TAG_STRING, line));
562 entries++;
564 response->AddTag(tag);
565 //printf("send Log tag %d %d\n", FirstEntry, entries);
569 static CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
571 CECPacket *response = new CECPacket(EC_OP_STATS);
573 switch (request->GetDetailLevel()) {
574 case EC_DETAIL_FULL:
575 // This is not an actual INC_UPDATE.
576 // amulegui only sets the detail level of the stats package to EC_DETAIL_INC_UPDATE
577 // so that the included conn state tag is created the way it is needed here.
578 case EC_DETAIL_INC_UPDATE:
579 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
580 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
581 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
582 AddLoggerTag(response, LoggerAccess);
583 // Needed only for the remote tray icon context menu
584 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SENT_BYTES, theStats::GetTotalSentBytes()));
585 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_RECEIVED_BYTES, theStats::GetTotalReceivedBytes()));
586 response->AddTag(CECTag(EC_TAG_STATS_SHARED_FILE_COUNT, theStats::GetSharedFileCount()));
587 /* fall through */
588 case EC_DETAIL_WEB:
589 case EC_DETAIL_CMD:
590 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
591 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
592 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
593 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
594 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
595 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
596 // User/Filecounts
598 uint32 totaluser = 0, totalfile = 0;
599 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
600 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
601 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
602 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
603 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
604 response->AddTag(CECTag(EC_TAG_STATS_KAD_NODES, CStatistics::GetKadNodes()));
606 // Kad stats
607 if (Kademlia::CKademlia::IsConnected()) {
608 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
609 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
610 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
611 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
612 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
613 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
614 response->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE, Kademlia::CKademlia::IsRunningInLANMode()));
615 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
616 uint32 BuddyIP = 0;
617 uint16 BuddyPort = 0;
618 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
619 if (Buddy) {
620 BuddyIP = Buddy->GetIP();
621 BuddyPort = Buddy->GetUDPPort();
623 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
624 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
626 case EC_DETAIL_UPDATE:
627 break;
630 return response;
633 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CFileEncoderMap &encoders)
635 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
637 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
639 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
641 // request can contain list of queried items
642 CTagSet<uint32, EC_TAG_KNOWNFILE> queryitems(request);
644 encoders.UpdateEncoders();
646 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
647 const CKnownFile *cur_file = theApp->sharedfiles->GetFileByIndex(i);
649 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->ECID())) ) {
650 continue;
653 CEC_SharedFile_Tag filetag(cur_file, detail_level);
654 CKnownFile_Encoder *enc = encoders[cur_file->ECID()];
655 if ( detail_level != EC_DETAIL_UPDATE ) {
656 enc->ResetEncoder();
658 enc->Encode(&filetag);
659 response->AddTag(filetag);
661 return response;
664 static CECPacket *Get_EC_Response_GetUpdate(CFileEncoderMap &encoders, CObjTagMap &tagmap)
666 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
668 encoders.UpdateEncoders();
669 for (CFileEncoderMap::iterator it = encoders.begin(); it != encoders.end(); ++it) {
670 const CKnownFile *cur_file = it->second->GetFile();
671 CValueMap &valuemap = tagmap.GetValueMap(cur_file->ECID());
672 // Completed cleared Partfiles are still stored as CPartfile,
673 // but encoded as KnownFile, so we have to check the encoder type
674 // instead of the file type.
675 if (it->second->IsPartFile_Encoder()) {
676 CEC_PartFile_Tag filetag(static_cast<const CPartFile*>(cur_file), EC_DETAIL_INC_UPDATE, &valuemap);
677 // Add information if partfile is shared
678 filetag.AddTag(EC_TAG_PARTFILE_SHARED, it->second->IsShared(), &valuemap);
680 CPartFile_Encoder * enc = static_cast<CPartFile_Encoder *>(encoders[cur_file->ECID()]);
681 enc->Encode(&filetag);
682 response->AddTag(filetag);
683 } else {
684 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
685 CKnownFile_Encoder * enc = encoders[cur_file->ECID()];
686 enc->Encode(&filetag);
687 response->AddTag(filetag);
691 // Add clients
692 CECEmptyTag clients(EC_TAG_CLIENT);
693 const CClientList::IDMap& clientList = theApp->clientlist->GetClientList();
694 bool onlyTransmittingClients = thePrefs::IsTransmitOnlyUploadingClients();
695 for (CClientList::IDMap::const_iterator it = clientList.begin(); it != clientList.end(); ++it) {
696 const CUpDownClient* cur_client = it->second.GetClient();
697 if (onlyTransmittingClients && !cur_client->IsDownloading()) {
698 // For poor CPU cores only transmit uploading clients. This will save a lot of CPU.
699 // Set ExternalConnect/TransmitOnlyUploadingClients to 1 for it.
700 continue;
702 CValueMap &valuemap = tagmap.GetValueMap(cur_client->ECID());
703 clients.AddTag(CEC_UpDownClient_Tag(cur_client, EC_DETAIL_INC_UPDATE, &valuemap));
705 response->AddTag(clients);
707 // Add servers
708 CECEmptyTag servers(EC_TAG_SERVER);
709 std::vector<const CServer*> serverlist = theApp->serverlist->CopySnapshot();
710 uint32 nrServers = serverlist.size();
711 for (uint32 i = 0; i < nrServers; i++) {
712 const CServer* cur_server = serverlist[i];
713 CValueMap &valuemap = tagmap.GetValueMap(cur_server->ECID());
714 servers.AddTag(CEC_Server_Tag(cur_server, &valuemap));
716 response->AddTag(servers);
718 // Add friends
719 CECEmptyTag friends(EC_TAG_FRIEND);
720 for (CFriendList::const_iterator it = theApp->friendlist->begin(); it != theApp->friendlist->end(); ++it) {
721 const CFriend* cur_friend = *it;
722 CValueMap &valuemap = tagmap.GetValueMap(cur_friend->ECID());
723 friends.AddTag(CEC_Friend_Tag(cur_friend, &valuemap));
725 response->AddTag(friends);
727 return response;
730 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
732 CECPacket *response = new CECPacket(op);
734 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
737 // request can contain list of queried items
738 // (not for incremental update of course)
739 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
741 const CClientRefList& clients = theApp->uploadqueue->GetUploadingList();
742 CClientRefList::const_iterator it = clients.begin();
743 for (; it != clients.end(); ++it) {
744 CUpDownClient* cur_client = it->GetClient();
746 if (!cur_client) { // shouldn't happen
747 continue;
749 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
750 continue;
752 CValueMap *valuemap = NULL;
753 if (detail_level == EC_DETAIL_INC_UPDATE) {
754 valuemap = &tagmap.GetValueMap(cur_client->ECID());
756 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
758 response->AddTag(cli_tag);
761 return response;
765 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
767 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
769 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
771 // request can contain list of queried items
772 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
774 encoders.UpdateEncoders();
776 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
777 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
779 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
780 continue;
783 CEC_PartFile_Tag filetag(cur_file, detail_level);
785 CPartFile_Encoder * enc = static_cast<CPartFile_Encoder *>(encoders[cur_file->ECID()]);
786 if ( detail_level != EC_DETAIL_UPDATE ) {
787 enc->ResetEncoder();
789 enc->Encode(&filetag);
791 response->AddTag(filetag);
793 return response;
797 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
799 CECPacket *response = NULL;
801 // request can contain multiple files.
802 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); ++it1) {
803 const CECTag &hashtag = *it1;
805 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
807 CMD4Hash hash = hashtag.GetMD4Data();
808 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
810 if ( !pfile ) {
811 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
812 response = new CECPacket(EC_OP_FAILED);
813 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
814 //return response;
815 break;
817 switch (request->GetOpCode()) {
818 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
819 CoreNotify_PartFile_Swap_A4AF(pfile);
820 break;
821 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
822 CoreNotify_PartFile_Swap_A4AF_Auto(pfile);
823 break;
824 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
825 CoreNotify_PartFile_Swap_A4AF_Others(pfile);
826 break;
827 case EC_OP_PARTFILE_PAUSE:
828 pfile->PauseFile();
829 break;
830 case EC_OP_PARTFILE_RESUME:
831 pfile->ResumeFile();
832 pfile->SavePartFile();
833 break;
834 case EC_OP_PARTFILE_STOP:
835 pfile->StopFile();
836 break;
837 case EC_OP_PARTFILE_PRIO_SET: {
838 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
839 if ( prio == PR_AUTO ) {
840 pfile->SetAutoDownPriority(1);
841 } else {
842 pfile->SetAutoDownPriority(0);
843 pfile->SetDownPriority(prio);
846 break;
847 case EC_OP_PARTFILE_DELETE:
848 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
849 theApp->downloadqueue->StartNextFile(pfile);
851 pfile->Delete();
852 break;
854 case EC_OP_PARTFILE_SET_CAT:
855 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
856 break;
858 default:
859 response = new CECPacket(EC_OP_FAILED);
860 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
861 break;
864 if (!response) {
865 response = new CECPacket(EC_OP_NOOP);
867 return response;
870 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
872 CECPacket *response = NULL;
874 wxString full_addr = request->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS)->GetStringData();
875 wxString name = request->GetTagByNameSafe(EC_TAG_SERVER_NAME)->GetStringData();
877 wxString s_ip = full_addr.Left(full_addr.Find(':'));
878 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
880 long port = StrToULong(s_port);
881 CServer* toadd = new CServer(port, s_ip);
882 toadd->SetListName(name.IsEmpty() ? full_addr : name);
884 if ( theApp->AddServer(toadd, true) ) {
885 response = new CECPacket(EC_OP_NOOP);
886 } else {
887 response = new CECPacket(EC_OP_FAILED);
888 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
889 delete toadd;
892 return response;
895 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
897 CECPacket *response = NULL;
898 const CECTag *srv_tag = request->GetTagByName(EC_TAG_SERVER);
899 CServer *srv = 0;
900 if ( srv_tag ) {
901 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
902 // server tag passed, but server not found
903 if ( !srv ) {
904 response = new CECPacket(EC_OP_FAILED);
905 response->AddTag(CECTag(EC_TAG_STRING,
906 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
907 return response;
910 switch (request->GetOpCode()) {
911 case EC_OP_SERVER_DISCONNECT:
912 theApp->serverconnect->Disconnect();
913 response = new CECPacket(EC_OP_NOOP);
914 break;
915 case EC_OP_SERVER_REMOVE:
916 if ( srv ) {
917 theApp->serverlist->RemoveServer(srv);
918 response = new CECPacket(EC_OP_NOOP);
919 } else {
920 response = new CECPacket(EC_OP_FAILED);
921 response->AddTag(CECTag(EC_TAG_STRING,
922 wxTRANSLATE("need to define server to be removed")));
924 break;
925 case EC_OP_SERVER_CONNECT:
926 if (thePrefs::GetNetworkED2K()) {
927 if ( srv ) {
928 theApp->serverconnect->ConnectToServer(srv);
929 response = new CECPacket(EC_OP_NOOP);
930 } else {
931 theApp->serverconnect->ConnectToAnyServer();
932 response = new CECPacket(EC_OP_NOOP);
934 } else {
935 response = new CECPacket(EC_OP_FAILED);
936 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
938 break;
940 if (!response) {
941 response = new CECPacket(EC_OP_FAILED);
942 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
944 return response;
948 static CECPacket *Get_EC_Response_Friend(const CECPacket *request)
950 CECPacket *response = NULL;
951 const CECTag *tag = request->GetTagByName(EC_TAG_FRIEND_ADD);
952 if (tag) {
953 const CECTag *subtag = tag->GetTagByName(EC_TAG_CLIENT);
954 if (subtag) {
955 CUpDownClient * client = theApp->clientlist->FindClientByECID(subtag->GetInt());
956 if (client) {
957 theApp->friendlist->AddFriend(CCLIENTREF(client, wxT("Get_EC_Response_Friend theApp->friendlist->AddFriend")));
958 response = new CECPacket(EC_OP_NOOP);
960 } else {
961 const CECTag *hashtag = tag->GetTagByName(EC_TAG_FRIEND_HASH);
962 const CECTag *iptag = tag->GetTagByName(EC_TAG_FRIEND_IP);
963 const CECTag *porttag = tag->GetTagByName(EC_TAG_FRIEND_PORT);
964 const CECTag *nametag = tag->GetTagByName(EC_TAG_FRIEND_NAME);
965 if (hashtag && iptag && porttag && nametag) {
966 theApp->friendlist->AddFriend(hashtag->GetMD4Data(), iptag->GetInt(), porttag->GetInt(), nametag->GetStringData());
967 response = new CECPacket(EC_OP_NOOP);
970 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_REMOVE))) {
971 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
972 if (subtag) {
973 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
974 if (Friend) {
975 theApp->friendlist->RemoveFriend(Friend);
976 response = new CECPacket(EC_OP_NOOP);
979 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_FRIENDSLOT))) {
980 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
981 if (subtag) {
982 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
983 if (Friend) {
984 theApp->friendlist->SetFriendSlot(Friend, tag->GetInt() != 0);
985 response = new CECPacket(EC_OP_NOOP);
988 } else if ((tag = request->GetTagByName(EC_TAG_FRIEND_SHARED))) {
989 response = new CECPacket(EC_OP_FAILED);
990 response->AddTag(CECTag(EC_TAG_STRING, wxT("Request shared files list not implemented yet.")));
991 #if 0
992 // This works fine - but there is no way atm to transfer the results to amulegui, so disable it for now.
994 const CECTag *subtag = tag->GetTagByName(EC_TAG_FRIEND);
995 if (subtag) {
996 CFriend * Friend = theApp->friendlist->FindFriend(subtag->GetInt());
997 if (Friend) {
998 theApp->friendlist->RequestSharedFileList(Friend);
999 response = new CECPacket(EC_OP_NOOP);
1001 } else if ((subtag = tag->GetTagByName(EC_TAG_CLIENT))) {
1002 CUpDownClient * client = theApp->clientlist->FindClientByECID(subtag->GetInt());
1003 if (client) {
1004 client->RequestSharedFileList();
1005 response = new CECPacket(EC_OP_NOOP);
1008 #endif
1011 if (!response) {
1012 response = new CECPacket(EC_OP_FAILED);
1013 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
1015 return response;
1019 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
1021 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1023 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1025 // request can contain list of queried items
1026 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
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 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
1033 continue;
1035 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
1037 return response;
1040 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
1042 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1044 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
1045 CSearchResultList::const_iterator it = list.begin();
1046 while (it != list.end()) {
1047 CSearchFile* sf = *it++;
1048 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
1049 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
1050 // Add the children
1051 if (sf->HasChildren()) {
1052 const CSearchResultList& children = sf->GetChildren();
1053 for (size_t i = 0; i < children.size(); ++i) {
1054 CSearchFile* sfc = children.at(i);
1055 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
1056 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
1060 return response;
1063 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
1065 CECPacket *response = new CECPacket(EC_OP_STRINGS);
1066 for (CECPacket::const_iterator it = request->begin(); it != request->end(); ++it) {
1067 const CECTag &tag = *it;
1068 CMD4Hash hash = tag.GetMD4Data();
1069 uint8 category = tag.GetFirstTagSafe()->GetInt();
1070 theApp->searchlist->AddFileToDownloadByHash(hash, category);
1072 return response;
1075 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
1077 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
1078 theApp->searchlist->StopSearch();
1079 return reply;
1082 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
1084 wxString response;
1086 const CEC_Search_Tag *search_request = static_cast<const CEC_Search_Tag *>(request->GetFirstTagSafe());
1087 theApp->searchlist->RemoveResults(0xffffffff);
1089 CSearchList::CSearchParams params;
1090 params.searchString = search_request->SearchText();
1091 params.typeText = search_request->SearchFileType();
1092 params.extension = search_request->SearchExt();
1093 params.minSize = search_request->MinSize();
1094 params.maxSize = search_request->MaxSize();
1095 params.availability = search_request->Avail();
1098 EC_SEARCH_TYPE search_type = search_request->SearchType();
1099 SearchType core_search_type = LocalSearch;
1100 uint32 op = EC_OP_FAILED;
1101 switch (search_type) {
1102 case EC_SEARCH_GLOBAL:
1103 core_search_type = GlobalSearch;
1104 /* fall through */
1105 case EC_SEARCH_KAD:
1106 if (core_search_type != GlobalSearch) { // Not a global search obviously
1107 core_search_type = KadSearch;
1109 /* fall through */
1110 case EC_SEARCH_LOCAL: {
1111 uint32 search_id = 0xffffffff;
1112 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
1113 if (!error.IsEmpty()) {
1114 response = error;
1115 } else {
1116 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
1117 op = EC_OP_STRINGS;
1119 break;
1121 case EC_SEARCH_WEB:
1122 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
1123 break;
1126 CECPacket *reply = new CECPacket(op);
1127 // error or search in progress
1128 reply->AddTag(CECTag(EC_TAG_STRING, response));
1130 return reply;
1133 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1135 CECPacket *response = new CECPacket(EC_OP_NOOP);
1136 for (CECPacket::const_iterator it = request->begin(); it != request->end(); ++it) {
1137 const CECTag &tag = *it;
1138 CMD4Hash hash = tag.GetMD4Data();
1139 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1140 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1141 if ( !cur_file ) {
1142 continue;
1144 if (prio == PR_AUTO) {
1145 cur_file->SetAutoUpPriority(1);
1146 cur_file->UpdateAutoUpPriority();
1147 } else {
1148 cur_file->SetAutoUpPriority(0);
1149 cur_file->SetUpPriority(prio);
1151 Notify_SharedFilesUpdateItem(cur_file);
1154 return response;
1157 void CPartFile_Encoder::Encode(CECTag *parent)
1160 // Source part frequencies
1162 CKnownFile_Encoder::Encode(parent);
1165 // Gaps
1167 const CGapList& gaplist = m_PartFile()->GetGapList();
1168 const size_t gap_list_size = gaplist.size();
1169 ArrayOfUInts64 gaps;
1170 gaps.reserve(gap_list_size * 2);
1172 for (CGapList::const_iterator curr_pos = gaplist.begin();
1173 curr_pos != gaplist.end(); ++curr_pos) {
1174 gaps.push_back(curr_pos.start());
1175 gaps.push_back(curr_pos.end());
1178 int gap_enc_size = 0;
1179 bool changed;
1180 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1181 if (changed) {
1182 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1184 delete[] gap_enc_data;
1187 // Requested blocks
1189 ArrayOfUInts64 req_buffer;
1190 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1191 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1193 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1194 Requested_Block_Struct* block = *curr_pos2;
1195 req_buffer.push_back(block->StartOffset);
1196 req_buffer.push_back(block->EndOffset);
1198 int req_enc_size = 0;
1199 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1200 if (changed) {
1201 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1203 delete[] req_enc_data;
1206 // Source names
1208 // First count occurrence of all source names
1210 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1211 typedef std::map<wxString, int> strIntMap;
1212 strIntMap nameMap;
1213 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1214 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1215 const CClientRef &cur_src = *it;
1216 if (cur_src.GetRequestFile() != m_file || cur_src.GetClientFilename().Length() == 0) {
1217 continue;
1219 const wxString &name = cur_src.GetClientFilename();
1220 strIntMap::iterator itm = nameMap.find(name);
1221 if (itm == nameMap.end()) {
1222 nameMap[name] = 1;
1223 } else {
1224 itm->second++;
1228 // Go through our last list
1230 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1231 SourcenameItemMap::iterator it2 = it1++;
1232 strIntMap::iterator itm = nameMap.find(it2->second.name);
1233 if (itm == nameMap.end()) {
1234 // name doesn't exist anymore, tell client to forget it
1235 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1236 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1237 sourceNames.AddTag(tag);
1238 // and forget it
1239 m_sourcenameItemMap.erase(it2);
1240 } else {
1241 // update count if it changed
1242 if (it2->second.count != itm->second) {
1243 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1244 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1245 sourceNames.AddTag(tag);
1246 it2->second.count = itm->second;
1248 // remove it from nameMap so that only new names are left there
1249 nameMap.erase(itm);
1253 // Add new names
1255 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); ++it3) {
1256 int id = ++m_sourcenameID;
1257 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1258 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1259 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1260 sourceNames.AddTag(tag);
1261 // remember it
1262 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1264 if (sourceNames.HasChildTags()) {
1265 parent->AddTag(sourceNames);
1270 void CPartFile_Encoder::ResetEncoder()
1272 CKnownFile_Encoder::ResetEncoder();
1273 m_gap_status.ResetEncoder();
1274 m_req_status.ResetEncoder();
1277 void CKnownFile_Encoder::Encode(CECTag *parent)
1280 // Source part frequencies
1282 // Reference to the availability list
1283 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1284 static_cast<const CPartFile*>(m_file)->m_SrcpartFrequency :
1285 m_file->m_AvailPartFrequency;
1286 // Don't add tag if available parts aren't populated yet.
1287 if (!list.empty()) {
1288 int part_enc_size;
1289 bool changed;
1290 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1291 if (changed) {
1292 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1294 delete[] part_enc_data;
1298 static CECPacket *GetStatsGraphs(const CECPacket *request)
1300 CECPacket *response = NULL;
1302 switch (request->GetDetailLevel()) {
1303 case EC_DETAIL_WEB:
1304 case EC_DETAIL_FULL: {
1305 double dTimestamp = 0.0;
1306 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1307 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1309 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1310 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1311 uint32 *graphData;
1312 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1313 if (numPoints) {
1314 response = new CECPacket(EC_OP_STATSGRAPHS);
1315 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1316 delete [] graphData;
1317 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1318 } else {
1319 response = new CECPacket(EC_OP_FAILED);
1320 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1322 break;
1324 case EC_DETAIL_INC_UPDATE:
1325 case EC_DETAIL_UPDATE:
1326 case EC_DETAIL_CMD:
1327 // No graphs
1328 response = new CECPacket(EC_OP_FAILED);
1329 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1330 break;
1332 if (!response) {
1333 response = new CECPacket(EC_OP_FAILED);
1334 // Unknown reason
1337 return response;
1340 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1343 if ( !request ) {
1344 return 0;
1347 CECPacket *response = NULL;
1349 switch (request->GetOpCode()) {
1351 // Misc commands
1353 case EC_OP_SHUTDOWN:
1354 if (!theApp->IsOnShutDown()) {
1355 response = new CECPacket(EC_OP_NOOP);
1356 AddLogLineC(_("External Connection: shutdown requested"));
1357 #ifndef AMULE_DAEMON
1359 wxCloseEvent evt;
1360 evt.SetCanVeto(false);
1361 theApp->ShutDown(evt);
1363 #else
1364 theApp->ExitMainLoop();
1365 #endif
1366 } else {
1367 response = new CECPacket(EC_OP_FAILED);
1368 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1370 break;
1371 case EC_OP_ADD_LINK:
1372 for (CECPacket::const_iterator it = request->begin(); it != request->end(); ++it) {
1373 const CECTag &tag = *it;
1374 wxString link = tag.GetStringData();
1375 int category = 0;
1376 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1377 if (cattag) {
1378 category = cattag->GetInt();
1380 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link);
1381 if (response) {
1382 delete response;
1384 if ( theApp->downloadqueue->AddLink(link, category) ) {
1385 response = new CECPacket(EC_OP_NOOP);
1386 } else {
1387 // Error messages are printed by the add function.
1388 response = new CECPacket(EC_OP_FAILED);
1389 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1392 break;
1394 // Status requests
1396 case EC_OP_STAT_REQ:
1397 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1398 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1399 break;
1400 case EC_OP_GET_CONNSTATE:
1401 response = new CECPacket(EC_OP_MISC_DATA);
1402 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1403 break;
1407 case EC_OP_GET_SHARED_FILES:
1408 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1409 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1411 break;
1412 case EC_OP_GET_DLOAD_QUEUE:
1413 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1414 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1416 break;
1418 // This will evolve into an update-all for inc tags
1420 case EC_OP_GET_UPDATE:
1421 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1422 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1424 break;
1425 case EC_OP_GET_ULOAD_QUEUE:
1426 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1427 break;
1428 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1429 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1430 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1431 case EC_OP_PARTFILE_PAUSE:
1432 case EC_OP_PARTFILE_RESUME:
1433 case EC_OP_PARTFILE_STOP:
1434 case EC_OP_PARTFILE_PRIO_SET:
1435 case EC_OP_PARTFILE_DELETE:
1436 case EC_OP_PARTFILE_SET_CAT:
1437 response = Get_EC_Response_PartFile_Cmd(request);
1438 break;
1439 case EC_OP_SHAREDFILES_RELOAD:
1440 theApp->sharedfiles->Reload();
1441 response = new CECPacket(EC_OP_NOOP);
1442 break;
1443 case EC_OP_SHARED_SET_PRIO:
1444 response = Get_EC_Response_Set_SharedFile_Prio(request);
1445 break;
1446 case EC_OP_RENAME_FILE: {
1447 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1448 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1449 // search first in downloadqueue - it might be in known files as well
1450 CKnownFile* file = theApp->downloadqueue->GetFileByID(fileHash);
1451 if (!file) {
1452 file = theApp->knownfiles->FindKnownFileByID(fileHash);
1454 if (!file) {
1455 response = new CECPacket(EC_OP_FAILED);
1456 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1457 break;
1459 if (newName.IsEmpty()) {
1460 response = new CECPacket(EC_OP_FAILED);
1461 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1462 break;
1465 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1466 response = new CECPacket(EC_OP_NOOP);
1467 } else {
1468 response = new CECPacket(EC_OP_FAILED);
1469 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1472 break;
1474 case EC_OP_CLEAR_COMPLETED: {
1475 ListOfUInts32 toClear;
1476 for (CECTag::const_iterator it = request->begin(); it != request->end(); ++it) {
1477 if (it->GetTagName() == EC_TAG_ECID) {
1478 toClear.push_back(it->GetInt());
1481 theApp->downloadqueue->ClearCompleted(toClear);
1482 response = new CECPacket(EC_OP_NOOP);
1483 break;
1485 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE: {
1486 theApp->sharedfiles->Reload();
1487 uint32 idClient = request->GetTagByNameSafe(EC_TAG_CLIENT)->GetInt();
1488 CUpDownClient * client = theApp->clientlist->FindClientByECID(idClient);
1489 CMD4Hash idFile = request->GetTagByNameSafe(EC_TAG_PARTFILE)->GetMD4Data();
1490 CPartFile * file = theApp->downloadqueue->GetFileByID(idFile);
1491 if (client && file) {
1492 client->SwapToAnotherFile( true, false, false, file);
1494 response = new CECPacket(EC_OP_NOOP);
1495 break;
1497 case EC_OP_SHARED_FILE_SET_COMMENT: {
1498 CMD4Hash hash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1499 CKnownFile * file = theApp->sharedfiles->GetFileByID(hash);
1500 if (file) {
1501 wxString newComment = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT)->GetStringData();
1502 uint8 newRating = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING)->GetInt();
1503 CoreNotify_KnownFile_Comment_Set(file, newComment, newRating);
1505 response = new CECPacket(EC_OP_NOOP);
1506 break;
1510 // Server commands
1512 case EC_OP_SERVER_ADD:
1513 response = Get_EC_Response_Server_Add(request);
1514 break;
1515 case EC_OP_SERVER_DISCONNECT:
1516 case EC_OP_SERVER_CONNECT:
1517 case EC_OP_SERVER_REMOVE:
1518 response = Get_EC_Response_Server(request);
1519 break;
1520 case EC_OP_GET_SERVER_LIST: {
1521 response = new CECPacket(EC_OP_SERVER_LIST);
1522 if (!thePrefs::GetNetworkED2K()) {
1523 // Kad only: just send an empty list
1524 break;
1526 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1527 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1528 for (
1529 std::vector<const CServer*>::const_iterator it = servers.begin();
1530 it != servers.end();
1531 ++it
1533 response->AddTag(CEC_Server_Tag(*it, detail_level));
1536 break;
1537 case EC_OP_SERVER_UPDATE_FROM_URL: {
1538 wxString url = request->GetFirstTagSafe()->GetStringData();
1540 // Save the new url, and update the UI (if not amuled).
1541 Notify_ServersURLChanged(url);
1542 thePrefs::SetEd2kServersUrl(url);
1544 theApp->serverlist->UpdateServerMetFromURL(url);
1545 response = new CECPacket(EC_OP_NOOP);
1546 break;
1548 case EC_OP_SERVER_SET_STATIC_PRIO: {
1549 uint32 ecid = request->GetTagByNameSafe(EC_TAG_SERVER)->GetInt();
1550 CServer * server = theApp->serverlist->GetServerByECID(ecid);
1551 if (server) {
1552 const CECTag * staticTag = request->GetTagByName(EC_TAG_SERVER_STATIC);
1553 if (staticTag) {
1554 theApp->serverlist->SetStaticServer(server, staticTag->GetInt() > 0);
1556 const CECTag * prioTag = request->GetTagByName(EC_TAG_SERVER_PRIO);
1557 if (prioTag) {
1558 theApp->serverlist->SetServerPrio(server, prioTag->GetInt());
1561 response = new CECPacket(EC_OP_NOOP);
1562 break;
1565 // Friends
1567 case EC_OP_FRIEND:
1568 response = Get_EC_Response_Friend(request);
1569 break;
1572 // IPFilter
1574 case EC_OP_IPFILTER_RELOAD:
1575 NotifyAlways_IPFilter_Reload();
1576 response = new CECPacket(EC_OP_NOOP);
1577 break;
1579 case EC_OP_IPFILTER_UPDATE: {
1580 wxString url = request->GetFirstTagSafe()->GetStringData();
1581 if (url.IsEmpty()) {
1582 url = thePrefs::IPFilterURL();
1584 NotifyAlways_IPFilter_Update(url);
1585 response = new CECPacket(EC_OP_NOOP);
1586 break;
1589 // Search
1591 case EC_OP_SEARCH_START:
1592 response = Get_EC_Response_Search(request);
1593 break;
1595 case EC_OP_SEARCH_STOP:
1596 response = Get_EC_Response_Search_Stop(request);
1597 break;
1599 case EC_OP_SEARCH_RESULTS:
1600 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1601 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1602 } else {
1603 response = Get_EC_Response_Search_Results(request);
1605 break;
1607 case EC_OP_SEARCH_PROGRESS:
1608 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1609 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1610 theApp->searchlist->GetSearchProgress()));
1611 break;
1613 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1614 response = Get_EC_Response_Search_Results_Download(request);
1615 break;
1617 // Preferences
1619 case EC_OP_GET_PREFERENCES:
1620 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1621 break;
1622 case EC_OP_SET_PREFERENCES:
1623 static_cast<const CEC_Prefs_Packet *>(request)->Apply();
1624 theApp->glob_prefs->Save();
1625 if (thePrefs::IsFilteringClients()) {
1626 theApp->clientlist->FilterQueues();
1628 if (thePrefs::IsFilteringServers()) {
1629 theApp->serverlist->FilterServers();
1631 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1632 theApp->DisconnectED2K();
1634 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1635 theApp->StopKad();
1637 response = new CECPacket(EC_OP_NOOP);
1638 break;
1640 case EC_OP_CREATE_CATEGORY:
1641 if ( request->GetTagCount() == 1 ) {
1642 CEC_Category_Tag tag(*static_cast<const CEC_Category_Tag*>(request->GetFirstTagSafe()));
1643 if (tag.Create()) {
1644 response = new CECPacket(EC_OP_NOOP);
1645 } else {
1646 response = new CECPacket(EC_OP_FAILED);
1647 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1648 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag.Path()));
1650 Notify_CategoryAdded();
1651 } else {
1652 response = new CECPacket(EC_OP_NOOP);
1654 break;
1655 case EC_OP_UPDATE_CATEGORY:
1656 if ( request->GetTagCount() == 1 ) {
1657 CEC_Category_Tag tag(*static_cast<const CEC_Category_Tag*>(request->GetFirstTagSafe()));
1658 if (tag.Apply()) {
1659 response = new CECPacket(EC_OP_NOOP);
1660 } else {
1661 response = new CECPacket(EC_OP_FAILED);
1662 response->AddTag(CECTag(EC_TAG_CATEGORY, tag.GetInt()));
1663 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag.Path()));
1665 Notify_CategoryUpdate(tag.GetInt());
1666 } else {
1667 response = new CECPacket(EC_OP_NOOP);
1669 break;
1670 case EC_OP_DELETE_CATEGORY:
1671 if ( request->GetTagCount() == 1 ) {
1672 uint32 cat = request->GetFirstTagSafe()->GetInt();
1673 // this noes not only update the gui, but actually deletes the cat
1674 Notify_CategoryDelete(cat);
1676 response = new CECPacket(EC_OP_NOOP);
1677 break;
1680 // Logging
1682 case EC_OP_ADDLOGLINE:
1683 // cppcheck-suppress duplicateBranch
1684 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1685 AddLogLineC(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1686 } else {
1687 AddLogLineN(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1689 response = new CECPacket(EC_OP_NOOP);
1690 break;
1691 case EC_OP_ADDDEBUGLOGLINE:
1692 // cppcheck-suppress duplicateBranch
1693 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1694 AddDebugLogLineC(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1695 } else {
1696 AddDebugLogLineN(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1698 response = new CECPacket(EC_OP_NOOP);
1699 break;
1700 case EC_OP_GET_LOG:
1701 response = new CECPacket(EC_OP_LOG);
1702 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1703 break;
1704 case EC_OP_GET_DEBUGLOG:
1705 response = new CECPacket(EC_OP_DEBUGLOG);
1706 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1707 break;
1708 case EC_OP_RESET_LOG:
1709 theApp->GetLog(true);
1710 response = new CECPacket(EC_OP_NOOP);
1711 break;
1712 case EC_OP_RESET_DEBUGLOG:
1713 theApp->GetDebugLog(true);
1714 response = new CECPacket(EC_OP_NOOP);
1715 break;
1716 case EC_OP_GET_LAST_LOG_ENTRY:
1718 wxString tmp = theApp->GetLog(false);
1719 if (tmp.Last() == '\n') {
1720 tmp.RemoveLast();
1722 response = new CECPacket(EC_OP_LOG);
1723 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1725 break;
1726 case EC_OP_GET_SERVERINFO:
1727 response = new CECPacket(EC_OP_SERVERINFO);
1728 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1729 break;
1730 case EC_OP_CLEAR_SERVERINFO:
1731 theApp->GetServerLog(true);
1732 response = new CECPacket(EC_OP_NOOP);
1733 break;
1735 // Statistics
1737 case EC_OP_GET_STATSGRAPHS:
1738 response = GetStatsGraphs(request);
1739 break;
1740 case EC_OP_GET_STATSTREE: {
1741 theApp->m_statistics->UpdateStatsTree();
1742 response = new CECPacket(EC_OP_STATSTREE);
1743 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1744 if (tree) {
1745 response->AddTag(*tree);
1746 delete tree;
1748 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1749 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1750 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1752 break;
1756 // Kad
1758 case EC_OP_KAD_START:
1759 if (thePrefs::GetNetworkKademlia()) {
1760 response = new CECPacket(EC_OP_NOOP);
1761 if ( !Kademlia::CKademlia::IsRunning() ) {
1762 Kademlia::CKademlia::Start();
1763 theApp->ShowConnectionState();
1765 } else {
1766 response = new CECPacket(EC_OP_FAILED);
1767 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1769 break;
1770 case EC_OP_KAD_STOP:
1771 theApp->StopKad();
1772 theApp->ShowConnectionState();
1773 response = new CECPacket(EC_OP_NOOP);
1774 break;
1775 case EC_OP_KAD_UPDATE_FROM_URL: {
1776 wxString url = request->GetFirstTagSafe()->GetStringData();
1778 // Save the new url, and update the UI (if not amuled).
1779 Notify_NodesURLChanged(url);
1780 thePrefs::SetKadNodesUrl(url);
1782 theApp->UpdateNotesDat(url);
1783 response = new CECPacket(EC_OP_NOOP);
1784 break;
1786 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1787 if (thePrefs::GetNetworkKademlia()) {
1788 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1789 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1790 theApp->ShowConnectionState();
1791 response = new CECPacket(EC_OP_NOOP);
1792 } else {
1793 response = new CECPacket(EC_OP_FAILED);
1794 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1796 break;
1799 // Networks
1800 // These requests are currently used only in the text client
1802 case EC_OP_CONNECT:
1803 if (thePrefs::GetNetworkED2K()) {
1804 response = new CECPacket(EC_OP_STRINGS);
1805 if (theApp->IsConnectedED2K()) {
1806 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1807 } else {
1808 theApp->serverconnect->ConnectToAnyServer();
1809 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1812 if (thePrefs::GetNetworkKademlia()) {
1813 if (!response) {
1814 response = new CECPacket(EC_OP_STRINGS);
1816 if (theApp->IsConnectedKad()) {
1817 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1818 } else {
1819 theApp->StartKad();
1820 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1823 if (response) {
1824 theApp->ShowConnectionState();
1825 } else {
1826 response = new CECPacket(EC_OP_FAILED);
1827 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1829 break;
1830 case EC_OP_DISCONNECT:
1831 if (theApp->IsConnected()) {
1832 response = new CECPacket(EC_OP_STRINGS);
1833 if (theApp->IsConnectedED2K()) {
1834 theApp->serverconnect->Disconnect();
1835 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1837 if (theApp->IsConnectedKad()) {
1838 theApp->StopKad();
1839 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1841 theApp->ShowConnectionState();
1842 } else {
1843 response = new CECPacket(EC_OP_NOOP);
1845 break;
1847 if (!response) {
1848 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request->GetOpCode());
1849 wxFAIL;
1850 response = new CECPacket(EC_OP_FAILED);
1851 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1853 return response;
1857 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1861 * Core general status
1863 ECStatusMsgSource::ECStatusMsgSource()
1865 m_last_ed2k_status_sent = 0xffffffff;
1866 m_last_kad_status_sent = 0xffffffff;
1867 m_server = (void *)0xffffffff;
1870 uint32 ECStatusMsgSource::GetEd2kStatus()
1872 if ( theApp->IsConnectedED2K() ) {
1873 return theApp->GetED2KID();
1874 } else if ( theApp->serverconnect->IsConnecting() ) {
1875 return 1;
1876 } else {
1877 return 0;
1881 uint32 ECStatusMsgSource::GetKadStatus()
1883 if ( theApp->IsConnectedKad() ) {
1884 return 1;
1885 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1886 return 2;
1887 } else if ( Kademlia::CKademlia::IsRunning() ) {
1888 return 3;
1890 return 0;
1893 CECPacket *ECStatusMsgSource::GetNextPacket()
1895 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1896 (m_last_kad_status_sent != GetKadStatus()) ||
1897 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1899 m_last_ed2k_status_sent = GetEd2kStatus();
1900 m_last_kad_status_sent = GetKadStatus();
1901 m_server = theApp->serverconnect->GetCurrentServer();
1903 CECPacket *response = new CECPacket(EC_OP_STATS);
1904 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1905 return response;
1907 return 0;
1911 * Downloading files
1913 ECPartFileMsgSource::ECPartFileMsgSource()
1915 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1916 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1917 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1918 m_dirty_status[cur_file->GetFileHash()] = status;
1922 void ECPartFileMsgSource::SetDirty(const CPartFile *file)
1924 CMD4Hash filehash = file->GetFileHash();
1925 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1926 m_dirty_status[filehash].m_dirty = true;;
1930 void ECPartFileMsgSource::SetNew(const CPartFile *file)
1932 CMD4Hash filehash = file->GetFileHash();
1933 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1934 PARTFILE_STATUS status = { true, false, false, false, true, file };
1935 m_dirty_status[filehash] = status;
1938 void ECPartFileMsgSource::SetCompleted(const CPartFile *file)
1940 CMD4Hash filehash = file->GetFileHash();
1941 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1943 m_dirty_status[filehash].m_finished = true;
1946 void ECPartFileMsgSource::SetRemoved(const CPartFile *file)
1948 CMD4Hash filehash = file->GetFileHash();
1949 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1951 m_dirty_status[filehash].m_removed = true;
1954 CECPacket *ECPartFileMsgSource::GetNextPacket()
1956 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1957 it != m_dirty_status.end(); it++) {
1958 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1959 CMD4Hash filehash = it->first;
1961 const CPartFile *partfile = it->second.m_file;
1963 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1964 if ( it->second.m_removed ) {
1965 CECTag tag(EC_TAG_PARTFILE, filehash);
1966 packet->AddTag(tag);
1967 m_dirty_status.erase(it);
1968 } else {
1969 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1970 packet->AddTag(tag);
1972 m_dirty_status[filehash].m_new = false;
1973 m_dirty_status[filehash].m_dirty = false;
1975 return packet;
1978 return 0;
1982 * Shared files - similar to downloading
1984 ECKnownFileMsgSource::ECKnownFileMsgSource()
1986 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1987 const CKnownFile *cur_file = theApp->sharedfiles->GetFileByIndex(i);
1988 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1989 m_dirty_status[cur_file->GetFileHash()] = status;
1993 void ECKnownFileMsgSource::SetDirty(const CKnownFile *file)
1995 CMD4Hash filehash = file->GetFileHash();
1996 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1997 m_dirty_status[filehash].m_dirty = true;;
2001 void ECKnownFileMsgSource::SetNew(const CKnownFile *file)
2003 CMD4Hash filehash = file->GetFileHash();
2004 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
2005 KNOWNFILE_STATUS status = { true, false, false, true, file };
2006 m_dirty_status[filehash] = status;
2009 void ECKnownFileMsgSource::SetRemoved(const CKnownFile *file)
2011 CMD4Hash filehash = file->GetFileHash();
2012 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
2014 m_dirty_status[filehash].m_removed = true;
2017 CECPacket *ECKnownFileMsgSource::GetNextPacket()
2019 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
2020 it != m_dirty_status.end(); it++) {
2021 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
2022 CMD4Hash filehash = it->first;
2024 const CKnownFile *partfile = it->second.m_file;
2026 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
2027 if ( it->second.m_removed ) {
2028 CECTag tag(EC_TAG_PARTFILE, filehash);
2029 packet->AddTag(tag);
2030 m_dirty_status.erase(it);
2031 } else {
2032 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
2033 packet->AddTag(tag);
2035 m_dirty_status[filehash].m_new = false;
2036 m_dirty_status[filehash].m_dirty = false;
2038 return packet;
2041 return 0;
2045 * Notification about search status
2047 ECSearchMsgSource::ECSearchMsgSource()
2051 CECPacket *ECSearchMsgSource::GetNextPacket()
2053 if ( m_dirty_status.empty() ) {
2054 return 0;
2057 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
2058 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
2059 it != m_dirty_status.end(); it++) {
2061 if ( it->second.m_new ) {
2062 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
2063 it->second.m_new = false;
2064 } else if ( it->second.m_dirty ) {
2065 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
2070 return response;
2073 void ECSearchMsgSource::FlushStatus()
2075 m_dirty_status.clear();
2078 void ECSearchMsgSource::SetDirty(const CSearchFile *file)
2080 if ( m_dirty_status.count(file->GetFileHash()) ) {
2081 m_dirty_status[file->GetFileHash()].m_dirty = true;
2082 } else {
2083 m_dirty_status[file->GetFileHash()].m_new = true;
2084 m_dirty_status[file->GetFileHash()].m_dirty = true;
2085 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
2086 m_dirty_status[file->GetFileHash()].m_file = file;
2090 void ECSearchMsgSource::SetChildDirty(const CSearchFile *file)
2092 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
2096 * Notification about uploading clients
2098 CECPacket *ECClientMsgSource::GetNextPacket()
2100 return 0;
2104 // Notification iface per-client
2106 ECNotifier::ECNotifier()
2110 ECNotifier::~ECNotifier()
2112 while (m_msg_source.begin() != m_msg_source.end())
2113 Remove_EC_Client(m_msg_source.begin()->first);
2116 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
2118 CECPacket *packet = 0;
2120 // priority 0 is highest
2122 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2123 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
2124 break;
2127 return packet;
2130 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
2133 // OnOutput is called for a first time before
2134 // socket is registered
2136 if ( m_msg_source.count(sock) ) {
2137 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2138 if ( !notifier_array ) {
2139 return 0;
2141 CECPacket *packet = GetNextPacket(notifier_array);
2142 //printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
2143 return packet;
2144 } else {
2145 return 0;
2150 // Interface to notification macros
2152 void ECNotifier::DownloadFile_SetDirty(const CPartFile *file)
2154 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2155 i != m_msg_source.end(); ++i) {
2156 CECServerSocket *sock = i->first;
2157 if ( sock->HaveNotificationSupport() ) {
2158 ECUpdateMsgSource **notifier_array = i->second;
2159 static_cast<ECPartFileMsgSource *>(notifier_array[EC_PARTFILE])->SetDirty(file);
2162 NextPacketToSocket();
2165 void ECNotifier::DownloadFile_RemoveFile(const CPartFile *file)
2167 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2168 i != m_msg_source.end(); ++i) {
2169 ECUpdateMsgSource **notifier_array = i->second;
2170 static_cast<ECPartFileMsgSource *>(notifier_array[EC_PARTFILE])->SetRemoved(file);
2172 NextPacketToSocket();
2175 void ECNotifier::DownloadFile_RemoveSource(const CPartFile *)
2177 // per-partfile source list is not supported (yet), and IMHO quite useless
2180 void ECNotifier::DownloadFile_AddFile(const CPartFile *file)
2182 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2183 i != m_msg_source.end(); ++i) {
2184 ECUpdateMsgSource **notifier_array = i->second;
2185 static_cast<ECPartFileMsgSource *>(notifier_array[EC_PARTFILE])->SetNew(file);
2187 NextPacketToSocket();
2190 void ECNotifier::DownloadFile_AddSource(const CPartFile *)
2192 // per-partfile source list is not supported (yet), and IMHO quite useless
2195 void ECNotifier::SharedFile_AddFile(const CKnownFile *file)
2197 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2198 i != m_msg_source.end(); ++i) {
2199 ECUpdateMsgSource **notifier_array = i->second;
2200 static_cast<ECKnownFileMsgSource *>(notifier_array[EC_KNOWN])->SetNew(file);
2202 NextPacketToSocket();
2205 void ECNotifier::SharedFile_RemoveFile(const CKnownFile *file)
2207 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2208 i != m_msg_source.end(); ++i) {
2209 ECUpdateMsgSource **notifier_array = i->second;
2210 static_cast<ECKnownFileMsgSource *>(notifier_array[EC_KNOWN])->SetRemoved(file);
2212 NextPacketToSocket();
2215 void ECNotifier::SharedFile_RemoveAllFiles()
2217 // need to figure out what to do here
2220 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2222 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2223 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2224 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2225 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2226 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2227 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2229 m_msg_source[sock] = notifier_array;
2232 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2234 if (m_msg_source.count(sock)) {
2235 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2237 m_msg_source.erase(sock);
2239 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2240 delete notifier_array[i];
2242 delete [] notifier_array;
2246 void ECNotifier::NextPacketToSocket()
2248 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2249 i != m_msg_source.end(); ++i) {
2250 CECServerSocket *sock = i->first;
2251 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2252 ECUpdateMsgSource **notifier_array = i->second;
2253 CECPacket *packet = GetNextPacket(notifier_array);
2254 if ( packet ) {
2255 //printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2256 sock->SendPacket(packet);
2262 // File_checked_for_headers