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