fix: improve Service connection method and permissions for Windows and Unix
This commit is contained in:
@@ -24,6 +24,7 @@
|
||||
- Linux 现在在新生成的配置中默认将 TUN 栈恢复为 mixed 模式
|
||||
- 为代理延迟测试的 URL 设置增加了保护以及添加了安全的备用 URL
|
||||
- 更新了 Wayland 合成器检测逻辑,从而在 Hyprland 会话中保留原生 Wayland 后端
|
||||
- 改进 Windows 和 Unix 的 服务连接方式以及权限,避免无法连接服务或内核
|
||||
|
||||
### 🐞 修复问题
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import AdmZip from "adm-zip";
|
||||
import { execSync } from "child_process";
|
||||
import fs from "fs";
|
||||
import fsp from "fs/promises";
|
||||
import zlib from "zlib";
|
||||
import { extract } from "tar";
|
||||
import path from "path";
|
||||
import AdmZip from "adm-zip";
|
||||
import fetch from "node-fetch";
|
||||
import { HttpsProxyAgent } from "https-proxy-agent";
|
||||
import { execSync } from "child_process";
|
||||
import { log_info, log_debug, log_error, log_success } from "./utils.mjs";
|
||||
import { glob } from "glob";
|
||||
import { HttpsProxyAgent } from "https-proxy-agent";
|
||||
import fetch from "node-fetch";
|
||||
import path from "path";
|
||||
import { extract } from "tar";
|
||||
import zlib from "zlib";
|
||||
import { log_debug, log_error, log_info, log_success } from "./utils.mjs";
|
||||
|
||||
const cwd = process.cwd();
|
||||
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
|
||||
@@ -383,8 +383,8 @@ const resolvePlugin = async () => {
|
||||
const resolveServicePermission = async () => {
|
||||
const serviceExecutables = [
|
||||
"clash-verge-service*",
|
||||
"install-service*",
|
||||
"uninstall-service*",
|
||||
"clash-verge-service-install*",
|
||||
"clash-verge-service-uninstall*",
|
||||
];
|
||||
const resDir = path.join(cwd, "src-tauri/resources");
|
||||
for (let f of serviceExecutables) {
|
||||
@@ -430,7 +430,7 @@ async function resolveLocales() {
|
||||
/**
|
||||
* main
|
||||
*/
|
||||
const SERVICE_URL = `https://github.com/clash-verge-rev/clash-verge-service/releases/download/${SIDECAR_HOST}`;
|
||||
const SERVICE_URL = `https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download/${SIDECAR_HOST}`;
|
||||
|
||||
const resolveService = () => {
|
||||
let ext = platform === "win32" ? ".exe" : "";
|
||||
@@ -445,8 +445,8 @@ const resolveInstall = () => {
|
||||
let ext = platform === "win32" ? ".exe" : "";
|
||||
let suffix = platform === "linux" ? "-" + SIDECAR_HOST : "";
|
||||
resolveResource({
|
||||
file: "install-service" + suffix + ext,
|
||||
downloadURL: `${SERVICE_URL}/install-service${ext}`,
|
||||
file: "clash-verge-service-install" + suffix + ext,
|
||||
downloadURL: `${SERVICE_URL}/clash-verge-service-install${ext}`,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -455,8 +455,8 @@ const resolveUninstall = () => {
|
||||
let suffix = platform === "linux" ? "-" + SIDECAR_HOST : "";
|
||||
|
||||
resolveResource({
|
||||
file: "uninstall-service" + suffix + ext,
|
||||
downloadURL: `${SERVICE_URL}/uninstall-service${ext}`,
|
||||
file: "clash-verge-service-uninstall" + suffix + ext,
|
||||
downloadURL: `${SERVICE_URL}/clash-verge-service-uninstall${ext}`,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
714
src-tauri/Cargo.lock
generated
714
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -85,8 +85,12 @@ console-subscriber = { version = "0.4.1", optional = true }
|
||||
tauri-plugin-devtools = { version = "2.0.1" }
|
||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo" }
|
||||
clash_verge_logger = { version = "0.1.0", git = "https://github.com/clash-verge-rev/clash-verge-logger" }
|
||||
clash_verge_service_ipc = { version = "2.0.7", git = "https://github.com/clash-verge-rev/clash-verge-service-ipc" }
|
||||
|
||||
clash_verge_service_ipc = { version = "2.0.14", features = [
|
||||
"client",
|
||||
], git = "https://github.com/clash-verge-rev/clash-verge-service-ipc" }
|
||||
# clash_verge_service_ipc = { version = "2.0.14", features = [
|
||||
# "client",
|
||||
# ], path = "../../clash-verge-service-ipc" }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
runas = "=1.2.0"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/bin/bash
|
||||
chmod +x /usr/bin/install-service
|
||||
chmod +x /usr/bin/uninstall-service
|
||||
chmod +x /usr/bin/clash-verge-service-install
|
||||
chmod +x /usr/bin/clash-verge-service-uninstall
|
||||
chmod +x /usr/bin/clash-verge-service
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
#!/bin/bash
|
||||
/usr/bin/uninstall-service
|
||||
/usr/bin/clash-verge-service-uninstall
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use super::CmdResult;
|
||||
use crate::{
|
||||
core::{
|
||||
CoreManager,
|
||||
service::{self, SERVICE_MANAGER, ServiceStatus},
|
||||
},
|
||||
core::service::{self, SERVICE_MANAGER, ServiceStatus},
|
||||
utils::i18n::t,
|
||||
};
|
||||
|
||||
@@ -17,10 +14,6 @@ async fn execute_service_operation_sync(status: ServiceStatus, op_type: &str) ->
|
||||
let emsg = format!("{} Service failed: {}", op_type, e);
|
||||
return Err(t(emsg.as_str()).await);
|
||||
}
|
||||
if CoreManager::global().restart_core().await.is_err() {
|
||||
let emsg = "Restart Core failed";
|
||||
return Err(t(emsg).await);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -870,7 +870,6 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
pub async fn prestart_core(&self) -> Result<()> {
|
||||
SERVICE_MANAGER.lock().await.refresh().await?;
|
||||
match SERVICE_MANAGER.lock().await.current() {
|
||||
ServiceStatus::Ready => {
|
||||
self.set_running_mode(RunningMode::Service);
|
||||
@@ -912,6 +911,9 @@ impl CoreManager {
|
||||
pub async fn restart_core(&self) -> Result<()> {
|
||||
logging!(info, Type::Core, "Restarting core");
|
||||
self.stop_core().await?;
|
||||
if SERVICE_MANAGER.lock().await.init().await.is_ok() {
|
||||
logging_error!(Type::Setup, SERVICE_MANAGER.lock().await.refresh().await);
|
||||
}
|
||||
self.start_core().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ pub mod handle;
|
||||
pub mod hotkey;
|
||||
pub mod logger;
|
||||
pub mod service;
|
||||
pub mod service_ipc;
|
||||
pub mod sysopt;
|
||||
pub mod timer;
|
||||
pub mod tray;
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
use crate::{
|
||||
config::Config,
|
||||
core::service_ipc::{IpcCommand, send_ipc_request},
|
||||
logging, logging_error,
|
||||
utils::{dirs, logging::Type},
|
||||
utils::{dirs, init::service_writer_config, logging::Type},
|
||||
};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clash_verge_service_ipc::CoreConfig;
|
||||
use once_cell::sync::Lazy;
|
||||
use std::{env::current_exe, path::PathBuf, process::Command as StdCommand};
|
||||
use std::{
|
||||
env::current_exe,
|
||||
path::{Path, PathBuf},
|
||||
process::Command as StdCommand,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
const REQUIRED_SERVICE_VERSION: &str = "1.1.2"; // 定义所需的服务版本号
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ServiceStatus {
|
||||
Ready,
|
||||
@@ -35,7 +38,7 @@ async fn uninstall_service() -> Result<()> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
let binary_path = dirs::service_path()?;
|
||||
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
|
||||
let uninstall_path = binary_path.with_file_name("clash-verge-service-uninstall.exe");
|
||||
|
||||
if !uninstall_path.exists() {
|
||||
bail!(format!("uninstaller not found: {uninstall_path:?}"));
|
||||
@@ -70,7 +73,7 @@ async fn install_service() -> Result<()> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
let binary_path = dirs::service_path()?;
|
||||
let install_path = binary_path.with_file_name("install-service.exe");
|
||||
let install_path = binary_path.with_file_name("clash-verge-service-install.exe");
|
||||
|
||||
if !install_path.exists() {
|
||||
bail!(format!("installer not found: {install_path:?}"));
|
||||
@@ -119,7 +122,8 @@ async fn uninstall_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "uninstall service");
|
||||
use users::get_effective_uid;
|
||||
|
||||
let uninstall_path = tauri::utils::platform::current_exe()?.with_file_name("uninstall-service");
|
||||
let uninstall_path =
|
||||
tauri::utils::platform::current_exe()?.with_file_name("clash-verge-service-uninstall");
|
||||
|
||||
if !uninstall_path.exists() {
|
||||
bail!(format!("uninstaller not found: {uninstall_path:?}"));
|
||||
@@ -159,7 +163,8 @@ async fn install_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "install service");
|
||||
use users::get_effective_uid;
|
||||
|
||||
let install_path = tauri::utils::platform::current_exe()?.with_file_name("install-service");
|
||||
let install_path =
|
||||
tauri::utils::platform::current_exe()?.with_file_name("clash-verge-service-install");
|
||||
|
||||
if !install_path.exists() {
|
||||
bail!(format!("installer not found: {install_path:?}"));
|
||||
@@ -218,7 +223,7 @@ async fn uninstall_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "uninstall service");
|
||||
|
||||
let binary_path = dirs::service_path()?;
|
||||
let uninstall_path = binary_path.with_file_name("uninstall-service");
|
||||
let uninstall_path = binary_path.with_file_name("clash-verge-service-uninstall");
|
||||
|
||||
if !uninstall_path.exists() {
|
||||
bail!(format!("uninstaller not found: {uninstall_path:?}"));
|
||||
@@ -254,7 +259,7 @@ async fn install_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "install service");
|
||||
|
||||
let binary_path = dirs::service_path()?;
|
||||
let install_path = binary_path.with_file_name("install-service");
|
||||
let install_path = binary_path.with_file_name("clash-verge-service-install");
|
||||
|
||||
if !install_path.exists() {
|
||||
bail!(format!("installer not found: {install_path:?}"));
|
||||
@@ -314,21 +319,17 @@ pub async fn force_reinstall_service() -> Result<()> {
|
||||
async fn check_service_version() -> Result<String> {
|
||||
let version_arc: Result<String> = {
|
||||
logging!(info, Type::Service, "开始检查服务版本 (IPC)");
|
||||
let payload = serde_json::json!({});
|
||||
let response = send_ipc_request(IpcCommand::GetVersion, payload).await?;
|
||||
|
||||
let data = response
|
||||
.data
|
||||
.ok_or_else(|| anyhow::anyhow!("服务版本响应中没有数据"))?;
|
||||
|
||||
if let Some(nested_data) = data.get("data")
|
||||
&& let Some(version) = nested_data.get("version").and_then(|v| v.as_str())
|
||||
{
|
||||
// logging!(info, Type::Service, true, "获取到服务版本: {}", version);
|
||||
Ok(version.to_string())
|
||||
} else {
|
||||
Ok("unknown".to_string())
|
||||
let response = clash_verge_service_ipc::get_version()
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
if response.code > 0 {
|
||||
let err_msg = response.message;
|
||||
logging!(error, Type::Service, "获取服务版本失败: {}", err_msg);
|
||||
return Err(anyhow::anyhow!(err_msg));
|
||||
}
|
||||
|
||||
let version = response.data.unwrap_or("unknown".to_string());
|
||||
Ok(version)
|
||||
};
|
||||
|
||||
match version_arc.as_ref() {
|
||||
@@ -340,7 +341,7 @@ async fn check_service_version() -> Result<String> {
|
||||
/// 检查服务是否需要重装
|
||||
pub async fn check_service_needs_reinstall() -> bool {
|
||||
match check_service_version().await {
|
||||
Ok(version) => version != REQUIRED_SERVICE_VERSION,
|
||||
Ok(version) => version != clash_verge_service_ipc::VERSION,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -356,35 +357,25 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result
|
||||
let bin_ext = if cfg!(windows) { ".exe" } else { "" };
|
||||
let bin_path = current_exe()?.with_file_name(format!("{clash_core}{bin_ext}"));
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"core_type": clash_core,
|
||||
"bin_path": dirs::path_to_str(&bin_path)?,
|
||||
"config_dir": dirs::path_to_str(&dirs::app_home_dir()?)?,
|
||||
"config_file": dirs::path_to_str(config_file)?,
|
||||
// TODO 迁移 Service日志后删除
|
||||
"log_file": dirs::path_to_str(&dirs::service_log_file()?)?,
|
||||
});
|
||||
let payload = clash_verge_service_ipc::ClashConfig {
|
||||
core_config: CoreConfig {
|
||||
config_path: dirs::path_to_str(config_file)?.to_string(),
|
||||
core_path: dirs::path_to_str(&bin_path)?.to_string(),
|
||||
config_dir: dirs::path_to_str(&dirs::app_home_dir()?)?.to_string(),
|
||||
},
|
||||
log_config: service_writer_config().await?,
|
||||
};
|
||||
|
||||
let response = send_ipc_request(IpcCommand::StartClash, payload)
|
||||
let response = clash_verge_service_ipc::start_clash(&payload)
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
|
||||
if !response.success {
|
||||
let err_msg = response.error.unwrap_or_else(|| "启动核心失败".to_string());
|
||||
if response.code > 0 {
|
||||
let err_msg = response.message;
|
||||
logging!(error, Type::Service, "启动核心失败: {}", err_msg);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
if let Some(data) = &response.data
|
||||
&& let Some(code) = data.get("code").and_then(|c| c.as_u64())
|
||||
&& code != 0
|
||||
{
|
||||
let msg = data
|
||||
.get("msg")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("未知错误");
|
||||
bail!("启动核心失败: {}", msg);
|
||||
}
|
||||
|
||||
logging!(info, Type::Service, "服务成功启动核心");
|
||||
Ok(())
|
||||
}
|
||||
@@ -405,53 +396,51 @@ pub(super) async fn run_core_by_service(config_file: &PathBuf) -> Result<()> {
|
||||
pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "通过服务停止核心 (IPC)");
|
||||
|
||||
let payload = serde_json::json!({});
|
||||
let response = send_ipc_request(IpcCommand::StopClash, payload)
|
||||
let response = clash_verge_service_ipc::stop_clash()
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
|
||||
if !response.success {
|
||||
let err_msg = response.error.unwrap_or_else(|| "停止核心失败".to_string());
|
||||
if response.code > 0 {
|
||||
let err_msg = response.message;
|
||||
logging!(error, Type::Service, "停止核心失败: {}", err_msg);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
if let Some(data) = &response.data
|
||||
&& let Some(code) = data.get("code")
|
||||
{
|
||||
let code_value = code.as_u64().unwrap_or(1);
|
||||
let msg = data
|
||||
.get("msg")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("未知错误");
|
||||
|
||||
if code_value != 0 {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"停止核心返回错误: code={}, msg={}",
|
||||
code_value,
|
||||
msg
|
||||
);
|
||||
bail!("停止核心失败: {}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
logging!(info, Type::Service, "服务成功停止核心");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查服务是否正在运行
|
||||
pub async fn is_service_available() -> Result<()> {
|
||||
check_service_version().await?;
|
||||
clash_verge_service_ipc::connect().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_service_ipc_path_exists() -> bool {
|
||||
Path::new(clash_verge_service_ipc::IPC_PATH).exists()
|
||||
}
|
||||
|
||||
impl ServiceManager {
|
||||
pub fn default() -> Self {
|
||||
Self(ServiceStatus::Unavailable("Need Checks".into()))
|
||||
}
|
||||
|
||||
pub fn config() -> Option<clash_verge_service_ipc::IpcConfig> {
|
||||
Some(clash_verge_service_ipc::IpcConfig {
|
||||
default_timeout: Duration::from_millis(30),
|
||||
retry_delay: Duration::from_millis(250),
|
||||
max_retries: 6,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn init(&mut self) -> Result<()> {
|
||||
if let Err(e) = clash_verge_service_ipc::connect().await {
|
||||
self.0 = ServiceStatus::Unavailable("服务连接失败: {e}".to_string());
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn current(&self) -> ServiceStatus {
|
||||
self.0.clone()
|
||||
}
|
||||
@@ -487,31 +476,26 @@ impl ServiceManager {
|
||||
match status {
|
||||
ServiceStatus::Ready => {
|
||||
logging!(info, Type::Service, "服务就绪,直接启动");
|
||||
Ok(())
|
||||
}
|
||||
ServiceStatus::NeedsReinstall | ServiceStatus::ReinstallRequired => {
|
||||
logging!(info, Type::Service, "服务需要重装,执行重装流程");
|
||||
reinstall_service().await?;
|
||||
self.0 = ServiceStatus::Ready;
|
||||
Ok(())
|
||||
}
|
||||
ServiceStatus::ForceReinstallRequired => {
|
||||
logging!(info, Type::Service, "服务需要强制重装,执行强制重装流程");
|
||||
force_reinstall_service().await?;
|
||||
self.0 = ServiceStatus::Ready;
|
||||
Ok(())
|
||||
}
|
||||
ServiceStatus::InstallRequired => {
|
||||
logging!(info, Type::Service, "需要安装服务,执行安装流程");
|
||||
install_service().await?;
|
||||
self.0 = ServiceStatus::Ready;
|
||||
Ok(())
|
||||
}
|
||||
ServiceStatus::UninstallRequired => {
|
||||
logging!(info, Type::Service, "服务需要卸载,执行卸载流程");
|
||||
uninstall_service().await?;
|
||||
self.0 = ServiceStatus::Unavailable("Service Uninstalled".into());
|
||||
Ok(())
|
||||
}
|
||||
ServiceStatus::Unavailable(reason) => {
|
||||
logging!(
|
||||
@@ -521,9 +505,10 @@ impl ServiceManager {
|
||||
reason
|
||||
);
|
||||
self.0 = ServiceStatus::Unavailable(reason.clone());
|
||||
Err(anyhow::anyhow!("服务不可用: {}", reason))
|
||||
return Err(anyhow::anyhow!("服务不可用: {}", reason));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,347 +0,0 @@
|
||||
use crate::{logging, utils::logging::Type};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use backoff::{Error as BackoffError, ExponentialBackoff};
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
#[cfg(unix)]
|
||||
use tokio::net::UnixStream;
|
||||
#[cfg(windows)]
|
||||
use tokio::net::windows::named_pipe::ClientOptions;
|
||||
|
||||
const IPC_SOCKET_NAME: &str = if cfg!(windows) {
|
||||
r"\\.\pipe\clash-verge-service"
|
||||
} else {
|
||||
"/tmp/clash-verge-service.sock"
|
||||
};
|
||||
|
||||
// 定义命令类型
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum IpcCommand {
|
||||
GetClash,
|
||||
GetVersion,
|
||||
StartClash,
|
||||
StopClash,
|
||||
}
|
||||
|
||||
// IPC消息格式
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcRequest {
|
||||
pub id: String,
|
||||
pub timestamp: u64,
|
||||
pub command: IpcCommand,
|
||||
pub payload: serde_json::Value,
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcResponse {
|
||||
pub id: String,
|
||||
pub success: bool,
|
||||
pub data: Option<serde_json::Value>,
|
||||
pub error: Option<String>,
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
// 密钥派生函数
|
||||
fn derive_secret_key() -> Vec<u8> {
|
||||
// to do
|
||||
// 从系统安全存储中获取或从程序安装时生成的密钥文件中读取
|
||||
let unique_app_id = "clash-verge-app-secret-fuck-me-until-daylight";
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(unique_app_id.as_bytes());
|
||||
hasher.finalize().to_vec()
|
||||
}
|
||||
|
||||
// 创建带签名的请求
|
||||
pub fn create_signed_request(
|
||||
command: IpcCommand,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<IpcRequest> {
|
||||
let id = nanoid::nanoid!(32);
|
||||
let timestamp = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
let unsigned_request = IpcRequest {
|
||||
id: id.clone(),
|
||||
timestamp,
|
||||
command: command.clone(),
|
||||
payload: payload.clone(),
|
||||
signature: String::new(),
|
||||
};
|
||||
|
||||
let unsigned_json = serde_json::to_string(&unsigned_request)?;
|
||||
let signature = sign_message(&unsigned_json)?;
|
||||
|
||||
Ok(IpcRequest {
|
||||
id,
|
||||
timestamp,
|
||||
command,
|
||||
payload,
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
// 签名消息
|
||||
fn sign_message(message: &str) -> Result<String> {
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
let secret_key = derive_secret_key();
|
||||
let mut mac = HmacSha256::new_from_slice(&secret_key).context("HMAC初始化失败")?;
|
||||
|
||||
mac.update(message.as_bytes());
|
||||
let result = mac.finalize();
|
||||
let signature = hex::encode(result.into_bytes());
|
||||
|
||||
Ok(signature)
|
||||
}
|
||||
|
||||
// 验证响应签名
|
||||
pub fn verify_response_signature(response: &IpcResponse) -> Result<bool> {
|
||||
let verification_response = IpcResponse {
|
||||
id: response.id.clone(),
|
||||
success: response.success,
|
||||
data: response.data.clone(),
|
||||
error: response.error.clone(),
|
||||
signature: String::new(),
|
||||
};
|
||||
|
||||
let message = serde_json::to_string(&verification_response)?;
|
||||
let expected_signature = sign_message(&message)?;
|
||||
|
||||
Ok(expected_signature == response.signature)
|
||||
}
|
||||
|
||||
fn create_backoff_strategy() -> ExponentialBackoff {
|
||||
ExponentialBackoff {
|
||||
initial_interval: Duration::from_millis(50),
|
||||
max_interval: Duration::from_secs(1),
|
||||
max_elapsed_time: Some(Duration::from_secs(3)),
|
||||
multiplier: 1.5,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send_ipc_request(
|
||||
command: IpcCommand,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<IpcResponse> {
|
||||
let command_type = format!("{command:?}");
|
||||
|
||||
let operation = || async {
|
||||
match send_ipc_request_internal(command.clone(), payload.clone()).await {
|
||||
Ok(response) => Ok(response),
|
||||
Err(e) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"IPC请求失败,准备重试: 命令={}, 错误={}",
|
||||
command_type,
|
||||
e
|
||||
);
|
||||
Err(BackoffError::transient(e))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match backoff::future::retry(create_backoff_strategy(), operation).await {
|
||||
Ok(response) => {
|
||||
// logging!(
|
||||
// info,
|
||||
// Type::Service,
|
||||
// true,
|
||||
// "IPC请求成功: 命令={}, 成功={}",
|
||||
// command_type,
|
||||
// response.success
|
||||
// );
|
||||
Ok(response)
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"IPC请求最终失败,重试已耗尽: 命令={}, 错误={}",
|
||||
command_type,
|
||||
e
|
||||
);
|
||||
Err(anyhow::anyhow!("IPC请求重试失败: {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 内部IPC请求实现(不带重试)
|
||||
async fn send_ipc_request_internal(
|
||||
command: IpcCommand,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<IpcResponse> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
send_ipc_request_windows(command, payload).await
|
||||
}
|
||||
#[cfg(target_family = "unix")]
|
||||
{
|
||||
send_ipc_request_unix(command, payload).await
|
||||
}
|
||||
}
|
||||
|
||||
// IPC连接管理-win
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn send_ipc_request_windows(
|
||||
command: IpcCommand,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<IpcResponse> {
|
||||
let request = create_signed_request(command, payload)?;
|
||||
let request_json = serde_json::to_string(&request)?;
|
||||
let request_bytes = request_json.as_bytes();
|
||||
let len_bytes = (request_bytes.len() as u32).to_be_bytes();
|
||||
|
||||
let mut pipe = match ClientOptions::new().open(IPC_SOCKET_NAME) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, "连接到服务命名管道失败: {}", e);
|
||||
return Err(anyhow::anyhow!("无法连接到服务命名管道: {}", e));
|
||||
}
|
||||
};
|
||||
|
||||
logging!(info, Type::Service, "服务连接成功 (Windows)");
|
||||
|
||||
pipe.write_all(&len_bytes).await?;
|
||||
pipe.write_all(request_bytes).await?;
|
||||
pipe.flush().await?;
|
||||
|
||||
let mut response_len_bytes = [0u8; 4];
|
||||
pipe.read_exact(&mut response_len_bytes).await?;
|
||||
let response_len = u32::from_be_bytes(response_len_bytes) as usize;
|
||||
|
||||
let mut response_bytes = vec![0u8; response_len];
|
||||
pipe.read_exact(&mut response_bytes).await?;
|
||||
|
||||
let response: IpcResponse = serde_json::from_slice(&response_bytes)
|
||||
.map_err(|e| anyhow::anyhow!("解析响应失败: {}", e))?;
|
||||
|
||||
if !verify_response_signature(&response)? {
|
||||
logging!(error, Type::Service, "服务响应签名验证失败");
|
||||
bail!("服务响应签名验证失败");
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
// IPC连接管理-unix
|
||||
#[cfg(target_family = "unix")]
|
||||
async fn send_ipc_request_unix(
|
||||
command: IpcCommand,
|
||||
payload: serde_json::Value,
|
||||
) -> Result<IpcResponse> {
|
||||
let request = create_signed_request(command, payload)?;
|
||||
let request_json = serde_json::to_string(&request)?;
|
||||
|
||||
let mut stream = match UnixStream::connect(IPC_SOCKET_NAME).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, "连接到Unix套接字失败: {}", e);
|
||||
return Err(anyhow::anyhow!("无法连接到服务Unix套接字: {}", e));
|
||||
}
|
||||
};
|
||||
|
||||
let request_bytes = request_json.as_bytes();
|
||||
let len_bytes = (request_bytes.len() as u32).to_be_bytes();
|
||||
|
||||
stream.write_all(&len_bytes).await?;
|
||||
stream.write_all(request_bytes).await?;
|
||||
stream.flush().await?;
|
||||
|
||||
// 读取响应长度
|
||||
let mut response_len_bytes = [0u8; 4];
|
||||
stream.read_exact(&mut response_len_bytes).await?;
|
||||
let response_len = u32::from_be_bytes(response_len_bytes) as usize;
|
||||
|
||||
let mut response_bytes = vec![0u8; response_len];
|
||||
stream.read_exact(&mut response_bytes).await?;
|
||||
|
||||
let response: IpcResponse = serde_json::from_slice(&response_bytes)
|
||||
.map_err(|e| anyhow::anyhow!("解析响应失败: {}", e))?;
|
||||
|
||||
if !verify_response_signature(&response)? {
|
||||
logging!(error, Type::Service, "服务响应签名验证失败");
|
||||
bail!("服务响应签名验证失败");
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_create_signed_request() {
|
||||
let command = IpcCommand::GetVersion;
|
||||
let payload = serde_json::json!({"test": "data"});
|
||||
|
||||
let result = create_signed_request(command, payload);
|
||||
assert!(result.is_ok());
|
||||
|
||||
if let Ok(request) = result {
|
||||
assert!(!request.id.is_empty());
|
||||
assert!(!request.signature.is_empty());
|
||||
assert_eq!(request.command, IpcCommand::GetVersion);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sign_and_verify_message() {
|
||||
let test_message = "test message for signing";
|
||||
|
||||
let signature_result = sign_message(test_message);
|
||||
assert!(signature_result.is_ok());
|
||||
|
||||
if let Ok(signature) = signature_result {
|
||||
assert!(!signature.is_empty());
|
||||
|
||||
// 测试相同消息产生相同签名
|
||||
if let Ok(signature2) = sign_message(test_message) {
|
||||
assert_eq!(signature, signature2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_response_signature() {
|
||||
let response = IpcResponse {
|
||||
id: "test-id".to_string(),
|
||||
success: true,
|
||||
data: Some(serde_json::json!({"result": "success"})),
|
||||
error: None,
|
||||
signature: String::new(),
|
||||
};
|
||||
|
||||
// 创建正确的签名
|
||||
let verification_response = IpcResponse {
|
||||
id: response.id.clone(),
|
||||
success: response.success,
|
||||
data: response.data.clone(),
|
||||
error: response.error.clone(),
|
||||
signature: String::new(),
|
||||
};
|
||||
|
||||
if let Ok(message) = serde_json::to_string(&verification_response)
|
||||
&& let Ok(correct_signature) = sign_message(&message)
|
||||
{
|
||||
let signed_response = IpcResponse {
|
||||
signature: correct_signature,
|
||||
..response
|
||||
};
|
||||
|
||||
let verification_result = verify_response_signature(&signed_response);
|
||||
assert!(verification_result.is_ok());
|
||||
if let Ok(is_valid) = verification_result {
|
||||
assert!(is_valid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,21 +144,6 @@ pub fn service_path() -> Result<PathBuf> {
|
||||
Ok(res_dir.join("clash-verge-service.exe"))
|
||||
}
|
||||
|
||||
// TODO 迁移 Service日志后删除
|
||||
pub fn service_log_file() -> Result<PathBuf> {
|
||||
use chrono::Local;
|
||||
|
||||
let log_dir = app_logs_dir()?.join("service");
|
||||
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M").to_string();
|
||||
let log_file = format!("{local_time}.log");
|
||||
let log_file = log_dir.join(log_file);
|
||||
|
||||
let _ = std::fs::create_dir_all(&log_dir);
|
||||
|
||||
Ok(log_file)
|
||||
}
|
||||
|
||||
pub fn sidecar_log_dir() -> Result<PathBuf> {
|
||||
let log_dir = app_logs_dir()?.join("sidecar");
|
||||
let _ = std::fs::create_dir_all(&log_dir);
|
||||
@@ -207,7 +192,7 @@ pub fn get_encryption_key() -> Result<Vec<u8>> {
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn ensure_mihomo_safe_dir() -> Option<PathBuf> {
|
||||
["/var/tmp", "/tmp"]
|
||||
["/tmp"]
|
||||
.iter()
|
||||
.map(PathBuf::from)
|
||||
.find(|path| path.exists())
|
||||
|
||||
@@ -93,8 +93,6 @@ pub async fn sidecar_writer() -> Result<FileLogWriter> {
|
||||
.try_build()?)
|
||||
}
|
||||
|
||||
// TODO 后续迁移新 service 时使用
|
||||
#[allow(dead_code)]
|
||||
pub async fn service_writer_config() -> Result<WriterConfig> {
|
||||
let (log_max_size, log_max_count) = {
|
||||
let verge_guard = Config::verge().await;
|
||||
|
||||
@@ -3,7 +3,11 @@ use anyhow::Result;
|
||||
use crate::{
|
||||
config::Config,
|
||||
core::{
|
||||
CoreManager, Timer, handle, hotkey::Hotkey, service::SERVICE_MANAGER, sysopt, tray::Tray,
|
||||
CoreManager, Timer, handle,
|
||||
hotkey::Hotkey,
|
||||
service::{SERVICE_MANAGER, ServiceManager, is_service_ipc_path_exists},
|
||||
sysopt,
|
||||
tray::Tray,
|
||||
},
|
||||
logging, logging_error,
|
||||
module::lightweight::{auto_lightweight_mode_init, run_once_auto_lightweight},
|
||||
@@ -46,7 +50,7 @@ pub fn resolve_setup_async() {
|
||||
"Version: {}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
init_service_manager().await;
|
||||
futures::join!(init_service_manager());
|
||||
|
||||
futures::join!(
|
||||
init_work_config(),
|
||||
@@ -189,7 +193,18 @@ pub(super) async fn init_verge_config() {
|
||||
|
||||
pub(super) async fn init_service_manager() {
|
||||
logging!(info, Type::Setup, "Initializing service manager...");
|
||||
logging_error!(Type::Setup, SERVICE_MANAGER.lock().await.refresh().await);
|
||||
clash_verge_service_ipc::set_config(ServiceManager::config()).await;
|
||||
if !is_service_ipc_path_exists() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Setup,
|
||||
"Service IPC path does not exist, service may be unavailable"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if SERVICE_MANAGER.lock().await.init().await.is_ok() {
|
||||
logging_error!(Type::Setup, SERVICE_MANAGER.lock().await.refresh().await);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn init_core_manager() {
|
||||
|
||||
@@ -25,8 +25,8 @@
|
||||
},
|
||||
"externalBin": [
|
||||
"./resources/clash-verge-service",
|
||||
"./resources/install-service",
|
||||
"./resources/uninstall-service",
|
||||
"./resources/clash-verge-service-install",
|
||||
"./resources/clash-verge-service-uninstall",
|
||||
"./sidecar/verge-mihomo",
|
||||
"./sidecar/verge-mihomo-alpha"
|
||||
]
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useCallback } from "react";
|
||||
|
||||
import { installService, restartCore } from "@/services/cmds";
|
||||
import { showNotice } from "@/services/noticeService";
|
||||
import { useSystemState } from "./use-system-state";
|
||||
|
||||
const executeWithErrorHandling = async (
|
||||
operation: () => Promise<void>,
|
||||
@@ -23,6 +24,8 @@ const executeWithErrorHandling = async (
|
||||
};
|
||||
|
||||
export const useServiceInstaller = () => {
|
||||
const { mutateRunningMode, mutateServiceOk } = useSystemState();
|
||||
|
||||
const installServiceAndRestartCore = useCallback(async () => {
|
||||
await executeWithErrorHandling(
|
||||
() => installService(),
|
||||
@@ -31,6 +34,6 @@ export const useServiceInstaller = () => {
|
||||
);
|
||||
|
||||
await executeWithErrorHandling(() => restartCore(), "Restarting Core...");
|
||||
}, []);
|
||||
}, [mutateRunningMode, mutateServiceOk]);
|
||||
return { installServiceAndRestartCore };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user