sysopt.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. use crate::{config::Config, log_err};
  2. use anyhow::{anyhow, Result};
  3. use auto_launch::{AutoLaunch, AutoLaunchBuilder};
  4. use once_cell::sync::OnceCell;
  5. use parking_lot::Mutex;
  6. use std::env::current_exe;
  7. use std::sync::Arc;
  8. use sysproxy::Sysproxy;
  9. use tauri::async_runtime::Mutex as TokioMutex;
  10. pub struct Sysopt {
  11. /// current system proxy setting
  12. cur_sysproxy: Arc<Mutex<Option<Sysproxy>>>,
  13. /// record the original system proxy
  14. /// recover it when exit
  15. old_sysproxy: Arc<Mutex<Option<Sysproxy>>>,
  16. /// helps to auto launch the app
  17. auto_launch: Arc<Mutex<Option<AutoLaunch>>>,
  18. /// record whether the guard async is running or not
  19. guard_state: Arc<TokioMutex<bool>>,
  20. }
  21. #[cfg(target_os = "windows")]
  22. 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>";
  23. #[cfg(target_os = "linux")]
  24. 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";
  25. #[cfg(target_os = "macos")]
  26. static DEFAULT_BYPASS: &str =
  27. "127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>";
  28. impl Sysopt {
  29. pub fn global() -> &'static Sysopt {
  30. static SYSOPT: OnceCell<Sysopt> = OnceCell::new();
  31. SYSOPT.get_or_init(|| Sysopt {
  32. cur_sysproxy: Arc::new(Mutex::new(None)),
  33. old_sysproxy: Arc::new(Mutex::new(None)),
  34. auto_launch: Arc::new(Mutex::new(None)),
  35. guard_state: Arc::new(TokioMutex::new(false)),
  36. })
  37. }
  38. /// init the sysproxy
  39. pub fn init_sysproxy(&self) -> Result<()> {
  40. let port = Config::verge()
  41. .latest()
  42. .verge_mixed_port
  43. .unwrap_or(Config::clash().data().get_mixed_port());
  44. let (enable, bypass) = {
  45. let verge = Config::verge();
  46. let verge = verge.latest();
  47. (
  48. verge.enable_system_proxy.unwrap_or(false),
  49. verge.system_proxy_bypass.clone(),
  50. )
  51. };
  52. let current = Sysproxy {
  53. enable,
  54. host: String::from("127.0.0.1"),
  55. port,
  56. bypass: match bypass {
  57. Some(bypass) => {
  58. if bypass.is_empty() {
  59. DEFAULT_BYPASS.into()
  60. } else {
  61. bypass
  62. }
  63. }
  64. None => DEFAULT_BYPASS.into(),
  65. },
  66. };
  67. if enable {
  68. let old = Sysproxy::get_system_proxy().ok();
  69. current.set_system_proxy()?;
  70. *self.old_sysproxy.lock() = old;
  71. *self.cur_sysproxy.lock() = Some(current);
  72. }
  73. // run the system proxy guard
  74. self.guard_proxy();
  75. Ok(())
  76. }
  77. /// update the system proxy
  78. pub fn update_sysproxy(&self) -> Result<()> {
  79. let mut cur_sysproxy = self.cur_sysproxy.lock();
  80. let old_sysproxy = self.old_sysproxy.lock();
  81. if cur_sysproxy.is_none() || old_sysproxy.is_none() {
  82. drop(cur_sysproxy);
  83. drop(old_sysproxy);
  84. return self.init_sysproxy();
  85. }
  86. let (enable, bypass) = {
  87. let verge = Config::verge();
  88. let verge = verge.latest();
  89. (
  90. verge.enable_system_proxy.unwrap_or(false),
  91. verge.system_proxy_bypass.clone(),
  92. )
  93. };
  94. let mut sysproxy = cur_sysproxy.take().unwrap();
  95. sysproxy.enable = enable;
  96. sysproxy.bypass = match bypass {
  97. Some(bypass) => {
  98. if bypass.is_empty() {
  99. DEFAULT_BYPASS.into()
  100. } else {
  101. bypass
  102. }
  103. }
  104. None => DEFAULT_BYPASS.into(),
  105. };
  106. let port = Config::verge()
  107. .latest()
  108. .verge_mixed_port
  109. .unwrap_or(Config::clash().data().get_mixed_port());
  110. sysproxy.port = port;
  111. sysproxy.set_system_proxy()?;
  112. *cur_sysproxy = Some(sysproxy);
  113. Ok(())
  114. }
  115. /// reset the sysproxy
  116. pub fn reset_sysproxy(&self) -> Result<()> {
  117. let mut cur_sysproxy = self.cur_sysproxy.lock();
  118. let mut old_sysproxy = self.old_sysproxy.lock();
  119. let cur_sysproxy = cur_sysproxy.take();
  120. if let Some(mut old) = old_sysproxy.take() {
  121. // 如果原代理和当前代理 端口一致,就disable关闭,否则就恢复原代理设置
  122. // 当前没有设置代理的时候,不确定旧设置是否和当前一致,全关了
  123. let port_same = cur_sysproxy.map_or(true, |cur| old.port == cur.port);
  124. if old.enable && port_same {
  125. old.enable = false;
  126. log::info!(target: "app", "reset proxy by disabling the original proxy");
  127. } else {
  128. log::info!(target: "app", "reset proxy to the original proxy");
  129. }
  130. old.set_system_proxy()?;
  131. } else if let Some(mut cur @ Sysproxy { enable: true, .. }) = cur_sysproxy {
  132. // 没有原代理,就按现在的代理设置disable即可
  133. log::info!(target: "app", "reset proxy by disabling the current proxy");
  134. cur.enable = false;
  135. cur.set_system_proxy()?;
  136. } else {
  137. log::info!(target: "app", "reset proxy with no action");
  138. }
  139. Ok(())
  140. }
  141. /// init the auto launch
  142. pub fn init_launch(&self) -> Result<()> {
  143. let app_exe = current_exe()?;
  144. // let app_exe = dunce::canonicalize(app_exe)?;
  145. let app_name = app_exe
  146. .file_stem()
  147. .and_then(|f| f.to_str())
  148. .ok_or(anyhow!("failed to get file stem"))?;
  149. let app_path = app_exe
  150. .as_os_str()
  151. .to_str()
  152. .ok_or(anyhow!("failed to get app_path"))?
  153. .to_string();
  154. // fix issue #26
  155. #[cfg(target_os = "windows")]
  156. let app_path = format!("\"{app_path}\"");
  157. // use the /Applications/Clash Verge.app path
  158. #[cfg(target_os = "macos")]
  159. let app_path = (|| -> Option<String> {
  160. let path = std::path::PathBuf::from(&app_path);
  161. let path = path.parent()?.parent()?.parent()?;
  162. let extension = path.extension()?.to_str()?;
  163. match extension == "app" {
  164. true => Some(path.as_os_str().to_str()?.to_string()),
  165. false => None,
  166. }
  167. })()
  168. .unwrap_or(app_path);
  169. // fix #403
  170. #[cfg(target_os = "linux")]
  171. let app_path = {
  172. use crate::core::handle::Handle;
  173. use tauri::Manager;
  174. let handle = Handle::global();
  175. match handle.app_handle.lock().as_ref() {
  176. Some(app_handle) => {
  177. let appimage = app_handle.env().appimage;
  178. appimage
  179. .and_then(|p| p.to_str().map(|s| s.to_string()))
  180. .unwrap_or(app_path)
  181. }
  182. None => app_path,
  183. }
  184. };
  185. let auto = AutoLaunchBuilder::new()
  186. .set_app_name(app_name)
  187. .set_app_path(&app_path)
  188. .build()?;
  189. *self.auto_launch.lock() = Some(auto);
  190. Ok(())
  191. }
  192. /// update the startup
  193. pub fn update_launch(&self) -> Result<()> {
  194. let auto_launch = self.auto_launch.lock();
  195. if auto_launch.is_none() {
  196. drop(auto_launch);
  197. return self.init_launch();
  198. }
  199. let enable = { Config::verge().latest().enable_auto_launch };
  200. let enable = enable.unwrap_or(false);
  201. let auto_launch = auto_launch.as_ref().unwrap();
  202. match enable {
  203. true => auto_launch.enable()?,
  204. false => log_err!(auto_launch.disable()), // 忽略关闭的错误
  205. };
  206. Ok(())
  207. }
  208. /// launch a system proxy guard
  209. /// read config from file directly
  210. pub fn guard_proxy(&self) {
  211. use tokio::time::{sleep, Duration};
  212. let guard_state = self.guard_state.clone();
  213. tauri::async_runtime::spawn(async move {
  214. // if it is running, exit
  215. let mut state = guard_state.lock().await;
  216. if *state {
  217. return;
  218. }
  219. *state = true;
  220. drop(state);
  221. // default duration is 10s
  222. let mut wait_secs = 10u64;
  223. loop {
  224. sleep(Duration::from_secs(wait_secs)).await;
  225. let (enable, guard, guard_duration, bypass) = {
  226. let verge = Config::verge();
  227. let verge = verge.latest();
  228. (
  229. verge.enable_system_proxy.unwrap_or(false),
  230. verge.enable_proxy_guard.unwrap_or(false),
  231. verge.proxy_guard_duration.unwrap_or(10),
  232. verge.system_proxy_bypass.clone(),
  233. )
  234. };
  235. // stop loop
  236. if !enable || !guard {
  237. break;
  238. }
  239. // update duration
  240. wait_secs = guard_duration;
  241. log::debug!(target: "app", "try to guard the system proxy");
  242. let port = {
  243. Config::verge()
  244. .latest()
  245. .verge_mixed_port
  246. .unwrap_or(Config::clash().data().get_mixed_port())
  247. };
  248. let sysproxy = Sysproxy {
  249. enable: true,
  250. host: "127.0.0.1".into(),
  251. port,
  252. bypass: match bypass {
  253. Some(bypass) => {
  254. if bypass.is_empty() {
  255. DEFAULT_BYPASS.into()
  256. } else {
  257. bypass
  258. }
  259. }
  260. None => DEFAULT_BYPASS.into(),
  261. },
  262. };
  263. log_err!(sysproxy.set_system_proxy());
  264. }
  265. let mut state = guard_state.lock().await;
  266. *state = false;
  267. drop(state);
  268. });
  269. }
  270. }