Files
clash-proxy/src-tauri/src/core/core.rs

269 lines
9.3 KiB
Rust
Raw Normal View History

2024-06-19 10:04:28 +08:00
use crate::config::*;
2024-11-18 05:58:06 +08:00
use crate::core::{clash_api, handle, service};
use crate::core::tray::Tray;
2022-11-18 18:18:41 +08:00
use crate::log_err;
2024-06-19 10:04:28 +08:00
use crate::utils::dirs;
use anyhow::{bail, Result};
2022-11-14 01:26:33 +08:00
use once_cell::sync::OnceCell;
use serde_yaml::Mapping;
use std::{sync::Arc, time::Duration};
2024-09-02 19:33:17 +08:00
use tauri_plugin_shell::ShellExt;
2024-09-27 00:24:05 +08:00
use tokio::sync::Mutex;
2022-11-14 01:26:33 +08:00
use tokio::time::sleep;
#[derive(Debug)]
pub struct CoreManager {
2024-09-27 00:24:05 +08:00
running: Arc<Mutex<bool>>,
2022-11-14 01:26:33 +08:00
}
impl CoreManager {
pub fn global() -> &'static CoreManager {
static CORE_MANAGER: OnceCell<CoreManager> = OnceCell::new();
CORE_MANAGER.get_or_init(|| CoreManager {
2024-09-27 00:24:05 +08:00
running: Arc::new(Mutex::new(false)),
2022-11-14 01:26:33 +08:00
})
}
2024-09-27 00:24:05 +08:00
pub async fn init(&self) -> Result<()> {
log::trace!("run core start");
// 启动clash
log_err!(Self::global().start_core().await);
log::trace!("run core end");
2022-11-14 01:26:33 +08:00
Ok(())
}
/// 检查订阅是否正确
2024-09-02 19:33:17 +08:00
pub async fn check_config(&self) -> Result<()> {
2022-11-18 18:18:41 +08:00
let config_path = Config::generate_file(ConfigType::Check)?;
2022-11-14 01:26:33 +08:00
let config_path = dirs::path_to_str(&config_path)?;
2022-11-16 01:26:41 +08:00
let clash_core = { Config::verge().latest().clash_core.clone() };
2024-09-27 00:24:05 +08:00
let clash_core = clash_core.unwrap_or("verge-mihomo".into());
2024-07-08 00:29:49 +08:00
let test_dir = dirs::app_home_dir()?.join("test");
let test_dir = dirs::path_to_str(&test_dir)?;
let app_handle = handle::Handle::global().app_handle().unwrap();
2024-11-18 05:58:06 +08:00
let _ = app_handle
.shell()
.sidecar(clash_core)?
.args(["-t", "-d", test_dir, "-f", config_path])
.output()
.await?;
2022-11-14 01:26:33 +08:00
Ok(())
}
2024-09-27 00:24:05 +08:00
/// 停止核心运行
pub async fn stop_core(&self) -> Result<()> {
let mut running = self.running.lock().await;
if !*running {
log::debug!("core is not running");
return Ok(());
}
2024-09-27 00:24:05 +08:00
2024-06-19 10:43:58 +08:00
// 关闭tun模式
let mut disable = Mapping::new();
let mut tun = Mapping::new();
tun.insert("enable".into(), false.into());
disable.insert("tun".into(), tun.into());
log::debug!(target: "app", "disable tun mode");
log_err!(clash_api::patch_configs(&disable).await);
2024-06-19 10:43:58 +08:00
// 服务模式
if service::check_service().await.is_ok() {
log::info!(target: "app", "stop the core by service");
service::stop_core_by_service().await?;
2024-10-08 02:39:17 +08:00
}
*running = false;
2024-09-27 00:24:05 +08:00
Ok(())
}
2024-09-27 00:24:05 +08:00
/// 启动核心
pub async fn start_core(&self) -> Result<()> {
let mut running = self.running.lock().await;
if *running {
log::info!("core is running");
return Ok(());
}
2024-09-27 00:24:05 +08:00
let config_path = Config::generate_file(ConfigType::Run)?;
// 服务模式
2024-10-08 02:39:17 +08:00
if service::check_service().await.is_ok() {
log::info!(target: "app", "try to run core in service mode");
service::run_core_by_service(&config_path).await?;
2022-11-17 20:19:40 +08:00
}
// 流量订阅
#[cfg(target_os = "macos")]
log_err!(Tray::global().subscribe_traffic().await);
*running = true;
2022-11-14 01:26:33 +08:00
Ok(())
}
/// 重启内核
2024-09-27 00:24:05 +08:00
pub async fn restart_core(&self) -> Result<()> {
// 重新启动app
self.stop_core().await?;
self.start_core().await?;
2022-11-14 01:26:33 +08:00
Ok(())
}
/// 切换核心
pub async fn change_core(&self, clash_core: Option<String>) -> Result<()> {
let clash_core = clash_core.ok_or(anyhow::anyhow!("clash core is null"))?;
2024-06-19 10:04:28 +08:00
const CLASH_CORES: [&str; 2] = ["verge-mihomo", "verge-mihomo-alpha"];
2022-11-14 01:26:33 +08:00
if !CLASH_CORES.contains(&clash_core.as_str()) {
2022-11-14 01:26:33 +08:00
bail!("invalid clash core name \"{clash_core}\"");
}
log::info!(target: "app", "change core to `{clash_core}`");
2022-11-18 20:15:34 +08:00
2022-11-18 18:18:41 +08:00
Config::verge().draft().clash_core = Some(clash_core);
// 更新订阅
Config::generate().await?;
2024-09-02 19:33:17 +08:00
self.check_config().await?;
2022-11-21 22:27:55 +08:00
2024-09-27 00:24:05 +08:00
match self.restart_core().await {
2022-11-14 01:26:33 +08:00
Ok(_) => {
2022-11-18 18:18:41 +08:00
Config::verge().apply();
Config::runtime().apply();
log_err!(Config::verge().latest().save_file());
2022-11-14 01:26:33 +08:00
Ok(())
}
Err(err) => {
2022-11-16 01:26:41 +08:00
Config::verge().discard();
2022-11-18 18:18:41 +08:00
Config::runtime().discard();
2022-11-14 01:26:33 +08:00
Err(err)
}
}
}
/// 使用子进程验证配置
pub async fn validate_config(&self) -> Result<(bool, String)> {
println!("[core配置验证] 开始验证配置");
let config_path = Config::generate_file(ConfigType::Check)?;
let config_path = dirs::path_to_str(&config_path)?;
println!("[core配置验证] 配置文件路径: {}", config_path);
let clash_core = { Config::verge().latest().clash_core.clone() };
let clash_core = clash_core.unwrap_or("verge-mihomo".into());
println!("[core配置验证] 使用内核: {}", clash_core);
let app_handle = handle::Handle::global().app_handle().unwrap();
let test_dir = dirs::app_home_dir()?.join("test");
let test_dir = dirs::path_to_str(&test_dir)?;
println!("[core配置验证] 测试目录: {}", test_dir);
// 使用子进程运行clash验证配置
println!("[core配置验证] 运行子进程验证配置");
let output = app_handle
.shell()
.sidecar(clash_core)?
.args(["-t", "-d", test_dir, "-f", config_path])
.output()
.await?;
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
// 检查进程退出状态和错误输出
let error_keywords = ["FATA", "fatal", "Parse config error", "level=fatal"];
let has_error = !output.status.success() || error_keywords.iter().any(|&kw| stderr.contains(kw));
println!("[core配置验证] 退出状态: {:?}", output.status);
if !stderr.is_empty() {
println!("[core配置验证] 错误输出: {}", stderr);
}
if !stdout.is_empty() {
println!("[core配置验证] 标准输出: {}", stdout);
}
if has_error {
let error_msg = if stderr.is_empty() {
if let Some(code) = output.status.code() {
handle::Handle::notice_message("config_validate::error", &code.to_string());
String::new()
} else {
handle::Handle::notice_message("config_validate::process_terminated", "");
String::new()
}
} else {
handle::Handle::notice_message("config_validate::stderr_error", &*stderr);
String::new()
};
Ok((false, error_msg))
} else {
handle::Handle::notice_message("config_validate::success", "");
Ok((true, String::new()))
}
}
/// 更新proxies等配置
2022-11-18 18:18:41 +08:00
pub async fn update_config(&self) -> Result<()> {
println!("[core配置更新] 开始更新配置");
// 1. 先生成新的配置内容
println!("[core配置更新] 生成新的配置内容");
Config::generate().await?;
// 2. 生成临时文件并进行验证
println!("[core配置更新] 生成临时配置文件用于验证");
let temp_config = Config::generate_file(ConfigType::Check)?;
let temp_config = dirs::path_to_str(&temp_config)?;
println!("[core配置更新] 临时配置文件路径: {}", temp_config);
2022-11-14 01:26:33 +08:00
// 3. 验证配置
let (is_valid, error_msg) = match self.validate_config().await {
Ok((valid, msg)) => (valid, msg),
Err(e) => {
println!("[core配置更新] 验证过程发生错误: {}", e);
Config::runtime().discard(); // 验证失败时丢弃新配置
return Err(e);
}
};
2022-11-14 01:26:33 +08:00
if !is_valid {
println!("[core配置更新] 配置验证未通过,保持当前配置不变");
Config::runtime().discard(); // 验证失败时丢弃新配置
return Err(anyhow::anyhow!(error_msg));
}
// 4. 验证通过后,生成正式的运行时配置
println!("[core配置更新] 验证通过,生成运行时配置");
let run_path = Config::generate_file(ConfigType::Run)?;
let run_path = dirs::path_to_str(&run_path)?;
2022-11-18 18:18:41 +08:00
// 5. 应用新配置
println!("[core配置更新] 应用新配置");
2024-07-08 00:29:49 +08:00
for i in 0..10 {
match clash_api::put_configs(run_path).await {
Ok(_) => {
println!("[core配置更新] 配置应用成功");
Config::runtime().apply(); // 应用成功时保存新配置
break;
}
2022-11-14 01:26:33 +08:00
Err(err) => {
2024-07-08 00:29:49 +08:00
if i < 9 {
println!("[core配置更新] 第{}次重试应用配置", i + 1);
2022-11-18 22:08:06 +08:00
log::info!(target: "app", "{err}");
2022-11-14 01:26:33 +08:00
} else {
println!("[core配置更新] 配置应用失败: {}", err);
Config::runtime().discard(); // 应用失败时丢弃新配置
return Err(err.into());
2022-11-14 01:26:33 +08:00
}
}
}
2024-07-08 00:29:49 +08:00
sleep(Duration::from_millis(100)).await;
2022-11-14 01:26:33 +08:00
}
Ok(())
}
}