file(1) 和 libmagic 用于确定 mime 类型的文件在哪里?

K. *_*gor 4 mime-type

根据man 5 magic

“文件 /usr/share/misc/magic 指定要测试的模式、如果找到特定模式要打印的消息或 MIME 类型,以及要从文件中提取的附加信息。”

所以我去找那个文件:

$ file /usr/share/misc/magic
/usr/share/misc/magic: symbolic link to `../file/magic'

$ ll /usr/share/file/magic
total 8
drwxr-xr-x 2 root root 4096 2011-08-08 13:52 ./
drwxr-xr-x 3 root root 4096 2011-10-12 07:27 ../
Run Code Online (Sandbox Code Playgroud)

所以看起来手册页中指定的文件实际上是一个指向空目录的符号链接。我的 Ubuntu 11.10 系统上的那个文件在哪里?

我想查看它的原因是file --mime命令和 python 魔术模块都为某些文件返回了相同的错误 mime 类型,我想查看该文件的格式,以便我可以负责任地修改相关关联。谢谢。

更新:

感谢@Caesium 将我指向strace命令。将输出从管道传输到grep magic,我得到以下输出:

open("/usr/lib/libmagic.so.1", O_RDONLY) = 3
access("/home/phoenix/.magic", R_OK)    = -1 ENOENT (No such file or directory)
open("/etc/magic.mgc", O_RDONLY)        = -1 ENOENT (No such file or directory)
stat("/etc/magic", {st_mode=S_IFREG|0644, st_size=111, ...}) = 0
open("/etc/magic", O_RDONLY)            = 3
open("/usr/share/misc/magic.mgc", O_RDONLY) = 3
Run Code Online (Sandbox Code Playgroud)

因此,它似乎file首先查找/home/username/.magic,然后/etc/magic.mgc,然后/etc/magic,最后/usr/share/misc/magic.mgc确定的文件类型。这表明添加特定于用户的关联规则的适当位置在 中/home/username/.magic,而系统范围的规则在 中/etc/magic。我选择了后一个选项。

为了记录,这里是我的补充/etc/magic

# python: file(1) magic for python modules and scripts
0 string """ a python script text executable
!:mime text/x-python
0 regex #!\ .*\ python a python script text executable
!:mime text/x-python
# pyc file: first four bytes are magic number
# which changes with each python version.
# this is for version 2.7.2:
0 belong 0x03f30d0a python compiled
!:mime application/x-python-bytecode
Run Code Online (Sandbox Code Playgroud)

魔法手册页不鼓励使用“regex”(出于性能原因),但我认为这对我来说是最简单的选择。我希望这有助于其他人解决这个问题,如果他们遇到这个问题——现在被检​​测为 text/x-python 的文件以前被 libmagic 识别为 text/x-java,坦率地说,这看起来很荒谬。

Cae*_*ium 5

你快到了;它在/usr/share/file/magic.mgc

$ file /usr/share/file/magic.mgc
/usr/share/file/magic.mgc: magic binary file for file(1) cmd (version 7) (little endian)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我实际上只是通过环顾四周发现了这一点,但是您可以通过strace以下方式证明它实际上正在使用该文件:

$ strace file /
<snip lots of output>
open("/usr/share/misc/magic.mgc", O_RDONLY) = 3
<snip a bit more output>
Run Code Online (Sandbox Code Playgroud)

/usr/share/misc/magic.mgc只是另一个符号链接。我猜联机帮助页已过时。