Upstream tarball 10026
[amule.git] / src / ExternalConn.cpp
blob05ad4cee0e13ecf83f52e7be79f091cef10a3975
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 if (HaveNotificationSupport()) {
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<uint32, 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->ECID())) ) {
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 const CClientPtrList& clients = (op == EC_OP_WAIT_QUEUE) ? theApp->uploadqueue->GetWaitingList()
517 : theApp->uploadqueue->GetUploadingList();
518 CClientPtrList::const_iterator it = clients.begin();
519 for (; it != clients.end(); ++it) {
520 CUpDownClient* cur_client = *it;
522 if (!cur_client) { // shouldn't happen
523 continue;
525 if (!queryitems.empty() && !queryitems.count(cur_client->ECID())) {
526 continue;
528 CValueMap *valuemap = NULL;
529 if (detail_level == EC_DETAIL_INC_UPDATE) {
530 valuemap = &tagmap.GetValueMap(cur_client);
532 CEC_UpDownClient_Tag cli_tag(cur_client, detail_level, valuemap);
534 response->AddTag(cli_tag);
537 return response;
541 static CECPacket *Get_EC_Response_GetDownloadQueue(CPartFile_Encoder_Map &encoders, CObjTagMap &tagmap)
543 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
545 encoders.UpdateEncoders(theApp->downloadqueue);
546 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
547 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
549 CValueMap &valuemap = tagmap.GetValueMap(cur_file);
550 CEC_PartFile_Tag filetag(cur_file, EC_DETAIL_INC_UPDATE, &valuemap);
551 CPartFile_Encoder &enc = encoders[cur_file];
552 enc.Encode(&filetag);
554 response->AddTag(filetag);
556 return response;
559 static CECPacket *Get_EC_Response_GetDownloadQueue(const CECPacket *request, CPartFile_Encoder_Map &encoders)
561 CECPacket *response = new CECPacket(EC_OP_DLOAD_QUEUE);
563 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
565 // request can contain list of queried items
566 CTagSet<uint32, EC_TAG_PARTFILE> queryitems(request);
568 encoders.UpdateEncoders(theApp->downloadqueue);
570 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
571 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
573 if ( !queryitems.empty() && !queryitems.count(cur_file->ECID()) ) {
574 continue;
577 CEC_PartFile_Tag filetag(cur_file, detail_level);
579 CPartFile_Encoder &enc = encoders[cur_file];
580 if ( detail_level != EC_DETAIL_UPDATE ) {
581 enc.ResetEncoder();
583 enc.Encode(&filetag);
585 response->AddTag(filetag);
587 return response;
591 static CECPacket *Get_EC_Response_PartFile_Cmd(const CECPacket *request)
593 CECPacket *response = NULL;
595 // request can contain multiple files.
596 for (unsigned int i = 0; i < request->GetTagCount(); ++i) {
597 const CECTag *hashtag = request->GetTagByIndex(i);
599 wxASSERT(hashtag->GetTagName() == EC_TAG_PARTFILE);
601 CMD4Hash hash = hashtag->GetMD4Data();
602 CPartFile *pfile = theApp->downloadqueue->GetFileByID( hash );
604 if ( !pfile ) {
605 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash.Encode());
606 response = new CECPacket(EC_OP_FAILED);
607 response->AddTag(CECTag(EC_TAG_STRING, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash.Encode()));
608 //return response;
609 break;
611 switch (request->GetOpCode()) {
612 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
613 if ((pfile->GetStatus(false) == PS_READY) ||
614 (pfile->GetStatus(false) == PS_EMPTY)) {
615 CPartFile::SourceSet::const_iterator it = pfile->GetA4AFList().begin();
616 while ( it != pfile->GetA4AFList().end() ) {
617 CUpDownClient *cur_source = *it++;
619 cur_source->SwapToAnotherFile(true, false, false, pfile);
622 break;
623 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
624 pfile->SetA4AFAuto(!pfile->IsA4AFAuto());
625 break;
626 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
627 if ((pfile->GetStatus(false) == PS_READY) ||
628 (pfile->GetStatus(false) == PS_EMPTY)) {
629 CPartFile::SourceSet::const_iterator it = pfile->GetSourceList().begin();
630 while ( it != pfile->GetSourceList().end() ) {
631 CUpDownClient* cur_source = *it++;
633 cur_source->SwapToAnotherFile(false, false, false, NULL);
636 break;
637 case EC_OP_PARTFILE_PAUSE:
638 pfile->PauseFile();
639 break;
640 case EC_OP_PARTFILE_RESUME:
641 pfile->ResumeFile();
642 pfile->SavePartFile();
643 break;
644 case EC_OP_PARTFILE_STOP:
645 pfile->StopFile();
646 break;
647 case EC_OP_PARTFILE_PRIO_SET: {
648 uint8 prio = hashtag->GetTagByIndexSafe(0)->GetInt();
649 if ( prio == PR_AUTO ) {
650 pfile->SetAutoDownPriority(1);
651 } else {
652 pfile->SetAutoDownPriority(0);
653 pfile->SetDownPriority(prio);
656 break;
657 case EC_OP_PARTFILE_DELETE:
658 if ( thePrefs::StartNextFile() && (pfile->GetStatus() != PS_PAUSED) ) {
659 theApp->downloadqueue->StartNextFile(pfile);
661 pfile->Delete();
662 break;
664 case EC_OP_PARTFILE_SET_CAT:
665 pfile->SetCategory(hashtag->GetTagByIndexSafe(0)->GetInt());
666 break;
668 default:
669 response = new CECPacket(EC_OP_FAILED);
670 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
671 break;
674 if (!response) {
675 response = new CECPacket(EC_OP_NOOP);
677 return response;
680 static CECPacket *Get_EC_Response_Server_Add(const CECPacket *request)
682 CECPacket *response = NULL;
684 const CECTag *srv_tag = request->GetTagByIndex(0);
686 wxString full_addr = srv_tag->GetTagByName(EC_TAG_SERVER_ADDRESS)->GetStringData();
687 wxString name = srv_tag->GetTagByName(EC_TAG_SERVER_NAME)->GetStringData();
689 wxString s_ip = full_addr.Left(full_addr.Find(':'));
690 wxString s_port = full_addr.Mid(full_addr.Find(':') + 1);
692 long port = StrToULong(s_port);
693 CServer* toadd = new CServer(port, s_ip);
694 toadd->SetListName(name.IsEmpty() ? full_addr : name);
696 if ( theApp->AddServer(toadd, true) ) {
697 response = new CECPacket(EC_OP_NOOP);
698 } else {
699 response = new CECPacket(EC_OP_FAILED);
700 response->AddTag(CECTag(EC_TAG_STRING, _("Server not added")));
701 delete toadd;
704 return response;
707 static CECPacket *Get_EC_Response_Server(const CECPacket *request)
709 CECPacket *response = NULL;
710 const CECTag *srv_tag = request->GetTagByIndex(0);
711 CServer *srv = 0;
712 if ( srv_tag ) {
713 srv = theApp->serverlist->GetServerByIPTCP(srv_tag->GetIPv4Data().IP(), srv_tag->GetIPv4Data().m_port);
714 // server tag passed, but server not found
715 if ( !srv ) {
716 response = new CECPacket(EC_OP_FAILED);
717 response->AddTag(CECTag(EC_TAG_STRING,
718 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag->GetIPv4Data().StringIP()));
719 return response;
722 switch (request->GetOpCode()) {
723 case EC_OP_SERVER_DISCONNECT:
724 theApp->serverconnect->Disconnect();
725 response = new CECPacket(EC_OP_NOOP);
726 break;
727 case EC_OP_SERVER_REMOVE:
728 if ( srv ) {
729 theApp->serverlist->RemoveServer(srv);
730 response = new CECPacket(EC_OP_NOOP);
731 } else {
732 response = new CECPacket(EC_OP_FAILED);
733 response->AddTag(CECTag(EC_TAG_STRING,
734 wxTRANSLATE("need to define server to be removed")));
736 break;
737 case EC_OP_SERVER_CONNECT:
738 if (thePrefs::GetNetworkED2K()) {
739 if ( srv ) {
740 theApp->serverconnect->ConnectToServer(srv);
741 response = new CECPacket(EC_OP_NOOP);
742 } else {
743 theApp->serverconnect->ConnectToAnyServer();
744 response = new CECPacket(EC_OP_NOOP);
746 } else {
747 response = new CECPacket(EC_OP_FAILED);
748 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("eD2k is disabled in preferences.")));
750 break;
752 if (!response) {
753 response = new CECPacket(EC_OP_FAILED);
754 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("OOPS! OpCode processing error!")));
756 return response;
759 static CECPacket *Get_EC_Response_Search_Results(const CECPacket *request)
761 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
763 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
765 // request can contain list of queried items
766 CTagSet<CMD4Hash, EC_TAG_SEARCHFILE> queryitems(request);
768 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
769 CSearchResultList::const_iterator it = list.begin();
770 while (it != list.end()) {
771 CSearchFile* sf = *it++;
772 if ( !queryitems.empty() && !queryitems.count(sf->GetFileHash()) ) {
773 continue;
775 response->AddTag(CEC_SearchFile_Tag(sf, detail_level));
777 return response;
780 static CECPacket *Get_EC_Response_Search_Results(CObjTagMap &tagmap)
782 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
784 const CSearchResultList& list = theApp->searchlist->GetSearchResults(0xffffffff);
785 CSearchResultList::const_iterator it = list.begin();
786 while (it != list.end()) {
787 CSearchFile* sf = *it++;
788 CValueMap &valuemap = tagmap.GetValueMap(sf);
789 response->AddTag(CEC_SearchFile_Tag(sf, EC_DETAIL_INC_UPDATE, &valuemap));
791 return response;
794 static CECPacket *Get_EC_Response_Search_Results_Download(const CECPacket *request)
796 CECPacket *response = new CECPacket(EC_OP_STRINGS);
797 for (unsigned int i = 0;i < request->GetTagCount();i++) {
798 const CECTag *tag = request->GetTagByIndex(i);
799 CMD4Hash hash = tag->GetMD4Data();
800 uint8 category = tag->GetTagByIndexSafe(0)->GetInt();
801 theApp->searchlist->AddFileToDownloadByHash(hash, category);
803 return response;
806 static CECPacket *Get_EC_Response_Search_Stop(const CECPacket *WXUNUSED(request))
808 CECPacket *reply = new CECPacket(EC_OP_MISC_DATA);
809 theApp->searchlist->StopGlobalSearch();
810 return reply;
813 static CECPacket *Get_EC_Response_Search(const CECPacket *request)
815 wxString response;
817 CEC_Search_Tag *search_request = (CEC_Search_Tag *)request->GetTagByIndex(0);
818 theApp->searchlist->RemoveResults(0xffffffff);
820 CSearchList::CSearchParams params;
821 params.searchString = search_request->SearchText();
822 params.typeText = search_request->SearchFileType();
823 params.extension = search_request->SearchExt();
824 params.minSize = search_request->MinSize();
825 params.maxSize = search_request->MaxSize();
826 params.availability = search_request->Avail();
829 EC_SEARCH_TYPE search_type = search_request->SearchType();
830 SearchType core_search_type = LocalSearch;
831 switch (search_type) {
832 case EC_SEARCH_GLOBAL:
833 core_search_type = GlobalSearch;
834 case EC_SEARCH_KAD:
835 if (core_search_type != GlobalSearch) { // Not a global search obviously
836 core_search_type = KadSearch;
838 case EC_SEARCH_LOCAL: {
839 uint32 search_id = 0xffffffff;
840 wxString error = theApp->searchlist->StartNewSearch(&search_id, core_search_type, params);
841 if (!error.IsEmpty()) {
842 response = error;
843 } else {
844 response = wxTRANSLATE("Search in progress. Refetch results in a moment!");
846 break;
848 case EC_SEARCH_WEB:
849 response = wxTRANSLATE("WebSearch from remote interface makes no sense.");
850 break;
853 CECPacket *reply = new CECPacket(EC_OP_FAILED);
854 // error or search in progress
855 reply->AddTag(CECTag(EC_TAG_STRING, response));
857 return reply;
860 static CECPacket *Get_EC_Response_Set_SharedFile_Prio(const CECPacket *request)
862 CECPacket *response = new CECPacket(EC_OP_NOOP);
863 for (unsigned int i = 0;i < request->GetTagCount();i++) {
864 const CECTag *tag = request->GetTagByIndex(i);
865 CMD4Hash hash = tag->GetMD4Data();
866 uint8 prio = tag->GetTagByIndexSafe(0)->GetInt();
867 CKnownFile* cur_file = theApp->sharedfiles->GetFileByID(hash);
868 if ( !cur_file ) {
869 continue;
871 if (prio == PR_AUTO) {
872 cur_file->SetAutoUpPriority(1);
873 cur_file->UpdateAutoUpPriority();
874 } else {
875 cur_file->SetAutoUpPriority(0);
876 cur_file->SetUpPriority(prio);
878 Notify_SharedFilesUpdateItem(cur_file);
881 return response;
884 static CECPacket *Get_EC_Response_Kad_Connect(const CECPacket *request)
886 CECPacket *response;
887 if (thePrefs::GetNetworkKademlia()) {
888 response = new CECPacket(EC_OP_NOOP);
889 if ( !Kademlia::CKademlia::IsRunning() ) {
890 Kademlia::CKademlia::Start();
891 theApp->ShowConnectionState();
893 const CECTag *addrtag = request->GetTagByIndex(0);
894 if ( addrtag ) {
895 uint32 ip = addrtag->GetIPv4Data().IP();
896 uint16 port = addrtag->GetIPv4Data().m_port;
897 Kademlia::CKademlia::Bootstrap(ip, port, true);
899 } else {
900 response = new CECPacket(EC_OP_FAILED);
901 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Kad is disabled in preferences.")));
904 return response;
907 void CPartFile_Encoder::Encode(CECTag *parent)
910 // Source part frequencies
912 // These are not always populated, don't send a tag in this case
914 if (!m_file->m_SrcpartFrequency.empty()) {
915 int part_enc_size;
916 bool changed;
917 const uint8 *part_enc_data = m_part_status.Encode(m_file->m_SrcpartFrequency, part_enc_size, changed);
918 if (changed) {
919 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
921 delete[] part_enc_data;
925 // Gaps
927 const CGapList& gaplist = m_file->GetNewGapList();
928 const size_t gap_list_size = gaplist.size();
929 ArrayOfUInts64 gaps;
930 gaps.reserve(gap_list_size * 2);
932 for (CGapList::const_iterator curr_pos = gaplist.begin();
933 curr_pos != gaplist.end(); ++curr_pos) {
934 gaps.push_back(curr_pos.start());
935 gaps.push_back(curr_pos.end());
938 int gap_enc_size = 0;
939 bool changed;
940 const uint8 *gap_enc_data = m_gap_status.Encode(gaps, gap_enc_size, changed);
941 if (changed) {
942 parent->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS, gap_enc_size, (void *)gap_enc_data));
944 delete[] gap_enc_data;
947 // Requested blocks
949 ArrayOfUInts64 req_buffer;
950 const CPartFile::CReqBlockPtrList& requestedblocks = m_file->GetRequestedBlockList();
951 CPartFile::CReqBlockPtrList::const_iterator curr_pos2 = requestedblocks.begin();
953 for ( ; curr_pos2 != requestedblocks.end(); ++curr_pos2 ) {
954 Requested_Block_Struct* block = *curr_pos2;
955 req_buffer.push_back(block->StartOffset);
956 req_buffer.push_back(block->EndOffset);
958 int req_enc_size = 0;
959 const uint8 *req_enc_data = m_req_status.Encode(req_buffer, req_enc_size, changed);
960 if (changed) {
961 parent->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS, req_enc_size, (void *)req_enc_data));
963 delete[] req_enc_data;
966 // Source names
968 // First count occurrence of all source names
970 CECEmptyTag sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES);
971 typedef std::map<wxString, int> strIntMap;
972 strIntMap nameMap;
973 const CPartFile::SourceSet &sources = m_file->GetSourceList();
974 for (CPartFile::SourceSet::const_iterator it = sources.begin(); it != sources.end(); ++it) {
975 CUpDownClient *cur_src = *it;
976 if (cur_src->GetRequestFile() != m_file || cur_src->GetClientFilename().Length() == 0) {
977 continue;
979 const wxString &name = cur_src->GetClientFilename();
980 strIntMap::iterator itm = nameMap.find(name);
981 if (itm == nameMap.end()) {
982 nameMap[name] = 1;
983 } else {
984 itm->second++;
988 // Go through our last list
990 for (SourcenameItemMap::iterator it1 = m_sourcenameItemMap.begin(); it1 != m_sourcenameItemMap.end();) {
991 SourcenameItemMap::iterator it2 = it1++;
992 strIntMap::iterator itm = nameMap.find(it2->second.name);
993 if (itm == nameMap.end()) {
994 // name doesn't exist anymore, tell client to forget it
995 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
996 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, 0));
997 sourceNames.AddTag(tag);
998 // and forget it
999 m_sourcenameItemMap.erase(it2);
1000 } else {
1001 // update count if it changed
1002 if (it2->second.count != itm->second) {
1003 CECTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, it2->first);
1004 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, itm->second));
1005 sourceNames.AddTag(tag);
1006 it2->second.count = itm->second;
1008 // remove it from nameMap so that only new names are left there
1009 nameMap.erase(itm);
1013 // Add new names
1015 for (strIntMap::iterator it3 = nameMap.begin(); it3 != nameMap.end(); it3++) {
1016 int id = ++m_sourcenameID;
1017 CECIntTag tag(EC_TAG_PARTFILE_SOURCE_NAMES, id);
1018 tag.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES, it3->first));
1019 tag.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS, it3->second));
1020 sourceNames.AddTag(tag);
1021 // remember it
1022 m_sourcenameItemMap[id] = SourcenameItem(it3->first, it3->second);
1024 if (sourceNames.HasChildTags()) {
1025 parent->AddTag(sourceNames);
1030 void CPartFile_Encoder::ResetEncoder()
1032 m_part_status.ResetEncoder();
1033 m_gap_status.ResetEncoder();
1034 m_req_status.ResetEncoder();
1037 void CKnownFile_Encoder::Encode(CECTag *parent)
1039 // Reference to the availability list
1040 const ArrayOfUInts16& list = m_file->IsPartFile() ?
1041 ((CPartFile*)m_file)->m_SrcpartFrequency :
1042 m_file->m_AvailPartFrequency;
1043 // Don't add tag if available parts aren't populated yet.
1044 if (!list.empty()) {
1045 int part_enc_size;
1046 bool changed;
1047 const uint8 *part_enc_data = m_enc_data.Encode(list, part_enc_size, changed);
1048 if (changed) {
1049 parent->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS, part_enc_size, part_enc_data));
1051 delete[] part_enc_data;
1055 static CECPacket *GetStatsGraphs(const CECPacket *request)
1057 CECPacket *response = NULL;
1059 switch (request->GetDetailLevel()) {
1060 case EC_DETAIL_WEB:
1061 case EC_DETAIL_FULL: {
1062 double dTimestamp = 0.0;
1063 if (request->GetTagByName(EC_TAG_STATSGRAPH_LAST) != NULL) {
1064 dTimestamp = request->GetTagByName(EC_TAG_STATSGRAPH_LAST)->GetDoubleData();
1066 uint16 nScale = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE)->GetInt();
1067 uint16 nMaxPoints = request->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH)->GetInt();
1068 uint32 *graphData;
1069 unsigned int numPoints = theApp->m_statistics->GetHistoryForWeb(nMaxPoints, (double)nScale, &dTimestamp, &graphData);
1070 if (numPoints) {
1071 response = new CECPacket(EC_OP_STATSGRAPHS);
1072 response->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA, 4 * numPoints * sizeof(uint32), graphData));
1073 delete [] graphData;
1074 response->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST, dTimestamp));
1075 } else {
1076 response = new CECPacket(EC_OP_FAILED);
1077 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("No points for graph.")));
1079 break;
1081 case EC_DETAIL_INC_UPDATE:
1082 case EC_DETAIL_UPDATE:
1083 case EC_DETAIL_CMD:
1084 // No graphs
1085 response = new CECPacket(EC_OP_FAILED);
1086 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Your client is not configured for this detail level.")));
1087 break;
1089 if (!response) {
1090 response = new CECPacket(EC_OP_FAILED);
1091 // Unknown reason
1094 return response;
1097 CECPacket *CECServerSocket::ProcessRequest2(const CECPacket *request,
1098 CPartFile_Encoder_Map &enc_part_map, CKnownFile_Encoder_Map &enc_shared_map, CObjTagMap &objmap)
1101 if ( !request ) {
1102 return 0;
1105 CECPacket *response = NULL;
1107 switch (request->GetOpCode()) {
1109 // Misc commands
1111 case EC_OP_SHUTDOWN:
1112 if (!theApp->IsOnShutDown()) {
1113 response = new CECPacket(EC_OP_NOOP);
1114 AddLogLineM(true, _("External Connection: shutdown requested"));
1115 #ifndef AMULE_DAEMON
1117 wxCloseEvent evt;
1118 evt.SetCanVeto(false);
1119 theApp->ShutDown(evt);
1121 #else
1122 theApp->ExitMainLoop();
1123 #endif
1124 } else {
1125 response = new CECPacket(EC_OP_FAILED);
1126 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already shutting down.")));
1128 break;
1129 case EC_OP_ADD_LINK:
1130 for(unsigned int i = 0; i < request->GetTagCount();i++) {
1131 const CECTag *tag = request->GetTagByIndex(i);
1132 wxString link = tag->GetStringData();
1133 int category = 0;
1134 const CECTag *cattag = tag->GetTagByName(EC_TAG_PARTFILE_CAT);
1135 if (cattag) {
1136 category = cattag->GetInt();
1138 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link);
1139 if ( theApp->downloadqueue->AddLink(link, category) ) {
1140 response = new CECPacket(EC_OP_NOOP);
1141 } else {
1142 // Error messages are printed by the add function.
1143 response = new CECPacket(EC_OP_FAILED);
1144 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid link or already on list.")));
1147 break;
1149 // Status requests
1151 case EC_OP_STAT_REQ:
1152 response = Get_EC_Response_StatRequest(request, m_LoggerAccess);
1153 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1154 break;
1155 case EC_OP_GET_CONNSTATE:
1156 response = new CECPacket(EC_OP_MISC_DATA);
1157 response->AddTag(CEC_ConnState_Tag(request->GetDetailLevel()));
1158 break;
1162 case EC_OP_GET_SHARED_FILES:
1163 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1164 response = Get_EC_Response_GetSharedFiles(enc_shared_map, objmap);
1165 } else {
1166 response = Get_EC_Response_GetSharedFiles(request, enc_shared_map);
1168 break;
1169 case EC_OP_GET_DLOAD_QUEUE:
1170 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1171 response = Get_EC_Response_GetDownloadQueue(enc_part_map, objmap);
1172 } else {
1173 response = Get_EC_Response_GetDownloadQueue(request, enc_part_map);
1175 break;
1176 case EC_OP_GET_ULOAD_QUEUE:
1177 response = Get_EC_Response_GetClientQueue(request, objmap, EC_OP_ULOAD_QUEUE);
1178 break;
1179 case EC_OP_GET_WAIT_QUEUE:
1180 response = Get_EC_Response_GetClientQueue(request, objmap, EC_OP_WAIT_QUEUE);
1181 break;
1182 case EC_OP_PARTFILE_REMOVE_NO_NEEDED:
1183 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE:
1184 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE:
1185 case EC_OP_PARTFILE_CLEANUP_SOURCES:
1186 case EC_OP_PARTFILE_SWAP_A4AF_THIS:
1187 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO:
1188 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS:
1189 case EC_OP_PARTFILE_PAUSE:
1190 case EC_OP_PARTFILE_RESUME:
1191 case EC_OP_PARTFILE_STOP:
1192 case EC_OP_PARTFILE_PRIO_SET:
1193 case EC_OP_PARTFILE_DELETE:
1194 case EC_OP_PARTFILE_SET_CAT:
1195 response = Get_EC_Response_PartFile_Cmd(request);
1196 break;
1197 case EC_OP_SHAREDFILES_RELOAD:
1198 theApp->sharedfiles->Reload();
1199 response = new CECPacket(EC_OP_NOOP);
1200 break;
1201 case EC_OP_SHARED_SET_PRIO:
1202 response = Get_EC_Response_Set_SharedFile_Prio(request);
1203 break;
1204 case EC_OP_RENAME_FILE: {
1205 CMD4Hash fileHash = request->GetTagByNameSafe(EC_TAG_KNOWNFILE)->GetMD4Data();
1206 CKnownFile* file = theApp->knownfiles->FindKnownFileByID(fileHash);
1207 wxString newName = request->GetTagByNameSafe(EC_TAG_PARTFILE_NAME)->GetStringData();
1208 if (!file) {
1209 file = theApp->downloadqueue->GetFileByID(fileHash);
1211 if (!file) {
1212 response = new CECPacket(EC_OP_FAILED);
1213 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("File not found.")));
1214 break;
1216 if (newName.IsEmpty()) {
1217 response = new CECPacket(EC_OP_FAILED);
1218 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid file name.")));
1219 break;
1222 if (theApp->sharedfiles->RenameFile(file, CPath(newName))) {
1223 response = new CECPacket(EC_OP_NOOP);
1224 } else {
1225 response = new CECPacket(EC_OP_FAILED);
1226 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Unable to rename file.")));
1229 break;
1234 // Server commands
1236 case EC_OP_SERVER_ADD:
1237 response = Get_EC_Response_Server_Add(request);
1238 break;
1239 case EC_OP_SERVER_DISCONNECT:
1240 case EC_OP_SERVER_CONNECT:
1241 case EC_OP_SERVER_REMOVE:
1242 response = Get_EC_Response_Server(request);
1243 break;
1244 case EC_OP_GET_SERVER_LIST: {
1245 response = new CECPacket(EC_OP_SERVER_LIST);
1246 if (!thePrefs::GetNetworkED2K()) {
1247 // Kad only: just send an empty list
1248 break;
1250 EC_DETAIL_LEVEL detail_level = request->GetDetailLevel();
1251 std::vector<const CServer*> servers = theApp->serverlist->CopySnapshot();
1252 for (
1253 std::vector<const CServer*>::const_iterator it = servers.begin();
1254 it != servers.end();
1255 ++it
1257 response->AddTag(CEC_Server_Tag(*it, detail_level));
1260 break;
1261 case EC_OP_SERVER_UPDATE_FROM_URL: {
1262 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1264 // Save the new url, and update the UI (if not amuled).
1265 Notify_ServersURLChanged(url);
1266 thePrefs::SetEd2kServersUrl(url);
1268 theApp->serverlist->UpdateServerMetFromURL(url);
1269 response = new CECPacket(EC_OP_NOOP);
1270 break;
1273 // IPFilter
1275 case EC_OP_IPFILTER_RELOAD:
1276 theApp->ipfilter->Reload();
1277 response = new CECPacket(EC_OP_NOOP);
1278 break;
1280 case EC_OP_IPFILTER_UPDATE: {
1281 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1282 if (url == wxEmptyString) {
1283 url = thePrefs::IPFilterURL();
1285 theApp->ipfilter->Update(url);
1286 response = new CECPacket(EC_OP_NOOP);
1287 break;
1290 // Search
1292 case EC_OP_SEARCH_START:
1293 response = Get_EC_Response_Search(request);
1294 break;
1296 case EC_OP_SEARCH_STOP:
1297 response = Get_EC_Response_Search_Stop(request);
1298 break;
1300 case EC_OP_SEARCH_RESULTS:
1301 if ( request->GetDetailLevel() == EC_DETAIL_INC_UPDATE ) {
1302 response = Get_EC_Response_Search_Results(objmap);
1303 } else {
1304 response = Get_EC_Response_Search_Results(request);
1306 break;
1308 case EC_OP_SEARCH_PROGRESS:
1309 response = new CECPacket(EC_OP_SEARCH_PROGRESS);
1310 response->AddTag(CECTag(EC_TAG_SEARCH_STATUS,
1311 theApp->searchlist->GetSearchProgress()));
1312 break;
1314 case EC_OP_DOWNLOAD_SEARCH_RESULT:
1315 response = Get_EC_Response_Search_Results_Download(request);
1316 break;
1318 // Preferences
1320 case EC_OP_GET_PREFERENCES:
1321 response = new CEC_Prefs_Packet(request->GetTagByNameSafe(EC_TAG_SELECT_PREFS)->GetInt(), request->GetDetailLevel());
1322 break;
1323 case EC_OP_SET_PREFERENCES:
1324 ((CEC_Prefs_Packet *)request)->Apply();
1325 theApp->glob_prefs->Save();
1326 if (thePrefs::IsFilteringClients()) {
1327 theApp->clientlist->FilterQueues();
1329 if (thePrefs::IsFilteringServers()) {
1330 theApp->serverlist->FilterServers();
1332 if (!thePrefs::GetNetworkED2K() && theApp->IsConnectedED2K()) {
1333 theApp->DisconnectED2K();
1335 if (!thePrefs::GetNetworkKademlia() && theApp->IsConnectedKad()) {
1336 theApp->StopKad();
1338 response = new CECPacket(EC_OP_NOOP);
1339 break;
1341 case EC_OP_CREATE_CATEGORY:
1342 if ( request->GetTagCount() == 1 ) {
1343 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetTagByIndex(0);
1344 if (tag->Create()) {
1345 response = new CECPacket(EC_OP_NOOP);
1346 } else {
1347 response = new CECPacket(EC_OP_FAILED);
1348 response->AddTag(CECTag(EC_TAG_CATEGORY, theApp->glob_prefs->GetCatCount() - 1));
1349 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1351 Notify_CategoryAdded();
1352 } else {
1353 response = new CECPacket(EC_OP_NOOP);
1355 break;
1356 case EC_OP_UPDATE_CATEGORY:
1357 if ( request->GetTagCount() == 1 ) {
1358 CEC_Category_Tag *tag = (CEC_Category_Tag *)request->GetTagByIndex(0);
1359 if (tag->Apply()) {
1360 response = new CECPacket(EC_OP_NOOP);
1361 } else {
1362 response = new CECPacket(EC_OP_FAILED);
1363 response->AddTag(CECTag(EC_TAG_CATEGORY, tag->GetInt()));
1364 response->AddTag(CECTag(EC_TAG_CATEGORY_PATH, tag->Path()));
1366 Notify_CategoryUpdate(tag->GetInt());
1367 } else {
1368 response = new CECPacket(EC_OP_NOOP);
1370 break;
1371 case EC_OP_DELETE_CATEGORY:
1372 if ( request->GetTagCount() == 1 ) {
1373 uint32 cat = request->GetTagByIndex(0)->GetInt();
1374 // this noes not only update the gui, but actually deletes the cat
1375 Notify_CategoryDelete(cat);
1377 response = new CECPacket(EC_OP_NOOP);
1378 break;
1381 // Logging
1383 case EC_OP_ADDLOGLINE:
1384 AddLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1385 response = new CECPacket(EC_OP_NOOP);
1386 break;
1387 case EC_OP_ADDDEBUGLOGLINE:
1388 AddDebugLogLineM( (request->GetTagByName(EC_TAG_LOG_TO_STATUS) != NULL), logGeneral, request->GetTagByNameSafe(EC_TAG_STRING)->GetStringData() );
1389 response = new CECPacket(EC_OP_NOOP);
1390 break;
1391 case EC_OP_GET_LOG:
1392 response = new CECPacket(EC_OP_LOG);
1393 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetLog(false)));
1394 break;
1395 case EC_OP_GET_DEBUGLOG:
1396 response = new CECPacket(EC_OP_DEBUGLOG);
1397 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetDebugLog(false)));
1398 break;
1399 case EC_OP_RESET_LOG:
1400 theApp->GetLog(true);
1401 response = new CECPacket(EC_OP_NOOP);
1402 break;
1403 case EC_OP_RESET_DEBUGLOG:
1404 theApp->GetDebugLog(true);
1405 response = new CECPacket(EC_OP_NOOP);
1406 break;
1407 case EC_OP_GET_LAST_LOG_ENTRY:
1409 wxString tmp = theApp->GetLog(false);
1410 if (tmp.Last() == '\n') {
1411 tmp.RemoveLast();
1413 response = new CECPacket(EC_OP_LOG);
1414 response->AddTag(CECTag(EC_TAG_STRING, tmp.AfterLast('\n')));
1416 break;
1417 case EC_OP_GET_SERVERINFO:
1418 response = new CECPacket(EC_OP_SERVERINFO);
1419 response->AddTag(CECTag(EC_TAG_STRING, theApp->GetServerLog(false)));
1420 break;
1421 case EC_OP_CLEAR_SERVERINFO:
1422 theApp->GetServerLog(true);
1423 response = new CECPacket(EC_OP_NOOP);
1424 break;
1426 // Statistics
1428 case EC_OP_GET_STATSGRAPHS:
1429 response = GetStatsGraphs(request);
1430 break;
1431 case EC_OP_GET_STATSTREE: {
1432 theApp->m_statistics->UpdateStatsTree();
1433 response = new CECPacket(EC_OP_STATSTREE);
1434 CECTag* tree = theStats::GetECStatTree(request->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING)->GetInt());
1435 if (tree) {
1436 response->AddTag(*tree);
1437 delete tree;
1439 if (request->GetDetailLevel() == EC_DETAIL_WEB) {
1440 response->AddTag(CECTag(EC_TAG_SERVER_VERSION, wxT(VERSION)));
1441 response->AddTag(CECTag(EC_TAG_USER_NICK, thePrefs::GetUserNick()));
1443 break;
1447 // Kad
1449 case EC_OP_KAD_START:
1450 response = Get_EC_Response_Kad_Connect(request);
1451 break;
1452 case EC_OP_KAD_STOP:
1453 theApp->StopKad();
1454 response = new CECPacket(EC_OP_NOOP);
1455 break;
1456 case EC_OP_KAD_UPDATE_FROM_URL: {
1457 wxString url = request->GetTagByIndexSafe(0)->GetStringData();
1459 // Save the new url, and update the UI (if not amuled).
1460 Notify_NodesURLChanged(url);
1461 thePrefs::SetKadNodesUrl(url);
1463 theApp->UpdateNotesDat(url);
1464 response = new CECPacket(EC_OP_NOOP);
1465 break;
1467 case EC_OP_KAD_BOOTSTRAP_FROM_IP:
1468 theApp->BootstrapKad(request->GetTagByIndexSafe(0)->GetInt(),
1469 request->GetTagByIndexSafe(1)->GetInt());
1470 response = new CECPacket(EC_OP_NOOP);
1471 break;
1474 // Networks
1476 case EC_OP_CONNECT:
1477 if (thePrefs::GetNetworkED2K()) {
1478 response = new CECPacket(EC_OP_STRINGS);
1479 if (theApp->IsConnectedED2K()) {
1480 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to eD2k.")));
1481 } else {
1482 theApp->serverconnect->ConnectToAnyServer();
1483 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to eD2k...")));
1486 if (thePrefs::GetNetworkKademlia()) {
1487 if (!response) {
1488 response = new CECPacket(EC_OP_STRINGS);
1490 if (theApp->IsConnectedKad()) {
1491 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Already connected to Kad.")));
1492 } else {
1493 theApp->StartKad();
1494 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Connecting to Kad...")));
1497 if (!response) {
1498 response = new CECPacket(EC_OP_FAILED);
1499 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("All networks are disabled.")));
1501 break;
1502 case EC_OP_DISCONNECT:
1503 if (theApp->IsConnected()) {
1504 response = new CECPacket(EC_OP_STRINGS);
1505 if (theApp->IsConnectedED2K()) {
1506 theApp->serverconnect->Disconnect();
1507 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from eD2k.")));
1509 if (theApp->IsConnectedKad()) {
1510 theApp->StopKad();
1511 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Disconnected from Kad.")));
1513 } else {
1514 response = new CECPacket(EC_OP_NOOP);
1516 break;
1518 default:
1519 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request->GetOpCode()));
1520 wxFAIL;
1521 response = new CECPacket(EC_OP_FAILED);
1522 response->AddTag(CECTag(EC_TAG_STRING, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1523 break;
1525 return response;
1529 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1533 * Core general status
1535 ECStatusMsgSource::ECStatusMsgSource()
1537 m_last_ed2k_status_sent = 0xffffffff;
1538 m_last_kad_status_sent = 0xffffffff;
1539 m_server = (void *)0xffffffff;
1542 uint32 ECStatusMsgSource::GetEd2kStatus()
1544 if ( theApp->IsConnectedED2K() ) {
1545 return theApp->GetED2KID();
1546 } else if ( theApp->serverconnect->IsConnecting() ) {
1547 return 1;
1548 } else {
1549 return 0;
1553 uint32 ECStatusMsgSource::GetKadStatus()
1555 if ( theApp->IsConnectedKad() ) {
1556 return 1;
1557 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1558 return 2;
1559 } else if ( Kademlia::CKademlia::IsRunning() ) {
1560 return 3;
1562 return 0;
1565 CECPacket *ECStatusMsgSource::GetNextPacket()
1567 if ( (m_last_ed2k_status_sent != GetEd2kStatus()) ||
1568 (m_last_kad_status_sent != GetKadStatus()) ||
1569 (m_server != theApp->serverconnect->GetCurrentServer()) ) {
1571 m_last_ed2k_status_sent = GetEd2kStatus();
1572 m_last_kad_status_sent = GetKadStatus();
1573 m_server = theApp->serverconnect->GetCurrentServer();
1575 CECPacket *response = new CECPacket(EC_OP_STATS);
1576 response->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE));
1577 return response;
1579 return 0;
1583 * Downloading files
1585 ECPartFileMsgSource::ECPartFileMsgSource()
1587 for (unsigned int i = 0; i < theApp->downloadqueue->GetFileCount(); i++) {
1588 CPartFile *cur_file = theApp->downloadqueue->GetFileByIndex(i);
1589 PARTFILE_STATUS status = { true, false, false, false, true, cur_file };
1590 m_dirty_status[cur_file->GetFileHash()] = status;
1594 void ECPartFileMsgSource::SetDirty(CPartFile *file)
1596 CMD4Hash filehash = file->GetFileHash();
1597 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1598 m_dirty_status[filehash].m_dirty = true;;
1602 void ECPartFileMsgSource::SetNew(CPartFile *file)
1604 CMD4Hash filehash = file->GetFileHash();
1605 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1606 PARTFILE_STATUS status = { true, false, false, false, true, file };
1607 m_dirty_status[filehash] = status;
1610 void ECPartFileMsgSource::SetCompleted(CPartFile *file)
1612 CMD4Hash filehash = file->GetFileHash();
1613 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1615 m_dirty_status[filehash].m_finished = true;
1618 void ECPartFileMsgSource::SetRemoved(CPartFile *file)
1620 CMD4Hash filehash = file->GetFileHash();
1621 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1623 m_dirty_status[filehash].m_removed = true;
1626 CECPacket *ECPartFileMsgSource::GetNextPacket()
1628 for(std::map<CMD4Hash, PARTFILE_STATUS>::iterator it = m_dirty_status.begin();
1629 it != m_dirty_status.end(); it++) {
1630 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1631 CMD4Hash filehash = it->first;
1633 CPartFile *partfile = it->second.m_file;
1635 CECPacket *packet = new CECPacket(EC_OP_DLOAD_QUEUE);
1636 if ( it->second.m_removed ) {
1637 CECTag tag(EC_TAG_PARTFILE, filehash);
1638 packet->AddTag(tag);
1639 m_dirty_status.erase(it);
1640 } else {
1641 CEC_PartFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1642 packet->AddTag(tag);
1644 m_dirty_status[filehash].m_new = false;
1645 m_dirty_status[filehash].m_dirty = false;
1647 return packet;
1650 return 0;
1654 * Shared files - similar to downloading
1656 ECKnownFileMsgSource::ECKnownFileMsgSource()
1658 for (unsigned int i = 0; i < theApp->sharedfiles->GetFileCount(); i++) {
1659 CKnownFile *cur_file = (CKnownFile *)theApp->sharedfiles->GetFileByIndex(i);
1660 KNOWNFILE_STATUS status = { true, false, false, true, cur_file };
1661 m_dirty_status[cur_file->GetFileHash()] = status;
1665 void ECKnownFileMsgSource::SetDirty(CKnownFile *file)
1667 CMD4Hash filehash = file->GetFileHash();
1668 if ( m_dirty_status.find(filehash) != m_dirty_status.end() ) {
1669 m_dirty_status[filehash].m_dirty = true;;
1673 void ECKnownFileMsgSource::SetNew(CKnownFile *file)
1675 CMD4Hash filehash = file->GetFileHash();
1676 wxASSERT ( m_dirty_status.find(filehash) == m_dirty_status.end() );
1677 KNOWNFILE_STATUS status = { true, false, false, true, file };
1678 m_dirty_status[filehash] = status;
1681 void ECKnownFileMsgSource::SetRemoved(CKnownFile *file)
1683 CMD4Hash filehash = file->GetFileHash();
1684 wxASSERT ( m_dirty_status.find(filehash) != m_dirty_status.end() );
1686 m_dirty_status[filehash].m_removed = true;
1689 CECPacket *ECKnownFileMsgSource::GetNextPacket()
1691 for(std::map<CMD4Hash, KNOWNFILE_STATUS>::iterator it = m_dirty_status.begin();
1692 it != m_dirty_status.end(); it++) {
1693 if ( it->second.m_new || it->second.m_dirty || it->second.m_removed) {
1694 CMD4Hash filehash = it->first;
1696 CKnownFile *partfile = it->second.m_file;
1698 CECPacket *packet = new CECPacket(EC_OP_SHARED_FILES);
1699 if ( it->second.m_removed ) {
1700 CECTag tag(EC_TAG_PARTFILE, filehash);
1701 packet->AddTag(tag);
1702 m_dirty_status.erase(it);
1703 } else {
1704 CEC_SharedFile_Tag tag(partfile, it->second.m_new ? EC_DETAIL_FULL : EC_DETAIL_UPDATE);
1705 packet->AddTag(tag);
1707 m_dirty_status[filehash].m_new = false;
1708 m_dirty_status[filehash].m_dirty = false;
1710 return packet;
1713 return 0;
1717 * Notification about search status
1719 ECSearchMsgSource::ECSearchMsgSource()
1723 CECPacket *ECSearchMsgSource::GetNextPacket()
1725 if ( m_dirty_status.empty() ) {
1726 return 0;
1729 CECPacket *response = new CECPacket(EC_OP_SEARCH_RESULTS);
1730 for(std::map<CMD4Hash, SEARCHFILE_STATUS>::iterator it = m_dirty_status.begin();
1731 it != m_dirty_status.end(); it++) {
1733 if ( it->second.m_new ) {
1734 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_FULL));
1735 it->second.m_new = false;
1736 } else if ( it->second.m_dirty ) {
1737 response->AddTag(CEC_SearchFile_Tag(it->second.m_file, EC_DETAIL_UPDATE));
1742 return response;
1745 void ECSearchMsgSource::FlushStatus()
1747 m_dirty_status.clear();
1750 void ECSearchMsgSource::SetDirty(CSearchFile *file)
1752 if ( m_dirty_status.count(file->GetFileHash()) ) {
1753 m_dirty_status[file->GetFileHash()].m_dirty = true;
1754 } else {
1755 m_dirty_status[file->GetFileHash()].m_new = true;
1756 m_dirty_status[file->GetFileHash()].m_dirty = true;
1757 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1758 m_dirty_status[file->GetFileHash()].m_file = file;
1762 void ECSearchMsgSource::SetChildDirty(CSearchFile *file)
1764 m_dirty_status[file->GetFileHash()].m_child_dirty = true;
1768 * Notification about uploading clients
1770 CECPacket *ECClientMsgSource::GetNextPacket()
1772 return 0;
1776 // Notification iface per-client
1778 ECNotifier::ECNotifier()
1782 CECPacket *ECNotifier::GetNextPacket(ECUpdateMsgSource *msg_source_array[])
1784 CECPacket *packet = 0;
1786 // priority 0 is highest
1788 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1789 if ( (packet = msg_source_array[i]->GetNextPacket()) != 0 ) {
1790 break;
1793 return packet;
1796 CECPacket *ECNotifier::GetNextPacket(CECServerSocket *sock)
1799 // OnOutput is called for a first time before
1800 // socket is registered
1802 if ( m_msg_source.count(sock) ) {
1803 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1804 if ( !notifier_array ) {
1805 return 0;
1807 CECPacket *packet = GetNextPacket(notifier_array);
1808 printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
1809 return packet;
1810 } else {
1811 return 0;
1816 // Interface to notification macros
1818 void ECNotifier::DownloadFile_SetDirty(CPartFile *file)
1820 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1821 i != m_msg_source.end(); i++) {
1822 CECServerSocket *sock = i->first;
1823 if ( sock->HaveNotificationSupport() ) {
1824 ECUpdateMsgSource **notifier_array = i->second;
1825 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetDirty(file);
1828 NextPacketToSocket();
1831 void ECNotifier::DownloadFile_RemoveFile(CPartFile *file)
1833 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1834 i != m_msg_source.end(); i++) {
1835 ECUpdateMsgSource **notifier_array = i->second;
1836 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetRemoved(file);
1838 NextPacketToSocket();
1841 void ECNotifier::DownloadFile_RemoveSource(CPartFile *)
1843 // per-partfile source list is not supported (yet), and IMHO quite useless
1846 void ECNotifier::DownloadFile_AddFile(CPartFile *file)
1848 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1849 i != m_msg_source.end(); i++) {
1850 ECUpdateMsgSource **notifier_array = i->second;
1851 ((ECPartFileMsgSource *)notifier_array[EC_PARTFILE])->SetNew(file);
1853 NextPacketToSocket();
1856 void ECNotifier::DownloadFile_AddSource(CPartFile *)
1858 // per-partfile source list is not supported (yet), and IMHO quite useless
1861 void ECNotifier::SharedFile_AddFile(CKnownFile *file)
1863 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1864 i != m_msg_source.end(); i++) {
1865 ECUpdateMsgSource **notifier_array = i->second;
1866 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetNew(file);
1868 NextPacketToSocket();
1871 void ECNotifier::SharedFile_RemoveFile(CKnownFile *file)
1873 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1874 i != m_msg_source.end(); i++) {
1875 ECUpdateMsgSource **notifier_array = i->second;
1876 ((ECKnownFileMsgSource *)notifier_array[EC_KNOWN])->SetRemoved(file);
1878 NextPacketToSocket();
1881 void ECNotifier::SharedFile_RemoveAllFiles()
1883 // need to figure out what to do here
1886 void ECNotifier::Add_EC_Client(CECServerSocket *sock)
1888 ECUpdateMsgSource **notifier_array = new ECUpdateMsgSource *[EC_STATUS_LAST_PRIO];
1889 notifier_array[EC_STATUS] = new ECStatusMsgSource();
1890 notifier_array[EC_SEARCH] = new ECSearchMsgSource();
1891 notifier_array[EC_PARTFILE] = new ECPartFileMsgSource();
1892 notifier_array[EC_CLIENT] = new ECClientMsgSource();
1893 notifier_array[EC_KNOWN] = new ECKnownFileMsgSource();
1895 m_msg_source[sock] = notifier_array;
1898 void ECNotifier::Remove_EC_Client(CECServerSocket *sock)
1900 if (m_msg_source.count(sock)) {
1901 ECUpdateMsgSource **notifier_array = m_msg_source[sock];
1903 m_msg_source.erase(sock);
1905 for(int i = 0; i < EC_STATUS_LAST_PRIO; i++) {
1906 delete notifier_array[i];
1908 delete [] notifier_array;
1912 void ECNotifier::NextPacketToSocket()
1914 for(std::map<CECServerSocket *, ECUpdateMsgSource **>::iterator i = m_msg_source.begin();
1915 i != m_msg_source.end(); i++) {
1916 CECServerSocket *sock = i->first;
1917 if ( sock->HaveNotificationSupport() && !sock->DataPending() ) {
1918 ECUpdateMsgSource **notifier_array = i->second;
1919 CECPacket *packet = GetNextPacket(notifier_array);
1920 if ( packet ) {
1921 printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
1922 sock->SendPacket(packet);
1928 // File_checked_for_headers