diff --git a/senbei-io/src/android/mod.rs b/senbei-io/src/android/mod.rs index 768f689..b92a035 100644 --- a/senbei-io/src/android/mod.rs +++ b/senbei-io/src/android/mod.rs @@ -204,6 +204,66 @@ pub fn inspect_package(package: &Path, limits: &ResourceLimits) -> Result::` +/// for an APK, `\::` inside a bundle. Only the +/// named entry (and, in a bundle, the nested APK holding it) is extracted, under +/// the same archive ceilings as a restore. +pub fn read_package_entry(package: &Path, label: &str, limits: &ResourceLimits) -> Result> { + let (outer, inner) = label + .rsplit_once("::") + .with_context(|| format!("`{label}` names no package entry"))?; + let bundle = package + .extension() + .and_then(|value| value.to_str()) + .is_some_and(|value| { + value.eq_ignore_ascii_case("apks") || value.eq_ignore_ascii_case("xapk") + }); + let temporary = tempfile::tempdir().context("create entry workspace")?; + let mut budget = archive_limits::ArchiveBudget::from_limits(limits); + let mut archive = budget.open_archive(package)?; + let entry_index = |archive: &mut ZipArchive, + wanted: &dyn Fn(&Path) -> bool| + -> Result> { + for index in 0..archive.len() { + let entry = archive.by_index(index)?; + if entry.is_dir() { + continue; + } + if let Some(name) = entry.enclosed_name() + && wanted(&name) + { + return Ok(Some((index, name))); + } + } + Ok(None) + }; + let names = |name: &Path, label: &str| name.display().to_string() == label; + let path = if bundle { + // The nested APK is the top-level entry the label's package part ends with. + let (index, name) = entry_index(&mut archive, &|name: &Path| { + let name = name.display().to_string(); + outer.ends_with(&name) && outer[..outer.len() - name.len()].ends_with(['\\', '/']) + })? + .with_context(|| format!("`{outer}` is not in `{}`", package.display()))?; + limits.check_depth(1)?; + let nested_path = extract_entry(&mut archive, index, &temporary, &name, &mut budget) + .with_context(|| format!("extract `{}`", name.display()))?; + let mut nested = budget.open_archive(&nested_path)?; + let (index, name) = entry_index(&mut nested, &|name: &Path| names(name, inner))? + .with_context(|| format!("`{inner}` is not in `{outer}`"))?; + extract_entry(&mut nested, index, &temporary, &name, &mut budget) + .with_context(|| format!("extract `{label}`"))? + } else { + let (index, name) = entry_index(&mut archive, &|name: &Path| names(name, inner))? + .with_context(|| format!("`{inner}` is not in `{}`", package.display()))?; + extract_entry(&mut archive, index, &temporary, &name, &mut budget) + .with_context(|| format!("extract `{label}`"))? + }; + std::fs::read(&path).with_context(|| format!("read extracted `{label}`")) +} + fn manifest_report(source: &str, inventory: &context::PackageInventory) -> ManifestReport { let (package, version) = match &inventory.key { context::AppKey::Manifest { diff --git a/senbei-io/src/logfile.rs b/senbei-io/src/logfile.rs index 7027520..924d499 100644 --- a/senbei-io/src/logfile.rs +++ b/senbei-io/src/logfile.rs @@ -56,6 +56,15 @@ pub fn local_stamp_display() -> String { ) } +/// Local wall-clock `HH:MM:SS.mmm`, for the lines of a live run view. +pub fn local_clock() -> String { + let t = local_parts(); + format!( + "{:02}:{:02}:{:02}.{:03}", + t.hour, t.minute, t.second, t.millisecond + ) +} + struct LocalParts { year: u32, month: u32, @@ -63,6 +72,7 @@ struct LocalParts { hour: u32, minute: u32, second: u32, + millisecond: u32, } fn local_parts() -> LocalParts { @@ -77,16 +87,17 @@ fn local_parts() -> LocalParts { hour: st.wHour as u32, minute: st.wMinute as u32, second: st.wSecond as u32, + millisecond: st.wMilliseconds as u32, } } #[cfg(all(not(windows), not(target_arch = "wasm32")))] { // Local wall clock via POSIX localtime_r — same semantics as Windows GetLocalTime. use std::time::{SystemTime, UNIX_EPOCH}; - let secs_u = SystemTime::now() + let now = SystemTime::now() .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); + .unwrap_or_default(); + let secs_u = now.as_secs(); let t: libc::time_t = secs_u as libc::time_t; let mut tm = unsafe { std::mem::zeroed::() }; let ok = unsafe { libc::localtime_r(&t, &mut tm) }; @@ -100,6 +111,7 @@ fn local_parts() -> LocalParts { hour: tm.tm_hour as u32, minute: tm.tm_min as u32, second: tm.tm_sec as u32, + millisecond: now.subsec_millis(), } } #[cfg(all(not(windows), target_arch = "wasm32"))] @@ -134,6 +146,7 @@ fn utc_parts(secs: u64) -> LocalParts { hour: time_of_day / 3600, minute: (time_of_day % 3600) / 60, second: time_of_day % 60, + millisecond: 0, } } diff --git a/senbei-io/src/observe.rs b/senbei-io/src/observe.rs index 4b96e74..9bb480d 100644 --- a/senbei-io/src/observe.rs +++ b/senbei-io/src/observe.rs @@ -22,6 +22,12 @@ pub trait RunObserver: Send + Sync { /// the run was started with `verbose`. fn progress(&self, _event: &senbei_engine::progress::Event) {} + /// One input finished, as recorded before a dry run or an inspection + /// drops its outputs. The files named by `outputs` and by each entry's + /// `output` exist for the duration of this call; a dry run or an + /// inspection deletes them when the run ends. + fn produced(&self, _input: &InputReport) {} + /// One input finished. This is the report the run keeps for it. fn input_finished(&self, _input: &InputReport) {} } diff --git a/senbei-io/src/report.rs b/senbei-io/src/report.rs index addd950..3f49249 100644 --- a/senbei-io/src/report.rs +++ b/senbei-io/src/report.rs @@ -634,6 +634,9 @@ impl Collector { input.analysis_incomplete = true; input.status = InputStatus::Error; } + if let Some(observer) = &self.observer { + observer.produced(&input); + } if matches!(self.mode, Mode::DryRun | Mode::Inspect) { // Research inspection and dry runs keep their actual recovery // outcomes, but never advertise temporary artifacts as outputs. diff --git a/senbei-io/src/scan.rs b/senbei-io/src/scan.rs index fb39811..e1213fb 100644 --- a/senbei-io/src/scan.rs +++ b/senbei-io/src/scan.rs @@ -1,6 +1,7 @@ use senbei_engine::detect; use std::io::Read; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; use walkdir::WalkDir; /// Bytes read per file for content detection. `detect` inspects the DOS/PE @@ -125,6 +126,26 @@ pub fn find_targets_with_limits( root: &Path, scan_all: bool, limits: &senbei_engine::android::ResourceLimits, +) -> ScanResult { + find_targets_inner(root, scan_all, limits, None) +} + +/// [`find_targets_with_limits`], counting targets into `found` as the content +/// probe classifies them, so a front end can show the scan's progress. +pub fn find_targets_counted( + root: &Path, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, + found: &AtomicUsize, +) -> ScanResult { + find_targets_inner(root, scan_all, limits, Some(found)) +} + +fn find_targets_inner( + root: &Path, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, + found: Option<&AtomicUsize>, ) -> ScanResult { // Phase 1: serial traversal collecting regular-file paths only. No file is // opened here; `readdir` is fast relative to the content probe that follows, @@ -190,17 +211,27 @@ pub fn find_targets_with_limits( let n = paths.len(); let mut class: Vec> = vec![Some(Class::None); n]; let workers = senbei_engine::thread_cap().clamp(1, n.max(1)); + let classify_counted = |path: &Path| { + let class = classify(path, limits); + if let Some(found) = found + && matches!(class, Some(c) if c != Class::None) + { + found.fetch_add(1, Ordering::Relaxed); + } + class + }; if workers <= 1 { for (p, c) in paths.iter().zip(class.iter_mut()) { - *c = classify(p, limits); + *c = classify_counted(p); } } else { let chunk = n.div_ceil(workers); + let classify_counted = &classify_counted; std::thread::scope(|scope| { for (pc, cc) in paths.chunks(chunk).zip(class.chunks_mut(chunk)) { scope.spawn(move || { for (p, c) in pc.iter().zip(cc.iter_mut()) { - *c = classify(p, limits); + *c = classify_counted(p); } }); } @@ -277,6 +308,55 @@ fn classify(path: &Path, limits: &senbei_engine::android::ResourceLimits) -> Opt r.ok() } +/// What one input is, judged the way a single-file run dispatches it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InputClass { + /// An il2cpp metadata blob, recognized by its magic. + Metadata, + /// A protected AArch64 shared library. + AndroidLibrary, + /// An Android app package (`.apk`/`.apks`/`.xapk`). + AndroidPackage, + /// A CrackProof-protected PE. + Windows, + /// None of these. A single-file run reports it as not protected. + NotTarget, +} + +/// Classify one input the way a single-file run would dispatch it, reading its +/// first 8 KiB (and, for an AArch64 ELF, the section table the probe needs). +/// +/// Unlike a folder scan, a single-file run is not bound to target filenames: a +/// metadata blob is recognized by its magic, whatever it is called. +pub fn classify_input( + path: &Path, + limits: &senbei_engine::android::ResourceLimits, +) -> std::io::Result { + let file = std::fs::File::open(path)?; + let mut head = Vec::with_capacity(DETECT_PREFIX as usize); + file.take(DETECT_PREFIX).read_to_end(&mut head)?; + let class = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if senbei_metadata::is_metadata(&head) { + return InputClass::Metadata; + } + if crate::android::is_elf64_aarch64(&head) { + return if crate::android::probe_so_file_with_limits(path, limits).unwrap_or(true) { + InputClass::AndroidLibrary + } else { + InputClass::NotTarget + }; + } + if crate::android::is_app_package(path, &head) { + return InputClass::AndroidPackage; + } + if detect(&head).is_some() { + return InputClass::Windows; + } + InputClass::NotTarget + })); + Ok(class.unwrap_or(InputClass::NotTarget)) +} + /// Read up to `max` bytes from the start of `path`. Returns `None` on any I/O /// error (the file is simply not treated as a candidate). fn read_prefix(path: &Path, max: u64) -> Option> { diff --git a/senbei-io/src/windows/mod.rs b/senbei-io/src/windows/mod.rs index 6808846..85d42a3 100644 --- a/senbei-io/src/windows/mod.rs +++ b/senbei-io/src/windows/mod.rs @@ -424,7 +424,7 @@ fn write_u32_at(buf: &mut [u8], off: usize, val: u32) { /// splice fires only when the first 32 bytes of `comp` equal the stub's header /// at offset 4096 — a 32-byte match on the key-table/magic region that confirms /// the pairing and leaves ordinary (non-companion) inputs untouched. -pub(crate) fn splice_companion(stub: &[u8], comp: &[u8]) -> Option> { +pub fn splice_companion(stub: &[u8], comp: &[u8]) -> Option> { let hdr_end = HEADER_OFF + 32; if stub.len() >= hdr_end && comp.len() >= 32 && stub[HEADER_OFF..hdr_end] == comp[..32] { let mut spliced = Vec::with_capacity(HEADER_OFF + comp.len());