xref: /netbsd-src/external/bsd/file/dist/src/compress.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: compress.c,v 1.8 2013/12/01 19:32:15 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.72 2013/11/18 17:54:58 christos Exp $")
42 #else
43 __RCSID("$NetBSD: compress.c,v 1.8 2013/12/01 19:32:15 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 #ifndef __MINGW32__
55 #include <sys/ioctl.h>
56 #endif
57 #ifdef HAVE_SYS_WAIT_H
58 #include <sys/wait.h>
59 #endif
60 #if defined(HAVE_SYS_TIME_H)
61 #include <sys/time.h>
62 #endif
63 #if defined(HAVE_ZLIB_H) && defined(HAVE_LIBZ)
64 #define BUILTIN_DECOMPRESS
65 #include <zlib.h>
66 #endif
67 
68 private const struct {
69 	const char magic[8];
70 	size_t maglen;
71 	const char *argv[3];
72 	int silent;
73 } compr[] = {
74 	{ "\037\235", 2, { "gzip", "-cdq", NULL }, 1 },		/* compressed */
75 	/* Uncompress can get stuck; so use gzip first if we have it
76 	 * Idea from Damien Clark, thanks! */
77 	{ "\037\235", 2, { "uncompress", "-c", NULL }, 1 },	/* compressed */
78 	{ "\037\213", 2, { "gzip", "-cdq", NULL }, 1 },		/* gzipped */
79 	{ "\037\236", 2, { "gzip", "-cdq", NULL }, 1 },		/* frozen */
80 	{ "\037\240", 2, { "gzip", "-cdq", NULL }, 1 },		/* SCO LZH */
81 	/* the standard pack utilities do not accept standard input */
82 	{ "\037\036", 2, { "gzip", "-cdq", NULL }, 0 },		/* packed */
83 	{ "PK\3\4",   4, { "gzip", "-cdq", NULL }, 1 },		/* pkzipped, */
84 					    /* ...only first file examined */
85 	{ "BZh",      3, { "bzip2", "-cd", NULL }, 1 },		/* bzip2-ed */
86 	{ "LZIP",     4, { "lzip", "-cdq", NULL }, 1 },
87  	{ "\3757zXZ\0",6,{ "xz", "-cd", NULL }, 1 },		/* XZ Utils */
88  	{ "LRZI",     4, { "lrzip", "-dqo-", NULL }, 1 },	/* LRZIP */
89 };
90 
91 #define NODATA ((size_t)~0)
92 
93 private ssize_t swrite(int, const void *, size_t);
94 #if HAVE_FORK
95 private size_t ncompr = sizeof(compr) / sizeof(compr[0]);
96 private size_t uncompressbuf(struct magic_set *, int, size_t,
97     const unsigned char *, unsigned char **, size_t);
98 #ifdef BUILTIN_DECOMPRESS
99 private size_t uncompressgzipped(struct magic_set *, const unsigned char *,
100     unsigned char **, size_t);
101 #endif
102 
103 protected int
104 file_zmagic(struct magic_set *ms, int fd, const char *name,
105     const unsigned char *buf, size_t nbytes)
106 {
107 	unsigned char *newbuf = NULL;
108 	size_t i, nsz;
109 	int rv = 0;
110 	int mime = ms->flags & MAGIC_MIME;
111 
112 	if ((ms->flags & MAGIC_COMPRESS) == 0)
113 		return 0;
114 
115 	for (i = 0; i < ncompr; i++) {
116 		if (nbytes < compr[i].maglen)
117 			continue;
118 		if (memcmp(buf, compr[i].magic, compr[i].maglen) == 0 &&
119 		    (nsz = uncompressbuf(ms, fd, i, buf, &newbuf,
120 		    nbytes)) != NODATA) {
121 			ms->flags &= ~MAGIC_COMPRESS;
122 			rv = -1;
123 			if (file_buffer(ms, -1, name, newbuf, nsz) == -1)
124 				goto error;
125 
126 			if (mime == MAGIC_MIME || mime == 0) {
127 				if (file_printf(ms, mime ?
128 				    " compressed-encoding=" : " (") == -1)
129 					goto error;
130 				if (file_buffer(ms, -1, NULL, buf, nbytes) == -1)
131 					goto error;
132 				if (!mime && file_printf(ms, ")") == -1)
133 					goto error;
134 			}
135 
136 			rv = 1;
137 			break;
138 		}
139 	}
140 error:
141 	free(newbuf);
142 	ms->flags |= MAGIC_COMPRESS;
143 	return rv;
144 }
145 #endif
146 /*
147  * `safe' write for sockets and pipes.
148  */
149 private ssize_t
150 swrite(int fd, const void *buf, size_t n)
151 {
152 	ssize_t rv;
153 	size_t rn = n;
154 
155 	do
156 		switch (rv = write(fd, buf, n)) {
157 		case -1:
158 			if (errno == EINTR)
159 				continue;
160 			return -1;
161 		default:
162 			n -= rv;
163 			buf = CAST(const char *, buf) + rv;
164 			break;
165 		}
166 	while (n > 0);
167 	return rn;
168 }
169 
170 
171 /*
172  * `safe' read for sockets and pipes.
173  */
174 protected ssize_t
175 sread(int fd, void *buf, size_t n, int canbepipe __attribute__((__unused__)))
176 {
177 	ssize_t rv;
178 #ifdef FIONREAD
179 	int t = 0;
180 #endif
181 	size_t rn = n;
182 
183 	if (fd == STDIN_FILENO)
184 		goto nocheck;
185 
186 #ifdef FIONREAD
187 	if (canbepipe && (ioctl(fd, FIONREAD, &t) == -1 || t == 0)) {
188 #ifdef FD_ZERO
189 		ssize_t cnt;
190 		for (cnt = 0;; cnt++) {
191 			fd_set check;
192 			struct timeval tout = {0, 100 * 1000};
193 			int selrv;
194 
195 			FD_ZERO(&check);
196 			FD_SET(fd, &check);
197 
198 			/*
199 			 * Avoid soft deadlock: do not read if there
200 			 * is nothing to read from sockets and pipes.
201 			 */
202 			selrv = select(fd + 1, &check, NULL, NULL, &tout);
203 			if (selrv == -1) {
204 				if (errno == EINTR || errno == EAGAIN)
205 					continue;
206 			} else if (selrv == 0 && cnt >= 5) {
207 				return 0;
208 			} else
209 				break;
210 		}
211 #endif
212 		(void)ioctl(fd, FIONREAD, &t);
213 	}
214 
215 	if (t > 0 && (size_t)t < n) {
216 		n = t;
217 		rn = n;
218 	}
219 #endif
220 
221 nocheck:
222 	do
223 		switch ((rv = read(fd, buf, n))) {
224 		case -1:
225 			if (errno == EINTR)
226 				continue;
227 			return -1;
228 		case 0:
229 			return rn - n;
230 		default:
231 			n -= rv;
232 			buf = ((char *)buf) + rv;
233 			break;
234 		}
235 	while (n > 0);
236 	return rn;
237 }
238 
239 protected int
240 file_pipe2file(struct magic_set *ms, int fd, const void *startbuf,
241     size_t nbytes)
242 {
243 	char buf[4096];
244 	ssize_t r;
245 	int tfd;
246 
247 	(void)strlcpy(buf, "/tmp/file.XXXXXX", sizeof buf);
248 #ifndef HAVE_MKSTEMP
249 	{
250 		char *ptr = mktemp(buf);
251 		tfd = open(ptr, O_RDWR|O_TRUNC|O_EXCL|O_CREAT, 0600);
252 		r = errno;
253 		(void)unlink(ptr);
254 		errno = r;
255 	}
256 #else
257 	{
258 		int te;
259 		tfd = mkstemp(buf);
260 		te = errno;
261 		(void)unlink(buf);
262 		errno = te;
263 	}
264 #endif
265 	if (tfd == -1) {
266 		file_error(ms, errno,
267 		    "cannot create temporary file for pipe copy");
268 		return -1;
269 	}
270 
271 	if (swrite(tfd, startbuf, nbytes) != (ssize_t)nbytes)
272 		r = 1;
273 	else {
274 		while ((r = sread(fd, buf, sizeof(buf), 1)) > 0)
275 			if (swrite(tfd, buf, (size_t)r) != r)
276 				break;
277 	}
278 
279 	switch (r) {
280 	case -1:
281 		file_error(ms, errno, "error copying from pipe to temp file");
282 		return -1;
283 	case 0:
284 		break;
285 	default:
286 		file_error(ms, errno, "error while writing to temp file");
287 		return -1;
288 	}
289 
290 	/*
291 	 * We duplicate the file descriptor, because fclose on a
292 	 * tmpfile will delete the file, but any open descriptors
293 	 * can still access the phantom inode.
294 	 */
295 	if ((fd = dup2(tfd, fd)) == -1) {
296 		file_error(ms, errno, "could not dup descriptor for temp file");
297 		return -1;
298 	}
299 	(void)close(tfd);
300 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
301 		file_badseek(ms);
302 		return -1;
303 	}
304 	return fd;
305 }
306 #if HAVE_FORK
307 #ifdef BUILTIN_DECOMPRESS
308 
309 #define FHCRC		(1 << 1)
310 #define FEXTRA		(1 << 2)
311 #define FNAME		(1 << 3)
312 #define FCOMMENT	(1 << 4)
313 
314 private size_t
315 uncompressgzipped(struct magic_set *ms, const unsigned char *old,
316     unsigned char **newch, size_t n)
317 {
318 	unsigned char flg = old[3];
319 	size_t data_start = 10;
320 	z_stream z;
321 	int rc;
322 
323 	if (flg & FEXTRA) {
324 		if (data_start+1 >= n)
325 			return 0;
326 		data_start += 2 + old[data_start] + old[data_start + 1] * 256;
327 	}
328 	if (flg & FNAME) {
329 		while(data_start < n && old[data_start])
330 			data_start++;
331 		data_start++;
332 	}
333 	if(flg & FCOMMENT) {
334 		while(data_start < n && old[data_start])
335 			data_start++;
336 		data_start++;
337 	}
338 	if(flg & FHCRC)
339 		data_start += 2;
340 
341 	if (data_start >= n)
342 		return 0;
343 	if ((*newch = CAST(unsigned char *, malloc(HOWMANY + 1))) == NULL) {
344 		return 0;
345 	}
346 
347 	/* XXX: const castaway, via strchr */
348 	z.next_in = (Bytef *)strchr((const char *)old + data_start,
349 	    old[data_start]);
350 	z.avail_in = CAST(uint32_t, (n - data_start));
351 	z.next_out = *newch;
352 	z.avail_out = HOWMANY;
353 	z.zalloc = Z_NULL;
354 	z.zfree = Z_NULL;
355 	z.opaque = Z_NULL;
356 
357 	/* LINTED bug in header macro */
358 	rc = inflateInit2(&z, -15);
359 	if (rc != Z_OK) {
360 		file_error(ms, 0, "zlib: %s", z.msg);
361 		return 0;
362 	}
363 
364 	rc = inflate(&z, Z_SYNC_FLUSH);
365 	if (rc != Z_OK && rc != Z_STREAM_END) {
366 		file_error(ms, 0, "zlib: %s", z.msg);
367 		return 0;
368 	}
369 
370 	n = (size_t)z.total_out;
371 	(void)inflateEnd(&z);
372 
373 	/* let's keep the nul-terminate tradition */
374 	(*newch)[n] = '\0';
375 
376 	return n;
377 }
378 #endif
379 
380 private size_t
381 uncompressbuf(struct magic_set *ms, int fd, size_t method,
382     const unsigned char *old, unsigned char **newch, size_t n)
383 {
384 	int fdin[2], fdout[2];
385 	ssize_t r;
386 	pid_t pid;
387 
388 #ifdef BUILTIN_DECOMPRESS
389         /* FIXME: This doesn't cope with bzip2 */
390 	if (method == 2)
391 		return uncompressgzipped(ms, old, newch, n);
392 #endif
393 	(void)fflush(stdout);
394 	(void)fflush(stderr);
395 
396 	if ((fd != -1 && pipe(fdin) == -1) || pipe(fdout) == -1) {
397 		file_error(ms, errno, "cannot create pipe");
398 		return NODATA;
399 	}
400 	switch (pid = fork()) {
401 	case 0:	/* child */
402 		(void) close(0);
403 		if (fd != -1) {
404 		    if (dup(fd) == -1)
405 			_exit(1);
406 		    (void) lseek(0, (off_t)0, SEEK_SET);
407 		} else {
408 		    if (dup(fdin[0]) == -1)
409 			_exit(1);
410 		    (void) close(fdin[0]);
411 		    (void) close(fdin[1]);
412 		}
413 
414 		(void) close(1);
415 		if (dup(fdout[1]) == -1)
416 			_exit(1);
417 		(void) close(fdout[0]);
418 		(void) close(fdout[1]);
419 #ifndef DEBUG
420 		if (compr[method].silent)
421 			(void)close(2);
422 #endif
423 
424 		(void)execvp(compr[method].argv[0],
425 		    (char *const *)(intptr_t)compr[method].argv);
426 #ifdef DEBUG
427 		(void)fprintf(stderr, "exec `%s' failed (%s)\n",
428 		    compr[method].argv[0], strerror(errno));
429 #endif
430 		exit(1);
431 		/*NOTREACHED*/
432 	case -1:
433 		file_error(ms, errno, "could not fork");
434 		return NODATA;
435 
436 	default: /* parent */
437 		(void) close(fdout[1]);
438 		if (fd == -1) {
439 			(void) close(fdin[0]);
440 			/*
441 			 * fork again, to avoid blocking because both
442 			 * pipes filled
443 			 */
444 			switch (fork()) {
445 			case 0: /* child */
446 				(void)close(fdout[0]);
447 				if (swrite(fdin[1], old, n) != (ssize_t)n) {
448 #ifdef DEBUG
449 					(void)fprintf(stderr,
450 					    "Write failed (%s)\n",
451 					    strerror(errno));
452 #endif
453 					exit(1);
454 				}
455 				exit(0);
456 				/*NOTREACHED*/
457 
458 			case -1:
459 #ifdef DEBUG
460 				(void)fprintf(stderr, "Fork failed (%s)\n",
461 				    strerror(errno));
462 #endif
463 				exit(1);
464 				/*NOTREACHED*/
465 
466 			default:  /* parent */
467 				break;
468 			}
469 			(void) close(fdin[1]);
470 			fdin[1] = -1;
471 		}
472 
473 		if ((*newch = (unsigned char *) malloc(HOWMANY + 1)) == NULL) {
474 #ifdef DEBUG
475 			(void)fprintf(stderr, "Malloc failed (%s)\n",
476 			    strerror(errno));
477 #endif
478 			n = 0;
479 			goto err;
480 		}
481 		if ((r = sread(fdout[0], *newch, HOWMANY, 0)) <= 0) {
482 #ifdef DEBUG
483 			(void)fprintf(stderr, "Read failed (%s)\n",
484 			    strerror(errno));
485 #endif
486 			free(*newch);
487 			n = 0;
488 			*newch = NULL;
489 			goto err;
490 		} else {
491 			n = r;
492 		}
493  		/* NUL terminate, as every buffer is handled here. */
494  		(*newch)[n] = '\0';
495 err:
496 		if (fdin[1] != -1)
497 			(void) close(fdin[1]);
498 		(void) close(fdout[0]);
499 #ifdef WNOHANG
500 		while (waitpid(pid, NULL, WNOHANG) != -1)
501 			continue;
502 #else
503 		(void)wait(NULL);
504 #endif
505 		(void) close(fdin[0]);
506 
507 		return n;
508 	}
509 }
510 #endif
511