-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathamule-remote-gui.cpp
More file actions
2769 lines (2272 loc) · 78.6 KB
/
Copy pathamule-remote-gui.cpp
File metadata and controls
2769 lines (2272 loc) · 78.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// This file is part of the aMule Project.
//
// Copyright (c) 2003-2026 aMule Team ( https://amule-org.github.io )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//
#include <wx/ipc.h>
#include <wx/cmdline.h> // Needed for wxCmdLineParser
#include <wx/config.h> // Do_not_auto_remove (win32)
#include <wx/fileconf.h> // Needed for wxFileConfig
#include <wx/socket.h> // Needed for wxSocketBase
#if defined(__WXGTK__) && !defined(__APPLE__)
#include <glib.h> // g_set_prgname() — wl_app_id / WM_CLASS binding
#endif
#include <common/Format.h>
#include <common/StringFunctions.h>
#include <common/MD5Sum.h>
#include <include/common/EventIDs.h>
#include "amule.h" // Interface declarations.
#include "CamuleArtProvider.h" // Needed for wxArtProvider::Push() in OnInit
#include "amuleDlg.h" // Needed for CamuleDlg
#include "ClientCredits.h"
#include "SourceListCtrl.h"
#include "ChatWnd.h"
#include "DataToText.h" // Needed for GetSoftName()
#include "DownloadListCtrl.h" // Needed for CDownloadListCtrl
#include "Friend.h"
#include "GetTickCount.h" // Needed for GetTickCount64
#include "GuiEvents.h"
#ifdef ENABLE_IP2COUNTRY
#include "IP2Country.h" // Needed for IP2Country
#endif
#include "InternalEvents.h" // Needed for wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
#include "Logger.h"
#include "muuli_wdr.h" // Needed for IDs
#include "PartFile.h" // Needed for CPartFile
#include "SearchDlg.h" // Needed for CSearchDlg
#include "Server.h" // Needed for GetListName
#include "ServerWnd.h" // Needed for CServerWnd
#include "SharedFilesCtrl.h" // Needed for CSharedFilesCtrl
#include "SharedFilesWnd.h" // Needed for CSharedFilesWnd
#include "TransferWnd.h" // Needed for CTransferWnd
#include "UpDownClientEC.h" // Needed for CUpDownClient
#include "ServerListCtrl.h" // Needed for CServerListCtrl
#include "ScopedPtr.h"
#include "StatisticsDlg.h" // Needed for CStatisticsDlg
#include "KadDlg.h" // Needed for CKadDlg::UpdateGraph
#include "ArchSpecific.h" // Needed for ENDIAN_NTOHL
CEConnectDlg::CEConnectDlg()
:
wxDialog(theApp->amuledlg, -1, _("Connect to remote amule"), wxDefaultPosition)
{
CoreConnect(this, true);
wxString pref_host, pref_port;
// Use the literal loopback address rather than "localhost":
// on Windows, "localhost" lookups can fail intermittently
// (IPv4 vs IPv6 stack ordering, hosts-file shape, ...).
// 127.0.0.1 is portable across every supported OS. Same default
// as amulecmd / amuleweb (CaMuleExternalConnector). (#822)
wxConfig::Get()->Read("/EC/Host", &pref_host, "127.0.0.1");
wxConfig::Get()->Read("/EC/Port", &pref_port, "4712");
wxConfig::Get()->Read("/EC/Password", &pwd_hash);
long pref_force_zlib;
wxConfig::Get()->Read("/EC/ForceZLIB", &pref_force_zlib, 0);
CastChild(ID_REMOTE_HOST, wxTextCtrl)->SetValue(pref_host);
CastChild(ID_REMOTE_PORT, wxTextCtrl)->SetValue(pref_port);
CastChild(ID_EC_PASSWD, wxTextCtrl)->SetValue(pwd_hash);
CastChild(ID_EC_FORCE_ZLIB, wxCheckBox)->SetValue(pref_force_zlib != 0);
CentreOnParent();
}
wxString CEConnectDlg::PassHash()
{
return pwd_hash;
}
wxBEGIN_EVENT_TABLE(CEConnectDlg, wxDialog)
EVT_BUTTON(wxID_OK, CEConnectDlg::OnOK)
wxEND_EVENT_TABLE()
void CEConnectDlg::OnOK(wxCommandEvent& evt)
{
wxString s_port = CastChild(ID_REMOTE_PORT, wxTextCtrl)->GetValue();
port = StrToLong(s_port);
host = CastChild(ID_REMOTE_HOST, wxTextCtrl)->GetValue();
passwd = CastChild(ID_EC_PASSWD, wxTextCtrl)->GetValue();
if (passwd != pwd_hash) {
pwd_hash = MD5Sum(passwd).GetHash();
}
m_save_user_pass = CastChild(ID_EC_SAVE, wxCheckBox)->IsChecked();
m_force_zlib = CastChild(ID_EC_FORCE_ZLIB, wxCheckBox)->IsChecked();
evt.Skip();
}
wxDEFINE_EVENT(wxEVT_EC_INIT_DONE, wxEvent);
wxBEGIN_EVENT_TABLE(CamuleRemoteGuiApp, wxApp)
// Core timer
EVT_TIMER(ID_CORE_TIMER_EVENT, CamuleRemoteGuiApp::OnPollTimer)
// Watchdog on the initial EC connect attempt
EVT_TIMER(ID_REMOTE_CONNECT_TIMEOUT_TIMER, CamuleRemoteGuiApp::OnConnectTimeout)
EVT_CUSTOM(wxEVT_EC_CONNECTION, -1, CamuleRemoteGuiApp::OnECConnection)
EVT_CUSTOM(wxEVT_EC_INIT_DONE, -1, CamuleRemoteGuiApp::OnECInitDone)
EVT_MULE_NOTIFY(CamuleRemoteGuiApp::OnNotifyEvent)
#ifdef ENABLE_IP2COUNTRY
// HTTPDownload finished
EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD, -1, CamuleRemoteGuiApp::OnFinishedHTTPDownload)
#endif
wxEND_EVENT_TABLE()
IMPLEMENT_APP(CamuleRemoteGuiApp)
int CamuleRemoteGuiApp::OnExit()
{
StopTickTimer();
wxSocketBase::Shutdown(); // needed because we also called Initialize() manually
return wxApp::OnExit();
}
#if wxUSE_ON_FATAL_EXCEPTION
// Gracefully handle fatal exceptions and print backtrace if possible.
// Mirrors CamuleApp::OnFatalException (amule.cpp) -- without this
// override amulegui crashes produce no symbolicated amule frames,
// which makes diagnosing GTK-callback-into-stale-widget bugs like
// #692 a guessing game.
void CamuleRemoteGuiApp::OnFatalException()
{
/* Print the backtrace */
wxString msg;
msg << "\n--------------------------------------------------------------------------------\n"
<< "A fatal error has occurred and amulegui has crashed.\n"
<< "Please assist us in fixing this problem by reporting the backtrace below as a\n"
<< "GitHub issue, including as much information as possible regarding the\n"
<< "circumstances of this crash. Issue tracker:\n"
<< " https://github.com/amule-org/amule/issues\n"
<< "If possible, please try to generate a real backtrace of this crash:\n"
<< " https://amule-org.github.io/docs/contributing/bug-report\n\n"
<< "----------------------------=| BACKTRACE FOLLOWS: |=----------------------------\n"
<< "Current version is: " << FullMuleVersion
<< "\nRunning on: " << OSDescription
<< "\n\n"
<< get_backtrace(1) // 1 == skip this function.
<< "\n--------------------------------------------------------------------------------\n";
theLogger.EmergencyLog(msg, true);
}
#endif
void CamuleRemoteGuiApp::OnPollTimer(wxTimerEvent&)
{
static int request_step = 0;
static uint32 msPrevStats = 0;
if (m_connect->RequestFifoFull()) {
return;
}
switch (request_step) {
case 0:
// We used to update the connection state here, but that's done with the stats in the next step now.
request_step++;
break;
case 1: {
CECPacket stats_req(EC_OP_STAT_REQ, EC_DETAIL_INC_UPDATE);
m_connect->SendRequest(&m_stats_updater, &stats_req);
request_step++;
break;
}
case 2:
if (amuledlg->m_sharedfileswnd->IsShown()
|| amuledlg->m_chatwnd->IsShown()
|| amuledlg->m_serverwnd->IsShown()) {
// update downloads, shared files and servers
knownfiles->DoRequery(EC_OP_GET_UPDATE, EC_TAG_KNOWNFILE);
} else if (amuledlg->m_transferwnd->IsShown()) {
// update both downloads and shared files
knownfiles->DoRequery(EC_OP_GET_UPDATE, EC_TAG_KNOWNFILE);
} else if (amuledlg->m_searchwnd->IsShown()) {
if (searchlist->m_curr_search != -1) {
searchlist->DoRequery(EC_OP_SEARCH_RESULTS, EC_TAG_SEARCHFILE);
}
} else if (amuledlg->m_statisticswnd->IsShown()) {
int sStatsUpdate = thePrefs::GetStatsInterval();
uint32 msCur = theStats::GetUptimeMillis();
if ((sStatsUpdate > 0) && ((int)(msCur - msPrevStats) > sStatsUpdate*1000)) {
msPrevStats = msCur;
stattree->DoRequery();
}
// Pull graph history every poll cycle while the dialog is
// visible. The handler asks only for points newer than the
// last timestamp the daemon reported, so the EC pipe carries
// just the delta even on a 1 Hz timer.
statgraphs->DoRequery();
}
// Back to the roots
request_step = 0;
break;
default:
wxFAIL;
request_step = 0;
}
// Check for new links once per second.
static uint64 lastED2KLinkCheck = 0;
uint64 now = GetTickCount64();
if (now - lastED2KLinkCheck >= 1000) {
AddLinksFromFile();
lastED2KLinkCheck = now;
}
}
void CamuleRemoteGuiApp::OnFinishedHTTPDownload(CMuleInternalEvent& event)
{
if (event.GetInt() == HTTP_GeoIP) {
amuledlg->IP2CountryDownloadFinished(event.GetExtraLong());
// If we updated, the dialog is already up. Redraw it to show the flags.
amuledlg->Refresh();
}
}
void CamuleRemoteGuiApp::ShutDown(wxCloseEvent &WXUNUSED(evt))
{
// Stop the Core Timer
delete poll_timer;
poll_timer = NULL;
delete connect_timeout_timer;
connect_timeout_timer = NULL;
m_AsioService->Stop();
delete m_AsioService;
m_AsioService = NULL;
// Destroy the EC socket
m_connect->Destroy();
m_connect = NULL;
//
if (amuledlg) {
amuledlg->DlgShutDown();
amuledlg->Destroy();
amuledlg = NULL;
}
delete m_allUploadingKnownFile;
delete stattree;
}
bool CamuleRemoteGuiApp::OnInit()
{
StartTickTimer();
amuledlg = NULL;
connect_timeout_timer = NULL;
// ShutDown() unconditionally deletes these, but Startup() — where they
// are allocated — only runs after a successful EC connect. Null them so
// a connect-timeout teardown doesn't delete an indeterminate pointer.
stattree = NULL;
m_allUploadingKnownFile = NULL;
#if defined(__WXGTK__) && !defined(__APPLE__)
// Set the GTK program name to the canonical app id. On Wayland,
// GTK derives wl_app_id (xdg_toplevel.set_app_id) from
// g_get_prgname(); compositors match wl_app_id against the
// .desktop filename to bind windows to launcher icons. Without
// this the binding falls back to argv[0], which differs across
// packaging formats (AppImage's argv[0] is "aMuleGUI", distro
// installs use "amulegui", Flatpak renames the .desktop entirely).
// On X11 the same value also feeds into WM_CLASS, matching
// StartupWMClass=org.amule.aMule.gui in the .desktop file. Must run
// before any GTK window is created — same fix the monolithic amule
// has in CamuleApp::OnInit; amulegui shipped without it, so on
// GNOME / wlroots the taskbar icon never bound to the launcher
// and showed the generic fallback. (#562 follow-up.)
// Skipped on macOS even under wxGTK (MacPorts): no Wayland or
// .desktop binding exists, and app identity is set via Info.plist
// in the .app bundle. Dropping the call lets that build skip the
// glib2 dep entirely (#641).
g_set_prgname("org.amule.aMule.gui");
#endif
// Register the embedded-PNG art provider before any UI work.
// wxArtProvider::Push takes ownership of the pointer; wx tears
// the providers down at app exit.
wxArtProvider::Push(new CamuleArtProvider());
// Get theApp
theApp = &wxGetApp();
// Handle uncaught exceptions
InstallMuleExceptionHandler();
// Parse cmdline arguments.
if (!InitCommon(AMULE_APP_BASE::argc, AMULE_APP_BASE::argv)) {
return false;
}
// Initialize wx sockets (needed for http download in background with Asio sockets)
wxSocketBase::Initialize();
// Create the polling timer
poll_timer = new wxTimer(this,ID_CORE_TIMER_EVENT);
if (!poll_timer) {
AddLogLineCS(_("Fatal Error: Failed to create Poll Timer"));
OnExit();
}
m_connect = new CRemoteConnect(this);
m_AsioService = new CAsioService;
glob_prefs = new CPreferencesRem(m_connect);
long enableZLIB;
wxConfig::Get()->Read("/EC/ZLIB", &enableZLIB, 1);
m_connect->SetCapabilities(enableZLIB != 0, true, false); // ZLIB, UTF8 numbers, notification
// The ForceZLIB override is read from the connection dialog
// (see ShowConnectionDialog) so the user's checkbox choice in this
// session overrides the persisted /EC/ForceZLIB value.
InitCustomLanguages();
InitLocale(m_locale, StrLang2wx(thePrefs::GetLanguageID()));
if (ShowConnectionDialog()) {
// The watchdog timer is armed inside ShowConnectionDialog right
// before each ConnectToCore call — the retry loop re-arms it on
// every attempt, so OnInit doesn't need to touch it here.
AddLogLineNS(_("Going to event loop..."));
return true;
}
// User cancelled (or ShowConnectionDialog failed before reaching the
// connect step). Tear down the partial init so the Asio thread pool,
// poll timer and remote-connect socket don't leak — wx will never
// call ShutDown() / OnExit() because the main loop isn't entered when
// OnInit() returns false, so we have to unwind manually here. Without
// this, wx reports "4 threads were not terminated by the application".
if (m_AsioService) {
m_AsioService->Stop();
delete m_AsioService;
m_AsioService = NULL;
}
if (m_connect) {
m_connect->Destroy();
m_connect = NULL;
}
if (poll_timer) {
delete poll_timer;
poll_timer = NULL;
}
return false;
}
bool CamuleRemoteGuiApp::CryptoAvailable() const
{
return thePrefs::IsSecureIdentEnabled(); // good enough
}
bool CamuleRemoteGuiApp::ShowConnectionDialog()
{
// The dialog is kept alive across retry attempts so the values the
// user typed (host / port / password / Force-ZLIB) survive a wrong
// guess — they only need to fix the field that was wrong instead of
// re-typing everything. Destroyed in Startup() on success or below
// when the user cancels.
if (!dialog) {
dialog = new CEConnectDlg;
}
while (true) {
if (m_skipConnectionDialog) {
wxCommandEvent evt;
dialog->OnOK(evt);
// --skip is a one-shot: on retry the user must see the
// dialog so they can correct the bad values.
m_skipConnectionDialog = false;
} else if (dialog->ShowModal() != wxID_OK) {
dialog->Destroy();
dialog = NULL;
return false;
}
AddLogLineNS(_("Connecting..."));
// Watchdog on the EC connect. When the host is unreachable the
// TCP SYN can silently time out over several minutes while the
// main loop is running with no visible window, which the OS
// reports as "not responding". Fire a shorter timeout so we
// can show an error and re-prompt instead. Re-armed on every
// retry attempt so the user gets the same 15s budget each time.
delete connect_timeout_timer;
connect_timeout_timer = new wxTimer(this, ID_REMOTE_CONNECT_TIMEOUT_TIMER);
connect_timeout_timer->StartOnce(15000);
// Apply the dialog's Force-ZLIB checkbox state to the EC client
// before each ConnectToCore attempt (re-applied per retry so
// the user can toggle it between attempts if they need to).
m_connect->SetForceZlib(dialog->ForceZlib());
if (m_connect->ConnectToCore(dialog->Host(), dialog->Port(),
dialog->Login(), dialog->PassHash(),
"amule-remote", "0x0001")) {
// Sync part succeeded; async OnECConnection will
// resolve the auth outcome.
return true;
}
// Sync failure (DNS / immediate connect-refused). The async
// path won't fire — cancel the watchdog ourselves, show the
// error, recreate the EC client so its half-baked socket
// state is gone, and loop back to the dialog.
connect_timeout_timer->Stop();
delete connect_timeout_timer;
connect_timeout_timer = NULL;
wxMessageBox(_("Connection failed. Please check the host, port, and password."),
_("ERROR"), wxOK | wxICON_ERROR);
ResetEcConnect();
}
}
void CamuleRemoteGuiApp::ResetEcConnect()
{
// Tear down the busted EC client and recreate a fresh one. The
// CRemoteConnect's socket / auth state isn't safe to reuse after
// a failed handshake. glob_prefs holds a reference to m_connect
// so it's reborn alongside. Both objects are only fully wired
// into the rest of the app by Startup(), which doesn't run until
// a successful connect — recreating them here is safe.
delete glob_prefs;
glob_prefs = NULL;
if (m_connect) {
m_connect->Destroy();
m_connect = NULL;
}
m_connect = new CRemoteConnect(this);
glob_prefs = new CPreferencesRem(m_connect);
long enableZLIB;
wxConfig::Get()->Read("/EC/ZLIB", &enableZLIB, 1);
m_connect->SetCapabilities(enableZLIB != 0, true, false);
}
void CamuleRemoteGuiApp::OnECConnection(wxEvent& event) {
// Connect attempt resolved one way or the other — kill the watchdog.
if (connect_timeout_timer) {
connect_timeout_timer->Stop();
delete connect_timeout_timer;
connect_timeout_timer = NULL;
}
wxECSocketEvent& evt = *((wxECSocketEvent*)&event);
AddLogLineNS(_("Remote GUI EC event handler"));
wxString reply = evt.GetServerReply();
AddLogLineC(reply);
if (evt.GetResult() == true) {
// Connected - go to next init step
glob_prefs->LoadRemote();
} else if (dialog) {
// Connect failed during the initial attempt or a previous
// retry (dialog is still alive — it's only destroyed in
// Startup() after a successful connect). Show the error,
// reset the EC client, and reopen the dialog with the
// previous values still in place so the user can fix the
// wrong field and try again. If the user cancels the retry,
// then we shut down.
wxMessageBox(
(CFormat(_("Connection Failed. Unable to connect to %s:%d\n")) % dialog->Host() % dialog->Port()) + reply,
_("ERROR"), wxOK | wxICON_ERROR);
ResetEcConnect();
if (!ShowConnectionDialog()) {
AddLogLineNS(_("Going down"));
wxCloseEvent ev;
ShutDown(ev);
ExitMainLoop();
}
} else {
// Server disconnected after Startup() already ran — the
// dialog is gone, the rest of the app is wired up, and we
// have no clean path back. Tell the user and shut down.
AddLogLineNS(_("Going down"));
wxMessageBox(_("Connection closed - aMule has terminated probably."), _("ERROR"), wxOK);
wxCloseEvent ev;
ShutDown(ev);
ExitMainLoop();
}
}
void CamuleRemoteGuiApp::OnConnectTimeout(wxTimerEvent&)
{
delete connect_timeout_timer;
connect_timeout_timer = NULL;
wxString host = dialog ? dialog->Host() : wxString();
long port = dialog ? dialog->Port() : 0;
wxMessageBox(
CFormat(_("Connection timed out. Unable to reach %s:%d within the allotted time.\nPlease check the host, port and that aMule is running with External Connections enabled."))
% host % port,
_("ERROR"), wxOK | wxICON_ERROR);
// Reset the EC client and reopen the dialog so the user can
// correct the host / port / etc. If they cancel, then quit.
ResetEcConnect();
if (!ShowConnectionDialog()) {
wxCloseEvent ev;
ShutDown(ev);
ExitMainLoop();
}
}
void CamuleRemoteGuiApp::OnECInitDone(wxEvent& )
{
Startup();
}
void CamuleRemoteGuiApp::OnNotifyEvent(CMuleGUIEvent& evt)
{
evt.Notify();
}
void CamuleRemoteGuiApp::Startup() {
if (dialog->SaveUserPass()) {
wxConfig::Get()->Write("/EC/Host", dialog->Host());
wxConfig::Get()->Write("/EC/Port", dialog->Port());
wxConfig::Get()->Write("/EC/Password", dialog->PassHash());
wxConfig::Get()->Write("/EC/ForceZLIB", dialog->ForceZlib() ? 1l : 0l);
}
dialog->Destroy();
dialog = NULL;
m_ConnState = 0;
m_clientID = 0;
serverconnect = new CServerConnectRem(m_connect);
m_statistics = new CStatistics(*m_connect);
stattree = new CStatTreeRem(m_connect);
statgraphs = new CStatGraphRem(m_connect);
clientlist = new CUpDownClientListRem(m_connect);
searchlist = new CSearchListRem(m_connect);
serverlist = new CServerListRem(m_connect);
friendlist = new CFriendListRem(m_connect);
sharedfiles = new CSharedFilesRem(m_connect);
knownfiles = new CKnownFilesRem(m_connect);
downloadqueue = new CDownQueueRem(m_connect);
ipfilter = new CIPFilterRem(m_connect);
m_allUploadingKnownFile = new CKnownFile;
// Create main dialog
InitGui(m_geometryEnabled, m_geometryString);
// Forward wxLog events to CLogger
wxLog::SetActiveTarget(new CLoggerTarget);
knownfiles->DoRequery(EC_OP_GET_UPDATE, EC_TAG_KNOWNFILE);
// Start the Poll Timer
poll_timer->Start(1000);
amuledlg->StartGuiTimer();
// Now activate GeoIP, so that the download dialog doesn't get destroyed immediately
#ifdef ENABLE_IP2COUNTRY
if (thePrefs::IsGeoIPEnabled()) {
amuledlg->m_IP2Country->Enable();
}
#endif
}
int CamuleRemoteGuiApp::ShowAlert(wxString msg, wxString title, int flags)
{
return CamuleGuiBase::ShowAlert(msg, title, flags);
}
void CamuleRemoteGuiApp::AddRemoteLogLine(const wxString& line)
{
amuledlg->AddLogLine(line);
}
int CamuleRemoteGuiApp::InitGui(bool geometry_enabled, wxString &geom_string)
{
CamuleGuiBase::InitGui(geometry_enabled, geom_string);
SetTopWindow(amuledlg);
AddLogLineN(_("Ready")); // The first log line after the window is up triggers output of all the ones before
return 0;
}
bool CamuleRemoteGuiApp::CopyTextToClipboard(wxString strText)
{
return CamuleGuiBase::CopyTextToClipboard(strText);
}
uint32 CamuleRemoteGuiApp::GetPublicIP()
{
return 0;
}
wxString CamuleRemoteGuiApp::GetLog(bool reset)
{
if (reset) {
amuledlg->ResetLog(ID_LOGVIEW);
CECPacket req(EC_OP_RESET_LOG);
m_connect->SendPacket(&req);
}
return "";
}
wxString CamuleRemoteGuiApp::GetServerLog(bool)
{
return "";
}
bool CamuleRemoteGuiApp::AddServer(CServer * server, bool)
{
CECPacket req(EC_OP_SERVER_ADD);
req.AddTag(CECTag(EC_TAG_SERVER_ADDRESS, CFormat("%s:%d") % server->GetAddress() % server->GetPort()));
req.AddTag(CECTag(EC_TAG_SERVER_NAME, server->GetListName()));
m_connect->SendPacket(&req);
return true;
}
bool CamuleRemoteGuiApp::IsFirewalled() const
{
if (IsConnectedED2K() && !serverconnect->IsLowID()) {
return false;
}
return IsFirewalledKad();
}
bool CamuleRemoteGuiApp::IsConnectedED2K() const {
return serverconnect && serverconnect->IsConnected();
}
void CamuleRemoteGuiApp::StartKad() {
m_connect->StartKad();
}
void CamuleRemoteGuiApp::StopKad() {
m_connect->StopKad();
}
void CamuleRemoteGuiApp::BootstrapKad(uint32 ip, uint16 port)
{
CECPacket req(EC_OP_KAD_BOOTSTRAP_FROM_IP);
req.AddTag(CECTag(EC_TAG_BOOTSTRAP_IP, ip));
req.AddTag(CECTag(EC_TAG_BOOTSTRAP_PORT, port));
m_connect->SendPacket(&req);
}
void CamuleRemoteGuiApp::UpdateNotesDat(const wxString& url)
{
CECPacket req(EC_OP_KAD_UPDATE_FROM_URL);
req.AddTag(CECTag(EC_TAG_KADEMLIA_UPDATE_URL, url));
m_connect->SendPacket(&req);
}
void CamuleRemoteGuiApp::DisconnectED2K() {
if (IsConnectedED2K()) {
m_connect->DisconnectED2K();
}
}
uint32 CamuleRemoteGuiApp::GetED2KID() const
{
return serverconnect ? serverconnect->GetClientID() : 0;
}
uint32 CamuleRemoteGuiApp::GetID() const
{
return m_clientID;
}
void CamuleRemoteGuiApp::ShowUserCount() {
wxString buffer;
static const wxString s_singlenetstatusformat = _("Users: %s | Files: %s");
static const wxString s_bothnetstatusformat = _("Users: E: %s K: %s | Files: E: %s K: %s");
if (thePrefs::GetNetworkED2K() && thePrefs::GetNetworkKademlia()) {
buffer = CFormat(s_bothnetstatusformat) % CastItoIShort(theStats::GetED2KUsers()) % CastItoIShort(theStats::GetKadUsers()) % CastItoIShort(theStats::GetED2KFiles()) % CastItoIShort(theStats::GetKadFiles());
} else if (thePrefs::GetNetworkED2K()) {
buffer = CFormat(s_singlenetstatusformat) % CastItoIShort(theStats::GetED2KUsers()) % CastItoIShort(theStats::GetED2KFiles());
} else if (thePrefs::GetNetworkKademlia()) {
buffer = CFormat(s_singlenetstatusformat) % CastItoIShort(theStats::GetKadUsers()) % CastItoIShort(theStats::GetKadFiles());
} else {
buffer = _("No networks selected");
}
Notify_ShowUserCount(buffer);
}
/*
* Preferences: holds both local and remote settings.
*
* First, everything is loaded from local config file. Later, settings
* that are relevant on remote side only are loaded thru EC
*/
CPreferencesRem::CPreferencesRem(CRemoteConnect *conn)
{
m_conn = conn;
//
// Settings queried from remote side
//
m_exchange_send_selected_prefs =
EC_PREFS_GENERAL |
EC_PREFS_CONNECTIONS |
EC_PREFS_MESSAGEFILTER |
EC_PREFS_ONLINESIG |
EC_PREFS_SERVERS |
EC_PREFS_FILES |
EC_PREFS_DIRECTORIES |
EC_PREFS_SECURITY |
EC_PREFS_CORETWEAKS |
EC_PREFS_REMOTECONTROLS |
EC_PREFS_KADEMLIA;
m_exchange_recv_selected_prefs =
m_exchange_send_selected_prefs |
EC_PREFS_CATEGORIES;
}
void CPreferencesRem::HandlePacket(const CECPacket *packet)
{
static_cast<const CEC_Prefs_Packet *>(packet)->Apply();
const CECTag *cat_tags = packet->GetTagByName(EC_TAG_PREFS_CATEGORIES);
if (cat_tags) {
for (CECTag::const_iterator it = cat_tags->begin(); it != cat_tags->end(); ++it) {
const CECTag &cat_tag = *it;
Category_Struct *cat = new Category_Struct;
cat->title = cat_tag.GetTagByName(EC_TAG_CATEGORY_TITLE)->GetStringData();
cat->path = CPath(cat_tag.GetTagByName(EC_TAG_CATEGORY_PATH)->GetStringData());
cat->comment = cat_tag.GetTagByName(EC_TAG_CATEGORY_COMMENT)->GetStringData();
cat->color = cat_tag.GetTagByName(EC_TAG_CATEGORY_COLOR)->GetInt();
cat->prio = cat_tag.GetTagByName(EC_TAG_CATEGORY_PRIO)->GetInt();
theApp->glob_prefs->AddCat(cat);
}
} else {
Category_Struct *cat = new Category_Struct;
cat->title = _("All");
cat->color = 0;
cat->prio = PR_NORMAL;
theApp->glob_prefs->AddCat(cat);
}
wxECInitDoneEvent event;
theApp->AddPendingEvent(event);
}
bool CPreferencesRem::LoadRemote()
{
//
// override local settings with remote
CECPacket req(EC_OP_GET_PREFERENCES, EC_DETAIL_UPDATE);
// bring categories too
req.AddTag(CECTag(EC_TAG_SELECT_PREFS, m_exchange_recv_selected_prefs));
m_conn->SendRequest(this, &req);
return true;
}
void CPreferencesRem::SendToRemote()
{
CEC_Prefs_Packet pref_packet(m_exchange_send_selected_prefs, EC_DETAIL_UPDATE, EC_DETAIL_FULL);
m_conn->SendPacket(&pref_packet);
}
// Surfaces the EC_OP_FAILED reply from amuled's EC_OP_ADD_LINK handler
// to the user. CDownQueueRem::AddLink used to drop the reply on the
// floor (fire-and-forget SendPacket), so a malformed ed2k link -- e.g.
// the original #310 reproducer `ed2k::3D366ED505B977FC61C9A6EE01E96329`
// -- silently did nothing. amuled does the right thing now (logs
// "Unknown protocol of link" and returns EC_OP_FAILED + EC_TAG_STRING),
// but the GUI side has to actually show the message.
class CAddLinkHandler : public CECPacketHandlerBase {
virtual void HandlePacket(const CECPacket *packet);
};
void CAddLinkHandler::HandlePacket(const CECPacket *packet)
{
if (packet->GetOpCode() == EC_OP_FAILED) {
// Daemon-side EC_OP_ADD_LINK always tags the failure response
// with an EC_TAG_STRING explaining what went wrong. Reuse that
// string as the fallback too (it's already in the i18n catalog
// at po/amule.pot:1783, so no new string needs adding here).
const CECTag *tag = packet->GetFirstTagSafe();
wxString msg = (tag && tag->IsString())
? wxGetTranslation(tag->GetStringData())
: wxGetTranslation(wxTRANSLATE("Invalid link or already on list."));
// Defer the modal off the OnPacketReceived call stack: wxMessageBox
// spins a nested wx event loop, which dispatches CoreNotify_LibSocket*
// events that re-enter CECSocket::OnInput on the same socket and
// clobber its rx state (m_curr_rx_data / m_bytes_needed / m_in_header).
// Under heavy notification load — a batched-link add against a
// big shareset — the corrupted parse trips a protocol-error
// CloseSocket, which is the desync amuled logs as "External
// connection closed" right after the AddLink batch (#757 part 1).
wxTheApp->CallAfter([msg]() {
wxMessageBox(msg, _("ERROR"), wxOK | wxICON_ERROR);
});
}
delete this;
}
class CCatHandler : public CECPacketHandlerBase {
virtual void HandlePacket(const CECPacket *packet);
};
void CCatHandler::HandlePacket(const CECPacket *packet)
{
if (packet->GetOpCode() == EC_OP_FAILED) {
const CECTag * catTag = packet->GetTagByName(EC_TAG_CATEGORY);
const CECTag * pathTag = packet->GetTagByName(EC_TAG_CATEGORY_PATH);
if (catTag && pathTag && catTag->GetInt() < theApp->glob_prefs->GetCatCount()) {
int cat = catTag->GetInt();
Category_Struct* cs = theApp->glob_prefs->GetCategory(cat);
wxString msg = CFormat(_("Can't create directory '%s' for category '%s', keeping directory '%s'."))
% cs->path.GetPrintable() % cs->title % pathTag->GetStringData();
cs->path = CPath(pathTag->GetStringData());
theApp->amuledlg->m_transferwnd->UpdateCategory(cat);
theApp->amuledlg->m_transferwnd->downloadlistctrl->Refresh();
// Same re-entrancy hazard as CAddLinkHandler above: keep the
// modal off the OnPacketReceived stack so a nested wx event
// loop doesn't corrupt CECSocket rx state.
wxTheApp->CallAfter([msg]() {
wxMessageBox(msg, _("ERROR"), wxOK);
});
}
}
delete this;
}
bool CPreferencesRem::CreateCategory(
Category_Struct *& category,
const wxString& name,
const CPath& path,
const wxString& comment,
uint32 color,
uint8 prio)
{
CECPacket req(EC_OP_CREATE_CATEGORY);
CEC_Category_Tag tag(0xffffffff, name, path.GetRaw(), comment, color, prio);
req.AddTag(tag);
m_conn->SendRequest(new CCatHandler, &req);
category = new Category_Struct();
category->path = path;
category->title = name;
category->comment = comment;
category->color = color;
category->prio = prio;
AddCat(category);
return true;
}
bool CPreferencesRem::UpdateCategory(
uint8 cat,
const wxString& name,
const CPath& path,
const wxString& comment,
uint32 color,
uint8 prio)
{
CECPacket req(EC_OP_UPDATE_CATEGORY);
CEC_Category_Tag tag(cat, name, path.GetRaw(), comment, color, prio);
req.AddTag(tag);
m_conn->SendRequest(new CCatHandler, &req);
Category_Struct *category = m_CatList[cat];
category->path = path;
category->title = name;
category->comment = comment;
category->color = color;
category->prio = prio;
return true;
}
void CPreferencesRem::RemoveCat(uint8 cat)
{
CECPacket req(EC_OP_DELETE_CATEGORY);
CEC_Category_Tag tag(cat, EC_DETAIL_CMD);
req.AddTag(tag);
m_conn->SendPacket(&req);
CPreferences::RemoveCat(cat);
}
//
// Container implementation
//
CServerConnectRem::CServerConnectRem(CRemoteConnect *conn)
{
m_CurrServer = 0;
m_Conn = conn;
}
void CServerConnectRem::ConnectToAnyServer()
{
CECPacket req(EC_OP_SERVER_CONNECT);
m_Conn->SendPacket(&req);
}
void CServerConnectRem::StopConnectionTry()
{
// lfroen: isn't Disconnect the same ?
}
void CServerConnectRem::Disconnect()