xref: /freebsd/contrib/file/src/compress.c (revision 780fb4a2fa9a9aee5ac48a60b790f567c0dc13e9)
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.106 2017/11/02 20:25:39 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(ZLIBSUPPORT)
66 #define BUILTIN_DECOMPRESS
67 #include <zlib.h>
68 #endif
69 #ifdef DEBUG
70 int tty = -1;
71 #define DPRINTF(...)	do { \
72 	if (tty == -1) \
73 		tty = open("/dev/tty", O_RDWR); \
74 	if (tty == -1) \
75 		abort(); \
76 	dprintf(tty, __VA_ARGS__); \
77 } while (/*CONSTCOND*/0)
78 #else
79 #define DPRINTF(...)
80 #endif
81 
82 #ifdef ZLIBSUPPORT
83 /*
84  * The following python code is not really used because ZLIBSUPPORT is only
85  * defined if we have a built-in zlib, and the built-in zlib handles that.
86  * That is not true for android where we have zlib.h and not -lz.
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 = CAST(unsigned char *, CAST(void *, &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 static const char *zstd_args[] = {
137 	"zstd", "-cd", NULL
138 };
139 
140 private const struct {
141 	const void *magic;
142 	size_t maglen;
143 	const char **argv;
144 } compr[] = {
145 	{ "\037\235",	2, gzip_args },		/* compressed */
146 	/* Uncompress can get stuck; so use gzip first if we have it
147 	 * Idea from Damien Clark, thanks! */
148 	{ "\037\235",	2, uncompress_args },	/* compressed */
149 	{ "\037\213",	2, gzip_args },		/* gzipped */
150 	{ "\037\236",	2, gzip_args },		/* frozen */
151 	{ "\037\240",	2, gzip_args },		/* SCO LZH */
152 	/* the standard pack utilities do not accept standard input */
153 	{ "\037\036",	2, gzip_args },		/* packed */
154 	{ "PK\3\4",	4, gzip_args },		/* pkzipped, */
155 	/* ...only first file examined */
156 	{ "BZh",	3, bzip2_args },	/* bzip2-ed */
157 	{ "LZIP",	4, lzip_args },		/* lzip-ed */
158  	{ "\3757zXZ\0",	6, xz_args },		/* XZ Utils */
159  	{ "LRZI",	4, lrzip_args },	/* LRZIP */
160  	{ "\004\"M\030",4, lz4_args },		/* LZ4 */
161  	{ "\x28\xB5\x2F\xFD", 4, zstd_args },	/* zstd */
162 #ifdef ZLIBSUPPORT
163 	{ RCAST(const void *, zlibcmp),	0, zlib_args },		/* zlib */
164 #endif
165 };
166 
167 #define OKDATA 	0
168 #define NODATA	1
169 #define ERRDATA	2
170 
171 private ssize_t swrite(int, const void *, size_t);
172 #if HAVE_FORK
173 private size_t ncompr = sizeof(compr) / sizeof(compr[0]);
174 private int uncompressbuf(int, size_t, size_t, const unsigned char *,
175     unsigned char **, size_t *);
176 #ifdef BUILTIN_DECOMPRESS
177 private int uncompresszlib(const unsigned char *, unsigned char **, size_t,
178     size_t *, int);
179 private int uncompressgzipped(const unsigned char *, unsigned char **, size_t,
180     size_t *);
181 #endif
182 static int makeerror(unsigned char **, size_t *, const char *, ...)
183     __attribute__((__format__(__printf__, 3, 4)));
184 private const char *methodname(size_t);
185 
186 protected int
187 file_zmagic(struct magic_set *ms, const struct buffer *b, const char *name)
188 {
189 	unsigned char *newbuf = NULL;
190 	size_t i, nsz;
191 	char *rbuf;
192 	file_pushbuf_t *pb;
193 	int urv, prv, rv = 0;
194 	int mime = ms->flags & MAGIC_MIME;
195 	int fd = b->fd;
196 	const unsigned char *buf = b->fbuf;
197 	size_t nbytes = b->flen;
198 #ifdef HAVE_SIGNAL_H
199 	sig_t osigpipe;
200 #endif
201 
202 	if ((ms->flags & MAGIC_COMPRESS) == 0)
203 		return 0;
204 
205 #ifdef HAVE_SIGNAL_H
206 	osigpipe = signal(SIGPIPE, SIG_IGN);
207 #endif
208 	for (i = 0; i < ncompr; i++) {
209 		int zm;
210 		if (nbytes < compr[i].maglen)
211 			continue;
212 #ifdef ZLIBSUPPORT
213 		if (compr[i].maglen == 0)
214 			zm = (RCAST(int (*)(const unsigned char *),
215 			    CCAST(void *, compr[i].magic)))(buf);
216 		else
217 #endif
218 			zm = memcmp(buf, compr[i].magic, compr[i].maglen) == 0;
219 
220 		if (!zm)
221 			continue;
222 		nsz = nbytes;
223 		urv = uncompressbuf(fd, ms->bytes_max, i, buf, &newbuf, &nsz);
224 		DPRINTF("uncompressbuf = %d, %s, %zu\n", urv, (char *)newbuf,
225 		    nsz);
226 		switch (urv) {
227 		case OKDATA:
228 		case ERRDATA:
229 
230 			ms->flags &= ~MAGIC_COMPRESS;
231 			if (urv == ERRDATA)
232 				prv = file_printf(ms, "%s ERROR: %s",
233 				    methodname(i), newbuf);
234 			else
235 				prv = file_buffer(ms, -1, name, newbuf, nsz);
236 			if (prv == -1)
237 				goto error;
238 			rv = 1;
239 			if ((ms->flags & MAGIC_COMPRESS_TRANSP) != 0)
240 				goto out;
241 			if (mime != MAGIC_MIME && mime != 0)
242 				goto out;
243 			if ((file_printf(ms,
244 			    mime ? " compressed-encoding=" : " (")) == -1)
245 				goto error;
246 			if ((pb = file_push_buffer(ms)) == NULL)
247 				goto error;
248 			/*
249 			 * XXX: If file_buffer fails here, we overwrite
250 			 * the compressed text. FIXME.
251 			 */
252 			if (file_buffer(ms, -1, NULL, buf, nbytes) == -1)
253 				goto error;
254 			if ((rbuf = file_pop_buffer(ms, pb)) != NULL) {
255 				if (file_printf(ms, "%s", rbuf) == -1) {
256 					free(rbuf);
257 					goto error;
258 				}
259 				free(rbuf);
260 			}
261 			if (!mime && file_printf(ms, ")") == -1)
262 				goto error;
263 			/*FALLTHROUGH*/
264 		case NODATA:
265 			break;
266 		default:
267 			abort();
268 			/*NOTREACHED*/
269 		error:
270 			rv = -1;
271 			break;
272 		}
273 	}
274 out:
275 	DPRINTF("rv = %d\n", rv);
276 
277 #ifdef HAVE_SIGNAL_H
278 	(void)signal(SIGPIPE, osigpipe);
279 #endif
280 	free(newbuf);
281 	ms->flags |= MAGIC_COMPRESS;
282 	DPRINTF("Zmagic returns %d\n", rv);
283 	return rv;
284 }
285 #endif
286 /*
287  * `safe' write for sockets and pipes.
288  */
289 private ssize_t
290 swrite(int fd, const void *buf, size_t n)
291 {
292 	ssize_t rv;
293 	size_t rn = n;
294 
295 	do
296 		switch (rv = write(fd, buf, n)) {
297 		case -1:
298 			if (errno == EINTR)
299 				continue;
300 			return -1;
301 		default:
302 			n -= rv;
303 			buf = CAST(const char *, buf) + rv;
304 			break;
305 		}
306 	while (n > 0);
307 	return rn;
308 }
309 
310 
311 /*
312  * `safe' read for sockets and pipes.
313  */
314 protected ssize_t
315 sread(int fd, void *buf, size_t n, int canbepipe __attribute__((__unused__)))
316 {
317 	ssize_t rv;
318 #ifdef FIONREAD
319 	int t = 0;
320 #endif
321 	size_t rn = n;
322 
323 	if (fd == STDIN_FILENO)
324 		goto nocheck;
325 
326 #ifdef FIONREAD
327 	if (canbepipe && (ioctl(fd, FIONREAD, &t) == -1 || t == 0)) {
328 #ifdef FD_ZERO
329 		ssize_t cnt;
330 		for (cnt = 0;; cnt++) {
331 			fd_set check;
332 			struct timeval tout = {0, 100 * 1000};
333 			int selrv;
334 
335 			FD_ZERO(&check);
336 			FD_SET(fd, &check);
337 
338 			/*
339 			 * Avoid soft deadlock: do not read if there
340 			 * is nothing to read from sockets and pipes.
341 			 */
342 			selrv = select(fd + 1, &check, NULL, NULL, &tout);
343 			if (selrv == -1) {
344 				if (errno == EINTR || errno == EAGAIN)
345 					continue;
346 			} else if (selrv == 0 && cnt >= 5) {
347 				return 0;
348 			} else
349 				break;
350 		}
351 #endif
352 		(void)ioctl(fd, FIONREAD, &t);
353 	}
354 
355 	if (t > 0 && (size_t)t < n) {
356 		n = t;
357 		rn = n;
358 	}
359 #endif
360 
361 nocheck:
362 	do
363 		switch ((rv = read(fd, buf, n))) {
364 		case -1:
365 			if (errno == EINTR)
366 				continue;
367 			return -1;
368 		case 0:
369 			return rn - n;
370 		default:
371 			n -= rv;
372 			buf = CAST(char *, CCAST(void *, buf)) + rv;
373 			break;
374 		}
375 	while (n > 0);
376 	return rn;
377 }
378 
379 protected int
380 file_pipe2file(struct magic_set *ms, int fd, const void *startbuf,
381     size_t nbytes)
382 {
383 	char buf[4096];
384 	ssize_t r;
385 	int tfd;
386 
387 	(void)strlcpy(buf, "/tmp/file.XXXXXX", sizeof buf);
388 #ifndef HAVE_MKSTEMP
389 	{
390 		char *ptr = mktemp(buf);
391 		tfd = open(ptr, O_RDWR|O_TRUNC|O_EXCL|O_CREAT, 0600);
392 		r = errno;
393 		(void)unlink(ptr);
394 		errno = r;
395 	}
396 #else
397 	{
398 		int te;
399 		tfd = mkstemp(buf);
400 		te = errno;
401 		(void)unlink(buf);
402 		errno = te;
403 	}
404 #endif
405 	if (tfd == -1) {
406 		file_error(ms, errno,
407 		    "cannot create temporary file for pipe copy");
408 		return -1;
409 	}
410 
411 	if (swrite(tfd, startbuf, nbytes) != (ssize_t)nbytes)
412 		r = 1;
413 	else {
414 		while ((r = sread(fd, buf, sizeof(buf), 1)) > 0)
415 			if (swrite(tfd, buf, (size_t)r) != r)
416 				break;
417 	}
418 
419 	switch (r) {
420 	case -1:
421 		file_error(ms, errno, "error copying from pipe to temp file");
422 		return -1;
423 	case 0:
424 		break;
425 	default:
426 		file_error(ms, errno, "error while writing to temp file");
427 		return -1;
428 	}
429 
430 	/*
431 	 * We duplicate the file descriptor, because fclose on a
432 	 * tmpfile will delete the file, but any open descriptors
433 	 * can still access the phantom inode.
434 	 */
435 	if ((fd = dup2(tfd, fd)) == -1) {
436 		file_error(ms, errno, "could not dup descriptor for temp file");
437 		return -1;
438 	}
439 	(void)close(tfd);
440 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
441 		file_badseek(ms);
442 		return -1;
443 	}
444 	return fd;
445 }
446 #if HAVE_FORK
447 #ifdef BUILTIN_DECOMPRESS
448 
449 #define FHCRC		(1 << 1)
450 #define FEXTRA		(1 << 2)
451 #define FNAME		(1 << 3)
452 #define FCOMMENT	(1 << 4)
453 
454 
455 private int
456 uncompressgzipped(const unsigned char *old, unsigned char **newch,
457     size_t bytes_max, size_t *n)
458 {
459 	unsigned char flg = old[3];
460 	size_t data_start = 10;
461 
462 	if (flg & FEXTRA) {
463 		if (data_start + 1 >= *n)
464 			goto err;
465 		data_start += 2 + old[data_start] + old[data_start + 1] * 256;
466 	}
467 	if (flg & FNAME) {
468 		while(data_start < *n && old[data_start])
469 			data_start++;
470 		data_start++;
471 	}
472 	if (flg & FCOMMENT) {
473 		while(data_start < *n && old[data_start])
474 			data_start++;
475 		data_start++;
476 	}
477 	if (flg & FHCRC)
478 		data_start += 2;
479 
480 	if (data_start >= *n)
481 		goto err;
482 
483 	*n -= data_start;
484 	old += data_start;
485 	return uncompresszlib(old, newch, bytes_max, n, 0);
486 err:
487 	return makeerror(newch, n, "File too short");
488 }
489 
490 private int
491 uncompresszlib(const unsigned char *old, unsigned char **newch,
492     size_t bytes_max, size_t *n, int zlib)
493 {
494 	int rc;
495 	z_stream z;
496 
497 	if ((*newch = CAST(unsigned char *, malloc(bytes_max + 1))) == NULL)
498 		return makeerror(newch, n, "No buffer, %s", strerror(errno));
499 
500 	z.next_in = CCAST(Bytef *, old);
501 	z.avail_in = CAST(uint32_t, *n);
502 	z.next_out = *newch;
503 	z.avail_out = CAST(unsigned int, bytes_max);
504 	z.zalloc = Z_NULL;
505 	z.zfree = Z_NULL;
506 	z.opaque = Z_NULL;
507 
508 	/* LINTED bug in header macro */
509 	rc = zlib ? inflateInit(&z) : inflateInit2(&z, -15);
510 	if (rc != Z_OK)
511 		goto err;
512 
513 	rc = inflate(&z, Z_SYNC_FLUSH);
514 	if (rc != Z_OK && rc != Z_STREAM_END)
515 		goto err;
516 
517 	*n = (size_t)z.total_out;
518 	rc = inflateEnd(&z);
519 	if (rc != Z_OK)
520 		goto err;
521 
522 	/* let's keep the nul-terminate tradition */
523 	(*newch)[*n] = '\0';
524 
525 	return OKDATA;
526 err:
527 	strlcpy((char *)*newch, z.msg ? z.msg : zError(rc), bytes_max);
528 	*n = strlen((char *)*newch);
529 	return ERRDATA;
530 }
531 #endif
532 
533 static int
534 makeerror(unsigned char **buf, size_t *len, const char *fmt, ...)
535 {
536 	char *msg;
537 	va_list ap;
538 	int rv;
539 
540 	va_start(ap, fmt);
541 	rv = vasprintf(&msg, fmt, ap);
542 	va_end(ap);
543 	if (rv < 0) {
544 		*buf = NULL;
545 		*len = 0;
546 		return NODATA;
547 	}
548 	*buf = (unsigned char *)msg;
549 	*len = strlen(msg);
550 	return ERRDATA;
551 }
552 
553 static void
554 closefd(int *fd, size_t i)
555 {
556 	if (fd[i] == -1)
557 		return;
558 	(void) close(fd[i]);
559 	fd[i] = -1;
560 }
561 
562 static void
563 closep(int *fd)
564 {
565 	size_t i;
566 	for (i = 0; i < 2; i++)
567 		closefd(fd, i);
568 }
569 
570 static void
571 copydesc(int i, int *fd)
572 {
573 	int j = fd[i == STDIN_FILENO ? 0 : 1];
574 	if (j == i)
575 		return;
576 	if (dup2(j, i) == -1) {
577 		DPRINTF("dup(%d, %d) failed (%s)\n", j, i, strerror(errno));
578 		exit(1);
579 	}
580 	closep(fd);
581 }
582 
583 static void
584 writechild(int fdp[3][2], const void *old, size_t n)
585 {
586 	int status;
587 
588 	closefd(fdp[STDIN_FILENO], 0);
589 	/*
590 	 * fork again, to avoid blocking because both
591 	 * pipes filled
592 	 */
593 	switch (fork()) {
594 	case 0: /* child */
595 		closefd(fdp[STDOUT_FILENO], 0);
596 		if (swrite(fdp[STDIN_FILENO][1], old, n) != (ssize_t)n) {
597 			DPRINTF("Write failed (%s)\n", strerror(errno));
598 			exit(1);
599 		}
600 		exit(0);
601 		/*NOTREACHED*/
602 
603 	case -1:
604 		DPRINTF("Fork failed (%s)\n", strerror(errno));
605 		exit(1);
606 		/*NOTREACHED*/
607 
608 	default:  /* parent */
609 		if (wait(&status) == -1) {
610 			DPRINTF("Wait failed (%s)\n", strerror(errno));
611 			exit(1);
612 		}
613 		DPRINTF("Grandchild wait return %#x\n", status);
614 	}
615 	closefd(fdp[STDIN_FILENO], 1);
616 }
617 
618 static ssize_t
619 filter_error(unsigned char *ubuf, ssize_t n)
620 {
621 	char *p;
622 	char *buf;
623 
624 	ubuf[n] = '\0';
625 	buf = (char *)ubuf;
626 	while (isspace((unsigned char)*buf))
627 		buf++;
628 	DPRINTF("Filter error[[[%s]]]\n", buf);
629 	if ((p = strchr((char *)buf, '\n')) != NULL)
630 		*p = '\0';
631 	if ((p = strchr((char *)buf, ';')) != NULL)
632 		*p = '\0';
633 	if ((p = strrchr((char *)buf, ':')) != NULL) {
634 		++p;
635 		while (isspace((unsigned char)*p))
636 			p++;
637 		n = strlen(p);
638 		memmove(ubuf, p, CAST(size_t, n + 1));
639 	}
640 	DPRINTF("Filter error after[[[%s]]]\n", (char *)ubuf);
641 	if (islower(*ubuf))
642 		*ubuf = toupper(*ubuf);
643 	return n;
644 }
645 
646 private const char *
647 methodname(size_t method)
648 {
649 #ifdef BUILTIN_DECOMPRESS
650         /* FIXME: This doesn't cope with bzip2 */
651 	if (method == 2 || compr[method].maglen == 0)
652 	    return "zlib";
653 #endif
654 	return compr[method].argv[0];
655 }
656 
657 private int
658 uncompressbuf(int fd, size_t bytes_max, size_t method, const unsigned char *old,
659     unsigned char **newch, size_t* n)
660 {
661 	int fdp[3][2];
662 	int status, rv;
663 	size_t i;
664 	ssize_t r;
665 
666 #ifdef BUILTIN_DECOMPRESS
667         /* FIXME: This doesn't cope with bzip2 */
668 	if (method == 2)
669 		return uncompressgzipped(old, newch, bytes_max, n);
670 	if (compr[method].maglen == 0)
671 		return uncompresszlib(old, newch, bytes_max, n, 1);
672 #endif
673 	(void)fflush(stdout);
674 	(void)fflush(stderr);
675 
676 	for (i = 0; i < __arraycount(fdp); i++)
677 		fdp[i][0] = fdp[i][1] = -1;
678 
679 	if ((fd == -1 && pipe(fdp[STDIN_FILENO]) == -1) ||
680 	    pipe(fdp[STDOUT_FILENO]) == -1 || pipe(fdp[STDERR_FILENO]) == -1) {
681 		closep(fdp[STDIN_FILENO]);
682 		closep(fdp[STDOUT_FILENO]);
683 		return makeerror(newch, n, "Cannot create pipe, %s",
684 		    strerror(errno));
685 	}
686 	switch (fork()) {
687 	case 0:	/* child */
688 		if (fd != -1) {
689 			fdp[STDIN_FILENO][0] = fd;
690 			(void) lseek(fd, (off_t)0, SEEK_SET);
691 		}
692 
693 		for (i = 0; i < __arraycount(fdp); i++)
694 			copydesc(CAST(int, i), fdp[i]);
695 
696 		(void)execvp(compr[method].argv[0],
697 		    (char *const *)(intptr_t)compr[method].argv);
698 		dprintf(STDERR_FILENO, "exec `%s' failed, %s",
699 		    compr[method].argv[0], strerror(errno));
700 		exit(1);
701 		/*NOTREACHED*/
702 	case -1:
703 		return makeerror(newch, n, "Cannot fork, %s",
704 		    strerror(errno));
705 
706 	default: /* parent */
707 		for (i = 1; i < __arraycount(fdp); i++)
708 			closefd(fdp[i], 1);
709 
710 		/* Write the buffer data to the child, if we don't have fd */
711 		if (fd == -1)
712 			writechild(fdp, old, *n);
713 
714 		*newch = CAST(unsigned char *, malloc(bytes_max + 1));
715 		if (*newch == NULL) {
716 			rv = makeerror(newch, n, "No buffer, %s",
717 			    strerror(errno));
718 			goto err;
719 		}
720 		rv = OKDATA;
721 		if ((r = sread(fdp[STDOUT_FILENO][0], *newch, bytes_max, 0)) > 0)
722 			break;
723 		DPRINTF("Read stdout failed %d (%s)\n", fdp[STDOUT_FILENO][0],
724 		    r != -1 ? strerror(errno) : "no data");
725 
726 		rv = ERRDATA;
727 		if (r == 0 &&
728 		    (r = sread(fdp[STDERR_FILENO][0], *newch, bytes_max, 0)) > 0)
729 		{
730 			r = filter_error(*newch, r);
731 			break;
732 		}
733 		free(*newch);
734 		if  (r == 0)
735 			rv = makeerror(newch, n, "Read failed, %s",
736 			    strerror(errno));
737 		else
738 			rv = makeerror(newch, n, "No data");
739 		goto err;
740 	}
741 
742 	*n = r;
743 	/* NUL terminate, as every buffer is handled here. */
744 	(*newch)[*n] = '\0';
745 err:
746 	closefd(fdp[STDIN_FILENO], 1);
747 	closefd(fdp[STDOUT_FILENO], 0);
748 	closefd(fdp[STDERR_FILENO], 0);
749 	if (wait(&status) == -1) {
750 		free(*newch);
751 		rv = makeerror(newch, n, "Wait failed, %s", strerror(errno));
752 		DPRINTF("Child wait return %#x\n", status);
753 	} else if (!WIFEXITED(status)) {
754 		DPRINTF("Child not exited (%#x)\n", status);
755 	} else if (WEXITSTATUS(status) != 0) {
756 		DPRINTF("Child exited (%#x)\n", WEXITSTATUS(status));
757 	}
758 
759 	closefd(fdp[STDIN_FILENO], 0);
760 	DPRINTF("Returning %p n=%zu rv=%d\n", *newch, *n, rv);
761 
762 	return rv;
763 }
764 #endif
765