forked from therealaleph/MasterHttpRelayVPN-RUST
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.rs
More file actions
2735 lines (2626 loc) · 122 KB
/
Copy pathui.rs
File metadata and controls
2735 lines (2626 loc) · 122 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
use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use eframe::egui;
use tokio::runtime::Runtime;
use tokio::sync::Mutex as AsyncMutex;
use tokio::task::JoinHandle;
use mhrv_rs::cert_installer::{install_ca, reconcile_sudo_environment, remove_ca};
use mhrv_rs::config::{Config, FrontingGroup, ScriptId};
use mhrv_rs::data_dir;
use mhrv_rs::domain_fronter::{DomainFronter, DEFAULT_GOOGLE_SNI_POOL};
use mhrv_rs::lan_utils::{detect_lan_ip, is_share_on_lan};
use mhrv_rs::mitm::{MitmCertManager, CA_CERT_FILE};
use mhrv_rs::proxy_server::ProxyServer;
use mhrv_rs::{scan_ips, scan_sni, test_cmd};
const VERSION: &str = env!("CARGO_PKG_VERSION");
const WIN_WIDTH: f32 = 520.0;
const WIN_HEIGHT: f32 = 680.0;
const LOG_MAX: usize = 200;
fn main() -> eframe::Result<()> {
let _ = rustls::crypto::ring::default_provider().install_default();
// Re-point HOME at the invoking user if this binary was launched
// under sudo (see cert_installer::reconcile_sudo_environment). Must
// run before any data_dir / firefox_profile_dirs call.
reconcile_sudo_environment();
mhrv_rs::rlimit::raise_nofile_limit_best_effort();
let shared = Arc::new(Shared::default());
let (cmd_tx, cmd_rx) = std::sync::mpsc::channel::<Cmd>();
// Load the user's saved form first so we can seed the tracing filter
// with their saved log level. Otherwise the form's log-level combobox
// would only ever take effect via env var or after Save → restart, and
// users on the UI binary (issue #401) reasonably expect the saved
// config.toml `log_level` to apply at boot like it does for the CLI.
let (form, load_err) = load_form();
let initial_toast = load_err.map(|e| (e, Instant::now()));
// Hook tracing events into the Recent log panel. Without this every
// tracing::info! / debug! / trace! the proxy emits gets swallowed and
// the panel only ever shows our manual push_log calls, making the log
// level selector look useless (issue #12 bug 2).
//
// Filter precedence (issue #401 fix in v1.8.2):
// 1. RUST_LOG env var if set — explicit override
// 2. Saved config's `log_level` (passed from form) — what users mean
// when they pick a level in the UI
// 3. "info,hyper=warn" — sensible default
//
// Save inside the running UI also installs the new filter via the
// reload handle (see `LOG_RELOAD` below), so users don't need to
// restart for a config change to take effect.
install_ui_tracing(shared.clone(), &form.log_level);
let shared_bg = shared.clone();
std::thread::Builder::new()
.name("mhrv-bg".into())
.spawn(move || background_thread(shared_bg, cmd_rx))
.expect("failed to spawn background thread");
// Pick the renderer. Default is `glow` (OpenGL 2+) because that's
// what we shipped through v1.0.x and it has the least binary-size
// overhead. Users on older Windows boxes / RDP sessions / headless
// VMs that crashed with `egui_glow requires opengl 2.0+` (issue
// #28) can force the wgpu backend — DX12 on Windows, Vulkan on
// Linux, Metal on macOS — by setting the env var:
//
// MHRV_RENDERER=wgpu mhrv-rs-ui
//
// The launcher scripts (run.bat / run.command / run.sh) honour
// the same variable and forward it through.
let use_wgpu = std::env::var("MHRV_RENDERER")
.map(|v| v.eq_ignore_ascii_case("wgpu"))
.unwrap_or(false);
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([WIN_WIDTH, WIN_HEIGHT])
.with_min_inner_size([420.0, 400.0])
.with_title(format!("mhrv-rs {}", VERSION)),
renderer: if use_wgpu {
eframe::Renderer::Wgpu
} else {
eframe::Renderer::Glow
},
..Default::default()
};
eframe::run_native(
"mhrv-rs",
options,
Box::new(move |cc| {
cc.egui_ctx.set_visuals(egui::Visuals::dark());
Ok(Box::new(App {
shared,
cmd_tx,
form,
last_poll: Instant::now(),
toast: initial_toast,
}))
}),
)
}
#[derive(Default)]
struct Shared {
state: Mutex<UiState>,
}
#[derive(Default)]
struct UiState {
running: bool,
started_at: Option<Instant>,
last_stats: Option<mhrv_rs::domain_fronter::StatsSnapshot>,
last_per_site: Vec<(String, mhrv_rs::domain_fronter::HostStat)>,
log: VecDeque<String>,
/// Result + timestamp for transient status banners (auto-hide after 10s).
ca_trusted: Option<bool>,
ca_trusted_at: Option<Instant>,
last_test_ok: Option<bool>,
last_test_msg: String,
last_test_msg_at: Option<Instant>,
/// Per-SNI probe results, populated by Cmd::TestSni / TestAllSni.
sni_probe: HashMap<String, SniProbeState>,
/// Most recent result of the Check-for-updates button (issue #15).
/// `None` = never checked this session. `Some(InFlight)` during the
/// probe, then the resolved outcome.
last_update_check: Option<UpdateProbeState>,
last_update_check_at: Option<Instant>,
/// Set while a download of a release asset is in flight. `None` when
/// idle or after a completed download has been acknowledged.
download_in_progress: bool,
/// Set while an install-or-remove cert op is in flight. Install and
/// Remove share this single flag so they can't race each other:
/// clicking Install → Remove back-to-back would otherwise leave the
/// final trust/file state dependent on thread scheduling — an
/// in-flight install could re-trust the CA after Remove had already
/// deleted it, or vice versa. Both UI buttons disable while this
/// is set, and both handlers gate-and-flip it.
cert_op_in_progress: bool,
/// Set synchronously when `Cmd::Start` is received by the background
/// thread, cleared synchronously when `Cmd::Stop` completes. Broader
/// than `running` (which only flips after the MITM manager has
/// finished loading). Used to block `Remove CA` during the window
/// between start-click and `running = true` — otherwise a queued
/// `Cmd::RemoveCa` could delete `ca/` while the server is partway
/// through loading the keypair into memory.
proxy_active: bool,
/// One-line status of the most recent download (Ok(path) or Err(msg)).
last_download: Option<Result<std::path::PathBuf, String>>,
last_download_at: Option<Instant>,
}
#[derive(Clone, Debug)]
enum UpdateProbeState {
InFlight,
Done(mhrv_rs::update_check::UpdateCheck),
}
#[derive(Clone, Debug)]
enum SniProbeState {
InFlight,
Ok(u32),
Failed(String),
}
enum Cmd {
Start(Config),
Stop,
Test(Config),
InstallCa,
RemoveCa,
CheckCaTrusted,
PollStats,
/// Probe a single SNI against the given google_ip. Result is written
/// into UiState::sni_probe keyed by the SNI string.
TestSni {
google_ip: String,
sni: String,
},
/// Probe a batch of SNI names. Results appear in UiState::sni_probe one
/// by one as each probe finishes.
TestAllSni {
google_ip: String,
snis: Vec<String>,
},
/// Hit github.com + the Releases API and compare the running version
/// to the latest tag. Result is written to UiState::last_update_check.
/// `route` controls whether the request goes direct or is tunnelled
/// through our local HTTP proxy (useful when the user's ISP IP has
/// exhausted GitHub's unauthenticated rate limit).
CheckUpdate {
route: mhrv_rs::update_check::Route,
},
/// Download a release asset to ~/Downloads. Fires when the user clicks
/// the "Download update" button after a successful CheckUpdate surfaces
/// an UpdateAvailable with a matching platform asset.
DownloadUpdate {
route: mhrv_rs::update_check::Route,
url: String,
name: String,
},
}
struct App {
shared: Arc<Shared>,
cmd_tx: Sender<Cmd>,
form: FormState,
last_poll: Instant,
toast: Option<(String, Instant)>,
}
#[derive(Clone)]
struct FormState {
/// `"apps_script"` (default), `"direct"`, or `"full"`. Controls
/// whether the Apps Script relay is wired up at all. In `direct`,
/// the form tolerates an empty script_id / auth_key.
/// On load we normalize the legacy `"google_only"` string to
/// `"direct"` so the next save rewrites the on-disk config.
mode: String,
script_id: String,
auth_key: String,
google_ip: String,
front_domain: String,
listen_host: String,
listen_port: String,
socks5_port: String,
log_level: String,
verify_ssl: bool,
upstream_socks5: String,
parallel_relay: u8,
show_auth_key: bool,
/// SNI rotation pool entries. Each item has a sni name + a checkbox
/// flag indicating whether it's in the active rotation.
sni_pool: Vec<SniRow>,
/// Text field buffer for the "+ add custom SNI" input at the bottom of
/// the SNI editor window.
sni_custom_input: String,
/// Whether the floating SNI editor window is open.
sni_editor_open: bool,
/// Whether the Recent log panel is shown. User toggles with a checkbox.
show_log: bool,
fetch_ips_from_api: bool,
max_ips_to_scan: usize,
scan_batch_size: usize,
google_ip_validation: bool,
normalize_x_graphql: bool,
youtube_via_relay: bool,
passthrough_hosts: Vec<String>,
/// Round-tripped from config.toml so the UI's save path doesn't
/// drop the user's setting. Not currently exposed as a UI control;
/// users edit `block_quic` directly in `config.toml` (Issue #213).
block_quic: bool,
/// Round-tripped from config.toml and exposed beside QUIC blocking.
/// Default true to push WebRTC apps toward TCP TURN instead of slow
/// UDP ICE retries.
block_stun: bool,
/// Round-tripped from config.toml. Not exposed as a UI control —
/// users edit `disable_padding` directly when needed (Issue #391).
/// Default false (padding active).
disable_padding: bool,
/// Round-tripped from config.toml. Not exposed as a UI control —
/// users edit `force_http1` directly when needed. Default false
/// (HTTP/2 multiplexing on the relay leg active).
force_http1: bool,
/// Round-tripped from config.toml. Not exposed in the UI form yet —
/// the bypass-DoH default is the right answer for almost everyone
/// (DoH already encrypts, the tunnel was just adding latency), so
/// this is a config-only opt-out. See config.rs `tunnel_doh`.
tunnel_doh: bool,
/// User-supplied DoH hostnames added to the built-in default list,
/// round-tripped from config.toml. See config.rs `bypass_doh_hosts`.
bypass_doh_hosts: Vec<String>,
/// PR #763: when true, immediately reject browser DoH CONNECTs so the
/// browser falls back to system DNS (tun2proxy virtual DNS — instant).
/// Round-tripped from config.toml. Desktop UI doesn't expose a toggle
/// yet — Android does. See config.rs `block_doh`.
block_doh: bool,
/// Multi-edge fronting groups. Round-tripped from config.toml so
/// the UI's Save doesn't drop the user's hand-edited groups —
/// there is no UI editor for these yet, only file-edited config.
/// See config.rs `fronting_groups`.
fronting_groups: Vec<FrontingGroup>,
/// Auto-blacklist tuning + per-batch timeout. Config-only knobs (no UI
/// fields yet — power-user file edit). Round-tripped through FormState
/// so Save preserves the user's hand-edited values. See config.rs
/// `auto_blacklist_*` and `request_timeout_secs`.
auto_blacklist_strikes: u32,
auto_blacklist_window_secs: u64,
auto_blacklist_cooldown_secs: u64,
request_timeout_secs: u64,
stream_timeout_secs: u64,
/// Optional second-hop exit node for CF-anti-bot bypass (chatgpt.com /
/// claude.ai / grok.com / x.com). Config-only — no UI editor yet.
/// See `assets/exit_node/` for the generic exit-node handler.
exit_node: mhrv_rs::config::ExitNodeConfig,
}
#[derive(Clone, Debug)]
struct SniRow {
name: String,
enabled: bool,
}
fn load_form() -> (FormState, Option<String>) {
// Try the user-data config first, then the cwd fallback. Report WHY load
// fails so the user isn't silently shown a blank form (issue: user reports
// 'settings saved to file but not loaded back'). Without this signal the
// failure is invisible — `.ok()` swallows it and the form looks fresh.
let path = data_dir::resolve_config_path(None);
let (existing, load_err): (Option<Config>, Option<String>) = if path.exists() {
tracing::info!("config: attempting load from {}", path.display());
match Config::load(&path) {
Ok((c, _)) => {
tracing::info!("config: loaded OK from {}", path.display());
(Some(c), None)
}
Err(e) => {
let msg = format!("Config at {} failed to load: {}", path.display(), e);
tracing::warn!("{}", msg);
(None, Some(msg))
}
}
} else {
tracing::info!(
"config: no config found at {} — starting with defaults",
path.display()
);
(None, None)
};
let form = if let Some(c) = existing {
let sid = match &c.script_id {
Some(ScriptId::One(s)) => s.clone(),
Some(ScriptId::Many(v)) => v.join("\n"),
None => match &c.script_ids {
Some(ScriptId::One(s)) => s.clone(),
Some(ScriptId::Many(v)) => v.join("\n"),
None => String::new(),
},
};
let sni_pool = sni_pool_for_form(c.sni_hosts.as_deref(), &c.front_domain);
// Normalize the legacy `google_only` mode string on load. The
// backend's `mode_kind()` accepts the alias forever, but storing
// it as `direct` in the form means the next Save rewrites the
// on-disk config to the new name — one-way migration, no warn
// on every startup.
let mode_normalized = if c.mode == "google_only" {
"direct".to_string()
} else {
c.mode.clone()
};
FormState {
mode: mode_normalized,
script_id: sid,
auth_key: c.auth_key,
google_ip: c.google_ip,
front_domain: c.front_domain,
listen_host: c.listen_host,
listen_port: c.listen_port.to_string(),
socks5_port: c.socks5_port.map(|p| p.to_string()).unwrap_or_default(),
log_level: c.log_level,
verify_ssl: c.verify_ssl,
upstream_socks5: c.upstream_socks5.unwrap_or_default(),
parallel_relay: c.parallel_relay,
show_auth_key: false,
sni_pool,
sni_custom_input: String::new(),
sni_editor_open: false,
show_log: true,
fetch_ips_from_api: c.fetch_ips_from_api,
max_ips_to_scan: c.max_ips_to_scan,
google_ip_validation: c.google_ip_validation,
scan_batch_size: c.scan_batch_size,
normalize_x_graphql: c.normalize_x_graphql,
youtube_via_relay: c.youtube_via_relay,
passthrough_hosts: c.passthrough_hosts.clone(),
block_quic: c.block_quic,
block_stun: c.block_stun,
disable_padding: c.disable_padding,
force_http1: c.force_http1,
tunnel_doh: c.tunnel_doh,
bypass_doh_hosts: c.bypass_doh_hosts.clone(),
block_doh: c.block_doh,
fronting_groups: c.fronting_groups.clone(),
auto_blacklist_strikes: c.auto_blacklist_strikes,
auto_blacklist_window_secs: c.auto_blacklist_window_secs,
auto_blacklist_cooldown_secs: c.auto_blacklist_cooldown_secs,
request_timeout_secs: c.request_timeout_secs,
stream_timeout_secs: c.stream_timeout_secs,
exit_node: c.exit_node.clone(),
}
} else {
FormState {
mode: "apps_script".into(),
script_id: String::new(),
auth_key: String::new(),
google_ip: "216.239.38.120".into(),
front_domain: "www.google.com".into(),
listen_host: "127.0.0.1".into(),
listen_port: "8085".into(),
socks5_port: "8086".into(),
log_level: "info".into(),
verify_ssl: true,
upstream_socks5: String::new(),
parallel_relay: 0,
show_auth_key: false,
sni_pool: sni_pool_for_form(None, "www.google.com"),
sni_custom_input: String::new(),
sni_editor_open: false,
show_log: true,
fetch_ips_from_api: false,
max_ips_to_scan: 100,
google_ip_validation: true,
scan_batch_size: 500,
normalize_x_graphql: false,
youtube_via_relay: false,
passthrough_hosts: Vec::new(),
block_quic: true,
block_stun: false,
disable_padding: false,
force_http1: false,
tunnel_doh: true,
bypass_doh_hosts: Vec::new(),
block_doh: true,
fronting_groups: Vec::new(),
// Defaults match `default_auto_blacklist_*` and
// `default_request_timeout_secs` in src/config.rs.
auto_blacklist_strikes: 3,
auto_blacklist_window_secs: 30,
auto_blacklist_cooldown_secs: 120,
request_timeout_secs: 30,
stream_timeout_secs: 300,
exit_node: mhrv_rs::config::ExitNodeConfig::default(),
}
};
(form, load_err)
}
/// Build the initial `sni_pool` list shown in the editor.
///
/// If the user has explicit `sni_hosts` configured, we show exactly those
/// rows (all enabled). Otherwise we show the default Google pool plus any
/// missing entries, all enabled, with the user's `front_domain` first.
fn sni_pool_for_form(user: Option<&[String]>, front_domain: &str) -> Vec<SniRow> {
let user_clean: Vec<String> = user
.unwrap_or(&[])
.iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if !user_clean.is_empty() {
return user_clean
.into_iter()
.map(|name| SniRow {
name,
enabled: true,
})
.collect();
}
// Default: primary + the other Google-edge subdomains, primary first,
// all enabled.
let primary = front_domain.trim().to_string();
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
if !primary.is_empty() {
seen.insert(primary.clone());
out.push(SniRow {
name: primary,
enabled: true,
});
}
for s in DEFAULT_GOOGLE_SNI_POOL {
if seen.insert(s.to_string()) {
out.push(SniRow {
name: (*s).to_string(),
enabled: true,
});
}
}
out
}
impl FormState {
fn to_config(&self) -> Result<Config, String> {
// `direct` and the legacy `google_only` alias both run without
// an Apps Script relay, so neither requires a script_id.
let is_direct = self.mode == "direct" || self.mode == "google_only";
if !is_direct {
if self.script_id.trim().is_empty() {
return Err("Apps Script ID is required".into());
}
if self.auth_key.trim().is_empty() {
return Err("Auth key is required".into());
}
}
let listen_port: u16 = self
.listen_port
.parse()
.map_err(|_| "HTTP port must be a number".to_string())?;
let socks5_port: Option<u16> = if self.socks5_port.trim().is_empty() {
None
} else {
Some(
self.socks5_port
.parse()
.map_err(|_| "SOCKS5 port must be a number".to_string())?,
)
};
if socks5_port == Some(listen_port) {
return Err("HTTP and SOCKS5 ports must be different".into());
}
let ids: Vec<String> = self
.script_id
.split(|c: char| c == '\n' || c == ',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
let script_id = if ids.is_empty() {
None
} else if ids.len() == 1 {
Some(ScriptId::One(ids[0].clone()))
} else {
Some(ScriptId::Many(ids))
};
Ok(Config {
mode: self.mode.clone(),
google_ip: self.google_ip.trim().to_string(),
front_domain: self.front_domain.trim().to_string(),
script_id,
script_ids: None,
auth_key: self.auth_key.clone(),
listen_host: self.listen_host.trim().to_string(),
listen_port,
socks5_port,
log_level: self.log_level.trim().to_string(),
verify_ssl: self.verify_ssl,
hosts: std::collections::HashMap::new(),
enable_batching: false,
upstream_socks5: {
let v = self.upstream_socks5.trim();
if v.is_empty() {
None
} else {
Some(v.to_string())
}
},
parallel_relay: self.parallel_relay,
sni_hosts: {
let active: Vec<String> = self
.sni_pool
.iter()
.filter(|r| r.enabled)
.map(|r| r.name.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
// None = "use auto-expansion default", Some(list) = explicit.
// If the user's pool is empty/all-off we still save as None so
// the backend falls back to sensible defaults instead of dying
// on an empty pool.
if active.is_empty() {
None
} else {
Some(active)
}
},
fetch_ips_from_api: self.fetch_ips_from_api,
max_ips_to_scan: self.max_ips_to_scan,
google_ip_validation: self.google_ip_validation,
scan_batch_size: self.scan_batch_size,
normalize_x_graphql: self.normalize_x_graphql,
// UI form doesn't expose youtube_via_relay yet — it's a
// config-only flag for now. Passed through from the loaded
// config if set, otherwise defaults to false.
youtube_via_relay: self.youtube_via_relay,
// Similarly config-only for now; round-trips through the
// file so the UI doesn't drop the user's entries on save.
passthrough_hosts: self.passthrough_hosts.clone(),
// Issue #213: block_quic is config-only for now (no UI
// control yet). Round-trip through the file so save
// doesn't drop a user-set true.
block_quic: self.block_quic,
block_stun: self.block_stun,
// Issue #391: disable_padding is config-only for now.
// Round-trip preserves the user's choice.
disable_padding: self.disable_padding,
// HTTP/2 multiplexing kill switch. Config-only for now;
// round-trip preserves the user's choice across Save.
force_http1: self.force_http1,
// DoH bypass is enabled-by-default with `tunnel_doh = false`.
// Round-trip the user's choice (and any extra hostnames they
// added) so save doesn't drop them.
tunnel_doh: self.tunnel_doh,
bypass_doh_hosts: self.bypass_doh_hosts.clone(),
// PR #763: block_doh defaults to true (rejects browser DoH so
// tun2proxy's virtual DNS handles name lookups, saving the
// ~1.5s tunnel round-trip per DNS query). Desktop UI doesn't
// expose a toggle yet (Android does), so this is a config-only
// round-trip — we keep whatever the user has in config.toml.
block_doh: self.block_doh,
// Multi-edge fronting groups: file-edited only for now,
// round-tripped through the UI so Save doesn't drop them.
fronting_groups: self.fronting_groups.clone(),
// PR #448 (Android): adaptive coalesce window. Desktop UI
// doesn't expose sliders for these yet (Android does), so
// we pass 0 to keep the compiled defaults (40ms step,
// 1000ms max). Round-trip planned for the v1.8.x desktop UI
// batch alongside the system-proxy toggle (#432).
coalesce_step_ms: 0,
coalesce_max_ms: 0,
// Auto-blacklist + batch timeout: config-only knobs (#391,
// #444, #430). Round-trip through FormState so Save doesn't
// drop hand-edited values. UI editor planned alongside the
// v1.8.x desktop UI batch.
auto_blacklist_strikes: self.auto_blacklist_strikes,
auto_blacklist_window_secs: self.auto_blacklist_window_secs,
auto_blacklist_cooldown_secs: self.auto_blacklist_cooldown_secs,
request_timeout_secs: self.request_timeout_secs,
stream_timeout_secs: self.stream_timeout_secs,
// Exit-node config (CF-anti-bot bypass for chatgpt.com / claude.ai
// / grok.com / x.com). Round-trip through FormState — config-only
// editing for now, UI editor planned for v1.9.x desktop UI batch.
exit_node: self.exit_node.clone(),
})
}
}
fn save_config(cfg: &Config) -> Result<PathBuf, String> {
let path = data_dir::config_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let toml_str = toml::to_string_pretty(&mhrv_rs::config::TomlConfig::from(cfg))
.map_err(|e| e.to_string())?;
std::fs::write(&path, toml_str).map_err(|e| e.to_string())?;
Ok(path)
}
#[derive(serde::Serialize)]
struct ConfigWire<'a> {
mode: &'a str,
google_ip: &'a str,
front_domain: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
script_id: Option<ScriptIdWire<'a>>,
auth_key: &'a str,
listen_host: &'a str,
listen_port: u16,
#[serde(skip_serializing_if = "Option::is_none")]
socks5_port: Option<u16>,
log_level: &'a str,
verify_ssl: bool,
#[serde(skip_serializing_if = "std::collections::HashMap::is_empty")]
hosts: &'a std::collections::HashMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
upstream_socks5: Option<&'a str>,
#[serde(skip_serializing_if = "is_zero_u8")]
parallel_relay: u8,
#[serde(skip_serializing_if = "Option::is_none")]
sni_hosts: Option<Vec<&'a str>>,
#[serde(skip_serializing_if = "is_false")]
normalize_x_graphql: bool,
#[serde(skip_serializing_if = "is_false")]
youtube_via_relay: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
passthrough_hosts: &'a Vec<String>,
// IP-scan knobs. These used to be missing from the wire struct, so
// every Save-config silently dropped them — the user would toggle
// "fetch from API" on, save, reopen, and find it off again. Add
// them here and keep them in sync if Config ever grows more.
#[serde(skip_serializing_if = "is_false")]
fetch_ips_from_api: bool,
max_ips_to_scan: usize,
scan_batch_size: usize,
google_ip_validation: bool,
/// Default false (= bypass DoH). Only emitted when explicitly true
/// so unchanged configs stay clean.
#[serde(skip_serializing_if = "is_false")]
tunnel_doh: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
bypass_doh_hosts: &'a Vec<String>,
/// PR #763: default true (= browser DoH rejected, system DNS used).
/// Skip when matching default to keep unchanged configs clean —
/// emit only when the user has explicitly disabled the block.
#[serde(skip_serializing_if = "is_true")]
block_doh: bool,
/// Default false. Emit only when the user enables STUN/TURN blocking.
#[serde(skip_serializing_if = "is_false")]
block_stun: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
fronting_groups: &'a Vec<FrontingGroup>,
/// Auto-blacklist tuning + batch timeout (#391, #444, #430). Skip
/// serialization when matching the historical defaults so unchanged
/// configs stay clean — only emitted when the user has explicitly
/// tuned them.
#[serde(skip_serializing_if = "is_default_strikes")]
auto_blacklist_strikes: u32,
#[serde(skip_serializing_if = "is_default_window_secs")]
auto_blacklist_window_secs: u64,
#[serde(skip_serializing_if = "is_default_cooldown_secs")]
auto_blacklist_cooldown_secs: u64,
#[serde(skip_serializing_if = "is_default_timeout_secs")]
request_timeout_secs: u64,
#[serde(skip_serializing_if = "is_default_stream_timeout_secs")]
stream_timeout_secs: u64,
/// HTTP/2 multiplexing kill switch. Default false (h2 active); only
/// emitted on save when the user has explicitly disabled h2, so
/// unchanged configs stay clean.
#[serde(skip_serializing_if = "is_false")]
force_http1: bool,
/// Exit-node config (CF-anti-bot bypass for chatgpt.com / claude.ai /
/// grok.com / x.com via exit-node second-hop relay). Skip when fully
/// default (disabled with no URL/PSK/hosts) so configs without
/// exit-node setup stay clean. Round-tripped through FormState so
/// Save preserves user-edited values.
#[serde(skip_serializing_if = "is_default_exit_node")]
exit_node: &'a mhrv_rs::config::ExitNodeConfig,
}
fn is_default_strikes(v: &u32) -> bool { *v == 3 }
fn is_default_window_secs(v: &u64) -> bool { *v == 30 }
fn is_default_cooldown_secs(v: &u64) -> bool { *v == 120 }
fn is_default_timeout_secs(v: &u64) -> bool { *v == 30 }
fn is_default_stream_timeout_secs(v: &u64) -> bool { *v == 300 }
fn is_default_exit_node(en: &&mhrv_rs::config::ExitNodeConfig) -> bool {
!en.enabled
&& en.relay_url.is_empty()
&& en.psk.is_empty()
&& en.hosts.is_empty()
&& (en.mode.is_empty() || en.mode == "selective")
}
fn is_false(b: &bool) -> bool {
!*b
}
fn is_true(b: &bool) -> bool {
*b
}
fn is_zero_u8(v: &u8) -> bool {
*v == 0
}
#[derive(serde::Serialize)]
#[serde(untagged)]
enum ScriptIdWire<'a> {
One(&'a str),
Many(Vec<&'a str>),
}
impl<'a> From<&'a Config> for ConfigWire<'a> {
fn from(c: &'a Config) -> Self {
let script_id = c.script_id.as_ref().map(|s| match s {
ScriptId::One(v) => ScriptIdWire::One(v.as_str()),
ScriptId::Many(v) => ScriptIdWire::Many(v.iter().map(String::as_str).collect()),
});
ConfigWire {
mode: c.mode.as_str(),
google_ip: c.google_ip.as_str(),
front_domain: c.front_domain.as_str(),
script_id,
auth_key: c.auth_key.as_str(),
listen_host: c.listen_host.as_str(),
listen_port: c.listen_port,
socks5_port: c.socks5_port,
log_level: c.log_level.as_str(),
verify_ssl: c.verify_ssl,
hosts: &c.hosts,
upstream_socks5: c.upstream_socks5.as_deref(),
parallel_relay: c.parallel_relay,
sni_hosts: c
.sni_hosts
.as_ref()
.map(|v| v.iter().map(String::as_str).collect()),
normalize_x_graphql: c.normalize_x_graphql,
youtube_via_relay: c.youtube_via_relay,
passthrough_hosts: &c.passthrough_hosts,
fetch_ips_from_api: c.fetch_ips_from_api,
max_ips_to_scan: c.max_ips_to_scan,
scan_batch_size: c.scan_batch_size,
google_ip_validation: c.google_ip_validation,
tunnel_doh: c.tunnel_doh,
bypass_doh_hosts: &c.bypass_doh_hosts,
block_doh: c.block_doh,
block_stun: c.block_stun,
fronting_groups: &c.fronting_groups,
auto_blacklist_strikes: c.auto_blacklist_strikes,
auto_blacklist_window_secs: c.auto_blacklist_window_secs,
auto_blacklist_cooldown_secs: c.auto_blacklist_cooldown_secs,
request_timeout_secs: c.request_timeout_secs,
stream_timeout_secs: c.stream_timeout_secs,
force_http1: c.force_http1,
exit_node: &c.exit_node,
}
}
}
/// Accent color — same blue used throughout the UI for primary actions.
const ACCENT: egui::Color32 = egui::Color32::from_rgb(70, 120, 180);
const ACCENT_HOVER: egui::Color32 = egui::Color32::from_rgb(90, 145, 205);
const OK_GREEN: egui::Color32 = egui::Color32::from_rgb(80, 180, 100);
const ERR_RED: egui::Color32 = egui::Color32::from_rgb(220, 110, 110);
/// Draw a "section card" — a rounded frame with a faint fill and a small
/// heading above it. Used to visually group related form rows.
fn section(ui: &mut egui::Ui, title: &str, body: impl FnOnce(&mut egui::Ui)) {
ui.add_space(6.0);
ui.label(
egui::RichText::new(title)
.size(12.0)
.color(egui::Color32::from_gray(180))
.strong(),
);
ui.add_space(2.0);
let frame = egui::Frame::none()
.fill(egui::Color32::from_rgb(28, 30, 34))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(50, 54, 60)))
.rounding(6.0)
.inner_margin(egui::Margin::same(10.0));
frame.show(ui, body);
}
/// A primary accent-filled button. Used for the headline action in a row
/// (Start / Stop / SNI pool).
fn primary_button(text: &str) -> egui::Button<'_> {
egui::Button::new(
egui::RichText::new(text)
.color(egui::Color32::WHITE)
.strong(),
)
.fill(ACCENT)
.min_size(egui::vec2(120.0, 28.0))
.rounding(4.0)
}
/// A compact form row: label on the left (fixed width for vertical alignment),
/// widget on the right filling the remaining space.
fn form_row(
ui: &mut egui::Ui,
label: &str,
hover: Option<&str>,
widget: impl FnOnce(&mut egui::Ui, egui::Id),
) {
ui.horizontal(|ui| {
let resp = ui.add_sized(
[120.0, 20.0],
egui::Label::new(egui::RichText::new(label).color(egui::Color32::from_gray(200))),
);
let label_id = resp.id;
if let Some(h) = hover {
resp.on_hover_text(h);
}
widget(ui, label_id);
});
}
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
if self.last_poll.elapsed() > Duration::from_millis(700) {
let _ = self.cmd_tx.send(Cmd::PollStats);
self.last_poll = Instant::now();
}
ctx.request_repaint_after(Duration::from_millis(500));
egui::CentralPanel::default().show(ctx, |ui| {
ui.style_mut().spacing.item_spacing = egui::vec2(8.0, 6.0);
// Wrap the whole central panel in a vertical scroll area so the
// form + stats + log panel stay accessible on short screens
// (~13" laptops at default scaling). Nested scroll areas still
// work fine within this outer scroller.
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.show(ui, |ui| {
// ── Header row: project name, version (→ github), status pill ─
let running = self.shared.state.lock().unwrap().running;
ui.horizontal(|ui| {
ui.hyperlink_to(
egui::RichText::new("mhrv-rs").size(20.0).strong(),
"https://github.com/therealaleph/MasterHttpRelayVPN-RUST",
);
ui.hyperlink_to(
egui::RichText::new(format!("v{}", VERSION))
.color(egui::Color32::from_gray(140))
.monospace(),
format!(
"https://github.com/therealaleph/MasterHttpRelayVPN-RUST/releases/tag/v{}",
VERSION
),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (fill, dot, label) = if running {
(
egui::Color32::from_rgb(30, 60, 40),
OK_GREEN,
"running",
)
} else {
(
egui::Color32::from_rgb(60, 35, 35),
ERR_RED,
"stopped",
)
};
egui::Frame::none()
.fill(fill)
.rounding(12.0)
.inner_margin(egui::Margin::symmetric(10.0, 3.0))
.show(ui, |ui| {
ui.horizontal(|ui| {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(8.0, 8.0),
egui::Sense::hover(),
);
ui.painter().circle_filled(rect.center(), 4.0, dot);
ui.label(
egui::RichText::new(label)
.color(dot)
.monospace()
.strong(),
);
});
});
});
});
ui.add_space(2.0);
// ── Section: Mode ─────────────────────────────────────────────
// Surfacing the mode at the top of the form because it changes
// which of the sections below are actually used. `direct` runs
// without the Apps Script relay (Google edge + any configured
// fronting_groups via the SNI-rewrite tunnel only) — useful as
// a bootstrap to deploy Code.gs, or as a standalone mode for
// users who only need access to fronting-group targets.
section(ui, "Mode", |ui| {
form_row(ui, "Mode", Some(
"apps_script: DPI bypass via Apps Script relay (needs cert).\n\
full: tunnel ALL traffic through Apps Script + tunnel node (no cert needed).\n\
direct: SNI-rewrite tunnel only — no relay (Google edge + any fronting_groups)."
), |ui, _label_id| {
egui::ComboBox::from_id_source("mode")
.selected_text(match self.form.mode.as_str() {
"direct" | "google_only" => "Direct (no relay)",
"full" => "Full tunnel (no cert)",
_ => "Apps Script (MITM)",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.form.mode,
"apps_script".into(),
"Apps Script (MITM)",
);
ui.selectable_value(
&mut self.form.mode,
"full".into(),
"Full tunnel (no cert)",
);
ui.selectable_value(
&mut self.form.mode,
"direct".into(),
"Direct (no relay)",
);
});
});
if self.form.mode == "direct" || self.form.mode == "google_only" {
ui.horizontal(|ui| {
ui.add_space(120.0 + 8.0);
ui.small(egui::RichText::new(
"Direct mode — SNI-rewrite tunnel only. Reach the Google edge (and any configured fronting_groups) without an Apps Script relay.",
)
.color(OK_GREEN));
});
}
if self.form.mode == "full" {
ui.horizontal(|ui| {
ui.add_space(120.0 + 8.0);
ui.small(egui::RichText::new(
"Full tunnel — all traffic tunneled end-to-end via Apps Script + remote tunnel node. No certificate needed.",
)
.color(OK_GREEN));
});
}
});
let direct_mode = self.form.mode == "direct" || self.form.mode == "google_only";
// ── Section: Apps Script relay ────────────────────────────────
section(ui, "Apps Script relay", |ui| {
ui.add_enabled_ui(!direct_mode, |ui| {
form_row(ui, "Deployment IDs", Some(
"One deployment ID per line. Proxy round-robins between them and sidelines \
any ID that hits its daily quota for 10 minutes before retrying."