]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/file/compress.c
This commit was generated by cvs2svn to compensate for changes in r167617,
[FreeBSD/FreeBSD.git] / contrib / file / compress.c
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 #include "magic.h"
37 #include <stdio.h>
38 #include <stdlib.h>
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42 #include <string.h>
43 #include <errno.h>
44 #include <sys/types.h>
45 #ifdef HAVE_SYS_WAIT_H
46 #include <sys/wait.h>
47 #endif
48 #ifdef HAVE_LIBZ
49 #include <zlib.h>
50 #endif
51
52 #ifndef lint
53 FILE_RCSID("@(#)$Id: compress.c,v 1.42 2005/03/06 05:58:22 christos Exp $")
54 #endif
55
56
57 private struct {
58         const char *magic;
59         size_t maglen;
60         const char *const argv[3];
61         int silent;
62 } compr[] = {
63         { "\037\235", 2, { "gzip", "-cdq", NULL }, 1 },         /* compressed */
64         /* Uncompress can get stuck; so use gzip first if we have it
65          * Idea from Damien Clark, thanks! */
66         { "\037\235", 2, { "uncompress", "-c", NULL }, 1 },     /* compressed */
67         { "\037\213", 2, { "gzip", "-cdq", NULL }, 1 },         /* gzipped */
68         { "\037\236", 2, { "gzip", "-cdq", NULL }, 1 },         /* frozen */
69         { "\037\240", 2, { "gzip", "-cdq", NULL }, 1 },         /* SCO LZH */
70         /* the standard pack utilities do not accept standard input */
71         { "\037\036", 2, { "gzip", "-cdq", NULL }, 0 },         /* packed */
72         { "PK\3\4",   4, { "gzip", "-cdq", NULL }, 1 },         /* pkzipped, */
73                                             /* ...only first file examined */
74         { "BZh",      3, { "bzip2", "-cd", NULL }, 1 },         /* bzip2-ed */
75 };
76
77 private int ncompr = sizeof(compr) / sizeof(compr[0]);
78
79
80 private ssize_t swrite(int, const void *, size_t);
81 private ssize_t sread(int, void *, size_t);
82 private size_t uncompressbuf(struct magic_set *, int, size_t,
83     const unsigned char *, unsigned char **, size_t);
84 #ifdef HAVE_LIBZ
85 private size_t uncompressgzipped(struct magic_set *, const unsigned char *,
86     unsigned char **, size_t);
87 #endif
88
89 protected int
90 file_zmagic(struct magic_set *ms, int fd, const unsigned char *buf,
91     size_t nbytes)
92 {
93         unsigned char *newbuf = NULL;
94         size_t i, nsz;
95         int rv = 0;
96
97         if ((ms->flags & MAGIC_COMPRESS) == 0)
98                 return 0;
99
100         for (i = 0; i < ncompr; i++) {
101                 if (nbytes < compr[i].maglen)
102                         continue;
103                 if (memcmp(buf, compr[i].magic, compr[i].maglen) == 0 &&
104                     (nsz = uncompressbuf(ms, fd, i, buf, &newbuf,
105                     nbytes)) != 0) {
106                         ms->flags &= ~MAGIC_COMPRESS;
107                         rv = -1;
108                         if (file_buffer(ms, -1, newbuf, nsz) == -1)
109                                 goto error;
110                         if (file_printf(ms, " (") == -1)
111                                 goto error;
112                         if (file_buffer(ms, -1, buf, nbytes) == -1)
113                                 goto error;
114                         if (file_printf(ms, ")") == -1)
115                                 goto error;
116                         rv = 1;
117                         break;
118                 }
119         }
120 error:
121         if (newbuf)
122                 free(newbuf);
123         ms->flags |= MAGIC_COMPRESS;
124         return rv;
125 }
126
127 /*
128  * `safe' write for sockets and pipes.
129  */
130 private ssize_t
131 swrite(int fd, const void *buf, size_t n)
132 {
133         int rv;
134         size_t rn = n;
135
136         do
137                 switch (rv = write(fd, buf, n)) {
138                 case -1:
139                         if (errno == EINTR)
140                                 continue;
141                         return -1;
142                 default:
143                         n -= rv;
144                         buf = ((const char *)buf) + rv;
145                         break;
146                 }
147         while (n > 0);
148         return rn;
149 }
150
151
152 /*
153  * `safe' read for sockets and pipes.
154  */
155 private ssize_t
156 sread(int fd, void *buf, size_t n)
157 {
158         int rv;
159         size_t rn = n;
160
161         do
162                 switch (rv = read(fd, buf, n)) {
163                 case -1:
164                         if (errno == EINTR)
165                                 continue;
166                         return -1;
167                 case 0:
168                         return rn - n;
169                 default:
170                         n -= rv;
171                         buf = ((char *)buf) + rv;
172                         break;
173                 }
174         while (n > 0);
175         return rn;
176 }
177
178 protected int
179 file_pipe2file(struct magic_set *ms, int fd, const void *startbuf,
180     size_t nbytes)
181 {
182         char buf[4096];
183         int r, tfd;
184
185         (void)strcpy(buf, "/tmp/file.XXXXXX");
186 #ifndef HAVE_MKSTEMP
187         {
188                 char *ptr = mktemp(buf);
189                 tfd = open(ptr, O_RDWR|O_TRUNC|O_EXCL|O_CREAT, 0600);
190                 r = errno;
191                 (void)unlink(ptr);
192                 errno = r;
193         }
194 #else
195         tfd = mkstemp(buf);
196         r = errno;
197         (void)unlink(buf);
198         errno = r;
199 #endif
200         if (tfd == -1) {
201                 file_error(ms, errno,
202                     "cannot create temporary file for pipe copy");
203                 return -1;
204         }
205
206         if (swrite(tfd, startbuf, nbytes) != (ssize_t)nbytes)
207                 r = 1;
208         else {
209                 while ((r = sread(fd, buf, sizeof(buf))) > 0)
210                         if (swrite(tfd, buf, (size_t)r) != r)
211                                 break;
212         }
213
214         switch (r) {
215         case -1:
216                 file_error(ms, errno, "error copying from pipe to temp file");
217                 return -1;
218         case 0:
219                 break;
220         default:
221                 file_error(ms, errno, "error while writing to temp file");
222                 return -1;
223         }
224
225         /*
226          * We duplicate the file descriptor, because fclose on a
227          * tmpfile will delete the file, but any open descriptors
228          * can still access the phantom inode.
229          */
230         if ((fd = dup2(tfd, fd)) == -1) {
231                 file_error(ms, errno, "could not dup descriptor for temp file");
232                 return -1;
233         }
234         (void)close(tfd);
235         if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
236                 file_badseek(ms);
237                 return -1;
238         }
239         return fd;
240 }
241
242 #ifdef HAVE_LIBZ
243
244 #define FHCRC           (1 << 1)
245 #define FEXTRA          (1 << 2)
246 #define FNAME           (1 << 3)
247 #define FCOMMENT        (1 << 4)
248
249 private size_t
250 uncompressgzipped(struct magic_set *ms, const unsigned char *old,
251     unsigned char **newch, size_t n)
252 {
253         unsigned char flg = old[3];
254         size_t data_start = 10;
255         z_stream z;
256         int rc;
257
258         if (flg & FEXTRA) {
259                 if (data_start+1 >= n)
260                         return 0;
261                 data_start += 2 + old[data_start] + old[data_start + 1] * 256;
262         }
263         if (flg & FNAME) {
264                 while(data_start < n && old[data_start])
265                         data_start++;
266                 data_start++;
267         }
268         if(flg & FCOMMENT) {
269                 while(data_start < n && old[data_start])
270                         data_start++;
271                 data_start++;
272         }
273         if(flg & FHCRC)
274                 data_start += 2;
275
276         if (data_start >= n)
277                 return 0;
278         if ((*newch = (unsigned char *)malloc(HOWMANY + 1)) == NULL) {
279                 return 0;
280         }
281         
282         /* XXX: const castaway, via strchr */
283         z.next_in = (Bytef *)strchr((const char *)old + data_start,
284             old[data_start]);
285         z.avail_in = n - data_start;
286         z.next_out = *newch;
287         z.avail_out = HOWMANY;
288         z.zalloc = Z_NULL;
289         z.zfree = Z_NULL;
290         z.opaque = Z_NULL;
291
292         rc = inflateInit2(&z, -15);
293         if (rc != Z_OK) {
294                 file_error(ms, 0, "zlib: %s", z.msg);
295                 return 0;
296         }
297
298         rc = inflate(&z, Z_SYNC_FLUSH);
299         if (rc != Z_OK && rc != Z_STREAM_END) {
300                 file_error(ms, 0, "zlib: %s", z.msg);
301                 return 0;
302         }
303
304         n = (size_t)z.total_out;
305         inflateEnd(&z);
306         
307         /* let's keep the nul-terminate tradition */
308         (*newch)[n++] = '\0';
309
310         return n;
311 }
312 #endif
313
314 private size_t
315 uncompressbuf(struct magic_set *ms, int fd, size_t method,
316     const unsigned char *old, unsigned char **newch, size_t n)
317 {
318         int fdin[2], fdout[2];
319         int r;
320
321 #ifdef HAVE_LIBZ
322         if (method == 2)
323                 return uncompressgzipped(ms, old, newch, n);
324 #endif
325         (void)fflush(stdout);
326         (void)fflush(stderr);
327
328         if ((fd != -1 && pipe(fdin) == -1) || pipe(fdout) == -1) {
329                 file_error(ms, errno, "cannot create pipe");    
330                 return 0;
331         }
332         switch (fork()) {
333         case 0: /* child */
334                 (void) close(0);
335                 if (fd != -1) {
336                     (void) dup(fd);
337                     (void) lseek(0, (off_t)0, SEEK_SET);
338                 } else {
339                     (void) dup(fdin[0]);
340                     (void) close(fdin[0]);
341                     (void) close(fdin[1]);
342                 }
343
344                 (void) close(1);
345                 (void) dup(fdout[1]);
346                 (void) close(fdout[0]);
347                 (void) close(fdout[1]);
348 #ifndef DEBUG
349                 if (compr[method].silent)
350                         (void)close(2);
351 #endif
352
353                 execvp(compr[method].argv[0],
354                        (char *const *)(intptr_t)compr[method].argv);
355 #ifdef DEBUG
356                 (void)fprintf(stderr, "exec `%s' failed (%s)\n",
357                     compr[method].argv[0], strerror(errno));
358 #endif
359                 exit(1);
360                 /*NOTREACHED*/
361         case -1:
362                 file_error(ms, errno, "could not fork");
363                 return 0;
364
365         default: /* parent */
366                 (void) close(fdout[1]);
367                 if (fd == -1) {
368                         (void) close(fdin[0]);
369                         /* 
370                          * fork again, to avoid blocking because both
371                          * pipes filled
372                          */
373                         switch (fork()) {
374                         case 0: /* child */
375                                 (void)close(fdout[0]);
376                                 if (swrite(fdin[1], old, n) != n) {
377 #ifdef DEBUG
378                                         (void)fprintf(stderr,
379                                             "Write failed (%s)\n",
380                                             strerror(errno));
381 #endif
382                                         exit(1);
383                                 }
384                                 exit(0);
385                                 /*NOTREACHED*/
386
387                         case -1:
388 #ifdef DEBUG
389                                 (void)fprintf(stderr, "Fork failed (%s)\n",
390                                     strerror(errno));
391 #endif
392                                 exit(1);
393                                 /*NOTREACHED*/
394
395                         default:  /* parent */
396                                 break;
397                         }
398                         (void) close(fdin[1]);
399                         fdin[1] = -1;
400                 }
401
402                 if ((*newch = (unsigned char *) malloc(HOWMANY + 1)) == NULL) {
403 #ifdef DEBUG
404                         (void)fprintf(stderr, "Malloc failed (%s)\n",
405                             strerror(errno));
406 #endif
407                         n = 0;
408                         goto err;
409                 }
410                 if ((r = sread(fdout[0], *newch, HOWMANY)) <= 0) {
411 #ifdef DEBUG
412                         (void)fprintf(stderr, "Read failed (%s)\n",
413                             strerror(errno));
414 #endif
415                         free(*newch);
416                         n = 0;
417                         newch[0] = '\0';
418                         goto err;
419                 } else {
420                         n = r;
421                 }
422                 /* NUL terminate, as every buffer is handled here. */
423                 (*newch)[n++] = '\0';
424 err:
425                 if (fdin[1] != -1)
426                         (void) close(fdin[1]);
427                 (void) close(fdout[0]);
428 #ifdef WNOHANG
429                 while (waitpid(-1, NULL, WNOHANG) != -1)
430                         continue;
431 #else
432                 (void)wait(NULL);
433 #endif
434                 return n;
435         }
436 }