• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

src/H03-May-2022-2,5711,952

.cargo-checksum.jsonH A D03-May-202289 11

.cargo_vcs_info.jsonH A D25-Feb-202074 65

.directoryH A D25-Feb-202063 54

.gitignoreH A D07-Apr-201739 64

CHANGELOG.mdH A D25-Feb-20201.2 KiB4228

Cargo.lockH A D25-Feb-202013.3 KiB306269

Cargo.tomlH A D25-Feb-20201.6 KiB7258

Cargo.toml.orig-cargoH A D25-Feb-20201.1 KiB3933

LICENSEH A D23-Feb-20201.1 KiB2217

README.mdH A D23-Feb-20207.9 KiB11663

README.md

1# tree_magic
2
3tree_magic is a Rust crate that determines the MIME type a given file or byte stream.
4
5Read the documentation at https://docs.rs/tree_magic/
6
7`stable` users: You may need to include the `cli` feature flag, even if you're using it as a library! (This is fixed on `nightly`)
8
9Unlike the typical approach that libmagic and file(1) uses, this loads all the file types in a tree based on subclasses. (EX: `application/vnd.openxmlformats-officedocument.wordprocessingml.document` (MS Office 2007) subclasses `application/zip` which subclasses `application/octet-stream`) Then, instead of checking the file against *every* file type, it can traverse down the tree and only check the file types that make sense to check. (After all, the fastest check is the check that never gets run.)
10
11This library also provides the ability to check if a file is a certain type without going through the process of checking it against every file type.
12
13A simple command-line client `tmagic` is also provided that acts as a replacement for `file --mime-type`, excluding charset information.
14
15## Performance
16
17This is fast. FAST.
18
19This is a test of my Downloads folder (sorry, can't find a good publicly available set of random files) on OpenSUSE Tumbleweed. `tmagic` was compiled with `cargo build --release`, and `file` came from the OpenSUSE repos. This is a warm run, which means I've ran both programs through a few times. System is a dual-core Intel Core i7 640M, and results were measured with `time`.
20
21Program | real | user | sys
22--------|------|------|-----
23tmagic 0.2.0 | 0m0.063s | 0m0.052s | 0m0.004s
24file-5.30 --mime-type | 0m0.924s | 0.800s | 0.116s
25
26There's a couple things that lead to this. Mainly:
27
28- Less types to parse due to graph approach.
29
30- First 4K of file is loaded then passed to all parsers, instead of constantly reloading from disk. (When doing that, the time was more around ~0.130s.)
31
32- The most common types (image/png, image/jpeg, application/zip, etc.) are checked before the exotic ones.
33
34- Everything that can be processed in a lazy_static! is.
35
36Nightly users can also run `cargo bench` for some benchmarks. For tree_magic 0.2.0 on the same hardware:
37
38    test from_u8::application_zip  ... bench:      17,086 ns/iter (+/- 845)
39    test from_u8::image_gif        ... bench:       5,027 ns/iter (+/- 520)
40    test from_u8::image_png        ... bench:       4,421 ns/iter (+/- 1,795)
41    test from_u8::text_plain       ... bench:     112,578 ns/iter (+/- 11,778)
42    test match_u8::application_zip ... bench:         222 ns/iter (+/- 144)
43    test match_u8::image_gif       ... bench:         140 ns/iter (+/- 14)
44    test match_u8::image_png       ... bench:         139 ns/iter (+/- 18)
45    test match_u8::text_plain      ... bench:          44 ns/iter (+/- 3)
46
47However, it should be noted that the FreeDesktop.org magic files less filetypes than the magic files used by libmagic. (On my system tree_magic supports 400 types, while `/usr/share/misc/magic` contains 855 `!:mime` tags.) It is, however, significantly easier to parse, as it only covers magic numbers and not attributes or anything like that. See the TODO section for plans to fix this.
48
49## Compatibility
50
51This has been tested using Rust Stable and Nightly on Windows 7 and OpenSUSE Tumbleweed Linux.
52
53All mime information and relation information is loaded from the Shared MIME-info Database as described at https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html. If you beleive that this is not present on your system, turn off the `sys_fdo_magic` feature flag.
54
55This provides the most common file types, but it's still missing some important ones, like LibreOffice or MS Office 2007+ support or ISO files. Expect this to improve, especially as the `zip` checker is added.
56
57### Architecture
58
59`tree_magic` is split up into different "checker" modules. Each checker handles a certain set of filetypes, and only those. For instance, the `basetype` checker handles the `inode/*` and `text/plain` types, while the `fdo_magic` checker handles anything with a magic number. Th idea here is that instead of following the `libmagic` route of having one magic descriptor format that fits every file, we can specialize and choose the checker that suits the file format best.
60
61During library initialization, each checker is queried for the types is supports and the parent->child relations between them. During this time, the checkers can load any rules, schemas, etc. into memory. A big philosophy here is that **time during the checking phase is many times more valuable than during the init phase**. The library only gets initialized once, and the library can check thousands of files during a program's lifetime.
62
63From the list of file types and relations, a directed graph is built, and each node is added to a hash map. The library user can use these directly to find parents, children, etc. of a given MIME if needed.
64
65When a file needs to be checked against a certain MIME (match_*), each checker is queried to see if it supports that type, and if so, it runs the checker. If the checker returns true, it must be that type.
66
67When a file needs it's MIME type found (from_*), the library starts at the `all/all` node of the type graph (or whichever node the user specifies) and walks down the tree. If a match is found, it continues searching down that branch. If no match is found, it retrieves the deepest MIME type found.
68
69## TODO
70
71### Improve fdo-magic checker
72
73Right now the `fdo-magic` checker does not handle endianess. It also does not handle magic files stored in the user's home directory.
74
75### Additional checkers
76
77It is planned to have custom file checking functions for many types. Here's some ideas:
78
79- `zip`: Everything that subclasses `application/zip` can be determined further by peeking at the zip's directory listing.
80
81- `grep`: Text files such as program scripts and configuration files could be parsed with a regex (or whatever works best).
82
83- `json`, `toml`, `xml`, etc: Check the given file against a schema and return true if it matches. (By this point there should be few enough potential matches that it should be okay to load the entire file)
84
85- (specialized parsers): Binary (or text) files without any sort of magic can be checked for compliance against a quick and dirty `nom` parser instead of the weird heuristics used by libmagic.
86
87To add additional checker types, add a new module exporting:
88
89- `init::get_supported() -> Vec<(String)>`
90
91- `init::get_subclasses() -> Vec<String, String)>`
92
93- `test::from_u8(&[u8], &str) -> bool`
94
95- `test::from_filpath(&str, &str) -> Result<bool, std::io::Error>`
96
97and then add references to those functions into the CHECKERS lazy_static! in `lib.rs`. The bottommost entries get searched first.
98
99### Caching
100
101Going forward, it is essential for a checker (like `basetype`'s metadata, or that json/toml/xml example) to be able to cache an in-memory representation of the file, so it doesn't have to get re-loaded and re-parsed for every new type. With the current architecture, this is rather difficult to implement.
102
103### Multiple file types
104
105There are some weird files out there ( [Polyglot quines](https://en.wikipedia.org/wiki/Polyglot_(computing)) come to mind. ) that are multiple file types. This might be worth handling for security reasons. (It's not a huge priority, though.)
106
107### Parallel processing
108
109Right now this is single-threaded. This is an embarasingly parallel task (multiple files, multiple types, multiple rules for each type...), so there should be a great speed benefit.
110
111## TO NOT DO
112
113### File attributes
114
115`libmagic` and `file`, by default, print descriptive strings detailing the file type and, for things like JPEG images or ELF files, a whole bunch of metadata. This is not something `tree_magic` will ever support, as it is entirely unnecessary. Support for attributes would best be handled in a seperate crate that, given a MIME, can extract metadata in a predictable, machine readable format.
116