magic.c revision 1.1.1.6
1/*	$NetBSD: magic.c,v 1.1.1.6 2013/12/01 19:28:16 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.81 2013/11/29 15:42:51 christos Exp $")
40#else
41__RCSID("$NetBSD: magic.c,v 1.1.1.6 2013/12/01 19:28:16 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#ifdef HAVE_LIMITS_H
54#include <limits.h>	/* for PIPE_BUF */
55#endif
56
57#if defined(HAVE_UTIMES)
58# include <sys/time.h>
59#elif defined(HAVE_UTIME)
60# if defined(HAVE_SYS_UTIME_H)
61#  include <sys/utime.h>
62# elif defined(HAVE_UTIME_H)
63#  include <utime.h>
64# endif
65#endif
66
67#ifdef HAVE_UNISTD_H
68#include <unistd.h>	/* for read() */
69#endif
70
71#ifndef PIPE_BUF
72/* Get the PIPE_BUF from pathconf */
73#ifdef _PC_PIPE_BUF
74#define PIPE_BUF pathconf(".", _PC_PIPE_BUF)
75#else
76#define PIPE_BUF 512
77#endif
78#endif
79
80private void close_and_restore(const struct magic_set *, const char *, int,
81    const struct stat *);
82private int unreadable_info(struct magic_set *, mode_t, const char *);
83private const char* get_default_magic(void);
84#ifndef COMPILE_ONLY
85private const char *file_or_fd(struct magic_set *, const char *, int);
86#endif
87
88#ifndef	STDIN_FILENO
89#define	STDIN_FILENO	0
90#endif
91
92private const char *
93get_default_magic(void)
94{
95	static const char hmagic[] = "/.magic/magic.mgc";
96	static char *default_magic;
97	char *home, *hmagicpath;
98
99#ifndef WIN32
100	struct stat st;
101
102	if (default_magic) {
103		free(default_magic);
104		default_magic = NULL;
105	}
106	if ((home = getenv("HOME")) == NULL)
107		return MAGIC;
108
109	if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0)
110		return MAGIC;
111	if (stat(hmagicpath, &st) == -1) {
112		free(hmagicpath);
113		if (asprintf(&hmagicpath, "%s/.magic", home) < 0)
114			return MAGIC;
115		if (stat(hmagicpath, &st) == -1)
116			goto out;
117		if (S_ISDIR(st.st_mode)) {
118			free(hmagicpath);
119			if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0)
120				return MAGIC;
121			if (access(hmagicpath, R_OK) == -1)
122				goto out;
123		}
124	}
125
126	if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0)
127		goto out;
128	free(hmagicpath);
129	return default_magic;
130out:
131	default_magic = NULL;
132	free(hmagicpath);
133	return MAGIC;
134#else
135	char *hmagicp = hmagicpath;
136	char *tmppath = NULL;
137
138#define APPENDPATH() \
139	do { \
140		if (tmppath && access(tmppath, R_OK) != -1) { \
141			if (hmagicpath == NULL) \
142				hmagicpath = tmppath; \
143			else { \
144				if (asprintf(&hmagicp, "%s%c%s", hmagicpath, \
145				    PATHSEP, tmppath) >= 0) { \
146					free(hmagicpath); \
147					hmagicpath = hmagicp; \
148				} \
149				free(tmppath); \
150			} \
151			tmppath = NULL; \
152		} \
153	} while (/*CONSTCOND*/0)
154
155	if (default_magic) {
156		free(default_magic);
157		default_magic = NULL;
158	}
159
160	/* First, try to get user-specific magic file */
161	if ((home = getenv("LOCALAPPDATA")) == NULL) {
162		if ((home = getenv("USERPROFILE")) != NULL)
163			if (asprintf(&tmppath,
164			    "%s/Local Settings/Application Data%s", home,
165			    hmagic) < 0)
166				tmppath = NULL;
167	} else {
168		if (asprintf(&tmppath, "%s%s", home, hmagic) < 0)
169			tmppath = NULL;
170	}
171
172	APPENDPATH();
173
174	/* Second, try to get a magic file from Common Files */
175	if ((home = getenv("COMMONPROGRAMFILES")) != NULL) {
176		if (asprintf(&tmppath, "%s%s", home, hmagic) >= 0)
177			APPENDPATH();
178	}
179
180	/* Third, try to get magic file relative to dll location */
181	LPTSTR dllpath = malloc(sizeof(*dllpath) * (MAX_PATH + 1));
182	dllpath[MAX_PATH] = 0;	/* just in case long path gets truncated and not null terminated */
183	if (GetModuleFileNameA(NULL, dllpath, MAX_PATH)){
184		PathRemoveFileSpecA(dllpath);
185		if (strlen(dllpath) > 3 &&
186		    stricmp(&dllpath[strlen(dllpath) - 3], "bin") == 0) {
187			if (asprintf(&tmppath,
188			    "%s/../share/misc/magic.mgc", dllpath) >= 0)
189				APPENDPATH();
190		} else {
191			if (asprintf(&tmppath,
192			    "%s/share/misc/magic.mgc", dllpath) >= 0)
193				APPENDPATH();
194			else if (asprintf(&tmppath,
195			    "%s/magic.mgc", dllpath) >= 0)
196				APPENDPATH();
197		}
198	}
199
200	/* Don't put MAGIC constant - it likely points to a file within MSys
201	tree */
202	default_magic = hmagicpath;
203	return default_magic;
204#endif
205}
206
207public const char *
208magic_getpath(const char *magicfile, int action)
209{
210	if (magicfile != NULL)
211		return magicfile;
212
213	magicfile = getenv("MAGIC");
214	if (magicfile != NULL)
215		return magicfile;
216
217	return action == FILE_LOAD ? get_default_magic() : MAGIC;
218}
219
220public struct magic_set *
221magic_open(int flags)
222{
223	return file_ms_alloc(flags);
224}
225
226private int
227unreadable_info(struct magic_set *ms, mode_t md, const char *file)
228{
229	/* We cannot open it, but we were able to stat it. */
230	if (access(file, W_OK) == 0)
231		if (file_printf(ms, "writable, ") == -1)
232			return -1;
233	if (access(file, X_OK) == 0)
234		if (file_printf(ms, "executable, ") == -1)
235			return -1;
236	if (S_ISREG(md))
237		if (file_printf(ms, "regular file, ") == -1)
238			return -1;
239	if (file_printf(ms, "no read permission") == -1)
240		return -1;
241	return 0;
242}
243
244public void
245magic_close(struct magic_set *ms)
246{
247	if (ms == NULL)
248		return;
249	file_ms_free(ms);
250}
251
252/*
253 * load a magic file
254 */
255public int
256magic_load(struct magic_set *ms, const char *magicfile)
257{
258	if (ms == NULL)
259		return -1;
260	return file_apprentice(ms, magicfile, FILE_LOAD);
261}
262
263public int
264magic_compile(struct magic_set *ms, const char *magicfile)
265{
266	if (ms == NULL)
267		return -1;
268	return file_apprentice(ms, magicfile, FILE_COMPILE);
269}
270
271public int
272magic_check(struct magic_set *ms, const char *magicfile)
273{
274	if (ms == NULL)
275		return -1;
276	return file_apprentice(ms, magicfile, FILE_CHECK);
277}
278
279public int
280magic_list(struct magic_set *ms, const char *magicfile)
281{
282	if (ms == NULL)
283		return -1;
284	return file_apprentice(ms, magicfile, FILE_LIST);
285}
286
287private void
288close_and_restore(const struct magic_set *ms, const char *name, int fd,
289    const struct stat *sb)
290{
291	if (fd == STDIN_FILENO || name == NULL)
292		return;
293	(void) close(fd);
294
295	if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) {
296		/*
297		 * Try to restore access, modification times if read it.
298		 * This is really *bad* because it will modify the status
299		 * time of the file... And of course this will affect
300		 * backup programs
301		 */
302#ifdef HAVE_UTIMES
303		struct timeval  utsbuf[2];
304		(void)memset(utsbuf, 0, sizeof(utsbuf));
305		utsbuf[0].tv_sec = sb->st_atime;
306		utsbuf[1].tv_sec = sb->st_mtime;
307
308		(void) utimes(name, utsbuf); /* don't care if loses */
309#elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H)
310		struct utimbuf  utbuf;
311
312		(void)memset(&utbuf, 0, sizeof(utbuf));
313		utbuf.actime = sb->st_atime;
314		utbuf.modtime = sb->st_mtime;
315		(void) utime(name, &utbuf); /* don't care if loses */
316#endif
317	}
318}
319
320#ifndef COMPILE_ONLY
321
322/*
323 * find type of descriptor
324 */
325public const char *
326magic_descriptor(struct magic_set *ms, int fd)
327{
328	if (ms == NULL)
329		return NULL;
330	return file_or_fd(ms, NULL, fd);
331}
332
333/*
334 * find type of named file
335 */
336public const char *
337magic_file(struct magic_set *ms, const char *inname)
338{
339	if (ms == NULL)
340		return NULL;
341	return file_or_fd(ms, inname, STDIN_FILENO);
342}
343
344private const char *
345file_or_fd(struct magic_set *ms, const char *inname, int fd)
346{
347	int	rv = -1;
348	unsigned char *buf;
349	struct stat	sb;
350	ssize_t nbytes = 0;	/* number of bytes read from a datafile */
351	int	ispipe = 0;
352	off_t	pos = (off_t)-1;
353
354	/*
355	 * one extra for terminating '\0', and
356	 * some overlapping space for matches near EOF
357	 */
358#define SLOP (1 + sizeof(union VALUETYPE))
359	if ((buf = CAST(unsigned char *, malloc(HOWMANY + SLOP))) == NULL)
360		return NULL;
361
362	if (file_reset(ms) == -1)
363		goto done;
364
365	switch (file_fsmagic(ms, inname, &sb)) {
366	case -1:		/* error */
367		goto done;
368	case 0:			/* nothing found */
369		break;
370	default:		/* matched it and printed type */
371		rv = 0;
372		goto done;
373	}
374
375	if (inname == NULL) {
376		if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode))
377			ispipe = 1;
378		else
379			pos = lseek(fd, (off_t)0, SEEK_CUR);
380	} else {
381		int flags = O_RDONLY|O_BINARY;
382		int okstat = stat(inname, &sb) == 0;
383
384		if (okstat && S_ISFIFO(sb.st_mode)) {
385#ifdef O_NONBLOCK
386			flags |= O_NONBLOCK;
387#endif
388			ispipe = 1;
389		}
390
391		errno = 0;
392		if ((fd = open(inname, flags)) < 0) {
393			if (okstat &&
394			    unreadable_info(ms, sb.st_mode, inname) == -1)
395				goto done;
396			rv = 0;
397			goto done;
398		}
399#ifdef O_NONBLOCK
400		if ((flags = fcntl(fd, F_GETFL)) != -1) {
401			flags &= ~O_NONBLOCK;
402			(void)fcntl(fd, F_SETFL, flags);
403		}
404#endif
405	}
406
407	/*
408	 * try looking at the first HOWMANY bytes
409	 */
410	if (ispipe) {
411		ssize_t r = 0;
412
413		while ((r = sread(fd, (void *)&buf[nbytes],
414		    (size_t)(HOWMANY - nbytes), 1)) > 0) {
415			nbytes += r;
416			if (r < PIPE_BUF) break;
417		}
418
419		if (nbytes == 0) {
420			/* We can not read it, but we were able to stat it. */
421			if (unreadable_info(ms, sb.st_mode, inname) == -1)
422				goto done;
423			rv = 0;
424			goto done;
425		}
426
427	} else {
428		if ((nbytes = read(fd, (char *)buf, HOWMANY)) == -1) {
429			file_error(ms, errno, "cannot read `%s'", inname);
430			goto done;
431		}
432	}
433
434	(void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
435	if (file_buffer(ms, fd, inname, buf, (size_t)nbytes) == -1)
436		goto done;
437	rv = 0;
438done:
439	free(buf);
440	if (pos != (off_t)-1)
441		(void)lseek(fd, pos, SEEK_SET);
442	close_and_restore(ms, inname, fd, &sb);
443	return rv == 0 ? file_getbuffer(ms) : NULL;
444}
445
446
447public const char *
448magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
449{
450	if (ms == NULL)
451		return NULL;
452	if (file_reset(ms) == -1)
453		return NULL;
454	/*
455	 * The main work is done here!
456	 * We have the file name and/or the data buffer to be identified.
457	 */
458	if (file_buffer(ms, -1, NULL, buf, nb) == -1) {
459		return NULL;
460	}
461	return file_getbuffer(ms);
462}
463#endif
464
465public const char *
466magic_error(struct magic_set *ms)
467{
468	if (ms == NULL)
469		return "Magic database is not open";
470	return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
471}
472
473public int
474magic_errno(struct magic_set *ms)
475{
476	if (ms == NULL)
477		return EINVAL;
478	return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
479}
480
481public int
482magic_setflags(struct magic_set *ms, int flags)
483{
484	if (ms == NULL)
485		return -1;
486#if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
487	if (flags & MAGIC_PRESERVE_ATIME)
488		return -1;
489#endif
490	ms->flags = flags;
491	return 0;
492}
493
494public int
495magic_version(void)
496{
497	return MAGIC_VERSION;
498}
499