Upstream tarball 9964
[amule.git] / src / ExternalConn.cpp
blob8824e54a2f361db8733fff320d46390a0ceb7e8c
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();
256 void ExternalConn::OnServerEvent(wxSocketEvent& WXUNUSED(event))
258 CECServerSocket *sock = new CECServerSocket(m_ec_notifier);
259 // Accept new connection if there is one in the pending
260 // connections queue, else exit. We use Accept(FALSE) for
261 // non-blocking accept (although if we got here, there
262 // should ALWAYS be a pending connection).
263 if ( m_ECServer->AcceptWith(*sock, false) ) {
264 AddLogLineM(false, _("New external connection accepted"));
265 } else {
266 delete sock;
267 AddLogLineM(false, _("ERROR: couldn't accept a new external connection"));
273 // Authentication
275 const CECPacket *CECServerSocket::Authenticate(const CECPacket *request)
277 CECPacket *response;
279 if (request == NULL) {
280 response = new CECPacket(EC_OP_AUTH_FAIL);
281 return response;
284 // Password must be specified if we are to allow remote connections
285 if ( thePrefs::ECPassword().IsEmpty() ) {
286 AddLogLineM(true, _("External connection refused due to empty password in preferences!"));
288 return new CECPacket(EC_OP_AUTH_FAIL);
291 if ((m_conn_state == CONN_INIT) && (request->GetOpCode() == EC_OP_AUTH_REQ) ) {
292 const CECTag *clientName = request->GetTagByName(EC_TAG_CLIENT_NAME);
293 const CECTag *clientVersion = request->GetTagByName(EC_TAG_CLIENT_VERSION);
295 AddLogLineM(false, CFormat( _("Connecting client: %s %s") )
296 % ( clientName ? clientName->GetStringData() : wxString(_("Unknown")) )
297 % ( clientVersion ? clientVersion->GetStringData() : wxString(_("Unknown version")) ) );
298 const CECTag *protocol = request->GetTagByName(EC_TAG_PROTOCOL_VERSION);
299 #ifdef EC_VERSION_ID
300 // For SVN versions, both client and server must use SVNDATE, and they must be the same
301 CMD4Hash vhash;
302 if (!vhash.Decode(wxT(EC_VERSION_ID))) {
303 response = new CECPacket(EC_OP_AUTH_FAIL);
304 response->AddTag(CECTag(EC_TAG_STRING, wxT("Fatal error, version hash is not a valid MD4-hash.")));
305 } else if (!request->GetTagByName(EC_TAG_VERSION_ID) || request->GetTagByNameSafe(EC_TAG_VERSION_ID)->GetMD4Data() != vhash) {
306 response = new CECPacket(EC_OP_AUTH_FAIL);
307 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
308 #else
309 // For release versions, we don't want to allow connections from any arbitrary SVN client.
310 if (request->GetTagByName(EC_TAG_VERSION_ID)) {
311 response = new CECPacket(EC_OP_AUTH_FAIL);
312 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("You cannot connect to a release version from an arbitrary SVN version! *sigh* possible crash prevented")));
313 #endif
314 } else if (protocol != NULL) {
315 uint16 proto_version = protocol->GetInt();
316 if (proto_version == EC_CURRENT_PROTOCOL_VERSION) {
317 response = new CECPacket(EC_OP_AUTH_SALT);
318 response->AddTag(CECTag(EC_TAG_PASSWD_SALT, m_passwd_salt));
319 m_conn_state = CONN_SALT_SENT;
320 } else {
321 response = new CECPacket(EC_OP_AUTH_FAIL);
322 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid protocol version.") + wxString::Format(wxT("( %i != %i )"),proto_version,EC_CURRENT_PROTOCOL_VERSION)));
324 } else {
325 response = new CECPacket(EC_OP_AUTH_FAIL);
326 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Missing protocol version tag.")));
328 } else if ((m_conn_state == CONN_SALT_SENT) && (request->GetOpCode() == EC_OP_AUTH_PASSWD)) {
329 const CECTag *passwd = request->GetTagByName(EC_TAG_PASSWD_HASH);
330 CMD4Hash passh;
332 if (!passh.Decode(thePrefs::ECPassword())) {
333 AddLogLineM(false, wxT("EC Auth failed, invalid hash specificed as EC password: ") + thePrefs::ECPassword());
334 response = new CECPacket(EC_OP_AUTH_FAIL);
335 response->AddTag(CECTag(EC_TAG_STRING, wxT("Authentication failed, invalid hash specified as EC password.")));
336 } else {
337 wxString saltHash = MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt).GetHash();
338 wxString saltStr = CFormat(wxT("%lX")) % m_passwd_salt;
340 passh.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash).GetHash());
342 if (passwd && passwd->GetMD4Data() == passh) {
343 response = new CECPacket(EC_OP_AUTH_OK);
344 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
345 } else {
346 if (passwd) {
347 AddLogLineM(false, wxT("EC Auth failed: (") + passwd->GetMD4Data().Encode() + wxT(" != ") + passh.Encode() + wxT(")."));
348 } else {
349 AddLogLineM(false, wxT("EC Auth failed. Password tag missing."));
352 response = new CECPacket(EC_OP_AUTH_FAIL);
353 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Authentication failed.")));
356 } else {
357 response = new CECPacket(EC_OP_AUTH_FAIL);
358 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid request, please authenticate first.")));
361 if (response->GetOpCode() == EC_OP_AUTH_OK) {
362 m_conn_state = CONN_ESTABLISHED;
363 AddLogLineM(false, _("Access granted."));
364 } else if (response->GetTagByIndex(0)->IsString()) {
365 AddLogLineM(false, wxGetTranslation(response->GetTagByIndex(0)->GetStringData()));
368 return response;
371 // Make a Logger tag (if there are any logging messages) and add it to the response
372 static void AddLoggerTag(CECPacket *response, CLoggerAccess &LoggerAccess)
374 if (LoggerAccess.HasString()) {
375 CECEmptyTag tag(EC_TAG_STATS_LOGGER_MESSAGE);
376 // Tag structure is fix: tag carries nothing, inside are the strings
377 // maximum of 200 log lines per message
378 int entries = 0;
379 wxString line;
380 while (entries < 200 && LoggerAccess.GetString(line)) {
381 tag.AddTag(CECTag(EC_TAG_STRING, line));
382 entries++;
384 response->AddTag(tag);
385 //printf("send Log tag %d %d\n", FirstEntry, entries);
389 static CECPacket *Get_EC_Response_StatRequest(const CECPacket *request, CLoggerAccess &LoggerAccess)
391 CECPacket *response = new CECPacket(EC_OP_STATS);
393 switch (request->GetDetailLevel()) {
394 case EC_DETAIL_FULL:
395 response->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD, (uint32)theStats::GetUpOverheadRate()));
396 response->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD, (uint32)theStats::GetDownOverheadRate()));
397 response->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT, /*(uint32)*/theStats::GetBannedCount()));
398 AddLoggerTag(response, LoggerAccess);
399 case EC_DETAIL_WEB:
400 case EC_DETAIL_CMD:
401 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED, (uint32)theStats::GetUploadRate()));
402 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED, (uint32)(theStats::GetDownloadRate())));
403 response->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxUpload()*1024.0)));
404 response->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT, (uint32)(thePrefs::GetMaxDownload()*1024.0)));
405 response->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN, /*(uint32)*/theStats::GetWaitingUserCount()));
406 response->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT, /*(uint32)*/theStats::GetFoundSources()));
407 // User/Filecounts
409 uint32 totaluser = 0, totalfile = 0;
410 theApp->serverlist->GetUserFileStatus( totaluser, totalfile );
411 response->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS, totaluser));
412 response->AddTag(CECTag(EC_TAG_STATS_KAD_USERS, Kademlia::CKademlia::GetKademliaUsers()));
413 response->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES, totalfile));
414 response->AddTag(CECTag(EC_TAG_STATS_KAD_FILES, Kademlia::CKademlia::GetKademliaFiles()));
416 // Kad stats
417 if (Kademlia::CKademlia::IsConnected()) {
418 response->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
419 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource));
420 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword));
421 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes));
422 response->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad));
423 response->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
424 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS, theApp->clientlist->GetBuddyStatus()));
425 uint32 BuddyIP = 0;
426 uint16 BuddyPort = 0;
427 CUpDownClient * Buddy = theApp->clientlist->GetBuddy();
428 if (Buddy) {
429 BuddyIP = Buddy->GetIP();
430 BuddyPort = Buddy->GetUDPPort();
432 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP, BuddyIP));
433 response->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT, BuddyPort));
435 case EC_DETAIL_UPDATE:
436 case EC_DETAIL_INC_UPDATE:
437 break;
440 return response;
443 static CECPacket *Get_EC_Response_GetSharedFiles(const CECPacket *request, CKnownFile_Encoder_Map &encoders)
445 wxASSERT(request->GetOpCode() == EC_OP_GET_SHARED_FILES);
447 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
449 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
451 // request can contain list of queried items
452 CTagSet<CMD4Hash, EC_TAG_KNOWNFILE> queryitems(request);
454 encoders.UpdateEncoders(theApp->sharedfiles);
456 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
457 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
459 if ( !cur_file || (!queryitems.empty() && !queryitems.count(cur_file->GetFileHash())) ) {
460 continue;
463 CEC_SharedFile_Tag filetag(cur_file, detail_level);
464 CKnownFile_Encoder &enc = encoders[cur_file];
465 if ( detail_level != EC_DETAIL_UPDATE ) {
466 enc.ResetEncoder();
468 enc.Encode(&filetag);
469 response->AddTag(filetag);
471 return response;
474 static CECPacket *Get_EC_Response_GetSharedFiles(CKnownFile_Encoder_Map &encoders, CObjTagMap &tagmap)
476 CECPacket *response = new CECPacket(EC_OP_SHARED_FILES);
478 encoders.UpdateEncoders(theApp->sharedfiles);
479 for (uint32 i = 0; i < theApp->sharedfiles->GetFileCount(); ++i) {
480 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
483 // Hashes of tags are maintained on "per-object" basis. So, in this mode only
484 // same kind of objects can go into particular query type.
485 // But files from download queue (aka partfiles) need to be listed both as downloads
486 // and as shares (with different tag content).
487 // So simply increment the object pointer - it's only a map key and never used for referencing.
489 void * mapKey = cur_file;
490 if (!cur_file) continue;
491 if (cur_file->IsPartFile()) {
492 mapKey = (void *) ((char *)mapKey + 1);
495 CValueMap &valuemap = tagmap.GetValueMap(mapKey);
496 CEC_SharedFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
497 CKnownFile_Encoder &enc = encoders[cur_file];
498 enc.Encode(&filetag);
500 response->AddTag(filetag);
502 return response;
505 static CECPacket *Get_EC_Response_GetClientQueue(const CECPacket *request, CObjTagMap &tagmap, int op)
507 CECPacket *response = new CECPacket(op);
509 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
512 // request can contain list of queried items
513 // (not for incremental update of course)
514 CTagSet<uint32, EC_TAG_CLIENT> queryitems(request);
516 std::set<uint32> idSet;
518 const CClientPtrList& clients = (op == EC_OP_WAIT_QUEUE) ? theApp->uploadqueue->GetWaitingList()
519 : theApp->uploadqueue->GetUploadingList();
520 CClientPtrList::const_iterator it = clients.begin();
521 for (; it != clients.end(); ++it) {
522 CUpDownClient* cur_client = *it;
524 if (!cur_client) { // shouldn't happen
525 continue;
527 // Sometimes clients can have the same ID. Make sure we transmit something unique.
528 uint32 id = cur_client->GetUserIDHybrid();
529 while (idSet.count(id)) {
530 id++;
532 idSet.insert(id);
534 if (!queryitems.empty() && !queryitems.count(id)) {
535 continue;
537 CValueMap *valuemap = NULL;
538 if (detail_level == EC_DETAIL_INC_UPDATE) {
539 valuemap = &tagmap.GetValueMap(cur_client);
541 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, id, valuemap);
543 response->AddTag(cli_tag);
546 return response;
550 static CECPacket *Get_EC_Response_GetDownloadQueue(CPartFile_Encoder_Map &encoders, CObjTagMap &tagmap)
552 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
554 encoders.UpdateEncoders(theApp->downloadqueue);
555 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
556 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
558 CValueMap &valuemap = tagmap.GetValueMap(cur_file);
559 CEC_PartFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, true, &valuemap);
560 CPartFile_Encoder &enc = encoders[cur_file];
561 enc.Encode(&filetag);
563 response->AddTag(filetag);
565 return response;
568 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CPartFile_Encoder_Map &encoders, bool detail = false)
570 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
572 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
574 // request can contain list of queried items
575 CTagSet<CMD4Hash, EC_TAG_PARTFILE> queryitems(request);
577 encoders.UpdateEncoders(theApp->downloadqueue);
579 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
580 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
582 if ( !queryitems.empty() && !queryitems.count(cur_file->GetFileHash()) ) {
583 continue;
586 CEC_PartFile_Tag filetag(cur_file, detail_level, detail);
588 CPartFile_Encoder &enc = encoders[cur_file];
589 if ( detail_level != EC_DETAIL_UPDATE ) {
590 enc.ResetEncoder();
592 enc.Encode(&filetag);
594 response->AddTag(filetag);
596 return response;
600 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
602 CECPacket *response = NULL;
604 // request can contain multiple files.
605 for (unsigned int i = 0; i < request->GetTagCount(); ++i) {
606 const CECTag *hashtag = request->GetTagByIndex(i);
608 wxASSERT(hashtag->GetTagName() == EC_TAG_PARTFILE);
610 CMD4Hash hash = hashtag->GetMD4Data();
611 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
613 if ( !pfile ) {
614 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
615 response = new CECPacket(EC_OP_FAILED);
616 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
617 //return response;
618 break;
620 switch (request->GetOpCode()) {
621 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
622 if ((pfile->GetStatus(false) == PS_READY) ||
623 (pfile->GetStatus(false) == PS_EMPTY)) {
624 CPartFile::SourceSet::const_iterator it = pfile->GetA4AFList().begin();
625 while ( it != pfile->GetA4AFList().end() ) {
626 CUpDownClient *cur_source = *it++;
628 cur_source->SwapToAnotherFile(true, false, false, pfile);
631 break;
632 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
633 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
634 break;
635 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
636 if ((pfile->GetStatus(false) == PS_READY) ||
637 (pfile->GetStatus(false) == PS_EMPTY)) {
638 CPartFile::SourceSet::const_iterator it = pfile->GetSourceList().begin();
639 while ( it != pfile->GetSourceList().end() ) {
640 CUpDownClient* cur_source = *it++;
642 cur_source->SwapToAnotherFile(false, false, false, NULL);
645 break;
646 case EC_OP_PARTFILE_PAUSE:
647 pfile->PauseFile();
648 break;
649 case EC_OP_PARTFILE_RESUME:
650 pfile->ResumeFile();
651 pfile->SavePartFile();
652 break;
653 case EC_OP_PARTFILE_STOP:
654 pfile->StopFile();
655 break;
656 case EC_OP_PARTFILE_PRIO_SET: {
657 uint8 prio = hashtag->GetTagByIndexSafe(0)->GetInt();
658 if ( prio == PR_AUTO ) {
659 pfile->SetAutoDownPriority(1);
660 } else {
661 pfile->SetAutoDownPriority(0);
662 pfile->SetDownPriority(prio);
665 break;
666 case EC_OP_PARTFILE_DELETE:
667 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
668 theApp->downloadqueue->StartNextFile(pfile);
670 pfile->Delete();
671 break;
673 case EC_OP_PARTFILE_SET_CAT:
674 pfile->SetCategory(hashtag->GetTagByIndexSafe(0)->GetInt());
675 break;
677 default:
678 response = new CECPacket(EC_OP_FAILED);
679 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
680 break;
683 if (!response) {
684 response = new CECPacket(EC_OP_NOOP);
686 return response;
689 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
691 CECPacket *response = NULL;
693 const CECTag *srv_tag = request->GetTagByIndex(0);
695 wxString full_addr = srv_tag->GetTagByName(EC_TAG_SERVER_ADDRESS)->GetStringData();
696 wxString name = srv_tag->GetTagByName(EC_TAG_SERVER_NAME)->GetStringData();
698 wxString s_ip = full_addr.Left(full_addr.Find(':'));
699 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
701 long port = StrToULong(s_port);
702 CServer* toadd = new CServer(port, s_ip);
703 toadd->SetListName(name.IsEmpty() ? full_addr : name);
705 if ( theApp->AddServer(toadd, true) ) {
706 response = new CECPacket(EC_OP_NOOP);
707 } else {
708 response = new CECPacket(EC_OP_FAILED);
709 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
710 delete toadd;
713 return response;
716 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
718 CECPacket *response = NULL;
719 const CECTag *srv_tag = request->GetTagByIndex(0);
720 CServer *srv = 0;
721 if ( srv_tag ) {
722 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
723 // server tag passed, but server not found
724 if ( !srv ) {
725 response = new CECPacket(EC_OP_FAILED);
726 response->AddTag(CECTag(EC_TAG_STRING,
727 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
728 return response;
731 switch (request->GetOpCode()) {
732 case EC_OP_SERVER_DISCONNECT:
733 theApp->serverconnect->Disconnect();
734 response = new CECPacket(EC_OP_NOOP);
735 break;
736 case EC_OP_SERVER_REMOVE:
737 if ( srv ) {
738 theApp->serverlist->RemoveServer(srv);
739 response = new CECPacket(EC_OP_NOOP);
740 } else {
741 response = new CECPacket(EC_OP_FAILED);
742 response->AddTag(CECTag(EC_TAG_STRING,
743 wxTRANSLATE("need to define server to be removed")));
745 break;
746 case EC_OP_SERVER_CONNECT:
747 if (thePrefs::GetNetworkED2K()) {
748 if ( srv ) {
749 theApp->serverconnect->ConnectToServer(srv);
750 response = new CECPacket(EC_OP_NOOP);
751 } else {
752 theApp->serverconnect->ConnectToAnyServer();
753 response = new CECPacket(EC_OP_NOOP);
755 } else {
756 response = new CECPacket(EC_OP_FAILED);
757 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
759 break;
761 if (!response) {
762 response = new CECPacket(EC_OP_FAILED);
763 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
765 return response;
768 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
770 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
772 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
774 // request can contain list of queried items
775 CTagSet<CMD4Hash, EC_TAG_SEARCHFILE> queryitems(request);
777 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
778 CSearchResultList::const_iterator it = list.begin();
779 while (it != list.end()) {
780 CSearchFile* sf = *it++;
781 if ( !queryitems.empty() && !queryitems.count(sf->GetFileHash()) ) {
782 continue;
784 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
786 return response;
789 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
791 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
793 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
794 CSearchResultList::const_iterator it = list.begin();
795 while (it != list.end()) {
796 CSearchFile* sf = *it++;
797 CValueMap &valuemap = tagmap.GetValueMap(sf);
798 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
800 return response;
803 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
805 CECPacket *response = new CECPacket(EC_OP_STRINGS);
806 for (unsigned int i = 0;i < request->GetTagCount();i++) {
807 const CECTag *tag = request->GetTagByIndex(i);
808 CMD4Hash hash = tag->GetMD4Data();
809 uint8 category = tag->GetTagByIndexSafe(0)->GetInt();
810 theApp->searchlist->AddFileToDownloadByHash(hash, category);
812 return response;
815 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
817 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
818 theApp->searchlist->StopGlobalSearch();
819 return reply;
822 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
824 wxString response;
826 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetTagByIndex(0);
827 theApp->searchlist->RemoveResults(0xffffffff);
829 CSearchList::CSearchParams params;
830 params.searchString = search_request->SearchText();
831 params.typeText = search_request->SearchFileType();
832 params.extension = search_request->SearchExt();
833 params.minSize = search_request->MinSize();
834 params.maxSize = search_request->MaxSize();
835 params.availability = search_request->Avail();
838 EC_SEARCH_TYPE search_type = search_request->SearchType();
839 SearchType core_search_type = LocalSearch;
840 switch (search_type) {
841 case EC_SEARCH_GLOBAL:
842 core_search_type = GlobalSearch;
843 case EC_SEARCH_KAD:
844 if (core_search_type != GlobalSearch) { // Not a global search obviously
845 core_search_type = KadSearch;
847 case EC_SEARCH_LOCAL: {
848 uint32 search_id = 0xffffffff;
849 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
850 if (!error.IsEmpty()) {
851 response = error;
852 } else {
853 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
855 break;
857 case EC_SEARCH_WEB:
858 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
859 break;
862 CECPacket *reply = new CECPacket(EC_OP_FAILED);
863 // error or search in progress
864 reply->AddTag(CECTag(EC_TAG_STRING, response));
866 return reply;
869 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
871 CECPacket *response = new CECPacket(EC_OP_NOOP);
872 for (unsigned int i = 0;i < request->GetTagCount();i++) {
873 const CECTag *tag = request->GetTagByIndex(i);
874 CMD4Hash hash = tag->GetMD4Data();
875 uint8 prio = tag->GetTagByIndexSafe(0)->GetInt();
876 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
877 if ( !cur_file ) {
878 continue;
880 if (prio == PR_AUTO) {
881 cur_file->SetAutoUpPriority(1);
882 cur_file->UpdateAutoUpPriority();
883 } else {
884 cur_file->SetAutoUpPriority(0);
885 cur_file->SetUpPriority(prio);
889 return response;
892 static CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
894 CECPacket *response;
895 if (thePrefs::GetNetworkKademlia()) {
896 response = new CECPacket(EC_OP_NOOP);
897 if ( !Kademlia::CKademlia::IsRunning() ) {
898 Kademlia::CKademlia::Start();
899 theApp->ShowConnectionState();
901 const CECTag *addrtag = request->GetTagByIndex(0);
902 if ( addrtag ) {
903 uint32 ip = addrtag->GetIPv4Data().IP();
904 uint16 port = addrtag->GetIPv4Data().m_port;
905 Kademlia::CKademlia::Bootstrap(ip, port, true);
907 } else {
908 response = new CECPacket(EC_OP_FAILED);
909 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
912 return response;
915 // init with some default size
916 CPartFile_Encoder::GapBuffer CPartFile_Encoder::m_gap_buffer(128);
918 // encoder side
919 CPartFile_Encoder::CPartFile_Encoder(CPartFile *file) :
920 m_enc_data(file->GetPartCount(), file->GetGapList().size() * 2)
922 m_file = file;
925 // decoder side
926 CPartFile_Encoder::CPartFile_Encoder(int size): m_enc_data(size, 0)
928 m_file = 0;
931 CPartFile_Encoder::~CPartFile_Encoder()
935 // stl side :)
936 CPartFile_Encoder::CPartFile_Encoder()
938 m_file = 0;
941 CPartFile_Encoder::CPartFile_Encoder(const CPartFile_Encoder &obj) : m_enc_data(obj.m_enc_data)
943 m_file = obj.m_file;
946 CPartFile_Encoder &CPartFile_Encoder::operator=(const CPartFile_Encoder &obj)
948 m_file = obj.m_file;
949 m_enc_data = obj.m_enc_data;
950 return *this;
953 void CPartFile_Encoder::Encode(CECTag *parent)
955 const CGapList& gaplist = m_file->GetNewGapList();
956 const size_t gap_list_size = gaplist.size();
958 if ( m_gap_buffer.size() < gap_list_size * 2 ) {
959 m_gap_buffer.clear();
960 m_gap_buffer.resize(gap_list_size * 2);
963 GapBuffer::iterator it = m_gap_buffer.begin();
965 for (CGapList::const_iterator curr_pos = gaplist.begin(); curr_pos != gaplist.end(); ++curr_pos) {
966 *it++ = ENDIAN_HTONLL(curr_pos.start());
967 *it++ = ENDIAN_HTONLL(curr_pos.end());
970 m_enc_data.m_gap_status.Realloc(gap_list_size*2*sizeof(uint64));
971 int gap_enc_size = 0;
972 const unsigned char *gap_enc_data = m_enc_data.m_gap_status.Encode((unsigned char *)&m_gap_buffer[0], gap_enc_size);
974 int part_enc_size;
975 const unsigned char *part_enc_data = m_enc_data.m_part_status.Encode(m_file->m_SrcpartFrequency, part_enc_size);
978 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
981 // Put data inside of tag in following order:
982 // [num_of_gaps] [gap_enc_data]
984 unsigned char *tagdata;
985 CECTag etag(EC_TAG_PARTFILE_GAP_STATUS,
986 sizeof(uint32) + gap_enc_size, (void **)&tagdata);
988 // real number of gaps - so remote size can realloc
989 RawPokeUInt32( tagdata, ENDIAN_HTONL( gap_list_size ) );
990 tagdata += sizeof(uint32);
991 memcpy(tagdata, gap_enc_data, gap_enc_size);
993 parent->AddTag(etag);
995 it = m_gap_buffer.begin();
997 const CPartFile::CReqBlockPtrList& requestedblocks = m_file->GetRequestedBlockList();
998 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
1000 wxASSERT(m_gap_buffer.size() >= requestedblocks.size() * 2);
1001 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
1002 Requested_Block_Struct* block = *curr_pos2;
1003 *it++ = ENDIAN_HTONLL(block->StartOffset);
1004 *it++ = ENDIAN_HTONLL(block->EndOffset);
1006 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS,
1007 requestedblocks.size() * 2 * sizeof(uint64), (void *)&m_gap_buffer[0]));
1010 // encoder side
1011 CKnownFile_Encoder::CKnownFile_Encoder(CKnownFile *file) :
1012 m_enc_data(file->GetPartCount(), true)
1014 m_file = file;
1017 CKnownFile_Encoder::CKnownFile_Encoder()
1019 m_file = 0;
1022 CKnownFile_Encoder::~CKnownFile_Encoder()
1026 CKnownFile_Encoder::CKnownFile_Encoder(const CKnownFile_Encoder &obj) : m_enc_data(obj.m_enc_data)
1028 m_file = obj.m_file;
1031 CKnownFile_Encoder &CKnownFile_Encoder::operator=(const CKnownFile_Encoder &obj)
1033 m_file = obj.m_file;
1034 m_enc_data = obj.m_enc_data;
1035 return *this;
1038 void CKnownFile_Encoder::Encode(CECTag *parent)
1040 int part_enc_size;
1041 const unsigned char *part_enc_data = m_enc_data.Encode(m_file->m_AvailPartFrequency, part_enc_size);
1043 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1046 static CECPacket *GetStatsGraphs(const CECPacket *request)
1048 CECPacket *response = NULL;
1050 switch (request->GetDetailLevel()) {
1051 case EC_DETAIL_WEB:
1052 case EC_DETAIL_FULL: {
1053 double dTimestamp = 0.0;
1054 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1055 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1057 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1058 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1059 uint32 *graphData;
1060 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1061 if (numPoints) {
1062 response = new CECPacket(EC_OP_STATSGRAPHS);
1063 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1064 delete [] graphData;
1065 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1066 } else {
1067 response = new CECPacket(EC_OP_FAILED);
1068 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1070 break;
1072 case EC_DETAIL_INC_UPDATE:
1073 case EC_DETAIL_UPDATE:
1074 case EC_DETAIL_CMD:
1075 // No graphs
1076 response = new CECPacket(EC_OP_FAILED);
1077 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1078 break;
1080 if (!response) {
1081 response = new CECPacket(EC_OP_FAILED);
1082 // Unknown reason
1085 return response;
1088 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request,
1089 CPartFile_Encoder_Map &enc_part_map, CKnownFile_Encoder_Map &enc_shared_map, CObjTagMap &objmap)
1092 if ( !request ) {
1093 return 0;
1096 CECPacket *response = NULL;
1098 switch (request->GetOpCode()) {
1100 // Misc commands
1102 case EC_OP_SHUTDOWN:
1103 if (!theApp->IsOnShutDown()) {
1104 response = new CECPacket(EC_OP_NOOP);
1105 AddLogLineM(true, _("External Connection: shutdown requested"));
1106 #ifndef AMULE_DAEMON
1108 wxCloseEvent evt;
1109 evt.SetCanVeto(false);
1110 theApp->ShutDown(evt);
1112 #else
1113 theApp->ExitMainLoop();
1114 #endif
1115 } else {
1116 response = new CECPacket(EC_OP_FAILED);
1117 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1119 break;
1120 case EC_OP_ADD_LINK:
1121 for(unsigned int i = 0; i < request->GetTagCount();i++) {
1122 const CECTag *tag = request->GetTagByIndex(i);
1123 wxString link = tag->GetStringData();
1124 int category = 0;
1125 const CECTag *cattag = tag->GetTagByName(EC_TAG_PARTFILE_CAT);
1126 if (cattag) {
1127 category = cattag->GetInt();
1129 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link);
1130 if ( theApp->downloadqueue->AddLink(link, category) ) {
1131 response = new CECPacket(EC_OP_NOOP);
1132 } else {
1133 // Error messages are printed by the add function.
1134 response = new CECPacket(EC_OP_FAILED);
1135 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1138 break;
1140 // Status requests
1142 case EC_OP_STAT_REQ:
1143 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1144 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1145 break;
1146 case EC_OP_GET_CONNSTATE:
1147 response = new CECPacket(EC_OP_MISC_DATA);
1148 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1149 break;
1153 case EC_OP_GET_SHARED_FILES:
1154 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1155 response = Get_EC_Response_GetSharedFiles(enc_shared_map, objmap);
1156 } else {
1157 response = Get_EC_Response_GetSharedFiles(request, enc_shared_map);
1159 break;
1160 case EC_OP_GET_DLOAD_QUEUE:
1161 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1162 response = Get_EC_Response_GetDownloadQueue(enc_part_map, objmap);
1163 } else {
1164 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map);
1166 break;
1167 // transmit source names and comments only if file detail dialog is open
1168 case EC_OP_GET_DLOAD_QUEUE_DETAIL:
1169 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1170 response = Get_EC_Response_GetDownloadQueue(enc_part_map, objmap);
1171 } else {
1172 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map, true);
1174 break;
1175 case EC_OP_GET_ULOAD_QUEUE:
1176 response = Get_EC_Response_GetClientQueue(request, objmap, EC_OP_ULOAD_QUEUE);
1177 break;
1178 case EC_OP_GET_WAIT_QUEUE:
1179 response = Get_EC_Response_GetClientQueue(request, objmap, EC_OP_WAIT_QUEUE);
1180 break;
1181 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1182 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1183 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1184 case EC_OP_PARTFILE_CLEANUP_SOURCES:
1185 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1186 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1187 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1188 case EC_OP_PARTFILE_PAUSE:
1189 case EC_OP_PARTFILE_RESUME:
1190 case EC_OP_PARTFILE_STOP:
1191 case EC_OP_PARTFILE_PRIO_SET:
1192 case EC_OP_PARTFILE_DELETE:
1193 case EC_OP_PARTFILE_SET_CAT:
1194 response = Get_EC_Response_PartFile_Cmd(request);
1195 break;
1196 case EC_OP_SHAREDFILES_RELOAD:
1197 theApp->sharedfiles->Reload();
1198 response = new CECPacket(EC_OP_NOOP);
1199 break;
1200 case EC_OP_SHARED_SET_PRIO:
1201 response = Get_EC_Response_Set_SharedFile_Prio(request);
1202 break;
1203 case EC_OP_RENAME_FILE: {
1204 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1205 CKnownFile* file = theApp->knownfiles->FindKnownFileByID(fileHash);
1206 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1207 if (!file) {
1208 file = theApp->downloadqueue->GetFileByID(fileHash);
1210 if (!file) {
1211 response = new CECPacket(EC_OP_FAILED);
1212 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1213 break;
1215 if (newName.IsEmpty()) {
1216 response = new CECPacket(EC_OP_FAILED);
1217 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1218 break;
1221 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1222 response = new CECPacket(EC_OP_NOOP);
1223 } else {
1224 response = new CECPacket(EC_OP_FAILED);
1225 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1228 break;
1233 // Server commands
1235 case EC_OP_SERVER_ADD:
1236 response = Get_EC_Response_Server_Add(request);
1237 break;
1238 case EC_OP_SERVER_DISCONNECT:
1239 case EC_OP_SERVER_CONNECT:
1240 case EC_OP_SERVER_REMOVE:
1241 response = Get_EC_Response_Server(request);
1242 break;
1243 case EC_OP_GET_SERVER_LIST: {
1244 response = new CECPacket(EC_OP_SERVER_LIST);
1245 if (!thePrefs::GetNetworkED2K()) {
1246 // Kad only: just send an empty list
1247 break;
1249 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1250 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1251 for (
1252 std::vector<const CServer*>::const_iterator it = servers.begin();
1253 it != servers.end();
1254 ++it
1256 response->AddTag(CEC_Server_Tag(*it, detail_level));
1259 break;
1260 case EC_OP_SERVER_UPDATE_FROM_URL: {
1261 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1263 // Save the new url, and update the UI (if not amuled).
1264 Notify_ServersURLChanged(url);
1265 thePrefs::SetEd2kServersUrl(url);
1267 theApp->serverlist->UpdateServerMetFromURL(url);
1268 response = new CECPacket(EC_OP_NOOP);
1269 break;
1272 // IPFilter
1274 case EC_OP_IPFILTER_RELOAD:
1275 theApp->ipfilter->Reload();
1276 response = new CECPacket(EC_OP_NOOP);
1277 break;
1279 case EC_OP_IPFILTER_UPDATE: {
1280 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1281 if (url == wxEmptyString) {
1282 url = thePrefs::IPFilterURL();
1284 theApp->ipfilter->Update(url);
1285 response = new CECPacket(EC_OP_NOOP);
1286 break;
1289 // Search
1291 case EC_OP_SEARCH_START:
1292 response = Get_EC_Response_Search(request);
1293 break;
1295 case EC_OP_SEARCH_STOP:
1296 response = Get_EC_Response_Search_Stop(request);
1297 break;
1299 case EC_OP_SEARCH_RESULTS:
1300 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1301 response = Get_EC_Response_Search_Results(objmap);
1302 } else {
1303 response = Get_EC_Response_Search_Results(request);
1305 break;
1307 case EC_OP_SEARCH_PROGRESS:
1308 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1309 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1310 theApp->searchlist->GetSearchProgress()));
1311 break;
1313 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1314 response = Get_EC_Response_Search_Results_Download(request);
1315 break;
1317 // Preferences
1319 case EC_OP_GET_PREFERENCES:
1320 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1321 break;
1322 case EC_OP_SET_PREFERENCES:
1323 ((CEC_Prefs_Packet *)request)->Apply();
1324 theApp->glob_prefs->Save();
1325 if (thePrefs::IsFilteringClients()) {
1326 theApp->clientlist->FilterQueues();
1328 if (thePrefs::IsFilteringServers()) {
1329 theApp->serverlist->FilterServers();
1331 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1332 theApp->DisconnectED2K();
1334 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1335 theApp->StopKad();
1337 response = new CECPacket(EC_OP_NOOP);
1338 break;
1340 case EC_OP_CREATE_CATEGORY:
1341 if ( request->GetTagCount() == 1 ) {
1342 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetTagByIndex(0);
1343 if (tag->Create()) {
1344 response = new CECPacket(EC_OP_NOOP);
1345 } else {
1346 response = new CECPacket(EC_OP_FAILED);
1347 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1348 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1350 Notify_CategoryAdded();
1351 } else {
1352 response = new CECPacket(EC_OP_NOOP);
1354 break;
1355 case EC_OP_UPDATE_CATEGORY:
1356 if ( request->GetTagCount() == 1 ) {
1357 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetTagByIndex(0);
1358 if (tag->Apply()) {
1359 response = new CECPacket(EC_OP_NOOP);
1360 } else {
1361 response = new CECPacket(EC_OP_FAILED);
1362 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1363 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1365 Notify_CategoryUpdate(tag->GetInt());
1366 } else {
1367 response = new CECPacket(EC_OP_NOOP);
1369 break;
1370 case EC_OP_DELETE_CATEGORY:
1371 if ( request->GetTagCount() == 1 ) {
1372 uint32 cat = request->GetTagByIndex(0)->GetInt();
1373 // this noes not only update the gui, but actually deletes the cat
1374 Notify_CategoryDelete(cat);
1376 response = new CECPacket(EC_OP_NOOP);
1377 break;
1380 // Logging
1382 case EC_OP_ADDLOGLINE:
1383 AddLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1384 response = new CECPacket(EC_OP_NOOP);
1385 break;
1386 case EC_OP_ADDDEBUGLOGLINE:
1387 AddDebugLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1388 response = new CECPacket(EC_OP_NOOP);
1389 break;
1390 case EC_OP_GET_LOG:
1391 response = new CECPacket(EC_OP_LOG);
1392 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1393 break;
1394 case EC_OP_GET_DEBUGLOG:
1395 response = new CECPacket(EC_OP_DEBUGLOG);
1396 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1397 break;
1398 case EC_OP_RESET_LOG:
1399 theApp->GetLog(true);
1400 response = new CECPacket(EC_OP_NOOP);
1401 break;
1402 case EC_OP_RESET_DEBUGLOG:
1403 theApp->GetDebugLog(true);
1404 response = new CECPacket(EC_OP_NOOP);
1405 break;
1406 case EC_OP_GET_LAST_LOG_ENTRY:
1408 wxString tmp = theApp->GetLog(false);
1409 if (tmp.Last() == '\n') {
1410 tmp.RemoveLast();
1412 response = new CECPacket(EC_OP_LOG);
1413 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1415 break;
1416 case EC_OP_GET_SERVERINFO:
1417 response = new CECPacket(EC_OP_SERVERINFO);
1418 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1419 break;
1420 case EC_OP_CLEAR_SERVERINFO:
1421 theApp->GetServerLog(true);
1422 response = new CECPacket(EC_OP_NOOP);
1423 break;
1425 // Statistics
1427 case EC_OP_GET_STATSGRAPHS:
1428 response = GetStatsGraphs(request);
1429 break;
1430 case EC_OP_GET_STATSTREE: {
1431 theApp->m_statistics->UpdateStatsTree();
1432 response = new CECPacket(EC_OP_STATSTREE);
1433 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1434 if (tree) {
1435 response->AddTag(*tree);
1436 delete tree;
1438 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1439 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1440 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1442 break;
1446 // Kad
1448 case EC_OP_KAD_START:
1449 response = Get_EC_Response_Kad_Connect(request);
1450 break;
1451 case EC_OP_KAD_STOP:
1452 theApp->StopKad();
1453 response = new CECPacket(EC_OP_NOOP);
1454 break;
1455 case EC_OP_KAD_UPDATE_FROM_URL: {
1456 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1458 // Save the new url, and update the UI (if not amuled).
1459 Notify_NodesURLChanged(url);
1460 thePrefs::SetKadNodesUrl(url);
1462 theApp->UpdateNotesDat(url);
1463 response = new CECPacket(EC_OP_NOOP);
1464 break;
1466 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1467 theApp->BootstrapKad(request->GetTagByIndexSafe(0)->GetInt(),
1468 request->GetTagByIndexSafe(1)->GetInt());
1469 response = new CECPacket(EC_OP_NOOP);
1470 break;
1473 // Networks
1475 case EC_OP_CONNECT:
1476 if (thePrefs::GetNetworkED2K()) {
1477 response = new CECPacket(EC_OP_STRINGS);
1478 if (theApp->IsConnectedED2K()) {
1479 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1480 } else {
1481 theApp->serverconnect->ConnectToAnyServer();
1482 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1485 if (thePrefs::GetNetworkKademlia()) {
1486 if (!response) {
1487 response = new CECPacket(EC_OP_STRINGS);
1489 if (theApp->IsConnectedKad()) {
1490 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1491 } else {
1492 theApp->StartKad();
1493 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1496 if (!response) {
1497 response = new CECPacket(EC_OP_FAILED);
1498 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1500 break;
1501 case EC_OP_DISCONNECT:
1502 if (theApp->IsConnected()) {
1503 response = new CECPacket(EC_OP_STRINGS);
1504 if (theApp->IsConnectedED2K()) {
1505 theApp->serverconnect->Disconnect();
1506 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1508 if (theApp->IsConnectedKad()) {
1509 theApp->StopKad();
1510 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1512 } else {
1513 response = new CECPacket(EC_OP_NOOP);
1515 break;
1517 default:
1518 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1519 wxFAIL;
1520 response = new CECPacket(EC_OP_FAILED);
1521 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1522 break;
1524 return response;
1528 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1532 * Core general status
1534 ECStatusMsgSource::ECStatusMsgSource()
1536 m_last_ed2k_status_sent = 0xffffffff;
1537 m_last_kad_status_sent = 0xffffffff;
1538 m_server = (void *)0xffffffff;
1541 uint32 ECStatusMsgSource::GetEd2kStatus()
1543 if ( theApp->IsConnectedED2K() ) {
1544 return theApp->GetED2KID();
1545 } else if ( theApp->serverconnect->IsConnecting() ) {
1546 return 1;
1547 } else {
1548 return 0;
1552 uint32 ECStatusMsgSource::GetKadStatus()
1554 if ( theApp->IsConnectedKad() ) {
1555 return 1;
1556 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1557 return 2;
1558 } else if ( Kademlia::CKademlia::IsRunning() ) {
1559 return 3;
1561 return 0;
1564 CECPacket *ECStatusMsgSource::GetNextPacket()
1566 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1567 (m_last_kad_status_sent != GetKadStatus()) ||
1568 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1570 m_last_ed2k_status_sent = GetEd2kStatus();
1571 m_last_kad_status_sent = GetKadStatus();
1572 m_server = theApp->serverconnect->GetCurrentServer();
1574 CECPacket *response = new CECPacket(EC_OP_STATS);
1575 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1576 return response;
1578 return 0;
1582 * Downloading files
1584 ECPartFileMsgSource::ECPartFileMsgSource()
1586 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1587 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1588 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1589 m_dirty_status[cur_file->GetFileHash()] = status;
1593 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1595 CMD4Hash filehash = file->GetFileHash();
1596 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1597 m_dirty_status[filehash].m_dirty = true;;
1601 void ECPartFileMsgSource::SetNew(CPartFile *file)
1603 CMD4Hash filehash = file->GetFileHash();
1604 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1605 PARTFILE_STATUS status = { true, false, false, false, true, file };
1606 m_dirty_status[filehash] = status;
1609 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1611 CMD4Hash filehash = file->GetFileHash();
1612 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1614 m_dirty_status[filehash].m_finished = true;
1617 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1619 CMD4Hash filehash = file->GetFileHash();
1620 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1622 m_dirty_status[filehash].m_removed = true;
1625 CECPacket *ECPartFileMsgSource::GetNextPacket()
1627 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1628 it != m_dirty_status.end(); it++) {
1629 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1630 CMD4Hash filehash = it->first;
1632 CPartFile *partfile = it->second.m_file;
1634 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1635 if ( it->second.m_removed ) {
1636 CECTag tag(EC_TAG_PARTFILE, filehash);
1637 packet->AddTag(tag);
1638 m_dirty_status.erase(it);
1639 } else {
1640 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1641 packet->AddTag(tag);
1643 m_dirty_status[filehash].m_new = false;
1644 m_dirty_status[filehash].m_dirty = false;
1646 return packet;
1649 return 0;
1653 * Shared files - similar to downloading
1655 ECKnownFileMsgSource::ECKnownFileMsgSource()
1657 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1658 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1659 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1660 m_dirty_status[cur_file->GetFileHash()] = status;
1664 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1666 CMD4Hash filehash = file->GetFileHash();
1667 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1668 m_dirty_status[filehash].m_dirty = true;;
1672 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1674 CMD4Hash filehash = file->GetFileHash();
1675 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1676 KNOWNFILE_STATUS status = { true, false, false, true, file };
1677 m_dirty_status[filehash] = status;
1680 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1682 CMD4Hash filehash = file->GetFileHash();
1683 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1685 m_dirty_status[filehash].m_removed = true;
1688 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1690 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1691 it != m_dirty_status.end(); it++) {
1692 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1693 CMD4Hash filehash = it->first;
1695 CKnownFile *partfile = it->second.m_file;
1697 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1698 if ( it->second.m_removed ) {
1699 CECTag tag(EC_TAG_PARTFILE, filehash);
1700 packet->AddTag(tag);
1701 m_dirty_status.erase(it);
1702 } else {
1703 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1704 packet->AddTag(tag);
1706 m_dirty_status[filehash].m_new = false;
1707 m_dirty_status[filehash].m_dirty = false;
1709 return packet;
1712 return 0;
1716 * Notification about search status
1718 ECSearchMsgSource::ECSearchMsgSource()
1722 CECPacket *ECSearchMsgSource::GetNextPacket()
1724 if ( m_dirty_status.empty() ) {
1725 return 0;
1728 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1729 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1730 it != m_dirty_status.end(); it++) {
1732 if ( it->second.m_new ) {
1733 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1734 it->second.m_new = false;
1735 } else if ( it->second.m_dirty ) {
1736 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1741 return response;
1744 void ECSearchMsgSource::FlushStatus()
1746 m_dirty_status.clear();
1749 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1751 if ( m_dirty_status.count(file->GetFileHash()) ) {
1752 m_dirty_status[file->GetFileHash()].m_dirty = true;
1753 } else {
1754 m_dirty_status[file->GetFileHash()].m_new = true;
1755 m_dirty_status[file->GetFileHash()].m_dirty = true;
1756 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1757 m_dirty_status[file->GetFileHash()].m_file = file;
1761 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1763 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1767 * Notification about uploading clients
1769 CECPacket *ECClientMsgSource::GetNextPacket()
1771 return 0;
1775 // Notification iface per-client
1777 ECNotifier::ECNotifier()
1781 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1783 CECPacket *packet = 0;
1785 // priority 0 is highest
1787 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1788 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1789 break;
1792 return packet;
1795 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1798 // OnOutput is called for a first time before
1799 // socket is registered
1801 if ( m_msg_source.count(sock) ) {
1802 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1803 if ( !notifier_array ) {
1804 return 0;
1806 CECPacket *packet = GetNextPacket(notifier_array);
1807 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1808 return packet;
1809 } else {
1810 return 0;
1815 // Interface to notification macros
1817 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
1819 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1820 i != m_msg_source.end(); i++) {
1821 CECServerSocket *sock = i->first;
1822 if ( sock->HaveNotificationSupport() ) {
1823 ECUpdateMsgSource **notifier_array = i->second;
1824 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
1827 NextPacketToSocket();
1830 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
1832 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1833 i != m_msg_source.end(); i++) {
1834 ECUpdateMsgSource **notifier_array = i->second;
1835 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
1837 NextPacketToSocket();
1840 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
1842 // per-partfile source list is not supported (yet), and IMHO quite useless
1845 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
1847 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1848 i != m_msg_source.end(); i++) {
1849 ECUpdateMsgSource **notifier_array = i->second;
1850 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
1852 NextPacketToSocket();
1855 void ECNotifier::DownloadFile_AddSource(CPartFile *)
1857 // per-partfile source list is not supported (yet), and IMHO quite useless
1860 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
1862 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1863 i != m_msg_source.end(); i++) {
1864 ECUpdateMsgSource **notifier_array = i->second;
1865 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
1867 NextPacketToSocket();
1870 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
1872 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1873 i != m_msg_source.end(); i++) {
1874 ECUpdateMsgSource **notifier_array = i->second;
1875 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
1877 NextPacketToSocket();
1880 void ECNotifier::SharedFile_RemoveAllFiles()
1882 // need to figure out what to do here
1885 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
1887 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
1888 notifier_array[EC_STATUS] = new ECStatusMsgSource();
1889 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
1890 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
1891 notifier_array[EC_CLIENT] = new ECClientMsgSource();
1892 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
1894 m_msg_source[sock] = notifier_array;
1897 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
1899 if (m_msg_source.count(sock)) {
1900 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1902 m_msg_source.erase(sock);
1904 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1905 delete notifier_array[i];
1907 delete [] notifier_array;
1911 void ECNotifier::NextPacketToSocket()
1913 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1914 i != m_msg_source.end(); i++) {
1915 CECServerSocket *sock = i->first;
1916 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
1917 ECUpdateMsgSource **notifier_array = i->second;
1918 CECPacket *packet = GetNextPacket(notifier_array);
1919 if ( packet ) {
1920 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
1921 sock->SendPacket(packet);
1927 // File_checked_for_headers