xref: /freebsd/contrib/file/src/compress.c (revision a5ff72cb0e51a7675d4e2b5810a2b6dad5b91960)
1 /*
2  * Copyright (c) Ian F. Darwin 1986-1995.
3  * Software written by Ian F. Darwin and others;
4  * maintained 1995-present by Christos Zoulas and others.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice immediately at the beginning of the file, without modification,
11  *    this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*
29  * compress routines:
30  *	zmagic() - returns 0 if not recognized, uncompresses and prints
31  *		   information if recognized
32  *	uncompress(method, old, n, newch) - uncompress old into new,
33  *					    using method, return sizeof new
34  */
35 #include "file.h"
36 
37 #ifndef lint
38 FILE_RCSID("@(#)$File: compress.c,v 1.93 2016/03/31 17:51:12 christos Exp $")
39 #endif
40 
41 #include "magic.h"
42 #include <stdlib.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #include <string.h>
47 #include <errno.h>
48 #include <ctype.h>
49 #include <stdarg.h>
50 #ifdef HAVE_SIGNAL_H
51 #include <signal.h>
52 # ifndef HAVE_SIG_T
53 typedef void (*sig_t)(int);
54 # endif /* HAVE_SIG_T */
55 #endif
56 #if !defined(__MINGW32__) && !defined(WIN32)
57 #include <sys/ioctl.h>
58 #endif
59 #ifdef HAVE_SYS_WAIT_H
60 #include <sys/wait.h>
61 #endif
62 #if defined(HAVE_SYS_TIME_H)
63 #include <sys/time.h>
64 #endif
65 #if defined(HAVE_ZLIB_H) && defined(HAVE_LIBZ)
66 #define BUILTIN_DECOMPRESS
67 #include <zlib.h>
68 #define ZLIBSUPPORT
69 #endif
70 #ifdef DEBUG
71 int tty = -1;
72 #define DPRINTF(...)	do { \
73 	if (tty == -1) \
74 		tty = open("/dev/tty", O_RDWR); \
75 	if (tty == -1) \
76 		abort(); \
77 	dprintf(tty, __VA_ARGS__); \
78 } while (/*CONSTCOND*/0)
79 #else
80 #define DPRINTF(...)
81 #endif
82 
83 #ifdef ZLIBSUPPORT
84 /*
85  * The following python code is not really used because ZLIBSUPPORT is only
86  * defined if we have a built-in zlib, and the built-in zlib handles that.
87  */
88 static const char zlibcode[] =
89     "import sys, zlib; sys.stdout.write(zlib.decompress(sys.stdin.read()))";
90 
91 static const char *zlib_args[] = { "python", "-c", zlibcode, NULL };
92 
93 static int
94 zlibcmp(const unsigned char *buf)
95 {
96 	unsigned short x = 1;
97 	unsigned char *s = (unsigned char *)&x;
98 
99 	if ((buf[0] & 0xf) != 8 || (buf[0] & 0x80) != 0)
100 		return 0;
101 	if (s[0] != 1)	/* endianness test */
102 		x = buf[0] | (buf[1] << 8);
103 	else
104 		x = buf[1] | (buf[0] << 8);
105 	if (x % 31)
106 		return 0;
107 	return 1;
108 }
109 #endif
110 
111 #define gzip_flags "-cd"
112 #define lrzip_flags "-do"
113 #define lzip_flags gzip_flags
114 
115 static const char *gzip_args[] = {
116 	"gzip", gzip_flags, NULL
117 };
118 static const char *uncompress_args[] = {
119 	"uncompress", "-c", NULL
120 };
121 static const char *bzip2_args[] = {
122 	"bzip2", "-cd", NULL
123 };
124 static const char *lzip_args[] = {
125 	"lzip", lzip_flags, NULL
126 };
127 static const char *xz_args[] = {
128 	"xz", "-cd", NULL
129 };
130 static const char *lrzip_args[] = {
131 	"lrzip", lrzip_flags, NULL
132 };
133 static const char *lz4_args[] = {
134 	"lz4", "-cd", NULL
135 };
136 
137 private const struct {
138 	const void *magic;
139 	size_t maglen;
140 	const char **argv;
141 } compr[] = {
142 	{ "\037\235",	2, gzip_args },		/* compressed */
143 	/* Uncompress can get stuck; so use gzip first if we have it
144 	 * Idea from Damien Clark, thanks! */
145 	{ "\037\235",	2, uncompress_args },	/* compressed */
146 	{ "\037\213",	2, gzip_args },		/* gzipped */
147 	{ "\037\236",	2, gzip_args },		/* frozen */
148 	{ "\037\240",	2, gzip_args },		/* SCO LZH */
149 	/* the standard pack utilities do not accept standard input */
150 	{ "\037\036",	2, gzip_args },		/* packed */
151 	{ "PK\3\4",	4, gzip_args },		/* pkzipped, */
152 	/* ...only first file examined */
153 	{ "BZh",	3, bzip2_args },	/* bzip2-ed */
154 	{ "LZIP",	4, lzip_args },		/* lzip-ed */
155  	{ "\3757zXZ\0",	6, xz_args },		/* XZ Utils */
156  	{ "LRZI",	4, lrzip_args },	/* LRZIP */
157  	{ "\004\"M\030",4, lz4_args },		/* LZ4 */
158 #ifdef ZLIBSUPPORT
159 	{ zlibcmp,	0, zlib_args },		/* zlib */
160 #endif
161 };
162 
163 #define OKDATA 	0
164 #define NODATA	1
165 #define ERRDATA	2
166 
167 private ssize_t swrite(int, const void *, size_t);
168 #if HAVE_FORK
169 private size_t ncompr = sizeof(compr) / sizeof(compr[0]);
170 private int uncompressbuf(int, size_t, size_t, const unsigned char *,
171     unsigned char **, size_t *);
172 #ifdef BUILTIN_DECOMPRESS
173 private int uncompresszlib(const unsigned char *, unsigned char **, size_t,
174     size_t *, int);
175 private int uncompressgzipped(const unsigned char *, unsigned char **, size_t,
176     size_t *);
177 #endif
178 static int makeerror(unsigned char **, size_t *, const char *, ...)
179     __attribute__((__format__(__printf__, 3, 4)));
180 private const char *methodname(size_t);
181 
182 protected int
183 file_zmagic(struct magic_set *ms, int fd, const char *name,
184     const unsigned char *buf, size_t nbytes)
185 {
186 	unsigned char *newbuf = NULL;
187 	size_t i, nsz;
188 	char *rbuf;
189 	file_pushbuf_t *pb;
190 	int rv = 0;
191 	int mime = ms->flags & MAGIC_MIME;
192 #ifdef HAVE_SIGNAL_H
193 	sig_t osigpipe;
194 #endif
195 
196 	if ((ms->flags & MAGIC_COMPRESS) == 0)
197 		return 0;
198 
199 #ifdef HAVE_SIGNAL_H
200 	osigpipe = signal(SIGPIPE, SIG_IGN);
201 #endif
202 	for (i = 0; i < ncompr; i++) {
203 		int zm;
204 		if (nbytes < compr[i].maglen)
205 			continue;
206 #ifdef ZLIBSUPPORT
207 		if (compr[i].maglen == 0)
208 			zm = (CAST(int (*)(const unsigned char *),
209 			    CCAST(void *, compr[i].magic)))(buf);
210 		else
211 #endif
212 			zm = memcmp(buf, compr[i].magic, compr[i].maglen) == 0;
213 
214 		if (!zm)
215 			continue;
216 		nsz = nbytes;
217 		rv = uncompressbuf(fd, ms->bytes_max, i, buf, &newbuf, &nsz);
218 		DPRINTF("uncompressbuf = %d, %s, %zu\n", rv, (char *)newbuf,
219 		    nsz);
220 		switch (rv) {
221 		case OKDATA:
222 		case ERRDATA:
223 
224 			ms->flags &= ~MAGIC_COMPRESS;
225 			if (rv == ERRDATA)
226 				rv = file_printf(ms, "%s ERROR: %s",
227 				    methodname(i), newbuf);
228 			else
229 				rv = file_buffer(ms, -1, name, newbuf, nsz);
230 			if (rv == -1)
231 				goto error;
232 			DPRINTF("rv = %d\n", rv);
233 			if ((ms->flags & MAGIC_COMPRESS_TRANSP) != 0)
234 				goto out;
235 			if (mime != MAGIC_MIME && mime != 0)
236 				goto out;
237 			if ((file_printf(ms,
238 			    mime ? " compressed-encoding=" : " (")) == -1)
239 				goto error;
240 			if ((pb = file_push_buffer(ms)) == NULL)
241 				goto error;
242 			if (file_buffer(ms, -1, NULL, buf, nbytes) == -1)
243 				goto error;
244 			if ((rbuf = file_pop_buffer(ms, pb)) != NULL) {
245 				if (file_printf(ms, "%s", rbuf) == -1) {
246 					free(rbuf);
247 					goto error;
248 				}
249 				free(rbuf);
250 			}
251 			if (!mime && file_printf(ms, ")") == -1)
252 				goto error;
253 			goto out;
254 		case NODATA:
255 			goto out;
256 		default:
257 			abort();
258 		}
259 	}
260 out:
261 	rv = 1;
262 error:
263 #ifdef HAVE_SIGNAL_H
264 	(void)signal(SIGPIPE, osigpipe);
265 #endif
266 	free(newbuf);
267 	ms->flags |= MAGIC_COMPRESS;
268 	DPRINTF("Zmagic returns %d\n", rv);
269 	return rv;
270 }
271 #endif
272 /*
273  * `safe' write for sockets and pipes.
274  */
275 private ssize_t
276 swrite(int fd, const void *buf, size_t n)
277 {
278 	ssize_t rv;
279 	size_t rn = n;
280 
281 	do
282 		switch (rv = write(fd, buf, n)) {
283 		case -1:
284 			if (errno == EINTR)
285 				continue;
286 			return -1;
287 		default:
288 			n -= rv;
289 			buf = CAST(const char *, buf) + rv;
290 			break;
291 		}
292 	while (n > 0);
293 	return rn;
294 }
295 
296 
297 /*
298  * `safe' read for sockets and pipes.
299  */
300 protected ssize_t
301 sread(int fd, void *buf, size_t n, int canbepipe __attribute__((__unused__)))
302 {
303 	ssize_t rv;
304 #ifdef FIONREAD
305 	int t = 0;
306 #endif
307 	size_t rn = n;
308 
309 	if (fd == STDIN_FILENO)
310 		goto nocheck;
311 
312 #ifdef FIONREAD
313 	if (canbepipe && (ioctl(fd, FIONREAD, &t) == -1 || t == 0)) {
314 #ifdef FD_ZERO
315 		ssize_t cnt;
316 		for (cnt = 0;; cnt++) {
317 			fd_set check;
318 			struct timeval tout = {0, 100 * 1000};
319 			int selrv;
320 
321 			FD_ZERO(&check);
322 			FD_SET(fd, &check);
323 
324 			/*
325 			 * Avoid soft deadlock: do not read if there
326 			 * is nothing to read from sockets and pipes.
327 			 */
328 			selrv = select(fd + 1, &check, NULL, NULL, &tout);
329 			if (selrv == -1) {
330 				if (errno == EINTR || errno == EAGAIN)
331 					continue;
332 			} else if (selrv == 0 && cnt >= 5) {
333 				return 0;
334 			} else
335 				break;
336 		}
337 #endif
338 		(void)ioctl(fd, FIONREAD, &t);
339 	}
340 
341 	if (t > 0 && (size_t)t < n) {
342 		n = t;
343 		rn = n;
344 	}
345 #endif
346 
347 nocheck:
348 	do
349 		switch ((rv = read(fd, buf, n))) {
350 		case -1:
351 			if (errno == EINTR)
352 				continue;
353 			return -1;
354 		case 0:
355 			return rn - n;
356 		default:
357 			n -= rv;
358 			buf = ((char *)buf) + rv;
359 			break;
360 		}
361 	while (n > 0);
362 	return rn;
363 }
364 
365 protected int
366 file_pipe2file(struct magic_set *ms, int fd, const void *startbuf,
367     size_t nbytes)
368 {
369 	char buf[4096];
370 	ssize_t r;
371 	int tfd;
372 
373 	(void)strlcpy(buf, "/tmp/file.XXXXXX", sizeof buf);
374 #ifndef HAVE_MKSTEMP
375 	{
376 		char *ptr = mktemp(buf);
377 		tfd = open(ptr, O_RDWR|O_TRUNC|O_EXCL|O_CREAT, 0600);
378 		r = errno;
379 		(void)unlink(ptr);
380 		errno = r;
381 	}
382 #else
383 	{
384 		int te;
385 		tfd = mkstemp(buf);
386 		te = errno;
387 		(void)unlink(buf);
388 		errno = te;
389 	}
390 #endif
391 	if (tfd == -1) {
392 		file_error(ms, errno,
393 		    "cannot create temporary file for pipe copy");
394 		return -1;
395 	}
396 
397 	if (swrite(tfd, startbuf, nbytes) != (ssize_t)nbytes)
398 		r = 1;
399 	else {
400 		while ((r = sread(fd, buf, sizeof(buf), 1)) > 0)
401 			if (swrite(tfd, buf, (size_t)r) != r)
402 				break;
403 	}
404 
405 	switch (r) {
406 	case -1:
407 		file_error(ms, errno, "error copying from pipe to temp file");
408 		return -1;
409 	case 0:
410 		break;
411 	default:
412 		file_error(ms, errno, "error while writing to temp file");
413 		return -1;
414 	}
415 
416 	/*
417 	 * We duplicate the file descriptor, because fclose on a
418 	 * tmpfile will delete the file, but any open descriptors
419 	 * can still access the phantom inode.
420 	 */
421 	if ((fd = dup2(tfd, fd)) == -1) {
422 		file_error(ms, errno, "could not dup descriptor for temp file");
423 		return -1;
424 	}
425 	(void)close(tfd);
426 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
427 		file_badseek(ms);
428 		return -1;
429 	}
430 	return fd;
431 }
432 #if HAVE_FORK
433 #ifdef BUILTIN_DECOMPRESS
434 
435 #define FHCRC		(1 << 1)
436 #define FEXTRA		(1 << 2)
437 #define FNAME		(1 << 3)
438 #define FCOMMENT	(1 << 4)
439 
440 
441 private int
442 uncompressgzipped(const unsigned char *old, unsigned char **newch,
443     size_t bytes_max, size_t *n)
444 {
445 	unsigned char flg = old[3];
446 	size_t data_start = 10;
447 
448 	if (flg & FEXTRA) {
449 		if (data_start + 1 >= *n)
450 			goto err;
451 		data_start += 2 + old[data_start] + old[data_start + 1] * 256;
452 	}
453 	if (flg & FNAME) {
454 		while(data_start < *n && old[data_start])
455 			data_start++;
456 		data_start++;
457 	}
458 	if (flg & FCOMMENT) {
459 		while(data_start < *n && old[data_start])
460 			data_start++;
461 		data_start++;
462 	}
463 	if (flg & FHCRC)
464 		data_start += 2;
465 
466 	if (data_start >= *n)
467 		goto err;
468 
469 	*n -= data_start;
470 	old += data_start;
471 	return uncompresszlib(old, newch, bytes_max, n, 0);
472 err:
473 	return makeerror(newch, n, "File too short");
474 }
475 
476 private int
477 uncompresszlib(const unsigned char *old, unsigned char **newch,
478     size_t bytes_max, size_t *n, int zlib)
479 {
480 	int rc;
481 	z_stream z;
482 
483 	if ((*newch = CAST(unsigned char *, malloc(bytes_max + 1))) == NULL)
484 		return makeerror(newch, n, "No buffer, %s", strerror(errno));
485 
486 	z.next_in = CCAST(Bytef *, old);
487 	z.avail_in = CAST(uint32_t, *n);
488 	z.next_out = *newch;
489 	z.avail_out = bytes_max;
490 	z.zalloc = Z_NULL;
491 	z.zfree = Z_NULL;
492 	z.opaque = Z_NULL;
493 
494 	/* LINTED bug in header macro */
495 	rc = zlib ? inflateInit(&z) : inflateInit2(&z, -15);
496 	if (rc != Z_OK)
497 		goto err;
498 
499 	rc = inflate(&z, Z_SYNC_FLUSH);
500 	if (rc != Z_OK && rc != Z_STREAM_END)
501 		goto err;
502 
503 	*n = (size_t)z.total_out;
504 	rc = inflateEnd(&z);
505 	if (rc != Z_OK)
506 		goto err;
507 
508 	/* let's keep the nul-terminate tradition */
509 	(*newch)[*n] = '\0';
510 
511 	return OKDATA;
512 err:
513 	strlcpy((char *)*newch, z.msg, bytes_max);
514 	*n = strlen((char *)*newch);
515 	return ERRDATA;
516 }
517 #endif
518 
519 static int
520 makeerror(unsigned char **buf, size_t *len, const char *fmt, ...)
521 {
522 	char *msg;
523 	va_list ap;
524 	int rv;
525 
526 	va_start(ap, fmt);
527 	rv = vasprintf(&msg, fmt, ap);
528 	va_end(ap);
529 	if (rv < 0) {
530 		*buf = NULL;
531 		*len = 0;
532 		return NODATA;
533 	}
534 	*buf = (unsigned char *)msg;
535 	*len = strlen(msg);
536 	return ERRDATA;
537 }
538 
539 static void
540 closefd(int *fd, size_t i)
541 {
542 	if (fd[i] == -1)
543 		return;
544 	(void) close(fd[i]);
545 	fd[i] = -1;
546 }
547 
548 static void
549 closep(int *fd)
550 {
551 	size_t i;
552 	for (i = 0; i < 2; i++)
553 		closefd(fd, i);
554 }
555 
556 static void
557 copydesc(int i, int *fd)
558 {
559 	int j = fd[i == STDIN_FILENO ? 0 : 1];
560 	if (j == i)
561 		return;
562 	if (dup2(j, i) == -1) {
563 		DPRINTF("dup(%d, %d) failed (%s)\n", j, i, strerror(errno));
564 		exit(1);
565 	}
566 	closep(fd);
567 }
568 
569 static void
570 writechild(int fdp[3][2], const void *old, size_t n)
571 {
572 	int status;
573 
574 	closefd(fdp[STDIN_FILENO], 0);
575 	/*
576 	 * fork again, to avoid blocking because both
577 	 * pipes filled
578 	 */
579 	switch (fork()) {
580 	case 0: /* child */
581 		closefd(fdp[STDOUT_FILENO], 0);
582 		if (swrite(fdp[STDIN_FILENO][1], old, n) != (ssize_t)n) {
583 			DPRINTF("Write failed (%s)\n", strerror(errno));
584 			exit(1);
585 		}
586 		exit(0);
587 		/*NOTREACHED*/
588 
589 	case -1:
590 		DPRINTF("Fork failed (%s)\n", strerror(errno));
591 		exit(1);
592 		/*NOTREACHED*/
593 
594 	default:  /* parent */
595 		if (wait(&status) == -1) {
596 			DPRINTF("Wait failed (%s)\n", strerror(errno));
597 			exit(1);
598 		}
599 		DPRINTF("Grandchild wait return %#x\n", status);
600 	}
601 	closefd(fdp[STDIN_FILENO], 1);
602 }
603 
604 static ssize_t
605 filter_error(unsigned char *ubuf, ssize_t n)
606 {
607 	char *p;
608 	char *buf;
609 
610 	ubuf[n] = '\0';
611 	buf = (char *)ubuf;
612 	while (isspace((unsigned char)*buf))
613 		buf++;
614 	DPRINTF("Filter error[[[%s]]]\n", buf);
615 	if ((p = strchr((char *)buf, '\n')) != NULL)
616 		*p = '\0';
617 	if ((p = strchr((char *)buf, ';')) != NULL)
618 		*p = '\0';
619 	if ((p = strrchr((char *)buf, ':')) != NULL) {
620 		++p;
621 		while (isspace((unsigned char)*p))
622 			p++;
623 		n = strlen(p);
624 		memmove(ubuf, p, n + 1);
625 	}
626 	DPRINTF("Filter error after[[[%s]]]\n", (char *)ubuf);
627 	if (islower(*ubuf))
628 		*ubuf = toupper(*ubuf);
629 	return n;
630 }
631 
632 private const char *
633 methodname(size_t method)
634 {
635 #ifdef BUILTIN_DECOMPRESS
636         /* FIXME: This doesn't cope with bzip2 */
637 	if (method == 2 || compr[method].maglen == 0)
638 	    return "zlib";
639 #endif
640 	return compr[method].argv[0];
641 }
642 
643 private int
644 uncompressbuf(int fd, size_t bytes_max, size_t method, const unsigned char *old,
645     unsigned char **newch, size_t* n)
646 {
647 	int fdp[3][2];
648 	int status, rv;
649 	size_t i;
650 	ssize_t r;
651 
652 #ifdef BUILTIN_DECOMPRESS
653         /* FIXME: This doesn't cope with bzip2 */
654 	if (method == 2)
655 		return uncompressgzipped(old, newch, bytes_max, n);
656 	if (compr[method].maglen == 0)
657 		return uncompresszlib(old, newch, bytes_max, n, 1);
658 #endif
659 	(void)fflush(stdout);
660 	(void)fflush(stderr);
661 
662 	for (i = 0; i < __arraycount(fdp); i++)
663 		fdp[i][0] = fdp[i][1] = -1;
664 
665 	if ((fd == -1 && pipe(fdp[STDIN_FILENO]) == -1) ||
666 	    pipe(fdp[STDOUT_FILENO]) == -1 || pipe(fdp[STDERR_FILENO]) == -1) {
667 		closep(fdp[STDIN_FILENO]);
668 		closep(fdp[STDOUT_FILENO]);
669 		return makeerror(newch, n, "Cannot create pipe, %s",
670 		    strerror(errno));
671 	}
672 	switch (fork()) {
673 	case 0:	/* child */
674 		if (fd != -1) {
675 			fdp[STDIN_FILENO][0] = fd;
676 			(void) lseek(fd, (off_t)0, SEEK_SET);
677 		}
678 
679 		for (i = 0; i < __arraycount(fdp); i++)
680 			copydesc(i, fdp[i]);
681 
682 		(void)execvp(compr[method].argv[0],
683 		    (char *const *)(intptr_t)compr[method].argv);
684 		dprintf(STDERR_FILENO, "exec `%s' failed, %s",
685 		    compr[method].argv[0], strerror(errno));
686 		exit(1);
687 		/*NOTREACHED*/
688 	case -1:
689 		return makeerror(newch, n, "Cannot fork, %s",
690 		    strerror(errno));
691 
692 	default: /* parent */
693 		for (i = 1; i < __arraycount(fdp); i++)
694 			closefd(fdp[i], 1);
695 
696 		/* Write the buffer data to the child, if we don't have fd */
697 		if (fd == -1)
698 			writechild(fdp, old, *n);
699 
700 		*newch = CAST(unsigned char *, malloc(bytes_max + 1));
701 		if (*newch == NULL) {
702 			rv = makeerror(newch, n, "No buffer, %s",
703 			    strerror(errno));
704 			goto err;
705 		}
706 		rv = OKDATA;
707 		if ((r = sread(fdp[STDOUT_FILENO][0], *newch, bytes_max, 0)) > 0)
708 			break;
709 		DPRINTF("Read stdout failed %d (%s)\n", fdp[STDOUT_FILENO][0],
710 		    r != -1 ? strerror(errno) : "no data");
711 
712 		rv = ERRDATA;
713 		if (r == 0 &&
714 		    (r = sread(fdp[STDERR_FILENO][0], *newch, bytes_max, 0)) > 0)
715 		{
716 			r = filter_error(*newch, r);
717 			break;
718 		}
719 		free(*newch);
720 		if  (r == 0)
721 			rv = makeerror(newch, n, "Read failed, %s",
722 			    strerror(errno));
723 		else
724 			rv = makeerror(newch, n, "No data");
725 		goto err;
726 	}
727 
728 	*n = r;
729 	/* NUL terminate, as every buffer is handled here. */
730 	(*newch)[*n] = '\0';
731 err:
732 	closefd(fdp[STDIN_FILENO], 1);
733 	closefd(fdp[STDOUT_FILENO], 0);
734 	closefd(fdp[STDERR_FILENO], 0);
735 	if (wait(&status) == -1) {
736 		free(*newch);
737 		rv = makeerror(newch, n, "Wait failed, %s", strerror(errno));
738 		DPRINTF("Child wait return %#x\n", status);
739 	} else if (!WIFEXITED(status)) {
740 		DPRINTF("Child not exited (0x%x)\n", status);
741 	} else if (WEXITSTATUS(status) != 0) {
742 		DPRINTF("Child exited (0x%d)\n", WEXITSTATUS(status));
743 	}
744 
745 	closefd(fdp[STDIN_FILENO], 0);
746 	DPRINTF("Returning %p n=%zu rv=%d\n", *newch, *n, rv);
747 
748 	return rv;
749 }
750 #endif
751