forked from therealaleph/MasterHttpRelayVPN-RUST
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
2144 lines (1955 loc) · 83.6 KB
/
Copy pathmain.rs
File metadata and controls
2144 lines (1955 loc) · 83.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
//! HTTP Tunnel Node for MasterHttpRelayVPN "full" mode.
//!
//! Bridges HTTP tunnel requests (from Apps Script) to real TCP connections.
//! Supports both single-op (`POST /tunnel`) and batch (`POST /tunnel/batch`)
//! modes. Batch mode processes all active sessions in one HTTP round trip,
//! dramatically reducing the number of Apps Script calls.
//!
//! Env vars:
//! TUNNEL_AUTH_KEY — shared secret (required)
//! PORT — listen port (default 8080, Cloud Run sets this)
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::body::Bytes;
use axum::extract::State;
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use axum::{routing::post, Json, Router};
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
use tokio::net::tcp::OwnedWriteHalf;
use tokio::net::{lookup_host, TcpStream, UdpSocket};
use tokio::sync::{mpsc, Mutex, Notify};
use tokio::task::JoinSet;
mod udpgw;
/// Structured error code returned when the tunnel-node receives an op it
/// doesn't recognize. Clients use this (rather than string-matching `e`) to
/// detect a version mismatch and gracefully fall back.
const CODE_UNSUPPORTED_OP: &str = "UNSUPPORTED_OP";
/// Drain-phase deadline when the batch contained writes or new
/// connections. We expect upstream servers to respond fast (TLS
/// ServerHello, HTTP response) so this is a ceiling for slow targets;
/// `wait_for_any_drainable` returns much sooner — usually within
/// milliseconds — once any session in the batch fires its notify.
const ACTIVE_DRAIN_DEADLINE: Duration = Duration::from_millis(350);
/// Adaptive straggler settle: after the first session in an active batch
/// wakes the drain, keep checking in STEP increments whether new data is
/// still arriving. Stops when no new data arrived in the last STEP (the
/// burst is over) or MAX is reached. Packing more session responses into
/// one batch saves quota on high-latency relays (~1.5s Apps Script overhead).
const STRAGGLER_SETTLE_STEP: Duration = Duration::from_millis(40);
const STRAGGLER_SETTLE_MAX: Duration = Duration::from_millis(500);
/// Drain-phase deadline when the batch is a pure poll (no writes, no new
/// connections — clients just asking "any push data?"). Holding the
/// response open delivers server-initiated bytes (push notifications,
/// chat messages, server-sent events) within roughly one RTT instead of
/// waiting for the client's next tick.
///
/// **This is a knob, not a constant of nature.** It trades push latency
/// against the worst-case "client wants to send while mid-poll" delay:
/// the tunnel-client's `tunnel_loop` is strictly serial (one in-flight
/// op per session), so any local bytes that arrive while the poll is
/// being held are stuck in the kernel until the poll returns.
///
/// 15 s keeps persistent connections (Telegram XMPP on :5222, Google
/// Push on :5228) alive without forcing frequent reconnects. At 5 s,
/// apps like Telegram interpreted the frequent empty returns as
/// connection instability and rotated sessions — each reconnect costs
/// a full TLS handshake (~4 s through Apps Script), causing visible
/// video/voice interruptions. 15 s is well below the client's
/// `BATCH_TIMEOUT` (30 s) and Apps Script's UrlFetch ceiling (~60 s).
/// Tested on censored networks in Iran where users reported smoother
/// Telegram video playback and fewer session resets at this value.
const LONGPOLL_DEADLINE: Duration = Duration::from_secs(15);
/// Bound on each UDP session's inbound queue. Beyond this we drop oldest
/// to keep recent voice/media packets moving — a stale RTP frame is
/// worse than a missing one. Sized so a 256-deep queue at typical 1500B
/// payloads is ~384 KB before backpressure kicks in.
const UDP_QUEUE_LIMIT: usize = 256;
/// Receive buffer for the UDP reader task. Must be ≥ 65535 to handle
/// a maximum-size IPv4 datagram without truncation.
const UDP_RECV_BUF_BYTES: usize = 65536;
/// First queue-drop on a session always logs at warn level; subsequent
/// drops log at debug only every Nth occurrence so a single congested
/// session can't flood the operator's log.
const UDP_QUEUE_DROP_LOG_STRIDE: u64 = 100;
// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------
/// Writer half — either a real TCP socket or an in-process duplex channel
/// (used for virtual sessions like udpgw).
enum SessionWriter {
Tcp(OwnedWriteHalf),
Duplex(tokio::io::WriteHalf<tokio::io::DuplexStream>),
}
impl SessionWriter {
async fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
match self {
SessionWriter::Tcp(w) => w.write_all(buf).await,
SessionWriter::Duplex(w) => w.write_all(buf).await,
}
}
async fn flush(&mut self) -> std::io::Result<()> {
match self {
SessionWriter::Tcp(w) => w.flush().await,
SessionWriter::Duplex(w) => w.flush().await,
}
}
}
struct SessionInner {
writer: Mutex<SessionWriter>,
read_buf: Mutex<Vec<u8>>,
eof: AtomicBool,
last_active: Mutex<Instant>,
/// Fired by `reader_task` whenever new bytes land in `read_buf` or the
/// upstream socket closes. `wait_for_any_drainable` listens on this
/// to wake the drain phase as soon as any session has something to
/// ship, replacing the old fixed-sleep heuristic.
notify: Notify,
}
struct ManagedSession {
inner: Arc<SessionInner>,
reader_handle: tokio::task::JoinHandle<()>,
/// For udpgw sessions, the server task handle (so we can abort on close).
udpgw_handle: Option<tokio::task::JoinHandle<()>>,
}
impl ManagedSession {
fn abort_all(&self) {
self.reader_handle.abort();
if let Some(ref h) = self.udpgw_handle {
h.abort();
}
}
}
/// UDP equivalent of `SessionInner`. Holds a *connected* `UdpSocket`
/// pinned to one `(host, port)` upstream so we don't have to re-resolve
/// or re-parse the destination on every datagram. `notify` is fired by
/// the reader task on each inbound datagram (or on socket error) so the
/// batch drain phase can wake without polling — same primitive as the
/// TCP path.
struct UdpSessionInner {
socket: Arc<UdpSocket>,
packets: Mutex<VecDeque<Vec<u8>>>,
last_active: Mutex<Instant>,
notify: Notify,
/// Set when the upstream socket dies (recv error). Mirrors TCP's
/// `eof`: once true, subsequent batch drains return `eof: Some(true)`
/// so the proxy-side session task knows to exit instead of polling
/// a zombie session until the 120 s idle reaper kills it.
eof: AtomicBool,
/// Total datagrams dropped because the queue hit `UDP_QUEUE_LIMIT`.
/// Surfaced via tracing so operators can correlate "choppy call"
/// reports with relay backpressure.
queue_drops: AtomicU64,
}
struct ManagedUdpSession {
inner: Arc<UdpSessionInner>,
reader_handle: tokio::task::JoinHandle<()>,
}
async fn create_session(host: &str, port: u16) -> std::io::Result<ManagedSession> {
let addr = format!("{}:{}", host, port);
let stream = tokio::time::timeout(Duration::from_secs(10), TcpStream::connect(&addr))
.await
.map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "connect timeout"))??;
let _ = stream.set_nodelay(true);
let (reader, writer) = stream.into_split();
let inner = Arc::new(SessionInner {
writer: Mutex::new(SessionWriter::Tcp(writer)),
read_buf: Mutex::new(Vec::with_capacity(32768)),
eof: AtomicBool::new(false),
last_active: Mutex::new(Instant::now()),
notify: Notify::new(),
});
let inner_ref = inner.clone();
let reader_handle = tokio::spawn(reader_task(reader, inner_ref));
Ok(ManagedSession { inner, reader_handle, udpgw_handle: None })
}
/// Create a virtual udpgw session backed by an in-process duplex channel.
fn create_udpgw_session() -> ManagedSession {
let (client_half, server_half) = tokio::io::duplex(65536);
let (read_half, write_half) = tokio::io::split(client_half);
let inner = Arc::new(SessionInner {
writer: Mutex::new(SessionWriter::Duplex(write_half)),
read_buf: Mutex::new(Vec::with_capacity(32768)),
eof: AtomicBool::new(false),
last_active: Mutex::new(Instant::now()),
notify: Notify::new(),
});
let inner_ref = inner.clone();
let reader_handle = tokio::spawn(reader_task(read_half, inner_ref));
let udpgw_handle = Some(tokio::spawn(udpgw::udpgw_server_task(server_half)));
ManagedSession { inner, reader_handle, udpgw_handle }
}
async fn reader_task(mut reader: impl AsyncRead + Unpin, session: Arc<SessionInner>) {
let mut buf = vec![0u8; 65536];
loop {
match reader.read(&mut buf).await {
Ok(0) => {
session.eof.store(true, Ordering::Release);
session.notify.notify_one();
break;
}
Ok(n) => {
// Extend the buffer before notifying. The MutexGuard is
// dropped at the end of the statement, *before* the
// notify_one call below, so any waiter that wakes on the
// notify and then locks read_buf can immediately observe
// the new bytes — no torn read where the wake fires but
// the buffer still looks empty. Notify::notify_one also
// stores a permit if no waiter is currently registered,
// so we never lose an edge across the spawn race in
// wait_for_any_drainable.
session.read_buf.lock().await.extend_from_slice(&buf[..n]);
session.notify.notify_one();
}
Err(_) => {
session.eof.store(true, Ordering::Release);
session.notify.notify_one();
break;
}
}
}
}
async fn create_udp_session(host: &str, port: u16) -> std::io::Result<ManagedUdpSession> {
let mut addrs = lookup_host((host, port)).await?;
let remote = addrs.next().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::AddrNotAvailable,
"no UDP address resolved",
)
})?;
let bind_addr = if remote.is_ipv4() {
"0.0.0.0:0"
} else {
"[::]:0"
};
let socket = UdpSocket::bind(bind_addr).await?;
socket.connect(remote).await?;
let socket = Arc::new(socket);
let inner = Arc::new(UdpSessionInner {
socket: socket.clone(),
packets: Mutex::new(VecDeque::with_capacity(UDP_QUEUE_LIMIT)),
last_active: Mutex::new(Instant::now()),
notify: Notify::new(),
eof: AtomicBool::new(false),
queue_drops: AtomicU64::new(0),
});
let inner_ref = inner.clone();
let reader_handle = tokio::spawn(udp_reader_task(socket, inner_ref));
Ok(ManagedUdpSession {
inner,
reader_handle,
})
}
/// UDP analogue of `reader_task`. Reads from the connected UDP socket
/// and queues each datagram on the session. Drops oldest on overflow,
/// updates `last_active` so server-push (download-only) UDP keeps the
/// session out of the idle reaper, and fires `notify` so the batch
/// drain phase can wake without polling.
async fn udp_reader_task(socket: Arc<UdpSocket>, session: Arc<UdpSessionInner>) {
let mut buf = vec![0u8; UDP_RECV_BUF_BYTES];
loop {
match socket.recv(&mut buf).await {
// Empty datagram is valid UDP; nothing to forward, ignore.
Ok(0) => {}
Ok(n) => {
let mut packets = session.packets.lock().await;
if packets.len() >= UDP_QUEUE_LIMIT {
packets.pop_front();
let dropped = session.queue_drops.fetch_add(1, Ordering::Relaxed) + 1;
if dropped == 1 {
tracing::warn!(
"udp queue full ({}); dropping oldest. Apps Script polling cannot keep up with upstream rate.",
UDP_QUEUE_LIMIT
);
} else if dropped % UDP_QUEUE_DROP_LOG_STRIDE == 0 {
tracing::debug!("udp queue drops: {} on session", dropped);
}
}
packets.push_back(buf[..n].to_vec());
drop(packets);
// Inbound packet counts as activity — keeps server-push
// UDP (e.g. SIP/RTP, server-sent telemetry) out of the
// idle reaper. Empty `udp_data` polls deliberately do
// NOT bump this (see batch handler).
*session.last_active.lock().await = Instant::now();
session.notify.notify_one();
}
Err(e) => {
// Upstream socket died (ICMP unreachable on a connected
// socket, container netns torn down, etc.). Surface eof
// so the proxy-side session task can exit on its next
// poll instead of looping until the idle reaper.
tracing::debug!("udp upstream recv error: {} — marking session eof", e);
session.eof.store(true, Ordering::Release);
session.notify.notify_one();
break;
}
}
}
}
/// Drain whatever is currently buffered — no waiting.
/// Used by batch mode where we poll frequently.
async fn drain_now(session: &SessionInner) -> (Vec<u8>, bool) {
let mut buf = session.read_buf.lock().await;
let data = std::mem::take(&mut *buf);
let eof = session.eof.load(Ordering::Acquire);
(data, eof)
}
/// Block until *any* of `inners` has buffered data, hits EOF, or the
/// deadline elapses — whichever comes first. Returns immediately if any
/// session is already drainable when called.
///
/// This replaces the legacy `sleep(150ms)` + `sleep(200ms)` retry pattern
/// in batch drain. With `reader_task` firing `notify_one` on each
/// appended chunk, a typical TLS ServerHello (~30-50 ms) wakes the wait
/// in milliseconds instead of paying the 150 ms ceiling. For pure-poll
/// batches the same primitive holds the response open until upstream
/// pushes data or `LONGPOLL_DEADLINE` elapses, turning idle sessions
/// into a true long-poll.
///
/// Race-safety:
/// * `Notify::notify_one` stores a one-shot permit if no waiter is
/// registered, so a notify that fires between the buffer check and
/// the watcher's `.notified().await` is consumed on the next poll
/// rather than lost.
/// * Watchers self-filter against observable session state. A prior
/// batch that returned via the spawn-race shortcut may leave a
/// stale permit on the `Notify`; this batch's watcher will consume
/// it but, finding the buffer empty and EOF unset, loop back to
/// wait for a real notify. Without this filter, an idle long-poll
/// batch could return in <1 ms on a stale permit and degrade push
/// delivery to the client's idle re-poll cadence.
async fn wait_for_any_drainable(inners: &[Arc<SessionInner>], deadline: Duration) {
if inners.is_empty() {
return;
}
// One watcher per session. Each loops until it observes real state
// (eof set or buffer non-empty) before signaling — see the
// race-safety note on `wait_for_any_drainable` for why. We abort the
// watchers on return; the only state they hold is a notify
// subscription, so abort is clean.
let (tx, mut rx) = mpsc::channel::<()>(1);
let mut watchers = Vec::with_capacity(inners.len());
for inner in inners {
let inner = inner.clone();
let tx = tx.clone();
watchers.push(tokio::spawn(async move {
loop {
inner.notify.notified().await;
if inner.eof.load(Ordering::Acquire) {
break;
}
if !inner.read_buf.lock().await.is_empty() {
break;
}
// Stale permit (notify fired but state didn't change in
// an observable way — e.g., bytes were already drained
// by a prior batch). Loop back and wait for a real
// notify, don't wake the caller.
}
let _ = tx.try_send(());
}));
}
drop(tx);
// Spawn-race shortcut: if state was already drainable when we got
// here (bytes arrived between phase 1 and this point), return
// without entering the select. The watcher self-filtering above
// means the unconsumed permit we leave behind here is harmless to
// future batches.
let already_ready = is_any_drainable(inners).await;
if !already_ready {
tokio::select! {
_ = rx.recv() => {}
_ = tokio::time::sleep(deadline) => {}
}
}
for w in &watchers {
w.abort();
}
}
/// True iff any session is currently drainable: its read buffer has
/// bytes, or it's been marked EOF. Pulled out of `wait_for_any_drainable`
/// so the same predicate can drive both the spawn-race shortcut and the
/// post-wake straggler poll.
async fn is_any_drainable(inners: &[Arc<SessionInner>]) -> bool {
for inner in inners {
if inner.eof.load(Ordering::Acquire) {
return true;
}
if !inner.read_buf.lock().await.is_empty() {
return true;
}
}
false
}
/// Drain whatever UDP datagrams are currently queued — no waiting.
/// Returns the eof flag alongside packets so the batch handler can
/// surface upstream-socket death without an extra round-trip.
async fn drain_udp_now(session: &UdpSessionInner) -> (Vec<Vec<u8>>, bool) {
let mut packets = session.packets.lock().await;
let drained: Vec<Vec<u8>> = packets.drain(..).collect();
let eof = session.eof.load(Ordering::Acquire);
(drained, eof)
}
/// UDP analogue of `wait_for_any_drainable`. Wakes when any session has
/// at least one queued packet OR has been marked eof. Same race-safety
/// contract: watchers self-filter against observable state to ignore
/// stale permits.
async fn wait_for_any_udp_drainable(inners: &[Arc<UdpSessionInner>], deadline: Duration) {
if inners.is_empty() {
return;
}
let (tx, mut rx) = mpsc::channel::<()>(1);
let mut watchers = Vec::with_capacity(inners.len());
for inner in inners {
let inner = inner.clone();
let tx = tx.clone();
watchers.push(tokio::spawn(async move {
loop {
inner.notify.notified().await;
if inner.eof.load(Ordering::Acquire) {
break;
}
if !inner.packets.lock().await.is_empty() {
break;
}
// Stale permit — packets were already drained by a
// prior batch. Loop back, don't wake the caller.
}
let _ = tx.try_send(());
}));
}
drop(tx);
let already_ready = is_any_udp_drainable(inners).await;
if !already_ready {
tokio::select! {
_ = rx.recv() => {}
_ = tokio::time::sleep(deadline) => {}
}
}
for w in &watchers {
w.abort();
}
}
async fn is_any_udp_drainable(inners: &[Arc<UdpSessionInner>]) -> bool {
for inner in inners {
if inner.eof.load(Ordering::Acquire) {
return true;
}
if !inner.packets.lock().await.is_empty() {
return true;
}
}
false
}
/// Wait for response data with drain window. Used by single-op mode.
async fn wait_and_drain(session: &SessionInner, max_wait: Duration) -> (Vec<u8>, bool) {
let deadline = Instant::now() + max_wait;
let mut prev_len = 0usize;
let mut last_growth = Instant::now();
let mut ever_had_data = false;
loop {
let (cur_len, is_eof) = {
let buf = session.read_buf.lock().await;
(buf.len(), session.eof.load(Ordering::Acquire))
};
if cur_len > prev_len {
last_growth = Instant::now();
prev_len = cur_len;
ever_had_data = true;
}
if is_eof { break; }
if Instant::now() >= deadline { break; }
if ever_had_data && last_growth.elapsed() > Duration::from_millis(100) { break; }
tokio::time::sleep(Duration::from_millis(10)).await;
}
let mut buf = session.read_buf.lock().await;
let data = std::mem::take(&mut *buf);
let eof = session.eof.load(Ordering::Acquire);
(data, eof)
}
// ---------------------------------------------------------------------------
// App state
// ---------------------------------------------------------------------------
#[derive(Clone)]
struct AppState {
sessions: Arc<Mutex<HashMap<String, ManagedSession>>>,
udp_sessions: Arc<Mutex<HashMap<String, ManagedUdpSession>>>,
auth_key: String,
/// Active probing defense: when false (default, production), bad
/// AUTH_KEY responses are a generic-looking 404 with no JSON-shaped
/// "unauthorized" body — same as a static nginx 404. Active scanners
/// that POST malformed payloads to `/tunnel` to discover proxy
/// endpoints categorize this as a non-tunnel host and move on.
/// Enable via `MHRV_DIAGNOSTIC=1` for setup/debugging — restores the
/// previous JSON `{"e":"unauthorized"}` body so it's clear *which*
/// of "wrong key", "wrong URL path", or "wrong tunnel-node" you've
/// hit. (Inspired by #365 Section 3.)
diagnostic_mode: bool,
}
// ---------------------------------------------------------------------------
// Protocol types — single op (backward compat)
// ---------------------------------------------------------------------------
#[derive(Deserialize)]
struct TunnelRequest {
k: String,
op: String,
#[serde(default)] host: Option<String>,
#[serde(default)] port: Option<u16>,
#[serde(default)] sid: Option<String>,
#[serde(default)] data: Option<String>,
}
#[derive(Serialize, Clone, Debug)]
struct TunnelResponse {
#[serde(skip_serializing_if = "Option::is_none")] sid: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] d: Option<String>,
/// UDP datagrams returned to the client, base64-encoded individually.
/// `None` for TCP responses; `Some(vec![])` is never serialized
/// (the field is dropped when empty by the empty-on-None check above).
#[serde(skip_serializing_if = "Option::is_none")] pkts: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")] eof: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] e: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] code: Option<String>,
}
impl TunnelResponse {
fn error(msg: impl Into<String>) -> Self {
Self { sid: None, d: None, pkts: None, eof: None, e: Some(msg.into()), code: None }
}
fn unsupported_op(op: &str) -> Self {
Self {
sid: None, d: None, pkts: None, eof: None,
e: Some(format!("unknown op: {}", op)),
code: Some(CODE_UNSUPPORTED_OP.into()),
}
}
}
// ---------------------------------------------------------------------------
// Protocol types — batch
// ---------------------------------------------------------------------------
#[derive(Deserialize)]
struct BatchRequest {
k: String,
ops: Vec<BatchOp>,
}
#[derive(Deserialize)]
struct BatchOp {
op: String,
#[serde(default)] sid: Option<String>,
#[serde(default)] host: Option<String>,
#[serde(default)] port: Option<u16>,
#[serde(default)] d: Option<String>, // base64 data
}
#[derive(Serialize)]
struct BatchResponse {
r: Vec<TunnelResponse>,
}
// ---------------------------------------------------------------------------
// Single-op handler (backward compat)
// ---------------------------------------------------------------------------
async fn handle_tunnel(
State(state): State<AppState>,
Json(req): Json<TunnelRequest>,
) -> axum::response::Response {
if req.k != state.auth_key {
return decoy_or_unauthorized(state.diagnostic_mode);
}
let resp: TunnelResponse = match req.op.as_str() {
"connect" => handle_connect(&state, req.host, req.port).await,
"connect_data" => {
handle_connect_data_single(&state, req.host, req.port, req.data).await
}
"data" => handle_data_single(&state, req.sid, req.data).await,
"close" => handle_close(&state, req.sid).await,
other => TunnelResponse::unsupported_op(other),
};
Json(resp).into_response()
}
/// Active-probing defense for the bad-auth path. Production default is
/// a 404 with a generic "Not Found" HTML body that mimics a vanilla
/// nginx/apache static error page — active scanners categorize this
/// as a regular web server with nothing interesting and move on.
/// `MHRV_DIAGNOSTIC=1` restores the previous JSON `{"e":"unauthorized"}`
/// body so misconfigured clients get a clear error during setup.
fn decoy_or_unauthorized(diagnostic_mode: bool) -> axum::response::Response {
if diagnostic_mode {
return Json(TunnelResponse::error("unauthorized")).into_response();
}
let body = "<html>\r\n<head><title>404 Not Found</title></head>\r\n\
<body>\r\n<center><h1>404 Not Found</h1></center>\r\n\
<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n";
(
StatusCode::NOT_FOUND,
[(header::CONTENT_TYPE, "text/html")],
body,
)
.into_response()
}
// ---------------------------------------------------------------------------
// Batch handler
// ---------------------------------------------------------------------------
async fn handle_batch(
State(state): State<AppState>,
body: Bytes,
) -> impl IntoResponse {
// Decompress if gzipped
let json_bytes = if body.starts_with(&[0x1f, 0x8b]) {
match decompress_gzip(&body) {
Ok(b) => b,
Err(e) => {
let resp = serde_json::to_vec(&BatchResponse {
r: vec![TunnelResponse::error(format!("gzip decode: {}", e))],
}).unwrap_or_default();
return (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], resp);
}
}
} else {
body.to_vec()
};
let req: BatchRequest = match serde_json::from_slice(&json_bytes) {
Ok(r) => r,
Err(e) => {
let resp = serde_json::to_vec(&BatchResponse {
r: vec![TunnelResponse::error(format!("bad json: {}", e))],
}).unwrap_or_default();
return (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], resp);
}
};
if req.k != state.auth_key {
if state.diagnostic_mode {
let resp = serde_json::to_vec(&BatchResponse {
r: vec![TunnelResponse::error("unauthorized")],
}).unwrap_or_default();
return (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], resp);
}
// Production: same nginx-404 decoy as the single-op path. See
// `decoy_or_unauthorized` for rationale.
let body = "<html>\r\n<head><title>404 Not Found</title></head>\r\n\
<body>\r\n<center><h1>404 Not Found</h1></center>\r\n\
<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n"
.as_bytes()
.to_vec();
return (StatusCode::NOT_FOUND, [(header::CONTENT_TYPE, "text/html")], body);
}
// Process all ops in two phases.
//
// Phase 1: dispatch new connections concurrently and write outbound
// bytes for "data" ops. We track whether any op did real work
// (`had_writes_or_connects`) — this drives the deadline picked in
// phase 2.
//
// `connect` and `connect_data` each establish a brand-new upstream TCP
// connection (up to 10 s timeout in `create_session`). Running them
// inline would head-of-line-block every other op in the batch, so we
// dispatch both into a JoinSet and await them concurrently below.
//
// `connect_data` dominates in practice (new clients), but `connect`
// still fires from server-speaks-first ports and from the preread
// timeout fallback path.
let mut results: Vec<(usize, TunnelResponse)> = Vec::with_capacity(req.ops.len());
let mut tcp_drains: Vec<(usize, String)> = Vec::new();
let mut udp_drains: Vec<(usize, String)> = Vec::new();
// True iff the batch contained any op that performed a real action
// upstream — a new connection or a non-empty data write. A batch of
// only empty "data" / "udp_data" polls (and possibly closes) leaves
// this false and qualifies for long-poll behavior in phase 2.
let mut had_writes_or_connects = false;
enum NewConn {
Connect(TunnelResponse),
ConnectData(Result<String, TunnelResponse>),
UdpOpen(Result<String, TunnelResponse>),
}
let mut new_conn_jobs: JoinSet<(usize, NewConn)> = JoinSet::new();
for (i, op) in req.ops.iter().enumerate() {
match op.op.as_str() {
"connect" => {
had_writes_or_connects = true;
let state = state.clone();
let host = op.host.clone();
let port = op.port;
new_conn_jobs.spawn(async move {
(i, NewConn::Connect(handle_connect(&state, host, port).await))
});
}
"connect_data" => {
had_writes_or_connects = true;
let state = state.clone();
let host = op.host.clone();
let port = op.port;
let d = op.d.clone();
new_conn_jobs.spawn(async move {
// Drop the returned Arc<SessionInner>: phase 2 below
// re-looks up each sid under one sessions-map lock,
// which is cheap. The Arc return is a convenience for
// the single-op path only.
let r = handle_connect_data_phase1(&state, host, port, d)
.await
.map(|(sid, _inner)| sid);
(i, NewConn::ConnectData(r))
});
}
"udp_open" => {
// An open *with* an initial datagram is real upstream
// work; an open without one (rare — current proxy
// never invokes it that way) is just resource alloc
// and shouldn't suppress long-poll on sibling polls.
if op.d.as_deref().map(|d| !d.is_empty()).unwrap_or(false) {
had_writes_or_connects = true;
}
let state = state.clone();
let host = op.host.clone();
let port = op.port;
let d = op.d.clone();
new_conn_jobs.spawn(async move {
let r = handle_udp_open_phase1(&state, host, port, d)
.await
.map(|(sid, _inner)| sid);
(i, NewConn::UdpOpen(r))
});
}
"data" => {
let sid = match &op.sid {
Some(s) if !s.is_empty() => s.clone(),
_ => { results.push((i, TunnelResponse::error("missing sid"))); continue; }
};
// Write outbound data
let sessions = state.sessions.lock().await;
if let Some(session) = sessions.get(&sid) {
*session.inner.last_active.lock().await = Instant::now();
if let Some(ref data_b64) = op.d {
if !data_b64.is_empty() {
had_writes_or_connects = true;
if let Ok(bytes) = B64.decode(data_b64) {
if !bytes.is_empty() {
let mut w = session.inner.writer.lock().await;
let _ = w.write_all(&bytes).await;
let _ = w.flush().await;
}
}
}
}
drop(sessions);
tcp_drains.push((i, sid));
} else {
drop(sessions);
results.push((i, eof_response(sid)));
}
}
"udp_data" => {
let sid = match &op.sid {
Some(s) if !s.is_empty() => s.clone(),
_ => { results.push((i, TunnelResponse::error("missing sid"))); continue; }
};
let inner = {
let sessions = state.udp_sessions.lock().await;
sessions.get(&sid).map(|s| s.inner.clone())
};
if let Some(inner) = inner {
let mut had_uplink = false;
if let Some(ref data_b64) = op.d {
if !data_b64.is_empty() {
let bytes = match B64.decode(data_b64) {
Ok(b) => b,
Err(e) => {
results.push((
i,
TunnelResponse::error(format!("bad base64: {}", e)),
));
continue;
}
};
if !bytes.is_empty() {
had_writes_or_connects = true;
had_uplink = true;
let _ = inner.socket.send(&bytes).await;
}
}
}
// last_active is bumped only on real activity:
// outbound here, or inbound in udp_reader_task.
// Empty long-poll batches must not refresh it, else
// the idle reaper never fires.
if had_uplink {
*inner.last_active.lock().await = Instant::now();
}
udp_drains.push((i, sid));
} else {
results.push((i, eof_response(sid)));
}
}
"close" => {
let r = handle_close(&state, op.sid.clone()).await;
results.push((i, r));
}
other => {
results.push((i, TunnelResponse::unsupported_op(other)));
}
}
}
// Await all concurrent connect / connect_data / udp_open jobs.
// Successful drain-bearing ones join the appropriate drain list;
// plain connects go straight to results.
while let Some(join) = new_conn_jobs.join_next().await {
match join {
Ok((i, NewConn::Connect(r))) => results.push((i, r)),
Ok((i, NewConn::ConnectData(Ok(sid)))) => tcp_drains.push((i, sid)),
Ok((i, NewConn::ConnectData(Err(r)))) => results.push((i, r)),
Ok((i, NewConn::UdpOpen(Ok(sid)))) => udp_drains.push((i, sid)),
Ok((i, NewConn::UdpOpen(Err(r)))) => results.push((i, r)),
Err(e) => {
tracing::error!("new-connection task panicked: {}", e);
}
}
}
// Phase 2: signal-driven wait for any session (TCP or UDP) to have
// data, then drain TCP and UDP independently in a single pass each.
// Deadlines:
// * `ACTIVE_DRAIN_DEADLINE` (~350 ms) when the batch had real work.
// Typical responses arrive in ms; the wait helpers return on
// the first notify. For active batches we settle for
// `STRAGGLER_SETTLE` so neighbors whose replies trail by a few
// ms aren't reported empty.
// * `LONGPOLL_DEADLINE` for pure-poll batches — held open until
// upstream pushes data. UDP idle polls benefit from this just
// as much as TCP, so the same window applies.
if !tcp_drains.is_empty() || !udp_drains.is_empty() {
let deadline = if had_writes_or_connects {
ACTIVE_DRAIN_DEADLINE
} else {
LONGPOLL_DEADLINE
};
let tcp_inners: Vec<Arc<SessionInner>> = {
let sessions = state.sessions.lock().await;
tcp_drains
.iter()
.filter_map(|(_, sid)| sessions.get(sid).map(|s| s.inner.clone()))
.collect()
};
let udp_inners: Vec<Arc<UdpSessionInner>> = {
let sessions = state.udp_sessions.lock().await;
udp_drains
.iter()
.filter_map(|(_, sid)| sessions.get(sid).map(|s| s.inner.clone()))
.collect()
};
// Wait for either side to wake. Running both concurrently means
// a TCP-only batch isn't slowed by a stale UDP watch list, and
// vice versa.
tokio::join!(
wait_for_any_drainable(&tcp_inners, deadline),
wait_for_any_udp_drainable(&udp_inners, deadline),
);
if had_writes_or_connects {
// Adaptive settle: keep waiting in steps while new data
// keeps arriving. Break when:
// 1. No new data arrived in the last step (burst is over)
// 2. 500ms max reached
let settle_end = Instant::now() + STRAGGLER_SETTLE_MAX;
let mut prev_tcp_bytes: usize = 0;
let mut prev_udp_pkts: usize = 0;
// Snapshot current buffer sizes.
for inner in &tcp_inners {
prev_tcp_bytes += inner.read_buf.lock().await.len();
}
for inner in &udp_inners {
prev_udp_pkts += inner.packets.lock().await.len();
}
loop {
let now = Instant::now();
if now >= settle_end {
break;
}
let remaining = settle_end.duration_since(now);
tokio::time::sleep(STRAGGLER_SETTLE_STEP.min(remaining)).await;
// Measure current buffer sizes.
let mut tcp_bytes: usize = 0;
let mut udp_pkts: usize = 0;
for inner in &tcp_inners {
tcp_bytes += inner.read_buf.lock().await.len();
}
for inner in &udp_inners {
udp_pkts += inner.packets.lock().await.len();
}
// No new data since last step — burst is over.
if tcp_bytes == prev_tcp_bytes && udp_pkts == prev_udp_pkts {
break;
}
prev_tcp_bytes = tcp_bytes;
prev_udp_pkts = udp_pkts;
}
}
// ---- TCP drain ----
if !tcp_drains.is_empty() {
let sessions = state.sessions.lock().await;
for (i, sid) in &tcp_drains {
if let Some(session) = sessions.get(sid) {
let (data, eof) = drain_now(&session.inner).await;
results.push((*i, tcp_drain_response(sid.clone(), data, eof)));
} else {
results.push((*i, eof_response(sid.clone())));
}
}
drop(sessions);
// Clean up eof TCP sessions.
let mut sessions = state.sessions.lock().await;
for (_, sid) in &tcp_drains {
if let Some(s) = sessions.get(sid) {
if s.inner.eof.load(Ordering::Acquire) {
if let Some(s) = sessions.remove(sid) {
s.reader_handle.abort();
tracing::info!("session {} closed by remote (batch)", sid);
}
}
}
}
}
// ---- UDP drain ----
if !udp_drains.is_empty() {
{
let sessions = state.udp_sessions.lock().await;
for (i, sid) in &udp_drains {
if let Some(session) = sessions.get(sid) {
let (packets, eof) = drain_udp_now(&session.inner).await;
results.push((*i, udp_drain_response(sid.clone(), packets, eof)));
} else {
results.push((*i, eof_response(sid.clone())));
}