Upstream tarball 10142
[amule.git] / src / ExternalConn.cpp
blobb0f3852488e9383dd2fc38b32d3ded079e7b64b2
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 AddLogLineM(false, _("Unauthorized access attempt. Connection closed."));
517 m_conn_state = CONN_FAILED;
520 return response;
523 // Make a Logger tag (if there are any logging messages) and add it to the response
524 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
526 if (LoggerAccess.HasString()) {
527 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
528 // Tag structure is fix: tag carries nothing, inside are the strings
529 // maximum of 200 log lines per message
530 int entries = 0;
531 wxString line;
532 while (entries < 200 && LoggerAccess.GetString(line)) {
533 tag.AddTag(CECTag(EC_TAG_STRING, line));
534 entries++;
536 response->AddTag(tag);
537 //printf("send Log tag %d %d\n", FirstEntry, entries);
541 static CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
543 CECPacket *response = new CECPacket(EC_OP_STATS);
545 switch (request->GetDetailLevel()) {
546 case EC_DETAIL_FULL:
547 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
548 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
549 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
550 AddLoggerTag(response, LoggerAccess);
551 case EC_DETAIL_WEB:
552 case EC_DETAIL_CMD:
553 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
554 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
555 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
556 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
557 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
558 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
559 // User/Filecounts
561 uint32 totaluser = 0, totalfile = 0;
562 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
563 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
564 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
565 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
566 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
568 // Kad stats
569 if (Kademlia::CKademlia::IsConnected()) {
570 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
571 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
572 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
573 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
574 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
575 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
576 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
577 uint32 BuddyIP = 0;
578 uint16 BuddyPort = 0;
579 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
580 if (Buddy) {
581 BuddyIP = Buddy->GetIP();
582 BuddyPort = Buddy->GetUDPPort();
584 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
585 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
587 case EC_DETAIL_UPDATE:
588 case EC_DETAIL_INC_UPDATE:
589 break;
592 return response;
595 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CFileEncoderMap &encoders)
597 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
599 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
601 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
603 // request can contain list of queried items
604 CTagSet<uint32, EC_TAG_KNOWNFILE> queryitems(request);
606 encoders.UpdateEncoders();
608 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
609 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
611 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->ECID())) ) {
612 continue;
615 CEC_SharedFile_Tag filetag(cur_file, detail_level);
616 CKnownFile_Encoder *enc = encoders[cur_file->ECID()];
617 if ( detail_level != EC_DETAIL_UPDATE ) {
618 enc->ResetEncoder();
620 enc->Encode(&filetag);
621 response->AddTag(filetag);
623 return response;
626 static CECPacket *Get_EC_Response_GetUpdate(CFileEncoderMap &encoders, CObjTagMap &tagmap)
628 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
630 encoders.UpdateEncoders();
631 for (CFileEncoderMap::iterator it = encoders.begin(); it != encoders.end(); ++it) {
632 const CKnownFile *cur_file = it->second->GetFile();
633 CValueMap &valuemap = tagmap.GetValueMap(cur_file->ECID());
634 if (cur_file->IsCPartFile()) {
635 CEC_PartFile_Tag filetag((const CPartFile*) cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
636 // Add information if partfile is shared
637 filetag.AddTag(EC_TAG_PARTFILE_SHARED, it->second->IsShared(), &valuemap);
639 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
640 enc->Encode(&filetag);
641 response->AddTag(filetag);
642 } else {
643 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
644 CKnownFile_Encoder * enc = encoders[cur_file->ECID()];
645 enc->Encode(&filetag);
646 response->AddTag(filetag);
649 return response;
652 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
654 CECPacket *response = new CECPacket(op);
656 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
659 // request can contain list of queried items
660 // (not for incremental update of course)
661 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
663 const CClientPtrList& clients = (op == EC_OP_WAIT_QUEUE) ? theApp->uploadqueue->GetWaitingList()
664 : theApp->uploadqueue->GetUploadingList();
665 CClientPtrList::const_iterator it = clients.begin();
666 for (; it != clients.end(); ++it) {
667 CUpDownClient* cur_client = *it;
669 if (!cur_client) { // shouldn't happen
670 continue;
672 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
673 continue;
675 CValueMap *valuemap = NULL;
676 if (detail_level == EC_DETAIL_INC_UPDATE) {
677 valuemap = &tagmap.GetValueMap(cur_client->ECID());
679 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
681 response->AddTag(cli_tag);
684 return response;
688 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
690 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
692 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
694 // request can contain list of queried items
695 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
697 encoders.UpdateEncoders();
699 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
700 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
702 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
703 continue;
706 CEC_PartFile_Tag filetag(cur_file, detail_level);
708 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
709 if ( detail_level != EC_DETAIL_UPDATE ) {
710 enc->ResetEncoder();
712 enc->Encode(&filetag);
714 response->AddTag(filetag);
716 return response;
720 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
722 CECPacket *response = NULL;
724 // request can contain multiple files.
725 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); it1++) {
726 const CECTag &hashtag = *it1;
728 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
730 CMD4Hash hash = hashtag.GetMD4Data();
731 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
733 if ( !pfile ) {
734 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
735 response = new CECPacket(EC_OP_FAILED);
736 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
737 //return response;
738 break;
740 switch (request->GetOpCode()) {
741 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
742 if ((pfile->GetStatus(false) == PS_READY) ||
743 (pfile->GetStatus(false) == PS_EMPTY)) {
744 CKnownFile::SourceSet::const_iterator it = pfile->GetA4AFList().begin();
745 while ( it != pfile->GetA4AFList().end() ) {
746 CUpDownClient *cur_source = *it++;
748 cur_source->SwapToAnotherFile(true, false, false, pfile);
751 break;
752 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
753 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
754 break;
755 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
756 if ((pfile->GetStatus(false) == PS_READY) ||
757 (pfile->GetStatus(false) == PS_EMPTY)) {
758 CKnownFile::SourceSet::const_iterator it = pfile->GetSourceList().begin();
759 while ( it != pfile->GetSourceList().end() ) {
760 CUpDownClient* cur_source = *it++;
762 cur_source->SwapToAnotherFile(false, false, false, NULL);
765 break;
766 case EC_OP_PARTFILE_PAUSE:
767 pfile->PauseFile();
768 break;
769 case EC_OP_PARTFILE_RESUME:
770 pfile->ResumeFile();
771 pfile->SavePartFile();
772 break;
773 case EC_OP_PARTFILE_STOP:
774 pfile->StopFile();
775 break;
776 case EC_OP_PARTFILE_PRIO_SET: {
777 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
778 if ( prio == PR_AUTO ) {
779 pfile->SetAutoDownPriority(1);
780 } else {
781 pfile->SetAutoDownPriority(0);
782 pfile->SetDownPriority(prio);
785 break;
786 case EC_OP_PARTFILE_DELETE:
787 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
788 theApp->downloadqueue->StartNextFile(pfile);
790 pfile->Delete();
791 break;
793 case EC_OP_PARTFILE_SET_CAT:
794 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
795 break;
797 default:
798 response = new CECPacket(EC_OP_FAILED);
799 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
800 break;
803 if (!response) {
804 response = new CECPacket(EC_OP_NOOP);
806 return response;
809 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
811 CECPacket *response = NULL;
813 const CECTag *srv_tag = request->GetFirstTagSafe();
815 wxString full_addr = srv_tag->GetTagByName(EC_TAG_SERVER_ADDRESS)->GetStringData();
816 wxString name = srv_tag->GetTagByName(EC_TAG_SERVER_NAME)->GetStringData();
818 wxString s_ip = full_addr.Left(full_addr.Find(':'));
819 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
821 long port = StrToULong(s_port);
822 CServer* toadd = new CServer(port, s_ip);
823 toadd->SetListName(name.IsEmpty() ? full_addr : name);
825 if ( theApp->AddServer(toadd, true) ) {
826 response = new CECPacket(EC_OP_NOOP);
827 } else {
828 response = new CECPacket(EC_OP_FAILED);
829 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
830 delete toadd;
833 return response;
836 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
838 CECPacket *response = NULL;
839 const CECTag *srv_tag = request->GetFirstTagSafe();
840 CServer *srv = 0;
841 if ( srv_tag ) {
842 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
843 // server tag passed, but server not found
844 if ( !srv ) {
845 response = new CECPacket(EC_OP_FAILED);
846 response->AddTag(CECTag(EC_TAG_STRING,
847 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
848 return response;
851 switch (request->GetOpCode()) {
852 case EC_OP_SERVER_DISCONNECT:
853 theApp->serverconnect->Disconnect();
854 response = new CECPacket(EC_OP_NOOP);
855 break;
856 case EC_OP_SERVER_REMOVE:
857 if ( srv ) {
858 theApp->serverlist->RemoveServer(srv);
859 response = new CECPacket(EC_OP_NOOP);
860 } else {
861 response = new CECPacket(EC_OP_FAILED);
862 response->AddTag(CECTag(EC_TAG_STRING,
863 wxTRANSLATE("need to define server to be removed")));
865 break;
866 case EC_OP_SERVER_CONNECT:
867 if (thePrefs::GetNetworkED2K()) {
868 if ( srv ) {
869 theApp->serverconnect->ConnectToServer(srv);
870 response = new CECPacket(EC_OP_NOOP);
871 } else {
872 theApp->serverconnect->ConnectToAnyServer();
873 response = new CECPacket(EC_OP_NOOP);
875 } else {
876 response = new CECPacket(EC_OP_FAILED);
877 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
879 break;
881 if (!response) {
882 response = new CECPacket(EC_OP_FAILED);
883 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
885 return response;
888 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
890 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
892 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
894 // request can contain list of queried items
895 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
897 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
898 CSearchResultList::const_iterator it = list.begin();
899 while (it != list.end()) {
900 CSearchFile* sf = *it++;
901 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
902 continue;
904 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
906 return response;
909 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
911 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
913 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
914 CSearchResultList::const_iterator it = list.begin();
915 while (it != list.end()) {
916 CSearchFile* sf = *it++;
917 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
918 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
919 /* Here we could add the children, if amulegui were able to merge them.
920 if (sf->HasChildren()) {
921 const CSearchResultList& children = sf->GetChildren();
922 for (size_t i = 0; i < children.size(); ++i) {
923 CSearchFile* sfc = children.at(i);
924 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
925 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
930 return response;
933 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
935 CECPacket *response = new CECPacket(EC_OP_STRINGS);
936 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
937 const CECTag &tag = *it;
938 CMD4Hash hash = tag.GetMD4Data();
939 uint8 category = tag.GetFirstTagSafe()->GetInt();
940 theApp->searchlist->AddFileToDownloadByHash(hash, category);
942 return response;
945 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
947 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
948 theApp->searchlist->StopGlobalSearch();
949 return reply;
952 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
954 wxString response;
956 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetFirstTagSafe();
957 theApp->searchlist->RemoveResults(0xffffffff);
959 CSearchList::CSearchParams params;
960 params.searchString = search_request->SearchText();
961 params.typeText = search_request->SearchFileType();
962 params.extension = search_request->SearchExt();
963 params.minSize = search_request->MinSize();
964 params.maxSize = search_request->MaxSize();
965 params.availability = search_request->Avail();
968 EC_SEARCH_TYPE search_type = search_request->SearchType();
969 SearchType core_search_type = LocalSearch;
970 switch (search_type) {
971 case EC_SEARCH_GLOBAL:
972 core_search_type = GlobalSearch;
973 case EC_SEARCH_KAD:
974 if (core_search_type != GlobalSearch) { // Not a global search obviously
975 core_search_type = KadSearch;
977 case EC_SEARCH_LOCAL: {
978 uint32 search_id = 0xffffffff;
979 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
980 if (!error.IsEmpty()) {
981 response = error;
982 } else {
983 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
985 break;
987 case EC_SEARCH_WEB:
988 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
989 break;
992 CECPacket *reply = new CECPacket(EC_OP_FAILED);
993 // error or search in progress
994 reply->AddTag(CECTag(EC_TAG_STRING, response));
996 return reply;
999 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1001 CECPacket *response = new CECPacket(EC_OP_NOOP);
1002 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1003 const CECTag &tag = *it;
1004 CMD4Hash hash = tag.GetMD4Data();
1005 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1006 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1007 if ( !cur_file ) {
1008 continue;
1010 if (prio == PR_AUTO) {
1011 cur_file->SetAutoUpPriority(1);
1012 cur_file->UpdateAutoUpPriority();
1013 } else {
1014 cur_file->SetAutoUpPriority(0);
1015 cur_file->SetUpPriority(prio);
1017 Notify_SharedFilesUpdateItem(cur_file);
1020 return response;
1023 static CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
1025 CECPacket *response;
1026 if (thePrefs::GetNetworkKademlia()) {
1027 response = new CECPacket(EC_OP_NOOP);
1028 if ( !Kademlia::CKademlia::IsRunning() ) {
1029 Kademlia::CKademlia::Start();
1030 theApp->ShowConnectionState();
1032 const CECTag *addrtag = request->GetFirstTagSafe();
1033 if ( addrtag ) {
1034 uint32 ip = addrtag->GetIPv4Data().IP();
1035 uint16 port = addrtag->GetIPv4Data().m_port;
1036 Kademlia::CKademlia::Bootstrap(ip, port, true);
1038 } else {
1039 response = new CECPacket(EC_OP_FAILED);
1040 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1043 return response;
1046 void CPartFile_Encoder::Encode(CECTag *parent)
1049 // Source part frequencies
1051 CKnownFile_Encoder::Encode(parent);
1054 // Gaps
1056 const CGapList& gaplist = m_PartFile()->GetNewGapList();
1057 const size_t gap_list_size = gaplist.size();
1058 ArrayOfUInts64 gaps;
1059 gaps.reserve(gap_list_size * 2);
1061 for (CGapList::const_iterator curr_pos = gaplist.begin();
1062 curr_pos != gaplist.end(); ++curr_pos) {
1063 gaps.push_back(curr_pos.start());
1064 gaps.push_back(curr_pos.end());
1067 int gap_enc_size = 0;
1068 bool changed;
1069 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1070 if (changed) {
1071 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1073 delete[] gap_enc_data;
1076 // Requested blocks
1078 ArrayOfUInts64 req_buffer;
1079 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1080 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1082 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1083 Requested_Block_Struct* block = *curr_pos2;
1084 req_buffer.push_back(block->StartOffset);
1085 req_buffer.push_back(block->EndOffset);
1087 int req_enc_size = 0;
1088 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1089 if (changed) {
1090 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1092 delete[] req_enc_data;
1095 // Source names
1097 // First count occurrence of all source names
1099 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1100 typedef std::map<wxString, int> strIntMap;
1101 strIntMap nameMap;
1102 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1103 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1104 CUpDownClient *cur_src = *it;
1105 if (cur_src->GetRequestFile() != m_file || cur_src->GetClientFilename().Length() == 0) {
1106 continue;
1108 const wxString &name = cur_src->GetClientFilename();
1109 strIntMap::iterator itm = nameMap.find(name);
1110 if (itm == nameMap.end()) {
1111 nameMap[name] = 1;
1112 } else {
1113 itm->second++;
1117 // Go through our last list
1119 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1120 SourcenameItemMap::iterator it2 = it1++;
1121 strIntMap::iterator itm = nameMap.find(it2->second.name);
1122 if (itm == nameMap.end()) {
1123 // name doesn't exist anymore, tell client to forget it
1124 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1125 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1126 sourceNames.AddTag(tag);
1127 // and forget it
1128 m_sourcenameItemMap.erase(it2);
1129 } else {
1130 // update count if it changed
1131 if (it2->second.count != itm->second) {
1132 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1133 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1134 sourceNames.AddTag(tag);
1135 it2->second.count = itm->second;
1137 // remove it from nameMap so that only new names are left there
1138 nameMap.erase(itm);
1142 // Add new names
1144 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1145 int id = ++m_sourcenameID;
1146 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1147 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1148 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1149 sourceNames.AddTag(tag);
1150 // remember it
1151 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1153 if (sourceNames.HasChildTags()) {
1154 parent->AddTag(sourceNames);
1159 void CPartFile_Encoder::ResetEncoder()
1161 CKnownFile_Encoder::ResetEncoder();
1162 m_gap_status.ResetEncoder();
1163 m_req_status.ResetEncoder();
1166 void CKnownFile_Encoder::Encode(CECTag *parent)
1169 // Source part frequencies
1171 // Reference to the availability list
1172 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1173 ((CPartFile*)m_file)->m_SrcpartFrequency :
1174 m_file->m_AvailPartFrequency;
1175 // Don't add tag if available parts aren't populated yet.
1176 if (!list.empty()) {
1177 int part_enc_size;
1178 bool changed;
1179 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1180 if (changed) {
1181 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1183 delete[] part_enc_data;
1187 static CECPacket *GetStatsGraphs(const CECPacket *request)
1189 CECPacket *response = NULL;
1191 switch (request->GetDetailLevel()) {
1192 case EC_DETAIL_WEB:
1193 case EC_DETAIL_FULL: {
1194 double dTimestamp = 0.0;
1195 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1196 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1198 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1199 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1200 uint32 *graphData;
1201 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1202 if (numPoints) {
1203 response = new CECPacket(EC_OP_STATSGRAPHS);
1204 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1205 delete [] graphData;
1206 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1207 } else {
1208 response = new CECPacket(EC_OP_FAILED);
1209 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1211 break;
1213 case EC_DETAIL_INC_UPDATE:
1214 case EC_DETAIL_UPDATE:
1215 case EC_DETAIL_CMD:
1216 // No graphs
1217 response = new CECPacket(EC_OP_FAILED);
1218 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1219 break;
1221 if (!response) {
1222 response = new CECPacket(EC_OP_FAILED);
1223 // Unknown reason
1226 return response;
1229 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1232 if ( !request ) {
1233 return 0;
1236 CECPacket *response = NULL;
1238 switch (request->GetOpCode()) {
1240 // Misc commands
1242 case EC_OP_SHUTDOWN:
1243 if (!theApp->IsOnShutDown()) {
1244 response = new CECPacket(EC_OP_NOOP);
1245 AddLogLineM(true, _("External Connection: shutdown requested"));
1246 #ifndef AMULE_DAEMON
1248 wxCloseEvent evt;
1249 evt.SetCanVeto(false);
1250 theApp->ShutDown(evt);
1252 #else
1253 theApp->ExitMainLoop();
1254 #endif
1255 } else {
1256 response = new CECPacket(EC_OP_FAILED);
1257 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1259 break;
1260 case EC_OP_ADD_LINK:
1261 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1262 const CECTag &tag = *it;
1263 wxString link = tag.GetStringData();
1264 int category = 0;
1265 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1266 if (cattag) {
1267 category = cattag->GetInt();
1269 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link);
1270 if ( theApp->downloadqueue->AddLink(link, category) ) {
1271 response = new CECPacket(EC_OP_NOOP);
1272 } else {
1273 // Error messages are printed by the add function.
1274 response = new CECPacket(EC_OP_FAILED);
1275 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1278 break;
1280 // Status requests
1282 case EC_OP_STAT_REQ:
1283 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1284 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1285 break;
1286 case EC_OP_GET_CONNSTATE:
1287 response = new CECPacket(EC_OP_MISC_DATA);
1288 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1289 break;
1293 case EC_OP_GET_SHARED_FILES:
1294 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1295 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1297 break;
1298 case EC_OP_GET_DLOAD_QUEUE:
1299 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1300 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1302 break;
1304 // This will evolve into an update-all for inc tags
1306 case EC_OP_GET_UPDATE:
1307 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1308 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1310 break;
1311 case EC_OP_GET_ULOAD_QUEUE:
1312 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1313 break;
1314 case EC_OP_GET_WAIT_QUEUE:
1315 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_WAIT_QUEUE);
1316 break;
1317 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1318 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1319 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1320 case EC_OP_PARTFILE_CLEANUP_SOURCES:
1321 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1322 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1323 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1324 case EC_OP_PARTFILE_PAUSE:
1325 case EC_OP_PARTFILE_RESUME:
1326 case EC_OP_PARTFILE_STOP:
1327 case EC_OP_PARTFILE_PRIO_SET:
1328 case EC_OP_PARTFILE_DELETE:
1329 case EC_OP_PARTFILE_SET_CAT:
1330 response = Get_EC_Response_PartFile_Cmd(request);
1331 break;
1332 case EC_OP_SHAREDFILES_RELOAD:
1333 theApp->sharedfiles->Reload();
1334 response = new CECPacket(EC_OP_NOOP);
1335 break;
1336 case EC_OP_SHARED_SET_PRIO:
1337 response = Get_EC_Response_Set_SharedFile_Prio(request);
1338 break;
1339 case EC_OP_RENAME_FILE: {
1340 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1341 CKnownFile* file = theApp->knownfiles->FindKnownFileByID(fileHash);
1342 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1343 if (!file) {
1344 file = theApp->downloadqueue->GetFileByID(fileHash);
1346 if (!file) {
1347 response = new CECPacket(EC_OP_FAILED);
1348 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1349 break;
1351 if (newName.IsEmpty()) {
1352 response = new CECPacket(EC_OP_FAILED);
1353 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1354 break;
1357 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1358 response = new CECPacket(EC_OP_NOOP);
1359 } else {
1360 response = new CECPacket(EC_OP_FAILED);
1361 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1364 break;
1369 // Server commands
1371 case EC_OP_SERVER_ADD:
1372 response = Get_EC_Response_Server_Add(request);
1373 break;
1374 case EC_OP_SERVER_DISCONNECT:
1375 case EC_OP_SERVER_CONNECT:
1376 case EC_OP_SERVER_REMOVE:
1377 response = Get_EC_Response_Server(request);
1378 break;
1379 case EC_OP_GET_SERVER_LIST: {
1380 response = new CECPacket(EC_OP_SERVER_LIST);
1381 if (!thePrefs::GetNetworkED2K()) {
1382 // Kad only: just send an empty list
1383 break;
1385 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1386 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1387 for (
1388 std::vector<const CServer*>::const_iterator it = servers.begin();
1389 it != servers.end();
1390 ++it
1392 response->AddTag(CEC_Server_Tag(*it, detail_level));
1395 break;
1396 case EC_OP_SERVER_UPDATE_FROM_URL: {
1397 wxString url = request->GetFirstTagSafe()->GetStringData();
1399 // Save the new url, and update the UI (if not amuled).
1400 Notify_ServersURLChanged(url);
1401 thePrefs::SetEd2kServersUrl(url);
1403 theApp->serverlist->UpdateServerMetFromURL(url);
1404 response = new CECPacket(EC_OP_NOOP);
1405 break;
1408 // IPFilter
1410 case EC_OP_IPFILTER_RELOAD:
1411 theApp->ipfilter->Reload();
1412 response = new CECPacket(EC_OP_NOOP);
1413 break;
1415 case EC_OP_IPFILTER_UPDATE: {
1416 wxString url = request->GetFirstTagSafe()->GetStringData();
1417 if (url == wxEmptyString) {
1418 url = thePrefs::IPFilterURL();
1420 theApp->ipfilter->Update(url);
1421 response = new CECPacket(EC_OP_NOOP);
1422 break;
1425 // Search
1427 case EC_OP_SEARCH_START:
1428 response = Get_EC_Response_Search(request);
1429 break;
1431 case EC_OP_SEARCH_STOP:
1432 response = Get_EC_Response_Search_Stop(request);
1433 break;
1435 case EC_OP_SEARCH_RESULTS:
1436 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1437 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1438 } else {
1439 response = Get_EC_Response_Search_Results(request);
1441 break;
1443 case EC_OP_SEARCH_PROGRESS:
1444 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1445 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1446 theApp->searchlist->GetSearchProgress()));
1447 break;
1449 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1450 response = Get_EC_Response_Search_Results_Download(request);
1451 break;
1453 // Preferences
1455 case EC_OP_GET_PREFERENCES:
1456 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1457 break;
1458 case EC_OP_SET_PREFERENCES:
1459 ((CEC_Prefs_Packet *)request)->Apply();
1460 theApp->glob_prefs->Save();
1461 if (thePrefs::IsFilteringClients()) {
1462 theApp->clientlist->FilterQueues();
1464 if (thePrefs::IsFilteringServers()) {
1465 theApp->serverlist->FilterServers();
1467 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1468 theApp->DisconnectED2K();
1470 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1471 theApp->StopKad();
1473 response = new CECPacket(EC_OP_NOOP);
1474 break;
1476 case EC_OP_CREATE_CATEGORY:
1477 if ( request->GetTagCount() == 1 ) {
1478 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1479 if (tag->Create()) {
1480 response = new CECPacket(EC_OP_NOOP);
1481 } else {
1482 response = new CECPacket(EC_OP_FAILED);
1483 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1484 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1486 Notify_CategoryAdded();
1487 } else {
1488 response = new CECPacket(EC_OP_NOOP);
1490 break;
1491 case EC_OP_UPDATE_CATEGORY:
1492 if ( request->GetTagCount() == 1 ) {
1493 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1494 if (tag->Apply()) {
1495 response = new CECPacket(EC_OP_NOOP);
1496 } else {
1497 response = new CECPacket(EC_OP_FAILED);
1498 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1499 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1501 Notify_CategoryUpdate(tag->GetInt());
1502 } else {
1503 response = new CECPacket(EC_OP_NOOP);
1505 break;
1506 case EC_OP_DELETE_CATEGORY:
1507 if ( request->GetTagCount() == 1 ) {
1508 uint32 cat = request->GetFirstTagSafe()->GetInt();
1509 // this noes not only update the gui, but actually deletes the cat
1510 Notify_CategoryDelete(cat);
1512 response = new CECPacket(EC_OP_NOOP);
1513 break;
1516 // Logging
1518 case EC_OP_ADDLOGLINE:
1519 AddLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1520 response = new CECPacket(EC_OP_NOOP);
1521 break;
1522 case EC_OP_ADDDEBUGLOGLINE:
1523 AddDebugLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1524 response = new CECPacket(EC_OP_NOOP);
1525 break;
1526 case EC_OP_GET_LOG:
1527 response = new CECPacket(EC_OP_LOG);
1528 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1529 break;
1530 case EC_OP_GET_DEBUGLOG:
1531 response = new CECPacket(EC_OP_DEBUGLOG);
1532 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1533 break;
1534 case EC_OP_RESET_LOG:
1535 theApp->GetLog(true);
1536 response = new CECPacket(EC_OP_NOOP);
1537 break;
1538 case EC_OP_RESET_DEBUGLOG:
1539 theApp->GetDebugLog(true);
1540 response = new CECPacket(EC_OP_NOOP);
1541 break;
1542 case EC_OP_GET_LAST_LOG_ENTRY:
1544 wxString tmp = theApp->GetLog(false);
1545 if (tmp.Last() == '\n') {
1546 tmp.RemoveLast();
1548 response = new CECPacket(EC_OP_LOG);
1549 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1551 break;
1552 case EC_OP_GET_SERVERINFO:
1553 response = new CECPacket(EC_OP_SERVERINFO);
1554 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1555 break;
1556 case EC_OP_CLEAR_SERVERINFO:
1557 theApp->GetServerLog(true);
1558 response = new CECPacket(EC_OP_NOOP);
1559 break;
1561 // Statistics
1563 case EC_OP_GET_STATSGRAPHS:
1564 response = GetStatsGraphs(request);
1565 break;
1566 case EC_OP_GET_STATSTREE: {
1567 theApp->m_statistics->UpdateStatsTree();
1568 response = new CECPacket(EC_OP_STATSTREE);
1569 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1570 if (tree) {
1571 response->AddTag(*tree);
1572 delete tree;
1574 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1575 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1576 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1578 break;
1582 // Kad
1584 case EC_OP_KAD_START:
1585 response = Get_EC_Response_Kad_Connect(request);
1586 break;
1587 case EC_OP_KAD_STOP:
1588 theApp->StopKad();
1589 response = new CECPacket(EC_OP_NOOP);
1590 break;
1591 case EC_OP_KAD_UPDATE_FROM_URL: {
1592 wxString url = request->GetFirstTagSafe()->GetStringData();
1594 // Save the new url, and update the UI (if not amuled).
1595 Notify_NodesURLChanged(url);
1596 thePrefs::SetKadNodesUrl(url);
1598 theApp->UpdateNotesDat(url);
1599 response = new CECPacket(EC_OP_NOOP);
1600 break;
1602 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1603 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1604 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1605 response = new CECPacket(EC_OP_NOOP);
1606 break;
1609 // Networks
1611 case EC_OP_CONNECT:
1612 if (thePrefs::GetNetworkED2K()) {
1613 response = new CECPacket(EC_OP_STRINGS);
1614 if (theApp->IsConnectedED2K()) {
1615 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1616 } else {
1617 theApp->serverconnect->ConnectToAnyServer();
1618 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1621 if (thePrefs::GetNetworkKademlia()) {
1622 if (!response) {
1623 response = new CECPacket(EC_OP_STRINGS);
1625 if (theApp->IsConnectedKad()) {
1626 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1627 } else {
1628 theApp->StartKad();
1629 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1632 if (!response) {
1633 response = new CECPacket(EC_OP_FAILED);
1634 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1636 break;
1637 case EC_OP_DISCONNECT:
1638 if (theApp->IsConnected()) {
1639 response = new CECPacket(EC_OP_STRINGS);
1640 if (theApp->IsConnectedED2K()) {
1641 theApp->serverconnect->Disconnect();
1642 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1644 if (theApp->IsConnectedKad()) {
1645 theApp->StopKad();
1646 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1648 } else {
1649 response = new CECPacket(EC_OP_NOOP);
1651 break;
1653 if (!response) {
1654 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1655 wxFAIL;
1656 response = new CECPacket(EC_OP_FAILED);
1657 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1659 return response;
1663 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1667 * Core general status
1669 ECStatusMsgSource::ECStatusMsgSource()
1671 m_last_ed2k_status_sent = 0xffffffff;
1672 m_last_kad_status_sent = 0xffffffff;
1673 m_server = (void *)0xffffffff;
1676 uint32 ECStatusMsgSource::GetEd2kStatus()
1678 if ( theApp->IsConnectedED2K() ) {
1679 return theApp->GetED2KID();
1680 } else if ( theApp->serverconnect->IsConnecting() ) {
1681 return 1;
1682 } else {
1683 return 0;
1687 uint32 ECStatusMsgSource::GetKadStatus()
1689 if ( theApp->IsConnectedKad() ) {
1690 return 1;
1691 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1692 return 2;
1693 } else if ( Kademlia::CKademlia::IsRunning() ) {
1694 return 3;
1696 return 0;
1699 CECPacket *ECStatusMsgSource::GetNextPacket()
1701 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1702 (m_last_kad_status_sent != GetKadStatus()) ||
1703 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1705 m_last_ed2k_status_sent = GetEd2kStatus();
1706 m_last_kad_status_sent = GetKadStatus();
1707 m_server = theApp->serverconnect->GetCurrentServer();
1709 CECPacket *response = new CECPacket(EC_OP_STATS);
1710 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1711 return response;
1713 return 0;
1717 * Downloading files
1719 ECPartFileMsgSource::ECPartFileMsgSource()
1721 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1722 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1723 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1724 m_dirty_status[cur_file->GetFileHash()] = status;
1728 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1730 CMD4Hash filehash = file->GetFileHash();
1731 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1732 m_dirty_status[filehash].m_dirty = true;;
1736 void ECPartFileMsgSource::SetNew(CPartFile *file)
1738 CMD4Hash filehash = file->GetFileHash();
1739 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1740 PARTFILE_STATUS status = { true, false, false, false, true, file };
1741 m_dirty_status[filehash] = status;
1744 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1746 CMD4Hash filehash = file->GetFileHash();
1747 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1749 m_dirty_status[filehash].m_finished = true;
1752 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1754 CMD4Hash filehash = file->GetFileHash();
1755 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1757 m_dirty_status[filehash].m_removed = true;
1760 CECPacket *ECPartFileMsgSource::GetNextPacket()
1762 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1763 it != m_dirty_status.end(); it++) {
1764 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1765 CMD4Hash filehash = it->first;
1767 CPartFile *partfile = it->second.m_file;
1769 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1770 if ( it->second.m_removed ) {
1771 CECTag tag(EC_TAG_PARTFILE, filehash);
1772 packet->AddTag(tag);
1773 m_dirty_status.erase(it);
1774 } else {
1775 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1776 packet->AddTag(tag);
1778 m_dirty_status[filehash].m_new = false;
1779 m_dirty_status[filehash].m_dirty = false;
1781 return packet;
1784 return 0;
1788 * Shared files - similar to downloading
1790 ECKnownFileMsgSource::ECKnownFileMsgSource()
1792 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1793 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1794 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1795 m_dirty_status[cur_file->GetFileHash()] = status;
1799 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1801 CMD4Hash filehash = file->GetFileHash();
1802 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1803 m_dirty_status[filehash].m_dirty = true;;
1807 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1809 CMD4Hash filehash = file->GetFileHash();
1810 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1811 KNOWNFILE_STATUS status = { true, false, false, true, file };
1812 m_dirty_status[filehash] = status;
1815 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1817 CMD4Hash filehash = file->GetFileHash();
1818 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1820 m_dirty_status[filehash].m_removed = true;
1823 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1825 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1826 it != m_dirty_status.end(); it++) {
1827 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1828 CMD4Hash filehash = it->first;
1830 CKnownFile *partfile = it->second.m_file;
1832 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1833 if ( it->second.m_removed ) {
1834 CECTag tag(EC_TAG_PARTFILE, filehash);
1835 packet->AddTag(tag);
1836 m_dirty_status.erase(it);
1837 } else {
1838 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1839 packet->AddTag(tag);
1841 m_dirty_status[filehash].m_new = false;
1842 m_dirty_status[filehash].m_dirty = false;
1844 return packet;
1847 return 0;
1851 * Notification about search status
1853 ECSearchMsgSource::ECSearchMsgSource()
1857 CECPacket *ECSearchMsgSource::GetNextPacket()
1859 if ( m_dirty_status.empty() ) {
1860 return 0;
1863 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1864 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1865 it != m_dirty_status.end(); it++) {
1867 if ( it->second.m_new ) {
1868 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1869 it->second.m_new = false;
1870 } else if ( it->second.m_dirty ) {
1871 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1876 return response;
1879 void ECSearchMsgSource::FlushStatus()
1881 m_dirty_status.clear();
1884 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1886 if ( m_dirty_status.count(file->GetFileHash()) ) {
1887 m_dirty_status[file->GetFileHash()].m_dirty = true;
1888 } else {
1889 m_dirty_status[file->GetFileHash()].m_new = true;
1890 m_dirty_status[file->GetFileHash()].m_dirty = true;
1891 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1892 m_dirty_status[file->GetFileHash()].m_file = file;
1896 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1898 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1902 * Notification about uploading clients
1904 CECPacket *ECClientMsgSource::GetNextPacket()
1906 return 0;
1910 // Notification iface per-client
1912 ECNotifier::ECNotifier()
1916 ECNotifier::~ECNotifier()
1918 while (m_msg_source.begin() != m_msg_source.end())
1919 Remove_EC_Client(m_msg_source.begin()->first);
1922 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1924 CECPacket *packet = 0;
1926 // priority 0 is highest
1928 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1929 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1930 break;
1933 return packet;
1936 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1939 // OnOutput is called for a first time before
1940 // socket is registered
1942 if ( m_msg_source.count(sock) ) {
1943 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1944 if ( !notifier_array ) {
1945 return 0;
1947 CECPacket *packet = GetNextPacket(notifier_array);
1948 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1949 return packet;
1950 } else {
1951 return 0;
1956 // Interface to notification macros
1958 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
1960 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1961 i != m_msg_source.end(); i++) {
1962 CECServerSocket *sock = i->first;
1963 if ( sock->HaveNotificationSupport() ) {
1964 ECUpdateMsgSource **notifier_array = i->second;
1965 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
1968 NextPacketToSocket();
1971 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
1973 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1974 i != m_msg_source.end(); i++) {
1975 ECUpdateMsgSource **notifier_array = i->second;
1976 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
1978 NextPacketToSocket();
1981 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
1983 // per-partfile source list is not supported (yet), and IMHO quite useless
1986 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
1988 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1989 i != m_msg_source.end(); i++) {
1990 ECUpdateMsgSource **notifier_array = i->second;
1991 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
1993 NextPacketToSocket();
1996 void ECNotifier::DownloadFile_AddSource(CPartFile *)
1998 // per-partfile source list is not supported (yet), and IMHO quite useless
2001 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
2003 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2004 i != m_msg_source.end(); i++) {
2005 ECUpdateMsgSource **notifier_array = i->second;
2006 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
2008 NextPacketToSocket();
2011 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
2013 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2014 i != m_msg_source.end(); i++) {
2015 ECUpdateMsgSource **notifier_array = i->second;
2016 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
2018 NextPacketToSocket();
2021 void ECNotifier::SharedFile_RemoveAllFiles()
2023 // need to figure out what to do here
2026 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2028 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2029 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2030 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2031 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2032 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2033 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2035 m_msg_source[sock] = notifier_array;
2038 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2040 if (m_msg_source.count(sock)) {
2041 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2043 m_msg_source.erase(sock);
2045 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2046 delete notifier_array[i];
2048 delete [] notifier_array;
2052 void ECNotifier::NextPacketToSocket()
2054 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2055 i != m_msg_source.end(); i++) {
2056 CECServerSocket *sock = i->first;
2057 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2058 ECUpdateMsgSource **notifier_array = i->second;
2059 CECPacket *packet = GetNextPacket(notifier_array);
2060 if ( packet ) {
2061 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2062 sock->SendPacket(packet);
2068 // File_checked_for_headers