View Javadoc
1   /*
2    * Copyright 2025 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.buffer.ByteBufAllocator;
21  import io.netty.buffer.Unpooled;
22  import io.netty.util.internal.ObjectUtil;
23  import io.netty.util.internal.UnstableApi;
24  
25  import java.io.IOException;
26  import java.io.InputStream;
27  
28  /**
29   * Decompresses a compressed block {@link ByteBuf} using the Zstandard algorithm.
30   * See <a href="https://facebook.github.io/zstd">Zstandard</a>.
31   */
32  @UnstableApi
33  public final class ZstdDecompressor implements Decompressor {
34      /**
35       * Default upper bound on the {@code Window_Log} accepted by the decompressor.
36       * {@code 27} corresponds to a 128 MiB decompression window.
37       */
38      public static final int DEFAULT_MAX_WINDOW_LOG = 27;
39      private static final int MIN_WINDOW_LOG = 10;
40      private static final int MAX_WINDOW_LOG = 31;
41      private static final int DEFAULT_MAX_FORWARD_BYTES = CompressionUtil.DEFAULT_MAX_FORWARD_BYTES;
42  
43      private final ByteBufAllocator allocator;
44      private final int outputBufferSize;
45  
46      private final MutableByteBufInputStream mutableInput = new MutableByteBufInputStream();
47      private final ZstdInputStreamNoFinalizer output;
48  
49      ZstdDecompressor(Builder builder, ByteBufAllocator allocator) {
50          this(builder, allocator, DEFAULT_MAX_FORWARD_BYTES);
51      }
52  
53      // Package-private for testing, as the default is read from a system property once per JVM.
54      ZstdDecompressor(Builder builder, ByteBufAllocator allocator, int defaultMaxForwardBytes) {
55          // Don't use static here as we want to still allow to load the classes.
56          try {
57              Zstd.ensureAvailability();
58          } catch (Throwable throwable) {
59              throw new ExceptionInInitializerError(throwable);
60          }
61          this.allocator = allocator;
62          // A threshold of zero or less cannot size a buffer.
63          this.outputBufferSize = defaultMaxForwardBytes > 0 ?
64                  defaultMaxForwardBytes : ZstdDecoder.DEFAULT_OUTPUT_BUFFER_SIZE;
65          ZstdInputStreamNoFinalizer output = null;
66          try {
67              output = new ZstdInputStreamNoFinalizer(mutableInput);
68              output.setContinuous(true);
69              output.setLongMax(builder.maxWindowLog);
70              this.output = output;
71          } catch (IOException e) {
72              if (output != null) {
73                  try {
74                      output.close();
75                  } catch (IOException closeException) {
76                      e.addSuppressed(closeException);
77                  }
78              }
79              throw new DecompressionException(e);
80          }
81      }
82  
83      @Override
84      public Status status() throws DecompressionException {
85          try {
86              if (output.available() == 0) {
87                  if (!output.getContinuous()) {
88                      return Status.COMPLETE;
89                  }
90                  return Status.NEED_INPUT;
91              }
92              return Status.NEED_OUTPUT;
93          } catch (IOException e) {
94              throw new DecompressionException(e);
95          }
96      }
97  
98      @Override
99      public void addInput(ByteBuf buf) throws DecompressionException {
100         if (!buf.isReadable()) {
101             buf.release();
102             return;
103         }
104         if (mutableInput.current != null) {
105             mutableInput.current.release();
106         }
107         mutableInput.current = buf;
108     }
109 
110     @Override
111     public void endOfInput() throws DecompressionException {
112         try {
113             output.setContinuous(false);
114             if (output.read() != -1) {
115                 throw new DecompressionException("Unexpected output after end of input");
116             }
117         } catch (IOException e) {
118             throw new DecompressionException(e);
119         }
120     }
121 
122     @Override
123     public ByteBuf takeOutput() throws DecompressionException {
124         ByteBuf buf = allocator.buffer(outputBufferSize, outputBufferSize);
125         try {
126             buf.writeBytes(output, outputBufferSize);
127         } catch (IOException e) {
128             buf.release();
129             throw new DecompressionException(e);
130         }
131         if (buf.isReadable()) {
132             return buf;
133         }
134         buf.release();
135         return Unpooled.EMPTY_BUFFER;
136     }
137 
138     @Override
139     public void close() {
140         if (mutableInput.current != null) {
141             mutableInput.current.release();
142             mutableInput.current = null;
143         }
144         try {
145             output.close();
146         } catch (IOException ignored) {
147             // ignore
148         }
149     }
150 
151     @UnstableApi
152     public static Builder builder() {
153         return new Builder();
154     }
155 
156     @UnstableApi
157     public static final class Builder extends AbstractDecompressorBuilder {
158         private int maxWindowLog = DEFAULT_MAX_WINDOW_LOG;
159 
160         Builder() {
161         }
162 
163         /**
164          * Set the upper bound on the accepted {@code Window_Log}.
165          * <p>
166          * The window log size bounds the memory usage of the sliding window for ZSTD frame decompression. Frames
167          * declaring a larger window will be rejected to bound the memory the decompressor may allocate per stream.
168          *
169          * @param maxWindowLog upper bound on the {@code Window_Log} field of incoming frames; must be in
170          *                     {@code [10, 31]}
171          * @return This builder
172          */
173         @UnstableApi
174         public Builder maxWindowLog(int maxWindowLog) {
175             this.maxWindowLog = ObjectUtil.checkInRange(
176                     maxWindowLog, MIN_WINDOW_LOG, MAX_WINDOW_LOG, "maxWindowLog");
177             return this;
178         }
179 
180         @Override
181         public Decompressor build(ByteBufAllocator allocator) throws DecompressionException {
182             return new DefensiveDecompressor(new ZstdDecompressor(this, allocator));
183         }
184     }
185 
186     private static final class MutableByteBufInputStream extends InputStream {
187         ByteBuf current;
188 
189         @Override
190         public int read() {
191             if (available() == 0) {
192                 return -1;
193             }
194             return current.readByte() & 0xff;
195         }
196 
197         @Override
198         public int read(byte[] b, int off, int len) {
199             int available = available();
200             if (available == 0) {
201                 return -1;
202             }
203 
204             len = Math.min(available, len);
205             current.readBytes(b, off, len);
206             return len;
207         }
208 
209         @Override
210         public int available() {
211             return current == null ? 0 : current.readableBytes();
212         }
213     }
214 }