__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. """
  2. magic is a wrapper around the libmagic file identification library.
  3. See README for more information.
  4. Usage:
  5. >>> import magic
  6. >>> magic.from_file("testdata/test.pdf")
  7. 'PDF document, version 1.2'
  8. >>> magic.from_file("testdata/test.pdf", mime=True)
  9. 'application/pdf'
  10. >>> magic.from_buffer(open("testdata/test.pdf").read(1024))
  11. 'PDF document, version 1.2'
  12. >>>
  13. """
  14. import sys
  15. import glob
  16. import ctypes
  17. import ctypes.util
  18. import threading
  19. import logging
  20. from ctypes import c_char_p, c_int, c_size_t, c_void_p, byref, POINTER
  21. # avoid shadowing the real open with the version from compat.py
  22. _real_open = open
  23. class MagicException(Exception):
  24. def __init__(self, message):
  25. super(Exception, self).__init__(message)
  26. self.message = message
  27. class Magic:
  28. """
  29. Magic is a wrapper around the libmagic C library.
  30. """
  31. def __init__(self, mime=False, magic_file=None, mime_encoding=False,
  32. keep_going=False, uncompress=False, raw=False, extension=False):
  33. """
  34. Create a new libmagic wrapper.
  35. mime - if True, mimetypes are returned instead of textual descriptions
  36. mime_encoding - if True, codec is returned
  37. magic_file - use a mime database other than the system default
  38. keep_going - don't stop at the first match, keep going
  39. uncompress - Try to look inside compressed files.
  40. raw - Do not try to decode "non-printable" chars.
  41. extension - Print a slash-separated list of valid extensions for the file type found.
  42. """
  43. self.flags = MAGIC_NONE
  44. if mime:
  45. self.flags |= MAGIC_MIME_TYPE
  46. if mime_encoding:
  47. self.flags |= MAGIC_MIME_ENCODING
  48. if keep_going:
  49. self.flags |= MAGIC_CONTINUE
  50. if uncompress:
  51. self.flags |= MAGIC_COMPRESS
  52. if raw:
  53. self.flags |= MAGIC_RAW
  54. if extension:
  55. self.flags |= MAGIC_EXTENSION
  56. self.cookie = magic_open(self.flags)
  57. self.lock = threading.Lock()
  58. magic_load(self.cookie, magic_file)
  59. # MAGIC_EXTENSION was added in 523 or 524, so bail if
  60. # it doesn't appear to be available
  61. if extension and (not _has_version or version() < 524):
  62. raise NotImplementedError('MAGIC_EXTENSION is not supported in this version of libmagic')
  63. # For https://github.com/ahupp/python-magic/issues/190
  64. # libmagic has fixed internal limits that some files exceed, causing
  65. # an error. We can avoid this (at least for the sample file given)
  66. # by bumping the limit up. It's not clear if this is a general solution
  67. # or whether other internal limits should be increased, but given
  68. # the lack of other reports I'll assume this is rare.
  69. if _has_param:
  70. try:
  71. self.setparam(MAGIC_PARAM_NAME_MAX, 64)
  72. except MagicException as e:
  73. # some versions of libmagic fail this call,
  74. # so rather than fail hard just use default behavior
  75. pass
  76. def from_buffer(self, buf):
  77. """
  78. Identify the contents of `buf`
  79. """
  80. with self.lock:
  81. try:
  82. # if we're on python3, convert buf to bytes
  83. # otherwise this string is passed as wchar*
  84. # which is not what libmagic expects
  85. if type(buf) == str and str != bytes:
  86. buf = buf.encode('utf-8', errors='replace')
  87. return maybe_decode(magic_buffer(self.cookie, buf))
  88. except MagicException as e:
  89. return self._handle509Bug(e)
  90. def from_file(self, filename):
  91. # raise FileNotFoundException or IOError if the file does not exist
  92. with _real_open(filename):
  93. pass
  94. with self.lock:
  95. try:
  96. return maybe_decode(magic_file(self.cookie, filename))
  97. except MagicException as e:
  98. return self._handle509Bug(e)
  99. def from_descriptor(self, fd):
  100. with self.lock:
  101. try:
  102. return maybe_decode(magic_descriptor(self.cookie, fd))
  103. except MagicException as e:
  104. return self._handle509Bug(e)
  105. def _handle509Bug(self, e):
  106. # libmagic 5.09 has a bug where it might fail to identify the
  107. # mimetype of a file and returns null from magic_file (and
  108. # likely _buffer), but also does not return an error message.
  109. if e.message is None and (self.flags & MAGIC_MIME_TYPE):
  110. return "application/octet-stream"
  111. else:
  112. raise e
  113. def setparam(self, param, val):
  114. return magic_setparam(self.cookie, param, val)
  115. def getparam(self, param):
  116. return magic_getparam(self.cookie, param)
  117. def __del__(self):
  118. # no _thread_check here because there can be no other
  119. # references to this object at this point.
  120. # during shutdown magic_close may have been cleared already so
  121. # make sure it exists before using it.
  122. # the self.cookie check should be unnecessary and was an
  123. # incorrect fix for a threading problem, however I'm leaving
  124. # it in because it's harmless and I'm slightly afraid to
  125. # remove it.
  126. if hasattr(self, 'cookie') and self.cookie and magic_close:
  127. magic_close(self.cookie)
  128. self.cookie = None
  129. _instances = {}
  130. def _get_magic_type(mime):
  131. i = _instances.get(mime)
  132. if i is None:
  133. i = _instances[mime] = Magic(mime=mime)
  134. return i
  135. def from_file(filename, mime=False):
  136. """"
  137. Accepts a filename and returns the detected filetype. Return
  138. value is the mimetype if mime=True, otherwise a human readable
  139. name.
  140. >>> magic.from_file("testdata/test.pdf", mime=True)
  141. 'application/pdf'
  142. """
  143. m = _get_magic_type(mime)
  144. return m.from_file(filename)
  145. def from_buffer(buffer, mime=False):
  146. """
  147. Accepts a binary string and returns the detected filetype. Return
  148. value is the mimetype if mime=True, otherwise a human readable
  149. name.
  150. >>> magic.from_buffer(open("testdata/test.pdf").read(1024))
  151. 'PDF document, version 1.2'
  152. """
  153. m = _get_magic_type(mime)
  154. return m.from_buffer(buffer)
  155. def from_descriptor(fd, mime=False):
  156. """
  157. Accepts a file descriptor and returns the detected filetype. Return
  158. value is the mimetype if mime=True, otherwise a human readable
  159. name.
  160. >>> f = open("testdata/test.pdf")
  161. >>> magic.from_descriptor(f.fileno())
  162. 'PDF document, version 1.2'
  163. """
  164. m = _get_magic_type(mime)
  165. return m.from_descriptor(fd)
  166. from . import loader
  167. libmagic = loader.load_lib()
  168. magic_t = ctypes.c_void_p
  169. def errorcheck_null(result, func, args):
  170. if result is None:
  171. err = magic_error(args[0])
  172. raise MagicException(err)
  173. else:
  174. return result
  175. def errorcheck_negative_one(result, func, args):
  176. if result == -1:
  177. err = magic_error(args[0])
  178. raise MagicException(err)
  179. else:
  180. return result
  181. # return str on python3. Don't want to unconditionally
  182. # decode because that results in unicode on python2
  183. def maybe_decode(s):
  184. if str == bytes:
  185. return s
  186. else:
  187. # backslashreplace here because sometimes libmagic will return metadata in the charset
  188. # of the file, which is unknown to us (e.g the title of a Word doc)
  189. return s.decode('utf-8', 'backslashreplace')
  190. def coerce_filename(filename):
  191. if filename is None:
  192. return None
  193. # ctypes will implicitly convert unicode strings to bytes with
  194. # .encode('ascii'). If you use the filesystem encoding
  195. # then you'll get inconsistent behavior (crashes) depending on the user's
  196. # LANG environment variable
  197. is_unicode = (sys.version_info[0] <= 2 and
  198. isinstance(filename, unicode)) or \
  199. (sys.version_info[0] >= 3 and
  200. isinstance(filename, str))
  201. if is_unicode:
  202. return filename.encode('utf-8', 'surrogateescape')
  203. else:
  204. return filename
  205. magic_open = libmagic.magic_open
  206. magic_open.restype = magic_t
  207. magic_open.argtypes = [c_int]
  208. magic_close = libmagic.magic_close
  209. magic_close.restype = None
  210. magic_close.argtypes = [magic_t]
  211. magic_error = libmagic.magic_error
  212. magic_error.restype = c_char_p
  213. magic_error.argtypes = [magic_t]
  214. magic_errno = libmagic.magic_errno
  215. magic_errno.restype = c_int
  216. magic_errno.argtypes = [magic_t]
  217. _magic_file = libmagic.magic_file
  218. _magic_file.restype = c_char_p
  219. _magic_file.argtypes = [magic_t, c_char_p]
  220. _magic_file.errcheck = errorcheck_null
  221. def magic_file(cookie, filename):
  222. return _magic_file(cookie, coerce_filename(filename))
  223. _magic_buffer = libmagic.magic_buffer
  224. _magic_buffer.restype = c_char_p
  225. _magic_buffer.argtypes = [magic_t, c_void_p, c_size_t]
  226. _magic_buffer.errcheck = errorcheck_null
  227. def magic_buffer(cookie, buf):
  228. return _magic_buffer(cookie, buf, len(buf))
  229. magic_descriptor = libmagic.magic_descriptor
  230. magic_descriptor.restype = c_char_p
  231. magic_descriptor.argtypes = [magic_t, c_int]
  232. magic_descriptor.errcheck = errorcheck_null
  233. _magic_descriptor = libmagic.magic_descriptor
  234. _magic_descriptor.restype = c_char_p
  235. _magic_descriptor.argtypes = [magic_t, c_int]
  236. _magic_descriptor.errcheck = errorcheck_null
  237. def magic_descriptor(cookie, fd):
  238. return _magic_descriptor(cookie, fd)
  239. _magic_load = libmagic.magic_load
  240. _magic_load.restype = c_int
  241. _magic_load.argtypes = [magic_t, c_char_p]
  242. _magic_load.errcheck = errorcheck_negative_one
  243. def magic_load(cookie, filename):
  244. return _magic_load(cookie, coerce_filename(filename))
  245. magic_setflags = libmagic.magic_setflags
  246. magic_setflags.restype = c_int
  247. magic_setflags.argtypes = [magic_t, c_int]
  248. magic_check = libmagic.magic_check
  249. magic_check.restype = c_int
  250. magic_check.argtypes = [magic_t, c_char_p]
  251. magic_compile = libmagic.magic_compile
  252. magic_compile.restype = c_int
  253. magic_compile.argtypes = [magic_t, c_char_p]
  254. _has_param = False
  255. if hasattr(libmagic, 'magic_setparam') and hasattr(libmagic, 'magic_getparam'):
  256. _has_param = True
  257. _magic_setparam = libmagic.magic_setparam
  258. _magic_setparam.restype = c_int
  259. _magic_setparam.argtypes = [magic_t, c_int, POINTER(c_size_t)]
  260. _magic_setparam.errcheck = errorcheck_negative_one
  261. _magic_getparam = libmagic.magic_getparam
  262. _magic_getparam.restype = c_int
  263. _magic_getparam.argtypes = [magic_t, c_int, POINTER(c_size_t)]
  264. _magic_getparam.errcheck = errorcheck_negative_one
  265. def magic_setparam(cookie, param, val):
  266. if not _has_param:
  267. raise NotImplementedError("magic_setparam not implemented")
  268. v = c_size_t(val)
  269. return _magic_setparam(cookie, param, byref(v))
  270. def magic_getparam(cookie, param):
  271. if not _has_param:
  272. raise NotImplementedError("magic_getparam not implemented")
  273. val = c_size_t()
  274. _magic_getparam(cookie, param, byref(val))
  275. return val.value
  276. _has_version = False
  277. if hasattr(libmagic, "magic_version"):
  278. _has_version = True
  279. magic_version = libmagic.magic_version
  280. magic_version.restype = c_int
  281. magic_version.argtypes = []
  282. def version():
  283. if not _has_version:
  284. raise NotImplementedError("magic_version not implemented")
  285. return magic_version()
  286. MAGIC_NONE = 0x000000 # No flags
  287. MAGIC_DEBUG = 0x000001 # Turn on debugging
  288. MAGIC_SYMLINK = 0x000002 # Follow symlinks
  289. MAGIC_COMPRESS = 0x000004 # Check inside compressed files
  290. MAGIC_DEVICES = 0x000008 # Look at the contents of devices
  291. MAGIC_MIME_TYPE = 0x000010 # Return a mime string
  292. MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding
  293. # TODO: should be
  294. # MAGIC_MIME = MAGIC_MIME_TYPE | MAGIC_MIME_ENCODING
  295. MAGIC_MIME = 0x000010 # Return a mime string
  296. MAGIC_EXTENSION = 0x1000000 # Return a /-separated list of extensions
  297. MAGIC_CONTINUE = 0x000020 # Return all matches
  298. MAGIC_CHECK = 0x000040 # Print warnings to stderr
  299. MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit
  300. MAGIC_RAW = 0x000100 # Don't translate unprintable chars
  301. MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors
  302. MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files
  303. MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files
  304. MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries
  305. MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type
  306. MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details
  307. MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files
  308. MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff
  309. MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran
  310. MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens
  311. MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic
  312. MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic
  313. MAGIC_PARAM_ELF_PHNUM_MAX = 2 # Max ELF notes processed
  314. MAGIC_PARAM_ELF_SHNUM_MAX = 3 # Max ELF program sections processed
  315. MAGIC_PARAM_ELF_NOTES_MAX = 4 # # Max ELF sections processed
  316. MAGIC_PARAM_REGEX_MAX = 5 # Length limit for regex searches
  317. MAGIC_PARAM_BYTES_MAX = 6 # Max number of bytes to read from file
  318. # This package name conflicts with the one provided by upstream
  319. # libmagic. This is a common source of confusion for users. To
  320. # resolve, We ship a copy of that module, and expose it's functions
  321. # wrapped in deprecation warnings.
  322. def _add_compat(to_module):
  323. import warnings, re
  324. from magic import compat
  325. def deprecation_wrapper(fn):
  326. def _(*args, **kwargs):
  327. warnings.warn(
  328. "Using compatibility mode with libmagic's python binding. "
  329. "See https://github.com/ahupp/python-magic/blob/master/COMPAT.md for details.",
  330. PendingDeprecationWarning)
  331. return fn(*args, **kwargs)
  332. return _
  333. fn = ['detect_from_filename',
  334. 'detect_from_content',
  335. 'detect_from_fobj',
  336. 'open']
  337. for fname in fn:
  338. to_module[fname] = deprecation_wrapper(compat.__dict__[fname])
  339. # copy constants over, ensuring there's no conflicts
  340. is_const_re = re.compile("^[A-Z_]+$")
  341. allowed_inconsistent = set(['MAGIC_MIME'])
  342. for name, value in compat.__dict__.items():
  343. if is_const_re.match(name):
  344. if name in to_module:
  345. if name in allowed_inconsistent:
  346. continue
  347. if to_module[name] != value:
  348. raise Exception("inconsistent value for " + name)
  349. else:
  350. continue
  351. else:
  352. to_module[name] = value
  353. _add_compat(globals())