fix(shim): 优化配置解析、跨平台编码与 UAC 提权逻辑
- 使用 `OsString`/`PathBuf` 替代 `String`,实现跨平台无损编码与命令行参数透传 - 完善 `FromLua` 转换与边界校验,拦截空洞 (`nil`) 及非整数键 - 修复环境变量拼接时由于内置分隔符导致的 `join_paths` 报错 - 优化 Windows 下 UAC 提权执行逻辑,改用宽字符 API (`ShellExecuteExW`)
This commit is contained in:
@@ -2,7 +2,7 @@
|
|||||||
name = "rshim"
|
name = "rshim"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.85"
|
rust-version = "1.94"
|
||||||
license = "MIT OR Unlicense"
|
license = "MIT OR Unlicense"
|
||||||
description = "A fast, safe Rust shim launcher for Scoop"
|
description = "A fast, safe Rust shim launcher for Scoop"
|
||||||
|
|
||||||
@@ -29,3 +29,4 @@ dunce = "1.0.5"
|
|||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
tracing-appender = "0.2"
|
tracing-appender = "0.2"
|
||||||
|
encoding_rs = "0.8.35"
|
||||||
|
|||||||
4
build.rs
4
build.rs
@@ -20,7 +20,7 @@ fn main() {
|
|||||||
|
|
||||||
// cargo:rerun-if-changed -> 当指定文件变化时,重新运行 xxx
|
// cargo:rerun-if-changed -> 当指定文件变化时,重新运行 xxx
|
||||||
println!("cargo:rerun-if-changed=build.rs");
|
println!("cargo:rerun-if-changed=build.rs");
|
||||||
println!("cargo:rerun-if-changed=shims.lua");
|
println!("cargo:rerun-if-changed=rshim.lua");
|
||||||
println!("cargo:rustc-env=OUTPUT_DIR={}", output_dir.display());
|
println!("cargo:rustc-env=OUTPUT_DIR={}", output_dir.display());
|
||||||
|
|
||||||
// 创建目录
|
// 创建目录
|
||||||
@@ -35,7 +35,7 @@ fn main() {
|
|||||||
|
|
||||||
// 复制文件
|
// 复制文件
|
||||||
let source = PathBuf::from(&manifest_dir).join("shims.lua");
|
let source = PathBuf::from(&manifest_dir).join("shims.lua");
|
||||||
let destination = output_dir.join("shims.lua");
|
let destination = output_dir.join("rshim.lua");
|
||||||
|
|
||||||
if source.exists() {
|
if source.exists() {
|
||||||
fs::copy(&source, &destination).expect("Failed to copy shims.lua");
|
fs::copy(&source, &destination).expect("Failed to copy shims.lua");
|
||||||
|
|||||||
10
shims.lua
10
shims.lua
@@ -9,6 +9,16 @@ return {
|
|||||||
---------------------------------------------------
|
---------------------------------------------------
|
||||||
-- 1. 标准相对路径 + 正斜杠拼接 (最推荐,绿色便携)
|
-- 1. 标准相对路径 + 正斜杠拼接 (最推荐,绿色便携)
|
||||||
---------------------------------------------------
|
---------------------------------------------------
|
||||||
|
["numa"] = {
|
||||||
|
target = base_dir .. "/tools/numa/numa.exe",
|
||||||
|
-- 追加参数
|
||||||
|
args = { "--help" },
|
||||||
|
-- 注入环境变量,使用 get_env 获取宿主机当前值
|
||||||
|
env = {
|
||||||
|
PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
["git"] = {
|
["git"] = {
|
||||||
target = base_dir .. "/git/bin/git.exe",
|
target = base_dir .. "/git/bin/git.exe",
|
||||||
-- 追加参数
|
-- 追加参数
|
||||||
|
|||||||
173
src/config.rs
173
src/config.rs
@@ -1,25 +1,43 @@
|
|||||||
use mlua::{FromLua, Lua, Table, Value};
|
use mlua::{FromLua, Lua, LuaString, ObjectLike, Table, Value};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::ffi::OsString;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
/// 构造一个带上下文的 FromLua 转换错误,便于定位配置问题
|
/// 构造一个带上下文的 FromLua 转换错误,便于定位配置问题
|
||||||
fn conversion_error(message: impl Into<String>) -> mlua::Error {
|
fn conversion_error(message: impl Into<String>) -> mlua::Error {
|
||||||
mlua::Error::FromLuaConversionError {
|
mlua::Error::FromLuaConversionError {
|
||||||
from: "Lua value".into(),
|
from: "Lua value",
|
||||||
to: "ShimConfig".into(),
|
to: "ShimConfig".into(),
|
||||||
message: Some(message.into()),
|
message: Some(message.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 将 Lua 字符串转为 Rust 字符串;非 UTF-8 字节替换为 U+FFFD 并告警
|
/// 将 Lua 字符串转为 Rust 字符串;非 UTF-8 字节替换为 U+FFFD 并告警
|
||||||
fn lua_string_to_string(s: mlua::LuaString) -> String {
|
fn lua_string_to_os_string(s: LuaString) -> Result<OsString, mlua::Error> {
|
||||||
match s.to_str() {
|
let raw_bytes = &s.as_bytes().to_vec();
|
||||||
Ok(str_val) => str_val.to_string(),
|
// 1. Unix 平台:直接零拷贝透传原始字节(无损支持任意编码)
|
||||||
Err(_) => {
|
#[cfg(unix)]
|
||||||
tracing::warn!("配置字符串包含非 UTF-8 字节,已替换为 U+FFFD");
|
{
|
||||||
s.to_string_lossy()
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
Ok(OsStr::from_bytes(raw_bytes).to_os_string())
|
||||||
|
}
|
||||||
|
// 2. Windows 平台:优先按 UTF-8 解码,失败则按当前系统本地代码页 (ANSI/GBK) 转换
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
// 先尝试标准的 UTF-8
|
||||||
|
if let Ok(utf8_str) = std::str::from_utf8(raw_bytes) {
|
||||||
|
return Ok(OsString::from(utf8_str));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 非 UTF-8 时,按系统默认的 ANSI/OEM (如 GBK) 进行安全解码
|
||||||
|
let (cow, _, had_errors) = encoding_rs::GBK.decode(raw_bytes);
|
||||||
|
if had_errors {
|
||||||
|
return Err(mlua::Error::RuntimeError(
|
||||||
|
"Path contains invalid/unsupported byte encoding".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(OsString::from(cow.as_ref()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,20 +92,20 @@ fn validate_env_key(key: &str) -> mlua::Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 递归将任意 Lua Value 展开为扁平的字符串片段列表
|
/// 递归将任意 Lua Value 展开为扁平的字符串片段列表
|
||||||
fn collect_env_strings(value: Value, out: &mut Vec<String>) -> mlua::Result<()> {
|
fn collect_env_strings(value: Value, out: &mut Vec<OsString>) -> mlua::Result<()> {
|
||||||
match value {
|
match value {
|
||||||
// 1. 字符串
|
// 1. 字符串
|
||||||
Value::String(s) => out.push(lua_string_to_string(s)),
|
Value::String(s) => out.push(lua_string_to_os_string(s)?),
|
||||||
// 2. 整数与浮点数
|
// 2. 整数与浮点数
|
||||||
Value::Integer(i) => out.push(i.to_string()),
|
Value::Integer(i) => out.push(OsString::from(i.to_string())),
|
||||||
Value::Number(n) => {
|
Value::Number(n) => {
|
||||||
tracing::warn!(value = %n, "环境变量中的浮点数将按十进制格式转换为字符串");
|
tracing::warn!(value = %n, "环境变量中的浮点数将按十进制格式转换为字符串");
|
||||||
out.push(n.to_string());
|
out.push(OsString::from(n.to_string()));
|
||||||
}
|
}
|
||||||
// 3. 布尔值
|
// 3. 布尔值
|
||||||
Value::Boolean(b) => {
|
Value::Boolean(b) => {
|
||||||
tracing::warn!(value = %b, "环境变量中的布尔值将转换为字符串");
|
tracing::warn!(value = %b, "环境变量中的布尔值将转换为字符串");
|
||||||
out.push(b.to_string());
|
out.push(OsString::from(b.to_string()));
|
||||||
}
|
}
|
||||||
// 4. 表/数组:必须是连续整数下标的纯序列,递归解包(支持任意深度的嵌套数组)
|
// 4. 表/数组:必须是连续整数下标的纯序列,递归解包(支持任意深度的嵌套数组)
|
||||||
Value::Table(tbl) => for_each_sequence_item(&tbl, |item| collect_env_strings(item, out))?,
|
Value::Table(tbl) => for_each_sequence_item(&tbl, |item| collect_env_strings(item, out))?,
|
||||||
@@ -108,8 +126,8 @@ fn collect_env_strings(value: Value, out: &mut Vec<String>) -> mlua::Result<()>
|
|||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct ShimConfig {
|
pub struct ShimConfig {
|
||||||
pub target: PathBuf,
|
pub target: PathBuf,
|
||||||
pub args: Vec<String>,
|
pub args: Vec<OsString>,
|
||||||
pub env: HashMap<String, String>,
|
pub env: HashMap<String, OsString>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ShimConfig {
|
impl ShimConfig {
|
||||||
@@ -139,6 +157,7 @@ impl ShimConfig {
|
|||||||
/// 实现 FromLua Trait,由 mlua 自动处理 Table 转换
|
/// 实现 FromLua Trait,由 mlua 自动处理 Table 转换
|
||||||
impl FromLua for ShimConfig {
|
impl FromLua for ShimConfig {
|
||||||
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
|
||||||
|
// 脚本返回必须是一个 Table 变体
|
||||||
let table = match value {
|
let table = match value {
|
||||||
Value::Table(t) => t,
|
Value::Table(t) => t,
|
||||||
_ => {
|
_ => {
|
||||||
@@ -151,25 +170,41 @@ impl FromLua for ShimConfig {
|
|||||||
|
|
||||||
// 必填字段: target(严格限定为字符串,避免数字被 mlua 宽松转为字符串后掩盖错误)
|
// 必填字段: target(严格限定为字符串,避免数字被 mlua 宽松转为字符串后掩盖错误)
|
||||||
let target = match table.get::<Value>("target")? {
|
let target = match table.get::<Value>("target")? {
|
||||||
Value::String(s) => lua_string_to_string(s),
|
Value::String(s) => lua_string_to_os_string(s)?,
|
||||||
Value::Nil => {
|
Value::Nil => {
|
||||||
return Err(conversion_error("缺少必填字段 target(应为字符串路径)"));
|
return Err(conversion_error("缺少必填字段 target(应为字符串路径)"));
|
||||||
}
|
}
|
||||||
other => {
|
other => {
|
||||||
return Err(conversion_error(format!(
|
return Err(conversion_error(format!(
|
||||||
"target 必须是字符串,实际是 {}",
|
"target 需为有效的路径且类型必须是字符串,实际类型是 {}",
|
||||||
other.type_name()
|
other.type_name()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// 可选字段: args(缺失或 nil 时默认空列表;保留空字符串参数,与提权路径的 "" 语义一致)
|
// 可选字段: args(缺失或 nil 时默认空列表;保留空字符串参数,与提权路径的 "" 语义一致)
|
||||||
|
// let args = match table.get::<Option<Value>>("args")? {
|
||||||
|
// None => Vec::new(),
|
||||||
|
// Some(Value::Table(tbl)) => {
|
||||||
|
// let mut args = Vec::new();
|
||||||
|
// for_each_sequence_item(&tbl, |item| match item {
|
||||||
|
// Value::String(s) => {
|
||||||
|
// args.push(lua_string_to_string(s));
|
||||||
|
// Ok(())
|
||||||
|
// }
|
||||||
|
// other => Err(conversion_error(format!(
|
||||||
|
// "args 数组元素必须是字符串,实际是 {}",
|
||||||
|
// other.type_name()
|
||||||
|
// ))),
|
||||||
|
// })?;
|
||||||
|
// args
|
||||||
|
// }
|
||||||
let args = match table.get::<Option<Value>>("args")? {
|
let args = match table.get::<Option<Value>>("args")? {
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
Some(Value::Table(tbl)) => {
|
Some(Value::Table(tbl)) => {
|
||||||
let mut args = Vec::new();
|
let mut args = Vec::new();
|
||||||
for_each_sequence_item(&tbl, |item| match item {
|
for_each_sequence_item(&tbl, |item| match item {
|
||||||
Value::String(s) => {
|
Value::String(s) => {
|
||||||
args.push(lua_string_to_string(s));
|
args.push(lua_string_to_os_string(s)?);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
other => Err(conversion_error(format!(
|
other => Err(conversion_error(format!(
|
||||||
@@ -187,7 +222,7 @@ impl FromLua for ShimConfig {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
// 可选字段: env(只允许缺失/nil,其他类型由 Option<Table> 转换报错,不再静默忽略)
|
// 可选字段: env(只允许缺失/nil,其他类型由 Option<Table> 转换报错,不再静默忽略)
|
||||||
let env_table: Option<Table> = table.get("env")?;
|
let env_table = table.get::<Option<Table>>("env")?;
|
||||||
println!("env_table:{:?}", env_table);
|
println!("env_table:{:?}", env_table);
|
||||||
let mut env = HashMap::new();
|
let mut env = HashMap::new();
|
||||||
if let Some(env_table) = env_table {
|
if let Some(env_table) = env_table {
|
||||||
@@ -200,25 +235,36 @@ impl FromLua for ShimConfig {
|
|||||||
|
|
||||||
// 空数组/空串也显式设置(空值表示清空该变量),
|
// 空数组/空串也显式设置(空值表示清空该变量),
|
||||||
// 与“未配置该变量(继承宿主环境)”相区分
|
// 与“未配置该变量(继承宿主环境)”相区分
|
||||||
let joined_os_str =
|
let joined_os_str = std::env::join_paths(parts).map_err(|e| {
|
||||||
std::env::join_paths(parts.iter().map(PathBuf::from)).map_err(|e| {
|
conversion_error(format!(
|
||||||
conversion_error(format!(
|
"环境变量 [{}] 的值无法用系统路径分隔符拼接: {}",
|
||||||
"环境变量 [{}] 的值无法用系统路径分隔符拼接: {}",
|
key, e
|
||||||
key, e
|
))
|
||||||
))
|
|
||||||
})?;
|
|
||||||
println!("环境变量拼接结果:{:?}", joined_os_str);
|
|
||||||
|
|
||||||
let joined_str = joined_os_str.into_string().map_err(|_| {
|
|
||||||
conversion_error(format!("环境变量 [{}] 的值不是合法文本", key))
|
|
||||||
})?;
|
})?;
|
||||||
if joined_str.contains('\0') {
|
println!("环境变量拼接结果:{:?}", joined_os_str);
|
||||||
return Err(conversion_error(format!(
|
// 检查是否包含非法 NUL 字符
|
||||||
"环境变量 [{}] 的值不能包含 NUL 字符",
|
#[cfg(unix)]
|
||||||
key
|
{
|
||||||
)));
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
if joined_os_str.as_bytes().contains(&0) {
|
||||||
|
return Err(conversion_error(format!(
|
||||||
|
"环境变量 [{}] 的值不能包含 NUL 字符",
|
||||||
|
key
|
||||||
|
)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
env.insert(key, joined_str);
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
if joined_os_str.encode_wide().any(|c| c == 0) {
|
||||||
|
return Err(conversion_error(format!(
|
||||||
|
"环境变量 [{}] 的值不能包含 NUL 字符",
|
||||||
|
key
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
env.insert(key, joined_os_str);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
println!("环境变量结果:{:?}", env);
|
println!("环境变量结果:{:?}", env);
|
||||||
@@ -236,8 +282,26 @@ mod tests {
|
|||||||
|
|
||||||
fn parse(src: &str) -> mlua::Result<ShimConfig> {
|
fn parse(src: &str) -> mlua::Result<ShimConfig> {
|
||||||
let lua = Lua::new();
|
let lua = Lua::new();
|
||||||
|
// 模拟 runtime 注入的 get_env:返回按平台分隔符拆分的段数组(空变量返回空表)
|
||||||
|
let get_env = lua
|
||||||
|
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
||||||
|
let value = std::env::var(key).unwrap_or_default();
|
||||||
|
let segments: Vec<String> = if value.is_empty() {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
std::env::split_paths(std::ffi::OsStr::new(&value))
|
||||||
|
.map(|p| p.to_string_lossy().into_owned())
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
lua.create_sequence_from(segments)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lua.globals().set("get_env", get_env).unwrap();
|
||||||
|
|
||||||
let value = lua.load(src).eval::<Value>()?;
|
let value = lua.load(src).eval::<Value>()?;
|
||||||
ShimConfig::from_lua(value, &lua)
|
let t = ShimConfig::from_lua(value, &lua);
|
||||||
|
println!("读取出的数据:{:?}", t.clone()?);
|
||||||
|
t
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -248,8 +312,10 @@ mod tests {
|
|||||||
target = "C:/tools/git.exe",
|
target = "C:/tools/git.exe",
|
||||||
args = { "--no-pager" },
|
args = { "--no-pager" },
|
||||||
env = {
|
env = {
|
||||||
PATH = { "C:/tools/git/bin", "C:/Windows" },
|
PATH = { "C:/tools/git/bin", "C:/Windows",get_env("PATH") },
|
||||||
HOME = "C:/tools/home",
|
HOME = "C:/tools/home",
|
||||||
|
CONST = 3,
|
||||||
|
BOOL = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"#,
|
"#,
|
||||||
@@ -257,13 +323,13 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(cfg.target, PathBuf::from("C:/tools/git.exe"));
|
assert_eq!(cfg.target, PathBuf::from("C:/tools/git.exe"));
|
||||||
assert_eq!(cfg.args, vec!["--no-pager"]);
|
assert_eq!(cfg.args, vec!["--no-pager"]);
|
||||||
assert_eq!(
|
assert_eq!(cfg.env.get("HOME").unwrap().to_str(), Some("C:/tools/home"));
|
||||||
cfg.env.get("HOME").map(String::as_str),
|
// PATH 前缀来自配置,随后附加 get_env("PATH") 拆出的宿主 PATH 段
|
||||||
Some("C:/tools/home")
|
let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
||||||
);
|
assert!(
|
||||||
assert_eq!(
|
path == "C:/tools/git/bin;C:/Windows"
|
||||||
cfg.env.get("PATH").map(String::as_str),
|
|| path.starts_with("C:/tools/git/bin;C:/Windows;"),
|
||||||
Some("C:/tools/git/bin;C:/Windows")
|
"unexpected PATH: {path}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,13 +349,26 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn keeps_empty_env_value() {
|
fn keeps_empty_env_value() {
|
||||||
let cfg = parse(r#"return { target = "t.exe", env = { FOO = "" } }"#).unwrap();
|
let cfg = parse(r#"return { target = "t.exe", env = { FOO = "" } }"#).unwrap();
|
||||||
assert_eq!(cfg.env.get("FOO").map(String::as_str), Some(""));
|
assert_eq!(cfg.env.get("FOO").unwrap().to_str(), Some(""));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn empty_array_clears_env_var() {
|
fn empty_array_clears_env_var() {
|
||||||
let cfg = parse(r#"return { target = "t.exe", env = { PATH = {} } }"#).unwrap();
|
let cfg = parse(r#"return { target = "t.exe", env = { PATH = {} } }"#).unwrap();
|
||||||
assert_eq!(cfg.env.get("PATH").map(String::as_str), Some(""));
|
assert_eq!(cfg.env.get("PATH").unwrap().to_str(), Some(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expands_nested_env_array() {
|
||||||
|
// get_env("PATH") 现在返回拆分后的段数组,嵌套表应被递归展开
|
||||||
|
let cfg = parse(
|
||||||
|
r#"return { target = "t.exe", env = { PATH = { "C:/a", { "C:/b", "C:/c" } } } }"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cfg.env.get("PATH").unwrap().to_str(),
|
||||||
|
Some("C:/a;C:/b;C:/c")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
138
src/main.rs
138
src/main.rs
@@ -1,8 +1,13 @@
|
|||||||
use std::{env, ffi::CString, mem::size_of, path::Path, process::exit, ptr::null_mut};
|
|
||||||
|
|
||||||
use rshim::Shim;
|
use rshim::Shim;
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
use std::{env, ffi::CString, mem::size_of, path::Path, process::exit, ptr::null_mut};
|
||||||
use tracing_subscriber::{EnvFilter, fmt};
|
use tracing_subscriber::{EnvFilter, fmt};
|
||||||
|
|
||||||
|
use std::ffi::{OsStr, OsString};
|
||||||
|
|
||||||
|
use windows_sys::Win32::UI::Shell::{SHELLEXECUTEINFOW, ShellExecuteExW};
|
||||||
|
|
||||||
|
use windows_sys::Win32::Foundation::CloseHandle;
|
||||||
use windows_sys::{
|
use windows_sys::{
|
||||||
Win32::{
|
Win32::{
|
||||||
Foundation::{FALSE, TRUE},
|
Foundation::{FALSE, TRUE},
|
||||||
@@ -58,7 +63,7 @@ fn main() {
|
|||||||
eprintln!("警告: 注册控制台中断事件处理器失败。");
|
eprintln!("警告: 注册控制台中断事件处理器失败。");
|
||||||
}
|
}
|
||||||
|
|
||||||
let calling_args: Vec<_> = env::args().skip(1).collect();
|
let calling_args: Vec<_> = env::args_os().skip(1).collect();
|
||||||
let shim = match Shim::load() {
|
let shim = match Shim::load() {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -74,7 +79,7 @@ fn main() {
|
|||||||
let mut args = shim.args.clone();
|
let mut args = shim.args.clone();
|
||||||
args.extend_from_slice(&calling_args);
|
args.extend_from_slice(&calling_args);
|
||||||
|
|
||||||
let mut cmd = match cmd.spawn() {
|
let mut child = match cmd.spawn() {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(e) if e.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED) => {
|
Err(e) if e.raw_os_error() == Some(ERROR_ELEVATION_REQUIRED) => {
|
||||||
exit(execute_elevated(&shim.target, &args, Some(&shim.env)))
|
exit(execute_elevated(&shim.target, &args, Some(&shim.env)))
|
||||||
@@ -88,7 +93,7 @@ fn main() {
|
|||||||
exit(EXIT_FAILED_SPAWN_PROG);
|
exit(EXIT_FAILED_SPAWN_PROG);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let status = match cmd.wait() {
|
let status = match child.wait() {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
@@ -101,11 +106,15 @@ fn main() {
|
|||||||
};
|
};
|
||||||
exit(status.code().unwrap_or(EXIT_PROG_TERMINATED))
|
exit(status.code().unwrap_or(EXIT_PROG_TERMINATED))
|
||||||
}
|
}
|
||||||
|
// 辅助函数:将任意 OsStr 转换为以 \0 结尾的 UTF-16 宽字符向量 (Vec<u16>)
|
||||||
|
fn to_wide_null(s: impl AsRef<OsStr>) -> Vec<u16> {
|
||||||
|
s.as_ref().encode_wide().chain(std::iter::once(0)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
fn execute_elevated(
|
fn execute_elevated(
|
||||||
program: &Path,
|
program: &Path,
|
||||||
args: &[String],
|
args: &[OsString],
|
||||||
env_vars: Option<&std::collections::HashMap<String, String>>,
|
env_vars: Option<&std::collections::HashMap<String, OsString>>,
|
||||||
) -> i32 {
|
) -> i32 {
|
||||||
// 若提权启动,在此处将环境变量设置给当前进程(即将弹窗 UAC 的进程,随后会被子进程继承)
|
// 若提权启动,在此处将环境变量设置给当前进程(即将弹窗 UAC 的进程,随后会被子进程继承)
|
||||||
if let Some(env_map) = env_vars {
|
if let Some(env_map) = env_vars {
|
||||||
@@ -115,53 +124,112 @@ fn execute_elevated(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 2. 将参数列表按 Windows 命令行规则拼装为单个命令行字符串
|
||||||
let runas = CString::new("runas").unwrap();
|
let mut arguments_os = OsString::new();
|
||||||
let program = CString::new(program.to_str().unwrap()).unwrap();
|
for (i, arg) in args.iter().enumerate() {
|
||||||
let mut arguments = String::new();
|
if i > 0 {
|
||||||
for arg in args.iter() {
|
arguments_os.push(" ");
|
||||||
arguments.push(' ');
|
}
|
||||||
if arg.len() == 0 {
|
let arg_str = arg.to_string_lossy();
|
||||||
arguments.push_str("\"\"");
|
if arg_str.is_empty() {
|
||||||
} else if arg.find(&[' ', '\t', '"'][..]).is_none() {
|
arguments_os.push("\"\"");
|
||||||
arguments.push_str(&arg);
|
} else if !arg_str.contains([' ', '\t', '"']) {
|
||||||
|
arguments_os.push(arg);
|
||||||
} else {
|
} else {
|
||||||
arguments.push('"');
|
// 包含空格或引号时进行标准转义包裹
|
||||||
for c in arg.chars() {
|
arguments_os.push("\"");
|
||||||
|
for c in arg_str.chars() {
|
||||||
match c {
|
match c {
|
||||||
'\\' => arguments.push_str("\\\\"),
|
'\\' => arguments_os.push("\\\\"),
|
||||||
'"' => arguments.push_str("\\\""),
|
'"' => arguments_os.push("\\\""),
|
||||||
c => arguments.push(c),
|
_ => arguments_os.push(c.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
arguments.push('"');
|
arguments_os.push("\"");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// let runas = CString::new("runas").unwrap();
|
||||||
|
// let program = CString::new(program.to_str().unwrap()).unwrap();
|
||||||
|
// let mut arguments = String::new();
|
||||||
|
// for arg in args.iter() {
|
||||||
|
// arguments.push(' ');
|
||||||
|
// if arg.len() == 0 {
|
||||||
|
// arguments.push_str("\"\"");
|
||||||
|
// } else if arg.find(&[' ', '\t', '"'][..]).is_none() {
|
||||||
|
// arguments.push_str(&arg);
|
||||||
|
// } else {
|
||||||
|
// arguments.push('"');
|
||||||
|
// for c in arg.chars() {
|
||||||
|
// match c {
|
||||||
|
// '\\' => arguments.push_str("\\\\"),
|
||||||
|
// '"' => arguments.push_str("\\\""),
|
||||||
|
// c => arguments.push(c),
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// arguments.push('"');
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// 3. 准备 Windows 宽字符参数
|
||||||
|
let runas = to_wide_null("runas");
|
||||||
|
let program_wide = to_wide_null(program.as_os_str());
|
||||||
|
let arguments_wide = to_wide_null(&arguments_os);
|
||||||
|
|
||||||
let arguments = CString::new(&arguments[..]).unwrap();
|
let mut info = SHELLEXECUTEINFOW {
|
||||||
let mut info = SHELLEXECUTEINFOA::default();
|
cbSize: size_of::<SHELLEXECUTEINFOW>() as u32,
|
||||||
info.cbSize = size_of::<SHELLEXECUTEINFOA>() as u32;
|
fMask: SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS,
|
||||||
info.fMask = SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS;
|
hwnd: null_mut(),
|
||||||
info.lpVerb = runas.as_ptr().cast::<u8>();
|
lpVerb: runas.as_ptr(),
|
||||||
info.lpFile = program.as_ptr().cast::<u8>();
|
lpFile: program_wide.as_ptr(),
|
||||||
info.lpParameters = arguments.as_ptr().cast::<u8>();
|
lpParameters: arguments_wide.as_ptr(),
|
||||||
info.nShow = SW_NORMAL;
|
lpDirectory: null_mut(),
|
||||||
|
nShow: SW_NORMAL as i32,
|
||||||
|
hInstApp: null_mut(),
|
||||||
|
lpIDList: null_mut(),
|
||||||
|
lpClass: null_mut(),
|
||||||
|
hkeyClass: null_mut(),
|
||||||
|
dwHotKey: 0,
|
||||||
|
Anonymous: unsafe { std::mem::zeroed() },
|
||||||
|
hProcess: null_mut(),
|
||||||
|
};
|
||||||
|
// let arguments = CString::new(&arguments[..]).unwrap();
|
||||||
|
// let mut info = SHELLEXECUTEINFOA::default();
|
||||||
|
// info.cbSize = size_of::<SHELLEXECUTEINFOA>() as u32;
|
||||||
|
// info.fMask = SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS;
|
||||||
|
// info.lpVerb = runas.as_ptr().cast::<u8>();
|
||||||
|
// info.lpFile = program.as_ptr().cast::<u8>();
|
||||||
|
// info.lpParameters = arguments.as_ptr().cast::<u8>();
|
||||||
|
// info.nShow = SW_NORMAL;
|
||||||
let res = unsafe {
|
let res = unsafe {
|
||||||
CoInitializeEx(
|
CoInitializeEx(
|
||||||
null_mut(),
|
null_mut(),
|
||||||
(COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32,
|
(COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32,
|
||||||
);
|
);
|
||||||
ShellExecuteExA(&mut info as *mut _)
|
// ShellExecuteExA(&mut info as *mut _)
|
||||||
|
ShellExecuteExW(&mut info)
|
||||||
};
|
};
|
||||||
if res == FALSE || info.hProcess == null_mut() {
|
if res == FALSE || info.hProcess == null_mut() {
|
||||||
return EXIT_FAILED_SPAWN_PROG;
|
return EXIT_FAILED_SPAWN_PROG;
|
||||||
}
|
}
|
||||||
let mut code: u32 = 0;
|
// 5. 等待提权子进程执行结束并获取退出状态码
|
||||||
|
let mut exit_code: u32 = 0;
|
||||||
unsafe {
|
unsafe {
|
||||||
WaitForSingleObject(info.hProcess, INFINITE);
|
WaitForSingleObject(info.hProcess, INFINITE);
|
||||||
if GetExitCodeProcess(info.hProcess, &mut code as *mut _) == FALSE {
|
let ok = GetExitCodeProcess(info.hProcess, &mut exit_code);
|
||||||
|
CloseHandle(info.hProcess); // 释放进程句柄,防止资源泄露
|
||||||
|
|
||||||
|
if ok == FALSE {
|
||||||
return EXIT_FAILED_WAIT_PROG;
|
return EXIT_FAILED_WAIT_PROG;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
code as i32
|
|
||||||
|
exit_code as i32
|
||||||
|
|
||||||
|
// let mut code: u32 = 0;
|
||||||
|
// unsafe {
|
||||||
|
// WaitForSingleObject(info.hProcess, INFINITE);
|
||||||
|
// if GetExitCodeProcess(info.hProcess, &mut code as *mut _) == FALSE {
|
||||||
|
// return EXIT_FAILED_WAIT_PROG;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// code as i32
|
||||||
}
|
}
|
||||||
|
|||||||
130
src/runtime.rs
130
src/runtime.rs
@@ -1,6 +1,7 @@
|
|||||||
use crate::error::ShimError;
|
use crate::error::ShimError;
|
||||||
use crate::{ShimConfig, ShimLayout};
|
use crate::{ShimConfig, ShimLayout};
|
||||||
use mlua::{FromLua, Lua, StdLib, Table, Value};
|
use mlua::{FromLua, Lua, StdLib, Table, Value};
|
||||||
|
use std::ffi::OsStr;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::{env, fs};
|
use std::{env, fs};
|
||||||
/// 将 Path 转换为适合 Lua 使用的安全字符串路径
|
/// 将 Path 转换为适合 Lua 使用的安全字符串路径
|
||||||
@@ -36,9 +37,36 @@ impl LuaRuntime {
|
|||||||
.map_err(|e| ShimError::Environment(e.to_string()))?;
|
.map_err(|e| ShimError::Environment(e.to_string()))?;
|
||||||
|
|
||||||
// 2. 安全暴露 get_env 供配置读取环境变量
|
// 2. 安全暴露 get_env 供配置读取环境变量
|
||||||
|
// 返回按平台路径分隔符拆分后的段数组(自动剥离引号包裹),
|
||||||
|
// 便于 PATH 等列表变量直接嵌入数组:PATH = { prefix, get_env("PATH") }
|
||||||
let get_env = lua
|
let get_env = lua
|
||||||
.create_function(|_, key: String| -> mlua::Result<String> {
|
.create_function(|lua, key: String| -> mlua::Result<Table> {
|
||||||
Ok(env::var(key).unwrap_or_default())
|
// 缺失变量视为空字符串,拆分后得到空表(不贡献任何路径段)
|
||||||
|
let value = env::var_os(key).unwrap_or_default();
|
||||||
|
// 空输入返回空表;否则按平台分隔符拆分(split_paths 会剥离引号包裹)
|
||||||
|
if value.is_empty() {
|
||||||
|
return lua.create_table();
|
||||||
|
}
|
||||||
|
let table = lua.create_table()?;
|
||||||
|
for (i, p) in env::split_paths(&value).enumerate() {
|
||||||
|
// 3. 跨平台提取原始字节并转为 LuaString,保证 100% 无损
|
||||||
|
#[cfg(unix)]
|
||||||
|
let lua_str = {
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
lua.create_string(p.as_os_str().as_bytes())?
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
let lua_str = {
|
||||||
|
// Windows 路径是 UTF-16,转成字符串或保持其字节表达
|
||||||
|
let s = p.to_string_lossy();
|
||||||
|
lua.create_string(s.as_bytes())?
|
||||||
|
};
|
||||||
|
|
||||||
|
table.set(i + 1, lua_str)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(table)
|
||||||
})
|
})
|
||||||
.map_err(|e| ShimError::Environment(e.to_string()))?;
|
.map_err(|e| ShimError::Environment(e.to_string()))?;
|
||||||
|
|
||||||
@@ -96,7 +124,7 @@ impl LuaRuntime {
|
|||||||
/// 执行指定脚本文件,直接返回完整的 Lua Table
|
/// 执行指定脚本文件,直接返回完整的 Lua Table
|
||||||
pub fn eval_script<T: FromLua>(&self, path: impl AsRef<Path>) -> Result<T, ShimError> {
|
pub fn eval_script<T: FromLua>(&self, path: impl AsRef<Path>) -> Result<T, ShimError> {
|
||||||
let path = path.as_ref();
|
let path = path.as_ref();
|
||||||
|
// println!("path {:?}", path);
|
||||||
let bytes = fs::read(path)?;
|
let bytes = fs::read(path)?;
|
||||||
let code = String::from_utf8(bytes).map_err(|e| {
|
let code = String::from_utf8(bytes).map_err(|e| {
|
||||||
ShimError::InvalidConfig(format!(
|
ShimError::InvalidConfig(format!(
|
||||||
@@ -105,7 +133,7 @@ impl LuaRuntime {
|
|||||||
e.utf8_error()
|
e.utf8_error()
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
|
println!("code {:?}", code);
|
||||||
let chunk_name = format!("@{}", path.display());
|
let chunk_name = format!("@{}", path.display());
|
||||||
|
|
||||||
self.lua
|
self.lua
|
||||||
@@ -159,4 +187,98 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(matches!(value, Value::Boolean(true)));
|
assert!(matches!(value, Value::Boolean(true)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_env_returns_split_table() {
|
||||||
|
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||||
|
let value: Value = runtime
|
||||||
|
.lua
|
||||||
|
.load(r#"return get_env("PATH")"#)
|
||||||
|
.eval()
|
||||||
|
.unwrap();
|
||||||
|
let table = match value {
|
||||||
|
Value::Table(t) => t,
|
||||||
|
other => panic!("expected table, got {}", other.type_name()),
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
table.raw_len() >= 1,
|
||||||
|
"PATH should have at least one segment"
|
||||||
|
);
|
||||||
|
|
||||||
|
// split_paths 会剥离引号包裹,拆分段不应再含双引号
|
||||||
|
for i in 1..=table.raw_len() {
|
||||||
|
let seg: String = table.raw_get(i).unwrap();
|
||||||
|
assert!(
|
||||||
|
!seg.contains('"'),
|
||||||
|
"segment should not contain quote: {seg:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_env_missing_returns_empty_table() {
|
||||||
|
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||||
|
let value: Value = runtime
|
||||||
|
.lua
|
||||||
|
.load(r#"return get_env("RSHIM_TEST_NO_SUCH_VAR_12345")"#)
|
||||||
|
.eval()
|
||||||
|
.unwrap();
|
||||||
|
match value {
|
||||||
|
Value::Table(t) => assert_eq!(t.raw_len(), 0),
|
||||||
|
other => panic!("expected table, got {}", other.type_name()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn path_with_get_env_joins_without_quote_error() {
|
||||||
|
// 复现用户场景:PATH = { base_dir .. "/tools/numa", get_env("PATH") }
|
||||||
|
// 宿主 PATH 即使含双引号,也应拆分后正常拼接,而不是报错
|
||||||
|
let runtime = LuaRuntime::new(&test_layout()).unwrap();
|
||||||
|
let cfg: ShimConfig = runtime
|
||||||
|
.lua
|
||||||
|
.load(
|
||||||
|
r#"
|
||||||
|
return {
|
||||||
|
target = __SHIM_DIR__ .. "/tools/numa/numa.exe",
|
||||||
|
args = { "--help" },
|
||||||
|
env = {
|
||||||
|
PATH = { __SHIM_DIR__ .. "/tools/numa", get_env("PATH") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.eval()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let path = cfg.env.get("PATH").unwrap().to_str().unwrap();
|
||||||
|
let prefix = std::env::temp_dir()
|
||||||
|
.join("rshim-test-layout")
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/")
|
||||||
|
+ "/tools/numa;";
|
||||||
|
assert!(path.starts_with(&prefix), "unexpected PATH: {path}");
|
||||||
|
|
||||||
|
// 宿主 PATH 的段应被附加在配置前缀之后
|
||||||
|
let host = std::env::var("PATH").unwrap_or_default();
|
||||||
|
if !host.is_empty() {
|
||||||
|
let host_first = std::env::split_paths(&host)
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.into_owned();
|
||||||
|
assert!(
|
||||||
|
path.contains(&host_first),
|
||||||
|
"missing host PATH segment: {host_first}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 宿主 PATH 里引号包裹的畸形段(如 "D:\\...\\bin;")应被原样保留,
|
||||||
|
// 而不是让整个配置加载失败
|
||||||
|
if host.contains('"') {
|
||||||
|
assert!(
|
||||||
|
path.contains('"'),
|
||||||
|
"quoted host segments should be preserved"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ impl Shim {
|
|||||||
target_name: &str,
|
target_name: &str,
|
||||||
) -> Result<ShimConfig, ShimError> {
|
) -> Result<ShimConfig, ShimError> {
|
||||||
// 策略 1: 尝试加载全局配置文件 shims.lua
|
// 策略 1: 尝试加载全局配置文件 shims.lua
|
||||||
let global_config = paths.root_dir.join("shims.lua");
|
let global_config = paths.root_dir.join("rshim.lua");
|
||||||
if global_config.is_file() {
|
if global_config.is_file() {
|
||||||
trace!(path = %global_config.display(), "发现全局配置文件,尝试解析");
|
trace!(path = %global_config.display(), "发现全局配置文件,尝试解析");
|
||||||
let root_table: Table = runtime.eval_script(&global_config)?;
|
let root_table: Table = runtime.eval_script(&global_config)?;
|
||||||
|
|||||||
Reference in New Issue
Block a user