2022-11-14 01:26:33 +08:00
|
|
|
|
use super::{clash_api, logger::Logger};
|
2022-11-18 18:18:41 +08:00
|
|
|
|
use crate::log_err;
|
|
|
|
|
|
use crate::{config::*, utils::dirs};
|
2022-11-14 01:26:33 +08:00
|
|
|
|
use anyhow::{bail, Context, Result};
|
|
|
|
|
|
use once_cell::sync::OnceCell;
|
|
|
|
|
|
use parking_lot::Mutex;
|
|
|
|
|
|
use std::{fs, io::Write, sync::Arc, time::Duration};
|
|
|
|
|
|
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
|
|
|
|
|
|
use tauri::api::process::{Command, CommandChild, CommandEvent};
|
|
|
|
|
|
use tokio::time::sleep;
|
|
|
|
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
|
pub struct CoreManager {
|
|
|
|
|
|
sidecar: Arc<Mutex<Option<CommandChild>>>,
|
|
|
|
|
|
|
|
|
|
|
|
#[allow(unused)]
|
|
|
|
|
|
use_service_mode: Arc<Mutex<bool>>,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl CoreManager {
|
|
|
|
|
|
pub fn global() -> &'static CoreManager {
|
|
|
|
|
|
static CORE_MANAGER: OnceCell<CoreManager> = OnceCell::new();
|
|
|
|
|
|
|
|
|
|
|
|
CORE_MANAGER.get_or_init(|| CoreManager {
|
|
|
|
|
|
sidecar: Arc::new(Mutex::new(None)),
|
|
|
|
|
|
use_service_mode: Arc::new(Mutex::new(false)),
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn init(&self) -> Result<()> {
|
|
|
|
|
|
// kill old clash process
|
2022-11-18 09:35:05 +08:00
|
|
|
|
let _ = dirs::clash_pid_path()
|
|
|
|
|
|
.and_then(|path| fs::read(path).map(|p| p.to_vec()).context(""))
|
|
|
|
|
|
.and_then(|pid| String::from_utf8_lossy(&pid).parse().context(""))
|
|
|
|
|
|
.map(|pid| {
|
2022-11-14 01:26:33 +08:00
|
|
|
|
let mut system = System::new();
|
|
|
|
|
|
system.refresh_all();
|
|
|
|
|
|
system.process(Pid::from_u32(pid)).map(|proc| {
|
|
|
|
|
|
if proc.name().contains("clash") {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
log::debug!(target: "app", "kill old clash process");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
proc.kill();
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
2022-11-18 09:35:05 +08:00
|
|
|
|
});
|
2022-11-14 01:26:33 +08:00
|
|
|
|
|
|
|
|
|
|
tauri::async_runtime::spawn(async {
|
2022-11-17 20:19:40 +08:00
|
|
|
|
// 启动clash
|
2022-11-18 18:18:41 +08:00
|
|
|
|
log_err!(Self::global().run_core().await);
|
2022-11-14 01:26:33 +08:00
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// 检查配置是否正确
|
|
|
|
|
|
pub 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() };
|
|
|
|
|
|
let clash_core = clash_core.unwrap_or("clash".into());
|
2022-11-14 01:26:33 +08:00
|
|
|
|
|
2022-11-21 23:11:56 +08:00
|
|
|
|
let app_dir = dirs::app_home_dir()?;
|
|
|
|
|
|
let app_dir = dirs::path_to_str(&app_dir)?;
|
|
|
|
|
|
|
2022-11-14 01:26:33 +08:00
|
|
|
|
let output = Command::new_sidecar(clash_core)?
|
2022-11-21 23:11:56 +08:00
|
|
|
|
.args(["-t", "-d", app_dir, "-f", config_path])
|
2022-11-14 01:26:33 +08:00
|
|
|
|
.output()?;
|
|
|
|
|
|
|
|
|
|
|
|
if !output.status.success() {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
let error = clash_api::parse_check_output(output.stdout.clone());
|
|
|
|
|
|
Logger::global().set_log(output.stdout);
|
|
|
|
|
|
bail!("{error}");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// 启动核心
|
2022-11-17 20:19:40 +08:00
|
|
|
|
pub async fn run_core(&self) -> Result<()> {
|
2022-11-18 18:18:41 +08:00
|
|
|
|
let config_path = Config::generate_file(ConfigType::Run)?;
|
|
|
|
|
|
|
2022-11-22 22:01:34 +08:00
|
|
|
|
let mut should_kill = match self.sidecar.lock().take() {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
Some(child) => {
|
2022-11-22 22:01:34 +08:00
|
|
|
|
log::debug!(target: "app", "stop the core by sidecar");
|
2022-11-18 22:08:06 +08:00
|
|
|
|
let _ = child.kill();
|
|
|
|
|
|
true
|
|
|
|
|
|
}
|
|
|
|
|
|
None => false,
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2022-11-22 22:01:34 +08:00
|
|
|
|
#[cfg(target_os = "windows")]
|
|
|
|
|
|
if *self.use_service_mode.lock() {
|
|
|
|
|
|
log::debug!(target: "app", "stop the core by service");
|
|
|
|
|
|
log_err!(super::win_service::stop_core_by_service().await);
|
|
|
|
|
|
should_kill = true;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-11-18 22:08:06 +08:00
|
|
|
|
// 这里得等一会儿
|
|
|
|
|
|
if should_kill {
|
|
|
|
|
|
sleep(Duration::from_millis(500)).await;
|
2022-11-18 20:15:34 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-11-17 20:19:40 +08:00
|
|
|
|
#[cfg(target_os = "windows")]
|
|
|
|
|
|
{
|
|
|
|
|
|
use super::win_service;
|
|
|
|
|
|
|
|
|
|
|
|
// 服务模式
|
2022-11-22 22:01:34 +08:00
|
|
|
|
let enable = { Config::verge().latest().enable_service_mode.clone() };
|
|
|
|
|
|
let enable = enable.unwrap_or(false);
|
2022-11-17 20:19:40 +08:00
|
|
|
|
|
|
|
|
|
|
*self.use_service_mode.lock() = enable;
|
|
|
|
|
|
|
|
|
|
|
|
if enable {
|
|
|
|
|
|
// 服务模式启动失败就直接运行sidecar
|
2022-11-22 20:46:46 +08:00
|
|
|
|
log::debug!(target: "app", "try to run core in service mode");
|
|
|
|
|
|
|
|
|
|
|
|
match (|| async {
|
2022-11-17 20:19:40 +08:00
|
|
|
|
win_service::check_service().await?;
|
2022-11-18 20:15:34 +08:00
|
|
|
|
win_service::run_core_by_service(&config_path).await
|
2022-11-22 20:46:46 +08:00
|
|
|
|
})()
|
|
|
|
|
|
.await
|
|
|
|
|
|
{
|
2022-11-17 20:19:40 +08:00
|
|
|
|
Ok(_) => return Ok(()),
|
|
|
|
|
|
Err(err) => {
|
|
|
|
|
|
// 修改这个值,免得stop出错
|
|
|
|
|
|
*self.use_service_mode.lock() = false;
|
|
|
|
|
|
log::error!(target: "app", "{err}");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-11-14 01:26:33 +08:00
|
|
|
|
|
2022-11-18 09:35:05 +08:00
|
|
|
|
let app_dir = dirs::app_home_dir()?;
|
2022-11-14 01:26:33 +08:00
|
|
|
|
let app_dir = dirs::path_to_str(&app_dir)?;
|
|
|
|
|
|
|
2022-11-16 01:26:41 +08:00
|
|
|
|
let clash_core = { Config::verge().latest().clash_core.clone() };
|
|
|
|
|
|
let clash_core = clash_core.unwrap_or("clash".into());
|
2022-11-14 01:26:33 +08:00
|
|
|
|
|
2022-11-18 18:18:41 +08:00
|
|
|
|
let config_path = dirs::path_to_str(&config_path)?;
|
|
|
|
|
|
|
2022-11-14 01:26:33 +08:00
|
|
|
|
// fix #212
|
|
|
|
|
|
let args = match clash_core.as_str() {
|
2022-11-18 18:18:41 +08:00
|
|
|
|
"clash-meta" => vec!["-m", "-d", app_dir, "-f", config_path],
|
|
|
|
|
|
_ => vec!["-d", app_dir, "-f", config_path],
|
2022-11-14 01:26:33 +08:00
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
let cmd = Command::new_sidecar(clash_core)?;
|
|
|
|
|
|
let (mut rx, cmd_child) = cmd.args(args).spawn()?;
|
|
|
|
|
|
|
|
|
|
|
|
// 将pid写入文件中
|
2022-11-22 20:46:46 +08:00
|
|
|
|
crate::log_err!((|| {
|
2022-11-14 01:26:33 +08:00
|
|
|
|
let pid = cmd_child.pid();
|
2022-11-18 09:35:05 +08:00
|
|
|
|
let path = dirs::clash_pid_path()?;
|
2022-11-14 01:26:33 +08:00
|
|
|
|
fs::File::create(path)
|
|
|
|
|
|
.context("failed to create the pid file")?
|
|
|
|
|
|
.write(format!("{pid}").as_bytes())
|
|
|
|
|
|
.context("failed to write pid to the file")?;
|
|
|
|
|
|
<Result<()>>::Ok(())
|
2022-11-22 20:46:46 +08:00
|
|
|
|
})());
|
2022-11-14 01:26:33 +08:00
|
|
|
|
|
2022-11-18 20:15:34 +08:00
|
|
|
|
let mut sidecar = self.sidecar.lock();
|
2022-11-14 01:26:33 +08:00
|
|
|
|
*sidecar = Some(cmd_child);
|
|
|
|
|
|
|
|
|
|
|
|
tauri::async_runtime::spawn(async move {
|
|
|
|
|
|
while let Some(event) = rx.recv().await {
|
|
|
|
|
|
match event {
|
|
|
|
|
|
CommandEvent::Stdout(line) => {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
let stdout = clash_api::parse_log(line.clone());
|
|
|
|
|
|
log::info!(target: "app", "[clash]: {stdout}");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
Logger::global().set_log(line);
|
|
|
|
|
|
}
|
|
|
|
|
|
CommandEvent::Stderr(err) => {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
let stdout = clash_api::parse_log(err.clone());
|
|
|
|
|
|
log::error!(target: "app", "[clash]: {stdout}");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
Logger::global().set_log(err);
|
|
|
|
|
|
}
|
|
|
|
|
|
CommandEvent::Error(err) => {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
log::error!(target: "app", "[clash]: {err}");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
Logger::global().set_log(err);
|
|
|
|
|
|
}
|
|
|
|
|
|
CommandEvent::Terminated(_) => {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
log::info!(target: "app", "clash core terminated");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
_ => {}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// 停止核心运行
|
|
|
|
|
|
pub fn stop_core(&self) -> Result<()> {
|
2022-11-17 20:19:40 +08:00
|
|
|
|
#[cfg(target_os = "windows")]
|
|
|
|
|
|
if *self.use_service_mode.lock() {
|
2022-11-22 22:01:34 +08:00
|
|
|
|
log::debug!(target: "app", "stop the core by service");
|
2022-11-17 20:19:40 +08:00
|
|
|
|
tauri::async_runtime::block_on(async move {
|
|
|
|
|
|
log_err!(super::win_service::stop_core_by_service().await);
|
|
|
|
|
|
});
|
|
|
|
|
|
return Ok(());
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-11-14 01:26:33 +08:00
|
|
|
|
let mut sidecar = self.sidecar.lock();
|
|
|
|
|
|
if let Some(child) = sidecar.take() {
|
2022-11-22 22:01:34 +08:00
|
|
|
|
log::debug!(target: "app", "stop the core by sidecar");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
let _ = child.kill();
|
|
|
|
|
|
}
|
|
|
|
|
|
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"))?;
|
|
|
|
|
|
|
|
|
|
|
|
if &clash_core != "clash" && &clash_core != "clash-meta" {
|
|
|
|
|
|
bail!("invalid clash core name \"{clash_core}\"");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-11-18 20:15:34 +08:00
|
|
|
|
log::debug!(target: "app", "change core to `{clash_core}`");
|
|
|
|
|
|
|
2022-11-18 18:18:41 +08:00
|
|
|
|
Config::verge().draft().clash_core = Some(clash_core);
|
|
|
|
|
|
|
2022-11-21 22:27:55 +08:00
|
|
|
|
self.check_config()?;
|
|
|
|
|
|
|
2022-11-14 01:26:33 +08:00
|
|
|
|
// 清掉旧日志
|
|
|
|
|
|
Logger::global().clear_log();
|
|
|
|
|
|
|
2022-11-17 20:19:40 +08:00
|
|
|
|
match self.run_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)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-11-18 18:18:41 +08:00
|
|
|
|
/// 更新proxies那些
|
|
|
|
|
|
/// 如果涉及端口和外部控制则需要重启
|
|
|
|
|
|
pub async fn update_config(&self) -> Result<()> {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
log::debug!(target: "app", "try to update clash config");
|
|
|
|
|
|
|
2022-11-18 18:18:41 +08:00
|
|
|
|
// 更新配置
|
|
|
|
|
|
Config::generate()?;
|
2022-11-14 01:26:33 +08:00
|
|
|
|
|
|
|
|
|
|
// 检查配置是否正常
|
|
|
|
|
|
self.check_config()?;
|
|
|
|
|
|
|
2022-11-18 18:18:41 +08:00
|
|
|
|
// 更新运行时配置
|
|
|
|
|
|
let path = Config::generate_file(ConfigType::Run)?;
|
|
|
|
|
|
let path = dirs::path_to_str(&path)?;
|
|
|
|
|
|
|
2022-11-14 01:26:33 +08:00
|
|
|
|
// 发送请求 发送5次
|
|
|
|
|
|
for i in 0..5 {
|
2022-11-18 18:18:41 +08:00
|
|
|
|
match clash_api::put_configs(path).await {
|
2022-11-14 01:26:33 +08:00
|
|
|
|
Ok(_) => break,
|
|
|
|
|
|
Err(err) => {
|
|
|
|
|
|
if i < 4 {
|
2022-11-18 22:08:06 +08:00
|
|
|
|
log::info!(target: "app", "{err}");
|
2022-11-14 01:26:33 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
bail!(err);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
sleep(Duration::from_millis(250)).await;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|