sysopt.rs 9.3 KB

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