xref: /netbsd-src/usr.bin/gzip/unbzip2.c (revision d20841bb642898112fe68f0ad3f7b26dddf56f07)
1 /*	$NetBSD: unbzip2.c,v 1.1 2004/01/01 02:44:09 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 	char            *inbuf, *outbuf;
15 
16 	if ((inbuf = malloc(INBUFSIZE)) == NULL)
17 	        maybe_err(1, "malloc");
18 	if ((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 	                if (ret == BZ_STREAM_END)
60 	                        break;
61 
62 	        case BZ_DATA_ERROR:
63 	                maybe_errx(1, "bzip2 data integrity error");
64 	        case BZ_DATA_ERROR_MAGIC:
65 	                maybe_errx(1, "bzip2 magic number error");
66 	        case BZ_MEM_ERROR:
67 	                maybe_errx(1, "bzip2 out of memory");
68 	        }
69 	}
70 
71 	if (BZ2_bzDecompressEnd(&bzs) != BZ_OK)
72 	        return (0);
73 
74 	return (bytes_out);
75 }
76