Upstream tarball 9716
[amule.git] / src / ExternalConn.cpp
blobdb9a88c4310a620223ac9fcdf23078d4a794502f
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 //-------------------- CECServerSocket --------------------
61 class CECServerSocket : public CECMuleSocket
63 public:
64 CECServerSocket(ECNotifier *notifier);
65 virtual ~CECServerSocket();
67 virtual const CECPacket *OnPacketReceived(const CECPacket *packet);
68 virtual void OnLost();
70 virtual void WriteDoneAndQueueEmpty();
71 private:
72 ECNotifier *m_ec_notifier;
74 const CECPacket *Authenticate(const CECPacket *);
76 enum {
77 CONN_INIT,
78 CONN_SALT_SENT,
79 CONN_ESTABLISHED,
80 CONN_FAILED
81 } m_conn_state;
83 uint64_t m_passwd_salt;
84 CLoggerAccess m_LoggerAccess;
85 CPartFile_Encoder_Map m_part_encoder;
86 CKnownFile_Encoder_Map m_shared_encoder;
87 CObjTagMap m_obj_tagmap;
88 CECPacket *ProcessRequest2(
89 const CECPacket *request,
90 CPartFile_Encoder_Map &,
91 CKnownFile_Encoder_Map &,
92 CObjTagMap &);
97 CECServerSocket::CECServerSocket(ECNotifier *notifier)
99 CECMuleSocket(true),
100 m_conn_state(CONN_INIT),
101 m_passwd_salt(GetRandomUint64()),
102 m_part_encoder(),
103 m_shared_encoder(),
104 m_obj_tagmap()
106 wxASSERT(theApp->ECServerHandler);
107 theApp->ECServerHandler->AddSocket(this);
108 m_ec_notifier = notifier;
112 CECServerSocket::~CECServerSocket()
114 wxASSERT(theApp->ECServerHandler);
115 theApp->ECServerHandler->RemoveSocket(this);
119 const CECPacket *CECServerSocket::OnPacketReceived(const CECPacket *packet)
121 packet->DebugPrint(true);
123 const CECPacket *reply = NULL;
125 if (m_conn_state == CONN_FAILED) {
126 // Client didn't close the socket when authentication failed.
127 AddLogLineM(false, _("Client sent packet after authentication failed."));
128 CloseSocket();
131 if (m_conn_state != CONN_ESTABLISHED) {
132 reply = Authenticate(packet);
133 if (reply->GetOpCode() == EC_OP_AUTH_FAIL) {
134 // Access denied!
135 AddLogLineM(false, _("Unauthorized access attempt. Connection closed."));
136 m_conn_state = CONN_FAILED;
137 } else {
138 theApp->ECServerHandler->m_ec_notifier->Add_EC_Client(this);
140 } else {
141 reply = ProcessRequest2(
142 packet, m_part_encoder, m_shared_encoder, m_obj_tagmap);
144 return reply;
148 void CECServerSocket::OnLost()
150 AddLogLineM(false,_("External connection closed."));
151 theApp->ECServerHandler->m_ec_notifier->Remove_EC_Client(this);
152 DestroySocket();
155 void CECServerSocket::WriteDoneAndQueueEmpty()
157 if ( HaveNotificationSupport() && (m_conn_state == CONN_ESTABLISHED) ) {
158 CECPacket *packet = m_ec_notifier->GetNextPacket(this);
159 if ( packet ) {
160 SendPacket(packet);
162 } else {
163 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
167 //-------------------- ExternalConn --------------------
169 enum
170 { // id for sockets
171 SERVER_ID = 1000
175 BEGIN_EVENT_TABLE(ExternalConn, wxEvtHandler)
176 EVT_SOCKET(SERVER_ID, ExternalConn::OnServerEvent)
177 END_EVENT_TABLE()
180 ExternalConn::ExternalConn(amuleIPV4Address addr, wxString *msg)
182 wxString msgLocal;
183 m_ECServer = NULL;
184 // Are we allowed to accept External Connections?
185 if ( thePrefs::AcceptExternalConnections() ) {
186 // We must have a valid password, otherwise we will not allow EC connections
187 if (thePrefs::ECPassword().IsEmpty()) {
188 *msg += wxT("External connections disabled due to empty password!\n");
189 AddLogLineM(true, _("External connections disabled due to empty password!"));
190 return;
193 // Create the socket
194 m_ECServer = new wxSocketServer(addr, wxSOCKET_REUSEADDR);
195 m_ECServer->SetEventHandler(*this, SERVER_ID);
196 m_ECServer->SetNotify(wxSOCKET_CONNECTION_FLAG);
197 m_ECServer->Notify(true);
199 int port = addr.Service();
200 wxString ip = addr.IPAddress();
201 if (m_ECServer->Ok()) {
202 msgLocal = wxT("*** TCP socket (ECServer) listening on ") + ip +
203 wxString::Format(wxT(":%d"), port);
204 *msg += msgLocal + wxT("\n");
205 AddLogLineM(false, msgLocal);
206 } else {
207 msgLocal = wxT("Could not listen for external connections at ") + ip +
208 wxString::Format(wxT(":%d!"), port);
209 *msg += msgLocal + wxT("\n");
210 AddLogLineM(false, msgLocal);
212 } else {
213 *msg += wxT("External connections disabled in config file\n");
214 AddLogLineM(false,_("External connections disabled in config file"));
216 m_ec_notifier = new ECNotifier();
220 ExternalConn::~ExternalConn()
222 KillAllSockets();
223 delete m_ECServer;
224 delete m_ec_notifier;
228 void ExternalConn::AddSocket(CECServerSocket *s)
230 wxASSERT(s);
231 socket_list.insert(s);
235 void ExternalConn::RemoveSocket(CECServerSocket *s)
237 wxASSERT(s);
238 socket_list.erase(s);
242 void ExternalConn::KillAllSockets()
244 AddDebugLogLineM(false, logGeneral,
245 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
246 socket_list.size());
247 SocketSet::iterator it = socket_list.begin();
248 while (it != socket_list.end()) {
249 CECServerSocket *s = *(it++);
250 s->Close();
251 s->Destroy();
252 delete s;
257 void ExternalConn::OnServerEvent(wxSocketEvent& WXUNUSED(event))
259 CECServerSocket *sock = new CECServerSocket(m_ec_notifier);
260 // Accept new connection if there is one in the pending
261 // connections queue, else exit. We use Accept(FALSE) for
262 // non-blocking accept (although if we got here, there
263 // should ALWAYS be a pending connection).
264 if ( m_ECServer->AcceptWith(*sock, false) ) {
265 AddLogLineM(false, _("New external connection accepted"));
266 } else {
267 delete sock;
268 AddLogLineM(false, _("ERROR: couldn't accept a new external connection"));
274 // Authentication
276 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
278 CECPacket *response;
280 if (request == NULL) {
281 response = new CECPacket(EC_OP_AUTH_FAIL);
282 return response;
285 // Password must be specified if we are to allow remote connections
286 if ( thePrefs::ECPassword().IsEmpty() ) {
287 AddLogLineM(true, _("External connection refused due to empty password in preferences!"));
289 return new CECPacket(EC_OP_AUTH_FAIL);
292 if ((m_conn_state == CONN_INIT) && (request->GetOpCode() == EC_OP_AUTH_REQ) ) {
293 const CECTag *clientName = request->GetTagByName(EC_TAG_CLIENT_NAME);
294 const CECTag *clientVersion = request->GetTagByName(EC_TAG_CLIENT_VERSION);
296 AddLogLineM(false, CFormat( _("Connecting client: %s %s") )
297 % ( clientName ? clientName->GetStringData() : wxString(_("Unknown")) )
298 % ( clientVersion ? clientVersion->GetStringData() : wxString(_("Unknown version")) ) );
299 const CECTag *protocol = request->GetTagByName(EC_TAG_PROTOCOL_VERSION);
300 #ifdef EC_VERSION_ID
301 // For SVN versions, both client and server must use SVNDATE, and they must be the same
302 CMD4Hash vhash;
303 if (!vhash.Decode(wxT(EC_VERSION_ID))) {
304 response = new CECPacket(EC_OP_AUTH_FAIL);
305 response->AddTag(CECTag(EC_TAG_STRING, wxT("Fatal error, version hash is not a valid MD4-hash.")));
306 } else if (!request->GetTagByName(EC_TAG_VERSION_ID) || request->GetTagByNameSafe(EC_TAG_VERSION_ID)->GetMD4Data() != vhash) {
307 response = new CECPacket(EC_OP_AUTH_FAIL);
308 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
309 #else
310 // For release versions, we don't want to allow connections from any arbitrary SVN client.
311 if (request->GetTagByName(EC_TAG_VERSION_ID)) {
312 response = new CECPacket(EC_OP_AUTH_FAIL);
313 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("You cannot connect to a release version from an arbitrary SVN version! *sigh* possible crash prevented")));
314 #endif
315 } else if (protocol != NULL) {
316 uint16 proto_version = protocol->GetInt();
317 if (proto_version == EC_CURRENT_PROTOCOL_VERSION) {
318 response = new CECPacket(EC_OP_AUTH_SALT);
319 response->AddTag(CECTag(EC_TAG_PASSWD_SALT, m_passwd_salt));
320 m_conn_state = CONN_SALT_SENT;
321 } else {
322 response = new CECPacket(EC_OP_AUTH_FAIL);
323 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid protocol version.") + wxString::Format(wxT("( %i != %i )"),proto_version,EC_CURRENT_PROTOCOL_VERSION)));
325 } else {
326 response = new CECPacket(EC_OP_AUTH_FAIL);
327 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Missing protocol version tag.")));
329 } else if ((m_conn_state == CONN_SALT_SENT) && (request->GetOpCode() == EC_OP_AUTH_PASSWD)) {
330 const CECTag *passwd = request->GetTagByName(EC_TAG_PASSWD_HASH);
331 CMD4Hash passh;
333 if (!passh.Decode(thePrefs::ECPassword())) {
334 AddLogLineM(false, wxT("EC Auth failed, invalid hash specificed as EC password: ") + thePrefs::ECPassword());
335 response = new CECPacket(EC_OP_AUTH_FAIL);
336 response->AddTag(CECTag(EC_TAG_STRING, wxT("Authentication failed, invalid hash specified as EC password.")));
337 } else {
338 wxString saltHash = MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt).GetHash();
339 wxString saltStr = CFormat(wxT("%lX")) % m_passwd_salt;
341 passh.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash).GetHash());
343 if (passwd && passwd->GetMD4Data() == passh) {
344 response = new CECPacket(EC_OP_AUTH_OK);
345 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
346 } else {
347 if (passwd) {
348 AddLogLineM(false, wxT("EC Auth failed: (") + passwd->GetMD4Data().Encode() + wxT(" != ") + passh.Encode() + wxT(")."));
349 } else {
350 AddLogLineM(false, wxT("EC Auth failed. Password tag missing."));
353 response = new CECPacket(EC_OP_AUTH_FAIL);
354 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Authentication failed.")));
357 } else {
358 response = new CECPacket(EC_OP_AUTH_FAIL);
359 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid request, please authenticate first.")));
362 if (response->GetOpCode() == EC_OP_AUTH_OK) {
363 m_conn_state = CONN_ESTABLISHED;
364 AddLogLineM(false, _("Access granted."));
365 } else if (response->GetTagByIndex(0)->IsString()) {
366 AddLogLineM(false, wxGetTranslation(response->GetTagByIndex(0)->GetStringData()));
369 return response;
372 // Make a Logger tag (if there are any logging messages) and add it to the response
373 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
375 if (LoggerAccess.HasString()) {
376 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
377 // Tag structure is fix: tag carries nothing, inside are the strings
378 // maximum of 200 log lines per message
379 int entries = 0;
380 wxString line;
381 while (entries < 200 && LoggerAccess.GetString(line)) {
382 tag.AddTag(CECTag(EC_TAG_STRING, line));
383 entries++;
385 response->AddTag(tag);
386 //printf("send Log tag %d %d\n", FirstEntry, entries);
390 CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
392 CECPacket *response = new CECPacket(EC_OP_STATS);
394 switch (request->GetDetailLevel()) {
395 case EC_DETAIL_FULL:
396 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
397 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
398 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
399 AddLoggerTag(response, LoggerAccess);
400 case EC_DETAIL_WEB:
401 case EC_DETAIL_CMD:
402 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
403 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
404 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
405 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
406 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
407 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
408 // User/Filecounts
410 uint32 totaluser = 0, totalfile = 0;
411 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
412 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
413 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
414 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
415 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
417 // Kad stats
418 if (Kademlia::CKademlia::IsConnected()) {
419 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
420 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
421 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
422 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
423 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
424 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
425 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
426 uint32 BuddyIP = 0;
427 uint16 BuddyPort = 0;
428 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
429 if (Buddy) {
430 BuddyIP = Buddy->GetIP();
431 BuddyPort = Buddy->GetUDPPort();
433 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
434 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
436 case EC_DETAIL_UPDATE:
437 case EC_DETAIL_INC_UPDATE:
438 break;
441 return response;
444 CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CKnownFile_Encoder_Map &encoders)
446 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
448 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
450 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
452 // request can contain list of queried items
453 CTagSet<CMD4Hash, EC_TAG_KNOWNFILE> queryitems(request);
455 encoders.UpdateEncoders(theApp->sharedfiles);
457 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
458 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
460 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->GetFileHash())) ) {
461 continue;
464 CEC_SharedFile_Tag filetag(cur_file, detail_level);
465 CKnownFile_Encoder &enc = encoders[cur_file];
466 if ( detail_level != EC_DETAIL_UPDATE ) {
467 enc.ResetEncoder();
469 enc.Encode(&filetag);
470 response->AddTag(filetag);
472 return response;
475 CECPacket *Get_EC_Response_GetSharedFiles(CKnownFile_Encoder_Map &encoders, CObjTagMap &tagmap)
477 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
479 encoders.UpdateEncoders(theApp->sharedfiles);
480 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
481 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
484 // Hashes of tags are maintained on "per-object" basis. So, in this mode only
485 // same kind of objects can go into particular query type.
486 // Particulary here it means that files from download queue (aka partfiles)
487 // will not ne shown as shared files. Remote gui can do combine them if wishes
489 if ( !cur_file || cur_file->IsPartFile() ) continue;
491 CValueMap &valuemap = tagmap.GetValueMap(cur_file);
492 CEC_SharedFile_Tag filetag(cur_file, valuemap);
493 CKnownFile_Encoder &enc = encoders[cur_file];
494 enc.Encode(&filetag);
496 response->AddTag(filetag);
498 return response;
501 CECPacket *Get_EC_Response_GetWaitQueue(const CECPacket *request)
503 wxASSERT(request->GetOpCode() == EC_OP_GET_WAIT_QUEUE);
505 CECPacket *response = new CECPacket(EC_OP_WAIT_QUEUE);
507 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
510 // request can contain list of queried items
511 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
513 const CClientPtrList& uploading = theApp->uploadqueue->GetWaitingList();
514 CClientPtrList::const_iterator it = uploading.begin();
515 for (; it != uploading.end(); ++it) {
516 CUpDownClient* cur_client = *it;
518 if ( !cur_client || (!queryitems.empty() && !queryitems.count(cur_client->GetUserIDHybrid())) ) {
519 continue;
521 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level);
523 response->AddTag(cli_tag);
526 return response;
529 CECPacket *Get_EC_Response_GetWaitQueue(CObjTagMap &tagmap)
531 CECPacket *response = new CECPacket(EC_OP_WAIT_QUEUE);
533 const CClientPtrList& uploading = theApp->uploadqueue->GetWaitingList();
534 CClientPtrList::const_iterator it = uploading.begin();
535 for (; it != uploading.end(); ++it) {
536 CUpDownClient* cur_client = *it;
538 CValueMap &valuemap = tagmap.GetValueMap(cur_client);
539 CEC_UpDownClient_Tag cli_tag(cur_client, valuemap);
541 response->AddTag(cli_tag);
544 return response;
547 CECPacket *Get_EC_Response_GetUpQueue(const CECPacket *request)
549 wxASSERT(request->GetOpCode() == EC_OP_GET_ULOAD_QUEUE);
551 CECPacket *response = new CECPacket(EC_OP_ULOAD_QUEUE);
553 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
556 // request can contain list of queried items
557 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
560 const CClientPtrList& uploading = theApp->uploadqueue->GetUploadingList();
561 CClientPtrList::const_iterator it = uploading.begin();
562 for (; it != uploading.end(); ++it) {
563 CUpDownClient* cur_client = *it;
565 if ( !cur_client || (!queryitems.empty() && !queryitems.count(cur_client->GetUserIDHybrid())) ) {
566 continue;
569 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level);
570 response->AddTag(cli_tag);
573 return response;
577 CECPacket *Get_EC_Response_GetUpQueue(CObjTagMap &tagmap)
579 CECPacket *response = new CECPacket(EC_OP_ULOAD_QUEUE);
581 const CClientPtrList& uploading = theApp->uploadqueue->GetUploadingList();
582 CClientPtrList::const_iterator it = uploading.begin();
583 for (; it != uploading.end(); ++it) {
584 CUpDownClient* cur_client = *it;
586 CValueMap &valuemap = tagmap.GetValueMap(cur_client);
587 CEC_UpDownClient_Tag cli_tag(cur_client, valuemap);
589 response->AddTag(cli_tag);
592 return response;
596 CECPacket *Get_EC_Response_GetDownloadQueue(CPartFile_Encoder_Map &encoders, CObjTagMap &tagmap)
598 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
600 encoders.UpdateEncoders(theApp->downloadqueue);
601 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
602 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
604 CValueMap &valuemap = tagmap.GetValueMap(cur_file);
605 CEC_PartFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, true, &valuemap);
606 CPartFile_Encoder &enc = encoders[cur_file];
607 enc.Encode(&filetag);
609 response->AddTag(filetag);
611 return response;
614 CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CPartFile_Encoder_Map &encoders, bool detail = false)
616 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
618 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
620 // request can contain list of queried items
621 CTagSet<CMD4Hash, EC_TAG_PARTFILE> queryitems(request);
623 encoders.UpdateEncoders(theApp->downloadqueue);
625 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
626 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
628 if ( !queryitems.empty() && !queryitems.count(cur_file->GetFileHash()) ) {
629 continue;
632 CEC_PartFile_Tag filetag(cur_file, detail_level, detail);
634 CPartFile_Encoder &enc = encoders[cur_file];
635 if ( detail_level != EC_DETAIL_UPDATE ) {
636 enc.ResetEncoder();
638 enc.Encode(&filetag);
640 response->AddTag(filetag);
642 return response;
646 CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
648 CECPacket *response = NULL;
650 // request can contain multiple files.
651 for (unsigned int i = 0; i < request->GetTagCount(); ++i) {
652 const CECTag *hashtag = request->GetTagByIndex(i);
654 wxASSERT(hashtag->GetTagName() == EC_TAG_PARTFILE);
656 CMD4Hash hash = hashtag->GetMD4Data();
657 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
659 if ( !pfile ) {
660 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
661 response = new CECPacket(EC_OP_FAILED);
662 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
663 //return response;
664 break;
666 switch (request->GetOpCode()) {
667 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
668 if ((pfile->GetStatus(false) == PS_READY) ||
669 (pfile->GetStatus(false) == PS_EMPTY)) {
670 CPartFile::SourceSet::const_iterator it = pfile->GetA4AFList().begin();
671 while ( it != pfile->GetA4AFList().end() ) {
672 CUpDownClient *cur_source = *it++;
674 cur_source->SwapToAnotherFile(true, false, false, pfile);
677 break;
678 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
679 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
680 break;
681 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
682 if ((pfile->GetStatus(false) == PS_READY) ||
683 (pfile->GetStatus(false) == PS_EMPTY)) {
684 CPartFile::SourceSet::const_iterator it = pfile->GetSourceList().begin();
685 while ( it != pfile->GetSourceList().end() ) {
686 CUpDownClient* cur_source = *it++;
688 cur_source->SwapToAnotherFile(false, false, false, NULL);
691 break;
692 case EC_OP_PARTFILE_PAUSE:
693 pfile->PauseFile();
694 break;
695 case EC_OP_PARTFILE_RESUME:
696 pfile->ResumeFile();
697 pfile->SavePartFile();
698 break;
699 case EC_OP_PARTFILE_STOP:
700 pfile->StopFile();
701 break;
702 case EC_OP_PARTFILE_PRIO_SET: {
703 uint8 prio = hashtag->GetTagByIndexSafe(0)->GetInt();
704 if ( prio == PR_AUTO ) {
705 pfile->SetAutoDownPriority(1);
706 } else {
707 pfile->SetAutoDownPriority(0);
708 pfile->SetDownPriority(prio);
711 break;
712 case EC_OP_PARTFILE_DELETE:
713 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
714 theApp->downloadqueue->StartNextFile(pfile);
716 pfile->Delete();
717 break;
719 case EC_OP_PARTFILE_SET_CAT:
720 pfile->SetCategory(hashtag->GetTagByIndexSafe(0)->GetInt());
721 break;
723 default:
724 response = new CECPacket(EC_OP_FAILED);
725 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
726 break;
729 if (!response) {
730 response = new CECPacket(EC_OP_NOOP);
732 return response;
735 CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
737 CECPacket *response = NULL;
739 const CECTag *srv_tag = request->GetTagByIndex(0);
741 wxString full_addr = srv_tag->GetTagByName(EC_TAG_SERVER_ADDRESS)->GetStringData();
742 wxString name = srv_tag->GetTagByName(EC_TAG_SERVER_NAME)->GetStringData();
744 wxString s_ip = full_addr.Left(full_addr.Find(':'));
745 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
747 long port = StrToULong(s_port);
748 CServer* toadd = new CServer(port, s_ip);
749 toadd->SetListName(name.IsEmpty() ? full_addr : name);
751 if ( theApp->AddServer(toadd, true) ) {
752 response = new CECPacket(EC_OP_NOOP);
753 } else {
754 response = new CECPacket(EC_OP_FAILED);
755 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
756 delete toadd;
759 return response;
762 CECPacket *Get_EC_Response_Server(const CECPacket *request)
764 CECPacket *response = NULL;
765 const CECTag *srv_tag = request->GetTagByIndex(0);
766 CServer *srv = 0;
767 if ( srv_tag ) {
768 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
769 // server tag passed, but server not found
770 if ( !srv ) {
771 response = new CECPacket(EC_OP_FAILED);
772 response->AddTag(CECTag(EC_TAG_STRING,
773 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
774 return response;
777 switch (request->GetOpCode()) {
778 case EC_OP_SERVER_DISCONNECT:
779 theApp->serverconnect->Disconnect();
780 response = new CECPacket(EC_OP_NOOP);
781 break;
782 case EC_OP_SERVER_REMOVE:
783 if ( srv ) {
784 theApp->serverlist->RemoveServer(srv);
785 response = new CECPacket(EC_OP_NOOP);
786 } else {
787 response = new CECPacket(EC_OP_FAILED);
788 response->AddTag(CECTag(EC_TAG_STRING,
789 wxTRANSLATE("need to define server to be removed")));
791 break;
792 case EC_OP_SERVER_CONNECT:
793 if (thePrefs::GetNetworkED2K()) {
794 if ( srv ) {
795 theApp->serverconnect->ConnectToServer(srv);
796 response = new CECPacket(EC_OP_NOOP);
797 } else {
798 theApp->serverconnect->ConnectToAnyServer();
799 response = new CECPacket(EC_OP_NOOP);
801 } else {
802 response = new CECPacket(EC_OP_FAILED);
803 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
805 break;
807 if (!response) {
808 response = new CECPacket(EC_OP_FAILED);
809 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
811 return response;
814 CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
816 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
818 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
820 // request can contain list of queried items
821 CTagSet<CMD4Hash, EC_TAG_SEARCHFILE> queryitems(request);
823 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
824 CSearchResultList::const_iterator it = list.begin();
825 while (it != list.end()) {
826 CSearchFile* sf = *it++;
827 if ( !queryitems.empty() && !queryitems.count(sf->GetFileHash()) ) {
828 continue;
830 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
832 return response;
835 CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
837 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
839 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
840 CSearchResultList::const_iterator it = list.begin();
841 while (it != list.end()) {
842 CSearchFile* sf = *it++;
843 CValueMap &valuemap = tagmap.GetValueMap(sf);
844 response->AddTag(CEC_SearchFile_Tag(sf, valuemap));
846 return response;
849 CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
851 CECPacket *response = new CECPacket(EC_OP_STRINGS);
852 for (unsigned int i = 0;i < request->GetTagCount();i++) {
853 const CECTag *tag = request->GetTagByIndex(i);
854 CMD4Hash hash = tag->GetMD4Data();
855 uint8 category = tag->GetTagByIndexSafe(0)->GetInt();
856 theApp->searchlist->AddFileToDownloadByHash(hash, category);
858 return response;
861 CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
863 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
864 theApp->searchlist->StopGlobalSearch();
865 return reply;
868 CECPacket *Get_EC_Response_Search(const CECPacket *request)
870 wxString response;
872 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetTagByIndex(0);
873 theApp->searchlist->RemoveResults(0xffffffff);
875 CSearchList::CSearchParams params;
876 params.searchString = search_request->SearchText();
877 params.typeText = search_request->SearchFileType();
878 params.extension = search_request->SearchExt();
879 params.minSize = search_request->MinSize();
880 params.maxSize = search_request->MaxSize();
881 params.availability = search_request->Avail();
884 EC_SEARCH_TYPE search_type = search_request->SearchType();
885 SearchType core_search_type = LocalSearch;
886 switch (search_type) {
887 case EC_SEARCH_GLOBAL:
888 core_search_type = GlobalSearch;
889 case EC_SEARCH_KAD:
890 if (core_search_type != GlobalSearch) { // Not a global search obviously
891 core_search_type = KadSearch;
893 case EC_SEARCH_LOCAL: {
894 uint32 search_id = 0xffffffff;
895 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
896 if (!error.IsEmpty()) {
897 response = error;
898 } else {
899 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
901 break;
903 case EC_SEARCH_WEB:
904 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
905 break;
908 CECPacket *reply = new CECPacket(EC_OP_FAILED);
909 // error or search in progress
910 reply->AddTag(CECTag(EC_TAG_STRING, response));
912 return reply;
915 CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
917 CECPacket *response = new CECPacket(EC_OP_NOOP);
918 for (unsigned int i = 0;i < request->GetTagCount();i++) {
919 const CECTag *tag = request->GetTagByIndex(i);
920 CMD4Hash hash = tag->GetMD4Data();
921 uint8 prio = tag->GetTagByIndexSafe(0)->GetInt();
922 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
923 if ( !cur_file ) {
924 continue;
926 if (prio == PR_AUTO) {
927 cur_file->SetAutoUpPriority(1);
928 cur_file->UpdateAutoUpPriority();
929 } else {
930 cur_file->SetAutoUpPriority(0);
931 cur_file->SetUpPriority(prio);
935 return response;
938 CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
940 CECPacket *response;
941 if (thePrefs::GetNetworkKademlia()) {
942 response = new CECPacket(EC_OP_NOOP);
943 if ( !Kademlia::CKademlia::IsRunning() ) {
944 Kademlia::CKademlia::Start();
945 theApp->ShowConnectionState();
947 const CECTag *addrtag = request->GetTagByIndex(0);
948 if ( addrtag ) {
949 uint32 ip = addrtag->GetIPv4Data().IP();
950 uint16 port = addrtag->GetIPv4Data().m_port;
951 Kademlia::CKademlia::Bootstrap(ip, port, true);
953 } else {
954 response = new CECPacket(EC_OP_FAILED);
955 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
958 return response;
961 // init with some default size
962 CPartFile_Encoder::GapBuffer CPartFile_Encoder::m_gap_buffer(128);
964 // encoder side
965 CPartFile_Encoder::CPartFile_Encoder(CPartFile *file) :
966 m_enc_data(file->GetPartCount(), file->GetGapList().size() * 2)
968 m_file = file;
971 // decoder side
972 CPartFile_Encoder::CPartFile_Encoder(int size): m_enc_data(size, 0)
974 m_file = 0;
977 CPartFile_Encoder::~CPartFile_Encoder()
981 // stl side :)
982 CPartFile_Encoder::CPartFile_Encoder()
984 m_file = 0;
987 CPartFile_Encoder::CPartFile_Encoder(const CPartFile_Encoder &obj) : m_enc_data(obj.m_enc_data)
989 m_file = obj.m_file;
992 CPartFile_Encoder &CPartFile_Encoder::operator=(const CPartFile_Encoder &obj)
994 m_file = obj.m_file;
995 m_enc_data = obj.m_enc_data;
996 return *this;
999 void CPartFile_Encoder::Encode(CECTag *parent)
1001 const CGapList& gaplist = m_file->GetNewGapList();
1002 const size_t gap_list_size = gaplist.size();
1004 if ( m_gap_buffer.size() < gap_list_size * 2 ) {
1005 m_gap_buffer.clear();
1006 m_gap_buffer.resize(gap_list_size * 2);
1009 GapBuffer::iterator it = m_gap_buffer.begin();
1011 for (CGapList::const_iterator curr_pos = gaplist.begin(); curr_pos != gaplist.end(); ++curr_pos) {
1012 *it++ = ENDIAN_HTONLL(curr_pos.start());
1013 *it++ = ENDIAN_HTONLL(curr_pos.end());
1016 m_enc_data.m_gap_status.Realloc(gap_list_size*2*sizeof(uint64));
1017 int gap_enc_size = 0;
1018 const unsigned char *gap_enc_data = m_enc_data.m_gap_status.Encode((unsigned char *)&m_gap_buffer[0], gap_enc_size);
1020 int part_enc_size;
1021 const unsigned char *part_enc_data = m_enc_data.m_part_status.Encode(m_file->m_SrcpartFrequency, part_enc_size);
1024 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1027 // Put data inside of tag in following order:
1028 // [num_of_gaps] [gap_enc_data]
1030 unsigned char *tagdata;
1031 CECTag etag(EC_TAG_PARTFILE_GAP_STATUS,
1032 sizeof(uint32) + gap_enc_size, (void **)&tagdata);
1034 // real number of gaps - so remote size can realloc
1035 RawPokeUInt32( tagdata, ENDIAN_HTONL( gap_list_size ) );
1036 tagdata += sizeof(uint32);
1037 memcpy(tagdata, gap_enc_data, gap_enc_size);
1039 parent->AddTag(etag);
1041 it = m_gap_buffer.begin();
1043 const CPartFile::CReqBlockPtrList& requestedblocks = m_file->GetRequestedBlockList();
1044 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1046 wxASSERT(m_gap_buffer.size() >= requestedblocks.size() * 2);
1047 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1048 Requested_Block_Struct* block = *curr_pos2;
1049 *it++ = ENDIAN_HTONLL(block->StartOffset);
1050 *it++ = ENDIAN_HTONLL(block->EndOffset);
1052 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS,
1053 requestedblocks.size() * 2 * sizeof(uint64), (void *)&m_gap_buffer[0]));
1056 // encoder side
1057 CKnownFile_Encoder::CKnownFile_Encoder(CKnownFile *file) :
1058 m_enc_data(file->GetPartCount(), true)
1060 m_file = file;
1063 CKnownFile_Encoder::CKnownFile_Encoder()
1065 m_file = 0;
1068 CKnownFile_Encoder::~CKnownFile_Encoder()
1072 CKnownFile_Encoder::CKnownFile_Encoder(const CKnownFile_Encoder &obj) : m_enc_data(obj.m_enc_data)
1074 m_file = obj.m_file;
1077 CKnownFile_Encoder &CKnownFile_Encoder::operator=(const CKnownFile_Encoder &obj)
1079 m_file = obj.m_file;
1080 m_enc_data = obj.m_enc_data;
1081 return *this;
1084 void CKnownFile_Encoder::Encode(CECTag *parent)
1086 int part_enc_size;
1087 const unsigned char *part_enc_data = m_enc_data.Encode(m_file->m_AvailPartFrequency, part_enc_size);
1089 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1092 CECPacket *GetStatsGraphs(const CECPacket *request)
1094 CECPacket *response = NULL;
1096 switch (request->GetDetailLevel()) {
1097 case EC_DETAIL_WEB:
1098 case EC_DETAIL_FULL: {
1099 double dTimestamp = 0.0;
1100 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1101 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1103 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1104 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1105 uint32 *graphData;
1106 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1107 if (numPoints) {
1108 response = new CECPacket(EC_OP_STATSGRAPHS);
1109 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1110 delete [] graphData;
1111 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1112 } else {
1113 response = new CECPacket(EC_OP_FAILED);
1114 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1116 break;
1118 case EC_DETAIL_INC_UPDATE:
1119 case EC_DETAIL_UPDATE:
1120 case EC_DETAIL_CMD:
1121 // No graphs
1122 response = new CECPacket(EC_OP_FAILED);
1123 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1124 break;
1126 if (!response) {
1127 response = new CECPacket(EC_OP_FAILED);
1128 // Unknown reason
1131 return response;
1134 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request,
1135 CPartFile_Encoder_Map &enc_part_map, CKnownFile_Encoder_Map &enc_shared_map, CObjTagMap &objmap)
1138 if ( !request ) {
1139 return 0;
1142 CECPacket *response = NULL;
1144 switch (request->GetOpCode()) {
1146 // Misc commands
1148 case EC_OP_SHUTDOWN:
1149 if (!theApp->IsOnShutDown()) {
1150 response = new CECPacket(EC_OP_NOOP);
1151 AddLogLineM(true, _("External Connection: shutdown requested"));
1152 #ifndef AMULE_DAEMON
1154 wxCloseEvent evt;
1155 evt.SetCanVeto(false);
1156 theApp->ShutDown(evt);
1158 #else
1159 theApp->ExitMainLoop();
1160 #endif
1161 } else {
1162 response = new CECPacket(EC_OP_FAILED);
1163 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1165 break;
1166 case EC_OP_ADD_LINK:
1167 for(unsigned int i = 0; i < request->GetTagCount();i++) {
1168 const CECTag *tag = request->GetTagByIndex(i);
1169 wxString link = tag->GetStringData();
1170 int category = tag->GetTagByIndexSafe(0)->GetInt();
1171 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link);
1172 if ( theApp->downloadqueue->AddLink(link, category) ) {
1173 response = new CECPacket(EC_OP_NOOP);
1174 } else {
1175 // Error messages are printed by the add function.
1176 response = new CECPacket(EC_OP_FAILED);
1177 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1180 break;
1182 // Status requests
1184 case EC_OP_STAT_REQ:
1185 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1186 break;
1187 case EC_OP_GET_CONNSTATE:
1188 if (!response) {
1189 response = new CECPacket(EC_OP_MISC_DATA);
1191 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1192 break;
1196 case EC_OP_GET_SHARED_FILES:
1197 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1198 response = Get_EC_Response_GetSharedFiles(enc_shared_map, objmap);
1199 } else {
1200 response = Get_EC_Response_GetSharedFiles(request, enc_shared_map);
1202 break;
1203 case EC_OP_GET_DLOAD_QUEUE:
1204 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1205 response = Get_EC_Response_GetDownloadQueue(enc_part_map, objmap);
1206 } else {
1207 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map);
1209 break;
1210 // transmit source names and comments only if file detail dialog is open
1211 case EC_OP_GET_DLOAD_QUEUE_DETAIL:
1212 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1213 response = Get_EC_Response_GetDownloadQueue(enc_part_map, objmap);
1214 } else {
1215 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map, true);
1217 break;
1218 case EC_OP_GET_ULOAD_QUEUE:
1219 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1220 response = Get_EC_Response_GetUpQueue(objmap);
1221 } else {
1222 response = Get_EC_Response_GetUpQueue(request);
1224 break;
1225 case EC_OP_GET_WAIT_QUEUE:
1226 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1227 response = Get_EC_Response_GetWaitQueue(objmap);
1228 } else {
1229 response = Get_EC_Response_GetWaitQueue(request);
1231 break;
1232 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1233 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1234 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1235 case EC_OP_PARTFILE_CLEANUP_SOURCES:
1236 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1237 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1238 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1239 case EC_OP_PARTFILE_PAUSE:
1240 case EC_OP_PARTFILE_RESUME:
1241 case EC_OP_PARTFILE_STOP:
1242 case EC_OP_PARTFILE_PRIO_SET:
1243 case EC_OP_PARTFILE_DELETE:
1244 case EC_OP_PARTFILE_SET_CAT:
1245 response = Get_EC_Response_PartFile_Cmd(request);
1246 break;
1247 case EC_OP_SHAREDFILES_RELOAD:
1248 theApp->sharedfiles->Reload();
1249 response = new CECPacket(EC_OP_NOOP);
1250 break;
1251 case EC_OP_SHARED_SET_PRIO:
1252 response = Get_EC_Response_Set_SharedFile_Prio(request);
1253 break;
1254 case EC_OP_RENAME_FILE: {
1255 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1256 CKnownFile* file = theApp->knownfiles->FindKnownFileByID(fileHash);
1257 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1258 if (!file) {
1259 file = theApp->downloadqueue->GetFileByID(fileHash);
1261 if (!file) {
1262 response = new CECPacket(EC_OP_FAILED);
1263 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1264 break;
1266 if (newName.IsEmpty()) {
1267 response = new CECPacket(EC_OP_FAILED);
1268 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1269 break;
1272 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1273 response = new CECPacket(EC_OP_NOOP);
1274 } else {
1275 response = new CECPacket(EC_OP_FAILED);
1276 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1279 break;
1284 // Server commands
1286 case EC_OP_SERVER_ADD:
1287 response = Get_EC_Response_Server_Add(request);
1288 break;
1289 case EC_OP_SERVER_DISCONNECT:
1290 case EC_OP_SERVER_CONNECT:
1291 case EC_OP_SERVER_REMOVE:
1292 response = Get_EC_Response_Server(request);
1293 break;
1294 case EC_OP_GET_SERVER_LIST: {
1295 response = new CECPacket(EC_OP_SERVER_LIST);
1296 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1297 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1298 for (
1299 std::vector<const CServer*>::const_iterator it = servers.begin();
1300 it != servers.end();
1301 ++it
1303 response->AddTag(CEC_Server_Tag(*it, detail_level));
1306 break;
1307 case EC_OP_SERVER_UPDATE_FROM_URL: {
1308 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1310 // Save the new url, and update the UI (if not amuled).
1311 Notify_ServersURLChanged(url);
1312 thePrefs::SetEd2kServersUrl(url);
1314 theApp->serverlist->UpdateServerMetFromURL(url);
1315 response = new CECPacket(EC_OP_NOOP);
1316 break;
1319 // IPFilter
1321 case EC_OP_IPFILTER_RELOAD:
1322 theApp->ipfilter->Reload();
1323 response = new CECPacket(EC_OP_NOOP);
1324 break;
1326 // Search
1328 case EC_OP_SEARCH_START:
1329 response = Get_EC_Response_Search(request);
1330 break;
1332 case EC_OP_SEARCH_STOP:
1333 response = Get_EC_Response_Search_Stop(request);
1334 break;
1336 case EC_OP_SEARCH_RESULTS:
1337 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1338 response = Get_EC_Response_Search_Results(objmap);
1339 } else {
1340 response = Get_EC_Response_Search_Results(request);
1342 break;
1344 case EC_OP_SEARCH_PROGRESS:
1345 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1346 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1347 theApp->searchlist->GetSearchProgress()));
1348 break;
1350 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1351 response = Get_EC_Response_Search_Results_Download(request);
1352 break;
1354 // Preferences
1356 case EC_OP_GET_PREFERENCES:
1357 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1358 break;
1359 case EC_OP_SET_PREFERENCES:
1360 ((CEC_Prefs_Packet *)request)->Apply();
1361 theApp->glob_prefs->Save();
1362 if (thePrefs::IsFilteringClients()) {
1363 theApp->clientlist->FilterQueues();
1365 if (thePrefs::IsFilteringServers()) {
1366 theApp->serverlist->FilterServers();
1368 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1369 theApp->DisconnectED2K();
1371 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1372 theApp->StopKad();
1374 response = new CECPacket(EC_OP_NOOP);
1375 break;
1377 case EC_OP_CREATE_CATEGORY:
1378 if ( request->GetTagCount() == 1 ) {
1379 ((CEC_Category_Tag *)request->GetTagByIndex(0))->Create();
1380 Notify_CategoryAdded();
1382 response = new CECPacket(EC_OP_NOOP);
1383 break;
1384 case EC_OP_UPDATE_CATEGORY:
1385 if ( request->GetTagCount() == 1 ) {
1386 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetTagByIndex(0);
1387 tag->Apply();
1388 Notify_CategoryUpdate(tag->GetInt());
1390 response = new CECPacket(EC_OP_NOOP);
1391 break;
1392 case EC_OP_DELETE_CATEGORY:
1393 if ( request->GetTagCount() == 1 ) {
1394 uint32 cat = request->GetTagByIndex(0)->GetInt();
1395 Notify_CategoryDelete(cat);
1397 response = new CECPacket(EC_OP_NOOP);
1398 break;
1401 // Logging
1403 case EC_OP_ADDLOGLINE:
1404 AddLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1405 response = new CECPacket(EC_OP_NOOP);
1406 break;
1407 case EC_OP_ADDDEBUGLOGLINE:
1408 AddDebugLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1409 response = new CECPacket(EC_OP_NOOP);
1410 break;
1411 case EC_OP_GET_LOG:
1412 response = new CECPacket(EC_OP_LOG);
1413 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1414 break;
1415 case EC_OP_GET_DEBUGLOG:
1416 response = new CECPacket(EC_OP_DEBUGLOG);
1417 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1418 break;
1419 case EC_OP_RESET_LOG:
1420 theApp->GetLog(true);
1421 response = new CECPacket(EC_OP_NOOP);
1422 break;
1423 case EC_OP_RESET_DEBUGLOG:
1424 theApp->GetDebugLog(true);
1425 response = new CECPacket(EC_OP_NOOP);
1426 break;
1427 case EC_OP_GET_LAST_LOG_ENTRY:
1429 wxString tmp = theApp->GetLog(false);
1430 if (tmp.Last() == '\n') {
1431 tmp.RemoveLast();
1433 response = new CECPacket(EC_OP_LOG);
1434 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1436 break;
1437 case EC_OP_GET_SERVERINFO:
1438 response = new CECPacket(EC_OP_SERVERINFO);
1439 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1440 break;
1441 case EC_OP_CLEAR_SERVERINFO:
1442 theApp->GetServerLog(true);
1443 response = new CECPacket(EC_OP_NOOP);
1444 break;
1446 // Statistics
1448 case EC_OP_GET_STATSGRAPHS:
1449 response = GetStatsGraphs(request);
1450 break;
1451 case EC_OP_GET_STATSTREE: {
1452 theApp->m_statistics->UpdateStatsTree();
1453 response = new CECPacket(EC_OP_STATSTREE);
1454 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1455 if (tree) {
1456 response->AddTag(*tree);
1457 delete tree;
1459 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1460 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1461 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1463 break;
1467 // Kad
1469 case EC_OP_KAD_START:
1470 response = Get_EC_Response_Kad_Connect(request);
1471 break;
1472 case EC_OP_KAD_STOP:
1473 theApp->StopKad();
1474 response = new CECPacket(EC_OP_NOOP);
1475 break;
1476 case EC_OP_KAD_UPDATE_FROM_URL: {
1477 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1479 // Save the new url, and update the UI (if not amuled).
1480 Notify_NodesURLChanged(url);
1481 thePrefs::SetKadNodesUrl(url);
1483 theApp->UpdateNotesDat(url);
1484 response = new CECPacket(EC_OP_NOOP);
1485 break;
1487 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1488 theApp->BootstrapKad(request->GetTagByIndexSafe(0)->GetInt(),
1489 request->GetTagByIndexSafe(1)->GetInt());
1490 response = new CECPacket(EC_OP_NOOP);
1491 break;
1494 // Networks
1496 case EC_OP_CONNECT:
1497 if (thePrefs::GetNetworkED2K()) {
1498 response = new CECPacket(EC_OP_STRINGS);
1499 if (theApp->IsConnectedED2K()) {
1500 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1501 } else {
1502 theApp->serverconnect->ConnectToAnyServer();
1503 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1506 if (thePrefs::GetNetworkKademlia()) {
1507 if (!response) {
1508 response = new CECPacket(EC_OP_STRINGS);
1510 if (theApp->IsConnectedKad()) {
1511 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1512 } else {
1513 theApp->StartKad();
1514 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1517 if (!response) {
1518 response = new CECPacket(EC_OP_FAILED);
1519 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1521 break;
1522 case EC_OP_DISCONNECT:
1523 if (theApp->IsConnected()) {
1524 response = new CECPacket(EC_OP_STRINGS);
1525 if (theApp->IsConnectedED2K()) {
1526 theApp->serverconnect->Disconnect();
1527 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1529 if (theApp->IsConnectedKad()) {
1530 theApp->StopKad();
1531 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1533 } else {
1534 response = new CECPacket(EC_OP_NOOP);
1536 break;
1538 default:
1539 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1540 wxFAIL;
1541 response = new CECPacket(EC_OP_FAILED);
1542 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1543 break;
1545 return response;
1549 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1553 * Core general status
1555 ECStatusMsgSource::ECStatusMsgSource()
1557 m_last_ed2k_status_sent = 0xffffffff;
1558 m_last_kad_status_sent = 0xffffffff;
1559 m_server = (void *)0xffffffff;
1562 uint32 ECStatusMsgSource::GetEd2kStatus()
1564 if ( theApp->IsConnectedED2K() ) {
1565 return theApp->GetED2KID();
1566 } else if ( theApp->serverconnect->IsConnecting() ) {
1567 return 1;
1568 } else {
1569 return 0;
1573 uint32 ECStatusMsgSource::GetKadStatus()
1575 if ( theApp->IsConnectedKad() ) {
1576 return 1;
1577 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1578 return 2;
1579 } else if ( Kademlia::CKademlia::IsRunning() ) {
1580 return 3;
1582 return 0;
1585 CECPacket *ECStatusMsgSource::GetNextPacket()
1587 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1588 (m_last_kad_status_sent != GetKadStatus()) ||
1589 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1591 m_last_ed2k_status_sent = GetEd2kStatus();
1592 m_last_kad_status_sent = GetKadStatus();
1593 m_server = theApp->serverconnect->GetCurrentServer();
1595 CECPacket *response = new CECPacket(EC_OP_STATS);
1596 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1597 return response;
1599 return 0;
1603 * Downloading files
1605 ECPartFileMsgSource::ECPartFileMsgSource()
1607 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1608 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1609 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1610 m_dirty_status[cur_file->GetFileHash()] = status;
1614 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1616 CMD4Hash filehash = file->GetFileHash();
1617 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1618 m_dirty_status[filehash].m_dirty = true;;
1622 void ECPartFileMsgSource::SetNew(CPartFile *file)
1624 CMD4Hash filehash = file->GetFileHash();
1625 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1626 PARTFILE_STATUS status = { true, false, false, false, true, file };
1627 m_dirty_status[filehash] = status;
1630 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1632 CMD4Hash filehash = file->GetFileHash();
1633 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1635 m_dirty_status[filehash].m_finished = true;
1638 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1640 CMD4Hash filehash = file->GetFileHash();
1641 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1643 m_dirty_status[filehash].m_removed = true;
1646 CECPacket *ECPartFileMsgSource::GetNextPacket()
1648 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1649 it != m_dirty_status.end(); it++) {
1650 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1651 CMD4Hash filehash = it->first;
1653 CPartFile *partfile = it->second.m_file;
1655 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1656 if ( it->second.m_removed ) {
1657 CECTag tag(EC_TAG_PARTFILE, filehash);
1658 packet->AddTag(tag);
1659 m_dirty_status.erase(it);
1660 } else {
1661 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1662 packet->AddTag(tag);
1664 m_dirty_status[filehash].m_new = false;
1665 m_dirty_status[filehash].m_dirty = false;
1667 return packet;
1670 return 0;
1674 * Shared files - similar to downloading
1676 ECKnownFileMsgSource::ECKnownFileMsgSource()
1678 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1679 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1680 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1681 m_dirty_status[cur_file->GetFileHash()] = status;
1685 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1687 CMD4Hash filehash = file->GetFileHash();
1688 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1689 m_dirty_status[filehash].m_dirty = true;;
1693 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1695 CMD4Hash filehash = file->GetFileHash();
1696 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1697 KNOWNFILE_STATUS status = { true, false, false, true, file };
1698 m_dirty_status[filehash] = status;
1701 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1703 CMD4Hash filehash = file->GetFileHash();
1704 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1706 m_dirty_status[filehash].m_removed = true;
1709 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1711 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1712 it != m_dirty_status.end(); it++) {
1713 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1714 CMD4Hash filehash = it->first;
1716 CKnownFile *partfile = it->second.m_file;
1718 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1719 if ( it->second.m_removed ) {
1720 CECTag tag(EC_TAG_PARTFILE, filehash);
1721 packet->AddTag(tag);
1722 m_dirty_status.erase(it);
1723 } else {
1724 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1725 packet->AddTag(tag);
1727 m_dirty_status[filehash].m_new = false;
1728 m_dirty_status[filehash].m_dirty = false;
1730 return packet;
1733 return 0;
1737 * Notification about search status
1739 ECSearchMsgSource::ECSearchMsgSource()
1743 CECPacket *ECSearchMsgSource::GetNextPacket()
1745 if ( m_dirty_status.empty() ) {
1746 return 0;
1749 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1750 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1751 it != m_dirty_status.end(); it++) {
1753 if ( it->second.m_new ) {
1754 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1755 it->second.m_new = false;
1756 } else if ( it->second.m_dirty ) {
1757 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1762 return response;
1765 void ECSearchMsgSource::FlushStatus()
1767 m_dirty_status.clear();
1770 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1772 if ( m_dirty_status.count(file->GetFileHash()) ) {
1773 m_dirty_status[file->GetFileHash()].m_dirty = true;
1774 } else {
1775 m_dirty_status[file->GetFileHash()].m_new = true;
1776 m_dirty_status[file->GetFileHash()].m_dirty = true;
1777 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1778 m_dirty_status[file->GetFileHash()].m_file = file;
1782 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1784 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1788 * Notification about uploading clients
1790 CECPacket *ECClientMsgSource::GetNextPacket()
1792 return 0;
1796 // Notification iface per-client
1798 ECNotifier::ECNotifier()
1802 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1804 CECPacket *packet = 0;
1806 // priority 0 is highest
1808 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1809 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1810 break;
1813 return packet;
1816 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1819 // OnOutput is called for a first time before
1820 // socket is registered
1822 if ( m_msg_source.count(sock) ) {
1823 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1824 if ( !notifier_array ) {
1825 return 0;
1827 CECPacket *packet = GetNextPacket(notifier_array);
1828 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1829 return packet;
1830 } else {
1831 return 0;
1836 // Interface to notification macros
1838 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
1840 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1841 i != m_msg_source.end(); i++) {
1842 CECServerSocket *sock = i->first;
1843 if ( sock->HaveNotificationSupport() ) {
1844 ECUpdateMsgSource **notifier_array = i->second;
1845 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
1848 NextPacketToSocket();
1851 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
1853 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1854 i != m_msg_source.end(); i++) {
1855 ECUpdateMsgSource **notifier_array = i->second;
1856 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
1858 NextPacketToSocket();
1861 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
1863 // per-partfile source list is not supported (yet), and IMHO quite useless
1866 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
1868 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1869 i != m_msg_source.end(); i++) {
1870 ECUpdateMsgSource **notifier_array = i->second;
1871 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
1873 NextPacketToSocket();
1876 void ECNotifier::DownloadFile_AddSource(CPartFile *)
1878 // per-partfile source list is not supported (yet), and IMHO quite useless
1881 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
1883 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1884 i != m_msg_source.end(); i++) {
1885 ECUpdateMsgSource **notifier_array = i->second;
1886 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
1888 NextPacketToSocket();
1891 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
1893 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1894 i != m_msg_source.end(); i++) {
1895 ECUpdateMsgSource **notifier_array = i->second;
1896 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
1898 NextPacketToSocket();
1901 void ECNotifier::SharedFile_RemoveAllFiles()
1903 // need to figure out what to do here
1906 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
1908 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
1909 notifier_array[EC_STATUS] = new ECStatusMsgSource();
1910 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
1911 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
1912 notifier_array[EC_CLIENT] = new ECClientMsgSource();
1913 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
1915 m_msg_source[sock] = notifier_array;
1918 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
1920 if (m_msg_source.count(sock)) {
1921 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1923 m_msg_source.erase(sock);
1925 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1926 delete notifier_array[i];
1928 delete [] notifier_array;
1932 void ECNotifier::NextPacketToSocket()
1934 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1935 i != m_msg_source.end(); i++) {
1936 CECServerSocket *sock = i->first;
1937 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
1938 ECUpdateMsgSource **notifier_array = i->second;
1939 CECPacket *packet = GetNextPacket(notifier_array);
1940 if ( packet ) {
1941 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
1942 sock->SendPacket(packet);
1948 // File_checked_for_headers