Skip to main content

magic/
lib.rs

1// SPDX-FileCopyrightText: © The `magic` Rust crate authors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! # About
5//!
6//! This crate provides bindings for the `libmagic` C library, which recognizes the
7//! type of data contained in a file (or buffer).
8//!
9//! You might be familiar with `libmagic`'s command-line-interface; [`file`](https://www.darwinsys.com/file/):
10//!
11//! ```shell
12//! $ file data/tests/rust-logo-128x128-blk.png
13//! data/tests/rust-logo-128x128-blk.png: PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced
14//! ```
15//!
16//! ## `libmagic`
17//!
18//! Understanding how the `libmagic` C library and thus this Rust crate works requires a bit of glossary.
19//!
20//! `libmagic` at its core can analyze a file or buffer and return a mostly unstructured text that describes the analysis result.
21//! There are built-in tests for special cases such as symlinks and compressed files
22//! and there are magic databases with signatures which can be supplied by the user for the generic cases
23//! ("if those bytes look like this, it's a PNG image file").
24//!
25//! The analysis behaviour can be influenced by so-called flags and parameters.
26//! Flags are either set or unset and do not have a value, parameters have a value.
27//!
28//! Databases can be in text form or compiled binary form for faster access. They can be loaded from files on disk or from in-memory buffers.
29//! A regular `libmagic` / `file` installation contains a default database file that includes a plethora of file formats.
30//!
31//! Most `libmagic` functionality requires a configured instance which is called a "magic cookie".
32//! Creating a cookie instance requires initial flags and usually loaded databases.
33//!
34//! # Usage example
35//!
36//! ```rust
37//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
38//! # use std::convert::TryInto;
39//! // open a new configuration with flags
40//! let cookie = magic::Cookie::open(magic::cookie::Flags::ERROR)?;
41//!
42//! // load a specific database
43//! // (so exact test text assertion below works regardless of the system's default database version)
44//! let database = ["data/tests/db-images-png"].try_into()?;
45//! // you can instead load the default database
46//! //let database = Default::default();
47//!
48//! let cookie = cookie.load(&database)?;
49//!
50//! // analyze a test file
51//! let file_to_analyze = "data/tests/rust-logo-128x128-blk.png";
52//! let expected_analysis_result = "PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced";
53//! assert_eq!(cookie.file(file_to_analyze)?, expected_analysis_result);
54//! # Ok(())
55//! # }
56//! ```
57//!
58//! See further examples in [`examples/`](https://github.com/robo9k/rust-magic/tree/main/examples).
59//!
60//! # MIME example
61//!
62//! Return a MIME type with "charset" encoding parameter:
63//!
64//! ```shell
65//! $ file --mime data/tests/rust-logo-128x128-blk.png
66//! data/tests/rust-logo-128x128-blk.png: image/png; charset=binary
67//! ```
68//! ```rust
69//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
70//! # use std::convert::TryInto;
71//! // open a new configuration with flags for mime type and encoding
72//! let flags = magic::cookie::Flags::MIME_TYPE | magic::cookie::Flags::MIME_ENCODING;
73//! let cookie = magic::Cookie::open(flags)?;
74//!
75//! // load a specific database
76//! let database = ["data/tests/db-images-png"].try_into()?;
77//! let cookie = cookie.load(&database)?;
78//!
79//! // analyze a test file
80//! let file_to_analyze = "data/tests/rust-logo-128x128-blk.png";
81//! let expected_analysis_result = "image/png; charset=binary";
82//! assert_eq!(cookie.file(file_to_analyze)?, expected_analysis_result);
83//! # Ok(())
84//! # }
85//! ```
86//!
87//! See [`magic::cookie::Flags::MIME`](crate::cookie::Flags::MIME).
88//!
89//! # Filename extensions example
90//!
91//! Return slash-separated filename extensions (the ".png" in "example.png")
92//! from file contents (the input filename is not used for detection):
93//!
94//! ```shell
95//! $ file --extension data/tests/rust-logo-128x128-blk.png
96//! data/tests/rust-logo-128x128-blk.png: png
97//! ```
98//! ```rust
99//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
100//! # use std::convert::TryInto;
101//! // open a new configuration with flags for filename extension
102//! let flags = magic::cookie::Flags::EXTENSION;
103//! let cookie = magic::Cookie::open(flags)?;
104//!
105//! // load a specific database
106//! let database = ["data/tests/db-images-png"].try_into()?;
107//! let cookie = cookie.load(&database)?;
108//!
109//! // analyze a test file
110//! let file_to_analyze = "data/tests/rust-logo-128x128-blk.png";
111//! let expected_analysis_result = "png";
112//! assert_eq!(cookie.file(file_to_analyze)?, expected_analysis_result);
113//! # Ok(())
114//! # }
115//! ```
116//!
117//! See [`magic::cookie::Flags::EXTENSION`](crate::cookie::Flags::EXTENSION).
118//!
119//! # Further reading
120//!
121//! * [`Cookie::open()`][Cookie::open]
122//! * cookie [`Flags`](crate::cookie::Flags), in particular:
123//!     * [`Flags::ERROR`](crate::cookie::Flags::ERROR)
124//!     * [`Flags::MIME`](crate::cookie::Flags::MIME)
125//!     * [`Flags::EXTENSION`](crate::cookie::Flags::EXTENSION)
126//!     * [`Flags::CONTINUE`](crate::cookie::Flags::CONTINUE)
127//!     * [`Flags::NO_CHECK_BUILTIN`](crate::cookie::Flags::NO_CHECK_BUILTIN)
128//! * [`Cookie::load()`](Cookie::load), [`Cookie::load_buffers()`](Cookie::load_buffers)
129//! * [`Cookie::file()`](Cookie::file), [`Cookie::buffer()`](Cookie::buffer)
130//!
131//! Note that while some `libmagic` functions return somewhat structured text, e.g. MIME types and file extensions,
132//! the `magic` crate does not attempt to parse them into Rust data types since the format is not guaranteed by the C FFI API.
133//!
134//! Check the [crate README](https://crates.io/crates/magic) for required dependencies and MSRV.
135//!
136//! # Features
137//!
138//! ## `libmagic` API features
139//! - `libmagic+v5-40` — Enable `libmagic` v5.40 API
140//! - `libmagic+v5-44` — Enable `libmagic` v5.44 API
141//! - `libmagic+v5-45` — Enable `libmagic` v5.45 API
142//!
143//! # Safety
144//!
145//! This crate is a binding to the `libmagic` C library and as such subject to its security problems.
146//! Please note that `libmagic` has several CVEs, listed on e.g. [Repology](https://repology.org/project/file/cves).
147//! Make sure that you are using an up-to-date version of `libmagic` and ideally
148//! add additional security layers such as sandboxing (which this crate does _not_ provide)
149//! and __do not use it on untrusted input__ e.g. from users on the internet!
150//!
151//! The Rust code of this crate needs to use some `unsafe` for interacting with the `libmagic` C FFI.
152//!
153//! This crate has not been audited nor is it ready for production use.
154//!
155//! This Rust project / crate is not affiliated with the original `file` / `libmagic` C project.
156//!
157//! # Use cases
158//!
159//! `libmagic` can help to identify unknown content. It does this by looking at byte patterns, among other things.
160//! This does not guarantee that e.g. a file which is detected as a PNG image is indeed a valid PNG image.
161//!
162//! Maybe you just want a mapping from file name extensions to MIME types instead, e.g. ".png" ↔ "image/png"?
163//! In this case you do not even need to look at file contents and could use e.g. the [`mime_guess` crate](https://crates.io/crates/mime_guess).
164//!
165//! Maybe you want to be certain that a file is valid for a kown format, e.g. a PNG image?
166//! In this case you should use a parser for that format specifically, e.g. the [`image` crate](https://crates.io/crates/image).
167//!
168//! Maybe you want to know if a file contains other, malicious content?
169//! In this case you should use an anti-virus software, e.g. [ClamAV](https://www.clamav.net/), [Virus Total](https://www.virustotal.com/).
170//!
171//! Maybe you need to support platforms that are tricky with the `libmagic` C library, e.g. wasm32?
172//! In this case you could use alternative Rust implementations, e.g. the [`file_type` crate](https://crates.io/crates/file_type).
173//!
174//! Maybe you want to use the `libmagic` database files without the C library, i.e. pure Rust?
175//! In this case you could use alternative Rust re-implementations, e.g. the [`pure-magic` crate](https://crates.io/crates/pure-magic).
176
177#![cfg_attr(docsrs, feature(doc_cfg))]
178#![cfg_attr(docsrs, doc(auto_cfg(hide(docsrs))))]
179#![deny(unsafe_code)]
180
181use core::ffi::c_int;
182
183mod ffi;
184
185/// Returns the version of the `libmagic` C library as reported by itself.
186///
187/// # Examples
188/// A version of "5.41" is returned as `541`.
189#[doc(alias = "magic_version")]
190pub fn libmagic_version() -> c_int {
191    crate::ffi::version()
192}
193
194/// Functionality for [`Cookie`]
195pub mod cookie {
196    use std::convert::TryFrom;
197    use std::ffi::{c_int, CString};
198    use std::path::Path;
199
200    use magic_sys as libmagic;
201
202    bitflags::bitflags! {
203        /// Configuration bits for [`Cookie`]
204        ///
205        /// A bitflags instance is a combined set of individual flags.
206        /// `cookie::Flags` are configuration bits for `Cookie` instances that specify how the cookie should behave.
207        ///
208        /// `cookie::Flags` influence several functions, e.g. [`Cookie::file()`](Cookie::file)
209        /// but also [`Cookie::load()`](Cookie::load).
210        ///
211        /// Flags are initially set when a new cookie is created with [`Cookie::open()`](Cookie::open)
212        /// and can be overwritten lateron with [`Cookie::set_flags()`](Cookie::set_flags).
213        ///
214        /// Flags of particular interest:
215        /// - [`ERROR`](Flags::ERROR)
216        /// - [`MIME`](Flags::MIME)
217        /// - [`EXTENSION`](Flags::EXTENSION)
218        /// - [`CONTINUE`](Flags::CONTINUE)
219        /// - [`NO_CHECK_BUILTIN`](Flags::NO_CHECK_BUILTIN)
220        ///
221        /// # Examples
222        ///
223        /// ```
224        /// // default flags
225        /// // `: Flags` type annotation is only needed for this example
226        /// // if you pass it to Cookie::open() etc., Rust will figure it out
227        /// let flags: magic::cookie::Flags = Default::default();
228        ///
229        /// // custom flags combination
230        /// let flags = magic::cookie::Flags::COMPRESS | magic::cookie::Flags::DEVICES;
231        /// ```
232        ///
233        /// # Errors
234        ///
235        /// Some flags might not be supported on all platforms, i.e.
236        /// - [`Cookie::open()`](Cookie::open) might return a [`cookie::OpenError`](OpenError)
237        /// - [`Cookie::set_flags()`](Cookie::set_flags) might return a [`cookie::SetFlagsError`](SetFlagsError)
238        ///
239        /// # Misc
240        ///
241        /// NOTE: The flag descriptions are mostly copied from `man libmagic 3`.
242        ///
243        /// `MAGIC_NONE` is the default, meaning "No special handling" and has no constant.
244        /// ```
245        /// let default_flags: magic::cookie::Flags = Default::default();
246        /// assert_eq!(default_flags, magic::cookie::Flags::empty());
247        /// ```
248        #[derive(std::default::Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
249        pub struct Flags: c_int {
250            // MAGIC_NONE is 0/default, see https://docs.rs/bitflags/latest/bitflags/#zero-bit-flags
251
252            // Define unnamed flag for all other bits https://docs.rs/bitflags/latest/bitflags/#externally-defined-flags
253            const _                 = !0;
254
255            /// Print debugging messages to `stderr`
256            ///
257            /// This is equivalent to the `file` CLI option `--debug`.
258            ///
259            /// NOTE: Those messages are printed by `libmagic` itself, no this Rust crate.
260            #[doc(alias = "MAGIC_DEBUG")]
261            #[doc(alias = "--debug")]
262            const DEBUG             = libmagic::MAGIC_DEBUG;
263
264            /// If the file queried is a symlink, follow it
265            ///
266            /// This is equivalent to the `file` CLI option `--dereference`.
267            #[doc(alias = "MAGIC_SYMLINK")]
268            #[doc(alias = "--dereference")]
269            const SYMLINK           = libmagic::MAGIC_SYMLINK;
270
271            /// If the file is compressed, unpack it and look at the contents
272            ///
273            /// This is equivalent to the `file` CLI option `--uncompress`.
274            #[doc(alias = "MAGIC_COMPRESS")]
275            #[doc(alias = "--uncompress")]
276            const COMPRESS          = libmagic::MAGIC_COMPRESS;
277
278            /// If the file is a block or character special device, then open the device and try to look in its contents
279            ///
280            /// This is equivalent to the `file` CLI option `--special-files`.
281            #[doc(alias = "MAGIC_DEVICES")]
282            #[doc(alias = "--special-files")]
283            const DEVICES           = libmagic::MAGIC_DEVICES;
284
285            /// Return a MIME type string, instead of a textual description
286            ///
287            /// See also: [`Flags::MIME`]
288            ///
289            /// This is equivalent to the `file` CLI option `--mime-type`.
290            ///
291            /// NOTE: `libmagic` uses non-standard MIME types for at least some built-in checks,
292            /// e.g. `inode/*` (also see [`Flags::SYMLINK`], [`Flags::DEVICES`]):
293            /// ```shell
294            /// $ file --mime-type /proc/self/exe
295            /// /proc/self/exe: inode/symlink
296            ///
297            /// $ file --mime-type /dev/sda
298            /// /dev/sda: inode/blockdevice
299            /// ```
300            #[doc(alias = "MAGIC_MIME_TYPE")]
301            #[doc(alias = "--mime-type")]
302            const MIME_TYPE         = libmagic::MAGIC_MIME_TYPE;
303
304            /// Return all matches, not just the first
305            ///
306            /// This is equivalent to the `file` CLI option `--keep-going`.
307            #[doc(alias = "MAGIC_CONTINUE")]
308            #[doc(alias = "--keep-going")]
309            const CONTINUE          = libmagic::MAGIC_CONTINUE;
310
311            /// Check the magic database for consistency and print warnings to `stderr`
312            ///
313            /// NOTE: Those warnings are printed by `libmagic` itself, no this Rust crate.
314            #[doc(alias = "MAGIC_CHECK")]
315            const CHECK             = libmagic::MAGIC_CHECK;
316
317            /// On systems that support `utime(2)` or `utimes(2)`, attempt to preserve the access time of files analyzed
318            ///
319            /// This is equivalent to the `file` CLI option `--preserve-date`.
320            #[doc(alias = "MAGIC_PRESERVE_ATIME")]
321            #[doc(alias = "--preserve-date")]
322            const PRESERVE_ATIME    = libmagic::MAGIC_PRESERVE_ATIME;
323
324            /// Don't translate unprintable characters to a `\\ooo` octal representation
325            ///
326            /// This is equivalent to the `file` CLI option `--raw`.
327            #[doc(alias = "MAGIC_RAW")]
328            #[doc(alias = "--raw")]
329            const RAW               = libmagic::MAGIC_RAW;
330
331            /// Treat operating system errors while trying to open files and follow symlinks as real errors, instead of printing them in the magic buffer
332            #[doc(alias = "MAGIC_ERROR")]
333            const ERROR             = libmagic::MAGIC_ERROR;
334
335            /// Return a MIME encoding, instead of a textual description
336            ///
337            /// See also: [`Flags::MIME`]
338            ///
339            /// This is equivalent to the `file` CLI option `--mime-encoding`.
340            ///
341            /// NOTE: `libmagic` uses non-standard MIME `charset` values, e.g. for binary files:
342            /// ```shell
343            /// $ file --mime-encoding /proc/self/exe
344            /// binary
345            /// ```
346            #[doc(alias = "MAGIC_MIME_ENCODING")]
347            #[doc(alias = "--mime-encoding")]
348            const MIME_ENCODING     = libmagic::MAGIC_MIME_ENCODING;
349
350            /// A shorthand for `MIME_TYPE | MIME_ENCODING`
351            ///
352            /// See also: [`Flags::MIME_TYPE`], [`Flags::MIME_ENCODING`]
353            ///
354            /// This is equivalent to the `file` CLI option `--mime`.
355            ///
356            /// NOTE: `libmagic` returns a parseable MIME type with a `charset` field:
357            /// ```shell
358            /// $ file --mime /proc/self/exe
359            /// /proc/self/exe: inode/symlink; charset=binary
360            /// ```
361            #[doc(alias = "MAGIC_MIME")]
362            #[doc(alias = "--mime")]
363            const MIME              = Self::MIME_TYPE.bits()
364                                    | Self::MIME_ENCODING.bits();
365
366            /// Return the Apple creator and type
367            ///
368            /// This is equivalent to the `file` CLI option `--apple`.
369            #[doc(alias = "MAGIC_APPLE")]
370            #[doc(alias = "--apple")]
371            const APPLE             = libmagic::MAGIC_APPLE;
372
373            /// Return a slash-separated list of extensions for this file type
374            ///
375            /// This is equivalent to the `file` CLI option `--extension`.
376            ///
377            /// NOTE: `libmagic` returns a list with one or more extensions without a leading "." (dot):
378            /// ```shell
379            /// $ file --extension example.jpg
380            /// example.jpg: jpeg/jpg/jpe/jfif
381            ///
382            /// $ file --extension /proc/self/exe
383            /// /proc/self/exe: ???
384            /// ```
385            #[doc(alias = "MAGIC_EXTENSION")]
386            #[doc(alias = "--extension")]
387            const EXTENSION         = libmagic::MAGIC_EXTENSION;
388
389            /// Don't report on compression, only report about the uncompressed data
390            ///
391            /// This is equivalent to the `file` CLI option `--uncompress-noreport`.
392            #[doc(alias = "MAGIC_COMPRESS_TRANSP")]
393            #[doc(alias = "--uncompress-noreport")]
394            const COMPRESS_TRANSP   = libmagic::MAGIC_COMPRESS_TRANSP;
395
396            /// A shorthand for `EXTENSION | MIME | APPLE`
397            #[doc(alias = "MAGIC_NODESC")]
398            const NODESC            = Self::EXTENSION.bits()
399                                    | Self::MIME.bits()
400                                    | Self::APPLE.bits();
401
402            /// Don't look inside compressed files
403            ///
404            /// This is equivalent to the `file` CLI option `--exclude compress`.
405            #[doc(alias = "MAGIC_NO_CHECK_COMPRESS")]
406            #[doc(alias = "--exclude compress")]
407            const NO_CHECK_COMPRESS = libmagic::MAGIC_NO_CHECK_COMPRESS;
408
409            /// Don't examine tar files
410            ///
411            /// This is equivalent to the `file` CLI option `--exclude tar`.
412            #[doc(alias = "MAGIC_NO_CHECK_TAR")]
413            #[doc(alias = "--exclude tar")]
414            const NO_CHECK_TAR      = libmagic::MAGIC_NO_CHECK_TAR;
415
416            /// Don't consult magic files
417            ///
418            /// This is equivalent to the `file` CLI option `--exclude soft`.
419            #[doc(alias = "MAGIC_NO_CHECK_SOFT")]
420            #[doc(alias = "--exclude soft")]
421            const NO_CHECK_SOFT     = libmagic::MAGIC_NO_CHECK_SOFT;
422
423            /// Check for EMX application type (only on EMX)
424            ///
425            /// This is equivalent to the `file` CLI option `--exclude apptype`.
426            #[doc(alias = "MAGIC_NO_CHECK_APPTYPE")]
427            #[doc(alias = "--exclude apptype")]
428            const NO_CHECK_APPTYPE  = libmagic::MAGIC_NO_CHECK_APPTYPE;
429
430            /// Don't print ELF details
431            ///
432            /// This is equivalent to the `file` CLI option `--exclude elf`.
433            #[doc(alias = "MAGIC_NO_CHECK_ELF")]
434            #[doc(alias = "--exclude elf")]
435            const NO_CHECK_ELF      = libmagic::MAGIC_NO_CHECK_ELF;
436
437            /// Don't check for various types of text files
438            ///
439            /// This is equivalent to the `file` CLI option `--exclude text`.
440            #[doc(alias = "MAGIC_NO_CHECK_TEXT")]
441            #[doc(alias = "--exclude text")]
442            const NO_CHECK_TEXT     = libmagic::MAGIC_NO_CHECK_TEXT;
443
444            /// Don't get extra information on MS Composite Document Files
445            ///
446            /// This is equivalent to the `file` CLI option `--exclude cdf`.
447            #[doc(alias = "MAGIC_NO_CHECK_CDF")]
448            #[doc(alias = "--exclude cdf")]
449            const NO_CHECK_CDF      = libmagic::MAGIC_NO_CHECK_CDF;
450
451            /// Don't examine CSV files
452            ///
453            /// This is equivalent to the `file` CLI option `--exclude csv`.
454            #[doc(alias = "MAGIC_NO_CHECK_CSV")]
455            #[doc(alias = "--exclude csv")]
456            const NO_CHECK_CSV      = libmagic::MAGIC_NO_CHECK_CSV;
457
458            /// Don't look for known tokens inside ascii files
459            ///
460            /// This is equivalent to the `file` CLI option `--exclude tokens`.
461            #[doc(alias = "MAGIC_NO_CHECK_TOKENS")]
462            #[doc(alias = "--exclude tokens")]
463            const NO_CHECK_TOKENS   = libmagic::MAGIC_NO_CHECK_TOKENS;
464
465            /// Don't check text encodings
466            ///
467            /// This is equivalent to the `file` CLI option `--exclude encoding`.
468            #[doc(alias = "MAGIC_NO_CHECK_ENCODING")]
469            #[doc(alias = "--exclude encoding")]
470            const NO_CHECK_ENCODING = libmagic::MAGIC_NO_CHECK_ENCODING;
471
472            /// Don't examine JSON files
473            ///
474            /// This is equivalent to the `file` CLI option `--exclude json`.
475            #[doc(alias = "MAGIC_NO_CHECK_JSON")]
476            #[doc(alias = "--exclude json")]
477            const NO_CHECK_JSON     = libmagic::MAGIC_NO_CHECK_JSON;
478
479            #[cfg(feature = "libmagic+v5-44")]
480            #[cfg_attr(docsrs, doc(cfg(feature = "libmagic+v5-44")))]
481            /// Don't allow decompressors that use fork
482            ///
483            /// The enabled-by-default sandboxing of the `file` CLI implicitly activates this flag if available.
484            #[doc(alias = "MAGIC_NO_COMPRESS_FORK")]
485            const NO_COMPRESS_FORK  = libmagic::MAGIC_NO_COMPRESS_FORK;
486
487            #[cfg(feature = "libmagic+v5-45")]
488            #[cfg_attr(docsrs, doc(cfg(feature = "libmagic+v5-45")))]
489            ///  Don't examine SIMH tape files
490            ///
491            /// This is equivalent to the `file` CLI option `--exclude simh`.
492            #[doc(alias = "MAGIC_NO_CHECK_SIMH")]
493            const NO_CHECK_SIMH     = libmagic::MAGIC_NO_CHECK_SIMH;
494
495            /// No built-in tests; only consult the magic file
496            #[doc(alias = "MAGIC_NO_CHECK_BUILTIN")]
497            #[cfg(not(feature = "libmagic+v5-45"))]
498            #[cfg_attr(docsrs, doc(auto_cfg = false))]
499            const NO_CHECK_BUILTIN  = Self::NO_CHECK_COMPRESS.bits()
500                                    | Self::NO_CHECK_TAR.bits()
501                                    | Self::NO_CHECK_APPTYPE.bits()
502                                    | Self::NO_CHECK_ELF.bits()
503                                    | Self::NO_CHECK_TEXT.bits()
504                                    | Self::NO_CHECK_CSV.bits()
505                                    | Self::NO_CHECK_CDF.bits()
506                                    | Self::NO_CHECK_TOKENS.bits()
507                                    | Self::NO_CHECK_ENCODING.bits()
508                                    | Self::NO_CHECK_JSON.bits();
509            /// No built-in tests; only consult the magic file
510            #[cfg(feature = "libmagic+v5-45")]
511            #[cfg_attr(docsrs, doc(auto_cfg = false))]
512            const NO_CHECK_BUILTIN  = Self::NO_CHECK_COMPRESS.bits()
513                                    | Self::NO_CHECK_TAR.bits()
514                                    | Self::NO_CHECK_APPTYPE.bits()
515                                    | Self::NO_CHECK_ELF.bits()
516                                    | Self::NO_CHECK_TEXT.bits()
517                                    | Self::NO_CHECK_CSV.bits()
518                                    | Self::NO_CHECK_CDF.bits()
519                                    | Self::NO_CHECK_TOKENS.bits()
520                                    | Self::NO_CHECK_ENCODING.bits()
521                                    | Self::NO_CHECK_JSON.bits()
522                                    | Self::NO_CHECK_SIMH.bits();
523        }
524    }
525
526    impl std::fmt::Display for Flags {
527        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
528            bitflags::parser::to_writer(self, f)
529        }
530    }
531
532    /// Invalid [`DatabasePaths`]
533    ///
534    /// This is returned from [`DatabasePaths::new()`](DatabasePaths::new)
535    #[derive(Debug)]
536    pub struct InvalidDatabasePathError {}
537
538    impl std::error::Error for InvalidDatabasePathError {}
539
540    impl std::fmt::Display for InvalidDatabasePathError {
541        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
542            write!(f, "invalid database files path")
543        }
544    }
545
546    /// Magic database file paths
547    ///
548    /// `libmagic` requires database file paths for certain operations on a [`Cookie`] that must:
549    /// - be a valid C string
550    /// - not contain ":" (colon), since that is used to separate multiple file paths (on all platforms)
551    ///
552    /// Those operations are [`Cookie::load()`](Cookie::load), [`Cookie::compile()`](Cookie::compile), [`Cookie::check()`](Cookie::check), [`Cookie::list()`](Cookie::list).\
553    /// [`Cookie::file()`](Cookie::file) does not take database file paths but the single file to inspect instead.
554    ///
555    /// The default unnamed database can be constructed with [`Default::default()`](DatabasePaths::default).
556    /// Explicit paths can be constructed manually with [`new()`](DatabasePaths::new) or by fallible conversion from an array, slice or Vec
557    /// containing something convertible as [`std::path::Path`], or a single something.
558    ///
559    /// Note that this only ensures the paths themselves are valid.
560    /// Operating on those database file paths can still fail,
561    /// for example if they refer to files that do not exist, can not be opened or do not have the required format.
562    ///
563    /// # Examples
564    ///
565    /// ```
566    /// # use std::convert::TryInto;
567    /// # use magic::cookie::DatabasePaths;
568    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
569    /// // `: DatabasePaths` type annotation is only needed for these examples
570    /// // if you pass it to Cookie::load() etc., Rust will figure it out
571    ///
572    /// // construct default unnamed database paths
573    /// let database: DatabasePaths = Default::default();
574    ///
575    /// // construct from single path
576    /// let database: DatabasePaths = "first-directory/first-database".try_into()?;
577    /// let database: DatabasePaths =
578    ///     std::path::Path::new("second-directory/second-database").try_into()?;
579    ///
580    /// // construct from multiple paths in array
581    /// let array: [&'static str; 2] = [
582    ///     "first-directory/first-database",
583    ///     "second-directory/second-database",
584    /// ];
585    /// let database: DatabasePaths = array.try_into()?;
586    ///
587    /// // construct from multiple paths in slice
588    /// let database: DatabasePaths = [
589    ///     "first-directory/first-database".as_ref(),
590    ///     std::path::Path::new("second-directory/second-database"),
591    /// ]
592    /// .try_into()?;
593    ///
594    /// // construct from multiple paths in Vec
595    /// let database: DatabasePaths = vec![
596    ///     std::ffi::OsStr::new("first-directory/first-database"),
597    ///     "second-directory/second-database".as_ref(),
598    /// ]
599    /// .try_into()?;
600    /// # Ok(())
601    /// # }
602    /// ```
603    ///
604    /// ```
605    /// # use magic::cookie::DatabasePaths;
606    /// // can also be cloned
607    /// let database: DatabasePaths = Default::default();
608    /// let another_database = database.clone();
609    /// ```
610    #[derive(Clone)]
611    pub struct DatabasePaths {
612        filenames: Option<CString>,
613    }
614
615    impl std::fmt::Debug for DatabasePaths {
616        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
617            let mut list = f.debug_list();
618
619            if let Some(cstr) = &self.filenames {
620                cstr.as_bytes()
621                    .split(|&b| b == DATABASE_FILENAME_SEPARATOR_U8)
622                    .for_each(|filename| {
623                        if let Ok(s) = std::str::from_utf8(filename) {
624                            list.entry(&s as _);
625                        } else {
626                            list.entry(&"<non utf8 string>" as _);
627                        }
628                    });
629            }
630
631            list.finish()
632        }
633    }
634
635    const DATABASE_FILENAME_SEPARATOR: &str = ":";
636    const DATABASE_FILENAME_SEPARATOR_U8: u8 = b':';
637
638    impl DatabasePaths {
639        /// Create a new database paths instance
640        ///
641        /// Using one of the `TryFrom` implementations is recommended instead, see [`DatabasePaths`] examples.
642        ///
643        /// Empty `paths` returns [`Default::default()`](DatabasePaths::default).
644        ///
645        /// # Errors
646        ///
647        /// If the `paths` contain a ":" (colon), a [`cookie::InvalidDatabasePathError`](InvalidDatabasePathError) will be returned.
648        ///
649        pub fn new<I, P>(paths: I) -> Result<Self, InvalidDatabasePathError>
650        where
651            I: IntoIterator<Item = P>,
652            P: AsRef<Path>,
653        {
654            // this is not the most efficient nor correct for Windows, but consistent with previous behaviour
655
656            let filename = paths
657                .into_iter()
658                .map(|f| f.as_ref().to_string_lossy().into_owned())
659                .collect::<Vec<String>>()
660                .join(DATABASE_FILENAME_SEPARATOR);
661
662            Ok(Self {
663                filenames: match filename.is_empty() {
664                    true => None,
665                    _ => Some(CString::new(filename).map_err(|_| InvalidDatabasePathError {})?),
666                },
667            })
668        }
669    }
670
671    impl Default for DatabasePaths {
672        /// Returns the path for the default unnamed database/s
673        ///
674        /// Note that the default database/s can be overwritten by setting the "MAGIC" environment variable
675        /// to a colon-separated text of database file paths:
676        /// ```shell
677        /// $ export MAGIC='data/tests/db-python:data/tests/db-images-png-precompiled.mgc'
678        /// $ # file-ish uses `DatabasePaths::default()`
679        /// $ cargo run --example file-ish -- data/tests/rust-logo-128x128-blk.png
680        /// ```
681        /// This is a feature of `libmagic` itself, not of this Rust crate.
682        ///
683        /// Note that the `file` CLI (which uses `libmagic`) prints the location of its default database with:
684        /// ```shell
685        /// $ file --version
686        /// file-5.38
687        /// magic file from /etc/magic:/usr/share/misc/magic
688        ///
689        /// $ export MAGIC='data/tests/db-python:data/tests/db-images-png-precompiled.mgc'
690        /// $ file --version
691        /// file-5.39
692        /// magic file from data/tests/db-python:data/tests/db-images-png-precompiled.mgc
693        /// ```
694        fn default() -> Self {
695            Self { filenames: None }
696        }
697    }
698
699    impl<P: AsRef<std::path::Path>, const N: usize> TryFrom<[P; N]> for DatabasePaths {
700        type Error = InvalidDatabasePathError;
701
702        /// Invokes [`DatabasePaths::new()`](DatabasePaths::new)
703        fn try_from(value: [P; N]) -> Result<Self, <Self as TryFrom<[P; N]>>::Error> {
704            Self::new(value)
705        }
706    }
707
708    impl<P: AsRef<std::path::Path>> TryFrom<Vec<P>> for DatabasePaths {
709        type Error = InvalidDatabasePathError;
710
711        /// Invokes [`DatabasePaths::new()`](DatabasePaths::new)
712        fn try_from(value: Vec<P>) -> Result<Self, <Self as TryFrom<Vec<P>>>::Error> {
713            Self::new(value)
714        }
715    }
716
717    impl<P: AsRef<std::path::Path>> TryFrom<&'_ [P]> for DatabasePaths {
718        type Error = InvalidDatabasePathError;
719
720        /// Invokes [`DatabasePaths::new()`](DatabasePaths::new)
721        fn try_from(value: &[P]) -> Result<Self, <Self as TryFrom<&[P]>>::Error> {
722            Self::new(value)
723        }
724    }
725
726    macro_rules! databasepaths_try_from_impl {
727        ($t:ty) => {
728            impl TryFrom<$t> for DatabasePaths {
729                type Error = InvalidDatabasePathError;
730
731                /// Invokes [`DatabasePaths::new()`](DatabasePaths::new)
732                fn try_from(value: $t) -> Result<Self, <Self as TryFrom<$t>>::Error> {
733                    DatabasePaths::new(std::iter::once(value))
734                }
735            }
736        };
737    }
738
739    // missing for now are:
740    // - Cow<'_, OsStr>
741    // - std::path::Component<'_>
742    // - std::path::Components<'_>
743    // - std::path::Iter<'_>
744    databasepaths_try_from_impl!(&str);
745    databasepaths_try_from_impl!(&std::ffi::OsStr);
746    databasepaths_try_from_impl!(std::ffi::OsString);
747    databasepaths_try_from_impl!(&std::path::Path);
748    databasepaths_try_from_impl!(std::path::PathBuf);
749    databasepaths_try_from_impl!(String);
750
751    /// Error within several [`Cookie`] functions
752    ///
753    /// Most functions on a [`Cookie`] can return an error from `libmagic`,
754    /// which unfortunately is not very structured.
755    #[derive(Debug)]
756    pub struct Error {
757        function: &'static str,
758        //#[backtrace]
759        source: crate::ffi::CookieError,
760    }
761
762    impl std::error::Error for Error {
763        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
764            Some(&self.source)
765        }
766    }
767
768    impl std::fmt::Display for Error {
769        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
770            let Self { function, .. } = self;
771            write!(f, "magic cookie error in `libmagic` function {0}", function,)
772        }
773    }
774
775    /// Typestate marker of opened [`Cookie`]
776    ///
777    /// In this state, a cookie has only been [opened](Cookie::open) but databases are not [loaded](Cookie::load) yet.
778    #[derive(Debug)]
779    pub enum Open {}
780
781    /// Typestate marker of loaded [`Cookie`]
782    ///
783    /// In this state, a cookie has both been [opened](Cookie::open) and databases are [loaded](Cookie::load).
784    #[derive(Debug)]
785    pub enum Load {}
786
787    mod private {
788        pub trait Sealed {}
789
790        impl Sealed for super::Open {}
791        impl Sealed for super::Load {}
792    }
793
794    /// Typestate marker for [`Cookie`]
795    ///
796    /// A cookie can either be in the [`Open`] or [`Load`] state
797    pub trait State: private::Sealed {}
798
799    impl State for Open {}
800    impl State for Load {}
801
802    /// Combined configuration of [`Flags`], parameters and databases
803    ///
804    /// A "cookie" is `libmagic` lingo for a combined configuration of
805    /// - [`cookie::Flags`](crate::cookie::Flags)
806    /// - parameters (not implemented yet)
807    /// - loaded datbases, e.g. [`cookie::DatabasePaths`](crate::cookie::DatabasePaths)
808    ///
809    /// A cookie advances through 2 states: opened, then loaded.
810    /// ```
811    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
812    /// // create new cookie in initial opened state with given flags
813    /// let cookie = magic::Cookie::open(magic::cookie::Flags::default())?;
814    ///
815    /// // advance cookie into loaded state
816    /// let cookie = cookie.load(&magic::cookie::DatabasePaths::default())?;
817    /// # Ok(())
818    /// # }
819    /// ```
820    ///
821    /// In either state, you can use operations that do not require
822    /// already loaded magic databases:
823    /// - [`Cookie::load()`](Cookie::load), [`Cookie::load_buffers()`](Cookie::load_buffers) to load databases and transition into the loaded state
824    /// - [`Cookie::set_flags()`](Cookie::set_flags) to overwrite the initial flags given in [`Cookie::open()`](Cookie::open)
825    /// - [`Cookie::compile()`](Cookie::compile), [`Cookie::check()`](Cookie::check), [`Cookie::list()`](Cookie::list) to operate on magic database files
826    ///
827    /// Once in the loaded state, you can perform magic "queries":
828    /// - [`Cookie::file()`](Cookie::file), [`Cookie::buffer()`](Cookie::buffer)
829    #[derive(Debug)]
830    #[doc(alias = "magic_t")]
831    #[doc(alias = "magic_set")]
832    pub struct Cookie<S: State> {
833        cookie: crate::ffi::Cookie,
834        marker: std::marker::PhantomData<S>,
835    }
836
837    /// Error within [`Cookie::load()`](Cookie::load) or [`Cookie::load_buffers()`](Cookie::load_buffers)
838    ///
839    /// This is like [`cookie:Error`](Error) but also has the cookie in its original state.
840    ///
841    /// # Examples
842    ///
843    /// ```
844    /// # use std::convert::TryInto;
845    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
846    /// let cookie = magic::Cookie::open(Default::default())?;
847    /// let database = "data/tests/db-images-png".try_into()?;
848    /// // try to load an existing database, consuming and returning early
849    /// let cookie = cookie.load(&database)?;
850    ///
851    /// let database = "doesntexist.mgc".try_into()?;
852    /// // load a database that does not exist
853    /// let cookie = match cookie.load(&database) {
854    ///     Err(err) => {
855    ///         println!("whoopsie: {:?}", err);
856    ///         // recover the loaded cookie without dropping it
857    ///         err.cookie()
858    ///     },
859    ///     Ok(cookie) => cookie,
860    /// };
861    ///
862    /// let database = "data/tests/db-python".try_into()?;
863    /// // try to load another existing database
864    /// let cookie = cookie.load(&database)?;
865    /// # Ok(())
866    /// # }
867    /// ```
868    #[derive(Debug)]
869    pub struct LoadError<S: State> {
870        function: &'static str,
871        //#[backtrace]
872        source: crate::ffi::CookieError,
873        cookie: Cookie<S>,
874    }
875
876    impl<S: State> std::error::Error for LoadError<S>
877    where
878        Self: std::fmt::Debug,
879    {
880        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
881            Some(&self.source)
882        }
883    }
884
885    impl<S: State> std::fmt::Display for LoadError<S> {
886        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
887            let Self { function, .. } = self;
888            write!(f, "magic cookie error in `libmagic` function {0}", function,)
889        }
890    }
891
892    impl<S: State> LoadError<S> {
893        /// Returns the cookie in its original state
894        pub fn cookie(self) -> Cookie<S> {
895            self.cookie
896        }
897    }
898
899    impl<S: State> Drop for Cookie<S> {
900        /// Closes the loaded magic database files and deallocates any resources used
901        #[doc(alias = "magic_close")]
902        fn drop(&mut self) {
903            crate::ffi::close(&mut self.cookie);
904        }
905    }
906
907    /// Operations that are valid in the [`Open`] state
908    ///
909    /// A new cookie created with [`Cookie::open`](Cookie::open) does not have any databases [loaded](Cookie::load).
910    impl Cookie<Open> {
911        /// Creates a new configuration cookie, `flags` specify how other operations on this cookie should behave
912        ///
913        /// This does not [`load()`](Cookie::load) any databases yet.
914        ///
915        /// The `flags` can be changed lateron with [`set_flags()`](Cookie::set_flags).
916        ///
917        /// # Examples
918        ///
919        /// ```
920        /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
921        /// // open a new cookie with default flags
922        /// let cookie = magic::Cookie::open(Default::default())?;
923        ///
924        /// // open a new cookie with custom flags
925        /// let flags = magic::cookie::Flags::COMPRESS | magic::cookie::Flags::DEVICES;
926        /// let cookie = magic::Cookie::open(flags)?;
927        /// # Ok(())
928        /// # }
929        /// ```
930        ///
931        /// # Errors
932        ///
933        /// If there was an `libmagic` internal error allocating a new cookie, a [`cookie::OpenError`](OpenError) will be returned.
934        ///
935        /// If the given `flags` are unsupported on the current platform, a [`cookie::OpenError`](OpenError) will be returned.
936        #[doc(alias = "magic_open")]
937        pub fn open(flags: Flags) -> Result<Cookie<Open>, OpenError> {
938            match crate::ffi::open(flags.bits()) {
939                Err(err) => Err(OpenError {
940                    flags,
941                    kind: match err.errno().kind() {
942                        std::io::ErrorKind::InvalidInput => OpenErrorKind::UnsupportedFlags,
943                        _ => OpenErrorKind::Errno,
944                    },
945                    source: err,
946                }),
947                Ok(cookie) => {
948                    let cookie = Cookie {
949                        cookie,
950                        marker: std::marker::PhantomData,
951                    };
952                    Ok(cookie)
953                }
954            }
955        }
956    }
957
958    /// Operations that are valid in the [`Load`] state
959    ///
960    /// An opened cookie with [loaded](Cookie::load) databases can inspect [files](Cookie::file) and [buffers](Cookie::buffer).
961    impl Cookie<Load> {
962        /// Returns a textual description of the contents of the file `filename`
963        ///
964        /// Requires to [`load()`](Cookie::load) databases before calling.
965        ///
966        /// # Examples
967        ///
968        /// ```
969        /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
970        /// // open a new cookie with default flags and database
971        /// let cookie = magic::Cookie::open(Default::default())?.load(&Default::default())?;
972        ///
973        /// let file_description = cookie.file("data/tests/rust-logo-128x128-blk.png");
974        /// # Ok(())
975        /// # }
976        /// ```
977        ///
978        /// # Errors
979        ///
980        /// If there was an `libmagic` internal error, a [`cookie::Error`](Error) will be returned.
981        ///
982        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
983        #[doc(alias = "magic_file")]
984        pub fn file<P: AsRef<Path>>(&self, filename: P) -> Result<String, Error> {
985            let c_string = CString::new(filename.as_ref().to_string_lossy().into_owned()).unwrap();
986            match crate::ffi::file(&self.cookie, c_string.as_c_str()) {
987                Ok(res) => Ok(res.to_string_lossy().to_string()),
988                Err(err) => Err(Error {
989                    function: "magic_file",
990                    source: err,
991                }),
992            }
993        }
994
995        /// Returns a textual description of the contents of the `buffer`
996        ///
997        /// Requires to [`load()`](Cookie::load) databases before calling.
998        ///
999        /// # Examples
1000        ///
1001        /// ```
1002        /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1003        /// // open a new cookie with default flags and database
1004        /// let cookie = magic::Cookie::open(Default::default())?.load(&Default::default())?;
1005        ///
1006        /// let buffer = b"%PDF-\xE2\x80\xA6";
1007        /// let buffer_description = cookie.buffer(buffer);
1008        /// # Ok(())
1009        /// # }
1010        /// ```
1011        ///
1012        /// # Errors
1013        ///
1014        /// If there was an `libmagic` internal error, a [`cookie::Error`](Error) will be returned.
1015        ///
1016        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
1017        #[doc(alias = "magic_buffer")]
1018        pub fn buffer(&self, buffer: &[u8]) -> Result<String, Error> {
1019            match crate::ffi::buffer(&self.cookie, buffer) {
1020                Ok(res) => Ok(res.to_string_lossy().to_string()),
1021                Err(err) => Err(Error {
1022                    function: "magic_buffer",
1023                    source: err,
1024                }),
1025            }
1026        }
1027    }
1028
1029    /// Operations that are valid in any state
1030    impl<S: State> Cookie<S> {
1031        /// Loads the given database `filenames` for further queries
1032        ///
1033        /// Adds ".mgc" to the database filenames as appropriate.
1034        ///
1035        /// Calling `load()` or [`load_buffers()`](Cookie::load_buffers) replaces the previously loaded database/s.
1036        ///
1037        /// This is equivalent to the using the `file` CLI:
1038        /// ```shell
1039        /// $ file --magic-file 'data/tests/db-images-png:data/tests/db-python' --version
1040        /// file-5.39
1041        /// magic file from data/tests/db-images-png:data/tests/db-python
1042        /// ```
1043        ///
1044        /// # Examples
1045        /// ```rust
1046        /// # use std::convert::TryInto;
1047        /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1048        /// // open a new cookie with default flags
1049        /// let cookie = magic::Cookie::open(Default::default())?;
1050        ///
1051        /// // load the default unnamed database
1052        /// let database = Default::default();
1053        /// let cookie = cookie.load(&database)?;
1054        ///
1055        /// // load databases from files
1056        /// let databases = ["data/tests/db-images-png", "data/tests/db-python"].try_into()?;
1057        /// let cookie = cookie.load(&databases)?;
1058        ///
1059        /// // load precompiled database from file
1060        /// let database = "data/tests/db-images-png-precompiled.mgc".try_into()?;
1061        /// let cookie = cookie.load(&database)?;
1062        /// # Ok(())
1063        /// # }
1064        /// ```
1065        ///
1066        /// # Errors
1067        ///
1068        /// If there was an `libmagic` internal error, a [`cookie::LoadError`](LoadError) will be returned,
1069        /// which contains the cookie in its original state.
1070        ///
1071        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
1072        #[doc(alias = "magic_load")]
1073        #[doc(alias = "--magic-file")]
1074        pub fn load(self, filenames: &DatabasePaths) -> Result<Cookie<Load>, LoadError<S>> {
1075            match crate::ffi::load(&self.cookie, filenames.filenames.as_deref()) {
1076                Err(err) => Err(LoadError {
1077                    function: "magic_load",
1078                    source: err,
1079                    cookie: self,
1080                }),
1081                Ok(_) => {
1082                    let mut cookie = std::mem::ManuallyDrop::new(self);
1083
1084                    let cookie = Cookie {
1085                        cookie: crate::ffi::Cookie::new(&mut cookie.cookie),
1086                        marker: std::marker::PhantomData,
1087                    };
1088                    Ok(cookie)
1089                }
1090            }
1091        }
1092
1093        /// Loads the given compiled databases `buffers` for further queries
1094        ///
1095        /// Databases need to be compiled with a compatible `libmagic` version.
1096        ///
1097        /// This function can be used in environments where `libmagic` does
1098        /// not have direct access to the filesystem, but can access the magic
1099        /// database via shared memory or other IPC means.
1100        ///
1101        /// Calling `load_buffers()` or [`load()`](Cookie::load) replaces the previously loaded database/s.
1102        ///
1103        /// # Errors
1104        ///
1105        /// If there was an `libmagic` internal error, a [`cookie::LoadError`](LoadError) will be returned,
1106        /// which contains the cookie in its original state.
1107        ///
1108        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
1109        #[doc(alias = "magic_load_buffers")]
1110        pub fn load_buffers(self, buffers: &[&[u8]]) -> Result<Cookie<Load>, LoadError<S>> {
1111            match crate::ffi::load_buffers(&self.cookie, buffers) {
1112                Err(err) => Err(LoadError {
1113                    function: "magic_load_buffers",
1114                    source: err,
1115                    cookie: self,
1116                }),
1117                Ok(_) => {
1118                    let mut cookie = std::mem::ManuallyDrop::new(self);
1119
1120                    let cookie = Cookie {
1121                        cookie: crate::ffi::Cookie::new(&mut cookie.cookie),
1122                        marker: std::marker::PhantomData,
1123                    };
1124                    Ok(cookie)
1125                }
1126            }
1127        }
1128
1129        /// Sets the `flags` to use for this configuration
1130        ///
1131        /// Overwrites any previously set flags, e.g. those from [`load()`](Cookie::load).
1132        ///
1133        /// # Examples
1134        /// ```rust
1135        /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1136        /// // open a new cookie with initial default flags
1137        /// let cookie = magic::Cookie::open(Default::default())?;
1138        ///
1139        /// // overwrite the initial flags
1140        /// let flags = magic::cookie::Flags::COMPRESS | magic::cookie::Flags::DEVICES;
1141        /// cookie.set_flags(flags)?;
1142        /// # Ok(())
1143        /// # }
1144        /// ```
1145        ///
1146        /// # Errors
1147        ///
1148        /// If the given `flags` are unsupported on the current platform, an [`cookie::SetFlagsError`](SetFlagsError) will be returned.
1149        #[doc(alias = "magic_setflags")]
1150        pub fn set_flags(&self, flags: Flags) -> Result<(), SetFlagsError> {
1151            let ret = crate::ffi::setflags(&self.cookie, flags.bits());
1152            match ret {
1153                // according to `libmagic` man page this is the only flag that could be unsupported
1154                Err(err) => Err(SetFlagsError {
1155                    flags: Flags::PRESERVE_ATIME,
1156                    source: err,
1157                }),
1158                Ok(_) => Ok(()),
1159            }
1160        }
1161
1162        // TODO: check, compile, list and load mostly do the same, refactor!
1163
1164        /// Compiles the given database files `filenames` for faster access
1165        ///
1166        /// The compiled files created are named from the `basename` of each file argument with ".mgc" appended to it.
1167        ///
1168        /// This is equivalent to the following `file` CLI command:
1169        /// ```shell
1170        /// $ file --compile --magic-file data/tests/db-images-png:data/tests/db-python
1171        /// ```
1172        ///
1173        /// # Errors
1174        ///
1175        /// If there was an `libmagic` internal error, a [`cookie::Error`](Error) will be returned.
1176        ///
1177        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
1178        #[doc(alias = "magic_compile")]
1179        #[doc(alias = "--compile")]
1180        pub fn compile(&self, filenames: &DatabasePaths) -> Result<(), Error> {
1181            match crate::ffi::compile(&self.cookie, filenames.filenames.as_deref()) {
1182                Err(err) => Err(Error {
1183                    function: "magic_compile",
1184                    source: err,
1185                }),
1186                Ok(_) => Ok(()),
1187            }
1188        }
1189
1190        /// Checks the validity of entries in the database files `filenames`
1191        ///
1192        /// # Errors
1193        ///
1194        /// If there was an `libmagic` internal error, a [`cookie::Error`](Error) will be returned.
1195        ///
1196        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
1197        #[doc(alias = "magic_check")]
1198        pub fn check(&self, filenames: &DatabasePaths) -> Result<(), Error> {
1199            match crate::ffi::check(&self.cookie, filenames.filenames.as_deref()) {
1200                Err(err) => Err(Error {
1201                    function: "magic_check",
1202                    source: err,
1203                }),
1204                Ok(_) => Ok(()),
1205            }
1206        }
1207
1208        /// Dumps all magic entries in the given database files `filenames` in a human readable format
1209        ///
1210        /// This is equivalent to the following `file` CLI command:
1211        /// ```shell
1212        /// $ file --checking-printout --magic-file data/tests/db-images-png:data/tests/db-python
1213        /// ```
1214        ///
1215        /// # Errors
1216        ///
1217        /// If there was an `libmagic` internal error, a [`cookie::Error`](Error) will be returned.
1218        ///
1219        /// If `libmagic` violates its API contract, e.g. by not setting the last error, a [`cookie::Error`](Error) will be returned.
1220        #[doc(alias = "magic_list")]
1221        #[doc(alias = "--checking-printout")]
1222        pub fn list(&self, filenames: &DatabasePaths) -> Result<(), Error> {
1223            match crate::ffi::list(&self.cookie, filenames.filenames.as_deref()) {
1224                Err(err) => Err(Error {
1225                    function: "magic_list",
1226                    source: err,
1227                }),
1228                Ok(_) => Ok(()),
1229            }
1230        }
1231    }
1232
1233    /// Error within [`Cookie::open()`](Cookie::open)
1234    ///
1235    /// Note that a similar [`cookie::SetFlagsError`](SetFlagsError) can also occur
1236    #[derive(Debug)]
1237    pub struct OpenError {
1238        flags: Flags,
1239        kind: OpenErrorKind,
1240        //#[backtrace]
1241        source: crate::ffi::OpenError,
1242    }
1243
1244    impl std::error::Error for OpenError {
1245        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1246            Some(&self.source)
1247        }
1248    }
1249
1250    impl std::fmt::Display for OpenError {
1251        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1252            let Self { flags, kind, .. } = self;
1253            write!(
1254                f,
1255                "could not open magic cookie: {0}",
1256                match kind {
1257                    OpenErrorKind::UnsupportedFlags => format!("unsupported flags {0}", flags),
1258                    OpenErrorKind::Errno => "other error".to_string(),
1259                }
1260            )
1261        }
1262    }
1263
1264    /// Kind of [`OpenError`]
1265    #[derive(Debug)]
1266    enum OpenErrorKind {
1267        /// Unsupported flags given
1268        UnsupportedFlags,
1269        /// Other kind
1270        Errno,
1271    }
1272
1273    /// Error within [`Cookie::set_flags()`](Cookie::set_flags)
1274    ///
1275    /// Note that a similar [`cookie::OpenError`](OpenError) can also occur
1276    #[derive(Debug)]
1277    pub struct SetFlagsError {
1278        flags: Flags,
1279        //#[backtrace]
1280        source: crate::ffi::SetFlagsError,
1281    }
1282
1283    impl std::error::Error for SetFlagsError {
1284        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1285            Some(&self.source)
1286        }
1287    }
1288
1289    impl std::fmt::Display for SetFlagsError {
1290        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1291            let Self { flags, .. } = self;
1292            write!(f, "could not set magic cookie flags {0}", flags)
1293        }
1294    }
1295} // mod cookie
1296
1297pub use crate::cookie::Cookie;
1298
1299#[cfg(test)]
1300mod tests {
1301    use super::cookie::Flags;
1302    use super::cookie::{
1303        DatabasePaths, Error, InvalidDatabasePathError, LoadError, OpenError, SetFlagsError,
1304    };
1305    use super::cookie::{Load, Open};
1306    use super::Cookie;
1307    use std::convert::TryInto;
1308
1309    fn assert_impl_debug<T: std::fmt::Debug>() {}
1310    fn assert_impl_display<T: std::fmt::Display>() {}
1311    fn assert_impl_error<T: std::error::Error>() {}
1312
1313    // Using relative paths to test files should be fine, since cargo doc
1314    // https://doc.rust-lang.org/cargo/reference/build-scripts.html#inputs-to-the-build-script
1315    // states that cwd == CARGO_MANIFEST_DIR
1316
1317    #[test]
1318    fn file() {
1319        let cookie = Cookie::open(Flags::ERROR).unwrap();
1320        let databases = &["data/tests/db-images-png"].try_into().unwrap();
1321        let cookie = cookie.load(databases).unwrap();
1322
1323        let path = "data/tests/rust-logo-128x128-blk.png";
1324
1325        assert_eq!(
1326            cookie.file(path).ok().unwrap(),
1327            "PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced"
1328        );
1329
1330        cookie.set_flags(Flags::MIME_TYPE).unwrap();
1331        assert_eq!(cookie.file(path).ok().unwrap(), "image/png");
1332
1333        cookie
1334            .set_flags(Flags::MIME_TYPE | Flags::MIME_ENCODING)
1335            .unwrap();
1336        assert_eq!(cookie.file(path).ok().unwrap(), "image/png; charset=binary");
1337    }
1338
1339    #[test]
1340    fn buffer() {
1341        let cookie = Cookie::open(Flags::ERROR).unwrap();
1342        let databases = &["data/tests/db-python"].try_into().unwrap();
1343        let cookie = cookie.load(databases).unwrap();
1344
1345        let s = b"#!/usr/bin/env python\nprint('Hello, world!')";
1346        assert_eq!(
1347            cookie.buffer(s).ok().unwrap(),
1348            "Python script, ASCII text executable"
1349        );
1350
1351        cookie.set_flags(Flags::MIME_TYPE).unwrap();
1352        assert_eq!(cookie.buffer(s).ok().unwrap(), "text/x-python");
1353    }
1354
1355    #[test]
1356    fn file_error() {
1357        let cookie = Cookie::open(Flags::ERROR).unwrap();
1358        let cookie = cookie.load(&Default::default()).unwrap();
1359
1360        let ret = cookie.file("non-existent_file.txt");
1361        assert!(ret.is_err());
1362    }
1363
1364    #[test]
1365    fn load_default() {
1366        let cookie = Cookie::open(Flags::ERROR).unwrap();
1367        assert!(cookie.load(&Default::default()).is_ok());
1368    }
1369
1370    #[test]
1371    fn load_one() {
1372        let cookie = Cookie::open(Flags::ERROR).unwrap();
1373        let databases = &["data/tests/db-images-png"].try_into().unwrap();
1374        assert!(cookie.load(databases).is_ok());
1375    }
1376
1377    #[test]
1378    fn load_multiple() {
1379        let cookie = Cookie::open(Flags::ERROR).unwrap();
1380        let databases = &["data/tests/db-images-png", "data/tests/db-python"]
1381            .try_into()
1382            .unwrap();
1383        assert!(cookie.load(databases).is_ok());
1384    }
1385
1386    #[test]
1387    fn cookie_impl_debug() {
1388        assert_impl_debug::<Cookie<Open>>();
1389        assert_impl_debug::<Cookie<Load>>();
1390    }
1391
1392    #[test]
1393    #[ignore] // FIXME: the binary .mgc file depends on libmagic (internal format) version
1394    fn load_buffers_file() {
1395        let cookie = Cookie::open(Flags::ERROR).unwrap();
1396        // file --compile --magic-file data/tests/db-images-png
1397        let magic_database = std::fs::read("data/tests/db-images-png-precompiled.mgc").unwrap();
1398        let buffers = vec![magic_database.as_slice()];
1399        let cookie = cookie.load_buffers(&buffers).unwrap();
1400
1401        let path = "data/tests/rust-logo-128x128-blk.png";
1402        assert_eq!(
1403            cookie.file(path).ok().unwrap(),
1404            "PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced"
1405        );
1406    }
1407
1408    #[test]
1409    fn libmagic_version() {
1410        let version = super::libmagic_version();
1411
1412        assert!(version > 500);
1413    }
1414
1415    #[test]
1416    fn error_impls() {
1417        assert_impl_debug::<Error>();
1418        assert_impl_display::<Error>();
1419        assert_impl_error::<Error>();
1420    }
1421
1422    #[test]
1423    fn databasepath_impls() {
1424        assert_impl_debug::<DatabasePaths>();
1425    }
1426
1427    #[test]
1428    fn invaliddatabasepatherror_impls() {
1429        assert_impl_debug::<InvalidDatabasePathError>();
1430        assert_impl_display::<InvalidDatabasePathError>();
1431        assert_impl_error::<InvalidDatabasePathError>();
1432    }
1433
1434    #[test]
1435    fn loaderror_impls() {
1436        assert_impl_debug::<LoadError<Open>>();
1437        assert_impl_debug::<LoadError<Load>>();
1438        assert_impl_display::<LoadError<Open>>();
1439        assert_impl_display::<LoadError<Load>>();
1440        assert_impl_error::<LoadError<Open>>();
1441        assert_impl_error::<LoadError<Load>>();
1442    }
1443
1444    #[test]
1445    fn openerror_impls() {
1446        assert_impl_debug::<OpenError>();
1447        assert_impl_display::<OpenError>();
1448        assert_impl_error::<OpenError>();
1449    }
1450
1451    #[test]
1452    fn setflagserror_impls() {
1453        assert_impl_debug::<SetFlagsError>();
1454        assert_impl_display::<SetFlagsError>();
1455        assert_impl_error::<SetFlagsError>();
1456    }
1457}
1458
1459#[cfg(doctest)]
1460#[doc=include_str!("../README-crate.md")]
1461mod readme {}