Skip to main content

tiny_tree_magic/
lib.rs

1use std::collections::{HashMap, VecDeque, hash_map::Entry};
2use std::error::Error as StdError;
3use std::fmt;
4use std::hint::cold_path;
5use std::ops::Range;
6use std::str::from_utf8;
7
8use memchr::{memchr, memmem::find};
9
10pub struct Database<C> {
11    cache: C,
12    types: Box<[FrozenType]>,
13    matches: FrozenMatches,
14    children: FrozenChildren,
15    text_idx: u32,
16    binary_idx: u32,
17}
18
19#[derive(Debug, Default)]
20struct Type {
21    matches: Vec<Match>,
22    children: Vec<u32>,
23}
24
25#[derive(Debug)]
26struct Match {
27    cnt: u32,
28    off: u32,
29}
30
31#[derive(Debug)]
32struct FrozenType {
33    mime_type_off: u32,
34    matches: Range<u32>,
35    children: Range<u32>,
36}
37
38type FrozenMatches = Box<[Match]>;
39
40type FrozenChildren = Box<[u32]>;
41
42impl<C> Database<C>
43where
44    C: AsRef<[u8]>,
45{
46    /// Open the given MIME-info `cache`
47    ///
48    /// This can be an in-memory buffer or a memory map of a [mime.cache file](https://specifications.freedesktop.org/shared-mime-info/latest/ar01s02.html#id-1.3.12).
49    ///
50    /// ```no_run
51    /// # use std::error::Error;
52    /// use std::fs::File;
53    ///
54    /// use memmap2::Mmap;
55    /// use tiny_tree_magic::Database;
56    ///
57    /// let cache = unsafe { Mmap::map(&File::open("/usr/share/mime/mime.cache")?)? };
58    ///
59    /// let database = Database::open(cache)?;
60    /// # Ok::<_, Box<dyn Error>>(())
61    /// ```
62    #[cold]
63    pub fn open(cache: C) -> Result<Self, Error> {
64        let (parents, types) = parse_offsets(cache.as_ref()).ok_or(Error::MalformedOffsets)?;
65
66        let mut parents = parse_parents(cache.as_ref(), parents).ok_or(Error::MalformedParents)?;
67
68        let mut types = parse_types(cache.as_ref(), types).ok_or(Error::MalformedTypes)?;
69
70        let (text_off, binary_off) = parents_to_children(cache.as_ref(), &mut parents, &mut types)?;
71
72        let types = sort(types, parents)?;
73
74        Ok(Self::freeze(cache, types, text_off, binary_off))
75    }
76
77    fn freeze(cache: C, types: Vec<(u32, Type)>, text_off: u32, binary_off: u32) -> Self {
78        let mut matches =
79            Vec::with_capacity(types.iter().map(|(_, r#type)| r#type.matches.len()).sum());
80        let mut children =
81            Vec::with_capacity(types.iter().map(|(_, r#type)| r#type.children.len()).sum());
82
83        let types = types
84            .into_iter()
85            .map(|(mime_type_off, r#type)| {
86                let matches_start = u32::try_from(matches.len()).unwrap();
87                let matches_len = u32::try_from(r#type.matches.len()).unwrap();
88                let matches_end = matches_start.checked_add(matches_len).unwrap();
89                matches.extend(r#type.matches);
90
91                let children_start = u32::try_from(children.len()).unwrap();
92                let children_len = u32::try_from(r#type.children.len()).unwrap();
93                let children_end = children_start.checked_add(children_len).unwrap();
94                children.extend(r#type.children);
95
96                FrozenType {
97                    mime_type_off,
98                    matches: matches_start..matches_end,
99                    children: children_start..children_end,
100                }
101            })
102            .collect::<Box<[_]>>();
103
104        let mime_type_off_to_type_idx = types
105            .iter()
106            .enumerate()
107            .map(|(idx, r#type)| (r#type.mime_type_off, u32::try_from(idx).unwrap()))
108            .collect::<HashMap<_, _>>();
109
110        for type_idx in &mut children {
111            *type_idx = mime_type_off_to_type_idx[type_idx];
112        }
113
114        Self {
115            cache,
116            types,
117            matches: matches.into(),
118            children: children.into(),
119            text_idx: mime_type_off_to_type_idx[&text_off],
120            binary_idx: mime_type_off_to_type_idx[&binary_off],
121        }
122    }
123
124    pub fn r#match<'a>(&'a self, bytes: &[u8]) -> Result<&'a str, Error> {
125        let is_text = memchr(0, bytes).is_none();
126
127        let text_type = &self.types[self.text_idx as usize];
128        let binary_type = &self.types[self.binary_idx as usize];
129
130        let mime_type_off = if is_text
131            && let Some(mime_type_off) = self.match_children(None, &text_type.children, bytes)?
132        {
133            mime_type_off
134        } else if let Some(mime_type_off) =
135            self.match_children(None, &binary_type.children, bytes)?
136        {
137            mime_type_off
138        } else if is_text {
139            text_type.mime_type_off
140        } else {
141            binary_type.mime_type_off
142        };
143
144        resolve_mime_type(self.cache.as_ref(), mime_type_off).ok_or(Error::InvalidMimeType)
145    }
146
147    fn match_children(
148        &self,
149        default: Option<u32>,
150        children: &Range<u32>,
151        bytes: &[u8],
152    ) -> Result<Option<u32>, Error> {
153        let children = &self.children[children.start as usize..children.end as usize];
154
155        for type_idx in children {
156            let r#type = &self.types[*type_idx as usize];
157
158            let matches = &self.matches[r#type.matches.start as usize..r#type.matches.end as usize];
159
160            for r#match in matches {
161                if try_match(self.cache.as_ref(), 0, r#match.cnt, r#match.off, bytes)
162                    .ok_or(Error::MalformedMatch)?
163                {
164                    return self.match_children(
165                        Some(r#type.mime_type_off),
166                        &r#type.children,
167                        bytes,
168                    );
169                }
170            }
171        }
172
173        Ok(default)
174    }
175}
176
177fn try_match(cache: &[u8], depth: u8, cnt: u32, off: u32, bytes: &[u8]) -> Option<bool> {
178    if depth == 128 {
179        cold_path();
180        return None;
181    }
182
183    let cnt = cnt as usize;
184    let off = off as usize;
185
186    let matchlets = cache.get(off..)?.get(..32 * cnt)?;
187
188    for idx in 0..cnt {
189        let matchlet = &matchlets[32 * idx..][..32];
190
191        if try_matchlet(cache, matchlet, bytes)? {
192            let cnt = parse_u32(matchlet, 24);
193            let off = parse_u32(matchlet, 28);
194
195            if cnt == 0 || try_match(cache, depth + 1, cnt, off, bytes)? {
196                return Some(true);
197            }
198        }
199    }
200
201    Some(false)
202}
203
204#[inline]
205fn try_matchlet(cache: &[u8], matchlet: &[u8], bytes: &[u8]) -> Option<bool> {
206    let range_start = parse_u32(matchlet, 0) as usize;
207    let range_length = parse_u32(matchlet, 4) as usize;
208    let data_length = parse_u32(matchlet, 12) as usize;
209    let data_offset = parse_u32(matchlet, 16) as usize;
210    let mask_offset = parse_u32(matchlet, 20) as usize;
211
212    let data = cache.get(data_offset..)?.get(..data_length)?;
213
214    let mask = if mask_offset != 0 {
215        Some(cache.get(mask_offset..)?.get(..data_length)?)
216    } else {
217        None
218    };
219
220    for pos in range_start..range_start + range_length {
221        if let Some(bytes) = bytes.get(pos..pos + data_length) {
222            if let Some(mask) = mask {
223                if data
224                    .iter()
225                    .zip(mask)
226                    .zip(bytes)
227                    .all(|((data, mask), byte)| data & mask == byte & mask)
228                {
229                    return Some(true);
230                }
231            } else {
232                if compare(data, bytes) {
233                    return Some(true);
234                }
235            }
236        } else {
237            break;
238        }
239    }
240
241    Some(false)
242}
243
244#[inline]
245fn compare(lhs: &[u8], rhs: &[u8]) -> bool {
246    let len = lhs.len();
247    debug_assert_eq!(len, rhs.len());
248
249    if len >= 8 {
250        let lhs_lo = u64::from_le_bytes(lhs[..8].try_into().unwrap());
251        let rhs_lo = u64::from_le_bytes(rhs[..8].try_into().unwrap());
252        if lhs_lo != rhs_lo {
253            return false;
254        } else if len == 8 {
255            return true;
256        }
257
258        let lhs_hi = u64::from_le_bytes(lhs[len - 8..].try_into().unwrap());
259        let rhs_hi = u64::from_le_bytes(rhs[len - 8..].try_into().unwrap());
260        if lhs_hi != rhs_hi {
261            return false;
262        } else if len <= 16 {
263            return true;
264        }
265    } else if len >= 4 {
266        let lhs_lo = u32::from_le_bytes(lhs[..4].try_into().unwrap());
267        let rhs_lo = u32::from_le_bytes(rhs[..4].try_into().unwrap());
268        if lhs_lo != rhs_lo {
269            return false;
270        }
271
272        let lhs_hi = u32::from_le_bytes(lhs[len - 4..].try_into().unwrap());
273        let rhs_hi = u32::from_le_bytes(rhs[len - 4..].try_into().unwrap());
274        return lhs_hi == rhs_hi;
275    } else if len > 0 {
276        let lhs_lo = lhs[0];
277        let rhs_lo = rhs[0];
278        if lhs_lo != rhs_lo {
279            return false;
280        }
281
282        let lhs_mid = lhs[len / 2];
283        let rhs_mid = rhs[len / 2];
284        if lhs_mid != rhs_mid {
285            return false;
286        }
287
288        let lhs_hi = lhs[len - 1];
289        let rhs_hi = rhs[len - 1];
290        return lhs_hi == rhs_hi;
291    } else {
292        return true;
293    }
294
295    lhs == rhs
296}
297
298fn sort(
299    mut types: HashMap<u32, Type>,
300    mut parents: HashMap<u32, Vec<u32>>,
301) -> Result<Vec<(u32, Type)>, Error> {
302    let mut sorted = Vec::with_capacity(types.len());
303
304    let mut orphans = types
305        .keys()
306        .copied()
307        .filter(|mime_type_off| !parents.contains_key(mime_type_off))
308        .collect::<VecDeque<_>>();
309
310    while let Some(orphan_mime_type_off) = orphans.pop_back() {
311        let orphan_type = types.remove(&orphan_mime_type_off).unwrap();
312
313        for child_mime_type_off in &orphan_type.children {
314            match parents.entry(*child_mime_type_off) {
315                Entry::Occupied(mut entry) => {
316                    let parents = entry.get_mut();
317
318                    parents.retain(|parent_mime_type_off| {
319                        *parent_mime_type_off != orphan_mime_type_off
320                    });
321
322                    if parents.is_empty() {
323                        entry.remove();
324
325                        orphans.push_front(*child_mime_type_off);
326                    }
327                }
328                Entry::Vacant(_) => unreachable!(),
329            }
330        }
331
332        sorted.push((orphan_mime_type_off, orphan_type));
333    }
334
335    if parents.is_empty() {
336        Ok(sorted)
337    } else {
338        Err(Error::MalformedParents)
339    }
340}
341
342fn parents_to_children(
343    cache: &[u8],
344    parents: &mut HashMap<u32, Vec<u32>>,
345    types: &mut HashMap<u32, Type>,
346) -> Result<(u32, u32), Error> {
347    types.retain(|mime_type_off, _type| resolve_mime_type(cache, *mime_type_off).is_some());
348
349    parents.retain(|mime_type_off, parents| {
350        if types.contains_key(mime_type_off) {
351            parents.retain(|parent_mime_type_off| types.contains_key(parent_mime_type_off));
352
353            !parents.is_empty()
354        } else {
355            false
356        }
357    });
358
359    let text_off =
360        find_or_insert_mime_type(cache, types, "text/plain\0").ok_or(Error::MissingTextPlain)?;
361
362    let binary_off = find_or_insert_mime_type(cache, types, "application/octet-stream\0")
363        .ok_or(Error::MissingApplicationOctetStream)?;
364
365    for mime_type_off in types.keys() {
366        if *mime_type_off != text_off
367            && *mime_type_off != binary_off
368            && let Entry::Vacant(entry) = parents.entry(*mime_type_off)
369        {
370            let mime_type = resolve_mime_type(cache, *mime_type_off).unwrap();
371
372            let parent_mime_type_off = if mime_type.starts_with("text/") {
373                text_off
374            } else {
375                binary_off
376            };
377
378            entry.insert(vec![parent_mime_type_off]);
379        }
380    }
381
382    for (mime_type_off, parents) in parents {
383        for parent_mime_type_off in parents {
384            types
385                .get_mut(parent_mime_type_off)
386                .unwrap()
387                .children
388                .push(*mime_type_off);
389        }
390    }
391
392    for r#type in types.values_mut() {
393        r#type.children.sort_unstable();
394        r#type.children.dedup();
395    }
396
397    Ok((text_off, binary_off))
398}
399
400fn find_or_insert_mime_type(
401    cache: &[u8],
402    types: &mut HashMap<u32, Type>,
403    mime_type0: &str,
404) -> Option<u32> {
405    let mime_type = &mime_type0[..mime_type0.len() - 1];
406
407    let mime_type_off = types
408        .keys()
409        .copied()
410        .find(|mime_type_off| resolve_mime_type(cache, *mime_type_off) == Some(mime_type));
411
412    mime_type_off.or_else(|| {
413        let mime_type_off = find(cache, mime_type0.as_bytes())?.try_into().ok()?;
414
415        types.insert(mime_type_off, Default::default());
416
417        Some(mime_type_off)
418    })
419}
420
421fn resolve_mime_type(cache: &[u8], mime_type_off: u32) -> Option<&str> {
422    let off = mime_type_off as usize;
423    let bytes = cache.get(off..)?;
424
425    let pos = memchr(0, bytes)?;
426    let mime_type = &bytes[..pos];
427
428    from_utf8(mime_type).ok()
429}
430
431fn parse_offsets(cache: &[u8]) -> Option<(&[u8], &[u8])> {
432    if cache.len() < 2 * 2 + 9 * 4 {
433        return None;
434    }
435
436    let parents_off = parse_u32(cache, 2 * 2 + 4) as usize;
437    let types_off = parse_u32(cache, 2 * 2 + 5 * 4) as usize;
438
439    let parents = cache.get(parents_off..)?;
440    let types = cache.get(types_off..)?;
441
442    Some((parents, types))
443}
444
445fn parse_parents<'a>(cache: &'a [u8], bytes: &'a [u8]) -> Option<HashMap<u32, Vec<u32>>> {
446    if bytes.len() < 4 {
447        return None;
448    }
449
450    let cnt = parse_u32(bytes, 0) as usize;
451
452    let bytes = bytes.get(4..)?.get(..8 * cnt)?;
453
454    let mut parents = HashMap::<_, Vec<_>>::with_capacity(cnt);
455
456    for idx in 0..cnt {
457        let bytes = &bytes[8 * idx..][..8];
458
459        let mime_type_off = parse_u32(bytes, 0);
460        let parents_off = parse_u32(bytes, 4) as usize;
461
462        let bytes = cache.get(parents_off..)?;
463
464        if bytes.len() < 4 {
465            return None;
466        }
467
468        let cnt = parse_u32(bytes, 0) as usize;
469
470        let bytes = bytes.get(4..)?.get(..4 * cnt)?;
471
472        let parents = parents.entry(mime_type_off).or_default();
473        parents.reserve(cnt);
474
475        for idx in 0..cnt {
476            let parent_mime_type_off = parse_u32(bytes, 4 * idx);
477
478            parents.push(parent_mime_type_off);
479        }
480    }
481
482    Some(parents)
483}
484
485fn parse_types(cache: &[u8], bytes: &[u8]) -> Option<HashMap<u32, Type>> {
486    if bytes.len() < 3 * 4 {
487        return None;
488    }
489
490    let cnt = parse_u32(bytes, 0) as usize;
491    let off = parse_u32(bytes, 8) as usize;
492
493    let bytes = cache.get(off..)?.get(..16 * cnt)?;
494
495    let mut types = HashMap::<_, Type>::with_capacity(cnt);
496
497    for idx in 0..cnt {
498        let bytes = &bytes[16 * idx..];
499
500        let mime_type_off = parse_u32(bytes, 4);
501
502        let cnt = parse_u32(bytes, 8);
503        let off = parse_u32(bytes, 12);
504
505        types
506            .entry(mime_type_off)
507            .or_default()
508            .matches
509            .push(Match { cnt, off });
510    }
511
512    Some(types)
513}
514
515fn parse_u32(bytes: &[u8], off: usize) -> u32 {
516    u32::from_be_bytes(bytes[off..][..4].try_into().unwrap())
517}
518
519#[derive(Debug)]
520pub enum Error {
521    MalformedOffsets,
522    MalformedParents,
523    MalformedTypes,
524    MalformedMatch,
525    MissingTextPlain,
526    MissingApplicationOctetStream,
527    InvalidMimeType,
528}
529
530impl fmt::Display for Error {
531    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
532        let msg = match self {
533            Self::MalformedOffsets => "Malformed offsets",
534            Self::MalformedParents => "Malformed parents",
535            Self::MalformedTypes => "Malformed types",
536            Self::MalformedMatch => "Malformed match",
537            Self::MissingTextPlain => "Missing text/plain MIME type",
538            Self::MissingApplicationOctetStream => "Missing application/octet-stream MIME type",
539            Self::InvalidMimeType => "Invalid MIME type",
540        };
541
542        fmt.write_str(msg)
543    }
544}
545
546impl StdError for Error {}