use std::{
collections::HashSet,
ffi::OsString,
fmt,
fs::read_to_string,
io,
net::{IpAddr, Ipv6Addr},
os::unix::prelude::IntoRawFd,
path::{Path, PathBuf},
};
use derivative::Derivative;
use duct::{cmd, Handle};
use ipnet::IpNet;
use itertools::Itertools;
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use shadowsocks_gtk_rs::consts::*;
use which::which;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetadataOverride {
display_name: Option<String>,
pwd: Option<PathBuf>,
bin_path: Option<PathBuf>,
}
trait ToLaunchArgs {
fn to_launch_args(&self) -> Vec<OsString>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigFileOptions {
config_path: PathBuf,
}
impl ToLaunchArgs for ConfigFileOptions {
fn to_launch_args(&self) -> Vec<OsString> {
vec!["--config".into(), (&self.config_path).into()]
}
}
#[derive(Derivative, Clone, Serialize, Deserialize)]
#[derivative(Debug)]
pub struct ConnectOptions {
local_addr: (IpAddr, u16),
server_addr: (String, u16),
#[derivative(Debug(format_with = "password_omit"))]
password: String,
encrypt_method: String,
}
impl ToLaunchArgs for ConnectOptions {
fn to_launch_args(&self) -> Vec<OsString> {
let mut args = vec![];
let local_addr = {
let (a, p) = self.local_addr;
match a {
IpAddr::V4(v4) => format!("{}:{}", v4, p),
IpAddr::V6(v6) => format!("[{}]:{}", v6, p),
}
};
args.extend_from_slice(&["--local-addr".into(), local_addr.into()]);
let server_addr = {
let (a, p) = &self.server_addr;
match a.parse::<Ipv6Addr>() {
Ok(_) => format!("[{}]:{}", a, p), Err(_) => format!("{}:{}", a, p), }
};
args.extend_from_slice(&["--server-addr".into(), server_addr.into()]);
args.extend_from_slice(&["--password".into(), (&self.password).into()]);
args.extend_from_slice(&["--encrypt-method".into(), (&self.encrypt_method).into()]);
args
}
}
fn password_omit(_: &str, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "*hidden*")
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyOptions {
}
impl ToLaunchArgs for ProxyOptions {
fn to_launch_args(&self) -> Vec<OsString> {
vec![]
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TunOptions {
if_name: Option<String>,
if_addr: Option<IpNet>,
}
impl ToLaunchArgs for TunOptions {
fn to_launch_args(&self) -> Vec<OsString> {
let mut args = vec!["--protocol".into(), "tun".into()];
if let Some(if_name) = &self.if_name {
args.extend_from_slice(&["--tun-interface-name".into(), if_name.into()]);
}
if let Some(if_addr) = &self.if_addr {
args.extend_from_slice(&["--tun-interface-address".into(), if_addr.to_string().into()]);
}
args
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedOptions {
extra_args: Option<Vec<String>>,
}
impl ToLaunchArgs for AdvancedOptions {
fn to_launch_args(&self) -> Vec<OsString> {
let mut args = vec![];
if let Some(extra) = &self.extra_args {
args.append(&mut extra.iter().map_into().collect())
}
args
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "kebab-case")] pub enum ProfileConfig {
ConfigFile {
#[serde(flatten)]
metadata: MetadataOverride,
#[serde(flatten)]
opts: ConfigFileOptions,
#[serde(flatten)]
adv_opts: AdvancedOptions,
},
Proxy {
#[serde(flatten)]
metadata: MetadataOverride,
#[serde(flatten)]
conn_opts: ConnectOptions,
#[serde(flatten)]
opts: ProxyOptions,
#[serde(flatten)]
adv_opts: AdvancedOptions,
},
Tun {
#[serde(flatten)]
metadata: MetadataOverride,
#[serde(flatten)]
conn_opts: ConnectOptions,
#[serde(flatten)]
opts: TunOptions,
#[serde(flatten)]
adv_opts: AdvancedOptions,
},
}
impl ProfileConfig {
fn get_metadata_override(&self) -> &MetadataOverride {
use ProfileConfig::*;
match self {
ConfigFile { metadata, .. } => metadata,
Proxy { metadata, .. } => metadata,
Tun { metadata, .. } => metadata,
}
}
fn to_launch_args(&self) -> Vec<OsString> {
use ProfileConfig::*;
match self {
ConfigFile { opts, adv_opts, .. } => {
let mut args = opts.to_launch_args();
args.append(&mut adv_opts.to_launch_args());
args
}
Proxy {
conn_opts,
opts,
adv_opts,
..
} => {
let mut args = conn_opts.to_launch_args();
args.append(&mut opts.to_launch_args());
args.append(&mut adv_opts.to_launch_args());
args
}
Tun {
conn_opts,
opts,
adv_opts,
..
} => {
let mut args = conn_opts.to_launch_args();
args.append(&mut opts.to_launch_args());
args.append(&mut adv_opts.to_launch_args());
args
}
}
}
}
#[derive(Debug, Clone)]
pub struct ProfileMetadata {
pub display_name: String,
pwd: PathBuf,
bin_path: PathBuf,
}
#[derive(Debug, Clone)]
pub struct Profile {
pub metadata: ProfileMetadata,
config: ProfileConfig,
}
impl Profile {
pub fn run_sslocal(&self, stdout: Option<impl IntoRawFd>, stderr: Option<impl IntoRawFd>) -> io::Result<Handle> {
let ProfileMetadata { pwd, bin_path, .. } = &self.metadata;
let mut expr = cmd(bin_path, self.config.to_launch_args()).dir(pwd).stdin_null();
expr = match stdout {
Some(fd) => expr.stdout_file(fd),
None => expr.stdout_null(),
};
expr = match stderr {
Some(fd) => expr.stderr_file(fd),
None => expr.stderr_null(),
};
expr.unchecked() .start()
}
}
#[derive(Debug, Clone)]
pub struct ProfileGroup {
pub display_name: String,
pub content: Vec<ProfileFolder>,
}
#[derive(Debug)]
pub enum ProfileLoadError {
NotDirectory(String),
ConfigParseError(serde_yaml::Error),
BadBinary(which::Error),
NameConflict(String),
NoConfigFile(String),
EmptyGroup(String),
IOError(io::Error),
}
impl fmt::Display for ProfileLoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ProfileLoadError::*;
let prefix = "ProfileLoadError";
match self {
NotDirectory(s) => write!(f, "{}-NotDirectory: {}", prefix, s),
ConfigParseError(e) => write!(f, "{}-ConfigParseError: {}", prefix, e),
BadBinary(e) => write!(f, "{}-BadBinary: {}", prefix, e),
NameConflict(s) => write!(f, "{}-NameConflict: {}", prefix, s),
NoConfigFile(s) => write!(f, "{}-NoConfigFile: {}", prefix, s),
EmptyGroup(s) => write!(f, "{}-EmptyGroup: {}", prefix, s),
IOError(e) => write!(f, "{}-IOError: {}", prefix, e),
}
}
}
impl From<serde_yaml::Error> for ProfileLoadError {
fn from(err: serde_yaml::Error) -> Self {
Self::ConfigParseError(err)
}
}
impl From<which::Error> for ProfileLoadError {
fn from(err: which::Error) -> Self {
Self::BadBinary(err)
}
}
impl From<io::Error> for ProfileLoadError {
fn from(err: io::Error) -> Self {
Self::IOError(err)
}
}
#[derive(Derivative, Clone)]
#[derivative(Debug)]
pub enum ProfileFolder {
#[derivative(Debug = "transparent")]
Profile(Profile),
#[derivative(Debug = "transparent")]
Group(ProfileGroup),
}
impl ProfileFolder {
pub fn from_path_recurse(path: impl AsRef<Path>) -> Result<Self, ProfileLoadError> {
let mut seen_names = HashSet::new();
Self::from_path_recurse_impl(path.as_ref(), &mut seen_names)?
.ok_or(ProfileLoadError::EmptyGroup(path.as_ref().to_string_lossy().into()))
}
fn from_path_recurse_impl(
path: impl AsRef<Path>,
seen_names: &mut HashSet<String>,
) -> Result<Option<Self>, ProfileLoadError> {
let path = path.as_ref().canonicalize()?;
let full_path_str = path.to_string_lossy();
if !path.is_dir() {
return Err(ProfileLoadError::NotDirectory(full_path_str.into()));
}
if path.join(PROFILE_IGNORE_FILE_NAME).is_file() {
return Ok(None);
}
let default_display_name = path
.file_name()
.unwrap() .to_str()
.unwrap() .to_string();
let config_path = path.join(PROFILE_CONFIG_FILE_NAME);
if config_path.is_file() {
let content = read_to_string(config_path)?;
let config: ProfileConfig = serde_yaml::from_str(&content)?;
let metadata = {
let mo = config.get_metadata_override().clone();
let display_name = mo.display_name.unwrap_or(default_display_name);
if let Some(_) = seen_names.replace(display_name.clone()) {
return Err(ProfileLoadError::NameConflict(display_name));
}
let pwd = mo.pwd.unwrap_or(path.clone());
let bin_path = mo
.bin_path
.map(|p| which(p))
.unwrap_or(which(SSLOCAL_LOOKUP_NAME_DEFAULT))?;
ProfileMetadata {
display_name,
pwd,
bin_path,
}
};
return Ok(Some(Self::Profile(Profile { metadata, config })));
}
let has_files = path.read_dir()?.any(|ent_res| match ent_res {
Ok(ent) => ent.path().is_file(),
Err(err) => {
warn!("Cannot open a file or directory: {}", err);
false
}
});
if has_files {
return Err(ProfileLoadError::NoConfigFile(full_path_str.into()));
}
let mut subdirs = vec![];
for ent_res in path.read_dir()? {
let subdir_path = ent_res?.path();
match Self::from_path_recurse_impl(&subdir_path, seen_names) {
Ok(Some(cf)) => subdirs.push(cf),
Ok(None) => info!("Ignored a directory and its children: {:?}", subdir_path),
Err(err) => return Err(err),
};
}
if subdirs.is_empty() {
error!(
"The specified profile directory is empty; \
please read Q&A for a guide on creating a configuration"
);
error!("See https://github.com/spyophobia/shadowsocks-gtk-rs/blob/master/res/QnA.md");
Err(ProfileLoadError::EmptyGroup(full_path_str.into()))
} else {
Ok(Some(ProfileFolder::Group(ProfileGroup {
display_name: default_display_name,
content: subdirs,
})))
}
}
pub fn profile_count(&self) -> usize {
use ProfileFolder::*;
match self {
Profile(_) => 1,
Group(g) => g.content.iter().map(|pf| pf.profile_count()).sum(),
}
}
#[allow(dead_code)]
pub fn get_profiles(&self) -> Vec<&Profile> {
use ProfileFolder::*;
match self {
Profile(p) => vec![p],
Group(g) => g.content.iter().flat_map(|pf| pf.get_profiles()).collect(),
}
}
pub fn lookup(&self, name: impl AsRef<str>) -> Option<&Profile> {
use ProfileFolder::*;
match self {
Profile(p) if p.metadata.display_name == name.as_ref() => Some(p),
Profile(_) => None,
Group(g) => g.content.iter().find_map(|pf| pf.lookup(name.as_ref())),
}
}
}