Skip to content

Commit

Permalink
Review fixes part 5
Browse files Browse the repository at this point in the history
  • Loading branch information
micahsnyder committed Nov 3, 2023
1 parent c947ac8 commit 22e943f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 24 deletions.
8 changes: 4 additions & 4 deletions libclamav_rust/src/fmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ impl<'a> FMap {
}

pub fn name(&self) -> &'static str {
let name_result = unsafe { str_from_ptr((*self.fmap_ptr).name) };
match name_result {
Ok(Some(name)) => name,
_ => "",
unsafe {
str_from_ptr((*self.fmap_ptr).name)
.unwrap_or(Some("<invalid-utf8>"))
.unwrap_or("<unnamed>")
}
}
}
43 changes: 23 additions & 20 deletions libclamav_rust/src/fuzzy_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ use image::{imageops::FilterType::Lanczos3, DynamicImage, ImageBuffer, Luma, Pix
use log::{debug, error, warn};
use num_traits::{NumCast, ToPrimitive, Zero};
use rustdct::DctPlanner;
use thiserror::Error;
use thiserror;
use transpose::transpose;

use crate::{ffi_error, ffi_util::FFIError, rrf_call, sys, validate_str_param};

/// CdiffError enumerates all possible errors returned by this library.
#[derive(Error, Debug)]
pub enum FuzzyHashError {
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Invalid format")]
Format,

Expand All @@ -68,6 +68,9 @@ pub enum FuzzyHashError {

#[error("{0} parmeter is NULL")]
NullParam(&'static str),

#[error("{0} hash must be 16 characters in length")]
InvalidHashLength(&'static str),
}

#[derive(PartialEq, Eq, Hash, Debug)]
Expand All @@ -81,18 +84,18 @@ pub enum FuzzyHash {
}

impl TryFrom<&str> for ImageFuzzyHash {
type Error = &'static str;
type Error = Error;

fn try_from(value: &str) -> Result<Self, Self::Error> {
if value.len() != 16 {
return Err("Image fuzzy hash must be 16 characters in length");
return Err(Error::InvalidHashLength("ImageFuzzyHash"));
}

let mut hashbytes = [0; 8];
if hex::decode_to_slice(value, &mut hashbytes).is_ok() {
Ok(ImageFuzzyHash { bytes: hashbytes })
} else {
Err("Failed to decode image fuzzy hash bytes from hex to bytes")
Err(Error::FormatHashBytes(value.to_string()))
}
}
}
Expand Down Expand Up @@ -205,11 +208,11 @@ pub unsafe extern "C" fn _fuzzy_hash_calculate_image(
err: *mut *mut FFIError,
) -> bool {
if hash_out.is_null() {
return ffi_error!(err = err, FuzzyHashError::NullParam("hash_out"));
return ffi_error!(err = err, Error::NullParam("hash_out"));
}

let buffer = if file_bytes.is_null() {
return ffi_error!(err = err, FuzzyHashError::NullParam("file_bytes"));
return ffi_error!(err = err, Error::NullParam("file_bytes"));
} else {
slice::from_raw_parts(file_bytes, file_size)
};
Expand All @@ -223,7 +226,7 @@ pub unsafe extern "C" fn _fuzzy_hash_calculate_image(
if hash_out_len < hash_bytes.len() {
return ffi_error!(
err = err,
FuzzyHashError::InvalidParameter(format!(
Error::InvalidParameter(format!(
"hash_bytes output parameter too small to hold the hash: {} < {}",
hash_out_len,
hash_bytes.len()
Expand Down Expand Up @@ -257,24 +260,24 @@ impl FuzzyHashMap {
hexsig: &str,
lsig_id: u32,
subsig_id: u32,
) -> Result<(), FuzzyHashError> {
) -> Result<(), Error> {
let mut hexsig_split = hexsig.split('#');

let algorithm = match hexsig_split.next() {
Some(x) => x,
None => return Err(FuzzyHashError::Format),
None => return Err(Error::Format),
};

let hash = match hexsig_split.next() {
Some(x) => x,
None => return Err(FuzzyHashError::Format),
None => return Err(Error::Format),
};

let distance: u32 = match hexsig_split.next() {
Some(x) => match x.parse::<u32>() {
Ok(n) => n,
Err(_) => {
return Err(FuzzyHashError::FormatHammingDistance(x.to_string()));
return Err(Error::FormatHammingDistance(x.to_string()));
}
},
None => 0,
Expand All @@ -285,15 +288,15 @@ impl FuzzyHashMap {
error!(
"Non-zero hamming distances for image fuzzy hashes are not supported in this version."
);
return Err(FuzzyHashError::InvalidHammingDistance(distance));
return Err(Error::InvalidHammingDistance(distance));
}

match algorithm {
"fuzzy_img" => {
// Convert the hash string to an image fuzzy hash bytes struct
let image_fuzzy_hash = hash
.try_into()
.map_err(|e| FuzzyHashError::FormatHashBytes(format!("{}: {}", e, hash)))?;
.map_err(|e| Error::FormatHashBytes(format!("{}: {}", e, hash)))?;

let fuzzy_hash = FuzzyHash::Image(image_fuzzy_hash);

Expand All @@ -315,7 +318,7 @@ impl FuzzyHashMap {
}
_ => {
error!("Unknown fuzzy hash algorithm: {}", algorithm);
Err(FuzzyHashError::UnknownAlgorithm(algorithm.to_string()))
Err(Error::UnknownAlgorithm(algorithm.to_string()))
}
}
}
Expand Down Expand Up @@ -412,17 +415,17 @@ impl FuzzyHashMap {
///
/// param: hash_out is an output variable
/// param: hash_out_len indicates the size of the hash_out buffer
pub fn fuzzy_hash_calculate_image(buffer: &[u8]) -> Result<Vec<u8>, FuzzyHashError> {
pub fn fuzzy_hash_calculate_image(buffer: &[u8]) -> Result<Vec<u8>, Error> {

// Load image and attempt to catch panics in case the decoders encounter unexpected issues
let result = panic::catch_unwind(|| -> Result<DynamicImage, FuzzyHashError> {
let image = image::load_from_memory(buffer).map_err(FuzzyHashError::ImageLoad)?;
let result = panic::catch_unwind(|| -> Result<DynamicImage, Error> {
let image = image::load_from_memory(buffer).map_err(Error::ImageLoad)?;
Ok(image)
});

let og_image = match result {
Ok(image) => image?,
Err(_) => return Err(FuzzyHashError::ImageLoadPanic()),
Err(_) => return Err(Error::ImageLoadPanic()),
};

// Drop the alpha channel (if exists).
Expand Down
2 changes: 2 additions & 0 deletions libclamav_rust/src/onenote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ impl<'a> OneNote<'a> {

let embedded_files: Vec<ExtractedFile> = vec![];

// Verify that the OneNote document file magic is correct.
// We don't check this for the onenote_parser crate because it does this for us, and may add support for newer OneNote file formats in the future.
let file_magic = data.get(0..16).ok_or(Error::Format)?;
if file_magic != ONE_MAGIC {
return Err(Error::Format);
Expand Down

0 comments on commit 22e943f

Please sign in to comment.