1use std::collections::HashMap;
4use std::fmt::Display;
5use std::io::Read;
6use std::path::Path;
7use std::sync::OnceLock;
8
9use anyhow::{Result, bail, ensure};
10use clap::ValueEnum;
11use serde::{Deserialize, Serialize};
12
13#[allow(clippy::manual_non_exhaustive)]
15#[derive(ValueEnum, Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
16pub enum FileType {
17 DOCFILE,
21
22 ELF,
24
25 ELF32,
27
28 ELF64,
30
31 #[allow(non_camel_case_types)] ELF_LSB,
34
35 #[allow(non_camel_case_types)] ELF_MSB,
38
39 #[allow(non_camel_case_types)] ELF32_LSB,
42
43 #[allow(non_camel_case_types)] ELF64_LSB,
46
47 #[allow(non_camel_case_types)] ELF32_MSB,
50
51 #[allow(non_camel_case_types)] ELF64_MSB,
54
55 EXE,
57
58 MachO,
60
61 PDF,
63
64 PE32,
66
67 PE32DotNet,
69
70 PE32Native,
72
73 RTF,
75
76 XCOFF,
78
79 #[doc(hidden)]
81 #[serde(skip)]
82 #[clap(skip)]
83 DsStore,
84
85 #[default]
87 #[doc(hidden)]
88 #[serde(skip)]
89 #[clap(skip)]
90 NotSet,
91}
92
93const FILE_DETECTION_BUFFER_SIZE: usize = 384;
94
95const MAGIC32: [u8; 4] = [0xfe, 0xed, 0xfa, 0xce];
96const CIGAM32: [u8; 4] = [0xce, 0xfa, 0xed, 0xfe];
97const MAGIC64: [u8; 4] = [0xfe, 0xed, 0xfa, 0xcf];
98const CIGAM64: [u8; 4] = [0xcf, 0xfa, 0xed, 0xfe];
99const FAT_MACHO: [u8; 4] = [0xCA, 0xFE, 0xBA, 0xBE]; const MACH_O_MAGICS: [[u8; 4]; 4] = [MAGIC32, CIGAM32, MAGIC64, CIGAM64];
101
102const ELF_MAGIC: [u8; 4] = [0x7f, 0x45, 0x4c, 0x46]; const EXE_MAGICS: [[u8; 2]; 2] = [[0x4D, 0x5A], [0x5A, 0x4D]]; const PE_MAGIC: [u8; 4] = [0x50, 0x45, 0x00, 0x00];
105const PDF_MAGIC: [u8; 4] = [0x25, 0x50, 0x44, 0x46]; const RTF_MAGIC: [u8; 4] = [0x7B, 0x5C, 0x72, 0x74]; const XCOFF_MAGICS: [[u8; 2]; 2] = [[0x01, 0xDF], [0x01, 0xF7]]; const DOCFILE_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
110const DS_STORE_MAGIC: [u8; 8] = [0x00, 0x00, 0x00, 0x01, 0x42, 0x75, 0x64, 0x31];
111
112impl FileType {
113 #[inline]
117 #[must_use]
118 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
119 if bytes.starts_with(&DOCFILE_MAGIC) {
120 return Some(Self::DOCFILE);
121 }
122
123 if bytes.starts_with(&DS_STORE_MAGIC) {
124 return Some(Self::DsStore);
125 }
126
127 if bytes.starts_with(&ELF_MAGIC) {
128 if bytes[0x4] == 1 && bytes[0x5] == 1 {
130 return Some(Self::ELF32_LSB);
131 }
132 if bytes[0x4] == 1 && bytes[0x5] == 2 {
133 return Some(Self::ELF32_MSB);
134 }
135 if bytes[0x4] == 2 && bytes[0x5] == 1 {
136 return Some(Self::ELF64_LSB);
137 }
138 if bytes[0x4] == 2 && bytes[0x5] == 2 {
139 return Some(Self::ELF64_MSB);
140 }
141
142 if bytes[0x5] == 1 {
143 return Some(Self::ELF_LSB);
144 }
145 if bytes[0x5] == 2 {
146 return Some(Self::ELF_MSB);
147 }
148
149 if bytes[0x4] == 1 {
150 return Some(Self::ELF32);
151 }
152 if bytes[0x4] == 2 {
153 return Some(Self::ELF64);
154 }
155
156 return Some(Self::ELF);
157 }
158
159 if MACH_O_MAGICS.iter().any(|magic| bytes.starts_with(magic)) {
160 return Some(Self::MachO);
161 }
162
163 if bytes.starts_with(&FAT_MACHO) && Self::is_fat_macho(bytes) {
164 return Some(Self::MachO);
165 }
166
167 if bytes.starts_with(&PDF_MAGIC) {
168 return Some(Self::PDF);
169 }
170
171 if EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) {
172 if Self::is_pe32(bytes) {
173 if Self::is_dotnet(bytes) {
174 return Some(Self::PE32DotNet);
175 }
176 return Some(Self::PE32Native);
177 }
178
179 return Some(Self::EXE);
180 }
181
182 if bytes.starts_with(&RTF_MAGIC) {
183 return Some(Self::RTF);
184 }
185
186 if XCOFF_MAGICS.iter().any(|magic| bytes.starts_with(magic)) {
187 return Some(Self::XCOFF);
188 }
189
190 None
191 }
192
193 #[inline]
199 pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Option<Self>> {
200 let mut file = std::fs::File::open(path)?;
201 let mut buffer = [0; FILE_DETECTION_BUFFER_SIZE];
202 let read = file.read(&mut buffer)?;
203 Ok(Self::from_bytes(&buffer[..read]))
204 }
205
206 #[must_use]
217 pub fn matches(&self, bytes: &[u8]) -> bool {
218 match self {
219 FileType::DOCFILE => bytes.starts_with(&DOCFILE_MAGIC),
221 FileType::ELF => bytes.starts_with(&ELF_MAGIC),
222 FileType::ELF_LSB => bytes.starts_with(&ELF_MAGIC) && bytes[0x5] == 1,
223 FileType::ELF_MSB => bytes.starts_with(&ELF_MAGIC) && bytes[0x5] == 2,
224 FileType::ELF32 => bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 1,
225 FileType::ELF64 => bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 2,
226 FileType::ELF32_LSB => {
227 bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 1 && bytes[0x5] == 1
228 }
229 FileType::ELF32_MSB => {
230 bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 1 && bytes[0x5] == 2
231 }
232 FileType::ELF64_LSB => {
233 bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 2 && bytes[0x5] == 1
234 }
235 FileType::ELF64_MSB => {
236 bytes.starts_with(&ELF_MAGIC) && bytes[0x4] == 2 && bytes[0x5] == 2
237 }
238 FileType::EXE => EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)),
239 FileType::MachO => {
240 MACH_O_MAGICS.iter().any(|magic| bytes.starts_with(magic))
241 || bytes.starts_with(&FAT_MACHO) && Self::is_fat_macho(bytes)
242 }
243 FileType::PDF => bytes.starts_with(&PDF_MAGIC),
244 FileType::PE32 => {
245 EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) && Self::is_pe32(bytes)
246 }
247 FileType::PE32Native => {
248 EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) && !Self::is_dotnet(bytes)
249 }
250 FileType::PE32DotNet => {
251 EXE_MAGICS.iter().any(|magic| bytes.starts_with(magic)) && Self::is_dotnet(bytes)
252 }
253 FileType::RTF => bytes.starts_with(&RTF_MAGIC),
254 FileType::XCOFF => XCOFF_MAGICS.iter().any(|magic| bytes.starts_with(magic)),
255 FileType::DsStore => unreachable!("`FileType::DsStore` should never be used"),
256 FileType::NotSet => unreachable!("`FileType::NotSet` should never be used"),
257 }
258 }
259
260 #[inline]
266 pub fn matches_path<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
267 let mut file = std::fs::File::open(path)?;
268 let mut buffer = [0; FILE_DETECTION_BUFFER_SIZE];
269 let read = file.read(&mut buffer)?;
270 Ok(self.matches(&buffer[..read]))
271 }
272
273 #[inline]
275 fn is_pe32(bytes: &[u8]) -> bool {
276 if bytes.len() < 0x40 {
277 return false;
278 }
279
280 let pe_magic_offset = u32::from_le_bytes([
281 bytes[0x3C],
282 bytes[0x3C + 1],
283 bytes[0x3C + 2],
284 bytes[0x3C + 3],
285 ]) as usize;
286 pe_magic_offset < bytes.len()
287 && pe_magic_offset + PE_MAGIC.len() < bytes.len()
288 && bytes[pe_magic_offset..pe_magic_offset + 4] == PE_MAGIC
289 }
290
291 #[inline]
293 fn is_dotnet(bytes: &[u8]) -> bool {
294 if let Ok(pe) = goblin::pe::PE::parse(bytes) {
295 pe.clr_data.is_some()
296 } else {
297 false
298 }
299 }
300
301 #[inline]
303 fn is_fat_macho(bytes: &[u8]) -> bool {
304 u32::from_be_bytes([
305 bytes[0x04],
306 bytes[0x04 + 1],
307 bytes[0x04 + 2],
308 bytes[0x04 + 3],
309 ]) < 0x20
310 }
311
312 pub fn downgrade(self, other: FileType) -> Result<FileType> {
325 static DOWNGRADES: OnceLock<HashMap<FileType, Vec<FileType>>> = OnceLock::new();
328
329 ensure!(
330 other != FileType::DsStore,
331 "DS_Store files should be ignored."
332 );
333 if self == FileType::NotSet {
334 return Ok(other);
335 }
336
337 let downgrades = DOWNGRADES.get_or_init(|| {
338 let mut m = HashMap::new();
339 m.insert(FileType::EXE, vec![FileType::EXE]);
340 m.insert(FileType::PE32DotNet, vec![FileType::PE32, FileType::EXE]);
341 m.insert(FileType::PE32Native, vec![FileType::PE32, FileType::EXE]);
342 m.insert(FileType::PE32, vec![FileType::EXE]);
343
344 m.insert(FileType::ELF, vec![FileType::ELF]);
345 m.insert(FileType::ELF_LSB, vec![FileType::ELF]);
346 m.insert(FileType::ELF_MSB, vec![FileType::ELF]);
347 m.insert(FileType::ELF64, vec![FileType::ELF]);
348 m.insert(FileType::ELF32, vec![FileType::ELF]);
349
350 m.insert(
351 FileType::ELF64_LSB,
352 vec![FileType::ELF_LSB, FileType::ELF64, FileType::ELF],
353 );
354 m.insert(
355 FileType::ELF64_MSB,
356 vec![FileType::ELF_MSB, FileType::ELF64, FileType::ELF],
357 );
358
359 m.insert(
360 FileType::ELF32_LSB,
361 vec![FileType::ELF_LSB, FileType::ELF32, FileType::ELF],
362 );
363 m.insert(
364 FileType::ELF32_MSB,
365 vec![FileType::ELF_MSB, FileType::ELF32, FileType::ELF],
366 );
367 m
368 });
369
370 if let Some(related_types) = downgrades.get(&self) {
371 let Some(other_related_types) = downgrades.get(&other) else {
372 bail!("Downgrade from {self} to {other} not possible")
373 };
374 let mut common_types = Vec::new();
375
376 for related_type in related_types {
378 if other_related_types.contains(related_type) {
379 common_types.push(*related_type);
380 }
381 }
382
383 if let Some(common_type) = common_types.first() {
384 return Ok(*common_type);
385 }
386 }
387
388 bail!("Downgrade from {self} to {other} not possible")
389 }
390}
391
392impl From<FileType> for &'static str {
393 fn from(ft: FileType) -> &'static str {
394 match ft {
395 FileType::DOCFILE => "DOCFILE",
396 FileType::DsStore => "DS_Store",
397 FileType::ELF => "ELF",
398 FileType::ELF_LSB => "ELF_LSB",
399 FileType::ELF_MSB => "ELF_MSB",
400 FileType::ELF32 => "ELF32",
401 FileType::ELF64 => "ELF64",
402 FileType::ELF32_LSB => "ELF32_LSB",
403 FileType::ELF64_LSB => "ELF64_LSB",
404 FileType::ELF32_MSB => "ELF32_MSB",
405 FileType::ELF64_MSB => "ELF64_MSB",
406 FileType::EXE => "EXE",
407 FileType::MachO => "MachO",
408 FileType::PDF => "PDF",
409 FileType::PE32 => "PE32",
410 FileType::PE32DotNet => "PE32DotNet",
411 FileType::PE32Native => "PE32Native",
412 FileType::RTF => "RTF",
413 FileType::XCOFF => "XCOFF",
414 FileType::NotSet => "NotSet",
415 }
416 }
417}
418
419impl FileType {
420 #[must_use]
429 pub fn from_name(name: &str) -> Option<Self> {
430 let name = name.trim();
431 <Self as ValueEnum>::value_variants()
432 .iter()
433 .copied()
434 .find(|variant| {
435 let variant_name: &'static str = (*variant).into();
436 variant_name.eq_ignore_ascii_case(name)
437 })
438 }
439}
440
441impl Display for FileType {
442 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443 let s: &'static str = (*self).into();
444 write!(f, "{s}")
445 }
446}