Upstream tarball 10192
[amule.git] / src / ExternalConn.cpp
blob876bae6083947cc5959e245320a0cb6eece4ae9a
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 Kry ( elkry@sourceforge.net / http://www.amule.org )
5 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Copyright (c) 2008 Froenchenko Leonid (lfroen@gmail.com)
7 //
8 // Any parts of this program derived from the xMule, lMule or eMule project,
9 // or contributed by third-party developers are copyrighted by their
10 // respective authors.
12 // This program is free software; you can redistribute it and/or modify
13 // it under the terms of the GNU General Public License as published by
14 // the Free Software Foundation; either version 2 of the License, or
15 // (at your option) any later version.
17 // This program is distributed in the hope that it will be useful,
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 // GNU General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #ifdef HAVE_CONFIG_H
28 #include "config.h" // Needed for VERSION
29 #endif
31 #include <ec/cpp/ECMuleSocket.h> // Needed for CECSocket
33 #include <common/Format.h> // Needed for CFormat
35 #include <common/ClientVersion.h>
36 #include <common/MD5Sum.h>
38 #include "ExternalConn.h" // Interface declarations
39 #include "updownclient.h" // Needed for CUpDownClient
40 #include "Server.h" // Needed for CServer
41 #include "ServerList.h" // Needed for CServerList
42 #include "PartFile.h" // Needed for CPartFile
43 #include "ServerConnect.h" // Needed for CServerConnect
44 #include "UploadQueue.h" // Needed for CUploadQueue
45 #include "amule.h" // Needed for theApp
46 #include "SearchList.h" // Needed for GetSearchResults
47 #include "IPFilter.h" // Needed for CIPFilter
48 #include "ClientList.h"
49 #include "Preferences.h" // Needed for CPreferences
50 #include "Logger.h"
51 #include "GuiEvents.h" // Needed for Notify_* macros
52 #include "Statistics.h" // Needed for theStats
53 #include "KnownFileList.h" // Needed for CKnownFileList
54 #include "RandomFunctions.h"
55 #include "kademlia/kademlia/Kademlia.h"
56 #include "kademlia/kademlia/UDPFirewallTester.h"
59 //-------------------- File_Encoder --------------------
63 * Encode 'obtained parts' info to be sent to remote gui
65 class CKnownFile_Encoder {
66 // number of sources for each part for progress bar colouring
67 RLE_Data m_enc_data;
68 protected:
69 const CKnownFile *m_file;
70 public:
71 CKnownFile_Encoder(const CKnownFile *file = 0) { m_file = file; }
73 virtual ~CKnownFile_Encoder() {}
75 virtual void Encode(CECTag *parent_tag);
77 virtual void ResetEncoder()
79 m_enc_data.ResetEncoder();
82 virtual void SetShared() { }
83 virtual bool IsShared() { return true; }
84 virtual bool IsDownload() { return m_file->IsPartFile(); }
85 const CKnownFile * GetFile() { return m_file; }
88 /*!
89 * PartStatus strings and gap lists are quite long - RLE encoding will help.
91 * Instead of sending each time full part-status string, send
92 * RLE encoded difference from previous one.
94 * PartFileEncoderData class is used for decode only,
95 * while CPartFile_Encoder is used for encode only.
97 class CPartFile_Encoder : public CKnownFile_Encoder {
98 // blocks requested for download
99 RLE_Data m_req_status;
100 // gap list
101 RLE_Data m_gap_status;
102 // source names
103 SourcenameItemMap m_sourcenameItemMap;
104 // counter for unique source name ids
105 int m_sourcenameID;
106 // not all part files are shared (only when at least one part is complete)
107 bool m_shared;
109 // cast inherited member to CPartFile
110 CPartFile * m_PartFile() { wxASSERT(m_file->IsCPartFile()); return (CPartFile *)m_file; }
111 public:
112 // encoder side
113 CPartFile_Encoder(const CPartFile *file = 0) : CKnownFile_Encoder(file)
115 m_sourcenameID = 0;
116 m_shared = false;
119 virtual ~CPartFile_Encoder() {}
121 // encode - take data from m_file
122 virtual void Encode(CECTag *parent_tag);
124 // Encoder may reset history if full info requested
125 virtual void ResetEncoder();
127 virtual void SetShared() { m_shared = true; }
128 virtual bool IsShared() { return m_shared; }
129 virtual bool IsDownload() { return true; }
132 class CFileEncoderMap : public std::map<uint32, CKnownFile_Encoder*> {
133 typedef std::set<uint32> IDSet;
134 public:
135 ~CFileEncoderMap();
136 void UpdateEncoders();
139 CFileEncoderMap::~CFileEncoderMap()
141 // DeleteContents() causes infinite recursion here!
142 for (iterator it = begin(); it != end(); it++) {
143 delete it->second;
147 // Check if encoder contains files that are no longer used
148 // or if we have new files without encoder yet.
149 void CFileEncoderMap::UpdateEncoders()
151 IDSet curr_files, dead_files;
152 // Downloads
153 std::vector<CPartFile*> downloads;
154 theApp->downloadqueue->CopyFileList(downloads);
155 for (uint32 i = downloads.size(); i--;) {
156 uint32 id = downloads[i]->ECID();
157 curr_files.insert(id);
158 if (!count(id)) {
159 (*this)[id] = new CPartFile_Encoder(downloads[i]);
162 // Shares
163 std::vector<CKnownFile*> shares;
164 theApp->sharedfiles->CopyFileList(shares);
165 for (uint32 i = shares.size(); i--;) {
166 uint32 id = shares[i]->ECID();
167 if (shares[i]->IsPartFile()) { // we already have it
168 (*this)[id]->SetShared();
169 continue;
171 curr_files.insert(id);
172 if (!count(id)) {
173 (*this)[id] = new CKnownFile_Encoder(shares[i]);
176 // Check for removed files, and store them in a set for deletion.
177 // (std::map documentation is unclear if a construct like
178 // iterator to_del = it++; erase(to_del) ;
179 // works or invalidates it too.)
180 for (iterator it = begin(); it != end(); it++) {
181 if (!curr_files.count(it->first)) {
182 dead_files.insert(it->first);
185 // then delete them
186 for (IDSet::iterator it = dead_files.begin(); it != dead_files.end(); it++) {
187 iterator it2 = find(*it);
188 delete it2->second;
189 erase(it2);
194 //-------------------- CECServerSocket --------------------
196 class CECServerSocket : public CECMuleSocket
198 public:
199 CECServerSocket(ECNotifier *notifier);
200 virtual ~CECServerSocket();
202 virtual const CECPacket *OnPacketReceived(const CECPacket *packet, uint32 trueSize);
203 virtual void OnLost();
205 virtual void WriteDoneAndQueueEmpty();
206 private:
207 ECNotifier *m_ec_notifier;
209 const CECPacket *Authenticate(const CECPacket *);
211 enum {
212 CONN_INIT,
213 CONN_SALT_SENT,
214 CONN_ESTABLISHED,
215 CONN_FAILED
216 } m_conn_state;
218 uint64_t m_passwd_salt;
219 CLoggerAccess m_LoggerAccess;
220 CFileEncoderMap m_FileEncoder;
221 CObjTagMap m_obj_tagmap;
222 CECPacket *ProcessRequest2(const CECPacket *request);
224 virtual bool IsAuthorized() { return m_conn_state == CONN_ESTABLISHED; }
228 CECServerSocket::CECServerSocket(ECNotifier *notifier)
230 CECMuleSocket(true),
231 m_conn_state(CONN_INIT),
232 m_passwd_salt(GetRandomUint64())
234 wxASSERT(theApp->ECServerHandler);
235 theApp->ECServerHandler->AddSocket(this);
236 m_ec_notifier = notifier;
240 CECServerSocket::~CECServerSocket()
242 wxASSERT(theApp->ECServerHandler);
243 theApp->ECServerHandler->RemoveSocket(this);
247 const CECPacket *CECServerSocket::OnPacketReceived(const CECPacket *packet, uint32 trueSize)
249 packet->DebugPrint(true, trueSize);
251 const CECPacket *reply = NULL;
253 if (m_conn_state == CONN_FAILED) {
254 // Client didn't close the socket when authentication failed.
255 AddLogLineM(false, _("Client sent packet after authentication failed."));
256 CloseSocket();
259 if (m_conn_state != CONN_ESTABLISHED) {
260 // This is called twice:
261 // 1) send salt
262 // 2) verify password
263 reply = Authenticate(packet);
264 } else {
265 reply = ProcessRequest2(packet);
267 return reply;
271 void CECServerSocket::OnLost()
273 AddLogLineM(false,_("External connection closed."));
274 theApp->ECServerHandler->m_ec_notifier->Remove_EC_Client(this);
275 DestroySocket();
278 void CECServerSocket::WriteDoneAndQueueEmpty()
280 if ( HaveNotificationSupport() && (m_conn_state == CONN_ESTABLISHED) ) {
281 CECPacket *packet = m_ec_notifier->GetNextPacket(this);
282 if ( packet ) {
283 SendPacket(packet);
285 } else {
286 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
290 //-------------------- ExternalConn --------------------
292 enum
293 { // id for sockets
294 SERVER_ID = 1000
298 BEGIN_EVENT_TABLE(ExternalConn, wxEvtHandler)
299 EVT_SOCKET(SERVER_ID, ExternalConn::OnServerEvent)
300 END_EVENT_TABLE()
303 ExternalConn::ExternalConn(amuleIPV4Address addr, wxString *msg)
305 wxString msgLocal;
306 m_ECServer = NULL;
307 // Are we allowed to accept External Connections?
308 if ( thePrefs::AcceptExternalConnections() ) {
309 // We must have a valid password, otherwise we will not allow EC connections
310 if (thePrefs::ECPassword().IsEmpty()) {
311 *msg += wxT("External connections disabled due to empty password!\n");
312 AddLogLineM(true, _("External connections disabled due to empty password!"));
313 return;
316 // Create the socket
317 m_ECServer = new wxSocketServer(addr, wxSOCKET_REUSEADDR);
318 m_ECServer->SetEventHandler(*this, SERVER_ID);
319 m_ECServer->SetNotify(wxSOCKET_CONNECTION_FLAG);
320 m_ECServer->Notify(true);
322 int port = addr.Service();
323 wxString ip = addr.IPAddress();
324 if (m_ECServer->Ok()) {
325 msgLocal = wxT("*** TCP socket (ECServer) listening on ") + ip +
326 wxString::Format(wxT(":%d"), port);
327 *msg += msgLocal + wxT("\n");
328 AddLogLineM(false, msgLocal);
329 } else {
330 msgLocal = wxT("Could not listen for external connections at ") + ip +
331 wxString::Format(wxT(":%d!"), port);
332 *msg += msgLocal + wxT("\n");
333 AddLogLineM(false, msgLocal);
335 } else {
336 *msg += wxT("External connections disabled in config file\n");
337 AddLogLineM(false,_("External connections disabled in config file"));
339 m_ec_notifier = new ECNotifier();
343 ExternalConn::~ExternalConn()
345 KillAllSockets();
346 delete m_ECServer;
347 delete m_ec_notifier;
351 void ExternalConn::AddSocket(CECServerSocket *s)
353 wxASSERT(s);
354 socket_list.insert(s);
358 void ExternalConn::RemoveSocket(CECServerSocket *s)
360 wxASSERT(s);
361 socket_list.erase(s);
365 void ExternalConn::KillAllSockets()
367 AddDebugLogLineM(false, logGeneral,
368 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
369 socket_list.size());
370 SocketSet::iterator it = socket_list.begin();
371 while (it != socket_list.end()) {
372 CECServerSocket *s = *(it++);
373 s->Close();
374 s->Destroy();
379 void ExternalConn::OnServerEvent(wxSocketEvent& WXUNUSED(event))
381 CECServerSocket *sock = new CECServerSocket(m_ec_notifier);
382 // Accept new connection if there is one in the pending
383 // connections queue, else exit. We use Accept(FALSE) for
384 // non-blocking accept (although if we got here, there
385 // should ALWAYS be a pending connection).
386 if ( m_ECServer->AcceptWith(*sock, false) ) {
387 AddLogLineM(false, _("New external connection accepted"));
388 } else {
389 delete sock;
390 AddLogLineM(false, _("ERROR: couldn't accept a new external connection"));
396 // Authentication
398 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
400 CECPacket *response;
402 if (request == NULL) {
403 return new CECPacket(EC_OP_AUTH_FAIL);
406 // Password must be specified if we are to allow remote connections
407 if ( thePrefs::ECPassword().IsEmpty() ) {
408 AddLogLineM(true, _("External connection refused due to empty password in preferences!"));
410 return new CECPacket(EC_OP_AUTH_FAIL);
413 if ((m_conn_state == CONN_INIT) && (request->GetOpCode() == EC_OP_AUTH_REQ) ) {
414 const CECTag *clientName = request->GetTagByName(EC_TAG_CLIENT_NAME);
415 const CECTag *clientVersion = request->GetTagByName(EC_TAG_CLIENT_VERSION);
417 AddLogLineM(false, CFormat( _("Connecting client: %s %s") )
418 % ( clientName ? clientName->GetStringData() : wxString(_("Unknown")) )
419 % ( clientVersion ? clientVersion->GetStringData() : wxString(_("Unknown version")) ) );
420 const CECTag *protocol = request->GetTagByName(EC_TAG_PROTOCOL_VERSION);
421 #ifdef EC_VERSION_ID
422 // For SVN versions, both client and server must use SVNDATE, and they must be the same
423 CMD4Hash vhash;
424 if (!vhash.Decode(wxT(EC_VERSION_ID))) {
425 response = new CECPacket(EC_OP_AUTH_FAIL);
426 response->AddTag(CECTag(EC_TAG_STRING, wxT("Fatal error, version hash is not a valid MD4-hash.")));
427 } else if (!request->GetTagByName(EC_TAG_VERSION_ID) || request->GetTagByNameSafe(EC_TAG_VERSION_ID)->GetMD4Data() != vhash) {
428 response = new CECPacket(EC_OP_AUTH_FAIL);
429 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
430 #else
431 // For release versions, we don't want to allow connections from any arbitrary SVN client.
432 if (request->GetTagByName(EC_TAG_VERSION_ID)) {
433 response = new CECPacket(EC_OP_AUTH_FAIL);
434 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("You cannot connect to a release version from an arbitrary SVN version! *sigh* possible crash prevented")));
435 #endif
436 } else if (protocol != NULL) {
437 uint16 proto_version = protocol->GetInt();
438 if (proto_version == EC_CURRENT_PROTOCOL_VERSION) {
439 response = new CECPacket(EC_OP_AUTH_SALT);
440 response->AddTag(CECTag(EC_TAG_PASSWD_SALT, m_passwd_salt));
441 m_conn_state = CONN_SALT_SENT;
443 // So far ok, check capabilities of client
445 bool canZLIB = false, canUTF8numbers = false;
446 if (request->GetTagByName(EC_TAG_CAN_ZLIB)) {
447 canZLIB = true;
448 m_my_flags |= EC_FLAG_ZLIB;
450 if (request->GetTagByName(EC_TAG_CAN_UTF8_NUMBERS)) {
451 canUTF8numbers = true;
452 m_my_flags |= EC_FLAG_UTF8_NUMBERS;
454 m_haveNotificationSupport = request->GetTagByName(EC_TAG_CAN_NOTIFY) != NULL;
455 AddDebugLogLineN(logEC, CFormat(wxT("Client capabilities: ZLIB: %s UTF8 numbers: %s Push notification: %s") )
456 % (canZLIB ? wxT("yes") : wxT("no"))
457 % (canUTF8numbers ? wxT("yes") : wxT("no"))
458 % (m_haveNotificationSupport ? wxT("yes") : wxT("no")));
459 } else {
460 response = new CECPacket(EC_OP_AUTH_FAIL);
461 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid protocol version.") + wxString::Format(wxT("( %i != %i )"),proto_version,EC_CURRENT_PROTOCOL_VERSION)));
463 } else {
464 response = new CECPacket(EC_OP_AUTH_FAIL);
465 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Missing protocol version tag.")));
467 } else if ((m_conn_state == CONN_SALT_SENT) && (request->GetOpCode() == EC_OP_AUTH_PASSWD)) {
468 const CECTag *passwd = request->GetTagByName(EC_TAG_PASSWD_HASH);
469 CMD4Hash passh;
471 if (!passh.Decode(thePrefs::ECPassword())) {
472 wxString err = wxTRANSLATE("Authentication failed: invalid hash specified as EC password.");
473 AddLogLineM(false, wxString(wxGetTranslation(err)) + wxT(" ") + thePrefs::ECPassword());
474 response = new CECPacket(EC_OP_AUTH_FAIL);
475 response->AddTag(CECTag(EC_TAG_STRING, err));
476 } else {
477 wxString saltHash = MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt).GetHash();
478 wxString saltStr = CFormat(wxT("%lX")) % m_passwd_salt;
480 passh.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash).GetHash());
482 if (passwd && passwd->GetMD4Data() == passh) {
483 response = new CECPacket(EC_OP_AUTH_OK);
484 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
485 } else {
486 wxString err;
487 if (passwd) {
488 err = wxTRANSLATE("Authentication failed: wrong password.");
489 } else {
490 err = wxTRANSLATE("Authentication failed: missing password.");
493 response = new CECPacket(EC_OP_AUTH_FAIL);
494 response->AddTag(CECTag(EC_TAG_STRING, err));
495 AddLogLineM(false, wxGetTranslation(err));
498 } else {
499 response = new CECPacket(EC_OP_AUTH_FAIL);
500 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid request, please authenticate first.")));
503 if (response->GetOpCode() == EC_OP_AUTH_OK) {
504 m_conn_state = CONN_ESTABLISHED;
505 AddLogLineM(false, _("Access granted."));
506 // Establish notification handler if client supports it
507 if (HaveNotificationSupport()) {
508 theApp->ECServerHandler->m_ec_notifier->Add_EC_Client(this);
510 } else if (response->GetOpCode() == EC_OP_AUTH_FAIL) {
511 // Log message sent to client
512 if (response->GetFirstTagSafe()->IsString()) {
513 AddLogLineM(false, CFormat(_("Sent error message \"%s\" to client.")) % wxGetTranslation(response->GetFirstTagSafe()->GetStringData()));
515 // Access denied!
516 amuleIPV4Address address;
517 GetPeer(address);
518 AddLogLineM(false, CFormat(_("Unauthorized access attempt from %s. Connection closed.")) % address.IPAddress() );
519 m_conn_state = CONN_FAILED;
522 return response;
525 // Make a Logger tag (if there are any logging messages) and add it to the response
526 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
528 if (LoggerAccess.HasString()) {
529 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
530 // Tag structure is fix: tag carries nothing, inside are the strings
531 // maximum of 200 log lines per message
532 int entries = 0;
533 wxString line;
534 while (entries < 200 && LoggerAccess.GetString(line)) {
535 tag.AddTag(CECTag(EC_TAG_STRING, line));
536 entries++;
538 response->AddTag(tag);
539 //printf("send Log tag %d %d\n", FirstEntry, entries);
543 static CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
545 CECPacket *response = new CECPacket(EC_OP_STATS);
547 switch (request->GetDetailLevel()) {
548 case EC_DETAIL_FULL:
549 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
550 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
551 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
552 AddLoggerTag(response, LoggerAccess);
553 case EC_DETAIL_WEB:
554 case EC_DETAIL_CMD:
555 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
556 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
557 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
558 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
559 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
560 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
561 // User/Filecounts
563 uint32 totaluser = 0, totalfile = 0;
564 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
565 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
566 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
567 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
568 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
570 // Kad stats
571 if (Kademlia::CKademlia::IsConnected()) {
572 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
573 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
574 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
575 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
576 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
577 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
578 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
579 uint32 BuddyIP = 0;
580 uint16 BuddyPort = 0;
581 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
582 if (Buddy) {
583 BuddyIP = Buddy->GetIP();
584 BuddyPort = Buddy->GetUDPPort();
586 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
587 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
589 case EC_DETAIL_UPDATE:
590 case EC_DETAIL_INC_UPDATE:
591 break;
594 return response;
597 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CFileEncoderMap &encoders)
599 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
601 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
603 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
605 // request can contain list of queried items
606 CTagSet<uint32, EC_TAG_KNOWNFILE> queryitems(request);
608 encoders.UpdateEncoders();
610 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
611 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
613 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->ECID())) ) {
614 continue;
617 CEC_SharedFile_Tag filetag(cur_file, detail_level);
618 CKnownFile_Encoder *enc = encoders[cur_file->ECID()];
619 if ( detail_level != EC_DETAIL_UPDATE ) {
620 enc->ResetEncoder();
622 enc->Encode(&filetag);
623 response->AddTag(filetag);
625 return response;
628 static CECPacket *Get_EC_Response_GetUpdate(CFileEncoderMap &encoders, CObjTagMap &tagmap)
630 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
632 encoders.UpdateEncoders();
633 for (CFileEncoderMap::iterator it = encoders.begin(); it != encoders.end(); ++it) {
634 const CKnownFile *cur_file = it->second->GetFile();
635 CValueMap &valuemap = tagmap.GetValueMap(cur_file->ECID());
636 if (cur_file->IsCPartFile()) {
637 CEC_PartFile_Tag filetag((const CPartFile*) cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
638 // Add information if partfile is shared
639 filetag.AddTag(EC_TAG_PARTFILE_SHARED, it->second->IsShared(), &valuemap);
641 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
642 enc->Encode(&filetag);
643 response->AddTag(filetag);
644 } else {
645 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
646 CKnownFile_Encoder * enc = encoders[cur_file->ECID()];
647 enc->Encode(&filetag);
648 response->AddTag(filetag);
651 // Add clients
652 CECEmptyTag clients(EC_TAG_CLIENT);
653 const CClientList::IDMap& clientList = theApp->clientlist->GetClientList();
654 for (CClientList::IDMap::const_iterator it = clientList.begin(); it != clientList.end(); it++) {
655 const CUpDownClient* cur_client = it->second;
656 CValueMap &valuemap = tagmap.GetValueMap(cur_client->ECID());
657 clients.AddTag(CEC_UpDownClient_Tag(cur_client, EC_DETAIL_INC_UPDATE, &valuemap));
659 response->AddTag(clients);
661 return response;
664 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
666 CECPacket *response = new CECPacket(op);
668 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
671 // request can contain list of queried items
672 // (not for incremental update of course)
673 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
675 const CClientPtrList& clients = theApp->uploadqueue->GetUploadingList();
676 CClientPtrList::const_iterator it = clients.begin();
677 for (; it != clients.end(); ++it) {
678 CUpDownClient* cur_client = *it;
680 if (!cur_client) { // shouldn't happen
681 continue;
683 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
684 continue;
686 CValueMap *valuemap = NULL;
687 if (detail_level == EC_DETAIL_INC_UPDATE) {
688 valuemap = &tagmap.GetValueMap(cur_client->ECID());
690 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
692 response->AddTag(cli_tag);
695 return response;
699 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
701 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
703 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
705 // request can contain list of queried items
706 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
708 encoders.UpdateEncoders();
710 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
711 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
713 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
714 continue;
717 CEC_PartFile_Tag filetag(cur_file, detail_level);
719 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
720 if ( detail_level != EC_DETAIL_UPDATE ) {
721 enc->ResetEncoder();
723 enc->Encode(&filetag);
725 response->AddTag(filetag);
727 return response;
731 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
733 CECPacket *response = NULL;
735 // request can contain multiple files.
736 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); it1++) {
737 const CECTag &hashtag = *it1;
739 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
741 CMD4Hash hash = hashtag.GetMD4Data();
742 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
744 if ( !pfile ) {
745 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
746 response = new CECPacket(EC_OP_FAILED);
747 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
748 //return response;
749 break;
751 switch (request->GetOpCode()) {
752 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
753 if ((pfile->GetStatus(false) == PS_READY) ||
754 (pfile->GetStatus(false) == PS_EMPTY)) {
755 CKnownFile::SourceSet::const_iterator it = pfile->GetA4AFList().begin();
756 while ( it != pfile->GetA4AFList().end() ) {
757 CUpDownClient *cur_source = *it++;
759 cur_source->SwapToAnotherFile(true, false, false, pfile);
762 break;
763 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
764 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
765 break;
766 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
767 if ((pfile->GetStatus(false) == PS_READY) ||
768 (pfile->GetStatus(false) == PS_EMPTY)) {
769 CKnownFile::SourceSet::const_iterator it = pfile->GetSourceList().begin();
770 while ( it != pfile->GetSourceList().end() ) {
771 CUpDownClient* cur_source = *it++;
773 cur_source->SwapToAnotherFile(false, false, false, NULL);
776 break;
777 case EC_OP_PARTFILE_PAUSE:
778 pfile->PauseFile();
779 break;
780 case EC_OP_PARTFILE_RESUME:
781 pfile->ResumeFile();
782 pfile->SavePartFile();
783 break;
784 case EC_OP_PARTFILE_STOP:
785 pfile->StopFile();
786 break;
787 case EC_OP_PARTFILE_PRIO_SET: {
788 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
789 if ( prio == PR_AUTO ) {
790 pfile->SetAutoDownPriority(1);
791 } else {
792 pfile->SetAutoDownPriority(0);
793 pfile->SetDownPriority(prio);
796 break;
797 case EC_OP_PARTFILE_DELETE:
798 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
799 theApp->downloadqueue->StartNextFile(pfile);
801 pfile->Delete();
802 break;
804 case EC_OP_PARTFILE_SET_CAT:
805 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
806 break;
808 default:
809 response = new CECPacket(EC_OP_FAILED);
810 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
811 break;
814 if (!response) {
815 response = new CECPacket(EC_OP_NOOP);
817 return response;
820 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
822 CECPacket *response = NULL;
824 const CECTag *srv_tag = request->GetFirstTagSafe();
826 wxString full_addr = srv_tag->GetTagByName(EC_TAG_SERVER_ADDRESS)->GetStringData();
827 wxString name = srv_tag->GetTagByName(EC_TAG_SERVER_NAME)->GetStringData();
829 wxString s_ip = full_addr.Left(full_addr.Find(':'));
830 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
832 long port = StrToULong(s_port);
833 CServer* toadd = new CServer(port, s_ip);
834 toadd->SetListName(name.IsEmpty() ? full_addr : name);
836 if ( theApp->AddServer(toadd, true) ) {
837 response = new CECPacket(EC_OP_NOOP);
838 } else {
839 response = new CECPacket(EC_OP_FAILED);
840 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
841 delete toadd;
844 return response;
847 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
849 CECPacket *response = NULL;
850 const CECTag *srv_tag = request->GetFirstTagSafe();
851 CServer *srv = 0;
852 if ( srv_tag ) {
853 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
854 // server tag passed, but server not found
855 if ( !srv ) {
856 response = new CECPacket(EC_OP_FAILED);
857 response->AddTag(CECTag(EC_TAG_STRING,
858 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
859 return response;
862 switch (request->GetOpCode()) {
863 case EC_OP_SERVER_DISCONNECT:
864 theApp->serverconnect->Disconnect();
865 response = new CECPacket(EC_OP_NOOP);
866 break;
867 case EC_OP_SERVER_REMOVE:
868 if ( srv ) {
869 theApp->serverlist->RemoveServer(srv);
870 response = new CECPacket(EC_OP_NOOP);
871 } else {
872 response = new CECPacket(EC_OP_FAILED);
873 response->AddTag(CECTag(EC_TAG_STRING,
874 wxTRANSLATE("need to define server to be removed")));
876 break;
877 case EC_OP_SERVER_CONNECT:
878 if (thePrefs::GetNetworkED2K()) {
879 if ( srv ) {
880 theApp->serverconnect->ConnectToServer(srv);
881 response = new CECPacket(EC_OP_NOOP);
882 } else {
883 theApp->serverconnect->ConnectToAnyServer();
884 response = new CECPacket(EC_OP_NOOP);
886 } else {
887 response = new CECPacket(EC_OP_FAILED);
888 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
890 break;
892 if (!response) {
893 response = new CECPacket(EC_OP_FAILED);
894 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
896 return response;
899 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
901 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
903 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
905 // request can contain list of queried items
906 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
908 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
909 CSearchResultList::const_iterator it = list.begin();
910 while (it != list.end()) {
911 CSearchFile* sf = *it++;
912 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
913 continue;
915 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
917 return response;
920 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
922 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
924 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
925 CSearchResultList::const_iterator it = list.begin();
926 while (it != list.end()) {
927 CSearchFile* sf = *it++;
928 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
929 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
930 /* Here we could add the children, if amulegui were able to merge them.
931 if (sf->HasChildren()) {
932 const CSearchResultList& children = sf->GetChildren();
933 for (size_t i = 0; i < children.size(); ++i) {
934 CSearchFile* sfc = children.at(i);
935 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
936 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
941 return response;
944 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
946 CECPacket *response = new CECPacket(EC_OP_STRINGS);
947 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
948 const CECTag &tag = *it;
949 CMD4Hash hash = tag.GetMD4Data();
950 uint8 category = tag.GetFirstTagSafe()->GetInt();
951 theApp->searchlist->AddFileToDownloadByHash(hash, category);
953 return response;
956 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
958 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
959 theApp->searchlist->StopGlobalSearch();
960 return reply;
963 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
965 wxString response;
967 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetFirstTagSafe();
968 theApp->searchlist->RemoveResults(0xffffffff);
970 CSearchList::CSearchParams params;
971 params.searchString = search_request->SearchText();
972 params.typeText = search_request->SearchFileType();
973 params.extension = search_request->SearchExt();
974 params.minSize = search_request->MinSize();
975 params.maxSize = search_request->MaxSize();
976 params.availability = search_request->Avail();
979 EC_SEARCH_TYPE search_type = search_request->SearchType();
980 SearchType core_search_type = LocalSearch;
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!");
996 break;
998 case EC_SEARCH_WEB:
999 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
1000 break;
1003 CECPacket *reply = new CECPacket(EC_OP_FAILED);
1004 // error or search in progress
1005 reply->AddTag(CECTag(EC_TAG_STRING, response));
1007 return reply;
1010 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1012 CECPacket *response = new CECPacket(EC_OP_NOOP);
1013 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1014 const CECTag &tag = *it;
1015 CMD4Hash hash = tag.GetMD4Data();
1016 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1017 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1018 if ( !cur_file ) {
1019 continue;
1021 if (prio == PR_AUTO) {
1022 cur_file->SetAutoUpPriority(1);
1023 cur_file->UpdateAutoUpPriority();
1024 } else {
1025 cur_file->SetAutoUpPriority(0);
1026 cur_file->SetUpPriority(prio);
1028 Notify_SharedFilesUpdateItem(cur_file);
1031 return response;
1034 static CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
1036 CECPacket *response;
1037 if (thePrefs::GetNetworkKademlia()) {
1038 response = new CECPacket(EC_OP_NOOP);
1039 if ( !Kademlia::CKademlia::IsRunning() ) {
1040 Kademlia::CKademlia::Start();
1041 theApp->ShowConnectionState();
1043 const CECTag *addrtag = request->GetFirstTagSafe();
1044 if ( addrtag ) {
1045 uint32 ip = addrtag->GetIPv4Data().IP();
1046 uint16 port = addrtag->GetIPv4Data().m_port;
1047 Kademlia::CKademlia::Bootstrap(ip, port, true);
1049 } else {
1050 response = new CECPacket(EC_OP_FAILED);
1051 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1054 return response;
1057 void CPartFile_Encoder::Encode(CECTag *parent)
1060 // Source part frequencies
1062 CKnownFile_Encoder::Encode(parent);
1065 // Gaps
1067 const CGapList& gaplist = m_PartFile()->GetGapList();
1068 const size_t gap_list_size = gaplist.size();
1069 ArrayOfUInts64 gaps;
1070 gaps.reserve(gap_list_size * 2);
1072 for (CGapList::const_iterator curr_pos = gaplist.begin();
1073 curr_pos != gaplist.end(); ++curr_pos) {
1074 gaps.push_back(curr_pos.start());
1075 gaps.push_back(curr_pos.end());
1078 int gap_enc_size = 0;
1079 bool changed;
1080 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1081 if (changed) {
1082 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1084 delete[] gap_enc_data;
1087 // Requested blocks
1089 ArrayOfUInts64 req_buffer;
1090 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1091 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1093 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1094 Requested_Block_Struct* block = *curr_pos2;
1095 req_buffer.push_back(block->StartOffset);
1096 req_buffer.push_back(block->EndOffset);
1098 int req_enc_size = 0;
1099 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1100 if (changed) {
1101 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1103 delete[] req_enc_data;
1106 // Source names
1108 // First count occurrence of all source names
1110 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1111 typedef std::map<wxString, int> strIntMap;
1112 strIntMap nameMap;
1113 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1114 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1115 CUpDownClient *cur_src = *it;
1116 if (cur_src->GetRequestFile() != m_file || cur_src->GetClientFilename().Length() == 0) {
1117 continue;
1119 const wxString &name = cur_src->GetClientFilename();
1120 strIntMap::iterator itm = nameMap.find(name);
1121 if (itm == nameMap.end()) {
1122 nameMap[name] = 1;
1123 } else {
1124 itm->second++;
1128 // Go through our last list
1130 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1131 SourcenameItemMap::iterator it2 = it1++;
1132 strIntMap::iterator itm = nameMap.find(it2->second.name);
1133 if (itm == nameMap.end()) {
1134 // name doesn't exist anymore, tell client to forget it
1135 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1136 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1137 sourceNames.AddTag(tag);
1138 // and forget it
1139 m_sourcenameItemMap.erase(it2);
1140 } else {
1141 // update count if it changed
1142 if (it2->second.count != itm->second) {
1143 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1144 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1145 sourceNames.AddTag(tag);
1146 it2->second.count = itm->second;
1148 // remove it from nameMap so that only new names are left there
1149 nameMap.erase(itm);
1153 // Add new names
1155 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1156 int id = ++m_sourcenameID;
1157 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1158 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1159 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1160 sourceNames.AddTag(tag);
1161 // remember it
1162 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1164 if (sourceNames.HasChildTags()) {
1165 parent->AddTag(sourceNames);
1170 void CPartFile_Encoder::ResetEncoder()
1172 CKnownFile_Encoder::ResetEncoder();
1173 m_gap_status.ResetEncoder();
1174 m_req_status.ResetEncoder();
1177 void CKnownFile_Encoder::Encode(CECTag *parent)
1180 // Source part frequencies
1182 // Reference to the availability list
1183 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1184 ((CPartFile*)m_file)->m_SrcpartFrequency :
1185 m_file->m_AvailPartFrequency;
1186 // Don't add tag if available parts aren't populated yet.
1187 if (!list.empty()) {
1188 int part_enc_size;
1189 bool changed;
1190 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1191 if (changed) {
1192 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1194 delete[] part_enc_data;
1198 static CECPacket *GetStatsGraphs(const CECPacket *request)
1200 CECPacket *response = NULL;
1202 switch (request->GetDetailLevel()) {
1203 case EC_DETAIL_WEB:
1204 case EC_DETAIL_FULL: {
1205 double dTimestamp = 0.0;
1206 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1207 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1209 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1210 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1211 uint32 *graphData;
1212 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1213 if (numPoints) {
1214 response = new CECPacket(EC_OP_STATSGRAPHS);
1215 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1216 delete [] graphData;
1217 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1218 } else {
1219 response = new CECPacket(EC_OP_FAILED);
1220 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1222 break;
1224 case EC_DETAIL_INC_UPDATE:
1225 case EC_DETAIL_UPDATE:
1226 case EC_DETAIL_CMD:
1227 // No graphs
1228 response = new CECPacket(EC_OP_FAILED);
1229 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1230 break;
1232 if (!response) {
1233 response = new CECPacket(EC_OP_FAILED);
1234 // Unknown reason
1237 return response;
1240 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1243 if ( !request ) {
1244 return 0;
1247 CECPacket *response = NULL;
1249 switch (request->GetOpCode()) {
1251 // Misc commands
1253 case EC_OP_SHUTDOWN:
1254 if (!theApp->IsOnShutDown()) {
1255 response = new CECPacket(EC_OP_NOOP);
1256 AddLogLineM(true, _("External Connection: shutdown requested"));
1257 #ifndef AMULE_DAEMON
1259 wxCloseEvent evt;
1260 evt.SetCanVeto(false);
1261 theApp->ShutDown(evt);
1263 #else
1264 theApp->ExitMainLoop();
1265 #endif
1266 } else {
1267 response = new CECPacket(EC_OP_FAILED);
1268 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1270 break;
1271 case EC_OP_ADD_LINK:
1272 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1273 const CECTag &tag = *it;
1274 wxString link = tag.GetStringData();
1275 int category = 0;
1276 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1277 if (cattag) {
1278 category = cattag->GetInt();
1280 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link);
1281 if ( theApp->downloadqueue->AddLink(link, category) ) {
1282 response = new CECPacket(EC_OP_NOOP);
1283 } else {
1284 // Error messages are printed by the add function.
1285 response = new CECPacket(EC_OP_FAILED);
1286 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1289 break;
1291 // Status requests
1293 case EC_OP_STAT_REQ:
1294 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1295 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1296 break;
1297 case EC_OP_GET_CONNSTATE:
1298 response = new CECPacket(EC_OP_MISC_DATA);
1299 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1300 break;
1304 case EC_OP_GET_SHARED_FILES:
1305 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1306 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1308 break;
1309 case EC_OP_GET_DLOAD_QUEUE:
1310 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1311 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1313 break;
1315 // This will evolve into an update-all for inc tags
1317 case EC_OP_GET_UPDATE:
1318 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1319 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1321 break;
1322 case EC_OP_GET_ULOAD_QUEUE:
1323 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1324 break;
1325 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1326 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1327 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1328 case EC_OP_PARTFILE_CLEANUP_SOURCES:
1329 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1330 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1331 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1332 case EC_OP_PARTFILE_PAUSE:
1333 case EC_OP_PARTFILE_RESUME:
1334 case EC_OP_PARTFILE_STOP:
1335 case EC_OP_PARTFILE_PRIO_SET:
1336 case EC_OP_PARTFILE_DELETE:
1337 case EC_OP_PARTFILE_SET_CAT:
1338 response = Get_EC_Response_PartFile_Cmd(request);
1339 break;
1340 case EC_OP_SHAREDFILES_RELOAD:
1341 theApp->sharedfiles->Reload();
1342 response = new CECPacket(EC_OP_NOOP);
1343 break;
1344 case EC_OP_SHARED_SET_PRIO:
1345 response = Get_EC_Response_Set_SharedFile_Prio(request);
1346 break;
1347 case EC_OP_RENAME_FILE: {
1348 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1349 CKnownFile* file = theApp->knownfiles->FindKnownFileByID(fileHash);
1350 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1351 if (!file) {
1352 file = theApp->downloadqueue->GetFileByID(fileHash);
1354 if (!file) {
1355 response = new CECPacket(EC_OP_FAILED);
1356 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1357 break;
1359 if (newName.IsEmpty()) {
1360 response = new CECPacket(EC_OP_FAILED);
1361 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1362 break;
1365 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1366 response = new CECPacket(EC_OP_NOOP);
1367 } else {
1368 response = new CECPacket(EC_OP_FAILED);
1369 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1372 break;
1377 // Server commands
1379 case EC_OP_SERVER_ADD:
1380 response = Get_EC_Response_Server_Add(request);
1381 break;
1382 case EC_OP_SERVER_DISCONNECT:
1383 case EC_OP_SERVER_CONNECT:
1384 case EC_OP_SERVER_REMOVE:
1385 response = Get_EC_Response_Server(request);
1386 break;
1387 case EC_OP_GET_SERVER_LIST: {
1388 response = new CECPacket(EC_OP_SERVER_LIST);
1389 if (!thePrefs::GetNetworkED2K()) {
1390 // Kad only: just send an empty list
1391 break;
1393 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1394 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1395 for (
1396 std::vector<const CServer*>::const_iterator it = servers.begin();
1397 it != servers.end();
1398 ++it
1400 response->AddTag(CEC_Server_Tag(*it, detail_level));
1403 break;
1404 case EC_OP_SERVER_UPDATE_FROM_URL: {
1405 wxString url = request->GetFirstTagSafe()->GetStringData();
1407 // Save the new url, and update the UI (if not amuled).
1408 Notify_ServersURLChanged(url);
1409 thePrefs::SetEd2kServersUrl(url);
1411 theApp->serverlist->UpdateServerMetFromURL(url);
1412 response = new CECPacket(EC_OP_NOOP);
1413 break;
1416 // IPFilter
1418 case EC_OP_IPFILTER_RELOAD:
1419 theApp->ipfilter->Reload();
1420 response = new CECPacket(EC_OP_NOOP);
1421 break;
1423 case EC_OP_IPFILTER_UPDATE: {
1424 wxString url = request->GetFirstTagSafe()->GetStringData();
1425 if (url == wxEmptyString) {
1426 url = thePrefs::IPFilterURL();
1428 theApp->ipfilter->Update(url);
1429 response = new CECPacket(EC_OP_NOOP);
1430 break;
1433 // Search
1435 case EC_OP_SEARCH_START:
1436 response = Get_EC_Response_Search(request);
1437 break;
1439 case EC_OP_SEARCH_STOP:
1440 response = Get_EC_Response_Search_Stop(request);
1441 break;
1443 case EC_OP_SEARCH_RESULTS:
1444 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1445 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1446 } else {
1447 response = Get_EC_Response_Search_Results(request);
1449 break;
1451 case EC_OP_SEARCH_PROGRESS:
1452 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1453 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1454 theApp->searchlist->GetSearchProgress()));
1455 break;
1457 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1458 response = Get_EC_Response_Search_Results_Download(request);
1459 break;
1461 // Preferences
1463 case EC_OP_GET_PREFERENCES:
1464 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1465 break;
1466 case EC_OP_SET_PREFERENCES:
1467 ((CEC_Prefs_Packet *)request)->Apply();
1468 theApp->glob_prefs->Save();
1469 if (thePrefs::IsFilteringClients()) {
1470 theApp->clientlist->FilterQueues();
1472 if (thePrefs::IsFilteringServers()) {
1473 theApp->serverlist->FilterServers();
1475 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1476 theApp->DisconnectED2K();
1478 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1479 theApp->StopKad();
1481 response = new CECPacket(EC_OP_NOOP);
1482 break;
1484 case EC_OP_CREATE_CATEGORY:
1485 if ( request->GetTagCount() == 1 ) {
1486 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1487 if (tag->Create()) {
1488 response = new CECPacket(EC_OP_NOOP);
1489 } else {
1490 response = new CECPacket(EC_OP_FAILED);
1491 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1492 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1494 Notify_CategoryAdded();
1495 } else {
1496 response = new CECPacket(EC_OP_NOOP);
1498 break;
1499 case EC_OP_UPDATE_CATEGORY:
1500 if ( request->GetTagCount() == 1 ) {
1501 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1502 if (tag->Apply()) {
1503 response = new CECPacket(EC_OP_NOOP);
1504 } else {
1505 response = new CECPacket(EC_OP_FAILED);
1506 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1507 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1509 Notify_CategoryUpdate(tag->GetInt());
1510 } else {
1511 response = new CECPacket(EC_OP_NOOP);
1513 break;
1514 case EC_OP_DELETE_CATEGORY:
1515 if ( request->GetTagCount() == 1 ) {
1516 uint32 cat = request->GetFirstTagSafe()->GetInt();
1517 // this noes not only update the gui, but actually deletes the cat
1518 Notify_CategoryDelete(cat);
1520 response = new CECPacket(EC_OP_NOOP);
1521 break;
1524 // Logging
1526 case EC_OP_ADDLOGLINE:
1527 AddLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1528 response = new CECPacket(EC_OP_NOOP);
1529 break;
1530 case EC_OP_ADDDEBUGLOGLINE:
1531 AddDebugLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1532 response = new CECPacket(EC_OP_NOOP);
1533 break;
1534 case EC_OP_GET_LOG:
1535 response = new CECPacket(EC_OP_LOG);
1536 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1537 break;
1538 case EC_OP_GET_DEBUGLOG:
1539 response = new CECPacket(EC_OP_DEBUGLOG);
1540 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1541 break;
1542 case EC_OP_RESET_LOG:
1543 theApp->GetLog(true);
1544 response = new CECPacket(EC_OP_NOOP);
1545 break;
1546 case EC_OP_RESET_DEBUGLOG:
1547 theApp->GetDebugLog(true);
1548 response = new CECPacket(EC_OP_NOOP);
1549 break;
1550 case EC_OP_GET_LAST_LOG_ENTRY:
1552 wxString tmp = theApp->GetLog(false);
1553 if (tmp.Last() == '\n') {
1554 tmp.RemoveLast();
1556 response = new CECPacket(EC_OP_LOG);
1557 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1559 break;
1560 case EC_OP_GET_SERVERINFO:
1561 response = new CECPacket(EC_OP_SERVERINFO);
1562 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1563 break;
1564 case EC_OP_CLEAR_SERVERINFO:
1565 theApp->GetServerLog(true);
1566 response = new CECPacket(EC_OP_NOOP);
1567 break;
1569 // Statistics
1571 case EC_OP_GET_STATSGRAPHS:
1572 response = GetStatsGraphs(request);
1573 break;
1574 case EC_OP_GET_STATSTREE: {
1575 theApp->m_statistics->UpdateStatsTree();
1576 response = new CECPacket(EC_OP_STATSTREE);
1577 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1578 if (tree) {
1579 response->AddTag(*tree);
1580 delete tree;
1582 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1583 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1584 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1586 break;
1590 // Kad
1592 case EC_OP_KAD_START:
1593 response = Get_EC_Response_Kad_Connect(request);
1594 break;
1595 case EC_OP_KAD_STOP:
1596 theApp->StopKad();
1597 response = new CECPacket(EC_OP_NOOP);
1598 break;
1599 case EC_OP_KAD_UPDATE_FROM_URL: {
1600 wxString url = request->GetFirstTagSafe()->GetStringData();
1602 // Save the new url, and update the UI (if not amuled).
1603 Notify_NodesURLChanged(url);
1604 thePrefs::SetKadNodesUrl(url);
1606 theApp->UpdateNotesDat(url);
1607 response = new CECPacket(EC_OP_NOOP);
1608 break;
1610 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1611 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1612 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1613 response = new CECPacket(EC_OP_NOOP);
1614 break;
1617 // Networks
1619 case EC_OP_CONNECT:
1620 if (thePrefs::GetNetworkED2K()) {
1621 response = new CECPacket(EC_OP_STRINGS);
1622 if (theApp->IsConnectedED2K()) {
1623 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1624 } else {
1625 theApp->serverconnect->ConnectToAnyServer();
1626 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1629 if (thePrefs::GetNetworkKademlia()) {
1630 if (!response) {
1631 response = new CECPacket(EC_OP_STRINGS);
1633 if (theApp->IsConnectedKad()) {
1634 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1635 } else {
1636 theApp->StartKad();
1637 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1640 if (!response) {
1641 response = new CECPacket(EC_OP_FAILED);
1642 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1644 break;
1645 case EC_OP_DISCONNECT:
1646 if (theApp->IsConnected()) {
1647 response = new CECPacket(EC_OP_STRINGS);
1648 if (theApp->IsConnectedED2K()) {
1649 theApp->serverconnect->Disconnect();
1650 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1652 if (theApp->IsConnectedKad()) {
1653 theApp->StopKad();
1654 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1656 } else {
1657 response = new CECPacket(EC_OP_NOOP);
1659 break;
1661 if (!response) {
1662 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1663 wxFAIL;
1664 response = new CECPacket(EC_OP_FAILED);
1665 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1667 return response;
1671 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1675 * Core general status
1677 ECStatusMsgSource::ECStatusMsgSource()
1679 m_last_ed2k_status_sent = 0xffffffff;
1680 m_last_kad_status_sent = 0xffffffff;
1681 m_server = (void *)0xffffffff;
1684 uint32 ECStatusMsgSource::GetEd2kStatus()
1686 if ( theApp->IsConnectedED2K() ) {
1687 return theApp->GetED2KID();
1688 } else if ( theApp->serverconnect->IsConnecting() ) {
1689 return 1;
1690 } else {
1691 return 0;
1695 uint32 ECStatusMsgSource::GetKadStatus()
1697 if ( theApp->IsConnectedKad() ) {
1698 return 1;
1699 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1700 return 2;
1701 } else if ( Kademlia::CKademlia::IsRunning() ) {
1702 return 3;
1704 return 0;
1707 CECPacket *ECStatusMsgSource::GetNextPacket()
1709 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1710 (m_last_kad_status_sent != GetKadStatus()) ||
1711 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1713 m_last_ed2k_status_sent = GetEd2kStatus();
1714 m_last_kad_status_sent = GetKadStatus();
1715 m_server = theApp->serverconnect->GetCurrentServer();
1717 CECPacket *response = new CECPacket(EC_OP_STATS);
1718 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1719 return response;
1721 return 0;
1725 * Downloading files
1727 ECPartFileMsgSource::ECPartFileMsgSource()
1729 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1730 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1731 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1732 m_dirty_status[cur_file->GetFileHash()] = status;
1736 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1738 CMD4Hash filehash = file->GetFileHash();
1739 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1740 m_dirty_status[filehash].m_dirty = true;;
1744 void ECPartFileMsgSource::SetNew(CPartFile *file)
1746 CMD4Hash filehash = file->GetFileHash();
1747 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1748 PARTFILE_STATUS status = { true, false, false, false, true, file };
1749 m_dirty_status[filehash] = status;
1752 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1754 CMD4Hash filehash = file->GetFileHash();
1755 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1757 m_dirty_status[filehash].m_finished = true;
1760 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1762 CMD4Hash filehash = file->GetFileHash();
1763 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1765 m_dirty_status[filehash].m_removed = true;
1768 CECPacket *ECPartFileMsgSource::GetNextPacket()
1770 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1771 it != m_dirty_status.end(); it++) {
1772 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1773 CMD4Hash filehash = it->first;
1775 CPartFile *partfile = it->second.m_file;
1777 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1778 if ( it->second.m_removed ) {
1779 CECTag tag(EC_TAG_PARTFILE, filehash);
1780 packet->AddTag(tag);
1781 m_dirty_status.erase(it);
1782 } else {
1783 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1784 packet->AddTag(tag);
1786 m_dirty_status[filehash].m_new = false;
1787 m_dirty_status[filehash].m_dirty = false;
1789 return packet;
1792 return 0;
1796 * Shared files - similar to downloading
1798 ECKnownFileMsgSource::ECKnownFileMsgSource()
1800 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1801 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1802 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1803 m_dirty_status[cur_file->GetFileHash()] = status;
1807 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1809 CMD4Hash filehash = file->GetFileHash();
1810 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1811 m_dirty_status[filehash].m_dirty = true;;
1815 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1817 CMD4Hash filehash = file->GetFileHash();
1818 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1819 KNOWNFILE_STATUS status = { true, false, false, true, file };
1820 m_dirty_status[filehash] = status;
1823 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1825 CMD4Hash filehash = file->GetFileHash();
1826 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1828 m_dirty_status[filehash].m_removed = true;
1831 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1833 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1834 it != m_dirty_status.end(); it++) {
1835 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1836 CMD4Hash filehash = it->first;
1838 CKnownFile *partfile = it->second.m_file;
1840 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1841 if ( it->second.m_removed ) {
1842 CECTag tag(EC_TAG_PARTFILE, filehash);
1843 packet->AddTag(tag);
1844 m_dirty_status.erase(it);
1845 } else {
1846 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1847 packet->AddTag(tag);
1849 m_dirty_status[filehash].m_new = false;
1850 m_dirty_status[filehash].m_dirty = false;
1852 return packet;
1855 return 0;
1859 * Notification about search status
1861 ECSearchMsgSource::ECSearchMsgSource()
1865 CECPacket *ECSearchMsgSource::GetNextPacket()
1867 if ( m_dirty_status.empty() ) {
1868 return 0;
1871 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1872 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1873 it != m_dirty_status.end(); it++) {
1875 if ( it->second.m_new ) {
1876 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1877 it->second.m_new = false;
1878 } else if ( it->second.m_dirty ) {
1879 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1884 return response;
1887 void ECSearchMsgSource::FlushStatus()
1889 m_dirty_status.clear();
1892 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1894 if ( m_dirty_status.count(file->GetFileHash()) ) {
1895 m_dirty_status[file->GetFileHash()].m_dirty = true;
1896 } else {
1897 m_dirty_status[file->GetFileHash()].m_new = true;
1898 m_dirty_status[file->GetFileHash()].m_dirty = true;
1899 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1900 m_dirty_status[file->GetFileHash()].m_file = file;
1904 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1906 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1910 * Notification about uploading clients
1912 CECPacket *ECClientMsgSource::GetNextPacket()
1914 return 0;
1918 // Notification iface per-client
1920 ECNotifier::ECNotifier()
1924 ECNotifier::~ECNotifier()
1926 while (m_msg_source.begin() != m_msg_source.end())
1927 Remove_EC_Client(m_msg_source.begin()->first);
1930 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1932 CECPacket *packet = 0;
1934 // priority 0 is highest
1936 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1937 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1938 break;
1941 return packet;
1944 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1947 // OnOutput is called for a first time before
1948 // socket is registered
1950 if ( m_msg_source.count(sock) ) {
1951 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1952 if ( !notifier_array ) {
1953 return 0;
1955 CECPacket *packet = GetNextPacket(notifier_array);
1956 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1957 return packet;
1958 } else {
1959 return 0;
1964 // Interface to notification macros
1966 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
1968 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1969 i != m_msg_source.end(); i++) {
1970 CECServerSocket *sock = i->first;
1971 if ( sock->HaveNotificationSupport() ) {
1972 ECUpdateMsgSource **notifier_array = i->second;
1973 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
1976 NextPacketToSocket();
1979 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
1981 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1982 i != m_msg_source.end(); i++) {
1983 ECUpdateMsgSource **notifier_array = i->second;
1984 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
1986 NextPacketToSocket();
1989 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
1991 // per-partfile source list is not supported (yet), and IMHO quite useless
1994 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
1996 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1997 i != m_msg_source.end(); i++) {
1998 ECUpdateMsgSource **notifier_array = i->second;
1999 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
2001 NextPacketToSocket();
2004 void ECNotifier::DownloadFile_AddSource(CPartFile *)
2006 // per-partfile source list is not supported (yet), and IMHO quite useless
2009 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
2011 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2012 i != m_msg_source.end(); i++) {
2013 ECUpdateMsgSource **notifier_array = i->second;
2014 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
2016 NextPacketToSocket();
2019 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
2021 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2022 i != m_msg_source.end(); i++) {
2023 ECUpdateMsgSource **notifier_array = i->second;
2024 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
2026 NextPacketToSocket();
2029 void ECNotifier::SharedFile_RemoveAllFiles()
2031 // need to figure out what to do here
2034 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2036 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2037 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2038 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2039 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2040 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2041 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2043 m_msg_source[sock] = notifier_array;
2046 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2048 if (m_msg_source.count(sock)) {
2049 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2051 m_msg_source.erase(sock);
2053 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2054 delete notifier_array[i];
2056 delete [] notifier_array;
2060 void ECNotifier::NextPacketToSocket()
2062 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2063 i != m_msg_source.end(); i++) {
2064 CECServerSocket *sock = i->first;
2065 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2066 ECUpdateMsgSource **notifier_array = i->second;
2067 CECPacket *packet = GetNextPacket(notifier_array);
2068 if ( packet ) {
2069 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2070 sock->SendPacket(packet);
2076 // File_checked_for_headers