use std::fs::File;
use std::io::Read;
use std::time::Instant;
use legit_hashes::{
Algorithm, DECODE_MAX_ALLOC, DECODE_MAX_DIMENSION, DECODE_MAX_INPUT, Error as HashError, Hash, LumaBuf, RgbaBuf,
Signature, SignatureAlgorithm, blockhash_v1, decode_luma_v1, decode_rgba_v1, minhash_legacy_v1,
minhash_legacy_v1_shingles, minhash_v1, minhash_v1_shingles, pdq_v1, shingles_v1, simhash_v1, words_v1,
};
use sha1::{Digest, Sha1};
use crate::definition::{Definition, Input, Plan, Tokens};
use crate::inspect::{DECODED_FORMATS, Inspection, inspect};
use crate::orient::{moves_pixels, reorient};
use crate::request::{Entry, Orientation, Request, Source};
use crate::{DecodeFacts, DefinitionError, HashOutcome, Outcome, RequestError, SourceFacts, Timings};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Settings {
pub timings: bool,
pub max_pixels: Option<u64>,
pub max_text_bytes: Option<u64>,
}
pub(crate) fn text_too_large(length: usize, settings: Settings) -> Option<String> {
settings
.max_text_bytes
.filter(|most| length as u64 > *most)
.map(|most| format!("the text is `{length}` bytes; `--max-text-bytes` allows `{most}`"))
}
#[must_use]
pub fn hash(request: &Request, settings: Settings) -> Outcome {
let started = Instant::now();
let mut outcome = match &request.source {
Source::Text(text) => match text_too_large(text.len(), settings) {
Some(message) => Outcome::error(Some(request.id.clone()), RequestError::TooLarge, message),
None => hash_text(request, text),
},
Source::Path(path) => {
let read = Instant::now();
match read_file(path) {
Ok(bytes) => hash_image(request, &bytes, settings, Some(elapsed_us(read))),
Err((code, message)) => Outcome::error(Some(request.id.clone()), code, message),
}
}
Source::Bytes(bytes) => hash_image(request, bytes, settings, None),
};
if settings.timings {
let timings = outcome.timings.get_or_insert(Timings {
read_us: None,
decode_us: None,
total_us: 0,
});
timings.total_us = elapsed_us(started);
} else {
outcome.timings = None;
for entry in outcome.hashes.iter_mut().flatten() {
entry.time_us = None;
}
}
outcome
}
fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
bytes
.iter()
.flat_map(|byte| [DIGITS[usize::from(byte >> 4)], DIGITS[usize::from(byte & 15)]])
.map(char::from)
.collect()
}
fn elapsed_us(since: Instant) -> u64 {
u64::try_from(since.elapsed().as_micros()).unwrap_or(u64::MAX)
}
fn read_file(path: &std::path::Path) -> Result<Vec<u8>, (RequestError, String)> {
let failed = |error: std::io::Error| {
(
RequestError::ReadFailed,
format!("couldn't read `{}`: {error}", path.display()),
)
};
let file = File::open(path).map_err(failed)?;
let limit = DECODE_MAX_INPUT as u64;
let too_large = |bytes: u64| {
(
RequestError::TooLarge,
format!("`{}` is `{bytes}` bytes; at most `{limit}` are read", path.display()),
)
};
let length = file.metadata().map_err(failed)?.len();
if length > limit {
return Err(too_large(length));
}
let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
file.take(limit + 1).read_to_end(&mut bytes).map_err(failed)?;
if bytes.len() as u64 > limit {
return Err(too_large(bytes.len() as u64));
}
Ok(bytes)
}
fn wrong_source(entry: &Entry, plan: &Plan, image: bool) -> Option<HashOutcome> {
let id = plan.definition.id();
match (plan.definition.is_image(), image) {
(true, false) => Some(HashOutcome::failed(
&entry.id,
DefinitionError::WrongSource,
format!("`{id}` hashes images, and this request's source is text"),
)),
(false, true) => Some(HashOutcome::failed(
&entry.id,
DefinitionError::WrongSource,
format!("`{id}` hashes text, and this request's source is an image"),
)),
_ => None,
}
}
fn hash_text(request: &Request, text: &str) -> Outcome {
let mut outcome = Outcome::success(Some(request.id.clone()));
let hashes = request
.options
.definitions
.iter()
.map(|entry| match &entry.plan {
Err(failure) => HashOutcome::failed(&entry.id, failure.code, &failure.message),
Ok(plan) => wrong_source(entry, plan, false).unwrap_or_else(|| text_hash(entry, plan, text)),
})
.collect();
outcome.hashes = Some(hashes);
outcome
}
fn text_hash(entry: &Entry, plan: &Plan, text: &str) -> HashOutcome {
let started = Instant::now();
let mut result = HashOutcome::new(&entry.id);
let tokens = plan.tokens.unwrap_or(Tokens::Words);
match tokens {
Tokens::Words => result.tokens = Some("words"),
Tokens::Shingles(size) => result.shingle = Some(size),
}
let computed: Result<(), HashError> = (|| {
match plan.definition {
Definition::Bit(Algorithm::SimHashV1) => {
let hash = match tokens {
Tokens::Words => simhash_v1(words_v1(text).map(|word| (word, 1))),
Tokens::Shingles(size) => simhash_v1(shingles_v1(text, size as usize)?.map(|shingle| (shingle, 1))),
};
bit_hash(&mut result, &hash, plan)?;
}
Definition::Signature(algorithm) => {
let signature = signature(algorithm, tokens, text)?;
result.value = Some(signature.to_string());
result.empty = Some(signature.is_empty());
if let Some(bands) = plan.band_keys {
result.band_keys = Some(signature.band_keys_i64(bands)?);
}
}
Definition::Bit(algorithm) => return Err(HashError::NotAnImageAlgorithm(algorithm)),
}
Ok(())
})();
finish(result, computed, started)
}
fn signature(algorithm: SignatureAlgorithm, tokens: Tokens, text: &str) -> Result<Signature, HashError> {
match (algorithm, tokens) {
(SignatureAlgorithm::MinHashV1, Tokens::Words) => Ok(minhash_v1(words_v1(text))),
(SignatureAlgorithm::MinHashV1, Tokens::Shingles(size)) => minhash_v1_shingles(text, size as usize),
(SignatureAlgorithm::MinHashLegacyV1, Tokens::Words) => Ok(minhash_legacy_v1(words_v1(text))),
(SignatureAlgorithm::MinHashLegacyV1, Tokens::Shingles(size)) => {
minhash_legacy_v1_shingles(text, size as usize)
}
(other, _) => Err(HashError::UnknownAlgorithm(other.id().to_owned())),
}
}
fn bit_hash(result: &mut HashOutcome, hash: &Hash, plan: &Plan) -> Result<(), HashError> {
result.value = Some(hash.to_string());
if let Some(count) = plan.chunk_keys {
result.chunk_keys = Some(hash.chunks(count)?.into_iter().map(|key| key as i64).collect());
}
Ok(())
}
fn finish(mut result: HashOutcome, computed: Result<(), HashError>, started: Instant) -> HashOutcome {
match computed {
Ok(()) => {
result.time_us = Some(elapsed_us(started));
result
}
Err(error) => HashOutcome::failed(result.id, DefinitionError::InvalidParameter, error.to_string()),
}
}
struct Pixels {
rgba: Option<RgbaBuf>,
luma: Option<LumaBuf>,
width: u32,
height: u32,
}
fn hash_image(request: &Request, bytes: &[u8], settings: Settings, read_us: Option<u64>) -> Outcome {
let id = Some(request.id.clone());
let inspection = inspect(bytes);
let source = SourceFacts {
bytes: bytes.len() as u64,
sha1: hex(&Sha1::digest(bytes)),
};
let plans: Vec<&Plan> = request
.options
.definitions
.iter()
.filter_map(|entry| entry.plan.as_ref().ok())
.collect();
let wants = |input: Input| plans.iter().any(|plan| plan.definition.input() == input);
let (wants_rgba, wants_luma) = (wants(Input::Rgba), wants(Input::Luma));
let mut outcome = Outcome::success(id.clone());
outcome.source = Some(source.clone());
let fail = |code, message: String| {
let mut failed = Outcome::error(id.clone(), code, message);
failed.source = Some(source.clone());
failed.detected_format = Some(inspection.format);
failed.timings = read_us.map(|read_us| Timings {
read_us: Some(read_us),
decode_us: None,
total_us: 0,
});
failed
};
let mut decode_us = None;
if wants_rgba || wants_luma {
if !DECODED_FORMATS.contains(&inspection.format) {
return fail(
RequestError::DecodeFailed,
format!(
"unsupported format: {}; the runner decodes {}",
inspection.format,
DECODED_FORMATS.join(" and ")
),
);
}
if let Some(message) =
over_limits(&inspection, settings).or_else(|| over_decoders_size(bytes, &inspection, settings))
{
return fail(RequestError::TooLarge, message);
}
let started = Instant::now();
let orientation = match (request.options.orientation, inspection.orientation) {
(Orientation::Apply, Some(tag)) if moves_pixels(tag) => Some(tag),
_ => None,
};
let pixels = match decode(bytes, wants_rgba, wants_luma, orientation) {
Ok(pixels) => pixels,
Err(HashError::Decode(message)) if message.contains("limit") => {
return fail(RequestError::TooLarge, format!("couldn't decode the image: {message}"));
}
Err(error) => return fail(RequestError::DecodeFailed, error.to_string()),
};
decode_us = Some(elapsed_us(started));
if let Some(most) = settings.max_pixels
&& u64::from(pixels.width) * u64::from(pixels.height) > most
{
return fail(
RequestError::TooLarge,
format!(
"the image decoded to `{}x{}` pixels; `--max-pixels` allows `{most}`",
pixels.width, pixels.height
),
);
}
outcome.width = Some(pixels.width);
outcome.height = Some(pixels.height);
outcome.decode = Some(DecodeFacts {
format: inspection.format,
frames: inspection.frames.unwrap_or(1),
orientation_tag: inspection.orientation,
orientation_applied: orientation.is_some(),
truncated: inspection.truncated,
});
outcome.hashes = Some(image_hashes(request, &pixels));
} else {
outcome.hashes = Some(image_hashes(
request,
&Pixels {
rgba: None,
luma: None,
width: 0,
height: 0,
},
));
}
outcome.timings = Some(Timings {
read_us,
decode_us,
total_us: 0,
});
outcome
}
fn over_limits(inspection: &Inspection, settings: Settings) -> Option<String> {
let Some((width, height)) = inspection.size else {
return settings.max_pixels.map(|most| {
format!("its size could not be read before decoding, so `--max-pixels` (`{most}`) can't be held to; it isn't decoded")
});
};
if width > DECODE_MAX_DIMENSION || height > DECODE_MAX_DIMENSION {
return Some(format!(
"the image is `{width}x{height}`; a side may be at most `{DECODE_MAX_DIMENSION}` pixels"
));
}
let pixels = u64::from(width) * u64::from(height);
if let Some(bytes) = inspection.bytes_per_pixel.map(|each| pixels * each)
&& bytes > DECODE_MAX_ALLOC
{
return Some(format!(
"the image is `{width}x{height}`, `{bytes}` bytes decoded; the decoder may allocate at most `{DECODE_MAX_ALLOC}`"
));
}
match settings.max_pixels {
Some(most) if pixels > most => Some(format!(
"the image is `{width}x{height}`, `{pixels}` pixels; `--max-pixels` allows `{most}`"
)),
_ => None,
}
}
pub const MAX_METADATA_BYTES: u64 = 16 << 20;
fn over_decoders_size(bytes: &[u8], inspection: &Inspection, settings: Settings) -> Option<String> {
use image::ImageDecoder;
let most = settings.max_pixels?;
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.ok()?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(DECODE_MAX_DIMENSION);
limits.max_image_height = Some(DECODE_MAX_DIMENSION);
limits.max_alloc = Some(MAX_METADATA_BYTES);
reader.limits(limits);
let metadata = || {
format!(
"the decoder needs more than `{MAX_METADATA_BYTES}` bytes for the image's metadata, its ICC profile, or can't read it, before its size is known; `--max-pixels` is set"
)
};
let mut decoder = match reader.into_decoder() {
Ok(decoder) => decoder,
Err(image::ImageError::Limits(limit)) => {
return Some(match limit.kind() {
image::error::LimitErrorKind::DimensionError => format!(
"the decoder reads a side of more than `{DECODE_MAX_DIMENSION}` pixels; `--max-pixels` allows `{most}`"
),
_ => metadata(),
});
}
Err(_) => return None,
};
if inspection.icc_profile && !matches!(decoder.icc_profile(), Ok(Some(_))) {
return Some(metadata());
}
let (width, height) = decoder.dimensions();
let pixels = u64::from(width) * u64::from(height);
(pixels > most).then(|| {
format!("the decoder reads the image as `{width}x{height}`, `{pixels}` pixels; `--max-pixels` allows `{most}`")
})
}
fn decode(bytes: &[u8], rgba: bool, luma: bool, orientation: Option<u16>) -> Result<Pixels, HashError> {
if rgba {
let mut image = decode_rgba_v1(bytes)?;
if let Some(tag) = orientation {
let (width, height, pixels) = reorient(image.width(), image.height(), 4, image.into_pixels(), tag);
image = RgbaBuf::new(width, height, pixels)?;
}
let luma = if luma {
Some(LumaBuf::from_rgba8_v1(image.width(), image.height(), image.pixels())?)
} else {
None
};
return Ok(Pixels {
width: image.width(),
height: image.height(),
rgba: Some(image),
luma,
});
}
let mut image = decode_luma_v1(bytes)?;
if let Some(tag) = orientation {
let (width, height, pixels) = reorient(image.width(), image.height(), 1, image.into_pixels(), tag);
image = LumaBuf::new(width, height, pixels)?;
}
Ok(Pixels {
width: image.width(),
height: image.height(),
rgba: None,
luma: Some(image),
})
}
fn image_hashes(request: &Request, pixels: &Pixels) -> Vec<HashOutcome> {
request
.options
.definitions
.iter()
.map(|entry| match &entry.plan {
Err(failure) => HashOutcome::failed(&entry.id, failure.code, &failure.message),
Ok(plan) => wrong_source(entry, plan, true).unwrap_or_else(|| image_hash(entry, plan, pixels)),
})
.collect()
}
fn image_hash(entry: &Entry, plan: &Plan, pixels: &Pixels) -> HashOutcome {
let started = Instant::now();
let mut result = HashOutcome::new(&entry.id);
let computed: Result<(), HashError> = (|| {
let Definition::Bit(algorithm) = plan.definition else {
return Err(HashError::UnknownAlgorithm(plan.definition.id().to_owned()));
};
let hash = match (algorithm, &pixels.rgba, &pixels.luma) {
(Algorithm::PdqV1, Some(rgba), _) => {
let pdq = pdq_v1(rgba.view());
result.quality = Some(pdq.quality);
pdq.hash
}
(Algorithm::BlockhashV1, Some(rgba), _) => blockhash_v1(rgba.view()),
(_, _, Some(luma)) => algorithm.hash_luma(luma.view())?,
_ => return Err(HashError::NotAnImageAlgorithm(algorithm)),
};
bit_hash(&mut result, &hash, plan)
})();
finish(result, computed, started)
}