magic.c revision 1.16
1/*	$NetBSD: magic.c,v 1.16 2021/04/09 19:11:42 christos Exp $	*/
2
3/*
4 * Copyright (c) Christos Zoulas 2003.
5 * All Rights Reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice immediately at the beginning of the file, without modification,
12 *    this list of conditions, and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#ifdef WIN32
31#include <windows.h>
32#include <shlwapi.h>
33#endif
34
35#include "file.h"
36
37#ifndef	lint
38#if 0
39FILE_RCSID("@(#)$File: magic.c,v 1.114 2021/02/05 21:33:49 christos Exp $")
40#else
41__RCSID("$NetBSD: magic.c,v 1.16 2021/04/09 19:11:42 christos Exp $");
42#endif
43#endif	/* lint */
44
45#include "magic.h"
46
47#include <stdlib.h>
48#include <unistd.h>
49#include <string.h>
50#ifdef QUICK
51#include <sys/mman.h>
52#endif
53#include <limits.h>	/* for PIPE_BUF */
54
55#if defined(HAVE_UTIMES)
56# include <sys/time.h>
57#elif defined(HAVE_UTIME)
58# if defined(HAVE_SYS_UTIME_H)
59#  include <sys/utime.h>
60# elif defined(HAVE_UTIME_H)
61#  include <utime.h>
62# endif
63#endif
64
65#ifdef HAVE_UNISTD_H
66#include <unistd.h>	/* for read() */
67#endif
68
69#ifndef PIPE_BUF
70/* Get the PIPE_BUF from pathconf */
71#ifdef _PC_PIPE_BUF
72#define PIPE_BUF pathconf(".", _PC_PIPE_BUF)
73#else
74#define PIPE_BUF 512
75#endif
76#endif
77
78private void close_and_restore(const struct magic_set *, const char *, int,
79    const struct stat *);
80private int unreadable_info(struct magic_set *, mode_t, const char *);
81private const char* get_default_magic(void);
82#ifndef COMPILE_ONLY
83private const char *file_or_fd(struct magic_set *, const char *, int);
84#endif
85
86#ifndef	STDIN_FILENO
87#define	STDIN_FILENO	0
88#endif
89
90#ifdef WIN32
91/* HINSTANCE of this shared library. Needed for get_default_magic() */
92static HINSTANCE _w32_dll_instance = NULL;
93
94static void
95_w32_append_path(char **hmagicpath, const char *fmt, ...)
96{
97	char *tmppath;
98        char *newpath;
99	va_list ap;
100
101	va_start(ap, fmt);
102	if (vasprintf(&tmppath, fmt, ap) < 0) {
103		va_end(ap);
104		return;
105	}
106	va_end(ap);
107
108	if (access(tmppath, R_OK) == -1)
109		goto out;
110
111	if (*hmagicpath == NULL) {
112		*hmagicpath = tmppath;
113		return;
114	}
115
116	if (asprintf(&newpath, "%s%c%s", *hmagicpath, PATHSEP, tmppath) < 0)
117		goto out;
118
119	free(*hmagicpath);
120	free(tmppath);
121	*hmagicpath = newpath;
122	return;
123out:
124	free(tmppath);
125}
126
127static void
128_w32_get_magic_relative_to(char **hmagicpath, HINSTANCE module)
129{
130	static const char *trypaths[] = {
131		"%s/share/misc/magic.mgc",
132		"%s/magic.mgc",
133	};
134	LPSTR dllpath;
135	size_t sp;
136
137	dllpath = calloc(MAX_PATH + 1, sizeof(*dllpath));
138
139	if (!GetModuleFileNameA(module, dllpath, MAX_PATH))
140		goto out;
141
142	PathRemoveFileSpecA(dllpath);
143
144	if (module) {
145		char exepath[MAX_PATH];
146		GetModuleFileNameA(NULL, exepath, MAX_PATH);
147		PathRemoveFileSpecA(exepath);
148		if (stricmp(exepath, dllpath) == 0)
149			goto out;
150	}
151
152	sp = strlen(dllpath);
153	if (sp > 3 && stricmp(&dllpath[sp - 3], "bin") == 0) {
154		_w32_append_path(hmagicpath,
155		    "%s/../share/misc/magic.mgc", dllpath);
156		goto out;
157	}
158
159	for (sp = 0; sp < __arraycount(trypaths); sp++)
160		_w32_append_path(hmagicpath, trypaths[sp], dllpath);
161out:
162	free(dllpath);
163}
164
165/* Placate GCC by offering a sacrificial previous prototype */
166BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID);
167
168BOOL WINAPI
169DllMain(HINSTANCE hinstDLL, DWORD fdwReason,
170    LPVOID lpvReserved __attribute__((__unused__)))
171{
172	if (fdwReason == DLL_PROCESS_ATTACH)
173		_w32_dll_instance = hinstDLL;
174	return 1;
175}
176#endif
177
178private const char *
179get_default_magic(void)
180{
181	static const char hmagic[] = "/.magic/magic.mgc";
182	static char *default_magic;
183	char *home, *hmagicpath;
184
185#ifndef WIN32
186	struct stat st;
187
188	if (default_magic) {
189		free(default_magic);
190		default_magic = NULL;
191	}
192	if ((home = getenv("HOME")) == NULL)
193		return MAGIC;
194
195	if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0)
196		return MAGIC;
197	if (stat(hmagicpath, &st) == -1) {
198		free(hmagicpath);
199		if (asprintf(&hmagicpath, "%s/.magic", home) < 0)
200			return MAGIC;
201		if (stat(hmagicpath, &st) == -1)
202			goto out;
203		if (S_ISDIR(st.st_mode)) {
204			free(hmagicpath);
205			if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0)
206				return MAGIC;
207			if (access(hmagicpath, R_OK) == -1)
208				goto out;
209		}
210	}
211
212	if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0)
213		goto out;
214	free(hmagicpath);
215	return default_magic;
216out:
217	default_magic = NULL;
218	free(hmagicpath);
219	return MAGIC;
220#else
221	hmagicpath = NULL;
222
223	if (default_magic) {
224		free(default_magic);
225		default_magic = NULL;
226	}
227
228	/* First, try to get a magic file from user-application data */
229	if ((home = getenv("LOCALAPPDATA")) != NULL)
230		_w32_append_path(&hmagicpath, "%s%s", home, hmagic);
231
232	/* Second, try to get a magic file from the user profile data */
233	if ((home = getenv("USERPROFILE")) != NULL)
234		_w32_append_path(&hmagicpath,
235		    "%s/Local Settings/Application Data%s", home, hmagic);
236
237	/* Third, try to get a magic file from Common Files */
238	if ((home = getenv("COMMONPROGRAMFILES")) != NULL)
239		_w32_append_path(&hmagicpath, "%s%s", home, hmagic);
240
241	/* Fourth, try to get magic file relative to exe location */
242        _w32_get_magic_relative_to(&hmagicpath, NULL);
243
244	/* Fifth, try to get magic file relative to dll location */
245        _w32_get_magic_relative_to(&hmagicpath, _w32_dll_instance);
246
247	/* Avoid MAGIC constant - it likely points to a file within MSys tree */
248	default_magic = hmagicpath;
249	return default_magic;
250#endif
251}
252
253public const char *
254magic_getpath(const char *magicfile, int action)
255{
256	if (magicfile != NULL)
257		return magicfile;
258
259	magicfile = getenv("MAGIC");
260	if (magicfile != NULL)
261		return magicfile;
262
263	return action == FILE_LOAD ? get_default_magic() : MAGIC;
264}
265
266public struct magic_set *
267magic_open(int flags)
268{
269	return file_ms_alloc(flags);
270}
271
272private int
273unreadable_info(struct magic_set *ms, mode_t md, const char *file)
274{
275	if (file) {
276		/* We cannot open it, but we were able to stat it. */
277		if (access(file, W_OK) == 0)
278			if (file_printf(ms, "writable, ") == -1)
279				return -1;
280		if (access(file, X_OK) == 0)
281			if (file_printf(ms, "executable, ") == -1)
282				return -1;
283	}
284	if (S_ISREG(md))
285		if (file_printf(ms, "regular file, ") == -1)
286			return -1;
287	if (file_printf(ms, "no read permission") == -1)
288		return -1;
289	return 0;
290}
291
292public void
293magic_close(struct magic_set *ms)
294{
295	if (ms == NULL)
296		return;
297	file_ms_free(ms);
298}
299
300/*
301 * load a magic file
302 */
303public int
304magic_load(struct magic_set *ms, const char *magicfile)
305{
306	if (ms == NULL)
307		return -1;
308	return file_apprentice(ms, magicfile, FILE_LOAD);
309}
310
311#ifndef COMPILE_ONLY
312/*
313 * Install a set of compiled magic buffers.
314 */
315public int
316magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes,
317    size_t nbufs)
318{
319	if (ms == NULL)
320		return -1;
321	return buffer_apprentice(ms, RCAST(struct magic **, bufs),
322	    sizes, nbufs);
323}
324#endif
325
326public int
327magic_compile(struct magic_set *ms, const char *magicfile)
328{
329	if (ms == NULL)
330		return -1;
331	return file_apprentice(ms, magicfile, FILE_COMPILE);
332}
333
334public int
335magic_check(struct magic_set *ms, const char *magicfile)
336{
337	if (ms == NULL)
338		return -1;
339	return file_apprentice(ms, magicfile, FILE_CHECK);
340}
341
342public int
343magic_list(struct magic_set *ms, const char *magicfile)
344{
345	if (ms == NULL)
346		return -1;
347	return file_apprentice(ms, magicfile, FILE_LIST);
348}
349
350private void
351close_and_restore(const struct magic_set *ms, const char *name, int fd,
352    const struct stat *sb)
353{
354	if (fd == STDIN_FILENO || name == NULL)
355		return;
356	(void) close(fd);
357
358	if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) {
359		/*
360		 * Try to restore access, modification times if read it.
361		 * This is really *bad* because it will modify the status
362		 * time of the file... And of course this will affect
363		 * backup programs
364		 */
365#ifdef HAVE_UTIMES
366		struct timeval  utsbuf[2];
367		(void)memset(utsbuf, 0, sizeof(utsbuf));
368		utsbuf[0].tv_sec = sb->st_atime;
369		utsbuf[1].tv_sec = sb->st_mtime;
370
371		(void) utimes(name, utsbuf); /* don't care if loses */
372#elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H)
373		struct utimbuf  utbuf;
374
375		(void)memset(&utbuf, 0, sizeof(utbuf));
376		utbuf.actime = sb->st_atime;
377		utbuf.modtime = sb->st_mtime;
378		(void) utime(name, &utbuf); /* don't care if loses */
379#endif
380	}
381}
382
383#ifndef COMPILE_ONLY
384
385/*
386 * find type of descriptor
387 */
388public const char *
389magic_descriptor(struct magic_set *ms, int fd)
390{
391	if (ms == NULL)
392		return NULL;
393	return file_or_fd(ms, NULL, fd);
394}
395
396/*
397 * find type of named file
398 */
399public const char *
400magic_file(struct magic_set *ms, const char *inname)
401{
402	if (ms == NULL)
403		return NULL;
404	return file_or_fd(ms, inname, STDIN_FILENO);
405}
406
407private const char *
408file_or_fd(struct magic_set *ms, const char *inname, int fd)
409{
410	int	rv = -1;
411	unsigned char *buf;
412	struct stat	sb;
413	ssize_t nbytes = 0;	/* number of bytes read from a datafile */
414	int	ispipe = 0;
415	int	okstat = 0;
416	off_t	pos = CAST(off_t, -1);
417
418	if (file_reset(ms, 1) == -1)
419		goto out;
420
421	/*
422	 * one extra for terminating '\0', and
423	 * some overlapping space for matches near EOF
424	 */
425#define SLOP (1 + sizeof(union VALUETYPE))
426	if ((buf = CAST(unsigned char *, malloc(ms->bytes_max + SLOP))) == NULL)
427		return NULL;
428
429	switch (file_fsmagic(ms, inname, &sb)) {
430	case -1:		/* error */
431		goto done;
432	case 0:			/* nothing found */
433		break;
434	default:		/* matched it and printed type */
435		rv = 0;
436		goto done;
437	}
438
439#ifdef WIN32
440	/* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */
441	if (fd == STDIN_FILENO)
442		_setmode(STDIN_FILENO, O_BINARY);
443#endif
444	if (inname != NULL) {
445		int flags = O_RDONLY|O_BINARY|O_NONBLOCK|O_CLOEXEC;
446		errno = 0;
447		if ((fd = open(inname, flags)) < 0) {
448			okstat = stat(inname, &sb) == 0;
449			if (okstat && S_ISFIFO(sb.st_mode))
450				ispipe = 1;
451#ifdef WIN32
452			/*
453			 * Can't stat, can't open.  It may have been opened in
454			 * fsmagic, so if the user doesn't have read permission,
455			 * allow it to say so; otherwise an error was probably
456			 * displayed in fsmagic.
457			 */
458			if (!okstat && errno == EACCES) {
459				sb.st_mode = S_IFBLK;
460				okstat = 1;
461			}
462#endif
463			if (okstat &&
464			    unreadable_info(ms, sb.st_mode, inname) == -1)
465				goto done;
466			rv = 0;
467			goto done;
468		}
469#if O_CLOEXEC == 0
470		(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
471#endif
472	}
473
474	if (fd != -1) {
475		okstat = fstat(fd, &sb) == 0;
476		if (okstat && S_ISFIFO(sb.st_mode))
477			ispipe = 1;
478		if (inname == NULL)
479			pos = lseek(fd, CAST(off_t, 0), SEEK_CUR);
480	}
481
482	/*
483	 * try looking at the first ms->bytes_max bytes
484	 */
485	if (ispipe) {
486		if (fd != -1) {
487			ssize_t r = 0;
488
489			while ((r = sread(fd, RCAST(void *, &buf[nbytes]),
490			    CAST(size_t, ms->bytes_max - nbytes), 1)) > 0) {
491				nbytes += r;
492				if (r < PIPE_BUF) break;
493			}
494		}
495
496		if (nbytes == 0 && inname) {
497			/* We can not read it, but we were able to stat it. */
498			if (unreadable_info(ms, sb.st_mode, inname) == -1)
499				goto done;
500			rv = 0;
501			goto done;
502		}
503
504	} else if (fd != -1) {
505		/* Windows refuses to read from a big console buffer. */
506		size_t howmany =
507#if defined(WIN32)
508		    _isatty(fd) ? 8 * 1024 :
509#endif
510		    ms->bytes_max;
511		if ((nbytes = read(fd, RCAST(void *, buf), howmany)) == -1) {
512			if (inname == NULL && fd != STDIN_FILENO)
513				file_error(ms, errno, "cannot read fd %d", fd);
514			else
515				file_error(ms, errno, "cannot read `%s'",
516				    inname == NULL ? "/dev/stdin" : inname);
517			goto done;
518		}
519	}
520
521	(void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
522	if (file_buffer(ms, fd, okstat ? &sb : NULL, inname, buf, CAST(size_t, nbytes)) == -1)
523		goto done;
524	rv = 0;
525done:
526	free(buf);
527	if (fd != -1) {
528		if (pos != CAST(off_t, -1))
529			(void)lseek(fd, pos, SEEK_SET);
530		close_and_restore(ms, inname, fd, &sb);
531	}
532out:
533	return rv == 0 ? file_getbuffer(ms) : NULL;
534}
535
536
537public const char *
538magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
539{
540	if (ms == NULL)
541		return NULL;
542	if (file_reset(ms, 1) == -1)
543		return NULL;
544	/*
545	 * The main work is done here!
546	 * We have the file name and/or the data buffer to be identified.
547	 */
548	if (file_buffer(ms, -1, NULL, NULL, buf, nb) == -1) {
549		return NULL;
550	}
551	return file_getbuffer(ms);
552}
553#endif
554
555public const char *
556magic_error(struct magic_set *ms)
557{
558	if (ms == NULL)
559		return "Magic database is not open";
560	return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
561}
562
563public int
564magic_errno(struct magic_set *ms)
565{
566	if (ms == NULL)
567		return EINVAL;
568	return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
569}
570
571public int
572magic_getflags(struct magic_set *ms)
573{
574	if (ms == NULL)
575		return -1;
576
577	return ms->flags;
578}
579
580public int
581magic_setflags(struct magic_set *ms, int flags)
582{
583	if (ms == NULL)
584		return -1;
585#if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
586	if (flags & MAGIC_PRESERVE_ATIME)
587		return -1;
588#endif
589	ms->flags = flags;
590	return 0;
591}
592
593public int
594magic_version(void)
595{
596	return MAGIC_VERSION;
597}
598
599public int
600magic_setparam(struct magic_set *ms, int param, const void *val)
601{
602	if (ms == NULL)
603		return -1;
604	switch (param) {
605	case MAGIC_PARAM_INDIR_MAX:
606		ms->indir_max = CAST(uint16_t, *CAST(const size_t *, val));
607		return 0;
608	case MAGIC_PARAM_NAME_MAX:
609		ms->name_max = CAST(uint16_t, *CAST(const size_t *, val));
610		return 0;
611	case MAGIC_PARAM_ELF_PHNUM_MAX:
612		ms->elf_phnum_max = CAST(uint16_t, *CAST(const size_t *, val));
613		return 0;
614	case MAGIC_PARAM_ELF_SHNUM_MAX:
615		ms->elf_shnum_max = CAST(uint16_t, *CAST(const size_t *, val));
616		return 0;
617	case MAGIC_PARAM_ELF_NOTES_MAX:
618		ms->elf_notes_max = CAST(uint16_t, *CAST(const size_t *, val));
619		return 0;
620	case MAGIC_PARAM_REGEX_MAX:
621		ms->regex_max = CAST(uint16_t, *CAST(const size_t *, val));
622		return 0;
623	case MAGIC_PARAM_BYTES_MAX:
624		ms->bytes_max = *CAST(const size_t *, val);
625		return 0;
626	case MAGIC_PARAM_ENCODING_MAX:
627		ms->encoding_max = *CAST(const size_t *, val);
628		return 0;
629	default:
630		errno = EINVAL;
631		return -1;
632	}
633}
634
635public int
636magic_getparam(struct magic_set *ms, int param, void *val)
637{
638	if (ms == NULL)
639		return -1;
640	switch (param) {
641	case MAGIC_PARAM_INDIR_MAX:
642		*CAST(size_t *, val) = ms->indir_max;
643		return 0;
644	case MAGIC_PARAM_NAME_MAX:
645		*CAST(size_t *, val) = ms->name_max;
646		return 0;
647	case MAGIC_PARAM_ELF_PHNUM_MAX:
648		*CAST(size_t *, val) = ms->elf_phnum_max;
649		return 0;
650	case MAGIC_PARAM_ELF_SHNUM_MAX:
651		*CAST(size_t *, val) = ms->elf_shnum_max;
652		return 0;
653	case MAGIC_PARAM_ELF_NOTES_MAX:
654		*CAST(size_t *, val) = ms->elf_notes_max;
655		return 0;
656	case MAGIC_PARAM_REGEX_MAX:
657		*CAST(size_t *, val) = ms->regex_max;
658		return 0;
659	case MAGIC_PARAM_BYTES_MAX:
660		*CAST(size_t *, val) = ms->bytes_max;
661		return 0;
662	case MAGIC_PARAM_ENCODING_MAX:
663		*CAST(size_t *, val) = ms->encoding_max;
664		return 0;
665	default:
666		errno = EINVAL;
667		return -1;
668	}
669}
670