xref: /PHP-8.3/ext/fileinfo/libmagic/funcs.c (revision 25bb8178)
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.131 2022/09/13 18:46:07 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 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>	/* for pipe2() */
41 #endif
42 #if defined(HAVE_WCHAR_H)
43 #include <wchar.h>
44 #endif
45 #if defined(HAVE_WCTYPE_H)
46 #include <wctype.h>
47 #endif
48 #include <limits.h>
49 
50 #ifndef SIZE_MAX
51 #define SIZE_MAX	((size_t)~0)
52 #endif
53 
54 protected char *
file_copystr(char * buf,size_t blen,size_t width,const char * str)55 file_copystr(char *buf, size_t blen, size_t width, const char *str)
56 {
57 	if (blen == 0)
58 		return buf;
59 	if (width >= blen)
60 		width = blen - 1;
61 	memcpy(buf, str, width);
62 	buf[width] = '\0';
63 	return buf;
64 }
65 
66 private void
file_clearbuf(struct magic_set * ms)67 file_clearbuf(struct magic_set *ms)
68 {
69 	efree(ms->o.buf);
70 	ms->o.buf = NULL;
71 	ms->o.blen = 0;
72 }
73 
74 private int
file_checkfield(char * msg,size_t mlen,const char * what,const char ** pp)75 file_checkfield(char *msg, size_t mlen, const char *what, const char **pp)
76 {
77 	const char *p = *pp;
78 	int fw = 0;
79 
80 	while (*p && isdigit((unsigned char)*p))
81 		fw = fw * 10 + (*p++ - '0');
82 
83 	*pp = p;
84 
85 	if (fw < 1024)
86 		return 1;
87 	if (msg)
88 		snprintf(msg, mlen, "field %s too large: %d", what, fw);
89 
90 	return 0;
91 }
92 
93 protected int
file_checkfmt(char * msg,size_t mlen,const char * fmt)94 file_checkfmt(char *msg, size_t mlen, const char *fmt)
95 {
96 	const char *p;
97 	for (p = fmt; *p; p++) {
98 		if (*p != '%')
99 			continue;
100 		if (*++p == '%')
101 			continue;
102 		// Skip uninteresting.
103 		while (strchr("#0.'+- ", *p) != NULL)
104 			p++;
105 		if (*p == '*') {
106 			if (msg)
107 				snprintf(msg, mlen, "* not allowed in format");
108 			return -1;
109 		}
110 
111 		if (!file_checkfield(msg, mlen, "width", &p))
112 			return -1;
113 
114 		if (*p == '.') {
115 			p++;
116 			if (!file_checkfield(msg, mlen, "precision", &p))
117 				return -1;
118 		}
119 
120 		if (!isalpha((unsigned char)*p)) {
121 			if (msg)
122 				snprintf(msg, mlen, "bad format char: %c", *p);
123 			return -1;
124 		}
125 	}
126 	return 0;
127 }
128 
129 /*
130  * Like printf, only we append to a buffer.
131  */
132 protected int
file_vprintf(struct magic_set * ms,const char * fmt,va_list ap)133 file_vprintf(struct magic_set *ms, const char *fmt, va_list ap)
134 {
135 	size_t len;
136 	char *buf, *newstr;
137 	char tbuf[1024];
138 
139 	if (ms->event_flags & EVENT_HAD_ERR)
140 		return 0;
141 
142 	if (file_checkfmt(tbuf, sizeof(tbuf), fmt)) {
143 		file_clearbuf(ms);
144 		file_error(ms, 0, "Bad magic format `%s' (%s)", fmt, tbuf);
145 		return -1;
146 	}
147 
148 	len = vspprintf(&buf, 0, fmt, ap);
149 	if (len > 1024 || len + ms->o.blen > 1024 * 1024) {
150 		size_t blen = ms->o.blen;
151 		if (buf) efree(buf);
152 		file_clearbuf(ms);
153 		file_error(ms, 0, "Output buffer space exceeded %" SIZE_T_FORMAT "u+%"
154 		    SIZE_T_FORMAT "u", len, blen);
155 		return -1;
156 	}
157 
158 	if (ms->o.buf != NULL) {
159 		len = spprintf(&newstr, 0, "%s%s", ms->o.buf, buf);
160 		efree(buf);
161 		efree(ms->o.buf);
162 		buf = newstr;
163 	}
164 	ms->o.buf = buf;
165 	ms->o.blen = len;
166 	return 0;
167 }
168 
169 protected int
file_printf(struct magic_set * ms,const char * fmt,...)170 file_printf(struct magic_set *ms, const char *fmt, ...)
171 {
172 	int rv;
173 	va_list ap;
174 
175 	va_start(ap, fmt);
176 	rv = file_vprintf(ms, fmt, ap);
177 	va_end(ap);
178 	return rv;
179 }
180 
181 /*
182  * error - print best error message possible
183  */
184 /*VARARGS*/
185 __attribute__((__format__(__printf__, 3, 0)))
186 private void
file_error_core(struct magic_set * ms,int error,const char * f,va_list va,size_t lineno)187 file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
188     size_t lineno)
189 {
190 	/* Only the first error is ok */
191 	if (ms->event_flags & EVENT_HAD_ERR)
192 		return;
193 	if (lineno != 0) {
194 		file_clearbuf(ms);
195 		(void)file_printf(ms, "line %" SIZE_T_FORMAT "u:", lineno);
196 	}
197 	if (ms->o.buf && *ms->o.buf)
198 		(void)file_printf(ms, " ");
199 	(void)file_vprintf(ms, f, va);
200 	if (error > 0)
201 		(void)file_printf(ms, " (%s)", strerror(error));
202 	ms->event_flags |= EVENT_HAD_ERR;
203 	ms->error = error;
204 }
205 
206 /*VARARGS*/
207 protected void
file_error(struct magic_set * ms,int error,const char * f,...)208 file_error(struct magic_set *ms, int error, const char *f, ...)
209 {
210 	va_list va;
211 	va_start(va, f);
212 	file_error_core(ms, error, f, va, 0);
213 	va_end(va);
214 }
215 
216 /*
217  * Print an error with magic line number.
218  */
219 /*VARARGS*/
220 protected void
file_magerror(struct magic_set * ms,const char * f,...)221 file_magerror(struct magic_set *ms, const char *f, ...)
222 {
223 	va_list va;
224 	va_start(va, f);
225 	file_error_core(ms, 0, f, va, ms->line);
226 	va_end(va);
227 }
228 
229 protected void
file_oomem(struct magic_set * ms,size_t len)230 file_oomem(struct magic_set *ms, size_t len)
231 {
232 	file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
233 	    len);
234 }
235 
236 protected void
file_badseek(struct magic_set * ms)237 file_badseek(struct magic_set *ms)
238 {
239 	file_error(ms, errno, "error seeking");
240 }
241 
242 protected void
file_badread(struct magic_set * ms)243 file_badread(struct magic_set *ms)
244 {
245 	file_error(ms, errno, "error reading");
246 }
247 
248 #ifndef COMPILE_ONLY
249 #define FILE_SEPARATOR "\n- "
250 
251 protected int
file_separator(struct magic_set * ms)252 file_separator(struct magic_set *ms)
253 {
254 	return file_printf(ms, FILE_SEPARATOR);
255 }
256 
257 static void
trim_separator(struct magic_set * ms)258 trim_separator(struct magic_set *ms)
259 {
260 	size_t l;
261 
262 	if (ms->o.buf == NULL)
263 		return;
264 
265 	l = strlen(ms->o.buf);
266 	if (l < sizeof(FILE_SEPARATOR))
267 		return;
268 
269 	l -= sizeof(FILE_SEPARATOR) - 1;
270 	if (strcmp(ms->o.buf + l, FILE_SEPARATOR) != 0)
271 		return;
272 
273 	ms->o.buf[l] = '\0';
274 }
275 
276 static int
checkdone(struct magic_set * ms,int * rv)277 checkdone(struct magic_set *ms, int *rv)
278 {
279 	if ((ms->flags & MAGIC_CONTINUE) == 0)
280 		return 1;
281 	if (file_separator(ms) == -1)
282 		*rv = -1;
283 	return 0;
284 }
285 
286 protected int
file_default(struct magic_set * ms,size_t nb)287 file_default(struct magic_set *ms, size_t nb)
288 {
289 	if (ms->flags & MAGIC_MIME) {
290 		if ((ms->flags & MAGIC_MIME_TYPE) &&
291 		    file_printf(ms, "application/%s",
292 			nb ? "octet-stream" : "x-empty") == -1)
293 			return -1;
294 		return 1;
295 	}
296 	if (ms->flags & MAGIC_APPLE) {
297 		if (file_printf(ms, "UNKNUNKN") == -1)
298 			return -1;
299 		return 1;
300 	}
301 	if (ms->flags & MAGIC_EXTENSION) {
302 		if (file_printf(ms, "???") == -1)
303 			return -1;
304 		return 1;
305 	}
306 	return 0;
307 }
308 
309 /*
310  * The magic detection functions return:
311  *	 1: found
312  *	 0: not found
313  *	-1: error
314  */
315 /*ARGSUSED*/
316 protected int
file_buffer(struct magic_set * ms,php_stream * stream,zend_stat_t * st,const char * inname,const void * buf,size_t nb)317 file_buffer(struct magic_set *ms, php_stream *stream, zend_stat_t *st,
318     const char *inname,
319     const void *buf, size_t nb)
320 {
321 	int m = 0, rv = 0, looks_text = 0;
322 	const char *code = NULL;
323 	const char *code_mime = "binary";
324 	const char *def = "data";
325 	const char *ftype = NULL;
326 	char *rbuf = NULL;
327 	struct buffer b;
328 	int fd = -1;
329 
330 	if (stream) {
331 #ifdef _WIN64
332 		php_socket_t _fd = fd;
333 #else
334 		int _fd;
335 #endif
336 		int _ret = php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&_fd, 0);
337 		if (SUCCESS == _ret) {
338 			fd = (int)_fd;
339 		}
340 	}
341 
342 	buffer_init(&b, fd, st, buf, nb);
343 	ms->mode = b.st.st_mode;
344 
345 	if (nb == 0) {
346 		def = "empty";
347 		goto simple;
348 	} else if (nb == 1) {
349 		def = "very short file (no magic)";
350 		goto simple;
351 	}
352 
353 	if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
354 		looks_text = file_encoding(ms, &b, NULL, 0,
355 		    &code, &code_mime, &ftype);
356 	}
357 
358 #ifdef __EMX__
359 	if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
360 		m = file_os2_apptype(ms, inname, &b);
361 		if ((ms->flags & MAGIC_DEBUG) != 0)
362 			(void)fprintf(stderr, "[try os2_apptype %d]\n", m);
363 		switch (m) {
364 		case -1:
365 			return -1;
366 		case 0:
367 			break;
368 		default:
369 			return 1;
370 		}
371 	}
372 #endif
373 
374 #if PHP_FILEINFO_UNCOMPRESS
375 	/* try compression stuff */
376 	if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0) {
377 		m = file_zmagic(ms, &b, inname);
378 		if ((ms->flags & MAGIC_DEBUG) != 0)
379 			(void)fprintf(stderr, "[try zmagic %d]\n", m);
380 		if (m) {
381 			goto done_encoding;
382 		}
383 	}
384 #endif
385 	/* Check if we have a tar file */
386 	if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0) {
387 		m = file_is_tar(ms, &b);
388 		if ((ms->flags & MAGIC_DEBUG) != 0)
389 			(void)fprintf(stderr, "[try tar %d]\n", m);
390 		if (m) {
391 			if (checkdone(ms, &rv))
392 				goto done;
393 		}
394 	}
395 
396 	/* Check if we have a JSON file */
397 	if ((ms->flags & MAGIC_NO_CHECK_JSON) == 0) {
398 		m = file_is_json(ms, &b);
399 		if ((ms->flags & MAGIC_DEBUG) != 0)
400 			(void)fprintf(stderr, "[try json %d]\n", m);
401 		if (m) {
402 			if (checkdone(ms, &rv))
403 				goto done;
404 		}
405 	}
406 
407 	/* Check if we have a CSV file */
408 	if ((ms->flags & MAGIC_NO_CHECK_CSV) == 0) {
409 		m = file_is_csv(ms, &b, looks_text);
410 		if ((ms->flags & MAGIC_DEBUG) != 0)
411 			(void)fprintf(stderr, "[try csv %d]\n", m);
412 		if (m) {
413 			if (checkdone(ms, &rv))
414 				goto done;
415 		}
416 	}
417 
418 	/* Check if we have a CDF file */
419 	if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
420 		m = file_trycdf(ms, &b);
421 		if ((ms->flags & MAGIC_DEBUG) != 0)
422 			(void)fprintf(stderr, "[try cdf %d]\n", m);
423 		if (m) {
424 			if (checkdone(ms, &rv))
425 				goto done;
426 		}
427 	}
428 #ifdef BUILTIN_ELF
429 	if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && nb > 5 && fd != -1) {
430 		file_pushbuf_t *pb;
431 		/*
432 		 * We matched something in the file, so this
433 		 * *might* be an ELF file, and the file is at
434 		 * least 5 bytes long, so if it's an ELF file
435 		 * it has at least one byte past the ELF magic
436 		 * number - try extracting information from the
437 		 * ELF headers that cannot easily be  extracted
438 		 * with rules in the magic file. We we don't
439 		 * print the information yet.
440 		 */
441 		if ((pb = file_push_buffer(ms)) == NULL)
442 			return -1;
443 
444 		rv = file_tryelf(ms, &b);
445 		rbuf = file_pop_buffer(ms, pb);
446 		if (rv == -1) {
447 			free(rbuf);
448 			rbuf = NULL;
449 		}
450 		if ((ms->flags & MAGIC_DEBUG) != 0)
451 			(void)fprintf(stderr, "[try elf %d]\n", m);
452 	}
453 #endif
454 
455 	/* try soft magic tests */
456 	if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
457 		m = file_softmagic(ms, &b, NULL, NULL, BINTEST, looks_text);
458 		if ((ms->flags & MAGIC_DEBUG) != 0)
459 			(void)fprintf(stderr, "[try softmagic %d]\n", m);
460 		if (m == 1 && rbuf) {
461 			if (file_printf(ms, "%s", rbuf) == -1)
462 				goto done;
463 		}
464 		if (m) {
465 			if (checkdone(ms, &rv))
466 				goto done;
467 		}
468 	}
469 
470 	/* try text properties */
471 	if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
472 
473 		m = file_ascmagic(ms, &b, looks_text);
474 		if ((ms->flags & MAGIC_DEBUG) != 0)
475 			(void)fprintf(stderr, "[try ascmagic %d]\n", m);
476 		if (m) {
477 			goto done;
478 		}
479 	}
480 
481 simple:
482 	/* give up */
483 	if (m == 0) {
484 		m = 1;
485 		rv = file_default(ms, nb);
486 		if (rv == 0)
487 			if (file_printf(ms, "%s", def) == -1)
488 				rv = -1;
489 	}
490  done:
491 	trim_separator(ms);
492 	if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
493 		if (ms->flags & MAGIC_MIME_TYPE)
494 			if (file_printf(ms, "; charset=") == -1)
495 				rv = -1;
496 		if (file_printf(ms, "%s", code_mime) == -1)
497 			rv = -1;
498 	}
499 #if PHP_FILEINFO_UNCOMPRESS
500  done_encoding:
501 #endif
502 	efree(rbuf);
503 	buffer_fini(&b);
504 	if (rv)
505 		return rv;
506 
507 	return m;
508 }
509 #endif
510 
511 protected int
file_reset(struct magic_set * ms,int checkloaded)512 file_reset(struct magic_set *ms, int checkloaded)
513 {
514 	if (checkloaded && ms->mlist[0] == NULL) {
515 		file_error(ms, 0, "no magic files loaded");
516 		return -1;
517 	}
518 	file_clearbuf(ms);
519 	if (ms->o.pbuf) {
520 		efree(ms->o.pbuf);
521 		ms->o.pbuf = NULL;
522 	}
523 	ms->event_flags &= ~EVENT_HAD_ERR;
524 	ms->error = -1;
525 	return 0;
526 }
527 
528 #define OCTALIFY(n, o)	\
529 	/*LINTED*/ \
530 	(void)(*(n)++ = '\\', \
531 	*(n)++ = ((CAST(uint32_t, *(o)) >> 6) & 3) + '0', \
532 	*(n)++ = ((CAST(uint32_t, *(o)) >> 3) & 7) + '0', \
533 	*(n)++ = ((CAST(uint32_t, *(o)) >> 0) & 7) + '0', \
534 	(o)++)
535 
536 protected const char *
file_getbuffer(struct magic_set * ms)537 file_getbuffer(struct magic_set *ms)
538 {
539 	char *pbuf, *op, *np;
540 	size_t psize, len;
541 
542 	if (ms->event_flags & EVENT_HAD_ERR)
543 		return NULL;
544 
545 	if (ms->flags & MAGIC_RAW)
546 		return ms->o.buf;
547 
548 	if (ms->o.buf == NULL)
549 		return NULL;
550 
551 	/* * 4 is for octal representation, + 1 is for NUL */
552 	len = strlen(ms->o.buf);
553 	if (len > (SIZE_MAX - 1) / 4) {
554 		file_oomem(ms, len);
555 		return NULL;
556 	}
557 	psize = len * 4 + 1;
558 	if ((pbuf = CAST(char *, erealloc(ms->o.pbuf, psize))) == NULL) {
559 		file_oomem(ms, psize);
560 		return NULL;
561 	}
562 	ms->o.pbuf = pbuf;
563 
564 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
565 	{
566 		mbstate_t state;
567 		wchar_t nextchar;
568 		int mb_conv = 1;
569 		size_t bytesconsumed;
570 		char *eop;
571 		(void)memset(&state, 0, sizeof(mbstate_t));
572 
573 		np = ms->o.pbuf;
574 		op = ms->o.buf;
575 		eop = op + len;
576 
577 		while (op < eop) {
578 			bytesconsumed = mbrtowc(&nextchar, op,
579 			    CAST(size_t, eop - op), &state);
580 			if (bytesconsumed == CAST(size_t, -1) ||
581 			    bytesconsumed == CAST(size_t, -2)) {
582 				mb_conv = 0;
583 				break;
584 			}
585 
586 			if (iswprint(nextchar)) {
587 				(void)memcpy(np, op, bytesconsumed);
588 				op += bytesconsumed;
589 				np += bytesconsumed;
590 			} else {
591 				while (bytesconsumed-- > 0)
592 					OCTALIFY(np, op);
593 			}
594 		}
595 		*np = '\0';
596 
597 		/* Parsing succeeded as a multi-byte sequence */
598 		if (mb_conv != 0)
599 			return ms->o.pbuf;
600 	}
601 #endif
602 
603 	for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
604 		if (isprint(CAST(unsigned char, *op))) {
605 			*np++ = *op++;
606 		} else {
607 			OCTALIFY(np, op);
608 		}
609 	}
610 	*np = '\0';
611 	return ms->o.pbuf;
612 }
613 
614 protected int
file_check_mem(struct magic_set * ms,unsigned int level)615 file_check_mem(struct magic_set *ms, unsigned int level)
616 {
617 	size_t len;
618 
619 	if (level >= ms->c.len) {
620 		len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
621 		ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
622 		    emalloc(len) :
623 		    erealloc(ms->c.li, len));
624 		if (ms->c.li == NULL) {
625 			file_oomem(ms, len);
626 			return -1;
627 		}
628 	}
629 	ms->c.li[level].got_match = 0;
630 #ifdef ENABLE_CONDITIONALS
631 	ms->c.li[level].last_match = 0;
632 	ms->c.li[level].last_cond = COND_NONE;
633 #endif /* ENABLE_CONDITIONALS */
634 	return 0;
635 }
636 
637 protected size_t
file_printedlen(const struct magic_set * ms)638 file_printedlen(const struct magic_set *ms)
639 {
640 	return ms->o.blen;
641 }
642 
643 protected int
file_replace(struct magic_set * ms,const char * pat,const char * rep)644 file_replace(struct magic_set *ms, const char *pat, const char *rep)
645 {
646 	zend_string *pattern;
647 	uint32_t opts = 0;
648 	pcre_cache_entry *pce;
649 	zend_string *res;
650 	zend_string *repl;
651 	size_t rep_cnt = 0;
652 
653 	opts |= PCRE2_MULTILINE;
654 	pattern = convert_libmagic_pattern((char*)pat, strlen(pat), opts);
655 	if ((pce = pcre_get_compiled_regex_cache_ex(pattern, 0)) == NULL) {
656 		zend_string_release(pattern);
657 		rep_cnt = -1;
658 		goto out;
659 	}
660 	zend_string_release(pattern);
661 
662 	repl = zend_string_init(rep, strlen(rep), 0);
663 	res = php_pcre_replace_impl(pce, NULL, ms->o.buf, strlen(ms->o.buf), repl, -1, &rep_cnt);
664 
665 	zend_string_release_ex(repl, 0);
666 	if (NULL == res) {
667 		rep_cnt = -1;
668 		goto out;
669 	}
670 
671 	strncpy(ms->o.buf, ZSTR_VAL(res), ZSTR_LEN(res));
672 	ms->o.buf[ZSTR_LEN(res)] = '\0';
673 
674 	zend_string_release_ex(res, 0);
675 
676 out:
677 	return rep_cnt;
678 }
679 
680 protected file_pushbuf_t *
file_push_buffer(struct magic_set * ms)681 file_push_buffer(struct magic_set *ms)
682 {
683 	file_pushbuf_t *pb;
684 
685 	if (ms->event_flags & EVENT_HAD_ERR)
686 		return NULL;
687 
688 	if ((pb = (CAST(file_pushbuf_t *, emalloc(sizeof(*pb))))) == NULL)
689 		return NULL;
690 
691 	pb->buf = ms->o.buf;
692 	pb->blen = ms->o.blen;
693 	pb->offset = ms->offset;
694 
695 	ms->o.buf = NULL;
696 	ms->o.blen = 0;
697 	ms->offset = 0;
698 
699 	return pb;
700 }
701 
702 protected char *
file_pop_buffer(struct magic_set * ms,file_pushbuf_t * pb)703 file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
704 {
705 	char *rbuf;
706 
707 	if (ms->event_flags & EVENT_HAD_ERR) {
708 		efree(pb->buf);
709 		efree(pb);
710 		return NULL;
711 	}
712 
713 	rbuf = ms->o.buf;
714 
715 	ms->o.buf = pb->buf;
716 	ms->o.blen = pb->blen;
717 	ms->offset = pb->offset;
718 
719 	efree(pb);
720 	return rbuf;
721 }
722 
723 /*
724  * convert string to ascii printable format.
725  */
726 protected char *
file_printable(struct magic_set * ms,char * buf,size_t bufsiz,const char * str,size_t slen)727 file_printable(struct magic_set *ms, char *buf, size_t bufsiz,
728     const char *str, size_t slen)
729 {
730 	char *ptr, *eptr = buf + bufsiz - 1;
731 	const unsigned char *s = RCAST(const unsigned char *, str);
732 	const unsigned char *es = s + slen;
733 
734 	for (ptr = buf;  ptr < eptr && s < es && *s; s++) {
735 		if ((ms->flags & MAGIC_RAW) != 0 || isprint(*s)) {
736 			*ptr++ = *s;
737 			continue;
738 		}
739 		if (ptr >= eptr - 3)
740 			break;
741 		*ptr++ = '\\';
742 		*ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
743 		*ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
744 		*ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
745 	}
746 	*ptr = '\0';
747 	return buf;
748 }
749 
750 struct guid {
751 	uint32_t data1;
752 	uint16_t data2;
753 	uint16_t data3;
754 	uint8_t data4[8];
755 };
756 
757 protected int
file_parse_guid(const char * s,uint64_t * guid)758 file_parse_guid(const char *s, uint64_t *guid)
759 {
760 	struct guid *g = CAST(struct guid *, CAST(void *, guid));
761 #ifndef WIN32
762 	return sscanf(s,
763 	    "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
764 	    &g->data1, &g->data2, &g->data3, &g->data4[0], &g->data4[1],
765 	    &g->data4[2], &g->data4[3], &g->data4[4], &g->data4[5],
766 	    &g->data4[6], &g->data4[7]) == 11 ? 0 : -1;
767 #else
768 	/* MS-Windows runtime doesn't support %hhx, except under
769 	   non-default __USE_MINGW_ANSI_STDIO.  */
770 	uint16_t data16[8];
771 	int rv = sscanf(s, "%8x-%4hx-%4hx-%2hx%2hx-%2hx%2hx%2hx%2hx%2hx%2hx",
772 	    &g->data1, &g->data2, &g->data3, &data16[0], &data16[1],
773 	    &data16[2], &data16[3], &data16[4], &data16[5],
774 	    &data16[6], &data16[7]) == 11 ? 0 : -1;
775 	int i;
776 	for (i = 0; i < 8; i++)
777 	    g->data4[i] = data16[i];
778 	return rv;
779 #endif
780 }
781 
782 protected int
file_print_guid(char * str,size_t len,const uint64_t * guid)783 file_print_guid(char *str, size_t len, const uint64_t *guid)
784 {
785 	const struct guid *g = CAST(const struct guid *,
786 	    CAST(const void *, guid));
787 
788 #ifndef WIN32
789 	return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hhX%.2hhX-"
790 	    "%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX",
791 	    g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
792 	    g->data4[2], g->data4[3], g->data4[4], g->data4[5],
793 	    g->data4[6], g->data4[7]);
794 #else
795 	return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hX%.2hX-"
796 	    "%.2hX%.2hX%.2hX%.2hX%.2hX%.2hX",
797 	    g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
798 	    g->data4[2], g->data4[3], g->data4[4], g->data4[5],
799 	    g->data4[6], g->data4[7]);
800 #endif
801 }
802 
803 #if 0
804 protected int
805 file_pipe_closexec(int *fds)
806 {
807 #ifdef HAVE_PIPE2
808 	return pipe2(fds, O_CLOEXEC);
809 #else
810 	if (pipe(fds) == -1)
811 		return -1;
812 # ifdef F_SETFD
813 	(void)fcntl(fds[0], F_SETFD, FD_CLOEXEC);
814 	(void)fcntl(fds[1], F_SETFD, FD_CLOEXEC);
815 # endif
816 	return 0;
817 #endif
818 }
819 #endif
820 
821 protected int
file_clear_closexec(int fd)822 file_clear_closexec(int fd) {
823 #ifdef F_SETFD
824 	return fcntl(fd, F_SETFD, 0);
825 #else
826 	return 0;
827 #endif
828 }
829 
830 protected char *
file_strtrim(char * str)831 file_strtrim(char *str)
832 {
833 	char *last;
834 
835 	while (isspace(CAST(unsigned char, *str)))
836 		str++;
837 	last = str;
838 	while (*last)
839 		last++;
840 	--last;
841 	while (isspace(CAST(unsigned char, *last)))
842 		last--;
843 	*++last = '\0';
844 	return str;
845 }
846