xref: /netbsd-src/external/bsd/file/dist/src/magic.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: magic.c,v 1.5 2013/01/03 23:05:38 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
39 FILE_RCSID("@(#)$File: magic.c,v 1.77 2012/10/31 17:20:06 christos Exp $")
40 #else
41 __RCSID("$NetBSD: magic.c,v 1.5 2013/01/03 23:05:38 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 
80 private void close_and_restore(const struct magic_set *, const char *, int,
81     const struct stat *);
82 private int unreadable_info(struct magic_set *, mode_t, const char *);
83 private const char* get_default_magic(void);
84 #ifndef COMPILE_ONLY
85 private 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 
92 private const char *
93 get_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;
130 out:
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 
207 public const char *
208 magic_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 
220 public struct magic_set *
221 magic_open(int flags)
222 {
223 	return file_ms_alloc(flags);
224 }
225 
226 private int
227 unreadable_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 
244 public void
245 magic_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  */
255 public int
256 magic_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 
263 public int
264 magic_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 
271 public int
272 magic_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 
279 public int
280 magic_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 
287 private void
288 close_and_restore(const struct magic_set *ms, const char *name, int fd,
289     const struct stat *sb)
290 {
291 	if (fd == STDIN_FILENO)
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  */
325 public const char *
326 magic_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  */
336 public const char *
337 magic_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 
344 private const char *
345 file_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 
353 	/*
354 	 * one extra for terminating '\0', and
355 	 * some overlapping space for matches near EOF
356 	 */
357 #define SLOP (1 + sizeof(union VALUETYPE))
358 	if ((buf = CAST(unsigned char *, malloc(HOWMANY + SLOP))) == NULL)
359 		return NULL;
360 
361 	if (file_reset(ms) == -1)
362 		goto done;
363 
364 	switch (file_fsmagic(ms, inname, &sb)) {
365 	case -1:		/* error */
366 		goto done;
367 	case 0:			/* nothing found */
368 		break;
369 	default:		/* matched it and printed type */
370 		rv = 0;
371 		goto done;
372 	}
373 
374 	if (inname == NULL) {
375 		if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode))
376 			ispipe = 1;
377 	} else {
378 		int flags = O_RDONLY|O_BINARY;
379 
380 		if (stat(inname, &sb) == 0 && S_ISFIFO(sb.st_mode)) {
381 #ifdef O_NONBLOCK
382 			flags |= O_NONBLOCK;
383 #endif
384 			ispipe = 1;
385 		}
386 
387 		errno = 0;
388 		if ((fd = open(inname, flags)) < 0) {
389 			if (unreadable_info(ms, sb.st_mode, inname) == -1)
390 				goto done;
391 			rv = 0;
392 			goto done;
393 		}
394 #ifdef O_NONBLOCK
395 		if ((flags = fcntl(fd, F_GETFL)) != -1) {
396 			flags &= ~O_NONBLOCK;
397 			(void)fcntl(fd, F_SETFL, flags);
398 		}
399 #endif
400 	}
401 
402 	/*
403 	 * try looking at the first HOWMANY bytes
404 	 */
405 	if (ispipe) {
406 		ssize_t r = 0;
407 
408 		while ((r = sread(fd, (void *)&buf[nbytes],
409 		    (size_t)(HOWMANY - nbytes), 1)) > 0) {
410 			nbytes += r;
411 			if (r < PIPE_BUF) break;
412 		}
413 
414 		if (nbytes == 0) {
415 			/* We can not read it, but we were able to stat it. */
416 			if (unreadable_info(ms, sb.st_mode, inname) == -1)
417 				goto done;
418 			rv = 0;
419 			goto done;
420 		}
421 
422 	} else {
423 		if ((nbytes = read(fd, (char *)buf, HOWMANY)) == -1) {
424 			file_error(ms, errno, "cannot read `%s'", inname);
425 			goto done;
426 		}
427 	}
428 
429 	(void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
430 	if (file_buffer(ms, fd, inname, buf, (size_t)nbytes) == -1)
431 		goto done;
432 	rv = 0;
433 done:
434 	free(buf);
435 	close_and_restore(ms, inname, fd, &sb);
436 	return rv == 0 ? file_getbuffer(ms) : NULL;
437 }
438 
439 
440 public const char *
441 magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
442 {
443 	if (ms == NULL)
444 		return NULL;
445 	if (file_reset(ms) == -1)
446 		return NULL;
447 	/*
448 	 * The main work is done here!
449 	 * We have the file name and/or the data buffer to be identified.
450 	 */
451 	if (file_buffer(ms, -1, NULL, buf, nb) == -1) {
452 		return NULL;
453 	}
454 	return file_getbuffer(ms);
455 }
456 #endif
457 
458 public const char *
459 magic_error(struct magic_set *ms)
460 {
461 	if (ms == NULL)
462 		return "Magic database is not open";
463 	return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
464 }
465 
466 public int
467 magic_errno(struct magic_set *ms)
468 {
469 	if (ms == NULL)
470 		return EINVAL;
471 	return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
472 }
473 
474 public int
475 magic_setflags(struct magic_set *ms, int flags)
476 {
477 	if (ms == NULL)
478 		return -1;
479 #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
480 	if (flags & MAGIC_PRESERVE_ATIME)
481 		return -1;
482 #endif
483 	ms->flags = flags;
484 	return 0;
485 }
486