From 943fcf1721c445f570b02ca57791dfdb005b2d81 Mon Sep 17 00:00:00 2001 From: Franklin-Qi Date: Sat, 10 Oct 2026 10:05:00 +0800 Subject: [PATCH] pwcat: dump NSS password database via getpwent Add the pwcat helper used by gawk library routines such as passwd.awk. Print /etc/passwd-format lines from getpwent/endpwent, return ExitCode from main, and treat BrokenPipe as success. On platforms without a password database, print nothing and exit successfully. libc is needed because rustix/nix/uucore do not expose the password-database iterators. Closes #61 --- Cargo.lock | 1 + Cargo.toml | 7 +++ src/bin/pwcat.rs | 101 ++++++++++++++++++++++++++++++++++ tests/by-util/test_pwcat.rs | 104 ++++++++++++++++++++++++++++++++++++ tests/pwcat.rs | 27 ++++++++++ 5 files changed, 240 insertions(+) create mode 100644 src/bin/pwcat.rs create mode 100644 tests/by-util/test_pwcat.rs create mode 100644 tests/pwcat.rs diff --git a/Cargo.lock b/Cargo.lock index c503191..dd5c8ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1426,6 +1426,7 @@ dependencies = [ "either", "interpreter", "lexer", + "libc", "memchr", "parser", "thiserror", diff --git a/Cargo.toml b/Cargo.toml index 26f109c..f229d47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,13 @@ license.workspace = true name = "awk" path = "src/main.rs" +[[bin]] +name = "pwcat" +path = "src/bin/pwcat.rs" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [workspace.package] version = "0.1.0" license = "MIT OR Apache-2.0" diff --git a/src/bin/pwcat.rs b/src/bin/pwcat.rs new file mode 100644 index 0000000..cae1f5a --- /dev/null +++ b/src/bin/pwcat.rs @@ -0,0 +1,101 @@ +// This file is part of the uutils awk package. +// +// For the full copyright and license information, please view the LICENSE +// files that was distributed with this source code. + +//! Dump the password database in `/etc/passwd` format. +//! +//! Iterates the system password database with `getpwent()`/`endpwent()` so NSS +//! backends beyond local files (LDAP, SSSD, systemd-userdb, …) are included. +//! Intended for awk library helpers that need a portable passwd dump. +//! +//! Platforms without a password database get an empty dump and a successful exit. +//! +//! `nix`/`rustix`/`uucore::entries` expose name/uid lookups only, not `getpwent` +//! iteration, so this helper uses a small `libc` FFI surface. + +#[cfg(unix)] +use std::io::{self, Write}; +use std::process::ExitCode; + +#[cfg(unix)] +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(err) if err.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS, + Err(err) => { + let _ = writeln!(io::stderr(), "pwcat: {err}"); + ExitCode::FAILURE + } + } +} + +#[cfg(not(unix))] +fn main() -> ExitCode { + ExitCode::SUCCESS +} + +#[cfg(unix)] +fn run() -> io::Result<()> { + struct EndPwent; + + impl Drop for EndPwent { + fn drop(&mut self) { + // SAFETY: pairs with `setpwent` below; `pwcat` is single-threaded. + unsafe { + libc::endpwent(); + } + } + } + + let mut out = io::stdout().lock(); + + // SAFETY: `getpwent`/`setpwent`/`endpwent` share process-global state and are + // not thread-safe. `pwcat` is a single-threaded helper, so exclusive use is OK. + unsafe { + libc::setpwent(); + } + let _end = EndPwent; + + loop { + // SAFETY: see note above; pointer is only used while non-null and before + // the next `getpwent`/`endpwent` call. + let passwd = unsafe { libc::getpwent() }; + if passwd.is_null() { + break; + } + // SAFETY: `getpwent` returned a non-null pointer to a valid `passwd`. + let passwd = unsafe { &*passwd }; + + write_field(&mut out, passwd.pw_name)?; + out.write_all(b":")?; + write_field_or_star(&mut out, passwd.pw_passwd)?; + write!(out, ":{}:{}:", passwd.pw_uid, passwd.pw_gid)?; + write_field(&mut out, passwd.pw_gecos)?; + out.write_all(b":")?; + write_field(&mut out, passwd.pw_dir)?; + out.write_all(b":")?; + write_field(&mut out, passwd.pw_shell)?; + out.write_all(b"\n")?; + } + + Ok(()) +} + +#[cfg(unix)] +fn write_field(out: &mut impl Write, ptr: *const libc::c_char) -> io::Result<()> { + if ptr.is_null() { + return Ok(()); + } + // SAFETY: caller guarantees a NUL-terminated C string when non-null. + let bytes = unsafe { std::ffi::CStr::from_ptr(ptr) }.to_bytes(); + out.write_all(bytes) +} + +#[cfg(unix)] +fn write_field_or_star(out: &mut impl Write, ptr: *const libc::c_char) -> io::Result<()> { + if ptr.is_null() { + return out.write_all(b"*"); + } + write_field(out, ptr) +} diff --git a/tests/by-util/test_pwcat.rs b/tests/by-util/test_pwcat.rs new file mode 100644 index 0000000..cf72cc7 --- /dev/null +++ b/tests/by-util/test_pwcat.rs @@ -0,0 +1,104 @@ +// This file is part of the uutils awk package. +// +// For the full copyright and license information, please view the LICENSE +// files that was distributed with this source code. + +use std::process::{Command, Stdio}; + +use crate::{TESTS_BINARY, ucmd}; + +#[cfg_attr( + not(target_os = "linux"), + ignore = "pwcat tests require Linux NSS via getent" +)] +#[test] +fn pwcat_outputs_passwd_database_format() { + let result = ucmd().succeeds(); + let stdout = result.stdout_str(); + + assert!( + !stdout.is_empty(), + "pwcat produced no output; password database may be unavailable in this environment" + ); + + for line in stdout.lines().filter(|line| !line.is_empty()) { + let fields: Vec<&str> = line.split(':').collect(); + assert_eq!( + fields.len(), + 7, + "expected 7 colon-separated fields in line: {line}" + ); + assert!( + fields[2].chars().all(|ch| ch.is_ascii_digit()), + "expected numeric uid in line: {line}" + ); + assert!( + fields[3].chars().all(|ch| ch.is_ascii_digit()), + "expected numeric gid in line: {line}" + ); + } +} + +/// `pwcat` must match `getent passwd` so awk helpers that consume NSS dumps see +/// the same colon-separated records. +#[cfg_attr( + not(target_os = "linux"), + ignore = "pwcat tests require Linux NSS via getent" +)] +#[test] +fn pwcat_matches_getent_passwd() { + let getent = Command::new("getent") + .arg("passwd") + .output() + .expect("failed to spawn getent; install it or skip this host explicitly"); + assert!( + getent.status.success(), + "getent passwd is required for this test (exit {:?}): {}", + getent.status.code(), + String::from_utf8_lossy(&getent.stderr) + ); + + let pwcat = ucmd().succeeds(); + assert_eq!( + getent.stdout.as_slice(), + pwcat.stdout(), + "pwcat output should match getent passwd" + ); +} + +/// Force `EPIPE` by letting `head` close after one byte (closing an unread pipe +/// immediately can race if the whole dump fits in the pipe buffer). +#[cfg_attr( + not(target_os = "linux"), + ignore = "pwcat tests require Linux NSS via getent" +)] +#[test] +fn pwcat_ignores_broken_pipe() { + let mut head = Command::new("head") + .args(["-c", "1"]) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("failed to spawn head; install coreutils or skip this host explicitly"); + + let mut child = Command::new(TESTS_BINARY) + .stdout(head.stdin.take().expect("head stdin piped")) + .stderr(Stdio::piped()) + .spawn() + .expect("failed to spawn pwcat"); + + let status = child.wait().expect("failed to wait for pwcat"); + let _ = head.wait(); + + assert!( + status.success(), + "pwcat should treat broken pipe as success, got {status}" + ); +} + +#[cfg(not(unix))] +#[test] +fn pwcat_without_passwd_database_prints_nothing_and_succeeds() { + ucmd().succeeds().no_output(); +} diff --git a/tests/pwcat.rs b/tests/pwcat.rs new file mode 100644 index 0000000..0acb9d7 --- /dev/null +++ b/tests/pwcat.rs @@ -0,0 +1,27 @@ +// This file is part of the uutils awk package. +// +// For the full copyright and license information, please view the LICENSE +// files that was distributed with this source code. + +use std::env; + +use uutests::util::TestScenario; + +pub const TESTS_BINARY: &str = env!("CARGO_BIN_EXE_pwcat"); + +#[ctor::ctor(unsafe)] +fn init() { + unsafe { + env::set_var("UUTESTS_BINARY_PATH", TESTS_BINARY); + env::remove_var("UUTESTS_UTIL_NAME"); + env::set_var("UUTESTS_UTIL_NAME", ""); + env::set_var("UUTILS_MULTICALL", "0"); + } +} + +fn ucmd() -> uutests::util::UCommand { + TestScenario::new("pwcat").cmd(TESTS_BINARY) +} + +#[path = "by-util/test_pwcat.rs"] +mod test_pwcat;