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