2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 Kry ( elkry@sourceforge.net / http://www.amule.org )
5 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
6 // Copyright (c) 2008 Froenchenko Leonid (lfroen@gmail.com)
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>
37 #include "ExternalConn.h" // Interface declarations
38 #include "updownclient.h" // Needed for CUpDownClient
39 #include "Server.h" // Needed for CServer
40 #include "ServerList.h" // Needed for CServerList
41 #include "PartFile.h" // Needed for CPartFile
42 #include "ServerConnect.h" // Needed for CServerConnect
43 #include "UploadQueue.h" // Needed for CUploadQueue
44 #include "amule.h" // Needed for theApp
45 #include "SearchList.h" // Needed for GetSearchResults
46 #include "IPFilter.h" // Needed for CIPFilter
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
53 #include "kademlia/kademlia/Kademlia.h"
54 #include "kademlia/kademlia/UDPFirewallTester.h"
57 //-------------------- CECServerSocket --------------------
59 class CECServerSocket
: public CECMuleSocket
62 CECServerSocket(ECNotifier
*notifier
);
63 virtual ~CECServerSocket();
65 virtual const CECPacket
*OnPacketReceived(const CECPacket
*packet
);
66 virtual void OnLost();
68 virtual void WriteDoneAndQueueEmpty();
70 ECNotifier
*m_ec_notifier
;
73 CLoggerAccess m_LoggerAccess
;
74 CPartFile_Encoder_Map m_part_encoder
;
75 CKnownFile_Encoder_Map m_shared_encoder
;
76 CObjTagMap m_obj_tagmap
;
77 CECPacket
*ProcessRequest2(
78 const CECPacket
*request
,
79 CPartFile_Encoder_Map
&,
80 CKnownFile_Encoder_Map
&,
86 CECServerSocket::CECServerSocket(ECNotifier
*notifier
)
89 m_authenticated(false),
94 wxASSERT(theApp
->ECServerHandler
);
95 theApp
->ECServerHandler
->AddSocket(this);
96 m_ec_notifier
= notifier
;
100 CECServerSocket::~CECServerSocket()
102 wxASSERT(theApp
->ECServerHandler
);
103 theApp
->ECServerHandler
->RemoveSocket(this);
107 const CECPacket
*CECServerSocket::OnPacketReceived(const CECPacket
*packet
)
109 const CECPacket
*reply
= NULL
;
111 if (!m_authenticated
) {
112 reply
= ExternalConn::Authenticate(packet
);
113 if (reply
->GetOpCode() != EC_OP_AUTH_OK
) {
115 AddLogLineM(false, _("Unauthorized access attempt. Connection closed."));
118 m_authenticated
= true;
121 reply
= ProcessRequest2(
122 packet
, m_part_encoder
, m_shared_encoder
, m_obj_tagmap
);
128 void CECServerSocket::OnLost()
130 AddLogLineM(false,_("External connection closed."));
134 void CECServerSocket::WriteDoneAndQueueEmpty()
136 if ( HaveNotificationSupport() ) {
137 CECPacket
*packet
= m_ec_notifier
->GetNextPacket(this);
144 //-------------------- ExternalConn --------------------
152 BEGIN_EVENT_TABLE(ExternalConn
, wxEvtHandler
)
153 EVT_SOCKET(SERVER_ID
, ExternalConn::OnServerEvent
)
157 ExternalConn::ExternalConn(amuleIPV4Address addr
, wxString
*msg
)
161 // Are we allowed to accept External Connections?
162 if ( thePrefs::AcceptExternalConnections() ) {
163 // We must have a valid password, otherwise we will not allow EC connections
164 if (thePrefs::ECPassword().IsEmpty()) {
165 *msg
+= wxT("External connections disabled due to empty password!\n");
166 AddLogLineM(true, _("External connections disabled due to empty password!"));
171 m_ECServer
= new wxSocketServer(addr
, wxSOCKET_REUSEADDR
);
172 m_ECServer
->SetEventHandler(*this, SERVER_ID
);
173 m_ECServer
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
174 m_ECServer
->Notify(true);
176 int port
= addr
.Service();
177 wxString ip
= addr
.IPAddress();
178 if (m_ECServer
->Ok()) {
179 msgLocal
= wxT("*** TCP socket (ECServer) listening on ") + ip
+
180 wxString::Format(wxT(":%d"), port
);
181 *msg
+= msgLocal
+ wxT("\n");
182 AddLogLineM(false, msgLocal
);
184 msgLocal
= wxT("Could not listen for external connections at ") + ip
+
185 wxString::Format(wxT(":%d!"), port
);
186 *msg
+= msgLocal
+ wxT("\n");
187 AddLogLineM(false, msgLocal
);
190 *msg
+= wxT("External connections disabled in config file\n");
191 AddLogLineM(false,_("External connections disabled in config file"));
193 m_ec_notifier
= new ECNotifier();
197 ExternalConn::~ExternalConn()
201 delete m_ec_notifier
;
205 void ExternalConn::AddSocket(CECServerSocket
*s
)
208 socket_list
.insert(s
);
212 void ExternalConn::RemoveSocket(CECServerSocket
*s
)
215 socket_list
.erase(s
);
219 void ExternalConn::KillAllSockets()
221 AddDebugLogLineM(false, logGeneral
,
222 CFormat(wxT("ExternalConn::KillAllSockets(): %d sockets to destroy.")) %
224 SocketSet::iterator it
= socket_list
.begin();
225 while (it
!= socket_list
.end()) {
226 CECServerSocket
*s
= *(it
++);
234 void ExternalConn::OnServerEvent(wxSocketEvent
& WXUNUSED(event
))
236 CECServerSocket
*sock
= new CECServerSocket(m_ec_notifier
);
237 // Accept new connection if there is one in the pending
238 // connections queue, else exit. We use Accept(FALSE) for
239 // non-blocking accept (although if we got here, there
240 // should ALWAYS be a pending connection).
241 if ( m_ECServer
->AcceptWith(*sock
, false) ) {
242 AddLogLineM(false, _("New external connection accepted"));
245 AddLogLineM(false, _("ERROR: couldn't accept a new external connection"));
253 CECPacket
*ExternalConn::Authenticate(const CECPacket
*request
)
257 if (request
== NULL
) {
258 response
= new CECPacket(EC_OP_AUTH_FAIL
);
262 // Password must be specified if we are to allow remote connections
263 if ( thePrefs::ECPassword().IsEmpty() ) {
264 AddLogLineM(true, _("External connection refused due to empty password in preferences!"));
266 return new CECPacket(EC_OP_AUTH_FAIL
);
270 if (request
->GetOpCode() == EC_OP_AUTH_REQ
) {
271 const CECTag
*clientName
= request
->GetTagByName(EC_TAG_CLIENT_NAME
);
272 const CECTag
*clientVersion
= request
->GetTagByName(EC_TAG_CLIENT_VERSION
);
274 AddLogLineM(false, CFormat( _("Connecting client: %s %s") )
275 % ( clientName
? clientName
->GetStringData() : wxString(_("Unknown")) )
276 % ( clientVersion
? clientVersion
->GetStringData() : wxString(_("Unknown version")) ) );
277 const CECTag
*passwd
= request
->GetTagByName(EC_TAG_PASSWD_HASH
);
278 const CECTag
*protocol
= request
->GetTagByName(EC_TAG_PROTOCOL_VERSION
);
280 // For SVN versions, both client and server must use SVNDATE, and they must be the same
282 if (not vhash
.Decode(wxT(EC_VERSION_ID
))) {
283 response
= new CECPacket(EC_OP_AUTH_FAIL
);
284 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Fatal error, version hash is not a valid MD4-hash.")));
285 } else if (!request
->GetTagByName(EC_TAG_VERSION_ID
) || request
->GetTagByNameSafe(EC_TAG_VERSION_ID
)->GetMD4Data() != vhash
) {
286 response
= new CECPacket(EC_OP_AUTH_FAIL
);
287 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Incorrect EC version ID, there might be binary incompatibility. Use core and remote from same snapshot.")));
289 // For release versions, we don't want to allow connections from any arbitrary SVN client.
290 if (request
->GetTagByName(EC_TAG_VERSION_ID
)) {
291 response
= new CECPacket(EC_OP_AUTH_FAIL
);
292 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("You cannot connect to a release version from an arbitrary SVN version! *sigh* possible crash prevented")));
294 } else if (protocol
!= NULL
) {
295 uint16 proto_version
= protocol
->GetInt();
296 if (proto_version
== EC_CURRENT_PROTOCOL_VERSION
) {
299 if (!passh
.Decode(thePrefs::ECPassword())) {
300 AddLogLineM(false, wxT("EC Auth failed, invalid hash specificed as EC password: ") + thePrefs::ECPassword());
301 response
= new CECPacket(EC_OP_AUTH_FAIL
);
302 response
->AddTag(CECTag(EC_TAG_STRING
, wxT("Authentication failed, invalid hash specified as EC password.")));
303 } else if (passwd
&& passwd
->GetMD4Data() == passh
) {
304 response
= new CECPacket(EC_OP_AUTH_OK
);
307 AddLogLineM(false, wxT("EC Auth failed: (") + passwd
->GetMD4Data().Encode() + wxT(" != ") + passh
.Encode() + wxT(")."));
309 AddLogLineM(false, wxT("EC Auth failed. Password tag missing."));
312 response
= new CECPacket(EC_OP_AUTH_FAIL
);
313 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Authentication failed.")));
316 response
= new CECPacket(EC_OP_AUTH_FAIL
);
317 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid protocol version.") + wxString::Format(wxT("( %i != %i )"),proto_version
,EC_CURRENT_PROTOCOL_VERSION
)));
320 response
= new CECPacket(EC_OP_AUTH_FAIL
);
321 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Missing protocol version tag.")));
324 response
= new CECPacket(EC_OP_AUTH_FAIL
);
325 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid request, you should first authenticate.")));
328 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
330 if (response
->GetOpCode() == EC_OP_AUTH_OK
) {
331 AddLogLineM(false, _("Access granted."));
333 AddLogLineM(false, wxGetTranslation(response
->GetTagByIndex(0)->GetStringData()));
339 // Make a Logger tag (if there are any logging messages) and add it to the response
340 static void AddLoggerTag(CECPacket
*response
, CLoggerAccess
&LoggerAccess
)
342 if (LoggerAccess
.HasString()) {
343 CECEmptyTag
tag(EC_TAG_STATS_LOGGER_MESSAGE
);
344 // Tag structure is fix: tag carries nothing, inside are the strings
345 // maximum of 200 log lines per message
348 while (entries
< 200 && LoggerAccess
.GetString(line
)) {
349 tag
.AddTag(CECTag(EC_TAG_STRING
, line
));
352 response
->AddTag(tag
);
353 //printf("send Log tag %d %d\n", FirstEntry, entries);
357 CECPacket
*Get_EC_Response_StatRequest(const CECPacket
*request
, CLoggerAccess
&LoggerAccess
)
359 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
361 switch (request
->GetDetailLevel()) {
363 response
->AddTag(CECTag(EC_TAG_STATS_UP_OVERHEAD
, (uint32
)theStats::GetUpOverheadRate()));
364 response
->AddTag(CECTag(EC_TAG_STATS_DOWN_OVERHEAD
, (uint32
)theStats::GetDownOverheadRate()));
365 response
->AddTag(CECTag(EC_TAG_STATS_BANNED_COUNT
, /*(uint32)*/theStats::GetBannedCount()));
366 AddLoggerTag(response
, LoggerAccess
);
369 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED
, (uint32
)theStats::GetUploadRate()));
370 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED
, (uint32
)(theStats::GetDownloadRate())));
371 response
->AddTag(CECTag(EC_TAG_STATS_UL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxUpload()*1024.0)));
372 response
->AddTag(CECTag(EC_TAG_STATS_DL_SPEED_LIMIT
, (uint32
)(thePrefs::GetMaxDownload()*1024.0)));
373 response
->AddTag(CECTag(EC_TAG_STATS_UL_QUEUE_LEN
, /*(uint32)*/theStats::GetWaitingUserCount()));
374 response
->AddTag(CECTag(EC_TAG_STATS_TOTAL_SRC_COUNT
, /*(uint32)*/theStats::GetFoundSources()));
377 uint32 totaluser
= 0, totalfile
= 0;
378 theApp
->serverlist
->GetUserFileStatus( totaluser
, totalfile
);
379 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_USERS
, totaluser
));
380 response
->AddTag(CECTag(EC_TAG_STATS_KAD_USERS
, Kademlia::CKademlia::GetKademliaUsers()));
381 response
->AddTag(CECTag(EC_TAG_STATS_ED2K_FILES
, totalfile
));
382 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FILES
, Kademlia::CKademlia::GetKademliaFiles()));
385 if (Kademlia::CKademlia::IsConnected()) {
386 response
->AddTag(CECTag(EC_TAG_STATS_KAD_FIREWALLED_UDP
, Kademlia::CUDPFirewallTester::IsFirewalledUDP(true)));
387 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_SOURCES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexSource
));
388 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_KEYWORDS
, Kademlia::CKademlia::GetIndexed()->m_totalIndexKeyword
));
389 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_NOTES
, Kademlia::CKademlia::GetIndexed()->m_totalIndexNotes
));
390 response
->AddTag(CECTag(EC_TAG_STATS_KAD_INDEXED_LOAD
, Kademlia::CKademlia::GetIndexed()->m_totalIndexLoad
));
391 response
->AddTag(CECTag(EC_TAG_STATS_KAD_IP_ADRESS
, wxUINT32_SWAP_ALWAYS(Kademlia::CKademlia::GetPrefs()->GetIPAddress())));
392 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_STATUS
, theApp
->clientlist
->GetBuddyStatus()));
394 uint16 BuddyPort
= 0;
395 CUpDownClient
* Buddy
= theApp
->clientlist
->GetBuddy();
397 BuddyIP
= Buddy
->GetIP();
398 BuddyPort
= Buddy
->GetUDPPort();
400 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_IP
, BuddyIP
));
401 response
->AddTag(CECTag(EC_TAG_STATS_BUDDY_PORT
, BuddyPort
));
403 case EC_DETAIL_UPDATE
:
404 case EC_DETAIL_INC_UPDATE
:
411 CECPacket
*Get_EC_Response_GetSharedFiles(const CECPacket
*request
, CKnownFile_Encoder_Map
&encoders
)
413 wxASSERT(request
->GetOpCode() == EC_OP_GET_SHARED_FILES
);
415 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
417 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
419 // request can contain list of queried items
420 CTagSet
<CMD4Hash
, EC_TAG_KNOWNFILE
> queryitems(request
);
422 encoders
.UpdateEncoders(theApp
->sharedfiles
);
424 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
425 CKnownFile
*cur_file
= (CKnownFile
*)theApp
->sharedfiles
->GetFileByIndex(i
);
427 if ( !cur_file
|| (!queryitems
.empty() && !queryitems
.count(cur_file
->GetFileHash())) ) {
431 CEC_SharedFile_Tag
filetag(cur_file
, detail_level
);
432 CKnownFile_Encoder
&enc
= encoders
[cur_file
];
433 if ( detail_level
!= EC_DETAIL_UPDATE
) {
436 enc
.Encode(&filetag
);
437 response
->AddTag(filetag
);
442 CECPacket
*Get_EC_Response_GetSharedFiles(CKnownFile_Encoder_Map
&encoders
, CObjTagMap
&tagmap
)
444 CECPacket
*response
= new CECPacket(EC_OP_SHARED_FILES
);
446 encoders
.UpdateEncoders(theApp
->sharedfiles
);
447 for (uint32 i
= 0; i
< theApp
->sharedfiles
->GetFileCount(); ++i
) {
448 CKnownFile
*cur_file
= (CKnownFile
*)theApp
->sharedfiles
->GetFileByIndex(i
);
451 // Hashes of tags are maintained on "per-object" basis. So, in this mode only
452 // same kind of objects can go into particular query type.
453 // Particulary here it means that files from download queue (aka partfiles)
454 // will not ne shown as shared files. Remote gui can do combine them if wishes
456 if ( !cur_file
|| cur_file
->IsPartFile() ) continue;
458 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
);
459 CEC_SharedFile_Tag
filetag(cur_file
, valuemap
);
460 CKnownFile_Encoder
&enc
= encoders
[cur_file
];
461 enc
.Encode(&filetag
);
463 response
->AddTag(filetag
);
468 CECPacket
*Get_EC_Response_GetWaitQueue(const CECPacket
*request
)
470 wxASSERT(request
->GetOpCode() == EC_OP_GET_WAIT_QUEUE
);
472 CECPacket
*response
= new CECPacket(EC_OP_WAIT_QUEUE
);
474 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
477 // request can contain list of queried items
478 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
480 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetWaitingList();
481 CClientPtrList::const_iterator it
= uploading
.begin();
482 for (; it
!= uploading
.end(); ++it
) {
483 CUpDownClient
* cur_client
= *it
;
485 if ( !cur_client
|| (!queryitems
.empty() && !queryitems
.count(cur_client
->GetUserIDHybrid())) ) {
488 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
);
490 response
->AddTag(cli_tag
);
496 CECPacket
*Get_EC_Response_GetWaitQueue(CObjTagMap
&tagmap
)
498 CECPacket
*response
= new CECPacket(EC_OP_WAIT_QUEUE
);
500 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetWaitingList();
501 CClientPtrList::const_iterator it
= uploading
.begin();
502 for (; it
!= uploading
.end(); ++it
) {
503 CUpDownClient
* cur_client
= *it
;
505 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
);
506 CEC_UpDownClient_Tag
cli_tag(cur_client
, valuemap
);
508 response
->AddTag(cli_tag
);
514 CECPacket
*Get_EC_Response_GetUpQueue(const CECPacket
*request
)
516 wxASSERT(request
->GetOpCode() == EC_OP_GET_ULOAD_QUEUE
);
518 CECPacket
*response
= new CECPacket(EC_OP_ULOAD_QUEUE
);
520 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
523 // request can contain list of queried items
524 CTagSet
<uint32
, EC_TAG_CLIENT
> queryitems(request
);
527 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetUploadingList();
528 CClientPtrList::const_iterator it
= uploading
.begin();
529 for (; it
!= uploading
.end(); ++it
) {
530 CUpDownClient
* cur_client
= *it
;
532 if ( !cur_client
|| (!queryitems
.empty() && !queryitems
.count(cur_client
->GetUserIDHybrid())) ) {
536 CEC_UpDownClient_Tag
cli_tag(cur_client
, detail_level
);
537 response
->AddTag(cli_tag
);
544 CECPacket
*Get_EC_Response_GetUpQueue(CObjTagMap
&tagmap
)
546 CECPacket
*response
= new CECPacket(EC_OP_ULOAD_QUEUE
);
548 const CClientPtrList
& uploading
= theApp
->uploadqueue
->GetUploadingList();
549 CClientPtrList::const_iterator it
= uploading
.begin();
550 for (; it
!= uploading
.end(); ++it
) {
551 CUpDownClient
* cur_client
= *it
;
553 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_client
);
554 CEC_UpDownClient_Tag
cli_tag(cur_client
, valuemap
);
556 response
->AddTag(cli_tag
);
563 CECPacket
*Get_EC_Response_GetDownloadQueue(CPartFile_Encoder_Map
&encoders
, CObjTagMap
&tagmap
)
565 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
567 encoders
.UpdateEncoders(theApp
->downloadqueue
);
568 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
569 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
571 CValueMap
&valuemap
= tagmap
.GetValueMap(cur_file
);
572 CEC_PartFile_Tag
filetag(cur_file
, valuemap
);
573 CPartFile_Encoder
&enc
= encoders
[cur_file
];
574 enc
.Encode(&filetag
);
576 response
->AddTag(filetag
);
581 CECPacket
*Get_EC_Response_GetDownloadQueue(const CECPacket
*request
, CPartFile_Encoder_Map
&encoders
, bool detail
= false)
583 CECPacket
*response
= new CECPacket(EC_OP_DLOAD_QUEUE
);
585 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
587 // request can contain list of queried items
588 CTagSet
<CMD4Hash
, EC_TAG_PARTFILE
> queryitems(request
);
590 encoders
.UpdateEncoders(theApp
->downloadqueue
);
592 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
593 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
595 if ( !queryitems
.empty() && !queryitems
.count(cur_file
->GetFileHash()) ) {
599 CEC_PartFile_Tag
filetag(cur_file
, detail_level
, detail
);
601 CPartFile_Encoder
&enc
= encoders
[cur_file
];
602 if ( detail_level
!= EC_DETAIL_UPDATE
) {
605 enc
.Encode(&filetag
);
607 response
->AddTag(filetag
);
613 CECPacket
*Get_EC_Response_PartFile_Cmd(const CECPacket
*request
)
615 CECPacket
*response
= NULL
;
617 // request can contain multiple files.
618 for (unsigned int i
= 0; i
< request
->GetTagCount(); ++i
) {
619 const CECTag
*hashtag
= request
->GetTagByIndex(i
);
621 wxASSERT(hashtag
->GetTagName() == EC_TAG_PARTFILE
);
623 CMD4Hash hash
= hashtag
->GetMD4Data();
624 CPartFile
*pfile
= theApp
->downloadqueue
->GetFileByID( hash
);
627 AddLogLineM(false,CFormat(_("Remote PartFile command failed: FileHash not found: %s")) % hash
.Encode());
628 response
= new CECPacket(EC_OP_FAILED
);
629 response
->AddTag(CECTag(EC_TAG_STRING
, CFormat(wxString(wxTRANSLATE("FileHash not found: %s"))) % hash
.Encode()));
633 switch (request
->GetOpCode()) {
634 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
635 if ((pfile
->GetStatus(false) == PS_READY
) ||
636 (pfile
->GetStatus(false) == PS_EMPTY
)) {
637 CPartFile::SourceSet::const_iterator it
= pfile
->GetA4AFList().begin();
638 while ( it
!= pfile
->GetA4AFList().end() ) {
639 CUpDownClient
*cur_source
= *it
++;
641 cur_source
->SwapToAnotherFile(true, false, false, pfile
);
645 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
646 pfile
->SetA4AFAuto(!pfile
->IsA4AFAuto());
648 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
649 if ((pfile
->GetStatus(false) == PS_READY
) ||
650 (pfile
->GetStatus(false) == PS_EMPTY
)) {
651 CPartFile::SourceSet::const_iterator it
= pfile
->GetSourceList().begin();
652 while ( it
!= pfile
->GetSourceList().end() ) {
653 CUpDownClient
* cur_source
= *it
++;
655 cur_source
->SwapToAnotherFile(false, false, false, NULL
);
659 case EC_OP_PARTFILE_PAUSE
:
662 case EC_OP_PARTFILE_RESUME
:
664 pfile
->SavePartFile();
666 case EC_OP_PARTFILE_STOP
:
669 case EC_OP_PARTFILE_PRIO_SET
: {
670 uint8 prio
= hashtag
->GetTagByIndexSafe(0)->GetInt();
671 if ( prio
== PR_AUTO
) {
672 pfile
->SetAutoDownPriority(1);
674 pfile
->SetAutoDownPriority(0);
675 pfile
->SetDownPriority(prio
);
679 case EC_OP_PARTFILE_DELETE
:
680 if ( thePrefs::StartNextFile() && (pfile
->GetStatus() != PS_PAUSED
) ) {
681 theApp
->downloadqueue
->StartNextFile(pfile
);
686 case EC_OP_PARTFILE_SET_CAT
:
687 pfile
->SetCategory(hashtag
->GetTagByIndexSafe(0)->GetInt());
691 response
= new CECPacket(EC_OP_FAILED
);
692 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
697 response
= new CECPacket(EC_OP_NOOP
);
702 CECPacket
*Get_EC_Response_Server_Add(const CECPacket
*request
)
704 CECPacket
*response
= NULL
;
706 const CECTag
*srv_tag
= request
->GetTagByIndex(0);
708 wxString full_addr
= srv_tag
->GetTagByName(EC_TAG_SERVER_ADDRESS
)->GetStringData();
709 wxString name
= srv_tag
->GetTagByName(EC_TAG_SERVER_NAME
)->GetStringData();
711 wxString s_ip
= full_addr
.Left(full_addr
.Find(':'));
712 wxString s_port
= full_addr
.Mid(full_addr
.Find(':') + 1);
714 long port
= StrToULong(s_port
);
715 CServer
* toadd
= new CServer(port
, s_ip
);
716 toadd
->SetListName(name
.IsEmpty() ? full_addr
: name
);
718 if ( theApp
->AddServer(toadd
, true) ) {
719 response
= new CECPacket(EC_OP_NOOP
);
721 response
= new CECPacket(EC_OP_FAILED
);
722 response
->AddTag(CECTag(EC_TAG_STRING
, _("Server not added")));
729 CECPacket
*Get_EC_Response_Server(const CECPacket
*request
)
731 CECPacket
*response
= NULL
;
732 const CECTag
*srv_tag
= request
->GetTagByIndex(0);
735 srv
= theApp
->serverlist
->GetServerByIPTCP(srv_tag
->GetIPv4Data().IP(), srv_tag
->GetIPv4Data().m_port
);
736 // server tag passed, but server not found
738 response
= new CECPacket(EC_OP_FAILED
);
739 response
->AddTag(CECTag(EC_TAG_STRING
,
740 CFormat(wxString(wxTRANSLATE("server not found: %s"))) % srv_tag
->GetIPv4Data().StringIP()));
744 switch (request
->GetOpCode()) {
745 case EC_OP_SERVER_DISCONNECT
:
746 theApp
->serverconnect
->Disconnect();
747 response
= new CECPacket(EC_OP_NOOP
);
749 case EC_OP_SERVER_REMOVE
:
751 theApp
->serverlist
->RemoveServer(srv
);
752 response
= new CECPacket(EC_OP_NOOP
);
754 response
= new CECPacket(EC_OP_FAILED
);
755 response
->AddTag(CECTag(EC_TAG_STRING
,
756 wxTRANSLATE("need to define server to be removed")));
759 case EC_OP_SERVER_CONNECT
:
760 if (thePrefs::GetNetworkED2K()) {
762 theApp
->serverconnect
->ConnectToServer(srv
);
763 response
= new CECPacket(EC_OP_NOOP
);
765 theApp
->serverconnect
->ConnectToAnyServer();
766 response
= new CECPacket(EC_OP_NOOP
);
769 response
= new CECPacket(EC_OP_FAILED
);
770 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("eD2k is disabled in preferences.")));
775 response
= new CECPacket(EC_OP_FAILED
);
776 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("OOPS! OpCode processing error!")));
781 CECPacket
*Get_EC_Response_Search_Results(const CECPacket
*request
)
783 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
785 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
787 // request can contain list of queried items
788 CTagSet
<CMD4Hash
, EC_TAG_SEARCHFILE
> queryitems(request
);
790 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
791 CSearchResultList::const_iterator it
= list
.begin();
792 while (it
!= list
.end()) {
793 CSearchFile
* sf
= *it
++;
794 if ( !queryitems
.empty() && !queryitems
.count(sf
->GetFileHash()) ) {
797 response
->AddTag(CEC_SearchFile_Tag(sf
, detail_level
));
802 CECPacket
*Get_EC_Response_Search_Results(CObjTagMap
&tagmap
)
804 CECPacket
*response
= new CECPacket(EC_OP_SEARCH_RESULTS
);
806 const CSearchResultList
& list
= theApp
->searchlist
->GetSearchResults(0xffffffff);
807 CSearchResultList::const_iterator it
= list
.begin();
808 while (it
!= list
.end()) {
809 CSearchFile
* sf
= *it
++;
810 CValueMap
&valuemap
= tagmap
.GetValueMap(sf
);
811 response
->AddTag(CEC_SearchFile_Tag(sf
, valuemap
));
816 CECPacket
*Get_EC_Response_Search_Results_Download(const CECPacket
*request
)
818 CECPacket
*response
= new CECPacket(EC_OP_STRINGS
);
819 for (unsigned int i
= 0;i
< request
->GetTagCount();i
++) {
820 const CECTag
*tag
= request
->GetTagByIndex(i
);
821 CMD4Hash hash
= tag
->GetMD4Data();
822 uint8 category
= tag
->GetTagByIndexSafe(0)->GetInt();
823 theApp
->searchlist
->AddFileToDownloadByHash(hash
, category
);
828 CECPacket
*Get_EC_Response_Search_Stop(const CECPacket
*WXUNUSED(request
))
830 CECPacket
*reply
= new CECPacket(EC_OP_MISC_DATA
);
831 theApp
->searchlist
->StopGlobalSearch();
835 CECPacket
*Get_EC_Response_Search(const CECPacket
*request
)
839 CEC_Search_Tag
*search_request
= (CEC_Search_Tag
*)request
->GetTagByIndex(0);
840 theApp
->searchlist
->RemoveResults(0xffffffff);
842 CSearchList::CSearchParams params
;
843 params
.searchString
= search_request
->SearchText();
844 params
.typeText
= search_request
->SearchFileType();
845 params
.extension
= search_request
->SearchExt();
846 params
.minSize
= search_request
->MinSize();
847 params
.maxSize
= search_request
->MaxSize();
848 params
.availability
= search_request
->Avail();
851 EC_SEARCH_TYPE search_type
= search_request
->SearchType();
852 SearchType core_search_type
= LocalSearch
;
853 switch (search_type
) {
854 case EC_SEARCH_GLOBAL
:
855 core_search_type
= GlobalSearch
;
857 if (core_search_type
!= GlobalSearch
) { // Not a global search obviously
858 core_search_type
= KadSearch
;
860 case EC_SEARCH_LOCAL
: {
861 uint32 search_id
= 0xffffffff;
862 wxString error
= theApp
->searchlist
->StartNewSearch(&search_id
, core_search_type
, params
);
863 if (!error
.IsEmpty()) {
866 response
= wxTRANSLATE("Search in progress. Refetch results in a moment!");
871 response
= wxTRANSLATE("WebSearch from remote interface makes no sense.");
875 CECPacket
*reply
= new CECPacket(EC_OP_FAILED
);
876 // error or search in progress
877 reply
->AddTag(CECTag(EC_TAG_STRING
, response
));
882 CECPacket
*Get_EC_Response_Set_SharedFile_Prio(const CECPacket
*request
)
884 CECPacket
*response
= new CECPacket(EC_OP_NOOP
);
885 for (unsigned int i
= 0;i
< request
->GetTagCount();i
++) {
886 const CECTag
*tag
= request
->GetTagByIndex(i
);
887 CMD4Hash hash
= tag
->GetMD4Data();
888 uint8 prio
= tag
->GetTagByIndexSafe(0)->GetInt();
889 CKnownFile
* cur_file
= theApp
->sharedfiles
->GetFileByID(hash
);
893 if (prio
== PR_AUTO
) {
894 cur_file
->SetAutoUpPriority(1);
895 cur_file
->UpdateAutoUpPriority();
897 cur_file
->SetAutoUpPriority(0);
898 cur_file
->SetUpPriority(prio
);
905 CECPacket
*Get_EC_Response_Kad_Connect(const CECPacket
*request
)
908 if (thePrefs::GetNetworkKademlia()) {
909 response
= new CECPacket(EC_OP_NOOP
);
910 if ( !Kademlia::CKademlia::IsRunning() ) {
911 Kademlia::CKademlia::Start();
912 theApp
->ShowConnectionState();
914 const CECTag
*addrtag
= request
->GetTagByIndex(0);
916 uint32 ip
= addrtag
->GetIPv4Data().IP();
917 uint16 port
= addrtag
->GetIPv4Data().m_port
;
918 Kademlia::CKademlia::Bootstrap(ip
, port
, true);
921 response
= new CECPacket(EC_OP_FAILED
);
922 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Kad is disabled in preferences.")));
928 // init with some default size
929 CPartFile_Encoder::GapBuffer
CPartFile_Encoder::m_gap_buffer(128);
932 CPartFile_Encoder::CPartFile_Encoder(CPartFile
*file
) :
933 m_enc_data(file
->GetPartCount(), file
->GetGapList().size() * 2)
939 CPartFile_Encoder::CPartFile_Encoder(int size
): m_enc_data(size
, 0)
944 CPartFile_Encoder::~CPartFile_Encoder()
949 CPartFile_Encoder::CPartFile_Encoder()
954 CPartFile_Encoder::CPartFile_Encoder(const CPartFile_Encoder
&obj
) : m_enc_data(obj
.m_enc_data
)
959 CPartFile_Encoder
&CPartFile_Encoder::operator=(const CPartFile_Encoder
&obj
)
962 m_enc_data
= obj
.m_enc_data
;
966 void CPartFile_Encoder::Encode(CECTag
*parent
)
968 const CGapList
& gaplist
= m_file
->GetNewGapList();
969 const size_t gap_list_size
= gaplist
.size();
971 if ( m_gap_buffer
.size() < gap_list_size
* 2 ) {
972 m_gap_buffer
.clear();
973 m_gap_buffer
.resize(gap_list_size
* 2);
976 GapBuffer::iterator it
= m_gap_buffer
.begin();
978 for (CGapList::const_iterator curr_pos
= gaplist
.begin(); curr_pos
!= gaplist
.end(); ++curr_pos
) {
979 *it
++ = ENDIAN_HTONLL(curr_pos
.start());
980 *it
++ = ENDIAN_HTONLL(curr_pos
.end());
983 m_enc_data
.m_gap_status
.Realloc(gap_list_size
*2*sizeof(uint64
));
984 int gap_enc_size
= 0;
985 const unsigned char *gap_enc_data
= m_enc_data
.m_gap_status
.Encode((unsigned char *)&m_gap_buffer
[0], gap_enc_size
);
988 const unsigned char *part_enc_data
= m_enc_data
.m_part_status
.Encode(m_file
->m_SrcpartFrequency
, part_enc_size
);
991 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
994 // Put data inside of tag in following order:
995 // [num_of_gaps] [gap_enc_data]
997 unsigned char *tagdata
;
998 CECTag
etag(EC_TAG_PARTFILE_GAP_STATUS
,
999 sizeof(uint32
) + gap_enc_size
, (void **)&tagdata
);
1001 // real number of gaps - so remote size can realloc
1002 RawPokeUInt32( tagdata
, ENDIAN_HTONL( gap_list_size
) );
1003 tagdata
+= sizeof(uint32
);
1004 memcpy(tagdata
, gap_enc_data
, gap_enc_size
);
1006 parent
->AddTag(etag
);
1008 it
= m_gap_buffer
.begin();
1010 const CPartFile::CReqBlockPtrList
& requestedblocks
= m_file
->GetRequestedBlockList();
1011 CPartFile::CReqBlockPtrList::const_iterator curr_pos2
= requestedblocks
.begin();
1013 wxASSERT(m_gap_buffer
.size() >= requestedblocks
.size() * 2);
1014 for ( ; curr_pos2
!= requestedblocks
.end(); ++curr_pos2
) {
1015 Requested_Block_Struct
* block
= *curr_pos2
;
1016 *it
++ = ENDIAN_HTONLL(block
->StartOffset
);
1017 *it
++ = ENDIAN_HTONLL(block
->EndOffset
);
1019 parent
->AddTag(CECTag(EC_TAG_PARTFILE_REQ_STATUS
,
1020 requestedblocks
.size() * 2 * sizeof(uint64
), (void *)&m_gap_buffer
[0]));
1024 CKnownFile_Encoder::CKnownFile_Encoder(CKnownFile
*file
) :
1025 m_enc_data(file
->GetPartCount(), true)
1030 CKnownFile_Encoder::CKnownFile_Encoder()
1035 CKnownFile_Encoder::~CKnownFile_Encoder()
1039 CKnownFile_Encoder::CKnownFile_Encoder(const CKnownFile_Encoder
&obj
) : m_enc_data(obj
.m_enc_data
)
1041 m_file
= obj
.m_file
;
1044 CKnownFile_Encoder
&CKnownFile_Encoder::operator=(const CKnownFile_Encoder
&obj
)
1046 m_file
= obj
.m_file
;
1047 m_enc_data
= obj
.m_enc_data
;
1051 void CKnownFile_Encoder::Encode(CECTag
*parent
)
1054 const unsigned char *part_enc_data
= m_enc_data
.Encode(m_file
->m_AvailPartFrequency
, part_enc_size
);
1056 parent
->AddTag(CECTag(EC_TAG_PARTFILE_PART_STATUS
, part_enc_size
, part_enc_data
));
1059 CECPacket
*GetStatsGraphs(const CECPacket
*request
)
1061 CECPacket
*response
= NULL
;
1063 switch (request
->GetDetailLevel()) {
1065 case EC_DETAIL_FULL
: {
1066 double dTimestamp
= 0.0;
1067 if (request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
) != NULL
) {
1068 dTimestamp
= request
->GetTagByName(EC_TAG_STATSGRAPH_LAST
)->GetDoubleData();
1070 uint16 nScale
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_SCALE
)->GetInt();
1071 uint16 nMaxPoints
= request
->GetTagByNameSafe(EC_TAG_STATSGRAPH_WIDTH
)->GetInt();
1073 unsigned int numPoints
= theApp
->m_statistics
->GetHistoryForWeb(nMaxPoints
, (double)nScale
, &dTimestamp
, &graphData
);
1075 response
= new CECPacket(EC_OP_STATSGRAPHS
);
1076 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_DATA
, 4 * numPoints
* sizeof(uint32
), graphData
));
1077 delete [] graphData
;
1078 response
->AddTag(CECTag(EC_TAG_STATSGRAPH_LAST
, dTimestamp
));
1080 response
= new CECPacket(EC_OP_FAILED
);
1081 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("No points for graph.")));
1085 case EC_DETAIL_INC_UPDATE
:
1086 case EC_DETAIL_UPDATE
:
1089 response
= new CECPacket(EC_OP_FAILED
);
1090 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Your client is not configured for this detail level.")));
1094 response
= new CECPacket(EC_OP_FAILED
);
1101 CECPacket
*CECServerSocket::ProcessRequest2(const CECPacket
*request
,
1102 CPartFile_Encoder_Map
&enc_part_map
, CKnownFile_Encoder_Map
&enc_shared_map
, CObjTagMap
&objmap
)
1109 CECPacket
*response
= NULL
;
1111 switch (request
->GetOpCode()) {
1115 case EC_OP_SHUTDOWN
:
1116 if (!theApp
->IsOnShutDown()) {
1117 response
= new CECPacket(EC_OP_NOOP
);
1118 AddLogLineM(true, _("External Connection: shutdown requested"));
1119 #ifndef AMULE_DAEMON
1122 evt
.SetCanVeto(false);
1123 theApp
->ShutDown(evt
);
1126 theApp
->ExitMainLoop();
1129 response
= new CECPacket(EC_OP_FAILED
);
1130 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already shutting down.")));
1133 case EC_OP_ADD_LINK
:
1134 for(unsigned int i
= 0; i
< request
->GetTagCount();i
++) {
1135 const CECTag
*tag
= request
->GetTagByIndex(i
);
1136 wxString link
= tag
->GetStringData();
1137 int category
= tag
->GetTagByIndexSafe(0)->GetInt();
1138 AddLogLineM(true, CFormat(_("ExternalConn: adding link '%s'.")) % link
);
1139 if ( theApp
->downloadqueue
->AddLink(link
, category
) ) {
1140 response
= new CECPacket(EC_OP_NOOP
);
1142 // Error messages are printed by the add function.
1143 response
= new CECPacket(EC_OP_FAILED
);
1144 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid link or already on list.")));
1151 case EC_OP_STAT_REQ
:
1152 response
= Get_EC_Response_StatRequest(request
, m_LoggerAccess
);
1154 case EC_OP_GET_CONNSTATE
:
1156 response
= new CECPacket(EC_OP_MISC_DATA
);
1158 response
->AddTag(CEC_ConnState_Tag(request
->GetDetailLevel()));
1163 case EC_OP_GET_SHARED_FILES
:
1164 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1165 response
= Get_EC_Response_GetSharedFiles(enc_shared_map
, objmap
);
1167 response
= Get_EC_Response_GetSharedFiles(request
, enc_shared_map
);
1170 case EC_OP_GET_DLOAD_QUEUE
:
1171 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1172 response
= Get_EC_Response_GetDownloadQueue(enc_part_map
, objmap
);
1174 response
= Get_EC_Response_GetDownloadQueue(request
, enc_part_map
);
1177 // transmit source names and comments only if file detail dialog is open
1178 case EC_OP_GET_DLOAD_QUEUE_DETAIL
:
1179 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1180 response
= Get_EC_Response_GetDownloadQueue(enc_part_map
, objmap
);
1182 response
= Get_EC_Response_GetDownloadQueue(request
, enc_part_map
, true);
1185 case EC_OP_GET_ULOAD_QUEUE
:
1186 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1187 response
= Get_EC_Response_GetUpQueue(objmap
);
1189 response
= Get_EC_Response_GetUpQueue(request
);
1192 case EC_OP_GET_WAIT_QUEUE
:
1193 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1194 response
= Get_EC_Response_GetWaitQueue(objmap
);
1196 response
= Get_EC_Response_GetWaitQueue(request
);
1199 case EC_OP_PARTFILE_REMOVE_NO_NEEDED
:
1200 case EC_OP_PARTFILE_REMOVE_FULL_QUEUE
:
1201 case EC_OP_PARTFILE_REMOVE_HIGH_QUEUE
:
1202 case EC_OP_PARTFILE_CLEANUP_SOURCES
:
1203 case EC_OP_PARTFILE_SWAP_A4AF_THIS
:
1204 case EC_OP_PARTFILE_SWAP_A4AF_THIS_AUTO
:
1205 case EC_OP_PARTFILE_SWAP_A4AF_OTHERS
:
1206 case EC_OP_PARTFILE_PAUSE
:
1207 case EC_OP_PARTFILE_RESUME
:
1208 case EC_OP_PARTFILE_STOP
:
1209 case EC_OP_PARTFILE_PRIO_SET
:
1210 case EC_OP_PARTFILE_DELETE
:
1211 case EC_OP_PARTFILE_SET_CAT
:
1212 response
= Get_EC_Response_PartFile_Cmd(request
);
1214 case EC_OP_SHAREDFILES_RELOAD
:
1215 theApp
->sharedfiles
->Reload();
1216 response
= new CECPacket(EC_OP_NOOP
);
1218 case EC_OP_SHARED_SET_PRIO
:
1219 response
= Get_EC_Response_Set_SharedFile_Prio(request
);
1221 case EC_OP_RENAME_FILE
: {
1222 CMD4Hash fileHash
= request
->GetTagByNameSafe(EC_TAG_KNOWNFILE
)->GetMD4Data();
1223 CKnownFile
* file
= theApp
->knownfiles
->FindKnownFileByID(fileHash
);
1224 wxString newName
= request
->GetTagByNameSafe(EC_TAG_PARTFILE_NAME
)->GetStringData();
1226 file
= theApp
->downloadqueue
->GetFileByID(fileHash
);
1229 response
= new CECPacket(EC_OP_FAILED
);
1230 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("File not found.")));
1233 if (newName
.IsEmpty()) {
1234 response
= new CECPacket(EC_OP_FAILED
);
1235 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid file name.")));
1239 if (theApp
->sharedfiles
->RenameFile(file
, CPath(newName
))) {
1240 response
= new CECPacket(EC_OP_NOOP
);
1242 response
= new CECPacket(EC_OP_FAILED
);
1243 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Unable to rename file.")));
1253 case EC_OP_SERVER_ADD
:
1254 response
= Get_EC_Response_Server_Add(request
);
1256 case EC_OP_SERVER_DISCONNECT
:
1257 case EC_OP_SERVER_CONNECT
:
1258 case EC_OP_SERVER_REMOVE
:
1259 response
= Get_EC_Response_Server(request
);
1261 case EC_OP_GET_SERVER_LIST
: {
1262 response
= new CECPacket(EC_OP_SERVER_LIST
);
1263 EC_DETAIL_LEVEL detail_level
= request
->GetDetailLevel();
1264 std::vector
<const CServer
*> servers
= theApp
->serverlist
->CopySnapshot();
1266 std::vector
<const CServer
*>::const_iterator it
= servers
.begin();
1267 it
!= servers
.end();
1270 response
->AddTag(CEC_Server_Tag(*it
, detail_level
));
1274 case EC_OP_SERVER_UPDATE_FROM_URL
: {
1275 wxString url
= request
->GetTagByIndexSafe(0)->GetStringData();
1277 // Save the new url, and update the UI (if not amuled).
1278 Notify_ServersURLChanged(url
);
1279 thePrefs::SetEd2kServersUrl(url
);
1281 theApp
->serverlist
->UpdateServerMetFromURL(url
);
1282 response
= new CECPacket(EC_OP_NOOP
);
1288 case EC_OP_IPFILTER_RELOAD
:
1289 theApp
->ipfilter
->Reload();
1290 response
= new CECPacket(EC_OP_NOOP
);
1295 case EC_OP_SEARCH_START
:
1296 response
= Get_EC_Response_Search(request
);
1299 case EC_OP_SEARCH_STOP
:
1300 response
= Get_EC_Response_Search_Stop(request
);
1303 case EC_OP_SEARCH_RESULTS
:
1304 if ( request
->GetDetailLevel() == EC_DETAIL_INC_UPDATE
) {
1305 response
= Get_EC_Response_Search_Results(objmap
);
1307 response
= Get_EC_Response_Search_Results(request
);
1311 case EC_OP_SEARCH_PROGRESS
:
1312 response
= new CECPacket(EC_OP_SEARCH_PROGRESS
);
1313 response
->AddTag(CECTag(EC_TAG_SEARCH_STATUS
,
1314 theApp
->searchlist
->GetSearchProgress()));
1317 case EC_OP_DOWNLOAD_SEARCH_RESULT
:
1318 response
= Get_EC_Response_Search_Results_Download(request
);
1323 case EC_OP_GET_PREFERENCES
:
1324 response
= new CEC_Prefs_Packet(request
->GetTagByNameSafe(EC_TAG_SELECT_PREFS
)->GetInt(), request
->GetDetailLevel());
1326 case EC_OP_SET_PREFERENCES
:
1327 ((CEC_Prefs_Packet
*)request
)->Apply();
1328 theApp
->glob_prefs
->Save();
1329 if (thePrefs::IsFilteringClients()) {
1330 theApp
->clientlist
->FilterQueues();
1332 if (thePrefs::IsFilteringServers()) {
1333 theApp
->serverlist
->FilterServers();
1335 if (!thePrefs::GetNetworkED2K() && theApp
->IsConnectedED2K()) {
1336 theApp
->DisconnectED2K();
1338 if (!thePrefs::GetNetworkKademlia() && theApp
->IsConnectedKad()) {
1341 response
= new CECPacket(EC_OP_NOOP
);
1344 case EC_OP_CREATE_CATEGORY
:
1345 if ( request
->GetTagCount() == 1 ) {
1346 ((CEC_Category_Tag
*)request
->GetTagByIndex(0))->Create();
1347 Notify_CategoryAdded();
1349 response
= new CECPacket(EC_OP_NOOP
);
1351 case EC_OP_UPDATE_CATEGORY
:
1352 if ( request
->GetTagCount() == 1 ) {
1353 CEC_Category_Tag
*tag
= (CEC_Category_Tag
*)request
->GetTagByIndex(0);
1355 Notify_CategoryUpdate(tag
->GetInt());
1357 response
= new CECPacket(EC_OP_NOOP
);
1359 case EC_OP_DELETE_CATEGORY
:
1360 if ( request
->GetTagCount() == 1 ) {
1361 uint32 cat
= request
->GetTagByIndex(0)->GetInt();
1362 Notify_CategoryDelete(cat
);
1364 response
= new CECPacket(EC_OP_NOOP
);
1370 case EC_OP_ADDLOGLINE
:
1371 AddLogLineM( (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
), request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData() );
1372 response
= new CECPacket(EC_OP_NOOP
);
1374 case EC_OP_ADDDEBUGLOGLINE
:
1375 AddDebugLogLineM( (request
->GetTagByName(EC_TAG_LOG_TO_STATUS
) != NULL
), logGeneral
, request
->GetTagByNameSafe(EC_TAG_STRING
)->GetStringData() );
1376 response
= new CECPacket(EC_OP_NOOP
);
1379 response
= new CECPacket(EC_OP_LOG
);
1380 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetLog(false)));
1382 case EC_OP_GET_DEBUGLOG
:
1383 response
= new CECPacket(EC_OP_DEBUGLOG
);
1384 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetDebugLog(false)));
1386 case EC_OP_RESET_LOG
:
1387 theApp
->GetLog(true);
1388 response
= new CECPacket(EC_OP_NOOP
);
1390 case EC_OP_RESET_DEBUGLOG
:
1391 theApp
->GetDebugLog(true);
1392 response
= new CECPacket(EC_OP_NOOP
);
1394 case EC_OP_GET_LAST_LOG_ENTRY
:
1396 wxString tmp
= theApp
->GetLog(false);
1397 if (tmp
.Last() == '\n') {
1400 response
= new CECPacket(EC_OP_LOG
);
1401 response
->AddTag(CECTag(EC_TAG_STRING
, tmp
.AfterLast('\n')));
1404 case EC_OP_GET_SERVERINFO
:
1405 response
= new CECPacket(EC_OP_SERVERINFO
);
1406 response
->AddTag(CECTag(EC_TAG_STRING
, theApp
->GetServerLog(false)));
1408 case EC_OP_CLEAR_SERVERINFO
:
1409 theApp
->GetServerLog(true);
1410 response
= new CECPacket(EC_OP_NOOP
);
1415 case EC_OP_GET_STATSGRAPHS
:
1416 response
= GetStatsGraphs(request
);
1418 case EC_OP_GET_STATSTREE
: {
1419 theApp
->m_statistics
->UpdateStatsTree();
1420 response
= new CECPacket(EC_OP_STATSTREE
);
1421 CECTag
* tree
= theStats::GetECStatTree(request
->GetTagByNameSafe(EC_TAG_STATTREE_CAPPING
)->GetInt());
1423 response
->AddTag(*tree
);
1426 if (request
->GetDetailLevel() == EC_DETAIL_WEB
) {
1427 response
->AddTag(CECTag(EC_TAG_SERVER_VERSION
, wxT(VERSION
)));
1428 response
->AddTag(CECTag(EC_TAG_USER_NICK
, thePrefs::GetUserNick()));
1436 case EC_OP_KAD_START
:
1437 response
= Get_EC_Response_Kad_Connect(request
);
1439 case EC_OP_KAD_STOP
:
1441 response
= new CECPacket(EC_OP_NOOP
);
1443 case EC_OP_KAD_UPDATE_FROM_URL
: {
1444 wxString url
= request
->GetTagByIndexSafe(0)->GetStringData();
1446 // Save the new url, and update the UI (if not amuled).
1447 Notify_NodesURLChanged(url
);
1448 thePrefs::SetKadNodesUrl(url
);
1450 theApp
->UpdateNotesDat(url
);
1451 response
= new CECPacket(EC_OP_NOOP
);
1454 case EC_OP_KAD_BOOTSTRAP_FROM_IP
:
1455 theApp
->BootstrapKad(request
->GetTagByIndexSafe(0)->GetInt(),
1456 request
->GetTagByIndexSafe(1)->GetInt());
1457 response
= new CECPacket(EC_OP_NOOP
);
1464 if (thePrefs::GetNetworkED2K()) {
1465 response
= new CECPacket(EC_OP_STRINGS
);
1466 if (theApp
->IsConnectedED2K()) {
1467 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to eD2k.")));
1469 theApp
->serverconnect
->ConnectToAnyServer();
1470 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to eD2k...")));
1473 if (thePrefs::GetNetworkKademlia()) {
1475 response
= new CECPacket(EC_OP_STRINGS
);
1477 if (theApp
->IsConnectedKad()) {
1478 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Already connected to Kad.")));
1481 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Connecting to Kad...")));
1485 response
= new CECPacket(EC_OP_FAILED
);
1486 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("All networks are disabled.")));
1489 case EC_OP_DISCONNECT
:
1490 if (theApp
->IsConnected()) {
1491 response
= new CECPacket(EC_OP_STRINGS
);
1492 if (theApp
->IsConnectedED2K()) {
1493 theApp
->serverconnect
->Disconnect();
1494 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from eD2k.")));
1496 if (theApp
->IsConnectedKad()) {
1498 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Disconnected from Kad.")));
1501 response
= new CECPacket(EC_OP_NOOP
);
1506 AddLogLineM(false, wxString::Format(_("External Connection: invalid opcode received: %#x"), request
->GetOpCode()));
1508 response
= new CECPacket(EC_OP_FAILED
);
1509 response
->AddTag(CECTag(EC_TAG_STRING
, wxTRANSLATE("Invalid opcode (wrong protocol version?)")));
1516 * Here notification-based EC. Notification will be sorted by priority for possible throttling.
1520 * Core general status
1522 ECStatusMsgSource::ECStatusMsgSource()
1526 CECPacket
*ECStatusMsgSource::GetNextPacket()
1528 CECPacket
*response
= new CECPacket(EC_OP_STATS
);
1529 response
->AddTag(CEC_ConnState_Tag(EC_DETAIL_UPDATE
));
1536 ECPartFileMsgSource::ECPartFileMsgSource()
1538 PARTFILE_STATUS status
= { true, false, false, false };
1539 for (unsigned int i
= 0; i
< theApp
->downloadqueue
->GetFileCount(); i
++) {
1540 CPartFile
*cur_file
= theApp
->downloadqueue
->GetFileByIndex(i
);
1541 m_dirty_status
[cur_file
->GetFileHash()] = status
;
1545 void ECPartFileMsgSource::SetDirty(CPartFile
*file
)
1547 CMD4Hash filehash
= file
->GetFileHash();
1548 if ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() ) {
1550 // entry already present, meaning "dirty" flag is set
1554 PARTFILE_STATUS status
= { false, false, false, false };
1555 m_dirty_status
[filehash
] = status
;
1558 void ECPartFileMsgSource::SetNew(CPartFile
*file
)
1560 CMD4Hash filehash
= file
->GetFileHash();
1561 wxASSERT ( m_dirty_status
.find(filehash
) == m_dirty_status
.end() );
1562 PARTFILE_STATUS status
= { true, false, false, false };
1563 m_dirty_status
[filehash
] = status
;
1566 void ECPartFileMsgSource::SetCompleted(CPartFile
*file
)
1568 CMD4Hash filehash
= file
->GetFileHash();
1569 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1571 m_dirty_status
[filehash
].m_finished
= true;
1574 void ECPartFileMsgSource::SetRemoved(CPartFile
*file
)
1576 CMD4Hash filehash
= file
->GetFileHash();
1577 wxASSERT ( m_dirty_status
.find(filehash
) != m_dirty_status
.end() );
1579 m_dirty_status
[filehash
].m_removed
= true;
1582 CECPacket
*ECPartFileMsgSource::GetNextPacket()
1584 if ( m_dirty_status
.empty() ) {
1587 std::map
<CMD4Hash
, PARTFILE_STATUS
>::iterator it
= m_dirty_status
.begin();
1588 CMD4Hash filehash
= it
->first
;
1590 CPartFile
*partfile
= theApp
->downloadqueue
->GetFileByID(filehash
);
1592 CECPacket
*packet
= new CECPacket(EC_OP_DLOAD_QUEUE
);
1593 CEC_PartFile_Tag
tag(partfile
, EC_DETAIL_UPDATE
);
1594 packet
->AddTag(tag
);
1596 m_dirty_status
.erase(it
);
1602 * Notification about search status
1604 ECSearchMsgSource::ECSearchMsgSource()
1608 CECPacket
*ECSearchMsgSource::GetNextPacket()
1614 * Notification about uploading clients
1616 CECPacket
*ECClientMsgSource::GetNextPacket()
1622 // Notification iface per-client
1624 ECNotifier::ECNotifier()
1628 CECPacket
*ECNotifier::GetNextPacket(ECUpdateMsgSource
*msg_source_array
[])
1630 CECPacket
*packet
= 0;
1632 // priority 0 is highest
1634 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
1635 if ( (packet
= msg_source_array
[i
]->GetNextPacket()) != 0 ) {
1642 CECPacket
*ECNotifier::GetNextPacket(CECServerSocket
*sock
)
1644 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
1646 // OnOutput is called for a first time before
1647 // socket is registered
1649 if ( !notifier_array
) {
1652 CECPacket
*packet
= GetNextPacket(notifier_array
);
1657 // Interface to notification macros
1659 void ECNotifier::DownloadFile_SetDirty(CPartFile
*file
)
1661 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1662 i
!= m_msg_source
.end(); i
++) {
1663 ECUpdateMsgSource
**notifier_array
= i
->second
;
1664 ((ECPartFileMsgSource
*)notifier_array
[EC_PARTFILE
])->SetDirty(file
);
1666 NextPacketToSocket();
1669 void ECNotifier::DownloadFile_RemoveFile(CPartFile
*file
)
1671 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1672 i
!= m_msg_source
.end(); i
++) {
1673 ECUpdateMsgSource
**notifier_array
= i
->second
;
1674 ((ECPartFileMsgSource
*)notifier_array
[EC_PARTFILE
])->SetRemoved(file
);
1678 void ECNotifier::DownloadFile_RemoveSource(CPartFile
*)
1680 // per-partfile source list is not supported (yet), and IMHO quite useless
1683 void ECNotifier::DownloadFile_AddFile(CPartFile
*file
)
1685 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1686 i
!= m_msg_source
.end(); i
++) {
1687 ECUpdateMsgSource
**notifier_array
= i
->second
;
1688 ((ECPartFileMsgSource
*)notifier_array
[EC_PARTFILE
])->SetNew(file
);
1692 void ECNotifier::DownloadFile_AddSource(CPartFile
*)
1694 // per-partfile source list is not supported (yet), and IMHO quite useless
1697 void ECNotifier::Add_EC_Client(CECServerSocket
*sock
)
1699 ECUpdateMsgSource
**notifier_array
= new ECUpdateMsgSource
*[EC_STATUS_LAST_PRIO
];
1700 notifier_array
[EC_STATUS
] = new ECStatusMsgSource();
1701 notifier_array
[EC_SEARCH
] = new ECSearchMsgSource();
1702 notifier_array
[EC_PARTFILE
] = new ECPartFileMsgSource();
1703 notifier_array
[EC_CLIENT
] = new ECClientMsgSource();
1705 m_msg_source
[sock
] = notifier_array
;
1708 void ECNotifier::Remove_EC_Client(CECServerSocket
*sock
)
1710 ECUpdateMsgSource
**notifier_array
= m_msg_source
[sock
];
1711 m_msg_source
.erase(sock
);
1713 for(int i
= 0; i
< EC_STATUS_LAST_PRIO
; i
++) {
1714 delete notifier_array
[i
];
1716 delete [] notifier_array
;
1719 void ECNotifier::NextPacketToSocket()
1721 for(std::map
<CECServerSocket
*, ECUpdateMsgSource
**>::iterator i
= m_msg_source
.begin();
1722 i
!= m_msg_source
.end(); i
++) {
1723 CECServerSocket
*sock
= i
->first
;
1724 if ( sock
->HaveNotificationSupport() && !sock
->DataPending() ) {
1725 ECUpdateMsgSource
**notifier_array
= i
->second
;
1726 CECPacket
*packet
= GetNextPacket(notifier_array
);
1727 sock
->SendPacket(packet
);
1732 // File_checked_for_headers