use crate::errors::ToolError;
pub const OCTET_STREAM: &str = "application/octet-stream";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentType {
pub value: String,
pub disagreement: Option<String>,
}
pub fn decide(declared: Option<&str>, data: &[u8]) -> Result<ContentType, ToolError> {
let sniffed = sniff(data);
match (declared, sniffed) {
(Some(declared), Some(sniffed)) if types_agree(declared, sniffed) => Ok(ContentType {
value: sniffed.to_string(),
disagreement: None,
}),
(Some(declared), Some(sniffed)) => Ok(ContentType {
value: sniffed.to_string(),
disagreement: Some(format!(
"content_type was given as '{declared}' but the bytes are '{sniffed}'; \
recorded the type determined from the bytes"
)),
}),
(Some(declared), None) => Ok(ContentType {
value: declared.to_string(),
disagreement: None,
}),
(None, Some(sniffed)) => Ok(ContentType {
value: sniffed.to_string(),
disagreement: None,
}),
(None, None) => Err(ToolError::ContentTypeUndetermined),
}
}
#[must_use]
pub fn sniff(data: &[u8]) -> Option<&'static str> {
infer::get(data).map(|kind| kind.mime_type())
}
fn types_agree(one: &str, other: &str) -> bool {
let normal = |value: &str| {
let base = base_type(value);
if base == "image/jpg" {
"image/jpeg".to_string()
} else {
base
}
};
normal(one) == normal(other)
}
fn base_type(value: &str) -> String {
value
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
}
#[must_use]
pub fn is_generic(mime_type: &str) -> bool {
let base = base_type(mime_type);
base.is_empty() || base == OCTET_STREAM
}
pub fn check_declared(value: &str) -> Result<(), String> {
let name = |part: &str| {
!part.is_empty()
&& part
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
};
let visible = value.len() <= 255 && value.bytes().all(|b| (0x20..0x7f).contains(&b));
let base = value.split(';').next().unwrap_or("").trim();
match base.split_once('/') {
Some((kind, subtype)) if visible && name(kind) && name(subtype) => Ok(()),
_ => Err(format!(
"the 'mime_type' argument must be a content type such as 'image/png', as the blob \
reference's mimeType gives it; got {value:?}"
)),
}
}
#[must_use]
pub fn wants_sniff(served: Option<&str>, declared: Option<&str>) -> bool {
served.is_none_or(is_generic) || declared.is_some_and(|declared| !is_generic(declared))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServedType {
pub value: String,
pub disagreement: Option<String>,
}
#[must_use]
pub fn resolve_served(
served: Option<&str>,
declared: Option<&str>,
sniffed: Option<&str>,
) -> ServedType {
let served_specific = served.filter(|served| !is_generic(served));
let declared_specific = declared.filter(|declared| !is_generic(declared));
let value = match (served_specific, declared_specific, sniffed) {
(Some(served), _, _) => served,
(None, Some(declared), Some(sniffed)) if !types_agree(declared, sniffed) => sniffed,
(None, Some(declared), _) => declared,
(None, None, Some(sniffed)) => sniffed,
(None, None, None) => OCTET_STREAM,
};
let mut disagreements = Vec::new();
if let Some(declared) = declared_specific {
if let Some(served) = served_specific
&& !types_agree(declared, served)
{
disagreements.push(format!(
"the blob reference declares '{declared}' but the host served '{served}'"
));
}
if let Some(sniffed) = sniffed
&& !types_agree(declared, sniffed)
{
disagreements.push(format!(
"the blob reference declares '{declared}' but the bytes are '{sniffed}'"
));
}
}
ServedType {
value: value.to_string(),
disagreement: (!disagreements.is_empty()).then(|| disagreements.join("; ")),
}
}
#[must_use]
pub fn is_image(mime_type: &str) -> bool {
base_type(mime_type).starts_with("image/")
}
#[cfg(test)]
mod tests {
use super::*;
const PNG: &[u8] = &[
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
0x52,
];
const GIF: &[u8] = b"GIF89a\x01\x00\x01\x00\x00\x00\x00";
#[test]
fn sniffs_known_formats() {
assert_eq!(sniff(PNG), Some("image/png"));
assert_eq!(sniff(GIF), Some("image/gif"));
}
#[test]
fn plain_text_has_no_magic_bytes() {
assert_eq!(sniff(b"just some text"), None);
}
#[test]
fn sniffed_type_is_used_when_nothing_is_declared() {
let decided = decide(None, PNG).unwrap();
assert_eq!(decided.value, "image/png");
assert!(decided.disagreement.is_none());
}
#[test]
fn agreeing_declaration_produces_no_complaint() {
let decided = decide(Some("image/png"), PNG).unwrap();
assert_eq!(decided.value, "image/png");
assert!(decided.disagreement.is_none());
}
#[test]
fn parameters_and_case_do_not_count_as_disagreement() {
let decided = decide(Some("IMAGE/PNG; charset=binary"), PNG).unwrap();
assert!(decided.disagreement.is_none());
}
#[test]
fn image_jpg_is_treated_as_image_jpeg() {
let jpeg = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46];
let decided = decide(Some("image/jpg"), jpeg).unwrap();
assert_eq!(decided.value, "image/jpeg");
assert!(decided.disagreement.is_none());
}
#[test]
fn disagreement_is_reported_and_the_bytes_win() {
let decided = decide(Some("image/gif"), PNG).unwrap();
assert_eq!(decided.value, "image/png");
let complaint = decided.disagreement.expect("disagreement is reported");
assert!(complaint.contains("image/gif"));
assert!(complaint.contains("image/png"));
}
#[test]
fn a_declaration_stands_when_the_bytes_are_unrecognised() {
let decided = decide(Some("text/plain"), b"just some text").unwrap();
assert_eq!(decided.value, "text/plain");
assert!(decided.disagreement.is_none());
}
#[test]
fn undetermined_is_an_error_rather_than_a_guess() {
let error = decide(None, b"just some text").expect_err("nothing to go on");
assert!(matches!(error, ToolError::ContentTypeUndetermined));
assert!(error.to_string().contains("error-atpmcp-tool-14"));
}
#[test]
fn an_octet_stream_png_is_reported_by_its_reference_or_its_bytes() {
let by_reference = resolve_served(Some(OCTET_STREAM), Some("image/png"), Some("image/png"));
assert_eq!(by_reference.value, "image/png");
assert!(by_reference.disagreement.is_none());
let by_bytes = resolve_served(Some(OCTET_STREAM), None, Some("image/png"));
assert_eq!(by_bytes.value, "image/png");
assert!(by_bytes.disagreement.is_none());
}
#[test]
fn a_declared_type_stands_in_for_a_generic_one_when_the_bytes_say_nothing() {
for served in [
Some(OCTET_STREAM),
Some("Application/Octet-Stream; charset=binary"),
Some(""),
None,
] {
let decided = resolve_served(served, Some("text/plain"), None);
assert_eq!(decided.value, "text/plain", "{served:?}");
assert!(decided.disagreement.is_none());
}
}
#[test]
fn the_bytes_win_over_a_declared_type_they_contradict() {
let decided = resolve_served(
Some(OCTET_STREAM),
Some("image/png"),
Some("application/pdf"),
);
assert_eq!(decided.value, "application/pdf");
let note = decided.disagreement.expect("the contradiction is reported");
assert!(
note.contains("image/png") && note.contains("application/pdf"),
"{note}"
);
}
#[test]
fn a_specific_served_type_stands_and_a_declared_one_is_checked_against_it() {
let alone = resolve_served(Some("image/jpeg"), None, None);
assert_eq!(alone.value, "image/jpeg");
assert!(alone.disagreement.is_none());
let disagreeing = resolve_served(Some("image/jpeg"), Some("image/png"), Some("image/png"));
assert_eq!(disagreeing.value, "image/jpeg");
let note = disagreeing.disagreement.expect("reported, not refused");
assert!(note.contains("the host served 'image/jpeg'"), "{note}");
assert!(!note.contains("the bytes"), "the bytes agree: {note}");
let agreeing = resolve_served(Some("IMAGE/JPEG; q=1"), Some("image/jpg"), None);
assert!(agreeing.disagreement.is_none());
}
#[test]
fn with_nothing_to_go_on_a_blob_is_octet_stream() {
let decided = resolve_served(None, None, None);
assert_eq!(decided.value, OCTET_STREAM);
let generic = resolve_served(Some(OCTET_STREAM), Some(OCTET_STREAM), Some("image/gif"));
assert_eq!(generic.value, "image/gif");
assert!(generic.disagreement.is_none());
}
#[test]
fn a_sniff_is_wanted_only_when_it_can_change_the_answer() {
assert!(wants_sniff(None, None));
assert!(wants_sniff(Some(OCTET_STREAM), None));
assert!(wants_sniff(Some("image/png"), Some("image/png")));
assert!(!wants_sniff(Some("image/png"), None));
assert!(!wants_sniff(Some("image/png"), Some(OCTET_STREAM)));
}
#[test]
fn a_declared_type_must_be_a_content_type() {
for good in [
"image/png",
"text/plain; charset=utf-8",
"application/vnd.ipld.car",
"image/svg+xml",
] {
assert!(check_declared(good).is_ok(), "{good}");
}
for bad in [
"",
"png",
"image/",
"/png",
"image/png/x",
"image /png",
"image/png\n",
"imäge/png",
] {
let error = check_declared(bad).expect_err(bad);
assert!(error.contains("'mime_type'"), "{error}");
}
assert!(check_declared(&format!("image/{}", "x".repeat(300))).is_err());
}
#[test]
fn image_detection_ignores_parameters() {
assert!(is_image("image/png"));
assert!(is_image("IMAGE/JPEG; charset=binary"));
assert!(!is_image("application/pdf"));
assert!(!is_image("text/plain"));
}
}