View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * 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 distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  
16  package io.netty.handler.codec.http2;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufUtil;
20  import io.netty.buffer.Unpooled;
21  import io.netty.channel.Channel;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.ChannelPromise;
24  import io.netty.channel.DefaultChannelPromise;
25  import io.netty.handler.ssl.ApplicationProtocolNames;
26  import io.netty.util.AsciiString;
27  import io.netty.util.concurrent.EventExecutor;
28  
29  import static io.netty.buffer.Unpooled.directBuffer;
30  import static io.netty.buffer.Unpooled.unreleasableBuffer;
31  import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
32  import static io.netty.handler.codec.http2.Http2Exception.connectionError;
33  import static io.netty.handler.codec.http2.Http2Exception.headerListSizeError;
34  import static io.netty.util.CharsetUtil.UTF_8;
35  import static java.lang.Math.max;
36  import static java.lang.Math.min;
37  import static java.util.concurrent.TimeUnit.MILLISECONDS;
38  import static java.util.concurrent.TimeUnit.SECONDS;
39  
40  /**
41   * Constants and utility method used for encoding/decoding HTTP2 frames.
42   */
43  public final class Http2CodecUtil {
44      public static final int CONNECTION_STREAM_ID = 0;
45      public static final int HTTP_UPGRADE_STREAM_ID = 1;
46      public static final CharSequence HTTP_UPGRADE_SETTINGS_HEADER = AsciiString.cached("HTTP2-Settings");
47      public static final CharSequence HTTP_UPGRADE_PROTOCOL_NAME = "h2c";
48      public static final CharSequence TLS_UPGRADE_PROTOCOL_NAME = ApplicationProtocolNames.HTTP_2;
49  
50      public static final int PING_FRAME_PAYLOAD_LENGTH = 8;
51      public static final short MAX_UNSIGNED_BYTE = 0xff;
52      /**
53       * The maximum number of padding bytes. That is the 255 padding bytes appended to the end of a frame and the 1 byte
54       * pad length field.
55       */
56      public static final int MAX_PADDING = 256;
57      public static final long MAX_UNSIGNED_INT = 0xffffffffL;
58      public static final int FRAME_HEADER_LENGTH = 9;
59      public static final int SETTING_ENTRY_LENGTH = 6;
60      public static final int PRIORITY_ENTRY_LENGTH = 5;
61      public static final int INT_FIELD_LENGTH = 4;
62      public static final short MAX_WEIGHT = 256;
63      public static final short MIN_WEIGHT = 1;
64  
65      private static final ByteBuf CONNECTION_PREFACE =
66              unreleasableBuffer(directBuffer(24).writeBytes("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(UTF_8)))
67                      .asReadOnly();
68  
69      private static final int MAX_PADDING_LENGTH_LENGTH = 1;
70      public static final int DATA_FRAME_HEADER_LENGTH = FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH;
71      public static final int HEADERS_FRAME_HEADER_LENGTH =
72              FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH + INT_FIELD_LENGTH + 1;
73      public static final int PRIORITY_FRAME_LENGTH = FRAME_HEADER_LENGTH + PRIORITY_ENTRY_LENGTH;
74      public static final int RST_STREAM_FRAME_LENGTH = FRAME_HEADER_LENGTH + INT_FIELD_LENGTH;
75      public static final int PUSH_PROMISE_FRAME_HEADER_LENGTH =
76              FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH + INT_FIELD_LENGTH;
77      public static final int GO_AWAY_FRAME_HEADER_LENGTH = FRAME_HEADER_LENGTH + 2 * INT_FIELD_LENGTH;
78      public static final int WINDOW_UPDATE_FRAME_LENGTH = FRAME_HEADER_LENGTH + INT_FIELD_LENGTH;
79      public static final int CONTINUATION_FRAME_HEADER_LENGTH = FRAME_HEADER_LENGTH;
80  
81      public static final char SETTINGS_HEADER_TABLE_SIZE = 1;
82      public static final char SETTINGS_ENABLE_PUSH = 2;
83      public static final char SETTINGS_MAX_CONCURRENT_STREAMS = 3;
84      public static final char SETTINGS_INITIAL_WINDOW_SIZE = 4;
85      public static final char SETTINGS_MAX_FRAME_SIZE = 5;
86      public static final char SETTINGS_MAX_HEADER_LIST_SIZE = 6;
87      public static final char SETTINGS_ENABLE_CONNECT_PROTOCOL = 8;
88      public static final int NUM_STANDARD_SETTINGS = 7;
89  
90      public static final long MAX_HEADER_TABLE_SIZE = MAX_UNSIGNED_INT;
91      public static final long MAX_CONCURRENT_STREAMS = MAX_UNSIGNED_INT;
92      public static final int MAX_INITIAL_WINDOW_SIZE = Integer.MAX_VALUE;
93      public static final int MAX_FRAME_SIZE_LOWER_BOUND = 0x4000;
94      public static final int MAX_FRAME_SIZE_UPPER_BOUND = 0xffffff;
95      public static final long MAX_HEADER_LIST_SIZE = MAX_UNSIGNED_INT;
96  
97      public static final long MIN_HEADER_TABLE_SIZE = 0;
98      public static final long MIN_CONCURRENT_STREAMS = 0;
99      public static final int MIN_INITIAL_WINDOW_SIZE = 0;
100     public static final long MIN_HEADER_LIST_SIZE = 0;
101 
102     public static final int DEFAULT_WINDOW_SIZE = 65535;
103     public static final short DEFAULT_PRIORITY_WEIGHT = 16;
104     public static final int DEFAULT_HEADER_TABLE_SIZE = 4096;
105     /**
106      * <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">The initial value of this setting is unlimited</a>.
107      * However in practice we don't want to allow our peers to use unlimited memory by default. So we take advantage
108      * of the <q>For any given request, a lower limit than what is advertised MAY be enforced.</q> loophole.
109      */
110     public static final long DEFAULT_HEADER_LIST_SIZE = 8192;
111     public static final int DEFAULT_MAX_FRAME_SIZE = MAX_FRAME_SIZE_LOWER_BOUND;
112     /**
113      * The assumed minimum value for {@code SETTINGS_MAX_CONCURRENT_STREAMS} as
114      * recommended by the <a herf="https://tools.ietf.org/html/rfc7540#section-6.5.2">HTTP/2 spec</a>.
115      */
116     public static final int SMALLEST_MAX_CONCURRENT_STREAMS = 100;
117     static final int DEFAULT_MAX_RESERVED_STREAMS = SMALLEST_MAX_CONCURRENT_STREAMS;
118     static final int DEFAULT_MIN_ALLOCATION_CHUNK = 1024;
119 
120     /**
121      * Calculate the threshold in bytes which should trigger a {@code GO_AWAY} if a set of headers exceeds this amount.
122      * @param maxHeaderListSize
123      *      <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">SETTINGS_MAX_HEADER_LIST_SIZE</a> for the local
124      *      endpoint.
125      * @return the threshold in bytes which should trigger a {@code GO_AWAY} if a set of headers exceeds this amount.
126      */
127     public static long calculateMaxHeaderListSizeGoAway(long maxHeaderListSize) {
128         // This is equivalent to `maxHeaderListSize * 1.25` but we avoid floating point multiplication.
129         return maxHeaderListSize + (maxHeaderListSize >>> 2);
130     }
131 
132     public static final long DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MILLIS = MILLISECONDS.convert(30, SECONDS);
133 
134     public static final int DEFAULT_MAX_QUEUED_CONTROL_FRAMES = 10000;
135 
136     /**
137      * Returns {@code true} if the stream is an outbound stream.
138      *
139      * @param server    {@code true} if the endpoint is a server, {@code false} otherwise.
140      * @param streamId  the stream identifier
141      */
142     public static boolean isOutboundStream(boolean server, int streamId) {
143         boolean even = (streamId & 1) == 0;
144         return streamId > 0 && server == even;
145     }
146 
147     /**
148      * Returns true if the {@code streamId} is a valid HTTP/2 stream identifier.
149      */
150     public static boolean isStreamIdValid(int streamId) {
151         return streamId >= 0;
152     }
153 
154     static boolean isStreamIdValid(int streamId, boolean server) {
155         return isStreamIdValid(streamId) && server == ((streamId & 1) == 0);
156     }
157 
158     /**
159      * Indicates whether or not the given value for max frame size falls within the valid range.
160      */
161     public static boolean isMaxFrameSizeValid(int maxFrameSize) {
162         return maxFrameSize >= MAX_FRAME_SIZE_LOWER_BOUND && maxFrameSize <= MAX_FRAME_SIZE_UPPER_BOUND;
163     }
164 
165     /**
166      * Returns a buffer containing the {@link #CONNECTION_PREFACE}.
167      */
168     public static ByteBuf connectionPrefaceBuf() {
169         // Return a duplicate so that modifications to the reader index will not affect the original buffer.
170         return CONNECTION_PREFACE.retainedDuplicate();
171     }
172 
173     /**
174      * Iteratively looks through the causality chain for the given exception and returns the first
175      * {@link Http2Exception} or {@code null} if none.
176      */
177     public static Http2Exception getEmbeddedHttp2Exception(Throwable cause) {
178         while (cause != null) {
179             if (cause instanceof Http2Exception) {
180                 return (Http2Exception) cause;
181             }
182             cause = cause.getCause();
183         }
184         return null;
185     }
186 
187     /**
188      * Creates a buffer containing the error message from the given exception. If the cause is
189      * {@code null} returns an empty buffer.
190      */
191     public static ByteBuf toByteBuf(ChannelHandlerContext ctx, Throwable cause) {
192         if (cause == null || cause.getMessage() == null) {
193             return Unpooled.EMPTY_BUFFER;
194         }
195 
196         return ByteBufUtil.writeUtf8(ctx.alloc(), cause.getMessage());
197     }
198 
199     /**
200      * Reads a big-endian (31-bit) integer from the buffer.
201      */
202     public static int readUnsignedInt(ByteBuf buf) {
203         return buf.readInt() & 0x7fffffff;
204     }
205 
206     /**
207      * Writes an HTTP/2 frame header to the output buffer.
208      */
209     public static void writeFrameHeader(ByteBuf out, int payloadLength, byte type,
210             Http2Flags flags, int streamId) {
211         out.ensureWritable(FRAME_HEADER_LENGTH + payloadLength);
212         writeFrameHeaderInternal(out, payloadLength, type, flags, streamId);
213     }
214 
215     /**
216      * Calculate the amount of bytes that can be sent by {@code state}. The lower bound is {@code 0}.
217      */
218     public static int streamableBytes(StreamByteDistributor.StreamState state) {
219         return max(0, (int) min(state.pendingBytes(), state.windowSize()));
220     }
221 
222     /**
223      * Results in a RST_STREAM being sent for {@code streamId} due to violating
224      * <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">SETTINGS_MAX_HEADER_LIST_SIZE</a>.
225      * @param streamId The stream ID that was being processed when the exceptional condition occurred.
226      * @param maxHeaderListSize The max allowed size for a list of headers in bytes which was exceeded.
227      * @param onDecode {@code true} if the exception was encountered during decoder. {@code false} for encode.
228      * @throws Http2Exception a stream error.
229      */
230     public static void headerListSizeExceeded(int streamId, long maxHeaderListSize,
231                                               boolean onDecode) throws Http2Exception {
232         throw headerListSizeError(streamId, PROTOCOL_ERROR, onDecode, "Header size exceeded max " +
233                                   "allowed size (%d)", maxHeaderListSize);
234     }
235 
236     /**
237      * Results in a GO_AWAY being sent due to violating
238      * <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">SETTINGS_MAX_HEADER_LIST_SIZE</a> in an unrecoverable
239      * manner.
240      * @param maxHeaderListSize The max allowed size for a list of headers in bytes which was exceeded.
241      * @throws Http2Exception a connection error.
242      */
243     public static void headerListSizeExceeded(long maxHeaderListSize) throws Http2Exception {
244         throw connectionError(PROTOCOL_ERROR, "Header size exceeded max " +
245                 "allowed size (%d)", maxHeaderListSize);
246     }
247 
248     static void writeFrameHeaderInternal(ByteBuf out, int payloadLength, byte type,
249             Http2Flags flags, int streamId) {
250         out.writeMedium(payloadLength);
251         out.writeByte(type);
252         out.writeByte(flags.value());
253         out.writeInt(streamId);
254     }
255 
256     /**
257      * Provides the ability to associate the outcome of multiple {@link ChannelPromise}
258      * objects into a single {@link ChannelPromise} object.
259      */
260     static final class SimpleChannelPromiseAggregator extends DefaultChannelPromise {
261         private final ChannelPromise promise;
262         private int expectedCount;
263         private int doneCount;
264         private Throwable aggregateFailure;
265         private boolean doneAllocating;
266 
267         SimpleChannelPromiseAggregator(ChannelPromise promise, Channel c, EventExecutor e) {
268             super(c, e);
269             assert promise != null && !promise.isDone();
270             this.promise = promise;
271         }
272 
273         /**
274          * Allocate a new promise which will be used to aggregate the overall success of this promise aggregator.
275          * @return A new promise which will be aggregated.
276          * {@code null} if {@link #doneAllocatingPromises()} was previously called.
277          */
278         public ChannelPromise newPromise() {
279             assert !doneAllocating : "Done allocating. No more promises can be allocated.";
280             ++expectedCount;
281             return this;
282         }
283 
284         /**
285          * Signify that no more {@link #newPromise()} allocations will be made.
286          * The aggregation can not be successful until this method is called.
287          * @return The promise that is the aggregation of all promises allocated with {@link #newPromise()}.
288          */
289         public ChannelPromise doneAllocatingPromises() {
290             if (!doneAllocating) {
291                 doneAllocating = true;
292                 if (doneCount == expectedCount || expectedCount == 0) {
293                     return setPromise();
294                 }
295             }
296             return this;
297         }
298 
299         @Override
300         public boolean tryFailure(Throwable cause) {
301             if (allowFailure()) {
302                 ++doneCount;
303                 setAggregateFailure(cause);
304                 if (allPromisesDone()) {
305                     return tryPromise();
306                 }
307                 // TODO: We break the interface a bit here.
308                 // Multiple failure events can be processed without issue because this is an aggregation.
309                 return true;
310             }
311             return false;
312         }
313 
314         /**
315          * Fail this object if it has not already been failed.
316          * <p>
317          * This method will NOT throw an {@link IllegalStateException} if called multiple times
318          * because that may be expected.
319          */
320         @Override
321         public ChannelPromise setFailure(Throwable cause) {
322             if (allowFailure()) {
323                 ++doneCount;
324                 setAggregateFailure(cause);
325                 if (allPromisesDone()) {
326                     return setPromise();
327                 }
328             }
329             return this;
330         }
331 
332         @Override
333         public ChannelPromise setSuccess(Void result) {
334             if (awaitingPromises()) {
335                 ++doneCount;
336                 if (allPromisesDone()) {
337                     setPromise();
338                 }
339             }
340             return this;
341         }
342 
343         @Override
344         public boolean trySuccess(Void result) {
345             if (awaitingPromises()) {
346                 ++doneCount;
347                 if (allPromisesDone()) {
348                     return tryPromise();
349                 }
350                 // TODO: We break the interface a bit here.
351                 // Multiple success events can be processed without issue because this is an aggregation.
352                 return true;
353             }
354             return false;
355         }
356 
357         private boolean allowFailure() {
358             return awaitingPromises() || expectedCount == 0;
359         }
360 
361         private boolean awaitingPromises() {
362             return doneCount < expectedCount;
363         }
364 
365         private boolean allPromisesDone() {
366             return doneCount == expectedCount && doneAllocating;
367         }
368 
369         private ChannelPromise setPromise() {
370             if (aggregateFailure == null) {
371                 promise.setSuccess();
372                 return super.setSuccess(null);
373             } else {
374                 promise.setFailure(aggregateFailure);
375                 return super.setFailure(aggregateFailure);
376             }
377         }
378 
379         private boolean tryPromise() {
380             if (aggregateFailure == null) {
381                 promise.trySuccess();
382                 return super.trySuccess(null);
383             } else {
384                 promise.tryFailure(aggregateFailure);
385                 return super.tryFailure(aggregateFailure);
386             }
387         }
388 
389         private void setAggregateFailure(Throwable cause) {
390             if (aggregateFailure == null) {
391                 aggregateFailure = cause;
392             }
393         }
394     }
395 
396     public static void verifyPadding(int padding) {
397         if (padding < 0 || padding > MAX_PADDING) {
398             throw new IllegalArgumentException(String.format("Invalid padding '%d'. Padding must be between 0 and " +
399                                                              "%d (inclusive).", padding, MAX_PADDING));
400         }
401     }
402     private Http2CodecUtil() { }
403 }