1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.compression;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.handler.codec.ByteToMessageDecoder;
21
22 import java.util.List;
23
24 import static io.netty.handler.codec.compression.Bzip2Constants.BASE_BLOCK_SIZE;
25 import static io.netty.handler.codec.compression.Bzip2Constants.BLOCK_HEADER_MAGIC_1;
26 import static io.netty.handler.codec.compression.Bzip2Constants.BLOCK_HEADER_MAGIC_2;
27 import static io.netty.handler.codec.compression.Bzip2Constants.END_OF_STREAM_MAGIC_1;
28 import static io.netty.handler.codec.compression.Bzip2Constants.END_OF_STREAM_MAGIC_2;
29 import static io.netty.handler.codec.compression.Bzip2Constants.HUFFMAN_DECODE_MAX_CODE_LENGTH;
30 import static io.netty.handler.codec.compression.Bzip2Constants.HUFFMAN_MAXIMUM_TABLES;
31 import static io.netty.handler.codec.compression.Bzip2Constants.HUFFMAN_MAX_ALPHABET_SIZE;
32 import static io.netty.handler.codec.compression.Bzip2Constants.HUFFMAN_MINIMUM_TABLES;
33 import static io.netty.handler.codec.compression.Bzip2Constants.HUFFMAN_SELECTOR_LIST_MAX_LENGTH;
34 import static io.netty.handler.codec.compression.Bzip2Constants.HUFFMAN_SYMBOL_RANGE_SIZE;
35 import static io.netty.handler.codec.compression.Bzip2Constants.MAGIC_NUMBER;
36 import static io.netty.handler.codec.compression.Bzip2Constants.MAX_BLOCK_SIZE;
37 import static io.netty.handler.codec.compression.Bzip2Constants.MAX_SELECTORS;
38 import static io.netty.handler.codec.compression.Bzip2Constants.MIN_BLOCK_SIZE;
39
40
41
42
43
44
45 public class Bzip2Decoder extends ByteToMessageDecoder {
46
47
48
49 private enum State {
50 INIT,
51 INIT_BLOCK,
52 INIT_BLOCK_PARAMS,
53 RECEIVE_HUFFMAN_USED_MAP,
54 RECEIVE_HUFFMAN_USED_BITMAPS,
55 RECEIVE_SELECTORS_NUMBER,
56 RECEIVE_SELECTORS,
57 RECEIVE_HUFFMAN_LENGTH,
58 DECODE_HUFFMAN_DATA,
59 EOF,
60 CORRUPTED
61 }
62 private State currentState = State.INIT;
63
64
65
66
67 private final Bzip2BitReader reader = new Bzip2BitReader();
68
69
70
71
72 private Bzip2BlockDecompressor blockDecompressor;
73
74
75
76
77 private Bzip2HuffmanStageDecoder huffmanStageDecoder;
78
79
80
81
82 private int blockSize;
83
84
85
86
87 private int blockCRC;
88
89
90
91
92 private int streamCRC;
93
94 @Override
95 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
96 if (!in.isReadable()) {
97 return;
98 }
99
100 try {
101 decodeStateMachine(ctx, in, out);
102 } catch (Exception e) {
103
104 currentState = State.CORRUPTED;
105 blockDecompressor = null;
106 huffmanStageDecoder = null;
107 throw e;
108 }
109 }
110
111 private void decodeStateMachine(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
112 final Bzip2BitReader reader = this.reader;
113 reader.setByteBuf(in);
114
115 for (;;) {
116 switch (currentState) {
117 case INIT:
118 if (in.readableBytes() < 4) {
119 return;
120 }
121 int magicNumber = in.readUnsignedMedium();
122 if (magicNumber != MAGIC_NUMBER) {
123 throw new DecompressionException("Unexpected stream identifier contents. Mismatched bzip2 " +
124 "protocol version?");
125 }
126 int blockSize = in.readByte() - '0';
127 if (blockSize < MIN_BLOCK_SIZE || blockSize > MAX_BLOCK_SIZE) {
128 throw new DecompressionException("block size is invalid");
129 }
130 this.blockSize = blockSize * BASE_BLOCK_SIZE;
131
132 streamCRC = 0;
133 currentState = State.INIT_BLOCK;
134
135 case INIT_BLOCK:
136 if (!reader.hasReadableBytes(10)) {
137 return;
138 }
139
140 final int magic1 = reader.readBits(24);
141 final int magic2 = reader.readBits(24);
142 if (magic1 == END_OF_STREAM_MAGIC_1 && magic2 == END_OF_STREAM_MAGIC_2) {
143
144 final int storedCombinedCRC = reader.readInt();
145 if (storedCombinedCRC != streamCRC) {
146 throw new DecompressionException("stream CRC error");
147 }
148 currentState = State.EOF;
149 break;
150 }
151 if (magic1 != BLOCK_HEADER_MAGIC_1 || magic2 != BLOCK_HEADER_MAGIC_2) {
152 throw new DecompressionException("bad block header");
153 }
154 blockCRC = reader.readInt();
155 currentState = State.INIT_BLOCK_PARAMS;
156
157 case INIT_BLOCK_PARAMS:
158 if (!reader.hasReadableBits(25)) {
159 return;
160 }
161 final boolean blockRandomised = reader.readBoolean();
162 final int bwtStartPointer = reader.readBits(24);
163
164 blockDecompressor = new Bzip2BlockDecompressor(this.blockSize, blockCRC,
165 blockRandomised, bwtStartPointer, reader);
166 currentState = State.RECEIVE_HUFFMAN_USED_MAP;
167
168 case RECEIVE_HUFFMAN_USED_MAP:
169 if (!reader.hasReadableBits(16)) {
170 return;
171 }
172 blockDecompressor.huffmanInUse16 = reader.readBits(16);
173 currentState = State.RECEIVE_HUFFMAN_USED_BITMAPS;
174
175 case RECEIVE_HUFFMAN_USED_BITMAPS:
176 Bzip2BlockDecompressor blockDecompressor = this.blockDecompressor;
177 final int inUse16 = blockDecompressor.huffmanInUse16;
178 final int bitNumber = Integer.bitCount(inUse16);
179 final byte[] huffmanSymbolMap = blockDecompressor.huffmanSymbolMap;
180
181 if (!reader.hasReadableBits(bitNumber * HUFFMAN_SYMBOL_RANGE_SIZE + 3)) {
182 return;
183 }
184
185 int huffmanSymbolCount = 0;
186 if (bitNumber > 0) {
187 for (int i = 0; i < 16; i++) {
188 if ((inUse16 & 1 << 15 >>> i) != 0) {
189 for (int j = 0, k = i << 4; j < HUFFMAN_SYMBOL_RANGE_SIZE; j++, k++) {
190 if (reader.readBoolean()) {
191 huffmanSymbolMap[huffmanSymbolCount++] = (byte) k;
192 }
193 }
194 }
195 }
196 }
197 blockDecompressor.huffmanEndOfBlockSymbol = huffmanSymbolCount + 1;
198
199 int totalTables = reader.readBits(3);
200 if (totalTables < HUFFMAN_MINIMUM_TABLES || totalTables > HUFFMAN_MAXIMUM_TABLES) {
201 throw new DecompressionException("incorrect huffman groups number");
202 }
203 int alphaSize = huffmanSymbolCount + 2;
204 if (alphaSize > HUFFMAN_MAX_ALPHABET_SIZE) {
205 throw new DecompressionException("incorrect alphabet size");
206 }
207 huffmanStageDecoder = new Bzip2HuffmanStageDecoder(reader, totalTables, alphaSize);
208 currentState = State.RECEIVE_SELECTORS_NUMBER;
209
210 case RECEIVE_SELECTORS_NUMBER:
211 if (!reader.hasReadableBits(15)) {
212 return;
213 }
214 int totalSelectors = reader.readBits(15);
215 if (totalSelectors < 1 || totalSelectors > MAX_SELECTORS) {
216 throw new DecompressionException("incorrect selectors number");
217 }
218 huffmanStageDecoder.selectors = new byte[totalSelectors];
219
220 currentState = State.RECEIVE_SELECTORS;
221
222 case RECEIVE_SELECTORS:
223 Bzip2HuffmanStageDecoder huffmanStageDecoder = this.huffmanStageDecoder;
224 byte[] selectors = huffmanStageDecoder.selectors;
225 totalSelectors = selectors.length;
226 final Bzip2MoveToFrontTable tableMtf = huffmanStageDecoder.tableMTF;
227
228 int currSelector;
229
230 for (currSelector = huffmanStageDecoder.currentSelector;
231 currSelector < totalSelectors; currSelector++) {
232 if (!reader.hasReadableBits(HUFFMAN_SELECTOR_LIST_MAX_LENGTH)) {
233
234 huffmanStageDecoder.currentSelector = currSelector;
235 return;
236 }
237 int index = 0;
238 while (reader.readBoolean()) {
239 index++;
240 if (index >= huffmanStageDecoder.totalTables) {
241 throw new DecompressionException("incorrect selector index " + index);
242 }
243 }
244 selectors[currSelector] = tableMtf.indexToFront(index);
245 }
246
247 currentState = State.RECEIVE_HUFFMAN_LENGTH;
248
249 case RECEIVE_HUFFMAN_LENGTH:
250 huffmanStageDecoder = this.huffmanStageDecoder;
251 totalTables = huffmanStageDecoder.totalTables;
252 final byte[][] codeLength = huffmanStageDecoder.tableCodeLengths;
253 alphaSize = huffmanStageDecoder.alphabetSize;
254
255
256 int currGroup;
257 int currLength = huffmanStageDecoder.currentLength;
258 int currAlpha = 0;
259 boolean modifyLength = huffmanStageDecoder.modifyLength;
260 boolean saveStateAndReturn = false;
261 loop: for (currGroup = huffmanStageDecoder.currentGroup; currGroup < totalTables; currGroup++) {
262
263 if (!reader.hasReadableBits(5)) {
264 saveStateAndReturn = true;
265 break;
266 }
267 if (currLength < 0) {
268 currLength = reader.readBits(5);
269 }
270 for (currAlpha = huffmanStageDecoder.currentAlpha; currAlpha < alphaSize; currAlpha++) {
271
272 if (!reader.isReadable()) {
273 saveStateAndReturn = true;
274 break loop;
275 }
276 while (modifyLength || reader.readBoolean()) {
277 if (!reader.isReadable()) {
278 modifyLength = true;
279 saveStateAndReturn = true;
280 break loop;
281 }
282
283 currLength += reader.readBoolean() ? -1 : 1;
284 modifyLength = false;
285 if (!reader.isReadable()) {
286 saveStateAndReturn = true;
287 break loop;
288 }
289 }
290 if (currLength < 1 || currLength > HUFFMAN_DECODE_MAX_CODE_LENGTH) {
291 throw new DecompressionException("Bzip2 block Huffman code length not in range 1.."
292 + HUFFMAN_DECODE_MAX_CODE_LENGTH);
293 }
294 codeLength[currGroup][currAlpha] = (byte) currLength;
295 }
296 currLength = -1;
297 currAlpha = huffmanStageDecoder.currentAlpha = 0;
298 modifyLength = false;
299 }
300 if (saveStateAndReturn) {
301
302 huffmanStageDecoder.currentGroup = currGroup;
303 huffmanStageDecoder.currentLength = currLength;
304 huffmanStageDecoder.currentAlpha = currAlpha;
305 huffmanStageDecoder.modifyLength = modifyLength;
306 return;
307 }
308
309
310 huffmanStageDecoder.createHuffmanDecodingTables();
311 currentState = State.DECODE_HUFFMAN_DATA;
312
313 case DECODE_HUFFMAN_DATA:
314 blockDecompressor = this.blockDecompressor;
315 final int oldReaderIndex = in.readerIndex();
316 final boolean decoded = blockDecompressor.decodeHuffmanData(this.huffmanStageDecoder);
317 if (!decoded) {
318 return;
319 }
320
321
322
323 if (in.readerIndex() == oldReaderIndex && in.isReadable()) {
324 reader.refill();
325 }
326
327 final int blockLength = blockDecompressor.blockLength();
328 ByteBuf uncompressed = ctx.alloc().buffer(blockLength);
329 try {
330 int uncByte;
331 while ((uncByte = blockDecompressor.read()) >= 0) {
332 uncompressed.writeByte(uncByte);
333 }
334
335 currentState = State.INIT_BLOCK;
336 int currentBlockCRC = blockDecompressor.checkCRC();
337 streamCRC = (streamCRC << 1 | streamCRC >>> 31) ^ currentBlockCRC;
338
339 out.add(uncompressed);
340 uncompressed = null;
341 } finally {
342 if (uncompressed != null) {
343 uncompressed.release();
344 }
345 }
346
347
348 return;
349 case EOF:
350 case CORRUPTED:
351 in.skipBytes(in.readableBytes());
352 return;
353 default:
354 throw new IllegalStateException();
355 }
356 }
357 }
358
359
360
361
362
363 public boolean isClosed() {
364 return currentState == State.EOF;
365 }
366 }