use std::{
path::PathBuf,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use crate::fronts::parse_fronts;
use async_net::{Ipv4Addr, SocketAddr};
use bytes::Bytes;
use geph4_protocol::binder::client::{CachedBinderClient, DynBinderClient};
use geph4_protocol::binder::protocol::BinderClient;
use once_cell::sync::{Lazy, OnceCell};
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
static INIT_CONFIG: OnceCell<Opt> = OnceCell::new();
pub fn override_config(opt: Opt) {
INIT_CONFIG.get_or_init(|| opt);
}
pub static CONFIG: Lazy<Opt> = Lazy::new(|| INIT_CONFIG.get_or_init(Opt::from_args).clone());
#[derive(Debug, StructOpt, Deserialize, Serialize, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Opt {
Connect(ConnectOpt),
BridgeTest(crate::main_bridgetest::BridgeTestOpt),
Sync(crate::sync::SyncOpt),
BinderProxy(crate::binderproxy::BinderProxyOpt),
}
#[derive(Debug, StructOpt, Clone, Deserialize, Serialize)]
pub struct ConnectOpt {
#[structopt(flatten)]
pub common: CommonOpt,
#[structopt(flatten)]
pub auth: AuthOpt,
#[structopt(long)]
pub use_bridges: bool,
#[structopt(long)]
pub override_connect: Option<String>,
#[structopt(long)]
pub force_bridge: Option<Ipv4Addr>,
#[structopt(long, default_value = "1")]
pub udp_shard_count: usize,
#[structopt(long, default_value = "30")]
pub udp_shard_lifetime: u64,
#[structopt(long, default_value = "6")]
pub tcp_shard_count: usize,
#[structopt(long, default_value = "1")]
pub tcp_shard_lifetime: u64,
#[structopt(long, default_value = "127.0.0.1:9910")]
pub http_listen: SocketAddr,
#[structopt(long, default_value = "127.0.0.1:9909")]
pub socks5_listen: SocketAddr,
#[structopt(long, default_value = "127.0.0.1:9809")]
pub stats_listen: SocketAddr,
#[structopt(long, default_value = "127.0.0.1:15353")]
pub dns_listen: SocketAddr,
#[structopt(long)]
pub exit_server: Option<String>,
#[structopt(long)]
pub exclude_prc: bool,
#[structopt(long)]
pub stdio_vpn: bool,
#[structopt(long)]
pub sticky_bridges: bool,
#[structopt(long)]
pub vpn_mode: Option<VpnMode>,
#[structopt(long)]
pub use_tcp: bool,
#[structopt(long)]
pub forward_ports: Vec<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Serialize, Deserialize)]
pub enum VpnMode {
InheritedFd,
TunNoRoute,
TunRoute,
WinDivert,
Stdio,
}
impl FromStr for VpnMode {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"inherited-fd" => Ok(Self::InheritedFd),
"tun-no-route" => Ok(Self::TunNoRoute),
"tun-route" => Ok(Self::TunRoute),
"windivert" => Ok(Self::WinDivert),
"stdio" => Ok(Self::Stdio),
x => anyhow::bail!("unrecognized VPN mode {}", x),
}
}
}
#[derive(Debug, StructOpt, Clone, Deserialize, Serialize)]
pub struct CommonOpt {
#[structopt(
long,
default_value = "https://www.netlify.com/v4/next-gen,https://www.cdn77.com/next-gen,https://ajax.aspnetcdn.com/next-gen,https://d1hoqe10mv32pv.cloudfront.net/next-gen"
)]
binder_http_fronts: String,
#[structopt(
long,
default_value = "svitania-naidallszei.netlify.app,1049933718.rsc.cdn77.org,gephbinder-4.azureedge.net,dtnins2n354c4.cloudfront.net"
)]
binder_http_hosts: String,
#[structopt(
long,
default_value = "124526f4e692b589511369687498cce57492bf4da20f8d26019c1cc0c80b6e4b",
parse(from_str = str_to_x25519_pk)
)]
binder_master: x25519_dalek::PublicKey,
#[structopt(
long,
default_value = "4e01116de3721cc702f4c260977f4a1809194e9d3df803e17bb90db2a425e5ee",
parse(from_str = str_to_mizaru_pk)
)]
binder_mizaru_free: mizaru::PublicKey,
#[structopt(
long,
default_value = "44ab86f527fbfb5a038cc51a49e0467be6eb532c4b9c6cb5cdb430926c95bdab",
parse(from_str = str_to_mizaru_pk)
)]
binder_mizaru_plus: mizaru::PublicKey,
}
impl CommonOpt {
pub fn get_binder_client(&self) -> DynBinderClient {
BinderClient(parse_fronts(
*self.binder_master.as_bytes(),
self.binder_http_fronts
.split(',')
.zip(self.binder_http_hosts.split(','))
.map(|(k, v)| (k.to_string(), v.to_string())),
))
}
}
#[derive(Debug, StructOpt, Clone, Deserialize, Serialize)]
pub struct AuthOpt {
#[structopt(
long,
default_value = "auto",
parse(from_str = str_to_path)
)]
pub credential_cache: PathBuf,
#[structopt(long, default_value = "")]
pub username: String,
#[structopt(long, default_value = "")]
pub password: String,
}
fn str_to_path(src: &str) -> PathBuf {
if src == "auto" {
let mut config_dir = dirs::config_dir().unwrap();
config_dir.push("geph4-credentials");
config_dir
} else {
PathBuf::from(src)
}
}
fn str_to_x25519_pk(src: &str) -> x25519_dalek::PublicKey {
let raw_bts = hex::decode(src).unwrap();
let raw_bts: [u8; 32] = raw_bts.as_slice().try_into().unwrap();
x25519_dalek::PublicKey::from(raw_bts)
}
fn str_to_mizaru_pk(src: &str) -> mizaru::PublicKey {
let raw_bts = hex::decode(src).unwrap();
let raw_bts: [u8; 32] = raw_bts.as_slice().try_into().unwrap();
mizaru::PublicKey(raw_bts)
}
pub fn get_cached_binder_client(
common_opt: &CommonOpt,
auth_opt: &AuthOpt,
) -> anyhow::Result<CachedBinderClient> {
let mut dbpath = auth_opt.credential_cache.clone();
let quasi_user_id = hex::encode(
blake3::keyed_hash(
blake3::hash(auth_opt.password.as_bytes()).as_bytes(),
auth_opt.username.as_bytes(),
)
.as_bytes(),
);
dbpath.push(&quasi_user_id);
std::fs::create_dir_all(&dbpath)?;
let cbc = CachedBinderClient::new(
{
let dbpath = dbpath.clone();
move |key| {
let mut dbpath = dbpath.clone();
dbpath.push(format!("{}.json", key));
let r = std::fs::read(dbpath).ok()?;
let (tstamp, bts): (u64, Bytes) = bincode::deserialize(&r).ok()?;
if tstamp > SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() {
Some(bts)
} else {
None
}
}
},
{
let dbpath = dbpath.clone();
move |k, v, expires| {
let noviy_taymstamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
+ expires.as_secs();
let to_write =
bincode::serialize(&(noviy_taymstamp, Bytes::copy_from_slice(v))).unwrap();
let mut dbpath = dbpath.clone();
dbpath.push(format!("{}.json", k));
let _ = std::fs::write(dbpath, to_write);
}
},
common_opt.get_binder_client(),
&auth_opt.username,
&auth_opt.password,
);
Ok(cbc)
}