sysopt.rs 7.1 KB

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