2 * Copyright (c) Christos Zoulas 2003.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice immediately at the beginning of the file, without modification,
10 * this list of conditions, and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 FILE_RCSID("@(#)$File: magic.c,v 1.112 2020/06/08 19:44:10 christos Exp $")
47 #include <limits.h> /* for PIPE_BUF */
49 #if defined(HAVE_UTIMES)
50 # include <sys/time.h>
51 #elif defined(HAVE_UTIME)
52 # if defined(HAVE_SYS_UTIME_H)
53 # include <sys/utime.h>
54 # elif defined(HAVE_UTIME_H)
60 #include <unistd.h> /* for read() */
64 /* Get the PIPE_BUF from pathconf */
66 #define PIPE_BUF pathconf(".", _PC_PIPE_BUF)
72 private void close_and_restore(const struct magic_set *, const char *, int,
74 private int unreadable_info(struct magic_set *, mode_t, const char *);
75 private const char* get_default_magic(void);
77 private const char *file_or_fd(struct magic_set *, const char *, int);
81 #define STDIN_FILENO 0
85 /* HINSTANCE of this shared library. Needed for get_default_magic() */
86 static HINSTANCE _w32_dll_instance = NULL;
89 _w32_append_path(char **hmagicpath, const char *fmt, ...)
96 if (vasprintf(&tmppath, fmt, ap) < 0) {
102 if (access(tmppath, R_OK) == -1)
105 if (*hmagicpath == NULL) {
106 *hmagicpath = tmppath;
110 if (asprintf(&newpath, "%s%c%s", *hmagicpath, PATHSEP, tmppath) < 0)
115 *hmagicpath = newpath;
122 _w32_get_magic_relative_to(char **hmagicpath, HINSTANCE module)
124 static const char *trypaths[] = {
125 "%s/share/misc/magic.mgc",
131 dllpath = calloc(MAX_PATH + 1, sizeof(*dllpath));
133 if (!GetModuleFileNameA(module, dllpath, MAX_PATH))
136 PathRemoveFileSpecA(dllpath);
139 char exepath[MAX_PATH];
140 GetModuleFileNameA(NULL, exepath, MAX_PATH);
141 PathRemoveFileSpecA(exepath);
142 if (stricmp(exepath, dllpath) == 0)
146 sp = strlen(dllpath);
147 if (sp > 3 && stricmp(&dllpath[sp - 3], "bin") == 0) {
148 _w32_append_path(hmagicpath,
149 "%s/../share/misc/magic.mgc", dllpath);
153 for (sp = 0; sp < __arraycount(trypaths); sp++)
154 _w32_append_path(hmagicpath, trypaths[sp], dllpath);
159 /* Placate GCC by offering a sacrificial previous prototype */
160 BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID);
163 DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
164 LPVOID lpvReserved __attribute__((__unused__)))
166 if (fdwReason == DLL_PROCESS_ATTACH)
167 _w32_dll_instance = hinstDLL;
173 get_default_magic(void)
175 static const char hmagic[] = "/.magic/magic.mgc";
176 static char *default_magic;
177 char *home, *hmagicpath;
184 default_magic = NULL;
186 if ((home = getenv("HOME")) == NULL)
189 if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0)
191 if (stat(hmagicpath, &st) == -1) {
193 if (asprintf(&hmagicpath, "%s/.magic", home) < 0)
195 if (stat(hmagicpath, &st) == -1)
197 if (S_ISDIR(st.st_mode)) {
199 if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0)
201 if (access(hmagicpath, R_OK) == -1)
206 if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0)
209 return default_magic;
211 default_magic = NULL;
219 default_magic = NULL;
222 /* First, try to get a magic file from user-application data */
223 if ((home = getenv("LOCALAPPDATA")) != NULL)
224 _w32_append_path(&hmagicpath, "%s%s", home, hmagic);
226 /* Second, try to get a magic file from the user profile data */
227 if ((home = getenv("USERPROFILE")) != NULL)
228 _w32_append_path(&hmagicpath,
229 "%s/Local Settings/Application Data%s", home, hmagic);
231 /* Third, try to get a magic file from Common Files */
232 if ((home = getenv("COMMONPROGRAMFILES")) != NULL)
233 _w32_append_path(&hmagicpath, "%s%s", home, hmagic);
235 /* Fourth, try to get magic file relative to exe location */
236 _w32_get_magic_relative_to(&hmagicpath, NULL);
238 /* Fifth, try to get magic file relative to dll location */
239 _w32_get_magic_relative_to(&hmagicpath, _w32_dll_instance);
241 /* Avoid MAGIC constant - it likely points to a file within MSys tree */
242 default_magic = hmagicpath;
243 return default_magic;
248 magic_getpath(const char *magicfile, int action)
250 if (magicfile != NULL)
253 magicfile = getenv("MAGIC");
254 if (magicfile != NULL)
257 return action == FILE_LOAD ? get_default_magic() : MAGIC;
260 public struct magic_set *
261 magic_open(int flags)
263 return file_ms_alloc(flags);
267 unreadable_info(struct magic_set *ms, mode_t md, const char *file)
270 /* We cannot open it, but we were able to stat it. */
271 if (access(file, W_OK) == 0)
272 if (file_printf(ms, "writable, ") == -1)
274 if (access(file, X_OK) == 0)
275 if (file_printf(ms, "executable, ") == -1)
279 if (file_printf(ms, "regular file, ") == -1)
281 if (file_printf(ms, "no read permission") == -1)
287 magic_close(struct magic_set *ms)
298 magic_load(struct magic_set *ms, const char *magicfile)
302 return file_apprentice(ms, magicfile, FILE_LOAD);
307 * Install a set of compiled magic buffers.
310 magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes,
315 return buffer_apprentice(ms, RCAST(struct magic **, bufs),
321 magic_compile(struct magic_set *ms, const char *magicfile)
325 return file_apprentice(ms, magicfile, FILE_COMPILE);
329 magic_check(struct magic_set *ms, const char *magicfile)
333 return file_apprentice(ms, magicfile, FILE_CHECK);
337 magic_list(struct magic_set *ms, const char *magicfile)
341 return file_apprentice(ms, magicfile, FILE_LIST);
345 close_and_restore(const struct magic_set *ms, const char *name, int fd,
346 const struct stat *sb)
348 if (fd == STDIN_FILENO || name == NULL)
352 if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) {
354 * Try to restore access, modification times if read it.
355 * This is really *bad* because it will modify the status
356 * time of the file... And of course this will affect
360 struct timeval utsbuf[2];
361 (void)memset(utsbuf, 0, sizeof(utsbuf));
362 utsbuf[0].tv_sec = sb->st_atime;
363 utsbuf[1].tv_sec = sb->st_mtime;
365 (void) utimes(name, utsbuf); /* don't care if loses */
366 #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H)
367 struct utimbuf utbuf;
369 (void)memset(&utbuf, 0, sizeof(utbuf));
370 utbuf.actime = sb->st_atime;
371 utbuf.modtime = sb->st_mtime;
372 (void) utime(name, &utbuf); /* don't care if loses */
380 * find type of descriptor
383 magic_descriptor(struct magic_set *ms, int fd)
387 return file_or_fd(ms, NULL, fd);
391 * find type of named file
394 magic_file(struct magic_set *ms, const char *inname)
398 return file_or_fd(ms, inname, STDIN_FILENO);
402 file_or_fd(struct magic_set *ms, const char *inname, int fd)
407 ssize_t nbytes = 0; /* number of bytes read from a datafile */
410 off_t pos = CAST(off_t, -1);
412 if (file_reset(ms, 1) == -1)
416 * one extra for terminating '\0', and
417 * some overlapping space for matches near EOF
419 #define SLOP (1 + sizeof(union VALUETYPE))
420 if ((buf = CAST(unsigned char *, malloc(ms->bytes_max + SLOP))) == NULL)
423 switch (file_fsmagic(ms, inname, &sb)) {
426 case 0: /* nothing found */
428 default: /* matched it and printed type */
434 /* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */
435 if (fd == STDIN_FILENO)
436 _setmode(STDIN_FILENO, O_BINARY);
438 if (inname != NULL) {
439 int flags = O_RDONLY|O_BINARY|O_NONBLOCK;
441 if ((fd = open(inname, flags)) < 0) {
442 okstat = stat(inname, &sb) == 0;
443 if (okstat && S_ISFIFO(sb.st_mode))
447 * Can't stat, can't open. It may have been opened in
448 * fsmagic, so if the user doesn't have read permission,
449 * allow it to say so; otherwise an error was probably
450 * displayed in fsmagic.
452 if (!okstat && errno == EACCES) {
453 sb.st_mode = S_IFBLK;
458 unreadable_info(ms, sb.st_mode, inname) == -1)
466 okstat = fstat(fd, &sb) == 0;
467 if (okstat && S_ISFIFO(sb.st_mode))
470 pos = lseek(fd, CAST(off_t, 0), SEEK_CUR);
474 * try looking at the first ms->bytes_max bytes
480 while ((r = sread(fd, RCAST(void *, &buf[nbytes]),
481 CAST(size_t, ms->bytes_max - nbytes), 1)) > 0) {
483 if (r < PIPE_BUF) break;
487 if (nbytes == 0 && inname) {
488 /* We can not read it, but we were able to stat it. */
489 if (unreadable_info(ms, sb.st_mode, inname) == -1)
495 } else if (fd != -1) {
496 /* Windows refuses to read from a big console buffer. */
499 _isatty(fd) ? 8 * 1024 :
502 if ((nbytes = read(fd, RCAST(void *, buf), howmany)) == -1) {
503 if (inname == NULL && fd != STDIN_FILENO)
504 file_error(ms, errno, "cannot read fd %d", fd);
506 file_error(ms, errno, "cannot read `%s'",
507 inname == NULL ? "/dev/stdin" : inname);
512 (void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
513 if (file_buffer(ms, fd, okstat ? &sb : NULL, inname, buf, CAST(size_t, nbytes)) == -1)
519 if (pos != CAST(off_t, -1))
520 (void)lseek(fd, pos, SEEK_SET);
521 close_and_restore(ms, inname, fd, &sb);
524 return rv == 0 ? file_getbuffer(ms) : NULL;
529 magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
533 if (file_reset(ms, 1) == -1)
536 * The main work is done here!
537 * We have the file name and/or the data buffer to be identified.
539 if (file_buffer(ms, -1, NULL, NULL, buf, nb) == -1) {
542 return file_getbuffer(ms);
547 magic_error(struct magic_set *ms)
550 return "Magic database is not open";
551 return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
555 magic_errno(struct magic_set *ms)
559 return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
563 magic_getflags(struct magic_set *ms)
572 magic_setflags(struct magic_set *ms, int flags)
576 #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
577 if (flags & MAGIC_PRESERVE_ATIME)
587 return MAGIC_VERSION;
591 magic_setparam(struct magic_set *ms, int param, const void *val)
596 case MAGIC_PARAM_INDIR_MAX:
597 ms->indir_max = CAST(uint16_t, *CAST(const size_t *, val));
599 case MAGIC_PARAM_NAME_MAX:
600 ms->name_max = CAST(uint16_t, *CAST(const size_t *, val));
602 case MAGIC_PARAM_ELF_PHNUM_MAX:
603 ms->elf_phnum_max = CAST(uint16_t, *CAST(const size_t *, val));
605 case MAGIC_PARAM_ELF_SHNUM_MAX:
606 ms->elf_shnum_max = CAST(uint16_t, *CAST(const size_t *, val));
608 case MAGIC_PARAM_ELF_NOTES_MAX:
609 ms->elf_notes_max = CAST(uint16_t, *CAST(const size_t *, val));
611 case MAGIC_PARAM_REGEX_MAX:
612 ms->regex_max = CAST(uint16_t, *CAST(const size_t *, val));
614 case MAGIC_PARAM_BYTES_MAX:
615 ms->bytes_max = *CAST(const size_t *, val);
624 magic_getparam(struct magic_set *ms, int param, void *val)
629 case MAGIC_PARAM_INDIR_MAX:
630 *CAST(size_t *, val) = ms->indir_max;
632 case MAGIC_PARAM_NAME_MAX:
633 *CAST(size_t *, val) = ms->name_max;
635 case MAGIC_PARAM_ELF_PHNUM_MAX:
636 *CAST(size_t *, val) = ms->elf_phnum_max;
638 case MAGIC_PARAM_ELF_SHNUM_MAX:
639 *CAST(size_t *, val) = ms->elf_shnum_max;
641 case MAGIC_PARAM_ELF_NOTES_MAX:
642 *CAST(size_t *, val) = ms->elf_notes_max;
644 case MAGIC_PARAM_REGEX_MAX:
645 *CAST(size_t *, val) = ms->regex_max;
647 case MAGIC_PARAM_BYTES_MAX:
648 *CAST(size_t *, val) = ms->bytes_max;