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.99 2016/05/03 16:09:38 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);
141 char exepath[MAX_PATH];
142 GetModuleFileNameA(NULL, exepath, MAX_PATH);
143 PathRemoveFileSpecA(exepath);
144 if (stricmp(exepath, dllpath) == 0)
148 sp = strlen(dllpath);
149 if (sp > 3 && stricmp(&dllpath[sp - 3], "bin") == 0) {
150 _w32_append_path(hmagicpath,
151 "%s/../share/misc/magic.mgc", dllpath);
155 for (sp = 0; sp < __arraycount(trypaths); sp++)
156 _w32_append_path(hmagicpath, trypaths[sp], dllpath);
161 /* Placate GCC by offering a sacrificial previous prototype */
162 BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID);
165 DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
166 LPVOID lpvReserved __attribute__((__unused__)))
168 if (fdwReason == DLL_PROCESS_ATTACH)
169 _w32_dll_instance = hinstDLL;
175 get_default_magic(void)
177 static const char hmagic[] = "/.magic/magic.mgc";
178 static char *default_magic;
179 char *home, *hmagicpath;
186 default_magic = NULL;
188 if ((home = getenv("HOME")) == NULL)
191 if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0)
193 if (stat(hmagicpath, &st) == -1) {
195 if (asprintf(&hmagicpath, "%s/.magic", home) < 0)
197 if (stat(hmagicpath, &st) == -1)
199 if (S_ISDIR(st.st_mode)) {
201 if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0)
203 if (access(hmagicpath, R_OK) == -1)
208 if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0)
211 return default_magic;
213 default_magic = NULL;
221 default_magic = NULL;
224 /* First, try to get a magic file from user-application data */
225 if ((home = getenv("LOCALAPPDATA")) != NULL)
226 _w32_append_path(&hmagicpath, "%s%s", home, hmagic);
228 /* Second, try to get a magic file from the user profile data */
229 if ((home = getenv("USERPROFILE")) != NULL)
230 _w32_append_path(&hmagicpath,
231 "%s/Local Settings/Application Data%s", home, hmagic);
233 /* Third, try to get a magic file from Common Files */
234 if ((home = getenv("COMMONPROGRAMFILES")) != NULL)
235 _w32_append_path(&hmagicpath, "%s%s", home, hmagic);
237 /* Fourth, try to get magic file relative to exe location */
238 _w32_get_magic_relative_to(&hmagicpath, NULL);
240 /* Fifth, try to get magic file relative to dll location */
241 _w32_get_magic_relative_to(&hmagicpath, _w32_dll_instance);
243 /* Avoid MAGIC constant - it likely points to a file within MSys tree */
244 default_magic = hmagicpath;
245 return default_magic;
250 magic_getpath(const char *magicfile, int action)
252 if (magicfile != NULL)
255 magicfile = getenv("MAGIC");
256 if (magicfile != NULL)
259 return action == FILE_LOAD ? get_default_magic() : MAGIC;
262 public struct magic_set *
263 magic_open(int flags)
265 return file_ms_alloc(flags);
269 unreadable_info(struct magic_set *ms, mode_t md, const char *file)
272 /* We cannot open it, but we were able to stat it. */
273 if (access(file, W_OK) == 0)
274 if (file_printf(ms, "writable, ") == -1)
276 if (access(file, X_OK) == 0)
277 if (file_printf(ms, "executable, ") == -1)
281 if (file_printf(ms, "regular file, ") == -1)
283 if (file_printf(ms, "no read permission") == -1)
289 magic_close(struct magic_set *ms)
300 magic_load(struct magic_set *ms, const char *magicfile)
304 return file_apprentice(ms, magicfile, FILE_LOAD);
309 * Install a set of compiled magic buffers.
312 magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes,
317 return buffer_apprentice(ms, (struct magic **)bufs, sizes, nbufs);
322 magic_compile(struct magic_set *ms, const char *magicfile)
326 return file_apprentice(ms, magicfile, FILE_COMPILE);
330 magic_check(struct magic_set *ms, const char *magicfile)
334 return file_apprentice(ms, magicfile, FILE_CHECK);
338 magic_list(struct magic_set *ms, const char *magicfile)
342 return file_apprentice(ms, magicfile, FILE_LIST);
346 close_and_restore(const struct magic_set *ms, const char *name, int fd,
347 const struct stat *sb)
349 if (fd == STDIN_FILENO || name == NULL)
353 if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) {
355 * Try to restore access, modification times if read it.
356 * This is really *bad* because it will modify the status
357 * time of the file... And of course this will affect
361 struct timeval utsbuf[2];
362 (void)memset(utsbuf, 0, sizeof(utsbuf));
363 utsbuf[0].tv_sec = sb->st_atime;
364 utsbuf[1].tv_sec = sb->st_mtime;
366 (void) utimes(name, utsbuf); /* don't care if loses */
367 #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H)
368 struct utimbuf utbuf;
370 (void)memset(&utbuf, 0, sizeof(utbuf));
371 utbuf.actime = sb->st_atime;
372 utbuf.modtime = sb->st_mtime;
373 (void) utime(name, &utbuf); /* don't care if loses */
381 * find type of descriptor
384 magic_descriptor(struct magic_set *ms, int fd)
388 return file_or_fd(ms, NULL, fd);
392 * find type of named file
395 magic_file(struct magic_set *ms, const char *inname)
399 return file_or_fd(ms, inname, STDIN_FILENO);
403 file_or_fd(struct magic_set *ms, const char *inname, int fd)
408 ssize_t nbytes = 0; /* number of bytes read from a datafile */
410 off_t pos = (off_t)-1;
412 if (file_reset(ms) == -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);
439 if (inname == NULL) {
440 if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode))
443 pos = lseek(fd, (off_t)0, SEEK_CUR);
445 int flags = O_RDONLY|O_BINARY;
446 int okstat = stat(inname, &sb) == 0;
448 if (okstat && S_ISFIFO(sb.st_mode)) {
456 if ((fd = open(inname, flags)) < 0) {
459 * Can't stat, can't open. It may have been opened in
460 * fsmagic, so if the user doesn't have read permission,
461 * allow it to say so; otherwise an error was probably
462 * displayed in fsmagic.
464 if (!okstat && errno == EACCES) {
465 sb.st_mode = S_IFBLK;
470 unreadable_info(ms, sb.st_mode, inname) == -1)
476 if ((flags = fcntl(fd, F_GETFL)) != -1) {
477 flags &= ~O_NONBLOCK;
478 (void)fcntl(fd, F_SETFL, flags);
484 * try looking at the first ms->bytes_max bytes
489 while ((r = sread(fd, (void *)&buf[nbytes],
490 (size_t)(ms->bytes_max - nbytes), 1)) > 0) {
492 if (r < PIPE_BUF) break;
496 /* We can not read it, but we were able to stat it. */
497 if (unreadable_info(ms, sb.st_mode, inname) == -1)
504 /* Windows refuses to read from a big console buffer. */
507 _isatty(fd) ? 8 * 1024 :
510 if ((nbytes = read(fd, (char *)buf, howmany)) == -1) {
511 if (inname == NULL && fd != STDIN_FILENO)
512 file_error(ms, errno, "cannot read fd %d", fd);
514 file_error(ms, errno, "cannot read `%s'",
515 inname == NULL ? "/dev/stdin" : inname);
520 (void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
521 if (file_buffer(ms, fd, inname, buf, (size_t)nbytes) == -1)
527 if (pos != (off_t)-1)
528 (void)lseek(fd, pos, SEEK_SET);
529 close_and_restore(ms, inname, fd, &sb);
532 return rv == 0 ? file_getbuffer(ms) : NULL;
537 magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
541 if (file_reset(ms) == -1)
544 * The main work is done here!
545 * We have the file name and/or the data buffer to be identified.
547 if (file_buffer(ms, -1, NULL, buf, nb) == -1) {
550 return file_getbuffer(ms);
555 magic_error(struct magic_set *ms)
558 return "Magic database is not open";
559 return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
563 magic_errno(struct magic_set *ms)
567 return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
571 magic_setflags(struct magic_set *ms, int flags)
575 #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
576 if (flags & MAGIC_PRESERVE_ATIME)
586 return MAGIC_VERSION;
590 magic_setparam(struct magic_set *ms, int param, const void *val)
593 case MAGIC_PARAM_INDIR_MAX:
594 ms->indir_max = (uint16_t)*(const size_t *)val;
596 case MAGIC_PARAM_NAME_MAX:
597 ms->name_max = (uint16_t)*(const size_t *)val;
599 case MAGIC_PARAM_ELF_PHNUM_MAX:
600 ms->elf_phnum_max = (uint16_t)*(const size_t *)val;
602 case MAGIC_PARAM_ELF_SHNUM_MAX:
603 ms->elf_shnum_max = (uint16_t)*(const size_t *)val;
605 case MAGIC_PARAM_ELF_NOTES_MAX:
606 ms->elf_notes_max = (uint16_t)*(const size_t *)val;
608 case MAGIC_PARAM_REGEX_MAX:
609 ms->elf_notes_max = (uint16_t)*(const size_t *)val;
611 case MAGIC_PARAM_BYTES_MAX:
612 ms->bytes_max = *(const size_t *)val;
621 magic_getparam(struct magic_set *ms, int param, void *val)
624 case MAGIC_PARAM_INDIR_MAX:
625 *(size_t *)val = ms->indir_max;
627 case MAGIC_PARAM_NAME_MAX:
628 *(size_t *)val = ms->name_max;
630 case MAGIC_PARAM_ELF_PHNUM_MAX:
631 *(size_t *)val = ms->elf_phnum_max;
633 case MAGIC_PARAM_ELF_SHNUM_MAX:
634 *(size_t *)val = ms->elf_shnum_max;
636 case MAGIC_PARAM_ELF_NOTES_MAX:
637 *(size_t *)val = ms->elf_notes_max;
639 case MAGIC_PARAM_REGEX_MAX:
640 *(size_t *)val = ms->regex_max;
642 case MAGIC_PARAM_BYTES_MAX:
643 *(size_t *)val = ms->bytes_max;