1use std::fs::File;
90use std::io::{self, Read};
91use std::path::Path;
92
93use crate::registry::{language_info_for_file, languages, LanguageInfo};
94
95pub const DEFAULT_PREFIX_LEN: usize = 8 * 1024;
99
100#[derive(Debug, Clone, Copy)]
103#[non_exhaustive]
104pub enum FileClass {
105 Empty,
107 Oversize {
110 size: u64,
112 limit: u64,
114 },
115 Binary {
117 kind: BinaryKind,
120 mime: Option<&'static str>,
123 },
124 SourceText(SourceText),
126}
127
128impl FileClass {
129 pub fn is_source_text(&self) -> bool {
132 matches!(self, FileClass::SourceText(_))
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138#[non_exhaustive]
139pub enum BinaryKind {
140 Archive,
143 Compressed,
145 Elf,
147 Pe,
149 MachO,
151 Image,
153 Pdf,
155 Document,
158 Media,
160 Font,
162 Unknown,
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169#[non_exhaustive]
170pub enum TextEncoding {
171 Utf8,
173 Utf8Bom,
175 Utf16Le,
178 Utf16Be,
180 Latin1,
184}
185
186#[derive(Debug, Clone, Copy)]
188pub struct SourceText {
189 pub encoding: TextEncoding,
191 pub utf8_bom: bool,
195 pub by_extension: Option<&'static LanguageInfo>,
197 pub by_content: Option<&'static LanguageInfo>,
199}
200
201impl SourceText {
202 pub fn likely_language(&self) -> Option<&'static LanguageInfo> {
204 self.by_extension.or(self.by_content)
205 }
206
207 pub fn extension_agrees(&self) -> Option<bool> {
210 Some(self.by_extension?.key == self.by_content?.key)
211 }
212}
213
214#[derive(Debug, Clone, Copy)]
216pub struct ClassifyLimits {
217 pub prefix_len: usize,
220 pub max_size: Option<u64>,
223}
224
225impl Default for ClassifyLimits {
226 fn default() -> Self {
227 Self {
228 prefix_len: DEFAULT_PREFIX_LEN,
229 max_size: None,
230 }
231 }
232}
233
234pub fn classify(path: &Path, prefix: &[u8], file_size: u64, limits: &ClassifyLimits) -> FileClass {
253 if file_size == 0 {
254 return FileClass::Empty;
255 }
256 let magic = magic(prefix);
257 if let Some(m) = magic.as_ref().filter(|m| m.strong) {
258 return binary(m.kind, Some(m.mime));
259 }
260
261 let (encoding, body) = split_bom(prefix);
262 let stats = ByteStats::of(body, (prefix.len() as u64) < file_size);
263 if stats.looks_binary() {
264 return match magic {
265 Some(m) => binary(m.kind, Some(m.mime)),
266 None => binary(BinaryKind::Unknown, None),
267 };
268 }
269 if let Some(limit) = limits.max_size {
270 if file_size > limit {
271 return FileClass::Oversize {
272 size: file_size,
273 limit,
274 };
275 }
276 }
277 let had_utf8_bom = encoding == TextEncoding::Utf8Bom;
281 let encoding = if stats.invalid_utf8 == 0 {
282 encoding
283 } else {
284 TextEncoding::Latin1
285 };
286 FileClass::SourceText(SourceText {
287 encoding,
288 utf8_bom: had_utf8_bom,
289 by_extension: language_info_for_file(path),
290 by_content: content_language(body),
291 })
292}
293
294fn binary(kind: BinaryKind, mime: Option<&'static str>) -> FileClass {
295 FileClass::Binary { kind, mime }
296}
297
298fn split_bom(prefix: &[u8]) -> (TextEncoding, &[u8]) {
301 if let Some(rest) = prefix.strip_prefix(b"\xEF\xBB\xBF") {
302 (TextEncoding::Utf8Bom, rest)
303 } else if prefix.starts_with(b"\xFF\xFE") && !prefix.starts_with(b"\xFF\xFE\0\0") {
304 (TextEncoding::Utf16Le, &[])
307 } else if prefix.starts_with(b"\xFE\xFF") {
308 (TextEncoding::Utf16Be, &[])
309 } else {
310 (TextEncoding::Utf8, prefix)
311 }
312}
313
314#[doc(hidden)]
320pub fn __byte_counts(prefix: &[u8], file_size: u64) -> (usize, usize, usize, usize) {
321 let (_, body) = split_bom(prefix);
322 let s = ByteStats::of(body, (prefix.len() as u64) < file_size);
323 (s.len, s.nul, s.control, s.invalid_utf8)
324}
325
326pub fn classify_file(path: &Path, limits: &ClassifyLimits) -> io::Result<FileClass> {
336 let meta = std::fs::metadata(path)?;
337 if !meta.is_file() {
338 return Err(io::Error::new(
339 io::ErrorKind::InvalidInput,
340 format!("{} is not a regular file", path.display()),
341 ));
342 }
343 let file = File::open(path)?;
344 let mut prefix = Vec::with_capacity(limits.prefix_len.min(meta.len() as usize));
345 file.take(limits.prefix_len as u64)
346 .read_to_end(&mut prefix)?;
347 Ok(classify(path, &prefix, meta.len(), limits))
348}
349
350struct Magic {
356 kind: BinaryKind,
357 mime: &'static str,
358 strong: bool,
366}
367
368const STRONG: &[&str] = &[
372 "zip", "docx", "xlsx", "pptx", "odt", "ods", "odp", "epub", "ora", "gz", "xz", "zst", "lz4",
373 "7z", "rar", "rpm", "doc", "elf", "mach", "class", "wasm", "png", "jpg", "woff", "woff2",
374 "mkv", "webm",
375];
376
377fn magic(prefix: &[u8]) -> Option<Magic> {
378 let t = infer::get(prefix)?;
379 let ext = t.extension();
380 let kind = match (t.matcher_type(), ext) {
381 (infer::MatcherType::Text, _) | (_, "pem" | "rtf" | "ps") => return None,
384 (_, "elf") => BinaryKind::Elf,
385 (_, "exe" | "dll") => BinaryKind::Pe,
386 (_, "mach") => BinaryKind::MachO,
387 (_, "pdf") => BinaryKind::Pdf,
388 (_, "gz" | "bz2" | "bz3" | "xz" | "zst" | "lz4" | "Z" | "lz") => BinaryKind::Compressed,
389 (
390 _,
391 "zip" | "tar" | "rar" | "7z" | "ar" | "deb" | "rpm" | "cab" | "crx" | "cpio" | "par2",
392 ) => BinaryKind::Archive,
393 (infer::MatcherType::Image, _) => BinaryKind::Image,
394 (infer::MatcherType::Doc | infer::MatcherType::Book, _) => BinaryKind::Document,
395 (infer::MatcherType::Audio | infer::MatcherType::Video, _) => BinaryKind::Media,
396 (infer::MatcherType::Font, _) => BinaryKind::Font,
397 _ => BinaryKind::Unknown,
398 };
399 let strong = STRONG.contains(&ext) || (ext == "pdf" && prefix.starts_with(b"%PDF-"));
401 Some(Magic {
402 kind,
403 mime: t.mime_type(),
404 strong,
405 })
406}
407
408const NUL_FLOOR: usize = 8;
414const CONTROL_FLOOR: usize = 8;
417
418struct ByteStats {
419 len: usize,
420 nul: usize,
421 control: usize,
423 invalid_utf8: usize,
424}
425
426impl ByteStats {
427 fn of(b: &[u8], truncated: bool) -> Self {
428 let mut nul = 0;
429 let mut control = 0;
430 for &c in b {
431 match c {
432 0 => nul += 1,
433 b'\t' | b'\n' | 0x0B | 0x0C | b'\r' | 0x1A | 0x1B => {}
434 0x01..=0x1F | 0x7F => control += 1,
435 _ => {}
436 }
437 }
438 Self {
439 len: b.len(),
440 nul,
441 control,
442 invalid_utf8: invalid_utf8_bytes(b, truncated),
443 }
444 }
445
446 fn looks_binary(&self) -> bool {
459 let len = self.len;
460 (self.nul >= NUL_FLOOR && self.nul * 1000 > len)
461 || (self.control >= CONTROL_FLOOR && self.control * 100 > len * 5)
462 || (self.invalid_utf8 * 100 > len * 30 && self.nul + self.control >= NUL_FLOOR)
463 }
464}
465
466fn invalid_utf8_bytes(mut b: &[u8], truncated: bool) -> usize {
470 let mut invalid = 0;
471 loop {
472 match std::str::from_utf8(b) {
473 Ok(_) => return invalid,
474 Err(e) => {
475 let rest = &b[e.valid_up_to()..];
476 match e.error_len() {
477 Some(n) => {
478 invalid += n;
479 b = &rest[n..];
480 }
481 None => {
482 if !truncated {
483 invalid += rest.len();
484 }
485 return invalid;
486 }
487 }
488 }
489 }
490 }
491}
492
493fn content_language(body: &[u8]) -> Option<&'static LanguageInfo> {
498 let key = if body.starts_with(b"#!") {
499 let line_end = body.iter().position(|&c| c == b'\n').unwrap_or(body.len());
500 shebang_key(&String::from_utf8_lossy(&body[2..line_end]))?
501 } else if body.trim_ascii_start().starts_with(b"<?php") {
502 "php"
503 } else {
504 return None;
505 };
506 languages().iter().find(|l| l.key == key)
507}
508
509fn shebang_key(line: &str) -> Option<&'static str> {
513 let mut words = line.split_whitespace();
514 let mut interp = words.next()?.rsplit('/').next()?;
515 if interp == "env" {
516 interp = words.find(|w| !w.starts_with('-'))?;
517 }
518 let name = interp.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
519 Some(match name {
520 "python" | "pypy" => "python",
521 "node" | "nodejs" | "bun" => "javascript",
522 "deno" | "ts-node" | "tsx" => "typescript",
523 "lua" | "luajit" => "lua",
524 "php" => "php",
525 "swift" => "swift",
526 "kotlin" | "kotlinc" | "kscript" => "kotlin",
527 "scala" => "scala",
528 "java" => "java",
529 "rust-script" => "rust",
530 "sh" | "bash" | "dash" | "ksh" => "bash",
531 _ => return None,
532 })
533}
534
535#[cfg(test)]
536mod tests {
537 use super::*;
538
539 fn class(name: &str, bytes: &[u8]) -> FileClass {
540 classify(
541 Path::new(name),
542 bytes,
543 bytes.len() as u64,
544 &ClassifyLimits::default(),
545 )
546 }
547
548 fn binary_kind(name: &str, bytes: &[u8]) -> Option<BinaryKind> {
549 match class(name, bytes) {
550 FileClass::Binary { kind, .. } => Some(kind),
551 _ => None,
552 }
553 }
554
555 fn text(name: &str, bytes: &[u8]) -> SourceText {
556 match class(name, bytes) {
557 FileClass::SourceText(t) => t,
558 other => panic!("{name}: expected SourceText, got {other:?}"),
559 }
560 }
561
562 fn noise(n: usize) -> Vec<u8> {
565 let mut x: u32 = 0x9E37_79B9;
566 (0..n)
567 .map(|_| {
568 x ^= x << 13;
569 x ^= x >> 17;
570 x ^= x << 5;
571 x as u8
572 })
573 .collect()
574 }
575
576 fn with_header(header: &[u8]) -> Vec<u8> {
577 let mut v = header.to_vec();
578 v.extend(noise(4096));
579 v
580 }
581
582 fn tar() -> Vec<u8> {
583 let mut v = vec![0u8; 512];
584 v[..10].copy_from_slice(b"hello.txt\0");
585 v[257..263].copy_from_slice(b"ustar\0");
586 v.extend(b"hello\n");
587 v
588 }
589
590 fn pe() -> Vec<u8> {
591 let mut v = vec![0u8; 0x80];
592 v[..2].copy_from_slice(b"MZ");
593 v[0x3C] = 0x80;
594 v.extend(b"PE\0\0");
595 v.extend(noise(512));
596 v
597 }
598
599 #[test]
600 fn every_binary_kind_renamed_to_a_source_extension() {
601 let cases: Vec<(Vec<u8>, BinaryKind)> = vec![
602 (with_header(b"PK\x03\x04"), BinaryKind::Archive),
603 (tar(), BinaryKind::Archive),
604 (with_header(b"!<arch>\n"), BinaryKind::Archive),
605 (with_header(b"7z\xBC\xAF\x27\x1C"), BinaryKind::Archive),
606 (with_header(b"\x1F\x8B\x08\x00"), BinaryKind::Compressed),
607 (with_header(b"\xFD7zXZ\x00"), BinaryKind::Compressed),
608 (with_header(b"\x28\xB5\x2F\xFD"), BinaryKind::Compressed),
609 (with_header(b"BZh91AY&SY"), BinaryKind::Compressed),
610 (with_header(b"\x7FELF\x02\x01\x01"), BinaryKind::Elf),
611 (pe(), BinaryKind::Pe),
612 (with_header(b"\xCF\xFA\xED\xFE"), BinaryKind::MachO),
613 (
614 with_header(b"\xCA\xFE\xBA\xBE\x00\x00\x00\x02"),
615 BinaryKind::MachO,
616 ),
617 (with_header(b"\x89PNG\r\n\x1A\n"), BinaryKind::Image),
618 (with_header(b"\xFF\xD8\xFF\xE0"), BinaryKind::Image),
619 (with_header(b"GIF89a"), BinaryKind::Image),
620 (with_header(b"RIFF\0\0\0\0WEBPVP8 "), BinaryKind::Image),
621 (with_header(b"%PDF-1.7\n"), BinaryKind::Pdf),
622 (
623 with_header(b"\xCA\xFE\xBA\xBE\x00\x00\x00\x41"),
624 BinaryKind::Unknown,
625 ),
626 (noise(8192), BinaryKind::Unknown),
627 ];
628 for (bytes, want) in &cases {
629 for name in ["evil.c", "evil.rs", "evil.py"] {
630 assert_eq!(
631 binary_kind(name, bytes),
632 Some(*want),
633 "{name} with header {:02X?}",
634 &bytes[..8]
635 );
636 }
637 }
638 }
639
640 #[test]
641 fn unidentified_noise_is_binary() {
642 for name in ["evil.c", "evil.rs", "evil.py"] {
643 assert!(binary_kind(name, &noise(8192)).is_some(), "{name}");
644 }
645 assert!(matches!(
646 class("x.c", &[0x7F; 64]),
647 FileClass::Binary {
648 kind: BinaryKind::Unknown,
649 mime: None
650 }
651 ));
652 }
653
654 #[test]
655 fn binary_reports_mime() {
656 assert!(matches!(
657 class("a.c", &with_header(b"PK\x03\x04")),
658 FileClass::Binary {
659 mime: Some("application/zip"),
660 ..
661 }
662 ));
663 }
664
665 #[test]
668 fn weak_or_text_signatures_on_text_stay_text() {
669 let cases: &[(&str, &[u8])] = &[
670 ("mz.py", b"MZ = 3\nprint(MZ)\n"), ("bm.py", b"BM_SIZE = 4\n"), ("bc.c", b"BC_MAX = 1;\n"), ("g.py", b"GIF_DIR = 'x'\n"), ("b.py", b"BZh = 1\n"), ("fws.py", b"FWS = 2\n"), ("pdf.c", b"const char *h = \"%PDF-1.4\";\n"), ("ps.c", b"%!\n"), ("sh.rs", b"#!/bin/sh\necho\n"), ("page.php", b"<html><?php echo 1; ?></html>\n"), ("x.c", b"<?xml version=\"1.0\"?>\n"), ("k.c", b"-----BEGIN CERTIFICATE-----\nMII\n"), ];
683 for (name, src) in cases {
684 assert!(class(name, src).is_source_text(), "{name}");
685 }
686 }
687
688 #[test]
689 fn binary_beats_oversize() {
690 let limits = ClassifyLimits {
692 max_size: Some(1 << 20),
693 ..Default::default()
694 };
695 let got = classify(
696 Path::new("huge.c"),
697 &with_header(b"PK\x03\x04"),
698 2 << 30,
699 &limits,
700 );
701 assert!(matches!(
702 got,
703 FileClass::Binary {
704 kind: BinaryKind::Archive,
705 ..
706 }
707 ));
708 }
709
710 #[test]
711 fn weak_magic_binary_beats_oversize() {
712 let limits = ClassifyLimits {
714 max_size: Some(1 << 20),
715 ..Default::default()
716 };
717 let got = classify(Path::new("huge.c"), &pe(), 2 << 30, &limits);
718 assert!(matches!(
719 got,
720 FileClass::Binary {
721 kind: BinaryKind::Pe,
722 ..
723 }
724 ));
725 }
726
727 #[test]
728 fn utf8_source() {
729 let t = text(
730 "main.rs",
731 "fn main() { println!(\"héllo — ✓\"); }\n".as_bytes(),
732 );
733 assert_eq!(t.encoding, TextEncoding::Utf8);
734 #[cfg(feature = "lang-rust")]
735 assert_eq!(t.likely_language().unwrap().key, "rust");
736 }
737
738 #[test]
739 fn latin1_source() {
740 let src = b"/* Gr\xFC\xDFe, caf\xE9 */\nint main(void) { return 0; }\n";
742 assert_eq!(text("main.c", src).encoding, TextEncoding::Latin1);
743 }
744
745 #[test]
746 fn legacy_multibyte_text_is_not_binary() {
747 let mut src = b"// ".to_vec();
749 for _ in 0..200 {
750 src.extend(b"\xD6\xD0\xCE\xC4");
751 }
752 src.extend(b"\nint x;\n");
753 assert_eq!(text("gbk.c", &src).encoding, TextEncoding::Latin1);
754 }
755
756 #[test]
757 fn boms() {
758 let t = text("bom.py", b"\xEF\xBB\xBFprint('hi')\n");
759 assert_eq!(t.encoding, TextEncoding::Utf8Bom);
760 assert!(t.utf8_bom);
761 let t = text("w.c", b"\xFF\xFEi\0n\0t\0 \0x\0;\0");
762 assert_eq!(t.encoding, TextEncoding::Utf16Le);
763 let t = text("w.c", b"\xFE\xFF\0i\0n\0t");
764 assert_eq!(t.encoding, TextEncoding::Utf16Be);
765 }
766
767 fn utf16le(s: &str) -> Vec<u8> {
768 s.encode_utf16().flat_map(u16::to_le_bytes).collect()
769 }
770
771 fn utf32(s: &str, le: bool) -> Vec<u8> {
772 s.chars()
773 .flat_map(|c| {
774 let c = c as u32;
775 if le {
776 c.to_le_bytes()
777 } else {
778 c.to_be_bytes()
779 }
780 })
781 .collect()
782 }
783
784 const SNIPPET: &str = "int main(void) { return 0; }\n";
785
786 #[test]
787 fn utf32_boms_are_not_mistaken_for_utf16() {
788 let le = utf32(&format!("\u{FEFF}{SNIPPET}"), true);
790 assert_eq!(&le[..4], b"\xFF\xFE\0\0");
791 assert_eq!(binary_kind("w.c", &le), Some(BinaryKind::Unknown));
792 let be = utf32(&format!("\u{FEFF}{SNIPPET}"), false);
793 assert_eq!(&be[..4], b"\0\0\xFE\xFF");
794 assert_eq!(binary_kind("w.c", &be), Some(BinaryKind::Unknown));
795 }
796
797 #[test]
798 fn bomless_utf16_is_a_documented_false_binary() {
799 assert_eq!(
800 binary_kind("w.c", &utf16le(SNIPPET)),
801 Some(BinaryKind::Unknown)
802 );
803 }
804
805 #[test]
806 fn utf8_bom_with_invalid_bytes_keeps_the_bom_flag() {
807 let t = text("bom.c", b"\xEF\xBB\xBF/* caf\xE9 */\nint x;\n");
808 assert_eq!(t.encoding, TextEncoding::Latin1);
809 assert!(t.utf8_bom);
810 assert!(!text("plain.c", b"/* caf\xE9 */\n").utf8_bom);
811 }
812
813 #[test]
814 fn stray_nul_or_control_in_a_small_file_is_text() {
815 let mut src: Vec<u8> = b"int x;\n".iter().copied().cycle().take(500).collect();
817 src[100] = 0;
818 assert!(class("small.c", &src).is_source_text());
819 assert!(class("tiny.c", b"int x; /*\x01*/\n").is_source_text());
821 assert!(class("tiny.c", b"int y; /*\x08*/\n").is_source_text());
822 let mut src = b"int a;\n".repeat(4);
824 src.extend([0, 0, 0, 1, 2, 3, 0x08, 0x08]);
825 assert!(class("few.c", &src).is_source_text());
826 }
827
828 #[test]
829 fn crlf_formfeed_esc_and_sub_are_text() {
830 let src = b"int a;\r\n\x0C\r\n/* \x1B[1mbold\x1B[0m */\r\nint b;\r\n\x1A";
831 assert!(class("dos.c", src).is_source_text());
832 }
833
834 #[test]
835 fn large_source_at_caller_limit() {
836 let line = b"int f(int x) { return x + 1; }\n";
837 let src: Vec<u8> = line.iter().copied().cycle().take(64 * 1024).collect();
838 let size = src.len() as u64;
839 let prefix = &src[..DEFAULT_PREFIX_LEN];
840 let at = ClassifyLimits {
841 max_size: Some(size),
842 ..Default::default()
843 };
844 assert!(classify(Path::new("big.c"), prefix, size, &at).is_source_text());
845 let under = ClassifyLimits {
846 max_size: Some(size - 1),
847 ..Default::default()
848 };
849 assert!(matches!(
850 classify(Path::new("big.c"), prefix, size, &under),
851 FileClass::Oversize { size: s, limit: l } if s == size && l == size - 1
852 ));
853 assert!(classify(
855 Path::new("big.c"),
856 prefix,
857 u64::MAX,
858 &ClassifyLimits::default()
859 )
860 .is_source_text());
861 }
862
863 #[test]
864 fn empty_file() {
865 assert!(matches!(class("empty.c", b""), FileClass::Empty));
866 }
867
868 #[test]
869 fn truncated_prefix_mid_codepoint_is_still_utf8() {
870 let src = "// ✓✓✓\n".as_bytes();
871 let cut = &src[..5]; let got = classify(Path::new("a.c"), cut, 100, &ClassifyLimits::default());
873 match got {
874 FileClass::SourceText(t) => assert_eq!(t.encoding, TextEncoding::Utf8),
875 other => panic!("{other:?}"),
876 }
877 assert_eq!(text("a.c", cut).encoding, TextEncoding::Latin1);
879 }
880
881 #[test]
882 fn single_stray_nul_in_large_source_is_text() {
883 let mut src: Vec<u8> = b"int x;\n".iter().copied().cycle().take(4096).collect();
884 src[100] = 0;
885 assert!(class("nul.c", &src).is_source_text());
886 }
887
888 #[test]
889 fn shebang_hint_and_agreement() {
890 let t = text("tool", b"#!/usr/bin/env python3\nprint(1)\n");
891 assert!(t.by_extension.is_none());
892 #[cfg(feature = "lang-python")]
893 {
894 assert_eq!(t.likely_language().unwrap().key, "python");
895 assert_eq!(t.extension_agrees(), None);
896 let t = text("tool.py", b"#!/usr/bin/python3.12 -u\nprint(1)\n");
897 assert_eq!(t.extension_agrees(), Some(true));
898 }
899 #[cfg(all(feature = "lang-python", feature = "lang-c"))]
900 {
901 let t = text("odd.c", b"#!/usr/bin/env -S python3 -u\nprint(1)\n");
903 assert_eq!(t.extension_agrees(), Some(false));
904 assert_eq!(t.likely_language().unwrap().key, "c");
905 }
906 #[cfg(feature = "lang-php")]
907 assert_eq!(
908 text("page", b"\n<?php echo 1;").by_content.unwrap().key,
909 "php"
910 );
911 #[cfg(all(feature = "lang-bash", feature = "lang-c"))]
912 {
913 let t = text("x.c", b"#!/bin/sh\n");
915 assert_eq!(t.by_content.unwrap().key, "bash");
916 assert_eq!(t.extension_agrees(), Some(false));
917 assert_eq!(t.likely_language().unwrap().key, "c");
918 }
919 #[cfg(feature = "lang-bash")]
920 for line in ["#!/bin/bash\n", "#!/usr/bin/env dash\n", "#!/bin/ksh93\n"] {
921 assert_eq!(text("run", line.as_bytes()).by_content.unwrap().key, "bash");
922 }
923 #[cfg(not(feature = "lang-bash"))]
924 assert!(text("x.c", b"#!/bin/sh\n").by_content.is_none());
925 }
926
927 #[test]
928 fn classify_file_reads_bounded_prefix() {
929 let dir = std::env::temp_dir().join(format!("lps-classify-{}", std::process::id()));
930 std::fs::create_dir_all(&dir).unwrap();
931 let zip = dir.join("evil.c");
932 std::fs::write(&zip, with_header(b"PK\x03\x04")).unwrap();
933 let src = dir.join("ok.c");
934 std::fs::write(&src, b"int main(void) { return 0; }\n").unwrap();
935 let empty = dir.join("empty.c");
936 std::fs::write(&empty, b"").unwrap();
937 let limits = ClassifyLimits {
938 prefix_len: 16,
939 max_size: None,
940 };
941 assert!(matches!(
942 classify_file(&zip, &limits).unwrap(),
943 FileClass::Binary {
944 kind: BinaryKind::Archive,
945 ..
946 }
947 ));
948 assert!(classify_file(&src, &limits).unwrap().is_source_text());
949 assert!(matches!(
950 classify_file(&empty, &limits).unwrap(),
951 FileClass::Empty
952 ));
953 assert_eq!(
954 classify_file(&dir, &limits).unwrap_err().kind(),
955 io::ErrorKind::InvalidInput
956 );
957 assert_eq!(
958 classify_file(&dir.join("missing.c"), &limits)
959 .unwrap_err()
960 .kind(),
961 io::ErrorKind::NotFound
962 );
963 std::fs::remove_dir_all(&dir).unwrap();
964 }
965
966 fn scratch_dir(tag: &str) -> std::path::PathBuf {
967 let dir = std::env::temp_dir().join(format!("lps-classify-{tag}-{}", std::process::id()));
968 let _ = std::fs::remove_dir_all(&dir);
969 std::fs::create_dir_all(&dir).unwrap();
970 dir
971 }
972
973 #[cfg(unix)]
974 #[test]
975 fn classify_file_follows_symlinks() {
976 let dir = scratch_dir("symlink");
977 let zip = dir.join("real.zip");
978 std::fs::write(&zip, with_header(b"PK\x03\x04")).unwrap();
979 let link = dir.join("looks_like.c");
980 std::os::unix::fs::symlink(&zip, &link).unwrap();
981 assert!(matches!(
982 classify_file(&link, &ClassifyLimits::default()).unwrap(),
983 FileClass::Binary {
984 kind: BinaryKind::Archive,
985 ..
986 }
987 ));
988 let dangling = dir.join("dangling.c");
989 std::os::unix::fs::symlink(dir.join("nope"), &dangling).unwrap();
990 assert_eq!(
991 classify_file(&dangling, &ClassifyLimits::default())
992 .unwrap_err()
993 .kind(),
994 io::ErrorKind::NotFound
995 );
996 std::fs::remove_dir_all(&dir).unwrap();
997 }
998
999 #[cfg(unix)]
1000 #[test]
1001 fn classify_file_rejects_a_fifo_without_blocking() {
1002 let dir = scratch_dir("fifo");
1003 let fifo = dir.join("pipe.c");
1004 let ok = std::process::Command::new("mkfifo")
1005 .arg(&fifo)
1006 .status()
1007 .map(|s| s.success())
1008 .unwrap_or(false);
1009 if !ok {
1010 eprintln!("mkfifo unavailable; skipping");
1011 return;
1012 }
1013 let (tx, rx) = std::sync::mpsc::channel();
1016 let path = fifo.clone();
1017 std::thread::spawn(move || {
1018 let _ = tx.send(classify_file(&path, &ClassifyLimits::default()).map_err(|e| e.kind()));
1019 });
1020 let got = rx
1021 .recv_timeout(std::time::Duration::from_secs(5))
1022 .expect("classify_file blocked on a FIFO");
1023 assert_eq!(got.unwrap_err(), io::ErrorKind::InvalidInput);
1024 std::fs::remove_dir_all(&dir).unwrap();
1025 }
1026
1027 #[cfg(unix)]
1028 #[test]
1029 fn classify_file_reports_permission_errors() {
1030 use std::os::unix::fs::PermissionsExt;
1031 let dir = scratch_dir("perm");
1032 let locked = dir.join("locked.c");
1033 std::fs::write(&locked, b"int x;\n").unwrap();
1034 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
1035 if File::open(&locked).is_err() {
1037 assert_eq!(
1038 classify_file(&locked, &ClassifyLimits::default())
1039 .unwrap_err()
1040 .kind(),
1041 io::ErrorKind::PermissionDenied
1042 );
1043 }
1044 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
1045 std::fs::remove_dir_all(&dir).unwrap();
1046 }
1047
1048 #[test]
1051 fn strong_extensions_exist_in_infer() {
1052 for ext in STRONG {
1053 assert!(infer::is_supported(ext), "infer no longer knows {ext:?}");
1054 }
1055 for ext in [
1056 "exe", "dll", "mach", "pdf", "tar", "ar", "deb", "cab", "crx", "cpio", "par2", "bz2",
1057 "bz3", "Z", "lz", "pem", "rtf", "ps",
1058 ] {
1059 assert!(infer::is_supported(ext), "infer no longer knows {ext:?}");
1060 }
1061 }
1062}