2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2011 Kry ( elkry@sourceforge.net / http://www.amule.org )
5 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Copyright (c) 2008-2011 Froenchenko Leonid (lfroen@gmail.com)
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.
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
28 #include "config.h" // Needed for VERSION
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 "ClientList.h"
48 #include "Preferences.h" // Needed for CPreferences
50 #include "GuiEvents.h" // Needed for Notify_* macros
51 #include "Statistics.h" // Needed for theStats
52 #include "KnownFileList.h" // Needed for CKnownFileList
54 #include "FriendList.h"
55 #include "RandomFunctions.h"
56 #include "kademlia/kademlia/Kademlia.h"
57 #include "kademlia/kademlia/UDPFirewallTester.h"
58 #include "Statistics.h"
61 //-------------------- File_Encoder --------------------
65 * Encode 'obtained parts' info to be sent to remote gui
67 class CKnownFile_Encoder
{
68 // number of sources for each part for progress bar colouring
71 const CKnownFile
*m_file
;
73 CKnownFile_Encoder(const CKnownFile
*file
= 0) { m_file
= file
; }
75 virtual ~CKnownFile_Encoder() {}
77 virtual void Encode(CECTag
*parent_tag
);
79 virtual void ResetEncoder()
81 m_enc_data
.ResetEncoder();
84 virtual void SetShared() { }
85 virtual bool IsShared() { return true; }
86 virtual bool IsPartFile_Encoder() { return false; }
87 const CKnownFile
* GetFile() { return m_file
; }
91 * PartStatus strings and gap lists are quite long - RLE encoding will help.
93 * Instead of sending each time full part-status string, send
94 * RLE encoded difference from previous one.
96 * PartFileEncoderData class is used for decode only,
97 * while CPartFile_Encoder is used for encode only.
99 class CPartFile_Encoder
: public CKnownFile_Encoder
{
100 // blocks requested for download
101 RLE_Data m_req_status
;
103 RLE_Data m_gap_status
;
105 SourcenameItemMap m_sourcenameItemMap
;
106 // counter for unique source name ids
108 // not all part files are shared (only when at least one part is complete)
111 // cast inherited member to CPartFile
112 const CPartFile
* m_PartFile() { wxCHECK(m_file
->IsCPartFile(), NULL
); return static_cast<const CPartFile
*>(m_file
); }
115 CPartFile_Encoder(const CPartFile
*file
= 0) : CKnownFile_Encoder(file
)
121 virtual ~CPartFile_Encoder() {}
123 // encode - take data from m_file
124 virtual void Encode(CECTag
*parent_tag
);
126 // Encoder may reset history if full info requested
127 virtual void ResetEncoder();
129 virtual void SetShared() { m_shared
= true; }
130 virtual bool IsShared() { return m_shared
; }
131 virtual bool IsPartFile_Encoder() { return true; }
134 class CFileEncoderMap
: public std::map
<uint32
, CKnownFile_Encoder
*> {
135 typedef std::set
<uint32
> IDSet
;
138 void UpdateEncoders();
141 CFileEncoderMap::~CFileEncoderMap()
143 // DeleteContents() causes infinite recursion here!
144 for (iterator it
= begin(); it
!= end(); ++it
) {
149 // Check if encoder contains files that are no longer used
150 // or if we have new files without encoder yet.
151 void CFileEncoderMap::UpdateEncoders()
153 IDSet curr_files
, dead_files
;
155 std::vector
<CPartFile
*> downloads
;
156 theApp
->downloadqueue
->CopyFileList(downloads
, true);
157 for (uint32 i
= downloads
.size(); i
--;) {
158 uint32 id
= downloads
[i
]->ECID();
159 curr_files
.insert(id
);
161 (*this)[id
] = new CPartFile_Encoder(downloads
[i
]);
165 std::vector
<CKnownFile
*> shares
;
166 theApp
->sharedfiles
->CopyFileList(shares
);
167 for (uint32 i
= shares
.size(); i
--;) {
168 uint32 id
= shares
[i
]->ECID();
169 // Check if it is already there.
170 // The curr_files.count(id) is enough, the IsCPartFile() is just a speedup.
171 if (shares
[i
]->IsCPartFile() && curr_files
.count(id
)) {
172 (*this)[id
]->SetShared();
175 curr_files
.insert(id
);
177 (*this)[id
] = new CKnownFile_Encoder(shares
[i
]);
180 // Check for removed files, and store them in a set for deletion.
181 // (std::map documentation is unclear if a construct like
182 // iterator to_del = it++; erase(to_del) ;
183 // works or invalidates it too.)
184 for (iterator it
= begin(); it
!= end(); ++it
) {
185 if (!curr_files
.count(it
->first
)) {
186 dead_files
.insert(it
->first
);
190 for (IDSet::iterator it
= dead_files
.begin(); it
!= dead_files
.end(); ++it
) {
191 iterator it2
= find(*it
);
198 //-------------------- CECServerSocket --------------------
200 class CECServerSocket
: public CECMuleSocket
203 CECServerSocket(ECNotifier
*notifier
);
204 virtual ~CECServerSocket();
206 virtual const CECPacket
*OnPacketReceived(const CECPacket
*packet
, uint32 trueSize
);
207 virtual void OnLost();
209 virtual void WriteDoneAndQueueEmpty();
211 void ResetLog() { m_LoggerAccess
.Reset(); }
213 ECNotifier
*m_ec_notifier
;
215 const CECPacket
*Authenticate(const CECPacket
*);
224 uint64_t m_passwd_salt
;
225 CLoggerAccess m_LoggerAccess
;
226 CFileEncoderMap m_FileEncoder
;
227 CObjTagMap m_obj_tagmap
;
228 CECPacket
*ProcessRequest2(const CECPacket
*request
);
230 virtual bool IsAuthorized() { return m_conn_state
== CONN_ESTABLISHED
; }
234 CECServerSocket::CECServerSocket(ECNotifier
*notifier
)
237 m_conn_state(CONN_INIT
),
238 m_passwd_salt(GetRandomUint64())
240 wxASSERT(theApp
->ECServerHandler
);
241 theApp
->ECServerHandler
->AddSocket(this);
242 m_ec_notifier
= notifier
;
246 CECServerSocket::~CECServerSocket()
248 wxASSERT(theApp
->ECServerHandler
);
249 theApp
->ECServerHandler
->RemoveSocket(this);
253 const CECPacket
*CECServerSocket::OnPacketReceived(const CECPacket
*packet
, uint32 trueSize
)
255 packet
->DebugPrint(true, trueSize
);
257 const CECPacket
*reply
= NULL
;
259 if (m_conn_state
== CONN_FAILED
) {
260 // Client didn't close the socket when authentication failed.
261 AddLogLineN(_("Client sent packet after authentication failed."));
265 if (m_conn_state
!= CONN_ESTABLISHED
) {
266 // This is called twice:
268 // 2) verify password
269 reply
= Authenticate(packet
);
271 reply
= ProcessRequest2(packet
);
277 void CECServerSocket::OnLost()
279 AddLogLineN(_("External connection closed."));
280 theApp
->ECServerHandler
->m_ec_notifier
->Remove_EC_Client(this);
284 void CECServerSocket::WriteDoneAndQueueEmpty()
286 if ( HaveNotificationSupport() && (m_conn_state
== CONN_ESTABLISHED
) ) {
287 CECPacket
*packet
= m_ec_notifier
->GetNextPacket(this);
292 //printf("[EC] %p: WriteDoneAndQueueEmpty but notification disabled\n", this);
296 //-------------------- ExternalConn --------------------
304 BEGIN_EVENT_TABLE(ExternalConn
, wxEvtHandler
)
305 EVT_SOCKET(SERVER_ID
, ExternalConn::OnServerEvent
)
309 ExternalConn::ExternalConn(amuleIPV4Address addr
, wxString
*msg
)
313 // Are we allowed to accept External Connections?
314 if ( thePrefs::AcceptExternalConnections() ) {
315 // We must have a valid password, otherwise we will not allow EC connections
316 if (thePrefs::ECPassword().IsEmpty()) {
317 *msg
+= wxT("External connections disabled due to empty password!\n");
318 AddLogLineC(_("External connections disabled due to empty password!"));
323 m_ECServer
= new CExternalConnListener(addr
, wxSOCKET_REUSEADDR
, this);
324 m_ECServer
->SetEventHandler(*this, SERVER_ID
);
325 m_ECServer
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
326 m_ECServer
->Notify(true);
328 int port
= addr
.Service();
329 wxString ip
= addr
.IPAddress();
330 if (m_ECServer
->IsOk()) {
331 msgLocal
= CFormat(wxT("*** TCP socket (ECServer) listening on %s:%d")) % ip
% port
;
332 *msg
+= msgLocal
+ wxT("\n");
333 AddLogLineN(msgLocal
);
335 msgLocal
= CFormat(wxT("Could not listen for external connections at %s:%d!")) % ip
% port
;
336 *msg
+= msgLocal
+ wxT("\n");
337 AddLogLineN(msgLocal
);
340 *msg
+= wxT("External connections disabled in config file\n");
341 AddLogLineN(_("External connections disabled in config file"));
343 m_ec_notifier
= new ECNotifier();
347 ExternalConn::~ExternalConn()
351 delete m_ec_notifier
;
355 void ExternalConn::AddSocket(CECServerSocket
*s
)
358 socket_list
.insert(s
);
362 void ExternalConn::RemoveSocket(CECServerSocket
*s
)
365 socket_list
.erase(s
);
369 void ExternalConn::KillAllSockets()
371 AddDebugLogLineN(logGeneral
,
372 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
374 SocketSet::iterator it
= socket_list
.begin();
375 while (it
!= socket_list
.end()) {
376 CECServerSocket
*s
= *(it
++);
384 void ExternalConn::ResetAllLogs()
386 SocketSet::iterator it
= socket_list
.begin();
387 while (it
!= socket_list
.end()) {
388 CECServerSocket
*s
= *(it
++);
394 void ExternalConn::OnServerEvent(wxSocketEvent
& WXUNUSED(event
))
396 m_ECServer
->OnAccept();
400 void CExternalConnListener::OnAccept()
402 CECServerSocket
*sock
= new CECServerSocket(m_conn
->m_ec_notifier
);
403 // Accept new connection if there is one in the pending
404 // connections queue, else exit. We use Accept(FALSE) for
405 // non-blocking accept (although if we got here, there
406 // should ALWAYS be a pending connection).
407 if (AcceptWith(*sock
, false)) {
408 AddLogLineN(_("New external connection accepted"));
411 AddLogLineN(_("ERROR: couldn't accept a new external connection"));
419 const CECPacket
*CECServerSocket::Authenticate(const CECPacket
*request
)
423 if (request
== NULL
) {
424 return new CECPacket(EC_OP_AUTH_FAIL
);
427 // Password must be specified if we are to allow remote connections
428 if ( thePrefs::ECPassword().IsEmpty() ) {
429 AddLogLineC(_("External connection refused due to empty password in preferences!"));
431 return new CECPacket(EC_OP_AUTH_FAIL
);
434 if ((m_conn_state
== CONN_INIT
) && (request
->GetOpCode() == EC_OP_AUTH_REQ
) ) {
435 // cppcheck-suppress unreadVariable
436 const CECTag
*clientName
= request
->GetTagByName(EC_TAG_CLIENT_NAME
);
437 // cppcheck-suppress unreadVariable
438 const CECTag
*clientVersion
= request
->GetTagByName(EC_TAG_CLIENT_VERSION
);
440 AddLogLineN(CFormat( _("Connecting client: %s %s") )
441 % ( clientName
? clientName
->GetStringData() : wxString(_("Unknown")) )
442 % ( clientVersion
? clientVersion
->GetStringData() : wxString(_("Unknown version")) ) );
443 const CECTag
*protocol
= request
->GetTagByName(EC_TAG_PROTOCOL_VERSION
);
445 // For SVN versions, both client and server must use SVNDATE, and they must be the same
447 if (!vhash
.Decode(wxT(EC_VERSION_ID
))) {
448 response
= new CECPacket(EC_OP_AUTH_FAIL
);
449 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Fatal error, version hash is not a valid MD4-hash.")));
450 } else if (!request
->GetTagByName(EC_TAG_VERSION_ID
) || request
->GetTagByNameSafe(EC_TAG_VERSION_ID
)->GetMD4Data() != vhash
) {
451 response
= new CECPacket(EC_OP_AUTH_FAIL
);
452 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
454 // For release versions, we don't want to allow connections from any arbitrary SVN client.
455 if (request
->GetTagByName(EC_TAG_VERSION_ID
)) {
456 response
= new CECPacket(EC_OP_AUTH_FAIL
);
457 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("You cannot connect to a release version from an arbitrary development snapshot! *sigh* possible crash prevented")));
459 } else if (protocol
!= NULL
) {
460 uint16 proto_version
= protocol
->GetInt();
461 if (proto_version
== EC_CURRENT_PROTOCOL_VERSION
) {
462 response
= new CECPacket(EC_OP_AUTH_SALT
);
463 response
->AddTag(CECTag(EC_TAG_PASSWD_SALT
, m_passwd_salt
));
464 m_conn_state
= CONN_SALT_SENT
;
466 // So far ok, check capabilities of client
468 if (request
->GetTagByName(EC_TAG_CAN_ZLIB
)) {
469 m_my_flags
|= EC_FLAG_ZLIB
;
471 if (request
->GetTagByName(EC_TAG_CAN_UTF8_NUMBERS
)) {
472 m_my_flags
|= EC_FLAG_UTF8_NUMBERS
;
474 m_haveNotificationSupport
= request
->GetTagByName(EC_TAG_CAN_NOTIFY
) != NULL
;
475 AddDebugLogLineN(logEC
, CFormat(wxT("Client capabilities: ZLIB: %s UTF8 numbers: %s Push notification: %s") )
476 % ((m_my_flags
& EC_FLAG_ZLIB
) ? wxT("yes") : wxT("no"))
477 % ((m_my_flags
& EC_FLAG_UTF8_NUMBERS
) ? wxT("yes") : wxT("no"))
478 % (m_haveNotificationSupport
? wxT("yes") : wxT("no")));
480 response
= new CECPacket(EC_OP_AUTH_FAIL
);
481 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid protocol version.")
482 + CFormat(wxT("( %#.4x != %#.4x )")) % proto_version
% (uint16_t)EC_CURRENT_PROTOCOL_VERSION
));
485 response
= new CECPacket(EC_OP_AUTH_FAIL
);
486 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Missing protocol version tag.")));
488 } else if ((m_conn_state
== CONN_SALT_SENT
) && (request
->GetOpCode() == EC_OP_AUTH_PASSWD
)) {
489 const CECTag
*passwd
= request
->GetTagByName(EC_TAG_PASSWD_HASH
);
492 if (!passh
.Decode(thePrefs::ECPassword())) {
493 wxString err
= wxTRANSLATE("Authentication failed: invalid hash specified as EC password.");
494 AddLogLineN(wxString(wxGetTranslation(err
))
495 + wxT(" ") + thePrefs::ECPassword());
496 response
= new CECPacket(EC_OP_AUTH_FAIL
);
497 response
->AddTag(CECTag(EC_TAG_STRING
, err
));
499 wxString saltHash
= MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt
).GetHash();
500 wxString saltStr
= CFormat(wxT("%lX")) % m_passwd_salt
;
502 passh
.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash
).GetHash());
504 if (passwd
&& passwd
->GetMD4Data() == passh
) {
505 response
= new CECPacket(EC_OP_AUTH_OK
);
506 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
510 err
= wxTRANSLATE("Authentication failed: wrong password.");
512 err
= wxTRANSLATE("Authentication failed: missing password.");
515 response
= new CECPacket(EC_OP_AUTH_FAIL
);
516 response
->AddTag(CECTag(EC_TAG_STRING
, err
));
517 AddLogLineN(wxGetTranslation(err
));
521 response
= new CECPacket(EC_OP_AUTH_FAIL
);
522 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid request, please authenticate first.")));
525 if (response
->GetOpCode() == EC_OP_AUTH_OK
) {
526 m_conn_state
= CONN_ESTABLISHED
;
527 AddLogLineN(_("Access granted."));
528 // Establish notification handler if client supports it
529 if (HaveNotificationSupport()) {
530 theApp
->ECServerHandler
->m_ec_notifier
->Add_EC_Client(this);
532 } else if (response
->GetOpCode() == EC_OP_AUTH_FAIL
) {
533 // Log message sent to client
534 if (response
->GetFirstTagSafe()->IsString()) {
535 AddLogLineN(CFormat(_("Sent error message \"%s\" to client.")) % wxGetTranslation(response
->GetFirstTagSafe()->GetStringData()));
538 AddLogLineN(CFormat(_("Unauthorized access attempt from %s. Connection closed.")) % GetPeer() );
539 m_conn_state
= CONN_FAILED
;
545 // Make a Logger tag (if there are any logging messages) and add it to the response
546 static void AddLoggerTag(CECPacket
*response
, CLoggerAccess
&LoggerAccess
)
548 if (LoggerAccess
.HasString()) {
549 CECEmptyTag
tag(EC_TAG_STATS_LOGGER_MESSAGE
);
550 // Tag structure is fix: tag carries nothing, inside are the strings
551 // maximum of 200 log lines per message
554 while (entries
< 200 && LoggerAccess
.GetString(line
)) {
555 tag
.AddTag(CECTag(EC_TAG_STRING
, line
));
558 response
->AddTag(tag
);
559 //printf("send Log tag %d %d\n", FirstEntry, entries);
563 static CECPacket
*Get_EC_Response_StatRequest(const CECPacket
*request
, CLoggerAccess
&LoggerAccess
)
565 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
567 switch (request
->GetDetailLevel()) {
569 // This is not an actual INC_UPDATE.
570 // amulegui only sets the detail level of the stats package to EC_DETAIL_INC_UPDATE
571 // so that the included conn state tag is created the way it is needed here.
572 case EC_DETAIL_INC_UPDATE
:
573 response
->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD
, (uint32
)theStats::GetUpOverheadRate()));
574 response
->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD
, (uint32
)theStats::GetDownOverheadRate()));
575 response
->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT
, /*(uint32)*/theStats::GetBannedCount()));
576 AddLoggerTag(response
, LoggerAccess
);
577 // Needed only for the remote tray icon context menu
578 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SENT_BYTES
, theStats::GetTotalSentBytes()));
579 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_RECEIVED_BYTES
, theStats::GetTotalReceivedBytes()));
580 response
->AddTag(CECTag(EC_TAG_STATS_SHARED_FILE_COUNT
, theStats::GetSharedFileCount()));
583 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED
, (uint32
)theStats::GetUploadRate()));
584 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED
, (uint32
)(theStats::GetDownloadRate())));
585 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxUpload()*1024.0)));
586 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxDownload()*1024.0)));
587 response
->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN
, /*(uint32)*/theStats::GetWaitingUserCount()));
588 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT
, /*(uint32)*/theStats::GetFoundSources()));
591 uint32 totaluser
= 0, totalfile
= 0;
592 theApp
->serverlist
->GetUserFileStatus( totaluser
, totalfile
);
593 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS
, totaluser
));
594 response
->AddTag(CECTag(EC_TAG_STATS_KAD_USERS
, Kademlia::CKademlia::GetKademliaUsers()));
595 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES
, totalfile
));
596 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FILES
, Kademlia::CKademlia::GetKademliaFiles()));
597 response
->AddTag(CECTag(EC_TAG_STATS_KAD_NODES
, CStatistics::GetKadNodes()));
600 if (Kademlia::CKademlia::IsConnected()) {
601 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP
, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
602 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource
));
603 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS
, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword
));
604 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes
));
605 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD
, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad
));
606 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS
, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
607 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE
, Kademlia::CKademlia::IsRunningInLANMode()));
608 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS
, theApp
->clientlist
->GetBuddyStatus()));
610 uint16 BuddyPort
= 0;
611 CUpDownClient
* Buddy
= theApp
->clientlist
->GetBuddy();
613 BuddyIP
= Buddy
->GetIP();
614 BuddyPort
= Buddy
->GetUDPPort();
616 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP
, BuddyIP
));
617 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT
, BuddyPort
));
619 case EC_DETAIL_UPDATE
:
626 static CECPacket
*Get_EC_Response_GetSharedFiles(const CECPacket
*request
, CFileEncoderMap
&encoders
)
628 wxASSERT(request
->GetOpCode() == EC_OP_GET_SHARED_FILES
);
630 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
632 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
634 // request can contain list of queried items
635 CTagSet
<uint32
, EC_TAG_KNOWNFILE
> queryitems(request
);
637 encoders
.UpdateEncoders();
639 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
640 const CKnownFile
*cur_file
= theApp
->sharedfiles
->GetFileByIndex(i
);
642 if ( !cur_file
|| (!queryitems
.empty() && !queryitems
.count(cur_file
->ECID())) ) {
646 CEC_SharedFile_Tag
filetag(cur_file
, detail_level
);
647 CKnownFile_Encoder
*enc
= encoders
[cur_file
->ECID()];
648 if ( detail_level
!= EC_DETAIL_UPDATE
) {
651 enc
->Encode(&filetag
);
652 response
->AddTag(filetag
);
657 static CECPacket
*Get_EC_Response_GetUpdate(CFileEncoderMap
&encoders
, CObjTagMap
&tagmap
)
659 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
661 encoders
.UpdateEncoders();
662 for (CFileEncoderMap::iterator it
= encoders
.begin(); it
!= encoders
.end(); ++it
) {
663 const CKnownFile
*cur_file
= it
->second
->GetFile();
664 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
->ECID());
665 // Completed cleared Partfiles are still stored as CPartfile,
666 // but encoded as KnownFile, so we have to check the encoder type
667 // instead of the file type.
668 if (it
->second
->IsPartFile_Encoder()) {
669 CEC_PartFile_Tag
filetag(static_cast<const CPartFile
*>(cur_file
), EC_DETAIL_INC_UPDATE
, &valuemap
);
670 // Add information if partfile is shared
671 filetag
.AddTag(EC_TAG_PARTFILE_SHARED
, it
->second
->IsShared(), &valuemap
);
673 CPartFile_Encoder
* enc
= static_cast<CPartFile_Encoder
*>(encoders
[cur_file
->ECID()]);
674 enc
->Encode(&filetag
);
675 response
->AddTag(filetag
);
677 CEC_SharedFile_Tag
filetag(cur_file
, EC_DETAIL_INC_UPDATE
, &valuemap
);
678 CKnownFile_Encoder
* enc
= encoders
[cur_file
->ECID()];
679 enc
->Encode(&filetag
);
680 response
->AddTag(filetag
);
685 CECEmptyTag
clients(EC_TAG_CLIENT
);
686 const CClientList::IDMap
& clientList
= theApp
->clientlist
->GetClientList();
687 bool onlyTransmittingClients
= thePrefs::IsTransmitOnlyUploadingClients();
688 for (CClientList::IDMap::const_iterator it
= clientList
.begin(); it
!= clientList
.end(); ++it
) {
689 const CUpDownClient
* cur_client
= it
->second
.GetClient();
690 if (onlyTransmittingClients
&& !cur_client
->IsDownloading()) {
691 // For poor CPU cores only transmit uploading clients. This will save a lot of CPU.
692 // Set ExternalConnect/TransmitOnlyUploadingClients to 1 for it.
695 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
->ECID());
696 clients
.AddTag(CEC_UpDownClient_Tag(cur_client
, EC_DETAIL_INC_UPDATE
, &valuemap
));
698 response
->AddTag(clients
);
701 CECEmptyTag
servers(EC_TAG_SERVER
);
702 std::vector
<const CServer
*> serverlist
= theApp
->serverlist
->CopySnapshot();
703 uint32 nrServers
= serverlist
.size();
704 for (uint32 i
= 0; i
< nrServers
; i
++) {
705 const CServer
* cur_server
= serverlist
[i
];
706 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_server
->ECID());
707 servers
.AddTag(CEC_Server_Tag(cur_server
, &valuemap
));
709 response
->AddTag(servers
);
712 CECEmptyTag
friends(EC_TAG_FRIEND
);
713 for (CFriendList::const_iterator it
= theApp
->friendlist
->begin(); it
!= theApp
->friendlist
->end(); ++it
) {
714 const CFriend
* cur_friend
= *it
;
715 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_friend
->ECID());
716 friends
.AddTag(CEC_Friend_Tag(cur_friend
, &valuemap
));
718 response
->AddTag(friends
);
723 static CECPacket
*Get_EC_Response_GetClientQueue(const CECPacket
*request
, CObjTagMap
&tagmap
, int op
)
725 CECPacket
*response
= new CECPacket(op
);
727 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
730 // request can contain list of queried items
731 // (not for incremental update of course)
732 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
734 const CClientRefList
& clients
= theApp
->uploadqueue
->GetUploadingList();
735 CClientRefList::const_iterator it
= clients
.begin();
736 for (; it
!= clients
.end(); ++it
) {
737 CUpDownClient
* cur_client
= it
->GetClient();
739 if (!cur_client
) { // shouldn't happen
742 if (!queryitems
.empty() && !queryitems
.count(cur_client
->ECID())) {
745 CValueMap
*valuemap
= NULL
;
746 if (detail_level
== EC_DETAIL_INC_UPDATE
) {
747 valuemap
= &tagmap
.GetValueMap(cur_client
->ECID());
749 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
, valuemap
);
751 response
->AddTag(cli_tag
);
758 static CECPacket
*Get_EC_Response_GetDownloadQueue(const CECPacket
*request
, CFileEncoderMap
&encoders
)
760 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
762 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
764 // request can contain list of queried items
765 CTagSet
<uint32
, EC_TAG_PARTFILE
> queryitems(request
);
767 encoders
.UpdateEncoders();
769 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
770 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
772 if ( !queryitems
.empty() && !queryitems
.count(cur_file
->ECID()) ) {
776 CEC_PartFile_Tag
filetag(cur_file
, detail_level
);
778 CPartFile_Encoder
* enc
= static_cast<CPartFile_Encoder
*>(encoders
[cur_file
->ECID()]);
779 if ( detail_level
!= EC_DETAIL_UPDATE
) {
782 enc
->Encode(&filetag
);
784 response
->AddTag(filetag
);
790 static CECPacket
*Get_EC_Response_PartFile_Cmd(const CECPacket
*request
)
792 CECPacket
*response
= NULL
;
794 // request can contain multiple files.
795 for (CECPacket::const_iterator it1
= request
->begin(); it1
!= request
->end(); ++it1
) {
796 const CECTag
&hashtag
= *it1
;
798 wxASSERT(hashtag
.GetTagName() == EC_TAG_PARTFILE
);
800 CMD4Hash hash
= hashtag
.GetMD4Data();
801 CPartFile
*pfile
= theApp
->downloadqueue
->GetFileByID( hash
);
804 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash
.Encode());
805 response
= new CECPacket(EC_OP_FAILED
);
806 response
->AddTag(CECTag(EC_TAG_STRING
, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash
.Encode()));
810 switch (request
->GetOpCode()) {
811 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
812 CoreNotify_PartFile_Swap_A4AF(pfile
);
814 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
815 CoreNotify_PartFile_Swap_A4AF_Auto(pfile
);
817 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
818 CoreNotify_PartFile_Swap_A4AF_Others(pfile
);
820 case EC_OP_PARTFILE_PAUSE
:
823 case EC_OP_PARTFILE_RESUME
:
825 pfile
->SavePartFile();
827 case EC_OP_PARTFILE_STOP
:
830 case EC_OP_PARTFILE_PRIO_SET
: {
831 uint8 prio
= hashtag
.GetFirstTagSafe()->GetInt();
832 if ( prio
== PR_AUTO
) {
833 pfile
->SetAutoDownPriority(1);
835 pfile
->SetAutoDownPriority(0);
836 pfile
->SetDownPriority(prio
);
840 case EC_OP_PARTFILE_DELETE
:
841 if ( thePrefs::StartNextFile() && (pfile
->GetStatus() != PS_PAUSED
) ) {
842 theApp
->downloadqueue
->StartNextFile(pfile
);
847 case EC_OP_PARTFILE_SET_CAT
:
848 pfile
->SetCategory(hashtag
.GetFirstTagSafe()->GetInt());
852 response
= new CECPacket(EC_OP_FAILED
);
853 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
858 response
= new CECPacket(EC_OP_NOOP
);
863 static CECPacket
*Get_EC_Response_Server_Add(const CECPacket
*request
)
865 CECPacket
*response
= NULL
;
867 wxString full_addr
= request
->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS
)->GetStringData();
868 wxString name
= request
->GetTagByNameSafe(EC_TAG_SERVER_NAME
)->GetStringData();
870 wxString s_ip
= full_addr
.Left(full_addr
.Find(':'));
871 wxString s_port
= full_addr
.Mid(full_addr
.Find(':') + 1);
873 long port
= StrToULong(s_port
);
874 CServer
* toadd
= new CServer(port
, s_ip
);
875 toadd
->SetListName(name
.IsEmpty() ? full_addr
: name
);
877 if ( theApp
->AddServer(toadd
, true) ) {
878 response
= new CECPacket(EC_OP_NOOP
);
880 response
= new CECPacket(EC_OP_FAILED
);
881 response
->AddTag(CECTag(EC_TAG_STRING
, _("Server not added")));
888 static CECPacket
*Get_EC_Response_Server(const CECPacket
*request
)
890 CECPacket
*response
= NULL
;
891 const CECTag
*srv_tag
= request
->GetTagByName(EC_TAG_SERVER
);
894 srv
= theApp
->serverlist
->GetServerByIPTCP(srv_tag
->GetIPv4Data().IP(), srv_tag
->GetIPv4Data().m_port
);
895 // server tag passed, but server not found
897 response
= new CECPacket(EC_OP_FAILED
);
898 response
->AddTag(CECTag(EC_TAG_STRING
,
899 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag
->GetIPv4Data().StringIP()));
903 switch (request
->GetOpCode()) {
904 case EC_OP_SERVER_DISCONNECT
:
905 theApp
->serverconnect
->Disconnect();
906 response
= new CECPacket(EC_OP_NOOP
);
908 case EC_OP_SERVER_REMOVE
:
910 theApp
->serverlist
->RemoveServer(srv
);
911 response
= new CECPacket(EC_OP_NOOP
);
913 response
= new CECPacket(EC_OP_FAILED
);
914 response
->AddTag(CECTag(EC_TAG_STRING
,
915 wxTRANSLATE("need to define server to be removed")));
918 case EC_OP_SERVER_CONNECT
:
919 if (thePrefs::GetNetworkED2K()) {
921 theApp
->serverconnect
->ConnectToServer(srv
);
922 response
= new CECPacket(EC_OP_NOOP
);
924 theApp
->serverconnect
->ConnectToAnyServer();
925 response
= new CECPacket(EC_OP_NOOP
);
928 response
= new CECPacket(EC_OP_FAILED
);
929 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("eD2k is disabled in preferences.")));
934 response
= new CECPacket(EC_OP_FAILED
);
935 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
941 static CECPacket
*Get_EC_Response_Friend(const CECPacket
*request
)
943 CECPacket
*response
= NULL
;
944 const CECTag
*tag
= request
->GetTagByName(EC_TAG_FRIEND_ADD
);
946 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_CLIENT
);
948 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(subtag
->GetInt());
950 theApp
->friendlist
->AddFriend(CCLIENTREF(client
, wxT("Get_EC_Response_Friend theApp->friendlist->AddFriend")));
951 response
= new CECPacket(EC_OP_NOOP
);
954 const CECTag
*hashtag
= tag
->GetTagByName(EC_TAG_FRIEND_HASH
);
955 const CECTag
*iptag
= tag
->GetTagByName(EC_TAG_FRIEND_IP
);
956 const CECTag
*porttag
= tag
->GetTagByName(EC_TAG_FRIEND_PORT
);
957 const CECTag
*nametag
= tag
->GetTagByName(EC_TAG_FRIEND_NAME
);
958 if (hashtag
&& iptag
&& porttag
&& nametag
) {
959 theApp
->friendlist
->AddFriend(hashtag
->GetMD4Data(), iptag
->GetInt(), porttag
->GetInt(), nametag
->GetStringData());
960 response
= new CECPacket(EC_OP_NOOP
);
963 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_REMOVE
))) {
964 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
966 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
968 theApp
->friendlist
->RemoveFriend(Friend
);
969 response
= new CECPacket(EC_OP_NOOP
);
972 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_FRIENDSLOT
))) {
973 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
975 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
977 theApp
->friendlist
->SetFriendSlot(Friend
, tag
->GetInt() != 0);
978 response
= new CECPacket(EC_OP_NOOP
);
981 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_SHARED
))) {
982 response
= new CECPacket(EC_OP_FAILED
);
983 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Request shared files list not implemented yet.")));
985 // This works fine - but there is no way atm to transfer the results to amulegui, so disable it for now.
987 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
989 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
991 theApp
->friendlist
->RequestSharedFileList(Friend
);
992 response
= new CECPacket(EC_OP_NOOP
);
994 } else if ((subtag
= tag
->GetTagByName(EC_TAG_CLIENT
))) {
995 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(subtag
->GetInt());
997 client
->RequestSharedFileList();
998 response
= new CECPacket(EC_OP_NOOP
);
1005 response
= new CECPacket(EC_OP_FAILED
);
1006 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
1012 static CECPacket
*Get_EC_Response_Search_Results(const CECPacket
*request
)
1014 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
1016 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1018 // request can contain list of queried items
1019 CTagSet
<uint32
, EC_TAG_SEARCHFILE
> queryitems(request
);
1021 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
1022 CSearchResultList::const_iterator it
= list
.begin();
1023 while (it
!= list
.end()) {
1024 CSearchFile
* sf
= *it
++;
1025 if ( !queryitems
.empty() && !queryitems
.count(sf
->ECID()) ) {
1028 response
->AddTag(CEC_SearchFile_Tag(sf
, detail_level
));
1033 static CECPacket
*Get_EC_Response_Search_Results(CObjTagMap
&tagmap
)
1035 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
1037 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
1038 CSearchResultList::const_iterator it
= list
.begin();
1039 while (it
!= list
.end()) {
1040 CSearchFile
* sf
= *it
++;
1041 CValueMap
&valuemap
= tagmap
.GetValueMap(sf
->ECID());
1042 response
->AddTag(CEC_SearchFile_Tag(sf
, EC_DETAIL_INC_UPDATE
, &valuemap
));
1044 if (sf
->HasChildren()) {
1045 const CSearchResultList
& children
= sf
->GetChildren();
1046 for (size_t i
= 0; i
< children
.size(); ++i
) {
1047 CSearchFile
* sfc
= children
.at(i
);
1048 CValueMap
&valuemap1
= tagmap
.GetValueMap(sfc
->ECID());
1049 response
->AddTag(CEC_SearchFile_Tag(sfc
, EC_DETAIL_INC_UPDATE
, &valuemap1
));
1056 static CECPacket
*Get_EC_Response_Search_Results_Download(const CECPacket
*request
)
1058 CECPacket
*response
= new CECPacket(EC_OP_STRINGS
);
1059 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1060 const CECTag
&tag
= *it
;
1061 CMD4Hash hash
= tag
.GetMD4Data();
1062 uint8 category
= tag
.GetFirstTagSafe()->GetInt();
1063 theApp
->searchlist
->AddFileToDownloadByHash(hash
, category
);
1068 static CECPacket
*Get_EC_Response_Search_Stop(const CECPacket
*WXUNUSED(request
))
1070 CECPacket
*reply
= new CECPacket(EC_OP_MISC_DATA
);
1071 theApp
->searchlist
->StopSearch();
1075 static CECPacket
*Get_EC_Response_Search(const CECPacket
*request
)
1079 const CEC_Search_Tag
*search_request
= static_cast<const CEC_Search_Tag
*>(request
->GetFirstTagSafe());
1080 theApp
->searchlist
->RemoveResults(0xffffffff);
1082 CSearchList::CSearchParams params
;
1083 params
.searchString
= search_request
->SearchText();
1084 params
.typeText
= search_request
->SearchFileType();
1085 params
.extension
= search_request
->SearchExt();
1086 params
.minSize
= search_request
->MinSize();
1087 params
.maxSize
= search_request
->MaxSize();
1088 params
.availability
= search_request
->Avail();
1091 EC_SEARCH_TYPE search_type
= search_request
->SearchType();
1092 SearchType core_search_type
= LocalSearch
;
1093 uint32 op
= EC_OP_FAILED
;
1094 switch (search_type
) {
1095 case EC_SEARCH_GLOBAL
:
1096 core_search_type
= GlobalSearch
;
1098 if (core_search_type
!= GlobalSearch
) { // Not a global search obviously
1099 core_search_type
= KadSearch
;
1101 case EC_SEARCH_LOCAL
: {
1102 uint32 search_id
= 0xffffffff;
1103 wxString error
= theApp
->searchlist
->StartNewSearch(&search_id
, core_search_type
, params
);
1104 if (!error
.IsEmpty()) {
1107 response
= wxTRANSLATE("Search in progress. Refetch results in a moment!");
1113 response
= wxTRANSLATE("WebSearch from remote interface makes no sense.");
1117 CECPacket
*reply
= new CECPacket(op
);
1118 // error or search in progress
1119 reply
->AddTag(CECTag(EC_TAG_STRING
, response
));
1124 static CECPacket
*Get_EC_Response_Set_SharedFile_Prio(const CECPacket
*request
)
1126 CECPacket
*response
= new CECPacket(EC_OP_NOOP
);
1127 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1128 const CECTag
&tag
= *it
;
1129 CMD4Hash hash
= tag
.GetMD4Data();
1130 uint8 prio
= tag
.GetFirstTagSafe()->GetInt();
1131 CKnownFile
* cur_file
= theApp
->sharedfiles
->GetFileByID(hash
);
1135 if (prio
== PR_AUTO
) {
1136 cur_file
->SetAutoUpPriority(1);
1137 cur_file
->UpdateAutoUpPriority();
1139 cur_file
->SetAutoUpPriority(0);
1140 cur_file
->SetUpPriority(prio
);
1142 Notify_SharedFilesUpdateItem(cur_file
);
1148 void CPartFile_Encoder::Encode(CECTag
*parent
)
1151 // Source part frequencies
1153 CKnownFile_Encoder::Encode(parent
);
1158 const CGapList
& gaplist
= m_PartFile()->GetGapList();
1159 const size_t gap_list_size
= gaplist
.size();
1160 ArrayOfUInts64 gaps
;
1161 gaps
.reserve(gap_list_size
* 2);
1163 for (CGapList::const_iterator curr_pos
= gaplist
.begin();
1164 curr_pos
!= gaplist
.end(); ++curr_pos
) {
1165 gaps
.push_back(curr_pos
.start());
1166 gaps
.push_back(curr_pos
.end());
1169 int gap_enc_size
= 0;
1171 const uint8
*gap_enc_data
= m_gap_status
.Encode(gaps
, gap_enc_size
, changed
);
1173 parent
->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS
, gap_enc_size
, (void *)gap_enc_data
));
1175 delete[] gap_enc_data
;
1180 ArrayOfUInts64 req_buffer
;
1181 const CPartFile::CReqBlockPtrList
& requestedblocks
= m_PartFile()->GetRequestedBlockList();
1182 CPartFile::CReqBlockPtrList::const_iterator curr_pos2
= requestedblocks
.begin();
1184 for ( ; curr_pos2
!= requestedblocks
.end(); ++curr_pos2
) {
1185 Requested_Block_Struct
* block
= *curr_pos2
;
1186 req_buffer
.push_back(block
->StartOffset
);
1187 req_buffer
.push_back(block
->EndOffset
);
1189 int req_enc_size
= 0;
1190 const uint8
*req_enc_data
= m_req_status
.Encode(req_buffer
, req_enc_size
, changed
);
1192 parent
->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS
, req_enc_size
, (void *)req_enc_data
));
1194 delete[] req_enc_data
;
1199 // First count occurrence of all source names
1201 CECEmptyTag
sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES
);
1202 typedef std::map
<wxString
, int> strIntMap
;
1204 const CPartFile::SourceSet
&sources
= m_PartFile()->GetSourceList();
1205 for (CPartFile::SourceSet::const_iterator it
= sources
.begin(); it
!= sources
.end(); ++it
) {
1206 const CClientRef
&cur_src
= *it
;
1207 if (cur_src
.GetRequestFile() != m_file
|| cur_src
.GetClientFilename().Length() == 0) {
1210 const wxString
&name
= cur_src
.GetClientFilename();
1211 strIntMap::iterator itm
= nameMap
.find(name
);
1212 if (itm
== nameMap
.end()) {
1219 // Go through our last list
1221 for (SourcenameItemMap::iterator it1
= m_sourcenameItemMap
.begin(); it1
!= m_sourcenameItemMap
.end();) {
1222 SourcenameItemMap::iterator it2
= it1
++;
1223 strIntMap::iterator itm
= nameMap
.find(it2
->second
.name
);
1224 if (itm
== nameMap
.end()) {
1225 // name doesn't exist anymore, tell client to forget it
1226 CECTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, it2
->first
);
1227 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, 0));
1228 sourceNames
.AddTag(tag
);
1230 m_sourcenameItemMap
.erase(it2
);
1232 // update count if it changed
1233 if (it2
->second
.count
!= itm
->second
) {
1234 CECTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, it2
->first
);
1235 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, itm
->second
));
1236 sourceNames
.AddTag(tag
);
1237 it2
->second
.count
= itm
->second
;
1239 // remove it from nameMap so that only new names are left there
1246 for (strIntMap::iterator it3
= nameMap
.begin(); it3
!= nameMap
.end(); ++it3
) {
1247 int id
= ++m_sourcenameID
;
1248 CECIntTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, id
);
1249 tag
.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES
, it3
->first
));
1250 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, it3
->second
));
1251 sourceNames
.AddTag(tag
);
1253 m_sourcenameItemMap
[id
] = SourcenameItem(it3
->first
, it3
->second
);
1255 if (sourceNames
.HasChildTags()) {
1256 parent
->AddTag(sourceNames
);
1261 void CPartFile_Encoder::ResetEncoder()
1263 CKnownFile_Encoder::ResetEncoder();
1264 m_gap_status
.ResetEncoder();
1265 m_req_status
.ResetEncoder();
1268 void CKnownFile_Encoder::Encode(CECTag
*parent
)
1271 // Source part frequencies
1273 // Reference to the availability list
1274 const ArrayOfUInts16
& list
= m_file
->IsPartFile() ?
1275 static_cast<const CPartFile
*>(m_file
)->m_SrcpartFrequency
:
1276 m_file
->m_AvailPartFrequency
;
1277 // Don't add tag if available parts aren't populated yet.
1278 if (!list
.empty()) {
1281 const uint8
*part_enc_data
= m_enc_data
.Encode(list
, part_enc_size
, changed
);
1283 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
1285 delete[] part_enc_data
;
1289 static CECPacket
*GetStatsGraphs(const CECPacket
*request
)
1291 CECPacket
*response
= NULL
;
1293 switch (request
->GetDetailLevel()) {
1295 case EC_DETAIL_FULL
: {
1296 double dTimestamp
= 0.0;
1297 if (request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
) != NULL
) {
1298 dTimestamp
= request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
)->GetDoubleData();
1300 uint16 nScale
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE
)->GetInt();
1301 uint16 nMaxPoints
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH
)->GetInt();
1303 unsigned int numPoints
= theApp
->m_statistics
->GetHistoryForWeb(nMaxPoints
, (double)nScale
, &dTimestamp
, &graphData
);
1305 response
= new CECPacket(EC_OP_STATSGRAPHS
);
1306 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA
, 4 * numPoints
* sizeof(uint32
), graphData
));
1307 delete [] graphData
;
1308 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST
, dTimestamp
));
1310 response
= new CECPacket(EC_OP_FAILED
);
1311 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("No points for graph.")));
1315 case EC_DETAIL_INC_UPDATE
:
1316 case EC_DETAIL_UPDATE
:
1319 response
= new CECPacket(EC_OP_FAILED
);
1320 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Your client is not configured for this detail level.")));
1324 response
= new CECPacket(EC_OP_FAILED
);
1331 CECPacket
*CECServerSocket::ProcessRequest2(const CECPacket
*request
)
1338 CECPacket
*response
= NULL
;
1340 switch (request
->GetOpCode()) {
1344 case EC_OP_SHUTDOWN
:
1345 if (!theApp
->IsOnShutDown()) {
1346 response
= new CECPacket(EC_OP_NOOP
);
1347 AddLogLineC(_("External Connection: shutdown requested"));
1348 #ifndef AMULE_DAEMON
1351 evt
.SetCanVeto(false);
1352 theApp
->ShutDown(evt
);
1355 theApp
->ExitMainLoop();
1358 response
= new CECPacket(EC_OP_FAILED
);
1359 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already shutting down.")));
1362 case EC_OP_ADD_LINK
:
1363 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1364 const CECTag
&tag
= *it
;
1365 wxString link
= tag
.GetStringData();
1367 const CECTag
*cattag
= tag
.GetTagByName(EC_TAG_PARTFILE_CAT
);
1369 category
= cattag
->GetInt();
1371 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link
);
1372 if ( theApp
->downloadqueue
->AddLink(link
, category
) ) {
1373 response
= new CECPacket(EC_OP_NOOP
);
1375 // Error messages are printed by the add function.
1376 response
= new CECPacket(EC_OP_FAILED
);
1377 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid link or already on list.")));
1384 case EC_OP_STAT_REQ
:
1385 response
= Get_EC_Response_StatRequest(request
, m_LoggerAccess
);
1386 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1388 case EC_OP_GET_CONNSTATE
:
1389 response
= new CECPacket(EC_OP_MISC_DATA
);
1390 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1395 case EC_OP_GET_SHARED_FILES
:
1396 if ( request
->GetDetailLevel() != EC_DETAIL_INC_UPDATE
) {
1397 response
= Get_EC_Response_GetSharedFiles(request
, m_FileEncoder
);
1400 case EC_OP_GET_DLOAD_QUEUE
:
1401 if ( request
->GetDetailLevel() != EC_DETAIL_INC_UPDATE
) {
1402 response
= Get_EC_Response_GetDownloadQueue(request
, m_FileEncoder
);
1406 // This will evolve into an update-all for inc tags
1408 case EC_OP_GET_UPDATE
:
1409 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1410 response
= Get_EC_Response_GetUpdate(m_FileEncoder
, m_obj_tagmap
);
1413 case EC_OP_GET_ULOAD_QUEUE
:
1414 response
= Get_EC_Response_GetClientQueue(request
, m_obj_tagmap
, EC_OP_ULOAD_QUEUE
);
1416 case EC_OP_PARTFILE_REMOVE_NO_NEEDED
:
1417 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE
:
1418 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE
:
1419 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
1420 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
1421 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
1422 case EC_OP_PARTFILE_PAUSE
:
1423 case EC_OP_PARTFILE_RESUME
:
1424 case EC_OP_PARTFILE_STOP
:
1425 case EC_OP_PARTFILE_PRIO_SET
:
1426 case EC_OP_PARTFILE_DELETE
:
1427 case EC_OP_PARTFILE_SET_CAT
:
1428 response
= Get_EC_Response_PartFile_Cmd(request
);
1430 case EC_OP_SHAREDFILES_RELOAD
:
1431 theApp
->sharedfiles
->Reload();
1432 response
= new CECPacket(EC_OP_NOOP
);
1434 case EC_OP_SHARED_SET_PRIO
:
1435 response
= Get_EC_Response_Set_SharedFile_Prio(request
);
1437 case EC_OP_RENAME_FILE
: {
1438 CMD4Hash fileHash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1439 wxString newName
= request
->GetTagByNameSafe(EC_TAG_PARTFILE_NAME
)->GetStringData();
1440 // search first in downloadqueue - it might be in known files as well
1441 CKnownFile
* file
= theApp
->downloadqueue
->GetFileByID(fileHash
);
1443 file
= theApp
->knownfiles
->FindKnownFileByID(fileHash
);
1446 response
= new CECPacket(EC_OP_FAILED
);
1447 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("File not found.")));
1450 if (newName
.IsEmpty()) {
1451 response
= new CECPacket(EC_OP_FAILED
);
1452 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid file name.")));
1456 if (theApp
->sharedfiles
->RenameFile(file
, CPath(newName
))) {
1457 response
= new CECPacket(EC_OP_NOOP
);
1459 response
= new CECPacket(EC_OP_FAILED
);
1460 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Unable to rename file.")));
1465 case EC_OP_CLEAR_COMPLETED
: {
1466 ListOfUInts32 toClear
;
1467 for (CECTag::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1468 if (it
->GetTagName() == EC_TAG_ECID
) {
1469 toClear
.push_back(it
->GetInt());
1472 theApp
->downloadqueue
->ClearCompleted(toClear
);
1473 response
= new CECPacket(EC_OP_NOOP
);
1476 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE
: {
1477 theApp
->sharedfiles
->Reload();
1478 uint32 idClient
= request
->GetTagByNameSafe(EC_TAG_CLIENT
)->GetInt();
1479 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(idClient
);
1480 CMD4Hash idFile
= request
->GetTagByNameSafe(EC_TAG_PARTFILE
)->GetMD4Data();
1481 CPartFile
* file
= theApp
->downloadqueue
->GetFileByID(idFile
);
1482 if (client
&& file
) {
1483 client
->SwapToAnotherFile( true, false, false, file
);
1485 response
= new CECPacket(EC_OP_NOOP
);
1488 case EC_OP_SHARED_FILE_SET_COMMENT
: {
1489 CMD4Hash hash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1490 CKnownFile
* file
= theApp
->sharedfiles
->GetFileByID(hash
);
1492 wxString newComment
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT
)->GetStringData();
1493 uint8 newRating
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING
)->GetInt();
1494 CoreNotify_KnownFile_Comment_Set(file
, newComment
, newRating
);
1496 response
= new CECPacket(EC_OP_NOOP
);
1503 case EC_OP_SERVER_ADD
:
1504 response
= Get_EC_Response_Server_Add(request
);
1506 case EC_OP_SERVER_DISCONNECT
:
1507 case EC_OP_SERVER_CONNECT
:
1508 case EC_OP_SERVER_REMOVE
:
1509 response
= Get_EC_Response_Server(request
);
1511 case EC_OP_GET_SERVER_LIST
: {
1512 response
= new CECPacket(EC_OP_SERVER_LIST
);
1513 if (!thePrefs::GetNetworkED2K()) {
1514 // Kad only: just send an empty list
1517 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1518 std::vector
<const CServer
*> servers
= theApp
->serverlist
->CopySnapshot();
1520 std::vector
<const CServer
*>::const_iterator it
= servers
.begin();
1521 it
!= servers
.end();
1524 response
->AddTag(CEC_Server_Tag(*it
, detail_level
));
1528 case EC_OP_SERVER_UPDATE_FROM_URL
: {
1529 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1531 // Save the new url, and update the UI (if not amuled).
1532 Notify_ServersURLChanged(url
);
1533 thePrefs::SetEd2kServersUrl(url
);
1535 theApp
->serverlist
->UpdateServerMetFromURL(url
);
1536 response
= new CECPacket(EC_OP_NOOP
);
1539 case EC_OP_SERVER_SET_STATIC_PRIO
: {
1540 uint32 ecid
= request
->GetTagByNameSafe(EC_TAG_SERVER
)->GetInt();
1541 CServer
* server
= theApp
->serverlist
->GetServerByECID(ecid
);
1543 const CECTag
* staticTag
= request
->GetTagByName(EC_TAG_SERVER_STATIC
);
1545 theApp
->serverlist
->SetStaticServer(server
, staticTag
->GetInt() > 0);
1547 const CECTag
* prioTag
= request
->GetTagByName(EC_TAG_SERVER_PRIO
);
1549 theApp
->serverlist
->SetServerPrio(server
, prioTag
->GetInt());
1552 response
= new CECPacket(EC_OP_NOOP
);
1559 response
= Get_EC_Response_Friend(request
);
1565 case EC_OP_IPFILTER_RELOAD
:
1566 NotifyAlways_IPFilter_Reload();
1567 response
= new CECPacket(EC_OP_NOOP
);
1570 case EC_OP_IPFILTER_UPDATE
: {
1571 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1572 if (url
.IsEmpty()) {
1573 url
= thePrefs::IPFilterURL();
1575 NotifyAlways_IPFilter_Update(url
);
1576 response
= new CECPacket(EC_OP_NOOP
);
1582 case EC_OP_SEARCH_START
:
1583 response
= Get_EC_Response_Search(request
);
1586 case EC_OP_SEARCH_STOP
:
1587 response
= Get_EC_Response_Search_Stop(request
);
1590 case EC_OP_SEARCH_RESULTS
:
1591 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1592 response
= Get_EC_Response_Search_Results(m_obj_tagmap
);
1594 response
= Get_EC_Response_Search_Results(request
);
1598 case EC_OP_SEARCH_PROGRESS
:
1599 response
= new CECPacket(EC_OP_SEARCH_PROGRESS
);
1600 response
->AddTag(CECTag(EC_TAG_SEARCH_STATUS
,
1601 theApp
->searchlist
->GetSearchProgress()));
1604 case EC_OP_DOWNLOAD_SEARCH_RESULT
:
1605 response
= Get_EC_Response_Search_Results_Download(request
);
1610 case EC_OP_GET_PREFERENCES
:
1611 response
= new CEC_Prefs_Packet(request
->GetTagByNameSafe(EC_TAG_SELECT_PREFS
)->GetInt(), request
->GetDetailLevel());
1613 case EC_OP_SET_PREFERENCES
:
1614 static_cast<const CEC_Prefs_Packet
*>(request
)->Apply();
1615 theApp
->glob_prefs
->Save();
1616 if (thePrefs::IsFilteringClients()) {
1617 theApp
->clientlist
->FilterQueues();
1619 if (thePrefs::IsFilteringServers()) {
1620 theApp
->serverlist
->FilterServers();
1622 if (!thePrefs::GetNetworkED2K() && theApp
->IsConnectedED2K()) {
1623 theApp
->DisconnectED2K();
1625 if (!thePrefs::GetNetworkKademlia() && theApp
->IsConnectedKad()) {
1628 response
= new CECPacket(EC_OP_NOOP
);
1631 case EC_OP_CREATE_CATEGORY
:
1632 if ( request
->GetTagCount() == 1 ) {
1633 CEC_Category_Tag
tag(*static_cast<const CEC_Category_Tag
*>(request
->GetFirstTagSafe()));
1635 response
= new CECPacket(EC_OP_NOOP
);
1637 response
= new CECPacket(EC_OP_FAILED
);
1638 response
->AddTag(CECTag(EC_TAG_CATEGORY
, theApp
->glob_prefs
->GetCatCount() - 1));
1639 response
->AddTag(CECTag(EC_TAG_CATEGORY_PATH
, tag
.Path()));
1641 Notify_CategoryAdded();
1643 response
= new CECPacket(EC_OP_NOOP
);
1646 case EC_OP_UPDATE_CATEGORY
:
1647 if ( request
->GetTagCount() == 1 ) {
1648 CEC_Category_Tag
tag(*static_cast<const CEC_Category_Tag
*>(request
->GetFirstTagSafe()));
1650 response
= new CECPacket(EC_OP_NOOP
);
1652 response
= new CECPacket(EC_OP_FAILED
);
1653 response
->AddTag(CECTag(EC_TAG_CATEGORY
, tag
.GetInt()));
1654 response
->AddTag(CECTag(EC_TAG_CATEGORY_PATH
, tag
.Path()));
1656 Notify_CategoryUpdate(tag
.GetInt());
1658 response
= new CECPacket(EC_OP_NOOP
);
1661 case EC_OP_DELETE_CATEGORY
:
1662 if ( request
->GetTagCount() == 1 ) {
1663 uint32 cat
= request
->GetFirstTagSafe()->GetInt();
1664 // this noes not only update the gui, but actually deletes the cat
1665 Notify_CategoryDelete(cat
);
1667 response
= new CECPacket(EC_OP_NOOP
);
1673 case EC_OP_ADDLOGLINE
:
1674 // cppcheck-suppress duplicateBranch
1675 if (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
) {
1676 AddLogLineC(request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1678 AddLogLineN(request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1680 response
= new CECPacket(EC_OP_NOOP
);
1682 case EC_OP_ADDDEBUGLOGLINE
:
1683 // cppcheck-suppress duplicateBranch
1684 if (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
) {
1685 AddDebugLogLineC(logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1687 AddDebugLogLineN(logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1689 response
= new CECPacket(EC_OP_NOOP
);
1692 response
= new CECPacket(EC_OP_LOG
);
1693 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetLog(false)));
1695 case EC_OP_GET_DEBUGLOG
:
1696 response
= new CECPacket(EC_OP_DEBUGLOG
);
1697 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetDebugLog(false)));
1699 case EC_OP_RESET_LOG
:
1700 theApp
->GetLog(true);
1701 response
= new CECPacket(EC_OP_NOOP
);
1703 case EC_OP_RESET_DEBUGLOG
:
1704 theApp
->GetDebugLog(true);
1705 response
= new CECPacket(EC_OP_NOOP
);
1707 case EC_OP_GET_LAST_LOG_ENTRY
:
1709 wxString tmp
= theApp
->GetLog(false);
1710 if (tmp
.Last() == '\n') {
1713 response
= new CECPacket(EC_OP_LOG
);
1714 response
->AddTag(CECTag(EC_TAG_STRING
, tmp
.AfterLast('\n')));
1717 case EC_OP_GET_SERVERINFO
:
1718 response
= new CECPacket(EC_OP_SERVERINFO
);
1719 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetServerLog(false)));
1721 case EC_OP_CLEAR_SERVERINFO
:
1722 theApp
->GetServerLog(true);
1723 response
= new CECPacket(EC_OP_NOOP
);
1728 case EC_OP_GET_STATSGRAPHS
:
1729 response
= GetStatsGraphs(request
);
1731 case EC_OP_GET_STATSTREE
: {
1732 theApp
->m_statistics
->UpdateStatsTree();
1733 response
= new CECPacket(EC_OP_STATSTREE
);
1734 CECTag
* tree
= theStats::GetECStatTree(request
->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING
)->GetInt());
1736 response
->AddTag(*tree
);
1739 if (request
->GetDetailLevel() == EC_DETAIL_WEB
) {
1740 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
1741 response
->AddTag(CECTag(EC_TAG_USER_NICK
, thePrefs::GetUserNick()));
1749 case EC_OP_KAD_START
:
1750 if (thePrefs::GetNetworkKademlia()) {
1751 response
= new CECPacket(EC_OP_NOOP
);
1752 if ( !Kademlia::CKademlia::IsRunning() ) {
1753 Kademlia::CKademlia::Start();
1754 theApp
->ShowConnectionState();
1757 response
= new CECPacket(EC_OP_FAILED
);
1758 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
1761 case EC_OP_KAD_STOP
:
1763 theApp
->ShowConnectionState();
1764 response
= new CECPacket(EC_OP_NOOP
);
1766 case EC_OP_KAD_UPDATE_FROM_URL
: {
1767 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1769 // Save the new url, and update the UI (if not amuled).
1770 Notify_NodesURLChanged(url
);
1771 thePrefs::SetKadNodesUrl(url
);
1773 theApp
->UpdateNotesDat(url
);
1774 response
= new CECPacket(EC_OP_NOOP
);
1777 case EC_OP_KAD_BOOTSTRAP_FROM_IP
:
1778 if (thePrefs::GetNetworkKademlia()) {
1779 theApp
->BootstrapKad(request
->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP
)->GetInt(),
1780 request
->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT
)->GetInt());
1781 theApp
->ShowConnectionState();
1782 response
= new CECPacket(EC_OP_NOOP
);
1784 response
= new CECPacket(EC_OP_FAILED
);
1785 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
1791 // These requests are currently used only in the text client
1794 if (thePrefs::GetNetworkED2K()) {
1795 response
= new CECPacket(EC_OP_STRINGS
);
1796 if (theApp
->IsConnectedED2K()) {
1797 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to eD2k.")));
1799 theApp
->serverconnect
->ConnectToAnyServer();
1800 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to eD2k...")));
1803 if (thePrefs::GetNetworkKademlia()) {
1805 response
= new CECPacket(EC_OP_STRINGS
);
1807 if (theApp
->IsConnectedKad()) {
1808 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to Kad.")));
1811 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to Kad...")));
1815 theApp
->ShowConnectionState();
1817 response
= new CECPacket(EC_OP_FAILED
);
1818 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("All networks are disabled.")));
1821 case EC_OP_DISCONNECT
:
1822 if (theApp
->IsConnected()) {
1823 response
= new CECPacket(EC_OP_STRINGS
);
1824 if (theApp
->IsConnectedED2K()) {
1825 theApp
->serverconnect
->Disconnect();
1826 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from eD2k.")));
1828 if (theApp
->IsConnectedKad()) {
1830 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from Kad.")));
1832 theApp
->ShowConnectionState();
1834 response
= new CECPacket(EC_OP_NOOP
);
1839 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request
->GetOpCode());
1841 response
= new CECPacket(EC_OP_FAILED
);
1842 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1848 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1852 * Core general status
1854 ECStatusMsgSource::ECStatusMsgSource()
1856 m_last_ed2k_status_sent
= 0xffffffff;
1857 m_last_kad_status_sent
= 0xffffffff;
1858 m_server
= (void *)0xffffffff;
1861 uint32
ECStatusMsgSource::GetEd2kStatus()
1863 if ( theApp
->IsConnectedED2K() ) {
1864 return theApp
->GetED2KID();
1865 } else if ( theApp
->serverconnect
->IsConnecting() ) {
1872 uint32
ECStatusMsgSource::GetKadStatus()
1874 if ( theApp
->IsConnectedKad() ) {
1876 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1878 } else if ( Kademlia::CKademlia::IsRunning() ) {
1884 CECPacket
*ECStatusMsgSource::GetNextPacket()
1886 if ( (m_last_ed2k_status_sent
!= GetEd2kStatus()) ||
1887 (m_last_kad_status_sent
!= GetKadStatus()) ||
1888 (m_server
!= theApp
->serverconnect
->GetCurrentServer()) ) {
1890 m_last_ed2k_status_sent
= GetEd2kStatus();
1891 m_last_kad_status_sent
= GetKadStatus();
1892 m_server
= theApp
->serverconnect
->GetCurrentServer();
1894 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
1895 response
->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE
));
1904 ECPartFileMsgSource::ECPartFileMsgSource()
1906 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
1907 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
1908 PARTFILE_STATUS status
= { true, false, false, false, true, cur_file
};
1909 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1913 void ECPartFileMsgSource::SetDirty(const CPartFile
*file
)
1915 CMD4Hash filehash
= file
->GetFileHash();
1916 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1917 m_dirty_status
[filehash
].m_dirty
= true;;
1921 void ECPartFileMsgSource::SetNew(const CPartFile
*file
)
1923 CMD4Hash filehash
= file
->GetFileHash();
1924 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1925 PARTFILE_STATUS status
= { true, false, false, false, true, file
};
1926 m_dirty_status
[filehash
] = status
;
1929 void ECPartFileMsgSource::SetCompleted(const CPartFile
*file
)
1931 CMD4Hash filehash
= file
->GetFileHash();
1932 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1934 m_dirty_status
[filehash
].m_finished
= true;
1937 void ECPartFileMsgSource::SetRemoved(const CPartFile
*file
)
1939 CMD4Hash filehash
= file
->GetFileHash();
1940 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1942 m_dirty_status
[filehash
].m_removed
= true;
1945 CECPacket
*ECPartFileMsgSource::GetNextPacket()
1947 for(std::map
<CMD4Hash
, PARTFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
1948 it
!= m_dirty_status
.end(); it
++) {
1949 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
1950 CMD4Hash filehash
= it
->first
;
1952 const CPartFile
*partfile
= it
->second
.m_file
;
1954 CECPacket
*packet
= new CECPacket(EC_OP_DLOAD_QUEUE
);
1955 if ( it
->second
.m_removed
) {
1956 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
1957 packet
->AddTag(tag
);
1958 m_dirty_status
.erase(it
);
1960 CEC_PartFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
1961 packet
->AddTag(tag
);
1963 m_dirty_status
[filehash
].m_new
= false;
1964 m_dirty_status
[filehash
].m_dirty
= false;
1973 * Shared files - similar to downloading
1975 ECKnownFileMsgSource::ECKnownFileMsgSource()
1977 for (unsigned int i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); i
++) {
1978 const CKnownFile
*cur_file
= theApp
->sharedfiles
->GetFileByIndex(i
);
1979 KNOWNFILE_STATUS status
= { true, false, false, true, cur_file
};
1980 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1984 void ECKnownFileMsgSource::SetDirty(const CKnownFile
*file
)
1986 CMD4Hash filehash
= file
->GetFileHash();
1987 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1988 m_dirty_status
[filehash
].m_dirty
= true;;
1992 void ECKnownFileMsgSource::SetNew(const CKnownFile
*file
)
1994 CMD4Hash filehash
= file
->GetFileHash();
1995 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1996 KNOWNFILE_STATUS status
= { true, false, false, true, file
};
1997 m_dirty_status
[filehash
] = status
;
2000 void ECKnownFileMsgSource::SetRemoved(const CKnownFile
*file
)
2002 CMD4Hash filehash
= file
->GetFileHash();
2003 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
2005 m_dirty_status
[filehash
].m_removed
= true;
2008 CECPacket
*ECKnownFileMsgSource::GetNextPacket()
2010 for(std::map
<CMD4Hash
, KNOWNFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
2011 it
!= m_dirty_status
.end(); it
++) {
2012 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
2013 CMD4Hash filehash
= it
->first
;
2015 const CKnownFile
*partfile
= it
->second
.m_file
;
2017 CECPacket
*packet
= new CECPacket(EC_OP_SHARED_FILES
);
2018 if ( it
->second
.m_removed
) {
2019 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
2020 packet
->AddTag(tag
);
2021 m_dirty_status
.erase(it
);
2023 CEC_SharedFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
2024 packet
->AddTag(tag
);
2026 m_dirty_status
[filehash
].m_new
= false;
2027 m_dirty_status
[filehash
].m_dirty
= false;
2036 * Notification about search status
2038 ECSearchMsgSource::ECSearchMsgSource()
2042 CECPacket
*ECSearchMsgSource::GetNextPacket()
2044 if ( m_dirty_status
.empty() ) {
2048 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
2049 for(std::map
<CMD4Hash
, SEARCHFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
2050 it
!= m_dirty_status
.end(); it
++) {
2052 if ( it
->second
.m_new
) {
2053 response
->AddTag(CEC_SearchFile_Tag(it
->second
.m_file
, EC_DETAIL_FULL
));
2054 it
->second
.m_new
= false;
2055 } else if ( it
->second
.m_dirty
) {
2056 response
->AddTag(CEC_SearchFile_Tag(it
->second
.m_file
, EC_DETAIL_UPDATE
));
2064 void ECSearchMsgSource::FlushStatus()
2066 m_dirty_status
.clear();
2069 void ECSearchMsgSource::SetDirty(const CSearchFile
*file
)
2071 if ( m_dirty_status
.count(file
->GetFileHash()) ) {
2072 m_dirty_status
[file
->GetFileHash()].m_dirty
= true;
2074 m_dirty_status
[file
->GetFileHash()].m_new
= true;
2075 m_dirty_status
[file
->GetFileHash()].m_dirty
= true;
2076 m_dirty_status
[file
->GetFileHash()].m_child_dirty
= true;
2077 m_dirty_status
[file
->GetFileHash()].m_file
= file
;
2081 void ECSearchMsgSource::SetChildDirty(const CSearchFile
*file
)
2083 m_dirty_status
[file
->GetFileHash()].m_child_dirty
= true;
2087 * Notification about uploading clients
2089 CECPacket
*ECClientMsgSource::GetNextPacket()
2095 // Notification iface per-client
2097 ECNotifier::ECNotifier()
2101 ECNotifier::~ECNotifier()
2103 while (m_msg_source
.begin() != m_msg_source
.end())
2104 Remove_EC_Client(m_msg_source
.begin()->first
);
2107 CECPacket
*ECNotifier::GetNextPacket(ECUpdateMsgSource
*msg_source_array
[])
2109 CECPacket
*packet
= 0;
2111 // priority 0 is highest
2113 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
2114 if ( (packet
= msg_source_array
[i
]->GetNextPacket()) != 0 ) {
2121 CECPacket
*ECNotifier::GetNextPacket(CECServerSocket
*sock
)
2124 // OnOutput is called for a first time before
2125 // socket is registered
2127 if ( m_msg_source
.count(sock
) ) {
2128 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
2129 if ( !notifier_array
) {
2132 CECPacket
*packet
= GetNextPacket(notifier_array
);
2133 //printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
2141 // Interface to notification macros
2143 void ECNotifier::DownloadFile_SetDirty(const CPartFile
*file
)
2145 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2146 i
!= m_msg_source
.end(); ++i
) {
2147 CECServerSocket
*sock
= i
->first
;
2148 if ( sock
->HaveNotificationSupport() ) {
2149 ECUpdateMsgSource
**notifier_array
= i
->second
;
2150 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetDirty(file
);
2153 NextPacketToSocket();
2156 void ECNotifier::DownloadFile_RemoveFile(const CPartFile
*file
)
2158 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2159 i
!= m_msg_source
.end(); ++i
) {
2160 ECUpdateMsgSource
**notifier_array
= i
->second
;
2161 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetRemoved(file
);
2163 NextPacketToSocket();
2166 void ECNotifier::DownloadFile_RemoveSource(const CPartFile
*)
2168 // per-partfile source list is not supported (yet), and IMHO quite useless
2171 void ECNotifier::DownloadFile_AddFile(const CPartFile
*file
)
2173 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2174 i
!= m_msg_source
.end(); ++i
) {
2175 ECUpdateMsgSource
**notifier_array
= i
->second
;
2176 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetNew(file
);
2178 NextPacketToSocket();
2181 void ECNotifier::DownloadFile_AddSource(const CPartFile
*)
2183 // per-partfile source list is not supported (yet), and IMHO quite useless
2186 void ECNotifier::SharedFile_AddFile(const CKnownFile
*file
)
2188 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2189 i
!= m_msg_source
.end(); ++i
) {
2190 ECUpdateMsgSource
**notifier_array
= i
->second
;
2191 static_cast<ECKnownFileMsgSource
*>(notifier_array
[EC_KNOWN
])->SetNew(file
);
2193 NextPacketToSocket();
2196 void ECNotifier::SharedFile_RemoveFile(const CKnownFile
*file
)
2198 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2199 i
!= m_msg_source
.end(); ++i
) {
2200 ECUpdateMsgSource
**notifier_array
= i
->second
;
2201 static_cast<ECKnownFileMsgSource
*>(notifier_array
[EC_KNOWN
])->SetRemoved(file
);
2203 NextPacketToSocket();
2206 void ECNotifier::SharedFile_RemoveAllFiles()
2208 // need to figure out what to do here
2211 void ECNotifier::Add_EC_Client(CECServerSocket
*sock
)
2213 ECUpdateMsgSource
**notifier_array
= new ECUpdateMsgSource
*[EC_STATUS_LAST_PRIO
];
2214 notifier_array
[EC_STATUS
] = new ECStatusMsgSource();
2215 notifier_array
[EC_SEARCH
] = new ECSearchMsgSource();
2216 notifier_array
[EC_PARTFILE
] = new ECPartFileMsgSource();
2217 notifier_array
[EC_CLIENT
] = new ECClientMsgSource();
2218 notifier_array
[EC_KNOWN
] = new ECKnownFileMsgSource();
2220 m_msg_source
[sock
] = notifier_array
;
2223 void ECNotifier::Remove_EC_Client(CECServerSocket
*sock
)
2225 if (m_msg_source
.count(sock
)) {
2226 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
2228 m_msg_source
.erase(sock
);
2230 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
2231 delete notifier_array
[i
];
2233 delete [] notifier_array
;
2237 void ECNotifier::NextPacketToSocket()
2239 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2240 i
!= m_msg_source
.end(); ++i
) {
2241 CECServerSocket
*sock
= i
->first
;
2242 if ( sock
->HaveNotificationSupport() && !sock
->DataPending() ) {
2243 ECUpdateMsgSource
**notifier_array
= i
->second
;
2244 CECPacket
*packet
= GetNextPacket(notifier_array
);
2246 //printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2247 sock
->SendPacket(packet
);
2253 // File_checked_for_headers