Skip to main content

ghast_auth/
connect.rs

1//! Opening the game connection: target addresses, proxy routing policy and the [`Connector`].
2//!
3//! A [`Connector`] turns a [`TargetAddr`] into a connected [`TcpStream`] (with `TCP_NODELAY` set),
4//! either directly or through a [`Socks5Proxy`]. Which of the two is allowed for a given target is
5//! decided by a [`ProxyPolicy`], so an application can enforce rules such as "never connect to a
6//! public server without a proxy" in one place.
7//!
8//! # DNS
9//!
10//! When a target is reached through the proxy, its domain name is sent to the proxy and resolved
11//! there (SOCKS5 address type `DOMAINNAME`). The connector never resolves a proxied target
12//! locally, so no DNS query for it leaves the machine. Only two things are ever resolved locally,
13//! through the configured [`Resolve`] implementation: the proxy's own host name (if it is not an
14//! IP literal) and targets of *direct* connections.
15//!
16//! Minecraft `_minecraft._tcp` SRV records are not looked up here: SRV lookups cannot be done
17//! through SOCKS5, and doing them locally would leak the target name.
18
19use std::fmt;
20use std::future::Future;
21use std::io;
22use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
23use std::pin::Pin;
24use std::str::FromStr;
25use std::sync::Arc;
26use std::time::Duration;
27
28use thiserror::Error;
29use tokio::net::TcpStream;
30
31use crate::socks5::{self, Socks5Error, Socks5Proxy};
32
33/// Maximum length of a domain name in bytes (the SOCKS5 length prefix is one byte).
34pub const MAX_DOMAIN_LEN: usize = 255;
35
36/// The default Minecraft server port.
37pub const DEFAULT_MINECRAFT_PORT: u16 = 25565;
38
39/// Where to connect: an IP socket address or a domain name plus port.
40#[derive(Debug, Clone, PartialEq, Eq, Hash)]
41pub enum TargetAddr {
42    /// An IP address and port.
43    Ip(SocketAddr),
44    /// A domain name and port. Through a proxy the name is resolved by the proxy.
45    ///
46    /// Values built with [`TargetAddr::new`] or [`str::parse`] are validated (non-empty, at most
47    /// [`MAX_DOMAIN_LEN`] bytes, only `A-Z a-z 0-9 - . _`). A hand-built variant is validated
48    /// again before it is sent to a proxy.
49    Domain(String, u16),
50}
51
52/// Why a target address could not be parsed.
53#[derive(Debug, Clone, PartialEq, Eq, Error)]
54#[non_exhaustive]
55pub enum AddrError {
56    /// The host part is empty.
57    #[error("host is empty")]
58    EmptyHost,
59    /// No port was given and no default applies.
60    #[error("port is missing")]
61    MissingPort,
62    /// The port is not a number in `0..=65535`.
63    #[error("invalid port {0:?}")]
64    InvalidPort(String),
65    /// A bracketed IPv6 literal is malformed.
66    #[error("invalid IPv6 address {0:?}")]
67    InvalidIpv6(String),
68    /// The domain name is longer than [`MAX_DOMAIN_LEN`] bytes.
69    #[error("domain name is {0} bytes long, the maximum is {MAX_DOMAIN_LEN}")]
70    DomainTooLong(usize),
71    /// The domain name contains a character outside `A-Z a-z 0-9 - . _`.
72    ///
73    /// Internationalized names must be given in their ASCII (punycode) form.
74    #[error("domain name contains the invalid character {0:?}")]
75    InvalidDomainChar(char),
76}
77
78impl TargetAddr {
79    /// Builds a target from a host (IP literal or domain name) and a port.
80    ///
81    /// IP literals (including IPv6 without brackets) become [`TargetAddr::Ip`]; everything else is
82    /// validated as a domain name.
83    pub fn new(host: &str, port: u16) -> Result<Self, AddrError> {
84        let unbracketed = host
85            .strip_prefix('[')
86            .and_then(|h| h.strip_suffix(']'))
87            .unwrap_or(host);
88        if let Ok(ip) = unbracketed.parse::<IpAddr>() {
89            return Ok(Self::Ip(SocketAddr::new(ip, port)));
90        }
91        if unbracketed.len() != host.len() {
92            return Err(AddrError::InvalidIpv6(host.to_owned()));
93        }
94        validate_domain(host)?;
95        Ok(Self::Domain(host.to_owned(), port))
96    }
97
98    /// Parses `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 literal, using
99    /// `default_port` when the string has no port.
100    ///
101    /// ```
102    /// use ghast_auth::connect::{DEFAULT_MINECRAFT_PORT, TargetAddr};
103    ///
104    /// let t = TargetAddr::parse_with_default_port("mc.example.net", DEFAULT_MINECRAFT_PORT).unwrap();
105    /// assert_eq!(t, TargetAddr::Domain("mc.example.net".into(), 25565));
106    /// ```
107    pub fn parse_with_default_port(s: &str, default_port: u16) -> Result<Self, AddrError> {
108        parse_target(s, Some(default_port))
109    }
110
111    /// The port.
112    pub fn port(&self) -> u16 {
113        match self {
114            Self::Ip(addr) => addr.port(),
115            Self::Domain(_, port) => *port,
116        }
117    }
118
119    /// The host part as a string (IPv6 without brackets).
120    pub fn host(&self) -> String {
121        match self {
122            Self::Ip(addr) => addr.ip().to_string(),
123            Self::Domain(host, _) => host.clone(),
124        }
125    }
126
127    /// Returns `true` if the target is on this machine or on the local network: loopback,
128    /// private IPv4 ranges (RFC 1918), link-local, IPv6 unique-local, or the `localhost` name
129    /// (RFC 6761).
130    ///
131    /// Other domain names are **not** considered local, because deciding that would require a
132    /// local DNS lookup. CGNAT (`100.64.0.0/10`) is not considered local either.
133    pub fn is_local(&self) -> bool {
134        match self {
135            Self::Ip(addr) => is_local_ip(addr.ip()),
136            Self::Domain(host, _) => {
137                let host = host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase();
138                host == "localhost" || host.ends_with(".localhost")
139            }
140        }
141    }
142}
143
144impl From<SocketAddr> for TargetAddr {
145    fn from(addr: SocketAddr) -> Self {
146        Self::Ip(addr)
147    }
148}
149
150impl FromStr for TargetAddr {
151    type Err = AddrError;
152
153    /// Parses `host:port` or `[v6]:port`. The port is required; see
154    /// [`TargetAddr::parse_with_default_port`] for a default.
155    fn from_str(s: &str) -> Result<Self, Self::Err> {
156        parse_target(s, None)
157    }
158}
159
160impl fmt::Display for TargetAddr {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        match self {
163            Self::Ip(addr) => write!(f, "{addr}"),
164            Self::Domain(host, port) => write!(f, "{host}:{port}"),
165        }
166    }
167}
168
169fn parse_target(s: &str, default_port: Option<u16>) -> Result<TargetAddr, AddrError> {
170    let s = s.trim();
171    let parse_port = |p: &str| {
172        p.parse::<u16>()
173            .map_err(|_| AddrError::InvalidPort(p.to_owned()))
174    };
175    let need_default = || default_port.ok_or(AddrError::MissingPort);
176
177    if let Some(rest) = s.strip_prefix('[') {
178        let (inside, after) = rest
179            .split_once(']')
180            .ok_or_else(|| AddrError::InvalidIpv6(s.to_owned()))?;
181        let ip: Ipv6Addr = inside
182            .parse()
183            .map_err(|_| AddrError::InvalidIpv6(inside.to_owned()))?;
184        let port = match after {
185            "" => need_default()?,
186            _ => match after.strip_prefix(':') {
187                Some(p) => parse_port(p)?,
188                None => return Err(AddrError::InvalidIpv6(s.to_owned())),
189            },
190        };
191        return Ok(TargetAddr::Ip(SocketAddr::new(IpAddr::V6(ip), port)));
192    }
193    // A bare IPv6 literal has several colons and no port.
194    if let Ok(ip) = s.parse::<Ipv6Addr>() {
195        return Ok(TargetAddr::Ip(SocketAddr::new(
196            IpAddr::V6(ip),
197            need_default()?,
198        )));
199    }
200    let (host, port) = match s.rsplit_once(':') {
201        Some((host, port)) => (host, parse_port(port)?),
202        None => (s, need_default()?),
203    };
204    if host.is_empty() {
205        return Err(AddrError::EmptyHost);
206    }
207    if let Ok(ip) = host.parse::<Ipv4Addr>() {
208        return Ok(TargetAddr::Ip(SocketAddr::new(IpAddr::V4(ip), port)));
209    }
210    validate_domain(host)?;
211    Ok(TargetAddr::Domain(host.to_owned(), port))
212}
213
214pub(crate) fn validate_domain(host: &str) -> Result<(), AddrError> {
215    if host.is_empty() {
216        return Err(AddrError::EmptyHost);
217    }
218    if host.len() > MAX_DOMAIN_LEN {
219        return Err(AddrError::DomainTooLong(host.len()));
220    }
221    match host
222        .chars()
223        .find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')))
224    {
225        Some(c) => Err(AddrError::InvalidDomainChar(c)),
226        None => Ok(()),
227    }
228}
229
230fn is_local_ip(ip: IpAddr) -> bool {
231    match ip {
232        IpAddr::V4(v4) => is_local_v4(v4),
233        IpAddr::V6(v6) => {
234            if let Some(v4) = v6.to_ipv4_mapped() {
235                return is_local_v4(v4);
236            }
237            v6.is_loopback() || v6.is_unique_local() || v6.is_unicast_link_local()
238        }
239    }
240}
241
242fn is_local_v4(v4: Ipv4Addr) -> bool {
243    v4.is_loopback() || v4.is_private() || v4.is_link_local()
244}
245
246/// How a single connection should be routed. Returned by a [`ProxyPolicy`].
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub enum Route {
249    /// Connect through the configured proxy; fail with [`ConnectError::ProxyRequired`] if none
250    /// is configured.
251    Proxy,
252    /// Connect through the proxy if one is configured, otherwise directly.
253    PreferProxy,
254    /// Connect directly, even if a proxy is configured.
255    Direct,
256}
257
258/// A user-supplied routing rule, see [`ProxyPolicy::Custom`].
259pub type RouteFn = dyn Fn(&TargetAddr) -> Route + Send + Sync;
260
261/// Decides, per target, whether a connection must, may or must not use the proxy.
262#[derive(Clone, Default)]
263pub enum ProxyPolicy {
264    /// Use the proxy when one is configured, otherwise connect directly. ([`Route::PreferProxy`]
265    /// for every target.)
266    #[default]
267    PreferProxy,
268    /// Every connection must go through the proxy. ([`Route::Proxy`] for every target.)
269    RequireProxy,
270    /// Targets for which [`TargetAddr::is_local`] holds are connected directly (a remote proxy
271    /// usually cannot reach this machine's LAN); every other target must use the proxy.
272    RequireProxyExceptLocal,
273    /// A custom rule.
274    Custom(Arc<RouteFn>),
275}
276
277impl ProxyPolicy {
278    /// Builds a [`ProxyPolicy::Custom`] from a closure.
279    pub fn custom(f: impl Fn(&TargetAddr) -> Route + Send + Sync + 'static) -> Self {
280        Self::Custom(Arc::new(f))
281    }
282
283    /// The route this policy selects for `target`.
284    pub fn route(&self, target: &TargetAddr) -> Route {
285        match self {
286            Self::PreferProxy => Route::PreferProxy,
287            Self::RequireProxy => Route::Proxy,
288            Self::RequireProxyExceptLocal if target.is_local() => Route::Direct,
289            Self::RequireProxyExceptLocal => Route::Proxy,
290            Self::Custom(f) => f(target),
291        }
292    }
293}
294
295impl fmt::Debug for ProxyPolicy {
296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297        match self {
298            Self::PreferProxy => f.write_str("PreferProxy"),
299            Self::RequireProxy => f.write_str("RequireProxy"),
300            Self::RequireProxyExceptLocal => f.write_str("RequireProxyExceptLocal"),
301            Self::Custom(_) => f.write_str("Custom(..)"),
302        }
303    }
304}
305
306/// The future returned by [`Resolve::resolve`].
307pub type ResolveFuture<'a> = Pin<Box<dyn Future<Output = io::Result<Vec<SocketAddr>>> + Send + 'a>>;
308
309/// Local name resolution, used only for direct connections and for the proxy's own host name.
310///
311/// The default is [`SystemResolver`]. Applications can plug in their own (for example DNS over
312/// HTTPS, a static table, or a counter in tests).
313pub trait Resolve: Send + Sync {
314    /// Resolves `host` to socket addresses with the given port.
315    fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a>;
316}
317
318/// The operating system resolver (`getaddrinfo` through [`tokio::net::lookup_host`]).
319#[derive(Debug, Clone, Copy, Default)]
320pub struct SystemResolver;
321
322impl Resolve for SystemResolver {
323    fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a> {
324        Box::pin(async move { Ok(tokio::net::lookup_host((host, port)).await?.collect()) })
325    }
326}
327
328/// Timeouts used by the [`Connector`].
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub struct Timeouts {
331    /// Local DNS resolution (proxy host name or direct target).
332    pub resolve: Duration,
333    /// Each TCP connection attempt (to the proxy or the target).
334    pub connect: Duration,
335    /// The whole SOCKS5 negotiation, from the greeting to the CONNECT reply.
336    pub handshake: Duration,
337}
338
339impl Default for Timeouts {
340    fn default() -> Self {
341        Self {
342            resolve: Duration::from_secs(10),
343            connect: Duration::from_secs(10),
344            handshake: Duration::from_secs(15),
345        }
346    }
347}
348
349/// Which step of [`Connector::connect`] timed out.
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
351pub enum TimeoutStage {
352    /// Local DNS resolution.
353    Resolve,
354    /// The TCP connection attempt.
355    Connect,
356    /// The SOCKS5 negotiation.
357    Handshake,
358}
359
360impl fmt::Display for TimeoutStage {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        f.write_str(match self {
363            Self::Resolve => "DNS resolution",
364            Self::Connect => "TCP connect",
365            Self::Handshake => "SOCKS5 handshake",
366        })
367    }
368}
369
370/// Errors from [`Connector::connect`].
371#[derive(Debug, Error)]
372#[non_exhaustive]
373pub enum ConnectError {
374    /// The policy requires a proxy for this target but none is configured. Nothing was sent.
375    #[error("the proxy policy requires a proxy to connect to {0}, but none is configured")]
376    ProxyRequired(TargetAddr),
377    /// Local DNS resolution failed.
378    #[error("could not resolve {host}: {source}")]
379    Resolve {
380        /// The name being resolved.
381        host: String,
382        /// The resolver error.
383        #[source]
384        source: io::Error,
385    },
386    /// Local DNS resolution returned no addresses.
387    #[error("{0} resolved to no addresses")]
388    NoAddresses(String),
389    /// A step took longer than its [`Timeouts`] entry.
390    #[error("{0} timed out")]
391    Timeout(TimeoutStage),
392    /// The TCP connection to the target (direct) or the proxy failed.
393    #[error("could not connect to {addr}: {source}")]
394    Connect {
395        /// The last address that was tried.
396        addr: SocketAddr,
397        /// The socket error.
398        #[source]
399        source: io::Error,
400    },
401    /// The SOCKS5 negotiation failed (including the proxy refusing the CONNECT).
402    #[error("SOCKS5 proxy {proxy}: {source}")]
403    Socks5 {
404        /// The proxy address (credentials are never included).
405        proxy: TargetAddr,
406        /// What went wrong.
407        #[source]
408        source: Socks5Error,
409    },
410    /// Another socket error (for example setting `TCP_NODELAY`).
411    #[error(transparent)]
412    Io(#[from] io::Error),
413}
414
415/// Opens game connections, directly or through a SOCKS5 proxy.
416///
417/// Cheap to clone; one connector can serve many bots.
418#[derive(Clone)]
419pub struct Connector {
420    proxy: Option<Socks5Proxy>,
421    policy: ProxyPolicy,
422    timeouts: Timeouts,
423    resolver: Arc<dyn Resolve>,
424}
425
426impl Default for Connector {
427    fn default() -> Self {
428        Self::new()
429    }
430}
431
432impl fmt::Debug for Connector {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        f.debug_struct("Connector")
435            .field("proxy", &self.proxy)
436            .field("policy", &self.policy)
437            .field("timeouts", &self.timeouts)
438            .finish_non_exhaustive()
439    }
440}
441
442impl Connector {
443    /// A connector without a proxy, with [`ProxyPolicy::PreferProxy`], default [`Timeouts`] and
444    /// the [`SystemResolver`].
445    pub fn new() -> Self {
446        Self {
447            proxy: None,
448            policy: ProxyPolicy::default(),
449            timeouts: Timeouts::default(),
450            resolver: Arc::new(SystemResolver),
451        }
452    }
453
454    /// Sets the SOCKS5 proxy.
455    pub fn with_proxy(mut self, proxy: Socks5Proxy) -> Self {
456        self.proxy = Some(proxy);
457        self
458    }
459
460    /// Sets or clears the SOCKS5 proxy.
461    pub fn with_optional_proxy(mut self, proxy: Option<Socks5Proxy>) -> Self {
462        self.proxy = proxy;
463        self
464    }
465
466    /// Sets the routing policy.
467    pub fn with_policy(mut self, policy: ProxyPolicy) -> Self {
468        self.policy = policy;
469        self
470    }
471
472    /// Sets the timeouts.
473    pub fn with_timeouts(mut self, timeouts: Timeouts) -> Self {
474        self.timeouts = timeouts;
475        self
476    }
477
478    /// Replaces the local resolver.
479    pub fn with_resolver(mut self, resolver: Arc<dyn Resolve>) -> Self {
480        self.resolver = resolver;
481        self
482    }
483
484    /// The configured proxy, if any.
485    pub fn proxy(&self) -> Option<&Socks5Proxy> {
486        self.proxy.as_ref()
487    }
488
489    /// The routing policy.
490    pub fn policy(&self) -> &ProxyPolicy {
491        &self.policy
492    }
493
494    /// The route [`Connector::connect`] would take for `target`: `Some(true)` through the
495    /// proxy, `Some(false)` directly, `None` if the policy forbids connecting at all.
496    pub fn plan(&self, target: &TargetAddr) -> Option<bool> {
497        match (self.policy.route(target), self.proxy.is_some()) {
498            (Route::Proxy, true) | (Route::PreferProxy, true) => Some(true),
499            (Route::Proxy, false) => None,
500            (Route::PreferProxy, false) | (Route::Direct, _) => Some(false),
501        }
502    }
503
504    /// Connects to `target` according to the policy and returns a stream with `TCP_NODELAY` set.
505    ///
506    /// Through a proxy the stream is positioned right after the SOCKS5 CONNECT reply, so the
507    /// first bytes written are the game's handshake packet.
508    pub async fn connect(&self, target: &TargetAddr) -> Result<TcpStream, ConnectError> {
509        let stream = match (self.plan(target), &self.proxy) {
510            (None, _) => return Err(ConnectError::ProxyRequired(target.clone())),
511            (Some(true), Some(proxy)) => self.connect_via_proxy(proxy, target).await?,
512            (Some(_), _) => self.connect_addr(target).await?,
513        };
514        stream.set_nodelay(true)?;
515        Ok(stream)
516    }
517
518    async fn connect_via_proxy(
519        &self,
520        proxy: &Socks5Proxy,
521        target: &TargetAddr,
522    ) -> Result<TcpStream, ConnectError> {
523        let mut stream = self.connect_addr(proxy.addr()).await?;
524        // Disable Nagle before the negotiation so its small writes are not delayed.
525        stream.set_nodelay(true)?;
526        let negotiation = socks5::handshake(&mut stream, target, proxy.auth());
527        match tokio::time::timeout(self.timeouts.handshake, negotiation).await {
528            Err(_) => Err(ConnectError::Timeout(TimeoutStage::Handshake)),
529            Ok(Err(source)) => Err(ConnectError::Socks5 {
530                proxy: proxy.addr().clone(),
531                source,
532            }),
533            Ok(Ok(_bound)) => Ok(stream),
534        }
535    }
536
537    /// Opens a plain TCP connection, resolving `addr` locally if it is a domain name.
538    async fn connect_addr(&self, addr: &TargetAddr) -> Result<TcpStream, ConnectError> {
539        let candidates = match addr {
540            TargetAddr::Ip(ip) => vec![*ip],
541            TargetAddr::Domain(host, port) => {
542                let lookup = self.resolver.resolve(host, *port);
543                let addrs = match tokio::time::timeout(self.timeouts.resolve, lookup).await {
544                    Err(_) => return Err(ConnectError::Timeout(TimeoutStage::Resolve)),
545                    Ok(Err(source)) => {
546                        return Err(ConnectError::Resolve {
547                            host: host.clone(),
548                            source,
549                        });
550                    }
551                    Ok(Ok(addrs)) => addrs,
552                };
553                if addrs.is_empty() {
554                    return Err(ConnectError::NoAddresses(host.clone()));
555                }
556                addrs
557            }
558        };
559        let mut last_err = None;
560        for candidate in candidates {
561            match tokio::time::timeout(self.timeouts.connect, TcpStream::connect(candidate)).await {
562                Ok(Ok(stream)) => return Ok(stream),
563                Ok(Err(source)) => {
564                    last_err = Some(ConnectError::Connect {
565                        addr: candidate,
566                        source,
567                    })
568                }
569                Err(_) => last_err = Some(ConnectError::Timeout(TimeoutStage::Connect)),
570            }
571        }
572        // `candidates` is never empty here, so an error was recorded.
573        Err(last_err.unwrap_or(ConnectError::Timeout(TimeoutStage::Connect)))
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    fn ip(s: &str) -> TargetAddr {
582        TargetAddr::Ip(s.parse().unwrap())
583    }
584
585    #[test]
586    fn parse_targets() {
587        assert_eq!("1.2.3.4:25565".parse(), Ok(ip("1.2.3.4:25565")));
588        assert_eq!("[::1]:80".parse(), Ok(ip("[::1]:80")));
589        assert_eq!(
590            "mc.example.net:25570".parse(),
591            Ok(TargetAddr::Domain("mc.example.net".into(), 25570))
592        );
593        assert_eq!(
594            "mc.example.net".parse::<TargetAddr>(),
595            Err(AddrError::MissingPort)
596        );
597        assert_eq!(
598            TargetAddr::parse_with_default_port("mc.example.net", 25565),
599            Ok(TargetAddr::Domain("mc.example.net".into(), 25565))
600        );
601        assert_eq!(
602            TargetAddr::parse_with_default_port("::1", 25565),
603            Ok(ip("[::1]:25565"))
604        );
605        assert_eq!(
606            TargetAddr::parse_with_default_port("[fe80::1]", 1),
607            Ok(ip("[fe80::1]:1"))
608        );
609        assert_eq!(
610            "host:99999".parse::<TargetAddr>(),
611            Err(AddrError::InvalidPort("99999".into()))
612        );
613        assert_eq!(":25565".parse::<TargetAddr>(), Err(AddrError::EmptyHost));
614        assert!(matches!(
615            "[::1".parse::<TargetAddr>(),
616            Err(AddrError::InvalidIpv6(_))
617        ));
618        assert!(matches!(
619            "[nope]:1".parse::<TargetAddr>(),
620            Err(AddrError::InvalidIpv6(_))
621        ));
622        assert_eq!(
623            "bad host:1".parse::<TargetAddr>(),
624            Err(AddrError::InvalidDomainChar(' '))
625        );
626        assert_eq!(
627            "b\u{fc}cher.de:1".parse::<TargetAddr>(),
628            Err(AddrError::InvalidDomainChar('\u{fc}'))
629        );
630        let long = format!("{}:1", "a".repeat(256));
631        assert_eq!(
632            long.parse::<TargetAddr>(),
633            Err(AddrError::DomainTooLong(256))
634        );
635    }
636
637    #[test]
638    fn new_and_display() {
639        assert_eq!(TargetAddr::new("::1", 5), Ok(ip("[::1]:5")));
640        assert_eq!(TargetAddr::new("[::1]", 5), Ok(ip("[::1]:5")));
641        assert_eq!(TargetAddr::new("10.0.0.1", 5), Ok(ip("10.0.0.1:5")));
642        assert!(TargetAddr::new("[x]", 5).is_err());
643        assert_eq!(
644            TargetAddr::new("a.b", 7).unwrap().to_string(),
645            "a.b:7".to_owned()
646        );
647        assert_eq!(ip("[::1]:5").to_string(), "[::1]:5");
648        assert_eq!(ip("[::1]:5").host(), "::1");
649    }
650
651    #[test]
652    fn locality() {
653        for local in [
654            "127.0.0.1:1",
655            "10.1.2.3:1",
656            "172.16.0.1:1",
657            "10.0.0.10:25570",
658            "169.254.1.1:1",
659            "[::1]:1",
660            "[fd00::1]:1",
661            "[fe80::1]:1",
662            "[::ffff:10.0.0.1]:1",
663        ] {
664            assert!(ip(local).is_local(), "{local}");
665        }
666        for public in [
667            "8.8.8.8:1",
668            "100.64.0.1:1",
669            "172.32.0.1:1",
670            "[2001:db8::1]:1",
671            "[::ffff:8.8.8.8]:1",
672        ] {
673            assert!(!ip(public).is_local(), "{public}");
674        }
675        assert!(TargetAddr::new("localhost", 1).unwrap().is_local());
676        assert!(TargetAddr::new("LocalHost.", 1).unwrap().is_local());
677        assert!(TargetAddr::new("a.localhost", 1).unwrap().is_local());
678        assert!(!TargetAddr::new("lan-server", 1).unwrap().is_local());
679        assert!(!TargetAddr::new("localhost.example", 1).unwrap().is_local());
680    }
681
682    #[test]
683    fn policies() {
684        let lan = ip("10.0.0.10:25570");
685        let public = TargetAddr::new("mc.example.net", 25565).unwrap();
686        assert_eq!(ProxyPolicy::PreferProxy.route(&public), Route::PreferProxy);
687        assert_eq!(ProxyPolicy::RequireProxy.route(&lan), Route::Proxy);
688        assert_eq!(
689            ProxyPolicy::RequireProxyExceptLocal.route(&lan),
690            Route::Direct
691        );
692        assert_eq!(
693            ProxyPolicy::RequireProxyExceptLocal.route(&public),
694            Route::Proxy
695        );
696        let custom = ProxyPolicy::custom(|t| {
697            if t.port() == 25570 {
698                Route::Direct
699            } else {
700                Route::Proxy
701            }
702        });
703        assert_eq!(custom.route(&lan), Route::Direct);
704        assert_eq!(custom.route(&public), Route::Proxy);
705        assert_eq!(format!("{custom:?}"), "Custom(..)");
706    }
707
708    #[test]
709    fn plan() {
710        let lan = ip("10.0.0.10:25570");
711        let public = ip("8.8.8.8:25565");
712        let proxy: Socks5Proxy = "socks5h://127.0.0.1:1080".parse().unwrap();
713
714        let none = Connector::new().with_policy(ProxyPolicy::RequireProxyExceptLocal);
715        assert_eq!(none.plan(&lan), Some(false));
716        assert_eq!(none.plan(&public), None);
717
718        let some = none.clone().with_proxy(proxy.clone());
719        assert_eq!(some.plan(&lan), Some(false));
720        assert_eq!(some.plan(&public), Some(true));
721
722        let prefer = Connector::new();
723        assert_eq!(prefer.plan(&public), Some(false));
724        assert_eq!(prefer.clone().with_proxy(proxy).plan(&public), Some(true));
725    }
726}