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