sysopt.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 registry_mode = {
  52. let verge = Config::verge();
  53. let verge = verge.latest();
  54. verge.system_proxy_registry_mode.unwrap_or(false)
  55. };
  56. let current = Sysproxy {
  57. enable,
  58. host: String::from("127.0.0.1"),
  59. port,
  60. bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
  61. };
  62. if enable {
  63. let old = Sysproxy::get_system_proxy().ok();
  64. if registry_mode {
  65. #[cfg(windows)]
  66. current.set_system_proxy_with_registry()?;
  67. #[cfg(not(windows))]
  68. current.set_system_proxy()?;
  69. } else {
  70. current.set_system_proxy()?;
  71. }
  72. *self.old_sysproxy.lock() = old;
  73. *self.cur_sysproxy.lock() = Some(current);
  74. }
  75. // run the system proxy guard
  76. self.guard_proxy();
  77. Ok(())
  78. }
  79. /// update the system proxy
  80. pub fn update_sysproxy(&self) -> Result<()> {
  81. let mut cur_sysproxy = self.cur_sysproxy.lock();
  82. let old_sysproxy = self.old_sysproxy.lock();
  83. if cur_sysproxy.is_none() || old_sysproxy.is_none() {
  84. drop(cur_sysproxy);
  85. drop(old_sysproxy);
  86. return self.init_sysproxy();
  87. }
  88. let (enable, bypass) = {
  89. let verge = Config::verge();
  90. let verge = verge.latest();
  91. (
  92. verge.enable_system_proxy.unwrap_or(false),
  93. verge.system_proxy_bypass.clone(),
  94. )
  95. };
  96. let registry_mode = {
  97. let verge = Config::verge();
  98. let verge = verge.latest();
  99. verge.system_proxy_registry_mode.unwrap_or(false)
  100. };
  101. let mut sysproxy = cur_sysproxy.take().unwrap();
  102. sysproxy.enable = enable;
  103. sysproxy.bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
  104. let port = Config::verge()
  105. .latest()
  106. .verge_mixed_port
  107. .unwrap_or(Config::clash().data().get_mixed_port());
  108. sysproxy.port = port;
  109. if registry_mode {
  110. #[cfg(windows)]
  111. sysproxy.set_system_proxy_with_registry()?;
  112. #[cfg(not(windows))]
  113. sysproxy.set_system_proxy()?;
  114. } else {
  115. sysproxy.set_system_proxy()?;
  116. }
  117. *cur_sysproxy = Some(sysproxy);
  118. Ok(())
  119. }
  120. /// reset the sysproxy
  121. pub fn reset_sysproxy(&self) -> Result<()> {
  122. let mut cur_sysproxy = self.cur_sysproxy.lock();
  123. let mut old_sysproxy = self.old_sysproxy.lock();
  124. let registry_mode = {
  125. let verge = Config::verge();
  126. let verge = verge.latest();
  127. verge.system_proxy_registry_mode.unwrap_or(false)
  128. };
  129. let cur_sysproxy = cur_sysproxy.take();
  130. if let Some(mut old) = old_sysproxy.take() {
  131. // 如果原代理和当前代理 端口一致,就disable关闭,否则就恢复原代理设置
  132. // 当前没有设置代理的时候,不确定旧设置是否和当前一致,全关了
  133. let port_same = cur_sysproxy.map_or(true, |cur| old.port == cur.port);
  134. if old.enable && port_same {
  135. old.enable = false;
  136. log::info!(target: "app", "reset proxy by disabling the original proxy");
  137. } else {
  138. log::info!(target: "app", "reset proxy to the original proxy");
  139. }
  140. if registry_mode {
  141. #[cfg(windows)]
  142. old.set_system_proxy_with_registry()?;
  143. #[cfg(not(windows))]
  144. old.set_system_proxy()?;
  145. } else {
  146. old.set_system_proxy()?;
  147. }
  148. } else if let Some(mut cur @ Sysproxy { enable: true, .. }) = cur_sysproxy {
  149. // 没有原代理,就按现在的代理设置disable即可
  150. log::info!(target: "app", "reset proxy by disabling the current proxy");
  151. cur.enable = false;
  152. if registry_mode {
  153. #[cfg(windows)]
  154. cur.set_system_proxy_with_registry()?;
  155. #[cfg(not(windows))]
  156. cur.set_system_proxy()?;
  157. } else {
  158. cur.set_system_proxy()?;
  159. }
  160. } else {
  161. log::info!(target: "app", "reset proxy with no action");
  162. }
  163. Ok(())
  164. }
  165. /// init the auto launch
  166. pub fn init_launch(&self) -> Result<()> {
  167. let enable = { Config::verge().latest().enable_auto_launch };
  168. let enable = enable.unwrap_or(false);
  169. let app_exe = current_exe()?;
  170. let app_exe = dunce::canonicalize(app_exe)?;
  171. let app_name = app_exe
  172. .file_stem()
  173. .and_then(|f| f.to_str())
  174. .ok_or(anyhow!("failed to get file stem"))?;
  175. let app_path = app_exe
  176. .as_os_str()
  177. .to_str()
  178. .ok_or(anyhow!("failed to get app_path"))?
  179. .to_string();
  180. // fix issue #26
  181. #[cfg(target_os = "windows")]
  182. let app_path = format!("\"{app_path}\"");
  183. // use the /Applications/Clash Verge.app path
  184. #[cfg(target_os = "macos")]
  185. let app_path = (|| -> Option<String> {
  186. let path = std::path::PathBuf::from(&app_path);
  187. let path = path.parent()?.parent()?.parent()?;
  188. let extension = path.extension()?.to_str()?;
  189. match extension == "app" {
  190. true => Some(path.as_os_str().to_str()?.to_string()),
  191. false => None,
  192. }
  193. })()
  194. .unwrap_or(app_path);
  195. // fix #403
  196. #[cfg(target_os = "linux")]
  197. let app_path = {
  198. use crate::core::handle::Handle;
  199. use tauri::Manager;
  200. let handle = Handle::global();
  201. match handle.app_handle.lock().as_ref() {
  202. Some(app_handle) => {
  203. let appimage = app_handle.env().appimage;
  204. appimage
  205. .and_then(|p| p.to_str().map(|s| s.to_string()))
  206. .unwrap_or(app_path)
  207. }
  208. None => app_path,
  209. }
  210. };
  211. let auto = AutoLaunchBuilder::new()
  212. .set_app_name(app_name)
  213. .set_app_path(&app_path)
  214. .build()?;
  215. // 避免在开发时将自启动关了
  216. #[cfg(feature = "verge-dev")]
  217. if !enable {
  218. return Ok(());
  219. }
  220. #[cfg(target_os = "macos")]
  221. {
  222. if enable && !auto.is_enabled().unwrap_or(false) {
  223. // 避免重复设置登录项
  224. let _ = auto.disable();
  225. auto.enable()?;
  226. } else if !enable {
  227. let _ = auto.disable();
  228. }
  229. }
  230. #[cfg(not(target_os = "macos"))]
  231. if enable {
  232. auto.enable()?;
  233. }
  234. *self.auto_launch.lock() = Some(auto);
  235. Ok(())
  236. }
  237. /// update the startup
  238. pub fn update_launch(&self) -> Result<()> {
  239. let auto_launch = self.auto_launch.lock();
  240. if auto_launch.is_none() {
  241. drop(auto_launch);
  242. return self.init_launch();
  243. }
  244. let enable = { Config::verge().latest().enable_auto_launch };
  245. let enable = enable.unwrap_or(false);
  246. let auto_launch = auto_launch.as_ref().unwrap();
  247. match enable {
  248. true => auto_launch.enable()?,
  249. false => log_err!(auto_launch.disable()), // 忽略关闭的错误
  250. };
  251. Ok(())
  252. }
  253. /// launch a system proxy guard
  254. /// read config from file directly
  255. pub fn guard_proxy(&self) {
  256. use tokio::time::{sleep, Duration};
  257. let guard_state = self.guard_state.clone();
  258. let registry_mode = {
  259. let verge = Config::verge();
  260. let verge = verge.latest();
  261. verge.system_proxy_registry_mode.unwrap_or(false)
  262. };
  263. tauri::async_runtime::spawn(async move {
  264. // if it is running, exit
  265. let mut state = guard_state.lock().await;
  266. if *state {
  267. return;
  268. }
  269. *state = true;
  270. drop(state);
  271. // default duration is 10s
  272. let mut wait_secs = 10u64;
  273. loop {
  274. sleep(Duration::from_secs(wait_secs)).await;
  275. let (enable, guard, guard_duration, bypass) = {
  276. let verge = Config::verge();
  277. let verge = verge.latest();
  278. (
  279. verge.enable_system_proxy.unwrap_or(false),
  280. verge.enable_proxy_guard.unwrap_or(false),
  281. verge.proxy_guard_duration.unwrap_or(10),
  282. verge.system_proxy_bypass.clone(),
  283. )
  284. };
  285. // stop loop
  286. if !enable || !guard {
  287. break;
  288. }
  289. // update duration
  290. wait_secs = guard_duration;
  291. log::debug!(target: "app", "try to guard the system proxy");
  292. let port = {
  293. Config::verge()
  294. .latest()
  295. .verge_mixed_port
  296. .unwrap_or(Config::clash().data().get_mixed_port())
  297. };
  298. let sysproxy = Sysproxy {
  299. enable: true,
  300. host: "127.0.0.1".into(),
  301. port,
  302. bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
  303. };
  304. if registry_mode {
  305. #[cfg(windows)]
  306. log_err!(sysproxy.set_system_proxy_with_registry());
  307. #[cfg(not(windows))]
  308. log_err!(sysproxy.set_system_proxy());
  309. } else {
  310. log_err!(sysproxy.set_system_proxy());
  311. }
  312. }
  313. let mut state = guard_state.lock().await;
  314. *state = false;
  315. drop(state);
  316. });
  317. }
  318. }