rusnel 0.10.0

Rusnel is a fast TCP/UDP tunnel, transported over and encrypted using QUIC protocol. Single executable including both client and server
Documentation
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
use crate::common::utils::SerdeHelper;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::str::FromStr;

/// Wire-level protocol selector. Kept as a separate enum so the parser and
/// dispatchers can `match` on it directly without stringly-typed checks.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
    Tcp,
    Udp,
}

/// Direction of a tunnel relative to the *initiating* client. Forward is the
/// chisel-default (client opens a local listener; server reaches the
/// upstream); Reverse swaps those roles.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    Forward,
    Reverse,
}

/// A `host:port` pair as the user typed it on the CLI, before any DNS
/// resolution. We keep the host as a `String` (not an `IpAddr`) so DNS names
/// like `google.com` survive intact down to the actual `connect` call.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct HostPort {
    pub host: String,
    pub port: u16,
}

impl HostPort {
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port,
        }
    }

    /// Render as `host:port`, bracketing IPv6 literals so the output is safe
    /// to feed to `TcpStream::connect` and friends.
    pub fn to_addr_string(&self) -> String {
        if self.host.parse::<Ipv6Addr>().is_ok() {
            format!("[{}]:{}", self.host, self.port)
        } else {
            format!("{}:{}", self.host, self.port)
        }
    }
}

impl fmt::Display for HostPort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_addr_string())
    }
}

/// What kind of tunnel this remote represents. The `local` socket is always
/// the address the *initiating* client (or, for reverse remotes, the server)
/// listens on; the `remote` host:port is the peer's connect target. SOCKS5
/// has no static remote — the target is supplied per-connection by the SOCKS
/// handshake.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum RemoteKind {
    Tcp { local: SocketAddr, remote: HostPort },
    Udp { local: SocketAddr, remote: HostPort },
    Socks5 { local: SocketAddr },
}

impl RemoteKind {
    pub fn local(&self) -> SocketAddr {
        match self {
            RemoteKind::Tcp { local, .. }
            | RemoteKind::Udp { local, .. }
            | RemoteKind::Socks5 { local } => *local,
        }
    }

    pub fn protocol(&self) -> Option<Protocol> {
        match self {
            RemoteKind::Tcp { .. } => Some(Protocol::Tcp),
            RemoteKind::Udp { .. } => Some(Protocol::Udp),
            RemoteKind::Socks5 { .. } => None,
        }
    }
}

/// A single tunnel description (a *tunnel declaration*). One of these per
/// `--remote` flag on the client CLI; sent to the server in bulk inside
/// [`SessionHello`] right after the QUIC connection is established.
///
/// In the post-0.8 protocol the client never re-sends a `RemoteRequest`
/// per data conn — once the server accepts the hello and assigns each
/// declaration a `tunnel_id`, all subsequent bi-streams identify
/// themselves with [`OpenConn`] frames keyed by that id.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct RemoteRequest {
    pub direction: Direction,
    pub kind: RemoteKind,
    /// `true` when the user typed `stdio:host:port` (forward-only). The
    /// client pipes its own stdin/stdout to/from the QUIC stream instead
    /// of binding a local listener; the server side is unaffected (still
    /// a normal TCP/UDP `connect` to `kind.remote`). The dummy
    /// `kind.local` (always `0.0.0.0:0`) is never bound.
    #[serde(default)]
    pub stdio: bool,
}

impl RemoteRequest {
    pub fn new(direction: Direction, kind: RemoteKind) -> Self {
        Self {
            direction,
            kind,
            stdio: false,
        }
    }

    /// `true` if this remote represents SOCKS5 traffic — a standalone
    /// SOCKS5 listener declaration (`R:socks` for reverse, plain `socks`
    /// for forward). Used by the server's hello-time validation to gate
    /// SOCKS5 behind `--allow-socks`. Per-CONNECT / per-UDP-target
    /// dynamic streams the SOCKS handler manufactures at runtime no
    /// longer need their own flag — they are carried as
    /// [`OpenConn::dynamic`] under a parent SOCKS5 tunnel, which was
    /// already gated at hello time.
    pub fn is_socks(&self) -> bool {
        matches!(self.kind, RemoteKind::Socks5 { .. })
    }

    pub fn is_reversed(&self) -> bool {
        matches!(self.direction, Direction::Reverse)
    }

    pub fn is_stdio(&self) -> bool {
        self.stdio
    }

    /// `local_host:local_port` as a `SocketAddr`. Use the resulting value's
    /// `Display` for binding/listening — that path brackets IPv6 literals
    /// correctly (`[::1]:8080`).
    pub fn local_socket_addr(&self) -> SocketAddr {
        self.kind.local()
    }

    /// `remote_host:remote_port` formatted for `TcpStream::connect`,
    /// `UdpSocket::send_to`, and friends. Brackets bare IPv6 literals.
    /// Returns `None` for SOCKS5 remotes, which have no static target.
    pub fn remote_addr_string(&self) -> Option<String> {
        match &self.kind {
            RemoteKind::Tcp { remote, .. } | RemoteKind::Udp { remote, .. } => {
                Some(remote.to_addr_string())
            }
            RemoteKind::Socks5 { .. } => None,
        }
    }
}

impl fmt::Display for Protocol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Protocol::Tcp => write!(f, "tcp"),
            Protocol::Udp => write!(f, "udp"),
        }
    }
}

impl fmt::Display for RemoteRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_reversed() {
            write!(f, "R:")?;
        }
        if self.stdio {
            // stdio is always forward-only (rejected at parse time
            // otherwise) and is forbidden with SOCKS5, so the only
            // shapes here are Tcp/Udp.
            return match &self.kind {
                RemoteKind::Tcp { remote, .. } => {
                    write!(f, "stdio=>{}/tcp", remote.to_addr_string())
                }
                RemoteKind::Udp { remote, .. } => {
                    write!(f, "stdio=>{}/udp", remote.to_addr_string())
                }
                RemoteKind::Socks5 { .. } => write!(f, "stdio=>socks"),
            };
        }
        match &self.kind {
            RemoteKind::Socks5 { local } => write!(f, "{}=>socks", local.port()),
            RemoteKind::Tcp { local, remote } => {
                write!(f, "{}=>{}/tcp", local.port(), remote.to_addr_string())
            }
            RemoteKind::Udp { local, remote } => {
                write!(f, "{}=>{}/udp", local.port(), remote.to_addr_string())
            }
        }
    }
}

impl SerdeHelper for RemoteRequest {}

// ---------------------------------------------------------------------------
// Session-level handshake (post-0.8 wire protocol)
// ---------------------------------------------------------------------------
//
// Right after the QUIC connection is established the client opens its
// first bi-stream and sends a [`SessionHello`] carrying *every* tunnel
// declaration it wants. The server validates them all in one shot
// against `--allow-reverse` / `--allow-socks` and either accepts the
// whole batch — assigning one `tunnel_id` per declaration in the same
// order — or rejects the entire session. Subsequent bi-streams (in
// either direction) start with an [`OpenConn`] frame that names the
// `tunnel_id` they belong to, so neither side ever re-sends a full
// [`RemoteRequest`] on the data plane.

/// First control frame the client sends on a fresh QUIC connection.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SessionHello {
    pub remotes: Vec<RemoteRequest>,
}

impl SerdeHelper for SessionHello {}

/// Server's reply to [`SessionHello`]. On success, `tunnel_ids[i]` is
/// the server-assigned id for `hello.remotes[i]`. On failure, the
/// server closes the connection.
#[derive(Serialize, Deserialize, Debug)]
pub enum SessionHelloResponse {
    Ok { tunnel_ids: Vec<u64> },
    Failed(String),
}

impl SerdeHelper for SessionHelloResponse {}

/// Per-conn opener. Sent on the first 4 + body bytes of every
/// data-plane bi-stream (in either direction) so the receiving side
/// knows which tunnel this conn belongs to without consulting any
/// out-of-band state.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct OpenConn {
    pub tunnel_id: u64,
    /// SOCKS5-only: the per-CONNECT (TCP) or per-target (UDP) address
    /// the SOCKS handshake just resolved. `None` for static tunnels
    /// (the receiving side uses the parent tunnel's declared `kind`).
    pub dynamic: Option<DynamicTarget>,
}

impl SerdeHelper for OpenConn {}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum DynamicTarget {
    Tcp(HostPort),
    Udp(HostPort),
}

/// Reply to an [`OpenConn`]. `Ok` = "go ahead, start streaming"; `Failed`
/// surfaces a server-side reason (unknown tunnel id, dispatch error,
/// …) so the conn can be torn down cleanly instead of timing out.
#[derive(Serialize, Deserialize, Debug)]
pub enum OpenConnResponse {
    Ok,
    Failed(String),
}

impl SerdeHelper for OpenConnResponse {}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// Marker token the user types in place of `<remote-host>:<remote-port>` to
/// request a SOCKS5 dynamic tunnel.
const SOCKS_KEYWORD: &str = "socks";

/// Marker token that replaces the local-side `host:port` to request that
/// the client pipe its own stdin/stdout to/from the tunnel instead of
/// binding a local listener. Forward-only — `R:stdio:...` is rejected.
const STDIO_KEYWORD: &str = "stdio";

/// Default address for things that historically defaulted to `0.0.0.0` (the
/// IPv4 wildcard).
const ANY_V4: &str = "0.0.0.0";
/// Default address for SOCKS5's local listener.
const SOCKS_DEFAULT_LOCAL: &str = "127.0.0.1";
const SOCKS_DEFAULT_PORT: u16 = 1080;
/// Default `remote_host` used when the user omits it in a `stdio:port`
/// short-hand, matching chisel's behavior (`3000` resolves to
/// `127.0.0.1:3000` on the remote side).
const STDIO_DEFAULT_REMOTE_HOST: &str = "127.0.0.1";

/// Decomposed input as a sequence of structured layers. The parser pipes the
/// raw string through these sub-parses in order:
///
///   1. `parse_direction` strips the optional `R:` / `R/` prefix.
///   2. `parse_protocol` strips the optional `/tcp` / `/udp` suffix.
///   3. `split_addr_tokens` tokenizes the residual `host:port:host:port`
///      respecting `[…]` so IPv6 literals stay atomic.
///   4. `tokens_to_kind` dispatches on the token count and the SOCKS keyword
///      to build the final [`RemoteKind`].
impl FromStr for RemoteRequest {
    type Err = anyhow::Error;

    fn from_str(input: &str) -> Result<RemoteRequest> {
        let (direction, after_dir) = parse_direction(input)?;
        let (protocol_hint, body) = parse_protocol(after_dir)?;
        let tokens = split_addr_tokens(body)?;

        // Detect a leading `stdio` token. Stdio replaces the local
        // listener with the client's own stdin/stdout, so it only
        // makes sense in the *first* token slot and only on forward
        // tunnels (the server side of a reverse tunnel can't write to
        // the client's stdout).
        let (stdio, addr_tokens) = if !tokens.is_empty() && tokens[0] == STDIO_KEYWORD {
            if matches!(direction, Direction::Reverse) {
                return Err(anyhow!("Invalid format: stdio cannot be reversed"));
            }
            (true, &tokens[1..])
        } else {
            (false, tokens.as_slice())
        };

        let kind = if stdio {
            tokens_to_stdio_kind(addr_tokens, protocol_hint)?
        } else {
            tokens_to_kind(addr_tokens, protocol_hint)?
        };
        Ok(RemoteRequest {
            direction,
            kind,
            stdio,
        })
    }
}

/// Strip a leading `R:` ("reverse") marker. Matches chisel's syntax exactly:
/// the colon form is the only form accepted.
fn parse_direction(s: &str) -> Result<(Direction, &str)> {
    if let Some(rest) = s.strip_prefix("R:") {
        if rest.is_empty() {
            return Err(anyhow!("Invalid format: Missing details after R:"));
        }
        return Ok((Direction::Reverse, rest));
    }
    if s == "R" {
        return Err(anyhow!("Invalid format: Missing details after R"));
    }
    Ok((Direction::Forward, s))
}

/// Pop a trailing `/tcp` or `/udp` if present. Returns the protocol the
/// caller asked for (or `None` if no suffix), plus the residual address
/// portion. Errors out on any other suffix so silent typos don't slip
/// through as TCP.
fn parse_protocol(s: &str) -> Result<(Option<Protocol>, &str)> {
    match s.rsplit_once('/') {
        Some((head, "tcp")) => Ok((Some(Protocol::Tcp), head)),
        Some((head, "udp")) => Ok((Some(Protocol::Udp), head)),
        Some(_) => Err(anyhow!("Invalid protocol: Must be 'tcp' or 'udp'")),
        None => Ok((None, s)),
    }
}

/// Split `s` on `:` while treating `[...]` segments as a single atomic
/// token so IPv6 literals (which contain `:`) survive intact. Bracketed
/// tokens are returned *with* their brackets so [`unbracket`] can recognize
/// them later.
fn split_addr_tokens(s: &str) -> Result<Vec<&str>> {
    let bytes = s.as_bytes();
    let mut tokens = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'[' {
            let close_rel = bytes[i + 1..]
                .iter()
                .position(|&b| b == b']')
                .ok_or_else(|| anyhow!("Invalid format: unterminated '['"))?;
            let close = i + 1 + close_rel;
            tokens.push(&s[i..=close]);
            i = close + 1;
            if i < bytes.len() {
                if bytes[i] != b':' {
                    return Err(anyhow!("Invalid format: expected ':' after ']'"));
                }
                i += 1;
                if i == bytes.len() {
                    return Err(anyhow!("Invalid format: trailing ':' after ']'"));
                }
            }
        } else {
            let next = bytes[i..]
                .iter()
                .position(|&b| b == b':')
                .map(|p| i + p)
                .unwrap_or(bytes.len());
            tokens.push(&s[i..next]);
            i = next;
            if i < bytes.len() {
                i += 1;
                if i == bytes.len() {
                    return Err(anyhow!("Invalid format: trailing ':'"));
                }
            }
        }
    }
    Ok(tokens)
}

fn unbracket(s: &str) -> &str {
    if s.len() >= 2 && s.starts_with('[') && s.ends_with(']') {
        &s[1..s.len() - 1]
    } else {
        s
    }
}

fn parse_ip(s: &str, what: &str) -> Result<IpAddr> {
    unbracket(s)
        .parse::<IpAddr>()
        .map_err(|_| anyhow!("Invalid {what}"))
}

fn parse_port(s: &str, what: &str) -> Result<u16> {
    s.parse::<u16>().map_err(|_| anyhow!("Invalid {what}"))
}

/// `0.0.0.0` as an `IpAddr`. Cheap; called from the per-arity branches
/// below for the v4 wildcard default.
fn any_v4() -> IpAddr {
    // The literal is a constant — `parse` here is total. We unwrap to avoid
    // bubbling an `anyhow!` that can never fire at runtime.
    ANY_V4
        .parse::<IpAddr>()
        .unwrap_or(IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED))
}

fn socks_default_local() -> IpAddr {
    SOCKS_DEFAULT_LOCAL
        .parse::<IpAddr>()
        .unwrap_or(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST))
}

/// Combine a tokenized address with an optional protocol hint into a
/// [`RemoteKind`]. SOCKS5 ignores the protocol hint (it's TCP-only by
/// definition); the `tcp`/`udp` discriminator only matters for the
/// host:port shapes.
fn tokens_to_kind(tokens: &[&str], protocol: Option<Protocol>) -> Result<RemoteKind> {
    if tokens.is_empty() {
        return Err(anyhow!("Invalid format: Missing parts"));
    }

    // Each shape ends in either a `socks` keyword (build a Socks5) or a
    // host:port quadruple/triple/double/single (build Tcp/Udp). The shape
    // is fully determined by token count.
    match tokens.len() {
        1 => parse_one_token(tokens[0], protocol),
        2 => parse_two_tokens(tokens, protocol),
        3 => parse_three_tokens(tokens, protocol),
        4 => parse_four_tokens(tokens, protocol),
        _ => Err(anyhow!(
            "Invalid format: Unexpected number of address parts"
        )),
    }
}

fn parse_one_token(token: &str, protocol: Option<Protocol>) -> Result<RemoteKind> {
    if token == SOCKS_KEYWORD {
        return Ok(RemoteKind::Socks5 {
            local: SocketAddr::new(socks_default_local(), SOCKS_DEFAULT_PORT),
        });
    }
    let port = parse_port(token, "remote port")?;
    Ok(make_host_port_kind(
        SocketAddr::new(any_v4(), port),
        HostPort::new(ANY_V4, port),
        protocol,
    ))
}

fn parse_two_tokens(tokens: &[&str], protocol: Option<Protocol>) -> Result<RemoteKind> {
    if tokens[1] == SOCKS_KEYWORD {
        let local_port = parse_port(tokens[0], "remote port")?;
        return Ok(RemoteKind::Socks5 {
            local: SocketAddr::new(socks_default_local(), local_port),
        });
    }
    let remote_host = unbracket(tokens[0]).to_string();
    let remote_port = parse_port(tokens[1], "remote port")?;
    Ok(make_host_port_kind(
        SocketAddr::new(any_v4(), remote_port),
        HostPort::new(remote_host, remote_port),
        protocol,
    ))
}

fn parse_three_tokens(tokens: &[&str], protocol: Option<Protocol>) -> Result<RemoteKind> {
    if tokens[2] == SOCKS_KEYWORD {
        let local_host = parse_ip(tokens[0], "local host")?;
        let local_port = parse_port(tokens[1], "local port")?;
        return Ok(RemoteKind::Socks5 {
            local: SocketAddr::new(local_host, local_port),
        });
    }
    let local_port = parse_port(tokens[0], "local port")?;
    let remote_host = unbracket(tokens[1]).to_string();
    let remote_port = parse_port(tokens[2], "remote port")?;
    Ok(make_host_port_kind(
        SocketAddr::new(any_v4(), local_port),
        HostPort::new(remote_host, remote_port),
        protocol,
    ))
}

fn parse_four_tokens(tokens: &[&str], protocol: Option<Protocol>) -> Result<RemoteKind> {
    let local_host = parse_ip(tokens[0], "local host")?;
    let local_port = parse_port(tokens[1], "local port")?;
    let remote_host = unbracket(tokens[2]).to_string();
    let remote_port = parse_port(tokens[3], "remote port")?;
    Ok(make_host_port_kind(
        SocketAddr::new(local_host, local_port),
        HostPort::new(remote_host, remote_port),
        protocol,
    ))
}

/// Build a [`RemoteKind`] for a `stdio:...` declaration. The `local`
/// `SocketAddr` is a dummy `0.0.0.0:0` — the client's stdio dispatcher
/// never binds it. Stdio is incompatible with SOCKS5 (no `socks` keyword
/// allowed in the remainder) since stdio is a single-conn pipe.
fn tokens_to_stdio_kind(tokens: &[&str], protocol: Option<Protocol>) -> Result<RemoteKind> {
    if tokens.contains(&SOCKS_KEYWORD) {
        return Err(anyhow!(
            "Invalid format: stdio cannot be combined with socks"
        ));
    }
    let local = SocketAddr::new(any_v4(), 0);
    match tokens.len() {
        1 => {
            // `stdio:<port>` — chisel defaults the omitted remote host
            // to 127.0.0.1 (vs. 0.0.0.0 for a bare port short-hand).
            let port = parse_port(tokens[0], "remote port")?;
            Ok(make_host_port_kind(
                local,
                HostPort::new(STDIO_DEFAULT_REMOTE_HOST, port),
                protocol,
            ))
        }
        2 => {
            let remote_host = unbracket(tokens[0]).to_string();
            let remote_port = parse_port(tokens[1], "remote port")?;
            Ok(make_host_port_kind(
                local,
                HostPort::new(remote_host, remote_port),
                protocol,
            ))
        }
        0 => Err(anyhow!(
            "Invalid format: stdio requires a remote host:port or port"
        )),
        _ => Err(anyhow!(
            "Invalid format: stdio expects '<host>:<port>' or '<port>'"
        )),
    }
}

fn make_host_port_kind(
    local: SocketAddr,
    remote: HostPort,
    protocol: Option<Protocol>,
) -> RemoteKind {
    match protocol.unwrap_or(Protocol::Tcp) {
        Protocol::Tcp => RemoteKind::Tcp { local, remote },
        Protocol::Udp => RemoteKind::Udp { local, remote },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(s: &str) -> RemoteRequest {
        RemoteRequest::from_str(s).unwrap_or_else(|e| panic!("expected `{s}` to parse: {e}"))
    }

    fn ip(s: &str) -> IpAddr {
        s.parse().unwrap()
    }

    /// Convenience: pull the `(local, remote, protocol)` triple out of a
    /// host:port-shaped remote. Panics on Socks5 — tests that produce a
    /// SOCKS5 remote use `assert!(matches!(...))` directly.
    fn unwrap_hp(r: &RemoteRequest) -> (SocketAddr, &HostPort, Protocol) {
        match &r.kind {
            RemoteKind::Tcp { local, remote } => (*local, remote, Protocol::Tcp),
            RemoteKind::Udp { local, remote } => (*local, remote, Protocol::Udp),
            RemoteKind::Socks5 { .. } => panic!("expected host:port remote, got socks"),
        }
    }

    #[test]
    fn forward_just_remote_port() {
        let r = parse("1337");
        let (local, remote, proto) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("0.0.0.0"), 1337));
        assert_eq!(remote.host, "0.0.0.0");
        assert_eq!(remote.port, 1337);
        assert!(!r.is_reversed());
        assert_eq!(proto, Protocol::Tcp);
    }

    #[test]
    fn forward_remote_host_and_port() {
        let r = parse("example.com:1337");
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("0.0.0.0"), 1337));
        assert_eq!(remote.host, "example.com");
        assert_eq!(remote.port, 1337);
        assert!(!r.is_reversed());
    }

    #[test]
    fn forward_local_port_remote_host_port() {
        let r = parse("1337:google.com:80");
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("0.0.0.0"), 1337));
        assert_eq!(remote.host, "google.com");
        assert_eq!(remote.port, 80);
    }

    #[test]
    fn forward_full_quadruple() {
        let r = parse("192.168.1.14:5000:google.com:80");
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("192.168.1.14"), 5000));
        assert_eq!(remote.host, "google.com");
        assert_eq!(remote.port, 80);
    }

    #[test]
    fn forward_udp_protocol_suffix() {
        let r = parse("1.1.1.1:53/udp");
        let (_, remote, proto) = unwrap_hp(&r);
        assert_eq!(remote.host, "1.1.1.1");
        assert_eq!(remote.port, 53);
        assert_eq!(proto, Protocol::Udp);
    }

    #[test]
    fn socks_default_local() {
        let r = parse("socks");
        assert!(r.is_socks());
        assert_eq!(
            r.local_socket_addr(),
            SocketAddr::new(ip("127.0.0.1"), 1080)
        );
        assert!(!r.is_reversed());
    }

    #[test]
    fn socks_custom_local_port() {
        let r = parse("5000:socks");
        assert!(r.is_socks());
        assert_eq!(
            r.local_socket_addr(),
            SocketAddr::new(ip("127.0.0.1"), 5000)
        );
    }

    #[test]
    fn reverse_prefix_with_port() {
        let r = parse("R:2222:localhost:22");
        assert!(r.is_reversed());
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local.port(), 2222);
        assert_eq!(remote.host, "localhost");
        assert_eq!(remote.port, 22);
    }

    #[test]
    fn reverse_socks_default_local() {
        let r = parse("R:socks");
        assert!(r.is_reversed());
        assert!(r.is_socks());
        assert_eq!(
            r.local_socket_addr(),
            SocketAddr::new(ip("127.0.0.1"), 1080)
        );
    }

    #[test]
    fn reverse_socks_custom_local_port() {
        let r = parse("R:5000:socks");
        assert!(r.is_reversed());
        assert!(r.is_socks());
        assert_eq!(r.local_socket_addr().port(), 5000);
    }

    #[test]
    fn rejects_unknown_protocol() {
        let err = RemoteRequest::from_str("1.1.1.1:53/sctp").unwrap_err();
        assert!(
            err.to_string().contains("Invalid protocol"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_invalid_local_ip() {
        let err = RemoteRequest::from_str("not-an-ip:1:host:80").unwrap_err();
        assert!(
            err.to_string().contains("Invalid local host"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_invalid_port() {
        let err = RemoteRequest::from_str("99999").unwrap_err();
        assert!(
            err.to_string().contains("Invalid remote port"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_too_many_address_parts() {
        let err = RemoteRequest::from_str("a:b:c:d:e").unwrap_err();
        assert!(
            err.to_string()
                .contains("Unexpected number of address parts"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn ipv6_remote_host_port() {
        let r = parse("[::1]:80");
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("0.0.0.0"), 80));
        assert_eq!(remote.host, "::1");
        assert_eq!(remote.port, 80);
    }

    #[test]
    fn ipv6_local_port_remote_host_port() {
        let r = parse("8080:[2001:db8::1]:443");
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("0.0.0.0"), 8080));
        assert_eq!(remote.host, "2001:db8::1");
        assert_eq!(remote.port, 443);
    }

    #[test]
    fn ipv6_full_quadruple() {
        let r = parse("[::1]:5000:[2001:db8::1]:80/udp");
        let (local, remote, proto) = unwrap_hp(&r);
        assert_eq!(local, SocketAddr::new(ip("::1"), 5000));
        assert_eq!(remote.host, "2001:db8::1");
        assert_eq!(remote.port, 80);
        assert_eq!(proto, Protocol::Udp);
    }

    #[test]
    fn ipv6_local_only_with_socks() {
        let r = parse("[::1]:1080:socks");
        assert_eq!(r.local_socket_addr(), SocketAddr::new(ip("::1"), 1080));
        assert!(r.is_socks());
    }

    #[test]
    fn ipv6_reverse() {
        let r = parse("R:[::1]:5000:[2001:db8::1]:80");
        assert!(r.is_reversed());
        let (local, remote, _) = unwrap_hp(&r);
        assert_eq!(local.ip(), ip("::1"));
        assert_eq!(remote.host, "2001:db8::1");
    }

    #[test]
    fn rejects_unterminated_bracket() {
        let err = RemoteRequest::from_str("[::1:80").unwrap_err();
        assert!(
            err.to_string().contains("unterminated"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_missing_colon_after_bracket() {
        // `[::1]80` (no `:` between `]` and the port) is an obvious user
        // typo; reject it explicitly rather than silently producing a
        // one-token parse that fails later with a misleading error.
        let err = RemoteRequest::from_str("[::1]80").unwrap_err();
        assert!(
            err.to_string().contains("expected ':'"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn unbracketed_ipv6_still_rejected() {
        // Bare colon-rich tokens have always been ambiguous (could be IPv6
        // or `host:port:host:port…`). We require brackets for IPv6 — same
        // rule HTTP, ssh, and curl all use.
        assert!(RemoteRequest::from_str("fe80::1:53").is_err());
    }

    #[test]
    fn remote_addr_string_brackets_ipv6() {
        let r = parse("[2001:db8::1]:443");
        assert_eq!(r.remote_addr_string().as_deref(), Some("[2001:db8::1]:443"));
    }

    #[test]
    fn remote_addr_string_passes_dns_through() {
        let r = parse("example.com:80");
        assert_eq!(r.remote_addr_string().as_deref(), Some("example.com:80"));
    }

    #[test]
    fn remote_addr_string_none_for_socks() {
        let r = parse("socks");
        assert_eq!(r.remote_addr_string(), None);
    }

    #[test]
    fn local_socket_addr_handles_ipv6() {
        let r = parse("[::1]:8080:example.com:80");
        assert_eq!(r.local_socket_addr().to_string(), "[::1]:8080");
    }

    #[test]
    fn protocol_helpers() {
        assert_eq!(parse("80").kind.protocol(), Some(Protocol::Tcp));
        assert_eq!(parse("80/udp").kind.protocol(), Some(Protocol::Udp));
        assert_eq!(parse("socks").kind.protocol(), None);
    }

    #[test]
    fn rejects_r_slash_prefix() {
        // `R/` was a Rusnel-specific shorthand; we now match chisel
        // exactly and require the colon form.
        let err = RemoteRequest::from_str("R/1337:google.com:80").unwrap_err();
        assert!(
            err.to_string().contains("Invalid"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_bare_r() {
        let err = RemoteRequest::from_str("R").unwrap_err();
        assert!(
            err.to_string().contains("after R"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_empty_after_reverse_prefix() {
        let err = RemoteRequest::from_str("R:").unwrap_err();
        assert!(
            err.to_string().contains("after R:"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn stdio_with_remote_host_port() {
        let r = parse("stdio:example.com:22");
        assert!(r.is_stdio());
        assert!(!r.is_reversed());
        let (_, remote, proto) = unwrap_hp(&r);
        assert_eq!(remote.host, "example.com");
        assert_eq!(remote.port, 22);
        assert_eq!(proto, Protocol::Tcp);
    }

    #[test]
    fn stdio_with_just_port_defaults_remote_to_loopback() {
        // Per chisel's `stdio:80` short-hand: omitted remote host
        // resolves to 127.0.0.1 (not 0.0.0.0).
        let r = parse("stdio:80");
        assert!(r.is_stdio());
        let (_, remote, _) = unwrap_hp(&r);
        assert_eq!(remote.host, "127.0.0.1");
        assert_eq!(remote.port, 80);
    }

    #[test]
    fn stdio_with_udp_protocol_suffix() {
        let r = parse("stdio:1.1.1.1:53/udp");
        assert!(r.is_stdio());
        let (_, remote, proto) = unwrap_hp(&r);
        assert_eq!(remote.host, "1.1.1.1");
        assert_eq!(remote.port, 53);
        assert_eq!(proto, Protocol::Udp);
    }

    #[test]
    fn stdio_ipv6_remote() {
        let r = parse("stdio:[2001:db8::1]:443");
        assert!(r.is_stdio());
        let (_, remote, _) = unwrap_hp(&r);
        assert_eq!(remote.host, "2001:db8::1");
        assert_eq!(remote.port, 443);
    }

    #[test]
    fn rejects_reverse_stdio() {
        let err = RemoteRequest::from_str("R:stdio:example.com:22").unwrap_err();
        assert!(
            err.to_string().contains("stdio cannot be reversed"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_stdio_alone() {
        let err = RemoteRequest::from_str("stdio").unwrap_err();
        assert!(
            err.to_string().contains("stdio requires"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn rejects_stdio_socks() {
        let err = RemoteRequest::from_str("stdio:socks").unwrap_err();
        assert!(
            err.to_string()
                .contains("stdio cannot be combined with socks"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn stdio_round_trips_through_display() {
        let r = parse("stdio:example.com:22");
        assert_eq!(r.to_string(), "stdio=>example.com:22/tcp");
        let r = parse("stdio:1.1.1.1:53/udp");
        assert_eq!(r.to_string(), "stdio=>1.1.1.1:53/udp");
    }

    #[test]
    fn rejects_trailing_colon() {
        let err = RemoteRequest::from_str("1.1.1.1:").unwrap_err();
        assert!(
            err.to_string().contains("trailing ':'"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn idn_remote_host_passes_through() {
        let r = parse("示例網站.com:80");
        let (_, remote, _) = unwrap_hp(&r);
        assert_eq!(remote.host, "示例網站.com");
        assert_eq!(remote.port, 80);
    }
}