Skip to main content

deepdoc_core/
detect.rs

1//! File type detection: signature first, extension as a hint.
2//!
3//! Order (see `docs/PRD/03-tech-stack.md`):
4//! 1. magic bytes — `%PDF`, `{\rtf`, `PK\x03\x04` (then peek inside the ZIP for
5//!    `mimetype`, `word/`, `ppt/`, `xl/`);
6//! 2. extension, which is what decides the text formats (txt/md/csv/…);
7//! 3. a last-resort sniff for HTML in the head bytes.
8//!
9//! Detection is a pure function over [`Sniff`], so it is unit-testable without
10//! touching the filesystem.
11
12use std::path::{Path, PathBuf};
13
14use serde::{Deserialize, Serialize};
15
16use crate::error::{Error, Result};
17
18/// How many bytes of the file head are read for sniffing.
19pub const SNIFF_LEN: usize = 8 * 1024;
20
21/// A document format DeepDoc knows about.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
23#[serde(rename_all = "lowercase")]
24pub enum Format {
25    Txt,
26    Markdown,
27    Csv,
28    Html,
29    Rtf,
30    Docx,
31    Pptx,
32    Xlsx,
33    Odt,
34    Odp,
35    Ods,
36    Epub,
37    Pdf,
38}
39
40impl Format {
41    /// Every format DeepDoc knows about.
42    pub const ALL: [Format; 13] = [
43        Format::Txt,
44        Format::Markdown,
45        Format::Csv,
46        Format::Html,
47        Format::Rtf,
48        Format::Docx,
49        Format::Pptx,
50        Format::Xlsx,
51        Format::Odt,
52        Format::Odp,
53        Format::Ods,
54        Format::Epub,
55        Format::Pdf,
56    ];
57
58    /// Canonical lowercase name, as used in metadata and error messages.
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Format::Txt => "txt",
62            Format::Markdown => "markdown",
63            Format::Csv => "csv",
64            Format::Html => "html",
65            Format::Rtf => "rtf",
66            Format::Docx => "docx",
67            Format::Pptx => "pptx",
68            Format::Xlsx => "xlsx",
69            Format::Odt => "odt",
70            Format::Odp => "odp",
71            Format::Ods => "ods",
72            Format::Epub => "epub",
73            Format::Pdf => "pdf",
74        }
75    }
76
77    /// Map a file extension (without the dot, any case) onto a format.
78    pub fn from_extension(ext: &str) -> Option<Format> {
79        let ext = ext.to_ascii_lowercase();
80        Some(match ext.as_str() {
81            "txt" | "text" | "log" => Format::Txt,
82            "md" | "markdown" => Format::Markdown,
83            "csv" => Format::Csv,
84            "html" | "htm" | "xhtml" => Format::Html,
85            "rtf" => Format::Rtf,
86            "docx" => Format::Docx,
87            "pptx" => Format::Pptx,
88            "xlsx" => Format::Xlsx,
89            "odt" => Format::Odt,
90            "odp" => Format::Odp,
91            "ods" => Format::Ods,
92            "epub" => Format::Epub,
93            "pdf" => Format::Pdf,
94            _ => return None,
95        })
96    }
97}
98
99impl std::fmt::Display for Format {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str(self.as_str())
102    }
103}
104
105/// Everything detection needs about a file: its extension and its head bytes.
106#[derive(Debug, Clone)]
107pub struct Sniff {
108    pub extension: Option<String>,
109    pub head: Vec<u8>,
110}
111
112impl Sniff {
113    /// Build a sniff from parts — used by tests and by callers that already hold the bytes.
114    pub fn new(extension: Option<String>, head: Vec<u8>) -> Self {
115        Self { extension, head }
116    }
117
118    /// Read the head of `path` for sniffing.
119    pub fn read(path: &Path) -> Result<Sniff> {
120        use std::io::Read;
121
122        let extension = path
123            .extension()
124            .and_then(|e| e.to_str())
125            .map(|e| e.to_ascii_lowercase());
126
127        let mut file = std::fs::File::open(path).map_err(|e| Error::io(path, e))?;
128        let mut head = vec![0u8; SNIFF_LEN];
129        let mut filled = 0;
130        while filled < head.len() {
131            match file.read(&mut head[filled..]) {
132                Ok(0) => break,
133                Ok(n) => filled += n,
134                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
135                Err(e) => return Err(Error::io(path, e)),
136            }
137        }
138        head.truncate(filled);
139
140        Ok(Sniff { extension, head })
141    }
142}
143
144/// Detect the format of a file on disk.
145pub fn detect_path(path: &Path) -> Result<Format> {
146    let sniff = Sniff::read(path)?;
147    detect(&sniff).ok_or_else(|| Error::Unsupported {
148        path: PathBuf::from(path),
149    })
150}
151
152/// Detect a format from already-sniffed bytes. Pure.
153pub fn detect(sniff: &Sniff) -> Option<Format> {
154    if let Some(format) = detect_signature(&sniff.head) {
155        return Some(format);
156    }
157    if let Some(format) = sniff.extension.as_deref().and_then(Format::from_extension) {
158        return Some(format);
159    }
160    if looks_like_html(&sniff.head) {
161        return Some(Format::Html);
162    }
163    None
164}
165
166/// Detect a format from magic bytes alone.
167pub fn detect_signature(head: &[u8]) -> Option<Format> {
168    if head.starts_with(b"%PDF-") {
169        return Some(Format::Pdf);
170    }
171    if head.starts_with(b"{\\rtf") {
172        return Some(Format::Rtf);
173    }
174    if head.starts_with(b"PK\x03\x04") {
175        return detect_zip(head);
176    }
177    None
178}
179
180/// Classify a ZIP container by looking at what is stored inside it.
181///
182/// This reads the first local file header (ODF/EPUB put an uncompressed
183/// `mimetype` entry there) and otherwise scans the head bytes for the marker
184/// directories OOXML uses. It is a heuristic on the first [`SNIFF_LEN`] bytes;
185/// full central-directory reading arrives with the real ZIP extractors (Phase 3).
186fn detect_zip(head: &[u8]) -> Option<Format> {
187    if let Some(mimetype) = first_entry_mimetype(head) {
188        let format = match mimetype.as_str() {
189            "application/epub+zip" => Format::Epub,
190            "application/vnd.oasis.opendocument.text" => Format::Odt,
191            "application/vnd.oasis.opendocument.presentation" => Format::Odp,
192            "application/vnd.oasis.opendocument.spreadsheet" => Format::Ods,
193            _ => return None,
194        };
195        return Some(format);
196    }
197
198    // OOXML: the part names themselves identify the flavour.
199    if contains(head, b"word/") {
200        return Some(Format::Docx);
201    }
202    if contains(head, b"ppt/") {
203        return Some(Format::Pptx);
204    }
205    if contains(head, b"xl/") {
206        return Some(Format::Xlsx);
207    }
208    None
209}
210
211/// If the ZIP's first entry is named `mimetype`, return its (stored) content.
212fn first_entry_mimetype(head: &[u8]) -> Option<String> {
213    // Local file header: signature(4) .. name_len(2) @26, extra_len(2) @28, name @30.
214    const NAME_LEN_OFFSET: usize = 26;
215    const NAME_OFFSET: usize = 30;
216
217    let name_len =
218        u16::from_le_bytes([*head.get(NAME_LEN_OFFSET)?, *head.get(NAME_LEN_OFFSET + 1)?]) as usize;
219    let extra_len = u16::from_le_bytes([
220        *head.get(NAME_LEN_OFFSET + 2)?,
221        *head.get(NAME_LEN_OFFSET + 3)?,
222    ]) as usize;
223    let name = head.get(NAME_OFFSET..NAME_OFFSET + name_len)?;
224    if name != b"mimetype" {
225        return None;
226    }
227
228    // ODF/EPUB store `mimetype` uncompressed and first, so its bytes follow the header.
229    let start = NAME_OFFSET + name_len + extra_len;
230    let value = head.get(start..)?;
231    let end = value
232        .iter()
233        .position(
234            |b| !matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'+' | b'-' | b'/'),
235        )
236        .unwrap_or(value.len());
237    let mimetype = std::str::from_utf8(&value[..end]).ok()?;
238    (!mimetype.is_empty()).then(|| mimetype.to_string())
239}
240
241/// Last-resort HTML sniff for extensionless files.
242fn looks_like_html(head: &[u8]) -> bool {
243    let probe: Vec<u8> = head
244        .iter()
245        .take(512)
246        .map(|b| b.to_ascii_lowercase())
247        .collect();
248    contains(&probe, b"<!doctype html") || contains(&probe, b"<html")
249}
250
251fn contains(haystack: &[u8], needle: &[u8]) -> bool {
252    haystack
253        .windows(needle.len())
254        .any(|window| window == needle)
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn sniff(ext: &str, head: &[u8]) -> Sniff {
262        Sniff::new(Some(ext.to_string()), head.to_vec())
263    }
264
265    /// Build a minimal ZIP local file header for `name`, followed by `payload`.
266    fn zip_entry(name: &[u8], payload: &[u8]) -> Vec<u8> {
267        let mut bytes = Vec::new();
268        bytes.extend_from_slice(b"PK\x03\x04");
269        bytes.extend_from_slice(&[0u8; 22]); // version..uncompressed size
270        bytes.extend_from_slice(&(name.len() as u16).to_le_bytes());
271        bytes.extend_from_slice(&0u16.to_le_bytes()); // extra field length
272        bytes.extend_from_slice(name);
273        bytes.extend_from_slice(payload);
274        bytes
275    }
276
277    #[test]
278    fn extension_maps_to_format() {
279        assert_eq!(Format::from_extension("MD"), Some(Format::Markdown));
280        assert_eq!(Format::from_extension("htm"), Some(Format::Html));
281        assert_eq!(Format::from_extension("xlsx"), Some(Format::Xlsx));
282        assert_eq!(Format::from_extension("exe"), None);
283    }
284
285    #[test]
286    fn signature_beats_extension() {
287        // A PDF that someone named `.txt` is still a PDF.
288        let detected = detect(&sniff("txt", b"%PDF-1.7\n%\xe2\xe3\xcf\xd3"));
289        assert_eq!(detected, Some(Format::Pdf));
290    }
291
292    #[test]
293    fn text_formats_come_from_the_extension() {
294        assert_eq!(detect(&sniff("txt", b"hello")), Some(Format::Txt));
295        assert_eq!(detect(&sniff("csv", b"a,b\n1,2\n")), Some(Format::Csv));
296        assert_eq!(detect(&sniff("md", b"# Title\n")), Some(Format::Markdown));
297    }
298
299    #[test]
300    fn rtf_is_detected_by_signature() {
301        assert_eq!(detect(&sniff("bin", b"{\\rtf1\\ansi")), Some(Format::Rtf));
302    }
303
304    #[test]
305    fn ooxml_zip_is_classified_by_part_names() {
306        let docx = zip_entry(b"[Content_Types].xml", b"<Types/>word/document.xml");
307        assert_eq!(detect(&sniff("bin", &docx)), Some(Format::Docx));
308
309        let pptx = zip_entry(b"[Content_Types].xml", b"<Types/>ppt/presentation.xml");
310        assert_eq!(detect(&sniff("bin", &pptx)), Some(Format::Pptx));
311
312        let xlsx = zip_entry(b"[Content_Types].xml", b"<Types/>xl/workbook.xml");
313        assert_eq!(detect(&sniff("bin", &xlsx)), Some(Format::Xlsx));
314    }
315
316    #[test]
317    fn odf_and_epub_are_classified_by_mimetype_entry() {
318        let epub = zip_entry(b"mimetype", b"application/epub+zip");
319        assert_eq!(detect(&sniff("bin", &epub)), Some(Format::Epub));
320
321        let odt = zip_entry(b"mimetype", b"application/vnd.oasis.opendocument.text");
322        assert_eq!(detect(&sniff("bin", &odt)), Some(Format::Odt));
323
324        let ods = zip_entry(
325            b"mimetype",
326            b"application/vnd.oasis.opendocument.spreadsheet",
327        );
328        assert_eq!(detect(&sniff("bin", &ods)), Some(Format::Ods));
329    }
330
331    #[test]
332    fn html_is_sniffed_without_an_extension() {
333        let sniffed = Sniff::new(None, b"<!DOCTYPE HTML><html><body>hi".to_vec());
334        assert_eq!(detect(&sniffed), Some(Format::Html));
335    }
336
337    #[test]
338    fn unknown_type_is_not_detected() {
339        assert_eq!(detect(&sniff("exe", b"MZ\x90\x00")), None);
340        assert_eq!(detect(&Sniff::new(None, b"\x00\x01\x02".to_vec())), None);
341    }
342}