xref: /freebsd/contrib/file/src/funcs.c (revision 9fc5c47fa5c7fa58d61245f0408611943e613164)
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.83 2015/06/16 14:17:37 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 	file_error(ms, errno, "vasprintf failed");
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 	int mime = ms->flags & MAGIC_MIME;
182 	const unsigned char *ubuf = CAST(const unsigned char *, buf);
183 	unichar *u8buf = NULL;
184 	size_t ulen;
185 	const char *code = NULL;
186 	const char *code_mime = "binary";
187 	const char *type = "application/octet-stream";
188 	const char *def = "data";
189 	const char *ftype = NULL;
190 
191 	if (nb == 0) {
192 		def = "empty";
193 		type = "application/x-empty";
194 		goto simple;
195 	} else if (nb == 1) {
196 		def = "very short file (no magic)";
197 		goto simple;
198 	}
199 
200 	if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
201 		looks_text = file_encoding(ms, ubuf, nb, &u8buf, &ulen,
202 		    &code, &code_mime, &ftype);
203 	}
204 
205 #ifdef __EMX__
206 	if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
207 		switch (file_os2_apptype(ms, inname, buf, nb)) {
208 		case -1:
209 			return -1;
210 		case 0:
211 			break;
212 		default:
213 			return 1;
214 		}
215 	}
216 #endif
217 #if HAVE_FORK
218 	/* try compression stuff */
219 	if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0)
220 		if ((m = file_zmagic(ms, fd, inname, ubuf, nb)) != 0) {
221 			if ((ms->flags & MAGIC_DEBUG) != 0)
222 				(void)fprintf(stderr, "zmagic %d\n", m);
223 			goto done_encoding;
224 		}
225 #endif
226 	/* Check if we have a tar file */
227 	if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0)
228 		if ((m = file_is_tar(ms, ubuf, nb)) != 0) {
229 			if ((ms->flags & MAGIC_DEBUG) != 0)
230 				(void)fprintf(stderr, "tar %d\n", m);
231 			if (checkdone(ms, &rv))
232 				goto done;
233 		}
234 
235 	/* Check if we have a CDF file */
236 	if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0)
237 		if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) {
238 			if ((ms->flags & MAGIC_DEBUG) != 0)
239 				(void)fprintf(stderr, "cdf %d\n", m);
240 			if (checkdone(ms, &rv))
241 				goto done;
242 		}
243 
244 	/* try soft magic tests */
245 	if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0)
246 		if ((m = file_softmagic(ms, ubuf, nb, 0, NULL, BINTEST,
247 		    looks_text)) != 0) {
248 			if ((ms->flags & MAGIC_DEBUG) != 0)
249 				(void)fprintf(stderr, "softmagic %d\n", m);
250 #ifdef BUILTIN_ELF
251 			if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
252 			    nb > 5 && fd != -1) {
253 				/*
254 				 * We matched something in the file, so this
255 				 * *might* be an ELF file, and the file is at
256 				 * least 5 bytes long, so if it's an ELF file
257 				 * it has at least one byte past the ELF magic
258 				 * number - try extracting information from the
259 				 * ELF headers that cannot easily * be
260 				 * extracted with rules in the magic file.
261 				 */
262 				if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0)
263 					if ((ms->flags & MAGIC_DEBUG) != 0)
264 						(void)fprintf(stderr,
265 						    "elf %d\n", m);
266 			}
267 #endif
268 			if (checkdone(ms, &rv))
269 				goto done;
270 		}
271 
272 	/* try text properties */
273 	if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
274 
275 		if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) {
276 			if ((ms->flags & MAGIC_DEBUG) != 0)
277 				(void)fprintf(stderr, "ascmagic %d\n", m);
278 			if (checkdone(ms, &rv))
279 				goto done;
280 		}
281 	}
282 
283 simple:
284 	/* give up */
285 	m = 1;
286 	if ((!mime || (mime & MAGIC_MIME_TYPE)) &&
287 	    file_printf(ms, "%s", mime ? type : def) == -1) {
288 	    rv = -1;
289 	}
290  done:
291 	if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
292 		if (ms->flags & MAGIC_MIME_TYPE)
293 			if (file_printf(ms, "; charset=") == -1)
294 				rv = -1;
295 		if (file_printf(ms, "%s", code_mime) == -1)
296 			rv = -1;
297 	}
298 #if HAVE_FORK
299  done_encoding:
300 #endif
301 	free(u8buf);
302 	if (rv)
303 		return rv;
304 
305 	return m;
306 }
307 #endif
308 
309 protected int
310 file_reset(struct magic_set *ms)
311 {
312 	if (ms->mlist[0] == NULL) {
313 		file_error(ms, 0, "no magic files loaded");
314 		return -1;
315 	}
316 	if (ms->o.buf) {
317 		free(ms->o.buf);
318 		ms->o.buf = NULL;
319 	}
320 	if (ms->o.pbuf) {
321 		free(ms->o.pbuf);
322 		ms->o.pbuf = NULL;
323 	}
324 	ms->event_flags &= ~EVENT_HAD_ERR;
325 	ms->error = -1;
326 	return 0;
327 }
328 
329 #define OCTALIFY(n, o)	\
330 	/*LINTED*/ \
331 	(void)(*(n)++ = '\\', \
332 	*(n)++ = (((uint32_t)*(o) >> 6) & 3) + '0', \
333 	*(n)++ = (((uint32_t)*(o) >> 3) & 7) + '0', \
334 	*(n)++ = (((uint32_t)*(o) >> 0) & 7) + '0', \
335 	(o)++)
336 
337 protected const char *
338 file_getbuffer(struct magic_set *ms)
339 {
340 	char *pbuf, *op, *np;
341 	size_t psize, len;
342 
343 	if (ms->event_flags & EVENT_HAD_ERR)
344 		return NULL;
345 
346 	if (ms->flags & MAGIC_RAW)
347 		return ms->o.buf;
348 
349 	if (ms->o.buf == NULL)
350 		return NULL;
351 
352 	/* * 4 is for octal representation, + 1 is for NUL */
353 	len = strlen(ms->o.buf);
354 	if (len > (SIZE_MAX - 1) / 4) {
355 		file_oomem(ms, len);
356 		return NULL;
357 	}
358 	psize = len * 4 + 1;
359 	if ((pbuf = CAST(char *, realloc(ms->o.pbuf, psize))) == NULL) {
360 		file_oomem(ms, psize);
361 		return NULL;
362 	}
363 	ms->o.pbuf = pbuf;
364 
365 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
366 	{
367 		mbstate_t state;
368 		wchar_t nextchar;
369 		int mb_conv = 1;
370 		size_t bytesconsumed;
371 		char *eop;
372 		(void)memset(&state, 0, sizeof(mbstate_t));
373 
374 		np = ms->o.pbuf;
375 		op = ms->o.buf;
376 		eop = op + len;
377 
378 		while (op < eop) {
379 			bytesconsumed = mbrtowc(&nextchar, op,
380 			    (size_t)(eop - op), &state);
381 			if (bytesconsumed == (size_t)(-1) ||
382 			    bytesconsumed == (size_t)(-2)) {
383 				mb_conv = 0;
384 				break;
385 			}
386 
387 			if (iswprint(nextchar)) {
388 				(void)memcpy(np, op, bytesconsumed);
389 				op += bytesconsumed;
390 				np += bytesconsumed;
391 			} else {
392 				while (bytesconsumed-- > 0)
393 					OCTALIFY(np, op);
394 			}
395 		}
396 		*np = '\0';
397 
398 		/* Parsing succeeded as a multi-byte sequence */
399 		if (mb_conv != 0)
400 			return ms->o.pbuf;
401 	}
402 #endif
403 
404 	for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
405 		if (isprint((unsigned char)*op)) {
406 			*np++ = *op++;
407 		} else {
408 			OCTALIFY(np, op);
409 		}
410 	}
411 	*np = '\0';
412 	return ms->o.pbuf;
413 }
414 
415 protected int
416 file_check_mem(struct magic_set *ms, unsigned int level)
417 {
418 	size_t len;
419 
420 	if (level >= ms->c.len) {
421 		len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
422 		ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
423 		    malloc(len) :
424 		    realloc(ms->c.li, len));
425 		if (ms->c.li == NULL) {
426 			file_oomem(ms, len);
427 			return -1;
428 		}
429 	}
430 	ms->c.li[level].got_match = 0;
431 #ifdef ENABLE_CONDITIONALS
432 	ms->c.li[level].last_match = 0;
433 	ms->c.li[level].last_cond = COND_NONE;
434 #endif /* ENABLE_CONDITIONALS */
435 	return 0;
436 }
437 
438 protected size_t
439 file_printedlen(const struct magic_set *ms)
440 {
441 	return ms->o.buf == NULL ? 0 : strlen(ms->o.buf);
442 }
443 
444 protected int
445 file_replace(struct magic_set *ms, const char *pat, const char *rep)
446 {
447 	file_regex_t rx;
448 	int rc, rv = -1;
449 
450 	rc = file_regcomp(&rx, pat, REG_EXTENDED);
451 	if (rc) {
452 		file_regerror(&rx, rc, ms);
453 	} else {
454 		regmatch_t rm;
455 		int nm = 0;
456 		while (file_regexec(&rx, ms->o.buf, 1, &rm, 0) == 0) {
457 			ms->o.buf[rm.rm_so] = '\0';
458 			if (file_printf(ms, "%s%s", rep,
459 			    rm.rm_eo != 0 ? ms->o.buf + rm.rm_eo : "") == -1)
460 				goto out;
461 			nm++;
462 		}
463 		rv = nm;
464 	}
465 out:
466 	file_regfree(&rx);
467 	return rv;
468 }
469 
470 protected int
471 file_regcomp(file_regex_t *rx, const char *pat, int flags)
472 {
473 #ifdef USE_C_LOCALE
474 	rx->c_lc_ctype = newlocale(LC_CTYPE_MASK, "C", 0);
475 	assert(rx->c_lc_ctype != NULL);
476 	rx->old_lc_ctype = uselocale(rx->c_lc_ctype);
477 	assert(rx->old_lc_ctype != NULL);
478 #endif
479 	rx->pat = pat;
480 
481 	return rx->rc = regcomp(&rx->rx, pat, flags);
482 }
483 
484 protected int
485 file_regexec(file_regex_t *rx, const char *str, size_t nmatch,
486     regmatch_t* pmatch, int eflags)
487 {
488 	assert(rx->rc == 0);
489 	return regexec(&rx->rx, str, nmatch, pmatch, eflags);
490 }
491 
492 protected void
493 file_regfree(file_regex_t *rx)
494 {
495 	if (rx->rc == 0)
496 		regfree(&rx->rx);
497 #ifdef USE_C_LOCALE
498 	(void)uselocale(rx->old_lc_ctype);
499 	freelocale(rx->c_lc_ctype);
500 #endif
501 }
502 
503 protected void
504 file_regerror(file_regex_t *rx, int rc, struct magic_set *ms)
505 {
506 	char errmsg[512];
507 
508 	(void)regerror(rc, &rx->rx, errmsg, sizeof(errmsg));
509 	file_magerror(ms, "regex error %d for `%s', (%s)", rc, rx->pat,
510 	    errmsg);
511 }
512 
513 protected file_pushbuf_t *
514 file_push_buffer(struct magic_set *ms)
515 {
516 	file_pushbuf_t *pb;
517 
518 	if (ms->event_flags & EVENT_HAD_ERR)
519 		return NULL;
520 
521 	if ((pb = (CAST(file_pushbuf_t *, malloc(sizeof(*pb))))) == NULL)
522 		return NULL;
523 
524 	pb->buf = ms->o.buf;
525 	pb->offset = ms->offset;
526 
527 	ms->o.buf = NULL;
528 	ms->offset = 0;
529 
530 	return pb;
531 }
532 
533 protected char *
534 file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
535 {
536 	char *rbuf;
537 
538 	if (ms->event_flags & EVENT_HAD_ERR) {
539 		free(pb->buf);
540 		free(pb);
541 		return NULL;
542 	}
543 
544 	rbuf = ms->o.buf;
545 
546 	ms->o.buf = pb->buf;
547 	ms->offset = pb->offset;
548 
549 	free(pb);
550 	return rbuf;
551 }
552 
553 /*
554  * convert string to ascii printable format.
555  */
556 protected char *
557 file_printable(char *buf, size_t bufsiz, const char *str)
558 {
559 	char *ptr, *eptr;
560 	const unsigned char *s = (const unsigned char *)str;
561 
562 	for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) {
563 		if (isprint(*s)) {
564 			*ptr++ = *s;
565 			continue;
566 		}
567 		if (ptr >= eptr - 3)
568 			break;
569 		*ptr++ = '\\';
570 		*ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
571 		*ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
572 		*ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
573 	}
574 	*ptr = '\0';
575 	return buf;
576 }
577