shitbox/corebox/commands/chown/mod.rs

271 lines
7.9 KiB
Rust
Raw Permalink Normal View History

2023-01-20 12:08:04 -05:00
use super::{Cmd, Feedback};
2023-01-19 19:08:09 -05:00
use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command, ValueHint};
use shitbox::args;
2023-01-18 21:45:18 -05:00
use std::{
error::Error,
2023-01-19 19:08:09 -05:00
fs::File,
2023-01-18 21:45:18 -05:00
io,
os::{fd::AsRawFd, unix::prelude::MetadataExt},
path::PathBuf,
};
use walkdir::{DirEntry, WalkDir};
mod chgrp;
pub use chgrp::Chgrp;
#[derive(Debug)]
pub struct Chown;
impl Cmd for Chown {
fn cli(&self) -> clap::Command {
Command::new("chown")
.about("change file owner and group")
.author("Nathan Fisher")
.version(env!("CARGO_PKG_VERSION"))
.arg(
Arg::new("user")
.value_name("OWNER[:GROUP]")
.value_hint(ValueHint::Username)
.num_args(1)
.required(true),
)
.args(args())
.group(
ArgGroup::new("links")
.args(["cli-traverse", "full-traverse", "no-traverse"])
.requires("recursive")
.multiple(false),
)
}
fn run(&self, matches: &clap::ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
2023-01-19 19:08:09 -05:00
let recurse = Recurse::from_matches(matches);
let feedback = Feedback::from_matches(matches);
let (user, group) = if let Some(who) = matches.get_one::<String>("user") {
if let Some((u, g)) = who.split_once(':') {
2023-01-18 21:45:18 -05:00
let uid = pw::get_uid_for_name(u)
.ok_or(io::Error::new(io::ErrorKind::Other, "cannot get uid"))?;
let gid = pw::get_gid_for_groupname(g)
.ok_or(io::Error::new(io::ErrorKind::Other, "cannot get gid"))?;
2023-01-19 19:08:09 -05:00
(User { name: u, uid }, Some(Group { name: g, gid }))
} else {
2023-01-18 21:45:18 -05:00
let uid = pw::get_uid_for_name(who)
.ok_or(io::Error::new(io::ErrorKind::Other, "cannot get uid"))?;
2023-01-19 19:08:09 -05:00
(User { name: who, uid }, None)
}
} else {
return Err(Box::new(io::Error::new(
io::ErrorKind::Other,
"no user specified",
)));
};
if let Some(files) = matches.get_many::<String>("file") {
for f in files {
let action = Action {
path: PathBuf::from(f),
user: user.clone(),
group: group.clone(),
feedback,
};
2023-01-19 19:08:09 -05:00
if let Some(r) = recurse {
2023-02-20 23:00:35 -05:00
if action.path.is_dir()
&& action.path.is_symlink()
&& r.traversal != Traversal::NoLinks
{
2023-01-19 19:08:09 -05:00
action.recurse(recurse)?;
}
}
action.apply()?;
}
}
Ok(())
}
fn path(&self) -> Option<shitbox::Path> {
Some(shitbox::Path::Bin)
}
}
fn args() -> [Arg; 8] {
[
args::changes(),
args::verbose(),
args::recursive(),
Arg::new("cli-traverse")
.help("if a command line argument is a symbolic link to a directory, traverse it")
.short('H')
.action(ArgAction::SetTrue),
Arg::new("full-traverse")
.help("traverse every symbolic link encountered in a directory")
.short('L')
.action(ArgAction::SetTrue),
Arg::new("no-traverse")
.help("do not traverse any symbolic links (default)")
.short('P')
.action(ArgAction::SetTrue),
Arg::new("same-filesystem")
.help("do not cross filesystem boundaries (requires recursive)")
.short('s')
.requires("recursive")
.long("same-filesystem")
.action(ArgAction::SetTrue),
Arg::new("file")
.value_name("FILE")
.value_hint(ValueHint::AnyPath)
.num_args(1..)
.required(true),
]
}
#[derive(Clone, Copy, Debug, PartialEq)]
2023-02-20 23:00:35 -05:00
#[allow(clippy::enum_variant_names)]
enum Traversal {
CliLinks,
FullLinks,
NoLinks,
}
impl Traversal {
2023-01-19 19:08:09 -05:00
fn from_matches(matches: &ArgMatches) -> Self {
if matches.get_flag("full-traverse") {
Traversal::FullLinks
} else if matches.get_flag("cli-traverse") {
Self::CliLinks
} else {
Self::NoLinks
}
}
}
#[derive(Clone, Copy, Debug)]
struct Recurse {
traversal: Traversal,
same_filesystem: bool,
}
impl Recurse {
2023-01-19 19:08:09 -05:00
fn from_matches(matches: &ArgMatches) -> Option<Self> {
if matches.get_flag("recursive") {
Some(Self {
traversal: Traversal::from_matches(matches),
same_filesystem: matches.get_flag("same-filesystem"),
})
} else {
None
}
}
}
#[derive(Clone, Debug)]
2023-01-19 19:08:09 -05:00
struct User<'a> {
name: &'a str,
uid: u32,
}
#[derive(Clone, Debug)]
2023-01-19 19:08:09 -05:00
struct Group<'a> {
name: &'a str,
gid: u32,
}
#[derive(Debug)]
2023-01-19 19:08:09 -05:00
struct Action<'a> {
path: PathBuf,
2023-01-19 19:08:09 -05:00
user: User<'a>,
group: Option<Group<'a>>,
feedback: Option<Feedback>,
}
2023-01-19 19:08:09 -05:00
impl Action<'_> {
fn apply(&self) -> Result<(), Box<dyn Error>> {
let fd = File::open(&self.path)?;
let meta = fd.metadata()?;
let uid = meta.uid();
let gid = meta.gid();
unsafe {
2023-01-18 21:45:18 -05:00
if libc::fchown(
fd.as_raw_fd(),
self.user.uid,
self.group.as_ref().map(|x| x.gid).unwrap_or(gid),
) != 0
{
return Err(io::Error::last_os_error().into());
}
}
2023-01-19 19:08:09 -05:00
drop(fd);
if let Some(feedback) = self.feedback {
match feedback {
Feedback::Full => {
2023-01-18 21:45:18 -05:00
if self.user.uid != uid || self.group.as_ref().map(|x| x.gid) != Some(gid) {
2023-01-19 19:08:09 -05:00
self.display_changes(uid, gid)?;
} else {
2023-01-19 19:08:09 -05:00
self.display_retained();
}
}
Feedback::Changes => {
2023-01-18 21:45:18 -05:00
if self.user.uid != uid || self.group.as_ref().map(|x| x.gid) != Some(gid) {
2023-01-19 19:08:09 -05:00
self.display_changes(uid, gid)?;
}
2023-01-18 21:45:18 -05:00
}
}
}
Ok(())
}
2023-01-19 19:08:09 -05:00
fn display_changes(&self, uid: u32, gid: u32) -> Result<(), std::str::Utf8Error> {
let username = pw::get_username_for_uid(uid)?;
let groupname = pw::get_groupname_for_gid(gid)?;
if let Some(g) = &self.group {
println!(
"{} changed from {username}:{groupname} to {}:{}",
&self.path.display(),
&self.user.name,
&g.name
);
} else {
println!(
"{} changed from {username} to {}",
&self.path.display(),
&self.user.name
);
}
Ok(())
}
fn display_retained(&self) {
if let Some(g) = &self.group {
println!(
"{} retained as {}:{}",
&self.path.display(),
&self.user.name,
&g.name
);
} else {
println!("{} retained as {}", &self.path.display(), &self.user.name);
}
}
2023-02-20 23:00:35 -05:00
fn as_child(&self, entry: DirEntry) -> Result<Self, Box<dyn Error>> {
let path = entry.path().to_path_buf();
Ok(Self {
path,
user: self.user.clone(),
group: self.group.clone(),
feedback: self.feedback,
})
}
2023-01-19 19:08:09 -05:00
fn recurse(&self, recurse: Option<Recurse>) -> Result<(), Box<dyn Error>> {
let walker = WalkDir::new(&self.path)
2023-01-19 19:08:09 -05:00
.max_open(1)
.same_file_system(recurse.map_or(false, |x| x.same_filesystem))
2023-02-20 23:00:35 -05:00
.follow_links(recurse.map_or(false, |x| matches!(x.traversal, Traversal::FullLinks)));
for entry in walker {
let entry = entry?;
2023-02-20 23:00:35 -05:00
let action = self.as_child(entry)?;
action.apply()?;
}
Ok(())
}
}