1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//! This crate provides bindings for `libmagic`, which recognizes the
//! type of data contained in a file (or buffer).
//!
//! You should be already familiar with `libmagic`'s CLI command `file`:
//! ```sh
//! $ file rust-logo-128x128-blk.png
//! rust-logo-128x128-blk.png: PNG image data, 128 x 128, 8-bit/color RGBA, non-interlaced
//! ```
//!
//! # Usage example
//!
//! Here's an example of using this crate:
//!
//! ```no_run
//! use filemagic::Magic;
//!
//! fn main() {
//!    let test_file = "path/to/file";
//!    let cookie = Magic::open(Default::default()).expect("error");
//!     cookie.load::<String>(&[]).expect("error");
//!     let magic = cookie.file(&test_file).expect("error in magic");
//!     println!("magic= {}", magic);
//! }
//! ```
#![crate_type = "lib"]
#[macro_use]
extern crate bitflags;
#[macro_use]
pub mod macros;

extern crate libc;
use libc::{c_char, size_t};

mod api;

pub mod version;
pub use version::version;

pub mod flags;
pub use flags::Flags;

#[cfg(test)]
mod tests;

use std::{
    error,
    ffi::{CStr, CString},
    fmt::Display,
    path::Path,
    ptr, str,
};

fn db_filenames<P: AsRef<Path>>(filenames: &[P]) -> *const c_char {
    match filenames.len() {
        0 => ptr::null(),
        // FIXME: This is just plain wrong. I'm surprised it works at all..
        1 => CString::new(filenames[0].as_ref().to_string_lossy().into_owned())
            .unwrap()
            .into_raw(),
        _ => unimplemented!(),
    }
}

/// The error type used in this crate
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct FileMagicError {
    pub desc: String,
}

impl error::Error for FileMagicError {
    fn description(&self) -> &str {
        "internal libmagic error"
    }
}

impl Display for FileMagicError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.desc)
    }
}

/// Configuration of which `Flags` and magic databases to use
pub struct Magic {
    magic: *const api::Magic,
}

impl Drop for Magic {
    /// Closes the magic database and deallocates any resources used
    fn drop(&mut self) {
        unsafe { api::magic_close(self.magic) }
    }
}

impl Magic {
    fn last_error(&self) -> Option<FileMagicError> {
        let cookie = self.magic;

        unsafe {
            let e = api::magic_error(cookie);
            if e.is_null() {
                None
            } else {
                let slice = CStr::from_ptr(e).to_bytes();
                Some(self::FileMagicError {
                    desc: str::from_utf8(slice).unwrap().to_string(),
                })
            }
        }
    }

    fn magic_failure(&self) -> FileMagicError {
        match self.last_error() {
            Some(e) => e,
            None => self::FileMagicError {
                desc: "unknown error".to_string(),
            },
        }
    }

    /// Returns a textual explanation of the last error, if any
    ///
    /// You should not need to call this, since you can use the `FileMagicError` in
    /// the `Result` returned by the other functions.
    // TODO: Remove this entirely?
    pub fn error(&self) -> Option<String> {
        unsafe {
            let str = api::magic_error(self.magic);
            if str.is_null() {
                None
            } else {
                let slice = CStr::from_ptr(str).to_bytes();
                Some(str::from_utf8(slice).unwrap().to_string())
            }
        }
    }

    /// Returns a textual description of the contents of the `filename`
    pub fn file<P: AsRef<Path>>(&self, filename: P) -> Result<String, FileMagicError> {
        let cookie = self.magic;
        let f = CString::new(filename.as_ref().to_string_lossy().into_owned())
            .unwrap()
            .into_raw();
        unsafe {
            let str = api::magic_file(cookie, f);
            if str.is_null() {
                Err(self.magic_failure())
            } else {
                let slice = CStr::from_ptr(str).to_bytes();
                Ok(str::from_utf8(slice).unwrap().to_string())
            }
        }
    }

    /// Returns a textual description of the contents of the `buffer`
    pub fn buffer(&self, buffer: &[u8]) -> Result<String, FileMagicError> {
        let buffer_len = buffer.len() as size_t;
        let pbuffer = buffer.as_ptr();
        unsafe {
            let str = api::magic_buffer(self.magic, pbuffer, buffer_len);
            if str.is_null() {
                Err(self.magic_failure())
            } else {
                let slice = CStr::from_ptr(str).to_bytes();
                Ok(str::from_utf8(slice).unwrap().to_string())
            }
        }
    }

    /// Check the validity of entries in the database `filenames`
    pub fn check<P: AsRef<Path>>(&self, filenames: &[P]) -> Result<(), FileMagicError> {
        let cookie = self.magic;
        let db_filenames = db_filenames(filenames);
        let ret;

        unsafe {
            ret = api::magic_check(cookie, db_filenames);
        }
        if 0 == ret { Ok(()) } else { Err(self.magic_failure()) }
    }

    /// Compiles the given database `filenames` for faster access
    ///
    /// The compiled files created are named from the `basename` of each file argument with '.mgc' appended to it.
    pub fn compile<P: AsRef<Path>>(&self, filenames: &[P]) -> Result<(), FileMagicError> {
        let cookie = self.magic;
        let db_filenames = db_filenames(filenames);
        let ret;

        unsafe {
            ret = api::magic_compile(cookie, db_filenames);
        }
        if 0 == ret { Ok(()) } else { Err(self.magic_failure()) }
    }

    /// Dumps all magic entries in the given database `filenames` in a human readable format
    pub fn list<P: AsRef<Path>>(&self, filenames: &[P]) -> Result<(), FileMagicError> {
        let cookie = self.magic;
        let db_filenames = db_filenames(filenames);
        let ret;

        unsafe {
            ret = api::magic_list(cookie, db_filenames);
        }
        if 0 == ret { Ok(()) } else { Err(self.magic_failure()) }
    }

    /// Sets the flags to use
    ///
    /// Overwrites any previously set flags, e.g. those from `load()`.
    // TODO: libmagic itself has to magic_getflags, but we could remember them in Cookie?
    pub fn set_flags(&self, flags: Flags) -> bool {
        unsafe { api::magic_setflags(self.magic, flags.bits()) != -1 }
    }

    /// Creates a new configuration, `flags` specify how other functions should behave
    ///
    /// This does not `load()` any databases yet.
    pub fn open(flags: Flags) -> Result<Magic, FileMagicError> {
        let cookie;
        unsafe {
            cookie = api::magic_open((flags | Flags::ERROR).bits());
        }
        if cookie.is_null() {
            Err(self::FileMagicError {
                desc: "errno".to_string(),
            })
        } else {
            Ok(Magic { magic: cookie })
        }
    }

    /// Loads the given database `filenames` for further queries
    ///
    /// Adds '.mgc'	to the database	files as appropriate.
    pub fn load<P: AsRef<Path>>(&self, magic_databases: &[P]) -> Result<(), FileMagicError> {
        let cookie = self.magic;
        let db_filenames = db_filenames(magic_databases);
        let ret;

        unsafe {
            ret = api::magic_load(cookie, db_filenames);
        }
        if 0 == ret {
            Ok(())
        } else {
            Err(self.magic_failure())
        }
    }
}