feat(flash): expose root command and file primitives for stock boards
Add StockMethod::root_exec and StockMethod::root_put, with public wrappers next to the existing stock methods. root_exec runs a /bin/sh command line as root and returns combined output; root_put writes a payload at mode 0644 with parent directories created and supports multi-megabyte data. Existing install and restore paths are unchanged. Test coverage adds compile-level signature checks plus local path, quoting, and streamed-input tests; no test uses the network.
This commit is contained in:
@@ -149,6 +149,31 @@ pub trait StockMethod {
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError>;
|
||||
|
||||
/// Run `cmd` as root on a board running stock, over the network only, and
|
||||
/// return its combined standard output and standard error. `cmd` is a
|
||||
/// `/bin/sh` command line. A non-zero exit is an `Err` whose message is that
|
||||
/// combined output. `password` is the board's stock login password; `None`
|
||||
/// falls back to the configured board credential.
|
||||
fn root_exec(
|
||||
&self,
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
cmd: &str,
|
||||
) -> Result<String, StockError>;
|
||||
|
||||
/// Write `data` to `remote_path` as root on a board running stock, over the
|
||||
/// network only. Missing parent directories are created and the file is
|
||||
/// left mode 0644. The payload may be many megabytes; it is sent as a
|
||||
/// stream, not on a command line. `password` is the board's stock login
|
||||
/// password; `None` falls back to the configured board credential.
|
||||
fn root_put(
|
||||
&self,
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
data: &[u8],
|
||||
remote_path: &str,
|
||||
) -> Result<(), StockError>;
|
||||
|
||||
/// Update a board that already runs alkane to the `.afw`'s images, over the
|
||||
/// network only. Refuses a board that is not running alkane (a board on
|
||||
/// stock is installed with `install_from_stock`). The boot regions are not
|
||||
@@ -229,6 +254,26 @@ pub fn restore_to_stock(
|
||||
method().restore_to_stock(host, images, password)
|
||||
}
|
||||
|
||||
/// Run `cmd` as root on a board running stock (network-only), via the
|
||||
/// compiled-in method. `cmd` is a `/bin/sh` command line; the returned string
|
||||
/// is its combined output. A non-zero exit is an error whose message is that
|
||||
/// output.
|
||||
pub fn root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
|
||||
method().root_exec(host, password, cmd)
|
||||
}
|
||||
|
||||
/// Write `data` to `remote_path` as root on a board running stock
|
||||
/// (network-only), via the compiled-in method. Missing parent directories are
|
||||
/// created and the file is left mode 0644. Large payloads are streamed.
|
||||
pub fn root_put(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
data: &[u8],
|
||||
remote_path: &str,
|
||||
) -> Result<(), StockError> {
|
||||
method().root_put(host, password, data, remote_path)
|
||||
}
|
||||
|
||||
/// Check, over the network, that a Zynq board is up on alkane: the web page
|
||||
/// carries `marker` (case-insensitive) and SSH reports alkane with a kernel
|
||||
/// containing `kernel_version` (if non-empty). Retries until `timeout`.
|
||||
@@ -265,6 +310,8 @@ mod tests {
|
||||
let _: fn(&str, Option<&str>) -> Result<bool, StockError> = onboard_stock_backup_present;
|
||||
let _: fn(&str, Option<&str>, std::time::Duration) -> Result<(), StockError> =
|
||||
restore_from_onboard_backup;
|
||||
let _: fn(&str, Option<&str>, &str) -> Result<String, StockError> = root_exec;
|
||||
let _: fn(&str, Option<&str>, &[u8], &str) -> Result<(), StockError> = root_put;
|
||||
}
|
||||
|
||||
struct FakeMethod {
|
||||
@@ -291,6 +338,14 @@ mod tests {
|
||||
Err(StockError::NotImplemented)
|
||||
}
|
||||
|
||||
fn root_exec(&self, _: &str, _: Option<&str>, _: &str) -> Result<String, StockError> {
|
||||
Err(StockError::NotImplemented)
|
||||
}
|
||||
|
||||
fn root_put(&self, _: &str, _: Option<&str>, _: &[u8], _: &str) -> Result<(), StockError> {
|
||||
Err(StockError::NotImplemented)
|
||||
}
|
||||
|
||||
fn update_in_place(
|
||||
&self,
|
||||
_: &str,
|
||||
|
||||
@@ -614,6 +614,25 @@ fn run_command(
|
||||
} else {
|
||||
Stdio::null()
|
||||
});
|
||||
run_command_io(command, timeout, input)
|
||||
}
|
||||
|
||||
/// Run a command with a file as its standard input. The file is handed to the
|
||||
/// child directly, so a multi-megabyte payload is not copied through memory.
|
||||
fn run_command_stream(
|
||||
mut command: Command,
|
||||
timeout: Duration,
|
||||
input: fs::File,
|
||||
) -> Result<CmdResult, StockError> {
|
||||
command.stdin(Stdio::from(input));
|
||||
run_command_io(command, timeout, None)
|
||||
}
|
||||
|
||||
fn run_command_io(
|
||||
mut command: Command,
|
||||
timeout: Duration,
|
||||
input: Option<Vec<u8>>,
|
||||
) -> Result<CmdResult, StockError> {
|
||||
command.stdout(Stdio::piped());
|
||||
command.stderr(Stdio::piped());
|
||||
|
||||
@@ -787,6 +806,86 @@ fn ssh_push(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Quote one argument for a POSIX shell. A single-quoted string is literal, so
|
||||
// the only character needing work is the quote itself.
|
||||
fn shell_quote(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('\'');
|
||||
for c in value.chars() {
|
||||
if c == '\'' {
|
||||
out.push_str("'\\''");
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.push('\'');
|
||||
out
|
||||
}
|
||||
|
||||
// The combined output of a completed command: standard output followed by
|
||||
// standard error, joined with a newline if both are non-empty.
|
||||
fn command_output(result: &CmdResult) -> String {
|
||||
let mut out = text(&result.stdout);
|
||||
let error = text(&result.stderr);
|
||||
if !error.is_empty() {
|
||||
if !out.is_empty() && !out.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&error);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn command_exit_error(status: i32, output: String) -> StockError {
|
||||
if output.is_empty() {
|
||||
StockError::Method(format!("command exited with status {status}"))
|
||||
} else {
|
||||
StockError::Method(output)
|
||||
}
|
||||
}
|
||||
|
||||
// A command that reached the board and exited non-zero. Authentication and
|
||||
// transport failures are classified as such; everything else carries the
|
||||
// command's output.
|
||||
fn command_failure(result: &CmdResult) -> StockError {
|
||||
if result.timed_out {
|
||||
return StockError::Network("target did not respond".into());
|
||||
}
|
||||
let lower = text(&result.stderr).to_lowercase();
|
||||
let transport = lower.contains("permission denied")
|
||||
|| lower.contains("authentication failed")
|
||||
|| lower.contains("no supported authentication")
|
||||
|| lower.contains("connection refused")
|
||||
|| lower.contains("connection reset")
|
||||
|| lower.contains("connection closed")
|
||||
|| lower.contains("broken pipe")
|
||||
|| lower.contains("no route to host")
|
||||
|| lower.contains("could not resolve");
|
||||
if result.status == Some(255) && transport {
|
||||
return classify_ssh(result);
|
||||
}
|
||||
command_exit_error(result.status.unwrap_or(-1), command_output(result))
|
||||
}
|
||||
|
||||
fn validate_remote_path(path: &str) -> Result<(), StockError> {
|
||||
if path.is_empty() || path.contains('\0') || path.ends_with('/') {
|
||||
return Err(StockError::Method("invalid remote path".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remote_parent(path: &str) -> &str {
|
||||
match path.rfind('/') {
|
||||
Some(0) => "/",
|
||||
Some(index) => &path[..index],
|
||||
None => ".",
|
||||
}
|
||||
}
|
||||
|
||||
fn ssh_root_ready(host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||
ssh_probe(host, password)
|
||||
}
|
||||
|
||||
fn reboot_target(host: &str, password: Option<&str>) {
|
||||
let _ = run_command(
|
||||
ssh_command(
|
||||
@@ -955,6 +1054,18 @@ fn stock_web_upload(
|
||||
body: &Path,
|
||||
boundary: &str,
|
||||
tag: &str,
|
||||
) -> Result<(), StockError> {
|
||||
stock_web_upload_with_timeout(host, password, dir, body, boundary, tag, 600)
|
||||
}
|
||||
|
||||
fn stock_web_upload_with_timeout(
|
||||
host: &str,
|
||||
password: &str,
|
||||
dir: &Path,
|
||||
body: &Path,
|
||||
boundary: &str,
|
||||
tag: &str,
|
||||
max_time_secs: u64,
|
||||
) -> Result<(), StockError> {
|
||||
let config = dir.join(format!("upload-{tag}.cfg"));
|
||||
let output = dir.join(format!("upload-{tag}.out"));
|
||||
@@ -966,7 +1077,7 @@ fn stock_web_upload(
|
||||
"digest".to_string(),
|
||||
"location".to_string(),
|
||||
"max-redirs = 5".to_string(),
|
||||
"max-time = 600".to_string(),
|
||||
format!("max-time = {max_time_secs}"),
|
||||
format!(
|
||||
"url = {}",
|
||||
curl_quote(&format!("http://{host}/cgi-bin/upgrade.cgi"))
|
||||
@@ -987,7 +1098,7 @@ fn stock_web_upload(
|
||||
"write-out = \"%{http_code}\"".to_string(),
|
||||
],
|
||||
)?;
|
||||
let result = run_curl(&config, Duration::from_secs(620))?;
|
||||
let result = run_curl(&config, Duration::from_secs(max_time_secs + 20))?;
|
||||
match http_code(&result) {
|
||||
200..=299 => Ok(()),
|
||||
401 | 403 => Err(StockError::Auth("target rejected the credential".into())),
|
||||
@@ -1002,6 +1113,17 @@ fn stock_web_trigger(
|
||||
dir: &Path,
|
||||
cgi: &str,
|
||||
tag: &str,
|
||||
) -> Result<CmdResult, StockError> {
|
||||
stock_web_trigger_with_timeout(host, password, dir, cgi, tag, 900)
|
||||
}
|
||||
|
||||
fn stock_web_trigger_with_timeout(
|
||||
host: &str,
|
||||
password: &str,
|
||||
dir: &Path,
|
||||
cgi: &str,
|
||||
tag: &str,
|
||||
max_time_secs: u64,
|
||||
) -> Result<CmdResult, StockError> {
|
||||
let config = dir.join(format!("trigger-{tag}.cfg"));
|
||||
write_curl_config(
|
||||
@@ -1012,7 +1134,7 @@ fn stock_web_trigger(
|
||||
"digest".to_string(),
|
||||
"location".to_string(),
|
||||
"max-redirs = 5".to_string(),
|
||||
"max-time = 900".to_string(),
|
||||
format!("max-time = {max_time_secs}"),
|
||||
format!(
|
||||
"url = {}",
|
||||
curl_quote(&format!("http://{host}/cgi-bin/{cgi}"))
|
||||
@@ -1020,7 +1142,7 @@ fn stock_web_trigger(
|
||||
format!("user = {}", curl_quote(&format!("root:{password}"))),
|
||||
],
|
||||
)?;
|
||||
run_curl(&config, Duration::from_secs(920))
|
||||
run_curl(&config, Duration::from_secs(max_time_secs + 20))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- AFW
|
||||
@@ -1868,27 +1990,32 @@ fn flash_script(
|
||||
script
|
||||
}
|
||||
|
||||
fn web_base_entries() -> Vec<TarEntry> {
|
||||
vec![
|
||||
TarEntry {
|
||||
name: "d".to_string(),
|
||||
mode: 0o777,
|
||||
kind: b'2',
|
||||
link: "/tmp".to_string(),
|
||||
data: Vec::new(),
|
||||
},
|
||||
TarEntry {
|
||||
name: "p".to_string(),
|
||||
mode: 0o777,
|
||||
kind: b'2',
|
||||
link: "/www/pages/cgi-bin".to_string(),
|
||||
data: Vec::new(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn build_web_body(
|
||||
targets: &[FlashTarget],
|
||||
token: &str,
|
||||
cgi: &str,
|
||||
script: &str,
|
||||
) -> (Vec<u8>, String) {
|
||||
let mut entries = Vec::new();
|
||||
entries.push(TarEntry {
|
||||
name: "d".to_string(),
|
||||
mode: 0o777,
|
||||
kind: b'2',
|
||||
link: "/tmp".to_string(),
|
||||
data: Vec::new(),
|
||||
});
|
||||
entries.push(TarEntry {
|
||||
name: "p".to_string(),
|
||||
mode: 0o777,
|
||||
kind: b'2',
|
||||
link: "/www/pages/cgi-bin".to_string(),
|
||||
data: Vec::new(),
|
||||
});
|
||||
let mut entries = web_base_entries();
|
||||
for target in targets {
|
||||
entries.push(TarEntry {
|
||||
name: format!("d/.ak-{token}-{}", target.file),
|
||||
@@ -1905,7 +2032,10 @@ fn build_web_body(
|
||||
link: String::new(),
|
||||
data: script.as_bytes().to_vec(),
|
||||
});
|
||||
build_web_body_entries(entries)
|
||||
}
|
||||
|
||||
fn build_web_body_entries(entries: Vec<TarEntry>) -> (Vec<u8>, String) {
|
||||
let tar = build_tar(&entries);
|
||||
let gz = gzip_store(&tar);
|
||||
let boundary = format!("----alkane{}", random_token());
|
||||
@@ -2370,6 +2500,31 @@ fn onboard_stock_backup_present_impl(
|
||||
|
||||
// ---------------------------------------------------------------- install / restore
|
||||
|
||||
fn choose_web_password(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
dir: &Path,
|
||||
tag: &str,
|
||||
) -> Result<String, StockError> {
|
||||
let candidates = web_password_candidates(password);
|
||||
let mut last_auth = false;
|
||||
for (index, candidate) in candidates.iter().enumerate() {
|
||||
match stock_web_auth(host, candidate, dir, &format!("{tag}{index}")) {
|
||||
Ok(()) => return Ok(candidate.clone()),
|
||||
Err(StockError::Auth(_)) => {
|
||||
last_auth = true;
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
if last_auth {
|
||||
Err(StockError::Auth("target rejected the credential".into()))
|
||||
} else {
|
||||
Err(StockError::Network("target unreachable".into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn install_via_web(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
@@ -2378,27 +2533,7 @@ fn install_via_web(
|
||||
rootfs: Vec<u8>,
|
||||
) -> Result<(), StockError> {
|
||||
let dir = TempDir::new("web")?;
|
||||
let candidates = web_password_candidates(password);
|
||||
let mut chosen = None;
|
||||
let mut last_auth = false;
|
||||
for (index, candidate) in candidates.iter().enumerate() {
|
||||
match stock_web_auth(host, candidate, dir.path(), &format!("probe{index}")) {
|
||||
Ok(()) => {
|
||||
chosen = Some(candidate.clone());
|
||||
break;
|
||||
}
|
||||
Err(StockError::Auth(_)) => {
|
||||
last_auth = true;
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
let password = match chosen {
|
||||
Some(password) => password,
|
||||
None if last_auth => return Err(StockError::Auth("target rejected the credential".into())),
|
||||
None => return Err(StockError::Network("target unreachable".into())),
|
||||
};
|
||||
let password = choose_web_password(host, password, dir.path(), "probe")?;
|
||||
|
||||
let targets = stock_web_targets(kernel, dtb, rootfs)?;
|
||||
let token = random_token();
|
||||
@@ -2421,6 +2556,264 @@ fn install_via_web(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- root primitives
|
||||
//
|
||||
// These stay sealed inside this module. The public interface in `stock.rs`
|
||||
// describes only the operation and its result; nothing here is part of it.
|
||||
|
||||
fn root_exec_via_ssh(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
|
||||
let remote = format!("sh -c {}", shell_quote(cmd));
|
||||
let result = ssh_exec(host, password, &remote, Duration::from_secs(3600))?;
|
||||
if result.ok() {
|
||||
Ok(command_output(&result))
|
||||
} else {
|
||||
Err(command_failure(&result))
|
||||
}
|
||||
}
|
||||
|
||||
fn root_exec_via_web(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
|
||||
let dir = TempDir::new("root")?;
|
||||
let password = choose_web_password(host, password, dir.path(), "root")?;
|
||||
let token = random_token();
|
||||
let cgi = format!("zz{token}.cgi");
|
||||
let marker = format!("@@AKEXIT{token}@@");
|
||||
let script = format!(
|
||||
"#!/bin/sh\n\
|
||||
printf 'Content-type: text/plain\\r\\n\\r\\n'\n\
|
||||
trap 'rm -f /www/pages/cgi-bin/{cgi}' EXIT\n\
|
||||
sh -c {quoted} 2>&1\n\
|
||||
ak_code=$?\n\
|
||||
printf '{marker}%d\\n' \"$ak_code\"\n",
|
||||
cgi = cgi,
|
||||
quoted = shell_quote(cmd),
|
||||
marker = marker,
|
||||
);
|
||||
let mut entries = web_base_entries();
|
||||
entries.push(TarEntry {
|
||||
name: format!("p/{cgi}"),
|
||||
mode: 0o755,
|
||||
kind: b'0',
|
||||
link: String::new(),
|
||||
data: script.into_bytes(),
|
||||
});
|
||||
let (body, boundary) = build_web_body_entries(entries);
|
||||
let body_path = dir.join("upload.body");
|
||||
write_private(&body_path, &body)?;
|
||||
|
||||
stock_web_upload_with_timeout(
|
||||
host,
|
||||
&password,
|
||||
dir.path(),
|
||||
&body_path,
|
||||
&boundary,
|
||||
&token,
|
||||
1800,
|
||||
)?;
|
||||
let trigger = stock_web_trigger_with_timeout(host, &password, dir.path(), &cgi, &token, 3600)?;
|
||||
let output = text(&trigger.stdout);
|
||||
if let Some(index) = output.rfind(&marker) {
|
||||
let command_output = &output[..index];
|
||||
let status = output[index + marker.len()..]
|
||||
.trim()
|
||||
.parse::<i32>()
|
||||
.unwrap_or(-1);
|
||||
if status == 0 {
|
||||
return Ok(command_output.to_string());
|
||||
}
|
||||
return Err(command_exit_error(status, command_output.to_string()));
|
||||
}
|
||||
if trigger.timed_out {
|
||||
return Err(StockError::Network("target did not respond".into()));
|
||||
}
|
||||
if !trigger.ok() {
|
||||
return Err(StockError::Network("target unreachable".into()));
|
||||
}
|
||||
Err(StockError::Method("command channel did not respond".into()))
|
||||
}
|
||||
|
||||
fn root_put_via_ssh(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
data: &[u8],
|
||||
remote_path: &str,
|
||||
) -> Result<(), StockError> {
|
||||
let dir = TempDir::new("put")?;
|
||||
let payload = dir.join("payload");
|
||||
write_private(&payload, data)?;
|
||||
|
||||
let parent = remote_parent(remote_path);
|
||||
let prep = ssh_exec(
|
||||
host,
|
||||
password,
|
||||
&format!("mkdir -p {}", shell_quote(parent)),
|
||||
Duration::from_secs(60),
|
||||
)?;
|
||||
if !prep.ok() {
|
||||
return Err(command_failure(&prep));
|
||||
}
|
||||
|
||||
let token = random_token();
|
||||
let temp_path = format!("{remote_path}.ak-tmp-{token}");
|
||||
let remote = format!("cat > {}", shell_quote(&temp_path));
|
||||
let input = fs::File::open(&payload)
|
||||
.map_err(|e| StockError::Io(format!("could not read the payload: {e}")))?;
|
||||
let result = run_command_stream(
|
||||
ssh_command(host, password, &remote),
|
||||
Duration::from_secs(1800),
|
||||
input,
|
||||
)?;
|
||||
if result.timed_out {
|
||||
let _ = ssh_exec(
|
||||
host,
|
||||
password,
|
||||
&format!("rm -f {}", shell_quote(&temp_path)),
|
||||
Duration::from_secs(15),
|
||||
);
|
||||
return Err(StockError::Network("target transfer timed out".into()));
|
||||
}
|
||||
if !result.ok() {
|
||||
let _ = ssh_exec(
|
||||
host,
|
||||
password,
|
||||
&format!("rm -f {}", shell_quote(&temp_path)),
|
||||
Duration::from_secs(15),
|
||||
);
|
||||
return Err(command_failure(&result));
|
||||
}
|
||||
|
||||
let finalize = format!(
|
||||
"chmod 0644 {temp} && mv -f {temp} {path}",
|
||||
temp = shell_quote(&temp_path),
|
||||
path = shell_quote(remote_path),
|
||||
);
|
||||
let result = ssh_exec(host, password, &finalize, Duration::from_secs(60))?;
|
||||
if !result.ok() {
|
||||
let _ = ssh_exec(
|
||||
host,
|
||||
password,
|
||||
&format!("rm -f {}", shell_quote(&temp_path)),
|
||||
Duration::from_secs(15),
|
||||
);
|
||||
return Err(command_failure(&result));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn root_put_via_web(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
data: &[u8],
|
||||
remote_path: &str,
|
||||
) -> Result<(), StockError> {
|
||||
let dir = TempDir::new("put")?;
|
||||
let password = choose_web_password(host, password, dir.path(), "put")?;
|
||||
let token = random_token();
|
||||
let cgi = format!("zz{token}.cgi");
|
||||
let marker = format!("@@AKPUT{token}@@");
|
||||
let staged = format!("/tmp/.ak-put-{token}");
|
||||
let temp_path = format!("{remote_path}.ak-tmp-{token}");
|
||||
let parent = remote_parent(remote_path);
|
||||
let script = format!(
|
||||
"#!/bin/sh\n\
|
||||
f={staged}\n\
|
||||
t={temp}\n\
|
||||
trap 'rm -f \"$f\" \"$t\" /www/pages/cgi-bin/{cgi}' EXIT\n\
|
||||
mkdir -p {parent} || {{ printf '{marker}fail\\n'; exit 1; }}\n\
|
||||
cp \"$f\" \"$t\" || {{ printf '{marker}fail\\n'; exit 1; }}\n\
|
||||
chmod 0644 \"$t\" || {{ printf '{marker}fail\\n'; exit 1; }}\n\
|
||||
mv -f \"$t\" {path} || {{ printf '{marker}fail\\n'; exit 1; }}\n\
|
||||
printf '{marker}ok\\n'\n",
|
||||
staged = shell_quote(&staged),
|
||||
temp = shell_quote(&temp_path),
|
||||
cgi = cgi,
|
||||
parent = shell_quote(parent),
|
||||
marker = marker,
|
||||
path = shell_quote(remote_path),
|
||||
);
|
||||
|
||||
let mut entries = web_base_entries();
|
||||
entries.push(TarEntry {
|
||||
name: format!("d/.ak-put-{token}"),
|
||||
mode: 0o600,
|
||||
kind: b'0',
|
||||
link: String::new(),
|
||||
data: data.to_vec(),
|
||||
});
|
||||
entries.push(TarEntry {
|
||||
name: format!("p/{cgi}"),
|
||||
mode: 0o755,
|
||||
kind: b'0',
|
||||
link: String::new(),
|
||||
data: script.into_bytes(),
|
||||
});
|
||||
let (body, boundary) = build_web_body_entries(entries);
|
||||
let body_path = dir.join("upload.body");
|
||||
write_private(&body_path, &body)?;
|
||||
|
||||
stock_web_upload_with_timeout(
|
||||
host,
|
||||
&password,
|
||||
dir.path(),
|
||||
&body_path,
|
||||
&boundary,
|
||||
&token,
|
||||
1800,
|
||||
)?;
|
||||
let trigger = stock_web_trigger_with_timeout(host, &password, dir.path(), &cgi, &token, 1800)?;
|
||||
let output = text(&trigger.stdout);
|
||||
if output.contains(&format!("{marker}ok")) {
|
||||
return Ok(());
|
||||
}
|
||||
if output.contains(&format!("{marker}fail")) {
|
||||
return Err(StockError::Method("could not write the remote file".into()));
|
||||
}
|
||||
if trigger.timed_out {
|
||||
return Err(StockError::Network("target did not respond".into()));
|
||||
}
|
||||
if !trigger.ok() {
|
||||
return Err(StockError::Network("target unreachable".into()));
|
||||
}
|
||||
Err(StockError::Method("command channel did not respond".into()))
|
||||
}
|
||||
|
||||
fn root_exec_impl(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
|
||||
validate_host(host)?;
|
||||
let resolved = resolve_password(password);
|
||||
let ssh_password = resolved.as_deref();
|
||||
match ssh_root_ready(host, ssh_password) {
|
||||
Ok(()) => root_exec_via_ssh(host, ssh_password, cmd),
|
||||
Err(ssh_error) => {
|
||||
if is_stock_http(host) {
|
||||
root_exec_via_web(host, password, cmd)
|
||||
} else {
|
||||
Err(ssh_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn root_put_impl(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
data: &[u8],
|
||||
remote_path: &str,
|
||||
) -> Result<(), StockError> {
|
||||
validate_host(host)?;
|
||||
validate_remote_path(remote_path)?;
|
||||
let resolved = resolve_password(password);
|
||||
let ssh_password = resolved.as_deref();
|
||||
match ssh_root_ready(host, ssh_password) {
|
||||
Ok(()) => root_put_via_ssh(host, ssh_password, data, remote_path),
|
||||
Err(ssh_error) => {
|
||||
if is_stock_http(host) {
|
||||
root_put_via_web(host, password, data, remote_path)
|
||||
} else {
|
||||
Err(ssh_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The alkane write set for this board, placed on the given storage map:
|
||||
/// rootfs, then dtb, then kernel (so an interrupted write never leaves a new
|
||||
/// rootfs under an old kernel). `kernel` and `rootfs` are the uImage-wrapped
|
||||
@@ -2922,6 +3315,25 @@ impl StockMethod for Method {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn root_exec(
|
||||
&self,
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
cmd: &str,
|
||||
) -> Result<String, StockError> {
|
||||
root_exec_impl(host, password, cmd)
|
||||
}
|
||||
|
||||
fn root_put(
|
||||
&self,
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
data: &[u8],
|
||||
remote_path: &str,
|
||||
) -> Result<(), StockError> {
|
||||
root_put_impl(host, password, data, remote_path)
|
||||
}
|
||||
|
||||
fn update_in_place(
|
||||
&self,
|
||||
host: &str,
|
||||
@@ -2962,6 +3374,53 @@ pub fn method() -> &'static dyn StockMethod {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shell_quote_round_trips_awkward_arguments() {
|
||||
for value in [
|
||||
"/tmp/plain",
|
||||
"/tmp/with space",
|
||||
"/tmp/with'quote",
|
||||
"a$b`c`d\"e\\f",
|
||||
"line\nbreak",
|
||||
"",
|
||||
] {
|
||||
assert_eq!(
|
||||
shell_quote(value),
|
||||
format!("'{}'", value.replace('\'', "'\\''"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_paths_are_split_and_validated() {
|
||||
assert_eq!(remote_parent("/tmp/a/b"), "/tmp/a");
|
||||
assert_eq!(remote_parent("/tmp"), "/");
|
||||
assert_eq!(remote_parent("relative"), ".");
|
||||
assert!(validate_remote_path("/tmp/a").is_ok());
|
||||
assert!(validate_remote_path("").is_err());
|
||||
assert!(validate_remote_path("/tmp/").is_err());
|
||||
assert!(validate_remote_path("/tmp/\0bad").is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn streamed_command_input_is_transferred_whole() {
|
||||
let dir = TempDir::new("streamtest").expect("temp dir");
|
||||
let payload = vec![0xA5u8; 2 * 1024 * 1024 + 17];
|
||||
let input = dir.join("input");
|
||||
let output = dir.join("output");
|
||||
write_private(&input, &payload).expect("write input");
|
||||
let mut command = Command::new("sh");
|
||||
command
|
||||
.arg("-c")
|
||||
.arg(format!("cat > {}", shell_quote(&output.to_string_lossy())));
|
||||
let file = fs::File::open(&input).expect("open input");
|
||||
let result =
|
||||
run_command_stream(command, Duration::from_secs(30), file).expect("stream command");
|
||||
assert!(result.ok());
|
||||
assert_eq!(fs::read(&output).expect("read output"), payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn md5_known_vectors() {
|
||||
assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
|
||||
|
||||
Reference in New Issue
Block a user