Add ability to stop Kad search from aMuleGUI
[amule.git] / src / ExternalConn.cpp
blobc9153760f688cb36d55bf4a3fada19f3839454f2
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 Kry ( elkry@sourceforge.net / http://www.amule.org )
5 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Copyright (c) 2008 Froenchenko Leonid (lfroen@gmail.com)
7 //
8 // Any parts of this program derived from the xMule, lMule or eMule project,
9 // or contributed by third-party developers are copyrighted by their
10 // respective authors.
12 // This program is free software; you can redistribute it and/or modify
13 // it under the terms of the GNU General Public License as published by
14 // the Free Software Foundation; either version 2 of the License, or
15 // (at your option) any later version.
17 // This program is distributed in the hope that it will be useful,
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 // GNU General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #ifdef HAVE_CONFIG_H
28 #include "config.h" // Needed for VERSION
29 #endif
31 #include <ec/cpp/ECMuleSocket.h> // Needed for CECSocket
33 #include <common/Format.h> // Needed for CFormat
35 #include <common/ClientVersion.h>
36 #include <common/MD5Sum.h>
38 #include "ExternalConn.h" // Interface declarations
39 #include "updownclient.h" // Needed for CUpDownClient
40 #include "Server.h" // Needed for CServer
41 #include "ServerList.h" // Needed for CServerList
42 #include "PartFile.h" // Needed for CPartFile
43 #include "ServerConnect.h" // Needed for CServerConnect
44 #include "UploadQueue.h" // Needed for CUploadQueue
45 #include "amule.h" // Needed for theApp
46 #include "SearchList.h" // Needed for GetSearchResults
47 #include "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 "RandomFunctions.h"
54 #include "kademlia/kademlia/Kademlia.h"
55 #include "kademlia/kademlia/UDPFirewallTester.h"
58 //-------------------- File_Encoder --------------------
62 * Encode 'obtained parts' info to be sent to remote gui
64 class CKnownFile_Encoder {
65 // number of sources for each part for progress bar colouring
66 RLE_Data m_enc_data;
67 protected:
68 const CKnownFile *m_file;
69 public:
70 CKnownFile_Encoder(const CKnownFile *file = 0) { m_file = file; }
72 virtual ~CKnownFile_Encoder() {}
74 virtual void Encode(CECTag *parent_tag);
76 virtual void ResetEncoder()
78 m_enc_data.ResetEncoder();
81 virtual void SetShared() { }
82 virtual bool IsShared() { return true; }
83 virtual bool IsPartFile_Encoder() { return false; }
84 const CKnownFile * GetFile() { return m_file; }
87 /*!
88 * PartStatus strings and gap lists are quite long - RLE encoding will help.
90 * Instead of sending each time full part-status string, send
91 * RLE encoded difference from previous one.
93 * PartFileEncoderData class is used for decode only,
94 * while CPartFile_Encoder is used for encode only.
96 class CPartFile_Encoder : public CKnownFile_Encoder {
97 // blocks requested for download
98 RLE_Data m_req_status;
99 // gap list
100 RLE_Data m_gap_status;
101 // source names
102 SourcenameItemMap m_sourcenameItemMap;
103 // counter for unique source name ids
104 int m_sourcenameID;
105 // not all part files are shared (only when at least one part is complete)
106 bool m_shared;
108 // cast inherited member to CPartFile
109 CPartFile * m_PartFile() { wxASSERT(m_file->IsCPartFile()); return (CPartFile *)m_file; }
110 public:
111 // encoder side
112 CPartFile_Encoder(const CPartFile *file = 0) : CKnownFile_Encoder(file)
114 m_sourcenameID = 0;
115 m_shared = false;
118 virtual ~CPartFile_Encoder() {}
120 // encode - take data from m_file
121 virtual void Encode(CECTag *parent_tag);
123 // Encoder may reset history if full info requested
124 virtual void ResetEncoder();
126 virtual void SetShared() { m_shared = true; }
127 virtual bool IsShared() { return m_shared; }
128 virtual bool IsPartFile_Encoder() { return true; }
131 class CFileEncoderMap : public std::map<uint32, CKnownFile_Encoder*> {
132 typedef std::set<uint32> IDSet;
133 public:
134 ~CFileEncoderMap();
135 void UpdateEncoders();
138 CFileEncoderMap::~CFileEncoderMap()
140 // DeleteContents() causes infinite recursion here!
141 for (iterator it = begin(); it != end(); it++) {
142 delete it->second;
146 // Check if encoder contains files that are no longer used
147 // or if we have new files without encoder yet.
148 void CFileEncoderMap::UpdateEncoders()
150 IDSet curr_files, dead_files;
151 // Downloads
152 std::vector<CPartFile*> downloads;
153 theApp->downloadqueue->CopyFileList(downloads, true);
154 for (uint32 i = downloads.size(); i--;) {
155 uint32 id = downloads[i]->ECID();
156 curr_files.insert(id);
157 if (!count(id)) {
158 (*this)[id] = new CPartFile_Encoder(downloads[i]);
161 // Shares
162 std::vector<CKnownFile*> shares;
163 theApp->sharedfiles->CopyFileList(shares);
164 for (uint32 i = shares.size(); i--;) {
165 uint32 id = shares[i]->ECID();
166 // Check if it is already there.
167 // The curr_files.count(id) is enough, the IsCPartFile() is just a speedup.
168 if (shares[i]->IsCPartFile() && curr_files.count(id)) {
169 (*this)[id]->SetShared();
170 continue;
172 curr_files.insert(id);
173 if (!count(id)) {
174 (*this)[id] = new CKnownFile_Encoder(shares[i]);
177 // Check for removed files, and store them in a set for deletion.
178 // (std::map documentation is unclear if a construct like
179 // iterator to_del = it++; erase(to_del) ;
180 // works or invalidates it too.)
181 for (iterator it = begin(); it != end(); it++) {
182 if (!curr_files.count(it->first)) {
183 dead_files.insert(it->first);
186 // then delete them
187 for (IDSet::iterator it = dead_files.begin(); it != dead_files.end(); it++) {
188 iterator it2 = find(*it);
189 delete it2->second;
190 erase(it2);
195 //-------------------- CECServerSocket --------------------
197 class CECServerSocket : public CECMuleSocket
199 public:
200 CECServerSocket(ECNotifier *notifier);
201 virtual ~CECServerSocket();
203 virtual const CECPacket *OnPacketReceived(const CECPacket *packet, uint32 trueSize);
204 virtual void OnLost();
206 virtual void WriteDoneAndQueueEmpty();
208 void ResetLog() { m_LoggerAccess.Reset(); }
209 private:
210 ECNotifier *m_ec_notifier;
212 const CECPacket *Authenticate(const CECPacket *);
214 enum {
215 CONN_INIT,
216 CONN_SALT_SENT,
217 CONN_ESTABLISHED,
218 CONN_FAILED
219 } m_conn_state;
221 uint64_t m_passwd_salt;
222 CLoggerAccess m_LoggerAccess;
223 CFileEncoderMap m_FileEncoder;
224 CObjTagMap m_obj_tagmap;
225 CECPacket *ProcessRequest2(const CECPacket *request);
227 virtual bool IsAuthorized() { return m_conn_state == CONN_ESTABLISHED; }
231 CECServerSocket::CECServerSocket(ECNotifier *notifier)
233 CECMuleSocket(true),
234 m_conn_state(CONN_INIT),
235 m_passwd_salt(GetRandomUint64())
237 wxASSERT(theApp->ECServerHandler);
238 theApp->ECServerHandler->AddSocket(this);
239 m_ec_notifier = notifier;
243 CECServerSocket::~CECServerSocket()
245 wxASSERT(theApp->ECServerHandler);
246 theApp->ECServerHandler->RemoveSocket(this);
250 const CECPacket *CECServerSocket::OnPacketReceived(const CECPacket *packet, uint32 trueSize)
252 packet->DebugPrint(true, trueSize);
254 const CECPacket *reply = NULL;
256 if (m_conn_state == CONN_FAILED) {
257 // Client didn't close the socket when authentication failed.
258 AddLogLineN(_("Client sent packet after authentication failed."));
259 CloseSocket();
262 if (m_conn_state != CONN_ESTABLISHED) {
263 // This is called twice:
264 // 1) send salt
265 // 2) verify password
266 reply = Authenticate(packet);
267 } else {
268 reply = ProcessRequest2(packet);
270 return reply;
274 void CECServerSocket::OnLost()
276 AddLogLineN(_("External connection closed."));
277 theApp->ECServerHandler->m_ec_notifier->Remove_EC_Client(this);
278 DestroySocket();
281 void CECServerSocket::WriteDoneAndQueueEmpty()
283 if ( HaveNotificationSupport() && (m_conn_state == CONN_ESTABLISHED) ) {
284 CECPacket *packet = m_ec_notifier->GetNextPacket(this);
285 if ( packet ) {
286 SendPacket(packet);
288 } else {
289 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
293 //-------------------- ExternalConn --------------------
295 enum
296 { // id for sockets
297 SERVER_ID = 1000
301 BEGIN_EVENT_TABLE(ExternalConn, wxEvtHandler)
302 EVT_SOCKET(SERVER_ID, ExternalConn::OnServerEvent)
303 END_EVENT_TABLE()
306 ExternalConn::ExternalConn(amuleIPV4Address addr, wxString *msg)
308 wxString msgLocal;
309 m_ECServer = NULL;
310 // Are we allowed to accept External Connections?
311 if ( thePrefs::AcceptExternalConnections() ) {
312 // We must have a valid password, otherwise we will not allow EC connections
313 if (thePrefs::ECPassword().IsEmpty()) {
314 *msg += wxT("External connections disabled due to empty password!\n");
315 AddLogLineC(_("External connections disabled due to empty password!"));
316 return;
319 // Create the socket
320 m_ECServer = new wxSocketServer(addr, wxSOCKET_REUSEADDR);
321 m_ECServer->SetEventHandler(*this, SERVER_ID);
322 m_ECServer->SetNotify(wxSOCKET_CONNECTION_FLAG);
323 m_ECServer->Notify(true);
325 int port = addr.Service();
326 wxString ip = addr.IPAddress();
327 if (m_ECServer->Ok()) {
328 msgLocal = CFormat(wxT("*** TCP socket (ECServer) listening on %s:%d")) % ip % port;
329 *msg += msgLocal + wxT("\n");
330 AddLogLineN(msgLocal);
331 } else {
332 msgLocal = CFormat(wxT("Could not listen for external connections at %s:%d!")) % ip % port;
333 *msg += msgLocal + wxT("\n");
334 AddLogLineN(msgLocal);
336 } else {
337 *msg += wxT("External connections disabled in config file\n");
338 AddLogLineN(_("External connections disabled in config file"));
340 m_ec_notifier = new ECNotifier();
344 ExternalConn::~ExternalConn()
346 KillAllSockets();
347 delete m_ECServer;
348 delete m_ec_notifier;
352 void ExternalConn::AddSocket(CECServerSocket *s)
354 wxASSERT(s);
355 socket_list.insert(s);
359 void ExternalConn::RemoveSocket(CECServerSocket *s)
361 wxASSERT(s);
362 socket_list.erase(s);
366 void ExternalConn::KillAllSockets()
368 AddDebugLogLineN(logGeneral,
369 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
370 socket_list.size());
371 SocketSet::iterator it = socket_list.begin();
372 while (it != socket_list.end()) {
373 CECServerSocket *s = *(it++);
374 s->Close();
375 s->Destroy();
380 void ExternalConn::ResetAllLogs()
382 SocketSet::iterator it = socket_list.begin();
383 while (it != socket_list.end()) {
384 CECServerSocket *s = *(it++);
385 s->ResetLog();
390 void ExternalConn::OnServerEvent(wxSocketEvent& WXUNUSED(event))
392 CECServerSocket *sock = new CECServerSocket(m_ec_notifier);
393 // Accept new connection if there is one in the pending
394 // connections queue, else exit. We use Accept(FALSE) for
395 // non-blocking accept (although if we got here, there
396 // should ALWAYS be a pending connection).
397 if ( m_ECServer->AcceptWith(*sock, false) ) {
398 AddLogLineN(_("New external connection accepted"));
399 } else {
400 delete sock;
401 AddLogLineN(_("ERROR: couldn't accept a new external connection"));
407 // Authentication
409 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
411 CECPacket *response;
413 if (request == NULL) {
414 return new CECPacket(EC_OP_AUTH_FAIL);
417 // Password must be specified if we are to allow remote connections
418 if ( thePrefs::ECPassword().IsEmpty() ) {
419 AddLogLineC(_("External connection refused due to empty password in preferences!"));
421 return new CECPacket(EC_OP_AUTH_FAIL);
424 if ((m_conn_state == CONN_INIT) && (request->GetOpCode() == EC_OP_AUTH_REQ) ) {
425 const CECTag *clientName = request->GetTagByName(EC_TAG_CLIENT_NAME);
426 const CECTag *clientVersion = request->GetTagByName(EC_TAG_CLIENT_VERSION);
428 AddLogLineN(CFormat( _("Connecting client: %s %s") )
429 % ( clientName ? clientName->GetStringData() : wxString(_("Unknown")) )
430 % ( clientVersion ? clientVersion->GetStringData() : wxString(_("Unknown version")) ) );
431 const CECTag *protocol = request->GetTagByName(EC_TAG_PROTOCOL_VERSION);
432 #ifdef EC_VERSION_ID
433 // For SVN versions, both client and server must use SVNDATE, and they must be the same
434 CMD4Hash vhash;
435 if (!vhash.Decode(wxT(EC_VERSION_ID))) {
436 response = new CECPacket(EC_OP_AUTH_FAIL);
437 response->AddTag(CECTag(EC_TAG_STRING, wxT("Fatal error, version hash is not a valid MD4-hash.")));
438 } else if (!request->GetTagByName(EC_TAG_VERSION_ID) || request->GetTagByNameSafe(EC_TAG_VERSION_ID)->GetMD4Data() != vhash) {
439 response = new CECPacket(EC_OP_AUTH_FAIL);
440 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
441 #else
442 // For release versions, we don't want to allow connections from any arbitrary SVN client.
443 if (request->GetTagByName(EC_TAG_VERSION_ID)) {
444 response = new CECPacket(EC_OP_AUTH_FAIL);
445 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("You cannot connect to a release version from an arbitrary development snapshot! *sigh* possible crash prevented")));
446 #endif
447 } else if (protocol != NULL) {
448 uint16 proto_version = protocol->GetInt();
449 if (proto_version == EC_CURRENT_PROTOCOL_VERSION) {
450 response = new CECPacket(EC_OP_AUTH_SALT);
451 response->AddTag(CECTag(EC_TAG_PASSWD_SALT, m_passwd_salt));
452 m_conn_state = CONN_SALT_SENT;
454 // So far ok, check capabilities of client
456 bool canZLIB = false, canUTF8numbers = false;
457 if (request->GetTagByName(EC_TAG_CAN_ZLIB)) {
458 canZLIB = true;
459 m_my_flags |= EC_FLAG_ZLIB;
461 if (request->GetTagByName(EC_TAG_CAN_UTF8_NUMBERS)) {
462 canUTF8numbers = true;
463 m_my_flags |= EC_FLAG_UTF8_NUMBERS;
465 m_haveNotificationSupport = request->GetTagByName(EC_TAG_CAN_NOTIFY) != NULL;
466 AddDebugLogLineN(logEC, CFormat(wxT("Client capabilities: ZLIB: %s UTF8 numbers: %s Push notification: %s") )
467 % (canZLIB ? wxT("yes") : wxT("no"))
468 % (canUTF8numbers ? wxT("yes") : wxT("no"))
469 % (m_haveNotificationSupport ? wxT("yes") : wxT("no")));
470 } else {
471 response = new CECPacket(EC_OP_AUTH_FAIL);
472 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid protocol version.")
473 + CFormat(wxT("( %i != %i )")) % proto_version % EC_CURRENT_PROTOCOL_VERSION));
475 } else {
476 response = new CECPacket(EC_OP_AUTH_FAIL);
477 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Missing protocol version tag.")));
479 } else if ((m_conn_state == CONN_SALT_SENT) && (request->GetOpCode() == EC_OP_AUTH_PASSWD)) {
480 const CECTag *passwd = request->GetTagByName(EC_TAG_PASSWD_HASH);
481 CMD4Hash passh;
483 if (!passh.Decode(thePrefs::ECPassword())) {
484 wxString err = wxTRANSLATE("Authentication failed: invalid hash specified as EC password.");
485 AddLogLineN(wxString(wxGetTranslation(err))
486 + wxT(" ") + thePrefs::ECPassword());
487 response = new CECPacket(EC_OP_AUTH_FAIL);
488 response->AddTag(CECTag(EC_TAG_STRING, err));
489 } else {
490 wxString saltHash = MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt).GetHash();
491 wxString saltStr = CFormat(wxT("%lX")) % m_passwd_salt;
493 passh.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash).GetHash());
495 if (passwd && passwd->GetMD4Data() == passh) {
496 response = new CECPacket(EC_OP_AUTH_OK);
497 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
498 } else {
499 wxString err;
500 if (passwd) {
501 err = wxTRANSLATE("Authentication failed: wrong password.");
502 } else {
503 err = wxTRANSLATE("Authentication failed: missing password.");
506 response = new CECPacket(EC_OP_AUTH_FAIL);
507 response->AddTag(CECTag(EC_TAG_STRING, err));
508 AddLogLineN(wxGetTranslation(err));
511 } else {
512 response = new CECPacket(EC_OP_AUTH_FAIL);
513 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid request, please authenticate first.")));
516 if (response->GetOpCode() == EC_OP_AUTH_OK) {
517 m_conn_state = CONN_ESTABLISHED;
518 AddLogLineN(_("Access granted."));
519 // Establish notification handler if client supports it
520 if (HaveNotificationSupport()) {
521 theApp->ECServerHandler->m_ec_notifier->Add_EC_Client(this);
523 } else if (response->GetOpCode() == EC_OP_AUTH_FAIL) {
524 // Log message sent to client
525 if (response->GetFirstTagSafe()->IsString()) {
526 AddLogLineN(CFormat(_("Sent error message \"%s\" to client.")) % wxGetTranslation(response->GetFirstTagSafe()->GetStringData()));
528 // Access denied!
529 amuleIPV4Address address;
530 GetPeer(address);
531 AddLogLineN(CFormat(_("Unauthorized access attempt from %s. Connection closed.")) % address.IPAddress() );
532 m_conn_state = CONN_FAILED;
535 return response;
538 // Make a Logger tag (if there are any logging messages) and add it to the response
539 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
541 if (LoggerAccess.HasString()) {
542 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
543 // Tag structure is fix: tag carries nothing, inside are the strings
544 // maximum of 200 log lines per message
545 int entries = 0;
546 wxString line;
547 while (entries < 200 && LoggerAccess.GetString(line)) {
548 tag.AddTag(CECTag(EC_TAG_STRING, line));
549 entries++;
551 response->AddTag(tag);
552 //printf("send Log tag %d %d\n", FirstEntry, entries);
556 static CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
558 CECPacket *response = new CECPacket(EC_OP_STATS);
560 switch (request->GetDetailLevel()) {
561 case EC_DETAIL_FULL:
562 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
563 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
564 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
565 AddLoggerTag(response, LoggerAccess);
566 case EC_DETAIL_WEB:
567 case EC_DETAIL_CMD:
568 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
569 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
570 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
571 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
572 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
573 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
574 // User/Filecounts
576 uint32 totaluser = 0, totalfile = 0;
577 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
578 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
579 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
580 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
581 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
583 // Kad stats
584 if (Kademlia::CKademlia::IsConnected()) {
585 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
586 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
587 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
588 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
589 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
590 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
591 response->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE, Kademlia::CKademlia::IsRunningInLANMode()));
592 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
593 uint32 BuddyIP = 0;
594 uint16 BuddyPort = 0;
595 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
596 if (Buddy) {
597 BuddyIP = Buddy->GetIP();
598 BuddyPort = Buddy->GetUDPPort();
600 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
601 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
603 case EC_DETAIL_UPDATE:
604 case EC_DETAIL_INC_UPDATE:
605 break;
608 return response;
611 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CFileEncoderMap &encoders)
613 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
615 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
617 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
619 // request can contain list of queried items
620 CTagSet<uint32, EC_TAG_KNOWNFILE> queryitems(request);
622 encoders.UpdateEncoders();
624 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
625 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
627 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->ECID())) ) {
628 continue;
631 CEC_SharedFile_Tag filetag(cur_file, detail_level);
632 CKnownFile_Encoder *enc = encoders[cur_file->ECID()];
633 if ( detail_level != EC_DETAIL_UPDATE ) {
634 enc->ResetEncoder();
636 enc->Encode(&filetag);
637 response->AddTag(filetag);
639 return response;
642 static CECPacket *Get_EC_Response_GetUpdate(CFileEncoderMap &encoders, CObjTagMap &tagmap)
644 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
646 encoders.UpdateEncoders();
647 for (CFileEncoderMap::iterator it = encoders.begin(); it != encoders.end(); ++it) {
648 const CKnownFile *cur_file = it->second->GetFile();
649 CValueMap &valuemap = tagmap.GetValueMap(cur_file->ECID());
650 // Completed cleared Partfiles are still stored as CPartfile,
651 // but encoded as KnownFile, so we have to check the encoder type
652 // instead of the file type.
653 if (it->second->IsPartFile_Encoder()) {
654 CEC_PartFile_Tag filetag((const CPartFile*) cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
655 // Add information if partfile is shared
656 filetag.AddTag(EC_TAG_PARTFILE_SHARED, it->second->IsShared(), &valuemap);
658 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
659 enc->Encode(&filetag);
660 response->AddTag(filetag);
661 } else {
662 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
663 CKnownFile_Encoder * enc = encoders[cur_file->ECID()];
664 enc->Encode(&filetag);
665 response->AddTag(filetag);
668 // Add clients
669 CECEmptyTag clients(EC_TAG_CLIENT);
670 const CClientList::IDMap& clientList = theApp->clientlist->GetClientList();
671 for (CClientList::IDMap::const_iterator it = clientList.begin(); it != clientList.end(); it++) {
672 const CUpDownClient* cur_client = it->second;
673 CValueMap &valuemap = tagmap.GetValueMap(cur_client->ECID());
674 clients.AddTag(CEC_UpDownClient_Tag(cur_client, EC_DETAIL_INC_UPDATE, &valuemap));
676 response->AddTag(clients);
678 return response;
681 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
683 CECPacket *response = new CECPacket(op);
685 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
688 // request can contain list of queried items
689 // (not for incremental update of course)
690 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
692 const CClientPtrList& clients = theApp->uploadqueue->GetUploadingList();
693 CClientPtrList::const_iterator it = clients.begin();
694 for (; it != clients.end(); ++it) {
695 CUpDownClient* cur_client = *it;
697 if (!cur_client) { // shouldn't happen
698 continue;
700 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
701 continue;
703 CValueMap *valuemap = NULL;
704 if (detail_level == EC_DETAIL_INC_UPDATE) {
705 valuemap = &tagmap.GetValueMap(cur_client->ECID());
707 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
709 response->AddTag(cli_tag);
712 return response;
716 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
718 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
720 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
722 // request can contain list of queried items
723 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
725 encoders.UpdateEncoders();
727 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
728 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
730 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
731 continue;
734 CEC_PartFile_Tag filetag(cur_file, detail_level);
736 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
737 if ( detail_level != EC_DETAIL_UPDATE ) {
738 enc->ResetEncoder();
740 enc->Encode(&filetag);
742 response->AddTag(filetag);
744 return response;
748 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
750 CECPacket *response = NULL;
752 // request can contain multiple files.
753 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); it1++) {
754 const CECTag &hashtag = *it1;
756 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
758 CMD4Hash hash = hashtag.GetMD4Data();
759 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
761 if ( !pfile ) {
762 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
763 response = new CECPacket(EC_OP_FAILED);
764 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
765 //return response;
766 break;
768 switch (request->GetOpCode()) {
769 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
770 CoreNotify_PartFile_Swap_A4AF(pfile);
771 break;
772 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
773 CoreNotify_PartFile_Swap_A4AF_Auto(pfile);
774 break;
775 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
776 CoreNotify_PartFile_Swap_A4AF_Others(pfile);
777 break;
778 case EC_OP_PARTFILE_PAUSE:
779 pfile->PauseFile();
780 break;
781 case EC_OP_PARTFILE_RESUME:
782 pfile->ResumeFile();
783 pfile->SavePartFile();
784 break;
785 case EC_OP_PARTFILE_STOP:
786 pfile->StopFile();
787 break;
788 case EC_OP_PARTFILE_PRIO_SET: {
789 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
790 if ( prio == PR_AUTO ) {
791 pfile->SetAutoDownPriority(1);
792 } else {
793 pfile->SetAutoDownPriority(0);
794 pfile->SetDownPriority(prio);
797 break;
798 case EC_OP_PARTFILE_DELETE:
799 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
800 theApp->downloadqueue->StartNextFile(pfile);
802 pfile->Delete();
803 break;
805 case EC_OP_PARTFILE_SET_CAT:
806 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
807 break;
809 default:
810 response = new CECPacket(EC_OP_FAILED);
811 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
812 break;
815 if (!response) {
816 response = new CECPacket(EC_OP_NOOP);
818 return response;
821 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
823 CECPacket *response = NULL;
825 wxString full_addr = request->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS)->GetStringData();
826 wxString name = request->GetTagByNameSafe(EC_TAG_SERVER_NAME)->GetStringData();
828 wxString s_ip = full_addr.Left(full_addr.Find(':'));
829 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
831 long port = StrToULong(s_port);
832 CServer* toadd = new CServer(port, s_ip);
833 toadd->SetListName(name.IsEmpty() ? full_addr : name);
835 if ( theApp->AddServer(toadd, true) ) {
836 response = new CECPacket(EC_OP_NOOP);
837 } else {
838 response = new CECPacket(EC_OP_FAILED);
839 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
840 delete toadd;
843 return response;
846 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
848 CECPacket *response = NULL;
849 const CECTag *srv_tag = request->GetFirstTagSafe();
850 CServer *srv = 0;
851 if ( srv_tag ) {
852 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
853 // server tag passed, but server not found
854 if ( !srv ) {
855 response = new CECPacket(EC_OP_FAILED);
856 response->AddTag(CECTag(EC_TAG_STRING,
857 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
858 return response;
861 switch (request->GetOpCode()) {
862 case EC_OP_SERVER_DISCONNECT:
863 theApp->serverconnect->Disconnect();
864 response = new CECPacket(EC_OP_NOOP);
865 break;
866 case EC_OP_SERVER_REMOVE:
867 if ( srv ) {
868 theApp->serverlist->RemoveServer(srv);
869 response = new CECPacket(EC_OP_NOOP);
870 } else {
871 response = new CECPacket(EC_OP_FAILED);
872 response->AddTag(CECTag(EC_TAG_STRING,
873 wxTRANSLATE("need to define server to be removed")));
875 break;
876 case EC_OP_SERVER_CONNECT:
877 if (thePrefs::GetNetworkED2K()) {
878 if ( srv ) {
879 theApp->serverconnect->ConnectToServer(srv);
880 response = new CECPacket(EC_OP_NOOP);
881 } else {
882 theApp->serverconnect->ConnectToAnyServer();
883 response = new CECPacket(EC_OP_NOOP);
885 } else {
886 response = new CECPacket(EC_OP_FAILED);
887 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
889 break;
891 if (!response) {
892 response = new CECPacket(EC_OP_FAILED);
893 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
895 return response;
898 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
900 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
902 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
904 // request can contain list of queried items
905 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
907 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
908 CSearchResultList::const_iterator it = list.begin();
909 while (it != list.end()) {
910 CSearchFile* sf = *it++;
911 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
912 continue;
914 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
916 return response;
919 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
921 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
923 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
924 CSearchResultList::const_iterator it = list.begin();
925 while (it != list.end()) {
926 CSearchFile* sf = *it++;
927 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
928 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
929 /* Here we could add the children, if amulegui were able to merge them.
930 if (sf->HasChildren()) {
931 const CSearchResultList& children = sf->GetChildren();
932 for (size_t i = 0; i < children.size(); ++i) {
933 CSearchFile* sfc = children.at(i);
934 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
935 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
940 return response;
943 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
945 CECPacket *response = new CECPacket(EC_OP_STRINGS);
946 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
947 const CECTag &tag = *it;
948 CMD4Hash hash = tag.GetMD4Data();
949 uint8 category = tag.GetFirstTagSafe()->GetInt();
950 theApp->searchlist->AddFileToDownloadByHash(hash, category);
952 return response;
955 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
957 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
958 theApp->searchlist->StopSearch();
959 return reply;
962 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
964 wxString response;
966 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetFirstTagSafe();
967 theApp->searchlist->RemoveResults(0xffffffff);
969 CSearchList::CSearchParams params;
970 params.searchString = search_request->SearchText();
971 params.typeText = search_request->SearchFileType();
972 params.extension = search_request->SearchExt();
973 params.minSize = search_request->MinSize();
974 params.maxSize = search_request->MaxSize();
975 params.availability = search_request->Avail();
978 EC_SEARCH_TYPE search_type = search_request->SearchType();
979 SearchType core_search_type = LocalSearch;
980 uint32 op = EC_OP_FAILED;
981 switch (search_type) {
982 case EC_SEARCH_GLOBAL:
983 core_search_type = GlobalSearch;
984 case EC_SEARCH_KAD:
985 if (core_search_type != GlobalSearch) { // Not a global search obviously
986 core_search_type = KadSearch;
988 case EC_SEARCH_LOCAL: {
989 uint32 search_id = 0xffffffff;
990 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
991 if (!error.IsEmpty()) {
992 response = error;
993 } else {
994 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
995 op = EC_OP_STRINGS;
997 break;
999 case EC_SEARCH_WEB:
1000 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
1001 break;
1004 CECPacket *reply = new CECPacket(op);
1005 // error or search in progress
1006 reply->AddTag(CECTag(EC_TAG_STRING, response));
1008 return reply;
1011 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1013 CECPacket *response = new CECPacket(EC_OP_NOOP);
1014 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1015 const CECTag &tag = *it;
1016 CMD4Hash hash = tag.GetMD4Data();
1017 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1018 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1019 if ( !cur_file ) {
1020 continue;
1022 if (prio == PR_AUTO) {
1023 cur_file->SetAutoUpPriority(1);
1024 cur_file->UpdateAutoUpPriority();
1025 } else {
1026 cur_file->SetAutoUpPriority(0);
1027 cur_file->SetUpPriority(prio);
1029 Notify_SharedFilesUpdateItem(cur_file);
1032 return response;
1035 void CPartFile_Encoder::Encode(CECTag *parent)
1038 // Source part frequencies
1040 CKnownFile_Encoder::Encode(parent);
1043 // Gaps
1045 const CGapList& gaplist = m_PartFile()->GetGapList();
1046 const size_t gap_list_size = gaplist.size();
1047 ArrayOfUInts64 gaps;
1048 gaps.reserve(gap_list_size * 2);
1050 for (CGapList::const_iterator curr_pos = gaplist.begin();
1051 curr_pos != gaplist.end(); ++curr_pos) {
1052 gaps.push_back(curr_pos.start());
1053 gaps.push_back(curr_pos.end());
1056 int gap_enc_size = 0;
1057 bool changed;
1058 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1059 if (changed) {
1060 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1062 delete[] gap_enc_data;
1065 // Requested blocks
1067 ArrayOfUInts64 req_buffer;
1068 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1069 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1071 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1072 Requested_Block_Struct* block = *curr_pos2;
1073 req_buffer.push_back(block->StartOffset);
1074 req_buffer.push_back(block->EndOffset);
1076 int req_enc_size = 0;
1077 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1078 if (changed) {
1079 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1081 delete[] req_enc_data;
1084 // Source names
1086 // First count occurrence of all source names
1088 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1089 typedef std::map<wxString, int> strIntMap;
1090 strIntMap nameMap;
1091 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1092 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1093 CUpDownClient *cur_src = *it;
1094 if (cur_src->GetRequestFile() != m_file || cur_src->GetClientFilename().Length() == 0) {
1095 continue;
1097 const wxString &name = cur_src->GetClientFilename();
1098 strIntMap::iterator itm = nameMap.find(name);
1099 if (itm == nameMap.end()) {
1100 nameMap[name] = 1;
1101 } else {
1102 itm->second++;
1106 // Go through our last list
1108 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1109 SourcenameItemMap::iterator it2 = it1++;
1110 strIntMap::iterator itm = nameMap.find(it2->second.name);
1111 if (itm == nameMap.end()) {
1112 // name doesn't exist anymore, tell client to forget it
1113 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1114 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1115 sourceNames.AddTag(tag);
1116 // and forget it
1117 m_sourcenameItemMap.erase(it2);
1118 } else {
1119 // update count if it changed
1120 if (it2->second.count != itm->second) {
1121 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1122 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1123 sourceNames.AddTag(tag);
1124 it2->second.count = itm->second;
1126 // remove it from nameMap so that only new names are left there
1127 nameMap.erase(itm);
1131 // Add new names
1133 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1134 int id = ++m_sourcenameID;
1135 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1136 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1137 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1138 sourceNames.AddTag(tag);
1139 // remember it
1140 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1142 if (sourceNames.HasChildTags()) {
1143 parent->AddTag(sourceNames);
1148 void CPartFile_Encoder::ResetEncoder()
1150 CKnownFile_Encoder::ResetEncoder();
1151 m_gap_status.ResetEncoder();
1152 m_req_status.ResetEncoder();
1155 void CKnownFile_Encoder::Encode(CECTag *parent)
1158 // Source part frequencies
1160 // Reference to the availability list
1161 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1162 ((CPartFile*)m_file)->m_SrcpartFrequency :
1163 m_file->m_AvailPartFrequency;
1164 // Don't add tag if available parts aren't populated yet.
1165 if (!list.empty()) {
1166 int part_enc_size;
1167 bool changed;
1168 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1169 if (changed) {
1170 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1172 delete[] part_enc_data;
1176 static CECPacket *GetStatsGraphs(const CECPacket *request)
1178 CECPacket *response = NULL;
1180 switch (request->GetDetailLevel()) {
1181 case EC_DETAIL_WEB:
1182 case EC_DETAIL_FULL: {
1183 double dTimestamp = 0.0;
1184 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1185 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1187 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1188 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1189 uint32 *graphData;
1190 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1191 if (numPoints) {
1192 response = new CECPacket(EC_OP_STATSGRAPHS);
1193 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1194 delete [] graphData;
1195 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1196 } else {
1197 response = new CECPacket(EC_OP_FAILED);
1198 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1200 break;
1202 case EC_DETAIL_INC_UPDATE:
1203 case EC_DETAIL_UPDATE:
1204 case EC_DETAIL_CMD:
1205 // No graphs
1206 response = new CECPacket(EC_OP_FAILED);
1207 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1208 break;
1210 if (!response) {
1211 response = new CECPacket(EC_OP_FAILED);
1212 // Unknown reason
1215 return response;
1218 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1221 if ( !request ) {
1222 return 0;
1225 CECPacket *response = NULL;
1227 switch (request->GetOpCode()) {
1229 // Misc commands
1231 case EC_OP_SHUTDOWN:
1232 if (!theApp->IsOnShutDown()) {
1233 response = new CECPacket(EC_OP_NOOP);
1234 AddLogLineC(_("External Connection: shutdown requested"));
1235 #ifndef AMULE_DAEMON
1237 wxCloseEvent evt;
1238 evt.SetCanVeto(false);
1239 theApp->ShutDown(evt);
1241 #else
1242 theApp->ExitMainLoop();
1243 #endif
1244 } else {
1245 response = new CECPacket(EC_OP_FAILED);
1246 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1248 break;
1249 case EC_OP_ADD_LINK:
1250 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1251 const CECTag &tag = *it;
1252 wxString link = tag.GetStringData();
1253 int category = 0;
1254 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1255 if (cattag) {
1256 category = cattag->GetInt();
1258 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link);
1259 if ( theApp->downloadqueue->AddLink(link, category) ) {
1260 response = new CECPacket(EC_OP_NOOP);
1261 } else {
1262 // Error messages are printed by the add function.
1263 response = new CECPacket(EC_OP_FAILED);
1264 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1267 break;
1269 // Status requests
1271 case EC_OP_STAT_REQ:
1272 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1273 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1274 break;
1275 case EC_OP_GET_CONNSTATE:
1276 response = new CECPacket(EC_OP_MISC_DATA);
1277 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1278 break;
1282 case EC_OP_GET_SHARED_FILES:
1283 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1284 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1286 break;
1287 case EC_OP_GET_DLOAD_QUEUE:
1288 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1289 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1291 break;
1293 // This will evolve into an update-all for inc tags
1295 case EC_OP_GET_UPDATE:
1296 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1297 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1299 break;
1300 case EC_OP_GET_ULOAD_QUEUE:
1301 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1302 break;
1303 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1304 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1305 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1306 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1307 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1308 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1309 case EC_OP_PARTFILE_PAUSE:
1310 case EC_OP_PARTFILE_RESUME:
1311 case EC_OP_PARTFILE_STOP:
1312 case EC_OP_PARTFILE_PRIO_SET:
1313 case EC_OP_PARTFILE_DELETE:
1314 case EC_OP_PARTFILE_SET_CAT:
1315 response = Get_EC_Response_PartFile_Cmd(request);
1316 break;
1317 case EC_OP_SHAREDFILES_RELOAD:
1318 theApp->sharedfiles->Reload();
1319 response = new CECPacket(EC_OP_NOOP);
1320 break;
1321 case EC_OP_SHARED_SET_PRIO:
1322 response = Get_EC_Response_Set_SharedFile_Prio(request);
1323 break;
1324 case EC_OP_RENAME_FILE: {
1325 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1326 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1327 // search first in downloadqueue - it might be in known files as well
1328 CKnownFile* file = theApp->downloadqueue->GetFileByID(fileHash);
1329 if (!file) {
1330 file = theApp->knownfiles->FindKnownFileByID(fileHash);
1332 if (!file) {
1333 response = new CECPacket(EC_OP_FAILED);
1334 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1335 break;
1337 if (newName.IsEmpty()) {
1338 response = new CECPacket(EC_OP_FAILED);
1339 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1340 break;
1343 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1344 response = new CECPacket(EC_OP_NOOP);
1345 } else {
1346 response = new CECPacket(EC_OP_FAILED);
1347 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1350 break;
1352 case EC_OP_CLEAR_COMPLETED: {
1353 ListOfUInts32 toClear;
1354 for (CECTag::const_iterator it = request->begin(); it != request->end(); it++) {
1355 if (it->GetTagName() == EC_TAG_ECID) {
1356 toClear.push_back(it->GetInt());
1359 theApp->downloadqueue->ClearCompleted(toClear);
1360 response = new CECPacket(EC_OP_NOOP);
1361 break;
1363 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE: {
1364 theApp->sharedfiles->Reload();
1365 uint32 idClient = request->GetTagByNameSafe(EC_TAG_CLIENT)->GetInt();
1366 CUpDownClient * client = theApp->clientlist->FindClientByECID(idClient);
1367 CMD4Hash idFile = request->GetTagByNameSafe(EC_TAG_PARTFILE)->GetMD4Data();
1368 CPartFile * file = theApp->downloadqueue->GetFileByID(idFile);
1369 if (client && file) {
1370 client->SwapToAnotherFile( true, false, false, file);
1372 response = new CECPacket(EC_OP_NOOP);
1373 break;
1375 case EC_OP_SHARED_FILE_SET_COMMENT: {
1376 CMD4Hash hash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1377 CKnownFile * file = theApp->sharedfiles->GetFileByID(hash);
1378 if (file) {
1379 wxString newComment = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT)->GetStringData();
1380 uint8 newRating = request->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING)->GetInt();
1381 CoreNotify_KnownFile_Comment_Set(file, newComment, newRating);
1383 response = new CECPacket(EC_OP_NOOP);
1384 break;
1388 // Server commands
1390 case EC_OP_SERVER_ADD:
1391 response = Get_EC_Response_Server_Add(request);
1392 break;
1393 case EC_OP_SERVER_DISCONNECT:
1394 case EC_OP_SERVER_CONNECT:
1395 case EC_OP_SERVER_REMOVE:
1396 response = Get_EC_Response_Server(request);
1397 break;
1398 case EC_OP_GET_SERVER_LIST: {
1399 response = new CECPacket(EC_OP_SERVER_LIST);
1400 if (!thePrefs::GetNetworkED2K()) {
1401 // Kad only: just send an empty list
1402 break;
1404 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1405 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1406 for (
1407 std::vector<const CServer*>::const_iterator it = servers.begin();
1408 it != servers.end();
1409 ++it
1411 response->AddTag(CEC_Server_Tag(*it, detail_level));
1414 break;
1415 case EC_OP_SERVER_UPDATE_FROM_URL: {
1416 wxString url = request->GetFirstTagSafe()->GetStringData();
1418 // Save the new url, and update the UI (if not amuled).
1419 Notify_ServersURLChanged(url);
1420 thePrefs::SetEd2kServersUrl(url);
1422 theApp->serverlist->UpdateServerMetFromURL(url);
1423 response = new CECPacket(EC_OP_NOOP);
1424 break;
1427 // IPFilter
1429 case EC_OP_IPFILTER_RELOAD:
1430 NotifyAlways_IPFilter_Reload();
1431 response = new CECPacket(EC_OP_NOOP);
1432 break;
1434 case EC_OP_IPFILTER_UPDATE: {
1435 wxString url = request->GetFirstTagSafe()->GetStringData();
1436 if (url.IsEmpty()) {
1437 url = thePrefs::IPFilterURL();
1439 NotifyAlways_IPFilter_Update(url);
1440 response = new CECPacket(EC_OP_NOOP);
1441 break;
1444 // Search
1446 case EC_OP_SEARCH_START:
1447 response = Get_EC_Response_Search(request);
1448 break;
1450 case EC_OP_SEARCH_STOP:
1451 response = Get_EC_Response_Search_Stop(request);
1452 break;
1454 case EC_OP_SEARCH_RESULTS:
1455 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1456 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1457 } else {
1458 response = Get_EC_Response_Search_Results(request);
1460 break;
1462 case EC_OP_SEARCH_PROGRESS:
1463 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1464 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1465 theApp->searchlist->GetSearchProgress()));
1466 break;
1468 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1469 response = Get_EC_Response_Search_Results_Download(request);
1470 break;
1472 // Preferences
1474 case EC_OP_GET_PREFERENCES:
1475 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1476 break;
1477 case EC_OP_SET_PREFERENCES:
1478 ((CEC_Prefs_Packet *)request)->Apply();
1479 theApp->glob_prefs->Save();
1480 if (thePrefs::IsFilteringClients()) {
1481 theApp->clientlist->FilterQueues();
1483 if (thePrefs::IsFilteringServers()) {
1484 theApp->serverlist->FilterServers();
1486 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1487 theApp->DisconnectED2K();
1489 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1490 theApp->StopKad();
1492 response = new CECPacket(EC_OP_NOOP);
1493 break;
1495 case EC_OP_CREATE_CATEGORY:
1496 if ( request->GetTagCount() == 1 ) {
1497 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1498 if (tag->Create()) {
1499 response = new CECPacket(EC_OP_NOOP);
1500 } else {
1501 response = new CECPacket(EC_OP_FAILED);
1502 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1503 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1505 Notify_CategoryAdded();
1506 } else {
1507 response = new CECPacket(EC_OP_NOOP);
1509 break;
1510 case EC_OP_UPDATE_CATEGORY:
1511 if ( request->GetTagCount() == 1 ) {
1512 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1513 if (tag->Apply()) {
1514 response = new CECPacket(EC_OP_NOOP);
1515 } else {
1516 response = new CECPacket(EC_OP_FAILED);
1517 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1518 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1520 Notify_CategoryUpdate(tag->GetInt());
1521 } else {
1522 response = new CECPacket(EC_OP_NOOP);
1524 break;
1525 case EC_OP_DELETE_CATEGORY:
1526 if ( request->GetTagCount() == 1 ) {
1527 uint32 cat = request->GetFirstTagSafe()->GetInt();
1528 // this noes not only update the gui, but actually deletes the cat
1529 Notify_CategoryDelete(cat);
1531 response = new CECPacket(EC_OP_NOOP);
1532 break;
1535 // Logging
1537 case EC_OP_ADDLOGLINE:
1538 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1539 AddLogLineC(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1540 } else {
1541 AddLogLineN(request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1543 response = new CECPacket(EC_OP_NOOP);
1544 break;
1545 case EC_OP_ADDDEBUGLOGLINE:
1546 if (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL) {
1547 AddDebugLogLineC(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1548 } else {
1549 AddDebugLogLineN(logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData());
1551 response = new CECPacket(EC_OP_NOOP);
1552 break;
1553 case EC_OP_GET_LOG:
1554 response = new CECPacket(EC_OP_LOG);
1555 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1556 break;
1557 case EC_OP_GET_DEBUGLOG:
1558 response = new CECPacket(EC_OP_DEBUGLOG);
1559 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1560 break;
1561 case EC_OP_RESET_LOG:
1562 theApp->GetLog(true);
1563 response = new CECPacket(EC_OP_NOOP);
1564 break;
1565 case EC_OP_RESET_DEBUGLOG:
1566 theApp->GetDebugLog(true);
1567 response = new CECPacket(EC_OP_NOOP);
1568 break;
1569 case EC_OP_GET_LAST_LOG_ENTRY:
1571 wxString tmp = theApp->GetLog(false);
1572 if (tmp.Last() == '\n') {
1573 tmp.RemoveLast();
1575 response = new CECPacket(EC_OP_LOG);
1576 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1578 break;
1579 case EC_OP_GET_SERVERINFO:
1580 response = new CECPacket(EC_OP_SERVERINFO);
1581 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1582 break;
1583 case EC_OP_CLEAR_SERVERINFO:
1584 theApp->GetServerLog(true);
1585 response = new CECPacket(EC_OP_NOOP);
1586 break;
1588 // Statistics
1590 case EC_OP_GET_STATSGRAPHS:
1591 response = GetStatsGraphs(request);
1592 break;
1593 case EC_OP_GET_STATSTREE: {
1594 theApp->m_statistics->UpdateStatsTree();
1595 response = new CECPacket(EC_OP_STATSTREE);
1596 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1597 if (tree) {
1598 response->AddTag(*tree);
1599 delete tree;
1601 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1602 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1603 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1605 break;
1609 // Kad
1611 case EC_OP_KAD_START:
1612 if (thePrefs::GetNetworkKademlia()) {
1613 response = new CECPacket(EC_OP_NOOP);
1614 if ( !Kademlia::CKademlia::IsRunning() ) {
1615 Kademlia::CKademlia::Start();
1616 theApp->ShowConnectionState();
1618 } else {
1619 response = new CECPacket(EC_OP_FAILED);
1620 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1622 break;
1623 case EC_OP_KAD_STOP:
1624 theApp->StopKad();
1625 theApp->ShowConnectionState();
1626 response = new CECPacket(EC_OP_NOOP);
1627 break;
1628 case EC_OP_KAD_UPDATE_FROM_URL: {
1629 wxString url = request->GetFirstTagSafe()->GetStringData();
1631 // Save the new url, and update the UI (if not amuled).
1632 Notify_NodesURLChanged(url);
1633 thePrefs::SetKadNodesUrl(url);
1635 theApp->UpdateNotesDat(url);
1636 response = new CECPacket(EC_OP_NOOP);
1637 break;
1639 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1640 if (thePrefs::GetNetworkKademlia()) {
1641 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1642 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1643 theApp->ShowConnectionState();
1644 response = new CECPacket(EC_OP_NOOP);
1645 } else {
1646 response = new CECPacket(EC_OP_FAILED);
1647 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1649 break;
1652 // Networks
1653 // These requests are currently used only in the text client
1655 case EC_OP_CONNECT:
1656 if (thePrefs::GetNetworkED2K()) {
1657 response = new CECPacket(EC_OP_STRINGS);
1658 if (theApp->IsConnectedED2K()) {
1659 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1660 } else {
1661 theApp->serverconnect->ConnectToAnyServer();
1662 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1665 if (thePrefs::GetNetworkKademlia()) {
1666 if (!response) {
1667 response = new CECPacket(EC_OP_STRINGS);
1669 if (theApp->IsConnectedKad()) {
1670 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1671 } else {
1672 theApp->StartKad();
1673 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1676 if (response) {
1677 theApp->ShowConnectionState();
1678 } else {
1679 response = new CECPacket(EC_OP_FAILED);
1680 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1682 break;
1683 case EC_OP_DISCONNECT:
1684 if (theApp->IsConnected()) {
1685 response = new CECPacket(EC_OP_STRINGS);
1686 if (theApp->IsConnectedED2K()) {
1687 theApp->serverconnect->Disconnect();
1688 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1690 if (theApp->IsConnectedKad()) {
1691 theApp->StopKad();
1692 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1694 theApp->ShowConnectionState();
1695 } else {
1696 response = new CECPacket(EC_OP_NOOP);
1698 break;
1700 if (!response) {
1701 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request->GetOpCode());
1702 wxFAIL;
1703 response = new CECPacket(EC_OP_FAILED);
1704 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1706 return response;
1710 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1714 * Core general status
1716 ECStatusMsgSource::ECStatusMsgSource()
1718 m_last_ed2k_status_sent = 0xffffffff;
1719 m_last_kad_status_sent = 0xffffffff;
1720 m_server = (void *)0xffffffff;
1723 uint32 ECStatusMsgSource::GetEd2kStatus()
1725 if ( theApp->IsConnectedED2K() ) {
1726 return theApp->GetED2KID();
1727 } else if ( theApp->serverconnect->IsConnecting() ) {
1728 return 1;
1729 } else {
1730 return 0;
1734 uint32 ECStatusMsgSource::GetKadStatus()
1736 if ( theApp->IsConnectedKad() ) {
1737 return 1;
1738 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1739 return 2;
1740 } else if ( Kademlia::CKademlia::IsRunning() ) {
1741 return 3;
1743 return 0;
1746 CECPacket *ECStatusMsgSource::GetNextPacket()
1748 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1749 (m_last_kad_status_sent != GetKadStatus()) ||
1750 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1752 m_last_ed2k_status_sent = GetEd2kStatus();
1753 m_last_kad_status_sent = GetKadStatus();
1754 m_server = theApp->serverconnect->GetCurrentServer();
1756 CECPacket *response = new CECPacket(EC_OP_STATS);
1757 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1758 return response;
1760 return 0;
1764 * Downloading files
1766 ECPartFileMsgSource::ECPartFileMsgSource()
1768 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1769 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1770 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1771 m_dirty_status[cur_file->GetFileHash()] = status;
1775 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1777 CMD4Hash filehash = file->GetFileHash();
1778 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1779 m_dirty_status[filehash].m_dirty = true;;
1783 void ECPartFileMsgSource::SetNew(CPartFile *file)
1785 CMD4Hash filehash = file->GetFileHash();
1786 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1787 PARTFILE_STATUS status = { true, false, false, false, true, file };
1788 m_dirty_status[filehash] = status;
1791 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1793 CMD4Hash filehash = file->GetFileHash();
1794 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1796 m_dirty_status[filehash].m_finished = true;
1799 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1801 CMD4Hash filehash = file->GetFileHash();
1802 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1804 m_dirty_status[filehash].m_removed = true;
1807 CECPacket *ECPartFileMsgSource::GetNextPacket()
1809 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1810 it != m_dirty_status.end(); it++) {
1811 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1812 CMD4Hash filehash = it->first;
1814 CPartFile *partfile = it->second.m_file;
1816 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1817 if ( it->second.m_removed ) {
1818 CECTag tag(EC_TAG_PARTFILE, filehash);
1819 packet->AddTag(tag);
1820 m_dirty_status.erase(it);
1821 } else {
1822 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1823 packet->AddTag(tag);
1825 m_dirty_status[filehash].m_new = false;
1826 m_dirty_status[filehash].m_dirty = false;
1828 return packet;
1831 return 0;
1835 * Shared files - similar to downloading
1837 ECKnownFileMsgSource::ECKnownFileMsgSource()
1839 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1840 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1841 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1842 m_dirty_status[cur_file->GetFileHash()] = status;
1846 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1848 CMD4Hash filehash = file->GetFileHash();
1849 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1850 m_dirty_status[filehash].m_dirty = true;;
1854 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1856 CMD4Hash filehash = file->GetFileHash();
1857 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1858 KNOWNFILE_STATUS status = { true, false, false, true, file };
1859 m_dirty_status[filehash] = status;
1862 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1864 CMD4Hash filehash = file->GetFileHash();
1865 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1867 m_dirty_status[filehash].m_removed = true;
1870 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1872 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1873 it != m_dirty_status.end(); it++) {
1874 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1875 CMD4Hash filehash = it->first;
1877 CKnownFile *partfile = it->second.m_file;
1879 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1880 if ( it->second.m_removed ) {
1881 CECTag tag(EC_TAG_PARTFILE, filehash);
1882 packet->AddTag(tag);
1883 m_dirty_status.erase(it);
1884 } else {
1885 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1886 packet->AddTag(tag);
1888 m_dirty_status[filehash].m_new = false;
1889 m_dirty_status[filehash].m_dirty = false;
1891 return packet;
1894 return 0;
1898 * Notification about search status
1900 ECSearchMsgSource::ECSearchMsgSource()
1904 CECPacket *ECSearchMsgSource::GetNextPacket()
1906 if ( m_dirty_status.empty() ) {
1907 return 0;
1910 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1911 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1912 it != m_dirty_status.end(); it++) {
1914 if ( it->second.m_new ) {
1915 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1916 it->second.m_new = false;
1917 } else if ( it->second.m_dirty ) {
1918 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1923 return response;
1926 void ECSearchMsgSource::FlushStatus()
1928 m_dirty_status.clear();
1931 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1933 if ( m_dirty_status.count(file->GetFileHash()) ) {
1934 m_dirty_status[file->GetFileHash()].m_dirty = true;
1935 } else {
1936 m_dirty_status[file->GetFileHash()].m_new = true;
1937 m_dirty_status[file->GetFileHash()].m_dirty = true;
1938 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1939 m_dirty_status[file->GetFileHash()].m_file = file;
1943 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1945 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1949 * Notification about uploading clients
1951 CECPacket *ECClientMsgSource::GetNextPacket()
1953 return 0;
1957 // Notification iface per-client
1959 ECNotifier::ECNotifier()
1963 ECNotifier::~ECNotifier()
1965 while (m_msg_source.begin() != m_msg_source.end())
1966 Remove_EC_Client(m_msg_source.begin()->first);
1969 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1971 CECPacket *packet = 0;
1973 // priority 0 is highest
1975 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1976 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1977 break;
1980 return packet;
1983 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1986 // OnOutput is called for a first time before
1987 // socket is registered
1989 if ( m_msg_source.count(sock) ) {
1990 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1991 if ( !notifier_array ) {
1992 return 0;
1994 CECPacket *packet = GetNextPacket(notifier_array);
1995 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1996 return packet;
1997 } else {
1998 return 0;
2003 // Interface to notification macros
2005 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
2007 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2008 i != m_msg_source.end(); i++) {
2009 CECServerSocket *sock = i->first;
2010 if ( sock->HaveNotificationSupport() ) {
2011 ECUpdateMsgSource **notifier_array = i->second;
2012 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
2015 NextPacketToSocket();
2018 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
2020 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2021 i != m_msg_source.end(); i++) {
2022 ECUpdateMsgSource **notifier_array = i->second;
2023 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
2025 NextPacketToSocket();
2028 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
2030 // per-partfile source list is not supported (yet), and IMHO quite useless
2033 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
2035 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2036 i != m_msg_source.end(); i++) {
2037 ECUpdateMsgSource **notifier_array = i->second;
2038 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
2040 NextPacketToSocket();
2043 void ECNotifier::DownloadFile_AddSource(CPartFile *)
2045 // per-partfile source list is not supported (yet), and IMHO quite useless
2048 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
2050 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2051 i != m_msg_source.end(); i++) {
2052 ECUpdateMsgSource **notifier_array = i->second;
2053 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
2055 NextPacketToSocket();
2058 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
2060 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2061 i != m_msg_source.end(); i++) {
2062 ECUpdateMsgSource **notifier_array = i->second;
2063 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
2065 NextPacketToSocket();
2068 void ECNotifier::SharedFile_RemoveAllFiles()
2070 // need to figure out what to do here
2073 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2075 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2076 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2077 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2078 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2079 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2080 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2082 m_msg_source[sock] = notifier_array;
2085 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2087 if (m_msg_source.count(sock)) {
2088 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2090 m_msg_source.erase(sock);
2092 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2093 delete notifier_array[i];
2095 delete [] notifier_array;
2099 void ECNotifier::NextPacketToSocket()
2101 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2102 i != m_msg_source.end(); i++) {
2103 CECServerSocket *sock = i->first;
2104 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2105 ECUpdateMsgSource **notifier_array = i->second;
2106 CECPacket *packet = GetNextPacket(notifier_array);
2107 if ( packet ) {
2108 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2109 sock->SendPacket(packet);
2115 // File_checked_for_headers