This repository has been archived by the owner on Mar 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
magic.rs
121 lines (106 loc) · 3.31 KB
/
magic.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Copyright 2018-2020 Sebastian Wiesner <sebastian@swsnr.de>
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! Magic util functions for detecting image types.
use anyhow::Result;
use anyhow::{anyhow, Context};
use mime::Mime;
use tracing::{event, Level};
/// Whether the given data is SVG data.
pub fn is_svg(buffer: &[u8]) -> bool {
is_mimetype(buffer, &mime::IMAGE_SVG)
}
/// Whether the given data is a PNG image.
pub fn is_png(buffer: &[u8]) -> bool {
is_mimetype(buffer, &mime::IMAGE_PNG)
}
fn is_mimetype(buffer: &[u8], mime: &Mime) -> bool {
get_mimetype_for_buffer_with_file(buffer).map_or_else(
|error| {
event!(
Level::WARN,
?error,
"checking for mime type {} failed: {}",
mime,
error
);
false
},
|detected| detected == *mime,
)
}
fn get_mimetype_for_buffer_with_file(buffer: &[u8]) -> Result<Mime> {
use std::io::prelude::*;
use std::io::ErrorKind;
use std::process::*;
let mut process = Command::new("file")
.arg("--brief")
.arg("--mime-type")
.arg("-")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.with_context(|| "Failed to spawn mime --brief --mime-type")?;
process
.stdin
.as_mut()
.expect("Forgot to pipe stdin?")
.write_all(buffer)
.or_else(|error| match error.kind() {
ErrorKind::BrokenPipe => Ok(()),
_ => Err(error),
})?;
let output = process
.wait_with_output()
.with_context(|| "Failed to read output from mime --brief --mime-type")?;
if output.status.success() {
let stdout = std::str::from_utf8(&output.stdout)
.with_context(|| {
format!(
"mime --brief --mime-type returned non-utf8: {:?}",
output.stdout
)
})?
.trim();
let detected_type = stdout
.parse::<Mime>()
.with_context(|| format!("Failed to parse mime type from output: {}", stdout))?;
Ok(detected_type)
} else {
Err(anyhow!(
"file --brief --mime-type failed with status {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detect_mimetype_of_png_image() {
let data = include_bytes!("../sample/rust-logo-128x128.png");
assert!(is_png(data));
}
#[test]
fn detect_mimetype_of_svg_image() {
let data = include_bytes!("../sample/rust-logo.svg");
assert!(is_svg(data));
}
#[test]
fn detect_mimetype_of_magic_param_bytes_max_length() {
let data = std::iter::repeat(b'\0')
.take(1_048_576)
.collect::<Vec<u8>>();
assert!(!is_svg(&data));
}
#[test]
fn detect_mimetype_of_larger_than_magic_param_bytes_max_length() {
let data = std::iter::repeat(b'\0')
.take(1_048_576 * 2)
.collect::<Vec<u8>>();
assert!(!is_svg(&data));
}
}