View Javadoc
1   /*
2    * Copyright 2024 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 com.github.luben.zstd.ZstdInputStreamNoFinalizer;
19  import io.netty.buffer.ByteBuf;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.handler.codec.ByteToMessageDecoder;
22  import io.netty.util.internal.ObjectUtil;
23  
24  import java.io.Closeable;
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.util.List;
28  
29  /**
30   * Decompresses a compressed block {@link ByteBuf} using the Zstandard algorithm.
31   * See <a href="https://facebook.github.io/zstd">Zstandard</a>.
32   */
33  public final class ZstdDecoder extends ByteToMessageDecoder {
34      // Don't use static here as we want to still allow to load the classes.
35      {
36          try {
37              Zstd.ensureAvailability();
38          } catch (Throwable throwable) {
39              throw new ExceptionInInitializerError(throwable);
40          }
41      }
42  
43      private static final int DEFAULT_MAX_FORWARD_BYTES = CompressionUtil.DEFAULT_MAX_FORWARD_BYTES;
44      // Output buffer size while maxForwardBytes is zero or negative: such a threshold forwards every buffer that has
45      // content, but cannot size one. ZstdDecompressor uses it too.
46      static final int DEFAULT_OUTPUT_BUFFER_SIZE = 64 * 1024;
47      /**
48       * Default maximum size of a single output buffer, in bytes (4 MiB).
49       */
50      public static final int DEFAULT_MAXIMUM_ALLOCATION_SIZE = 4 * 1024 * 1024;
51      /**
52       * Default upper bound on the {@code Window_Log} accepted by the decoder.
53       * {@code 27} corresponds to a 128 MiB decompression window.
54       */
55      public static final int DEFAULT_MAX_WINDOW_LOG = 27;
56      private static final int MIN_WINDOW_LOG = 10;
57      private static final int MAX_WINDOW_LOG = 31;
58      private final int maxForwardBytes;
59      private final int outputBufferSize;
60      private final int maxWindowLog;
61      private final MutableByteBufInputStream inputStream = new MutableByteBufInputStream();
62      private ZstdInputStreamNoFinalizer zstdIs;
63  
64      private boolean needsRead;
65      private State currentState = State.DECOMPRESS_DATA;
66  
67      /**
68       * Current state of stream.
69       */
70      private enum State {
71          DECOMPRESS_DATA,
72          CORRUPTED
73      }
74  
75      /**
76       * Creates a new decoder with the {@link #DEFAULT_MAXIMUM_ALLOCATION_SIZE},
77       * and the {@link #DEFAULT_MAX_WINDOW_LOG} window log size.
78       * <p>
79       * The window log size bounds the memory usage of the sliding window for ZSTD frame decompression.
80       * Frames declaring a larger window will be rejected to bound the memory the decoder may allocate per stream.
81       *
82       */
83      public ZstdDecoder() {
84          this(DEFAULT_MAXIMUM_ALLOCATION_SIZE, DEFAULT_MAX_WINDOW_LOG);
85      }
86  
87      /**
88       * Creates a new decoder with the given maximum allocation size,
89       * and the {@link #DEFAULT_MAX_WINDOW_LOG} window log size.
90       * <p>
91       * The window log size bounds the memory usage of the sliding window for ZSTD frame decompression.
92       * Frames declaring a larger window will be rejected to bound the memory the decoder may allocate per stream.
93       *
94       * @param maximumAllocationSize maximum size of a single output buffer.
95       */
96      public ZstdDecoder(int maximumAllocationSize) {
97          this(maximumAllocationSize, DEFAULT_MAX_WINDOW_LOG);
98      }
99  
100     /**
101      * Creates a new decoder with an explicit upper bound on the accepted {@code Window_Log}.
102      *
103      * @param maximumAllocationSize maximum size of a single output buffer.
104      * @param maxWindowLog          upper bound on the {@code Window_Log} field of incoming
105      *                              frames; must be in {@code [10, 31]}. Frames declaring a
106      *                              larger window will be rejected to bound the memory the
107      *                              decoder may allocate per stream.
108      */
109     public ZstdDecoder(int maximumAllocationSize, int maxWindowLog) {
110         this(maximumAllocationSize, maxWindowLog, DEFAULT_MAX_FORWARD_BYTES);
111     }
112 
113     // Package-private for testing, as the default is read from a system property once per JVM.
114     ZstdDecoder(int maximumAllocationSize, int maxWindowLog, int defaultMaxForwardBytes) {
115         ObjectUtil.checkPositiveOrZero(maximumAllocationSize, "maximumAllocationSize");
116         this.maxForwardBytes = maximumAllocationSize > 0 ? maximumAllocationSize : defaultMaxForwardBytes;
117         this.outputBufferSize = maxForwardBytes > 0 ? maxForwardBytes : DEFAULT_OUTPUT_BUFFER_SIZE;
118         this.maxWindowLog = ObjectUtil.checkInRange(maxWindowLog, MIN_WINDOW_LOG, MAX_WINDOW_LOG, "maxWindowLog");
119     }
120 
121     @Override
122     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
123         needsRead = true;
124         try {
125             if (currentState == State.CORRUPTED) {
126                 in.skipBytes(in.readableBytes());
127 
128                 return;
129             }
130             inputStream.current = in;
131 
132             ByteBuf outBuffer = null;
133 
134             final int compressedLength = in.readableBytes();
135             try {
136                 long uncompressedLength;
137                 if (in.isDirect()) {
138                     uncompressedLength = com.github.luben.zstd.Zstd.getFrameContentSize(
139                             CompressionUtil.safeNioBuffer(in, in.readerIndex(), in.readableBytes()));
140                 } else {
141                     uncompressedLength = com.github.luben.zstd.Zstd.getFrameContentSize(
142                             in.array(), in.readerIndex() + in.arrayOffset(), in.readableBytes());
143                 }
144                 if (uncompressedLength <= 0) {
145                     // Let's start with the compressedLength * 2 as often we will not have everything
146                     // we need in the in buffer and don't want to reserve too much memory.
147                     uncompressedLength = compressedLength * 2L;
148                 }
149 
150                 int w;
151                 do {
152                     if (outBuffer == null) {
153                         // The frame content size is read from the (untrusted) frame header, so never use it
154                         // to size the buffer beyond what we forward in one go.
155                         outBuffer = ctx.alloc().heapBuffer((int) Math.min(outputBufferSize, uncompressedLength));
156                     }
157                     do {
158                         w = outBuffer.writeBytes(zstdIs, outBuffer.writableBytes());
159                     } while (w > 0 && outBuffer.isWritable());
160                     if (outBuffer.isReadable() &&
161                             (!outBuffer.isWritable() || outBuffer.readableBytes() >= maxForwardBytes)) {
162                         needsRead = false;
163                         ctx.fireChannelRead(outBuffer);
164                         outBuffer = null;
165                     }
166                 } while (w > 0);
167                 if (outBuffer != null && outBuffer.isReadable()) {
168                     needsRead = false;
169                     ctx.fireChannelRead(outBuffer);
170                     outBuffer = null;
171                 }
172             } finally {
173                 if (outBuffer != null) {
174                     outBuffer.release();
175                 }
176             }
177         } catch (Exception e) {
178             currentState = State.CORRUPTED;
179             throw new DecompressionException(e);
180         } finally {
181             inputStream.current = null;
182         }
183     }
184 
185     @Override
186     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
187         // Discard bytes of the cumulation buffer if needed.
188         discardSomeReadBytes();
189 
190         if (needsRead && !ctx.channel().config().isAutoRead()) {
191             ctx.read();
192         }
193         ctx.fireChannelReadComplete();
194     }
195 
196     @Override
197     public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
198         super.handlerAdded(ctx);
199         zstdIs = new ZstdInputStreamNoFinalizer(inputStream);
200         zstdIs.setContinuous(true);
201         // Bound the decompression window to mitigate memory amplification from frames that
202         // declare an oversized Window_Size.
203         zstdIs.setLongMax(maxWindowLog);
204     }
205 
206     @Override
207     protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
208         try {
209             closeSilently(zstdIs);
210         } finally {
211             super.handlerRemoved0(ctx);
212         }
213     }
214 
215     private static void closeSilently(Closeable closeable) {
216         if (closeable != null) {
217             try {
218                 closeable.close();
219             } catch (IOException ignore) {
220                 // ignore
221             }
222         }
223     }
224 
225     private static final class MutableByteBufInputStream extends InputStream {
226         ByteBuf current;
227 
228         @Override
229         public int read() {
230             if (current == null || !current.isReadable()) {
231                 return -1;
232             }
233             return current.readByte() & 0xff;
234         }
235 
236         @Override
237         public int read(byte[] b, int off, int len) {
238             int available = available();
239             if (available == 0) {
240                 return -1;
241             }
242 
243             len = Math.min(available, len);
244             current.readBytes(b, off, len);
245             return len;
246         }
247 
248         @Override
249         public int available() {
250             return current == null ? 0 : current.readableBytes();
251         }
252     }
253 }