use crate::MAX_RECURSION_DEPTH;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use anyhow::{Result, ensure};
use malwaredb_lzjd2::lzjd::LzDigest;
use rayon::prelude::*;
use walkdir::WalkDir;
#[inline]
pub fn lzjd_from_path<P: AsRef<Path>>(path: P) -> Result<LzDigest> {
ensure!(path.as_ref().is_file(), "Path must be a file");
let contents = std::fs::read(path)?;
ensure!(!contents.is_empty(), "empty file");
Ok(LzDigest::from(contents.as_slice()))
}
#[inline]
pub fn lzjd_compare_paths<P: AsRef<Path>>(path_a: P, path_b: P) -> Result<f32> {
let lzjd_a = lzjd_from_path(path_a)?;
let lzjd_b = lzjd_from_path(path_b)?;
Ok(lzjd_a.similarity(&lzjd_b))
}
#[derive(Debug, Clone)]
pub struct Similarity<P: AsRef<Path> + Send + Sync> {
pub path: P,
pub threshold: f32,
}
impl<P: AsRef<Path> + Send + Sync> Similarity<P> {
pub fn find<F>(&self, f: F) -> Result<usize>
where
F: Fn(&Path, &Path, f32) + Send + Sync,
{
ensure!(
self.path.as_ref().is_dir(),
"{} needs to be a directory",
self.path.as_ref().display()
);
let mut digests: Vec<(PathBuf, LzDigest)> = Vec::new();
for entry in WalkDir::new(&self.path)
.max_depth(MAX_RECURSION_DEPTH)
.follow_links(true)
.into_iter()
.flatten()
{
if entry.path().is_file() {
let digest = lzjd_from_path(entry.path())?;
digests.push((entry.into_path(), digest));
}
}
let similar_count = AtomicUsize::new(0);
digests
.par_iter()
.enumerate()
.for_each(|(index, (path_a, digest_a))| {
for (path_b, digest_b) in &digests[index + 1..] {
let similarity = digest_a.similarity(digest_b);
if similarity >= self.threshold {
f(path_a, path_b, similarity);
similar_count.fetch_add(1, Ordering::Relaxed);
}
}
});
Ok(similar_count.into_inner())
}
}