View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Uncompresses a {@link ByteBuf} encoded with the Bzip2 format.
42   *
43   * See <a href="https://en.wikipedia.org/wiki/Bzip2">Bzip2</a>.
44   */
45  public class Bzip2Decoder extends ByteToMessageDecoder {
46      /**
47       * Current state of stream.
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       * A reader that provides bit-level reads.
66       */
67      private final Bzip2BitReader reader = new Bzip2BitReader();
68  
69      /**
70       * The decompressor for the current block.
71       */
72      private Bzip2BlockDecompressor blockDecompressor;
73  
74      /**
75       * Bzip2 Huffman coding stage.
76       */
77      private Bzip2HuffmanStageDecoder huffmanStageDecoder;
78  
79      /**
80       * Always: in the range 0 .. 9. The current block size is 100000 * this number.
81       */
82      private int blockSize;
83  
84      /**
85       * The CRC of the current block as read from the block header.
86       */
87      private int blockCRC;
88  
89      /**
90       * The merged CRC of all blocks decompressed so far.
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             // The state is inconsistent after an error, so skip all further input.
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                  // fall through
135             case INIT_BLOCK:
136                 if (!reader.hasReadableBytes(10)) {
137                     return;
138                 }
139                 // Get the block magic bytes.
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                     // End of stream was reached. Check the combined CRC.
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                 // fall through
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                 // fall through
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                 // fall through
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                 // fall through
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                 // fall through
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                 // Get zero-terminated bit runs (0..62) of MTF'ed Huffman table. length = 1..6
230                 for (currSelector = huffmanStageDecoder.currentSelector;
231                             currSelector < totalSelectors; currSelector++) {
232                     if (!reader.hasReadableBits(HUFFMAN_SELECTOR_LIST_MAX_LENGTH)) {
233                         // Save state if end of current ByteBuf was reached
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                 // fall through
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                 /* Now the coding tables */
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                     // start_huffman_length
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                         // delta_bit_length: 1..40
272                         if (!reader.isReadable()) {
273                             saveStateAndReturn = true;
274                             break loop;
275                         }
276                         while (modifyLength || reader.readBoolean()) {  // 0=>next symbol; 1=>alter length
277                             if (!reader.isReadable()) {
278                                 modifyLength = true;
279                                 saveStateAndReturn = true;
280                                 break loop;
281                             }
282                             // 1=>decrement length;  0=>increment length
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                     // Save state if end of current ByteBuf was reached
302                     huffmanStageDecoder.currentGroup = currGroup;
303                     huffmanStageDecoder.currentLength = currLength;
304                     huffmanStageDecoder.currentAlpha = currAlpha;
305                     huffmanStageDecoder.modifyLength = modifyLength;
306                     return;
307                 }
308 
309                 // Finally create the Huffman tables
310                 huffmanStageDecoder.createHuffmanDecodingTables();
311                 currentState = State.DECODE_HUFFMAN_DATA;
312                 // fall through
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                 // It used to avoid "Bzip2Decoder.decode() did not read anything but decoded a message" exception.
321                 // Because previous operation may read only a few bits from Bzip2BitReader.bitBuffer and
322                 // don't read incoming ByteBuf.
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                     // We did read all the data, lets reset the state and do the CRC check.
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                 // Return here so the ByteBuf that was put in the List will be forwarded to the user and so can be
347                 // released as soon as possible.
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      * Returns {@code true} if and only if the end of the compressed stream
361      * has been reached.
362      */
363     public boolean isClosed() {
364         return currentState == State.EOF;
365     }
366 }