xref: /php-src/ext/fileinfo/libmagic/funcs.c (revision d3901b8c)
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.140 2023/05/21 17:08:34 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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 file_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 __attribute__ ((__unused__)),
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 #ifdef 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, code);
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 SIMH tape file */
419 	if ((ms->flags & MAGIC_NO_CHECK_SIMH) == 0) {
420 		m = file_is_simh(ms, &b);
421 		if ((ms->flags & MAGIC_DEBUG) != 0)
422 			(void)fprintf(stderr, "[try simh %d]\n", m);
423 		if (m) {
424 			if (checkdone(ms, &rv))
425 				goto done;
426 		}
427 	}
428 
429 	/* Check if we have a CDF file */
430 	if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
431 		m = file_trycdf(ms, &b);
432 		if ((ms->flags & MAGIC_DEBUG) != 0)
433 			(void)fprintf(stderr, "[try cdf %d]\n", m);
434 		if (m) {
435 			if (checkdone(ms, &rv))
436 				goto done;
437 		}
438 	}
439 #ifdef BUILTIN_ELF
440 	if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && nb > 5 && fd != -1) {
441 		file_pushbuf_t *pb;
442 		/*
443 		 * We matched something in the file, so this
444 		 * *might* be an ELF file, and the file is at
445 		 * least 5 bytes long, so if it's an ELF file
446 		 * it has at least one byte past the ELF magic
447 		 * number - try extracting information from the
448 		 * ELF headers that cannot easily be  extracted
449 		 * with rules in the magic file. We we don't
450 		 * print the information yet.
451 		 */
452 		if ((pb = file_push_buffer(ms)) == NULL)
453 			return -1;
454 
455 		rv = file_tryelf(ms, &b);
456 		rbuf = file_pop_buffer(ms, pb);
457 		if (rv == -1) {
458 			efree(rbuf);
459 			rbuf = NULL;
460 		}
461 		if ((ms->flags & MAGIC_DEBUG) != 0)
462 			(void)fprintf(stderr, "[try elf %d]\n", m);
463 	}
464 #endif
465 
466 	/* try soft magic tests */
467 	if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
468 		m = file_softmagic(ms, &b, NULL, NULL, BINTEST, looks_text);
469 		if ((ms->flags & MAGIC_DEBUG) != 0)
470 			(void)fprintf(stderr, "[try softmagic %d]\n", m);
471 		if (m == 1 && rbuf) {
472 			if (file_printf(ms, "%s", rbuf) == -1)
473 				goto done;
474 		}
475 		if (m) {
476 			if (checkdone(ms, &rv))
477 				goto done;
478 		}
479 	}
480 
481 	/* try text properties */
482 	if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
483 
484 		m = file_ascmagic(ms, &b, looks_text);
485 		if ((ms->flags & MAGIC_DEBUG) != 0)
486 			(void)fprintf(stderr, "[try ascmagic %d]\n", m);
487 		if (m) {
488 			goto done;
489 		}
490 	}
491 
492 simple:
493 	/* give up */
494 	if (m == 0) {
495 		m = 1;
496 		rv = file_default(ms, nb);
497 		if (rv == 0)
498 			if (file_printf(ms, "%s", def) == -1)
499 				rv = -1;
500 	}
501  done:
502 	trim_separator(ms);
503 	if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
504 		if (ms->flags & MAGIC_MIME_TYPE)
505 			if (file_printf(ms, "; charset=") == -1)
506 				rv = -1;
507 		if (file_printf(ms, "%s", code_mime) == -1)
508 			rv = -1;
509 	}
510 #ifdef PHP_FILEINFO_UNCOMPRESS
511  done_encoding:
512 #endif
513 	efree(rbuf);
514 	buffer_fini(&b);
515 	if (rv)
516 		return rv;
517 
518 	return m;
519 }
520 #endif
521 
522 file_protected int
file_reset(struct magic_set * ms,int checkloaded)523 file_reset(struct magic_set *ms, int checkloaded)
524 {
525 	if (checkloaded && ms->mlist[0] == NULL) {
526 		file_error(ms, 0, "no magic files loaded");
527 		return -1;
528 	}
529 	file_clearbuf(ms);
530 	if (ms->o.pbuf) {
531 		efree(ms->o.pbuf);
532 		ms->o.pbuf = NULL;
533 	}
534 	ms->event_flags &= ~EVENT_HAD_ERR;
535 	ms->error = -1;
536 	return 0;
537 }
538 
539 #define OCTALIFY(n, o)	\
540 	/*LINTED*/ \
541 	(void)(*(n)++ = '\\', \
542 	*(n)++ = ((CAST(uint32_t, *(o)) >> 6) & 3) + '0', \
543 	*(n)++ = ((CAST(uint32_t, *(o)) >> 3) & 7) + '0', \
544 	*(n)++ = ((CAST(uint32_t, *(o)) >> 0) & 7) + '0', \
545 	(o)++)
546 
547 file_protected const char *
file_getbuffer(struct magic_set * ms)548 file_getbuffer(struct magic_set *ms)
549 {
550 	char *pbuf, *op, *np;
551 	size_t psize, len;
552 
553 	if (ms->event_flags & EVENT_HAD_ERR)
554 		return NULL;
555 
556 	if (ms->flags & MAGIC_RAW)
557 		return ms->o.buf;
558 
559 	if (ms->o.buf == NULL)
560 		return NULL;
561 
562 	/* * 4 is for octal representation, + 1 is for NUL */
563 	len = strlen(ms->o.buf);
564 	if (len > (SIZE_MAX - 1) / 4) {
565 		file_oomem(ms, len);
566 		return NULL;
567 	}
568 	psize = len * 4 + 1;
569 	if ((pbuf = CAST(char *, erealloc(ms->o.pbuf, psize))) == NULL) {
570 		file_oomem(ms, psize);
571 		return NULL;
572 	}
573 	ms->o.pbuf = pbuf;
574 
575 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
576 	{
577 		mbstate_t state;
578 		wchar_t nextchar;
579 		int mb_conv = 1;
580 		size_t bytesconsumed;
581 		char *eop;
582 		(void)memset(&state, 0, sizeof(mbstate_t));
583 
584 		np = ms->o.pbuf;
585 		op = ms->o.buf;
586 		eop = op + len;
587 
588 		while (op < eop) {
589 			bytesconsumed = mbrtowc(&nextchar, op,
590 			    CAST(size_t, eop - op), &state);
591 			if (bytesconsumed == CAST(size_t, -1) ||
592 			    bytesconsumed == CAST(size_t, -2)) {
593 				mb_conv = 0;
594 				break;
595 			}
596 
597 			if (iswprint(nextchar)) {
598 				(void)memcpy(np, op, bytesconsumed);
599 				op += bytesconsumed;
600 				np += bytesconsumed;
601 			} else {
602 				while (bytesconsumed-- > 0)
603 					OCTALIFY(np, op);
604 			}
605 		}
606 		*np = '\0';
607 
608 		/* Parsing succeeded as a multi-byte sequence */
609 		if (mb_conv != 0)
610 			return ms->o.pbuf;
611 	}
612 #endif
613 
614 	for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
615 		if (isprint(CAST(unsigned char, *op))) {
616 			*np++ = *op++;
617 		} else {
618 			OCTALIFY(np, op);
619 		}
620 	}
621 	*np = '\0';
622 	return ms->o.pbuf;
623 }
624 
625 file_protected int
file_check_mem(struct magic_set * ms,unsigned int level)626 file_check_mem(struct magic_set *ms, unsigned int level)
627 {
628 	size_t len;
629 
630 	if (level >= ms->c.len) {
631 		len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
632 		ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
633 		    emalloc(len) :
634 		    erealloc(ms->c.li, len));
635 		if (ms->c.li == NULL) {
636 			file_oomem(ms, len);
637 			return -1;
638 		}
639 	}
640 	ms->c.li[level].got_match = 0;
641 #ifdef ENABLE_CONDITIONALS
642 	ms->c.li[level].last_match = 0;
643 	ms->c.li[level].last_cond = COND_NONE;
644 #endif /* ENABLE_CONDITIONALS */
645 	return 0;
646 }
647 
648 file_protected size_t
file_printedlen(const struct magic_set * ms)649 file_printedlen(const struct magic_set *ms)
650 {
651 	return ms->o.blen;
652 }
653 
654 file_protected int
file_replace(struct magic_set * ms,const char * pat,const char * rep)655 file_replace(struct magic_set *ms, const char *pat, const char *rep)
656 {
657 	zend_string *pattern;
658 	uint32_t opts = 0;
659 	pcre_cache_entry *pce;
660 	zend_string *res;
661 	zend_string *repl;
662 	size_t rep_cnt = 0;
663 
664 	opts |= PCRE2_MULTILINE;
665 	pattern = convert_libmagic_pattern((char*)pat, strlen(pat), opts);
666 	if ((pce = pcre_get_compiled_regex_cache_ex(pattern, 0)) == NULL) {
667 		zend_string_release(pattern);
668 		rep_cnt = -1;
669 		goto out;
670 	}
671 	zend_string_release(pattern);
672 
673 	repl = zend_string_init(rep, strlen(rep), 0);
674 	res = php_pcre_replace_impl(pce, NULL, ms->o.buf, strlen(ms->o.buf), repl, -1, &rep_cnt);
675 
676 	zend_string_release_ex(repl, 0);
677 	if (NULL == res) {
678 		rep_cnt = -1;
679 		goto out;
680 	}
681 
682 	memcpy(ms->o.buf, ZSTR_VAL(res), ZSTR_LEN(res));
683 	ms->o.buf[ZSTR_LEN(res)] = '\0';
684 
685 	zend_string_release_ex(res, 0);
686 
687 out:
688 	return rep_cnt;
689 }
690 
691 file_protected file_pushbuf_t *
file_push_buffer(struct magic_set * ms)692 file_push_buffer(struct magic_set *ms)
693 {
694 	file_pushbuf_t *pb;
695 
696 	if (ms->event_flags & EVENT_HAD_ERR)
697 		return NULL;
698 
699 	if ((pb = (CAST(file_pushbuf_t *, emalloc(sizeof(*pb))))) == NULL)
700 		return NULL;
701 
702 	pb->buf = ms->o.buf;
703 	pb->blen = ms->o.blen;
704 	pb->offset = ms->offset;
705 
706 	ms->o.buf = NULL;
707 	ms->o.blen = 0;
708 	ms->offset = 0;
709 
710 	return pb;
711 }
712 
713 file_protected char *
file_pop_buffer(struct magic_set * ms,file_pushbuf_t * pb)714 file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
715 {
716 	char *rbuf;
717 
718 	if (ms->event_flags & EVENT_HAD_ERR) {
719 		efree(pb->buf);
720 		efree(pb);
721 		return NULL;
722 	}
723 
724 	rbuf = ms->o.buf;
725 
726 	ms->o.buf = pb->buf;
727 	ms->o.blen = pb->blen;
728 	ms->offset = pb->offset;
729 
730 	efree(pb);
731 	return rbuf;
732 }
733 
734 /*
735  * convert string to ascii printable format.
736  */
737 file_protected char *
file_printable(struct magic_set * ms,char * buf,size_t bufsiz,const char * str,size_t slen)738 file_printable(struct magic_set *ms, char *buf, size_t bufsiz,
739     const char *str, size_t slen)
740 {
741 	char *ptr, *eptr = buf + bufsiz - 1;
742 	const unsigned char *s = RCAST(const unsigned char *, str);
743 	const unsigned char *es = s + slen;
744 
745 	for (ptr = buf;  ptr < eptr && s < es && *s; s++) {
746 		if ((ms->flags & MAGIC_RAW) != 0 || isprint(*s)) {
747 			*ptr++ = *s;
748 			continue;
749 		}
750 		if (ptr >= eptr - 3)
751 			break;
752 		*ptr++ = '\\';
753 		*ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
754 		*ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
755 		*ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
756 	}
757 	*ptr = '\0';
758 	return buf;
759 }
760 
761 struct guid {
762 	uint32_t data1;
763 	uint16_t data2;
764 	uint16_t data3;
765 	uint8_t data4[8];
766 };
767 
768 file_protected int
file_parse_guid(const char * s,uint64_t * guid)769 file_parse_guid(const char *s, uint64_t *guid)
770 {
771 	struct guid *g = CAST(struct guid *, CAST(void *, guid));
772 #ifndef WIN32
773 	return sscanf(s,
774 	    "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
775 	    &g->data1, &g->data2, &g->data3, &g->data4[0], &g->data4[1],
776 	    &g->data4[2], &g->data4[3], &g->data4[4], &g->data4[5],
777 	    &g->data4[6], &g->data4[7]) == 11 ? 0 : -1;
778 #else
779 	/* MS-Windows runtime doesn't support %hhx, except under
780 	   non-default __USE_MINGW_ANSI_STDIO.  */
781 	uint16_t data16[8];
782 	int rv = sscanf(s, "%8x-%4hx-%4hx-%2hx%2hx-%2hx%2hx%2hx%2hx%2hx%2hx",
783 	    &g->data1, &g->data2, &g->data3, &data16[0], &data16[1],
784 	    &data16[2], &data16[3], &data16[4], &data16[5],
785 	    &data16[6], &data16[7]) == 11 ? 0 : -1;
786 	int i;
787 	for (i = 0; i < 8; i++)
788 	    g->data4[i] = data16[i];
789 	return rv;
790 #endif
791 }
792 
793 file_protected int
file_print_guid(char * str,size_t len,const uint64_t * guid)794 file_print_guid(char *str, size_t len, const uint64_t *guid)
795 {
796 	const struct guid *g = CAST(const struct guid *,
797 	    CAST(const void *, guid));
798 
799 #ifndef WIN32
800 	return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hhX%.2hhX-"
801 	    "%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX",
802 	    g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
803 	    g->data4[2], g->data4[3], g->data4[4], g->data4[5],
804 	    g->data4[6], g->data4[7]);
805 #else
806 	return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hX%.2hX-"
807 	    "%.2hX%.2hX%.2hX%.2hX%.2hX%.2hX",
808 	    g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
809 	    g->data4[2], g->data4[3], g->data4[4], g->data4[5],
810 	    g->data4[6], g->data4[7]);
811 #endif
812 }
813 
814 #if 0
815 file_protected int
816 file_pipe_closexec(int *fds)
817 {
818 #ifdef __MINGW32__
819 	return 0;
820 #elif defined(HAVE_PIPE2)
821 	return pipe2(fds, O_CLOEXEC);
822 #else
823 	if (pipe(fds) == -1)
824 		return -1;
825 # ifdef F_SETFD
826 	(void)fcntl(fds[0], F_SETFD, FD_CLOEXEC);
827 	(void)fcntl(fds[1], F_SETFD, FD_CLOEXEC);
828 # endif
829 	return 0;
830 #endif
831 }
832 #endif
833 
834 file_protected int
file_clear_closexec(int fd)835 file_clear_closexec(int fd) {
836 #ifdef F_SETFD
837 	return fcntl(fd, F_SETFD, 0);
838 #else
839 	return 0;
840 #endif
841 }
842 
843 file_protected char *
file_strtrim(char * str)844 file_strtrim(char *str)
845 {
846 	char *last;
847 
848 	while (isspace(CAST(unsigned char, *str)))
849 		str++;
850 	last = str;
851 	while (*last)
852 		last++;
853 	--last;
854 	while (isspace(CAST(unsigned char, *last)))
855 		last--;
856 	*++last = '\0';
857 	return str;
858 }
859