2 * Copyright (C) 2009 Andy Spencer <spenceal@rose-hulman.edu>
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <arpa/inet.h>
25 #define debug(...) fprintf(stderr, __VA_ARGS__);
27 char *bunzip2(char *input, int input_len, int *output_len)
29 bz_stream *stream = calloc(1, sizeof(bz_stream));
31 switch (BZ2_bzDecompressInit(stream, 0, 0)) {
32 case BZ_CONFIG_ERROR: err(1, "the library has been mis-compiled");
33 case BZ_PARAM_ERROR: err(1, "Parameter error");
34 case BZ_MEM_ERROR: err(1, "insufficient memory is available");
35 //case BZ_OK: debug("success\n"); break;
36 //default: debug("unknown\n"); break;
40 int output_size = 512;
44 stream->next_in = input + stream->total_in_lo32;
45 stream->avail_in = input_len - stream->total_in_lo32;
47 output = realloc(output, output_size);
48 //debug("alloc %d\n", output_size);
49 stream->next_out = output + stream->total_out_lo32;
50 stream->avail_out = output_size - stream->total_out_lo32;
51 //debug("decompressing..\n"
55 // " avail_out = %u\n",
59 // stream->avail_out);
60 } while ((status = BZ2_bzDecompress(stream)) == BZ_OK && output_size < 1024*1024);
62 // debug("done with status %d = %d\n", status, BZ_STREAM_END);
64 *output_len = stream->total_out_lo32;
65 BZ2_bzDecompressEnd(stream);
69 int main(int argc, char **argv)
72 printf("usage: %s <input> <output>\n", argv[0]);
76 FILE *input = fopen(argv[1], "r");
77 FILE *output = fopen(argv[2], "w+");
78 if (!input) err(1, "error opening input");
79 if (!output) err(1, "error opening output");
83 char *buf = malloc(24);
86 //debug("reading header\n");
87 fread (buf, 1, 24, input);
88 fwrite(buf, 1, 24, output);
90 //debug("reading body\n");
91 while ((st = fread(&size, 1, 4, input))) {
92 //debug("read %u bytes\n", st);
93 //fwrite(&size, 1, 4, output); // DEBUG
94 size = abs(ntohl(size));
97 //debug("size = %x\n", size);
98 if (size > 10*1024*1024)
99 err(1, "sanity check failed, buf is to big: %d", size);
100 buf = realloc(buf, size);
101 fread (buf, 1, size, input);
102 //fwrite(buf, 1, size, output); // DEBUG
105 char *dec = bunzip2(buf, size, &dec_len);
106 // debug("decompressed %u bytes\n", dec_len);
107 fwrite(dec, 1, dec_len, output);