mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-21 19:52:12 +08:00
Compare commits
1
Commits
dev
..
fix/autostart
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2af44fab60 |
Generated
+12
-2
@@ -1118,6 +1118,7 @@ dependencies = [
|
|||||||
"open",
|
"open",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
|
"quick-xml 0.42.0",
|
||||||
"reqwest 0.13.5",
|
"reqwest 0.13.5",
|
||||||
"reqwest_dav",
|
"reqwest_dav",
|
||||||
"rfd 0.18.0",
|
"rfd 0.18.0",
|
||||||
@@ -5264,7 +5265,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"indexmap 2.14.0",
|
"indexmap 2.14.0",
|
||||||
"quick-xml",
|
"quick-xml 0.41.0",
|
||||||
"serde",
|
"serde",
|
||||||
"time",
|
"time",
|
||||||
]
|
]
|
||||||
@@ -5534,6 +5535,15 @@ dependencies = [
|
|||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quick-xml"
|
||||||
|
version = "0.42.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quinn"
|
name = "quinn"
|
||||||
version = "0.11.11"
|
version = "0.11.11"
|
||||||
@@ -8998,7 +9008,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quick-xml",
|
"quick-xml 0.41.0",
|
||||||
"quote",
|
"quote",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,10 @@
|
|||||||
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
|
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
|
||||||
- 修复使用系统代理时 IP 信息显示直连地址
|
- 修复使用系统代理时 IP 信息显示直连地址
|
||||||
|
|
||||||
|
**🖥️ Windows**
|
||||||
|
|
||||||
|
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|
||||||
- 修复 macOS TUN 模式下原有 DNS 被清除、关闭后 DNS 未恢复及联网后设置未生效
|
- 修复 macOS TUN 模式下原有 DNS 被清除、关闭后 DNS 未恢复及联网后设置未生效
|
||||||
|
|||||||
@@ -140,10 +140,16 @@ objc2-app-kit = { version = "0.3.2", features = [
|
|||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
deelevate = { workspace = true }
|
deelevate = { workspace = true }
|
||||||
|
quick-xml = "0.42.0"
|
||||||
runas = "=1.2.0"
|
runas = "=1.2.0"
|
||||||
winreg = "0.56.0"
|
winreg = "0.56.0"
|
||||||
windows-service = "0.8.1"
|
windows-service = "0.8.1"
|
||||||
windows = { version = "0.62.2", features = ["Win32_Globalization"] }
|
windows = { version = "0.62.2", features = [
|
||||||
|
"Win32_System_Com",
|
||||||
|
"Win32_System_Ole",
|
||||||
|
"Win32_System_TaskScheduler",
|
||||||
|
"Win32_System_Variant",
|
||||||
|
] }
|
||||||
windows-sys.workspace = true
|
windows-sys.workspace = true
|
||||||
|
|
||||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ ${StrLoc}
|
|||||||
|
|
||||||
Var PassiveMode
|
Var PassiveMode
|
||||||
Var UpdateMode
|
Var UpdateMode
|
||||||
|
Var KeepAutoLaunch
|
||||||
Var NoShortcutMode
|
Var NoShortcutMode
|
||||||
Var WixMode
|
Var WixMode
|
||||||
Var OldMainBinaryName
|
Var OldMainBinaryName
|
||||||
@@ -333,6 +334,9 @@ Function PageLeaveReinstall
|
|||||||
${EndIf}
|
${EndIf}
|
||||||
|
|
||||||
reinst_uninstall:
|
reinst_uninstall:
|
||||||
|
${If} $R0 = 1
|
||||||
|
StrCpy $KeepAutoLaunch 1
|
||||||
|
${EndIf}
|
||||||
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||||
|
|
||||||
HideWindow
|
HideWindow
|
||||||
@@ -345,6 +349,7 @@ Function PageLeaveReinstall
|
|||||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||||
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
|
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
|
||||||
|
${IfThen} $KeepAutoLaunch = 1 ${|} StrCpy $R1 "$R1 /KEEPAUTOLAUNCH" ${|}
|
||||||
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
|
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
|
||||||
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
|
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
|
||||||
ExecWait '$R1' $0
|
ExecWait '$R1' $0
|
||||||
@@ -1098,6 +1103,11 @@ Function un.onInit
|
|||||||
${IfNot} ${Errors}
|
${IfNot} ${Errors}
|
||||||
StrCpy $UpdateMode 1
|
StrCpy $UpdateMode 1
|
||||||
${EndIf}
|
${EndIf}
|
||||||
|
|
||||||
|
${GetOptions} $CMDLINE "/KEEPAUTOLAUNCH" $KeepAutoLaunch
|
||||||
|
${IfNot} ${Errors}
|
||||||
|
StrCpy $KeepAutoLaunch 1
|
||||||
|
${EndIf}
|
||||||
FunctionEnd
|
FunctionEnd
|
||||||
|
|
||||||
Section Uninstall
|
Section Uninstall
|
||||||
@@ -1291,6 +1301,24 @@ Section Uninstall
|
|||||||
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
||||||
${EndIf}
|
${EndIf}
|
||||||
|
|
||||||
|
${If} $UpdateMode <> 1
|
||||||
|
${AndIf} $KeepAutoLaunch <> 1
|
||||||
|
; UAC can run the uninstaller under a different account from the desktop user.
|
||||||
|
StrCpy $R0 0
|
||||||
|
${Do}
|
||||||
|
EnumRegKey $R1 HKU "" $R0
|
||||||
|
${If} $R1 == ""
|
||||||
|
${ExitDo}
|
||||||
|
${EndIf}
|
||||||
|
StrCpy $R3 "$R1\Software\Microsoft\Windows\CurrentVersion\Run"
|
||||||
|
ReadRegStr $R2 HKU "$R3" "Clash Verge Auto Launch"
|
||||||
|
${If} $R2 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
|
||||||
|
DeleteRegValue HKU "$R3" "Clash Verge Auto Launch"
|
||||||
|
${EndIf}
|
||||||
|
IntOp $R0 $R0 + 1
|
||||||
|
${Loop}
|
||||||
|
${EndIf}
|
||||||
|
|
||||||
; Delete app data if the checkbox is selected
|
; Delete app data if the checkbox is selected
|
||||||
; and if not updating
|
; and if not updating
|
||||||
${If} $DeleteAppDataCheckboxState = 1
|
${If} $DeleteAppDataCheckboxState = 1
|
||||||
|
|||||||
@@ -1,29 +1,25 @@
|
|||||||
#[cfg(target_os = "windows")]
|
|
||||||
use crate::utils::schtasks;
|
|
||||||
use crate::{config::Config, core::handle::Handle};
|
use crate::{config::Config, core::handle::Handle};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
use clash_verge_logging::logging_error;
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
use tauri_plugin_autostart::ManagerExt as _;
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
|
||||||
|
|
||||||
pub async fn update_launch() -> Result<()> {
|
pub async fn update_launch() -> Result<()> {
|
||||||
let enable_auto_launch = { Config::verge().await.latest_arc().enable_auto_launch };
|
let enable_auto_launch = { Config::verge().await.latest_arc().enable_auto_launch };
|
||||||
let is_enable = enable_auto_launch.unwrap_or(false);
|
let is_enable = enable_auto_launch.unwrap_or(false);
|
||||||
logging!(info, Type::System, "Setting auto-launch enabled state to: {is_enable}");
|
logging!(info, Type::System, "Setting auto-launch enabled state to: {is_enable}");
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
let app_handle = Handle::app_handle();
|
||||||
{
|
cfg_select! {
|
||||||
let is_admin = is_current_app_handle_admin(Handle::app_handle());
|
target_os = "windows" => {
|
||||||
|
use crate::utils::schtasks;
|
||||||
|
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||||
|
|
||||||
|
let is_admin = is_current_app_handle_admin(app_handle);
|
||||||
schtasks::set_auto_launch(is_enable, is_admin).await?;
|
schtasks::set_auto_launch(is_enable, is_admin).await?;
|
||||||
}
|
}
|
||||||
|
_ => {
|
||||||
|
use clash_verge_logging::logging_error;
|
||||||
|
use tauri_plugin_autostart::ManagerExt as _;
|
||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
{
|
|
||||||
let app_handle = Handle::app_handle();
|
|
||||||
let autostart_manager = app_handle.autolaunch();
|
let autostart_manager = app_handle.autolaunch();
|
||||||
if is_enable {
|
if is_enable {
|
||||||
logging_error!(Type::System, "{:?}", autostart_manager.enable());
|
logging_error!(Type::System, "{:?}", autostart_manager.enable());
|
||||||
@@ -31,6 +27,7 @@ pub async fn update_launch() -> Result<()> {
|
|||||||
logging_error!(Type::System, "{:?}", autostart_manager.disable());
|
logging_error!(Type::System, "{:?}", autostart_manager.disable());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,10 +48,13 @@ fn windows_owner_credentials(app_data_root: &Path) -> Result<(OwnerIdentity, Opt
|
|||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
fn windows_current_identity() -> Result<OwnerIdentity> {
|
fn windows_current_identity() -> Result<OwnerIdentity> {
|
||||||
Ok(OwnerIdentity::Windows {
|
Ok(OwnerIdentity::Windows {
|
||||||
sid: windows_owner::current_sid()?,
|
sid: current_user_sid()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub(crate) use windows_owner::{account_sid, current_sid as current_user_sid};
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub(crate) fn create_private_current_user_file(path: &Path) -> Result<std::fs::File> {
|
pub(crate) fn create_private_current_user_file(path: &Path) -> Result<std::fs::File> {
|
||||||
windows_owner::create_private_file(path)
|
windows_owner::create_private_file(path)
|
||||||
@@ -93,8 +96,8 @@ mod windows_owner {
|
|||||||
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _};
|
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use windows_sys::Win32::Foundation::{
|
use windows_sys::Win32::Foundation::{
|
||||||
CloseHandle, ERROR_ACCESS_DENIED, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, GENERIC_READ,
|
CloseHandle, ERROR_ACCESS_DENIED, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_INSUFFICIENT_BUFFER,
|
||||||
GENERIC_WRITE, GetLastError, INVALID_HANDLE_VALUE, LocalFree,
|
ERROR_PATH_NOT_FOUND, GENERIC_READ, GENERIC_WRITE, GetLastError, INVALID_HANDLE_VALUE, LocalFree,
|
||||||
};
|
};
|
||||||
use windows_sys::Win32::Security::Authorization::{
|
use windows_sys::Win32::Security::Authorization::{
|
||||||
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
|
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
|
||||||
@@ -103,8 +106,9 @@ mod windows_owner {
|
|||||||
use windows_sys::Win32::Security::{
|
use windows_sys::Win32::Security::{
|
||||||
ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetSecurityDescriptorControl,
|
ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetSecurityDescriptorControl,
|
||||||
GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, GetTokenInformation, IsValidSid, IsWellKnownSid,
|
GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, GetTokenInformation, IsValidSid, IsWellKnownSid,
|
||||||
OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SE_DACL_PROTECTED,
|
LookupAccountNameW, OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
|
||||||
SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid, WinLocalSystemSid,
|
PSID, SE_DACL_PROTECTED, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid,
|
||||||
|
WinLocalSystemSid,
|
||||||
};
|
};
|
||||||
use windows_sys::Win32::Storage::FileSystem::{
|
use windows_sys::Win32::Storage::FileSystem::{
|
||||||
BY_HANDLE_FILE_INFORMATION, CREATE_NEW, CreateFileW, FILE_ALL_ACCESS, FILE_ATTRIBUTE_DIRECTORY,
|
BY_HANDLE_FILE_INFORMATION, CREATE_NEW, CreateFileW, FILE_ALL_ACCESS, FILE_ATTRIBUTE_DIRECTORY,
|
||||||
@@ -123,7 +127,7 @@ mod windows_owner {
|
|||||||
crate::utils::server::INSTANCE_LOCK_FILE,
|
crate::utils::server::INSTANCE_LOCK_FILE,
|
||||||
];
|
];
|
||||||
|
|
||||||
pub(super) fn current_sid() -> Result<String> {
|
pub(crate) fn current_sid() -> Result<String> {
|
||||||
let mut token = std::ptr::null_mut();
|
let mut token = std::ptr::null_mut();
|
||||||
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
||||||
return Err(std::io::Error::last_os_error()).context("failed to open process token");
|
return Err(std::io::Error::last_os_error()).context("failed to open process token");
|
||||||
@@ -145,6 +149,44 @@ mod windows_owner {
|
|||||||
sid_to_string(token_user.User.Sid)
|
sid_to_string(token_user.User.Sid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn account_sid(account: &str) -> Result<String> {
|
||||||
|
let wide_account: Vec<_> = account.encode_utf16().chain([0]).collect();
|
||||||
|
let mut sid_size = 0;
|
||||||
|
let mut domain_len = 0;
|
||||||
|
let mut account_type = 0;
|
||||||
|
unsafe {
|
||||||
|
LookupAccountNameW(
|
||||||
|
std::ptr::null(),
|
||||||
|
wide_account.as_ptr(),
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
&mut sid_size,
|
||||||
|
std::ptr::null_mut(),
|
||||||
|
&mut domain_len,
|
||||||
|
&mut account_type,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER {
|
||||||
|
return Err(std::io::Error::last_os_error()).context("failed to size account SID buffer");
|
||||||
|
}
|
||||||
|
let mut sid = vec![0_usize; (sid_size as usize).div_ceil(std::mem::size_of::<usize>())];
|
||||||
|
let mut domain = vec![0_u16; domain_len as usize];
|
||||||
|
if unsafe {
|
||||||
|
LookupAccountNameW(
|
||||||
|
std::ptr::null(),
|
||||||
|
wide_account.as_ptr(),
|
||||||
|
sid.as_mut_ptr().cast(),
|
||||||
|
&mut sid_size,
|
||||||
|
domain.as_mut_ptr(),
|
||||||
|
&mut domain_len,
|
||||||
|
&mut account_type,
|
||||||
|
)
|
||||||
|
} == 0
|
||||||
|
{
|
||||||
|
return Err(std::io::Error::last_os_error()).context("failed to look up account SID");
|
||||||
|
}
|
||||||
|
sid_to_string(sid.as_mut_ptr().cast())
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn load_or_create_token(app_data_root: &Path, sid: &str) -> Result<String> {
|
pub(super) fn load_or_create_token(app_data_root: &Path, sid: &str) -> Result<String> {
|
||||||
let token_path = app_data_root.join(OWNER_TOKEN_FILE_NAME);
|
let token_path = app_data_root.join(OWNER_TOKEN_FILE_NAME);
|
||||||
let descriptor = LocalSecurityDescriptor::from_sid(sid)?;
|
let descriptor = LocalSecurityDescriptor::from_sid(sid)?;
|
||||||
@@ -640,12 +682,12 @@ mod windows_owner {
|
|||||||
fn sid_to_string(sid: PSID) -> Result<String> {
|
fn sid_to_string(sid: PSID) -> Result<String> {
|
||||||
let mut value = std::ptr::null_mut();
|
let mut value = std::ptr::null_mut();
|
||||||
if unsafe { ConvertSidToStringSidW(sid, &mut value) } == 0 || value.is_null() {
|
if unsafe { ConvertSidToStringSidW(sid, &mut value) } == 0 || value.is_null() {
|
||||||
return Err(std::io::Error::last_os_error()).context("failed to format process SID");
|
return Err(std::io::Error::last_os_error()).context("failed to format Windows SID");
|
||||||
}
|
}
|
||||||
let value = LocalWideString(value);
|
let value = LocalWideString(value);
|
||||||
let length = (0..).take_while(|index| unsafe { *value.0.add(*index) } != 0).count();
|
let length = (0..).take_while(|index| unsafe { *value.0.add(*index) } != 0).count();
|
||||||
String::from_utf16(unsafe { std::slice::from_raw_parts(value.0, length) })
|
String::from_utf16(unsafe { std::slice::from_raw_parts(value.0, length) })
|
||||||
.context("process SID is not valid UTF-16")
|
.context("Windows SID is not valid UTF-16")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_token(token: &[u8; TOKEN_BYTES]) -> String {
|
fn encode_token(token: &[u8; TOKEN_BYTES]) -> String {
|
||||||
|
|||||||
+266
-261
@@ -1,21 +1,38 @@
|
|||||||
use crate::utils::dirs::{self, PathBufExec as _};
|
use crate::{
|
||||||
use anyhow::{Context as _, Result, anyhow};
|
core::owner_identity::{account_sid, current_user_sid},
|
||||||
|
utils::dirs::PathBufExec as _,
|
||||||
|
};
|
||||||
|
use anyhow::{Context as _, Result, anyhow, bail, ensure};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use std::fs;
|
use quick_xml::escape::escape;
|
||||||
use std::os::windows::process::CommandExt as _;
|
use std::ffi::OsString;
|
||||||
|
use std::io::ErrorKind;
|
||||||
|
use std::os::windows::ffi::OsStrExt as _;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::{Command, Output};
|
use windows::{
|
||||||
use windows::Win32::Globalization::{GetACP, GetOEMCP, MULTI_BYTE_TO_WIDE_CHAR_FLAGS, MultiByteToWideChar};
|
Win32::{
|
||||||
|
Foundation::{E_ACCESSDENIED, ERROR_FILE_NOT_FOUND},
|
||||||
|
System::{
|
||||||
|
Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize},
|
||||||
|
TaskScheduler::{
|
||||||
|
ITaskFolder, ITaskService, TASK_CREATE, TASK_CREATION, TASK_LOGON_INTERACTIVE_TOKEN, TASK_UPDATE,
|
||||||
|
TaskScheduler,
|
||||||
|
},
|
||||||
|
Variant::VARIANT,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
core::{BSTR, Error as WindowsError},
|
||||||
|
};
|
||||||
|
use winreg::{
|
||||||
|
RegKey,
|
||||||
|
enums::{HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE},
|
||||||
|
};
|
||||||
|
|
||||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||||
const TASK_NAME_USER: &str = "Clash Verge";
|
const RUN_VALUE: &str = "Clash Verge Auto Launch";
|
||||||
const TASK_NAME_ADMIN: &str = "Clash Verge (Admin)";
|
|
||||||
const TASK_XML_DIR: &str = "tasks";
|
|
||||||
const TASK_XML_USER: &str = "clash-verge-task-user.xml";
|
|
||||||
const TASK_XML_ADMIN: &str = "clash-verge-task-admin.xml";
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum TaskMode {
|
enum TaskMode {
|
||||||
User,
|
User,
|
||||||
Admin,
|
Admin,
|
||||||
}
|
}
|
||||||
@@ -23,15 +40,8 @@ pub enum TaskMode {
|
|||||||
impl TaskMode {
|
impl TaskMode {
|
||||||
const fn name(self) -> &'static str {
|
const fn name(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Self::User => TASK_NAME_USER,
|
Self::User => "Clash Verge",
|
||||||
Self::Admin => TASK_NAME_ADMIN,
|
Self::Admin => "Clash Verge (Admin)",
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fn label(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::User => "user",
|
|
||||||
Self::Admin => "admin",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,42 +51,6 @@ impl TaskMode {
|
|||||||
Self::Admin => "HighestAvailable",
|
Self::Admin => "HighestAvailable",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const fn xml_file_name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::User => TASK_XML_USER,
|
|
||||||
Self::Admin => TASK_XML_ADMIN,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_exe_path() -> Result<PathBuf> {
|
|
||||||
let exe_path = std::env::current_exe().map_err(|e| anyhow!("failed to get exe path: {}", e))?;
|
|
||||||
Ok(exe_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_task_user_id() -> Result<String> {
|
|
||||||
let username = std::env::var_os("USERNAME")
|
|
||||||
.or_else(|| std::env::var_os("USER"))
|
|
||||||
.ok_or_else(|| anyhow!("failed to get current user name"))?;
|
|
||||||
let username = username.to_string_lossy();
|
|
||||||
let username = username.trim();
|
|
||||||
if username.is_empty() {
|
|
||||||
return Err(anyhow!("current user name is empty"));
|
|
||||||
}
|
|
||||||
|
|
||||||
let domain = std::env::var_os("USERDOMAIN")
|
|
||||||
.or_else(|| std::env::var_os("COMPUTERNAME"))
|
|
||||||
.map(|value| value.to_string_lossy().to_string());
|
|
||||||
|
|
||||||
if let Some(domain) = domain {
|
|
||||||
let domain = domain.trim();
|
|
||||||
if !domain.is_empty() {
|
|
||||||
return Ok(format!("{domain}\\{username}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(username.to_string())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_startup_dir() -> Result<PathBuf> {
|
fn get_startup_dir() -> Result<PathBuf> {
|
||||||
@@ -111,45 +85,23 @@ async fn cleanup_legacy_shortcuts() -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn task_xml_path(mode: TaskMode) -> Result<PathBuf> {
|
fn build_task_xml(mode: TaskMode, user_sid: &str, exe: &Path) -> String {
|
||||||
let dir = dirs::app_home_dir()?.join(TASK_XML_DIR);
|
let exe_path = escape(exe.to_string_lossy());
|
||||||
fs::create_dir_all(&dir).map_err(|e| anyhow!("failed to create task xml dir: {}", e))?;
|
let run_level = mode.xml_run_level();
|
||||||
Ok(dir.join(mode.xml_file_name()))
|
format!(
|
||||||
}
|
|
||||||
|
|
||||||
fn xml_escape(value: &str) -> String {
|
|
||||||
let mut escaped = String::with_capacity(value.len());
|
|
||||||
for ch in value.chars() {
|
|
||||||
match ch {
|
|
||||||
'&' => escaped.push_str("&"),
|
|
||||||
'<' => escaped.push_str("<"),
|
|
||||||
'>' => escaped.push_str(">"),
|
|
||||||
'"' => escaped.push_str("""),
|
|
||||||
'\'' => escaped.push_str("'"),
|
|
||||||
_ => escaped.push(ch),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
escaped
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_task_xml(mode: TaskMode) -> Result<String> {
|
|
||||||
let exe_path = get_exe_path()?.to_string_lossy().to_string();
|
|
||||||
let exe_path = xml_escape(&exe_path);
|
|
||||||
let user_id = xml_escape(&get_task_user_id()?);
|
|
||||||
Ok(format!(
|
|
||||||
r#"<?xml version="1.0" encoding="UTF-16"?>
|
r#"<?xml version="1.0" encoding="UTF-16"?>
|
||||||
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||||
<Triggers>
|
<Triggers>
|
||||||
<LogonTrigger>
|
<LogonTrigger>
|
||||||
<Enabled>true</Enabled>
|
<Enabled>true</Enabled>
|
||||||
<UserId>{}</UserId>
|
<UserId>{user_sid}</UserId>
|
||||||
</LogonTrigger>
|
</LogonTrigger>
|
||||||
</Triggers>
|
</Triggers>
|
||||||
<Principals>
|
<Principals>
|
||||||
<Principal id="Author">
|
<Principal id="Author">
|
||||||
<UserId>{}</UserId>
|
<UserId>{user_sid}</UserId>
|
||||||
<LogonType>InteractiveToken</LogonType>
|
<LogonType>InteractiveToken</LogonType>
|
||||||
<RunLevel>{}</RunLevel>
|
<RunLevel>{run_level}</RunLevel>
|
||||||
</Principal>
|
</Principal>
|
||||||
</Principals>
|
</Principals>
|
||||||
<Settings>
|
<Settings>
|
||||||
@@ -173,209 +125,262 @@ fn build_task_xml(mode: TaskMode) -> Result<String> {
|
|||||||
</Settings>
|
</Settings>
|
||||||
<Actions Context="Author">
|
<Actions Context="Author">
|
||||||
<Exec>
|
<Exec>
|
||||||
<Command>{}</Command>
|
<Command>{exe_path}</Command>
|
||||||
</Exec>
|
</Exec>
|
||||||
</Actions>
|
</Actions>
|
||||||
</Task>
|
</Task>
|
||||||
"#,
|
"#
|
||||||
user_id,
|
)
|
||||||
user_id,
|
|
||||||
mode.xml_run_level(),
|
|
||||||
exe_path
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_utf16le_with_bom(content: &str) -> Vec<u8> {
|
struct ComApartment;
|
||||||
let mut bytes = Vec::with_capacity(2 + content.len() * 2);
|
|
||||||
bytes.extend_from_slice(&[0xFF, 0xFE]);
|
|
||||||
for unit in content.encode_utf16() {
|
|
||||||
bytes.extend_from_slice(&unit.to_le_bytes());
|
|
||||||
}
|
|
||||||
bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_task_xml(mode: TaskMode) -> Result<PathBuf> {
|
impl ComApartment {
|
||||||
let task_xml = build_task_xml(mode)?;
|
fn initialize() -> Result<Self> {
|
||||||
let task_xml_path = task_xml_path(mode)?;
|
unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }.context("failed to initialize COM")?;
|
||||||
let encoded = encode_utf16le_with_bom(&task_xml);
|
Ok(Self)
|
||||||
fs::write(&task_xml_path, encoded).map_err(|e| anyhow!("failed to write task xml: {}", e))?;
|
|
||||||
Ok(task_xml_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decode_with_code_page(bytes: &[u8], code_page: u32) -> Option<String> {
|
|
||||||
if bytes.is_empty() {
|
|
||||||
return Some(String::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
let len = bytes.len();
|
|
||||||
if len > i32::MAX as usize {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let required = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, None) };
|
|
||||||
|
|
||||||
if required <= 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut wide = vec![0u16; required as usize];
|
|
||||||
let written = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, Some(&mut wide)) };
|
|
||||||
|
|
||||||
if written <= 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
wide.truncate(written as usize);
|
|
||||||
Some(String::from_utf16_lossy(&wide))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decode_console_output(bytes: &[u8]) -> String {
|
|
||||||
if let Ok(text) = std::str::from_utf8(bytes) {
|
|
||||||
return text.to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
let oem = unsafe { GetOEMCP() };
|
|
||||||
if let Some(text) = decode_with_code_page(bytes, oem) {
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
let acp = unsafe { GetACP() };
|
|
||||||
if let Some(text) = decode_with_code_page(bytes, acp) {
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
String::from_utf8_lossy(bytes).to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn output_message(output: &Output) -> String {
|
|
||||||
let stdout = decode_console_output(&output.stdout);
|
|
||||||
let stderr = decode_console_output(&output.stderr);
|
|
||||||
let stdout = stdout.trim();
|
|
||||||
let stderr = stderr.trim();
|
|
||||||
|
|
||||||
match (stdout.is_empty(), stderr.is_empty()) {
|
|
||||||
(true, true) => "unknown error".to_string(),
|
|
||||||
(false, true) => stdout.to_string(),
|
|
||||||
(true, false) => stderr.to_string(),
|
|
||||||
(false, false) => format!("{stdout} | {stderr}"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn schtasks_output(mut cmd: Command) -> Result<Output> {
|
impl Drop for ComApartment {
|
||||||
cmd.creation_flags(CREATE_NO_WINDOW)
|
fn drop(&mut self) {
|
||||||
.output()
|
unsafe { CoUninitialize() };
|
||||||
.map_err(|e| anyhow!("failed to execute schtasks: {}", e))
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_task_enabled(mode: TaskMode) -> Result<bool> {
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
let output = schtasks_output({
|
enum TaskOwner {
|
||||||
let mut cmd = Command::new("schtasks");
|
Missing,
|
||||||
cmd.args(["/Query", "/TN", mode.name()]);
|
CurrentUser,
|
||||||
cmd
|
OtherUser,
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(output.status.success())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_task(mode: TaskMode) -> Result<()> {
|
struct ScheduledTasks {
|
||||||
let task_xml_path = write_task_xml(mode)?;
|
folder: ITaskFolder,
|
||||||
let output = schtasks_output({
|
user_sid: String,
|
||||||
let mut cmd = Command::new("schtasks");
|
// Drop the COM interface before uninitializing the apartment.
|
||||||
cmd.args(["/Create", "/TN", mode.name(), "/XML"]);
|
_com: ComApartment,
|
||||||
cmd.arg(&task_xml_path);
|
}
|
||||||
cmd.arg("/F");
|
|
||||||
cmd
|
|
||||||
})?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
impl ScheduledTasks {
|
||||||
return Err(anyhow!(
|
fn connect() -> Result<Self> {
|
||||||
"failed to create {} task: {}",
|
let com = ComApartment::initialize()?;
|
||||||
mode.label(),
|
let service: ITaskService = unsafe { CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER) }
|
||||||
output_message(&output)
|
.context("failed to open Task Scheduler")?;
|
||||||
));
|
let empty = VARIANT::default();
|
||||||
|
unsafe { service.Connect(&empty, &empty, &empty, &empty) }.context("failed to connect to Task Scheduler")?;
|
||||||
|
let folder =
|
||||||
|
unsafe { service.GetFolder(&BSTR::from(r"\")) }.context("failed to open the Task Scheduler root folder")?;
|
||||||
|
Ok(Self {
|
||||||
|
folder,
|
||||||
|
user_sid: current_user_sid()?,
|
||||||
|
_com: com,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
logging!(info, Type::Setup, "Created {} auto-launch task", mode.label());
|
fn owner(&self, mode: TaskMode) -> Result<TaskOwner> {
|
||||||
|
let task = match unsafe { self.folder.GetTask(&BSTR::from(mode.name())) } {
|
||||||
|
Ok(task) => task,
|
||||||
|
Err(error) if task_missing(&error) => return Ok(TaskOwner::Missing),
|
||||||
|
Err(error) => return Err(error).with_context(|| format!("failed to find the {} task", mode.name())),
|
||||||
|
};
|
||||||
|
let principal_sid = (|| {
|
||||||
|
let principal = unsafe { task.Definition()?.Principal()? };
|
||||||
|
let mut user = BSTR::new();
|
||||||
|
unsafe { principal.UserId(&mut user)? };
|
||||||
|
let user = String::try_from(&user)?;
|
||||||
|
if user.starts_with("S-1-") {
|
||||||
|
return Ok(user);
|
||||||
|
}
|
||||||
|
account_sid(&user)
|
||||||
|
})()
|
||||||
|
.with_context(|| format!("failed to identify the owner of the {} task", mode.name()))?;
|
||||||
|
|
||||||
|
Ok(if principal_sid == self.user_sid {
|
||||||
|
TaskOwner::CurrentUser
|
||||||
|
} else {
|
||||||
|
TaskOwner::OtherUser
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_current_user_task(&self) -> Result<bool> {
|
||||||
|
let user_task = self.owner(TaskMode::User)?;
|
||||||
|
let admin_task = self.owner(TaskMode::Admin)?;
|
||||||
|
Ok(user_task == TaskOwner::CurrentUser || admin_task == TaskOwner::CurrentUser)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn register(&self, mode: TaskMode, exe: &Path, flags: TASK_CREATION) -> windows::core::Result<()> {
|
||||||
|
let xml = BSTR::from(build_task_xml(mode, &self.user_sid, exe));
|
||||||
|
let empty = VARIANT::default();
|
||||||
|
unsafe {
|
||||||
|
self.folder.RegisterTask(
|
||||||
|
&BSTR::from(mode.name()),
|
||||||
|
&xml,
|
||||||
|
flags.0,
|
||||||
|
&empty,
|
||||||
|
&empty,
|
||||||
|
TASK_LOGON_INTERACTIVE_TOKEN,
|
||||||
|
&empty,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.map(drop)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&self, mode: TaskMode) -> Result<()> {
|
||||||
|
match unsafe { self.folder.DeleteTask(&BSTR::from(mode.name()), 0) } {
|
||||||
|
Ok(()) => {
|
||||||
|
logging!(info, Type::Setup, "Removed the {} auto-launch task", mode.name());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(error) if task_missing(&error) => Ok(()),
|
||||||
|
Err(error) => Err(error).with_context(|| format!("failed to remove the {} task", mode.name())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn task_missing(error: &WindowsError) -> bool {
|
||||||
|
error.code() == ERROR_FILE_NOT_FOUND.to_hresult()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_startup_entry(exe: &Path) -> Result<()> {
|
||||||
|
let mut command = OsString::from("\"");
|
||||||
|
command.push(exe);
|
||||||
|
command.push("\"");
|
||||||
|
ensure!(
|
||||||
|
command.encode_wide().count() <= 260,
|
||||||
|
"the startup command exceeds the Windows Run entry limit"
|
||||||
|
);
|
||||||
|
|
||||||
|
let (key, _) = RegKey::predef(HKEY_CURRENT_USER)
|
||||||
|
.create_subkey_with_flags(RUN_KEY, KEY_SET_VALUE)
|
||||||
|
.context("failed to open the current user's Run key for writing")?;
|
||||||
|
key.set_value(RUN_VALUE, &command)
|
||||||
|
.context("failed to write the per-user startup entry")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn startup_entry_for_removal() -> Result<Option<RegKey>> {
|
||||||
|
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||||
|
let entry = hkcu
|
||||||
|
.open_subkey_with_flags(RUN_KEY, KEY_QUERY_VALUE)
|
||||||
|
.and_then(|key| key.get_raw_value(RUN_VALUE));
|
||||||
|
match entry {
|
||||||
|
Ok(_) => hkcu
|
||||||
|
.open_subkey_with_flags(RUN_KEY, KEY_SET_VALUE)
|
||||||
|
.map(Some)
|
||||||
|
.context("failed to open the current user's Run key for cleanup"),
|
||||||
|
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
|
||||||
|
Err(error) => Err(error).context("failed to inspect the per-user startup entry"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_startup_entry(key: Option<RegKey>) -> Result<()> {
|
||||||
|
if let Some(key) = key {
|
||||||
|
match key.delete_value(RUN_VALUE) {
|
||||||
|
Ok(()) => (),
|
||||||
|
Err(error) if error.kind() == ErrorKind::NotFound => (),
|
||||||
|
Err(error) => return Err(error).context("failed to remove the per-user startup entry"),
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_task(mode: TaskMode) -> Result<()> {
|
fn enable_auto_launch(
|
||||||
let output = schtasks_output({
|
tasks: &ScheduledTasks,
|
||||||
let mut cmd = Command::new("schtasks");
|
mode: TaskMode,
|
||||||
cmd.args(["/Delete", "/TN", mode.name(), "/F"]);
|
user_task: TaskOwner,
|
||||||
cmd
|
admin_task: TaskOwner,
|
||||||
})?;
|
) -> Result<()> {
|
||||||
|
let target = match mode {
|
||||||
|
TaskMode::User => user_task,
|
||||||
|
TaskMode::Admin => admin_task,
|
||||||
|
};
|
||||||
|
|
||||||
if output.status.success() {
|
ensure!(
|
||||||
logging!(info, Type::Setup, "Removed {} auto-launch task", mode.label());
|
target != TaskOwner::OtherUser,
|
||||||
return Ok(());
|
"the {} auto-launch task belongs to another Windows account",
|
||||||
}
|
mode.name()
|
||||||
|
);
|
||||||
if !is_task_enabled(mode)? {
|
let exe = std::env::current_exe().context("failed to get the app executable path")?;
|
||||||
|
let exe = dunce::simplified(&exe);
|
||||||
|
let fallback = startup_entry_for_removal()?;
|
||||||
|
let is_new_task = target == TaskOwner::Missing;
|
||||||
|
let flags = if is_new_task { TASK_CREATE } else { TASK_UPDATE };
|
||||||
|
if let Err(error) = tasks.register(mode, exe, flags) {
|
||||||
|
let can_fallback = mode == TaskMode::User && is_new_task && error.code() == E_ACCESSDENIED;
|
||||||
|
// A task could have appeared after the first lookup and may already launch the app.
|
||||||
|
if can_fallback && !tasks.has_current_user_task()? {
|
||||||
|
write_startup_entry(exe).with_context(|| format!("Task Scheduler denied registration ({error})"))?;
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
Type::Setup,
|
Type::Setup,
|
||||||
"{} auto-launch task not found, skipping removal",
|
"Using the per-user startup entry after Task Scheduler denied registration"
|
||||||
mode.label()
|
|
||||||
);
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
return Err(error).with_context(|| format!("failed to register the {} task", mode.name()));
|
||||||
Err(anyhow!(
|
|
||||||
"failed to remove {} task: {}",
|
|
||||||
mode.label(),
|
|
||||||
output_message(&output)
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_auto_launch(is_enable: bool, is_admin: bool) -> Result<()> {
|
|
||||||
let target = if is_admin { TaskMode::Admin } else { TaskMode::User };
|
|
||||||
let other = if is_admin { TaskMode::User } else { TaskMode::Admin };
|
|
||||||
|
|
||||||
if let Err(err) = cleanup_legacy_shortcuts().await {
|
|
||||||
logging!(warn, Type::Setup, "Failed to cleanup legacy startup shortcuts: {err:#}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if is_enable {
|
let cleanup = (|| {
|
||||||
if is_admin {
|
if mode == TaskMode::Admin && user_task == TaskOwner::CurrentUser {
|
||||||
create_task(target)?;
|
tasks.remove(TaskMode::User)?;
|
||||||
if let Err(err) = remove_task(other) {
|
|
||||||
let _ = remove_task(target);
|
|
||||||
return Err(err);
|
|
||||||
}
|
}
|
||||||
} else {
|
remove_startup_entry(fallback)
|
||||||
if is_task_enabled(other)? {
|
})();
|
||||||
return Err(anyhow!(
|
if let Err(error) = cleanup {
|
||||||
"admin auto-launch task exists; run the app as administrator to remove it before creating a user task"
|
if is_new_task && let Err(rollback) = tasks.remove(mode) {
|
||||||
));
|
return Err(error.context(format!(
|
||||||
|
"failed to roll back the new {} task: {rollback:#}",
|
||||||
|
mode.name()
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
create_task(target)?;
|
return Err(error);
|
||||||
|
}
|
||||||
|
logging!(info, Type::Setup, "Registered the {} auto-launch task", mode.name());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_auto_launch(enabled: bool, mode: TaskMode) -> Result<()> {
|
||||||
|
let tasks = ScheduledTasks::connect()?;
|
||||||
|
let admin_task = tasks.owner(TaskMode::Admin)?;
|
||||||
|
if mode == TaskMode::User && admin_task == TaskOwner::CurrentUser {
|
||||||
|
bail!("run Clash Verge as administrator to manage its existing elevated auto-launch task");
|
||||||
|
}
|
||||||
|
let user_task = tasks.owner(TaskMode::User)?;
|
||||||
|
if enabled {
|
||||||
|
return enable_auto_launch(&tasks, mode, user_task, admin_task);
|
||||||
|
}
|
||||||
|
|
||||||
|
let fallback = startup_entry_for_removal()?;
|
||||||
|
if admin_task == TaskOwner::CurrentUser {
|
||||||
|
tasks.remove(TaskMode::Admin)?;
|
||||||
|
}
|
||||||
|
if user_task == TaskOwner::CurrentUser {
|
||||||
|
tasks.remove(TaskMode::User)?;
|
||||||
|
}
|
||||||
|
remove_startup_entry(fallback)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_auto_launch(enabled: bool, is_admin: bool) -> Result<()> {
|
||||||
|
let mode = if is_admin { TaskMode::Admin } else { TaskMode::User };
|
||||||
|
let result = tokio::task::spawn_blocking(move || configure_auto_launch(enabled, mode)).await?;
|
||||||
|
result.map_err(|error| {
|
||||||
|
if mode == TaskMode::User
|
||||||
|
&& error
|
||||||
|
.downcast_ref::<WindowsError>()
|
||||||
|
.is_some_and(|error| error.code() == E_ACCESSDENIED)
|
||||||
|
{
|
||||||
|
error.context("run Clash Verge as administrator to manage its scheduled auto-launch tasks")
|
||||||
|
} else {
|
||||||
|
error
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if let Err(error) = cleanup_legacy_shortcuts().await {
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Setup,
|
||||||
|
"Failed to clean up legacy startup shortcuts: {error:#}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if is_admin {
|
|
||||||
let mut errors = Vec::new();
|
|
||||||
if let Err(err) = remove_task(TaskMode::User) {
|
|
||||||
errors.push(err);
|
|
||||||
}
|
|
||||||
if let Err(err) = remove_task(TaskMode::Admin) {
|
|
||||||
errors.push(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(err) = errors.into_iter().next() {
|
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
remove_task(TaskMode::User)?;
|
|
||||||
if is_task_enabled(TaskMode::Admin)? {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"admin auto-launch task exists; run the app as administrator to remove it"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export const SystemInfoCard = () => {
|
|||||||
try {
|
try {
|
||||||
await patchVerge({ enable_auto_launch: !verge.enable_auto_launch })
|
await patchVerge({ enable_auto_launch: !verge.enable_auto_launch })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('切换开机自启动状态失败:', err)
|
showNotice.error(err)
|
||||||
}
|
}
|
||||||
}, [verge, patchVerge])
|
}, [verge, patchVerge])
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user