Compare commits

...

6 Commits

3 changed files with 421 additions and 143 deletions
Generated
+42 -115
View File
@@ -4,9 +4,9 @@ version = 4
[[package]]
name = "anstream"
version = "0.6.21"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
@@ -25,9 +25,9 @@ checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
@@ -118,9 +118,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "clap"
version = "4.5.60"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a"
checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
dependencies = [
"clap_builder",
"clap_derive",
@@ -128,9 +128,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.60"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstream",
"anstyle",
@@ -140,18 +140,18 @@ dependencies = [
[[package]]
name = "clap_complete"
version = "4.5.66"
version = "4.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c757a3b7e39161a4e56f9365141ada2a6c915a8622c408ab6bb4b5d047371031"
checksum = "e0a7a9bfdb35811f9e59832f0f05975114d2251b415fb534108e6f34060fd772"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.5.55"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5"
checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
dependencies = [
"heck",
"proc-macro2",
@@ -167,9 +167,9 @@ checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831"
[[package]]
name = "clap_mangen"
version = "0.2.31"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ea63a92086df93893164221ad4f24142086d535b3a0957b9b9bea2dc86301"
checksum = "d82842b45bf9f6a3be090dd860095ac30728042c08e0d6261ca7259b5d850f07"
dependencies = [
"clap",
"roff",
@@ -183,9 +183,9 @@ checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "core-foundation"
version = "0.9.4"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
@@ -215,7 +215,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -603,9 +603,9 @@ dependencies = [
[[package]]
name = "native-tls"
version = "0.2.14"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e"
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
dependencies = [
"libc",
"log",
@@ -658,15 +658,15 @@ dependencies = [
[[package]]
name = "openssl-probe"
version = "0.1.6"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.111"
version = "0.9.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"
checksum = "f28a22dc7140cda5f096e5e7724a6962ca81a7f8bfd2979f9b18c11af56318c4"
dependencies = [
"cc",
"libc",
@@ -718,9 +718,9 @@ dependencies = [
[[package]]
name = "quote"
version = "1.0.44"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
@@ -733,9 +733,9 @@ checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "reqwest"
version = "0.13.2"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801"
checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
dependencies = [
"base64",
"bytes",
@@ -768,9 +768,9 @@ dependencies = [
[[package]]
name = "roff"
version = "0.2.2"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88f8660c1ff60292143c98d08fc6e2f654d722db50410e3f3797d40baaf9d8f3"
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
[[package]]
name = "rustix"
@@ -782,7 +782,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -811,9 +811,9 @@ dependencies = [
[[package]]
name = "security-framework"
version = "2.11.1"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags",
"core-foundation",
@@ -943,7 +943,7 @@ dependencies = [
"getrandom",
"once_cell",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1185,22 +1185,13 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
"windows-targets",
]
[[package]]
@@ -1212,22 +1203,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
@@ -1235,106 +1210,58 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link",
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm 0.53.1",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
"windows_x86_64_msvc 0.53.1",
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
+4 -4
View File
@@ -6,10 +6,10 @@ edition = "2024"
[dependencies]
anyhow = "1.0.102"
base64 = "0.22.1"
clap = { version = "4.5.60", features = ["derive"] }
clap_complete = "4.5.66"
clap_mangen = "0.2.31"
reqwest = { version = "0.13.2", default-features = false, features = ["blocking", "native-tls"] }
clap = { version = "4.6.1", features = ["derive"] }
clap_complete = "4.6.5"
clap_mangen = "0.3.0"
reqwest = { version = "0.13.4", default-features = false, features = ["blocking", "native-tls"] }
[lints.rust]
warnings = "deny"
+375 -24
View File
@@ -1,10 +1,10 @@
use anyhow::{Context, Result, bail};
use anyhow::{Context, Result, anyhow, bail};
use base64::Engine;
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use std::collections::{BTreeMap, HashMap};
use std::ffi::OsStr;
use std::fs;
use std::io::Write;
use std::io::{ErrorKind, Write};
#[cfg(unix)]
use std::os::unix::fs::{PermissionsExt, symlink};
use std::path::{Path, PathBuf};
@@ -22,6 +22,14 @@ const DEFAULT_JAVA_CACERTS_LINK: &str = "/etc/ssl/certs/java/cacerts";
const DEFAULT_PKI_TLS_CA_BUNDLE_CRT_LINK: &str = "/etc/pki/tls/certs/ca-bundle.crt";
const DEFAULT_PKI_TLS_CA_BUNDLE_TRUST_CRT_LINK: &str = "/etc/pki/tls/certs/ca-bundle.trust.crt";
const DEFAULT_PKI_TLS_JAVA_CACERTS_LINK: &str = "/etc/pki/tls/java/cacerts";
const TARGET_COMMAND_FALLBACK_DIRS: &[&str] = &[
"/usr/local/sbin",
"/usr/local/bin",
"/usr/sbin",
"/usr/bin",
"/sbin",
"/bin",
];
const DEFAULT_CERTDATA_URL: &str =
"https://hg.mozilla.org/projects/nss/raw-file/tip/lib/ckfw/builtins/certdata.txt";
const DEFAULT_CERTDATA_OUTPUT: &str = "certdata.txt";
@@ -760,7 +768,7 @@ fn run_certdata_fetch(args: CertdataFetchArgs) -> Result<()> {
fn http_get_text(client: &reqwest::blocking::Client, url: &str) -> Result<String> {
let response = match client.get(url).send() {
Ok(response) => response,
Err(err) if is_mozilla_hg_url(url) => {
Err(_err) if is_mozilla_hg_url(url) => {
println!("reqwest fetch failed for Mozilla hg URL; retrying via openssl.");
return openssl_https_get_text(url);
}
@@ -803,19 +811,11 @@ fn openssl_https_get_text(url: &str) -> Result<String> {
let bootstrap_ca_path = write_bootstrap_ca_tempfile()?;
let result = (|| {
let mut cmd = Command::new("openssl");
cmd.args([
"s_client",
"-quiet",
"-verify_return_error",
"-verifyCAfile",
bootstrap_ca_path.to_str().unwrap_or(""),
"-connect",
&format!("{host}:{port}"),
"-servername",
host,
]);
cmd.args(openssl_s_client_args(&bootstrap_ca_path, host, port));
if Path::new(DEFAULT_SSL_CERTS_DIR).is_dir() {
cmd.args(["-verifyCApath", DEFAULT_SSL_CERTS_DIR]);
cmd.args(openssl_s_client_capath_args(Path::new(
DEFAULT_SSL_CERTS_DIR,
)));
}
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -851,6 +851,24 @@ fn openssl_https_get_text(url: &str) -> Result<String> {
result
}
fn openssl_s_client_args(bootstrap_ca_path: &Path, host: &str, port: u16) -> Vec<String> {
vec![
"s_client".to_string(),
"-quiet".to_string(),
"-verify_return_error".to_string(),
"-CAfile".to_string(),
bootstrap_ca_path.display().to_string(),
"-connect".to_string(),
format!("{host}:{port}"),
"-servername".to_string(),
host.to_string(),
]
}
fn openssl_s_client_capath_args(ca_path: &Path) -> Vec<String> {
vec!["-CApath".to_string(), ca_path.display().to_string()]
}
fn write_bootstrap_ca_tempfile() -> Result<PathBuf> {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -2063,19 +2081,22 @@ fn run_target_command(
dry_run: bool,
envs: &[(&str, &str)],
) -> Result<()> {
let resolved_program = resolve_target_program(root, program);
let resolved_program_display = resolved_program.display().to_string();
if dry_run {
print_command_preview(root, program, args, envs);
print_command_preview(root, &resolved_program_display, args, envs);
return Ok(());
}
// Execute directly on the host or via chroot for image builds.
let mut cmd = if is_root_fs(root) {
let mut cmd = Command::new(program);
let mut cmd = Command::new(&resolved_program);
cmd.args(args);
cmd
} else {
let mut cmd = Command::new("chroot");
cmd.arg(root).arg(program).args(args);
cmd.arg(root).arg(&resolved_program).args(args);
cmd
};
@@ -2084,12 +2105,12 @@ fn run_target_command(
cmd.env(k, v);
}
let output = cmd.output().with_context(|| {
if is_root_fs(root) {
format!("failed to execute `{}`", program)
} else {
format!("failed to execute `chroot {} {}`", root.display(), program)
}
// `Command::output()` defaults stdin to `/dev/null`. Minimal chroots may
// not have device nodes yet, so inherit stdin while still capturing output.
cmd.stdin(Stdio::inherit());
let output = cmd.output().map_err(|err| {
command_spawn_error(root, &resolved_program, &resolved_program_display, err)
})?;
if output.status.success() {
@@ -2128,6 +2149,241 @@ fn run_target_command(
);
}
fn command_spawn_error(
root: &Path,
resolved_program: &Path,
resolved_program_display: &str,
err: std::io::Error,
) -> anyhow::Error {
let mut message = if is_root_fs(root) {
format!("failed to execute `{resolved_program_display}`: {err}")
} else {
format!(
"failed to execute `chroot {} {}`: {err}",
root.display(),
resolved_program_display
)
};
if err.kind() == ErrorKind::NotFound {
message.push_str(&exec_not_found_diagnostics(root, resolved_program));
}
anyhow!(message)
}
fn exec_not_found_diagnostics(root: &Path, resolved_program: &Path) -> String {
let program_host_path = path_in_root(root, resolved_program);
let mut details = vec![
String::new(),
"exec diagnostics for ENOENT:".to_string(),
format!(" target program path: {}", resolved_program.display()),
format!(" host-visible path: {}", program_host_path.display()),
];
match fs::symlink_metadata(&program_host_path) {
Ok(meta) => {
details.push(format!(
" target exists: yes (mode {:o}, {} bytes)",
meta.permissions().mode() & 0o7777,
meta.len()
));
}
Err(stat_err) => {
details.push(format!(" target exists: no ({stat_err})"));
return details.join("\n");
}
}
match fs::read(&program_host_path) {
Ok(bytes) => {
if let Some(interpreter) = shebang_interpreter(&bytes) {
details.push(format!(" script interpreter: {interpreter}"));
details.push(format!(
" script interpreter exists: {}",
path_existence_description(root, Path::new(&interpreter))
));
} else if is_elf(&bytes) {
details.push(" file format: ELF".to_string());
match elf_interpreter(&bytes) {
Some(interpreter) => {
details.push(format!(" ELF interpreter: {interpreter}"));
details.push(format!(
" ELF interpreter exists: {}",
path_existence_description(root, Path::new(&interpreter))
));
}
None => details.push(" ELF interpreter: none found".to_string()),
}
} else {
details.push(" file format: not ELF and no shebang".to_string());
}
}
Err(read_err) => details.push(format!(" failed to read target: {read_err}")),
}
details.join("\n")
}
fn path_existence_description(root: &Path, target_path: &Path) -> String {
if !target_path.is_absolute() {
return "not checked (interpreter path is not absolute)".to_string();
}
let host_path = path_in_root(root, target_path);
match fs::symlink_metadata(&host_path) {
Ok(meta) => format!(
"yes at {} (mode {:o}, {} bytes)",
host_path.display(),
meta.permissions().mode() & 0o7777,
meta.len()
),
Err(err) => format!("no at {} ({err})", host_path.display()),
}
}
fn shebang_interpreter(bytes: &[u8]) -> Option<String> {
if !bytes.starts_with(b"#!") {
return None;
}
let line_end = bytes
.iter()
.position(|b| *b == b'\n')
.unwrap_or(bytes.len());
let line = std::str::from_utf8(&bytes[2..line_end]).ok()?.trim();
let interpreter = line.split_whitespace().next()?;
Some(interpreter.to_string())
}
fn is_elf(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x7fELF")
}
fn elf_interpreter(bytes: &[u8]) -> Option<String> {
if !is_elf(bytes) || bytes.len() < 16 {
return None;
}
let class = bytes[4];
let data = bytes[5];
let little_endian = match data {
1 => true,
2 => false,
_ => return None,
};
let (phoff, phentsize, phnum) = match class {
1 => (
read_u32(bytes, 28, little_endian)? as usize,
read_u16(bytes, 42, little_endian)? as usize,
read_u16(bytes, 44, little_endian)? as usize,
),
2 => (
read_u64(bytes, 32, little_endian)? as usize,
read_u16(bytes, 54, little_endian)? as usize,
read_u16(bytes, 56, little_endian)? as usize,
),
_ => return None,
};
for index in 0..phnum {
let offset = phoff.checked_add(index.checked_mul(phentsize)?)?;
let header = bytes.get(offset..offset.checked_add(phentsize)?)?;
let p_type = read_u32(header, 0, little_endian)?;
if p_type != 3 {
continue;
}
let (interp_offset, interp_size) = match class {
1 => (
read_u32(header, 4, little_endian)? as usize,
read_u32(header, 16, little_endian)? as usize,
),
2 => (
read_u64(header, 8, little_endian)? as usize,
read_u64(header, 32, little_endian)? as usize,
),
_ => return None,
};
let interp_end = interp_offset.checked_add(interp_size)?;
let raw = bytes.get(interp_offset..interp_end)?;
let nul = raw.iter().position(|b| *b == 0).unwrap_or(raw.len());
return std::str::from_utf8(&raw[..nul]).ok().map(ToOwned::to_owned);
}
None
}
fn read_u16(bytes: &[u8], offset: usize, little_endian: bool) -> Option<u16> {
let raw: [u8; 2] = bytes.get(offset..offset.checked_add(2)?)?.try_into().ok()?;
Some(if little_endian {
u16::from_le_bytes(raw)
} else {
u16::from_be_bytes(raw)
})
}
fn read_u32(bytes: &[u8], offset: usize, little_endian: bool) -> Option<u32> {
let raw: [u8; 4] = bytes.get(offset..offset.checked_add(4)?)?.try_into().ok()?;
Some(if little_endian {
u32::from_le_bytes(raw)
} else {
u32::from_be_bytes(raw)
})
}
fn read_u64(bytes: &[u8], offset: usize, little_endian: bool) -> Option<u64> {
let raw: [u8; 8] = bytes.get(offset..offset.checked_add(8)?)?.try_into().ok()?;
Some(if little_endian {
u64::from_le_bytes(raw)
} else {
u64::from_be_bytes(raw)
})
}
fn resolve_target_program(root: &Path, program: &str) -> PathBuf {
let path_env = std::env::var_os("PATH");
resolve_target_program_with_path(root, program, path_env.as_deref())
}
fn resolve_target_program_with_path(
root: &Path,
program: &str,
path_env: Option<&OsStr>,
) -> PathBuf {
if program.contains('/') {
return PathBuf::from(program);
}
for candidate in target_command_search_candidates(program, path_env) {
if path_in_root(root, &candidate).exists() {
return candidate;
}
}
PathBuf::from(program)
}
fn target_command_search_candidates(program: &str, path_env: Option<&OsStr>) -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Some(path_env) = path_env {
for dir in std::env::split_paths(path_env).filter(|dir| dir.is_absolute()) {
candidates.push(dir.join(program));
}
}
for dir in TARGET_COMMAND_FALLBACK_DIRS {
let candidate = Path::new(dir).join(program);
if !candidates.iter().any(|existing| existing == &candidate) {
candidates.push(candidate);
}
}
candidates
}
fn print_command_preview(root: &Path, program: &str, args: &[String], envs: &[(&str, &str)]) {
// Keep dry-run output close to the real shell command for easier debugging.
let env_prefix = envs
@@ -2268,6 +2524,86 @@ CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
assert!(!is_root_fs(Path::new("/mnt/rootfs")));
}
#[test]
fn target_command_candidates_use_absolute_path_entries_and_fallbacks() {
let candidates = target_command_search_candidates(
"trust",
Some(std::ffi::OsStr::new("/custom/bin:relative:/usr/bin")),
);
assert_eq!(candidates[0], PathBuf::from("/custom/bin/trust"));
assert_eq!(candidates[1], PathBuf::from("/usr/bin/trust"));
assert!(candidates.contains(&PathBuf::from("/bin/trust")));
assert!(!candidates.contains(&PathBuf::from("relative/trust")));
}
#[test]
fn resolve_target_program_finds_binary_inside_selected_root() {
let root = unique_test_dir("target-command-root");
let trust_host_path = root.join("custom/bin/trust");
fs::create_dir_all(trust_host_path.parent().unwrap()).unwrap();
fs::write(&trust_host_path, b"").unwrap();
let resolved = resolve_target_program_with_path(
&root,
"trust",
Some(std::ffi::OsStr::new("/custom/bin")),
);
fs::remove_dir_all(&root).unwrap();
assert_eq!(resolved, PathBuf::from("/custom/bin/trust"));
}
#[test]
fn resolve_target_program_leaves_missing_program_unqualified() {
let root = unique_test_dir("target-command-missing");
fs::create_dir_all(&root).unwrap();
let resolved =
resolve_target_program_with_path(&root, "missing-tool", Some(std::ffi::OsStr::new("")));
fs::remove_dir_all(&root).unwrap();
assert_eq!(resolved, PathBuf::from("missing-tool"));
}
#[test]
fn shebang_interpreter_reads_first_command() {
let script = b"#!/usr/bin/env sh\nexit 0\n";
assert_eq!(shebang_interpreter(script).as_deref(), Some("/usr/bin/env"));
}
#[test]
fn elf_interpreter_reads_64_bit_pt_interp() {
let interpreter = b"/lib/ld-musl-x86_64.so.1\0";
let mut elf = vec![0u8; 160];
elf[0..4].copy_from_slice(b"\x7fELF");
elf[4] = 2; // 64-bit
elf[5] = 1; // little-endian
elf[32..40].copy_from_slice(&64u64.to_le_bytes()); // e_phoff
elf[54..56].copy_from_slice(&56u16.to_le_bytes()); // e_phentsize
elf[56..58].copy_from_slice(&1u16.to_le_bytes()); // e_phnum
elf[64..68].copy_from_slice(&3u32.to_le_bytes()); // PT_INTERP
elf[72..80].copy_from_slice(&128u64.to_le_bytes()); // p_offset
elf[96..104].copy_from_slice(&(interpreter.len() as u64).to_le_bytes()); // p_filesz
elf[128..128 + interpreter.len()].copy_from_slice(interpreter);
assert_eq!(
elf_interpreter(&elf).as_deref(),
Some("/lib/ld-musl-x86_64.so.1")
);
}
fn unique_test_dir(name: &str) -> PathBuf {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
std::env::temp_dir().join(format!("ca-certs-{name}-{}-{nonce}", std::process::id()))
}
#[test]
fn certdata_parser_extracts_revision_and_objects() {
let doc = parse_certdata(SAMPLE_CERTDATA).unwrap();
@@ -2358,6 +2694,21 @@ CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
assert!(out.contains("BEGINDATA"));
}
#[test]
fn openssl_s_client_args_use_portable_ca_file_flag() {
let args = openssl_s_client_args(Path::new("/tmp/bootstrap-ca.pem"), "hg.mozilla.org", 443);
assert!(args.contains(&"-CAfile".to_string()));
assert!(!args.contains(&"-verifyCAfile".to_string()));
assert!(!args.contains(&"-verifyCApath".to_string()));
}
#[test]
fn openssl_s_client_capath_args_use_libressl_portable_flag() {
let args = openssl_s_client_capath_args(Path::new("/etc/ssl/certs"));
assert_eq!(args, vec!["-CApath", "/etc/ssl/certs"]);
assert!(!args.contains(&"-verifyCApath".to_string()));
}
#[test]
fn decode_certdata_octal_multiline_decodes_bytes() {
let lines = vec![r"\101\102".to_string(), r"\103".to_string()];