别这样,因为你只是在储存
u32
在
VEC
,可以通过相应地调整大小和容量来避免使用虚拟值填充它:
extern crate libc;
#[derive(Debug)]
struct Info {
guid: u32,
ruid: u32,
groups: Vec<u32>,
num_groups: usize,
}
fn example(guid: u32) -> Info {
unsafe {
let ruid = libc::getuid();
if -1 == libc::seteuid(guid) {
panic!("seteuid")
}
let mut groups = Vec::new();
let mut attempts = 0;
loop {
let num_groups = libc::getgroups(groups.capacity() as i32, groups.as_mut_ptr());
if -1 == num_groups {
panic!("getgroups")
}
let num_groups = num_groups as usize;
if num_groups <= groups.capacity() {
groups.set_len(num_groups);
return Info {
guid,
ruid,
groups,
num_groups,
};
}
groups.reserve_exact(num_groups);
attempts += 1;
if attempts >= 3 {
panic!("Unstable amount of groups")
}
}
}
}
fn main() {
println!("{:?}", example(unsafe { libc::getuid() }));
}
然而,我不会重写所有这些,我会依赖现有的工作。这个
nix crate
提供漂亮的包装:
extern crate nix;
use nix::unistd::{self, Uid};
use std::u32;
fn example(guid: Uid) -> nix::Result<()> {
let ruid = unistd::getuid();
let no_change = Uid::from_raw(u32::MAX);
unistd::setresuid(no_change, guid, no_change)?;
let groups = nix::unistd::getgroups()?;
println!(
"real user id {} as user id {}, as user groups {:?}",
ruid, guid, groups
);
Ok(())
}
fn main() {
println!("{:?}", example(Uid::current()));
}