Upstream tarball 10147
[amule.git] / src / ExternalConn.cpp
blobb2199901f6c0952e38f63d6ef46a7f29303d9860
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 return response;
654 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
656 CECPacket *response = new CECPacket(op);
658 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
661 // request can contain list of queried items
662 // (not for incremental update of course)
663 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
665 const CClientPtrList& clients = (op == EC_OP_WAIT_QUEUE) ? theApp->uploadqueue->GetWaitingList()
666 : theApp->uploadqueue->GetUploadingList();
667 CClientPtrList::const_iterator it = clients.begin();
668 for (; it != clients.end(); ++it) {
669 CUpDownClient* cur_client = *it;
671 if (!cur_client) { // shouldn't happen
672 continue;
674 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
675 continue;
677 CValueMap *valuemap = NULL;
678 if (detail_level == EC_DETAIL_INC_UPDATE) {
679 valuemap = &tagmap.GetValueMap(cur_client->ECID());
681 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
683 response->AddTag(cli_tag);
686 return response;
690 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CFileEncoderMap &encoders)
692 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
694 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
696 // request can contain list of queried items
697 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
699 encoders.UpdateEncoders();
701 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
702 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
704 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
705 continue;
708 CEC_PartFile_Tag filetag(cur_file, detail_level);
710 CPartFile_Encoder * enc = (CPartFile_Encoder *) encoders[cur_file->ECID()];
711 if ( detail_level != EC_DETAIL_UPDATE ) {
712 enc->ResetEncoder();
714 enc->Encode(&filetag);
716 response->AddTag(filetag);
718 return response;
722 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
724 CECPacket *response = NULL;
726 // request can contain multiple files.
727 for (CECPacket::const_iterator it1 = request->begin(); it1 != request->end(); it1++) {
728 const CECTag &hashtag = *it1;
730 wxASSERT(hashtag.GetTagName() == EC_TAG_PARTFILE);
732 CMD4Hash hash = hashtag.GetMD4Data();
733 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
735 if ( !pfile ) {
736 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
737 response = new CECPacket(EC_OP_FAILED);
738 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
739 //return response;
740 break;
742 switch (request->GetOpCode()) {
743 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
744 if ((pfile->GetStatus(false) == PS_READY) ||
745 (pfile->GetStatus(false) == PS_EMPTY)) {
746 CKnownFile::SourceSet::const_iterator it = pfile->GetA4AFList().begin();
747 while ( it != pfile->GetA4AFList().end() ) {
748 CUpDownClient *cur_source = *it++;
750 cur_source->SwapToAnotherFile(true, false, false, pfile);
753 break;
754 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
755 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
756 break;
757 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
758 if ((pfile->GetStatus(false) == PS_READY) ||
759 (pfile->GetStatus(false) == PS_EMPTY)) {
760 CKnownFile::SourceSet::const_iterator it = pfile->GetSourceList().begin();
761 while ( it != pfile->GetSourceList().end() ) {
762 CUpDownClient* cur_source = *it++;
764 cur_source->SwapToAnotherFile(false, false, false, NULL);
767 break;
768 case EC_OP_PARTFILE_PAUSE:
769 pfile->PauseFile();
770 break;
771 case EC_OP_PARTFILE_RESUME:
772 pfile->ResumeFile();
773 pfile->SavePartFile();
774 break;
775 case EC_OP_PARTFILE_STOP:
776 pfile->StopFile();
777 break;
778 case EC_OP_PARTFILE_PRIO_SET: {
779 uint8 prio = hashtag.GetFirstTagSafe()->GetInt();
780 if ( prio == PR_AUTO ) {
781 pfile->SetAutoDownPriority(1);
782 } else {
783 pfile->SetAutoDownPriority(0);
784 pfile->SetDownPriority(prio);
787 break;
788 case EC_OP_PARTFILE_DELETE:
789 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
790 theApp->downloadqueue->StartNextFile(pfile);
792 pfile->Delete();
793 break;
795 case EC_OP_PARTFILE_SET_CAT:
796 pfile->SetCategory(hashtag.GetFirstTagSafe()->GetInt());
797 break;
799 default:
800 response = new CECPacket(EC_OP_FAILED);
801 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
802 break;
805 if (!response) {
806 response = new CECPacket(EC_OP_NOOP);
808 return response;
811 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
813 CECPacket *response = NULL;
815 const CECTag *srv_tag = request->GetFirstTagSafe();
817 wxString full_addr = srv_tag->GetTagByName(EC_TAG_SERVER_ADDRESS)->GetStringData();
818 wxString name = srv_tag->GetTagByName(EC_TAG_SERVER_NAME)->GetStringData();
820 wxString s_ip = full_addr.Left(full_addr.Find(':'));
821 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
823 long port = StrToULong(s_port);
824 CServer* toadd = new CServer(port, s_ip);
825 toadd->SetListName(name.IsEmpty() ? full_addr : name);
827 if ( theApp->AddServer(toadd, true) ) {
828 response = new CECPacket(EC_OP_NOOP);
829 } else {
830 response = new CECPacket(EC_OP_FAILED);
831 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
832 delete toadd;
835 return response;
838 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
840 CECPacket *response = NULL;
841 const CECTag *srv_tag = request->GetFirstTagSafe();
842 CServer *srv = 0;
843 if ( srv_tag ) {
844 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
845 // server tag passed, but server not found
846 if ( !srv ) {
847 response = new CECPacket(EC_OP_FAILED);
848 response->AddTag(CECTag(EC_TAG_STRING,
849 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
850 return response;
853 switch (request->GetOpCode()) {
854 case EC_OP_SERVER_DISCONNECT:
855 theApp->serverconnect->Disconnect();
856 response = new CECPacket(EC_OP_NOOP);
857 break;
858 case EC_OP_SERVER_REMOVE:
859 if ( srv ) {
860 theApp->serverlist->RemoveServer(srv);
861 response = new CECPacket(EC_OP_NOOP);
862 } else {
863 response = new CECPacket(EC_OP_FAILED);
864 response->AddTag(CECTag(EC_TAG_STRING,
865 wxTRANSLATE("need to define server to be removed")));
867 break;
868 case EC_OP_SERVER_CONNECT:
869 if (thePrefs::GetNetworkED2K()) {
870 if ( srv ) {
871 theApp->serverconnect->ConnectToServer(srv);
872 response = new CECPacket(EC_OP_NOOP);
873 } else {
874 theApp->serverconnect->ConnectToAnyServer();
875 response = new CECPacket(EC_OP_NOOP);
877 } else {
878 response = new CECPacket(EC_OP_FAILED);
879 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
881 break;
883 if (!response) {
884 response = new CECPacket(EC_OP_FAILED);
885 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
887 return response;
890 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
892 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
894 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
896 // request can contain list of queried items
897 CTagSet<uint32, EC_TAG_SEARCHFILE> queryitems(request);
899 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
900 CSearchResultList::const_iterator it = list.begin();
901 while (it != list.end()) {
902 CSearchFile* sf = *it++;
903 if ( !queryitems.empty() && !queryitems.count(sf->ECID()) ) {
904 continue;
906 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
908 return response;
911 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
913 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
915 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
916 CSearchResultList::const_iterator it = list.begin();
917 while (it != list.end()) {
918 CSearchFile* sf = *it++;
919 CValueMap &valuemap = tagmap.GetValueMap(sf->ECID());
920 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
921 /* Here we could add the children, if amulegui were able to merge them.
922 if (sf->HasChildren()) {
923 const CSearchResultList& children = sf->GetChildren();
924 for (size_t i = 0; i < children.size(); ++i) {
925 CSearchFile* sfc = children.at(i);
926 CValueMap &valuemap1 = tagmap.GetValueMap(sfc->ECID());
927 response->AddTag(CEC_SearchFile_Tag(sfc, EC_DETAIL_INC_UPDATE, &valuemap1));
932 return response;
935 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
937 CECPacket *response = new CECPacket(EC_OP_STRINGS);
938 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
939 const CECTag &tag = *it;
940 CMD4Hash hash = tag.GetMD4Data();
941 uint8 category = tag.GetFirstTagSafe()->GetInt();
942 theApp->searchlist->AddFileToDownloadByHash(hash, category);
944 return response;
947 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
949 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
950 theApp->searchlist->StopGlobalSearch();
951 return reply;
954 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
956 wxString response;
958 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetFirstTagSafe();
959 theApp->searchlist->RemoveResults(0xffffffff);
961 CSearchList::CSearchParams params;
962 params.searchString = search_request->SearchText();
963 params.typeText = search_request->SearchFileType();
964 params.extension = search_request->SearchExt();
965 params.minSize = search_request->MinSize();
966 params.maxSize = search_request->MaxSize();
967 params.availability = search_request->Avail();
970 EC_SEARCH_TYPE search_type = search_request->SearchType();
971 SearchType core_search_type = LocalSearch;
972 switch (search_type) {
973 case EC_SEARCH_GLOBAL:
974 core_search_type = GlobalSearch;
975 case EC_SEARCH_KAD:
976 if (core_search_type != GlobalSearch) { // Not a global search obviously
977 core_search_type = KadSearch;
979 case EC_SEARCH_LOCAL: {
980 uint32 search_id = 0xffffffff;
981 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
982 if (!error.IsEmpty()) {
983 response = error;
984 } else {
985 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
987 break;
989 case EC_SEARCH_WEB:
990 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
991 break;
994 CECPacket *reply = new CECPacket(EC_OP_FAILED);
995 // error or search in progress
996 reply->AddTag(CECTag(EC_TAG_STRING, response));
998 return reply;
1001 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
1003 CECPacket *response = new CECPacket(EC_OP_NOOP);
1004 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1005 const CECTag &tag = *it;
1006 CMD4Hash hash = tag.GetMD4Data();
1007 uint8 prio = tag.GetFirstTagSafe()->GetInt();
1008 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
1009 if ( !cur_file ) {
1010 continue;
1012 if (prio == PR_AUTO) {
1013 cur_file->SetAutoUpPriority(1);
1014 cur_file->UpdateAutoUpPriority();
1015 } else {
1016 cur_file->SetAutoUpPriority(0);
1017 cur_file->SetUpPriority(prio);
1019 Notify_SharedFilesUpdateItem(cur_file);
1022 return response;
1025 static CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
1027 CECPacket *response;
1028 if (thePrefs::GetNetworkKademlia()) {
1029 response = new CECPacket(EC_OP_NOOP);
1030 if ( !Kademlia::CKademlia::IsRunning() ) {
1031 Kademlia::CKademlia::Start();
1032 theApp->ShowConnectionState();
1034 const CECTag *addrtag = request->GetFirstTagSafe();
1035 if ( addrtag ) {
1036 uint32 ip = addrtag->GetIPv4Data().IP();
1037 uint16 port = addrtag->GetIPv4Data().m_port;
1038 Kademlia::CKademlia::Bootstrap(ip, port, true);
1040 } else {
1041 response = new CECPacket(EC_OP_FAILED);
1042 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
1045 return response;
1048 void CPartFile_Encoder::Encode(CECTag *parent)
1051 // Source part frequencies
1053 CKnownFile_Encoder::Encode(parent);
1056 // Gaps
1058 const CGapList& gaplist = m_PartFile()->GetNewGapList();
1059 const size_t gap_list_size = gaplist.size();
1060 ArrayOfUInts64 gaps;
1061 gaps.reserve(gap_list_size * 2);
1063 for (CGapList::const_iterator curr_pos = gaplist.begin();
1064 curr_pos != gaplist.end(); ++curr_pos) {
1065 gaps.push_back(curr_pos.start());
1066 gaps.push_back(curr_pos.end());
1069 int gap_enc_size = 0;
1070 bool changed;
1071 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
1072 if (changed) {
1073 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
1075 delete[] gap_enc_data;
1078 // Requested blocks
1080 ArrayOfUInts64 req_buffer;
1081 const CPartFile::CReqBlockPtrList& requestedblocks = m_PartFile()->GetRequestedBlockList();
1082 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1084 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1085 Requested_Block_Struct* block = *curr_pos2;
1086 req_buffer.push_back(block->StartOffset);
1087 req_buffer.push_back(block->EndOffset);
1089 int req_enc_size = 0;
1090 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
1091 if (changed) {
1092 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
1094 delete[] req_enc_data;
1097 // Source names
1099 // First count occurrence of all source names
1101 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
1102 typedef std::map<wxString, int> strIntMap;
1103 strIntMap nameMap;
1104 const CPartFile::SourceSet &sources = m_PartFile()->GetSourceList();
1105 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
1106 CUpDownClient *cur_src = *it;
1107 if (cur_src->GetRequestFile() != m_file || cur_src->GetClientFilename().Length() == 0) {
1108 continue;
1110 const wxString &name = cur_src->GetClientFilename();
1111 strIntMap::iterator itm = nameMap.find(name);
1112 if (itm == nameMap.end()) {
1113 nameMap[name] = 1;
1114 } else {
1115 itm->second++;
1119 // Go through our last list
1121 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
1122 SourcenameItemMap::iterator it2 = it1++;
1123 strIntMap::iterator itm = nameMap.find(it2->second.name);
1124 if (itm == nameMap.end()) {
1125 // name doesn't exist anymore, tell client to forget it
1126 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1127 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
1128 sourceNames.AddTag(tag);
1129 // and forget it
1130 m_sourcenameItemMap.erase(it2);
1131 } else {
1132 // update count if it changed
1133 if (it2->second.count != itm->second) {
1134 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1135 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1136 sourceNames.AddTag(tag);
1137 it2->second.count = itm->second;
1139 // remove it from nameMap so that only new names are left there
1140 nameMap.erase(itm);
1144 // Add new names
1146 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1147 int id = ++m_sourcenameID;
1148 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1149 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1150 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1151 sourceNames.AddTag(tag);
1152 // remember it
1153 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1155 if (sourceNames.HasChildTags()) {
1156 parent->AddTag(sourceNames);
1161 void CPartFile_Encoder::ResetEncoder()
1163 CKnownFile_Encoder::ResetEncoder();
1164 m_gap_status.ResetEncoder();
1165 m_req_status.ResetEncoder();
1168 void CKnownFile_Encoder::Encode(CECTag *parent)
1171 // Source part frequencies
1173 // Reference to the availability list
1174 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1175 ((CPartFile*)m_file)->m_SrcpartFrequency :
1176 m_file->m_AvailPartFrequency;
1177 // Don't add tag if available parts aren't populated yet.
1178 if (!list.empty()) {
1179 int part_enc_size;
1180 bool changed;
1181 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1182 if (changed) {
1183 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1185 delete[] part_enc_data;
1189 static CECPacket *GetStatsGraphs(const CECPacket *request)
1191 CECPacket *response = NULL;
1193 switch (request->GetDetailLevel()) {
1194 case EC_DETAIL_WEB:
1195 case EC_DETAIL_FULL: {
1196 double dTimestamp = 0.0;
1197 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1198 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1200 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1201 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1202 uint32 *graphData;
1203 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1204 if (numPoints) {
1205 response = new CECPacket(EC_OP_STATSGRAPHS);
1206 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1207 delete [] graphData;
1208 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1209 } else {
1210 response = new CECPacket(EC_OP_FAILED);
1211 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1213 break;
1215 case EC_DETAIL_INC_UPDATE:
1216 case EC_DETAIL_UPDATE:
1217 case EC_DETAIL_CMD:
1218 // No graphs
1219 response = new CECPacket(EC_OP_FAILED);
1220 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1221 break;
1223 if (!response) {
1224 response = new CECPacket(EC_OP_FAILED);
1225 // Unknown reason
1228 return response;
1231 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request)
1234 if ( !request ) {
1235 return 0;
1238 CECPacket *response = NULL;
1240 switch (request->GetOpCode()) {
1242 // Misc commands
1244 case EC_OP_SHUTDOWN:
1245 if (!theApp->IsOnShutDown()) {
1246 response = new CECPacket(EC_OP_NOOP);
1247 AddLogLineM(true, _("External Connection: shutdown requested"));
1248 #ifndef AMULE_DAEMON
1250 wxCloseEvent evt;
1251 evt.SetCanVeto(false);
1252 theApp->ShutDown(evt);
1254 #else
1255 theApp->ExitMainLoop();
1256 #endif
1257 } else {
1258 response = new CECPacket(EC_OP_FAILED);
1259 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1261 break;
1262 case EC_OP_ADD_LINK:
1263 for (CECPacket::const_iterator it = request->begin(); it != request->end(); it++) {
1264 const CECTag &tag = *it;
1265 wxString link = tag.GetStringData();
1266 int category = 0;
1267 const CECTag *cattag = tag.GetTagByName(EC_TAG_PARTFILE_CAT);
1268 if (cattag) {
1269 category = cattag->GetInt();
1271 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link);
1272 if ( theApp->downloadqueue->AddLink(link, category) ) {
1273 response = new CECPacket(EC_OP_NOOP);
1274 } else {
1275 // Error messages are printed by the add function.
1276 response = new CECPacket(EC_OP_FAILED);
1277 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1280 break;
1282 // Status requests
1284 case EC_OP_STAT_REQ:
1285 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1286 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1287 break;
1288 case EC_OP_GET_CONNSTATE:
1289 response = new CECPacket(EC_OP_MISC_DATA);
1290 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1291 break;
1295 case EC_OP_GET_SHARED_FILES:
1296 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1297 response = Get_EC_Response_GetSharedFiles(request, m_FileEncoder);
1299 break;
1300 case EC_OP_GET_DLOAD_QUEUE:
1301 if ( request->GetDetailLevel() != EC_DETAIL_INC_UPDATE ) {
1302 response = Get_EC_Response_GetDownloadQueue(request, m_FileEncoder);
1304 break;
1306 // This will evolve into an update-all for inc tags
1308 case EC_OP_GET_UPDATE:
1309 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1310 response = Get_EC_Response_GetUpdate(m_FileEncoder, m_obj_tagmap);
1312 break;
1313 case EC_OP_GET_ULOAD_QUEUE:
1314 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_ULOAD_QUEUE);
1315 break;
1316 case EC_OP_GET_WAIT_QUEUE:
1317 response = Get_EC_Response_GetClientQueue(request, m_obj_tagmap, EC_OP_WAIT_QUEUE);
1318 break;
1319 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1320 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1321 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1322 case EC_OP_PARTFILE_CLEANUP_SOURCES:
1323 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1324 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1325 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1326 case EC_OP_PARTFILE_PAUSE:
1327 case EC_OP_PARTFILE_RESUME:
1328 case EC_OP_PARTFILE_STOP:
1329 case EC_OP_PARTFILE_PRIO_SET:
1330 case EC_OP_PARTFILE_DELETE:
1331 case EC_OP_PARTFILE_SET_CAT:
1332 response = Get_EC_Response_PartFile_Cmd(request);
1333 break;
1334 case EC_OP_SHAREDFILES_RELOAD:
1335 theApp->sharedfiles->Reload();
1336 response = new CECPacket(EC_OP_NOOP);
1337 break;
1338 case EC_OP_SHARED_SET_PRIO:
1339 response = Get_EC_Response_Set_SharedFile_Prio(request);
1340 break;
1341 case EC_OP_RENAME_FILE: {
1342 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1343 CKnownFile* file = theApp->knownfiles->FindKnownFileByID(fileHash);
1344 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1345 if (!file) {
1346 file = theApp->downloadqueue->GetFileByID(fileHash);
1348 if (!file) {
1349 response = new CECPacket(EC_OP_FAILED);
1350 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1351 break;
1353 if (newName.IsEmpty()) {
1354 response = new CECPacket(EC_OP_FAILED);
1355 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1356 break;
1359 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1360 response = new CECPacket(EC_OP_NOOP);
1361 } else {
1362 response = new CECPacket(EC_OP_FAILED);
1363 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1366 break;
1371 // Server commands
1373 case EC_OP_SERVER_ADD:
1374 response = Get_EC_Response_Server_Add(request);
1375 break;
1376 case EC_OP_SERVER_DISCONNECT:
1377 case EC_OP_SERVER_CONNECT:
1378 case EC_OP_SERVER_REMOVE:
1379 response = Get_EC_Response_Server(request);
1380 break;
1381 case EC_OP_GET_SERVER_LIST: {
1382 response = new CECPacket(EC_OP_SERVER_LIST);
1383 if (!thePrefs::GetNetworkED2K()) {
1384 // Kad only: just send an empty list
1385 break;
1387 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1388 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1389 for (
1390 std::vector<const CServer*>::const_iterator it = servers.begin();
1391 it != servers.end();
1392 ++it
1394 response->AddTag(CEC_Server_Tag(*it, detail_level));
1397 break;
1398 case EC_OP_SERVER_UPDATE_FROM_URL: {
1399 wxString url = request->GetFirstTagSafe()->GetStringData();
1401 // Save the new url, and update the UI (if not amuled).
1402 Notify_ServersURLChanged(url);
1403 thePrefs::SetEd2kServersUrl(url);
1405 theApp->serverlist->UpdateServerMetFromURL(url);
1406 response = new CECPacket(EC_OP_NOOP);
1407 break;
1410 // IPFilter
1412 case EC_OP_IPFILTER_RELOAD:
1413 theApp->ipfilter->Reload();
1414 response = new CECPacket(EC_OP_NOOP);
1415 break;
1417 case EC_OP_IPFILTER_UPDATE: {
1418 wxString url = request->GetFirstTagSafe()->GetStringData();
1419 if (url == wxEmptyString) {
1420 url = thePrefs::IPFilterURL();
1422 theApp->ipfilter->Update(url);
1423 response = new CECPacket(EC_OP_NOOP);
1424 break;
1427 // Search
1429 case EC_OP_SEARCH_START:
1430 response = Get_EC_Response_Search(request);
1431 break;
1433 case EC_OP_SEARCH_STOP:
1434 response = Get_EC_Response_Search_Stop(request);
1435 break;
1437 case EC_OP_SEARCH_RESULTS:
1438 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1439 response = Get_EC_Response_Search_Results(m_obj_tagmap);
1440 } else {
1441 response = Get_EC_Response_Search_Results(request);
1443 break;
1445 case EC_OP_SEARCH_PROGRESS:
1446 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1447 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1448 theApp->searchlist->GetSearchProgress()));
1449 break;
1451 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1452 response = Get_EC_Response_Search_Results_Download(request);
1453 break;
1455 // Preferences
1457 case EC_OP_GET_PREFERENCES:
1458 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1459 break;
1460 case EC_OP_SET_PREFERENCES:
1461 ((CEC_Prefs_Packet *)request)->Apply();
1462 theApp->glob_prefs->Save();
1463 if (thePrefs::IsFilteringClients()) {
1464 theApp->clientlist->FilterQueues();
1466 if (thePrefs::IsFilteringServers()) {
1467 theApp->serverlist->FilterServers();
1469 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1470 theApp->DisconnectED2K();
1472 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1473 theApp->StopKad();
1475 response = new CECPacket(EC_OP_NOOP);
1476 break;
1478 case EC_OP_CREATE_CATEGORY:
1479 if ( request->GetTagCount() == 1 ) {
1480 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1481 if (tag->Create()) {
1482 response = new CECPacket(EC_OP_NOOP);
1483 } else {
1484 response = new CECPacket(EC_OP_FAILED);
1485 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1486 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1488 Notify_CategoryAdded();
1489 } else {
1490 response = new CECPacket(EC_OP_NOOP);
1492 break;
1493 case EC_OP_UPDATE_CATEGORY:
1494 if ( request->GetTagCount() == 1 ) {
1495 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetFirstTagSafe();
1496 if (tag->Apply()) {
1497 response = new CECPacket(EC_OP_NOOP);
1498 } else {
1499 response = new CECPacket(EC_OP_FAILED);
1500 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1501 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1503 Notify_CategoryUpdate(tag->GetInt());
1504 } else {
1505 response = new CECPacket(EC_OP_NOOP);
1507 break;
1508 case EC_OP_DELETE_CATEGORY:
1509 if ( request->GetTagCount() == 1 ) {
1510 uint32 cat = request->GetFirstTagSafe()->GetInt();
1511 // this noes not only update the gui, but actually deletes the cat
1512 Notify_CategoryDelete(cat);
1514 response = new CECPacket(EC_OP_NOOP);
1515 break;
1518 // Logging
1520 case EC_OP_ADDLOGLINE:
1521 AddLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1522 response = new CECPacket(EC_OP_NOOP);
1523 break;
1524 case EC_OP_ADDDEBUGLOGLINE:
1525 AddDebugLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1526 response = new CECPacket(EC_OP_NOOP);
1527 break;
1528 case EC_OP_GET_LOG:
1529 response = new CECPacket(EC_OP_LOG);
1530 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1531 break;
1532 case EC_OP_GET_DEBUGLOG:
1533 response = new CECPacket(EC_OP_DEBUGLOG);
1534 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1535 break;
1536 case EC_OP_RESET_LOG:
1537 theApp->GetLog(true);
1538 response = new CECPacket(EC_OP_NOOP);
1539 break;
1540 case EC_OP_RESET_DEBUGLOG:
1541 theApp->GetDebugLog(true);
1542 response = new CECPacket(EC_OP_NOOP);
1543 break;
1544 case EC_OP_GET_LAST_LOG_ENTRY:
1546 wxString tmp = theApp->GetLog(false);
1547 if (tmp.Last() == '\n') {
1548 tmp.RemoveLast();
1550 response = new CECPacket(EC_OP_LOG);
1551 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1553 break;
1554 case EC_OP_GET_SERVERINFO:
1555 response = new CECPacket(EC_OP_SERVERINFO);
1556 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1557 break;
1558 case EC_OP_CLEAR_SERVERINFO:
1559 theApp->GetServerLog(true);
1560 response = new CECPacket(EC_OP_NOOP);
1561 break;
1563 // Statistics
1565 case EC_OP_GET_STATSGRAPHS:
1566 response = GetStatsGraphs(request);
1567 break;
1568 case EC_OP_GET_STATSTREE: {
1569 theApp->m_statistics->UpdateStatsTree();
1570 response = new CECPacket(EC_OP_STATSTREE);
1571 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1572 if (tree) {
1573 response->AddTag(*tree);
1574 delete tree;
1576 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1577 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1578 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1580 break;
1584 // Kad
1586 case EC_OP_KAD_START:
1587 response = Get_EC_Response_Kad_Connect(request);
1588 break;
1589 case EC_OP_KAD_STOP:
1590 theApp->StopKad();
1591 response = new CECPacket(EC_OP_NOOP);
1592 break;
1593 case EC_OP_KAD_UPDATE_FROM_URL: {
1594 wxString url = request->GetFirstTagSafe()->GetStringData();
1596 // Save the new url, and update the UI (if not amuled).
1597 Notify_NodesURLChanged(url);
1598 thePrefs::SetKadNodesUrl(url);
1600 theApp->UpdateNotesDat(url);
1601 response = new CECPacket(EC_OP_NOOP);
1602 break;
1604 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1605 theApp->BootstrapKad(request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP)->GetInt(),
1606 request->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT)->GetInt());
1607 response = new CECPacket(EC_OP_NOOP);
1608 break;
1611 // Networks
1613 case EC_OP_CONNECT:
1614 if (thePrefs::GetNetworkED2K()) {
1615 response = new CECPacket(EC_OP_STRINGS);
1616 if (theApp->IsConnectedED2K()) {
1617 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1618 } else {
1619 theApp->serverconnect->ConnectToAnyServer();
1620 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1623 if (thePrefs::GetNetworkKademlia()) {
1624 if (!response) {
1625 response = new CECPacket(EC_OP_STRINGS);
1627 if (theApp->IsConnectedKad()) {
1628 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1629 } else {
1630 theApp->StartKad();
1631 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1634 if (!response) {
1635 response = new CECPacket(EC_OP_FAILED);
1636 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1638 break;
1639 case EC_OP_DISCONNECT:
1640 if (theApp->IsConnected()) {
1641 response = new CECPacket(EC_OP_STRINGS);
1642 if (theApp->IsConnectedED2K()) {
1643 theApp->serverconnect->Disconnect();
1644 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1646 if (theApp->IsConnectedKad()) {
1647 theApp->StopKad();
1648 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1650 } else {
1651 response = new CECPacket(EC_OP_NOOP);
1653 break;
1655 if (!response) {
1656 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1657 wxFAIL;
1658 response = new CECPacket(EC_OP_FAILED);
1659 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1661 return response;
1665 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1669 * Core general status
1671 ECStatusMsgSource::ECStatusMsgSource()
1673 m_last_ed2k_status_sent = 0xffffffff;
1674 m_last_kad_status_sent = 0xffffffff;
1675 m_server = (void *)0xffffffff;
1678 uint32 ECStatusMsgSource::GetEd2kStatus()
1680 if ( theApp->IsConnectedED2K() ) {
1681 return theApp->GetED2KID();
1682 } else if ( theApp->serverconnect->IsConnecting() ) {
1683 return 1;
1684 } else {
1685 return 0;
1689 uint32 ECStatusMsgSource::GetKadStatus()
1691 if ( theApp->IsConnectedKad() ) {
1692 return 1;
1693 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1694 return 2;
1695 } else if ( Kademlia::CKademlia::IsRunning() ) {
1696 return 3;
1698 return 0;
1701 CECPacket *ECStatusMsgSource::GetNextPacket()
1703 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1704 (m_last_kad_status_sent != GetKadStatus()) ||
1705 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1707 m_last_ed2k_status_sent = GetEd2kStatus();
1708 m_last_kad_status_sent = GetKadStatus();
1709 m_server = theApp->serverconnect->GetCurrentServer();
1711 CECPacket *response = new CECPacket(EC_OP_STATS);
1712 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1713 return response;
1715 return 0;
1719 * Downloading files
1721 ECPartFileMsgSource::ECPartFileMsgSource()
1723 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1724 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1725 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1726 m_dirty_status[cur_file->GetFileHash()] = status;
1730 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1732 CMD4Hash filehash = file->GetFileHash();
1733 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1734 m_dirty_status[filehash].m_dirty = true;;
1738 void ECPartFileMsgSource::SetNew(CPartFile *file)
1740 CMD4Hash filehash = file->GetFileHash();
1741 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1742 PARTFILE_STATUS status = { true, false, false, false, true, file };
1743 m_dirty_status[filehash] = status;
1746 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1748 CMD4Hash filehash = file->GetFileHash();
1749 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1751 m_dirty_status[filehash].m_finished = true;
1754 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1756 CMD4Hash filehash = file->GetFileHash();
1757 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1759 m_dirty_status[filehash].m_removed = true;
1762 CECPacket *ECPartFileMsgSource::GetNextPacket()
1764 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1765 it != m_dirty_status.end(); it++) {
1766 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1767 CMD4Hash filehash = it->first;
1769 CPartFile *partfile = it->second.m_file;
1771 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1772 if ( it->second.m_removed ) {
1773 CECTag tag(EC_TAG_PARTFILE, filehash);
1774 packet->AddTag(tag);
1775 m_dirty_status.erase(it);
1776 } else {
1777 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1778 packet->AddTag(tag);
1780 m_dirty_status[filehash].m_new = false;
1781 m_dirty_status[filehash].m_dirty = false;
1783 return packet;
1786 return 0;
1790 * Shared files - similar to downloading
1792 ECKnownFileMsgSource::ECKnownFileMsgSource()
1794 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1795 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1796 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1797 m_dirty_status[cur_file->GetFileHash()] = status;
1801 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1803 CMD4Hash filehash = file->GetFileHash();
1804 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1805 m_dirty_status[filehash].m_dirty = true;;
1809 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1811 CMD4Hash filehash = file->GetFileHash();
1812 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1813 KNOWNFILE_STATUS status = { true, false, false, true, file };
1814 m_dirty_status[filehash] = status;
1817 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1819 CMD4Hash filehash = file->GetFileHash();
1820 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1822 m_dirty_status[filehash].m_removed = true;
1825 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1827 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1828 it != m_dirty_status.end(); it++) {
1829 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1830 CMD4Hash filehash = it->first;
1832 CKnownFile *partfile = it->second.m_file;
1834 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1835 if ( it->second.m_removed ) {
1836 CECTag tag(EC_TAG_PARTFILE, filehash);
1837 packet->AddTag(tag);
1838 m_dirty_status.erase(it);
1839 } else {
1840 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1841 packet->AddTag(tag);
1843 m_dirty_status[filehash].m_new = false;
1844 m_dirty_status[filehash].m_dirty = false;
1846 return packet;
1849 return 0;
1853 * Notification about search status
1855 ECSearchMsgSource::ECSearchMsgSource()
1859 CECPacket *ECSearchMsgSource::GetNextPacket()
1861 if ( m_dirty_status.empty() ) {
1862 return 0;
1865 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1866 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1867 it != m_dirty_status.end(); it++) {
1869 if ( it->second.m_new ) {
1870 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1871 it->second.m_new = false;
1872 } else if ( it->second.m_dirty ) {
1873 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1878 return response;
1881 void ECSearchMsgSource::FlushStatus()
1883 m_dirty_status.clear();
1886 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1888 if ( m_dirty_status.count(file->GetFileHash()) ) {
1889 m_dirty_status[file->GetFileHash()].m_dirty = true;
1890 } else {
1891 m_dirty_status[file->GetFileHash()].m_new = true;
1892 m_dirty_status[file->GetFileHash()].m_dirty = true;
1893 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1894 m_dirty_status[file->GetFileHash()].m_file = file;
1898 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1900 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1904 * Notification about uploading clients
1906 CECPacket *ECClientMsgSource::GetNextPacket()
1908 return 0;
1912 // Notification iface per-client
1914 ECNotifier::ECNotifier()
1918 ECNotifier::~ECNotifier()
1920 while (m_msg_source.begin() != m_msg_source.end())
1921 Remove_EC_Client(m_msg_source.begin()->first);
1924 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1926 CECPacket *packet = 0;
1928 // priority 0 is highest
1930 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1931 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1932 break;
1935 return packet;
1938 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1941 // OnOutput is called for a first time before
1942 // socket is registered
1944 if ( m_msg_source.count(sock) ) {
1945 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1946 if ( !notifier_array ) {
1947 return 0;
1949 CECPacket *packet = GetNextPacket(notifier_array);
1950 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1951 return packet;
1952 } else {
1953 return 0;
1958 // Interface to notification macros
1960 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
1962 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1963 i != m_msg_source.end(); i++) {
1964 CECServerSocket *sock = i->first;
1965 if ( sock->HaveNotificationSupport() ) {
1966 ECUpdateMsgSource **notifier_array = i->second;
1967 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
1970 NextPacketToSocket();
1973 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
1975 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1976 i != m_msg_source.end(); i++) {
1977 ECUpdateMsgSource **notifier_array = i->second;
1978 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
1980 NextPacketToSocket();
1983 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
1985 // per-partfile source list is not supported (yet), and IMHO quite useless
1988 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
1990 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1991 i != m_msg_source.end(); i++) {
1992 ECUpdateMsgSource **notifier_array = i->second;
1993 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
1995 NextPacketToSocket();
1998 void ECNotifier::DownloadFile_AddSource(CPartFile *)
2000 // per-partfile source list is not supported (yet), and IMHO quite useless
2003 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
2005 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2006 i != m_msg_source.end(); i++) {
2007 ECUpdateMsgSource **notifier_array = i->second;
2008 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
2010 NextPacketToSocket();
2013 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
2015 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2016 i != m_msg_source.end(); i++) {
2017 ECUpdateMsgSource **notifier_array = i->second;
2018 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
2020 NextPacketToSocket();
2023 void ECNotifier::SharedFile_RemoveAllFiles()
2025 // need to figure out what to do here
2028 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
2030 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
2031 notifier_array[EC_STATUS] = new ECStatusMsgSource();
2032 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
2033 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
2034 notifier_array[EC_CLIENT] = new ECClientMsgSource();
2035 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
2037 m_msg_source[sock] = notifier_array;
2040 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
2042 if (m_msg_source.count(sock)) {
2043 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
2045 m_msg_source.erase(sock);
2047 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
2048 delete notifier_array[i];
2050 delete [] notifier_array;
2054 void ECNotifier::NextPacketToSocket()
2056 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
2057 i != m_msg_source.end(); i++) {
2058 CECServerSocket *sock = i->first;
2059 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
2060 ECUpdateMsgSource **notifier_array = i->second;
2061 CECPacket *packet = GetNextPacket(notifier_array);
2062 if ( packet ) {
2063 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2064 sock->SendPacket(packet);
2070 // File_checked_for_headers