forked from netty/netty
/
JdkZlibDecoder.java
511 lines (457 loc) · 17.5 KB
/
JdkZlibDecoder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.compression;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.ObjectUtil;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* Decompress a {@link ByteBuf} using the inflate algorithm.
*/
public class JdkZlibDecoder extends ZlibDecoder {
private static final int FHCRC = 0x02;
private static final int FEXTRA = 0x04;
private static final int FNAME = 0x08;
private static final int FCOMMENT = 0x10;
private static final int FRESERVED = 0xE0;
private Inflater inflater;
private final byte[] dictionary;
// GZIP related
private final ByteBufChecksum crc;
private final boolean decompressConcatenated;
private enum GzipState {
HEADER_START,
HEADER_END,
FLG_READ,
XLEN_READ,
SKIP_FNAME,
SKIP_COMMENT,
PROCESS_FHCRC,
FOOTER_START,
}
private GzipState gzipState = GzipState.HEADER_START;
private int flags = -1;
private int xlen = -1;
private volatile boolean finished;
private boolean decideZlibOrNone;
/**
* Creates a new instance with the default wrapper ({@link ZlibWrapper#ZLIB}).
*/
public JdkZlibDecoder() {
this(ZlibWrapper.ZLIB, null, false, 0);
}
/**
* Creates a new instance with the default wrapper ({@link ZlibWrapper#ZLIB})
* and the specified maximum buffer allocation.
*
* @param maxAllocation
* Maximum size of the decompression buffer. Must be >= 0.
* If zero, maximum size is decided by the {@link ByteBufAllocator}.
*/
public JdkZlibDecoder(int maxAllocation) {
this(ZlibWrapper.ZLIB, null, false, maxAllocation);
}
/**
* Creates a new instance with the specified preset dictionary. The wrapper
* is always {@link ZlibWrapper#ZLIB} because it is the only format that
* supports the preset dictionary.
*/
public JdkZlibDecoder(byte[] dictionary) {
this(ZlibWrapper.ZLIB, dictionary, false, 0);
}
/**
* Creates a new instance with the specified preset dictionary and maximum buffer allocation.
* The wrapper is always {@link ZlibWrapper#ZLIB} because it is the only format that
* supports the preset dictionary.
*
* @param maxAllocation
* Maximum size of the decompression buffer. Must be >= 0.
* If zero, maximum size is decided by the {@link ByteBufAllocator}.
*/
public JdkZlibDecoder(byte[] dictionary, int maxAllocation) {
this(ZlibWrapper.ZLIB, dictionary, false, maxAllocation);
}
/**
* Creates a new instance with the specified wrapper.
* Be aware that only {@link ZlibWrapper#GZIP}, {@link ZlibWrapper#ZLIB} and {@link ZlibWrapper#NONE} are
* supported atm.
*/
public JdkZlibDecoder(ZlibWrapper wrapper) {
this(wrapper, null, false, 0);
}
/**
* Creates a new instance with the specified wrapper and maximum buffer allocation.
* Be aware that only {@link ZlibWrapper#GZIP}, {@link ZlibWrapper#ZLIB} and {@link ZlibWrapper#NONE} are
* supported atm.
*
* @param maxAllocation
* Maximum size of the decompression buffer. Must be >= 0.
* If zero, maximum size is decided by the {@link ByteBufAllocator}.
*/
public JdkZlibDecoder(ZlibWrapper wrapper, int maxAllocation) {
this(wrapper, null, false, maxAllocation);
}
public JdkZlibDecoder(ZlibWrapper wrapper, boolean decompressConcatenated) {
this(wrapper, null, decompressConcatenated, 0);
}
public JdkZlibDecoder(ZlibWrapper wrapper, boolean decompressConcatenated, int maxAllocation) {
this(wrapper, null, decompressConcatenated, maxAllocation);
}
public JdkZlibDecoder(boolean decompressConcatenated) {
this(ZlibWrapper.GZIP, null, decompressConcatenated, 0);
}
public JdkZlibDecoder(boolean decompressConcatenated, int maxAllocation) {
this(ZlibWrapper.GZIP, null, decompressConcatenated, maxAllocation);
}
private JdkZlibDecoder(ZlibWrapper wrapper, byte[] dictionary, boolean decompressConcatenated, int maxAllocation) {
super(maxAllocation);
ObjectUtil.checkNotNull(wrapper, "wrapper");
this.decompressConcatenated = decompressConcatenated;
switch (wrapper) {
case GZIP:
inflater = new Inflater(true);
crc = ByteBufChecksum.wrapChecksum(new CRC32());
break;
case NONE:
inflater = new Inflater(true);
crc = null;
break;
case ZLIB:
inflater = new Inflater();
crc = null;
break;
case ZLIB_OR_NONE:
// Postpone the decision until decode(...) is called.
decideZlibOrNone = true;
crc = null;
break;
default:
throw new IllegalArgumentException("Only GZIP or ZLIB is supported, but you used " + wrapper);
}
this.dictionary = dictionary;
}
@Override
public boolean isClosed() {
return finished;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (finished) {
// Skip data received after finished.
in.skipBytes(in.readableBytes());
return;
}
int readableBytes = in.readableBytes();
if (readableBytes == 0) {
return;
}
if (decideZlibOrNone) {
// First two bytes are needed to decide if it's a ZLIB stream.
if (readableBytes < 2) {
return;
}
boolean nowrap = !looksLikeZlib(in.getShort(in.readerIndex()));
inflater = new Inflater(nowrap);
decideZlibOrNone = false;
}
if (crc != null) {
if (gzipState != GzipState.HEADER_END) {
if (gzipState == GzipState.FOOTER_START) {
if (!handleGzipFooter(in)) {
// Either there was not enough data or the input is finished.
return;
}
// If we consumed the footer we will start with the header again.
assert gzipState == GzipState.HEADER_START;
}
if (!readGZIPHeader(in)) {
// There was not enough data readable to read the GZIP header.
return;
}
// Some bytes may have been consumed, and so we must re-set the number of readable bytes.
readableBytes = in.readableBytes();
if (readableBytes == 0) {
return;
}
}
}
if (inflater.needsInput()) {
if (in.hasArray()) {
inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), readableBytes);
} else {
byte[] array = new byte[readableBytes];
in.getBytes(in.readerIndex(), array);
inflater.setInput(array);
}
}
ByteBuf decompressed = prepareDecompressBuffer(ctx, null, inflater.getRemaining() << 1);
try {
boolean readFooter = false;
while (!inflater.needsInput()) {
byte[] outArray = decompressed.array();
int writerIndex = decompressed.writerIndex();
int outIndex = decompressed.arrayOffset() + writerIndex;
int writable = decompressed.writableBytes();
int outputLength = inflater.inflate(outArray, outIndex, writable);
if (outputLength > 0) {
decompressed.writerIndex(writerIndex + outputLength);
if (crc != null) {
crc.update(outArray, outIndex, outputLength);
}
} else if (inflater.needsDictionary()) {
if (dictionary == null) {
throw new DecompressionException(
"decompression failure, unable to set dictionary as non was specified");
}
inflater.setDictionary(dictionary);
}
if (inflater.finished()) {
if (crc == null) {
finished = true; // Do not decode anymore.
} else {
readFooter = true;
}
break;
} else {
decompressed = prepareDecompressBuffer(ctx, decompressed, inflater.getRemaining() << 1);
}
}
in.skipBytes(readableBytes - inflater.getRemaining());
if (readFooter) {
gzipState = GzipState.FOOTER_START;
handleGzipFooter(in);
}
} catch (DataFormatException e) {
throw new DecompressionException("decompression failure", e);
} finally {
if (decompressed.isReadable()) {
out.add(decompressed);
} else {
decompressed.release();
}
}
}
private boolean handleGzipFooter(ByteBuf in) {
if (readGZIPFooter(in)) {
finished = !decompressConcatenated;
if (!finished) {
inflater.reset();
crc.reset();
gzipState = GzipState.HEADER_START;
return true;
}
}
return false;
}
@Override
protected void decompressionBufferExhausted(ByteBuf buffer) {
finished = true;
}
@Override
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
super.handlerRemoved0(ctx);
if (inflater != null) {
inflater.end();
}
}
private boolean readGZIPHeader(ByteBuf in) {
switch (gzipState) {
case HEADER_START:
if (in.readableBytes() < 10) {
return false;
}
// read magic numbers
int magic0 = in.readByte();
int magic1 = in.readByte();
if (magic0 != 31) {
throw new DecompressionException("Input is not in the GZIP format");
}
crc.update(magic0);
crc.update(magic1);
int method = in.readUnsignedByte();
if (method != Deflater.DEFLATED) {
throw new DecompressionException("Unsupported compression method "
+ method + " in the GZIP header");
}
crc.update(method);
flags = in.readUnsignedByte();
crc.update(flags);
if ((flags & FRESERVED) != 0) {
throw new DecompressionException(
"Reserved flags are set in the GZIP header");
}
// mtime (int)
crc.update(in, in.readerIndex(), 4);
in.skipBytes(4);
crc.update(in.readUnsignedByte()); // extra flags
crc.update(in.readUnsignedByte()); // operating system
gzipState = GzipState.FLG_READ;
// fall through
case FLG_READ:
if ((flags & FEXTRA) != 0) {
if (in.readableBytes() < 2) {
return false;
}
int xlen1 = in.readUnsignedByte();
int xlen2 = in.readUnsignedByte();
crc.update(xlen1);
crc.update(xlen2);
xlen |= xlen1 << 8 | xlen2;
}
gzipState = GzipState.XLEN_READ;
// fall through
case XLEN_READ:
if (xlen != -1) {
if (in.readableBytes() < xlen) {
return false;
}
crc.update(in, in.readerIndex(), xlen);
in.skipBytes(xlen);
}
gzipState = GzipState.SKIP_FNAME;
// fall through
case SKIP_FNAME:
if (!skipIfNeeded(in, FNAME)) {
return false;
}
gzipState = GzipState.SKIP_COMMENT;
// fall through
case SKIP_COMMENT:
if (!skipIfNeeded(in, FCOMMENT)) {
return false;
}
gzipState = GzipState.PROCESS_FHCRC;
// fall through
case PROCESS_FHCRC:
if ((flags & FHCRC) != 0) {
if (!verifyCrc16(in)) {
return false;
}
}
crc.reset();
gzipState = GzipState.HEADER_END;
// fall through
case HEADER_END:
return true;
default:
throw new IllegalStateException();
}
}
/**
* Skip bytes in the input if needed until we find the end marker {@code 0x00}.
* @param in the input
* @param flagMask the mask that should be present in the {@code flags} when we need to skip bytes.
* @return {@code true} if the operation is complete and we can move to the next state, {@code false} if we need
* the retry again once we have more readable bytes.
*/
private boolean skipIfNeeded(ByteBuf in, int flagMask) {
if ((flags & flagMask) != 0) {
for (;;) {
if (!in.isReadable()) {
// We didnt find the end yet, need to retry again once more data is readable
return false;
}
int b = in.readUnsignedByte();
crc.update(b);
if (b == 0x00) {
break;
}
}
}
// Skip is handled, we can move to the next processing state.
return true;
}
/**
* Read the GZIP footer.
*
* @param in the input.
* @return {@code true} if the footer could be read, {@code false} if the read could not be performed as
* the input {@link ByteBuf} doesn't have enough readable bytes (8 bytes).
*/
private boolean readGZIPFooter(ByteBuf in) {
if (in.readableBytes() < 8) {
return false;
}
boolean enoughData = verifyCrc(in);
assert enoughData;
// read ISIZE and verify
int dataLength = 0;
for (int i = 0; i < 4; ++i) {
dataLength |= in.readUnsignedByte() << i * 8;
}
int readLength = inflater.getTotalOut();
if (dataLength != readLength) {
throw new DecompressionException(
"Number of bytes mismatch. Expected: " + dataLength + ", Got: " + readLength);
}
return true;
}
/**
* Verifies CRC.
*
* @param in the input.
* @return {@code true} if verification could be performed, {@code false} if verification could not be performed as
* the input {@link ByteBuf} doesn't have enough readable bytes (4 bytes).
*/
private boolean verifyCrc(ByteBuf in) {
if (in.readableBytes() < 4) {
return false;
}
long crcValue = 0;
for (int i = 0; i < 4; ++i) {
crcValue |= (long) in.readUnsignedByte() << i * 8;
}
long readCrc = crc.getValue();
if (crcValue != readCrc) {
throw new DecompressionException(
"CRC value mismatch. Expected: " + crcValue + ", Got: " + readCrc);
}
return true;
}
private boolean verifyCrc16(ByteBuf in) {
if (in.readableBytes() < 2) {
return false;
}
long readCrc32 = crc.getValue();
long crc16Value = 0;
long readCrc16 = 0; // the two least significant bytes from the CRC32
for (int i = 0; i < 2; ++i) {
crc16Value |= (long) in.readUnsignedByte() << (i * 8);
readCrc16 |= ((readCrc32 >> (i * 8)) & 0xff) << (i * 8);
}
if (crc16Value != readCrc16) {
throw new DecompressionException(
"CRC16 value mismatch. Expected: " + crc16Value + ", Got: " + readCrc16);
}
return true;
}
/*
* Returns true if the cmf_flg parameter (think: first two bytes of a zlib stream)
* indicates that this is a zlib stream.
* <p>
* You can lookup the details in the ZLIB RFC:
* <a href="https://tools.ietf.org/html/rfc1950#section-2.2">RFC 1950</a>.
*/
private static boolean looksLikeZlib(short cmf_flg) {
return (cmf_flg & 0x7800) == 0x7800 &&
cmf_flg % 31 == 0;
}
}