Files
clash-proxy/src-tauri/src/core/sysopt.rs

411 lines
14 KiB
Rust
Raw Normal View History

2024-05-26 17:59:39 +08:00
use crate::{
config::{Config, IVerge},
log_err,
};
use anyhow::{anyhow, Result};
2022-04-20 01:44:47 +08:00
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
2022-11-14 01:26:33 +08:00
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
2024-04-13 15:45:50 +08:00
use std::env::current_exe;
2022-04-20 01:44:47 +08:00
use std::sync::Arc;
2024-05-26 17:59:39 +08:00
use sysproxy::{Autoproxy, Sysproxy};
2024-04-13 15:45:50 +08:00
use tauri::async_runtime::Mutex as TokioMutex;
2022-04-20 01:44:47 +08:00
pub struct Sysopt {
2022-11-12 11:37:23 +08:00
/// current system proxy setting
2022-11-14 01:26:33 +08:00
cur_sysproxy: Arc<Mutex<Option<Sysproxy>>>,
2022-04-20 01:44:47 +08:00
2022-11-12 11:37:23 +08:00
/// record the original system proxy
/// recover it when exit
2022-11-14 01:26:33 +08:00
old_sysproxy: Arc<Mutex<Option<Sysproxy>>>,
2022-04-20 01:44:47 +08:00
2024-05-26 17:59:39 +08:00
/// current auto proxy setting
cur_autoproxy: Arc<Mutex<Option<Autoproxy>>>,
/// record the original auto proxy
/// recover it when exit
old_autoproxy: Arc<Mutex<Option<Autoproxy>>>,
2022-11-12 11:37:23 +08:00
/// helps to auto launch the app
2022-11-14 01:26:33 +08:00
auto_launch: Arc<Mutex<Option<AutoLaunch>>>,
2022-04-20 01:44:47 +08:00
2022-11-12 11:37:23 +08:00
/// record whether the guard async is running or not
2022-11-14 01:26:33 +08:00
guard_state: Arc<TokioMutex<bool>>,
2022-04-20 01:44:47 +08:00
}
2022-09-11 20:58:55 +08:00
#[cfg(target_os = "windows")]
static DEFAULT_BYPASS: &str = "localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;<local>";
2022-09-11 20:58:55 +08:00
#[cfg(target_os = "linux")]
static DEFAULT_BYPASS: &str = "localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1";
2022-09-11 20:58:55 +08:00
#[cfg(target_os = "macos")]
2023-12-01 12:56:18 +08:00
static DEFAULT_BYPASS: &str =
"127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>";
2022-09-11 20:58:55 +08:00
2024-06-09 12:45:57 +08:00
fn get_bypass() -> String {
let bypass = DEFAULT_BYPASS.to_string();
2024-06-12 10:00:22 +08:00
let res = {
2024-06-09 12:45:57 +08:00
let verge = Config::verge();
let verge = verge.latest();
verge.system_proxy_bypass.clone()
2024-06-12 10:00:22 +08:00
};
let custom_bypass = match res {
2024-06-09 12:45:57 +08:00
Some(bypass) => bypass,
None => "".to_string(),
};
#[cfg(target_os = "windows")]
let bypass = if custom_bypass.is_empty() {
bypass
} else {
format!("{};{}", bypass, custom_bypass)
};
#[cfg(not(target_os = "windows"))]
let bypass = if custom_bypass.is_empty() {
bypass
} else {
format!("{},{}", bypass, custom_bypass)
};
2024-06-12 10:00:22 +08:00
bypass
2024-06-09 12:45:57 +08:00
}
2022-04-20 01:44:47 +08:00
impl Sysopt {
2022-11-14 01:26:33 +08:00
pub fn global() -> &'static Sysopt {
static SYSOPT: OnceCell<Sysopt> = OnceCell::new();
SYSOPT.get_or_init(|| Sysopt {
cur_sysproxy: Arc::new(Mutex::new(None)),
old_sysproxy: Arc::new(Mutex::new(None)),
2024-05-26 17:59:39 +08:00
cur_autoproxy: Arc::new(Mutex::new(None)),
old_autoproxy: Arc::new(Mutex::new(None)),
2022-11-14 01:26:33 +08:00
auto_launch: Arc::new(Mutex::new(None)),
guard_state: Arc::new(TokioMutex::new(false)),
})
2022-04-20 01:44:47 +08:00
}
2022-11-12 11:37:23 +08:00
/// init the sysproxy
2022-11-14 01:26:33 +08:00
pub fn init_sysproxy(&self) -> Result<()> {
2023-12-01 12:56:18 +08:00
let port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
2024-05-26 17:59:39 +08:00
let pac_port = IVerge::get_singleton_port();
2022-09-11 20:58:55 +08:00
2024-06-09 12:45:57 +08:00
let (enable, pac) = {
2022-11-16 01:26:41 +08:00
let verge = Config::verge();
let verge = verge.latest();
(
2024-01-10 17:36:35 +08:00
verge.enable_system_proxy.unwrap_or(false),
2024-05-26 17:59:39 +08:00
verge.proxy_auto_config.unwrap_or(false),
2022-11-16 01:26:41 +08:00
)
};
2024-05-26 19:07:14 +08:00
let mut sys = Sysproxy {
enable,
host: String::from("127.0.0.1"),
port,
2024-06-09 12:45:57 +08:00
bypass: get_bypass(),
2024-05-26 19:07:14 +08:00
};
let mut auto = Autoproxy {
enable,
url: format!("http://127.0.0.1:{pac_port}/commands/pac"),
};
if pac {
sys.enable = false;
2024-05-26 17:59:39 +08:00
let old = Sysproxy::get_system_proxy().ok();
sys.set_system_proxy()?;
*self.old_sysproxy.lock() = old;
*self.cur_sysproxy.lock() = Some(sys);
2024-05-26 19:07:14 +08:00
2024-05-26 17:59:39 +08:00
let old = Autoproxy::get_auto_proxy().ok();
auto.set_auto_proxy()?;
*self.old_autoproxy.lock() = old;
*self.cur_autoproxy.lock() = Some(auto);
} else {
2024-05-26 19:07:14 +08:00
auto.enable = false;
2024-05-26 17:59:39 +08:00
let old = Autoproxy::get_auto_proxy().ok();
auto.set_auto_proxy()?;
*self.old_autoproxy.lock() = old;
*self.cur_autoproxy.lock() = Some(auto);
2024-05-26 19:07:14 +08:00
2024-01-10 17:36:35 +08:00
let old = Sysproxy::get_system_proxy().ok();
2024-05-26 17:59:39 +08:00
sys.set_system_proxy()?;
2022-11-14 01:26:33 +08:00
*self.old_sysproxy.lock() = old;
2024-05-26 17:59:39 +08:00
*self.cur_sysproxy.lock() = Some(sys);
2022-11-12 11:37:23 +08:00
}
2022-04-20 01:44:47 +08:00
2022-11-12 11:37:23 +08:00
// run the system proxy guard
self.guard_proxy();
Ok(())
2022-04-20 01:44:47 +08:00
}
2022-11-12 11:37:23 +08:00
/// update the system proxy
2022-11-14 01:26:33 +08:00
pub fn update_sysproxy(&self) -> Result<()> {
let mut cur_sysproxy = self.cur_sysproxy.lock();
let old_sysproxy = self.old_sysproxy.lock();
2024-05-26 17:59:39 +08:00
let mut cur_autoproxy = self.cur_autoproxy.lock();
let old_autoproxy = self.old_autoproxy.lock();
2022-11-14 01:26:33 +08:00
2024-06-09 12:45:57 +08:00
let (enable, pac) = {
2022-11-16 01:26:41 +08:00
let verge = Config::verge();
let verge = verge.latest();
(
2024-01-10 17:36:35 +08:00
verge.enable_system_proxy.unwrap_or(false),
2024-05-26 17:59:39 +08:00
verge.proxy_auto_config.unwrap_or(false),
2022-11-16 01:26:41 +08:00
)
};
2024-06-12 10:00:22 +08:00
if pac && (cur_autoproxy.is_none() || old_autoproxy.is_none()) {
drop(cur_autoproxy);
drop(old_autoproxy);
return self.init_sysproxy();
2024-05-26 17:59:39 +08:00
}
2024-06-12 10:00:22 +08:00
if !pac && (cur_sysproxy.is_none() || old_sysproxy.is_none()) {
drop(cur_sysproxy);
drop(old_sysproxy);
return self.init_sysproxy();
}
2024-05-26 17:59:39 +08:00
let port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
let pac_port = IVerge::get_singleton_port();
2022-09-26 01:35:19 +08:00
2024-05-26 17:59:39 +08:00
let mut sysproxy = cur_sysproxy.take().unwrap();
2024-06-09 12:45:57 +08:00
sysproxy.bypass = get_bypass();
sysproxy.port = port;
2024-05-26 17:59:39 +08:00
let mut autoproxy = cur_autoproxy.take().unwrap();
autoproxy.url = format!("http://127.0.0.1:{pac_port}/commands/pac");
if pac {
sysproxy.enable = false;
sysproxy.set_system_proxy()?;
*cur_sysproxy = Some(sysproxy);
autoproxy.enable = enable;
autoproxy.set_auto_proxy()?;
*cur_autoproxy = Some(autoproxy);
} else {
autoproxy.enable = false;
autoproxy.set_auto_proxy()?;
*cur_autoproxy = Some(autoproxy);
sysproxy.enable = enable;
sysproxy.set_system_proxy()?;
*cur_sysproxy = Some(sysproxy);
}
2022-11-12 11:37:23 +08:00
Ok(())
}
2022-11-12 11:37:23 +08:00
/// reset the sysproxy
2022-11-14 01:26:33 +08:00
pub fn reset_sysproxy(&self) -> Result<()> {
let mut cur_sysproxy = self.cur_sysproxy.lock();
let mut old_sysproxy = self.old_sysproxy.lock();
2024-05-26 19:07:14 +08:00
let mut cur_autoproxy = self.cur_autoproxy.lock();
let mut old_autoproxy = self.old_autoproxy.lock();
2022-11-14 01:26:33 +08:00
let cur_sysproxy = cur_sysproxy.take();
2024-05-26 19:07:14 +08:00
let cur_autoproxy = cur_autoproxy.take();
2022-11-12 11:37:23 +08:00
2022-11-14 01:26:33 +08:00
if let Some(mut old) = old_sysproxy.take() {
2022-11-12 11:37:23 +08:00
// 如果原代理和当前代理 端口一致就disable关闭否则就恢复原代理设置
// 当前没有设置代理的时候,不确定旧设置是否和当前一致,全关了
2022-11-14 01:26:33 +08:00
let port_same = cur_sysproxy.map_or(true, |cur| old.port == cur.port);
2022-11-12 11:37:23 +08:00
if old.enable && port_same {
old.enable = false;
log::info!(target: "app", "reset proxy by disabling the original proxy");
} else {
log::info!(target: "app", "reset proxy to the original proxy");
}
old.set_system_proxy()?;
2022-11-14 01:26:33 +08:00
} else if let Some(mut cur @ Sysproxy { enable: true, .. }) = cur_sysproxy {
2022-11-12 11:37:23 +08:00
// 没有原代理就按现在的代理设置disable即可
log::info!(target: "app", "reset proxy by disabling the current proxy");
cur.enable = false;
cur.set_system_proxy()?;
2022-11-12 11:37:23 +08:00
} else {
log::info!(target: "app", "reset proxy with no action");
}
2022-04-20 01:44:47 +08:00
2024-05-26 19:07:14 +08:00
if let Some(mut old) = old_autoproxy.take() {
// 如果原代理和当前代理 URL一致就disable关闭否则就恢复原代理设置
// 当前没有设置代理的时候,不确定旧设置是否和当前一致,全关了
let url_same = cur_autoproxy.map_or(true, |cur| old.url == cur.url);
if old.enable && url_same {
old.enable = false;
log::info!(target: "app", "reset proxy by disabling the original proxy");
} else {
log::info!(target: "app", "reset proxy to the original proxy");
}
old.set_auto_proxy()?;
} else if let Some(mut cur @ Autoproxy { enable: true, .. }) = cur_autoproxy {
// 没有原代理就按现在的代理设置disable即可
log::info!(target: "app", "reset proxy by disabling the current proxy");
cur.enable = false;
cur.set_auto_proxy()?;
} else {
log::info!(target: "app", "reset proxy with no action");
}
2022-11-12 11:37:23 +08:00
Ok(())
2022-04-20 01:44:47 +08:00
}
2022-11-12 11:37:23 +08:00
/// init the auto launch
2022-11-14 01:26:33 +08:00
pub fn init_launch(&self) -> Result<()> {
2022-11-12 11:37:23 +08:00
let app_exe = current_exe()?;
2024-04-13 15:45:50 +08:00
// let app_exe = dunce::canonicalize(app_exe)?;
2022-11-12 11:37:23 +08:00
let app_name = app_exe
.file_stem()
.and_then(|f| f.to_str())
.ok_or(anyhow!("failed to get file stem"))?;
let app_path = app_exe
.as_os_str()
.to_str()
.ok_or(anyhow!("failed to get app_path"))?
.to_string();
// fix issue #26
#[cfg(target_os = "windows")]
let app_path = format!("\"{app_path}\"");
// use the /Applications/Clash Verge.app path
#[cfg(target_os = "macos")]
let app_path = (|| -> Option<String> {
let path = std::path::PathBuf::from(&app_path);
let path = path.parent()?.parent()?.parent()?;
let extension = path.extension()?.to_str()?;
match extension == "app" {
true => Some(path.as_os_str().to_str()?.to_string()),
false => None,
}
})()
.unwrap_or(app_path);
2023-02-11 23:19:08 +08:00
// fix #403
#[cfg(target_os = "linux")]
let app_path = {
2023-02-11 23:31:55 +08:00
use crate::core::handle::Handle;
2023-02-11 23:19:08 +08:00
use tauri::Manager;
let handle = Handle::global();
2023-03-16 23:45:48 +08:00
match handle.app_handle.lock().as_ref() {
Some(app_handle) => {
let appimage = app_handle.env().appimage;
appimage
2023-02-11 23:19:08 +08:00
.and_then(|p| p.to_str().map(|s| s.to_string()))
2023-03-16 23:45:48 +08:00
.unwrap_or(app_path)
}
None => app_path,
}
2023-02-11 23:19:08 +08:00
};
2022-11-12 11:37:23 +08:00
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(&app_path)
.build()?;
2022-11-14 01:26:33 +08:00
*self.auto_launch.lock() = Some(auto);
2022-04-20 01:44:47 +08:00
2022-11-12 11:37:23 +08:00
Ok(())
}
2022-04-20 01:44:47 +08:00
2022-11-12 11:37:23 +08:00
/// update the startup
2022-11-14 01:26:33 +08:00
pub fn update_launch(&self) -> Result<()> {
let auto_launch = self.auto_launch.lock();
if auto_launch.is_none() {
drop(auto_launch);
2022-11-12 11:37:23 +08:00
return self.init_launch();
2022-04-20 01:44:47 +08:00
}
2024-01-10 17:36:35 +08:00
let enable = { Config::verge().latest().enable_auto_launch };
2022-11-17 17:07:13 +08:00
let enable = enable.unwrap_or(false);
2022-11-14 01:26:33 +08:00
let auto_launch = auto_launch.as_ref().unwrap();
2022-09-11 20:58:55 +08:00
2022-11-12 11:37:23 +08:00
match enable {
true => auto_launch.enable()?,
2022-11-14 01:26:33 +08:00
false => log_err!(auto_launch.disable()), // 忽略关闭的错误
2022-11-12 11:37:23 +08:00
};
2022-04-20 01:44:47 +08:00
2022-11-12 11:37:23 +08:00
Ok(())
}
/// launch a system proxy guard
/// read config from file directly
pub fn guard_proxy(&self) {
use tokio::time::{sleep, Duration};
let guard_state = self.guard_state.clone();
2022-11-12 11:37:23 +08:00
tauri::async_runtime::spawn(async move {
// if it is running, exit
let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
2024-06-09 12:45:57 +08:00
let (enable, guard, guard_duration, pac) = {
2022-11-16 01:26:41 +08:00
let verge = Config::verge();
let verge = verge.latest();
(
2024-01-10 17:36:35 +08:00
verge.enable_system_proxy.unwrap_or(false),
verge.enable_proxy_guard.unwrap_or(false),
verge.proxy_guard_duration.unwrap_or(10),
2024-05-26 19:07:14 +08:00
verge.proxy_auto_config.unwrap_or(false),
2022-11-16 01:26:41 +08:00
)
};
2022-11-12 11:37:23 +08:00
// stop loop
if !enable || !guard {
break;
}
// update duration
wait_secs = guard_duration;
log::debug!(target: "app", "try to guard the system proxy");
2023-12-01 12:56:18 +08:00
let port = {
Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port())
};
2024-05-26 19:07:14 +08:00
let pac_port = IVerge::get_singleton_port();
if pac {
let autoproxy = Autoproxy {
enable: true,
url: format!("http://127.0.0.1:{pac_port}/commands/pac"),
};
log_err!(autoproxy.set_auto_proxy());
} else {
let sysproxy = Sysproxy {
enable: true,
host: "127.0.0.1".into(),
port,
2024-06-09 12:45:57 +08:00
bypass: get_bypass(),
2024-05-26 19:07:14 +08:00
};
2024-05-26 19:07:14 +08:00
log_err!(sysproxy.set_system_proxy());
}
2022-11-12 11:37:23 +08:00
}
let mut state = guard_state.lock().await;
*state = false;
2022-11-14 01:26:33 +08:00
drop(state);
2022-11-12 11:37:23 +08:00
});
}
2022-04-20 01:44:47 +08:00
}