xref: /freebsd/usr.bin/gzip/unpack.c (revision b3e7694832e81d7a904a10f525f8797b753bf0d3)
1 /*	$FreeBSD$	*/
2 /*	$NetBSD: unpack.c,v 1.3 2017/08/04 07:27:08 mrg Exp $	*/
3 
4 /*-
5  * SPDX-License-Identifier: BSD-2-Clause
6  *
7  * Copyright (c) 2009 Xin LI <delphij@FreeBSD.org>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 /* This file is #included by gzip.c */
32 
33 /*
34  * pack(1) file format:
35  *
36  * The first 7 bytes is the header:
37  *	00, 01 - Signature (US, RS), we already validated it earlier.
38  *	02..05 - Uncompressed size
39  *	    06 - Level for the huffman tree (<=24)
40  *
41  * pack(1) will then store symbols (leaf) nodes count in each huffman
42  * tree levels, each level would consume 1 byte (See [1]).
43  *
44  * After the symbol count table, there is the symbol table, storing
45  * symbols represented by corresponding leaf node.  EOB is not being
46  * explicitly transmitted (not necessary anyway) in the symbol table.
47  *
48  * Compressed data goes after the symbol table.
49  *
50  * NOTES
51  *
52  * [1] If we count EOB into the symbols, that would mean that we will
53  * have at most 256 symbols in the huffman tree.  pack(1) rejects empty
54  * file and files that just repeats one character, which means that we
55  * will have at least 2 symbols.  Therefore, pack(1) would reduce the
56  * last level symbol count by 2 which makes it a number in
57  * range [0..254], so all levels' symbol count would fit into 1 byte.
58  */
59 
60 #define	PACK_HEADER_LENGTH	7
61 #define	HTREE_MAXLEVEL		24
62 
63 /*
64  * unpack descriptor
65  *
66  * Represent the huffman tree in a similar way that pack(1) would
67  * store in a packed file.  We store all symbols in a linear table,
68  * and store pointers to each level's first symbol.  In addition to
69  * that, maintain two counts for each level: inner nodes count and
70  * leaf nodes count.
71  */
72 typedef struct {
73 	int	symbol_size;		/* Size of the symbol table */
74 	int	treelevels;		/* Levels for the huffman tree */
75 
76 	int    *symbolsin;		/* Table of leaf symbols count in each
77 					 * level */
78 	int    *inodesin;		/* Table of internal nodes count in
79 					 * each level */
80 
81 	char   *symbol;			/* The symbol table */
82 	char   *symbol_eob;		/* Pointer to the EOB symbol */
83 	char  **tree;			/* Decoding huffman tree (pointers to
84 					 * first symbol of each tree level */
85 
86 	off_t	uncompressed_size;	/* Uncompressed size */
87 	FILE   *fpIn;			/* Input stream */
88 	FILE   *fpOut;			/* Output stream */
89 } unpack_descriptor_t;
90 
91 /*
92  * Release resource allocated to an unpack descriptor.
93  *
94  * Caller is responsible to make sure that all of these pointers are
95  * initialized (in our case, they all point to valid memory block).
96  * We don't zero out pointers here because nobody else would ever
97  * reference the memory block without scrubbing them.
98  */
99 static void
100 unpack_descriptor_fini(unpack_descriptor_t *unpackd)
101 {
102 
103 	free(unpackd->symbolsin);
104 	free(unpackd->inodesin);
105 	free(unpackd->symbol);
106 	free(unpackd->tree);
107 
108 	fclose(unpackd->fpIn);
109 	fclose(unpackd->fpOut);
110 }
111 
112 /*
113  * Recursively fill the internal node count table
114  */
115 static void
116 unpackd_fill_inodesin(const unpack_descriptor_t *unpackd, int level)
117 {
118 
119 	/*
120 	 * The internal nodes would be 1/2 of total internal nodes and
121 	 * leaf nodes in the next level.  For the last level there
122 	 * would be no internal node by definition.
123 	 */
124 	if (level < unpackd->treelevels) {
125 		unpackd_fill_inodesin(unpackd, level + 1);
126 		unpackd->inodesin[level] = (unpackd->inodesin[level + 1] +
127 		    unpackd->symbolsin[level + 1]) / 2;
128 	} else
129 		unpackd->inodesin[level] = 0;
130 }
131 
132 /*
133  * Update counter for accepted bytes
134  */
135 static void
136 accepted_bytes(off_t *bytes_in, off_t newbytes)
137 {
138 
139 	if (bytes_in != NULL)
140 		(*bytes_in) += newbytes;
141 }
142 
143 /*
144  * Read file header and construct the tree.  Also, prepare the buffered I/O
145  * for decode routine.
146  *
147  * Return value is uncompressed size.
148  */
149 static void
150 unpack_parse_header(int in, int out, char *pre, size_t prelen, off_t *bytes_in,
151     unpack_descriptor_t *unpackd)
152 {
153 	unsigned char hdr[PACK_HEADER_LENGTH];	/* buffer for header */
154 	ssize_t bytesread;		/* Bytes read from the file */
155 	int i, j, thisbyte;
156 
157 	/* Prepend the header buffer if we already read some data */
158 	if (prelen != 0)
159 		memcpy(hdr, pre, prelen);
160 
161 	/* Read in and fill the rest bytes of header */
162 	bytesread = read(in, hdr + prelen, PACK_HEADER_LENGTH - prelen);
163 	if (bytesread < 0)
164 		maybe_err("Error reading pack header");
165 	infile_newdata(bytesread);
166 
167 	accepted_bytes(bytes_in, PACK_HEADER_LENGTH);
168 
169 	/* Obtain uncompressed length (bytes 2,3,4,5) */
170 	unpackd->uncompressed_size = 0;
171 	for (i = 2; i <= 5; i++) {
172 		unpackd->uncompressed_size <<= 8;
173 		unpackd->uncompressed_size |= hdr[i];
174 	}
175 
176 	/* Get the levels of the tree */
177 	unpackd->treelevels = hdr[6];
178 	if (unpackd->treelevels > HTREE_MAXLEVEL || unpackd->treelevels < 1)
179 		maybe_errx("Huffman tree has insane levels");
180 
181 	/* Let libc take care for buffering from now on */
182 	if ((unpackd->fpIn = fdopen(in, "r")) == NULL)
183 		maybe_err("Can not fdopen() input stream");
184 	if ((unpackd->fpOut = fdopen(out, "w")) == NULL)
185 		maybe_err("Can not fdopen() output stream");
186 
187 	/* Allocate for the tables of bounds and the tree itself */
188 	unpackd->inodesin =
189 	    calloc(unpackd->treelevels, sizeof(*(unpackd->inodesin)));
190 	unpackd->symbolsin =
191 	    calloc(unpackd->treelevels, sizeof(*(unpackd->symbolsin)));
192 	unpackd->tree =
193 	    calloc(unpackd->treelevels, (sizeof(*(unpackd->tree))));
194 	if (unpackd->inodesin == NULL || unpackd->symbolsin == NULL ||
195 	    unpackd->tree == NULL)
196 		maybe_err("calloc");
197 
198 	/* We count from 0 so adjust to match array upper bound */
199 	unpackd->treelevels--;
200 
201 	/* Read the levels symbol count table and calculate total */
202 	unpackd->symbol_size = 1;	/* EOB */
203 	for (i = 0; i <= unpackd->treelevels; i++) {
204 		if ((thisbyte = fgetc(unpackd->fpIn)) == EOF)
205 			maybe_err("File appears to be truncated");
206 		unpackd->symbolsin[i] = (unsigned char)thisbyte;
207 		unpackd->symbol_size += unpackd->symbolsin[i];
208 	}
209 	accepted_bytes(bytes_in, unpackd->treelevels);
210 	if (unpackd->symbol_size > 256)
211 		maybe_errx("Bad symbol table");
212 	infile_newdata(unpackd->treelevels);
213 
214 	/* Allocate for the symbol table, point symbol_eob at the beginning */
215 	unpackd->symbol_eob = unpackd->symbol = calloc(1, unpackd->symbol_size);
216 	if (unpackd->symbol == NULL)
217 		maybe_err("calloc");
218 
219 	/*
220 	 * Read in the symbol table, which contain [2, 256] symbols.
221 	 * In order to fit the count in one byte, pack(1) would offset
222 	 * it by reducing 2 from the actual number from the last level.
223 	 *
224 	 * We adjust the last level's symbol count by 1 here, because
225 	 * the EOB symbol is not being transmitted explicitly.  Another
226 	 * adjustment would be done later afterward.
227 	 */
228 	unpackd->symbolsin[unpackd->treelevels]++;
229 	for (i = 0; i <= unpackd->treelevels; i++) {
230 		unpackd->tree[i] = unpackd->symbol_eob;
231 		for (j = 0; j < unpackd->symbolsin[i]; j++) {
232 			if ((thisbyte = fgetc(unpackd->fpIn)) == EOF)
233 				maybe_errx("Symbol table truncated");
234 			*unpackd->symbol_eob++ = (char)thisbyte;
235 		}
236 		infile_newdata(unpackd->symbolsin[i]);
237 		accepted_bytes(bytes_in, unpackd->symbolsin[i]);
238 	}
239 
240 	/* Now, take account for the EOB symbol as well */
241 	unpackd->symbolsin[unpackd->treelevels]++;
242 
243 	/*
244 	 * The symbolsin table has been constructed now.
245 	 * Calculate the internal nodes count table based on it.
246 	 */
247 	unpackd_fill_inodesin(unpackd, 0);
248 }
249 
250 /*
251  * Decode huffman stream, based on the huffman tree.
252  */
253 static void
254 unpack_decode(const unpack_descriptor_t *unpackd, off_t *bytes_in)
255 {
256 	int thislevel, thiscode, thisbyte, inlevelindex;
257 	int i;
258 	off_t bytes_out = 0;
259 	const char *thissymbol;	/* The symbol pointer decoded from stream */
260 
261 	/*
262 	 * Decode huffman.  Fetch every bytes from the file, get it
263 	 * into 'thiscode' bit-by-bit, then output the symbol we got
264 	 * when one has been found.
265 	 *
266 	 * Assumption: sizeof(int) > ((max tree levels + 1) / 8).
267 	 * bad things could happen if not.
268 	 */
269 	thislevel = 0;
270 	thiscode = thisbyte = 0;
271 
272 	while ((thisbyte = fgetc(unpackd->fpIn)) != EOF) {
273 		accepted_bytes(bytes_in, 1);
274 		infile_newdata(1);
275 		check_siginfo();
276 
277 		/*
278 		 * Split one bit from thisbyte, from highest to lowest,
279 		 * feed the bit into thiscode, until we got a symbol from
280 		 * the tree.
281 		 */
282 		for (i = 7; i >= 0; i--) {
283 			thiscode = (thiscode << 1) | ((thisbyte >> i) & 1);
284 
285 			/* Did we got a symbol? (referencing leaf node) */
286 			if (thiscode >= unpackd->inodesin[thislevel]) {
287 				inlevelindex =
288 				    thiscode - unpackd->inodesin[thislevel];
289 				if (inlevelindex > unpackd->symbolsin[thislevel])
290 					maybe_errx("File corrupt");
291 
292 				thissymbol =
293 				    &(unpackd->tree[thislevel][inlevelindex]);
294 				if ((thissymbol == unpackd->symbol_eob) &&
295 				    (bytes_out == unpackd->uncompressed_size))
296 					goto finished;
297 
298 				fputc((*thissymbol), unpackd->fpOut);
299 				bytes_out++;
300 
301 				/* Prepare for next input */
302 				thislevel = 0; thiscode = 0;
303 			} else {
304 				thislevel++;
305 				if (thislevel > unpackd->treelevels)
306 					maybe_errx("File corrupt");
307 			}
308 		}
309 	}
310 
311 finished:
312 	if (bytes_out != unpackd->uncompressed_size)
313 		maybe_errx("Premature EOF");
314 }
315 
316 /* Handler for pack(1)'ed file */
317 static off_t
318 unpack(int in, int out, char *pre, size_t prelen, off_t *bytes_in)
319 {
320 	unpack_descriptor_t unpackd;
321 
322 	in = dup(in);
323 	if (in == -1)
324 		maybe_err("dup");
325 	out = dup(out);
326 	if (out == -1)
327 		maybe_err("dup");
328 
329 	unpack_parse_header(in, out, pre, prelen, bytes_in, &unpackd);
330 	unpack_decode(&unpackd, bytes_in);
331 	unpack_descriptor_fini(&unpackd);
332 
333 	/* If we reached here, the unpack was successful */
334 	return (unpackd.uncompressed_size);
335 }
336