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.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
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
38 FILE_RCSID("@(#)$File: compress.c,v 1.93 2016/03/31 17:51:12 christos Exp $")
53 typedef void (*sig_t)(int);
54 # endif /* HAVE_SIG_T */
56 #if !defined(__MINGW32__) && !defined(WIN32)
57 #include <sys/ioctl.h>
59 #ifdef HAVE_SYS_WAIT_H
62 #if defined(HAVE_SYS_TIME_H)
65 #if defined(HAVE_ZLIB_H) && defined(HAVE_LIBZ)
66 #define BUILTIN_DECOMPRESS
72 #define DPRINTF(...) do { \
74 tty = open("/dev/tty", O_RDWR); \
77 dprintf(tty, __VA_ARGS__); \
78 } while (/*CONSTCOND*/0)
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.
88 static const char zlibcode[] =
89 "import sys, zlib; sys.stdout.write(zlib.decompress(sys.stdin.read()))";
91 static const char *zlib_args[] = { "python", "-c", zlibcode, NULL };
94 zlibcmp(const unsigned char *buf)
97 unsigned char *s = (unsigned char *)&x;
99 if ((buf[0] & 0xf) != 8 || (buf[0] & 0x80) != 0)
101 if (s[0] != 1) /* endianness test */
102 x = buf[0] | (buf[1] << 8);
104 x = buf[1] | (buf[0] << 8);
111 #define gzip_flags "-cd"
112 #define lrzip_flags "-do"
113 #define lzip_flags gzip_flags
115 static const char *gzip_args[] = {
116 "gzip", gzip_flags, NULL
118 static const char *uncompress_args[] = {
119 "uncompress", "-c", NULL
121 static const char *bzip2_args[] = {
124 static const char *lzip_args[] = {
125 "lzip", lzip_flags, NULL
127 static const char *xz_args[] = {
130 static const char *lrzip_args[] = {
131 "lrzip", lrzip_flags, NULL
133 static const char *lz4_args[] = {
137 private const struct {
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 */
159 { zlibcmp, 0, zlib_args }, /* zlib */
167 private ssize_t swrite(int, const void *, size_t);
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,
175 private int uncompressgzipped(const unsigned char *, unsigned char **, size_t,
178 static int makeerror(unsigned char **, size_t *, const char *, ...)
179 __attribute__((__format__(__printf__, 3, 4)));
180 private const char *methodname(size_t);
183 file_zmagic(struct magic_set *ms, int fd, const char *name,
184 const unsigned char *buf, size_t nbytes)
186 unsigned char *newbuf = NULL;
191 int mime = ms->flags & MAGIC_MIME;
196 if ((ms->flags & MAGIC_COMPRESS) == 0)
200 osigpipe = signal(SIGPIPE, SIG_IGN);
202 for (i = 0; i < ncompr; i++) {
204 if (nbytes < compr[i].maglen)
207 if (compr[i].maglen == 0)
208 zm = (CAST(int (*)(const unsigned char *),
209 CCAST(void *, compr[i].magic)))(buf);
212 zm = memcmp(buf, compr[i].magic, compr[i].maglen) == 0;
217 rv = uncompressbuf(fd, ms->bytes_max, i, buf, &newbuf, &nsz);
218 DPRINTF("uncompressbuf = %d, %s, %zu\n", rv, (char *)newbuf,
224 ms->flags &= ~MAGIC_COMPRESS;
226 rv = file_printf(ms, "%s ERROR: %s",
227 methodname(i), newbuf);
229 rv = file_buffer(ms, -1, name, newbuf, nsz);
232 DPRINTF("rv = %d\n", rv);
233 if ((ms->flags & MAGIC_COMPRESS_TRANSP) != 0)
235 if (mime != MAGIC_MIME && mime != 0)
238 mime ? " compressed-encoding=" : " (")) == -1)
240 if ((pb = file_push_buffer(ms)) == NULL)
242 if (file_buffer(ms, -1, NULL, buf, nbytes) == -1)
244 if ((rbuf = file_pop_buffer(ms, pb)) != NULL) {
245 if (file_printf(ms, "%s", rbuf) == -1) {
251 if (!mime && file_printf(ms, ")") == -1)
264 (void)signal(SIGPIPE, osigpipe);
267 ms->flags |= MAGIC_COMPRESS;
268 DPRINTF("Zmagic returns %d\n", rv);
273 * `safe' write for sockets and pipes.
276 swrite(int fd, const void *buf, size_t n)
282 switch (rv = write(fd, buf, n)) {
289 buf = CAST(const char *, buf) + rv;
298 * `safe' read for sockets and pipes.
301 sread(int fd, void *buf, size_t n, int canbepipe __attribute__((__unused__)))
309 if (fd == STDIN_FILENO)
313 if (canbepipe && (ioctl(fd, FIONREAD, &t) == -1 || t == 0)) {
316 for (cnt = 0;; cnt++) {
318 struct timeval tout = {0, 100 * 1000};
325 * Avoid soft deadlock: do not read if there
326 * is nothing to read from sockets and pipes.
328 selrv = select(fd + 1, &check, NULL, NULL, &tout);
330 if (errno == EINTR || errno == EAGAIN)
332 } else if (selrv == 0 && cnt >= 5) {
338 (void)ioctl(fd, FIONREAD, &t);
341 if (t > 0 && (size_t)t < n) {
349 switch ((rv = read(fd, buf, n))) {
358 buf = ((char *)buf) + rv;
366 file_pipe2file(struct magic_set *ms, int fd, const void *startbuf,
373 (void)strlcpy(buf, "/tmp/file.XXXXXX", sizeof buf);
376 char *ptr = mktemp(buf);
377 tfd = open(ptr, O_RDWR|O_TRUNC|O_EXCL|O_CREAT, 0600);
392 file_error(ms, errno,
393 "cannot create temporary file for pipe copy");
397 if (swrite(tfd, startbuf, nbytes) != (ssize_t)nbytes)
400 while ((r = sread(fd, buf, sizeof(buf), 1)) > 0)
401 if (swrite(tfd, buf, (size_t)r) != r)
407 file_error(ms, errno, "error copying from pipe to temp file");
412 file_error(ms, errno, "error while writing to temp file");
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.
421 if ((fd = dup2(tfd, fd)) == -1) {
422 file_error(ms, errno, "could not dup descriptor for temp file");
426 if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
433 #ifdef BUILTIN_DECOMPRESS
435 #define FHCRC (1 << 1)
436 #define FEXTRA (1 << 2)
437 #define FNAME (1 << 3)
438 #define FCOMMENT (1 << 4)
442 uncompressgzipped(const unsigned char *old, unsigned char **newch,
443 size_t bytes_max, size_t *n)
445 unsigned char flg = old[3];
446 size_t data_start = 10;
449 if (data_start + 1 >= *n)
451 data_start += 2 + old[data_start] + old[data_start + 1] * 256;
454 while(data_start < *n && old[data_start])
458 if (flg & FCOMMENT) {
459 while(data_start < *n && old[data_start])
466 if (data_start >= *n)
471 return uncompresszlib(old, newch, bytes_max, n, 0);
473 return makeerror(newch, n, "File too short");
477 uncompresszlib(const unsigned char *old, unsigned char **newch,
478 size_t bytes_max, size_t *n, int zlib)
483 if ((*newch = CAST(unsigned char *, malloc(bytes_max + 1))) == NULL)
484 return makeerror(newch, n, "No buffer, %s", strerror(errno));
486 z.next_in = CCAST(Bytef *, old);
487 z.avail_in = CAST(uint32_t, *n);
489 z.avail_out = bytes_max;
494 /* LINTED bug in header macro */
495 rc = zlib ? inflateInit(&z) : inflateInit2(&z, -15);
499 rc = inflate(&z, Z_SYNC_FLUSH);
500 if (rc != Z_OK && rc != Z_STREAM_END)
503 *n = (size_t)z.total_out;
508 /* let's keep the nul-terminate tradition */
513 strlcpy((char *)*newch, z.msg, bytes_max);
514 *n = strlen((char *)*newch);
520 makeerror(unsigned char **buf, size_t *len, const char *fmt, ...)
527 rv = vasprintf(&msg, fmt, ap);
534 *buf = (unsigned char *)msg;
540 closefd(int *fd, size_t i)
552 for (i = 0; i < 2; i++)
557 copydesc(int i, int *fd)
559 int j = fd[i == STDIN_FILENO ? 0 : 1];
562 if (dup2(j, i) == -1) {
563 DPRINTF("dup(%d, %d) failed (%s)\n", j, i, strerror(errno));
570 writechild(int fdp[3][2], const void *old, size_t n)
574 closefd(fdp[STDIN_FILENO], 0);
576 * fork again, to avoid blocking because both
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));
590 DPRINTF("Fork failed (%s)\n", strerror(errno));
594 default: /* parent */
595 if (wait(&status) == -1) {
596 DPRINTF("Wait failed (%s)\n", strerror(errno));
599 DPRINTF("Grandchild wait return %#x\n", status);
601 closefd(fdp[STDIN_FILENO], 1);
605 filter_error(unsigned char *ubuf, ssize_t n)
612 while (isspace((unsigned char)*buf))
614 DPRINTF("Filter error[[[%s]]]\n", buf);
615 if ((p = strchr((char *)buf, '\n')) != NULL)
617 if ((p = strchr((char *)buf, ';')) != NULL)
619 if ((p = strrchr((char *)buf, ':')) != NULL) {
621 while (isspace((unsigned char)*p))
624 memmove(ubuf, p, n + 1);
626 DPRINTF("Filter error after[[[%s]]]\n", (char *)ubuf);
628 *ubuf = toupper(*ubuf);
633 methodname(size_t method)
635 #ifdef BUILTIN_DECOMPRESS
636 /* FIXME: This doesn't cope with bzip2 */
637 if (method == 2 || compr[method].maglen == 0)
640 return compr[method].argv[0];
644 uncompressbuf(int fd, size_t bytes_max, size_t method, const unsigned char *old,
645 unsigned char **newch, size_t* n)
652 #ifdef BUILTIN_DECOMPRESS
653 /* FIXME: This doesn't cope with bzip2 */
655 return uncompressgzipped(old, newch, bytes_max, n);
656 if (compr[method].maglen == 0)
657 return uncompresszlib(old, newch, bytes_max, n, 1);
659 (void)fflush(stdout);
660 (void)fflush(stderr);
662 for (i = 0; i < __arraycount(fdp); i++)
663 fdp[i][0] = fdp[i][1] = -1;
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",
675 fdp[STDIN_FILENO][0] = fd;
676 (void) lseek(fd, (off_t)0, SEEK_SET);
679 for (i = 0; i < __arraycount(fdp); i++)
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));
689 return makeerror(newch, n, "Cannot fork, %s",
692 default: /* parent */
693 for (i = 1; i < __arraycount(fdp); i++)
696 /* Write the buffer data to the child, if we don't have fd */
698 writechild(fdp, old, *n);
700 *newch = CAST(unsigned char *, malloc(bytes_max + 1));
701 if (*newch == NULL) {
702 rv = makeerror(newch, n, "No buffer, %s",
707 if ((r = sread(fdp[STDOUT_FILENO][0], *newch, bytes_max, 0)) > 0)
709 DPRINTF("Read stdout failed %d (%s)\n", fdp[STDOUT_FILENO][0],
710 r != -1 ? strerror(errno) : "no data");
714 (r = sread(fdp[STDERR_FILENO][0], *newch, bytes_max, 0)) > 0)
716 r = filter_error(*newch, r);
721 rv = makeerror(newch, n, "Read failed, %s",
724 rv = makeerror(newch, n, "No data");
729 /* NUL terminate, as every buffer is handled here. */
732 closefd(fdp[STDIN_FILENO], 1);
733 closefd(fdp[STDOUT_FILENO], 0);
734 closefd(fdp[STDERR_FILENO], 0);
735 if (wait(&status) == -1) {
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));
745 closefd(fdp[STDIN_FILENO], 0);
746 DPRINTF("Returning %p n=%zu rv=%d\n", *newch, *n, rv);