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