View Javadoc
1   /*
2    * Copyright 2016 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.http2;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.Channel;
20  import io.netty.channel.ChannelFuture;
21  import io.netty.channel.ChannelFutureListener;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.ChannelInboundHandler;
24  import io.netty.channel.ChannelPromise;
25  import io.netty.handler.codec.UnsupportedMessageTypeException;
26  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeEvent;
27  import io.netty.handler.codec.http2.Http2Connection.PropertyKey;
28  import io.netty.handler.codec.http2.Http2Stream.State;
29  import io.netty.handler.codec.http2.StreamBufferingEncoder.Http2ChannelClosedException;
30  import io.netty.handler.codec.http2.StreamBufferingEncoder.Http2GoAwayException;
31  import io.netty.util.ReferenceCountUtil;
32  import io.netty.util.ReferenceCounted;
33  import io.netty.util.collection.IntObjectHashMap;
34  import io.netty.util.collection.IntObjectMap;
35  import io.netty.util.internal.logging.InternalLogger;
36  import io.netty.util.internal.logging.InternalLoggerFactory;
37  
38  import static io.netty.buffer.ByteBufUtil.writeAscii;
39  import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_STREAM_ID;
40  import static io.netty.handler.codec.http2.Http2CodecUtil.isStreamIdValid;
41  import static io.netty.handler.codec.http2.Http2Error.NO_ERROR;
42  import static io.netty.util.internal.logging.InternalLogLevel.DEBUG;
43  
44  /**
45   * <p>An HTTP/2 handler that maps HTTP/2 frames to {@link Http2Frame} objects and vice versa. For every incoming HTTP/2
46   * frame, an {@link Http2Frame} object is created and propagated via {@link #channelRead}. Outbound {@link Http2Frame}
47   * objects received via {@link #write} are converted to the HTTP/2 wire format. HTTP/2 frames specific to a stream
48   * implement the {@link Http2StreamFrame} interface. The {@link Http2FrameCodec} is instantiated using the
49   * {@link Http2FrameCodecBuilder}. It's recommended for channel handlers to inherit from the
50   * {@link Http2ChannelDuplexHandler}, as it provides additional functionality like iterating over all active streams or
51   * creating outbound streams.
52   *
53   * <h3>Stream Lifecycle</h3>
54   * <p>
55   * The frame codec delivers and writes frames for active streams. An active stream is closed when either side sends a
56   * {@code RST_STREAM} frame or both sides send a frame with the {@code END_STREAM} flag set. Each
57   * {@link Http2StreamFrame} has a {@link Http2FrameStream} object attached that uniquely identifies a particular stream.
58   *
59   * <p>{@link Http2StreamFrame}s read from the channel always a {@link Http2FrameStream} object set, while when writing a
60   * {@link Http2StreamFrame} the application code needs to set a {@link Http2FrameStream} object using
61   * {@link Http2StreamFrame#stream(Http2FrameStream)}.
62   *
63   * <h3>Flow control</h3>
64   * <p>
65   * The frame codec automatically increments stream and connection flow control windows.
66   *
67   * <p>Incoming flow controlled frames need to be consumed by writing a {@link Http2WindowUpdateFrame} with the consumed
68   * number of bytes and the corresponding stream identifier set to the frame codec.
69   *
70   * <p>The local stream-level flow control window can be changed by writing a {@link Http2SettingsFrame} with the
71   * {@link Http2Settings#initialWindowSize()} set to the targeted value.
72   *
73   * <p>The connection-level flow control window can be changed by writing a {@link Http2WindowUpdateFrame} with the
74   * desired window size <em>increment</em> in bytes and the stream identifier set to {@code 0}. By default the initial
75   * connection-level flow control window is the same as initial stream-level flow control window.
76   *
77   * <h3>New inbound Streams</h3>
78   * <p>
79   * The first frame of an HTTP/2 stream must be an {@link Http2HeadersFrame}, which will have an {@link Http2FrameStream}
80   * object attached.
81   *
82   * <h3>New outbound Streams</h3>
83   * <p>
84   * A outbound HTTP/2 stream can be created by first instantiating a new {@link Http2FrameStream} object via
85   * {@link Http2ChannelDuplexHandler#newStream()}, and then writing a {@link Http2HeadersFrame} object with the stream
86   * attached.
87   *
88   * <pre> {@code
89   *     final Http2Stream2 stream = handler.newStream();
90   *     ctx.write(headersFrame.stream(stream)).addListener(new ChannelFutureListener() {
91   *
92   *         @Override
93   *         public void operationComplete(ChannelFuture f) {
94   *             if (f.isSuccess()) {
95   *                 // Stream is active and stream.id() returns a valid stream identifier.
96   *                 System.out.println("New stream with id " + stream.id() + " created.");
97   *             } else {
98   *                 // Stream failed to become active. Handle error.
99   *                 if (f.cause() instanceof Http2NoMoreStreamIdsException) {
100  *
101  *                 } else if (f.cause() instanceof Http2GoAwayException) {
102  *
103  *                 } else {
104  *
105  *                 }
106  *             }
107  *         }
108  *     }
109  *     }
110  * </pre>
111  *
112  * <p>If a new stream cannot be created due to stream id exhaustion of the endpoint, the {@link ChannelPromise} of the
113  * HEADERS frame will fail with a {@link Http2NoMoreStreamIdsException}.
114  *
115  * <p>The HTTP/2 standard allows for an endpoint to limit the maximum number of concurrently active streams via the
116  * {@code SETTINGS_MAX_CONCURRENT_STREAMS} setting. When this limit is reached, no new streams can be created. However,
117  * the {@link Http2FrameCodec} can be build with
118  * {@link Http2FrameCodecBuilder#encoderEnforceMaxConcurrentStreams(boolean)} enabled, in which case a new stream and
119  * its associated frames will be buffered until either the limit is increased or an active stream is closed. It's,
120  * however, possible that a buffered stream will never become active. That is, the channel might
121  * get closed or a GO_AWAY frame might be received. In the first case, all writes of buffered streams will fail with a
122  * {@link Http2ChannelClosedException}. In the second case, all writes of buffered streams with an identifier less than
123  * the last stream identifier of the GO_AWAY frame will fail with a {@link Http2GoAwayException}.
124  *
125  * <h3>Error Handling</h3>
126  * <p>
127  * Exceptions and errors are propagated via {@link ChannelInboundHandler#exceptionCaught}. Exceptions that apply to
128  * a specific HTTP/2 stream are wrapped in a {@link Http2FrameStreamException} and have the corresponding
129  * {@link Http2FrameStream} object attached.
130  *
131  * <h3>Reference Counting</h3>
132  * <p>
133  * Some {@link Http2StreamFrame}s implement the {@link ReferenceCounted} interface, as they carry
134  * reference counted objects (e.g. {@link ByteBuf}s). The frame codec will call {@link ReferenceCounted#retain()} before
135  * propagating a reference counted object through the pipeline, and thus an application handler needs to release such
136  * an object after having consumed it. For more information on reference counting take a look at
137  * <a href="https://netty.io/wiki/reference-counted-objects.html">Reference counted objects</a>
138  *
139  * <h3>HTTP Upgrade</h3>
140  * <p>
141  * Server-side HTTP to HTTP/2 upgrade is supported in conjunction with {@link Http2ServerUpgradeCodec}; the necessary
142  * HTTP-to-HTTP/2 conversion is performed automatically.
143  */
144 public class Http2FrameCodec extends Http2ConnectionHandler {
145 
146     private static final InternalLogger LOG = InternalLoggerFactory.getInstance(Http2FrameCodec.class);
147 
148     private static final Class<?>[] SUPPORTED_MESSAGES = new Class[] {
149             Http2DataFrame.class, Http2HeadersFrame.class, Http2WindowUpdateFrame.class, Http2ResetFrame.class,
150             Http2PingFrame.class, Http2SettingsFrame.class, Http2SettingsAckFrame.class, Http2GoAwayFrame.class,
151             Http2PushPromiseFrame.class, Http2PriorityFrame.class, Http2UnknownFrame.class };
152 
153     protected final PropertyKey streamKey;
154     private final PropertyKey upgradeKey;
155 
156     private final Integer initialFlowControlWindowSize;
157 
158     ChannelHandlerContext ctx;
159 
160     /**
161      * Number of buffered streams if the {@link StreamBufferingEncoder} is used.
162      **/
163     private int numBufferedStreams;
164     private final IntObjectMap<DefaultHttp2FrameStream> frameStreamToInitializeMap =
165             new IntObjectHashMap<DefaultHttp2FrameStream>(8);
166 
167     protected Http2FrameCodec(Http2ConnectionEncoder encoder, Http2ConnectionDecoder decoder,
168                               Http2Settings initialSettings, boolean decoupleCloseAndGoAway, boolean flushPreface) {
169         super(decoder, encoder, initialSettings, decoupleCloseAndGoAway, flushPreface);
170 
171         decoder.frameListener(new FrameListener());
172         connection().addListener(new ConnectionListener());
173         connection().remote().flowController().listener(new Http2RemoteFlowControllerListener());
174         streamKey = connection().newKey();
175         upgradeKey = connection().newKey();
176         initialFlowControlWindowSize = initialSettings.initialWindowSize();
177     }
178 
179     /**
180      * Creates a new outbound/local stream.
181      */
182     DefaultHttp2FrameStream newStream() {
183         return new DefaultHttp2FrameStream();
184     }
185 
186     /**
187      * Iterates over all active HTTP/2 streams.
188      *
189      * <p>This method must not be called outside of the event loop.
190      */
191     final void forEachActiveStream(final Http2FrameStreamVisitor streamVisitor) throws Http2Exception {
192         assert ctx.executor().inEventLoop();
193         if (connection().numActiveStreams() > 0) {
194             connection().forEachActiveStream(new Http2StreamVisitor() {
195                 @Override
196                 public boolean visit(Http2Stream stream) {
197                     try {
198                         return streamVisitor.visit((Http2FrameStream) stream.getProperty(streamKey));
199                     } catch (Throwable cause) {
200                         onError(ctx, false, cause);
201                         return false;
202                     }
203                 }
204             });
205         }
206     }
207 
208     /**
209      * Retrieve the number of streams currently in the process of being initialized.
210      * <p>
211      * This is package-private for testing only.
212      */
213     int numInitializingStreams() {
214         return frameStreamToInitializeMap.size();
215     }
216 
217     @Override
218     public final void handlerAdded(ChannelHandlerContext ctx) throws Exception {
219         this.ctx = ctx;
220         super.handlerAdded(ctx);
221         handlerAdded0(ctx);
222         // Must be after Http2ConnectionHandler does its initialization in handlerAdded above.
223         // The server will not send a connection preface so we are good to send a window update.
224         Http2Connection connection = connection();
225         if (connection.isServer()) {
226             tryExpandConnectionFlowControlWindow(connection);
227         }
228     }
229 
230     private void tryExpandConnectionFlowControlWindow(Http2Connection connection) throws Http2Exception {
231         if (initialFlowControlWindowSize != null) {
232             // The window size in the settings explicitly excludes the connection window. So we manually manipulate the
233             // connection window to accommodate more concurrent data per connection.
234             Http2Stream connectionStream = connection.connectionStream();
235             Http2LocalFlowController localFlowController = connection.local().flowController();
236             final int delta = initialFlowControlWindowSize - localFlowController.initialWindowSize(connectionStream);
237             // Only increase the connection window, don't decrease it.
238             if (delta > 0) {
239                 // Double the delta just so a single stream can't exhaust the connection window.
240                 localFlowController.incrementWindowSize(connectionStream, Math.max(delta << 1, delta));
241                 flush(ctx);
242             }
243         }
244     }
245 
246     void handlerAdded0(@SuppressWarnings("unsed") ChannelHandlerContext ctx) throws Exception {
247         // sub-class can override this for extra steps that needs to be done when the handler is added.
248     }
249 
250     /**
251      * Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via
252      * HTTP/2 on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
253      */
254     @Override
255     public final void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
256         if (evt == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) {
257             // The user event implies that we are on the client.
258             tryExpandConnectionFlowControlWindow(connection());
259 
260             // We schedule this on the EventExecutor to allow to have any extra handlers added to the pipeline
261             // before we pass the event to the next handler. This is needed as the event may be called from within
262             // handlerAdded(...) which will be run before other handlers will be added to the pipeline.
263             ctx.executor().execute(new Runnable() {
264                 @Override
265                 public void run() {
266                     ctx.fireUserEventTriggered(evt);
267                 }
268             });
269         } else if (evt instanceof UpgradeEvent) {
270             UpgradeEvent upgrade = (UpgradeEvent) evt;
271             try {
272                 onUpgradeEvent(ctx, upgrade.retain());
273                 Http2Stream stream = connection().stream(HTTP_UPGRADE_STREAM_ID);
274                 if (stream.getProperty(streamKey) == null) {
275                     // TODO: improve handler/stream lifecycle so that stream isn't active before handler added.
276                     // The stream was already made active, but ctx may have been null so it wasn't initialized.
277                     // https://github.com/netty/netty/issues/4942
278                     onStreamActive0(stream);
279                 }
280                 upgrade.upgradeRequest().headers().setInt(
281                         HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), HTTP_UPGRADE_STREAM_ID);
282                 stream.setProperty(upgradeKey, true);
283                 InboundHttpToHttp2Adapter.handle(
284                         ctx, connection(), decoder().frameListener(), upgrade.upgradeRequest().retain());
285             } finally {
286                 upgrade.release();
287             }
288         } else {
289             onUserEventTriggered(ctx, evt);
290             ctx.fireUserEventTriggered(evt);
291         }
292     }
293 
294     void onUserEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
295         // noop
296     }
297 
298     /**
299      * Processes all {@link Http2Frame}s. {@link Http2StreamFrame}s may only originate in child
300      * streams.
301      */
302     @Override
303     public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
304         if (msg instanceof Http2DataFrame) {
305             Http2DataFrame dataFrame = (Http2DataFrame) msg;
306             encoder().writeData(ctx, dataFrame.stream().id(), dataFrame.content(),
307                     dataFrame.padding(), dataFrame.isEndStream(), promise);
308         } else if (msg instanceof Http2HeadersFrame) {
309             writeHeadersFrame(ctx, (Http2HeadersFrame) msg, promise);
310         } else if (msg instanceof Http2WindowUpdateFrame) {
311             Http2WindowUpdateFrame frame = (Http2WindowUpdateFrame) msg;
312             Http2FrameStream frameStream = frame.stream();
313             // It is legit to send a WINDOW_UPDATE frame for the connection stream. The parent channel doesn't attempt
314             // to set the Http2FrameStream so we assume if it is null the WINDOW_UPDATE is for the connection stream.
315             try {
316                 if (frameStream == null) {
317                     increaseInitialConnectionWindow(frame.windowSizeIncrement());
318                 } else {
319                     consumeBytes(frameStream.id(), frame.windowSizeIncrement());
320                 }
321                 promise.setSuccess();
322             } catch (Throwable t) {
323                 promise.setFailure(t);
324             }
325         } else if (msg instanceof Http2ResetFrame) {
326             Http2ResetFrame rstFrame = (Http2ResetFrame) msg;
327             int id = rstFrame.stream().id();
328             // Only ever send a reset frame if stream may have existed before as otherwise we may send a RST on a
329             // stream in an invalid state and cause a connection error.
330             if (connection().streamMayHaveExisted(id)) {
331                 encoder().writeRstStream(ctx, rstFrame.stream().id(), rstFrame.errorCode(), promise);
332             } else {
333                 ReferenceCountUtil.release(rstFrame);
334                 promise.setFailure(Http2Exception.streamError(
335                         rstFrame.stream().id(), Http2Error.PROTOCOL_ERROR, "Stream never existed"));
336             }
337         } else if (msg instanceof Http2PingFrame) {
338             Http2PingFrame frame = (Http2PingFrame) msg;
339             encoder().writePing(ctx, frame.ack(), frame.content(), promise);
340         } else if (msg instanceof Http2SettingsFrame) {
341             encoder().writeSettings(ctx, ((Http2SettingsFrame) msg).settings(), promise);
342         } else if (msg instanceof Http2SettingsAckFrame) {
343             // In the event of manual SETTINGS ACK, it is assumed the encoder will apply the earliest received but not
344             // yet ACKed settings.
345             encoder().writeSettingsAck(ctx, promise);
346         } else if (msg instanceof Http2GoAwayFrame) {
347             writeGoAwayFrame(ctx, (Http2GoAwayFrame) msg, promise);
348         } else if (msg instanceof Http2PushPromiseFrame) {
349             Http2PushPromiseFrame pushPromiseFrame = (Http2PushPromiseFrame) msg;
350             writePushPromise(ctx, pushPromiseFrame, promise);
351         } else if (msg instanceof Http2PriorityFrame) {
352             Http2PriorityFrame priorityFrame = (Http2PriorityFrame) msg;
353             encoder().writePriority(ctx, priorityFrame.stream().id(), priorityFrame.streamDependency(),
354                     priorityFrame.weight(), priorityFrame.exclusive(), promise);
355         } else if (msg instanceof Http2UnknownFrame) {
356             Http2UnknownFrame unknownFrame = (Http2UnknownFrame) msg;
357             encoder().writeFrame(ctx, unknownFrame.frameType(), unknownFrame.stream().id(),
358                     unknownFrame.flags(), unknownFrame.content(), promise);
359         } else if (!(msg instanceof Http2Frame)) {
360             ctx.write(msg, promise);
361         } else {
362             ReferenceCountUtil.release(msg);
363             throw new UnsupportedMessageTypeException(msg, SUPPORTED_MESSAGES);
364         }
365     }
366 
367     private void increaseInitialConnectionWindow(int deltaBytes) throws Http2Exception {
368         // The LocalFlowController is responsible for detecting over/under flow.
369         connection().local().flowController().incrementWindowSize(connection().connectionStream(), deltaBytes);
370     }
371 
372     final boolean consumeBytes(int streamId, int bytes) throws Http2Exception {
373         Http2Stream stream = connection().stream(streamId);
374         // Upgraded requests are ineligible for stream control. We add the null check
375         // in case the stream has been deregistered.
376         if (stream != null && streamId == Http2CodecUtil.HTTP_UPGRADE_STREAM_ID) {
377             Boolean upgraded = stream.getProperty(upgradeKey);
378             if (Boolean.TRUE.equals(upgraded)) {
379                 return false;
380             }
381         }
382 
383         return connection().local().flowController().consumeBytes(stream, bytes);
384     }
385 
386     private void writeGoAwayFrame(ChannelHandlerContext ctx, Http2GoAwayFrame frame, ChannelPromise promise) {
387         if (frame.lastStreamId() > -1) {
388             frame.release();
389             throw new IllegalArgumentException("Last stream id must not be set on GOAWAY frame");
390         }
391 
392         int lastStreamCreated = connection().remote().lastStreamCreated();
393         long lastStreamId = lastStreamCreated + ((long) frame.extraStreamIds()) * 2;
394         // Check if the computation overflowed.
395         if (lastStreamId > Integer.MAX_VALUE) {
396             lastStreamId = Integer.MAX_VALUE;
397         }
398         goAway(ctx, (int) lastStreamId, frame.errorCode(), frame.content(), promise);
399     }
400 
401     private void writeHeadersFrame(final ChannelHandlerContext ctx, Http2HeadersFrame headersFrame,
402                                    ChannelPromise promise) {
403 
404         if (isStreamIdValid(headersFrame.stream().id())) {
405             encoder().writeHeaders(ctx, headersFrame.stream().id(), headersFrame.headers(), headersFrame.padding(),
406                     headersFrame.isEndStream(), promise);
407         } else if (initializeNewStream(ctx, (DefaultHttp2FrameStream) headersFrame.stream(), promise)) {
408             promise = promise.unvoid();
409 
410             final int streamId = headersFrame.stream().id();
411 
412             encoder().writeHeaders(ctx, streamId, headersFrame.headers(), headersFrame.padding(),
413                     headersFrame.isEndStream(), promise);
414 
415             if (!promise.isDone()) {
416                 numBufferedStreams++;
417                 // Clean up the stream being initialized if writing the headers fails and also
418                 // decrement the number of buffered streams.
419                 promise.addListener((ChannelFutureListener) channelFuture -> {
420                     numBufferedStreams--;
421                     handleHeaderFuture(channelFuture, streamId);
422                 });
423             } else {
424                 handleHeaderFuture(promise, streamId);
425             }
426         }
427     }
428 
429     private void writePushPromise(final ChannelHandlerContext ctx, Http2PushPromiseFrame pushPromiseFrame,
430                                   final ChannelPromise promise) {
431         if (isStreamIdValid(pushPromiseFrame.pushStream().id())) {
432             encoder().writePushPromise(ctx, pushPromiseFrame.stream().id(), pushPromiseFrame.pushStream().id(),
433                     pushPromiseFrame.http2Headers(), pushPromiseFrame.padding(), promise);
434         } else if (initializeNewStream(ctx, (DefaultHttp2FrameStream) pushPromiseFrame.pushStream(), promise)) {
435             final int streamId = pushPromiseFrame.stream().id();
436             encoder().writePushPromise(ctx, streamId, pushPromiseFrame.pushStream().id(),
437                     pushPromiseFrame.http2Headers(), pushPromiseFrame.padding(), promise);
438 
439             if (promise.isDone()) {
440                 handleHeaderFuture(promise, streamId);
441             } else {
442                 numBufferedStreams++;
443                 // Clean up the stream being initialized if writing the headers fails and also
444                 // decrement the number of buffered streams.
445                 promise.addListener((ChannelFutureListener) channelFuture -> {
446                     numBufferedStreams--;
447                     handleHeaderFuture(channelFuture, streamId);
448                 });
449             }
450         }
451     }
452 
453     private boolean initializeNewStream(ChannelHandlerContext ctx, DefaultHttp2FrameStream http2FrameStream,
454                                         ChannelPromise promise) {
455         final Http2Connection connection = connection();
456         final int streamId = connection.local().incrementAndGetNextStreamId();
457         if (streamId < 0) {
458             promise.setFailure(new Http2NoMoreStreamIdsException());
459 
460             // Simulate a GOAWAY being received due to stream exhaustion on this connection. We use the maximum
461             // valid stream ID for the current peer.
462             onHttp2Frame(ctx, new DefaultHttp2GoAwayFrame(connection.isServer() ? Integer.MAX_VALUE :
463                     Integer.MAX_VALUE - 1, NO_ERROR.code(),
464                     writeAscii(ctx.alloc(), "Stream IDs exhausted on local stream creation")));
465 
466             return false;
467         }
468         http2FrameStream.id = streamId;
469 
470         // Use a Map to store all pending streams as we may have multiple. This is needed as if we would store the
471         // stream in a field directly we may override the stored field before onStreamAdded(...) was called
472         // and so not correctly set the property for the buffered stream.
473         //
474         // See https://github.com/netty/netty/issues/8692
475         Object old = frameStreamToInitializeMap.put(streamId, http2FrameStream);
476 
477         // We should not re-use ids.
478         assert old == null;
479         return true;
480     }
481 
482     private void handleHeaderFuture(ChannelFuture channelFuture, int streamId) {
483         if (!channelFuture.isSuccess()) {
484             frameStreamToInitializeMap.remove(streamId);
485         }
486     }
487 
488     private void onStreamActive0(Http2Stream stream) {
489         if (stream.id() != Http2CodecUtil.HTTP_UPGRADE_STREAM_ID &&
490                 connection().local().isValidStreamId(stream.id())) {
491             return;
492         }
493 
494         DefaultHttp2FrameStream stream2 = newStream().setStreamAndProperty(streamKey, stream);
495         onHttp2StreamStateChanged(ctx, stream2);
496     }
497 
498     private final class ConnectionListener extends Http2ConnectionAdapter {
499         @Override
500         public void onStreamAdded(Http2Stream stream) {
501             DefaultHttp2FrameStream frameStream = frameStreamToInitializeMap.remove(stream.id());
502 
503             if (frameStream != null) {
504                 frameStream.setStreamAndProperty(streamKey, stream);
505             }
506         }
507 
508         @Override
509         public void onStreamActive(Http2Stream stream) {
510             onStreamActive0(stream);
511         }
512 
513         @Override
514         public void onStreamClosed(Http2Stream stream) {
515             onHttp2StreamStateChanged0(stream);
516         }
517 
518         @Override
519         public void onStreamHalfClosed(Http2Stream stream) {
520             onHttp2StreamStateChanged0(stream);
521         }
522 
523         private void onHttp2StreamStateChanged0(Http2Stream stream) {
524             DefaultHttp2FrameStream stream2 = stream.getProperty(streamKey);
525             if (stream2 != null) {
526                 onHttp2StreamStateChanged(ctx, stream2);
527             }
528         }
529     }
530 
531     @Override
532     protected void onConnectionError(
533             ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception http2Ex) {
534         if (!outbound) {
535             // allow the user to handle it first in the pipeline, and then automatically clean up.
536             // If this is not desired behavior the user can override this method.
537             //
538             // We only forward non outbound errors as outbound errors will already be reflected by failing the promise.
539             ctx.fireExceptionCaught(cause);
540         }
541         super.onConnectionError(ctx, outbound, cause, http2Ex);
542     }
543 
544     /**
545      * Exceptions for unknown streams, that is streams that have no {@link Http2FrameStream} object attached
546      * are simply logged and replied to by sending a RST_STREAM frame.
547      */
548     @Override
549     protected final void onStreamError(ChannelHandlerContext ctx, boolean outbound, Throwable cause,
550                                        Http2Exception.StreamException streamException) {
551         int streamId = streamException.streamId();
552         Http2Stream connectionStream = connection().stream(streamId);
553         if (connectionStream == null) {
554             onHttp2UnknownStreamError(ctx, cause, streamException);
555             // Write a RST_STREAM
556             super.onStreamError(ctx, outbound, cause, streamException);
557             return;
558         }
559 
560         Http2FrameStream stream = connectionStream.getProperty(streamKey);
561         if (stream == null) {
562             LOG.warn("{} Stream exception thrown without stream object attached.", ctx.channel(), cause);
563             // Write a RST_STREAM
564             super.onStreamError(ctx, outbound, cause, streamException);
565             return;
566         }
567 
568         if (!outbound) {
569             // We only forward non outbound errors as outbound errors will already be reflected by failing the promise.
570             onHttp2FrameStreamException(ctx, new Http2FrameStreamException(stream, streamException.error(), cause));
571         }
572     }
573 
574     private static void onHttp2UnknownStreamError(@SuppressWarnings("unused") ChannelHandlerContext ctx,
575             Throwable cause, Http2Exception.StreamException streamException) {
576         // We log here for debugging purposes. This exception will be propagated to the upper layers through other ways:
577         // - fireExceptionCaught
578         // - fireUserEventTriggered(Http2ResetFrame), see Http2MultiplexHandler#channelRead(...)
579         // - by failing write promise
580         // Receiver of the error is responsible for correct handling of this exception.
581         LOG.log(DEBUG, "{} Stream exception thrown for unknown stream {}.",
582                 ctx.channel(), streamException.streamId(), cause);
583     }
584 
585     @Override
586     protected final boolean isGracefulShutdownComplete() {
587         return super.isGracefulShutdownComplete() && numBufferedStreams == 0;
588     }
589 
590     private final class FrameListener implements Http2FrameListener {
591 
592         @Override
593         public void onUnknownFrame(
594                 ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags, ByteBuf payload) {
595             if (streamId == 0) {
596                 // Ignore unknown frames on connection stream, for example: HTTP/2 GREASE testing
597                 return;
598             }
599             Http2FrameStream stream = requireStream(streamId);
600             onHttp2Frame(ctx, newHttp2UnknownFrame(frameType, streamId, flags, payload.retain()).stream(stream));
601         }
602 
603         @Override
604         public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
605             onHttp2Frame(ctx, new DefaultHttp2SettingsFrame(settings));
606         }
607 
608         @Override
609         public void onPingRead(ChannelHandlerContext ctx, long data) {
610             onHttp2Frame(ctx, new DefaultHttp2PingFrame(data, false));
611         }
612 
613         @Override
614         public void onPingAckRead(ChannelHandlerContext ctx, long data) {
615             onHttp2Frame(ctx, new DefaultHttp2PingFrame(data, true));
616         }
617 
618         @Override
619         public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) {
620             Http2FrameStream stream = requireStream(streamId);
621             onHttp2Frame(ctx, new DefaultHttp2ResetFrame(errorCode).stream(stream));
622         }
623 
624         @Override
625         public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement) {
626             if (streamId == 0) {
627                 // Ignore connection window updates.
628                 return;
629             }
630             Http2FrameStream stream = requireStream(streamId);
631             onHttp2Frame(ctx, new DefaultHttp2WindowUpdateFrame(windowSizeIncrement).stream(stream));
632         }
633 
634         @Override
635         public void onHeadersRead(ChannelHandlerContext ctx, int streamId,
636                                   Http2Headers headers, int streamDependency, short weight, boolean
637                                           exclusive, int padding, boolean endStream) {
638             onHeadersRead(ctx, streamId, headers, padding, endStream);
639         }
640 
641         @Override
642         public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
643                                   int padding, boolean endOfStream) {
644             Http2FrameStream stream = requireStream(streamId);
645             onHttp2Frame(ctx, new DefaultHttp2HeadersFrame(headers, endOfStream, padding).stream(stream));
646         }
647 
648         @Override
649         public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
650                               boolean endOfStream) {
651             Http2FrameStream stream = requireStream(streamId);
652             final Http2DataFrame dataframe;
653             try {
654                 dataframe = new DefaultHttp2DataFrame(data.retain(), endOfStream, padding);
655             } catch (IllegalArgumentException e) {
656                 // Might be thrown in case of invalid padding / length.
657                 data.release();
658                 throw e;
659             }
660             dataframe.stream(stream);
661             onHttp2Frame(ctx, dataframe);
662             // We return the bytes in consumeBytes() once the stream channel consumed the bytes.
663             return 0;
664         }
665 
666         @Override
667         public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) {
668             onHttp2Frame(ctx, new DefaultHttp2GoAwayFrame(lastStreamId, errorCode, debugData.retain()));
669         }
670 
671         @Override
672         public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency,
673                                    short weight, boolean exclusive) {
674 
675             Http2Stream stream = connection().stream(streamId);
676             if (stream == null) {
677                 // The stream was not opened yet, let's just ignore this for now.
678                 return;
679             }
680             Http2FrameStream frameStream = requireStream(streamId);
681             onHttp2Frame(ctx, new DefaultHttp2PriorityFrame(streamDependency, weight, exclusive)
682                     .stream(frameStream));
683         }
684 
685         @Override
686         public void onSettingsAckRead(ChannelHandlerContext ctx) {
687             onHttp2Frame(ctx, Http2SettingsAckFrame.INSTANCE);
688         }
689 
690         @Override
691         public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
692                                       Http2Headers headers, int padding) {
693             Http2FrameStream stream = requireStream(streamId);
694             onHttp2Frame(ctx, new DefaultHttp2PushPromiseFrame(headers, padding, promisedStreamId)
695                     .pushStream(new DefaultHttp2FrameStream()
696                             .setStreamAndProperty(streamKey, connection().stream(promisedStreamId)))
697                     .stream(stream));
698         }
699 
700         private Http2FrameStream requireStream(int streamId) {
701             Http2FrameStream stream = connection().stream(streamId).getProperty(streamKey);
702             if (stream == null) {
703                 throw new IllegalStateException("Stream object required for identifier: " + streamId);
704             }
705             return stream;
706         }
707     }
708 
709     private void onUpgradeEvent(ChannelHandlerContext ctx, UpgradeEvent evt) {
710         ctx.fireUserEventTriggered(evt);
711     }
712 
713     private void onHttp2StreamWritabilityChanged(ChannelHandlerContext ctx, DefaultHttp2FrameStream stream,
714                                                  @SuppressWarnings("unused") boolean writable) {
715         ctx.fireUserEventTriggered(stream.writabilityChanged);
716     }
717 
718     void onHttp2StreamStateChanged(ChannelHandlerContext ctx, DefaultHttp2FrameStream stream) {
719         ctx.fireUserEventTriggered(stream.stateChanged);
720     }
721 
722     void onHttp2Frame(ChannelHandlerContext ctx, Http2Frame frame) {
723         ctx.fireChannelRead(frame);
724     }
725 
726     /**
727      * Create a Http2UnknownFrame. The ownership of the {@link ByteBuf} is transferred.
728      * */
729     protected Http2StreamFrame newHttp2UnknownFrame(byte frameType, int streamId, Http2Flags flags, ByteBuf payload) {
730         return new DefaultHttp2UnknownFrame(frameType, flags, payload);
731     }
732 
733     void onHttp2FrameStreamException(ChannelHandlerContext ctx, Http2FrameStreamException cause) {
734         ctx.fireExceptionCaught(cause);
735     }
736 
737     private final class Http2RemoteFlowControllerListener implements Http2RemoteFlowController.Listener {
738         @Override
739         public void writabilityChanged(Http2Stream stream) {
740             DefaultHttp2FrameStream frameStream = stream.getProperty(streamKey);
741             if (frameStream == null) {
742                 return;
743             }
744             onHttp2StreamWritabilityChanged(
745                     ctx, frameStream, connection().remote().flowController().isWritable(stream));
746         }
747     }
748 
749     /**
750      * {@link Http2FrameStream} implementation.
751      */
752     // TODO(buchgr): Merge Http2FrameStream and Http2Stream.
753     static class DefaultHttp2FrameStream implements Http2FrameStream {
754 
755         private volatile int id = -1;
756         private volatile Http2Stream stream;
757 
758         final Http2FrameStreamEvent stateChanged = Http2FrameStreamEvent.stateChanged(this);
759         final Http2FrameStreamEvent writabilityChanged = Http2FrameStreamEvent.writabilityChanged(this);
760 
761         Channel attachment;
762 
763         DefaultHttp2FrameStream setStreamAndProperty(PropertyKey streamKey, Http2Stream stream) {
764             assert id == -1 || stream.id() == id;
765             this.stream = stream;
766             this.id = stream.id();
767             stream.setProperty(streamKey, this);
768             return this;
769         }
770 
771         @Override
772         public int id() {
773             Http2Stream stream = this.stream;
774             return stream == null ? id : stream.id();
775         }
776 
777         @Override
778         public State state() {
779             Http2Stream stream = this.stream;
780             return stream == null ? State.IDLE : stream.state();
781         }
782 
783         @Override
784         public String toString() {
785             return String.valueOf(id());
786         }
787     }
788 }