mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-24 02:52:47 +08:00
feat: localize console output and add a run observer
Engine errors, integrity findings, and driver outcomes carry message codes from senbei-i18n, with their English unchanged, so reports, logs, and --json stay byte-identical. Verbose pipeline steps go through a progress sink instead of println!, and an error chain is translated through its first coded cause. The CLI takes the display language from SENBEI_LANG, or else from the system's preferred UI language, and translates console text: usage errors, help, per-file lines, the run summary, and the summary lines of the inspect report. Structural research evidence and saved logs stay English. When a translation leaves out context the English chain has, the English follows on a muted line. A front end can attach a RunObserver and a CancelToken to the Collector to follow a run input by input, receive verbose steps as events, and stop before the next input. A cancelled report says so. The CLI never cancels, so its JSON is unchanged.
This commit is contained in:
1 parent
9481b0ccf9
commit
4853fe22c0
39 files changed
+2016
-684
No files matched your search
@@ -14,6 +14,7 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
senbei-io.workspace = true
|
||||
senbei-engine.workspace = true
|
||||
senbei-i18n.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow.workspace = true
|
||||
|
||||
+80
-106
@@ -1,19 +1,26 @@
|
||||
use senbei_engine::android::ResourceLimits;
|
||||
use senbei_i18n::{Cli, Localize};
|
||||
use senbei_io::{
|
||||
job, pause, scan,
|
||||
job,
|
||||
message::of_error,
|
||||
pause, scan,
|
||||
ui::{self, ColorMode, Palette, Tone},
|
||||
};
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// Console text follows the user's language; logs and JSON stay English.
|
||||
senbei_i18n::set_current(senbei_io::locale::detect());
|
||||
let mut options = match Options::parse(std::env::args().skip(1)) {
|
||||
Ok(Outcome::Run(options)) => options,
|
||||
Ok(Outcome::Handled(code)) => return code,
|
||||
Err(message) => {
|
||||
let lang = senbei_i18n::current();
|
||||
eprintln!(
|
||||
"{}: {message}",
|
||||
Palette::stderr().paint(Tone::Error, "error")
|
||||
"{}: {}",
|
||||
Palette::stderr().paint(Tone::Error, Cli::Error.localize(lang)),
|
||||
message.localize(lang)
|
||||
);
|
||||
return std::process::ExitCode::from(2);
|
||||
}
|
||||
@@ -67,7 +74,7 @@ enum Outcome {
|
||||
}
|
||||
|
||||
impl Options {
|
||||
fn parse(args: impl Iterator<Item = String>) -> Result<Outcome, String> {
|
||||
fn parse(args: impl Iterator<Item = String>) -> Result<Outcome, Box<Cli>> {
|
||||
let mut args = args.peekable();
|
||||
let mut command = Command::Unpack;
|
||||
let mut subcommand: Option<String> = None;
|
||||
@@ -114,11 +121,14 @@ impl Options {
|
||||
}
|
||||
"--out" => match args.next() {
|
||||
Some(v) if !v.starts_with('-') => out = Some(v),
|
||||
_ => return Err("--out requires a directory argument".to_owned()),
|
||||
_ => return Err(Cli::OutRequiresDirectory.into()),
|
||||
},
|
||||
other if other.starts_with('-') => {
|
||||
print_help();
|
||||
return Err(format!("unknown option '{other}'"));
|
||||
return Err(Cli::UnknownOption {
|
||||
option: other.to_owned(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
// A subcommand is only a subcommand when it is the first
|
||||
// positional word. `senbei inspect` therefore means the
|
||||
@@ -137,9 +147,11 @@ impl Options {
|
||||
}
|
||||
other => {
|
||||
if let Some(prev) = &path {
|
||||
return Err(format!(
|
||||
"multiple input paths given ('{prev}' and '{other}')"
|
||||
));
|
||||
return Err(Cli::MultipleInputs {
|
||||
first: prev.clone(),
|
||||
second: other.to_owned(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
path = Some(other.to_string());
|
||||
}
|
||||
@@ -150,7 +162,7 @@ impl Options {
|
||||
// A subcommand with no path is a usage error; no arguments at all
|
||||
// still prints help and exits 2, as before.
|
||||
if let Some(subcommand) = subcommand {
|
||||
return Err(format!("'{subcommand}' requires an input path"));
|
||||
return Err(Cli::SubcommandNeedsPath { subcommand }.into());
|
||||
}
|
||||
print_help();
|
||||
return Ok(Outcome::Handled(std::process::ExitCode::from(2)));
|
||||
@@ -160,10 +172,10 @@ impl Options {
|
||||
// rejected rather than guessed at.
|
||||
if command == Command::Inspect {
|
||||
if dry_run {
|
||||
return Err("'inspect' writes nothing; drop --dry-run".to_owned());
|
||||
return Err(Cli::InspectNoDryRun.into());
|
||||
}
|
||||
if out.is_some() {
|
||||
return Err("'inspect' writes nothing; --out is not allowed".to_owned());
|
||||
return Err(Cli::InspectNoOut.into());
|
||||
}
|
||||
// `--strict-integrity` is meaningful: inspection runs the real
|
||||
// static check and reports its verdict.
|
||||
@@ -177,7 +189,7 @@ impl Options {
|
||||
if dry_run {
|
||||
// A dry run keeps nothing: no ordinary output directory, no log.
|
||||
if out.is_some() {
|
||||
return Err("--dry-run writes no output; --out is not allowed".to_owned());
|
||||
return Err(Cli::DryRunNoOut.into());
|
||||
}
|
||||
no_log = true;
|
||||
}
|
||||
@@ -201,20 +213,20 @@ impl Options {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_color(value: Option<&str>) -> Result<ColorMode, String> {
|
||||
fn parse_color(value: Option<&str>) -> Result<ColorMode, Box<Cli>> {
|
||||
match value {
|
||||
Some("auto") => Ok(ColorMode::Auto),
|
||||
Some("always") => Ok(ColorMode::Always),
|
||||
Some("never") => Ok(ColorMode::Never),
|
||||
_ => Err("--color requires auto, always, or never".to_owned()),
|
||||
_ => Err(Cli::ColorRequiresMode.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, String> {
|
||||
fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, Box<Cli>> {
|
||||
value
|
||||
.filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
.and_then(|text| text.parse().ok())
|
||||
.ok_or_else(|| "--threads requires a positive integer argument".to_owned())
|
||||
.ok_or_else(|| Cli::ThreadsRequiresInteger.into())
|
||||
}
|
||||
|
||||
/// Run the parsed command. Kept separate from argument parsing and the pause
|
||||
@@ -246,13 +258,10 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
|
||||
}
|
||||
Err(error) => {
|
||||
if options.machine {
|
||||
let report = job::error_report(job::Mode::Inspect, &format!("{error:#}"));
|
||||
let report = job::error_report(job::Mode::Inspect, of_error(&error));
|
||||
println!("{}", report.to_json());
|
||||
} else if options.quiet < 2 {
|
||||
eprintln!(
|
||||
"{}: {error:#}",
|
||||
Palette::stderr().paint(Tone::Error, "error")
|
||||
);
|
||||
ui::print_anyhow(&error);
|
||||
}
|
||||
1
|
||||
}
|
||||
@@ -273,13 +282,10 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
|
||||
}
|
||||
Err(error) => {
|
||||
if options.machine {
|
||||
let report = job::error_report(job::Mode::DryRun, &format!("{error:#}"));
|
||||
let report = job::error_report(job::Mode::DryRun, of_error(&error));
|
||||
println!("{}", report.to_json());
|
||||
} else if options.quiet < 2 {
|
||||
eprintln!(
|
||||
"{}: {error:#}",
|
||||
Palette::stderr().paint(Tone::Error, "error")
|
||||
);
|
||||
ui::print_anyhow(&error);
|
||||
}
|
||||
1
|
||||
}
|
||||
@@ -350,10 +356,12 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
|
||||
println!("{}", collector.finish().to_json());
|
||||
} else if options.quiet < 2 {
|
||||
println!("{}", summary.line_with_palette(Palette::stdout()));
|
||||
let done = Cli::DoneIn {
|
||||
ms: summary.duration_ms,
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
Palette::stdout()
|
||||
.paint(Tone::Muted, format!("done in {} ms", summary.duration_ms))
|
||||
Palette::stdout().paint(Tone::Muted, done.localize(senbei_i18n::current()))
|
||||
);
|
||||
}
|
||||
exit_code(&summary, options.strict_integrity)
|
||||
@@ -361,13 +369,10 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
|
||||
Err(error) => {
|
||||
if options.machine {
|
||||
let mut failed = collector;
|
||||
failed.push_error(format!("{error:#}"));
|
||||
failed.push_error(of_error(&error));
|
||||
println!("{}", failed.finish().to_json());
|
||||
} else if options.quiet < 2 {
|
||||
eprintln!(
|
||||
"{}: {error:#}",
|
||||
Palette::stderr().paint(Tone::Error, "error")
|
||||
);
|
||||
ui::print_anyhow(&error);
|
||||
}
|
||||
1
|
||||
}
|
||||
@@ -400,20 +405,27 @@ fn set_resource_limit(
|
||||
limits: &mut ResourceLimits,
|
||||
flag: &str,
|
||||
value: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let invalid = || format!("{flag} requires an unsigned integer argument");
|
||||
) -> Result<(), Box<Cli>> {
|
||||
let invalid = || Cli::LimitRequiresInteger {
|
||||
flag: flag.to_owned(),
|
||||
};
|
||||
let text = value
|
||||
.filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
.ok_or_else(invalid)?;
|
||||
let value: u64 = text.parse().map_err(|_| invalid())?;
|
||||
if value == 0 && flag != "--max-depth" {
|
||||
return Err(format!("{flag} must be greater than zero"));
|
||||
return Err(Cli::LimitMustBePositive {
|
||||
flag: flag.to_owned(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
match flag {
|
||||
"--max-entry-mib" | "--max-total-mib" => {
|
||||
let bytes = value
|
||||
.checked_mul(1024 * 1024)
|
||||
.ok_or_else(|| format!("{flag} exceeds the supported byte range"))?;
|
||||
.ok_or_else(|| Cli::LimitTooLarge {
|
||||
flag: flag.to_owned(),
|
||||
})?;
|
||||
if flag == "--max-entry-mib" {
|
||||
limits.max_entry_bytes = bytes;
|
||||
} else {
|
||||
@@ -422,7 +434,12 @@ fn set_resource_limit(
|
||||
}
|
||||
"--max-entries" => limits.max_entries = usize::try_from(value).map_err(|_| invalid())?,
|
||||
"--max-depth" => limits.max_depth = usize::try_from(value).map_err(|_| invalid())?,
|
||||
_ => return Err(format!("unknown resource option '{flag}'")),
|
||||
_ => {
|
||||
return Err(Cli::UnknownLimit {
|
||||
flag: flag.to_owned(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -431,73 +448,28 @@ fn print_help() {
|
||||
println!(
|
||||
"senbei [inspect|unpack] <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--threads N] [--color auto|always|never] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]"
|
||||
);
|
||||
println!(
|
||||
" <file|folder>\n\
|
||||
\x20 a CrackProof PE (.exe/.dll), an il2cpp global-metadata.dat,\n\
|
||||
\x20 a protected Android AArch64 library (.so), an Android app\n\
|
||||
\x20 package (.apk/.apks/.xapk), or a folder containing any of\n\
|
||||
\x20 these. The bare form is the same as 'unpack'."
|
||||
);
|
||||
println!(
|
||||
" inspect PATH\n\
|
||||
\x20 run the real static recovery for research, and report\n\
|
||||
\x20 everything observed: recognition evidence, each route\n\
|
||||
\x20 tried and why it was rejected, the route selected, the\n\
|
||||
\x20 static check's verdict, and the engines' own structural\n\
|
||||
\x20 evidence (protected-header fields, seeds, module records,\n\
|
||||
\x20 restored-image facts). Nothing is kept: no output file,\n\
|
||||
\x20 no log, no temporary tree, and the input is never run."
|
||||
);
|
||||
println!(" unpack PATH detection and recovery; writes outputs (the default).");
|
||||
println!(
|
||||
" --json write one versioned machine-readable report to stdout and\n\
|
||||
\x20 nothing else. Implies quiet and --no-log."
|
||||
);
|
||||
println!(
|
||||
" --dry-run run the real recovery but keep nothing: no output tree and\n\
|
||||
\x20 no log. Android extraction still uses its own temporary\n\
|
||||
\x20 workspace, which is discarded."
|
||||
);
|
||||
println!(
|
||||
" --threads N positive worker cap for this run. Overrides SENBEI_THREADS;\n\
|
||||
\x20 1 selects the sequential path. The environment is unchanged."
|
||||
);
|
||||
println!(
|
||||
" --color MODE auto (default), always, or never; --color=MODE also works.\n\
|
||||
\x20 Auto colors terminal stdout/stderr separately, unless\n\
|
||||
\x20 NO_COLOR is nonempty or TERM=dumb. Explicit always/never\n\
|
||||
\x20 override these variables. JSON and saved logs stay plain."
|
||||
);
|
||||
println!(
|
||||
" --scan-all probe selected .exe/.dll/.so/metadata names below the\n\
|
||||
\x20 size floor; other filenames remain excluded."
|
||||
);
|
||||
println!(
|
||||
" --strict-integrity\n\
|
||||
\x20 exit non-zero when any output fails the static integrity\n\
|
||||
\x20 check (a suspect) or a file errors. Off by default: a\n\
|
||||
\x20 suspect is still written and the process exits 0 unless\n\
|
||||
\x20 a file errors. Quiet levels are unchanged.\n\
|
||||
\x20 With 'inspect', the check applies to the image actually\n\
|
||||
\x20 recovered for research; no output file is retained."
|
||||
);
|
||||
let defaults = ResourceLimits::default();
|
||||
println!(
|
||||
" Android resource limits (MiB = 1048576 bytes):\n\
|
||||
\x20 --max-entry-mib N single archive entry/decoded buffer/output (default {})\n\
|
||||
\x20 --max-total-mib N cumulative archive bytes and per-engine task budget (default {})\n\
|
||||
\x20 --max-entries N archive entries/stage-2 records (default {})\n\
|
||||
\x20 --max-depth N nesting depth, root = 0 (default {})\n\
|
||||
\x20 Limits are checked before extraction/allocation; they are not a peak-RSS cap.",
|
||||
defaults.max_entry_bytes / (1024 * 1024),
|
||||
defaults.max_total_bytes / (1024 * 1024),
|
||||
defaults.max_entries,
|
||||
defaults.max_depth,
|
||||
);
|
||||
println!(
|
||||
" Exit codes: 0 success, 1 a target failed (or a suspect with\n\
|
||||
\x20 --strict-integrity), 2 the command line was rejected."
|
||||
);
|
||||
let lang = senbei_i18n::current();
|
||||
for block in [
|
||||
Cli::HelpPath,
|
||||
Cli::HelpInspect,
|
||||
Cli::HelpUnpack,
|
||||
Cli::HelpJson,
|
||||
Cli::HelpDryRun,
|
||||
Cli::HelpThreads,
|
||||
Cli::HelpColor,
|
||||
Cli::HelpScanAll,
|
||||
Cli::HelpStrictIntegrity,
|
||||
Cli::HelpLimits {
|
||||
entry_mib: defaults.max_entry_bytes / (1024 * 1024),
|
||||
total_mib: defaults.max_total_bytes / (1024 * 1024),
|
||||
entries: defaults.max_entries,
|
||||
depth: defaults.max_depth,
|
||||
},
|
||||
Cli::HelpExitCodes,
|
||||
] {
|
||||
println!("{}", block.localize(lang));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -641,7 +613,9 @@ mod command_line {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
match Options::parse(args.iter().map(|arg| (*arg).to_string()))? {
|
||||
let parsed = Options::parse(args.iter().map(|arg| (*arg).to_string()))
|
||||
.map_err(|error| error.localize(senbei_i18n::Lang::En).into_owned())?;
|
||||
match parsed {
|
||||
Outcome::Run(options) => Ok(options),
|
||||
Outcome::Handled(code) => Err(format!(
|
||||
"handled: {}",
|
||||
|
||||
@@ -10,6 +10,7 @@ fn senbei() -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
|
||||
command
|
||||
.arg("--no-pause")
|
||||
.env("SENBEI_LANG", "en")
|
||||
.env_remove("NO_COLOR")
|
||||
.env("TERM", "xterm-256color");
|
||||
command
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! The console follows SENBEI_LANG (or the system language); saved logs and
|
||||
//! `--json` reports stay English in every language.
|
||||
|
||||
#[path = "support/fixtures.rs"]
|
||||
mod fixtures;
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use senbei_i18n::{Cli, Lang, Localize};
|
||||
|
||||
fn senbei(lang: &str) -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
|
||||
command.arg("--no-pause").env("SENBEI_LANG", lang);
|
||||
command
|
||||
}
|
||||
|
||||
fn text(bytes: &[u8]) -> &str {
|
||||
std::str::from_utf8(bytes).expect("UTF-8 console output")
|
||||
}
|
||||
|
||||
fn fixture(root: &Path) -> std::path::PathBuf {
|
||||
let path = root.join("global-metadata.dat");
|
||||
std::fs::write(&path, fixtures::obfuscated_metadata()).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn without_timings(json: &str) -> String {
|
||||
let mut value: serde_json::Value = serde_json::from_str(json).expect("one JSON document");
|
||||
fn strip(value: &mut serde_json::Value) {
|
||||
match value {
|
||||
serde_json::Value::Object(map) => {
|
||||
map.remove("duration_ms");
|
||||
map.values_mut().for_each(strip);
|
||||
}
|
||||
serde_json::Value::Array(items) => items.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
strip(&mut value);
|
||||
value.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_errors_and_help_follow_the_language() {
|
||||
for lang in [Lang::ZhCn, Lang::ZhTw, Lang::Ja, Lang::Ko] {
|
||||
let output = senbei(lang.tag()).arg("--bogus").output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
let expected = format!(
|
||||
"{}: {}",
|
||||
Cli::Error.localize(lang),
|
||||
Cli::UnknownOption {
|
||||
option: "--bogus".into()
|
||||
}
|
||||
.localize(lang)
|
||||
);
|
||||
assert!(text(&output.stderr).contains(&expected), "{lang:?}");
|
||||
assert!(text(&output.stdout).contains(&*Cli::HelpJson.localize(lang)));
|
||||
assert_ne!(
|
||||
Cli::HelpJson.localize(lang),
|
||||
Cli::HelpJson.localize(Lang::En),
|
||||
"{lang:?} is still English"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_language_falls_back_to_english() {
|
||||
for value in ["fr", "C", "x-unknown"] {
|
||||
let output = senbei(value).arg("--bogus").output().unwrap();
|
||||
assert!(
|
||||
text(&output.stderr).contains("error: unknown option '--bogus'"),
|
||||
"{value}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_console_is_translated_while_logs_and_json_stay_english() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let input = fixture(temp.path());
|
||||
let out = temp.path().join("out");
|
||||
let output = senbei("zh-CN")
|
||||
.arg(&input)
|
||||
.arg("--out")
|
||||
.arg(&out)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", text(&output.stderr));
|
||||
let summary = Cli::Summary {
|
||||
unpacked: "0".into(),
|
||||
skipped: "0".into(),
|
||||
errors: "0".into(),
|
||||
suspect: "0".into(),
|
||||
metadata: "1".into(),
|
||||
};
|
||||
let stdout = text(&output.stdout);
|
||||
assert!(stdout.contains(&*summary.localize(Lang::ZhCn)), "{stdout}");
|
||||
assert!(!stdout.contains("unpacked"), "{stdout}");
|
||||
|
||||
let log = std::fs::read_dir(&out)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.find(|path| path.extension().is_some_and(|value| value == "log"))
|
||||
.expect("a run log");
|
||||
let log = std::fs::read_to_string(log).unwrap();
|
||||
assert!(
|
||||
log.contains("summary: 0 unpacked · 0 skipped · 0 errors · 0 suspect · 1 metadata"),
|
||||
"{log}"
|
||||
);
|
||||
|
||||
let json = |lang: &str| {
|
||||
let output = senbei(lang)
|
||||
.args(["inspect", "--json"])
|
||||
.arg(&input)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
without_timings(text(&output.stdout))
|
||||
};
|
||||
assert_eq!(json("ko"), json("en"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_text_translates_summary_lines_but_keeps_values() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let input = fixture(temp.path());
|
||||
let output = senbei("ja").arg("inspect").arg(&input).output().unwrap();
|
||||
assert!(output.status.success());
|
||||
let stdout = text(&output.stdout);
|
||||
let recovery = Cli::StaticRecovery {
|
||||
status: senbei_i18n::Term::Succeeded.localize(Lang::Ja).into_owned(),
|
||||
};
|
||||
assert!(stdout.contains(&*recovery.localize(Lang::Ja)), "{stdout}");
|
||||
assert!(!stdout.contains("static recovery"), "{stdout}");
|
||||
// Paths and the structural evidence are values, never translated.
|
||||
assert!(stdout.contains(&*input.display().to_string()), "{stdout}");
|
||||
assert!(stdout.contains("tried_seeds"), "{stdout}");
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! A front end follows a run through an observer and can stop it between
|
||||
//! inputs. The CLI uses neither, so its output and reports are unaffected.
|
||||
|
||||
#[path = "support/fixtures.rs"]
|
||||
mod fixtures;
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use senbei_engine::android::ResourceLimits;
|
||||
use senbei_io::job::{self, Collector, Mode};
|
||||
use senbei_io::observe::{CancelToken, RunObserver};
|
||||
use senbei_io::report::InputReport;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recorder {
|
||||
events: Mutex<Vec<String>>,
|
||||
/// Cancelled when the first input finishes.
|
||||
stop_after_first: Option<CancelToken>,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
fn push(&self, event: String) {
|
||||
self.events.lock().unwrap().push(event);
|
||||
}
|
||||
|
||||
fn events(&self) -> Vec<String> {
|
||||
self.events.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_name(path: &Path) -> String {
|
||||
path.parent()
|
||||
.and_then(Path::file_name)
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
impl RunObserver for Recorder {
|
||||
fn scanned(&self, inputs: usize) {
|
||||
self.push(format!("scanned {inputs}"));
|
||||
}
|
||||
|
||||
fn input_started(&self, path: &Path) {
|
||||
self.push(format!("started {}", parent_name(path)));
|
||||
}
|
||||
|
||||
fn progress(&self, event: &senbei_engine::progress::Event) {
|
||||
if let senbei_engine::progress::Event::Step { step, .. } = event {
|
||||
self.push(
|
||||
format!("step {step:?}")
|
||||
.split(' ')
|
||||
.take(2)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn input_finished(&self, input: &InputReport) {
|
||||
self.push(format!("finished {}", parent_name(Path::new(&input.path))));
|
||||
if let Some(cancel) = &self.stop_after_first {
|
||||
cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two applications, each with its own obfuscated metadata blob.
|
||||
fn two_apps(root: &Path) {
|
||||
for app in ["a", "b"] {
|
||||
let dir = root.join(app);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("global-metadata.dat"),
|
||||
fixtures::obfuscated_metadata(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn run(root: &Path, out: &Path, collector: &mut Collector) {
|
||||
job::run_folder_reported(
|
||||
root,
|
||||
Some(out),
|
||||
2,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
&ResourceLimits::default(),
|
||||
collector,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_observer_sees_each_input_start_progress_and_finish() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
two_apps(temp.path());
|
||||
let recorder = Arc::new(Recorder::default());
|
||||
let mut collector = Collector::new(Mode::Unpack).with_observer(recorder.clone());
|
||||
run(temp.path(), &temp.path().join("out"), &mut collector);
|
||||
assert_eq!(
|
||||
recorder.events(),
|
||||
[
|
||||
"scanned 2",
|
||||
"started a",
|
||||
"step WriteTo",
|
||||
"finished a",
|
||||
"started b",
|
||||
"step WriteTo",
|
||||
"finished b",
|
||||
]
|
||||
);
|
||||
let report = collector.finish();
|
||||
assert_eq!(report.inputs.len(), 2);
|
||||
assert!(!report.cancelled);
|
||||
assert!(!report.to_json().contains("cancelled"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_stops_before_the_next_input_and_is_reported() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
two_apps(temp.path());
|
||||
let cancel = CancelToken::new();
|
||||
let recorder = Arc::new(Recorder {
|
||||
stop_after_first: Some(cancel.clone()),
|
||||
..Recorder::default()
|
||||
});
|
||||
let mut collector = Collector::new(Mode::Unpack)
|
||||
.with_observer(recorder.clone())
|
||||
.with_cancel(cancel);
|
||||
let out = temp.path().join("out");
|
||||
run(temp.path(), &out, &mut collector);
|
||||
assert_eq!(
|
||||
recorder.events(),
|
||||
["scanned 2", "started a", "step WriteTo", "finished a"]
|
||||
);
|
||||
let report = collector.finish();
|
||||
assert_eq!(report.inputs.len(), 1);
|
||||
assert!(report.cancelled);
|
||||
assert!(report.to_json().contains("\"cancelled\":true"));
|
||||
assert!(out.join("a").join("global-metadata.unpack.dat").is_file());
|
||||
assert!(!out.join("b").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_cancelled_before_it_starts_processes_nothing() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
two_apps(temp.path());
|
||||
let cancel = CancelToken::new();
|
||||
cancel.cancel();
|
||||
let mut collector = Collector::new(Mode::DryRun).with_cancel(cancel);
|
||||
run(temp.path(), &temp.path().join("out"), &mut collector);
|
||||
let report = collector.finish();
|
||||
assert!(report.inputs.is_empty());
|
||||
assert!(report.cancelled);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ fn unreadable_unpack_input_blocks_routes_instead_of_inventing_an_attempt() {
|
||||
|
||||
fn senbei() -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
|
||||
command.arg("--no-pause");
|
||||
command.arg("--no-pause").env("SENBEI_LANG", "en");
|
||||
command
|
||||
}
|
||||
|
||||
@@ -638,6 +638,7 @@ fn a_relative_path_is_reported_verbatim() {
|
||||
let td = tempfile::tempdir().unwrap();
|
||||
write_plain(td.path(), "plain.exe");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_senbei"))
|
||||
.env("SENBEI_LANG", "en")
|
||||
.current_dir(td.path())
|
||||
.args(["--no-pause", "inspect", "plain.exe", "--json"])
|
||||
.output()
|
||||
|
||||
@@ -2,7 +2,9 @@ use std::process::Command;
|
||||
|
||||
fn command() -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
|
||||
command.args(["--no-pause", "--no-log"]);
|
||||
command
|
||||
.args(["--no-pause", "--no-log"])
|
||||
.env("SENBEI_LANG", "en");
|
||||
command
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@ use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn senbei() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_senbei"))
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
|
||||
command.env("SENBEI_LANG", "en");
|
||||
command
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
|
||||
@@ -835,10 +835,16 @@ fn run_pe(
|
||||
output.detected_kind = Some(kind_name(image.kind).to_owned());
|
||||
output.bytes = Some(image.bytes.len() as u64);
|
||||
output.sha256 = Some(sha256_hex(&image.bytes));
|
||||
let issues: Vec<String> = image
|
||||
.integrity
|
||||
.issues
|
||||
.iter()
|
||||
.map(|issue| issue.text().to_owned())
|
||||
.collect();
|
||||
output.integrity = Some(IntegrityInfo {
|
||||
ok: image.integrity.ok(),
|
||||
fatal: image.integrity.has_fatal(),
|
||||
issues: image.integrity.issues.clone(),
|
||||
issues: issues.clone(),
|
||||
});
|
||||
if expect_failure {
|
||||
output.fail("expected failure, but the input unpacked");
|
||||
@@ -847,13 +853,7 @@ fn run_pe(
|
||||
"expected failure, but the input unpacked",
|
||||
);
|
||||
} else {
|
||||
compare_output(
|
||||
&mut output,
|
||||
&image.bytes,
|
||||
expected,
|
||||
allow_suspect,
|
||||
&image.integrity.issues,
|
||||
);
|
||||
compare_output(&mut output, &image.bytes, expected, allow_suspect, &issues);
|
||||
finish_case(report, &mut output, "unpacked");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
use std::process::Command;
|
||||
|
||||
fn senbei() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_senbei"))
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
|
||||
command.env("SENBEI_LANG", "en");
|
||||
command
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user