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.93 2015/04/15 23:47:58 christos Exp $")
48 #include <limits.h> /* for PIPE_BUF */
51 #if defined(HAVE_UTIMES)
52 # include <sys/time.h>
53 #elif defined(HAVE_UTIME)
54 # if defined(HAVE_SYS_UTIME_H)
55 # include <sys/utime.h>
56 # elif defined(HAVE_UTIME_H)
62 #include <unistd.h> /* for read() */
66 /* Get the PIPE_BUF from pathconf */
68 #define PIPE_BUF pathconf(".", _PC_PIPE_BUF)
74 private void close_and_restore(const struct magic_set *, const char *, int,
76 private int unreadable_info(struct magic_set *, mode_t, const char *);
77 private const char* get_default_magic(void);
79 private const char *file_or_fd(struct magic_set *, const char *, int);
83 #define STDIN_FILENO 0
87 /* HINSTANCE of this shared library. Needed for get_default_magic() */
88 static HINSTANCE _w32_dll_instance = NULL;
91 _w32_append_path(char **hmagicpath, const char *fmt, ...)
98 if (vasprintf(&tmppath, fmt, ap) < 0) {
104 if (access(tmppath, R_OK) == -1)
107 if (*hmagicpath == NULL) {
108 *hmagicpath = tmppath;
112 if (asprintf(&newpath, "%s%c%s", *hmagicpath, PATHSEP, tmppath) < 0)
117 *hmagicpath = newpath;
124 _w32_get_magic_relative_to(char **hmagicpath, HINSTANCE module)
126 static const char *trypaths[] = {
127 "%s/share/misc/magic.mgc",
133 dllpath = calloc(MAX_PATH + 1, sizeof(*dllpath));
135 if (!GetModuleFileNameA(module, dllpath, MAX_PATH))
138 PathRemoveFileSpecA(dllpath);
140 sp = strlen(dllpath);
141 if (sp > 3 && stricmp(&dllpath[sp - 3], "bin") == 0) {
142 _w32_append_path(hmagicpath,
143 "%s/../share/misc/magic.mgc", dllpath);
147 for (sp = 0; sp < __arraycount(trypaths); sp++)
148 _w32_append_path(hmagicpath, trypaths[sp], dllpath);
153 /* Placate GCC by offering a sacrificial previous prototype */
154 BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID);
157 DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
158 LPVOID lpvReserved __attribute__((__unused__)))
160 if (fdwReason == DLL_PROCESS_ATTACH)
161 _w32_dll_instance = hinstDLL;
167 get_default_magic(void)
169 static const char hmagic[] = "/.magic/magic.mgc";
170 static char *default_magic;
171 char *home, *hmagicpath;
178 default_magic = NULL;
180 if ((home = getenv("HOME")) == NULL)
183 if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0)
185 if (stat(hmagicpath, &st) == -1) {
187 if (asprintf(&hmagicpath, "%s/.magic", home) < 0)
189 if (stat(hmagicpath, &st) == -1)
191 if (S_ISDIR(st.st_mode)) {
193 if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0)
195 if (access(hmagicpath, R_OK) == -1)
200 if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0)
203 return default_magic;
205 default_magic = NULL;
213 default_magic = NULL;
216 /* First, try to get a magic file from user-application data */
217 if ((home = getenv("LOCALAPPDATA")) != NULL)
218 _w32_append_path(&hmagicpath, "%s%s", home, hmagic);
220 /* Second, try to get a magic file from the user profile data */
221 if ((home = getenv("USERPROFILE")) != NULL)
222 _w32_append_path(&hmagicpath,
223 "%s/Local Settings/Application Data%s", home, hmagic);
225 /* Third, try to get a magic file from Common Files */
226 if ((home = getenv("COMMONPROGRAMFILES")) != NULL)
227 _w32_append_path(&hmagicpath, "%s%s", home, hmagic);
229 /* Fourth, try to get magic file relative to exe location */
230 _w32_get_magic_relative_to(&hmagicpath, NULL);
232 /* Fifth, try to get magic file relative to dll location */
233 _w32_get_magic_relative_to(&hmagicpath, _w32_dll_instance);
235 /* Avoid MAGIC constant - it likely points to a file within MSys tree */
236 default_magic = hmagicpath;
237 return default_magic;
242 magic_getpath(const char *magicfile, int action)
244 if (magicfile != NULL)
247 magicfile = getenv("MAGIC");
248 if (magicfile != NULL)
251 return action == FILE_LOAD ? get_default_magic() : MAGIC;
254 public struct magic_set *
255 magic_open(int flags)
257 return file_ms_alloc(flags);
261 unreadable_info(struct magic_set *ms, mode_t md, const char *file)
264 /* We cannot open it, but we were able to stat it. */
265 if (access(file, W_OK) == 0)
266 if (file_printf(ms, "writable, ") == -1)
268 if (access(file, X_OK) == 0)
269 if (file_printf(ms, "executable, ") == -1)
273 if (file_printf(ms, "regular file, ") == -1)
275 if (file_printf(ms, "no read permission") == -1)
281 magic_close(struct magic_set *ms)
292 magic_load(struct magic_set *ms, const char *magicfile)
296 return file_apprentice(ms, magicfile, FILE_LOAD);
301 * Install a set of compiled magic buffers.
304 magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes,
309 return buffer_apprentice(ms, (struct magic **)bufs, sizes, nbufs);
314 magic_compile(struct magic_set *ms, const char *magicfile)
318 return file_apprentice(ms, magicfile, FILE_COMPILE);
322 magic_check(struct magic_set *ms, const char *magicfile)
326 return file_apprentice(ms, magicfile, FILE_CHECK);
330 magic_list(struct magic_set *ms, const char *magicfile)
334 return file_apprentice(ms, magicfile, FILE_LIST);
338 close_and_restore(const struct magic_set *ms, const char *name, int fd,
339 const struct stat *sb)
341 if (fd == STDIN_FILENO || name == NULL)
345 if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) {
347 * Try to restore access, modification times if read it.
348 * This is really *bad* because it will modify the status
349 * time of the file... And of course this will affect
353 struct timeval utsbuf[2];
354 (void)memset(utsbuf, 0, sizeof(utsbuf));
355 utsbuf[0].tv_sec = sb->st_atime;
356 utsbuf[1].tv_sec = sb->st_mtime;
358 (void) utimes(name, utsbuf); /* don't care if loses */
359 #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H)
360 struct utimbuf utbuf;
362 (void)memset(&utbuf, 0, sizeof(utbuf));
363 utbuf.actime = sb->st_atime;
364 utbuf.modtime = sb->st_mtime;
365 (void) utime(name, &utbuf); /* don't care if loses */
373 * find type of descriptor
376 magic_descriptor(struct magic_set *ms, int fd)
380 return file_or_fd(ms, NULL, fd);
384 * find type of named file
387 magic_file(struct magic_set *ms, const char *inname)
391 return file_or_fd(ms, inname, STDIN_FILENO);
395 file_or_fd(struct magic_set *ms, const char *inname, int fd)
400 ssize_t nbytes = 0; /* number of bytes read from a datafile */
402 off_t pos = (off_t)-1;
404 if (file_reset(ms) == -1)
408 * one extra for terminating '\0', and
409 * some overlapping space for matches near EOF
411 #define SLOP (1 + sizeof(union VALUETYPE))
412 if ((buf = CAST(unsigned char *, malloc(HOWMANY + SLOP))) == NULL)
415 switch (file_fsmagic(ms, inname, &sb)) {
418 case 0: /* nothing found */
420 default: /* matched it and printed type */
426 /* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */
427 if (fd == STDIN_FILENO)
428 _setmode(STDIN_FILENO, O_BINARY);
431 if (inname == NULL) {
432 if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode))
435 pos = lseek(fd, (off_t)0, SEEK_CUR);
437 int flags = O_RDONLY|O_BINARY;
438 int okstat = stat(inname, &sb) == 0;
440 if (okstat && S_ISFIFO(sb.st_mode)) {
448 if ((fd = open(inname, flags)) < 0) {
451 * Can't stat, can't open. It may have been opened in
452 * fsmagic, so if the user doesn't have read permission,
453 * allow it to say so; otherwise an error was probably
454 * displayed in fsmagic.
456 if (!okstat && errno == EACCES) {
457 sb.st_mode = S_IFBLK;
462 unreadable_info(ms, sb.st_mode, inname) == -1)
468 if ((flags = fcntl(fd, F_GETFL)) != -1) {
469 flags &= ~O_NONBLOCK;
470 (void)fcntl(fd, F_SETFL, flags);
476 * try looking at the first HOWMANY bytes
481 while ((r = sread(fd, (void *)&buf[nbytes],
482 (size_t)(HOWMANY - nbytes), 1)) > 0) {
484 if (r < PIPE_BUF) break;
488 /* We can not read it, but we were able to stat it. */
489 if (unreadable_info(ms, sb.st_mode, inname) == -1)
496 /* Windows refuses to read from a big console buffer. */
498 #if defined(WIN32) && HOWMANY > 8 * 1024
499 _isatty(fd) ? 8 * 1024 :
502 if ((nbytes = read(fd, (char *)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, inname, buf, (size_t)nbytes) == -1)
518 if (pos != (off_t)-1)
519 (void)lseek(fd, pos, SEEK_SET);
520 close_and_restore(ms, inname, fd, &sb);
522 return rv == 0 ? file_getbuffer(ms) : NULL;
527 magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
531 if (file_reset(ms) == -1)
534 * The main work is done here!
535 * We have the file name and/or the data buffer to be identified.
537 if (file_buffer(ms, -1, NULL, buf, nb) == -1) {
540 return file_getbuffer(ms);
545 magic_error(struct magic_set *ms)
548 return "Magic database is not open";
549 return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
553 magic_errno(struct magic_set *ms)
557 return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
561 magic_setflags(struct magic_set *ms, int flags)
565 #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
566 if (flags & MAGIC_PRESERVE_ATIME)
576 return MAGIC_VERSION;
580 magic_setparam(struct magic_set *ms, int param, const void *val)
583 case MAGIC_PARAM_INDIR_MAX:
584 ms->indir_max = (uint16_t)*(const size_t *)val;
586 case MAGIC_PARAM_NAME_MAX:
587 ms->name_max = (uint16_t)*(const size_t *)val;
589 case MAGIC_PARAM_ELF_PHNUM_MAX:
590 ms->elf_phnum_max = (uint16_t)*(const size_t *)val;
592 case MAGIC_PARAM_ELF_SHNUM_MAX:
593 ms->elf_shnum_max = (uint16_t)*(const size_t *)val;
595 case MAGIC_PARAM_ELF_NOTES_MAX:
596 ms->elf_notes_max = (uint16_t)*(const size_t *)val;
605 magic_getparam(struct magic_set *ms, int param, void *val)
608 case MAGIC_PARAM_INDIR_MAX:
609 *(size_t *)val = ms->indir_max;
611 case MAGIC_PARAM_NAME_MAX:
612 *(size_t *)val = ms->name_max;
614 case MAGIC_PARAM_ELF_PHNUM_MAX:
615 *(size_t *)val = ms->elf_phnum_max;
617 case MAGIC_PARAM_ELF_SHNUM_MAX:
618 *(size_t *)val = ms->elf_shnum_max;
620 case MAGIC_PARAM_ELF_NOTES_MAX:
621 *(size_t *)val = ms->elf_notes_max;