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
|
package magic
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
)
var magicFiles map[string]bool
var mutex sync.Mutex
func init() {
magicFiles = make(map[string]bool)
}
func compileToMgc(file string) {
cookie := Open(MAGIC_NONE)
defer Close(cookie)
Compile(cookie, file)
}
func compileMagicFiles(dir string, files []string) {
// for some reason libmagic puts compiled files in the current working dir
// instead of the dir of the source file, so switch to the source dir,
// compile, then switch back
pwd, err := os.Getwd()
if err != nil {
return
}
err = os.Chdir(dir)
if err != nil {
return
}
defer os.Chdir(pwd)
for _, f := range files {
compileToMgc(f)
}
}
/* Add a directory for libmagic to search for .mgc databases. */
func AddMagicDir(dir string) error {
var err error
dir, err = filepath.Abs(dir)
if err != nil {
return err
}
fi, err := os.Stat(dir)
if err != nil {
return err
}
if fi.IsDir() == false {
return fmt.Errorf("Not a directory: %s", dir)
}
// get list of .magic files that need to be compiled to .mgc
var srcFiles []string
files, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
for _, fi = range files {
if filepath.Ext(fi.Name()) == ".magic" {
mgcSrc := filepath.Join(dir, fi.Name())
_, err := os.Stat(mgcSrc + ".mgc")
if err != nil {
srcFiles = append(srcFiles, mgcSrc)
}
}
}
// compile .magic files
if len(srcFiles) > 0 {
compileMagicFiles(dir, srcFiles)
}
files, err = ioutil.ReadDir(dir)
if err != nil {
return err
}
mutex.Lock()
for _, fi = range files {
if filepath.Ext(fi.Name()) == ".mgc" {
mgcFile := filepath.Join(dir, fi.Name())
magicFiles[mgcFile] = true
}
}
mutex.Unlock()
return nil
}
/* Get mimetype from a file. */
func MimeFromFile(path string) string {
cookie := Open(MAGIC_ERROR | MAGIC_MIME_TYPE)
defer Close(cookie)
mutex.Lock()
var mf []string
for f := range magicFiles {
mf = append(mf, f)
}
mutex.Unlock()
ret := Load(cookie, strings.Join(mf, ":"))
if ret != 0 {
return "application/octet-stream"
}
r := File(cookie, path)
return r
}
/* Get mimetype from a buffer. */
func MimeFromBytes(b []byte) string {
cookie := Open(MAGIC_ERROR | MAGIC_MIME_TYPE)
defer Close(cookie)
mutex.Lock()
var mf []string
for f := range magicFiles {
mf = append(mf, f)
}
mutex.Unlock()
ret := Load(cookie, strings.Join(mf, ":"))
if ret != 0 {
return "application/octet-stream"
}
r := Buffer(cookie, b)
return r
}
|