forked from amule-project/amule
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathamule-remote-gui.cpp
More file actions
4370 lines (3931 loc) · 154 KB
/
Copy pathamule-remote-gui.cpp
File metadata and controls
4370 lines (3931 loc) · 154 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 <algorithm> // Needed for std::min
#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 "ProtocolHandlerManager.h" // Needed for ProtocolHandler_QueueSchemeLink
#include "CamuleArtProvider.h" // Needed for wxArtProvider::Push() in OnInit
#include "amuleDlg.h" // Needed for CamuleDlg
#include "PrefsUnifiedDlg.h" // Needed for the shared-dirs editor refresh hook
#include <wx/sizer.h> // CReconnectDialog layout (issue #444)
#include <wx/stattext.h> // CReconnectDialog status label
#include <wx/button.h> // CReconnectDialog abort button
#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 GEOIP_GUI
#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 <tags/FileTags.h> // Needed for FT_MEDIA_* metadata tag names
#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);
// Default 1: a config predating this key gets encryption.
long pref_encryption;
wxConfig::Get()->Read("/EC/Encryption", &pref_encryption, 1);
CastChild(ID_EC_ENCRYPTION, wxCheckBox)->SetValue(pref_encryption != 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();
m_encryption = CastChild(ID_EC_ENCRYPTION, wxCheckBox)->IsChecked();
evt.Skip();
}
wxDEFINE_EVENT(wxEVT_EC_INIT_DONE, wxEvent);
// ----------------------------------------------------------------------
// Reconnect-after-loss dialog (issue #444). Shown modally while amulegui
// re-establishes a dropped EC connection: modal so the main window is
// frozen (the user must not act on stale data or queue EC commands at a
// dead socket), while the retry timer + socket events still pump in the
// modal loop. The wxID_CANCEL "Abort and exit" button ends the modal
// with wxID_CANCEL; a successful reconnect ends it with wxID_OK from
// CamuleRemoteGuiApp::OnECConnection.
// ----------------------------------------------------------------------
class CReconnectDialog : public wxDialog
{
public:
CReconnectDialog(wxWindow *parent, const wxString &target)
: wxDialog(parent, wxID_ANY, _("Connection lost"), wxDefaultPosition, wxDefaultSize, wxCAPTION)
, m_label(nullptr)
, m_target(target)
{
wxBoxSizer *top = new wxBoxSizer(wxVERTICAL);
m_label = new wxStaticText(this, wxID_ANY, wxEmptyString);
top->Add(m_label, 0, wxALL, 15);
top->Add(new wxButton(this, wxID_CANCEL, _("Abort and exit")),
0,
static_cast<int>(wxALIGN_CENTER) | wxLEFT | wxRIGHT | wxBOTTOM,
15);
SetAttempt(1);
SetSizerAndFit(top);
CentreOnParent();
}
// Shown while a connect attempt is in flight.
void SetAttempt(int n) { SetStatus(CFormat(_("Reconnecting... (attempt %d)")) % n); }
// Shown counting down to the next attempt after a failure.
void SetCountdown(int seconds) { SetStatus(CFormat(_("Next attempt in %d s...")) % seconds); }
private:
// Only the middle line changes; the (widest) "paused" line is constant,
// so the dialog keeps its size and doesn't jump on each update.
void SetStatus(const wxString &middle)
{
m_label->SetLabel(CFormat(_("Connection to %s lost.\n%s\n\nThe interface is paused "
"until the connection is restored.")) %
m_target % middle);
}
wxStaticText *m_label;
wxString m_target;
};
wxBEGIN_EVENT_TABLE(CamuleRemoteGuiApp, wxApp)
// macOS Dock right-click -> Quit ends the session without going through
// the red-X / Cmd+Q paths; catch it so ShutDown + OnExit cleanup still runs.
EVT_QUERY_END_SESSION(CamuleRemoteGuiApp::OnQueryEndSession)
EVT_END_SESSION(CamuleRemoteGuiApp::OnEndSession)
// 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)
// Spacing between reconnect attempts after a post-startup loss (#444)
EVT_TIMER(ID_REMOTE_RECONNECT_TIMER, CamuleRemoteGuiApp::OnReconnectTimer)
EVT_CUSTOM(wxEVT_EC_CONNECTION, -1, CamuleRemoteGuiApp::OnECConnection)
EVT_CUSTOM(wxEVT_EC_INIT_DONE, -1, CamuleRemoteGuiApp::OnECInitDone)
EVT_MULE_NOTIFY(CamuleRemoteGuiApp::OnNotifyEvent)
#ifdef GEOIP_GUI
// 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
// Mirror CamuleApp::OnExit (#141): drain the pending-delete queue (where
// CamuleDlg::OnClose -> ShutDown parked amuledlg->Destroy()) so the frame's
// lazily-scheduled destructor runs, then tear down wxConfig to flush it.
// Otherwise the red-X + confirm path reaches here with the destroy still
// queued and anything that chain persists is lost (CMD+Q happens to drain
// naturally). The _Exit(0) below skips wx's own cleanup that normally does
// both, so we do it by hand here. Column widths and sort orders no longer
// depend on this: CMuleDataViewCtrl writes those eagerly.
DeletePendingObjects();
delete wxConfigBase::Set(nullptr);
// Skip wx's static-destructor / module cleanup, exactly as the monolithic
// app does in CamuleGuiApp::OnExit (amule.cpp). wx's WebRequestModule
// teardown destroys the platform wxWebSession, whose dtor dereferences
// already-freed state and raise(SIGABRT)s on quit (amule-org/amule#18,
// PR #159). amulegui links wxWebRequest too, so it hits the identical
// crash. By this point our own cleanup (timer, sockets) has run; _Exit
// bypasses atexit + static destructors so the buggy wx dtor never runs.
// Remove once the upstream wx fix lands in a release we depend on.
//
// _Exit also skips ~CamuleAppCommon, which would release the
// single-instance lock; drop it here so muleLockRGUI is unlinked.
ReleaseSingleInstance();
std::_Exit(0);
return wxApp::OnExit();
}
void CamuleRemoteGuiApp::OnQueryEndSession(wxCloseEvent &evt)
{
// Flag the quit so CamuleDlg::OnClose skips its HideOnClose-veto branch
// and actually quits on a Dock right-click -> Quit (as for Cmd+Q).
SetQuitting();
evt.Skip();
}
void CamuleRemoteGuiApp::OnEndSession(wxCloseEvent &evt)
{
// The Dock-Quit path can bypass OnExit, so run ShutDown (unless OnClose
// already did -- it nulls amuledlg) and then OnExit explicitly, so the
// list-control destructors + wxConfig flush run and column widths / sort
// orders persist. Mirrors CamuleGuiApp::OnEndSession (amule-gui.cpp).
if (amuledlg) {
ShutDown(evt);
}
OnExit();
evt.Skip();
}
#ifdef __WXMAC__
void CamuleRemoteGuiApp::MacReopenApp()
{
// Dock-icon click (and re-launch from Finder / Launchpad) while no
// window is visible. wxApp's default handler only de-iconizes; a frame
// hidden with Show(false) -- the close-button HideOnClose path and the
// minimize-to-tray path both end there -- is not a candidate, so
// without this amulegui simply never came back. Mirrors CamuleGuiApp.
if (amuledlg) {
amuledlg->RestoreMainWindow();
}
}
void CamuleRemoteGuiApp::MacOpenFiles(const wxArrayString &fileNames)
{
// Also fires for Dock drops of arbitrary files; anything that is not
// a collection is ignored without complaint. Mirrors CamuleGuiApp.
OpenCollectionFiles(fileNames);
}
void CamuleRemoteGuiApp::MacOpenURL(const wxString &url)
{
ProtocolHandler_QueueSchemeLink(url);
}
#endif
#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::OnAssertFailure(
const wxChar *file, int line, const wxChar *func, const wxChar *cond, const wxChar *msg)
{
// Unlike CamuleApp there is no app-state gate here: the remote GUI has
// no equivalent of IsRunning(), and its window is either up or the
// assert came from a thread that cannot show a dialog anyway.
if (ReportAssertFailure(file, line, func, cond, msg, wxThread::IsMain())) {
wxApp::OnAssertFailure(file, line, func, cond, msg);
}
}
void CamuleRemoteGuiApp::OnPollTimer(wxTimerEvent &)
{
static int request_step = 0;
static uint32 msPrevStats = 0;
// Reply watchdog. EC has no application-level keepalive, and the daemon
// always answers, so requests outstanding with nothing coming back means
// the transport has gone quiet -- an SSH tunnel with no ServerAliveInterval,
// a NAT dropping an idle mapping, a proxy that stopped relaying. None of
// those close the socket: it stays ESTABLISHED with every queue empty and
// no error is ever raised, so neither OnLost nor OnError fires.
//
// Without this the failure is permanent AND silent. Once m_req_count passes
// m_req_fifo_thr the early-return below fires on every tick, so the client
// stops sending too -- and recovery would need a reply, which needs a
// request. The back-pressure brake becomes a deadlock the client can never
// leave, with a frozen UI and no message.
//
// Gated on the fifo rather than on the threshold so it trips on the real
// symptom (nothing answering) rather than waiting for the queue to fill.
if (m_connect->GetReqFifoSize() > 0 &&
m_connect->MillisecondsSinceLastReply() > EC_REPLY_TIMEOUT_MS) {
// Untranslated and debug-level on purpose: the user-facing messaging
// already comes from the path this drops into -- OnLost posts
// "Connection failure" and BeginReconnect announces the retry, both
// long since translated. Adding a new msgid here would have bought
// translators work for something nobody but a developer reads.
AddDebugLogLineN(logEC,
CFormat(wxT("EC reply watchdog: no reply for %u ms with %u requests "
"pending -- treating the connection as dead")) %
(unsigned)m_connect->MillisecondsSinceLastReply() %
(unsigned)m_connect->GetReqFifoSize());
// Close ourselves and dispatch the loss: a self-close suppresses the
// asio lost-event path, so without the explicit dispatch nothing would
// tell the GUI. Lands in OnECConnection(false) -> BeginReconnect().
m_connect->CloseAndDispatchLost();
return;
}
if (m_connect->RequestFifoFull()) {
return;
}
switch (request_step) {
case 0: {
CECPacket stats_req(EC_OP_STAT_REQ, EC_DETAIL_INC_UPDATE);
m_connect->SendRequest(&m_stats_updater, &stats_req);
request_step++;
break;
}
case 1:
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);
// Server-message log mirror: pull the cumulative
// server_msg buffer while the Network tab is up so the
// "Server Info" sub-panel reaches feature parity with
// the monolithic build. ed2k server messages are bursty
// (one-off on connect, the occasional ID-change notice,
// disconnect) so the natural cadence of the page step is
// plenty.
if (amuledlg->m_serverwnd->IsShown()) {
CECPacket srvinfo_req(EC_OP_GET_SERVERINFO);
m_connect->SendRequest(&m_serverinfo_handler, &srvinfo_req);
}
} 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()) {
// Reachability fix (#641): ask what searches the daemon
// currently holds -- independent of m_curr_search, which only
// ever reflects a search THIS client itself started -- so a
// search opened by another client, or one day restored from
// disk, gets a tab created here (CSearchListRem::HandlePacket).
// Search entries are near-static (id/name/kind barely change),
// so unlike the results union poll below this isn't asked every
// tick: once on (re)connect, and again only when a result turns
// up bearing a search ID with no tab yet (CreateItem sets
// m_needSearchListRequery) -- the daemon-side registry this
// reads never changes without a result also arriving for it.
// RequestSearchList (not DoRequery) on purpose: HandlePacket's
// EC_OP_SEARCH_LIST branch never reaches the base class's
// STATUS_REQ_SENT -> IDLE transition, so going through
// DoRequery would wedge this container's request state machine
// forever and silently drop every later EC_OP_SEARCH_RESULTS
// poll (got3nks, PR #680 review).
if (searchlist->m_needSearchListRequery) {
searchlist->RequestSearchList();
searchlist->m_needSearchListRequery = false;
}
// The union poll below already returns every active search's
// results regardless of m_curr_search (Get_EC_Response_Search_
// Results_Union iterates the daemon's own registry) -- the old
// m_curr_search-only gate just meant a client that never
// started a search of its own never asked at all, even once a
// tab existed for one it learned about above.
searchlist->DoRequery(EC_OP_SEARCH_RESULTS, EC_TAG_SEARCHFILE);
}
// Stats polling is always on, even when the Statistics dialog
// isn't the active tab. statgraphs->HandlePacket() also feeds
// the Kad node-count graph on the Network -> Kad sub-tab via
// m_kademliawnd->UpdateGraph(); gating on m_statisticswnd left
// the Kad graph empty whenever the user wasn't sitting on
// Statistics, and produced a visible gap in the Statistics
// graph itself across any tab switch. Both requests are cheap
// deltas: the graph sends m_lastTimestamp and the daemon
// returns only points newer than that (or EC_OP_FAILED "No
// points for graph."); the tree request honors
// thePrefs::GetStatsInterval().
{
int sStatsUpdate = thePrefs::GetStatsInterval();
uint32 msCur = theStats::GetUptimeMillis();
if ((sStatsUpdate > 0) && ((int)(msCur - msPrevStats) > sStatsUpdate * 1000)) {
msPrevStats = msCur;
stattree->DoRequery();
}
statgraphs->DoRequery();
}
// Incoming friend/chat messages are relayed by the daemon over EC
// (amulegui is receive-only). Poll unconditionally — like stats
// above, and unlike the per-tab data — so a message that arrives
// while the user is on another tab still triggers the new-message
// blink in CChatWnd::ProcessMessage. Cheap: an empty reply when
// nothing is pending. Gated on the daemon supporting the relay;
// old daemons never echo EC_TAG_CAN_CHAT and we never poll.
if (m_connect->ServerSupportsChat()) {
CECPacket chat_req(EC_OP_GET_CHAT_MESSAGES);
m_connect->SendRequest(&m_chatmsg_handler, &chat_req);
}
// 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 &WXUNUSED(event))
{
// amulegui has no local GeoIP resolver — country codes arrive over EC from
// the daemon (#439 / #440) — so it never starts a GeoIP download and there
// is nothing to finish here.
}
void CamuleRemoteGuiApp::ShutDown(wxCloseEvent &WXUNUSED(evt))
{
// A modal dialog (comments/ratings, file details, ...) runs its own event
// loop, and an EC drop is dispatched from whichever loop is current — so a
// shutdown can start with one of those dialogs still on the stack. Unwind
// to the outer loop first; Quit() resumes the teardown from there.
if (DeferShutDownToOuterLoop([this] { Quit(); })) {
return;
}
// 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;
m_tornDown = true;
}
void CamuleRemoteGuiApp::Quit()
{
if (m_tornDown) {
return;
}
wxCloseEvent ev;
ShutDown(ev);
// Still unset means ShutDown() postponed itself to the outer event loop;
// leaving the main loop now would drop the retry it queued.
if (m_tornDown) {
ExitMainLoop();
}
}
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());
// Must happen before any window exists; the connect dialog below is the
// first one amulegui creates. Without this amulegui stayed light on
// Windows while the monolithic amule, which has always asked, went dark.
FollowSystemAppearance();
// 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
// amulegui addresses searches by daemon-allocated ID (per-tab, several at
// once); advertise the multi-search capability. An old daemon won't echo
// it and amulegui stays single-search (ServerSupportsMultiSearch()).
m_connect->SetCanMultiSearch(true);
// amulegui shows incoming friend/chat messages read-only; ask the daemon
// to relay them (polled via EC_OP_GET_CHAT_MESSAGES). An old daemon won't
// echo the capability and amulegui simply never polls (ServerSupportsChat()).
m_connect->SetCanChat(true);
// 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 checkbox states to the EC client before each
// ConnectToCore attempt (re-applied per retry so the user can
// toggle them between attempts if they need to). ResetEcConnect()
// recreates m_connect on a failed handshake and deliberately does
// not re-apply these two: the dialog owns them and sets them again
// on the fresh object right here.
m_connect->SetForceZlib(dialog->ForceZlib());
m_connect->SetCanAEAD(dialog->Encryption());
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);
m_connect->SetCanMultiSearch(true);
m_connect->SetCanChat(true);
}
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) {
if (m_reconnecting) {
// Reconnected: close the modal reconnect dialog. Execution
// resumes right after ShowModal() in ShowReconnectDialog(),
// which re-arms the reconcile prune and restarts polling.
if (m_reconnectDlg) {
m_reconnectDlg->EndModal(wxID_OK);
} else {
// Reconnected behind a minimised window, so there is no
// modal loop to unwind and nothing to close -- finish
// here instead (issue #806).
FinishReconnect(wxID_OK);
}
} else {
// Connected - go to next init step
glob_prefs->LoadRemote();
}
} else if (m_reconnecting) {
// A reconnect attempt failed. Space out the next one; the modal
// dialog stays up with the attempt count and an Abort button.
ScheduleNextReconnect();
} 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"));
Quit();
}
} else {
// Connection lost after startup (e.g. the machine slept and the
// EC socket dropped). Don't quit — freeze the UI and reconnect in
// the background until we're back or the user aborts (issue #444).
BeginReconnect();
}
}
void CamuleRemoteGuiApp::OnConnectTimeout(wxTimerEvent &)
{
delete connect_timeout_timer;
connect_timeout_timer = NULL;
if (m_reconnecting) {
// This reconnect attempt hung (host unreachable, SYN black-holed).
// Treat it as a failed attempt and space out the next one; the
// modal reconnect dialog stays up with its Abort button (#444).
AddLogLineCS(_("Reconnect attempt timed out; retrying."));
ScheduleNextReconnect();
return;
}
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()) {
Quit();
}
}
void CamuleRemoteGuiApp::BeginReconnect()
{
if (m_reconnecting) {
return;
}
m_reconnecting = true;
m_reconnectAttempt = 0;
AddLogLineCS(_("Connection to the remote core was lost. Trying to reconnect..."));
// Freeze polling while disconnected: the poll timer would fire
// GET_UPDATE at a dead socket, and the GUI timer animates stale data.
if (poll_timer) {
poll_timer->Stop();
}
if (amuledlg) {
amuledlg->StopGuiTimer();
}
if (!m_reconnectTimer) {
m_reconnectTimer = new wxTimer(this, ID_REMOTE_RECONNECT_TIMER);
}
// Kick off the first attempt before deciding about the dialog, so the
// common case -- a blip that reconnects on the first try -- can be over
// with before anything is drawn.
AttemptReconnect();
// The dialog earns its intrusion by explaining a frozen window. With the
// window minimised or hidden to tray there is nothing on screen to
// explain, and a modal appearing over whatever the user is actually doing
// is worse than silence (issue #806). Retry quietly instead; the log still
// carries every attempt, and OnMainWindowRestored() puts the dialog up if
// the user comes back while this is still going.
//
// "Visible" has to mean both halves: minimized to Dock/taskbar keeps
// IsShown() true with nothing on screen, and hidden to tray leaves the
// iconized bit clear while the frame is gone. CamuleDlg tracks the
// iconized half from wxIconizeEvent rather than wxFrame::IsIconized(),
// which lies on wxGTK mid-transition. Compositors that never report
// iconize at all (Wayland xdg-shell has no such notification) keep the
// old behaviour for the minimize case.
if (amuledlg && !amuledlg->IsVisibleToUser()) {
return;
}
ShowReconnectDialog();
}
void CamuleRemoteGuiApp::ShowReconnectDialog()
{
if (!m_reconnecting || m_reconnectDlg) {
return;
}
m_reconnectDlg = new CReconnectDialog(amuledlg, CFormat(wxT("%s:%d")) % m_ecHost % m_ecPort);
// The retry loop has been running without us, so open on what it is
// actually doing rather than on "attempt 1": mid-countdown after a failed
// attempt, or in the middle of one.
if (m_reconnectCountdown > 0) {
m_reconnectDlg->SetCountdown(m_reconnectCountdown);
} else {
m_reconnectDlg->SetAttempt(m_reconnectAttempt);
}
// Run it modally: the retry timer and OnECConnection pump inside
// ShowModal(). A success calls EndModal(wxID_OK); the Abort button ends it
// with wxID_CANCEL.
const int result = m_reconnectDlg->ShowModal();
m_reconnectDlg->Destroy();
m_reconnectDlg = nullptr;
FinishReconnect(result);
}
void CamuleRemoteGuiApp::FinishReconnect(int result)
{
m_reconnecting = false;
m_reconnectCountdown = 0;
if (m_reconnectTimer) {
m_reconnectTimer->Stop();
}
delete connect_timeout_timer;
connect_timeout_timer = nullptr;
if (result == wxID_OK) {
AddLogLineCS(_("Reconnected to the remote core."));
// Everything we hold is keyed by ECID, and an ECID only means
// something within one daemon process: CECID hands them out from a
// counter that restarts with the process, so a restarted daemon
// reissues the same numbers in whatever order it loads files this
// time. Reconciling in place across that pairs our objects with
// whatever now happens to share their number.
//
// EC_TAG_SESSION_ID says which process we're talking to. Same value
// means the socket dropped but the daemon lived (a sleeping laptop,
// a dead tunnel), so the in-place reconcile below is right and keeps
// scroll and selection. Anything else -- a different value, or none
// at all because the daemon predates the tag -- means we cannot
// trust a single ID we hold, and starting over is the only correct
// answer even though it costs the user their scroll position.
const uint64 sessionId = m_connect ? m_connect->GetServerSessionId() : 0;
const bool sameSession = sessionId != 0 && sessionId == m_ecSessionId;
m_ecSessionId = sessionId;
if (!sameSession) {
AddLogLineNS(_("The remote core was restarted; reloading."));
if (knownfiles) {
knownfiles->ResetForNewDaemonSession();
}
if (clientlist) {
clientlist->ResetForNewSession();
}
if (serverlist) {
serverlist->ResetForNewSession();
}
if (friendlist) {
friendlist->ResetForNewSession();
}
} else if (knownfiles) {
// Same daemon: the next full poll reconciles every list against
// the fresh snapshot in place (update / add / prune) — no wipe,
// so scroll and selection survive.
knownfiles->ArmReconnectReconcile();
}
if (poll_timer) {
poll_timer->Start(EC_POLL_INTERVAL_MS);
}
if (amuledlg) {
amuledlg->StartGuiTimer();
}
} else {
// User aborted the reconnect.
AddLogLineNS(_("Going down"));
Quit();
}
}
void CamuleRemoteGuiApp::OnMainWindowRestored()
{
if (!m_reconnecting || m_reconnectDlg) {
return;
}
// Not straight from here: this runs inside the iconize event handler, and
// ShowReconnectDialog() ends in either a nested modal loop or Quit(). Let
// the handler return first (#738 is what tearing the main window down from
// a nested loop costs).
CallAfter(&CamuleRemoteGuiApp::ShowReconnectDialog);
}
void CamuleRemoteGuiApp::AttemptReconnect()
{
m_reconnectAttempt++;
if (m_reconnectDlg) {
m_reconnectDlg->SetAttempt(m_reconnectAttempt);
}
AddLogLineCS(CFormat(_("Reconnect attempt %d: connecting to %s:%d")) % m_reconnectAttempt % m_ecHost %
m_ecPort);