Skip to main content

Module magic

Module magic 

Source
Expand description

What a file is, decided by its contents.

The other half of the question crate::globs answers by name. A file with no extension, or one whose extension lies, can still be recognised by what is in it: %PDF- at offset 0, \x89PNG at offset 0, solid for an ASCII STL.

§The format

/usr/share/mime/magic is binary, and deliberately so — it is read at every content lookup on the system. After the header MIME-Magic\0\n it is a sequence of sections:

[<priority>:<mime type>]\n
[indent]>offset=LLvalue[&mask][~word][+range]\n

LL is two bytes, big-endian, giving the length of value — which is raw bytes and may itself contain a newline. That single detail is why this is parsed byte by byte and not with lines(): splitting on \n cuts rules in half, quietly, and the ones it cuts are the interesting ones.

§Nesting

A rule indented one deeper than the line above is a further condition on it. A rule matches when its own pattern matches and, if it has children, at least one child matches too. That is what makes >0=\x00\x05<?xml plus 1>0=...DocBook... mean “an XML file, and specifically a DocBook one” rather than two unrelated claims.

§Why this exists when globs2 already answered

Most of the time the name is right and this is not consulted at all — see crate::lookup for the order. It earns its place on the files that have no name to go on: something saved as download, a file being examined before it is renamed, stdin.

Structs§

Magic
The content rules, in the order the database gives them.
Match
What a content match found, and how much it should be trusted.

Functions§

head
The first SNIFF_BYTES of a file, for content matching.