1
2
3
4
5
6
7
8
9
10
11
12
13
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 import io.netty.util.internal.UnstableApi;
29
30 import static io.netty.buffer.Unpooled.directBuffer;
31 import static io.netty.buffer.Unpooled.unreleasableBuffer;
32 import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
33 import static io.netty.handler.codec.http2.Http2Exception.connectionError;
34 import static io.netty.handler.codec.http2.Http2Exception.headerListSizeError;
35 import static io.netty.util.CharsetUtil.UTF_8;
36 import static java.lang.Math.max;
37 import static java.lang.Math.min;
38 import static java.util.concurrent.TimeUnit.MILLISECONDS;
39 import static java.util.concurrent.TimeUnit.SECONDS;
40
41
42
43
44 @UnstableApi
45 public final class Http2CodecUtil {
46 public static final int CONNECTION_STREAM_ID = 0;
47 public static final int HTTP_UPGRADE_STREAM_ID = 1;
48 public static final CharSequence HTTP_UPGRADE_SETTINGS_HEADER = AsciiString.cached("HTTP2-Settings");
49 public static final CharSequence HTTP_UPGRADE_PROTOCOL_NAME = "h2c";
50 public static final CharSequence TLS_UPGRADE_PROTOCOL_NAME = ApplicationProtocolNames.HTTP_2;
51
52 public static final int PING_FRAME_PAYLOAD_LENGTH = 8;
53 public static final short MAX_UNSIGNED_BYTE = 0xff;
54
55
56
57
58 public static final int MAX_PADDING = 256;
59 public static final long MAX_UNSIGNED_INT = 0xffffffffL;
60 public static final int FRAME_HEADER_LENGTH = 9;
61 public static final int SETTING_ENTRY_LENGTH = 6;
62 public static final int PRIORITY_ENTRY_LENGTH = 5;
63 public static final int INT_FIELD_LENGTH = 4;
64 public static final short MAX_WEIGHT = 256;
65 public static final short MIN_WEIGHT = 1;
66
67 private static final ByteBuf CONNECTION_PREFACE =
68 unreleasableBuffer(directBuffer(24).writeBytes("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(UTF_8)))
69 .asReadOnly();
70
71 private static final int MAX_PADDING_LENGTH_LENGTH = 1;
72 public static final int DATA_FRAME_HEADER_LENGTH = FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH;
73 public static final int HEADERS_FRAME_HEADER_LENGTH =
74 FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH + INT_FIELD_LENGTH + 1;
75 public static final int PRIORITY_FRAME_LENGTH = FRAME_HEADER_LENGTH + PRIORITY_ENTRY_LENGTH;
76 public static final int RST_STREAM_FRAME_LENGTH = FRAME_HEADER_LENGTH + INT_FIELD_LENGTH;
77 public static final int PUSH_PROMISE_FRAME_HEADER_LENGTH =
78 FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH + INT_FIELD_LENGTH;
79 public static final int GO_AWAY_FRAME_HEADER_LENGTH = FRAME_HEADER_LENGTH + 2 * INT_FIELD_LENGTH;
80 public static final int WINDOW_UPDATE_FRAME_LENGTH = FRAME_HEADER_LENGTH + INT_FIELD_LENGTH;
81 public static final int CONTINUATION_FRAME_HEADER_LENGTH = FRAME_HEADER_LENGTH + MAX_PADDING_LENGTH_LENGTH;
82
83 public static final char SETTINGS_HEADER_TABLE_SIZE = 1;
84 public static final char SETTINGS_ENABLE_PUSH = 2;
85 public static final char SETTINGS_MAX_CONCURRENT_STREAMS = 3;
86 public static final char SETTINGS_INITIAL_WINDOW_SIZE = 4;
87 public static final char SETTINGS_MAX_FRAME_SIZE = 5;
88 public static final char SETTINGS_MAX_HEADER_LIST_SIZE = 6;
89 public static final int NUM_STANDARD_SETTINGS = 6;
90
91 public static final long MAX_HEADER_TABLE_SIZE = MAX_UNSIGNED_INT;
92 public static final long MAX_CONCURRENT_STREAMS = MAX_UNSIGNED_INT;
93 public static final int MAX_INITIAL_WINDOW_SIZE = Integer.MAX_VALUE;
94 public static final int MAX_FRAME_SIZE_LOWER_BOUND = 0x4000;
95 public static final int MAX_FRAME_SIZE_UPPER_BOUND = 0xffffff;
96 public static final long MAX_HEADER_LIST_SIZE = MAX_UNSIGNED_INT;
97
98 public static final long MIN_HEADER_TABLE_SIZE = 0;
99 public static final long MIN_CONCURRENT_STREAMS = 0;
100 public static final int MIN_INITIAL_WINDOW_SIZE = 0;
101 public static final long MIN_HEADER_LIST_SIZE = 0;
102
103 public static final int DEFAULT_WINDOW_SIZE = 65535;
104 public static final short DEFAULT_PRIORITY_WEIGHT = 16;
105 public static final int DEFAULT_HEADER_TABLE_SIZE = 4096;
106
107
108
109
110
111 public static final long DEFAULT_HEADER_LIST_SIZE = 8192;
112 public static final int DEFAULT_MAX_FRAME_SIZE = MAX_FRAME_SIZE_LOWER_BOUND;
113
114
115
116
117 public static final int SMALLEST_MAX_CONCURRENT_STREAMS = 100;
118 static final int DEFAULT_MAX_RESERVED_STREAMS = SMALLEST_MAX_CONCURRENT_STREAMS;
119 static final int DEFAULT_MIN_ALLOCATION_CHUNK = 1024;
120
121
122
123
124
125
126
127
128 public static long calculateMaxHeaderListSizeGoAway(long maxHeaderListSize) {
129
130 return maxHeaderListSize + (maxHeaderListSize >>> 2);
131 }
132
133 public static final long DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MILLIS = MILLISECONDS.convert(30, SECONDS);
134
135 public static final int DEFAULT_MAX_QUEUED_CONTROL_FRAMES = 10000;
136
137
138
139
140
141
142
143 public static boolean isOutboundStream(boolean server, int streamId) {
144 boolean even = (streamId & 1) == 0;
145 return streamId > 0 && server == even;
146 }
147
148
149
150
151 public static boolean isStreamIdValid(int streamId) {
152 return streamId >= 0;
153 }
154
155 static boolean isStreamIdValid(int streamId, boolean server) {
156 return isStreamIdValid(streamId) && server == ((streamId & 1) == 0);
157 }
158
159
160
161
162 public static boolean isMaxFrameSizeValid(int maxFrameSize) {
163 return maxFrameSize >= MAX_FRAME_SIZE_LOWER_BOUND && maxFrameSize <= MAX_FRAME_SIZE_UPPER_BOUND;
164 }
165
166
167
168
169 public static ByteBuf connectionPrefaceBuf() {
170
171 return CONNECTION_PREFACE.retainedDuplicate();
172 }
173
174
175
176
177
178 public static Http2Exception getEmbeddedHttp2Exception(Throwable cause) {
179 while (cause != null) {
180 if (cause instanceof Http2Exception) {
181 return (Http2Exception) cause;
182 }
183 cause = cause.getCause();
184 }
185 return null;
186 }
187
188
189
190
191
192 public static ByteBuf toByteBuf(ChannelHandlerContext ctx, Throwable cause) {
193 if (cause == null || cause.getMessage() == null) {
194 return Unpooled.EMPTY_BUFFER;
195 }
196
197 return ByteBufUtil.writeUtf8(ctx.alloc(), cause.getMessage());
198 }
199
200
201
202
203 public static int readUnsignedInt(ByteBuf buf) {
204 return buf.readInt() & 0x7fffffff;
205 }
206
207
208
209
210 public static void writeFrameHeader(ByteBuf out, int payloadLength, byte type,
211 Http2Flags flags, int streamId) {
212 out.ensureWritable(FRAME_HEADER_LENGTH + payloadLength);
213 writeFrameHeaderInternal(out, payloadLength, type, flags, streamId);
214 }
215
216
217
218
219 public static int streamableBytes(StreamByteDistributor.StreamState state) {
220 return max(0, (int) min(state.pendingBytes(), state.windowSize()));
221 }
222
223
224
225
226
227
228
229
230
231 public static void headerListSizeExceeded(int streamId, long maxHeaderListSize,
232 boolean onDecode) throws Http2Exception {
233 throw headerListSizeError(streamId, PROTOCOL_ERROR, onDecode, "Header size exceeded max " +
234 "allowed size (%d)", maxHeaderListSize);
235 }
236
237
238
239
240
241
242
243
244 public static void headerListSizeExceeded(long maxHeaderListSize) throws Http2Exception {
245 throw connectionError(PROTOCOL_ERROR, "Header size exceeded max " +
246 "allowed size (%d)", maxHeaderListSize);
247 }
248
249 static void writeFrameHeaderInternal(ByteBuf out, int payloadLength, byte type,
250 Http2Flags flags, int streamId) {
251 out.writeMedium(payloadLength);
252 out.writeByte(type);
253 out.writeByte(flags.value());
254 out.writeInt(streamId);
255 }
256
257
258
259
260
261 static final class SimpleChannelPromiseAggregator extends DefaultChannelPromise {
262 private final ChannelPromise promise;
263 private int expectedCount;
264 private int doneCount;
265 private Throwable aggregateFailure;
266 private boolean doneAllocating;
267
268 SimpleChannelPromiseAggregator(ChannelPromise promise, Channel c, EventExecutor e) {
269 super(c, e);
270 assert promise != null && !promise.isDone();
271 this.promise = promise;
272 }
273
274
275
276
277
278
279 public ChannelPromise newPromise() {
280 assert !doneAllocating : "Done allocating. No more promises can be allocated.";
281 ++expectedCount;
282 return this;
283 }
284
285
286
287
288
289
290 public ChannelPromise doneAllocatingPromises() {
291 if (!doneAllocating) {
292 doneAllocating = true;
293 if (doneCount == expectedCount || expectedCount == 0) {
294 return setPromise();
295 }
296 }
297 return this;
298 }
299
300 @Override
301 public boolean tryFailure(Throwable cause) {
302 if (allowFailure()) {
303 ++doneCount;
304 setAggregateFailure(cause);
305 if (allPromisesDone()) {
306 return tryPromise();
307 }
308
309
310 return true;
311 }
312 return false;
313 }
314
315
316
317
318
319
320
321 @Override
322 public ChannelPromise setFailure(Throwable cause) {
323 if (allowFailure()) {
324 ++doneCount;
325 setAggregateFailure(cause);
326 if (allPromisesDone()) {
327 return setPromise();
328 }
329 }
330 return this;
331 }
332
333 @Override
334 public ChannelPromise setSuccess(Void result) {
335 if (awaitingPromises()) {
336 ++doneCount;
337 if (allPromisesDone()) {
338 setPromise();
339 }
340 }
341 return this;
342 }
343
344 @Override
345 public boolean trySuccess(Void result) {
346 if (awaitingPromises()) {
347 ++doneCount;
348 if (allPromisesDone()) {
349 return tryPromise();
350 }
351
352
353 return true;
354 }
355 return false;
356 }
357
358 private boolean allowFailure() {
359 return awaitingPromises() || expectedCount == 0;
360 }
361
362 private boolean awaitingPromises() {
363 return doneCount < expectedCount;
364 }
365
366 private boolean allPromisesDone() {
367 return doneCount == expectedCount && doneAllocating;
368 }
369
370 private ChannelPromise setPromise() {
371 if (aggregateFailure == null) {
372 promise.setSuccess();
373 return super.setSuccess(null);
374 } else {
375 promise.setFailure(aggregateFailure);
376 return super.setFailure(aggregateFailure);
377 }
378 }
379
380 private boolean tryPromise() {
381 if (aggregateFailure == null) {
382 promise.trySuccess();
383 return super.trySuccess(null);
384 } else {
385 promise.tryFailure(aggregateFailure);
386 return super.tryFailure(aggregateFailure);
387 }
388 }
389
390 private void setAggregateFailure(Throwable cause) {
391 if (aggregateFailure == null) {
392 aggregateFailure = cause;
393 }
394 }
395 }
396
397 public static void verifyPadding(int padding) {
398 if (padding < 0 || padding > MAX_PADDING) {
399 throw new IllegalArgumentException(String.format("Invalid padding '%d'. Padding must be between 0 and " +
400 "%d (inclusive).", padding, MAX_PADDING));
401 }
402 }
403 private Http2CodecUtil() { }
404 }