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 --------------------
305 BEGIN_EVENT_TABLE(ExternalConn
, wxEvtHandler
)
306 EVT_SOCKET(SERVER_ID
, ExternalConn::OnServerEvent
)
311 ExternalConn::ExternalConn(amuleIPV4Address addr
, wxString
*msg
)
315 // Are we allowed to accept External Connections?
316 if ( thePrefs::AcceptExternalConnections() ) {
317 // We must have a valid password, otherwise we will not allow EC connections
318 if (thePrefs::ECPassword().IsEmpty()) {
319 *msg
+= wxT("External connections disabled due to empty password!\n");
320 AddLogLineC(_("External connections disabled due to empty password!"));
325 m_ECServer
= new CExternalConnListener(addr
, MULE_SOCKET_REUSEADDR
, this);
327 m_ECServer
->SetEventHandler(*this, SERVER_ID
);
328 m_ECServer
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
330 m_ECServer
->Notify(true);
332 int port
= addr
.Service();
333 wxString ip
= addr
.IPAddress();
334 if (m_ECServer
->IsOk()) {
335 msgLocal
= CFormat(wxT("*** TCP socket (ECServer) listening on %s:%d")) % ip
% port
;
336 *msg
+= msgLocal
+ wxT("\n");
337 AddLogLineN(msgLocal
);
339 msgLocal
= CFormat(wxT("Could not listen for external connections at %s:%d!")) % ip
% port
;
340 *msg
+= msgLocal
+ wxT("\n");
341 AddLogLineN(msgLocal
);
344 *msg
+= wxT("External connections disabled in config file\n");
345 AddLogLineN(_("External connections disabled in config file"));
347 m_ec_notifier
= new ECNotifier();
351 ExternalConn::~ExternalConn()
355 delete m_ec_notifier
;
359 void ExternalConn::AddSocket(CECServerSocket
*s
)
362 socket_list
.insert(s
);
366 void ExternalConn::RemoveSocket(CECServerSocket
*s
)
369 socket_list
.erase(s
);
373 void ExternalConn::KillAllSockets()
375 AddDebugLogLineN(logGeneral
,
376 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
378 SocketSet::iterator it
= socket_list
.begin();
379 while (it
!= socket_list
.end()) {
380 CECServerSocket
*s
= *(it
++);
388 void ExternalConn::ResetAllLogs()
390 SocketSet::iterator it
= socket_list
.begin();
391 while (it
!= socket_list
.end()) {
392 CECServerSocket
*s
= *(it
++);
399 void ExternalConn::OnServerEvent(wxSocketEvent
& WXUNUSED(event
))
401 m_ECServer
->OnAccept();
406 void CExternalConnListener::OnAccept()
408 CECServerSocket
*sock
= new CECServerSocket(m_conn
->m_ec_notifier
);
409 // Accept new connection if there is one in the pending
410 // connections queue, else exit. We use Accept(FALSE) for
411 // non-blocking accept (although if we got here, there
412 // should ALWAYS be a pending connection).
413 if (AcceptWith(*sock
, false)) {
414 AddLogLineN(_("New external connection accepted"));
417 AddLogLineN(_("ERROR: couldn't accept a new external connection"));
425 const CECPacket
*CECServerSocket::Authenticate(const CECPacket
*request
)
429 if (request
== NULL
) {
430 return new CECPacket(EC_OP_AUTH_FAIL
);
433 // Password must be specified if we are to allow remote connections
434 if ( thePrefs::ECPassword().IsEmpty() ) {
435 AddLogLineC(_("External connection refused due to empty password in preferences!"));
437 return new CECPacket(EC_OP_AUTH_FAIL
);
440 if ((m_conn_state
== CONN_INIT
) && (request
->GetOpCode() == EC_OP_AUTH_REQ
) ) {
441 // cppcheck-suppress unreadVariable
442 const CECTag
*clientName
= request
->GetTagByName(EC_TAG_CLIENT_NAME
);
443 // cppcheck-suppress unreadVariable
444 const CECTag
*clientVersion
= request
->GetTagByName(EC_TAG_CLIENT_VERSION
);
446 AddLogLineN(CFormat( _("Connecting client: %s %s") )
447 % ( clientName
? clientName
->GetStringData() : wxString(_("Unknown")) )
448 % ( clientVersion
? clientVersion
->GetStringData() : wxString(_("Unknown version")) ) );
449 const CECTag
*protocol
= request
->GetTagByName(EC_TAG_PROTOCOL_VERSION
);
451 // For SVN versions, both client and server must use SVNDATE, and they must be the same
453 if (!vhash
.Decode(wxT(EC_VERSION_ID
))) {
454 response
= new CECPacket(EC_OP_AUTH_FAIL
);
455 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Fatal error, version hash is not a valid MD4-hash.")));
456 } else if (!request
->GetTagByName(EC_TAG_VERSION_ID
) || request
->GetTagByNameSafe(EC_TAG_VERSION_ID
)->GetMD4Data() != vhash
) {
457 response
= new CECPacket(EC_OP_AUTH_FAIL
);
458 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
460 // For release versions, we don't want to allow connections from any arbitrary SVN client.
461 if (request
->GetTagByName(EC_TAG_VERSION_ID
)) {
462 response
= new CECPacket(EC_OP_AUTH_FAIL
);
463 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("You cannot connect to a release version from an arbitrary development snapshot! *sigh* possible crash prevented")));
465 } else if (protocol
!= NULL
) {
466 uint16 proto_version
= protocol
->GetInt();
467 if (proto_version
== EC_CURRENT_PROTOCOL_VERSION
) {
468 response
= new CECPacket(EC_OP_AUTH_SALT
);
469 response
->AddTag(CECTag(EC_TAG_PASSWD_SALT
, m_passwd_salt
));
470 m_conn_state
= CONN_SALT_SENT
;
472 // So far ok, check capabilities of client
474 if (request
->GetTagByName(EC_TAG_CAN_ZLIB
)) {
475 m_my_flags
|= EC_FLAG_ZLIB
;
477 if (request
->GetTagByName(EC_TAG_CAN_UTF8_NUMBERS
)) {
478 m_my_flags
|= EC_FLAG_UTF8_NUMBERS
;
480 m_haveNotificationSupport
= request
->GetTagByName(EC_TAG_CAN_NOTIFY
) != NULL
;
481 AddDebugLogLineN(logEC
, CFormat(wxT("Client capabilities: ZLIB: %s UTF8 numbers: %s Push notification: %s") )
482 % ((m_my_flags
& EC_FLAG_ZLIB
) ? wxT("yes") : wxT("no"))
483 % ((m_my_flags
& EC_FLAG_UTF8_NUMBERS
) ? wxT("yes") : wxT("no"))
484 % (m_haveNotificationSupport
? wxT("yes") : wxT("no")));
486 response
= new CECPacket(EC_OP_AUTH_FAIL
);
487 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid protocol version.")
488 + CFormat(wxT("( %#.4x != %#.4x )")) % proto_version
% (uint16_t)EC_CURRENT_PROTOCOL_VERSION
));
491 response
= new CECPacket(EC_OP_AUTH_FAIL
);
492 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Missing protocol version tag.")));
494 } else if ((m_conn_state
== CONN_SALT_SENT
) && (request
->GetOpCode() == EC_OP_AUTH_PASSWD
)) {
495 const CECTag
*passwd
= request
->GetTagByName(EC_TAG_PASSWD_HASH
);
498 if (!passh
.Decode(thePrefs::ECPassword())) {
499 wxString err
= wxTRANSLATE("Authentication failed: invalid hash specified as EC password.");
500 AddLogLineN(wxString(wxGetTranslation(err
))
501 + wxT(" ") + thePrefs::ECPassword());
502 response
= new CECPacket(EC_OP_AUTH_FAIL
);
503 response
->AddTag(CECTag(EC_TAG_STRING
, err
));
505 wxString saltHash
= MD5Sum(CFormat(wxT("%lX")) % m_passwd_salt
).GetHash();
506 wxString saltStr
= CFormat(wxT("%lX")) % m_passwd_salt
;
508 passh
.Decode(MD5Sum(thePrefs::ECPassword().Lower() + saltHash
).GetHash());
510 if (passwd
&& passwd
->GetMD4Data() == passh
) {
511 response
= new CECPacket(EC_OP_AUTH_OK
);
512 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
516 err
= wxTRANSLATE("Authentication failed: wrong password.");
518 err
= wxTRANSLATE("Authentication failed: missing password.");
521 response
= new CECPacket(EC_OP_AUTH_FAIL
);
522 response
->AddTag(CECTag(EC_TAG_STRING
, err
));
523 AddLogLineN(wxGetTranslation(err
));
527 response
= new CECPacket(EC_OP_AUTH_FAIL
);
528 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid request, please authenticate first.")));
531 if (response
->GetOpCode() == EC_OP_AUTH_OK
) {
532 m_conn_state
= CONN_ESTABLISHED
;
533 AddLogLineN(_("Access granted."));
534 // Establish notification handler if client supports it
535 if (HaveNotificationSupport()) {
536 theApp
->ECServerHandler
->m_ec_notifier
->Add_EC_Client(this);
538 } else if (response
->GetOpCode() == EC_OP_AUTH_FAIL
) {
539 // Log message sent to client
540 if (response
->GetFirstTagSafe()->IsString()) {
541 AddLogLineN(CFormat(_("Sent error message \"%s\" to client.")) % wxGetTranslation(response
->GetFirstTagSafe()->GetStringData()));
544 AddLogLineN(CFormat(_("Unauthorized access attempt from %s. Connection closed.")) % GetPeer() );
545 m_conn_state
= CONN_FAILED
;
551 // Make a Logger tag (if there are any logging messages) and add it to the response
552 static void AddLoggerTag(CECPacket
*response
, CLoggerAccess
&LoggerAccess
)
554 if (LoggerAccess
.HasString()) {
555 CECEmptyTag
tag(EC_TAG_STATS_LOGGER_MESSAGE
);
556 // Tag structure is fix: tag carries nothing, inside are the strings
557 // maximum of 200 log lines per message
560 while (entries
< 200 && LoggerAccess
.GetString(line
)) {
561 tag
.AddTag(CECTag(EC_TAG_STRING
, line
));
564 response
->AddTag(tag
);
565 //printf("send Log tag %d %d\n", FirstEntry, entries);
569 static CECPacket
*Get_EC_Response_StatRequest(const CECPacket
*request
, CLoggerAccess
&LoggerAccess
)
571 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
573 switch (request
->GetDetailLevel()) {
575 // This is not an actual INC_UPDATE.
576 // amulegui only sets the detail level of the stats package to EC_DETAIL_INC_UPDATE
577 // so that the included conn state tag is created the way it is needed here.
578 case EC_DETAIL_INC_UPDATE
:
579 response
->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD
, (uint32
)theStats::GetUpOverheadRate()));
580 response
->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD
, (uint32
)theStats::GetDownOverheadRate()));
581 response
->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT
, /*(uint32)*/theStats::GetBannedCount()));
582 AddLoggerTag(response
, LoggerAccess
);
583 // Needed only for the remote tray icon context menu
584 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SENT_BYTES
, theStats::GetTotalSentBytes()));
585 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_RECEIVED_BYTES
, theStats::GetTotalReceivedBytes()));
586 response
->AddTag(CECTag(EC_TAG_STATS_SHARED_FILE_COUNT
, theStats::GetSharedFileCount()));
590 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED
, (uint32
)theStats::GetUploadRate()));
591 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED
, (uint32
)(theStats::GetDownloadRate())));
592 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxUpload()*1024.0)));
593 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxDownload()*1024.0)));
594 response
->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN
, /*(uint32)*/theStats::GetWaitingUserCount()));
595 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT
, /*(uint32)*/theStats::GetFoundSources()));
598 uint32 totaluser
= 0, totalfile
= 0;
599 theApp
->serverlist
->GetUserFileStatus( totaluser
, totalfile
);
600 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS
, totaluser
));
601 response
->AddTag(CECTag(EC_TAG_STATS_KAD_USERS
, Kademlia::CKademlia::GetKademliaUsers()));
602 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES
, totalfile
));
603 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FILES
, Kademlia::CKademlia::GetKademliaFiles()));
604 response
->AddTag(CECTag(EC_TAG_STATS_KAD_NODES
, CStatistics::GetKadNodes()));
607 if (Kademlia::CKademlia::IsConnected()) {
608 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP
, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
609 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource
));
610 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS
, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword
));
611 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes
));
612 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD
, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad
));
613 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS
, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
614 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE
, Kademlia::CKademlia::IsRunningInLANMode()));
615 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS
, theApp
->clientlist
->GetBuddyStatus()));
617 uint16 BuddyPort
= 0;
618 CUpDownClient
* Buddy
= theApp
->clientlist
->GetBuddy();
620 BuddyIP
= Buddy
->GetIP();
621 BuddyPort
= Buddy
->GetUDPPort();
623 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP
, BuddyIP
));
624 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT
, BuddyPort
));
626 case EC_DETAIL_UPDATE
:
633 static CECPacket
*Get_EC_Response_GetSharedFiles(const CECPacket
*request
, CFileEncoderMap
&encoders
)
635 wxASSERT(request
->GetOpCode() == EC_OP_GET_SHARED_FILES
);
637 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
639 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
641 // request can contain list of queried items
642 CTagSet
<uint32
, EC_TAG_KNOWNFILE
> queryitems(request
);
644 encoders
.UpdateEncoders();
646 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
647 const CKnownFile
*cur_file
= theApp
->sharedfiles
->GetFileByIndex(i
);
649 if ( !cur_file
|| (!queryitems
.empty() && !queryitems
.count(cur_file
->ECID())) ) {
653 CEC_SharedFile_Tag
filetag(cur_file
, detail_level
);
654 CKnownFile_Encoder
*enc
= encoders
[cur_file
->ECID()];
655 if ( detail_level
!= EC_DETAIL_UPDATE
) {
658 enc
->Encode(&filetag
);
659 response
->AddTag(filetag
);
664 static CECPacket
*Get_EC_Response_GetUpdate(CFileEncoderMap
&encoders
, CObjTagMap
&tagmap
)
666 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
668 encoders
.UpdateEncoders();
669 for (CFileEncoderMap::iterator it
= encoders
.begin(); it
!= encoders
.end(); ++it
) {
670 const CKnownFile
*cur_file
= it
->second
->GetFile();
671 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
->ECID());
672 // Completed cleared Partfiles are still stored as CPartfile,
673 // but encoded as KnownFile, so we have to check the encoder type
674 // instead of the file type.
675 if (it
->second
->IsPartFile_Encoder()) {
676 CEC_PartFile_Tag
filetag(static_cast<const CPartFile
*>(cur_file
), EC_DETAIL_INC_UPDATE
, &valuemap
);
677 // Add information if partfile is shared
678 filetag
.AddTag(EC_TAG_PARTFILE_SHARED
, it
->second
->IsShared(), &valuemap
);
680 CPartFile_Encoder
* enc
= static_cast<CPartFile_Encoder
*>(encoders
[cur_file
->ECID()]);
681 enc
->Encode(&filetag
);
682 response
->AddTag(filetag
);
684 CEC_SharedFile_Tag
filetag(cur_file
, EC_DETAIL_INC_UPDATE
, &valuemap
);
685 CKnownFile_Encoder
* enc
= encoders
[cur_file
->ECID()];
686 enc
->Encode(&filetag
);
687 response
->AddTag(filetag
);
692 CECEmptyTag
clients(EC_TAG_CLIENT
);
693 const CClientList::IDMap
& clientList
= theApp
->clientlist
->GetClientList();
694 bool onlyTransmittingClients
= thePrefs::IsTransmitOnlyUploadingClients();
695 for (CClientList::IDMap::const_iterator it
= clientList
.begin(); it
!= clientList
.end(); ++it
) {
696 const CUpDownClient
* cur_client
= it
->second
.GetClient();
697 if (onlyTransmittingClients
&& !cur_client
->IsDownloading()) {
698 // For poor CPU cores only transmit uploading clients. This will save a lot of CPU.
699 // Set ExternalConnect/TransmitOnlyUploadingClients to 1 for it.
702 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
->ECID());
703 clients
.AddTag(CEC_UpDownClient_Tag(cur_client
, EC_DETAIL_INC_UPDATE
, &valuemap
));
705 response
->AddTag(clients
);
708 CECEmptyTag
servers(EC_TAG_SERVER
);
709 std::vector
<const CServer
*> serverlist
= theApp
->serverlist
->CopySnapshot();
710 uint32 nrServers
= serverlist
.size();
711 for (uint32 i
= 0; i
< nrServers
; i
++) {
712 const CServer
* cur_server
= serverlist
[i
];
713 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_server
->ECID());
714 servers
.AddTag(CEC_Server_Tag(cur_server
, &valuemap
));
716 response
->AddTag(servers
);
719 CECEmptyTag
friends(EC_TAG_FRIEND
);
720 for (CFriendList::const_iterator it
= theApp
->friendlist
->begin(); it
!= theApp
->friendlist
->end(); ++it
) {
721 const CFriend
* cur_friend
= *it
;
722 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_friend
->ECID());
723 friends
.AddTag(CEC_Friend_Tag(cur_friend
, &valuemap
));
725 response
->AddTag(friends
);
730 static CECPacket
*Get_EC_Response_GetClientQueue(const CECPacket
*request
, CObjTagMap
&tagmap
, int op
)
732 CECPacket
*response
= new CECPacket(op
);
734 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
737 // request can contain list of queried items
738 // (not for incremental update of course)
739 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
741 const CClientRefList
& clients
= theApp
->uploadqueue
->GetUploadingList();
742 CClientRefList::const_iterator it
= clients
.begin();
743 for (; it
!= clients
.end(); ++it
) {
744 CUpDownClient
* cur_client
= it
->GetClient();
746 if (!cur_client
) { // shouldn't happen
749 if (!queryitems
.empty() && !queryitems
.count(cur_client
->ECID())) {
752 CValueMap
*valuemap
= NULL
;
753 if (detail_level
== EC_DETAIL_INC_UPDATE
) {
754 valuemap
= &tagmap
.GetValueMap(cur_client
->ECID());
756 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
, valuemap
);
758 response
->AddTag(cli_tag
);
765 static CECPacket
*Get_EC_Response_GetDownloadQueue(const CECPacket
*request
, CFileEncoderMap
&encoders
)
767 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
769 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
771 // request can contain list of queried items
772 CTagSet
<uint32
, EC_TAG_PARTFILE
> queryitems(request
);
774 encoders
.UpdateEncoders();
776 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
777 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
779 if ( !queryitems
.empty() && !queryitems
.count(cur_file
->ECID()) ) {
783 CEC_PartFile_Tag
filetag(cur_file
, detail_level
);
785 CPartFile_Encoder
* enc
= static_cast<CPartFile_Encoder
*>(encoders
[cur_file
->ECID()]);
786 if ( detail_level
!= EC_DETAIL_UPDATE
) {
789 enc
->Encode(&filetag
);
791 response
->AddTag(filetag
);
797 static CECPacket
*Get_EC_Response_PartFile_Cmd(const CECPacket
*request
)
799 CECPacket
*response
= NULL
;
801 // request can contain multiple files.
802 for (CECPacket::const_iterator it1
= request
->begin(); it1
!= request
->end(); ++it1
) {
803 const CECTag
&hashtag
= *it1
;
805 wxASSERT(hashtag
.GetTagName() == EC_TAG_PARTFILE
);
807 CMD4Hash hash
= hashtag
.GetMD4Data();
808 CPartFile
*pfile
= theApp
->downloadqueue
->GetFileByID( hash
);
811 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash
.Encode());
812 response
= new CECPacket(EC_OP_FAILED
);
813 response
->AddTag(CECTag(EC_TAG_STRING
, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash
.Encode()));
817 switch (request
->GetOpCode()) {
818 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
819 CoreNotify_PartFile_Swap_A4AF(pfile
);
821 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
822 CoreNotify_PartFile_Swap_A4AF_Auto(pfile
);
824 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
825 CoreNotify_PartFile_Swap_A4AF_Others(pfile
);
827 case EC_OP_PARTFILE_PAUSE
:
830 case EC_OP_PARTFILE_RESUME
:
832 pfile
->SavePartFile();
834 case EC_OP_PARTFILE_STOP
:
837 case EC_OP_PARTFILE_PRIO_SET
: {
838 uint8 prio
= hashtag
.GetFirstTagSafe()->GetInt();
839 if ( prio
== PR_AUTO
) {
840 pfile
->SetAutoDownPriority(1);
842 pfile
->SetAutoDownPriority(0);
843 pfile
->SetDownPriority(prio
);
847 case EC_OP_PARTFILE_DELETE
:
848 if ( thePrefs::StartNextFile() && (pfile
->GetStatus() != PS_PAUSED
) ) {
849 theApp
->downloadqueue
->StartNextFile(pfile
);
854 case EC_OP_PARTFILE_SET_CAT
:
855 pfile
->SetCategory(hashtag
.GetFirstTagSafe()->GetInt());
859 response
= new CECPacket(EC_OP_FAILED
);
860 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
865 response
= new CECPacket(EC_OP_NOOP
);
870 static CECPacket
*Get_EC_Response_Server_Add(const CECPacket
*request
)
872 CECPacket
*response
= NULL
;
874 wxString full_addr
= request
->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS
)->GetStringData();
875 wxString name
= request
->GetTagByNameSafe(EC_TAG_SERVER_NAME
)->GetStringData();
877 wxString s_ip
= full_addr
.Left(full_addr
.Find(':'));
878 wxString s_port
= full_addr
.Mid(full_addr
.Find(':') + 1);
880 long port
= StrToULong(s_port
);
881 CServer
* toadd
= new CServer(port
, s_ip
);
882 toadd
->SetListName(name
.IsEmpty() ? full_addr
: name
);
884 if ( theApp
->AddServer(toadd
, true) ) {
885 response
= new CECPacket(EC_OP_NOOP
);
887 response
= new CECPacket(EC_OP_FAILED
);
888 response
->AddTag(CECTag(EC_TAG_STRING
, _("Server not added")));
895 static CECPacket
*Get_EC_Response_Server(const CECPacket
*request
)
897 CECPacket
*response
= NULL
;
898 const CECTag
*srv_tag
= request
->GetTagByName(EC_TAG_SERVER
);
901 srv
= theApp
->serverlist
->GetServerByIPTCP(srv_tag
->GetIPv4Data().IP(), srv_tag
->GetIPv4Data().m_port
);
902 // server tag passed, but server not found
904 response
= new CECPacket(EC_OP_FAILED
);
905 response
->AddTag(CECTag(EC_TAG_STRING
,
906 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag
->GetIPv4Data().StringIP()));
910 switch (request
->GetOpCode()) {
911 case EC_OP_SERVER_DISCONNECT
:
912 theApp
->serverconnect
->Disconnect();
913 response
= new CECPacket(EC_OP_NOOP
);
915 case EC_OP_SERVER_REMOVE
:
917 theApp
->serverlist
->RemoveServer(srv
);
918 response
= new CECPacket(EC_OP_NOOP
);
920 response
= new CECPacket(EC_OP_FAILED
);
921 response
->AddTag(CECTag(EC_TAG_STRING
,
922 wxTRANSLATE("need to define server to be removed")));
925 case EC_OP_SERVER_CONNECT
:
926 if (thePrefs::GetNetworkED2K()) {
928 theApp
->serverconnect
->ConnectToServer(srv
);
929 response
= new CECPacket(EC_OP_NOOP
);
931 theApp
->serverconnect
->ConnectToAnyServer();
932 response
= new CECPacket(EC_OP_NOOP
);
935 response
= new CECPacket(EC_OP_FAILED
);
936 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("eD2k is disabled in preferences.")));
941 response
= new CECPacket(EC_OP_FAILED
);
942 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
948 static CECPacket
*Get_EC_Response_Friend(const CECPacket
*request
)
950 CECPacket
*response
= NULL
;
951 const CECTag
*tag
= request
->GetTagByName(EC_TAG_FRIEND_ADD
);
953 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_CLIENT
);
955 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(subtag
->GetInt());
957 theApp
->friendlist
->AddFriend(CCLIENTREF(client
, wxT("Get_EC_Response_Friend theApp->friendlist->AddFriend")));
958 response
= new CECPacket(EC_OP_NOOP
);
961 const CECTag
*hashtag
= tag
->GetTagByName(EC_TAG_FRIEND_HASH
);
962 const CECTag
*iptag
= tag
->GetTagByName(EC_TAG_FRIEND_IP
);
963 const CECTag
*porttag
= tag
->GetTagByName(EC_TAG_FRIEND_PORT
);
964 const CECTag
*nametag
= tag
->GetTagByName(EC_TAG_FRIEND_NAME
);
965 if (hashtag
&& iptag
&& porttag
&& nametag
) {
966 theApp
->friendlist
->AddFriend(hashtag
->GetMD4Data(), iptag
->GetInt(), porttag
->GetInt(), nametag
->GetStringData());
967 response
= new CECPacket(EC_OP_NOOP
);
970 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_REMOVE
))) {
971 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
973 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
975 theApp
->friendlist
->RemoveFriend(Friend
);
976 response
= new CECPacket(EC_OP_NOOP
);
979 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_FRIENDSLOT
))) {
980 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
982 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
984 theApp
->friendlist
->SetFriendSlot(Friend
, tag
->GetInt() != 0);
985 response
= new CECPacket(EC_OP_NOOP
);
988 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_SHARED
))) {
989 response
= new CECPacket(EC_OP_FAILED
);
990 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Request shared files list not implemented yet.")));
992 // This works fine - but there is no way atm to transfer the results to amulegui, so disable it for now.
994 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
996 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
998 theApp
->friendlist
->RequestSharedFileList(Friend
);
999 response
= new CECPacket(EC_OP_NOOP
);
1001 } else if ((subtag
= tag
->GetTagByName(EC_TAG_CLIENT
))) {
1002 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(subtag
->GetInt());
1004 client
->RequestSharedFileList();
1005 response
= new CECPacket(EC_OP_NOOP
);
1012 response
= new CECPacket(EC_OP_FAILED
);
1013 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
1019 static CECPacket
*Get_EC_Response_Search_Results(const CECPacket
*request
)
1021 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
1023 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1025 // request can contain list of queried items
1026 CTagSet
<uint32
, EC_TAG_SEARCHFILE
> queryitems(request
);
1028 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
1029 CSearchResultList::const_iterator it
= list
.begin();
1030 while (it
!= list
.end()) {
1031 CSearchFile
* sf
= *it
++;
1032 if ( !queryitems
.empty() && !queryitems
.count(sf
->ECID()) ) {
1035 response
->AddTag(CEC_SearchFile_Tag(sf
, detail_level
));
1040 static CECPacket
*Get_EC_Response_Search_Results(CObjTagMap
&tagmap
)
1042 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
1044 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
1045 CSearchResultList::const_iterator it
= list
.begin();
1046 while (it
!= list
.end()) {
1047 CSearchFile
* sf
= *it
++;
1048 CValueMap
&valuemap
= tagmap
.GetValueMap(sf
->ECID());
1049 response
->AddTag(CEC_SearchFile_Tag(sf
, EC_DETAIL_INC_UPDATE
, &valuemap
));
1051 if (sf
->HasChildren()) {
1052 const CSearchResultList
& children
= sf
->GetChildren();
1053 for (size_t i
= 0; i
< children
.size(); ++i
) {
1054 CSearchFile
* sfc
= children
.at(i
);
1055 CValueMap
&valuemap1
= tagmap
.GetValueMap(sfc
->ECID());
1056 response
->AddTag(CEC_SearchFile_Tag(sfc
, EC_DETAIL_INC_UPDATE
, &valuemap1
));
1063 static CECPacket
*Get_EC_Response_Search_Results_Download(const CECPacket
*request
)
1065 CECPacket
*response
= new CECPacket(EC_OP_STRINGS
);
1066 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1067 const CECTag
&tag
= *it
;
1068 CMD4Hash hash
= tag
.GetMD4Data();
1069 uint8 category
= tag
.GetFirstTagSafe()->GetInt();
1070 theApp
->searchlist
->AddFileToDownloadByHash(hash
, category
);
1075 static CECPacket
*Get_EC_Response_Search_Stop(const CECPacket
*WXUNUSED(request
))
1077 CECPacket
*reply
= new CECPacket(EC_OP_MISC_DATA
);
1078 theApp
->searchlist
->StopSearch();
1082 static CECPacket
*Get_EC_Response_Search(const CECPacket
*request
)
1086 const CEC_Search_Tag
*search_request
= static_cast<const CEC_Search_Tag
*>(request
->GetFirstTagSafe());
1087 theApp
->searchlist
->RemoveResults(0xffffffff);
1089 CSearchList::CSearchParams params
;
1090 params
.searchString
= search_request
->SearchText();
1091 params
.typeText
= search_request
->SearchFileType();
1092 params
.extension
= search_request
->SearchExt();
1093 params
.minSize
= search_request
->MinSize();
1094 params
.maxSize
= search_request
->MaxSize();
1095 params
.availability
= search_request
->Avail();
1098 EC_SEARCH_TYPE search_type
= search_request
->SearchType();
1099 SearchType core_search_type
= LocalSearch
;
1100 uint32 op
= EC_OP_FAILED
;
1101 switch (search_type
) {
1102 case EC_SEARCH_GLOBAL
:
1103 core_search_type
= GlobalSearch
;
1106 if (core_search_type
!= GlobalSearch
) { // Not a global search obviously
1107 core_search_type
= KadSearch
;
1110 case EC_SEARCH_LOCAL
: {
1111 uint32 search_id
= 0xffffffff;
1112 wxString error
= theApp
->searchlist
->StartNewSearch(&search_id
, core_search_type
, params
);
1113 if (!error
.IsEmpty()) {
1116 response
= wxTRANSLATE("Search in progress. Refetch results in a moment!");
1122 response
= wxTRANSLATE("WebSearch from remote interface makes no sense.");
1126 CECPacket
*reply
= new CECPacket(op
);
1127 // error or search in progress
1128 reply
->AddTag(CECTag(EC_TAG_STRING
, response
));
1133 static CECPacket
*Get_EC_Response_Set_SharedFile_Prio(const CECPacket
*request
)
1135 CECPacket
*response
= new CECPacket(EC_OP_NOOP
);
1136 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1137 const CECTag
&tag
= *it
;
1138 CMD4Hash hash
= tag
.GetMD4Data();
1139 uint8 prio
= tag
.GetFirstTagSafe()->GetInt();
1140 CKnownFile
* cur_file
= theApp
->sharedfiles
->GetFileByID(hash
);
1144 if (prio
== PR_AUTO
) {
1145 cur_file
->SetAutoUpPriority(1);
1146 cur_file
->UpdateAutoUpPriority();
1148 cur_file
->SetAutoUpPriority(0);
1149 cur_file
->SetUpPriority(prio
);
1151 Notify_SharedFilesUpdateItem(cur_file
);
1157 void CPartFile_Encoder::Encode(CECTag
*parent
)
1160 // Source part frequencies
1162 CKnownFile_Encoder::Encode(parent
);
1167 const CGapList
& gaplist
= m_PartFile()->GetGapList();
1168 const size_t gap_list_size
= gaplist
.size();
1169 ArrayOfUInts64 gaps
;
1170 gaps
.reserve(gap_list_size
* 2);
1172 for (CGapList::const_iterator curr_pos
= gaplist
.begin();
1173 curr_pos
!= gaplist
.end(); ++curr_pos
) {
1174 gaps
.push_back(curr_pos
.start());
1175 gaps
.push_back(curr_pos
.end());
1178 int gap_enc_size
= 0;
1180 const uint8
*gap_enc_data
= m_gap_status
.Encode(gaps
, gap_enc_size
, changed
);
1182 parent
->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS
, gap_enc_size
, (void *)gap_enc_data
));
1184 delete[] gap_enc_data
;
1189 ArrayOfUInts64 req_buffer
;
1190 const CPartFile::CReqBlockPtrList
& requestedblocks
= m_PartFile()->GetRequestedBlockList();
1191 CPartFile::CReqBlockPtrList::const_iterator curr_pos2
= requestedblocks
.begin();
1193 for ( ; curr_pos2
!= requestedblocks
.end(); ++curr_pos2
) {
1194 Requested_Block_Struct
* block
= *curr_pos2
;
1195 req_buffer
.push_back(block
->StartOffset
);
1196 req_buffer
.push_back(block
->EndOffset
);
1198 int req_enc_size
= 0;
1199 const uint8
*req_enc_data
= m_req_status
.Encode(req_buffer
, req_enc_size
, changed
);
1201 parent
->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS
, req_enc_size
, (void *)req_enc_data
));
1203 delete[] req_enc_data
;
1208 // First count occurrence of all source names
1210 CECEmptyTag
sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES
);
1211 typedef std::map
<wxString
, int> strIntMap
;
1213 const CPartFile::SourceSet
&sources
= m_PartFile()->GetSourceList();
1214 for (CPartFile::SourceSet::const_iterator it
= sources
.begin(); it
!= sources
.end(); ++it
) {
1215 const CClientRef
&cur_src
= *it
;
1216 if (cur_src
.GetRequestFile() != m_file
|| cur_src
.GetClientFilename().Length() == 0) {
1219 const wxString
&name
= cur_src
.GetClientFilename();
1220 strIntMap::iterator itm
= nameMap
.find(name
);
1221 if (itm
== nameMap
.end()) {
1228 // Go through our last list
1230 for (SourcenameItemMap::iterator it1
= m_sourcenameItemMap
.begin(); it1
!= m_sourcenameItemMap
.end();) {
1231 SourcenameItemMap::iterator it2
= it1
++;
1232 strIntMap::iterator itm
= nameMap
.find(it2
->second
.name
);
1233 if (itm
== nameMap
.end()) {
1234 // name doesn't exist anymore, tell client to forget it
1235 CECTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, it2
->first
);
1236 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, 0));
1237 sourceNames
.AddTag(tag
);
1239 m_sourcenameItemMap
.erase(it2
);
1241 // update count if it changed
1242 if (it2
->second
.count
!= itm
->second
) {
1243 CECTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, it2
->first
);
1244 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, itm
->second
));
1245 sourceNames
.AddTag(tag
);
1246 it2
->second
.count
= itm
->second
;
1248 // remove it from nameMap so that only new names are left there
1255 for (strIntMap::iterator it3
= nameMap
.begin(); it3
!= nameMap
.end(); ++it3
) {
1256 int id
= ++m_sourcenameID
;
1257 CECIntTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, id
);
1258 tag
.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES
, it3
->first
));
1259 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, it3
->second
));
1260 sourceNames
.AddTag(tag
);
1262 m_sourcenameItemMap
[id
] = SourcenameItem(it3
->first
, it3
->second
);
1264 if (sourceNames
.HasChildTags()) {
1265 parent
->AddTag(sourceNames
);
1270 void CPartFile_Encoder::ResetEncoder()
1272 CKnownFile_Encoder::ResetEncoder();
1273 m_gap_status
.ResetEncoder();
1274 m_req_status
.ResetEncoder();
1277 void CKnownFile_Encoder::Encode(CECTag
*parent
)
1280 // Source part frequencies
1282 // Reference to the availability list
1283 const ArrayOfUInts16
& list
= m_file
->IsPartFile() ?
1284 static_cast<const CPartFile
*>(m_file
)->m_SrcpartFrequency
:
1285 m_file
->m_AvailPartFrequency
;
1286 // Don't add tag if available parts aren't populated yet.
1287 if (!list
.empty()) {
1290 const uint8
*part_enc_data
= m_enc_data
.Encode(list
, part_enc_size
, changed
);
1292 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
1294 delete[] part_enc_data
;
1298 static CECPacket
*GetStatsGraphs(const CECPacket
*request
)
1300 CECPacket
*response
= NULL
;
1302 switch (request
->GetDetailLevel()) {
1304 case EC_DETAIL_FULL
: {
1305 double dTimestamp
= 0.0;
1306 if (request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
) != NULL
) {
1307 dTimestamp
= request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
)->GetDoubleData();
1309 uint16 nScale
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE
)->GetInt();
1310 uint16 nMaxPoints
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH
)->GetInt();
1312 unsigned int numPoints
= theApp
->m_statistics
->GetHistoryForWeb(nMaxPoints
, (double)nScale
, &dTimestamp
, &graphData
);
1314 response
= new CECPacket(EC_OP_STATSGRAPHS
);
1315 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA
, 4 * numPoints
* sizeof(uint32
), graphData
));
1316 delete [] graphData
;
1317 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST
, dTimestamp
));
1319 response
= new CECPacket(EC_OP_FAILED
);
1320 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("No points for graph.")));
1324 case EC_DETAIL_INC_UPDATE
:
1325 case EC_DETAIL_UPDATE
:
1328 response
= new CECPacket(EC_OP_FAILED
);
1329 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Your client is not configured for this detail level.")));
1333 response
= new CECPacket(EC_OP_FAILED
);
1340 CECPacket
*CECServerSocket::ProcessRequest2(const CECPacket
*request
)
1347 CECPacket
*response
= NULL
;
1349 switch (request
->GetOpCode()) {
1353 case EC_OP_SHUTDOWN
:
1354 if (!theApp
->IsOnShutDown()) {
1355 response
= new CECPacket(EC_OP_NOOP
);
1356 AddLogLineC(_("External Connection: shutdown requested"));
1357 #ifndef AMULE_DAEMON
1360 evt
.SetCanVeto(false);
1361 theApp
->ShutDown(evt
);
1364 theApp
->ExitMainLoop();
1367 response
= new CECPacket(EC_OP_FAILED
);
1368 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already shutting down.")));
1371 case EC_OP_ADD_LINK
:
1372 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1373 const CECTag
&tag
= *it
;
1374 wxString link
= tag
.GetStringData();
1376 const CECTag
*cattag
= tag
.GetTagByName(EC_TAG_PARTFILE_CAT
);
1378 category
= cattag
->GetInt();
1380 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link
);
1381 if ( theApp
->downloadqueue
->AddLink(link
, category
) ) {
1382 response
= new CECPacket(EC_OP_NOOP
);
1384 // Error messages are printed by the add function.
1385 response
= new CECPacket(EC_OP_FAILED
);
1386 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid link or already on list.")));
1393 case EC_OP_STAT_REQ
:
1394 response
= Get_EC_Response_StatRequest(request
, m_LoggerAccess
);
1395 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1397 case EC_OP_GET_CONNSTATE
:
1398 response
= new CECPacket(EC_OP_MISC_DATA
);
1399 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1404 case EC_OP_GET_SHARED_FILES
:
1405 if ( request
->GetDetailLevel() != EC_DETAIL_INC_UPDATE
) {
1406 response
= Get_EC_Response_GetSharedFiles(request
, m_FileEncoder
);
1409 case EC_OP_GET_DLOAD_QUEUE
:
1410 if ( request
->GetDetailLevel() != EC_DETAIL_INC_UPDATE
) {
1411 response
= Get_EC_Response_GetDownloadQueue(request
, m_FileEncoder
);
1415 // This will evolve into an update-all for inc tags
1417 case EC_OP_GET_UPDATE
:
1418 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1419 response
= Get_EC_Response_GetUpdate(m_FileEncoder
, m_obj_tagmap
);
1422 case EC_OP_GET_ULOAD_QUEUE
:
1423 response
= Get_EC_Response_GetClientQueue(request
, m_obj_tagmap
, EC_OP_ULOAD_QUEUE
);
1425 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
1426 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
1427 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
1428 case EC_OP_PARTFILE_PAUSE
:
1429 case EC_OP_PARTFILE_RESUME
:
1430 case EC_OP_PARTFILE_STOP
:
1431 case EC_OP_PARTFILE_PRIO_SET
:
1432 case EC_OP_PARTFILE_DELETE
:
1433 case EC_OP_PARTFILE_SET_CAT
:
1434 response
= Get_EC_Response_PartFile_Cmd(request
);
1436 case EC_OP_SHAREDFILES_RELOAD
:
1437 theApp
->sharedfiles
->Reload();
1438 response
= new CECPacket(EC_OP_NOOP
);
1440 case EC_OP_SHARED_SET_PRIO
:
1441 response
= Get_EC_Response_Set_SharedFile_Prio(request
);
1443 case EC_OP_RENAME_FILE
: {
1444 CMD4Hash fileHash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1445 wxString newName
= request
->GetTagByNameSafe(EC_TAG_PARTFILE_NAME
)->GetStringData();
1446 // search first in downloadqueue - it might be in known files as well
1447 CKnownFile
* file
= theApp
->downloadqueue
->GetFileByID(fileHash
);
1449 file
= theApp
->knownfiles
->FindKnownFileByID(fileHash
);
1452 response
= new CECPacket(EC_OP_FAILED
);
1453 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("File not found.")));
1456 if (newName
.IsEmpty()) {
1457 response
= new CECPacket(EC_OP_FAILED
);
1458 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid file name.")));
1462 if (theApp
->sharedfiles
->RenameFile(file
, CPath(newName
))) {
1463 response
= new CECPacket(EC_OP_NOOP
);
1465 response
= new CECPacket(EC_OP_FAILED
);
1466 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Unable to rename file.")));
1471 case EC_OP_CLEAR_COMPLETED
: {
1472 ListOfUInts32 toClear
;
1473 for (CECTag::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1474 if (it
->GetTagName() == EC_TAG_ECID
) {
1475 toClear
.push_back(it
->GetInt());
1478 theApp
->downloadqueue
->ClearCompleted(toClear
);
1479 response
= new CECPacket(EC_OP_NOOP
);
1482 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE
: {
1483 theApp
->sharedfiles
->Reload();
1484 uint32 idClient
= request
->GetTagByNameSafe(EC_TAG_CLIENT
)->GetInt();
1485 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(idClient
);
1486 CMD4Hash idFile
= request
->GetTagByNameSafe(EC_TAG_PARTFILE
)->GetMD4Data();
1487 CPartFile
* file
= theApp
->downloadqueue
->GetFileByID(idFile
);
1488 if (client
&& file
) {
1489 client
->SwapToAnotherFile( true, false, false, file
);
1491 response
= new CECPacket(EC_OP_NOOP
);
1494 case EC_OP_SHARED_FILE_SET_COMMENT
: {
1495 CMD4Hash hash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1496 CKnownFile
* file
= theApp
->sharedfiles
->GetFileByID(hash
);
1498 wxString newComment
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT
)->GetStringData();
1499 uint8 newRating
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING
)->GetInt();
1500 CoreNotify_KnownFile_Comment_Set(file
, newComment
, newRating
);
1502 response
= new CECPacket(EC_OP_NOOP
);
1509 case EC_OP_SERVER_ADD
:
1510 response
= Get_EC_Response_Server_Add(request
);
1512 case EC_OP_SERVER_DISCONNECT
:
1513 case EC_OP_SERVER_CONNECT
:
1514 case EC_OP_SERVER_REMOVE
:
1515 response
= Get_EC_Response_Server(request
);
1517 case EC_OP_GET_SERVER_LIST
: {
1518 response
= new CECPacket(EC_OP_SERVER_LIST
);
1519 if (!thePrefs::GetNetworkED2K()) {
1520 // Kad only: just send an empty list
1523 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1524 std::vector
<const CServer
*> servers
= theApp
->serverlist
->CopySnapshot();
1526 std::vector
<const CServer
*>::const_iterator it
= servers
.begin();
1527 it
!= servers
.end();
1530 response
->AddTag(CEC_Server_Tag(*it
, detail_level
));
1534 case EC_OP_SERVER_UPDATE_FROM_URL
: {
1535 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1537 // Save the new url, and update the UI (if not amuled).
1538 Notify_ServersURLChanged(url
);
1539 thePrefs::SetEd2kServersUrl(url
);
1541 theApp
->serverlist
->UpdateServerMetFromURL(url
);
1542 response
= new CECPacket(EC_OP_NOOP
);
1545 case EC_OP_SERVER_SET_STATIC_PRIO
: {
1546 uint32 ecid
= request
->GetTagByNameSafe(EC_TAG_SERVER
)->GetInt();
1547 CServer
* server
= theApp
->serverlist
->GetServerByECID(ecid
);
1549 const CECTag
* staticTag
= request
->GetTagByName(EC_TAG_SERVER_STATIC
);
1551 theApp
->serverlist
->SetStaticServer(server
, staticTag
->GetInt() > 0);
1553 const CECTag
* prioTag
= request
->GetTagByName(EC_TAG_SERVER_PRIO
);
1555 theApp
->serverlist
->SetServerPrio(server
, prioTag
->GetInt());
1558 response
= new CECPacket(EC_OP_NOOP
);
1565 response
= Get_EC_Response_Friend(request
);
1571 case EC_OP_IPFILTER_RELOAD
:
1572 NotifyAlways_IPFilter_Reload();
1573 response
= new CECPacket(EC_OP_NOOP
);
1576 case EC_OP_IPFILTER_UPDATE
: {
1577 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1578 if (url
.IsEmpty()) {
1579 url
= thePrefs::IPFilterURL();
1581 NotifyAlways_IPFilter_Update(url
);
1582 response
= new CECPacket(EC_OP_NOOP
);
1588 case EC_OP_SEARCH_START
:
1589 response
= Get_EC_Response_Search(request
);
1592 case EC_OP_SEARCH_STOP
:
1593 response
= Get_EC_Response_Search_Stop(request
);
1596 case EC_OP_SEARCH_RESULTS
:
1597 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1598 response
= Get_EC_Response_Search_Results(m_obj_tagmap
);
1600 response
= Get_EC_Response_Search_Results(request
);
1604 case EC_OP_SEARCH_PROGRESS
:
1605 response
= new CECPacket(EC_OP_SEARCH_PROGRESS
);
1606 response
->AddTag(CECTag(EC_TAG_SEARCH_STATUS
,
1607 theApp
->searchlist
->GetSearchProgress()));
1610 case EC_OP_DOWNLOAD_SEARCH_RESULT
:
1611 response
= Get_EC_Response_Search_Results_Download(request
);
1616 case EC_OP_GET_PREFERENCES
:
1617 response
= new CEC_Prefs_Packet(request
->GetTagByNameSafe(EC_TAG_SELECT_PREFS
)->GetInt(), request
->GetDetailLevel());
1619 case EC_OP_SET_PREFERENCES
:
1620 static_cast<const CEC_Prefs_Packet
*>(request
)->Apply();
1621 theApp
->glob_prefs
->Save();
1622 if (thePrefs::IsFilteringClients()) {
1623 theApp
->clientlist
->FilterQueues();
1625 if (thePrefs::IsFilteringServers()) {
1626 theApp
->serverlist
->FilterServers();
1628 if (!thePrefs::GetNetworkED2K() && theApp
->IsConnectedED2K()) {
1629 theApp
->DisconnectED2K();
1631 if (!thePrefs::GetNetworkKademlia() && theApp
->IsConnectedKad()) {
1634 response
= new CECPacket(EC_OP_NOOP
);
1637 case EC_OP_CREATE_CATEGORY
:
1638 if ( request
->GetTagCount() == 1 ) {
1639 CEC_Category_Tag
tag(*static_cast<const CEC_Category_Tag
*>(request
->GetFirstTagSafe()));
1641 response
= new CECPacket(EC_OP_NOOP
);
1643 response
= new CECPacket(EC_OP_FAILED
);
1644 response
->AddTag(CECTag(EC_TAG_CATEGORY
, theApp
->glob_prefs
->GetCatCount() - 1));
1645 response
->AddTag(CECTag(EC_TAG_CATEGORY_PATH
, tag
.Path()));
1647 Notify_CategoryAdded();
1649 response
= new CECPacket(EC_OP_NOOP
);
1652 case EC_OP_UPDATE_CATEGORY
:
1653 if ( request
->GetTagCount() == 1 ) {
1654 CEC_Category_Tag
tag(*static_cast<const CEC_Category_Tag
*>(request
->GetFirstTagSafe()));
1656 response
= new CECPacket(EC_OP_NOOP
);
1658 response
= new CECPacket(EC_OP_FAILED
);
1659 response
->AddTag(CECTag(EC_TAG_CATEGORY
, tag
.GetInt()));
1660 response
->AddTag(CECTag(EC_TAG_CATEGORY_PATH
, tag
.Path()));
1662 Notify_CategoryUpdate(tag
.GetInt());
1664 response
= new CECPacket(EC_OP_NOOP
);
1667 case EC_OP_DELETE_CATEGORY
:
1668 if ( request
->GetTagCount() == 1 ) {
1669 uint32 cat
= request
->GetFirstTagSafe()->GetInt();
1670 // this noes not only update the gui, but actually deletes the cat
1671 Notify_CategoryDelete(cat
);
1673 response
= new CECPacket(EC_OP_NOOP
);
1679 case EC_OP_ADDLOGLINE
:
1680 // cppcheck-suppress duplicateBranch
1681 if (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
) {
1682 AddLogLineC(request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1684 AddLogLineN(request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1686 response
= new CECPacket(EC_OP_NOOP
);
1688 case EC_OP_ADDDEBUGLOGLINE
:
1689 // cppcheck-suppress duplicateBranch
1690 if (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
) {
1691 AddDebugLogLineC(logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1693 AddDebugLogLineN(logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1695 response
= new CECPacket(EC_OP_NOOP
);
1698 response
= new CECPacket(EC_OP_LOG
);
1699 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetLog(false)));
1701 case EC_OP_GET_DEBUGLOG
:
1702 response
= new CECPacket(EC_OP_DEBUGLOG
);
1703 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetDebugLog(false)));
1705 case EC_OP_RESET_LOG
:
1706 theApp
->GetLog(true);
1707 response
= new CECPacket(EC_OP_NOOP
);
1709 case EC_OP_RESET_DEBUGLOG
:
1710 theApp
->GetDebugLog(true);
1711 response
= new CECPacket(EC_OP_NOOP
);
1713 case EC_OP_GET_LAST_LOG_ENTRY
:
1715 wxString tmp
= theApp
->GetLog(false);
1716 if (tmp
.Last() == '\n') {
1719 response
= new CECPacket(EC_OP_LOG
);
1720 response
->AddTag(CECTag(EC_TAG_STRING
, tmp
.AfterLast('\n')));
1723 case EC_OP_GET_SERVERINFO
:
1724 response
= new CECPacket(EC_OP_SERVERINFO
);
1725 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetServerLog(false)));
1727 case EC_OP_CLEAR_SERVERINFO
:
1728 theApp
->GetServerLog(true);
1729 response
= new CECPacket(EC_OP_NOOP
);
1734 case EC_OP_GET_STATSGRAPHS
:
1735 response
= GetStatsGraphs(request
);
1737 case EC_OP_GET_STATSTREE
: {
1738 theApp
->m_statistics
->UpdateStatsTree();
1739 response
= new CECPacket(EC_OP_STATSTREE
);
1740 CECTag
* tree
= theStats::GetECStatTree(request
->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING
)->GetInt());
1742 response
->AddTag(*tree
);
1745 if (request
->GetDetailLevel() == EC_DETAIL_WEB
) {
1746 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
1747 response
->AddTag(CECTag(EC_TAG_USER_NICK
, thePrefs::GetUserNick()));
1755 case EC_OP_KAD_START
:
1756 if (thePrefs::GetNetworkKademlia()) {
1757 response
= new CECPacket(EC_OP_NOOP
);
1758 if ( !Kademlia::CKademlia::IsRunning() ) {
1759 Kademlia::CKademlia::Start();
1760 theApp
->ShowConnectionState();
1763 response
= new CECPacket(EC_OP_FAILED
);
1764 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
1767 case EC_OP_KAD_STOP
:
1769 theApp
->ShowConnectionState();
1770 response
= new CECPacket(EC_OP_NOOP
);
1772 case EC_OP_KAD_UPDATE_FROM_URL
: {
1773 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1775 // Save the new url, and update the UI (if not amuled).
1776 Notify_NodesURLChanged(url
);
1777 thePrefs::SetKadNodesUrl(url
);
1779 theApp
->UpdateNotesDat(url
);
1780 response
= new CECPacket(EC_OP_NOOP
);
1783 case EC_OP_KAD_BOOTSTRAP_FROM_IP
:
1784 if (thePrefs::GetNetworkKademlia()) {
1785 theApp
->BootstrapKad(request
->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP
)->GetInt(),
1786 request
->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT
)->GetInt());
1787 theApp
->ShowConnectionState();
1788 response
= new CECPacket(EC_OP_NOOP
);
1790 response
= new CECPacket(EC_OP_FAILED
);
1791 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
1797 // These requests are currently used only in the text client
1800 if (thePrefs::GetNetworkED2K()) {
1801 response
= new CECPacket(EC_OP_STRINGS
);
1802 if (theApp
->IsConnectedED2K()) {
1803 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to eD2k.")));
1805 theApp
->serverconnect
->ConnectToAnyServer();
1806 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to eD2k...")));
1809 if (thePrefs::GetNetworkKademlia()) {
1811 response
= new CECPacket(EC_OP_STRINGS
);
1813 if (theApp
->IsConnectedKad()) {
1814 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to Kad.")));
1817 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to Kad...")));
1821 theApp
->ShowConnectionState();
1823 response
= new CECPacket(EC_OP_FAILED
);
1824 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("All networks are disabled.")));
1827 case EC_OP_DISCONNECT
:
1828 if (theApp
->IsConnected()) {
1829 response
= new CECPacket(EC_OP_STRINGS
);
1830 if (theApp
->IsConnectedED2K()) {
1831 theApp
->serverconnect
->Disconnect();
1832 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from eD2k.")));
1834 if (theApp
->IsConnectedKad()) {
1836 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from Kad.")));
1838 theApp
->ShowConnectionState();
1840 response
= new CECPacket(EC_OP_NOOP
);
1845 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request
->GetOpCode());
1847 response
= new CECPacket(EC_OP_FAILED
);
1848 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1854 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1858 * Core general status
1860 ECStatusMsgSource::ECStatusMsgSource()
1862 m_last_ed2k_status_sent
= 0xffffffff;
1863 m_last_kad_status_sent
= 0xffffffff;
1864 m_server
= (void *)0xffffffff;
1867 uint32
ECStatusMsgSource::GetEd2kStatus()
1869 if ( theApp
->IsConnectedED2K() ) {
1870 return theApp
->GetED2KID();
1871 } else if ( theApp
->serverconnect
->IsConnecting() ) {
1878 uint32
ECStatusMsgSource::GetKadStatus()
1880 if ( theApp
->IsConnectedKad() ) {
1882 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1884 } else if ( Kademlia::CKademlia::IsRunning() ) {
1890 CECPacket
*ECStatusMsgSource::GetNextPacket()
1892 if ( (m_last_ed2k_status_sent
!= GetEd2kStatus()) ||
1893 (m_last_kad_status_sent
!= GetKadStatus()) ||
1894 (m_server
!= theApp
->serverconnect
->GetCurrentServer()) ) {
1896 m_last_ed2k_status_sent
= GetEd2kStatus();
1897 m_last_kad_status_sent
= GetKadStatus();
1898 m_server
= theApp
->serverconnect
->GetCurrentServer();
1900 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
1901 response
->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE
));
1910 ECPartFileMsgSource::ECPartFileMsgSource()
1912 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
1913 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
1914 PARTFILE_STATUS status
= { true, false, false, false, true, cur_file
};
1915 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1919 void ECPartFileMsgSource::SetDirty(const CPartFile
*file
)
1921 CMD4Hash filehash
= file
->GetFileHash();
1922 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1923 m_dirty_status
[filehash
].m_dirty
= true;;
1927 void ECPartFileMsgSource::SetNew(const CPartFile
*file
)
1929 CMD4Hash filehash
= file
->GetFileHash();
1930 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1931 PARTFILE_STATUS status
= { true, false, false, false, true, file
};
1932 m_dirty_status
[filehash
] = status
;
1935 void ECPartFileMsgSource::SetCompleted(const CPartFile
*file
)
1937 CMD4Hash filehash
= file
->GetFileHash();
1938 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1940 m_dirty_status
[filehash
].m_finished
= true;
1943 void ECPartFileMsgSource::SetRemoved(const CPartFile
*file
)
1945 CMD4Hash filehash
= file
->GetFileHash();
1946 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1948 m_dirty_status
[filehash
].m_removed
= true;
1951 CECPacket
*ECPartFileMsgSource::GetNextPacket()
1953 for(std::map
<CMD4Hash
, PARTFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
1954 it
!= m_dirty_status
.end(); it
++) {
1955 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
1956 CMD4Hash filehash
= it
->first
;
1958 const CPartFile
*partfile
= it
->second
.m_file
;
1960 CECPacket
*packet
= new CECPacket(EC_OP_DLOAD_QUEUE
);
1961 if ( it
->second
.m_removed
) {
1962 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
1963 packet
->AddTag(tag
);
1964 m_dirty_status
.erase(it
);
1966 CEC_PartFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
1967 packet
->AddTag(tag
);
1969 m_dirty_status
[filehash
].m_new
= false;
1970 m_dirty_status
[filehash
].m_dirty
= false;
1979 * Shared files - similar to downloading
1981 ECKnownFileMsgSource::ECKnownFileMsgSource()
1983 for (unsigned int i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); i
++) {
1984 const CKnownFile
*cur_file
= theApp
->sharedfiles
->GetFileByIndex(i
);
1985 KNOWNFILE_STATUS status
= { true, false, false, true, cur_file
};
1986 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1990 void ECKnownFileMsgSource::SetDirty(const CKnownFile
*file
)
1992 CMD4Hash filehash
= file
->GetFileHash();
1993 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1994 m_dirty_status
[filehash
].m_dirty
= true;;
1998 void ECKnownFileMsgSource::SetNew(const CKnownFile
*file
)
2000 CMD4Hash filehash
= file
->GetFileHash();
2001 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
2002 KNOWNFILE_STATUS status
= { true, false, false, true, file
};
2003 m_dirty_status
[filehash
] = status
;
2006 void ECKnownFileMsgSource::SetRemoved(const CKnownFile
*file
)
2008 CMD4Hash filehash
= file
->GetFileHash();
2009 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
2011 m_dirty_status
[filehash
].m_removed
= true;
2014 CECPacket
*ECKnownFileMsgSource::GetNextPacket()
2016 for(std::map
<CMD4Hash
, KNOWNFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
2017 it
!= m_dirty_status
.end(); it
++) {
2018 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
2019 CMD4Hash filehash
= it
->first
;
2021 const CKnownFile
*partfile
= it
->second
.m_file
;
2023 CECPacket
*packet
= new CECPacket(EC_OP_SHARED_FILES
);
2024 if ( it
->second
.m_removed
) {
2025 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
2026 packet
->AddTag(tag
);
2027 m_dirty_status
.erase(it
);
2029 CEC_SharedFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
2030 packet
->AddTag(tag
);
2032 m_dirty_status
[filehash
].m_new
= false;
2033 m_dirty_status
[filehash
].m_dirty
= false;
2042 * Notification about search status
2044 ECSearchMsgSource::ECSearchMsgSource()
2048 CECPacket
*ECSearchMsgSource::GetNextPacket()
2050 if ( m_dirty_status
.empty() ) {
2054 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
2055 for(std::map
<CMD4Hash
, SEARCHFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
2056 it
!= m_dirty_status
.end(); it
++) {
2058 if ( it
->second
.m_new
) {
2059 response
->AddTag(CEC_SearchFile_Tag(it
->second
.m_file
, EC_DETAIL_FULL
));
2060 it
->second
.m_new
= false;
2061 } else if ( it
->second
.m_dirty
) {
2062 response
->AddTag(CEC_SearchFile_Tag(it
->second
.m_file
, EC_DETAIL_UPDATE
));
2070 void ECSearchMsgSource::FlushStatus()
2072 m_dirty_status
.clear();
2075 void ECSearchMsgSource::SetDirty(const CSearchFile
*file
)
2077 if ( m_dirty_status
.count(file
->GetFileHash()) ) {
2078 m_dirty_status
[file
->GetFileHash()].m_dirty
= true;
2080 m_dirty_status
[file
->GetFileHash()].m_new
= true;
2081 m_dirty_status
[file
->GetFileHash()].m_dirty
= true;
2082 m_dirty_status
[file
->GetFileHash()].m_child_dirty
= true;
2083 m_dirty_status
[file
->GetFileHash()].m_file
= file
;
2087 void ECSearchMsgSource::SetChildDirty(const CSearchFile
*file
)
2089 m_dirty_status
[file
->GetFileHash()].m_child_dirty
= true;
2093 * Notification about uploading clients
2095 CECPacket
*ECClientMsgSource::GetNextPacket()
2101 // Notification iface per-client
2103 ECNotifier::ECNotifier()
2107 ECNotifier::~ECNotifier()
2109 while (m_msg_source
.begin() != m_msg_source
.end())
2110 Remove_EC_Client(m_msg_source
.begin()->first
);
2113 CECPacket
*ECNotifier::GetNextPacket(ECUpdateMsgSource
*msg_source_array
[])
2115 CECPacket
*packet
= 0;
2117 // priority 0 is highest
2119 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
2120 if ( (packet
= msg_source_array
[i
]->GetNextPacket()) != 0 ) {
2127 CECPacket
*ECNotifier::GetNextPacket(CECServerSocket
*sock
)
2130 // OnOutput is called for a first time before
2131 // socket is registered
2133 if ( m_msg_source
.count(sock
) ) {
2134 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
2135 if ( !notifier_array
) {
2138 CECPacket
*packet
= GetNextPacket(notifier_array
);
2139 //printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
2147 // Interface to notification macros
2149 void ECNotifier::DownloadFile_SetDirty(const CPartFile
*file
)
2151 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2152 i
!= m_msg_source
.end(); ++i
) {
2153 CECServerSocket
*sock
= i
->first
;
2154 if ( sock
->HaveNotificationSupport() ) {
2155 ECUpdateMsgSource
**notifier_array
= i
->second
;
2156 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetDirty(file
);
2159 NextPacketToSocket();
2162 void ECNotifier::DownloadFile_RemoveFile(const CPartFile
*file
)
2164 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2165 i
!= m_msg_source
.end(); ++i
) {
2166 ECUpdateMsgSource
**notifier_array
= i
->second
;
2167 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetRemoved(file
);
2169 NextPacketToSocket();
2172 void ECNotifier::DownloadFile_RemoveSource(const CPartFile
*)
2174 // per-partfile source list is not supported (yet), and IMHO quite useless
2177 void ECNotifier::DownloadFile_AddFile(const CPartFile
*file
)
2179 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2180 i
!= m_msg_source
.end(); ++i
) {
2181 ECUpdateMsgSource
**notifier_array
= i
->second
;
2182 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetNew(file
);
2184 NextPacketToSocket();
2187 void ECNotifier::DownloadFile_AddSource(const CPartFile
*)
2189 // per-partfile source list is not supported (yet), and IMHO quite useless
2192 void ECNotifier::SharedFile_AddFile(const CKnownFile
*file
)
2194 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2195 i
!= m_msg_source
.end(); ++i
) {
2196 ECUpdateMsgSource
**notifier_array
= i
->second
;
2197 static_cast<ECKnownFileMsgSource
*>(notifier_array
[EC_KNOWN
])->SetNew(file
);
2199 NextPacketToSocket();
2202 void ECNotifier::SharedFile_RemoveFile(const CKnownFile
*file
)
2204 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2205 i
!= m_msg_source
.end(); ++i
) {
2206 ECUpdateMsgSource
**notifier_array
= i
->second
;
2207 static_cast<ECKnownFileMsgSource
*>(notifier_array
[EC_KNOWN
])->SetRemoved(file
);
2209 NextPacketToSocket();
2212 void ECNotifier::SharedFile_RemoveAllFiles()
2214 // need to figure out what to do here
2217 void ECNotifier::Add_EC_Client(CECServerSocket
*sock
)
2219 ECUpdateMsgSource
**notifier_array
= new ECUpdateMsgSource
*[EC_STATUS_LAST_PRIO
];
2220 notifier_array
[EC_STATUS
] = new ECStatusMsgSource();
2221 notifier_array
[EC_SEARCH
] = new ECSearchMsgSource();
2222 notifier_array
[EC_PARTFILE
] = new ECPartFileMsgSource();
2223 notifier_array
[EC_CLIENT
] = new ECClientMsgSource();
2224 notifier_array
[EC_KNOWN
] = new ECKnownFileMsgSource();
2226 m_msg_source
[sock
] = notifier_array
;
2229 void ECNotifier::Remove_EC_Client(CECServerSocket
*sock
)
2231 if (m_msg_source
.count(sock
)) {
2232 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
2234 m_msg_source
.erase(sock
);
2236 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
2237 delete notifier_array
[i
];
2239 delete [] notifier_array
;
2243 void ECNotifier::NextPacketToSocket()
2245 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2246 i
!= m_msg_source
.end(); ++i
) {
2247 CECServerSocket
*sock
= i
->first
;
2248 if ( sock
->HaveNotificationSupport() && !sock
->DataPending() ) {
2249 ECUpdateMsgSource
**notifier_array
= i
->second
;
2250 CECPacket
*packet
= GetNextPacket(notifier_array
);
2252 //printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2253 sock
->SendPacket(packet
);
2259 // File_checked_for_headers