Home | History | Annotate | Line # | Download | only in gzip
unbzip2.c revision 1.3
      1 /*	$NetBSD: unbzip2.c,v 1.3 2004/03/30 11:43:32 mrg Exp $	*/
      2 
      3 /* This file is #included by gzip.c */
      4 
      5 #define INBUFSIZE	(64 * 1024)
      6 #define OUTBUFSIZE	(64 * 1024)
      7 
      8 static off_t
      9 unbzip2(int in, int out)
     10 {
     11 	int		n, ret, end_of_file;
     12 	off_t		bytes_out = 0;
     13 	bz_stream	bzs;
     14 	static char	*inbuf, *outbuf;
     15 
     16 	if (inbuf == NULL && (inbuf = malloc(INBUFSIZE)) == NULL)
     17 	        maybe_err(1, "malloc");
     18 	if (outbuf == NULL && (outbuf = malloc(OUTBUFSIZE)) == NULL)
     19 	        maybe_err(1, "malloc");
     20 
     21 	bzs.bzalloc = NULL;
     22 	bzs.bzfree = NULL;
     23 	bzs.opaque = NULL;
     24 
     25 	end_of_file = 0;
     26 	ret = BZ2_bzDecompressInit(&bzs, 0, 0);
     27 	if (ret != BZ_OK)
     28 	        maybe_errx(1, "bzip2 init");
     29 
     30 	bzs.avail_in = 0;
     31 
     32 	while (ret != BZ_STREAM_END) {
     33 	        if (bzs.avail_in == 0 && !end_of_file) {
     34 	                n = read(in, inbuf, INBUFSIZE);
     35 	                if (n < 0)
     36 	                        maybe_err(1, "read");
     37 	                if (n == 0)
     38 	                        end_of_file = 1;
     39 	                bzs.next_in = inbuf;
     40 	                bzs.avail_in = n;
     41 	        } else
     42 	                n = 0;
     43 
     44 	        bzs.next_out = outbuf;
     45 	        bzs.avail_out = OUTBUFSIZE;
     46 	        ret = BZ2_bzDecompress(&bzs);
     47 
     48 	        switch (ret) {
     49 	        case BZ_STREAM_END:
     50 	        case BZ_OK:
     51 	                if (ret == BZ_OK && end_of_file)
     52 	                        maybe_err(1, "read");
     53 	                if (!tflag) {
     54 	                        n = write(out, outbuf, OUTBUFSIZE - bzs.avail_out);
     55 	                        if (n < 0)
     56 	                                maybe_err(1, "write");
     57 	                }
     58 	                bytes_out += n;
     59 	                break;
     60 
     61 	        case BZ_DATA_ERROR:
     62 	                maybe_errx(1, "bzip2 data integrity error");
     63 	        case BZ_DATA_ERROR_MAGIC:
     64 	                maybe_errx(1, "bzip2 magic number error");
     65 	        case BZ_MEM_ERROR:
     66 	                maybe_errx(1, "bzip2 out of memory");
     67 	        }
     68 	}
     69 
     70 	if (BZ2_bzDecompressEnd(&bzs) != BZ_OK)
     71 	        return (0);
     72 
     73 	return (bytes_out);
     74 }
     75