View Javadoc
1   /*
2    * Copyright 2021 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  
17  package io.netty.handler.codec.compression;
18  
19  import com.aayushatharva.brotli4j.decoder.DecoderJNI;
20  import io.netty.buffer.ByteBuf;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.handler.codec.ByteToMessageDecoder;
23  import io.netty.util.internal.ObjectUtil;
24  
25  import java.nio.ByteBuffer;
26  import java.util.List;
27  
28  /**
29   * Decompresses a {@link ByteBuf} encoded with the brotli format.
30   * <p>
31   * See <a href="https://github.com/google/brotli">brotli</a>.
32   */
33  public final class BrotliDecoder extends ByteToMessageDecoder {
34  
35      private static final int DEFAULT_MAX_FORWARD_BYTES = CompressionUtil.DEFAULT_MAX_FORWARD_BYTES;
36      private static final int DEFAULT_INPUT_BUFFER_SIZE = 8 * 1024;
37      // Output buffer size while the forwarding threshold is zero or negative: such a threshold forwards every buffer
38      // that has content, but cannot size one.
39      static final int DEFAULT_OUTPUT_BUFFER_SIZE = 64 * 1024;
40  
41      private enum State {
42          DONE, NEEDS_MORE_INPUT, ERROR
43      }
44  
45      static {
46          try {
47              Brotli.ensureAvailability();
48          } catch (Throwable throwable) {
49              throw new ExceptionInInitializerError(throwable);
50          }
51      }
52  
53      private final int inputBufferSize;
54      private final int outputBufferSize;
55      private final int maxForwardBytes;
56      private DecoderJNI.Wrapper decoder;
57      private boolean destroyed;
58      private boolean needsRead;
59      private boolean pulledSinceLastPush;
60      private ByteBuf accumBuffer;
61  
62      /**
63       * Creates a new BrotliDecoder with a default 8kB input buffer
64       */
65      public BrotliDecoder() {
66          this(DEFAULT_INPUT_BUFFER_SIZE);
67      }
68  
69      /**
70       * Creates a new BrotliDecoder
71       * @param inputBufferSize desired size of the input buffer in bytes
72       */
73      public BrotliDecoder(int inputBufferSize) {
74          this(inputBufferSize == 0 ? DEFAULT_INPUT_BUFFER_SIZE : inputBufferSize, 0, DEFAULT_MAX_FORWARD_BYTES);
75      }
76  
77      /**
78       * Creates a new BrotliDecoder
79       * @param inputBufferSize desired size of the input buffer in bytes
80       * @param outputBufferSize desired max size of the output buffer in bytes
81       *                         (produce multiple output buffers if exceeded)
82       */
83      public BrotliDecoder(int inputBufferSize, int outputBufferSize) {
84          this(ObjectUtil.checkPositive(inputBufferSize, "inputBufferSize"),
85                  ObjectUtil.checkPositive(outputBufferSize, "outputBufferSize"), DEFAULT_MAX_FORWARD_BYTES);
86      }
87  
88      // An outputBufferSize of 0 takes defaultMaxForwardBytes instead. Package-private for testing, as that default is
89      // read from a system property once per JVM.
90      BrotliDecoder(int inputBufferSize, int outputBufferSize, int defaultMaxForwardBytes) {
91          this.inputBufferSize = ObjectUtil.checkPositive(inputBufferSize, "inputBufferSize");
92          this.maxForwardBytes = outputBufferSize > 0 ? outputBufferSize : defaultMaxForwardBytes;
93          this.outputBufferSize = maxForwardBytes > 0 ? maxForwardBytes : DEFAULT_OUTPUT_BUFFER_SIZE;
94      }
95  
96      /**
97       * Creates a new {@link BrotliDecoder} that use the {@code maxAllocation}
98       * semantics: the supplied value bounds the size of the emitted decompressed chunks.
99       * The input buffer size stays at the decoder's default.
100      *
101      * @param maxAllocation maximum size, in bytes, of each decompressed output
102      *                      buffer forwarded downstream; if {@code 0}, the
103      *                      decoder's default output cap is used.
104      */
105     public static BrotliDecoder newDecoderWithMaxAllocation(int maxAllocation) {
106         ObjectUtil.checkPositiveOrZero(maxAllocation, "maxAllocation");
107         return maxAllocation > 0 ?
108                 new BrotliDecoder(DEFAULT_INPUT_BUFFER_SIZE, maxAllocation) :
109                 new BrotliDecoder();
110     }
111 
112     private void forwardOutput(ChannelHandlerContext ctx) {
113         ByteBuffer nativeBuffer = decoder.pull(outputBufferSize);
114         pulledSinceLastPush = true;
115         // nativeBuffer actually wraps brotli's internal buffer so we need to copy its content
116         int remaining = nativeBuffer.remaining();
117         if (accumBuffer == null) {
118             accumBuffer = ctx.alloc().buffer(remaining);
119         }
120         accumBuffer.writeBytes(nativeBuffer);
121         needsRead = false;
122         if (accumBuffer.isReadable() && accumBuffer.readableBytes() >= maxForwardBytes) {
123             ctx.fireChannelRead(accumBuffer);
124             accumBuffer = null;
125         }
126     }
127 
128     private void flushAccumBuffer(ChannelHandlerContext ctx) {
129         if (accumBuffer != null && accumBuffer.isReadable()) {
130             ctx.fireChannelRead(accumBuffer);
131         } else if (accumBuffer != null) {
132             accumBuffer.release();
133         }
134         accumBuffer = null;
135     }
136 
137     private State decompress(ChannelHandlerContext ctx, ByteBuf input) {
138         for (;;) {
139             switch (decoder.getStatus()) {
140                 case DONE:
141                     return State.DONE;
142 
143                 case OK:
144                     push(0);
145                     break;
146 
147                 case NEEDS_MORE_INPUT:
148                     while (decoder.hasOutput()) {
149                         forwardOutput(ctx);
150                     }
151 
152                     if (!input.isReadable()) {
153                         if (pulledSinceLastPush) {
154                             // After a pull, the decoder reports NEEDS_MORE_INPUT as soon as all pushed input is
155                             // consumed, even if it could still produce more output from its internal state
156                             // (e.g. a long back-reference). Push without new input to find out.
157                             push(0);
158                             break;
159                         }
160                         return State.NEEDS_MORE_INPUT;
161                     }
162 
163                     ByteBuffer decoderInputBuffer = decoder.getInputBuffer();
164                     decoderInputBuffer.clear();
165                     int readBytes = readBytes(input, decoderInputBuffer);
166                     push(readBytes);
167                     break;
168 
169                 case NEEDS_MORE_OUTPUT:
170                     forwardOutput(ctx);
171                     break;
172 
173                 default:
174                     return State.ERROR;
175             }
176         }
177     }
178 
179     private void push(int length) {
180         pulledSinceLastPush = false;
181         decoder.push(length);
182     }
183 
184     private static int readBytes(ByteBuf in, ByteBuffer dest) {
185         int limit = Math.min(in.readableBytes(), dest.remaining());
186         ByteBuffer slice = dest.slice();
187         slice.limit(limit);
188         in.readBytes(slice);
189         dest.position(dest.position() + limit);
190         return limit;
191     }
192 
193     @Override
194     public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
195         decoder = new DecoderJNI.Wrapper(inputBufferSize);
196     }
197 
198     @Override
199     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
200         needsRead = true;
201         if (destroyed) {
202             // Skip data received after finished.
203             in.skipBytes(in.readableBytes());
204             return;
205         }
206 
207         if (!in.isReadable()) {
208             return;
209         }
210 
211         try {
212             State state = decompress(ctx, in);
213             if (state == State.DONE) {
214                 destroy();
215             } else if (state == State.ERROR) {
216                 throw new DecompressionException("Brotli stream corrupted");
217             }
218         } catch (Exception e) {
219             destroy();
220             throw e;
221         } finally {
222             flushAccumBuffer(ctx);
223         }
224     }
225 
226     private void destroy() {
227         if (!destroyed) {
228             destroyed = true;
229             decoder.destroy();
230         }
231     }
232 
233     @Override
234     protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
235         try {
236             destroy();
237         } finally {
238             super.handlerRemoved0(ctx);
239         }
240     }
241 
242     @Override
243     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
244         try {
245             destroy();
246         } finally {
247             super.channelInactive(ctx);
248         }
249     }
250 
251     @Override
252     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
253         // Discard bytes of the cumulation buffer if needed.
254         discardSomeReadBytes();
255 
256         if (needsRead && !ctx.channel().config().isAutoRead()) {
257             ctx.read();
258         }
259         ctx.fireChannelReadComplete();
260     }
261 }