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