sysopt.rs 9.6 KB

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