Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 10 additions & 19 deletions src/uu/ls/src/colors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,27 +534,18 @@ pub(crate) fn color_name(
target_symlink: Option<&PathData>,
wrap: bool,
) -> OsString {
// Check if the file has capabilities
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
))]
// Skip checking capabilities if LS_COLORS=ca=:; reuse PathData's
// cached xattr summary so this does not add a second llistxattr.
// Unsupported platforms stub `has_security_capability` to false.
if style_manager
.colors
.has_explicit_style_for(Indicator::Capabilities)
&& path.has_security_capability()
{
// Skip checking capabilities if LS_COLORS=ca=:
let has_capabilities = style_manager
let capabilities = style_manager
.colors
.has_explicit_style_for(Indicator::Capabilities)
&& uucore::fsxattr::has_security_cap_acl(&path.p_buf, path.must_dereference);

// If the file has capabilities, use a specific style for `ca` (capabilities)
if has_capabilities {
let capabilities = style_manager
.colors
.style_for_indicator(Indicator::Capabilities);
return style_manager.apply_style(capabilities, Some(path), name, wrap);
}
.style_for_indicator(Indicator::Capabilities);
return style_manager.apply_style(capabilities, Some(path), name, wrap);
}

if target_symlink.is_none()
Expand Down
43 changes: 2 additions & 41 deletions src/uu/ls/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,6 @@ use term_grid::{DEFAULT_SEPARATOR_SIZE, Direction, Filling, Grid, GridOptions};

#[cfg(unix)]
use uucore::entries;
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
))]
use uucore::fsxattr::has_acl;
#[cfg(unix)]
use uucore::libc::{dev_t, major, minor};
use uucore::{
Expand Down Expand Up @@ -970,22 +962,7 @@ fn display_item_long(
}

if let Some(md) = item.metadata() {
#[cfg(not(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
)))]
let is_acl_set = false;
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
))]
let is_acl_set = has_acl(item.path(), item.must_dereference);
let is_acl_set = item.has_acl();
state
.display_buf
.extend(display_permissions(md, true).as_bytes());
Expand Down Expand Up @@ -1406,23 +1383,7 @@ fn calculate_padding_collection(
// If any item has an ACL or non-trivial security context, widen
// the permissions column by one to reserve space for the `+`/`.`
// indicator.
#[cfg(not(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
)))]
let is_acl_set = false;
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
))]
let is_acl_set = has_acl(item.path(), item.must_dereference);
if context_len > 1 || is_acl_set {
if context_len > 1 || item.has_acl() {
padding_collections.permissions = PERMISSIONS_WIDTH + 1;
}

Expand Down
78 changes: 78 additions & 0 deletions src/uu/ls/src/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,15 @@ pub struct PathData<'a> {
// https://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
de: RefCell<Option<DirEntry>>,
security_context: OnceCell<Box<str>>,
// Shared across `-l` ACL/`+` checks and `--color` capability styling so
// each file only pays one `llistxattr`.
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
))]
xattr_summary: OnceCell<uucore::fsxattr::XattrSummary>,
// Name of the file - will be empty for . or ..
display_name: PathDataDisplayName<'a>,
// PathBuf that all above data corresponds to
Expand Down Expand Up @@ -890,6 +899,13 @@ impl<'a> PathData<'a> {
ft,
de,
security_context,
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
))]
xattr_summary: OnceCell::new(),
display_name,
p_buf,
must_dereference,
Expand All @@ -898,6 +914,68 @@ impl<'a> PathData<'a> {
}
}

/// Lists the xattrs on first use; later calls reuse the cached result.
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
))]
fn xattr_summary(&self) -> uucore::fsxattr::XattrSummary {
*self
.xattr_summary
.get_or_init(|| uucore::fsxattr::summarize_xattrs(&self.p_buf, self.must_dereference))
}

/// Whether this path has an ACL / `+` indicator.
pub(crate) fn has_acl(&self) -> bool {
#[cfg(target_os = "macos")]
{
uucore::fsxattr::has_acl(self.p_buf.as_ref(), self.must_dereference)
}
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
))]
{
self.xattr_summary().has_acl
}
#[cfg(not(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "macos",
target_os = "netbsd"
)))]
{
false
}
}

/// Whether this path has a `security.capability` xattr (color `ca` style).
pub(crate) fn has_security_capability(&self) -> bool {
#[cfg(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
))]
{
self.xattr_summary().has_capability
}
#[cfg(not(any(
target_os = "freebsd",
target_os = "hurd",
target_os = "linux",
target_os = "netbsd"
)))]
{
false
}
}

fn metadata(&self) -> Option<&Metadata> {
self.md
.get_or_init(|| {
Expand Down
2 changes: 1 addition & 1 deletion src/uucore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ extendedbigdecimal = ["bigdecimal", "num-traits"]
fast-inc = []
fs = ["dunce", "libc", "rustix/fs", "rustix/std", "windows-sys"]
fsext = ["libc", "windows-sys", "bstr", "wide"]
fsxattr = ["xattr", "itertools", "libc"]
fsxattr = ["xattr", "libc"]
hardware = []
lines = []
format = [
Expand Down
127 changes: 68 additions & 59 deletions src/uucore/src/lib/features/fsxattr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

//! Set of functions to manage xattr on files and dirs

use itertools::Itertools;
use rustc_hash::FxHashMap;
use std::ffi::{OsStr, OsString};
#[cfg(unix)]
Expand Down Expand Up @@ -241,6 +240,64 @@ pub fn apply_xattrs_fd_ignore_unsupported(
}
}

/// Summary of a single `listxattr` pass: whether a real ACL is present (the
/// `ls -l` `+` indicator) and whether `security.capability` is among them.
///
/// On macOS ACL detection uses a separate API; `ls` only caches this summary on
/// platforms where ACLs are exposed as xattrs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct XattrSummary {
pub has_acl: bool,
/// Linux file capabilities (`security.capability`); meaningful on Unix only.
#[cfg(unix)]
pub has_capability: bool,
}

/// List extended attributes once and derive the flags that `ls -l` / `--color`
/// need, so callers can share one `llistxattr` instead of issuing separate
/// scans for ACLs and capabilities.
pub fn summarize_xattrs<P: AsRef<Path>>(file: P, dereference: bool) -> XattrSummary {
let file = file.as_ref();
let attrs = if dereference {
xattr::list_deref(file)
} else {
xattr::list(file)
};

let Ok(list) = attrs else {
return XattrSummary::default();
};

let mut summary = XattrSummary::default();
#[cfg(not(target_os = "macos"))]
let mut has_nfs4_acl = false;
for name in list {
#[cfg(unix)]
if name.as_bytes() == b"security.capability" {
summary.has_capability = true;
}
// Match `has_acl`: only real ACL xattrs count, not e.g. selinux.
// macOS ACLs are not xattrs; PathData uses the ACL API there instead.
#[cfg(not(target_os = "macos"))]
{
if is_acl_xattr(&name) {
summary.has_acl = true;
}
has_nfs4_acl |= name == NFS4_ACL_XATTR;
}
}
#[cfg(not(target_os = "macos"))]
if !summary.has_acl && has_nfs4_acl {
let value = if dereference {
xattr::get_deref(file, NFS4_ACL_XATTR)
} else {
xattr::get(file, NFS4_ACL_XATTR)
};
summary.has_acl = matches!(value, Ok(Some(acl)) if nfs4_acl_is_nontrivial(&acl));
}
summary
}

/// Checks if a file has an Access Control List (ACL).
///
/// On macOS this asks the ACL API; elsewhere it looks at the file's extended
Expand All @@ -261,35 +318,8 @@ pub fn has_acl<P: AsRef<Path>>(file: P, dereference: bool) -> bool {
#[cfg(target_os = "macos")]
return macos_acl::has_extended_acl(file.as_ref(), dereference);

// don't use exacl here, it is doing more getxattr call then needed
#[cfg(not(target_os = "macos"))]
let attrs = if dereference {
xattr::list_deref(&file)
} else {
xattr::list(&file)
};

#[cfg(not(target_os = "macos"))]
{
let Ok(names) = attrs else { return false };
// Only ACL attributes count; other xattrs such as security.selinux don't.
let mut has_nfs4_acl = false;
for name in names {
if is_acl_xattr(&name) {
return true;
}
has_nfs4_acl |= name == NFS4_ACL_XATTR;
}
if !has_nfs4_acl {
return false;
}
let value = if dereference {
xattr::get_deref(&file, NFS4_ACL_XATTR)
} else {
xattr::get(&file, NFS4_ACL_XATTR)
};
matches!(value, Ok(Some(acl)) if nfs4_acl_is_nontrivial(&acl))
}
summarize_xattrs(file, dereference).has_acl
}

/// Whether `name` is an xattr that stores an ACL.
Expand Down Expand Up @@ -397,33 +427,6 @@ mod macos_acl {
}
}

/// Checks if a file has an Access Control List (ACL) named "security.capability" based on its extended attributes.
///
/// # Arguments
///
/// * `file` - A reference to the path of the file.
/// * `dereference` - Whether to inspect the target of a symlink instead of the link itself.
///
/// # Returns
///
/// `true` if the file has an extended attribute named "security.capability", `false` otherwise.
pub fn has_security_cap_acl<P: AsRef<Path>>(file: P, dereference: bool) -> bool {
// don't use exacl here, it is doing more getxattr call then needed
let attrs = if dereference {
xattr::list_deref(file)
} else {
xattr::list(file)
};

attrs.is_ok_and(|mut acl| {
#[cfg(unix)]
return acl.contains(OsStr::from_bytes(b"security.capability"));

#[cfg(not(unix))]
return false;
})
}

/// Returns the permissions bits of a file or directory which has Access Control List (ACL) entries based on its
/// extended attributes (Only works for linux)
///
Expand Down Expand Up @@ -690,19 +693,25 @@ mod tests {

// An unrelated xattr is not an ACL on any platform.
assert!(!has_acl(&file_path, true));
assert!(!has_security_cap_acl(&file_path, true));
let summary = summarize_xattrs(&file_path, true);
assert!(!summary.has_acl);
#[cfg(unix)]
assert!(!summary.has_capability);

// FreeBSD/NetBSD's xattr library does not support the "security" namespace
// (https://github.com/Stebalien/xattr/blob/master/src/sys/bsd.rs#L148).
// However, individual file systems might still implement additional namespaces according to
// https://man.freebsd.org/cgi/man.cgi?query=extattr&sektion=9&manpath=FreeBSD+14.3-RELEASE+and+Ports
#[cfg(not(any(target_os = "freebsd", target_os = "netbsd")))]
#[cfg(all(unix, not(any(target_os = "freebsd", target_os = "netbsd"))))]
{
let test_attr = "security.capability";
let test_value = b"";
xattr::set(&file_path, test_attr, test_value).unwrap();

assert!(has_security_cap_acl(&file_path, true));
let summary = summarize_xattrs(&file_path, true);
// Capability alone is not an ACL; only security.capability is set.
assert!(!summary.has_acl);
assert!(summary.has_capability);
}
}

Expand Down
Loading
Loading