2 Commits

Author SHA1 Message Date
e52ba67d7e feat(env): 支持环境变量数组跨平台自动拼接
- 支持在 Lua 中配置数组格式的环境变量(如 PATH),由 Rust 按 OS 自动使用 `;` 或 `:` 拼接
- 保持普通字符串格式环境变量的直接覆盖逻辑
- 新增 `ShimConfig::to_command()` 用于快速创建 Command 对象
- 新增 error.rs 明确错误类型
- 新增 build.rs 优化编译
2026-08-13 20:11:55 +08:00
4aa619f07e refactor: 配置文件引擎迁移至 mlua 并优化环境变量注入
- 配置文件解析引擎由 shim 替换为 mlua (Lua 5.4)
- 优化路由策略:统一以根目录 shims.lua 为入口,支持 tools/ 目录模块化降级探测
- 自动注入 __SHIM_DIR__ 绝对路径与 package.path 模块搜索路径
- 环境变量改用 Command::envs 安全注入,并在 UAC 提权时透传
2026-08-12 20:19:50 +08:00
8 changed files with 747 additions and 106 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/target
/.vscode
*.exe
./Cargo.lock

297
Cargo.lock generated
View File

@@ -1,25 +1,306 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
[[package]]
name = "bstr"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
dependencies = [
"memchr",
"serde_core",
]
[[package]]
name = "cc"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "either"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
[[package]]
name = "find-msvc-tools"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de"
[[package]]
name = "fs-err"
version = "2.5.0"
version = "3.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcd1163ae48bda72a20ae26d66a04d3094135cadab911cff418ae5e33f253431"
checksum = "b91aa448ca50d7e79433bdf3ee8d99215430d2ec02ade5aefab2a073a1822e8a"
dependencies = [
"autocfg",
]
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "lua-src"
version = "550.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75c110c2fa33f34e0de05448e1f3eb2e0631e7a69e2d8ae1586cffc9fc9f9949"
dependencies = [
"cc",
]
[[package]]
name = "luajit-src"
version = "210.7.2+b925b3e"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "920cf654b23d217c550ceea57c32cd2a413ea27b6d47ed77b5ee0cf655adefa6"
dependencies = [
"cc",
"which",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mlua"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad72ffa037cf5970c9860674f32f703fda25d86cf217475fe7a79c5f9961bcaa"
dependencies = [
"bstr",
"either",
"libc",
"mlua-sys",
"num-traits",
"parking_lot",
"rustc-hash",
]
[[package]]
name = "mlua-sys"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92136787b906d4e55cfe96cd6c62e010bb1a56889d0d6cf83eb016dbad07576b"
dependencies = [
"cc",
"cfg-if",
"libc",
"lua-src",
"luajit-src",
"pkg-config",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "pkg-config"
version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "rshim"
version = "0.1.0"
dependencies = [
"fs-err",
"mlua",
"thiserror",
"unicode-bom",
"winapi",
]
[[package]]
name = "unicode-bom"
version = "1.1.4"
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63ec69f541d875b783ca40184d655f2927c95f0bffd486faa83cd3ac3529ec32"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "smallvec"
version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-bom"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7eec5d1121208364f6793f7d2e222bf75a915c19557537745b195b253dd64217"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "which"
version = "8.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f3ef584124b911bcc3875c2f1472e80f24361ceb789bd1c62b3e9a3df9ff43c"
dependencies = [
"libc",
]
[[package]]
name = "winapi"
@@ -42,3 +323,9 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"

View File

@@ -2,7 +2,7 @@
name = "rshim"
version = "0.1.0"
authors = ["anonymous <anonymous@example.com>"]
edition = "2018"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -11,12 +11,11 @@ edition = "2018"
opt-level = "z"
panic = "abort"
[dependencies]
fs-err = "2.5.0"
unicode-bom = "1"
[dependencies.winapi]
version = "0.3"
features = [
fs-err = "3.3.1"
unicode-bom = "2.0.3"
thiserror={version = "2.0.20"}
mlua = { version = "0.12.0", features = ["lua54", "vendored"] }
winapi = { version = "0.3", features = [
"wincon",
"consoleapi",
"minwindef",
@@ -28,4 +27,6 @@ features = [
"processthreadsapi",
"objbase",
"impl-default"
]
] }

47
build.rs Normal file
View File

@@ -0,0 +1,47 @@
use std::env;
use std::fs;
use std::path::PathBuf;
fn main() {
// CARGO_MANIFEST_DIR -> 项目根目录路径
// CARGO_TARGET_DIR -> 用户自定义了 target 目录,使用该变量
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let target_dir = env::var("CARGO_TARGET_DIR")
.ok()
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(&manifest_dir).join("target"));
// PROFILE -> 获取当前构建配置文件debug/release
let profile = env::var("PROFILE").unwrap();
// let output_dir = target_dir.join(&profile);
// 在 target/debug/ 或 target/release/ 下创建 bin2 目录
let output_dir = target_dir.join(&profile).join("bin2");
// cargo:rerun-if-changed -> 当指定文件变化时,重新运行 xxx
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=shims.lua");
println!("cargo:rustc-env=OUTPUT_DIR={}", output_dir.display());
// 创建目录
let dirs = ["bin", "tools"];
for dir in &dirs {
let path = output_dir.join(dir);
if !path.exists() {
fs::create_dir_all(&path).expect(&format!("Failed to create {} directory", dir));
println!("Created: {:?}", path);
}
}
// 复制文件
let source = PathBuf::from(&manifest_dir).join("shims.lua");
let destination = output_dir.join("shims.lua");
if source.exists() {
fs::copy(&source, &destination).expect("Failed to copy shims.lua");
println!("Copied shims.lua to: {:?}", destination);
} else {
panic!("shims.lua not found at: {:?}", source);
}
}

59
shims.lua Normal file
View File

@@ -0,0 +1,59 @@
-- shims.lua (总控制台)
-- __SHIM_DIR__ 已经在 Rust 中注入完毕,并且是正斜杠格式 (例如 C:/Tools)
local base_dir = __SHIM_DIR__
-- 1. 自定义局部变量,方便复用与后续维护
local python_home = base_dir .. "/tools/python39"
return {
---------------------------------------------------
-- 1. 标准相对路径 + 正斜杠拼接 (最推荐,绿色便携)
---------------------------------------------------
["git"] = {
path = base_dir .. "/git/bin/git.exe",
-- 追加参数
args = { "--no-pager" },
-- 注入环境变量,使用 get_env 获取宿主机当前值
env = {
PATH = { base_dir .. "/git/bin", get_env("PATH") }
}
},
---------------------------------------------------
-- 2. Lua 原生字符串语法 [[ ]] (适合直接从 Windows 复制绝对路径)
---------------------------------------------------
["python"] = {
-- 在 [[]] 内部,\ 不需要写成 \\,直接粘贴即可
path = [[C:\Python310\python.exe]],
args = { "-B" },
-- 空字典也是合法的,等同于不设置
env = {
-- 普通字符串Rust 直接新建/覆盖该环境变量
PYTHON_HOME = python_home,
HOME = base_dir .. "/home",
-- 数组列表:将 python_home 以及 python_home/Scripts 依次拼接到 PATH 前面
PATH = {
python_home,
python_home .. "/Scripts",
get_env("PATH")
}
}
},
---------------------------------------------------
-- 3. 极简参数覆盖 (没有 args 和 env)
---------------------------------------------------
["curl"] = {
path = base_dir .. "/curl/curl.exe"
},
---------------------------------------------------
-- 4. 模块化路由 (得益于 Rust 注入的 package.path)
-- require 能够直接在当前目录 或 conf.d/ 目录下寻找 node.lua
---------------------------------------------------
["node"] = require("node"),
["npm"] = require("npm")
}

27
src/error.rs Normal file
View File

@@ -0,0 +1,27 @@
use std::path::PathBuf;
use thiserror::Error; // 推荐引入 thiserror 库,若不使用可手动实现 std::fmt::Display
#[derive(Debug, Error)]
pub enum ShimError {
#[error("路径解析失败: {0}")]
PathResolutionError(String),
#[error("获取环境信息失败: {0}")]
EnvError(String),
#[error("配置文件未找到: {0}")]
ConfigNotFound(String),
#[error("Lua 运行时/语法错误 [{file}]: {source}")]
LuaExecutionError {
file: String,
#[source]
source: mlua::Error,
},
#[error("配置格式非法: {0}")]
InvalidConfig(String),
#[error("IO 错误: {0}")]
Io(#[from] std::io::Error),
}

View File

@@ -3,9 +3,13 @@ use std::{
ffi::CString,
mem::size_of,
path::Path,
process::{exit, Command},
process::{Command, exit},
ptr::null_mut,
};
mod shims;
mod error;
use shims::Shim;
use winapi::{
shared::minwindef::{BOOL, DWORD, FALSE, TRUE},
@@ -14,7 +18,7 @@ use winapi::{
consoleapi,
objbase::{COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE},
processthreadsapi::GetExitCodeProcess,
shellapi::{ShellExecuteExA, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOA},
shellapi::{SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOA, ShellExecuteExA},
synchapi::WaitForSingleObject,
winbase::INFINITE,
wincon,
@@ -30,15 +34,12 @@ unsafe extern "system" fn routine_handler(evt: DWORD) -> BOOL {
wincon::CTRL_LOGOFF_EVENT => TRUE, //eprintln!("ctrl_logoff handled!"),
wincon::CTRL_SHUTDOWN_EVENT => TRUE, //eprintln!("ctrl_shutdown handled!"),
other => {
eprintln!("unknown event number: {}, unhandled!", other);
return FALSE;
eprintln!("未知的系统事件编号: {},未处理!", other);
FALSE
}
}
}
mod shims;
use shims::Shim;
const EXIT_FAILED_LOAD_SHIM: i32 = 1;
const EXIT_FAILED_SPAWN_PROG: i32 = 2;
const EXIT_FAILED_WAIT_PROG: i32 = 3;
@@ -48,31 +49,42 @@ const ERROR_ELEVATION_REQUIRED: i32 = 740;
fn main() {
let res: BOOL = unsafe { consoleapi::SetConsoleCtrlHandler(Some(routine_handler), TRUE) };
if res == FALSE {
eprintln!("shim: register Ctrl handler failed.");
eprintln!("警告: 注册控制台中断事件处理器失败。");
}
let calling_args: Vec<_> = env::args().skip(1).collect();
let shim = match Shim::init() {
Ok(v) => v,
Err(e) => {
eprintln!("Error while loading shim: {}", e);
eprintln!("加载代理(shim)配置时发生错误: {}", e);
exit(EXIT_FAILED_LOAD_SHIM);
}
};
let args = if let Some(mut shim_args) = shim.args {
shim_args.extend_from_slice(calling_args.as_slice());
shim_args
} else {
calling_args
};
let mut cmd = match Command::new(&shim.target_path).args(&args).spawn() {
Ok(v) => v,
Err(e) if e.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED) => {
exit(execute_elevated(&shim.target_path, &args))
// ======= 【修改位置 1构建 Command 并注入环境变量】 =======
let mut cmd_builder = Command::new(&shim.target_path);
cmd_builder.args(&args);
// 仅作用于目标子进程,完全 Safe 且隔离
if let Some(ref envs) = shim.envs {
cmd_builder.envs(envs);
}
let mut cmd = match cmd_builder.spawn() {
Ok(v) => v,
Err(e) if e.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED) => exit(execute_elevated(
&shim.target_path,
&args,
shim.envs.as_ref(),
)),
Err(e) => {
eprintln!(
"Error while spawning target program `{}`: {}",
"启动目标程序 [{}] 时发生错误: {}",
shim.target_path.to_string_lossy(),
e
);
@@ -83,7 +95,7 @@ fn main() {
Ok(v) => v,
Err(e) => {
eprintln!(
"Error while waiting target program `{}`: {}",
"等待目标程序 [{}] 执行完毕时发生错误: {}",
shim.target_path.to_string_lossy(),
e
);
@@ -93,7 +105,20 @@ fn main() {
exit(status.code().unwrap_or(EXIT_PROG_TERMINATED))
}
fn execute_elevated(program: &Path, args: &[String]) -> i32 {
fn execute_elevated(
program: &Path,
args: &[String],
envs: Option<&std::collections::HashMap<String, String>>,
) -> i32 {
// 若提权启动,在此处将环境变量设置给当前进程(即将弹窗 UAC 的进程,随后会被子进程继承)
if let Some(env_map) = envs {
for (k, v) in env_map {
unsafe {
env::set_var(k, v);
}
}
}
let runas = CString::new("runas").unwrap();
let program = CString::new(program.to_str().unwrap()).unwrap();
let mut params = String::new();
@@ -141,5 +166,5 @@ fn execute_elevated(program: &Path, args: &[String]) -> i32 {
return EXIT_FAILED_WAIT_PROG;
}
}
return code as i32;
code as i32
}

View File

@@ -1,89 +1,283 @@
use fs_err as fs;
use crate::error::ShimError;
use mlua::{Error as LuaError, FromLua, Lua, StdLib, Table, Value};
use std::process::Command;
use std::{
collections::HashMap,
env,
env, fs,
io::{Error, ErrorKind},
path::{Path, PathBuf},
};
pub struct Shim {
/// 将 Path 转换为适合 Lua 使用的安全字符串路径
fn normalize_path_for_lua(path: &Path) -> String {
let path_str = path.to_string_lossy();
// 1. 剥离 Windows UNC 规范路径前缀 (\\?\)
let clean_str = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
// 2. 将反斜杠转换成正斜杠(在非 UNC 路径下Windows 和 Lua 均完美支持 /
// 这样既避免了 Lua 字符串转义隐患,又不会破坏 Windows 路径
clean_str.replace('\\', "/")
}
pub struct ShimEnv {
pub bin_dir: PathBuf,
pub root_dir: PathBuf,
pub tools_dir: PathBuf,
pub target_name: String,
}
impl ShimEnv {
/// 提取当前代理程序的运行环境信息
pub fn new(current_exe: PathBuf) -> Result<Self, ShimError> {
let bin_dir = current_exe
.parent()
.ok_or_else(|| {
ShimError::PathResolutionError(format!(
"无法获取程序 [{}] 的父级 bin 目录",
current_exe.display()
))
})?
.to_path_buf();
println!("bin_dir目录 {}", bin_dir.display());
let root_dir = bin_dir
.parent()
.ok_or_else(|| {
ShimError::PathResolutionError(format!(
"无法获取 bin 目录 [{}] 的父级 root 目录",
bin_dir.display()
))
})?
.to_path_buf();
println!("root_dir 目录 {}", root_dir.display());
let tools_dir = root_dir.join("tools");
println!("tools_dir 目录 {}", tools_dir.display());
let target_name = current_exe
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| {
ShimError::PathResolutionError(format!(
"无法从路径 [{}] 提取有效的程序名称",
current_exe.display()
))
})?
.to_lowercase();
println!("程序名称 {}", target_name);
Ok(Self {
bin_dir,
root_dir,
tools_dir,
target_name,
})
}
}
#[derive(Debug, Clone)]
pub struct ShimConfig {
pub target_path: PathBuf,
pub args: Option<Vec<String>>,
pub envs: Option<HashMap<String, String>>,
}
impl ShimConfig {
/// 根据配置快速构建准备执行的 Command 对象
pub fn to_command(&self) -> Command {
let mut cmd = Command::new(&self.target_path);
if let Some(args) = &self.args {
cmd.args(args);
}
if let Some(envs) = &self.envs {
for (key, val) in envs {
// 直接应用环境变量Lua 端已经处理好字符串拼接或列表合并)
cmd.env(key, val);
}
}
cmd
}
}
/// 实现 FromLua Trait由 mlua 自动处理 Table 转换
impl FromLua for ShimConfig {
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
match value {
Value::Table(table) => {
let path_str: String = table.get("path")?;
let args: Option<Vec<String>> = table.get("args")?;
// 解析 env Table
let mut envs_map = HashMap::new();
if let Ok(env_table) = table.get::<Table>("env") {
// 获取当前系统的路径分隔符Windows 为 ";"Unix 为 ":"
#[cfg(windows)]
let sep = ";";
#[cfg(not(windows))]
let sep = ":";
for pair in env_table.pairs::<String, Value>() {
let (k, v) = pair?;
match v {
// 情况 1: 普通字符串,如 HOME = "C:/path" -> 直接覆盖
Value::String(s) => {
envs_map.insert(k, s.to_str()?.to_string());
}
// 情况 2: 数组 Table如 PATH = { bin_dir, get_env("PATH") }
Value::Table(arr) => {
let paths: Vec<String> = arr
// 将 arr 作为序列(数组)处理,每个元素转为 String
.sequence_values::<String>()
.filter_map(|r| r.ok())
.filter(|s| !s.is_empty()) // 过滤空串,防止生成不必要的连续 ;;
.collect();
let combined = paths.join(sep);
envs_map.insert(k, combined);
}
_ => {}
}
}
}
let envs = if envs_map.is_empty() {
None
} else {
Some(envs_map)
};
Ok(ShimConfig {
target_path: PathBuf::from(path_str),
args,
envs,
})
}
_ => Err(mlua::Error::FromLuaConversionError {
from: value.type_name(),
to: "ShimConfig".into(),
message: Some("Expected a Lua table".to_string()),
}),
}
}
}
pub struct LuaRuntime {
lua: Lua,
}
impl LuaRuntime {
/// 初始化限定权限的 Lua 沙箱环境
pub fn new(shim_env: &ShimEnv) -> Result<Self, ShimError> {
// 只加载安全的标准库,剥离 os / io 等风险模块
let lua = Lua::new_with(
StdLib::TABLE | StdLib::STRING | StdLib::MATH | StdLib::PACKAGE,
mlua::LuaOptions::default(),
)
.map_err(|e| ShimError::EnvError(format!("初始化 Lua 失败: {}", e)))?;
let globals = lua.globals();
// 统一使用 POSIX 风格路径规范化路径字符串
let root_dir_str = normalize_path_for_lua(&shim_env.root_dir);
let tools_dir_str = normalize_path_for_lua(&shim_env.tools_dir);
// 1. 注入锚点变量
globals
.set("__SHIM_DIR__", root_dir_str.clone())
.map_err(|e| ShimError::EnvError(e.to_string()))?;
// 2. 安全暴露 get_env 供配置读取环境变量
let get_env = lua
.create_function(|_, key: String| -> mlua::Result<String> {
Ok(env::var(key).unwrap_or_default())
})
.map_err(|e| ShimError::EnvError(e.to_string()))?;
globals
.set("get_env", get_env)
.map_err(|e| ShimError::EnvError(e.to_string()))?;
// 3. 配置 package.path确保 require 行为正常
if let Ok(package) = globals.get::<Table>("package") {
if let Ok(path) = package.get::<String>("path") {
let new_path = format!(
"{};{}/?.lua;{}/?/init.lua;{}/?.lua;{}/?/init.lua",
path, root_dir_str, root_dir_str, tools_dir_str, tools_dir_str
);
let _ = package.set("path", new_path);
}
}
Ok(Self { lua })
}
/// 执行指定脚本文件,直接返回完整的 Lua Table
pub fn evaluate_lua_script(&self, path: &Path) -> Result<Table, ShimError> {
let code = fs::read_to_string(path)?;
self.lua
.load(&code)
.set_name(path.to_string_lossy())
.eval::<Table>()
.map_err(|e| ShimError::LuaExecutionError {
file: path.display().to_string(),
source: e,
})
}
/// 将 Lua Value 解析转化为 ShimConfig 数据对象
pub fn parse_config(&self, value: Value) -> Result<ShimConfig, ShimError> {
ShimConfig::from_lua(value, &self.lua).map_err(|e| ShimError::InvalidConfig(e.to_string()))
}
}
pub struct Shim;
impl Shim {
pub fn init() -> Result<Self, Error> {
let shim_path = get_shim_file_path()?;
let kvs = parse_shim_file(&shim_path)?;
let target_path = match kvs.get("path") {
Some(p) => PathBuf::from(p),
None => {
return Err(Error::new(
ErrorKind::NotFound,
format!("no path key in {}", shim_path.to_string_lossy()),
))
pub fn init() -> Result<ShimConfig, ShimError> {
let current_exe = env::current_exe()
.map_err(|e| Error::new(ErrorKind::Other, format!("获取代理程序路径失败: {}", e)))?;
println!("当前目录 {}", current_exe.display());
let shim_env = ShimEnv::new(current_exe)?;
let runtime = LuaRuntime::new(&shim_env)?;
Self::resolve_config(&runtime, &shim_env)
}
};
let args = kvs.get("args").map(|a| {
a.split_whitespace()
.map(|s| s.to_string())
.collect::<Vec<_>>()
});
Ok(Self { target_path, args })
fn resolve_config(engine: &LuaRuntime, env: &ShimEnv) -> Result<ShimConfig, ShimError> {
// 策略 1: 尝试加载全局配置文件 shims.lua
let global_config = env.root_dir.join("shims.lua");
if global_config.is_file() {
let root_table = engine.evaluate_lua_script(&global_config)?;
// 检查 shims.lua 中是否存在以 target_name 命名的 Table 节点
if let Ok(target_val) = root_table.get::<Value>(env.target_name.as_str()) {
if matches!(target_val, Value::Table(_)) {
return engine.parse_config(target_val);
}
}
// 穿透:若全局配置文件存在但未包含当前程序的 key继续向下探查
}
// 策略 2: 降级寻找独立文件 ({exe}.lua)优先顺序tools/ > root/
let target_filename = format!("{}.lua", env.target_name);
let candidates = [
env.tools_dir.join(&target_filename),
env.root_dir.join(&target_filename),
];
for config_path in &candidates {
if config_path.is_file() {
let table = engine.evaluate_lua_script(config_path)?;
return engine.parse_config(Value::Table(table));
}
}
fn get_shim_file_path() -> Result<PathBuf, Error> {
let mut current_exe = env::current_exe().map_err(|e| {
Error::new(
ErrorKind::Other,
format!("acquiring shim executable path: {}", e),
)
})?;
if !current_exe.set_extension("shim") {
return Err(Error::new(
ErrorKind::Other,
format!("{} is not a file", current_exe.to_string_lossy()),
));
// 策略 3: 所有查找失败,抛出错误
Err(ShimError::ConfigNotFound(format!(
"未找到关于 '{}' 的配置。请检查 shims.lua 或特定的 {}.lua 文件",
env.target_name, env.target_name
)))
}
Ok(current_exe)
}
use unicode_bom::Bom;
fn parse_shim_file(shim_path: &Path) -> Result<HashMap<String, String>, Error> {
let mut kvs = HashMap::new();
let raw_content = fs::read_to_string(shim_path).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("reading {}: {}", shim_path.to_string_lossy(), e),
)
})?;
//NOTE: expedient trick for utf-8 with bom
let bom = Bom::from(raw_content.as_bytes());
for line in raw_content[bom.len()..]
.lines()
.filter(|l| !l.trim().is_empty())
{
let mut components = line.split("=");
let key = match components.next() {
Some(k) => k.trim(),
None => {
return Err(Error::new(
ErrorKind::InvalidData,
format!("invalid line in shim file: {}", line),
));
}
};
let value = match components.next() {
Some(v) => v.trim(),
None => {
return Err(Error::new(
ErrorKind::InvalidData,
format!("invalid line in shim file: {}", line),
));
}
};
kvs.insert(key.to_string(), value.to_string());
}
Ok(kvs)
}