clash copy.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. use super::{PrfEnhancedResult, Profiles, Verge, VergeConfig};
  2. use crate::log_if_err;
  3. use crate::utils::{config, dirs, help};
  4. use anyhow::{bail, Result};
  5. use reqwest::header::HeaderMap;
  6. use serde::{Deserialize, Serialize};
  7. use serde_yaml::{Mapping, Value};
  8. use std::{collections::HashMap, time::Duration};
  9. use tauri::api::process::{Command, CommandChild, CommandEvent};
  10. use tauri::Window;
  11. use tokio::time::sleep;
  12. #[derive(Default, Debug, Clone, Deserialize, Serialize)]
  13. pub struct ClashInfo {
  14. /// clash sidecar status
  15. pub status: String,
  16. /// clash core port
  17. pub port: Option<String>,
  18. /// same as `external-controller`
  19. pub server: Option<String>,
  20. /// clash secret
  21. pub secret: Option<String>,
  22. }
  23. pub struct Clash {
  24. /// maintain the clash config
  25. pub config: Mapping,
  26. /// some info
  27. pub info: ClashInfo,
  28. /// clash sidecar
  29. pub sidecar: Option<CommandChild>,
  30. /// save the main window
  31. pub window: Option<Window>,
  32. }
  33. impl Clash {
  34. pub fn new() -> Clash {
  35. let config = Clash::read_config();
  36. let info = Clash::get_info(&config);
  37. Clash {
  38. config,
  39. info,
  40. sidecar: None,
  41. window: None,
  42. }
  43. }
  44. /// get clash config
  45. fn read_config() -> Mapping {
  46. config::read_yaml::<Mapping>(dirs::clash_path())
  47. }
  48. /// save the clash config
  49. fn save_config(&self) -> Result<()> {
  50. config::save_yaml(
  51. dirs::clash_path(),
  52. &self.config,
  53. Some("# Default Config For Clash Core\n\n"),
  54. )
  55. }
  56. /// parse the clash's config.yaml
  57. /// get some information
  58. fn get_info(clash_config: &Mapping) -> ClashInfo {
  59. let key_port_1 = Value::from("port");
  60. let key_port_2 = Value::from("mixed-port");
  61. let key_server = Value::from("external-controller");
  62. let key_secret = Value::from("secret");
  63. let port = match clash_config.get(&key_port_1) {
  64. Some(value) => match value {
  65. Value::String(val_str) => Some(val_str.clone()),
  66. Value::Number(val_num) => Some(val_num.to_string()),
  67. _ => None,
  68. },
  69. _ => None,
  70. };
  71. let port = match port {
  72. Some(_) => port,
  73. None => match clash_config.get(&key_port_2) {
  74. Some(value) => match value {
  75. Value::String(val_str) => Some(val_str.clone()),
  76. Value::Number(val_num) => Some(val_num.to_string()),
  77. _ => None,
  78. },
  79. _ => None,
  80. },
  81. };
  82. let server = match clash_config.get(&key_server) {
  83. Some(value) => match value {
  84. Value::String(val_str) => {
  85. // `external-controller` could be
  86. // "127.0.0.1:9090" or ":9090"
  87. // Todo: maybe it could support single port
  88. let server = val_str.clone();
  89. let server = match server.starts_with(":") {
  90. true => format!("127.0.0.1{server}"),
  91. false => server,
  92. };
  93. Some(server)
  94. }
  95. _ => None,
  96. },
  97. _ => None,
  98. };
  99. let secret = match clash_config.get(&key_secret) {
  100. Some(value) => match value {
  101. Value::String(val_str) => Some(val_str.clone()),
  102. Value::Bool(val_bool) => Some(val_bool.to_string()),
  103. Value::Number(val_num) => Some(val_num.to_string()),
  104. _ => None,
  105. },
  106. _ => None,
  107. };
  108. ClashInfo {
  109. status: "init".into(),
  110. port,
  111. server,
  112. secret,
  113. }
  114. }
  115. /// save the main window
  116. pub fn set_window(&mut self, win: Option<Window>) {
  117. self.window = win;
  118. }
  119. /// run clash sidecar
  120. pub fn run_sidecar(&mut self, profiles: &Profiles, delay: bool) -> Result<()> {
  121. let app_dir = dirs::app_home_dir();
  122. let app_dir = app_dir.as_os_str().to_str().unwrap();
  123. let cmd = Command::new_sidecar("clash")?;
  124. let (mut rx, cmd_child) = cmd.args(["-d", app_dir]).spawn()?;
  125. self.sidecar = Some(cmd_child);
  126. // clash log
  127. tauri::async_runtime::spawn(async move {
  128. while let Some(event) = rx.recv().await {
  129. match event {
  130. CommandEvent::Stdout(line) => log::info!("[clash]: {}", line),
  131. CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
  132. _ => {}
  133. }
  134. }
  135. });
  136. // activate profile
  137. log_if_err!(self.activate(&profiles));
  138. log_if_err!(self.activate_enhanced(&profiles, delay, true));
  139. Ok(())
  140. }
  141. /// drop clash sidecar
  142. pub fn drop_sidecar(&mut self) -> Result<()> {
  143. if let Some(sidecar) = self.sidecar.take() {
  144. sidecar.kill()?;
  145. }
  146. Ok(())
  147. }
  148. /// restart clash sidecar
  149. /// should reactivate profile after restart
  150. pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<()> {
  151. self.update_config();
  152. self.drop_sidecar()?;
  153. self.run_sidecar(profiles, false)
  154. }
  155. /// update the clash info
  156. pub fn update_config(&mut self) {
  157. self.config = Clash::read_config();
  158. self.info = Clash::get_info(&self.config);
  159. }
  160. /// patch update the clash config
  161. pub fn patch_config(
  162. &mut self,
  163. patch: Mapping,
  164. verge: &mut Verge,
  165. profiles: &mut Profiles,
  166. ) -> Result<()> {
  167. let mix_port_key = Value::from("mixed-port");
  168. let mut port = None;
  169. for (key, value) in patch.into_iter() {
  170. let value = value.clone();
  171. // check whether the mix_port is changed
  172. if key == mix_port_key {
  173. if value.is_number() {
  174. port = value.as_i64().as_ref().map(|n| n.to_string());
  175. } else {
  176. port = value.as_str().as_ref().map(|s| s.to_string());
  177. }
  178. }
  179. self.config.insert(key.clone(), value);
  180. }
  181. self.save_config()?;
  182. if let Some(port) = port {
  183. self.restart_sidecar(profiles)?;
  184. verge.init_sysproxy(Some(port));
  185. }
  186. Ok(())
  187. }
  188. /// revise the `tun` and `dns` config
  189. fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
  190. macro_rules! revise {
  191. ($map: expr, $key: expr, $val: expr) => {
  192. let ret_key = Value::String($key.into());
  193. $map.insert(ret_key, Value::from($val));
  194. };
  195. }
  196. // if key not exists then append value
  197. macro_rules! append {
  198. ($map: expr, $key: expr, $val: expr) => {
  199. let ret_key = Value::String($key.into());
  200. if !$map.contains_key(&ret_key) {
  201. $map.insert(ret_key, Value::from($val));
  202. }
  203. };
  204. }
  205. // tun config
  206. let tun_val = config.get(&Value::from("tun"));
  207. let mut new_tun = Mapping::new();
  208. if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
  209. new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
  210. }
  211. revise!(new_tun, "enable", enable);
  212. if enable {
  213. append!(new_tun, "stack", "gvisor");
  214. append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
  215. append!(new_tun, "auto-route", true);
  216. append!(new_tun, "auto-detect-interface", true);
  217. }
  218. revise!(config, "tun", new_tun);
  219. // dns config
  220. let dns_val = config.get(&Value::from("dns"));
  221. let mut new_dns = Mapping::new();
  222. if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
  223. new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
  224. }
  225. // 借鉴cfw的默认配置
  226. revise!(new_dns, "enable", enable);
  227. if enable {
  228. append!(new_dns, "enhanced-mode", "fake-ip");
  229. append!(
  230. new_dns,
  231. "nameserver",
  232. vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
  233. );
  234. append!(new_dns, "fallback", vec![] as Vec<&str>);
  235. #[cfg(target_os = "windows")]
  236. append!(
  237. new_dns,
  238. "fake-ip-filter",
  239. vec![
  240. "dns.msftncsi.com",
  241. "www.msftncsi.com",
  242. "www.msftconnecttest.com"
  243. ]
  244. );
  245. }
  246. revise!(config, "dns", new_dns);
  247. config
  248. }
  249. /// activate the profile
  250. /// generate a new profile to the temp_dir
  251. /// then put the path to the clash core
  252. fn _activate(info: ClashInfo, config: Mapping, window: Option<Window>) -> Result<()> {
  253. let verge_config = VergeConfig::new();
  254. let tun_enable = verge_config.enable_tun_mode.unwrap_or(false);
  255. let config = Clash::_tun_mode(config, tun_enable);
  256. let temp_path = dirs::profiles_temp_path();
  257. config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
  258. tauri::async_runtime::spawn(async move {
  259. if info.server.is_none() {
  260. return;
  261. }
  262. let server = info.server.unwrap();
  263. let server = format!("http://{server}/configs");
  264. let mut headers = HeaderMap::new();
  265. headers.insert("Content-Type", "application/json".parse().unwrap());
  266. if let Some(secret) = info.secret.as_ref() {
  267. let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
  268. headers.insert("Authorization", secret);
  269. }
  270. let mut data = HashMap::new();
  271. data.insert("path", temp_path.as_os_str().to_str().unwrap());
  272. // retry 5 times
  273. for _ in 0..5 {
  274. match reqwest::ClientBuilder::new().no_proxy().build() {
  275. Ok(client) => {
  276. let builder = client.put(&server).headers(headers.clone()).json(&data);
  277. match builder.send().await {
  278. Ok(resp) => {
  279. if resp.status() != 204 {
  280. log::error!("failed to activate clash for status \"{}\"", resp.status());
  281. }
  282. // emit the window to update something
  283. if let Some(window) = window {
  284. window.emit("verge://refresh-clash-config", "yes").unwrap();
  285. }
  286. // do not retry
  287. break;
  288. }
  289. Err(err) => log::error!("failed to activate for `{err}`"),
  290. }
  291. }
  292. Err(err) => log::error!("failed to activate for `{err}`"),
  293. }
  294. sleep(Duration::from_millis(500)).await;
  295. }
  296. });
  297. Ok(())
  298. }
  299. /// enhanced profiles mode
  300. /// - (sync) refresh config if enhance chain is null
  301. /// - (async) enhanced config
  302. pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool, skip: bool) -> Result<()> {
  303. if self.window.is_none() {
  304. bail!("failed to get the main window");
  305. }
  306. let event_name = help::get_uid("e");
  307. let event_name = format!("enhanced-cb-{event_name}");
  308. // generate the payload
  309. let payload = profiles.gen_enhanced(event_name.clone())?;
  310. let info = self.info.clone();
  311. // do not run enhanced
  312. if payload.chain.len() == 0 {
  313. if skip {
  314. return Ok(());
  315. }
  316. let mut config = self.config.clone();
  317. let filter_data = Clash::strict_filter(payload.current);
  318. for (key, value) in filter_data.into_iter() {
  319. config.insert(key, value);
  320. }
  321. return Clash::_activate(info, config, self.window.clone());
  322. }
  323. let window = self.window.clone().unwrap();
  324. let window_move = self.window.clone();
  325. window.once(&event_name, move |event| {
  326. if let Some(result) = event.payload() {
  327. let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
  328. if let Some(data) = result.data {
  329. let mut config = Clash::read_config();
  330. let filter_data = Clash::loose_filter(data); // loose filter
  331. for (key, value) in filter_data.into_iter() {
  332. config.insert(key, value);
  333. }
  334. log_if_err!(Clash::_activate(info, config, window_move));
  335. log::info!("profile enhanced status {}", result.status);
  336. }
  337. result.error.map(|err| log::error!("{err}"));
  338. }
  339. });
  340. tauri::async_runtime::spawn(async move {
  341. // wait the window setup during resolve app
  342. if delay {
  343. sleep(Duration::from_secs(2)).await;
  344. }
  345. window.emit("script-handler", payload).unwrap();
  346. });
  347. Ok(())
  348. }
  349. /// activate the profile
  350. /// auto activate enhanced profile
  351. pub fn activate(&self, profiles: &Profiles) -> Result<()> {
  352. let data = profiles.gen_activate()?;
  353. let data = Clash::strict_filter(data);
  354. let info = self.info.clone();
  355. let mut config = self.config.clone();
  356. for (key, value) in data.into_iter() {
  357. config.insert(key, value);
  358. }
  359. Clash::_activate(info, config, self.window.clone())
  360. }
  361. /// only 5 default fields available (clash config fields)
  362. /// convert to lowercase
  363. fn strict_filter(config: Mapping) -> Mapping {
  364. // Only the following fields are allowed:
  365. // proxies/proxy-providers/proxy-groups/rule-providers/rules
  366. let valid_keys = vec![
  367. "proxies",
  368. "proxy-providers",
  369. "proxy-groups",
  370. "rules",
  371. "rule-providers",
  372. ];
  373. let mut new_config = Mapping::new();
  374. for (key, value) in config.into_iter() {
  375. key.as_str().map(|key_str| {
  376. // change to lowercase
  377. let mut key_str = String::from(key_str);
  378. key_str.make_ascii_lowercase();
  379. // filter
  380. if valid_keys.contains(&&*key_str) {
  381. new_config.insert(Value::String(key_str), value);
  382. }
  383. });
  384. }
  385. new_config
  386. }
  387. /// more clash config fields available
  388. /// convert to lowercase
  389. fn loose_filter(config: Mapping) -> Mapping {
  390. // all of these can not be revised by script or merge
  391. // http/https/socks port should be under control
  392. let not_allow = vec![
  393. "port",
  394. "socks-port",
  395. "mixed-port",
  396. "allow-lan",
  397. "mode",
  398. "external-controller",
  399. "secret",
  400. "log-level",
  401. ];
  402. let mut new_config = Mapping::new();
  403. for (key, value) in config.into_iter() {
  404. key.as_str().map(|key_str| {
  405. // change to lowercase
  406. let mut key_str = String::from(key_str);
  407. key_str.make_ascii_lowercase();
  408. // filter
  409. if !not_allow.contains(&&*key_str) {
  410. new_config.insert(Value::String(key_str), value);
  411. }
  412. });
  413. }
  414. new_config
  415. }
  416. }
  417. impl Default for Clash {
  418. fn default() -> Self {
  419. Clash::new()
  420. }
  421. }
  422. impl Drop for Clash {
  423. fn drop(&mut self) {
  424. if let Err(err) = self.drop_sidecar() {
  425. log::error!("{err}");
  426. }
  427. }
  428. }