1 /* $NetBSD: unbzip2.c,v 1.13 2009/12/05 03:23:37 mrg Exp $ */
4 * Copyright (c) 2006 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
32 /* This file is #included by gzip.c */
35 unbzip2(int in
, int out
, char *pre
, size_t prelen
, off_t
*bytes_in
)
37 int ret
, end_of_file
, cold
= 0;
40 static char *inbuf
, *outbuf
;
43 inbuf
= malloc(BUFLEN
);
45 outbuf
= malloc(BUFLEN
);
46 if (inbuf
== NULL
|| outbuf
== NULL
)
54 ret
= BZ2_bzDecompressInit(&bzs
, 0, 0);
56 maybe_errx("bzip2 init");
59 bzs
.avail_in
= prelen
;
65 while (ret
== BZ_OK
) {
66 if (bzs
.avail_in
== 0 && !end_of_file
) {
69 n
= read(in
, inbuf
, BUFLEN
);
80 bzs
.next_out
= outbuf
;
81 bzs
.avail_out
= BUFLEN
;
82 ret
= BZ2_bzDecompress(&bzs
);
87 if (ret
== BZ_OK
&& end_of_file
) {
89 * If we hit this after a stream end, consider
90 * it as the end of the whole file and don't
96 maybe_errx("truncated file");
99 if (!tflag
&& bzs
.avail_out
!= BUFLEN
) {
102 n
= write(out
, outbuf
, BUFLEN
- bzs
.avail_out
);
107 if (ret
== BZ_STREAM_END
&& !end_of_file
) {
108 if (BZ2_bzDecompressEnd(&bzs
) != BZ_OK
||
109 BZ2_bzDecompressInit(&bzs
, 0, 0) != BZ_OK
)
110 maybe_errx("bzip2 re-init");
117 maybe_warnx("bzip2 data integrity error");
120 case BZ_DATA_ERROR_MAGIC
:
121 maybe_warnx("bzip2 magic number error");
125 maybe_warnx("bzip2 out of memory");
129 maybe_warnx("unknown bzip2 error: %d", ret
);
134 if (ret
!= BZ_STREAM_END
|| BZ2_bzDecompressEnd(&bzs
) != BZ_OK
)