xref: /freebsd/contrib/file/src/funcs.c (revision 4928135658a9d0eaee37003df6137ab363fcb0b4)
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 #include "file.h"
28 
29 #ifndef	lint
30 FILE_RCSID("@(#)$File: funcs.c,v 1.94 2017/11/02 20:25:39 christos Exp $")
31 #endif	/* lint */
32 
33 #include "magic.h"
34 #include <assert.h>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <ctype.h>
39 #if defined(HAVE_WCHAR_H)
40 #include <wchar.h>
41 #endif
42 #if defined(HAVE_WCTYPE_H)
43 #include <wctype.h>
44 #endif
45 #if defined(HAVE_LIMITS_H)
46 #include <limits.h>
47 #endif
48 
49 #ifndef SIZE_MAX
50 #define SIZE_MAX	((size_t)~0)
51 #endif
52 
53 /*
54  * Like printf, only we append to a buffer.
55  */
56 protected int
57 file_vprintf(struct magic_set *ms, const char *fmt, va_list ap)
58 {
59 	int len;
60 	char *buf, *newstr;
61 
62 	if (ms->event_flags & EVENT_HAD_ERR)
63 		return 0;
64 	len = vasprintf(&buf, fmt, ap);
65 	if (len < 0)
66 		goto out;
67 
68 	if (ms->o.buf != NULL) {
69 		len = asprintf(&newstr, "%s%s", ms->o.buf, buf);
70 		free(buf);
71 		if (len < 0)
72 			goto out;
73 		free(ms->o.buf);
74 		buf = newstr;
75 	}
76 	ms->o.buf = buf;
77 	return 0;
78 out:
79 	fprintf(stderr, "vasprintf failed (%s)", strerror(errno));
80 	return -1;
81 }
82 
83 protected int
84 file_printf(struct magic_set *ms, const char *fmt, ...)
85 {
86 	int rv;
87 	va_list ap;
88 
89 	va_start(ap, fmt);
90 	rv = file_vprintf(ms, fmt, ap);
91 	va_end(ap);
92 	return rv;
93 }
94 
95 /*
96  * error - print best error message possible
97  */
98 /*VARARGS*/
99 __attribute__((__format__(__printf__, 3, 0)))
100 private void
101 file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
102     size_t lineno)
103 {
104 	/* Only the first error is ok */
105 	if (ms->event_flags & EVENT_HAD_ERR)
106 		return;
107 	if (lineno != 0) {
108 		free(ms->o.buf);
109 		ms->o.buf = NULL;
110 		file_printf(ms, "line %" SIZE_T_FORMAT "u:", lineno);
111 	}
112 	if (ms->o.buf && *ms->o.buf)
113 		file_printf(ms, " ");
114 	file_vprintf(ms, f, va);
115 	if (error > 0)
116 		file_printf(ms, " (%s)", strerror(error));
117 	ms->event_flags |= EVENT_HAD_ERR;
118 	ms->error = error;
119 }
120 
121 /*VARARGS*/
122 protected void
123 file_error(struct magic_set *ms, int error, const char *f, ...)
124 {
125 	va_list va;
126 	va_start(va, f);
127 	file_error_core(ms, error, f, va, 0);
128 	va_end(va);
129 }
130 
131 /*
132  * Print an error with magic line number.
133  */
134 /*VARARGS*/
135 protected void
136 file_magerror(struct magic_set *ms, const char *f, ...)
137 {
138 	va_list va;
139 	va_start(va, f);
140 	file_error_core(ms, 0, f, va, ms->line);
141 	va_end(va);
142 }
143 
144 protected void
145 file_oomem(struct magic_set *ms, size_t len)
146 {
147 	file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
148 	    len);
149 }
150 
151 protected void
152 file_badseek(struct magic_set *ms)
153 {
154 	file_error(ms, errno, "error seeking");
155 }
156 
157 protected void
158 file_badread(struct magic_set *ms)
159 {
160 	file_error(ms, errno, "error reading");
161 }
162 
163 #ifndef COMPILE_ONLY
164 
165 static int
166 checkdone(struct magic_set *ms, int *rv)
167 {
168 	if ((ms->flags & MAGIC_CONTINUE) == 0)
169 		return 1;
170 	if (file_printf(ms, "\n- ") == -1)
171 		*rv = -1;
172 	return 0;
173 }
174 
175 /*ARGSUSED*/
176 protected int
177 file_buffer(struct magic_set *ms, int fd, const char *inname __attribute__ ((__unused__)),
178     const void *buf, size_t nb)
179 {
180 	int m = 0, rv = 0, looks_text = 0;
181 	const char *code = NULL;
182 	const char *code_mime = "binary";
183 	const char *type = "application/octet-stream";
184 	const char *def = "data";
185 	const char *ftype = NULL;
186 	struct buffer b;
187 
188 	buffer_init(&b, fd, buf, nb);
189 
190 	if (nb == 0) {
191 		def = "empty";
192 		type = "application/x-empty";
193 		goto simple;
194 	} else if (nb == 1) {
195 		def = "very short file (no magic)";
196 		goto simple;
197 	}
198 
199 	if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
200 		looks_text = file_encoding(ms, &b, NULL, 0,
201 		    &code, &code_mime, &ftype);
202 	}
203 
204 #ifdef __EMX__
205 	if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
206 		m = file_os2_apptype(ms, inname, &b);
207 		if ((ms->flags & MAGIC_DEBUG) != 0)
208 			(void)fprintf(stderr, "[try os2_apptype %d]\n", m);
209 		switch (m) {
210 		case -1:
211 			return -1;
212 		case 0:
213 			break;
214 		default:
215 			return 1;
216 		}
217 	}
218 #endif
219 #if HAVE_FORK
220 	/* try compression stuff */
221 	if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0) {
222 		m = file_zmagic(ms, &b, inname);
223 		if ((ms->flags & MAGIC_DEBUG) != 0)
224 			(void)fprintf(stderr, "[try zmagic %d]\n", m);
225 		if (m) {
226 			goto done_encoding;
227 		}
228 	}
229 #endif
230 	/* Check if we have a tar file */
231 	if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0) {
232 		m = file_is_tar(ms, &b);
233 		if ((ms->flags & MAGIC_DEBUG) != 0)
234 			(void)fprintf(stderr, "[try tar %d]\n", m);
235 		if (m) {
236 			if (checkdone(ms, &rv))
237 				goto done;
238 		}
239 	}
240 
241 	/* Check if we have a CDF file */
242 	if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
243 		m = file_trycdf(ms, &b);
244 		if ((ms->flags & MAGIC_DEBUG) != 0)
245 			(void)fprintf(stderr, "[try cdf %d]\n", m);
246 		if (m) {
247 			if (checkdone(ms, &rv))
248 				goto done;
249 		}
250 	}
251 
252 	/* try soft magic tests */
253 	if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
254 		m = file_softmagic(ms, &b, NULL, NULL, BINTEST, looks_text);
255 		if ((ms->flags & MAGIC_DEBUG) != 0)
256 			(void)fprintf(stderr, "[try softmagic %d]\n", m);
257 		if (m) {
258 #ifdef BUILTIN_ELF
259 			if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
260 			    nb > 5 && fd != -1) {
261 				/*
262 				 * We matched something in the file, so this
263 				 * *might* be an ELF file, and the file is at
264 				 * least 5 bytes long, so if it's an ELF file
265 				 * it has at least one byte past the ELF magic
266 				 * number - try extracting information from the
267 				 * ELF headers that cannot easily * be
268 				 * extracted with rules in the magic file.
269 				 */
270 				m = file_tryelf(ms, &b);
271 				if ((ms->flags & MAGIC_DEBUG) != 0)
272 					(void)fprintf(stderr, "[try elf %d]\n",
273 					    m);
274 			}
275 #endif
276 			if (checkdone(ms, &rv))
277 				goto done;
278 		}
279 	}
280 
281 	/* try text properties */
282 	if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
283 
284 		m = file_ascmagic(ms, &b, looks_text);
285 		if ((ms->flags & MAGIC_DEBUG) != 0)
286 			(void)fprintf(stderr, "[try ascmagic %d]\n", m);
287 		if (m) {
288 			if (checkdone(ms, &rv))
289 				goto done;
290 		}
291 	}
292 
293 simple:
294 	/* give up */
295 	m = 1;
296 	if (ms->flags & MAGIC_MIME) {
297 		if ((ms->flags & MAGIC_MIME_TYPE) &&
298 		    file_printf(ms, "%s", type) == -1)
299 			rv = -1;
300 	} else if (ms->flags & MAGIC_APPLE) {
301 		if (file_printf(ms, "UNKNUNKN") == -1)
302 			rv = -1;
303 	} else if (ms->flags & MAGIC_EXTENSION) {
304 		if (file_printf(ms, "???") == -1)
305 			rv = -1;
306 	} else {
307 		if (file_printf(ms, "%s", def) == -1)
308 			rv = -1;
309 	}
310  done:
311 	if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
312 		if (ms->flags & MAGIC_MIME_TYPE)
313 			if (file_printf(ms, "; charset=") == -1)
314 				rv = -1;
315 		if (file_printf(ms, "%s", code_mime) == -1)
316 			rv = -1;
317 	}
318 #if HAVE_FORK
319  done_encoding:
320 #endif
321 	buffer_fini(&b);
322 	if (rv)
323 		return rv;
324 
325 	return m;
326 }
327 #endif
328 
329 protected int
330 file_reset(struct magic_set *ms, int checkloaded)
331 {
332 	if (checkloaded && ms->mlist[0] == NULL) {
333 		file_error(ms, 0, "no magic files loaded");
334 		return -1;
335 	}
336 	if (ms->o.buf) {
337 		free(ms->o.buf);
338 		ms->o.buf = NULL;
339 	}
340 	if (ms->o.pbuf) {
341 		free(ms->o.pbuf);
342 		ms->o.pbuf = NULL;
343 	}
344 	ms->event_flags &= ~EVENT_HAD_ERR;
345 	ms->error = -1;
346 	return 0;
347 }
348 
349 #define OCTALIFY(n, o)	\
350 	/*LINTED*/ \
351 	(void)(*(n)++ = '\\', \
352 	*(n)++ = (((uint32_t)*(o) >> 6) & 3) + '0', \
353 	*(n)++ = (((uint32_t)*(o) >> 3) & 7) + '0', \
354 	*(n)++ = (((uint32_t)*(o) >> 0) & 7) + '0', \
355 	(o)++)
356 
357 protected const char *
358 file_getbuffer(struct magic_set *ms)
359 {
360 	char *pbuf, *op, *np;
361 	size_t psize, len;
362 
363 	if (ms->event_flags & EVENT_HAD_ERR)
364 		return NULL;
365 
366 	if (ms->flags & MAGIC_RAW)
367 		return ms->o.buf;
368 
369 	if (ms->o.buf == NULL)
370 		return NULL;
371 
372 	/* * 4 is for octal representation, + 1 is for NUL */
373 	len = strlen(ms->o.buf);
374 	if (len > (SIZE_MAX - 1) / 4) {
375 		file_oomem(ms, len);
376 		return NULL;
377 	}
378 	psize = len * 4 + 1;
379 	if ((pbuf = CAST(char *, realloc(ms->o.pbuf, psize))) == NULL) {
380 		file_oomem(ms, psize);
381 		return NULL;
382 	}
383 	ms->o.pbuf = pbuf;
384 
385 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
386 	{
387 		mbstate_t state;
388 		wchar_t nextchar;
389 		int mb_conv = 1;
390 		size_t bytesconsumed;
391 		char *eop;
392 		(void)memset(&state, 0, sizeof(mbstate_t));
393 
394 		np = ms->o.pbuf;
395 		op = ms->o.buf;
396 		eop = op + len;
397 
398 		while (op < eop) {
399 			bytesconsumed = mbrtowc(&nextchar, op,
400 			    (size_t)(eop - op), &state);
401 			if (bytesconsumed == (size_t)(-1) ||
402 			    bytesconsumed == (size_t)(-2)) {
403 				mb_conv = 0;
404 				break;
405 			}
406 
407 			if (iswprint(nextchar)) {
408 				(void)memcpy(np, op, bytesconsumed);
409 				op += bytesconsumed;
410 				np += bytesconsumed;
411 			} else {
412 				while (bytesconsumed-- > 0)
413 					OCTALIFY(np, op);
414 			}
415 		}
416 		*np = '\0';
417 
418 		/* Parsing succeeded as a multi-byte sequence */
419 		if (mb_conv != 0)
420 			return ms->o.pbuf;
421 	}
422 #endif
423 
424 	for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
425 		if (isprint((unsigned char)*op)) {
426 			*np++ = *op++;
427 		} else {
428 			OCTALIFY(np, op);
429 		}
430 	}
431 	*np = '\0';
432 	return ms->o.pbuf;
433 }
434 
435 protected int
436 file_check_mem(struct magic_set *ms, unsigned int level)
437 {
438 	size_t len;
439 
440 	if (level >= ms->c.len) {
441 		len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
442 		ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
443 		    malloc(len) :
444 		    realloc(ms->c.li, len));
445 		if (ms->c.li == NULL) {
446 			file_oomem(ms, len);
447 			return -1;
448 		}
449 	}
450 	ms->c.li[level].got_match = 0;
451 #ifdef ENABLE_CONDITIONALS
452 	ms->c.li[level].last_match = 0;
453 	ms->c.li[level].last_cond = COND_NONE;
454 #endif /* ENABLE_CONDITIONALS */
455 	return 0;
456 }
457 
458 protected size_t
459 file_printedlen(const struct magic_set *ms)
460 {
461 	return ms->o.buf == NULL ? 0 : strlen(ms->o.buf);
462 }
463 
464 protected int
465 file_replace(struct magic_set *ms, const char *pat, const char *rep)
466 {
467 	file_regex_t rx;
468 	int rc, rv = -1;
469 
470 	rc = file_regcomp(&rx, pat, REG_EXTENDED);
471 	if (rc) {
472 		file_regerror(&rx, rc, ms);
473 	} else {
474 		regmatch_t rm;
475 		int nm = 0;
476 		while (file_regexec(&rx, ms->o.buf, 1, &rm, 0) == 0) {
477 			ms->o.buf[rm.rm_so] = '\0';
478 			if (file_printf(ms, "%s%s", rep,
479 			    rm.rm_eo != 0 ? ms->o.buf + rm.rm_eo : "") == -1)
480 				goto out;
481 			nm++;
482 		}
483 		rv = nm;
484 	}
485 out:
486 	file_regfree(&rx);
487 	return rv;
488 }
489 
490 protected int
491 file_regcomp(file_regex_t *rx, const char *pat, int flags)
492 {
493 #ifdef USE_C_LOCALE
494 	rx->c_lc_ctype = newlocale(LC_CTYPE_MASK, "C", 0);
495 	assert(rx->c_lc_ctype != NULL);
496 	rx->old_lc_ctype = uselocale(rx->c_lc_ctype);
497 	assert(rx->old_lc_ctype != NULL);
498 #else
499 	rx->old_lc_ctype = setlocale(LC_CTYPE, "C");
500 #endif
501 	rx->pat = pat;
502 
503 	return rx->rc = regcomp(&rx->rx, pat, flags);
504 }
505 
506 protected int
507 file_regexec(file_regex_t *rx, const char *str, size_t nmatch,
508     regmatch_t* pmatch, int eflags)
509 {
510 	assert(rx->rc == 0);
511 	/* XXX: force initialization because glibc does not always do this */
512 	memset(pmatch, 0, nmatch * sizeof(*pmatch));
513 	return regexec(&rx->rx, str, nmatch, pmatch, eflags);
514 }
515 
516 protected void
517 file_regfree(file_regex_t *rx)
518 {
519 	if (rx->rc == 0)
520 		regfree(&rx->rx);
521 #ifdef USE_C_LOCALE
522 	(void)uselocale(rx->old_lc_ctype);
523 	freelocale(rx->c_lc_ctype);
524 #else
525 	(void)setlocale(LC_CTYPE, rx->old_lc_ctype);
526 #endif
527 }
528 
529 protected void
530 file_regerror(file_regex_t *rx, int rc, struct magic_set *ms)
531 {
532 	char errmsg[512];
533 
534 	(void)regerror(rc, &rx->rx, errmsg, sizeof(errmsg));
535 	file_magerror(ms, "regex error %d for `%s', (%s)", rc, rx->pat,
536 	    errmsg);
537 }
538 
539 protected file_pushbuf_t *
540 file_push_buffer(struct magic_set *ms)
541 {
542 	file_pushbuf_t *pb;
543 
544 	if (ms->event_flags & EVENT_HAD_ERR)
545 		return NULL;
546 
547 	if ((pb = (CAST(file_pushbuf_t *, malloc(sizeof(*pb))))) == NULL)
548 		return NULL;
549 
550 	pb->buf = ms->o.buf;
551 	pb->offset = ms->offset;
552 
553 	ms->o.buf = NULL;
554 	ms->offset = 0;
555 
556 	return pb;
557 }
558 
559 protected char *
560 file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
561 {
562 	char *rbuf;
563 
564 	if (ms->event_flags & EVENT_HAD_ERR) {
565 		free(pb->buf);
566 		free(pb);
567 		return NULL;
568 	}
569 
570 	rbuf = ms->o.buf;
571 
572 	ms->o.buf = pb->buf;
573 	ms->offset = pb->offset;
574 
575 	free(pb);
576 	return rbuf;
577 }
578 
579 /*
580  * convert string to ascii printable format.
581  */
582 protected char *
583 file_printable(char *buf, size_t bufsiz, const char *str)
584 {
585 	char *ptr, *eptr;
586 	const unsigned char *s = (const unsigned char *)str;
587 
588 	for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) {
589 		if (isprint(*s)) {
590 			*ptr++ = *s;
591 			continue;
592 		}
593 		if (ptr >= eptr - 3)
594 			break;
595 		*ptr++ = '\\';
596 		*ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
597 		*ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
598 		*ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
599 	}
600 	*ptr = '\0';
601 	return buf;
602 }
603