Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/thirdparty/magic/magic.py
2992 views
1
"""
2
magic is a wrapper around the libmagic file identification library.
3
4
Usage:
5
6
>>> import magic
7
>>> magic.from_file("testdata/test.pdf")
8
'PDF document, version 1.2'
9
>>> magic.from_file("testdata/test.pdf", mime=True)
10
'application/pdf'
11
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
12
'PDF document, version 1.2'
13
>>>
14
15
"""
16
17
import sys
18
import os.path
19
20
class MagicException(Exception):
21
pass
22
23
class Magic:
24
"""
25
Magic is a wrapper around the libmagic C library.
26
"""
27
28
def __init__(self, mime=False, magic_file=None, mime_encoding=False):
29
"""
30
Create a new libmagic wrapper.
31
32
mime - if True, mimetypes are returned instead of textual descriptions
33
mime_encoding - if True, codec is returned
34
magic_file - use a mime database other than the system default
35
"""
36
37
flags = MAGIC_NONE
38
if mime:
39
flags |= MAGIC_MIME
40
elif mime_encoding:
41
flags |= MAGIC_MIME_ENCODING
42
43
self.cookie = magic_open(flags)
44
45
magic_load(self.cookie, magic_file)
46
47
48
def from_buffer(self, buf):
49
"""
50
Identify the contents of `buf`
51
"""
52
53
return magic_buffer(self.cookie, buf)
54
55
def from_file(self, filename):
56
"""
57
Identify the contents of file `filename`
58
raises IOError if the file does not exist
59
"""
60
61
if not os.path.exists(filename):
62
raise IOError("File does not exist: " + filename)
63
64
return magic_file(self.cookie, filename)
65
66
def __del__(self):
67
# during shutdown magic_close may have been cleared already
68
if self.cookie and magic_close:
69
magic_close(self.cookie)
70
self.cookie = None
71
72
_magic_mime = None
73
_magic = None
74
75
def _get_magic_mime():
76
global _magic_mime
77
if not _magic_mime:
78
_magic_mime = Magic(mime=True)
79
return _magic_mime
80
81
def _get_magic():
82
global _magic
83
if not _magic:
84
_magic = Magic()
85
return _magic
86
87
def _get_magic_type(mime):
88
if mime:
89
return _get_magic_mime()
90
else:
91
return _get_magic()
92
93
def from_file(filename, mime=False):
94
m = _get_magic_type(mime)
95
return m.from_file(filename)
96
97
def from_buffer(buffer, mime=False):
98
m = _get_magic_type(mime)
99
return m.from_buffer(buffer)
100
101
try:
102
libmagic = None
103
104
import ctypes
105
import ctypes.util
106
107
from ctypes import c_char_p, c_int, c_size_t, c_void_p
108
109
# Let's try to find magic or magic1
110
dll = ctypes.util.find_library('magic') or ctypes.util.find_library('magic1')
111
112
# This is necessary because find_library returns None if it doesn't find the library
113
if dll:
114
try:
115
libmagic = ctypes.CDLL(dll)
116
except WindowsError:
117
pass
118
119
if not libmagic or not libmagic._name:
120
platform_to_lib = {'darwin': ['/opt/local/lib/libmagic.dylib',
121
'/usr/local/lib/libmagic.dylib',
122
'/usr/local/Cellar/libmagic/5.10/lib/libmagic.dylib'],
123
'win32': ['magic1.dll']}
124
for dll in platform_to_lib.get(sys.platform, []):
125
try:
126
libmagic = ctypes.CDLL(dll)
127
except OSError:
128
pass
129
130
if not libmagic or not libmagic._name:
131
# It is better to raise an ImportError since we are importing magic module
132
raise ImportError('failed to find libmagic. Check your installation')
133
134
magic_t = ctypes.c_void_p
135
136
def errorcheck(result, func, args):
137
err = magic_error(args[0])
138
if err is not None:
139
raise MagicException(err)
140
else:
141
return result
142
143
def coerce_filename(filename):
144
if filename is None:
145
return None
146
return filename.encode(sys.getfilesystemencoding())
147
148
magic_open = libmagic.magic_open
149
magic_open.restype = magic_t
150
magic_open.argtypes = [c_int]
151
152
magic_close = libmagic.magic_close
153
magic_close.restype = None
154
magic_close.argtypes = [magic_t]
155
156
magic_error = libmagic.magic_error
157
magic_error.restype = c_char_p
158
magic_error.argtypes = [magic_t]
159
160
magic_errno = libmagic.magic_errno
161
magic_errno.restype = c_int
162
magic_errno.argtypes = [magic_t]
163
164
_magic_file = libmagic.magic_file
165
_magic_file.restype = c_char_p
166
_magic_file.argtypes = [magic_t, c_char_p]
167
_magic_file.errcheck = errorcheck
168
169
def magic_file(cookie, filename):
170
return _magic_file(cookie, coerce_filename(filename))
171
172
_magic_buffer = libmagic.magic_buffer
173
_magic_buffer.restype = c_char_p
174
_magic_buffer.argtypes = [magic_t, c_void_p, c_size_t]
175
_magic_buffer.errcheck = errorcheck
176
177
178
def magic_buffer(cookie, buf):
179
return _magic_buffer(cookie, buf, len(buf))
180
181
_magic_load = libmagic.magic_load
182
_magic_load.restype = c_int
183
_magic_load.argtypes = [magic_t, c_char_p]
184
_magic_load.errcheck = errorcheck
185
186
def magic_load(cookie, filename):
187
return _magic_load(cookie, coerce_filename(filename))
188
189
magic_setflags = libmagic.magic_setflags
190
magic_setflags.restype = c_int
191
magic_setflags.argtypes = [magic_t, c_int]
192
193
magic_check = libmagic.magic_check
194
magic_check.restype = c_int
195
magic_check.argtypes = [magic_t, c_char_p]
196
197
magic_compile = libmagic.magic_compile
198
magic_compile.restype = c_int
199
magic_compile.argtypes = [magic_t, c_char_p]
200
201
except (ImportError, OSError):
202
from_file = from_buffer = lambda *args, **kwargs: MAGIC_UNKNOWN_FILETYPE
203
204
MAGIC_NONE = 0x000000 # No flags
205
MAGIC_DEBUG = 0x000001 # Turn on debugging
206
MAGIC_SYMLINK = 0x000002 # Follow symlinks
207
MAGIC_COMPRESS = 0x000004 # Check inside compressed files
208
MAGIC_DEVICES = 0x000008 # Look at the contents of devices
209
MAGIC_MIME = 0x000010 # Return a mime string
210
MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding
211
MAGIC_CONTINUE = 0x000020 # Return all matches
212
MAGIC_CHECK = 0x000040 # Print warnings to stderr
213
MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit
214
MAGIC_RAW = 0x000100 # Don't translate unprintable chars
215
MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors
216
MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files
217
MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files
218
MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries
219
MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type
220
MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details
221
MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files
222
MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff
223
MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran
224
MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens
225
MAGIC_UNKNOWN_FILETYPE = b"unknown"
226
227