增加 util::is_root()

Signed-off-by: Jia Chao <jiachao2130@126.com>
This commit is contained in:
Jia Chao 2024-08-14 14:31:08 +08:00
parent 0d56cda3b3
commit 56a0ff0090
2 changed files with 26 additions and 0 deletions

View File

@ -13,6 +13,7 @@ description = "A complex toolset that include various small functions."
[dependencies] [dependencies]
futures-util = { version = "0.3" } futures-util = { version = "0.3" }
indicatif = { version = "0.17" } indicatif = { version = "0.17" }
libc = { version = "0.2.155" }
path-absolutize = { version = "3" } path-absolutize = { version = "3" }
reqwest = { version = "0.12", features = ["stream"] } reqwest = { version = "0.12", features = ["stream"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

View File

@ -18,3 +18,28 @@ pub fn uuid() -> String {
// 将 UUID 转换为字符串并返回 // 将 UUID 转换为字符串并返回
uuid.to_string() uuid.to_string()
} }
/// 检查当前进程是否以 root 权限运行。
///
/// 在类 Unix 系统中用户标识符UID为 0 的用户是 `root` 用户。
/// 这个函数通过调用 `libc` 库中的 `geteuid` 函数来获取当前进程的
/// 有效用户IDEffective User ID, EUID。如果 EUID 为 0则表明
/// 当前用户是 root。
///
/// # 返回值
///
/// * `true` - 如果当前进程是以 root 权限运行EUID 为 0
/// * `false` - 如果当前进程不是以 root 权限运行。
///
/// # 安全性
///
/// 该函数是 `unsafe` 块的一部分,因为它调用了外部的 C 函数 `geteuid`。
/// 使用 `unsafe` 是因为 Rust 无法保证这个外部函数的安全性,需要开发者手动
/// 确保调用是安全的。
pub fn is_root() -> bool {
// 使用不安全的代码块来调用 libc 库中的 geteuid 函数,
// 获取当前进程的有效用户 ID (EUID)。
// 如果 EUID 为 0表示当前用户为 root返回 true
// 否则返回 false。
unsafe { libc::geteuid() == 0 }
}