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()));
589 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED
, (uint32
)theStats::GetUploadRate()));
590 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED
, (uint32
)(theStats::GetDownloadRate())));
591 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxUpload()*1024.0)));
592 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxDownload()*1024.0)));
593 response
->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN
, /*(uint32)*/theStats::GetWaitingUserCount()));
594 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT
, /*(uint32)*/theStats::GetFoundSources()));
597 uint32 totaluser
= 0, totalfile
= 0;
598 theApp
->serverlist
->GetUserFileStatus( totaluser
, totalfile
);
599 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS
, totaluser
));
600 response
->AddTag(CECTag(EC_TAG_STATS_KAD_USERS
, Kademlia::CKademlia::GetKademliaUsers()));
601 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES
, totalfile
));
602 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FILES
, Kademlia::CKademlia::GetKademliaFiles()));
603 response
->AddTag(CECTag(EC_TAG_STATS_KAD_NODES
, CStatistics::GetKadNodes()));
606 if (Kademlia::CKademlia::IsConnected()) {
607 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP
, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
608 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource
));
609 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS
, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword
));
610 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes
));
611 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD
, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad
));
612 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS
, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
613 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IN_LAN_MODE
, Kademlia::CKademlia::IsRunningInLANMode()));
614 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS
, theApp
->clientlist
->GetBuddyStatus()));
616 uint16 BuddyPort
= 0;
617 CUpDownClient
* Buddy
= theApp
->clientlist
->GetBuddy();
619 BuddyIP
= Buddy
->GetIP();
620 BuddyPort
= Buddy
->GetUDPPort();
622 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP
, BuddyIP
));
623 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT
, BuddyPort
));
625 case EC_DETAIL_UPDATE
:
632 static CECPacket
*Get_EC_Response_GetSharedFiles(const CECPacket
*request
, CFileEncoderMap
&encoders
)
634 wxASSERT(request
->GetOpCode() == EC_OP_GET_SHARED_FILES
);
636 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
638 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
640 // request can contain list of queried items
641 CTagSet
<uint32
, EC_TAG_KNOWNFILE
> queryitems(request
);
643 encoders
.UpdateEncoders();
645 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
646 const CKnownFile
*cur_file
= theApp
->sharedfiles
->GetFileByIndex(i
);
648 if ( !cur_file
|| (!queryitems
.empty() && !queryitems
.count(cur_file
->ECID())) ) {
652 CEC_SharedFile_Tag
filetag(cur_file
, detail_level
);
653 CKnownFile_Encoder
*enc
= encoders
[cur_file
->ECID()];
654 if ( detail_level
!= EC_DETAIL_UPDATE
) {
657 enc
->Encode(&filetag
);
658 response
->AddTag(filetag
);
663 static CECPacket
*Get_EC_Response_GetUpdate(CFileEncoderMap
&encoders
, CObjTagMap
&tagmap
)
665 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
667 encoders
.UpdateEncoders();
668 for (CFileEncoderMap::iterator it
= encoders
.begin(); it
!= encoders
.end(); ++it
) {
669 const CKnownFile
*cur_file
= it
->second
->GetFile();
670 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
->ECID());
671 // Completed cleared Partfiles are still stored as CPartfile,
672 // but encoded as KnownFile, so we have to check the encoder type
673 // instead of the file type.
674 if (it
->second
->IsPartFile_Encoder()) {
675 CEC_PartFile_Tag
filetag(static_cast<const CPartFile
*>(cur_file
), EC_DETAIL_INC_UPDATE
, &valuemap
);
676 // Add information if partfile is shared
677 filetag
.AddTag(EC_TAG_PARTFILE_SHARED
, it
->second
->IsShared(), &valuemap
);
679 CPartFile_Encoder
* enc
= static_cast<CPartFile_Encoder
*>(encoders
[cur_file
->ECID()]);
680 enc
->Encode(&filetag
);
681 response
->AddTag(filetag
);
683 CEC_SharedFile_Tag
filetag(cur_file
, EC_DETAIL_INC_UPDATE
, &valuemap
);
684 CKnownFile_Encoder
* enc
= encoders
[cur_file
->ECID()];
685 enc
->Encode(&filetag
);
686 response
->AddTag(filetag
);
691 CECEmptyTag
clients(EC_TAG_CLIENT
);
692 const CClientList::IDMap
& clientList
= theApp
->clientlist
->GetClientList();
693 bool onlyTransmittingClients
= thePrefs::IsTransmitOnlyUploadingClients();
694 for (CClientList::IDMap::const_iterator it
= clientList
.begin(); it
!= clientList
.end(); ++it
) {
695 const CUpDownClient
* cur_client
= it
->second
.GetClient();
696 if (onlyTransmittingClients
&& !cur_client
->IsDownloading()) {
697 // For poor CPU cores only transmit uploading clients. This will save a lot of CPU.
698 // Set ExternalConnect/TransmitOnlyUploadingClients to 1 for it.
701 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
->ECID());
702 clients
.AddTag(CEC_UpDownClient_Tag(cur_client
, EC_DETAIL_INC_UPDATE
, &valuemap
));
704 response
->AddTag(clients
);
707 CECEmptyTag
servers(EC_TAG_SERVER
);
708 std::vector
<const CServer
*> serverlist
= theApp
->serverlist
->CopySnapshot();
709 uint32 nrServers
= serverlist
.size();
710 for (uint32 i
= 0; i
< nrServers
; i
++) {
711 const CServer
* cur_server
= serverlist
[i
];
712 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_server
->ECID());
713 servers
.AddTag(CEC_Server_Tag(cur_server
, &valuemap
));
715 response
->AddTag(servers
);
718 CECEmptyTag
friends(EC_TAG_FRIEND
);
719 for (CFriendList::const_iterator it
= theApp
->friendlist
->begin(); it
!= theApp
->friendlist
->end(); ++it
) {
720 const CFriend
* cur_friend
= *it
;
721 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_friend
->ECID());
722 friends
.AddTag(CEC_Friend_Tag(cur_friend
, &valuemap
));
724 response
->AddTag(friends
);
729 static CECPacket
*Get_EC_Response_GetClientQueue(const CECPacket
*request
, CObjTagMap
&tagmap
, int op
)
731 CECPacket
*response
= new CECPacket(op
);
733 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
736 // request can contain list of queried items
737 // (not for incremental update of course)
738 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
740 const CClientRefList
& clients
= theApp
->uploadqueue
->GetUploadingList();
741 CClientRefList::const_iterator it
= clients
.begin();
742 for (; it
!= clients
.end(); ++it
) {
743 CUpDownClient
* cur_client
= it
->GetClient();
745 if (!cur_client
) { // shouldn't happen
748 if (!queryitems
.empty() && !queryitems
.count(cur_client
->ECID())) {
751 CValueMap
*valuemap
= NULL
;
752 if (detail_level
== EC_DETAIL_INC_UPDATE
) {
753 valuemap
= &tagmap
.GetValueMap(cur_client
->ECID());
755 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
, valuemap
);
757 response
->AddTag(cli_tag
);
764 static CECPacket
*Get_EC_Response_GetDownloadQueue(const CECPacket
*request
, CFileEncoderMap
&encoders
)
766 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
768 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
770 // request can contain list of queried items
771 CTagSet
<uint32
, EC_TAG_PARTFILE
> queryitems(request
);
773 encoders
.UpdateEncoders();
775 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
776 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
778 if ( !queryitems
.empty() && !queryitems
.count(cur_file
->ECID()) ) {
782 CEC_PartFile_Tag
filetag(cur_file
, detail_level
);
784 CPartFile_Encoder
* enc
= static_cast<CPartFile_Encoder
*>(encoders
[cur_file
->ECID()]);
785 if ( detail_level
!= EC_DETAIL_UPDATE
) {
788 enc
->Encode(&filetag
);
790 response
->AddTag(filetag
);
796 static CECPacket
*Get_EC_Response_PartFile_Cmd(const CECPacket
*request
)
798 CECPacket
*response
= NULL
;
800 // request can contain multiple files.
801 for (CECPacket::const_iterator it1
= request
->begin(); it1
!= request
->end(); ++it1
) {
802 const CECTag
&hashtag
= *it1
;
804 wxASSERT(hashtag
.GetTagName() == EC_TAG_PARTFILE
);
806 CMD4Hash hash
= hashtag
.GetMD4Data();
807 CPartFile
*pfile
= theApp
->downloadqueue
->GetFileByID( hash
);
810 AddLogLineN(CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash
.Encode());
811 response
= new CECPacket(EC_OP_FAILED
);
812 response
->AddTag(CECTag(EC_TAG_STRING
, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash
.Encode()));
816 switch (request
->GetOpCode()) {
817 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
818 CoreNotify_PartFile_Swap_A4AF(pfile
);
820 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
821 CoreNotify_PartFile_Swap_A4AF_Auto(pfile
);
823 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
824 CoreNotify_PartFile_Swap_A4AF_Others(pfile
);
826 case EC_OP_PARTFILE_PAUSE
:
829 case EC_OP_PARTFILE_RESUME
:
831 pfile
->SavePartFile();
833 case EC_OP_PARTFILE_STOP
:
836 case EC_OP_PARTFILE_PRIO_SET
: {
837 uint8 prio
= hashtag
.GetFirstTagSafe()->GetInt();
838 if ( prio
== PR_AUTO
) {
839 pfile
->SetAutoDownPriority(1);
841 pfile
->SetAutoDownPriority(0);
842 pfile
->SetDownPriority(prio
);
846 case EC_OP_PARTFILE_DELETE
:
847 if ( thePrefs::StartNextFile() && (pfile
->GetStatus() != PS_PAUSED
) ) {
848 theApp
->downloadqueue
->StartNextFile(pfile
);
853 case EC_OP_PARTFILE_SET_CAT
:
854 pfile
->SetCategory(hashtag
.GetFirstTagSafe()->GetInt());
858 response
= new CECPacket(EC_OP_FAILED
);
859 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
864 response
= new CECPacket(EC_OP_NOOP
);
869 static CECPacket
*Get_EC_Response_Server_Add(const CECPacket
*request
)
871 CECPacket
*response
= NULL
;
873 wxString full_addr
= request
->GetTagByNameSafe(EC_TAG_SERVER_ADDRESS
)->GetStringData();
874 wxString name
= request
->GetTagByNameSafe(EC_TAG_SERVER_NAME
)->GetStringData();
876 wxString s_ip
= full_addr
.Left(full_addr
.Find(':'));
877 wxString s_port
= full_addr
.Mid(full_addr
.Find(':') + 1);
879 long port
= StrToULong(s_port
);
880 CServer
* toadd
= new CServer(port
, s_ip
);
881 toadd
->SetListName(name
.IsEmpty() ? full_addr
: name
);
883 if ( theApp
->AddServer(toadd
, true) ) {
884 response
= new CECPacket(EC_OP_NOOP
);
886 response
= new CECPacket(EC_OP_FAILED
);
887 response
->AddTag(CECTag(EC_TAG_STRING
, _("Server not added")));
894 static CECPacket
*Get_EC_Response_Server(const CECPacket
*request
)
896 CECPacket
*response
= NULL
;
897 const CECTag
*srv_tag
= request
->GetTagByName(EC_TAG_SERVER
);
900 srv
= theApp
->serverlist
->GetServerByIPTCP(srv_tag
->GetIPv4Data().IP(), srv_tag
->GetIPv4Data().m_port
);
901 // server tag passed, but server not found
903 response
= new CECPacket(EC_OP_FAILED
);
904 response
->AddTag(CECTag(EC_TAG_STRING
,
905 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag
->GetIPv4Data().StringIP()));
909 switch (request
->GetOpCode()) {
910 case EC_OP_SERVER_DISCONNECT
:
911 theApp
->serverconnect
->Disconnect();
912 response
= new CECPacket(EC_OP_NOOP
);
914 case EC_OP_SERVER_REMOVE
:
916 theApp
->serverlist
->RemoveServer(srv
);
917 response
= new CECPacket(EC_OP_NOOP
);
919 response
= new CECPacket(EC_OP_FAILED
);
920 response
->AddTag(CECTag(EC_TAG_STRING
,
921 wxTRANSLATE("need to define server to be removed")));
924 case EC_OP_SERVER_CONNECT
:
925 if (thePrefs::GetNetworkED2K()) {
927 theApp
->serverconnect
->ConnectToServer(srv
);
928 response
= new CECPacket(EC_OP_NOOP
);
930 theApp
->serverconnect
->ConnectToAnyServer();
931 response
= new CECPacket(EC_OP_NOOP
);
934 response
= new CECPacket(EC_OP_FAILED
);
935 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("eD2k is disabled in preferences.")));
940 response
= new CECPacket(EC_OP_FAILED
);
941 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
947 static CECPacket
*Get_EC_Response_Friend(const CECPacket
*request
)
949 CECPacket
*response
= NULL
;
950 const CECTag
*tag
= request
->GetTagByName(EC_TAG_FRIEND_ADD
);
952 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_CLIENT
);
954 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(subtag
->GetInt());
956 theApp
->friendlist
->AddFriend(CCLIENTREF(client
, wxT("Get_EC_Response_Friend theApp->friendlist->AddFriend")));
957 response
= new CECPacket(EC_OP_NOOP
);
960 const CECTag
*hashtag
= tag
->GetTagByName(EC_TAG_FRIEND_HASH
);
961 const CECTag
*iptag
= tag
->GetTagByName(EC_TAG_FRIEND_IP
);
962 const CECTag
*porttag
= tag
->GetTagByName(EC_TAG_FRIEND_PORT
);
963 const CECTag
*nametag
= tag
->GetTagByName(EC_TAG_FRIEND_NAME
);
964 if (hashtag
&& iptag
&& porttag
&& nametag
) {
965 theApp
->friendlist
->AddFriend(hashtag
->GetMD4Data(), iptag
->GetInt(), porttag
->GetInt(), nametag
->GetStringData());
966 response
= new CECPacket(EC_OP_NOOP
);
969 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_REMOVE
))) {
970 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
972 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
974 theApp
->friendlist
->RemoveFriend(Friend
);
975 response
= new CECPacket(EC_OP_NOOP
);
978 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_FRIENDSLOT
))) {
979 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
981 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
983 theApp
->friendlist
->SetFriendSlot(Friend
, tag
->GetInt() != 0);
984 response
= new CECPacket(EC_OP_NOOP
);
987 } else if ((tag
= request
->GetTagByName(EC_TAG_FRIEND_SHARED
))) {
988 response
= new CECPacket(EC_OP_FAILED
);
989 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Request shared files list not implemented yet.")));
991 // This works fine - but there is no way atm to transfer the results to amulegui, so disable it for now.
993 const CECTag
*subtag
= tag
->GetTagByName(EC_TAG_FRIEND
);
995 CFriend
* Friend
= theApp
->friendlist
->FindFriend(subtag
->GetInt());
997 theApp
->friendlist
->RequestSharedFileList(Friend
);
998 response
= new CECPacket(EC_OP_NOOP
);
1000 } else if ((subtag
= tag
->GetTagByName(EC_TAG_CLIENT
))) {
1001 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(subtag
->GetInt());
1003 client
->RequestSharedFileList();
1004 response
= new CECPacket(EC_OP_NOOP
);
1011 response
= new CECPacket(EC_OP_FAILED
);
1012 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
1018 static CECPacket
*Get_EC_Response_Search_Results(const CECPacket
*request
)
1020 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
1022 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1024 // request can contain list of queried items
1025 CTagSet
<uint32
, EC_TAG_SEARCHFILE
> queryitems(request
);
1027 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
1028 CSearchResultList::const_iterator it
= list
.begin();
1029 while (it
!= list
.end()) {
1030 CSearchFile
* sf
= *it
++;
1031 if ( !queryitems
.empty() && !queryitems
.count(sf
->ECID()) ) {
1034 response
->AddTag(CEC_SearchFile_Tag(sf
, detail_level
));
1039 static CECPacket
*Get_EC_Response_Search_Results(CObjTagMap
&tagmap
)
1041 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
1043 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
1044 CSearchResultList::const_iterator it
= list
.begin();
1045 while (it
!= list
.end()) {
1046 CSearchFile
* sf
= *it
++;
1047 CValueMap
&valuemap
= tagmap
.GetValueMap(sf
->ECID());
1048 response
->AddTag(CEC_SearchFile_Tag(sf
, EC_DETAIL_INC_UPDATE
, &valuemap
));
1050 if (sf
->HasChildren()) {
1051 const CSearchResultList
& children
= sf
->GetChildren();
1052 for (size_t i
= 0; i
< children
.size(); ++i
) {
1053 CSearchFile
* sfc
= children
.at(i
);
1054 CValueMap
&valuemap1
= tagmap
.GetValueMap(sfc
->ECID());
1055 response
->AddTag(CEC_SearchFile_Tag(sfc
, EC_DETAIL_INC_UPDATE
, &valuemap1
));
1062 static CECPacket
*Get_EC_Response_Search_Results_Download(const CECPacket
*request
)
1064 CECPacket
*response
= new CECPacket(EC_OP_STRINGS
);
1065 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1066 const CECTag
&tag
= *it
;
1067 CMD4Hash hash
= tag
.GetMD4Data();
1068 uint8 category
= tag
.GetFirstTagSafe()->GetInt();
1069 theApp
->searchlist
->AddFileToDownloadByHash(hash
, category
);
1074 static CECPacket
*Get_EC_Response_Search_Stop(const CECPacket
*WXUNUSED(request
))
1076 CECPacket
*reply
= new CECPacket(EC_OP_MISC_DATA
);
1077 theApp
->searchlist
->StopSearch();
1081 static CECPacket
*Get_EC_Response_Search(const CECPacket
*request
)
1085 const CEC_Search_Tag
*search_request
= static_cast<const CEC_Search_Tag
*>(request
->GetFirstTagSafe());
1086 theApp
->searchlist
->RemoveResults(0xffffffff);
1088 CSearchList::CSearchParams params
;
1089 params
.searchString
= search_request
->SearchText();
1090 params
.typeText
= search_request
->SearchFileType();
1091 params
.extension
= search_request
->SearchExt();
1092 params
.minSize
= search_request
->MinSize();
1093 params
.maxSize
= search_request
->MaxSize();
1094 params
.availability
= search_request
->Avail();
1097 EC_SEARCH_TYPE search_type
= search_request
->SearchType();
1098 SearchType core_search_type
= LocalSearch
;
1099 uint32 op
= EC_OP_FAILED
;
1100 switch (search_type
) {
1101 case EC_SEARCH_GLOBAL
:
1102 core_search_type
= GlobalSearch
;
1104 if (core_search_type
!= GlobalSearch
) { // Not a global search obviously
1105 core_search_type
= KadSearch
;
1107 case EC_SEARCH_LOCAL
: {
1108 uint32 search_id
= 0xffffffff;
1109 wxString error
= theApp
->searchlist
->StartNewSearch(&search_id
, core_search_type
, params
);
1110 if (!error
.IsEmpty()) {
1113 response
= wxTRANSLATE("Search in progress. Refetch results in a moment!");
1119 response
= wxTRANSLATE("WebSearch from remote interface makes no sense.");
1123 CECPacket
*reply
= new CECPacket(op
);
1124 // error or search in progress
1125 reply
->AddTag(CECTag(EC_TAG_STRING
, response
));
1130 static CECPacket
*Get_EC_Response_Set_SharedFile_Prio(const CECPacket
*request
)
1132 CECPacket
*response
= new CECPacket(EC_OP_NOOP
);
1133 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1134 const CECTag
&tag
= *it
;
1135 CMD4Hash hash
= tag
.GetMD4Data();
1136 uint8 prio
= tag
.GetFirstTagSafe()->GetInt();
1137 CKnownFile
* cur_file
= theApp
->sharedfiles
->GetFileByID(hash
);
1141 if (prio
== PR_AUTO
) {
1142 cur_file
->SetAutoUpPriority(1);
1143 cur_file
->UpdateAutoUpPriority();
1145 cur_file
->SetAutoUpPriority(0);
1146 cur_file
->SetUpPriority(prio
);
1148 Notify_SharedFilesUpdateItem(cur_file
);
1154 void CPartFile_Encoder::Encode(CECTag
*parent
)
1157 // Source part frequencies
1159 CKnownFile_Encoder::Encode(parent
);
1164 const CGapList
& gaplist
= m_PartFile()->GetGapList();
1165 const size_t gap_list_size
= gaplist
.size();
1166 ArrayOfUInts64 gaps
;
1167 gaps
.reserve(gap_list_size
* 2);
1169 for (CGapList::const_iterator curr_pos
= gaplist
.begin();
1170 curr_pos
!= gaplist
.end(); ++curr_pos
) {
1171 gaps
.push_back(curr_pos
.start());
1172 gaps
.push_back(curr_pos
.end());
1175 int gap_enc_size
= 0;
1177 const uint8
*gap_enc_data
= m_gap_status
.Encode(gaps
, gap_enc_size
, changed
);
1179 parent
->AddTag(CECTag(EC_TAG_PARTFILE_GAP_STATUS
, gap_enc_size
, (void *)gap_enc_data
));
1181 delete[] gap_enc_data
;
1186 ArrayOfUInts64 req_buffer
;
1187 const CPartFile::CReqBlockPtrList
& requestedblocks
= m_PartFile()->GetRequestedBlockList();
1188 CPartFile::CReqBlockPtrList::const_iterator curr_pos2
= requestedblocks
.begin();
1190 for ( ; curr_pos2
!= requestedblocks
.end(); ++curr_pos2
) {
1191 Requested_Block_Struct
* block
= *curr_pos2
;
1192 req_buffer
.push_back(block
->StartOffset
);
1193 req_buffer
.push_back(block
->EndOffset
);
1195 int req_enc_size
= 0;
1196 const uint8
*req_enc_data
= m_req_status
.Encode(req_buffer
, req_enc_size
, changed
);
1198 parent
->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS
, req_enc_size
, (void *)req_enc_data
));
1200 delete[] req_enc_data
;
1205 // First count occurrence of all source names
1207 CECEmptyTag
sourceNames(EC_TAG_PARTFILE_SOURCE_NAMES
);
1208 typedef std::map
<wxString
, int> strIntMap
;
1210 const CPartFile::SourceSet
&sources
= m_PartFile()->GetSourceList();
1211 for (CPartFile::SourceSet::const_iterator it
= sources
.begin(); it
!= sources
.end(); ++it
) {
1212 const CClientRef
&cur_src
= *it
;
1213 if (cur_src
.GetRequestFile() != m_file
|| cur_src
.GetClientFilename().Length() == 0) {
1216 const wxString
&name
= cur_src
.GetClientFilename();
1217 strIntMap::iterator itm
= nameMap
.find(name
);
1218 if (itm
== nameMap
.end()) {
1225 // Go through our last list
1227 for (SourcenameItemMap::iterator it1
= m_sourcenameItemMap
.begin(); it1
!= m_sourcenameItemMap
.end();) {
1228 SourcenameItemMap::iterator it2
= it1
++;
1229 strIntMap::iterator itm
= nameMap
.find(it2
->second
.name
);
1230 if (itm
== nameMap
.end()) {
1231 // name doesn't exist anymore, tell client to forget it
1232 CECTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, it2
->first
);
1233 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, 0));
1234 sourceNames
.AddTag(tag
);
1236 m_sourcenameItemMap
.erase(it2
);
1238 // update count if it changed
1239 if (it2
->second
.count
!= itm
->second
) {
1240 CECTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, it2
->first
);
1241 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, itm
->second
));
1242 sourceNames
.AddTag(tag
);
1243 it2
->second
.count
= itm
->second
;
1245 // remove it from nameMap so that only new names are left there
1252 for (strIntMap::iterator it3
= nameMap
.begin(); it3
!= nameMap
.end(); ++it3
) {
1253 int id
= ++m_sourcenameID
;
1254 CECIntTag
tag(EC_TAG_PARTFILE_SOURCE_NAMES
, id
);
1255 tag
.AddTag(CECTag(EC_TAG_PARTFILE_SOURCE_NAMES
, it3
->first
));
1256 tag
.AddTag(CECIntTag(EC_TAG_PARTFILE_SOURCE_NAMES_COUNTS
, it3
->second
));
1257 sourceNames
.AddTag(tag
);
1259 m_sourcenameItemMap
[id
] = SourcenameItem(it3
->first
, it3
->second
);
1261 if (sourceNames
.HasChildTags()) {
1262 parent
->AddTag(sourceNames
);
1267 void CPartFile_Encoder::ResetEncoder()
1269 CKnownFile_Encoder::ResetEncoder();
1270 m_gap_status
.ResetEncoder();
1271 m_req_status
.ResetEncoder();
1274 void CKnownFile_Encoder::Encode(CECTag
*parent
)
1277 // Source part frequencies
1279 // Reference to the availability list
1280 const ArrayOfUInts16
& list
= m_file
->IsPartFile() ?
1281 static_cast<const CPartFile
*>(m_file
)->m_SrcpartFrequency
:
1282 m_file
->m_AvailPartFrequency
;
1283 // Don't add tag if available parts aren't populated yet.
1284 if (!list
.empty()) {
1287 const uint8
*part_enc_data
= m_enc_data
.Encode(list
, part_enc_size
, changed
);
1289 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
1291 delete[] part_enc_data
;
1295 static CECPacket
*GetStatsGraphs(const CECPacket
*request
)
1297 CECPacket
*response
= NULL
;
1299 switch (request
->GetDetailLevel()) {
1301 case EC_DETAIL_FULL
: {
1302 double dTimestamp
= 0.0;
1303 if (request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
) != NULL
) {
1304 dTimestamp
= request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
)->GetDoubleData();
1306 uint16 nScale
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE
)->GetInt();
1307 uint16 nMaxPoints
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH
)->GetInt();
1309 unsigned int numPoints
= theApp
->m_statistics
->GetHistoryForWeb(nMaxPoints
, (double)nScale
, &dTimestamp
, &graphData
);
1311 response
= new CECPacket(EC_OP_STATSGRAPHS
);
1312 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA
, 4 * numPoints
* sizeof(uint32
), graphData
));
1313 delete [] graphData
;
1314 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST
, dTimestamp
));
1316 response
= new CECPacket(EC_OP_FAILED
);
1317 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("No points for graph.")));
1321 case EC_DETAIL_INC_UPDATE
:
1322 case EC_DETAIL_UPDATE
:
1325 response
= new CECPacket(EC_OP_FAILED
);
1326 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Your client is not configured for this detail level.")));
1330 response
= new CECPacket(EC_OP_FAILED
);
1337 CECPacket
*CECServerSocket::ProcessRequest2(const CECPacket
*request
)
1344 CECPacket
*response
= NULL
;
1346 switch (request
->GetOpCode()) {
1350 case EC_OP_SHUTDOWN
:
1351 if (!theApp
->IsOnShutDown()) {
1352 response
= new CECPacket(EC_OP_NOOP
);
1353 AddLogLineC(_("External Connection: shutdown requested"));
1354 #ifndef AMULE_DAEMON
1357 evt
.SetCanVeto(false);
1358 theApp
->ShutDown(evt
);
1361 theApp
->ExitMainLoop();
1364 response
= new CECPacket(EC_OP_FAILED
);
1365 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already shutting down.")));
1368 case EC_OP_ADD_LINK
:
1369 for (CECPacket::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1370 const CECTag
&tag
= *it
;
1371 wxString link
= tag
.GetStringData();
1373 const CECTag
*cattag
= tag
.GetTagByName(EC_TAG_PARTFILE_CAT
);
1375 category
= cattag
->GetInt();
1377 AddLogLineC(CFormat(_("ExternalConn: adding link '%s'.")) % link
);
1378 if ( theApp
->downloadqueue
->AddLink(link
, category
) ) {
1379 response
= new CECPacket(EC_OP_NOOP
);
1381 // Error messages are printed by the add function.
1382 response
= new CECPacket(EC_OP_FAILED
);
1383 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid link or already on list.")));
1390 case EC_OP_STAT_REQ
:
1391 response
= Get_EC_Response_StatRequest(request
, m_LoggerAccess
);
1392 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1394 case EC_OP_GET_CONNSTATE
:
1395 response
= new CECPacket(EC_OP_MISC_DATA
);
1396 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1401 case EC_OP_GET_SHARED_FILES
:
1402 if ( request
->GetDetailLevel() != EC_DETAIL_INC_UPDATE
) {
1403 response
= Get_EC_Response_GetSharedFiles(request
, m_FileEncoder
);
1406 case EC_OP_GET_DLOAD_QUEUE
:
1407 if ( request
->GetDetailLevel() != EC_DETAIL_INC_UPDATE
) {
1408 response
= Get_EC_Response_GetDownloadQueue(request
, m_FileEncoder
);
1412 // This will evolve into an update-all for inc tags
1414 case EC_OP_GET_UPDATE
:
1415 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1416 response
= Get_EC_Response_GetUpdate(m_FileEncoder
, m_obj_tagmap
);
1419 case EC_OP_GET_ULOAD_QUEUE
:
1420 response
= Get_EC_Response_GetClientQueue(request
, m_obj_tagmap
, EC_OP_ULOAD_QUEUE
);
1422 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
1423 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
1424 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
1425 case EC_OP_PARTFILE_PAUSE
:
1426 case EC_OP_PARTFILE_RESUME
:
1427 case EC_OP_PARTFILE_STOP
:
1428 case EC_OP_PARTFILE_PRIO_SET
:
1429 case EC_OP_PARTFILE_DELETE
:
1430 case EC_OP_PARTFILE_SET_CAT
:
1431 response
= Get_EC_Response_PartFile_Cmd(request
);
1433 case EC_OP_SHAREDFILES_RELOAD
:
1434 theApp
->sharedfiles
->Reload();
1435 response
= new CECPacket(EC_OP_NOOP
);
1437 case EC_OP_SHARED_SET_PRIO
:
1438 response
= Get_EC_Response_Set_SharedFile_Prio(request
);
1440 case EC_OP_RENAME_FILE
: {
1441 CMD4Hash fileHash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1442 wxString newName
= request
->GetTagByNameSafe(EC_TAG_PARTFILE_NAME
)->GetStringData();
1443 // search first in downloadqueue - it might be in known files as well
1444 CKnownFile
* file
= theApp
->downloadqueue
->GetFileByID(fileHash
);
1446 file
= theApp
->knownfiles
->FindKnownFileByID(fileHash
);
1449 response
= new CECPacket(EC_OP_FAILED
);
1450 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("File not found.")));
1453 if (newName
.IsEmpty()) {
1454 response
= new CECPacket(EC_OP_FAILED
);
1455 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid file name.")));
1459 if (theApp
->sharedfiles
->RenameFile(file
, CPath(newName
))) {
1460 response
= new CECPacket(EC_OP_NOOP
);
1462 response
= new CECPacket(EC_OP_FAILED
);
1463 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Unable to rename file.")));
1468 case EC_OP_CLEAR_COMPLETED
: {
1469 ListOfUInts32 toClear
;
1470 for (CECTag::const_iterator it
= request
->begin(); it
!= request
->end(); ++it
) {
1471 if (it
->GetTagName() == EC_TAG_ECID
) {
1472 toClear
.push_back(it
->GetInt());
1475 theApp
->downloadqueue
->ClearCompleted(toClear
);
1476 response
= new CECPacket(EC_OP_NOOP
);
1479 case EC_OP_CLIENT_SWAP_TO_ANOTHER_FILE
: {
1480 theApp
->sharedfiles
->Reload();
1481 uint32 idClient
= request
->GetTagByNameSafe(EC_TAG_CLIENT
)->GetInt();
1482 CUpDownClient
* client
= theApp
->clientlist
->FindClientByECID(idClient
);
1483 CMD4Hash idFile
= request
->GetTagByNameSafe(EC_TAG_PARTFILE
)->GetMD4Data();
1484 CPartFile
* file
= theApp
->downloadqueue
->GetFileByID(idFile
);
1485 if (client
&& file
) {
1486 client
->SwapToAnotherFile( true, false, false, file
);
1488 response
= new CECPacket(EC_OP_NOOP
);
1491 case EC_OP_SHARED_FILE_SET_COMMENT
: {
1492 CMD4Hash hash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1493 CKnownFile
* file
= theApp
->sharedfiles
->GetFileByID(hash
);
1495 wxString newComment
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE_COMMENT
)->GetStringData();
1496 uint8 newRating
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE_RATING
)->GetInt();
1497 CoreNotify_KnownFile_Comment_Set(file
, newComment
, newRating
);
1499 response
= new CECPacket(EC_OP_NOOP
);
1506 case EC_OP_SERVER_ADD
:
1507 response
= Get_EC_Response_Server_Add(request
);
1509 case EC_OP_SERVER_DISCONNECT
:
1510 case EC_OP_SERVER_CONNECT
:
1511 case EC_OP_SERVER_REMOVE
:
1512 response
= Get_EC_Response_Server(request
);
1514 case EC_OP_GET_SERVER_LIST
: {
1515 response
= new CECPacket(EC_OP_SERVER_LIST
);
1516 if (!thePrefs::GetNetworkED2K()) {
1517 // Kad only: just send an empty list
1520 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1521 std::vector
<const CServer
*> servers
= theApp
->serverlist
->CopySnapshot();
1523 std::vector
<const CServer
*>::const_iterator it
= servers
.begin();
1524 it
!= servers
.end();
1527 response
->AddTag(CEC_Server_Tag(*it
, detail_level
));
1531 case EC_OP_SERVER_UPDATE_FROM_URL
: {
1532 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1534 // Save the new url, and update the UI (if not amuled).
1535 Notify_ServersURLChanged(url
);
1536 thePrefs::SetEd2kServersUrl(url
);
1538 theApp
->serverlist
->UpdateServerMetFromURL(url
);
1539 response
= new CECPacket(EC_OP_NOOP
);
1542 case EC_OP_SERVER_SET_STATIC_PRIO
: {
1543 uint32 ecid
= request
->GetTagByNameSafe(EC_TAG_SERVER
)->GetInt();
1544 CServer
* server
= theApp
->serverlist
->GetServerByECID(ecid
);
1546 const CECTag
* staticTag
= request
->GetTagByName(EC_TAG_SERVER_STATIC
);
1548 theApp
->serverlist
->SetStaticServer(server
, staticTag
->GetInt() > 0);
1550 const CECTag
* prioTag
= request
->GetTagByName(EC_TAG_SERVER_PRIO
);
1552 theApp
->serverlist
->SetServerPrio(server
, prioTag
->GetInt());
1555 response
= new CECPacket(EC_OP_NOOP
);
1562 response
= Get_EC_Response_Friend(request
);
1568 case EC_OP_IPFILTER_RELOAD
:
1569 NotifyAlways_IPFilter_Reload();
1570 response
= new CECPacket(EC_OP_NOOP
);
1573 case EC_OP_IPFILTER_UPDATE
: {
1574 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1575 if (url
.IsEmpty()) {
1576 url
= thePrefs::IPFilterURL();
1578 NotifyAlways_IPFilter_Update(url
);
1579 response
= new CECPacket(EC_OP_NOOP
);
1585 case EC_OP_SEARCH_START
:
1586 response
= Get_EC_Response_Search(request
);
1589 case EC_OP_SEARCH_STOP
:
1590 response
= Get_EC_Response_Search_Stop(request
);
1593 case EC_OP_SEARCH_RESULTS
:
1594 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1595 response
= Get_EC_Response_Search_Results(m_obj_tagmap
);
1597 response
= Get_EC_Response_Search_Results(request
);
1601 case EC_OP_SEARCH_PROGRESS
:
1602 response
= new CECPacket(EC_OP_SEARCH_PROGRESS
);
1603 response
->AddTag(CECTag(EC_TAG_SEARCH_STATUS
,
1604 theApp
->searchlist
->GetSearchProgress()));
1607 case EC_OP_DOWNLOAD_SEARCH_RESULT
:
1608 response
= Get_EC_Response_Search_Results_Download(request
);
1613 case EC_OP_GET_PREFERENCES
:
1614 response
= new CEC_Prefs_Packet(request
->GetTagByNameSafe(EC_TAG_SELECT_PREFS
)->GetInt(), request
->GetDetailLevel());
1616 case EC_OP_SET_PREFERENCES
:
1617 static_cast<const CEC_Prefs_Packet
*>(request
)->Apply();
1618 theApp
->glob_prefs
->Save();
1619 if (thePrefs::IsFilteringClients()) {
1620 theApp
->clientlist
->FilterQueues();
1622 if (thePrefs::IsFilteringServers()) {
1623 theApp
->serverlist
->FilterServers();
1625 if (!thePrefs::GetNetworkED2K() && theApp
->IsConnectedED2K()) {
1626 theApp
->DisconnectED2K();
1628 if (!thePrefs::GetNetworkKademlia() && theApp
->IsConnectedKad()) {
1631 response
= new CECPacket(EC_OP_NOOP
);
1634 case EC_OP_CREATE_CATEGORY
:
1635 if ( request
->GetTagCount() == 1 ) {
1636 CEC_Category_Tag
tag(*static_cast<const CEC_Category_Tag
*>(request
->GetFirstTagSafe()));
1638 response
= new CECPacket(EC_OP_NOOP
);
1640 response
= new CECPacket(EC_OP_FAILED
);
1641 response
->AddTag(CECTag(EC_TAG_CATEGORY
, theApp
->glob_prefs
->GetCatCount() - 1));
1642 response
->AddTag(CECTag(EC_TAG_CATEGORY_PATH
, tag
.Path()));
1644 Notify_CategoryAdded();
1646 response
= new CECPacket(EC_OP_NOOP
);
1649 case EC_OP_UPDATE_CATEGORY
:
1650 if ( request
->GetTagCount() == 1 ) {
1651 CEC_Category_Tag
tag(*static_cast<const CEC_Category_Tag
*>(request
->GetFirstTagSafe()));
1653 response
= new CECPacket(EC_OP_NOOP
);
1655 response
= new CECPacket(EC_OP_FAILED
);
1656 response
->AddTag(CECTag(EC_TAG_CATEGORY
, tag
.GetInt()));
1657 response
->AddTag(CECTag(EC_TAG_CATEGORY_PATH
, tag
.Path()));
1659 Notify_CategoryUpdate(tag
.GetInt());
1661 response
= new CECPacket(EC_OP_NOOP
);
1664 case EC_OP_DELETE_CATEGORY
:
1665 if ( request
->GetTagCount() == 1 ) {
1666 uint32 cat
= request
->GetFirstTagSafe()->GetInt();
1667 // this noes not only update the gui, but actually deletes the cat
1668 Notify_CategoryDelete(cat
);
1670 response
= new CECPacket(EC_OP_NOOP
);
1676 case EC_OP_ADDLOGLINE
:
1677 // cppcheck-suppress duplicateBranch
1678 if (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
) {
1679 AddLogLineC(request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1681 AddLogLineN(request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1683 response
= new CECPacket(EC_OP_NOOP
);
1685 case EC_OP_ADDDEBUGLOGLINE
:
1686 // cppcheck-suppress duplicateBranch
1687 if (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
) {
1688 AddDebugLogLineC(logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1690 AddDebugLogLineN(logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData());
1692 response
= new CECPacket(EC_OP_NOOP
);
1695 response
= new CECPacket(EC_OP_LOG
);
1696 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetLog(false)));
1698 case EC_OP_GET_DEBUGLOG
:
1699 response
= new CECPacket(EC_OP_DEBUGLOG
);
1700 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetDebugLog(false)));
1702 case EC_OP_RESET_LOG
:
1703 theApp
->GetLog(true);
1704 response
= new CECPacket(EC_OP_NOOP
);
1706 case EC_OP_RESET_DEBUGLOG
:
1707 theApp
->GetDebugLog(true);
1708 response
= new CECPacket(EC_OP_NOOP
);
1710 case EC_OP_GET_LAST_LOG_ENTRY
:
1712 wxString tmp
= theApp
->GetLog(false);
1713 if (tmp
.Last() == '\n') {
1716 response
= new CECPacket(EC_OP_LOG
);
1717 response
->AddTag(CECTag(EC_TAG_STRING
, tmp
.AfterLast('\n')));
1720 case EC_OP_GET_SERVERINFO
:
1721 response
= new CECPacket(EC_OP_SERVERINFO
);
1722 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetServerLog(false)));
1724 case EC_OP_CLEAR_SERVERINFO
:
1725 theApp
->GetServerLog(true);
1726 response
= new CECPacket(EC_OP_NOOP
);
1731 case EC_OP_GET_STATSGRAPHS
:
1732 response
= GetStatsGraphs(request
);
1734 case EC_OP_GET_STATSTREE
: {
1735 theApp
->m_statistics
->UpdateStatsTree();
1736 response
= new CECPacket(EC_OP_STATSTREE
);
1737 CECTag
* tree
= theStats::GetECStatTree(request
->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING
)->GetInt());
1739 response
->AddTag(*tree
);
1742 if (request
->GetDetailLevel() == EC_DETAIL_WEB
) {
1743 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
1744 response
->AddTag(CECTag(EC_TAG_USER_NICK
, thePrefs::GetUserNick()));
1752 case EC_OP_KAD_START
:
1753 if (thePrefs::GetNetworkKademlia()) {
1754 response
= new CECPacket(EC_OP_NOOP
);
1755 if ( !Kademlia::CKademlia::IsRunning() ) {
1756 Kademlia::CKademlia::Start();
1757 theApp
->ShowConnectionState();
1760 response
= new CECPacket(EC_OP_FAILED
);
1761 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
1764 case EC_OP_KAD_STOP
:
1766 theApp
->ShowConnectionState();
1767 response
= new CECPacket(EC_OP_NOOP
);
1769 case EC_OP_KAD_UPDATE_FROM_URL
: {
1770 wxString url
= request
->GetFirstTagSafe()->GetStringData();
1772 // Save the new url, and update the UI (if not amuled).
1773 Notify_NodesURLChanged(url
);
1774 thePrefs::SetKadNodesUrl(url
);
1776 theApp
->UpdateNotesDat(url
);
1777 response
= new CECPacket(EC_OP_NOOP
);
1780 case EC_OP_KAD_BOOTSTRAP_FROM_IP
:
1781 if (thePrefs::GetNetworkKademlia()) {
1782 theApp
->BootstrapKad(request
->GetTagByNameSafe(EC_TAG_BOOTSTRAP_IP
)->GetInt(),
1783 request
->GetTagByNameSafe(EC_TAG_BOOTSTRAP_PORT
)->GetInt());
1784 theApp
->ShowConnectionState();
1785 response
= new CECPacket(EC_OP_NOOP
);
1787 response
= new CECPacket(EC_OP_FAILED
);
1788 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
1794 // These requests are currently used only in the text client
1797 if (thePrefs::GetNetworkED2K()) {
1798 response
= new CECPacket(EC_OP_STRINGS
);
1799 if (theApp
->IsConnectedED2K()) {
1800 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to eD2k.")));
1802 theApp
->serverconnect
->ConnectToAnyServer();
1803 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to eD2k...")));
1806 if (thePrefs::GetNetworkKademlia()) {
1808 response
= new CECPacket(EC_OP_STRINGS
);
1810 if (theApp
->IsConnectedKad()) {
1811 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to Kad.")));
1814 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to Kad...")));
1818 theApp
->ShowConnectionState();
1820 response
= new CECPacket(EC_OP_FAILED
);
1821 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("All networks are disabled.")));
1824 case EC_OP_DISCONNECT
:
1825 if (theApp
->IsConnected()) {
1826 response
= new CECPacket(EC_OP_STRINGS
);
1827 if (theApp
->IsConnectedED2K()) {
1828 theApp
->serverconnect
->Disconnect();
1829 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from eD2k.")));
1831 if (theApp
->IsConnectedKad()) {
1833 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from Kad.")));
1835 theApp
->ShowConnectionState();
1837 response
= new CECPacket(EC_OP_NOOP
);
1842 AddLogLineN(CFormat(_("External Connection: invalid opcode received: %#x")) % request
->GetOpCode());
1844 response
= new CECPacket(EC_OP_FAILED
);
1845 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1851 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1855 * Core general status
1857 ECStatusMsgSource::ECStatusMsgSource()
1859 m_last_ed2k_status_sent
= 0xffffffff;
1860 m_last_kad_status_sent
= 0xffffffff;
1861 m_server
= (void *)0xffffffff;
1864 uint32
ECStatusMsgSource::GetEd2kStatus()
1866 if ( theApp
->IsConnectedED2K() ) {
1867 return theApp
->GetED2KID();
1868 } else if ( theApp
->serverconnect
->IsConnecting() ) {
1875 uint32
ECStatusMsgSource::GetKadStatus()
1877 if ( theApp
->IsConnectedKad() ) {
1879 } else if ( Kademlia::CKademlia::IsFirewalled() ) {
1881 } else if ( Kademlia::CKademlia::IsRunning() ) {
1887 CECPacket
*ECStatusMsgSource::GetNextPacket()
1889 if ( (m_last_ed2k_status_sent
!= GetEd2kStatus()) ||
1890 (m_last_kad_status_sent
!= GetKadStatus()) ||
1891 (m_server
!= theApp
->serverconnect
->GetCurrentServer()) ) {
1893 m_last_ed2k_status_sent
= GetEd2kStatus();
1894 m_last_kad_status_sent
= GetKadStatus();
1895 m_server
= theApp
->serverconnect
->GetCurrentServer();
1897 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
1898 response
->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE
));
1907 ECPartFileMsgSource::ECPartFileMsgSource()
1909 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
1910 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
1911 PARTFILE_STATUS status
= { true, false, false, false, true, cur_file
};
1912 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1916 void ECPartFileMsgSource::SetDirty(const CPartFile
*file
)
1918 CMD4Hash filehash
= file
->GetFileHash();
1919 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1920 m_dirty_status
[filehash
].m_dirty
= true;;
1924 void ECPartFileMsgSource::SetNew(const CPartFile
*file
)
1926 CMD4Hash filehash
= file
->GetFileHash();
1927 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1928 PARTFILE_STATUS status
= { true, false, false, false, true, file
};
1929 m_dirty_status
[filehash
] = status
;
1932 void ECPartFileMsgSource::SetCompleted(const CPartFile
*file
)
1934 CMD4Hash filehash
= file
->GetFileHash();
1935 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1937 m_dirty_status
[filehash
].m_finished
= true;
1940 void ECPartFileMsgSource::SetRemoved(const CPartFile
*file
)
1942 CMD4Hash filehash
= file
->GetFileHash();
1943 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1945 m_dirty_status
[filehash
].m_removed
= true;
1948 CECPacket
*ECPartFileMsgSource::GetNextPacket()
1950 for(std::map
<CMD4Hash
, PARTFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
1951 it
!= m_dirty_status
.end(); it
++) {
1952 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
1953 CMD4Hash filehash
= it
->first
;
1955 const CPartFile
*partfile
= it
->second
.m_file
;
1957 CECPacket
*packet
= new CECPacket(EC_OP_DLOAD_QUEUE
);
1958 if ( it
->second
.m_removed
) {
1959 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
1960 packet
->AddTag(tag
);
1961 m_dirty_status
.erase(it
);
1963 CEC_PartFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
1964 packet
->AddTag(tag
);
1966 m_dirty_status
[filehash
].m_new
= false;
1967 m_dirty_status
[filehash
].m_dirty
= false;
1976 * Shared files - similar to downloading
1978 ECKnownFileMsgSource::ECKnownFileMsgSource()
1980 for (unsigned int i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); i
++) {
1981 const CKnownFile
*cur_file
= theApp
->sharedfiles
->GetFileByIndex(i
);
1982 KNOWNFILE_STATUS status
= { true, false, false, true, cur_file
};
1983 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1987 void ECKnownFileMsgSource::SetDirty(const CKnownFile
*file
)
1989 CMD4Hash filehash
= file
->GetFileHash();
1990 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1991 m_dirty_status
[filehash
].m_dirty
= true;;
1995 void ECKnownFileMsgSource::SetNew(const CKnownFile
*file
)
1997 CMD4Hash filehash
= file
->GetFileHash();
1998 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1999 KNOWNFILE_STATUS status
= { true, false, false, true, file
};
2000 m_dirty_status
[filehash
] = status
;
2003 void ECKnownFileMsgSource::SetRemoved(const CKnownFile
*file
)
2005 CMD4Hash filehash
= file
->GetFileHash();
2006 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
2008 m_dirty_status
[filehash
].m_removed
= true;
2011 CECPacket
*ECKnownFileMsgSource::GetNextPacket()
2013 for(std::map
<CMD4Hash
, KNOWNFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
2014 it
!= m_dirty_status
.end(); it
++) {
2015 if ( it
->second
.m_new
|| it
->second
.m_dirty
|| it
->second
.m_removed
) {
2016 CMD4Hash filehash
= it
->first
;
2018 const CKnownFile
*partfile
= it
->second
.m_file
;
2020 CECPacket
*packet
= new CECPacket(EC_OP_SHARED_FILES
);
2021 if ( it
->second
.m_removed
) {
2022 CECTag
tag(EC_TAG_PARTFILE
, filehash
);
2023 packet
->AddTag(tag
);
2024 m_dirty_status
.erase(it
);
2026 CEC_SharedFile_Tag
tag(partfile
, it
->second
.m_new
? EC_DETAIL_FULL
: EC_DETAIL_UPDATE
);
2027 packet
->AddTag(tag
);
2029 m_dirty_status
[filehash
].m_new
= false;
2030 m_dirty_status
[filehash
].m_dirty
= false;
2039 * Notification about search status
2041 ECSearchMsgSource::ECSearchMsgSource()
2045 CECPacket
*ECSearchMsgSource::GetNextPacket()
2047 if ( m_dirty_status
.empty() ) {
2051 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
2052 for(std::map
<CMD4Hash
, SEARCHFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
2053 it
!= m_dirty_status
.end(); it
++) {
2055 if ( it
->second
.m_new
) {
2056 response
->AddTag(CEC_SearchFile_Tag(it
->second
.m_file
, EC_DETAIL_FULL
));
2057 it
->second
.m_new
= false;
2058 } else if ( it
->second
.m_dirty
) {
2059 response
->AddTag(CEC_SearchFile_Tag(it
->second
.m_file
, EC_DETAIL_UPDATE
));
2067 void ECSearchMsgSource::FlushStatus()
2069 m_dirty_status
.clear();
2072 void ECSearchMsgSource::SetDirty(const CSearchFile
*file
)
2074 if ( m_dirty_status
.count(file
->GetFileHash()) ) {
2075 m_dirty_status
[file
->GetFileHash()].m_dirty
= true;
2077 m_dirty_status
[file
->GetFileHash()].m_new
= true;
2078 m_dirty_status
[file
->GetFileHash()].m_dirty
= true;
2079 m_dirty_status
[file
->GetFileHash()].m_child_dirty
= true;
2080 m_dirty_status
[file
->GetFileHash()].m_file
= file
;
2084 void ECSearchMsgSource::SetChildDirty(const CSearchFile
*file
)
2086 m_dirty_status
[file
->GetFileHash()].m_child_dirty
= true;
2090 * Notification about uploading clients
2092 CECPacket
*ECClientMsgSource::GetNextPacket()
2098 // Notification iface per-client
2100 ECNotifier::ECNotifier()
2104 ECNotifier::~ECNotifier()
2106 while (m_msg_source
.begin() != m_msg_source
.end())
2107 Remove_EC_Client(m_msg_source
.begin()->first
);
2110 CECPacket
*ECNotifier::GetNextPacket(ECUpdateMsgSource
*msg_source_array
[])
2112 CECPacket
*packet
= 0;
2114 // priority 0 is highest
2116 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
2117 if ( (packet
= msg_source_array
[i
]->GetNextPacket()) != 0 ) {
2124 CECPacket
*ECNotifier::GetNextPacket(CECServerSocket
*sock
)
2127 // OnOutput is called for a first time before
2128 // socket is registered
2130 if ( m_msg_source
.count(sock
) ) {
2131 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
2132 if ( !notifier_array
) {
2135 CECPacket
*packet
= GetNextPacket(notifier_array
);
2136 //printf("[EC] next update packet; opcode=%x\n",packet ? packet->GetOpCode() : 0xff);
2144 // Interface to notification macros
2146 void ECNotifier::DownloadFile_SetDirty(const CPartFile
*file
)
2148 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2149 i
!= m_msg_source
.end(); ++i
) {
2150 CECServerSocket
*sock
= i
->first
;
2151 if ( sock
->HaveNotificationSupport() ) {
2152 ECUpdateMsgSource
**notifier_array
= i
->second
;
2153 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetDirty(file
);
2156 NextPacketToSocket();
2159 void ECNotifier::DownloadFile_RemoveFile(const CPartFile
*file
)
2161 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2162 i
!= m_msg_source
.end(); ++i
) {
2163 ECUpdateMsgSource
**notifier_array
= i
->second
;
2164 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetRemoved(file
);
2166 NextPacketToSocket();
2169 void ECNotifier::DownloadFile_RemoveSource(const CPartFile
*)
2171 // per-partfile source list is not supported (yet), and IMHO quite useless
2174 void ECNotifier::DownloadFile_AddFile(const CPartFile
*file
)
2176 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2177 i
!= m_msg_source
.end(); ++i
) {
2178 ECUpdateMsgSource
**notifier_array
= i
->second
;
2179 static_cast<ECPartFileMsgSource
*>(notifier_array
[EC_PARTFILE
])->SetNew(file
);
2181 NextPacketToSocket();
2184 void ECNotifier::DownloadFile_AddSource(const CPartFile
*)
2186 // per-partfile source list is not supported (yet), and IMHO quite useless
2189 void ECNotifier::SharedFile_AddFile(const CKnownFile
*file
)
2191 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2192 i
!= m_msg_source
.end(); ++i
) {
2193 ECUpdateMsgSource
**notifier_array
= i
->second
;
2194 static_cast<ECKnownFileMsgSource
*>(notifier_array
[EC_KNOWN
])->SetNew(file
);
2196 NextPacketToSocket();
2199 void ECNotifier::SharedFile_RemoveFile(const CKnownFile
*file
)
2201 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2202 i
!= m_msg_source
.end(); ++i
) {
2203 ECUpdateMsgSource
**notifier_array
= i
->second
;
2204 static_cast<ECKnownFileMsgSource
*>(notifier_array
[EC_KNOWN
])->SetRemoved(file
);
2206 NextPacketToSocket();
2209 void ECNotifier::SharedFile_RemoveAllFiles()
2211 // need to figure out what to do here
2214 void ECNotifier::Add_EC_Client(CECServerSocket
*sock
)
2216 ECUpdateMsgSource
**notifier_array
= new ECUpdateMsgSource
*[EC_STATUS_LAST_PRIO
];
2217 notifier_array
[EC_STATUS
] = new ECStatusMsgSource();
2218 notifier_array
[EC_SEARCH
] = new ECSearchMsgSource();
2219 notifier_array
[EC_PARTFILE
] = new ECPartFileMsgSource();
2220 notifier_array
[EC_CLIENT
] = new ECClientMsgSource();
2221 notifier_array
[EC_KNOWN
] = new ECKnownFileMsgSource();
2223 m_msg_source
[sock
] = notifier_array
;
2226 void ECNotifier::Remove_EC_Client(CECServerSocket
*sock
)
2228 if (m_msg_source
.count(sock
)) {
2229 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
2231 m_msg_source
.erase(sock
);
2233 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
2234 delete notifier_array
[i
];
2236 delete [] notifier_array
;
2240 void ECNotifier::NextPacketToSocket()
2242 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
2243 i
!= m_msg_source
.end(); ++i
) {
2244 CECServerSocket
*sock
= i
->first
;
2245 if ( sock
->HaveNotificationSupport() && !sock
->DataPending() ) {
2246 ECUpdateMsgSource
**notifier_array
= i
->second
;
2247 CECPacket
*packet
= GetNextPacket(notifier_array
);
2249 //printf("[EC] sending update packet; opcode=%x\n",packet->GetOpCode());
2250 sock
->SendPacket(packet
);
2256 // File_checked_for_headers