11package org .geysermc .mcprotocollib .network .compression ;
22
33import io .netty .buffer .ByteBuf ;
4+ import io .netty .handler .codec .DecoderException ;
45
56import java .nio .ByteBuffer ;
67import java .util .zip .DataFormatException ;
@@ -23,26 +24,31 @@ public ZlibCompression(int level) {
2324
2425 @ Override
2526 public void inflate (ByteBuf source , ByteBuf destination , int uncompressedSize ) throws DataFormatException {
26- final int originalIndex = source .readerIndex ();
27- inflater .setInput (source .nioBuffer ());
27+ ByteBuffer input ;
28+ if (source .nioBufferCount () > 0 ) {
29+ input = source .nioBuffer ();
30+ source .skipBytes (source .readableBytes ());
31+ } else {
32+ input = ByteBuffer .allocateDirect (source .readableBytes ());
33+ source .readBytes (input );
34+ input .flip ();
35+ }
36+ inflater .setInput (input );
2837
2938 try {
30- while (!inflater .finished () && inflater .getBytesWritten () < uncompressedSize ) {
31- if (!destination .isWritable ()) {
32- destination .ensureWritable (ZLIB_BUFFER_SIZE );
33- }
34-
35- ByteBuffer destNioBuf = destination .nioBuffer (destination .writerIndex (),
36- destination .writableBytes ());
37- int produced = inflater .inflate (destNioBuf );
38- destination .writerIndex (destination .writerIndex () + produced );
39+ ByteBuffer nioBuffer = destination .internalNioBuffer (0 , uncompressedSize );
40+ int pos = nioBuffer .position ();
41+ inflater .inflate (nioBuffer );
42+ int actualUncompressedSize = nioBuffer .position () - pos ;
43+ if (actualUncompressedSize != uncompressedSize ) {
44+ throw new DecoderException (
45+ "Badly compressed packet - actual size of uncompressed payload "
46+ + actualUncompressedSize
47+ + " does not match declared size "
48+ + uncompressedSize );
49+ } else {
50+ destination .writerIndex (destination .writerIndex () + actualUncompressedSize );
3951 }
40-
41- if (!inflater .finished ()) {
42- throw new DataFormatException ("Received a deflate stream that was too large, wanted " + uncompressedSize );
43- }
44-
45- source .readerIndex (originalIndex + inflater .getTotalIn ());
4652 } finally {
4753 inflater .reset ();
4854 }
0 commit comments