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
use std::error::Error;
use std::net::IpAddr;
use std::path::PathBuf;
use std::str::FromStr;
use structopt::{clap::arg_enum, StructOpt};
use trust_dns_resolver::Resolver;
#[derive(StructOpt, Debug)]
pub enum TunnelerType {
Tcp,
Dns {
#[structopt(env)]
read_timeout_in_milliseconds: u64,
#[structopt(env)]
idle_client_timeout_in_milliseconds: u64,
#[structopt(default_value = "", env)]
client_suffix: String,
},
Tls {
#[structopt(env)]
ca_cert: PathBuf,
#[structopt(env)]
cert: PathBuf,
#[structopt(env)]
key: PathBuf,
#[structopt(env)]
server_hostname: String,
},
}
arg_enum! {
#[derive(Debug)]
pub enum TunneledType {
Tcp,
Udp,
}
}
fn parse_or_resolve_ip(src: &str) -> Result<IpAddr, Box<dyn Error>> {
IpAddr::from_str(src).or_else(|_| {
let resolver = Resolver::from_system_conf()?;
let response = resolver.lookup_ip(src)?;
response
.iter()
.next()
.ok_or_else(|| format!("failed to parse or resolve {} to an IP", src).into())
})
}
#[derive(StructOpt, Debug)]
pub struct Cli {
#[structopt(subcommand)]
pub tunneler_type: TunnelerType,
#[structopt(env, possible_values = &TunneledType::variants(), case_insensitive = true)]
pub tunneled_type: TunneledType,
#[structopt(env, parse(try_from_str = parse_or_resolve_ip))]
pub remote_address: IpAddr,
#[structopt(env)]
pub remote_port: u16,
#[structopt(default_value = "0.0.0.0", long, env)]
pub local_address: IpAddr,
#[structopt(default_value = "8888", long, env)]
pub local_port: u16,
#[structopt(default_value = "info", long, env)]
pub log_level: log::LevelFilter,
}
#[cfg(test)]
mod tests {
use std::net::{Ipv4Addr, Ipv6Addr};
use super::*;
#[test]
fn parse_or_resolve_ip_ipv4() -> Result<(), Box<dyn Error>> {
let res = parse_or_resolve_ip("127.0.0.1")?;
assert_eq!(res, IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
Ok(())
}
#[test]
fn parse_or_resolve_ip_ipv6() -> Result<(), Box<dyn Error>> {
let res = parse_or_resolve_ip("::1")?;
assert_eq!(res, IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
Ok(())
}
#[test]
fn parse_or_resolve_ip_lookup_success() -> Result<(), Box<dyn Error>> {
let res = parse_or_resolve_ip("localhost")?;
assert_eq!(res, IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
Ok(())
}
#[test]
fn parse_or_resolve_ip_lookup_fail() -> Result<(), Box<dyn Error>> {
let res = parse_or_resolve_ip("blablabla");
assert!(res.is_err());
Ok(())
}
}